@aceshooting/lyra-ui 28.1.0 → 28.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/dist/components/agent-tools/commit-card/commit-card.class.d.ts +2 -2
  3. package/dist/components/agent-tools/commit-card/commit-card.class.js +7 -8
  4. package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +1 -1
  5. package/dist/components/agent-tools/schema-viewer/schema-viewer.class.js +1 -1
  6. package/dist/components/agent-tools/span-waterfall/span-waterfall.class.js +1 -1
  7. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +4 -4
  8. package/dist/components/charts/chart/box-plot.class.d.ts +2 -2
  9. package/dist/components/charts/chart/box-plot.class.js +14 -14
  10. package/dist/components/charts/chart/chart.class.d.ts +2 -2
  11. package/dist/components/charts/chart/chart.class.js +14 -14
  12. package/dist/components/charts/chart/lite-chart.class.d.ts +1 -1
  13. package/dist/components/charts/chart/lite-chart.class.js +8 -8
  14. package/dist/components/conversation/message-feedback/message-feedback.class.js +2 -2
  15. package/dist/components/conversation/push-to-talk/push-to-talk.class.d.ts +2 -1
  16. package/dist/components/conversation/push-to-talk/push-to-talk.class.js +1 -1
  17. package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
  18. package/dist/components/data/data-grid/data-grid-processing.js +1 -1
  19. package/dist/components/data/flow-canvas/flow-canvas.class.js +1 -1
  20. package/dist/components/data/gauge/gauge.class.js +1 -1
  21. package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +1 -1
  22. package/dist/components/data/graph-query-builder/graph-query-builder.class.js +2 -2
  23. package/dist/components/data/heatmap/heatmap-label-cache.js +1 -0
  24. package/dist/components/data/heatmap/heatmap.class.d.ts +2 -2
  25. package/dist/components/data/heatmap/heatmap.class.js +2 -2
  26. package/dist/components/data/stat/stat.class.d.ts +11 -9
  27. package/dist/components/data/stat/stat.class.js +4 -2
  28. package/dist/components/data/tree/tree.class.js +1 -1
  29. package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
  30. package/dist/components/forms/color-picker/color-picker.class.js +3 -3
  31. package/dist/components/forms/combobox/combobox.class.d.ts +2 -4
  32. package/dist/components/forms/combobox/combobox.class.js +1 -1
  33. package/dist/components/forms/emoji-picker/emoji-picker.class.js +5 -5
  34. package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
  35. package/dist/components/forms/select/select.class.js +4 -3
  36. package/dist/components/forms/textarea/textarea.class.js +1 -1
  37. package/dist/components/forms/toggle-group/toggle-group.class.js +1 -1
  38. package/dist/components/layout/command-palette/command-palette.styles.js +1 -1
  39. package/dist/components/layout/details/accordion.class.js +1 -1
  40. package/dist/components/layout/filter-bar/filter-bar.class.js +3 -3
  41. package/dist/components/layout/menu/menu.class.d.ts +1 -1
  42. package/dist/components/layout/menu/menu.class.js +1 -1
  43. package/dist/components/layout/menubar/menubar.class.js +1 -1
  44. package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.d.ts +1 -1
  45. package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.js +1 -1
  46. package/dist/components/layout/page/page.class.d.ts +1 -1
  47. package/dist/components/layout/page/page.class.js +1 -1
  48. package/dist/components/layout/responsive-panel/responsive-panel.class.js +1 -1
  49. package/dist/components/layout/tab-group/tab-group.class.js +1 -1
  50. package/dist/components/layout/widget/widget.class.js +1 -1
  51. package/dist/components/media/attachment-trigger/attachment-trigger.class.js +1 -1
  52. package/dist/components/media/file-input/file-input.class.js +1 -1
  53. package/dist/components/media/image-viewer/image-viewer.class.js +1 -1
  54. package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
  55. package/dist/components/overlays/overlay/dropdown.class.js +1 -1
  56. package/dist/components/overlays/overlay/popover.class.js +1 -1
  57. package/dist/components/retrieval/chunk-inspector/chunk-inspector.class.d.ts +1 -1
  58. package/dist/components/retrieval/chunk-inspector/chunk-inspector.class.js +2 -2
  59. package/dist/components/retrieval/citation-badge/citation-badge.class.js +1 -1
  60. package/dist/components/retrieval/entity-chip/entity-chip.class.js +1 -1
  61. package/dist/components/retrieval/graph/graph-canvas.js +1 -1
  62. package/dist/components/retrieval/graph/graph.class.d.ts +1 -1
  63. package/dist/components/retrieval/graph/graph.class.js +1 -1
  64. package/dist/components/retrieval/graph-legend/graph-legend.class.js +2 -2
  65. package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.js +1 -1
  66. package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +1 -1
  67. package/dist/components/retrieval/retrieval-results/retrieval-results.class.d.ts +1 -1
  68. package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +4 -4
  69. package/dist/components/retrieval/source-picker/source-picker.class.d.ts +1 -1
  70. package/dist/components/retrieval/source-picker/source-picker.class.js +1 -1
  71. package/dist/components/utility/tour/tour.class.js +4 -4
  72. package/dist/components/viewers/email-viewer/email-viewer.class.js +1 -1
  73. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +1 -1
  74. package/dist/internal/dev-mode-attribute-warning.development.js +1 -1
  75. package/dist/internal/native-modal-carrier.js +2 -2
  76. package/dist/internal/overlay-manager.d.ts +2 -0
  77. package/dist/internal/overlay-manager.js +1 -1
  78. package/dist/internal/package-metadata.js +1 -1
  79. package/llms/components/lr-color-picker.md +2 -0
  80. package/llms/components/lr-commit-card.md +3 -2
  81. package/llms/components/lr-push-to-talk.md +3 -0
  82. package/llms/components/lr-select.md +2 -0
  83. package/llms/components/lr-stat.md +4 -0
  84. package/llms/peers.md +1 -1
  85. package/llms/shared/ai-and-peers.md +44 -0
  86. package/llms/shared.md +44 -0
  87. package/package.json +5 -5
  88. package/registrations.json +1 -1
@@ -1,3 +1,3 @@
1
- import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{tag}from"../../../internal/prefix.js";import{sizes}from"../../../internal/sizes.styles.js";import{normalizeReflectedOptionalSize,optionalSizeConverter}from"../../../internal/variants.js";import{literalSetConverter,optionalLiteralSetConverter}from"../../../internal/converters.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{isAccessibilitySubtreeExcluded,isAriaTrue}from"../../../internal/accessibility-visibility.js";import{composedParentElement,deepActiveElementIn}from"../../../internal/active-element.js";import{composedContains}from"../../../internal/overlay-stack.js";import{applyComposedFocusRepair,captureComposedFocusRepair,collectComposedFocusTargets}from"../../../internal/focus-navigation.js";import{resolveListMove}from"../../../internal/list-navigation.js";import{AdjacentRunScheduler,measureAdjacentRuns}from"../../../internal/adjacent-runs.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{styles}from"./toggle-group.styles.js";const SELECTION_MODE=literalSetConverter(["single","multiple"],"multiple"),ORIENTATION=literalSetConverter(["horizontal","vertical"],"horizontal"),APPEARANCE=optionalLiteralSetConverter(["plain","outlined"]),AMBIGUOUS_VALUE_WARNING_KEY="lyra-toggle-group-ambiguous-values",AMBIGUOUS_VALUE_WARNING="<lr-toggle-group>: empty or duplicate toggle values make the group value ambiguous; give each toggle a distinct value.",OBSERVED_ATTRIBUTES=["slot","pressed","disabled","value","hidden","inert","aria-hidden","aria-disabled","class","style"];class LyraToggleGroup extends LyraElement{static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-toggle-group-toggle-request","lr-change"])}static{this.identityEventDetailProperties=Object.freeze({"lr-toggle-group-toggle-request":Object.freeze(["option"])})}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={value:{attribute:!1,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0}}}get selectionMode(){return this._selectionMode}set selectionMode(next){const normalized=SELECTION_MODE.normalizeReflected(this,"selection-mode",next),old=this._selectionMode;old!==normalized&&(this._selectionMode=normalized,normalized==="single"&&(this.lastPressed=void 0),this.sync(),this.requestUpdate("selectionMode",old))}get orientation(){return this._orientation}set orientation(next){const normalized=ORIENTATION.normalizeReflected(this,"orientation",next),old=this._orientation;old!==normalized&&(this._orientation=normalized,this.requestUpdate("orientation",old))}get size(){return this._size}set size(next){const normalized=normalizeReflectedOptionalSize(this,next),old=this._size;old!==normalized&&(this._size=normalized,this.sync(),this.requestUpdate("size",old))}get appearance(){return this._appearance}set appearance(next){const normalized=APPEARANCE.normalizeReflected(this,"appearance",next),old=this._appearance;old!==normalized&&(this._appearance=normalized,this.sync(),this.requestUpdate("appearance",old))}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this.sync(),this.requestUpdate("disabled",old)}get value(){const values=new Set;for(const toggle of this.toggles())toggle.pressed&&values.add(toggle.value);return Object.freeze([...values])}set value(next){markVetoGuardWrite(this.groupGuard);const requested=Object.freeze(Array.isArray(next)?next.filter(entry=>typeof entry=="string"):[]),toggles=this.toggles();if(toggles.length===0){this.pendingValue=requested;return}this.pendingValue=void 0,this.applyValue(toggles,requested),this.sync()}constructor(){super(),this._disabled=!1,this._selectionMode="multiple",this._orientation="horizontal",this.linked=new Set,this.previousOrder=[],this.runPositions=new WeakMap,this.syncing=!1,this.runs=new AdjacentRunScheduler(this,()=>this.measureRuns()),this.generation=0,this.definitionSyncQueued=!1,this.groupGuard=new VetoWriteGuard,this.link={owns:toggle=>this.isConnected&&this.ownsToggle(toggle),pressedWritten:toggle=>this.onPressedWritten(toggle)},this.label="",this.onToggleRequest=event=>{const option=event.target;if(!this.isOwnedToggle(option))return;event.stopImmediatePropagation();const proposed=event.detail.pressed;let allowed=!1;requestThenCommit({requestDetail:{value:this.projectedValue(option,proposed),previousValue:this.value,option},emitRequest:(detail,init)=>this.emit("lr-toggle-group-toggle-request",detail,init),guard:this.groupGuard,commit:()=>{allowed=!0}}),allowed||event.preventDefault()},this.onToggleChange=event=>{this.isOwnedToggle(event.target)&&(event.stopImmediatePropagation(),this.emit("lr-change",{value:this.value}))},this.onKeyDown=event=>{if(event.defaultPrevented||event.altKey||event.ctrlKey||event.metaKey)return;const current=this.firstToggleInPath(event);if(!current||!this.isOwnedToggle(current))return;const available=this.toggles().filter(toggle=>this.isAvailable(toggle)),nextIndex=resolveListMove(event,{count:available.length,current:available.indexOf(current),orientation:this.orientation==="horizontal"?"horizontal":"vertical",direction:this.effectiveDirection});if(nextIndex===null)return;event.preventDefault();const next=available[nextIndex];this.lastFocused=next,this.project(this.toggles()),next.focus()},this.onFocusIn=event=>{const toggle=this.firstToggleInPath(event);if(!toggle||!this.isOwnedToggle(toggle))return;const snapshot=captureComposedFocusRepair(toggle,toggle);this.trackedFocus=snapshot?{toggle,snapshot}:void 0,this.lastFocused!==toggle&&(this.lastFocused=toggle,this.project(this.toggles()))},this.onFocusOut=()=>{const tracked=this.trackedFocus;tracked&&queueMicrotask(()=>{if(this.trackedFocus!==tracked)return;const active=deepActiveElementIn(this.ownerDocument);if(active!==null&&composedContains(tracked.toggle,active))return;const lost=active===null||active===this.ownerDocument.body||active===this.ownerDocument.documentElement,vanished=!tracked.toggle.isConnected||!this.isAvailable(tracked.toggle);(!lost||!vanished)&&(this.trackedFocus=void 0)})},this.onClick=event=>{const toggle=this.firstToggleInPath(event);!toggle||!this.isOwnedToggle(toggle)||this.lastFocused===toggle||(this.lastFocused=toggle,this.project(this.toggles()))},this.onSlotChange=()=>{this.sync()},this.addEventListener("lr-toggle-toggle-request",this.onToggleRequest,{capture:!0}),this.addEventListener("lr-change",this.onToggleChange,{capture:!0}),this.addEventListener("keydown",this.onKeyDown),this.addEventListener("focusin",this.onFocusIn),this.addEventListener("focusout",this.onFocusOut),this.addEventListener("click",this.onClick)}connectedCallback(){super.connectedCallback(),this.armMembershipObserver(),this.sync()}disconnectedCallback(){this.generation+=1,this.membershipObserver?.disconnect(),this.membershipObserver=void 0,this.runs.dispose(),this.definitionSyncQueued=!1,this.pendingValue=void 0,this.trackedFocus=void 0,this.lastPressed=void 0;for(const toggle of this.linked)toggle.leaveGroup(this.link);this.linked=new Set,this.previousOrder=[],super.disconnectedCallback()}updated(changed){super.updated(changed),this.runs.schedule()}focus(options){this.disabled||this.currentStop()?.focus(options)}blur(){this.toggles().find(toggle=>toggle.matches(":focus-within"))?.blur()}click(){this.disabled||this.currentStop()?.click()}currentStop(){return this.computeTabStop(this.toggles())}ownsToggle(element){if(element.localName!==tag("toggle"))return!1;const closest=element.closest;if(typeof closest!="function"||closest.call(element,tag("toggle-group"))!==this)return!1;let topLevel=element;for(;topLevel.parentElement&&topLevel.parentElement!==this;)topLevel=topLevel.parentElement;return topLevel.parentElement!==this?!1:!topLevel.getAttribute("slot")}isOwnedToggle(target){return target?.nodeType===1&&this.ownsToggle(target)&&typeof target.joinGroup=="function"}toggles(){return this.ownedElements().filter(element=>typeof element.joinGroup=="function")}ownedElements(){const querySelectorAll=this.querySelectorAll;return typeof querySelectorAll!="function"?[]:[...querySelectorAll.call(this,tag("toggle"))].filter(element=>this.ownsToggle(element))}isAvailable(toggle){if(this.disabled||toggle.disabled)return!1;for(let current=toggle;current;current=composedParentElement(current)){if(isAccessibilitySubtreeExcluded(current)||isAriaTrue(current.getAttribute("aria-disabled")))return!1;if(current===this)break}return!0}sync(){if(this.syncing||!this.isConnected)return;const elements=this.ownedElements(),toggles=this.toggles();elements.length!==toggles.length&&this.queueDefinitionSync(),this.syncing=!0;try{const current=new Set(toggles);for(const toggle of this.linked)current.has(toggle)||toggle.leaveGroup(this.link);for(const toggle of toggles)this.linked.has(toggle)||toggle.joinGroup(this.link);if(this.linked=current,this.selectionMode==="single"&&this.keepOnePressed(toggles),this.pendingValue!==void 0&&toggles.length>0){const pending=this.pendingValue;this.pendingValue=void 0,this.applyValue(toggles,pending)}}finally{this.syncing=!1}this.warnOnAmbiguousValues(toggles),this.observeSizes(toggles),this.project(toggles),this.runs.schedule()}keepOnePressed(toggles){const pressed=toggles.filter(toggle=>toggle.pressed);if(pressed.length<=1)return;const keep=this.lastPressed&&pressed.includes(this.lastPressed)?this.lastPressed:pressed[0];for(const toggle of pressed)toggle!==keep&&(toggle.pressed=!1)}applyValue(toggles,requested){const wasSyncing=this.syncing;this.syncing=!0;try{if(this.selectionMode==="single"){const wanted=requested.find(value=>toggles.some(toggle=>toggle.value===value)),chosen=wanted===void 0?void 0:toggles.find(toggle=>toggle.value===wanted);for(const toggle of toggles)toggle.pressed=toggle===chosen;chosen&&(this.lastPressed=chosen)}else{const wanted=new Set(requested);for(const toggle of toggles)toggle.pressed=wanted.has(toggle.value)}}finally{this.syncing=wasSyncing}}onPressedWritten(toggle){if(!(this.syncing||!this.isConnected||!this.ownsToggle(toggle))&&!(this.selectionMode!=="single"||!toggle.pressed)){this.lastPressed=toggle,this.syncing=!0;try{for(const other of this.toggles())other!==toggle&&other.pressed&&(other.pressed=!1)}finally{this.syncing=!1}}}warnOnAmbiguousValues(toggles){const seen=new Set;for(const toggle of toggles){if(toggle.value===""||seen.has(toggle.value)){devWarnOnce(AMBIGUOUS_VALUE_WARNING_KEY,AMBIGUOUS_VALUE_WARNING);return}seen.add(toggle.value)}}computeTabStop(toggles){const available=toggles.filter(toggle=>this.isAvailable(toggle));if(available.length===0)return;const anchor=this.lastFocused;if(anchor&&available.includes(anchor))return anchor;if(anchor){const index=this.previousOrder.indexOf(anchor);if(index>=0){const after=this.previousOrder.slice(index+1).find(toggle=>available.includes(toggle)),before=this.previousOrder.slice(0,index).reverse().find(toggle=>available.includes(toggle)),clamped=after??before;if(clamped)return this.lastFocused=clamped,clamped}this.lastFocused=void 0}return available.find(toggle=>toggle.pressed)??available[0]}project(toggles){const stop=this.computeTabStop(toggles);this.previousOrder=[...toggles];const horizontal=this.orientation==="horizontal";for(const toggle of toggles)toggle.setGroupProjection({disabled:this.disabled,tabbable:toggle===stop,size:this.size??null,appearance:this.appearance??null,run:horizontal?this.runPositions.get(toggle)??"standalone":"standalone"});this.repairFocus(toggles,stop)}repairFocus(toggles,stop){const tracked=this.trackedFocus;if(!tracked||toggles.includes(tracked.toggle)&&this.isAvailable(tracked.toggle)||(this.trackedFocus=void 0,!stop))return;const target=collectComposedFocusTargets(stop,{includeRoot:!1,mode:"programmatic"}).elements[0];target&&applyComposedFocusRepair(tracked.snapshot,()=>[target])}queueDefinitionSync(){if(this.definitionSyncQueued)return;const registry=this.ownerDocument?.defaultView?.customElements;if(!registry)return;this.definitionSyncQueued=!0;const generation=this.generation;registry.whenDefined(tag("toggle")).then(()=>{this.generation===generation&&(this.definitionSyncQueued=!1,this.isConnected&&this.sync())})}armMembershipObserver(){const MutationObserverCtor=this.ownerDocument?.defaultView?.MutationObserver;if(!MutationObserverCtor||this.membershipObserver)return;const generation=this.generation,observer=new MutationObserverCtor(()=>{this.membershipObserver!==observer||this.generation!==generation||!this.isConnected||this.sync()});this.membershipObserver=observer,observer.observe(this,{attributes:!0,childList:!0,subtree:!0,attributeFilter:OBSERVED_ATTRIBUTES})}observeSizes(toggles){this.runs.observe(toggles)}measureRuns(){const toggles=this.toggles(),positions=this.orientation==="horizontal"?measureAdjacentRuns(toggles,{direction:getComputedStyle(this).direction==="rtl"?"rtl":"ltr",joinable:()=>!0}):toggles.map(()=>"standalone");toggles.forEach((toggle,index)=>this.runPositions.set(toggle,positions[index])),this.project(toggles)}firstToggleInPath(event){for(const target of event.composedPath()){if(target===this)return;if(target.nodeType===1&&target.localName===tag("toggle"))return target}}projectedValue(option,pressed){if(this.selectionMode==="single")return Object.freeze(pressed?[option.value]:[]);const values=new Set;for(const toggle of this.toggles())(toggle===option?pressed:toggle.pressed)&&values.add(toggle.value);return Object.freeze([...values])}render(){const name=hostAriaLabel(this);return html`<div part="base" role="group" aria-label=${name??(this.label||nothing)}>
1
+ import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{tag}from"../../../internal/prefix.js";import{sizes}from"../../../internal/sizes.styles.js";import{normalizeReflectedOptionalSize,optionalSizeConverter}from"../../../internal/variants.js";import{literalSetConverter,optionalLiteralSetConverter}from"../../../internal/converters.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{isAccessibilitySubtreeExcluded,isAriaTrue}from"../../../internal/accessibility-visibility.js";import{composedParentElement,deepActiveElementIn}from"../../../internal/active-element.js";import{composedContains}from"../../../internal/overlay-stack.js";import{applyComposedFocusRepair,captureComposedFocusRepair,collectComposedFocusTargets}from"../../../internal/focus-navigation.js";import{resolveListMove}from"../../../internal/list-navigation.js";import{AdjacentRunScheduler,measureAdjacentRuns}from"../../../internal/adjacent-runs.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{styles}from"./toggle-group.styles.js";const SELECTION_MODE=literalSetConverter(["single","multiple"],"multiple"),ORIENTATION=literalSetConverter(["horizontal","vertical"],"horizontal"),APPEARANCE=optionalLiteralSetConverter(["plain","outlined"]),AMBIGUOUS_VALUE_WARNING_KEY="lyra-toggle-group-ambiguous-values",AMBIGUOUS_VALUE_WARNING="<lr-toggle-group>: empty or duplicate toggle values make the group value ambiguous; give each toggle a distinct value.",OBSERVED_ATTRIBUTES=["slot","pressed","disabled","value","hidden","inert","aria-hidden","aria-disabled","class","style"];class LyraToggleGroup extends LyraElement{static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-toggle-group-toggle-request","lr-change"])}static{this.identityEventDetailProperties=Object.freeze({"lr-toggle-group-toggle-request":Object.freeze(["option"])})}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={value:{attribute:!1,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0}}}get selectionMode(){return this._selectionMode}set selectionMode(next){const normalized=SELECTION_MODE.normalizeReflected(this,"selection-mode",next),old=this._selectionMode;old!==normalized&&(this._selectionMode=normalized,normalized==="single"&&(this.lastPressed=void 0),this.sync(),this.requestUpdate("selectionMode",old))}get orientation(){return this._orientation}set orientation(next){const normalized=ORIENTATION.normalizeReflected(this,"orientation",next),old=this._orientation;old!==normalized&&(this._orientation=normalized,this.requestUpdate("orientation",old))}get size(){return this._size}set size(next){const normalized=normalizeReflectedOptionalSize(this,next),old=this._size;old!==normalized&&(this._size=normalized,this.sync(),this.requestUpdate("size",old))}get appearance(){return this._appearance}set appearance(next){const normalized=APPEARANCE.normalizeReflected(this,"appearance",next),old=this._appearance;old!==normalized&&(this._appearance=normalized,this.sync(),this.requestUpdate("appearance",old))}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this.sync(),this.requestUpdate("disabled",old)}get value(){const values=new Set;for(const toggle of this.toggles())toggle.pressed&&values.add(toggle.value);return Object.freeze([...values])}set value(next){markVetoGuardWrite(this.groupGuard);const requested=Object.freeze(Array.isArray(next)?next.filter(entry=>typeof entry=="string"):[]),toggles=this.toggles();if(toggles.length===0){this.pendingValue=requested;return}this.pendingValue=void 0,this.applyValue(toggles,requested),this.sync()}constructor(){super(),this._disabled=!1,this._selectionMode="multiple",this._orientation="horizontal",this.linked=new Set,this.previousOrder=[],this.runPositions=new WeakMap,this.syncing=!1,this.runs=new AdjacentRunScheduler(this,()=>this.measureRuns()),this.generation=0,this.definitionSyncQueued=!1,this.groupGuard=new VetoWriteGuard,this.link={owns:toggle=>this.isConnected&&this.ownsToggle(toggle),pressedWritten:toggle=>this.onPressedWritten(toggle)},this.label="",this.onToggleRequest=event=>{const option=event.target;if(!this.isOwnedToggle(option))return;event.stopImmediatePropagation();const proposed=event.detail.pressed;let allowed=!1;requestThenCommit({requestDetail:{value:this.projectedValue(option,proposed),previousValue:this.value,option},emitRequest:(detail,init)=>this.emit("lr-toggle-group-toggle-request",detail,init),guard:this.groupGuard,commit:()=>{allowed=!0}}),allowed||event.preventDefault()},this.onToggleChange=event=>{this.isOwnedToggle(event.target)&&(event.stopImmediatePropagation(),this.emit("lr-change",{value:this.value}))},this.onKeyDown=event=>{if(event.defaultPrevented||event.altKey||event.ctrlKey||event.metaKey)return;const current=this.firstToggleInPath(event);if(!current||!this.isOwnedToggle(current))return;const available=this.toggles().filter(toggle=>this.isAvailable(toggle)),nextIndex=resolveListMove(event,{count:available.length,current:available.indexOf(current),orientation:this.orientation==="horizontal"?"horizontal":"vertical",direction:this.effectiveDirection});if(nextIndex===null)return;event.preventDefault();const next=available[nextIndex];this.lastFocused=next,this.project(this.toggles()),next.focus()},this.onFocusIn=event=>{const toggle=this.firstToggleInPath(event);if(!toggle||!this.isOwnedToggle(toggle))return;const snapshot=captureComposedFocusRepair(toggle,toggle);this.trackedFocus=snapshot?{toggle,snapshot}:void 0,this.lastFocused!==toggle&&(this.lastFocused=toggle,this.project(this.toggles()))},this.onFocusOut=()=>{const tracked=this.trackedFocus;tracked&&queueMicrotask(()=>{if(this.trackedFocus!==tracked)return;const active=deepActiveElementIn(this.ownerDocument);if(active!==null&&composedContains(tracked.toggle,active))return;const lost=active===null||active===this.ownerDocument.body||active===this.ownerDocument.documentElement,vanished=!tracked.toggle.isConnected||!this.isAvailable(tracked.toggle);(!lost||!vanished)&&(this.trackedFocus=void 0)})},this.onClick=event=>{const toggle=this.firstToggleInPath(event);!toggle||!this.isOwnedToggle(toggle)||this.lastFocused===toggle||(this.lastFocused=toggle,this.project(this.toggles()))},this.onSlotChange=()=>{this.sync()},this.addEventListener("lr-toggle-toggle-request",this.onToggleRequest,{capture:!0}),this.addEventListener("lr-change",this.onToggleChange,{capture:!0}),this.addEventListener("keydown",this.onKeyDown),this.addEventListener("focusin",this.onFocusIn),this.addEventListener("focusout",this.onFocusOut),this.addEventListener("click",this.onClick)}connectedCallback(){super.connectedCallback(),this.armMembershipObserver(),this.sync()}disconnectedCallback(){this.generation+=1,this.membershipObserver?.disconnect(),this.membershipObserver=void 0,this.runs.dispose(),this.definitionSyncQueued=!1,this.pendingValue=void 0,this.trackedFocus=void 0,this.lastPressed=void 0;for(const toggle of this.linked)toggle.leaveGroup(this.link);this.linked=new Set,this.previousOrder=[],super.disconnectedCallback()}updated(changed){super.updated(changed),this.runs.schedule()}focus(options){this.disabled||this.currentStop()?.focus(options)}blur(){this.toggles().find(toggle=>toggle.matches(":focus-within"))?.blur()}click(){this.disabled||this.currentStop()?.click()}currentStop(){return this.computeTabStop(this.toggles())}ownsToggle(element){if(element.localName!==tag("toggle"))return!1;const closest=element.closest;if(typeof closest!="function"||closest.call(element,tag("toggle-group"))!==this)return!1;let topLevel=element;for(;topLevel.parentElement&&topLevel.parentElement!==this;)topLevel=topLevel.parentElement;return topLevel.parentElement!==this?!1:!topLevel.getAttribute("slot")}isOwnedToggle(target){return target?.nodeType===1&&this.ownsToggle(target)&&typeof target.joinGroup=="function"}toggles(){return this.ownedElements().filter(element=>typeof element.joinGroup=="function")}ownedElements(){const querySelectorAll=this.querySelectorAll;return typeof querySelectorAll!="function"?[]:[...querySelectorAll.call(this,tag("toggle"))].filter(element=>this.ownsToggle(element))}isAvailable(toggle){if(this.disabled||toggle.disabled)return!1;for(let current=toggle;current;current=composedParentElement(current)){if(isAccessibilitySubtreeExcluded(current)||isAriaTrue(current.getAttribute("aria-disabled")))return!1;if(current===this)break}return!0}sync(){if(this.syncing||!this.isConnected)return;const elements=this.ownedElements(),toggles=this.toggles();elements.length!==toggles.length&&this.queueDefinitionSync(),this.syncing=!0;try{const current=new Set(toggles);for(const toggle of this.linked)current.has(toggle)||toggle.leaveGroup(this.link);for(const toggle of toggles)this.linked.has(toggle)||toggle.joinGroup(this.link);if(this.linked=current,this.selectionMode==="single"&&this.keepOnePressed(toggles),this.pendingValue!==void 0&&toggles.length>0){const pending=this.pendingValue;this.pendingValue=void 0,this.applyValue(toggles,pending)}}finally{this.syncing=!1}this.warnOnAmbiguousValues(toggles),this.observeSizes(toggles),this.project(toggles),this.runs.schedule()}keepOnePressed(toggles){const pressed=toggles.filter(toggle=>toggle.pressed);if(pressed.length<=1)return;const keep=this.lastPressed&&pressed.includes(this.lastPressed)?this.lastPressed:pressed[0];for(const toggle of pressed)toggle!==keep&&(toggle.pressed=!1)}applyValue(toggles,requested){const wasSyncing=this.syncing;this.syncing=!0;try{if(this.selectionMode==="single"){let chosen;if(requested.length<=1){const wanted=requested.find(value=>toggles.some(toggle=>toggle.value===value));chosen=wanted===void 0?void 0:toggles.find(toggle=>toggle.value===wanted)}else{const firstByValue=new Map;for(const toggle of toggles){const value=toggle.value;firstByValue.has(value)||firstByValue.set(value,toggle)}for(const value of requested)if(chosen=firstByValue.get(value),chosen)break}for(const toggle of toggles)toggle.pressed=toggle===chosen;chosen&&(this.lastPressed=chosen)}else{const wanted=new Set(requested);for(const toggle of toggles)toggle.pressed=wanted.has(toggle.value)}}finally{this.syncing=wasSyncing}}onPressedWritten(toggle){if(!(this.syncing||!this.isConnected||!this.ownsToggle(toggle))&&!(this.selectionMode!=="single"||!toggle.pressed)){this.lastPressed=toggle,this.syncing=!0;try{for(const other of this.toggles())other!==toggle&&other.pressed&&(other.pressed=!1)}finally{this.syncing=!1}}}warnOnAmbiguousValues(toggles){const seen=new Set;for(const toggle of toggles){if(toggle.value===""||seen.has(toggle.value)){devWarnOnce(AMBIGUOUS_VALUE_WARNING_KEY,AMBIGUOUS_VALUE_WARNING);return}seen.add(toggle.value)}}computeTabStop(toggles){const available=toggles.filter(toggle=>this.isAvailable(toggle));if(available.length===0)return;const anchor=this.lastFocused;if(anchor&&available.includes(anchor))return anchor;if(anchor){const index=this.previousOrder.indexOf(anchor);if(index>=0){const availableSet=available.length>1?new Set(available):void 0,isAvailable=toggle=>availableSet?availableSet.has(toggle):toggle===available[0];let clamped;for(let next=index+1;next<this.previousOrder.length;next+=1){const toggle=this.previousOrder[next];if(isAvailable(toggle)){clamped=toggle;break}}if(!clamped)for(let previous=index-1;previous>=0;previous-=1){const toggle=this.previousOrder[previous];if(isAvailable(toggle)){clamped=toggle;break}}if(clamped)return this.lastFocused=clamped,clamped}this.lastFocused=void 0}return available.find(toggle=>toggle.pressed)??available[0]}project(toggles){const stop=this.computeTabStop(toggles);this.previousOrder=[...toggles];const horizontal=this.orientation==="horizontal";for(const toggle of toggles)toggle.setGroupProjection({disabled:this.disabled,tabbable:toggle===stop,size:this.size??null,appearance:this.appearance??null,run:horizontal?this.runPositions.get(toggle)??"standalone":"standalone"});this.repairFocus(toggles,stop)}repairFocus(toggles,stop){const tracked=this.trackedFocus;if(!tracked||toggles.includes(tracked.toggle)&&this.isAvailable(tracked.toggle)||(this.trackedFocus=void 0,!stop))return;const target=collectComposedFocusTargets(stop,{includeRoot:!1,mode:"programmatic"}).elements[0];target&&applyComposedFocusRepair(tracked.snapshot,()=>[target])}queueDefinitionSync(){if(this.definitionSyncQueued)return;const registry=this.ownerDocument?.defaultView?.customElements;if(!registry)return;this.definitionSyncQueued=!0;const generation=this.generation;registry.whenDefined(tag("toggle")).then(()=>{this.generation===generation&&(this.definitionSyncQueued=!1,this.isConnected&&this.sync())})}armMembershipObserver(){const MutationObserverCtor=this.ownerDocument?.defaultView?.MutationObserver;if(!MutationObserverCtor||this.membershipObserver)return;const generation=this.generation,observer=new MutationObserverCtor(()=>{this.membershipObserver!==observer||this.generation!==generation||!this.isConnected||this.sync()});this.membershipObserver=observer,observer.observe(this,{attributes:!0,childList:!0,subtree:!0,attributeFilter:OBSERVED_ATTRIBUTES})}observeSizes(toggles){this.runs.observe(toggles)}measureRuns(){const toggles=this.toggles(),positions=this.orientation==="horizontal"?measureAdjacentRuns(toggles,{direction:getComputedStyle(this).direction==="rtl"?"rtl":"ltr",joinable:()=>!0}):toggles.map(()=>"standalone");toggles.forEach((toggle,index)=>this.runPositions.set(toggle,positions[index])),this.project(toggles)}firstToggleInPath(event){for(const target of event.composedPath()){if(target===this)return;if(target.nodeType===1&&target.localName===tag("toggle"))return target}}projectedValue(option,pressed){if(this.selectionMode==="single")return Object.freeze(pressed?[option.value]:[]);const values=new Set;for(const toggle of this.toggles())(toggle===option?pressed:toggle.pressed)&&values.add(toggle.value);return Object.freeze([...values])}render(){const name=hostAriaLabel(this);return html`<div part="base" role="group" aria-label=${name??(this.label||nothing)}>
2
2
  <slot @slotchange=${this.onSlotChange}></slot>
3
3
  </div>`}}__decorate([property({attribute:"selection-mode",reflect:!0,converter:SELECTION_MODE})],LyraToggleGroup.prototype,"selectionMode",null),__decorate([property({reflect:!0,converter:ORIENTATION})],LyraToggleGroup.prototype,"orientation",null),__decorate([property({reflect:!0,converter:optionalSizeConverter})],LyraToggleGroup.prototype,"size",null),__decorate([property({reflect:!0,converter:APPEARANCE})],LyraToggleGroup.prototype,"appearance",null),__decorate([property()],LyraToggleGroup.prototype,"label",void 0);export{LyraToggleGroup};
@@ -1 +1 @@
1
- import{iconHitTarget,focusRing}from"../../../internal/interactive-control.styles.js";import{css}from"lit";import{overlaySurface}from"../../../internal/overlay-surface.styles.js";const styles=css` :host { display: contents; --_lr-command-palette-z-index: var( --lr-overlay-stack-index, var(--lr-layer-modal) ); --_lr-command-palette-max-inline-size: var(--lr-size-48rem); --_lr-command-palette-max-block-size: 70vh; --_lr-command-palette-list-max-block-size: 50vh; --_lr-command-palette-offset-block-start: 12vh; --_lr-command-palette-row-height: var(--lr-size-3rem); --_lr-command-palette-group-height: var(--lr-size-2rem); } [part="backdrop"] { position: fixed; inset: 0; z-index: var( --lr-command-palette-z-index, var(--_lr-command-palette-z-index) ); display: grid; place-items: start center; padding-block-start: var( --lr-command-palette-offset-block-start, var(--_lr-command-palette-offset-block-start) ); background: var(--lr-color-overlay); } [part="dialog"] { inline-size: min( var( --lr-command-palette-max-inline-size, var(--_lr-command-palette-max-inline-size) ), calc(100vw - 2 * var(--lr-space-l)) ); min-inline-size: 0; max-block-size: var( --lr-command-palette-max-block-size, var(--_lr-command-palette-max-block-size) ); overflow: hidden; --_lr-overlay-surface: var(--lr-color-surface-container-highest); ${overlaySurface} box-shadow: var(--lr-overlay-shadow-modal, var(--lr-shadow-xl)); color: var(--lr-color-text); } [part="search"] { display: flex; align-items: center; min-inline-size: 0; gap: var(--lr-command-palette-search-gap, var(--lr-space-s)); padding: var(--lr-command-palette-search-padding, var(--lr-space-m)); border-block-end: var(--lr-border-width-thin) solid var(--lr-color-border); } [part="input"] { flex: 1; min-inline-size: 0; min-block-size: var(--lr-command-palette-search-min-height, auto); border: 0; outline: 0; background: transparent; color: inherit; font: inherit; font-size: var(--lr-command-palette-search-font-size, inherit); } [part="input"]:focus-visible { ${focusRing} border-radius: var(--lr-radius-xs); } [part="input"]::placeholder { color: var(--lr-color-text-quiet); opacity: 1; } [part="input"]::-webkit-search-cancel-button, [part="input"]::-webkit-search-decoration { -webkit-appearance: none; appearance: none; display: none; } [part="clear-button"] { flex: 0 0 auto; display: inline-flex; align-items: center; justify-content: center; ${iconHitTarget} border: 0; border-radius: var(--lr-radius-xs); background: transparent; cursor: pointer; color: var(--lr-color-text-quiet); padding: var(--lr-space-xs); font: inherit; transition: background-color var(--lr-transition-fast), color var(--lr-transition-fast); } [part="clear-button"]:hover { color: var(--lr-color-text); } [part="clear-button"]:active { color: var(--lr-color-text); background: color-mix( in oklab, var(--lr-color-surface), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part="clear-button"]:focus-visible { outline: var(--lr-focus-ring-width) solid var(--lr-focus-ring-color); outline-offset: calc(-1 * var(--lr-focus-ring-width)); } [part="list"] { position: relative; max-block-size: var( --lr-command-palette-list-max-block-size, var(--_lr-command-palette-list-max-block-size) ); overflow-x: hidden; overflow-y: auto; padding: var(--lr-space-xs); } [part="list-spacer"] { position: relative; min-inline-size: 0; } [part="command-group"] { display: contents; } [part="group"] { position: absolute; inset-inline: 0; block-size: var( --lr-command-palette-group-height, var(--_lr-command-palette-group-height) ); box-sizing: border-box; overflow: hidden; padding: var(--lr-space-xs) var(--lr-space-s); color: var(--lr-color-text-quiet); font-size: var(--lr-font-size-sm); font-weight: var(--lr-font-weight-semibold); text-overflow: ellipsis; white-space: nowrap; } [part="command"] { position: absolute; inset-inline: 0; display: flex; align-items: center; min-inline-size: 0; block-size: var( --lr-command-palette-row-height, var(--_lr-command-palette-row-height) ); box-sizing: border-box; gap: var(--lr-space-s); inline-size: 100%; overflow: hidden; padding: var(--lr-space-s); border: 0; border-radius: var(--lr-radius); background: transparent; color: inherit; font: inherit; text-align: start; cursor: pointer; transition: background-color var(--lr-transition-fast); } :where([part="command"]):hover:where(:not(:disabled)) { background: var( --lr-command-palette-active-bg, var(--lr-color-brand-quiet) ); } :where([part="command"]):active:where(:not(:disabled)) { background: color-mix( in oklab, var(--lr-command-palette-active-bg, var(--lr-color-brand-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part="command"][data-active="true"] { background: var( --lr-command-palette-active-bg, var(--lr-color-brand-quiet) ); } [part="command"][data-active="true"]:active:where(:not(:disabled)) { background: color-mix( in oklab, var(--lr-command-palette-active-bg, var(--lr-color-brand-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part="command"]:disabled { opacity: var(--lr-opacity-disabled); cursor: not-allowed; } [part="icon"] { display: inline-flex; align-items: center; flex: none; block-size: var(--lr-size-1em); max-inline-size: var(--lr-size-1-25rem); } [part="label"], [part="description"], [part="shortcut"] { min-inline-size: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } [part="label"] { flex: 0 1000 auto; } [part="description"] { flex: 1 1000 auto; color: var(--lr-color-text-quiet); font-size: var(--lr-font-size-sm); } [part="shortcut"] { flex: 0 1 auto; max-inline-size: 40%; color: var(--lr-color-text-quiet); font-family: var(--lr-font-mono); font-size: var(--lr-font-size-sm); } [part="empty"] { padding: var(--lr-space-l); color: var(--lr-color-text-quiet); text-align: center; } @media (forced-colors: active) { [part="command"][data-active="true"] { outline: var(--lr-border-width-medium) solid currentColor; outline-offset: calc(-1 * var(--lr-border-width-medium)); font-weight: var(--lr-font-weight-semibold); } } `;export{styles};
1
+ import{iconHitTarget,focusRing}from"../../../internal/interactive-control.styles.js";import{css}from"lit";import{overlaySurface}from"../../../internal/overlay-surface.styles.js";const styles=css` :host { display: contents; --_lr-command-palette-z-index: var( --lr-overlay-stack-index, var(--lr-layer-modal) ); --_lr-command-palette-max-inline-size: var(--lr-size-48rem); --_lr-command-palette-max-block-size: 70vh; --_lr-command-palette-list-max-block-size: 50vh; --_lr-command-palette-offset-block-start: 12vh; --_lr-command-palette-row-height: var(--lr-size-3rem); --_lr-command-palette-group-height: var(--lr-size-2rem); } [part="backdrop"] { position: fixed; inset: 0; z-index: var( --lr-command-palette-z-index, var(--_lr-command-palette-z-index) ); display: grid; place-items: start center; padding-block-start: var( --lr-command-palette-offset-block-start, var(--_lr-command-palette-offset-block-start) ); background: var(--lr-color-overlay); } [part="dialog"] { inline-size: min( var( --lr-command-palette-max-inline-size, var(--_lr-command-palette-max-inline-size) ), calc(100vw - 2 * var(--lr-space-l)) ); min-inline-size: 0; max-block-size: var( --lr-command-palette-max-block-size, var(--_lr-command-palette-max-block-size) ); overflow: hidden; --_lr-overlay-surface: var(--lr-color-surface-container-highest); ${overlaySurface} box-shadow: var(--lr-overlay-shadow-modal, var(--lr-shadow-xl)); color: var(--lr-color-text); } [part="search"] { display: flex; align-items: center; min-inline-size: 0; gap: var(--lr-command-palette-search-gap, var(--lr-space-s)); padding: var(--lr-command-palette-search-padding, var(--lr-space-m)); border-block-end: var(--lr-border-width-thin) solid var(--lr-color-border); } [part="input"] { flex: 1; min-inline-size: 0; min-block-size: var(--lr-command-palette-search-min-height, auto); border: 0; outline: 0; background: transparent; color: inherit; font: inherit; font-size: var(--lr-command-palette-search-font-size, inherit); } [part="input"]:focus-visible { ${focusRing} border-radius: var(--lr-radius-xs); } [part="input"]::placeholder { color: var(--lr-color-text-quiet); opacity: 1; } [part="input"]::-webkit-search-cancel-button, [part="input"]::-webkit-search-decoration { -webkit-appearance: none; appearance: none; display: none; } [part="clear-button"] { flex: 0 0 auto; display: inline-flex; align-items: center; justify-content: center; ${iconHitTarget} border: 0; border-radius: var(--lr-radius-xs); background: transparent; cursor: pointer; color: var(--lr-color-text-quiet); padding: var(--lr-space-xs); font: inherit; transition: background-color var(--lr-transition-fast), color var(--lr-transition-fast); } [part="clear-button"]:hover { color: var(--lr-color-text); } [part="clear-button"]:active { color: var(--lr-color-text); background: color-mix( in oklab, var(--lr-color-surface), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part="clear-button"]:focus-visible { outline: var(--lr-focus-ring-width) solid var(--lr-focus-ring-color); outline-offset: calc(-1 * var(--lr-focus-ring-width)); } [part="list"] { position: relative; max-block-size: var( --lr-command-palette-list-max-block-size, var(--_lr-command-palette-list-max-block-size) ); overflow-x: hidden; overflow-y: auto; padding: var(--lr-space-xs); } [part="list-spacer"] { position: relative; min-inline-size: 0; } [part="command-group"] { display: contents; } [part="group"] { position: absolute; inset-inline: 0; block-size: var( --lr-command-palette-group-height, var(--_lr-command-palette-group-height) ); box-sizing: border-box; overflow: hidden; padding: var(--lr-space-xs) var(--lr-space-s); color: var(--lr-color-text-quiet); font-size: var(--lr-font-size-sm); font-weight: var(--lr-font-weight-semibold); text-overflow: ellipsis; white-space: nowrap; } [part="command"] { position: absolute; inset-inline: 0; display: flex; align-items: center; min-inline-size: 0; block-size: var( --lr-command-palette-row-height, var(--_lr-command-palette-row-height) ); box-sizing: border-box; gap: var(--lr-space-s); inline-size: 100%; overflow: hidden; padding: var(--lr-space-s); border: 0; border-radius: var(--lr-radius); background: transparent; color: inherit; font: inherit; text-align: start; cursor: pointer; transition: background-color var(--lr-transition-fast); } :where([part="command"]):hover:where(:not(:disabled)) { background: var( --lr-command-palette-active-bg, var(--lr-color-brand-quiet) ); } :where([part="command"]):active:where(:not(:disabled)) { background: color-mix( in oklab, var(--lr-command-palette-active-bg, var(--lr-color-brand-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part="command"][data-active="true"] { background: var( --lr-command-palette-active-bg, var(--lr-color-brand-quiet) ); } [part="command"][data-active="true"]:active:where(:not(:disabled)) { background: color-mix( in oklab, var(--lr-command-palette-active-bg, var(--lr-color-brand-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part="command"]:disabled { opacity: var(--lr-opacity-disabled); cursor: not-allowed; } [part="icon"] { display: inline-flex; align-items: center; flex: none; block-size: var(--lr-size-1em); max-inline-size: var(--lr-size-1-25rem); } [part="label"], [part="description"], [part="shortcut"] { min-inline-size: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } [part="label"] { flex: 0 1000 auto; } [part="description"] { flex: 1 1000 auto; color: inherit; font-size: var(--lr-font-size-sm); } [part="shortcut"] { flex: 0 1 auto; max-inline-size: 40%; color: inherit; font-family: var(--lr-font-mono); font-size: var(--lr-font-size-sm); } [part="empty"] { padding: var(--lr-space-l); color: var(--lr-color-text-quiet); text-align: center; } @media (forced-colors: active) { [part="command"][data-active="true"] { outline: var(--lr-border-width-medium) solid currentColor; outline-offset: calc(-1 * var(--lr-border-width-medium)); font-weight: var(--lr-font-weight-semibold); } } `;export{styles};
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html}from"lit";import{property,query}from"lit/decorators.js";import{composedParentElement,deepActiveElementIn}from"../../../internal/active-element.js";import{isAccessibilitySubtreeExcluded}from"../../../internal/accessibility-visibility.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{LyraElement}from"../../../internal/lyra-element.js";import{tag}from"../../../internal/prefix.js";import{applyAccordionItemOwnerState,bindAccordionItemOwner,releaseAccordionItemOwner}from"./accordion-owner.js";import{styles}from"./accordion.styles.js";const VISIBILITY_STYLE=/display|visibility|content-visibility/i;function normalizeMode(value){return value==="single"||value==="single-collapsible"?value:"multiple"}class LyraAccordion extends LyraElement{constructor(){super(...arguments),this.#_mode="multiple",this.panels=new Set,this.#panelsInitialized=!1,this.iconPlacement="end",this.headingLevel="3",this.appearance="outlined",this.#handleSlotChange=event=>{this.#bindPanelsFromSlot(event.target)},this.#itemStateChangeReconciliationPending=!1,this.#handleOwnedItemStateChange=item=>{this.panels.has(item)&&(this.#itemStateChangeReconciliationPending||(this.#itemStateChangeReconciliationPending=!0,queueMicrotask(()=>{this.#itemStateChangeReconciliationPending=!1,this.#reconcileRovingFocus()})))},this.handleFocusIn=event=>{const item=this.#itemFor(event);!item||!this.#isNavigableItem(item)||(this.#lastFocusedItem=item,this.#syncRovingTabIndex(item))},this.handleKeyDown=event=>{if(event.altKey||event.ctrlKey||event.metaKey||event.isComposing)return;const current=this.#itemFor(event);if(!current||!this.#isNavigableItem(current)||!this.#itemTriggerOwnsEvent(current,event))return;const items=this.#navigableItems();if(items.length===0)return;const currentIndex=items.indexOf(current);if(currentIndex<0)return;const forwardKey=this.effectiveDirection==="rtl"?"ArrowLeft":"ArrowRight",backwardKey=this.effectiveDirection==="rtl"?"ArrowRight":"ArrowLeft";let nextIndex;if(event.key==="ArrowDown"||event.key===forwardKey?nextIndex=(currentIndex+1)%items.length:event.key==="ArrowUp"||event.key===backwardKey?nextIndex=(currentIndex-1+items.length)%items.length:event.key==="Home"?nextIndex=0:event.key==="End"&&(nextIndex=items.length-1),nextIndex===void 0)return;event.preventDefault(),event.stopPropagation();const next=items[nextIndex];this.#syncRovingTabIndex(next),next.focus()},this.#handleOwnedItemTransition=(item,expanded,source)=>!this.panels.has(item)||item.disabled||!expanded&&source==="user"&&this.mode==="single"?!1:expanded?this.#emitToggleVeto(item,!1)?this.mode==="multiple"||this.#collapseSiblings(item):!1:this.#emitToggleVeto(item,!0),this.#handleOwnedItemTransitionSettled=(item,expanded)=>{!this.panels.has(item)||item.expanded!==expanded||this.emit(expanded?"lr-after-expand":"lr-after-collapse",{item})}}static{this.identityEventDetailProperties=Object.freeze({"lr-expand":Object.freeze(["item"]),"lr-after-expand":Object.freeze(["item"]),"lr-collapse":Object.freeze(["item"]),"lr-after-collapse":Object.freeze(["item"]),"lr-toggle-request":Object.freeze(["item"])})}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-expand","lr-after-expand","lr-collapse","lr-after-collapse","lr-toggle-request"])}static{this.styles=[LyraElement.styles,styles]}#_mode;#rovingItem;#lastFocusedItem;#availabilityObserver;#panelsInitialized;get mode(){return this.#_mode}set mode(next){const normalized=normalizeMode(next),old=this.#_mode;if(normalized!==old){if(this.#panelsInitialized&&normalized!=="multiple"&&!this.#reconcileExpandedPanels(!1,normalized)){this.requestUpdate("mode",normalized);return}this.#_mode=normalized,this.requestUpdate("mode",old)}}connectedCallback(){super.connectedCallback(),this.#armAvailabilityObserver(),this.hasUpdated&&queueMicrotask(()=>{if(!this.isConnected)return;const slot=this.renderRoot.querySelector("slot");slot&&this.#bindPanels(slot.assignedElements({flatten:!0}))})}disconnectedCallback(){this.#resetAvailabilityObserver();for(const panel of this.panels)releaseAccordionItemOwner(panel,this);this.panels.clear(),this.#rovingItem=void 0,this.#lastFocusedItem=void 0,super.disconnectedCallback()}firstUpdated(changed){super.firstUpdated(changed);const slot=this.itemsSlot;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>this.#bindPanelsFromSlot(s))})}updated(changed){super.updated(changed),(changed.has("iconPlacement")||changed.has("headingLevel")||changed.has("appearance"))&&this.#syncPresentation()}expandAll(){if(this.mode==="multiple")for(const panel of this.panels)panel.disabled||panel.expanded||panel.expand()}collapseAll(){for(const panel of this.panels)panel.expanded&&this.#requestCollapse(panel)}#bindPanels(assigned){const itemTag=tag("accordion-item"),next=assigned.filter(element=>element.localName===itemTag),previous=new Set(this.panels);this.panels.clear();for(const panel of next)this.panels.add(panel);for(const panel of previous)this.panels.has(panel)||releaseAccordionItemOwner(panel,this);this.#syncPresentation(),this.#reconcileExpandedPanels(!this.#panelsInitialized),this.#panelsInitialized=!0,this.#syncRovingTabIndex()}#syncPresentation(){for(const panel of this.panels)bindAccordionItemOwner(panel,{owner:this,iconPlacement:this.iconPlacement,headingLevel:this.headingLevel,appearance:this.appearance,requestTransition:this.#handleOwnedItemTransition,transitionSettled:this.#handleOwnedItemTransitionSettled,stateChanged:this.#handleOwnedItemStateChange})}#reconcileExpandedPanels(silent=!1,mode=this.mode){if(mode==="multiple")return!0;let foundExpanded=!1;for(const panel of this.panels){if(!panel.expanded)continue;if(!foundExpanded){foundExpanded=!0;continue}if(!(silent?this.#performPanelState(panel,!1):this.#requestCollapse(panel)))return!1}return!0}#isNavigableItem(item,excluded=new Map){if(item.disabled)return!1;for(let current=item;current;current=composedParentElement(current)){let hidden=excluded.get(current);if(hidden===void 0&&excluded.set(current,hidden=isAccessibilitySubtreeExcluded(current)),hidden)return!1}return!0}#navigableItems(){const excluded=new Map;return[...this.panels].filter(panel=>this.#isNavigableItem(panel,excluded))}#syncRovingTabIndex(preferred){const items=this.#navigableItems(),active=preferred&&items.includes(preferred)?preferred:this.#rovingItem&&items.includes(this.#rovingItem)?this.#rovingItem:items.find(item=>item.isTabbable)??items[0];active&&(this.#rovingItem=active);for(const panel of this.panels)panel.isTabbable=panel===active;return active}#nextNavigableItem(displaced){const items=[...this.panels],index=items.indexOf(displaced);if(index<0)return this.#navigableItems()[0];const excluded=new Map,available=item=>this.#isNavigableItem(item,excluded);return items.slice(index+1).find(available)??items.slice(0,index).reverse().find(available)}#reconcileRovingFocus(displaced=this.#lastFocusedItem){const unavailable=displaced!==void 0&&this.panels.has(displaced)&&!this.#isNavigableItem(displaced),focused=deepActiveElementIn(this.ownerDocument),wasFocused=displaced===this.#lastFocusedItem&&(focused===null||focused===this.ownerDocument.body||focused===displaced||focused!==null&&displaced?.shadowRoot?.contains(focused)),active=this.#syncRovingTabIndex(unavailable?this.#nextNavigableItem(displaced):void 0);!unavailable||!active||!wasFocused||active.focus()}#armAvailabilityObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected||this.#availabilityObserver)return;const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const observer=new MutationObserverCtor(records=>{if(this.#availabilityObserver!==observer||!this.isConnected||this.ownerDocument!==ownerDocument)return;const touchesVisibility=value=>!!value&&VISIBILITY_STYLE.test(value);records.every(record=>record.attributeName==="style"&&record.target instanceof HTMLElement&&!touchesVisibility(record.oldValue)&&!touchesVisibility(record.target.getAttribute("style")))||this.#reconcileRovingFocus()});this.#availabilityObserver=observer,observer.observe(this,{attributes:!0,attributeOldValue:!0,subtree:!0,attributeFilter:["disabled","hidden","aria-hidden","inert","class","style"]});for(let ancestor=composedParentElement(this);ancestor;ancestor=composedParentElement(ancestor))observer.observe(ancestor,{attributes:!0,attributeOldValue:!0,attributeFilter:["hidden","aria-hidden","inert","class","style"]})}#resetAvailabilityObserver(){this.#availabilityObserver?.disconnect(),this.#availabilityObserver=void 0}#performPanelState(panel,expanded,announce=!1){return applyAccordionItemOwnerState(panel,expanded,announce),panel.expanded===expanded}#emitToggleVeto(item,collapsed){const directional=this.emit(collapsed?"lr-collapse":"lr-expand",{item},{cancelable:!0}),unified=this.emit("lr-toggle-request",{item,collapsed,expanded:!collapsed},{cancelable:!0});return!directional.defaultPrevented&&!unified.defaultPrevented}#requestCollapse(panel){return panel.expanded?this.#emitToggleVeto(panel,!0)?this.#performPanelState(panel,!1,!0):!1:!0}#collapseSiblings(source){for(const panel of this.panels)if(!(panel===source||!panel.expanded)&&!this.#requestCollapse(panel))return!1;return!0}#handleSlotChange;#bindPanelsFromSlot(slot){this.#bindPanels(slot.assignedElements({flatten:!0}))}#itemStateChangeReconciliationPending;#handleOwnedItemStateChange;#itemFor(event){const item=event.composedPath().find(node=>node?.nodeType===1&&node.localName===tag("accordion-item"));return item&&this.panels.has(item)?item:void 0}#itemTriggerOwnsEvent(item,event){return event.composedPath().some(node=>{if(node?.nodeType!==1)return!1;const element=node;return element.localName==="button"&&element.getRootNode()===item.shadowRoot&&element.getAttribute("part")?.split(/\s+/u).includes("button")===!0})}#handleOwnedItemTransition;#handleOwnedItemTransitionSettled;render(){return html`<div
1
+ import{__decorate}from"tslib";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html}from"lit";import{property,query}from"lit/decorators.js";import{composedParentElement,deepActiveElementIn}from"../../../internal/active-element.js";import{isAccessibilitySubtreeExcluded}from"../../../internal/accessibility-visibility.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{LyraElement}from"../../../internal/lyra-element.js";import{tag}from"../../../internal/prefix.js";import{applyAccordionItemOwnerState,bindAccordionItemOwner,releaseAccordionItemOwner}from"./accordion-owner.js";import{styles}from"./accordion.styles.js";const VISIBILITY_STYLE=/display|visibility|content-visibility/i;function normalizeMode(value){return value==="single"||value==="single-collapsible"?value:"multiple"}class LyraAccordion extends LyraElement{constructor(){super(...arguments),this.#_mode="multiple",this.panels=new Set,this.#panelsInitialized=!1,this.iconPlacement="end",this.headingLevel="3",this.appearance="outlined",this.#handleSlotChange=event=>{this.#bindPanelsFromSlot(event.target)},this.#itemStateChangeReconciliationPending=!1,this.#handleOwnedItemStateChange=item=>{this.panels.has(item)&&(this.#itemStateChangeReconciliationPending||(this.#itemStateChangeReconciliationPending=!0,queueMicrotask(()=>{this.#itemStateChangeReconciliationPending=!1,this.#reconcileRovingFocus()})))},this.handleFocusIn=event=>{const item=this.#itemFor(event);!item||!this.#isNavigableItem(item)||(this.#lastFocusedItem=item,this.#syncRovingTabIndex(item))},this.handleKeyDown=event=>{if(event.altKey||event.ctrlKey||event.metaKey||event.isComposing)return;const current=this.#itemFor(event);if(!current||!this.#isNavigableItem(current)||!this.#itemTriggerOwnsEvent(current,event))return;const items=this.#navigableItems();if(items.length===0)return;const currentIndex=items.indexOf(current);if(currentIndex<0)return;const forwardKey=this.effectiveDirection==="rtl"?"ArrowLeft":"ArrowRight",backwardKey=this.effectiveDirection==="rtl"?"ArrowRight":"ArrowLeft";let nextIndex;if(event.key==="ArrowDown"||event.key===forwardKey?nextIndex=(currentIndex+1)%items.length:event.key==="ArrowUp"||event.key===backwardKey?nextIndex=(currentIndex-1+items.length)%items.length:event.key==="Home"?nextIndex=0:event.key==="End"&&(nextIndex=items.length-1),nextIndex===void 0)return;event.preventDefault(),event.stopPropagation();const next=items[nextIndex];this.#syncRovingTabIndex(next),next.focus()},this.#handleOwnedItemTransition=(item,expanded,source)=>!this.panels.has(item)||item.disabled||!expanded&&source==="user"&&this.mode==="single"?!1:expanded?this.#emitToggleVeto(item,!1)?this.mode==="multiple"||this.#collapseSiblings(item):!1:this.#emitToggleVeto(item,!0),this.#handleOwnedItemTransitionSettled=(item,expanded)=>{!this.panels.has(item)||item.expanded!==expanded||this.emit(expanded?"lr-after-expand":"lr-after-collapse",{item})}}static{this.identityEventDetailProperties=Object.freeze({"lr-expand":Object.freeze(["item"]),"lr-after-expand":Object.freeze(["item"]),"lr-collapse":Object.freeze(["item"]),"lr-after-collapse":Object.freeze(["item"]),"lr-toggle-request":Object.freeze(["item"])})}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-expand","lr-after-expand","lr-collapse","lr-after-collapse","lr-toggle-request"])}static{this.styles=[LyraElement.styles,styles]}#_mode;#rovingItem;#lastFocusedItem;#availabilityObserver;#panelsInitialized;get mode(){return this.#_mode}set mode(next){const normalized=normalizeMode(next),old=this.#_mode;if(normalized!==old){if(this.#panelsInitialized&&normalized!=="multiple"&&!this.#reconcileExpandedPanels(!1,normalized)){this.requestUpdate("mode",normalized);return}this.#_mode=normalized,this.requestUpdate("mode",old)}}connectedCallback(){super.connectedCallback(),this.#armAvailabilityObserver(),this.hasUpdated&&queueMicrotask(()=>{if(!this.isConnected)return;const slot=this.renderRoot.querySelector("slot");slot&&this.#bindPanels(slot.assignedElements({flatten:!0}))})}disconnectedCallback(){this.#resetAvailabilityObserver();for(const panel of this.panels)releaseAccordionItemOwner(panel,this);this.panels.clear(),this.#rovingItem=void 0,this.#lastFocusedItem=void 0,super.disconnectedCallback()}firstUpdated(changed){super.firstUpdated(changed);const slot=this.itemsSlot;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>this.#bindPanelsFromSlot(s))})}updated(changed){super.updated(changed),(changed.has("iconPlacement")||changed.has("headingLevel")||changed.has("appearance"))&&this.#syncPresentation()}expandAll(){if(this.mode==="multiple")for(const panel of this.panels)panel.disabled||panel.expanded||panel.expand()}collapseAll(){for(const panel of this.panels)panel.expanded&&this.#requestCollapse(panel)}#bindPanels(assigned){const itemTag=tag("accordion-item"),next=assigned.filter(element=>element.localName===itemTag),previous=new Set(this.panels);this.panels.clear();for(const panel of next)this.panels.add(panel);for(const panel of previous)this.panels.has(panel)||releaseAccordionItemOwner(panel,this);this.#syncPresentation(),this.#reconcileExpandedPanels(!this.#panelsInitialized),this.#panelsInitialized=!0,this.#syncRovingTabIndex()}#syncPresentation(){for(const panel of this.panels)bindAccordionItemOwner(panel,{owner:this,iconPlacement:this.iconPlacement,headingLevel:this.headingLevel,appearance:this.appearance,requestTransition:this.#handleOwnedItemTransition,transitionSettled:this.#handleOwnedItemTransitionSettled,stateChanged:this.#handleOwnedItemStateChange})}#reconcileExpandedPanels(silent=!1,mode=this.mode){if(mode==="multiple")return!0;let foundExpanded=!1;for(const panel of this.panels){if(!panel.expanded)continue;if(!foundExpanded){foundExpanded=!0;continue}if(!(silent?this.#performPanelState(panel,!1):this.#requestCollapse(panel)))return!1}return!0}#isNavigableItem(item,excluded=new Map){if(item.disabled)return!1;for(let current=item;current;current=composedParentElement(current)){let hidden=excluded.get(current);if(hidden===void 0&&excluded.set(current,hidden=isAccessibilitySubtreeExcluded(current)),hidden)return!1}return!0}#navigableItems(){const excluded=new Map;return[...this.panels].filter(panel=>this.#isNavigableItem(panel,excluded))}#syncRovingTabIndex(preferred){const items=this.#navigableItems(),active=preferred&&items.includes(preferred)?preferred:this.#rovingItem&&items.includes(this.#rovingItem)?this.#rovingItem:items.find(item=>item.isTabbable)??items[0];active&&(this.#rovingItem=active);for(const panel of this.panels)panel.isTabbable=panel===active;return active}#nextNavigableItem(displaced){const items=[...this.panels],index=items.indexOf(displaced);if(index<0)return this.#navigableItems()[0];const excluded=new Map,available=item=>this.#isNavigableItem(item,excluded);return items.slice(index+1).find(available)??items.slice(0,index).reverse().find(available)}#reconcileRovingFocus(displaced=this.#lastFocusedItem){const unavailable=displaced!==void 0&&this.panels.has(displaced)&&!this.#isNavigableItem(displaced),focused=deepActiveElementIn(this.ownerDocument),wasFocused=displaced===this.#lastFocusedItem&&(focused===null||focused===this.ownerDocument.body||focused===displaced||focused!==null&&displaced?.shadowRoot?.contains(focused)),active=this.#syncRovingTabIndex(unavailable?this.#nextNavigableItem(displaced):void 0);!unavailable||!active||!wasFocused||active.focus()}#armAvailabilityObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected||this.#availabilityObserver)return;const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const observer=new MutationObserverCtor(records=>{if(this.#availabilityObserver!==observer||!this.isConnected||this.ownerDocument!==ownerDocument)return;const touchesVisibility=value=>!!value&&VISIBILITY_STYLE.test(value);records.every(record=>record.attributeName==="style"&&record.target instanceof HTMLElement&&!touchesVisibility(record.oldValue)&&!touchesVisibility(record.target.getAttribute("style")))||this.#reconcileRovingFocus()});this.#availabilityObserver=observer,observer.observe(this,{attributes:!0,attributeOldValue:!0,subtree:!0,attributeFilter:["disabled","hidden","aria-hidden","inert","class","style"]});for(let ancestor=composedParentElement(this);ancestor;ancestor=composedParentElement(ancestor))observer.observe(ancestor,{attributes:!0,attributeOldValue:!0,attributeFilter:["hidden","aria-hidden","inert","class","style"]})}#resetAvailabilityObserver(){this.#availabilityObserver?.disconnect(),this.#availabilityObserver=void 0}#performPanelState(panel,expanded,announce=!1){return applyAccordionItemOwnerState(panel,expanded,announce),panel.expanded===expanded}#emitToggleVeto(item,collapsed){const directional=this.emit(collapsed?"lr-collapse":"lr-expand",{item},{cancelable:!0}),unified=this.emit("lr-toggle-request",{item,collapsed,expanded:!collapsed},{cancelable:!0});return!directional.defaultPrevented&&!unified.defaultPrevented}#requestCollapse(panel){return panel.expanded?this.#emitToggleVeto(panel,!0)?this.#performPanelState(panel,!1,!0):!1:!0}#collapseSiblings(source){for(const panel of this.panels)if(!(panel===source||!panel.expanded)&&!this.#requestCollapse(panel))return!1;return!0}#handleSlotChange;#bindPanelsFromSlot(slot){this.isConnected&&this.#bindPanels(slot.assignedElements({flatten:!0}))}#itemStateChangeReconciliationPending;#handleOwnedItemStateChange;#itemFor(event){const item=event.composedPath().find(node=>node?.nodeType===1&&node.localName===tag("accordion-item"));return item&&this.panels.has(item)?item:void 0}#itemTriggerOwnsEvent(item,event){return event.composedPath().some(node=>{if(node?.nodeType!==1)return!1;const element=node;return element.localName==="button"&&element.getRootNode()===item.shadowRoot&&element.getAttribute("part")?.split(/\s+/u).includes("button")===!0})}#handleOwnedItemTransition;#handleOwnedItemTransitionSettled;render(){return html`<div
2
2
  part="base"
3
3
  @focusin=${this.handleFocusIn}
4
4
  @keydown=${this.handleKeyDown}
@@ -1,9 +1,9 @@
1
- import{__decorate}from"tslib";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{tag}from"../../../internal/prefix.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{collectFocusableElements,deepActiveElement}from"../../../internal/overlay-manager.js";import{getDateTimeFormat,getListFormat}from"../../../internal/intl-cache.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{DebounceController}from"../../../internal/debounce-controller.js";import{srOnly}from"../../../internal/a11y.js";import{styles}from"./filter-bar.styles.js";import{LYRA_DEFAULT_filterBarActiveFilters,LYRA_DEFAULT_filterBarReset}from"../../../internal/default-strings/layout.generated.js";import{LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings/shared.generated.js";const MAX_FILTER_COLLECTION_ENTRIES=1e4,MAX_FILTER_COLLECTION_NODES=5e4,MAX_FILTER_COLLECTION_DEPTH=16,OMIT_FILTER_VALUE=Symbol("omit-filter-value"),EMPTY_FILTERS=Object.freeze([]),EMPTY_VALUE=Object.freeze({}),EMPTY_DATE_PRESETS=Object.freeze([]);function isPlainFilterRecord(value){try{const prototype=Object.getPrototypeOf(value);return prototype===null||Object.getPrototypeOf(prototype)===null}catch{return!1}}function snapshotFilterEntry(value,budget,depth){if(value===null||typeof value!="object"&&typeof value!="function"||typeof value=="function")return value;if(depth>MAX_FILTER_COLLECTION_DEPTH||budget.remaining<=0)return OMIT_FILTER_VALUE;const existing=budget.seen.get(value);if(existing!==void 0)return existing;let isArray=!1;try{isArray=Array.isArray(value)}catch{return OMIT_FILTER_VALUE}if(isArray){const output2=[];budget.seen.set(value,output2);let length=0;try{const descriptor=Object.getOwnPropertyDescriptor(value,"length");descriptor&&"value"in descriptor&&typeof descriptor.value=="number"&&Number.isSafeInteger(descriptor.value)&&descriptor.value>=0&&(length=Math.min(descriptor.value,MAX_FILTER_COLLECTION_ENTRIES))}catch{return Object.freeze(output2)}for(let index=0;index<length&&budget.remaining>0;index+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value,String(index))}catch{continue}if(!descriptor||!("value"in descriptor))continue;budget.remaining-=1;const entry=snapshotFilterEntry(descriptor.value,budget,depth+1);entry!==OMIT_FILTER_VALUE&&output2.push(entry)}return Object.freeze(output2)}if(!isPlainFilterRecord(value))return value;const output={};budget.seen.set(value,output);let descriptors;try{descriptors=Object.getOwnPropertyDescriptors(value)}catch{return OMIT_FILTER_VALUE}let retained=0;for(const key of Reflect.ownKeys(descriptors)){if(retained>=MAX_FILTER_COLLECTION_ENTRIES||budget.remaining<=0)break;const descriptor=descriptors[key];if(!descriptor?.enumerable||!("value"in descriptor))continue;retained+=1,budget.remaining-=1;const entry=key==="icon"?descriptor.value:snapshotFilterEntry(descriptor.value,budget,depth+1);entry!==OMIT_FILTER_VALUE&&Object.defineProperty(output,key,{value:entry,enumerable:!0,configurable:!1,writable:!1})}return Object.freeze(output)}function snapshotFilterDefinitions(value){let isArray=!1;try{isArray=Array.isArray(value)}catch{return EMPTY_FILTERS}return isArray?snapshotFilterEntry(value,{remaining:MAX_FILTER_COLLECTION_NODES,seen:new WeakMap},0):EMPTY_FILTERS}function snapshotFilterFieldValue(value){let isArray=!1;try{isArray=Array.isArray(value)}catch{return}if(!isArray)return typeof value=="string"||typeof value=="boolean"||value===void 0?value:void 0;const output=[];let sourceLength=0;try{const descriptor=Object.getOwnPropertyDescriptor(value,"length");descriptor&&"value"in descriptor&&typeof descriptor.value=="number"&&Number.isSafeInteger(descriptor.value)&&descriptor.value>=0&&(sourceLength=descriptor.value)}catch{return Object.freeze(output)}const length=Math.min(sourceLength,MAX_FILTER_COLLECTION_ENTRIES);for(let index=0;index<length;index+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value,String(index))}catch{continue}descriptor&&"value"in descriptor&&typeof descriptor.value=="string"&&output.push(descriptor.value)}return Object.freeze(output)}const SELECT_EXPORT_PARTS=["form-control-label: filter-control-label","trigger: filter-control-field","display-input: filter-control-input","start: filter-control-start","end: filter-control-end","listbox: filter-control-listbox","option: filter-control-option","clear-button: filter-control-clear-button","expand-icon: filter-control-expand-icon","error: filter-control-error","hint: filter-control-hint"].join(", "),COMBOBOX_EXPORT_PARTS=["form-control-label: filter-control-label","combobox: filter-control-field","combobox-input: filter-control-input","start: filter-control-start","end: filter-control-end","listbox: filter-control-listbox","option: filter-control-option","tags: filter-control-tags","tag: filter-control-tag","tag-overflow: filter-control-tag-overflow","tag-label: filter-control-tag-label","tag__remove-button: filter-control-tag-remove-button","tag__remove-button__base: filter-control-tag-remove-button-base","clear-button: filter-control-clear-button","expand-icon: filter-control-expand-icon","error: filter-control-error","hint: filter-control-hint"].join(", "),INPUT_EXPORT_PARTS=["form-control-label: filter-control-label","input-wrapper: filter-control-field","input: filter-control-input","start: filter-control-start","end: filter-control-end","clear-button: filter-control-clear-button","error: filter-control-error","hint: filter-control-hint"].join(", "),CHECKBOX_MENU_EXPORT_PARTS=["base: filter-control-listbox"].join(", "),CHECKBOX_MENU_TRIGGER_EXPORT_PARTS=["base: filter-control-field","start: filter-control-start","label: filter-control-label-group","caret: filter-control-expand-icon"].join(", "),DATE_INPUT_EXPORT_PARTS=["form-control-label: filter-control-label","input-wrapper: filter-control-field","input: filter-control-input","start: filter-control-start","end: filter-control-end","clear-button: filter-control-clear-button","expand-button: filter-control-expand-button","expand-icon: filter-control-expand-icon","popup: filter-control-popup","error: filter-control-error","hint: filter-control-hint"].join(", "),SAFE_FILTER_ID_PART=/^[a-zA-Z][a-zA-Z0-9_-]*$/;function fieldPartNames(filterId){return SAFE_FILTER_ID_PART.test(filterId)?`field field-${filterId}`:"field"}function isChoiceDefinition(definition){return definition.type==="select"||definition.type==="combobox"||definition.type==="checkbox-menu"}function isBuiltInSet(value){return value==null?!1:typeof value=="boolean"?value:Array.isArray(value)?value.length>0:value!==""}function filterValueEqualsDefault(value,defaultValue){const valueIsArray=Array.isArray(value),defaultIsArray=Array.isArray(defaultValue);return valueIsArray||defaultIsArray?!valueIsArray||!defaultIsArray?!1:value.length===defaultValue.length&&value.every((entry,index)=>entry===defaultValue[index]):Object.is(value,defaultValue)}function defineFilterValueEntry(record,key,value){Object.defineProperty(record,key,{value,enumerable:!0,configurable:!0,writable:!0})}function cloneFilterValueRecord(value){const clone={},descriptors=Object.getOwnPropertyDescriptors(value);let retained=0;for(const key of Reflect.ownKeys(descriptors)){if(retained>=MAX_FILTER_COLLECTION_ENTRIES)break;const descriptor=descriptors[key];if(typeof key!="string"||!descriptor?.enumerable||!("value"in descriptor))continue;retained+=1;const fieldValue=snapshotFilterFieldValue(descriptor.value);fieldValue!==void 0&&defineFilterValueEntry(clone,key,fieldValue)}return clone}function cloneFilterValue(value){return Object.freeze(cloneFilterValueRecord(value))}class LyraFilterBar extends LyraElement{constructor(){super(...arguments),this.label="",this.disabled=!1,this.loading=!1,this.activeFiltersDisplay="all",this.touchedFilters=new Set,this.slotPresence=new SlotPresenceController(this),this._filters=EMPTY_FILTERS,this._value=EMPTY_VALUE,this.rawValue=EMPTY_VALUE,this.debounceControllers=new Map,this.chipFocusGeneration=0,this.schemaGeneration=0,this.onControlChange=(def,e)=>{const control=e.target;if(def.type==="combobox"&&this.isDebounced(def.debounce)){this.scheduleDebounce(def.filterId,control.value,def.debounce);return}this.setFilterValue(def.filterId,control.value,control.appliedPreset)},this.stopControlAlias=event=>{event.stopPropagation()},this.onCustomControlChange=(def,generation,e)=>{e.stopPropagation();const next=def.custom.adapter.valueFromEvent(e);if(this.isDebounced(def.debounce)){this.scheduleDebounce(def.filterId,next,def.debounce,pending=>this.setCustomContextValue(def,generation,pending));return}this.setCustomContextValue(def,generation,next)},this.stopMenuItemChangeAlias=event=>{event.stopPropagation()}}static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,filterBarActiveFilters:LYRA_DEFAULT_filterBarActiveFilters,filterBarReset:LYRA_DEFAULT_filterBarReset}}static{this.styles=[LyraElement.styles,srOnly,styles]}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-validity-change"])}static{this.properties={filters:{attribute:!1,noAccessor:!0},value:{attribute:!1,noAccessor:!0}}}get filters(){return this._filters}set filters(next){if(next===this.filtersInput)return;this.filtersInput=next;const old=this._filters,widened=next;this.cancelDebounce(),this.renewSchemaContext();const seen=new Set;this._filters=Object.freeze(snapshotFilterDefinitions(widened).filter(definition=>{try{return!definition||typeof definition.filterId!="string"||definition.filterId.length===0||definition.filterId!==definition.filterId.trim()||typeof definition.label!="string"||definition.label.trim().length===0||seen.has(definition.filterId)||isChoiceDefinition(definition)&&!Array.isArray(definition.options)||definition.type==="custom"&&(!definition.custom?.adapter||typeof definition.custom.render!="function")?!1:(seen.add(definition.filterId),!0)}catch{return!1}}).map(definition=>{const choices=definition.options;if(choices===void 0)return definition;const options=(Array.isArray(choices)?choices:[]).filter(option=>{try{return option!==null&&typeof option=="object"&&typeof Object.getOwnPropertyDescriptor(option,"value")?.value=="string"&&typeof Object.getOwnPropertyDescriptor(option,"label")?.value=="string"}catch{return!1}});return Object.freeze({...definition,options:Object.freeze(options)})}));const ids=new Set(this._filters.map(definition=>definition.filterId));this.touchedFilters=new Set([...this.touchedFilters].filter(id=>ids.has(id)));const oldValue=this._value;this._value=this.normalizeValue(this.rawValue),this.requestUpdate("filters",old),this._value!==oldValue&&this.requestUpdate("value",oldValue)}get value(){return cloneFilterValue(this._value)}set value(next){if(next===this.valueInput)return;this.valueInput=next;const old=this._value,widened=next;try{this.rawValue=cloneFilterValue(widened??EMPTY_VALUE)}catch{this.rawValue=EMPTY_VALUE}this._value=this.normalizeValue(widened),this.requestUpdate("value",old)}renewSchemaContext(){this.schemaAbortController?.abort();const AbortControllerCtor=this.ownerDocument.defaultView?.AbortController??AbortController;this.schemaAbortController=new AbortControllerCtor,this.schemaGeneration+=1}get schemaSignal(){return this.schemaAbortController||this.renewSchemaContext(),this.schemaAbortController.signal}isEmpty(def,value){if(def.type==="chip")return typeof def.isEmpty=="function"?def.isEmpty(value):!isBuiltInSet(value);if(def.type!=="custom")return!isBuiltInSet(value);const{adapter}=def.custom;if(adapter.isEmpty)return adapter.isEmpty(value);const clear=adapter.clearValue;return Array.isArray(value)&&Array.isArray(clear)?value.length===clear.length&&value.every((entry,index)=>entry===clear[index]):Object.is(value,clear)}valueFor(def){return Object.prototype.hasOwnProperty.call(this._value,def.filterId)?this._value[def.filterId]:def.type==="custom"?def.custom.adapter.clearValue:def.type==="chip"?def.clearValue:void 0}normalizeValue(value){const normalized={};for(const def of this._filters){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value??{},def.filterId)}catch{continue}if(!descriptor||!("value"in descriptor))continue;const fieldValue=snapshotFilterFieldValue(descriptor.value);this.isEmpty(def,fieldValue)||defineFilterValueEntry(normalized,def.filterId,fieldValue)}return Object.freeze(normalized)}get hasActiveFilters(){return this._filters.some(def=>!this.isEmpty(def,this.valueFor(def)))}filterIsChanged(def){const value=this.valueFor(def),defaultValue=def.defaultValue;return defaultValue!==void 0&&!this.isEmpty(def,defaultValue)?!filterValueEqualsDefault(value,defaultValue):!this.isEmpty(def,value)}get hasChangedFilters(){return this._filters.some(def=>this.filterIsChanged(def))}get hasResettableFilters(){return this.activeFiltersDisplay==="changed"?this.hasChangedFilters:this.hasActiveFilters}get invalidFilterIds(){return Object.freeze(this._filters.filter(def=>def.required&&this.isEmpty(def,this.valueFor(def))).map(def=>def.filterId))}checkValidity(){return this.invalidFilterIds.length===0}reportValidity(){const invalid=this.invalidFilterIds;return invalid.length&&(this.touchedFilters=new Set([...this.touchedFilters,...invalid])),invalid.length===0}reset(){if(this.disabled)return;this.cancelDebounce(),this.touchedFilters=new Set;const self=this;self.value=self.resetValue,self.emit("lr-input",Object.freeze({value:self.value,filterId:void 0,appliedPreset:void 0})),self.emit("lr-reset",Object.freeze({value:self.value}))}get resetValue(){const out={};for(const def of this._filters)if(def.defaultValue!==void 0&&!this.isEmpty(def,def.defaultValue)){const value=Array.isArray(def.defaultValue)?Object.freeze([...def.defaultValue]):def.defaultValue;defineFilterValueEntry(out,def.filterId,value)}return Object.freeze(out)}setFilterValue(id,value,appliedPreset){const definition=this._filters.find(candidate=>candidate.filterId===id);if(this.disabled||!definition)return;const next={...this._value};this.isEmpty(definition,value)?delete next[id]:defineFilterValueEntry(next,id,value);const self=this;self.value=next,self.emit("lr-input",Object.freeze({value:self.value,filterId:id,appliedPreset}))}setCustomContextValue(definition,generation,value){generation!==this.schemaGeneration||this.schemaSignal.aborted||!this.isConnected||!this._filters.includes(definition)||this.setFilterValue(definition.filterId,value)}markTouched(id){this.disabled||this.touchedFilters.has(id)||(this.touchedFilters=new Set(this.touchedFilters).add(id))}isDebounced(delay){return typeof delay=="number"&&Number.isFinite(delay)&&delay>0}scheduleDebounce(id,value,delay,commit=pending=>this.setFilterValue(id,pending)){let controller=this.debounceControllers.get(id);if(!controller){const created=new DebounceController(delay,pending=>{this.debounceControllers.get(id)===created&&this.debounceControllers.delete(id),pending!==void 0&&commit(pending)});controller=created,this.debounceControllers.set(id,created)}controller.delayMs=delay,controller.push(value)}hasPendingDebounce(id){return this.debounceControllers.get(id)?.pending??!1}onTextInput(def,e){if(this.disabled)return;const next=e.target.value??"";if(!this.isDebounced(def.debounce)){this.cancelDebounce(def.filterId),this.setFilterValue(def.filterId,next);return}this.scheduleDebounce(def.filterId,next,def.debounce)}flushDebounce(id){this.debounceControllers.get(id)?.flush()}cancelDebounce(id){for(const[key,controller]of this.debounceControllers)id!==void 0&&key!==id||(controller.dispose(),this.debounceControllers.delete(key))}onFieldFocusout(id){this.flushDebounce(id),this.markTouched(id)}repairFocusAfterChipRemoval(index,filterId,shouldRepairFocus){const generation=++this.chipFocusGeneration;shouldRepairFocus&&this.updateComplete.then(()=>{if(!this.isConnected||this.disabled||generation!==this.chipFocusGeneration||deepActiveElement(this.ownerDocument)!==this.ownerDocument.body)return;const chips=this.renderRoot.querySelectorAll('[part="chip"]'),chip=chips[Math.min(index,chips.length-1)],target=chip?collectFocusableElements(chip)[0]:void 0;if(target){target.focus();return}for(const control of this.renderRoot.querySelectorAll("[data-filter-id]"))if(control.dataset.filterId===filterId){collectFocusableElements(control)[0]?.focus();return}})}clearFilter(id,shouldRepairFocus=!1){if(this.disabled)return;this.cancelDebounce(id);const index=this.activeEntries.findIndex(entry=>entry.def.filterId===id),def=this._filters.find(f=>f.filterId===id);if(!def)return;const clearValue=def.type==="custom"?def.custom.adapter.clearValue:def.type==="chip"?def.clearValue??"":def.type==="checkbox-menu"||def.type==="combobox"&&def.multiple?[]:"";this.setFilterValue(id,clearValue),this.repairFocusAfterChipRemoval(Math.max(0,index),id,shouldRepairFocus)}displayValueFor(def,value){if(def.type==="custom"){const formatted=def.custom?.adapter.formatValue?.(value,this.effectiveLocale);return formatted!==void 0?formatted:Array.isArray(value)?getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(value):value===void 0?"":String(value)}if(def.type==="chip"){const formatted=typeof def.formatValue=="function"?def.formatValue(value,this.effectiveLocale):void 0;return formatted!==void 0?formatted:Array.isArray(value)?getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(value):value===void 0?"":String(value)}if(isChoiceDefinition(def)){const labels=(Array.isArray(value)?value.filter(entry=>typeof entry=="string"):typeof value=="string"?[value]:[]).map(v=>def.options?.find(o=>o.value===v)?.label??v);return labels.length>1?getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(labels):labels[0]??""}if(def.type==="text")return typeof value=="string"?value:"";if(typeof value!="string")return"";const formatter=getDateTimeFormat(this.effectiveLocale,{year:"numeric",month:"short",day:"numeric",timeZone:"UTC"}),parseIso=input=>{const match=/^(\d{4})-(\d{2})-(\d{2})$/.exec(input);if(!match)return;const year=Number(match[1]),month=Number(match[2]),day=Number(match[3]),date=new Date(0);return date.setUTCHours(0,0,0,0),date.setUTCFullYear(year,month-1,day),date.getUTCFullYear()===year&&date.getUTCMonth()===month-1&&date.getUTCDate()===day?date:void 0},segments=value.split("/");if(def.type==="date"&&segments.length!==1||def.type==="date-range"&&segments.length!==2)return value;const[startText,endText]=segments,start=parseIso(startText??""),end=endText===void 0?void 0:parseIso(endText);return!start||endText!==void 0&&(!end||end.getTime()<start.getTime())?value:end?formatter.formatRange(start,end):formatter.format(start)}get activeEntries(){return this.activeFiltersDisplay==="hidden"?[]:this._filters.filter(def=>!this.isEmpty(def,this.valueFor(def))).filter(def=>this.activeFiltersDisplay!=="changed"||!filterValueEqualsDefault(this.valueFor(def),def.defaultValue)).map(def=>({def,display:this.displayValueFor(def,this.valueFor(def))}))}disconnectedCallback(){super.disconnectedCallback(),this.cancelDebounce(),this.closeCheckboxMenus(),this.schemaAbortController?.abort(),this.schemaAbortController=void 0,this.schemaGeneration+=1}closeCheckboxMenus(){for(const menu of this.renderRoot?.querySelectorAll(`${tag("dropdown")}[data-filter-id]`)??[])menu.open&&(menu.open=!1)}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.closeCheckboxMenus(),(!this.schemaAbortController||this.schemaAbortController.signal.aborted)&&(this.renewSchemaContext(),this.hasUpdated&&this.requestUpdate()),this.hasUpdated&&queueMicrotask(()=>{this.isConnected&&this.syncTextControls()})}syncTextControls(){if(!this._filters.some(def=>def.type==="text"))return;const fields=new Map;for(const node of this.renderRoot.querySelectorAll(`${tag("input")}[data-filter-id]`)){const element=node,id=element.dataset.filterId;id!==void 0&&fields.set(id,element)}for(const def of this._filters){if(def.type!=="text"||this.hasPendingDebounce(def.filterId))continue;const field=fields.get(def.filterId);if(!field)continue;const raw=this._value[def.filterId],next=typeof raw=="string"?raw:"";field.value!==next&&(field.value=next)}}willUpdate(changed){super.willUpdate(changed),changed.has("disabled")&&this.disabled&&this.cancelDebounce()}updated(changed){if(super.updated(changed),this.syncTextControls(),changed.has("value")||changed.has("filters")){const invalidFilterIds=this.invalidFilterIds,valid=invalidFilterIds.length===0,key=JSON.stringify({valid,invalidFilterIds});key!==this.lastValidityKey&&(this.lastValidityKey=key,this.emit("lr-validity-change",Object.freeze({valid,invalidFilterIds:Object.freeze([...invalidFilterIds])})))}}renderStartAdornment(icon,slotName="start"){return icon==null?nothing:html`<span slot=${slotName} aria-hidden="true" inert>${icon}</span>`}renderOption(option){return html`<lr-option
1
+ import{__decorate}from"tslib";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{tag}from"../../../internal/prefix.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{collectFocusableElements,deepActiveElement}from"../../../internal/overlay-manager.js";import{getDateTimeFormat,getListFormat}from"../../../internal/intl-cache.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{DebounceController}from"../../../internal/debounce-controller.js";import{srOnly}from"../../../internal/a11y.js";import{styles}from"./filter-bar.styles.js";import{LYRA_DEFAULT_filterBarActiveFilters,LYRA_DEFAULT_filterBarReset}from"../../../internal/default-strings/layout.generated.js";import{LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings/shared.generated.js";const MAX_FILTER_COLLECTION_ENTRIES=1e4,MAX_FILTER_COLLECTION_NODES=5e4,MAX_FILTER_COLLECTION_DEPTH=16,OMIT_FILTER_VALUE=Symbol("omit-filter-value"),EMPTY_FILTERS=Object.freeze([]),EMPTY_VALUE=Object.freeze({}),EMPTY_DATE_PRESETS=Object.freeze([]);function isPlainFilterRecord(value){try{const prototype=Object.getPrototypeOf(value);return prototype===null||Object.getPrototypeOf(prototype)===null}catch{return!1}}function snapshotFilterEntry(value,budget,depth){if(value===null||typeof value!="object"&&typeof value!="function"||typeof value=="function")return value;if(depth>MAX_FILTER_COLLECTION_DEPTH||budget.remaining<=0)return OMIT_FILTER_VALUE;const existing=budget.seen.get(value);if(existing!==void 0)return existing;let isArray=!1;try{isArray=Array.isArray(value)}catch{return OMIT_FILTER_VALUE}if(isArray){const output2=[];budget.seen.set(value,output2);let length=0;try{const descriptor=Object.getOwnPropertyDescriptor(value,"length");descriptor&&"value"in descriptor&&typeof descriptor.value=="number"&&Number.isSafeInteger(descriptor.value)&&descriptor.value>=0&&(length=Math.min(descriptor.value,MAX_FILTER_COLLECTION_ENTRIES))}catch{return Object.freeze(output2)}for(let index=0;index<length&&budget.remaining>0;index+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value,String(index))}catch{continue}if(!descriptor||!("value"in descriptor))continue;budget.remaining-=1;const entry=snapshotFilterEntry(descriptor.value,budget,depth+1);entry!==OMIT_FILTER_VALUE&&output2.push(entry)}return Object.freeze(output2)}if(!isPlainFilterRecord(value))return value;const output={};budget.seen.set(value,output);let descriptors;try{descriptors=Object.getOwnPropertyDescriptors(value)}catch{return OMIT_FILTER_VALUE}let retained=0;for(const key of Reflect.ownKeys(descriptors)){if(retained>=MAX_FILTER_COLLECTION_ENTRIES||budget.remaining<=0)break;const descriptor=descriptors[key];if(!descriptor?.enumerable||!("value"in descriptor))continue;retained+=1,budget.remaining-=1;const entry=key==="icon"?descriptor.value:snapshotFilterEntry(descriptor.value,budget,depth+1);entry!==OMIT_FILTER_VALUE&&Object.defineProperty(output,key,{value:entry,enumerable:!0,configurable:!1,writable:!1})}return Object.freeze(output)}function snapshotFilterDefinitions(value){let isArray=!1;try{isArray=Array.isArray(value)}catch{return EMPTY_FILTERS}return isArray?snapshotFilterEntry(value,{remaining:MAX_FILTER_COLLECTION_NODES,seen:new WeakMap},0):EMPTY_FILTERS}function snapshotFilterFieldValue(value){let isArray=!1;try{isArray=Array.isArray(value)}catch{return}if(!isArray)return typeof value=="string"||typeof value=="boolean"||value===void 0?value:void 0;const output=[];let sourceLength=0;try{const descriptor=Object.getOwnPropertyDescriptor(value,"length");descriptor&&"value"in descriptor&&typeof descriptor.value=="number"&&Number.isSafeInteger(descriptor.value)&&descriptor.value>=0&&(sourceLength=descriptor.value)}catch{return Object.freeze(output)}const length=Math.min(sourceLength,MAX_FILTER_COLLECTION_ENTRIES);for(let index=0;index<length;index+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value,String(index))}catch{continue}descriptor&&"value"in descriptor&&typeof descriptor.value=="string"&&output.push(descriptor.value)}return Object.freeze(output)}const SELECT_EXPORT_PARTS=["form-control-label: filter-control-label","trigger: filter-control-field","display-input: filter-control-input","start: filter-control-start","end: filter-control-end","listbox: filter-control-listbox","option: filter-control-option","clear-button: filter-control-clear-button","expand-icon: filter-control-expand-icon","error: filter-control-error","hint: filter-control-hint"].join(", "),COMBOBOX_EXPORT_PARTS=["form-control-label: filter-control-label","combobox: filter-control-field","combobox-input: filter-control-input","start: filter-control-start","end: filter-control-end","listbox: filter-control-listbox","option: filter-control-option","tags: filter-control-tags","tag: filter-control-tag","tag-overflow: filter-control-tag-overflow","tag-label: filter-control-tag-label","tag__remove-button: filter-control-tag-remove-button","tag__remove-button__base: filter-control-tag-remove-button-base","clear-button: filter-control-clear-button","expand-icon: filter-control-expand-icon","error: filter-control-error","hint: filter-control-hint"].join(", "),INPUT_EXPORT_PARTS=["form-control-label: filter-control-label","input-wrapper: filter-control-field","input: filter-control-input","start: filter-control-start","end: filter-control-end","clear-button: filter-control-clear-button","error: filter-control-error","hint: filter-control-hint"].join(", "),CHECKBOX_MENU_EXPORT_PARTS=["base: filter-control-listbox"].join(", "),CHECKBOX_MENU_TRIGGER_EXPORT_PARTS=["base: filter-control-field","start: filter-control-start","label: filter-control-label-group","caret: filter-control-expand-icon"].join(", "),DATE_INPUT_EXPORT_PARTS=["form-control-label: filter-control-label","input-wrapper: filter-control-field","input: filter-control-input","start: filter-control-start","end: filter-control-end","clear-button: filter-control-clear-button","expand-button: filter-control-expand-button","expand-icon: filter-control-expand-icon","popup: filter-control-popup","error: filter-control-error","hint: filter-control-hint"].join(", "),SAFE_FILTER_ID_PART=/^[a-zA-Z][a-zA-Z0-9_-]*$/;function fieldPartNames(filterId){return SAFE_FILTER_ID_PART.test(filterId)?`field field-${filterId}`:"field"}function isChoiceDefinition(definition){return definition.type==="select"||definition.type==="combobox"||definition.type==="checkbox-menu"}function isBuiltInSet(value){return value==null?!1:typeof value=="boolean"?value:Array.isArray(value)?value.length>0:value!==""}function filterValueEqualsDefault(value,defaultValue){const valueIsArray=Array.isArray(value),defaultIsArray=Array.isArray(defaultValue);return valueIsArray||defaultIsArray?!valueIsArray||!defaultIsArray?!1:value.length===defaultValue.length&&value.every((entry,index)=>entry===defaultValue[index]):Object.is(value,defaultValue)}function defineFilterValueEntry(record,key,value){Object.defineProperty(record,key,{value,enumerable:!0,configurable:!0,writable:!0})}function cloneFilterValueRecord(value){const clone={},descriptors=Object.getOwnPropertyDescriptors(value);let retained=0;for(const key of Reflect.ownKeys(descriptors)){if(retained>=MAX_FILTER_COLLECTION_ENTRIES)break;const descriptor=descriptors[key];if(typeof key!="string"||!descriptor?.enumerable||!("value"in descriptor))continue;retained+=1;const fieldValue=snapshotFilterFieldValue(descriptor.value);fieldValue!==void 0&&defineFilterValueEntry(clone,key,fieldValue)}return clone}function cloneFilterValue(value){return Object.freeze(cloneFilterValueRecord(value))}class LyraFilterBar extends LyraElement{constructor(){super(...arguments),this.label="",this.disabled=!1,this.loading=!1,this.activeFiltersDisplay="all",this.touchedFilters=new Set,this.slotPresence=new SlotPresenceController(this),this._filters=EMPTY_FILTERS,this._value=EMPTY_VALUE,this.rawValue=EMPTY_VALUE,this.debounceControllers=new Map,this.chipFocusGeneration=0,this.schemaGeneration=0,this.onControlChange=(def,e)=>{const control=e.target;if(def.type==="combobox"&&this.isDebounced(def.debounce)){this.scheduleDebounce(def.filterId,control.value,def.debounce);return}this.setFilterValue(def.filterId,control.value,control.appliedPreset)},this.stopControlAlias=event=>{event.stopPropagation()},this.onCustomControlChange=(def,generation,e)=>{e.stopPropagation();const next=def.custom.adapter.valueFromEvent(e);if(this.isDebounced(def.debounce)){this.scheduleDebounce(def.filterId,next,def.debounce,pending=>this.setCustomContextValue(def,generation,pending));return}this.setCustomContextValue(def,generation,next)},this.stopMenuItemChangeAlias=event=>{event.stopPropagation()}}static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,filterBarActiveFilters:LYRA_DEFAULT_filterBarActiveFilters,filterBarReset:LYRA_DEFAULT_filterBarReset}}static{this.styles=[LyraElement.styles,srOnly,styles]}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-validity-change"])}static{this.properties={filters:{attribute:!1,noAccessor:!0},value:{attribute:!1,noAccessor:!0}}}get filters(){return this._filters}set filters(next){if(next===this.filtersInput)return;this.filtersInput=next;const old=this._filters,widened=next;this.cancelDebounce(),this.renewSchemaContext();const seen=new Set;this._filters=Object.freeze(snapshotFilterDefinitions(widened).filter(definition=>{try{return!definition||typeof definition.filterId!="string"||definition.filterId.length===0||definition.filterId!==definition.filterId.trim()||typeof definition.label!="string"||definition.label.trim().length===0||seen.has(definition.filterId)||isChoiceDefinition(definition)&&!Array.isArray(definition.options)||definition.type==="custom"&&(!definition.custom?.adapter||typeof definition.custom.render!="function")?!1:(seen.add(definition.filterId),!0)}catch{return!1}}).map(definition=>{const choices=definition.options;if(choices===void 0)return definition;const options=(Array.isArray(choices)?choices:[]).filter(option=>{try{return option!==null&&typeof option=="object"&&typeof Object.getOwnPropertyDescriptor(option,"value")?.value=="string"&&typeof Object.getOwnPropertyDescriptor(option,"label")?.value=="string"}catch{return!1}});return Object.freeze({...definition,options:Object.freeze(options)})}));const ids=new Set(this._filters.map(definition=>definition.filterId));this.touchedFilters=new Set([...this.touchedFilters].filter(id=>ids.has(id)));const oldValue=this._value;this._value=this.normalizeValue(this.rawValue),this.requestUpdate("filters",old),this._value!==oldValue&&this.requestUpdate("value",oldValue)}get value(){return cloneFilterValue(this._value)}set value(next){if(next===this.valueInput)return;this.valueInput=next;const old=this._value,widened=next;try{this.rawValue=cloneFilterValue(widened??EMPTY_VALUE)}catch{this.rawValue=EMPTY_VALUE}this._value=this.normalizeValue(widened),this.requestUpdate("value",old)}renewSchemaContext(){this.schemaAbortController?.abort();const AbortControllerCtor=this.ownerDocument.defaultView?.AbortController??AbortController;this.schemaAbortController=new AbortControllerCtor,this.schemaGeneration+=1}get schemaSignal(){return this.schemaAbortController||this.renewSchemaContext(),this.schemaAbortController.signal}isEmpty(def,value){if(def.type==="chip")return typeof def.isEmpty=="function"?def.isEmpty(value):!isBuiltInSet(value);if(def.type!=="custom")return!isBuiltInSet(value);const{adapter}=def.custom;if(adapter.isEmpty)return adapter.isEmpty(value);const clear=adapter.clearValue;return Array.isArray(value)&&Array.isArray(clear)?value.length===clear.length&&value.every((entry,index)=>entry===clear[index]):Object.is(value,clear)}valueFor(def){return Object.prototype.hasOwnProperty.call(this._value,def.filterId)?this._value[def.filterId]:def.type==="custom"?def.custom.adapter.clearValue:def.type==="chip"?def.clearValue:void 0}normalizeValue(value){const normalized={};for(const def of this._filters){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value??{},def.filterId)}catch{continue}if(!descriptor||!("value"in descriptor))continue;const fieldValue=snapshotFilterFieldValue(descriptor.value);this.isEmpty(def,fieldValue)||defineFilterValueEntry(normalized,def.filterId,fieldValue)}return Object.freeze(normalized)}get hasActiveFilters(){return this._filters.some(def=>!this.isEmpty(def,this.valueFor(def)))}filterIsChanged(def){const value=this.valueFor(def),defaultValue=def.defaultValue;return defaultValue!==void 0&&!this.isEmpty(def,defaultValue)?!filterValueEqualsDefault(value,defaultValue):!this.isEmpty(def,value)}get hasChangedFilters(){return this._filters.some(def=>this.filterIsChanged(def))}get hasResettableFilters(){return this.activeFiltersDisplay==="changed"?this.hasChangedFilters:this.hasActiveFilters}get invalidFilterIds(){return Object.freeze(this._filters.filter(def=>def.required&&this.isEmpty(def,this.valueFor(def))).map(def=>def.filterId))}checkValidity(){return this.invalidFilterIds.length===0}reportValidity(){const invalid=this.invalidFilterIds;return invalid.length&&(this.touchedFilters=new Set([...this.touchedFilters,...invalid])),invalid.length===0}reset(){if(this.disabled)return;this.cancelDebounce(),this.touchedFilters=new Set;const self=this;self.value=self.resetValue,self.emit("lr-input",Object.freeze({value:self.value,filterId:void 0,appliedPreset:void 0})),self.emit("lr-reset",Object.freeze({value:self.value}))}get resetValue(){const out={};for(const def of this._filters)if(def.defaultValue!==void 0&&!this.isEmpty(def,def.defaultValue)){const value=Array.isArray(def.defaultValue)?Object.freeze([...def.defaultValue]):def.defaultValue;defineFilterValueEntry(out,def.filterId,value)}return Object.freeze(out)}setFilterValue(id,value,appliedPreset){const definition=this._filters.find(candidate=>candidate.filterId===id);if(this.disabled||!definition)return;const next={...this._value};this.isEmpty(definition,value)?delete next[id]:defineFilterValueEntry(next,id,value);const self=this;self.value=next,self.emit("lr-input",Object.freeze({value:self.value,filterId:id,appliedPreset}))}setCustomContextValue(definition,generation,value){generation!==this.schemaGeneration||this.schemaSignal.aborted||!this.isConnected||!this._filters.includes(definition)||this.setFilterValue(definition.filterId,value)}markTouched(id){this.disabled||this.touchedFilters.has(id)||(this.touchedFilters=new Set(this.touchedFilters).add(id))}isDebounced(delay){return typeof delay=="number"&&Number.isFinite(delay)&&delay>0}scheduleDebounce(id,value,delay,commit=pending=>this.setFilterValue(id,pending)){let controller=this.debounceControllers.get(id);if(!controller){const created=new DebounceController(delay,pending=>{this.debounceControllers.get(id)===created&&this.debounceControllers.delete(id),pending!==void 0&&commit(pending)});controller=created,this.debounceControllers.set(id,created)}controller.delayMs=delay,controller.push(value)}hasPendingDebounce(id){return this.debounceControllers.get(id)?.pending??!1}onTextInput(def,e){if(this.disabled)return;const next=e.target.value??"";if(!this.isDebounced(def.debounce)){this.cancelDebounce(def.filterId),this.setFilterValue(def.filterId,next);return}this.scheduleDebounce(def.filterId,next,def.debounce)}flushDebounce(id){this.debounceControllers.get(id)?.flush()}cancelDebounce(id){for(const[key,controller]of this.debounceControllers)id!==void 0&&key!==id||(controller.dispose(),this.debounceControllers.delete(key))}onFieldFocusout(id){this.flushDebounce(id),this.markTouched(id)}repairFocusAfterChipRemoval(index,filterId,shouldRepairFocus){const generation=++this.chipFocusGeneration;shouldRepairFocus&&this.updateComplete.then(()=>{if(!this.isConnected||this.disabled||generation!==this.chipFocusGeneration||deepActiveElement(this.ownerDocument)!==this.ownerDocument.body)return;const chips=this.renderRoot.querySelectorAll('[part="chip"]'),chip=chips[Math.min(index,chips.length-1)],target=chip?collectFocusableElements(chip)[0]:void 0;if(target){target.focus();return}for(const control of this.renderRoot.querySelectorAll("[data-filter-id]"))if(control.dataset.filterId===filterId){collectFocusableElements(control)[0]?.focus();return}})}clearFilter(id,shouldRepairFocus=!1){if(this.disabled)return;this.cancelDebounce(id);const index=this.activeEntries.findIndex(entry=>entry.def.filterId===id),def=this._filters.find(f=>f.filterId===id);if(!def)return;const clearValue=def.type==="custom"?def.custom.adapter.clearValue:def.type==="chip"?def.clearValue??"":def.type==="checkbox-menu"||def.type==="combobox"&&def.multiple?[]:"";this.setFilterValue(id,clearValue),this.repairFocusAfterChipRemoval(Math.max(0,index),id,shouldRepairFocus)}displayValueFor(def,value){if(def.type==="custom"){const formatted=def.custom?.adapter.formatValue?.(value,this.effectiveLocale);return formatted!==void 0?formatted:Array.isArray(value)?getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(value):value===void 0?"":String(value)}if(def.type==="chip"){const formatted=typeof def.formatValue=="function"?def.formatValue(value,this.effectiveLocale):void 0;return formatted!==void 0?formatted:Array.isArray(value)?getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(value):value===void 0?"":String(value)}if(isChoiceDefinition(def)){const values=Array.isArray(value)?value.filter(entry=>typeof entry=="string"):typeof value=="string"?[value]:[],optionLabels=values.length>1?new Map:void 0;if(optionLabels)for(const option of def.options??[]){const optionValue=option.value;optionLabels.has(optionValue)||optionLabels.set(optionValue,option.label)}const labels=values.map(v=>optionLabels?optionLabels.get(v)??v:def.options?.find(o=>o.value===v)?.label??v);return labels.length>1?getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(labels):labels[0]??""}if(def.type==="text")return typeof value=="string"?value:"";if(typeof value!="string")return"";const formatter=getDateTimeFormat(this.effectiveLocale,{year:"numeric",month:"short",day:"numeric",timeZone:"UTC"}),parseIso=input=>{const match=/^(\d{4})-(\d{2})-(\d{2})$/.exec(input);if(!match)return;const year=Number(match[1]),month=Number(match[2]),day=Number(match[3]),date=new Date(0);return date.setUTCHours(0,0,0,0),date.setUTCFullYear(year,month-1,day),date.getUTCFullYear()===year&&date.getUTCMonth()===month-1&&date.getUTCDate()===day?date:void 0},segments=value.split("/");if(def.type==="date"&&segments.length!==1||def.type==="date-range"&&segments.length!==2)return value;const[startText,endText]=segments,start=parseIso(startText??""),end=endText===void 0?void 0:parseIso(endText);return!start||endText!==void 0&&(!end||end.getTime()<start.getTime())?value:end?formatter.formatRange(start,end):formatter.format(start)}get activeEntries(){return this.activeFiltersDisplay==="hidden"?[]:this._filters.filter(def=>!this.isEmpty(def,this.valueFor(def))).filter(def=>this.activeFiltersDisplay!=="changed"||!filterValueEqualsDefault(this.valueFor(def),def.defaultValue)).map(def=>({def,display:this.displayValueFor(def,this.valueFor(def))}))}disconnectedCallback(){super.disconnectedCallback(),this.cancelDebounce(),this.closeCheckboxMenus(),this.schemaAbortController?.abort(),this.schemaAbortController=void 0,this.schemaGeneration+=1}closeCheckboxMenus(){for(const menu of this.renderRoot?.querySelectorAll(`${tag("dropdown")}[data-filter-id]`)??[])menu.open&&(menu.open=!1)}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.closeCheckboxMenus(),(!this.schemaAbortController||this.schemaAbortController.signal.aborted)&&(this.renewSchemaContext(),this.hasUpdated&&this.requestUpdate()),this.hasUpdated&&queueMicrotask(()=>{this.isConnected&&this.syncTextControls()})}syncTextControls(){if(!this._filters.some(def=>def.type==="text"))return;const fields=new Map;for(const node of this.renderRoot.querySelectorAll(`${tag("input")}[data-filter-id]`)){const element=node,id=element.dataset.filterId;id!==void 0&&fields.set(id,element)}for(const def of this._filters){if(def.type!=="text"||this.hasPendingDebounce(def.filterId))continue;const field=fields.get(def.filterId);if(!field)continue;const raw=this._value[def.filterId],next=typeof raw=="string"?raw:"";field.value!==next&&(field.value=next)}}willUpdate(changed){super.willUpdate(changed),changed.has("disabled")&&this.disabled&&this.cancelDebounce()}updated(changed){if(super.updated(changed),this.syncTextControls(),changed.has("value")||changed.has("filters")){const invalidFilterIds=this.invalidFilterIds,valid=invalidFilterIds.length===0,key=JSON.stringify({valid,invalidFilterIds});key!==this.lastValidityKey&&(this.lastValidityKey=key,this.emit("lr-validity-change",Object.freeze({valid,invalidFilterIds:Object.freeze([...invalidFilterIds])})))}}renderStartAdornment(icon,slotName="start"){return icon==null?nothing:html`<span slot=${slotName} aria-hidden="true" inert>${icon}</span>`}renderOption(option){return html`<lr-option
2
2
  value=${option.value}
3
3
  search-text=${option.searchText??nothing}
4
4
  ?disabled=${option.disabled===!0}
5
5
  >${this.renderStartAdornment(option.icon)}${option.label}</lr-option
6
- >`}labelRouting(def){const hidden=def.labelVisibility==="hidden";return{label:hidden?"":def.label,placeholder:def.placeholder||(hidden?def.label:""),accessibleLabel:hidden?def.label:nothing}}labelAutoAttribute(def){return def.labelVisibility==="auto"}onCheckboxMenuToggle(def,event){if(event.stopPropagation(),event.preventDefault(),this.disabled)return;const detail=event.detail,current=this.valueFor(def),selected=Array.isArray(current)?current.filter(entry=>typeof entry=="string"):[],next=detail.checked?selected.includes(detail.value)?selected:[...selected,detail.value]:selected.filter(entry=>entry!==detail.value);this.setFilterValue(def.filterId,Object.freeze(next))}renderCheckboxMenu(def,value,errorText){const selected=Array.isArray(value)?value.filter(entry=>typeof entry=="string"):[],size=def.size??"m",routing=this.labelRouting(def),summary=selected.length>0?this.displayValueFor(def,value):routing.placeholder,showLabel=def.labelVisibility!=="hidden"||summary!==def.label;return html`<div
6
+ >`}labelRouting(def){const hidden=def.labelVisibility==="hidden";return{label:hidden?"":def.label,placeholder:def.placeholder||(hidden?def.label:""),accessibleLabel:hidden?def.label:nothing}}labelAutoAttribute(def){return def.labelVisibility==="auto"}onCheckboxMenuToggle(def,event){if(event.stopPropagation(),event.preventDefault(),this.disabled)return;const detail=event.detail,current=this.valueFor(def),selected=Array.isArray(current)?current.filter(entry=>typeof entry=="string"):[],next=detail.checked?selected.includes(detail.value)?selected:[...selected,detail.value]:selected.filter(entry=>entry!==detail.value);this.setFilterValue(def.filterId,Object.freeze(next))}renderCheckboxMenu(def,value,errorText){const selected=Array.isArray(value)?value.filter(entry=>typeof entry=="string"):[],selectedValues=new Set(selected),size=def.size??"m",routing=this.labelRouting(def),summary=selected.length>0?this.displayValueFor(def,value):routing.placeholder,showLabel=def.labelVisibility!=="hidden"||summary!==def.label;return html`<div
7
7
  part="filter-control"
8
8
  class="checkbox-menu"
9
9
  ?data-label-auto=${this.labelAutoAttribute(def)}
@@ -35,7 +35,7 @@ import{__decorate}from"tslib";import{eventCollectionSupport}from"../../../intern
35
35
  part="filter-control-option"
36
36
  type="checkbox"
37
37
  value=${option.value}
38
- ?checked=${selected.includes(option.value)}
38
+ ?checked=${selectedValues.has(option.value)}
39
39
  ?disabled=${option.disabled===!0}
40
40
  @lr-menu-item-change-request=${event=>this.onCheckboxMenuToggle(def,event)}
41
41
  @lr-menu-item-change=${this.stopMenuItemChangeAlias}
@@ -81,4 +81,4 @@ export declare class LyraMenu extends LyraElement<LyraMenuEventMap>{protected st
81
81
  * matching `lr-select`/`lr-model-select`'s established
82
82
  * `this.getAttribute('aria-label') ?? <computed default>` precedence
83
83
  * (see `effectiveLabel`). */
84
- label?:string;get dropdownOpen():boolean;set dropdownOpen(next:boolean);private items;private activeIndex;private itemsSlot?;private cleanup?;private presentationPositioned;private placedTopLayer?;private itemStateObserver?;private readonly popupController;private menubarAnchored;private pendingFocus;private submenuOpenTimer?;private submenuCloseTimer?;private readonly listId;private readonly owningMenu;private readonly typeBuffer;private createSubmenuController;connectedCallback():void;protected firstUpdated(changed:PropertyValues):void;private get hasStandalonePresentation();private get interactionOpen();private syncPresentationState;private onRegionSlotChange;private syncRegionState;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private reposition;private cancelPresentationHideWatch;private schedulePresentationHide;private focusAfterPlacement;disconnectedCallback():void;private scheduleOwnedTimeout;private clearOwnedTimeout;private openPresentation;private closePresentation;private onDocPointer;private onItemsSlotChange;private syncItemsFromSlot;private acquireItemOwner;private releaseItemOwner;private uncheckRadioGroupSiblings;private isNavigable;private applyDropdownSize;private itemStateChangeReconciliationPending;private onItemStateChangeEvent;private onItemStateChange;private rehomeZeroSurvivorFocus;private onOwnedItemSelect;private dismissAfterSelection;private applyRovingTabIndex;private focusRoving;private setActiveItem;private closeSubmenus;private openSubmenuItem;private clearSubmenuTimers;private ownItemFromEvent;private isForeignEvent;private onListFocusIn;private onListKeyDown;private onPopupPointerOver;private onPopupPointerLeave;private scheduleSubmenuClose;private onNestedSelect;private popupPart;private tabWouldLeavePopup;private onPopupKeyDown;private typeAhead;private resetTypeAhead;private get effectiveLabel();private renderContents;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-menu':LyraMenu;}}
84
+ label?:string;get dropdownOpen():boolean;set dropdownOpen(next:boolean);private items;private activeIndex;private itemsSlot?;private cleanup?;private presentationPositioned;private placedTopLayer?;private itemStateObserver?;private readonly popupController;private menubarAnchored;private pendingFocus;private submenuOpenTimer?;private submenuCloseTimer?;private readonly listId;private readonly owningMenu;private readonly typeBuffer;private createSubmenuController;connectedCallback():void;protected firstUpdated(changed:PropertyValues):void;private get hasStandalonePresentation();private get interactionOpen();private syncPresentationState;private onRegionSlotChange;private syncRegionState;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private reposition;private cancelPresentationHideWatch;private schedulePresentationHide;private focusAfterPlacement;disconnectedCallback():void;private scheduleOwnedTimeout;private clearOwnedTimeout;private openPresentation;private closePresentation;private onDocPointer;private onItemsSlotChange;private syncItemsFromSlot;private observeItems;private acquireItemOwner;private releaseItemOwner;private uncheckRadioGroupSiblings;private isNavigable;private applyDropdownSize;private itemStateChangeReconciliationPending;private onItemStateChangeEvent;private onItemStateChange;private rehomeZeroSurvivorFocus;private onOwnedItemSelect;private dismissAfterSelection;private applyRovingTabIndex;private focusRoving;private setActiveItem;private closeSubmenus;private openSubmenuItem;private clearSubmenuTimers;private ownItemFromEvent;private isForeignEvent;private onListFocusIn;private onListKeyDown;private onPopupPointerOver;private onPopupPointerLeave;private scheduleSubmenuClose;private onNestedSelect;private popupPart;private tabWouldLeavePopup;private onPopupKeyDown;private typeAhead;private resetTypeAhead;private get effectiveLabel();private renderContents;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-menu':LyraMenu;}}
@@ -1,4 +1,4 @@
1
- var _a;import{__decorate}from"tslib";import{maxCssTime}from"../../../internal/css-motion-time.js";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{deferredPlaceReady as place,syncTopLayerRelease,topLayerPlacement,waitForDeferredPlacement}from"../../../internal/anchored-overlay-runtime.js";import{TypeAheadBuffer}from"../../../internal/type-ahead-buffer.js";import{isRovingTargetAvailable,resolveListMove}from"../../../internal/list-navigation.js";import{PopupController}from"../../../internal/popup-controller.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{nextId,resolveAccessibleTrigger}from"../../../internal/a11y.js";import{collectFocusableElements,composedContains}from"../../../internal/overlay-manager.js";import{styles}from"./menu.styles.js";import{menuItemOwner,submenuPanelController}from"./menu-shared.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{tag}from"../../../internal/prefix.js";import{activeElementIn,isUsableActiveElement,safeDeepActiveElement}from"../../../internal/active-element.js";import{syncAriaDescribedByElements}from"../../../internal/aria-reflection.js";import"./menu-item.class.js";import{LYRA_DEFAULT_menuLabel}from"../../../internal/default-strings/shared.generated.js";const SUBMENU_PLACEMENT="right-start",SUBMENU_FALLBACK_PLACEMENTS=["right-end","left-start","left-end","bottom-start","top-start"],MENUBAR_PLACEMENT="bottom-start",SUBMENU_OPEN_DELAY=150,SUBMENU_CLOSE_DELAY=300;function isLyraMenuItemElement(value){return isHtmlElement(value)?value.localName===tag("menu-item")||value.localName===tag("dropdown-item"):!1}function isLyraMenuElement(value){return isHtmlElement(value)&&value.localName===tag("menu")}let menuWidthScaleRegistered=!1;function registerMenuWidthScale(){if(!menuWidthScaleRegistered&&(menuWidthScaleRegistered=!0,!(typeof CSS>"u"||typeof CSS.registerProperty!="function")))try{CSS.registerProperty({name:"--_lr-menu-max-inline-size",syntax:"<length-percentage>",inherits:!1,initialValue:"100%"})}catch{}}class LyraMenu extends LyraElement{constructor(){super(...arguments),this.presentationOpen=!1,this.presentationHidden=!0,this.submenuAnchor=null,this.submenuStateChange=null,this.dropdownContained=!1,this.dropdownOwner=null,this._dropdownOpen=!1,this.dropdownRendersMenuRole=!1,this.dropdownStayOpenOnSelect=!1,this.items=[],this.activeIndex=-1,this.presentationPositioned=!1,this.popupController=new PopupController({host:this,onPointer:event=>this.onDocPointer(event)}),this.menubarAnchored=!1,this.pendingFocus="first",this.listId=nextId("menu-list"),this.owningMenu={activate:item=>this.onOwnedItemSelect(item),uncheckRadioGroup:(item,group)=>this.uncheckRadioGroupSiblings(item,group)},this.typeBuffer=new TypeAheadBuffer(this),this[_a]=this.createSubmenuController(),this.onRegionSlotChange=()=>{this.syncRegionState()},this.onDocPointer=e=>{const path=e.composedPath();path.includes(this)||this.submenuAnchor&&path.includes(this.submenuAnchor)||this.closePresentation()},this.onItemsSlotChange=e=>{this.syncItemsFromSlot(e.target)},this.itemStateChangeReconciliationPending=!1,this.onItemStateChangeEvent=event=>{event.stopPropagation(),!this.itemStateChangeReconciliationPending&&(this.itemStateChangeReconciliationPending=!0,queueMicrotask(()=>{this.itemStateChangeReconciliationPending=!1,this.onItemStateChange()}))},this.onItemStateChange=()=>{const navigable=this.items.filter(item=>this.isNavigable(item));if(this.activeIndex>=0&&!this.isNavigable(this.items[this.activeIndex])){const current=this.activeIndex,displaced=this.items[current],focused=safeDeepActiveElement(this.ownerDocument),displacedHadFocus=focused===null||focused===this.ownerDocument.body||focused===displaced||composedContains(displaced,focused),next=navigable.find(item=>this.items.indexOf(item)>current)??navigable.find(item=>this.items.indexOf(item)<current);next?this.setActiveItem(next,displacedHadFocus):(this.activeIndex=-1,this.applyRovingTabIndex(),displacedHadFocus&&this.rehomeZeroSurvivorFocus());return}this.applyRovingTabIndex()},this.onListFocusIn=e=>{const target=e.target;if(!isLyraMenuItemElement(target))return;const index=this.items.indexOf(target);index===-1||index===this.activeIndex||!this.isNavigable(target)||(this.activeIndex=index,this.applyRovingTabIndex(),this.closeSubmenus(target))},this.onListKeyDown=e=>{if(this.isForeignEvent(e)||e.altKey||e.ctrlKey||e.metaKey||e.isComposing||e.keyCode===229)return;const isItemTarget=isLyraMenuItemElement(e.target);if(e.key==="Escape"&&isItemTarget&&!this.hasStandalonePresentation){e.preventDefault(),this.closePresentation({focusTrigger:!0});return}if(!isItemTarget)return;const navigable=this.items.filter(i=>this.isNavigable(i)),current=this.activeIndex>=0?this.items[this.activeIndex]:void 0,currentNavIndex=current?navigable.indexOf(current):-1,intoSubmenuKey=this.effectiveDirection==="rtl"?"ArrowLeft":"ArrowRight";switch(e.key){case"ArrowRight":case"ArrowLeft":e.key===intoSubmenuKey?current?.hasSubmenu&&this.isNavigable(current)&&(e.preventDefault(),this.closeSubmenus(current),current.openSubmenu("first")):this.submenuAnchor&&!this.menubarAnchored&&(e.preventDefault(),this.closePresentation({focusTrigger:!0}));break;case"ArrowDown":case"ArrowUp":case"Home":case"End":{e.preventDefault();const nextIndex=resolveListMove(e,{count:navigable.length,current:currentNavIndex,orientation:"vertical"});nextIndex!==null&&this.setActiveItem(navigable[nextIndex]);break}case"Enter":case" ":e.preventDefault(),current?.hasSubmenu?(this.closeSubmenus(current),current.openSubmenu("first")):current?.isLinkItem?current.click():current?.select();break;default:this.typeBuffer.accepts(e)&&this.typeAhead(e.key);return}},this.onPopupPointerOver=e=>{if(!this.interactionOpen)return;const hovered=this.ownItemFromEvent(e);this.clearOwnedTimeout(this.submenuOpenTimer),this.submenuOpenTimer=void 0;const opened=this.openSubmenuItem();opened&&opened===hovered?(this.clearOwnedTimeout(this.submenuCloseTimer),this.submenuCloseTimer=void 0):opened&&this.scheduleSubmenuClose(opened),!(!hovered||hovered===opened||!hovered.hasSubmenu||!this.isNavigable(hovered))&&(this.submenuOpenTimer=this.scheduleOwnedTimeout(()=>{this.submenuOpenTimer=void 0,!(!this.interactionOpen||!this.items.includes(hovered))&&(this.closeSubmenus(hovered),hovered.openSubmenu("none"))},SUBMENU_OPEN_DELAY))},this.onPopupPointerLeave=()=>{this.clearOwnedTimeout(this.submenuOpenTimer),this.submenuOpenTimer=void 0;const opened=this.openSubmenuItem();opened&&this.scheduleSubmenuClose(opened)},this.onNestedSelect=e=>{if(e.target===this)return;const event=e;this.dropdownStayOpenOnSelect&&event.preventDefault(),queueMicrotask(()=>{event.defaultPrevented||this.dismissAfterSelection(!0)})},this.onPopupKeyDown=e=>{const listEl=this.popupPart("list");if(e.key==="Escape"){if(listEl&&e.composedPath().includes(listEl)||this.hasStandalonePresentation)return;e.preventDefault(),this.closePresentation({focusTrigger:!0});return}e.key==="Tab"&&this.tabWouldLeavePopup(e)&&this.closePresentation()}}static{_a=submenuPanelController}static{this.defaultStrings={...super.defaultStrings,menuLabel:LYRA_DEFAULT_menuLabel}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-select"])}static{this.identityEventDetailProperties=Object.freeze({"lr-select":Object.freeze(["item"])})}static{this.styles=[LyraElement.styles,styles]}get dropdownOpen(){return this._dropdownOpen}set dropdownOpen(next){const normalized=!!next;if(normalized===this._dropdownOpen)return;const old=this._dropdownOpen;this._dropdownOpen=normalized,this.presentationOpen=normalized,this.requestUpdate("dropdownOpen",old)}createSubmenuController(){const menu=this;return{get open(){return menu.submenuAnchor!==null&&menu.presentationOpen},attach(anchor,onStateChange,options){menu.submenuAnchor&&menu.submenuAnchor!==anchor&&menu.closePresentation(),menu.menubarAnchored=options?.menubar===!0,menu.submenuAnchor=anchor,menu.submenuStateChange=onStateChange,menu.syncPresentationState(),menu.requestUpdate()},detach(anchor){menu.submenuAnchor===anchor&&(menu.closePresentation(),menu.submenuAnchor=null,menu.menubarAnchored=!1,menu.submenuStateChange=null,menu.cleanup?.(),menu.cleanup=void 0,menu.syncPresentationState(),menu.requestUpdate())},async show(focus="first"){menu.submenuAnchor&&(menu.openPresentation(focus),await menu.updateComplete,await menu.focusAfterPlacement(focus))},async hide(options){menu.closePresentation(options),await menu.updateComplete}}}connectedCallback(){if(super.connectedCallback(),registerMenuWidthScale(),this.hasUpdated){const slot=this.renderRoot.querySelector("slot:not([name])");slot&&this.syncItemsFromSlot(slot)}}firstUpdated(changed){super.firstUpdated(changed),this.syncRegionState(),this.syncPresentationState();const slot=this.itemsSlot;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>this.syncItemsFromSlot(s))})}get hasStandalonePresentation(){return!this.dropdownContained&&!this.submenuAnchor}get interactionOpen(){return this.hasStandalonePresentation||this.presentationOpen}syncPresentationState(){const standalone=this.hasStandalonePresentation;if(this.toggleAttribute("data-inline",standalone),this.toggleAttribute("data-submenu",this.submenuAnchor!==null),this.toggleAttribute("data-contained",this.dropdownContained),standalone){const active=this.activeIndex>=0?this.items[this.activeIndex]:void 0;if(!active||!this.isNavigable(active)){const first=this.items.find(item=>this.isNavigable(item));this.activeIndex=first?this.items.indexOf(first):-1}}else this.presentationOpen||(this.activeIndex=-1);this.applyRovingTabIndex()}syncRegionState(){const assigned=selector=>this.renderRoot.querySelector(selector)?.assignedElements({flatten:!0}).length??0;this.toggleAttribute("data-has-header",assigned('slot[name="header"]')>0),this.toggleAttribute("data-has-footer",assigned('slot[name="footer"]')>0),this.toggleAttribute("data-list-empty",assigned("slot:not([name])")===0)}willUpdate(changed){super.willUpdate(changed),this.presentationOpen&&this.submenuAnchor&&(this.cancelPresentationHideWatch(),this.presentationHidden=!1)}updated(changed){super.updated(changed);const list=this.renderRoot.querySelector('[part~="list"]')??void 0;syncAriaDescribedByElements(this,list,this.getAttribute("aria-describedby")),(changed.has("presentationOpen")||changed.has("dropdownOpen")||changed.has("dropdownContained"))&&(this.cleanup?.(),this.cleanup=void 0,this.presentationPositioned=!1,this.presentationOpen?this.submenuAnchor?(this.popupController.bindPointer(),this.reposition()):(this.popupController.unbindPointer(),this.presentationPositioned=!0,this.focusRoving(this.pendingFocus)):(this.popupController.unbindPointer(),this.resetTypeAhead(),this.activeIndex=-1,this.applyRovingTabIndex(),this.clearSubmenuTimers(),this.closeSubmenus(),this.submenuAnchor&&this.schedulePresentationHide())),changed.has("dropdownContained")&&this.syncPresentationState(),changed.has("dropdownSize")&&this.applyDropdownSize()}reposition(){this.cleanup?.(),this.cleanup=void 0,this.presentationPositioned=!1;const popup=this.renderRoot.querySelector(".submenu-surface");if(this.submenuAnchor&&popup){const placement=this.menubarAnchored?MENUBAR_PLACEMENT:rtlAwarePlacement(SUBMENU_PLACEMENT,this),topLayer=this.submenuAnchor.closest(tag("menubar"))?.topLayer===!0;this.placedTopLayer=syncTopLayerRelease(popup,this.placedTopLayer,topLayer),this.cleanup=place(this.submenuAnchor,popup,{placement,flipFallbackPlacements:this.menubarAnchored?void 0:SUBMENU_FALLBACK_PLACEMENTS.map(candidate=>rtlAwarePlacement(candidate,this)),...topLayerPlacement(topLayer,resolveEffectivePositioningStrategy(this,void 0,"fixed"))})}}cancelPresentationHideWatch(){this.presentationHideWatcher?.(),this.presentationHideWatcher=void 0}schedulePresentationHide(){this.cancelPresentationHideWatch();const surface=this.renderRoot.querySelector(".submenu-surface"),view=this.ownerDocument.defaultView,transitionMs=surface&&view?maxCssTime(view.getComputedStyle(surface).transitionDuration)+maxCssTime(view.getComputedStyle(surface).transitionDelay):0,waitForEvent=!!(surface&&view&&transitionMs>0&&!prefersReducedMotion(this));let settled=!1,timeout;const finish=()=>{settled||(settled=!0,timeout!==void 0&&view?.clearTimeout(timeout),surface?.removeEventListener("transitionend",onEnd),this.presentationHideWatcher===cancel&&(this.presentationHideWatcher=void 0),this.presentationHidden=!0)},onEnd=event=>{event.target===surface&&finish()},cancel=()=>{settled=!0,timeout!==void 0&&view?.clearTimeout(timeout),surface?.removeEventListener("transitionend",onEnd)};this.presentationHideWatcher=cancel,waitForEvent&&surface&&view?(surface.addEventListener("transitionend",onEnd),timeout=view.setTimeout(finish,transitionMs+50)):queueMicrotask(finish)}async focusAfterPlacement(focus){if(!this.presentationOpen||!this.submenuAnchor)return;const positioned=this.cleanup!==void 0&&(this.presentationPositioned||await waitForDeferredPlacement(()=>this.cleanup));if(!(!this.presentationOpen||!this.submenuAnchor)){if(!positioned){this.closePresentation(),await this.updateComplete;return}this.presentationPositioned=!0,this.focusRoving(focus)}}disconnectedCallback(){super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.presentationPositioned=!1,this.resetTypeAhead(),this.clearSubmenuTimers(),this.itemStateObserver?.disconnect(),this.itemStateObserver=void 0,this.popupController.unbindPointer();for(const item of this.items)this.releaseItemOwner(item);this._dropdownOpen=!1,this.presentationOpen=!1,this.cancelPresentationHideWatch(),this.presentationHidden=!0,this.submenuStateChange?.(!1)}scheduleOwnedTimeout(callback,delay){const owner=this.ownerDocument.defaultView;if(owner)return{owner,handle:owner.setTimeout(callback,delay)}}clearOwnedTimeout(timer){timer&&timer.owner.clearTimeout(timer.handle)}focusContained(focus="first"){if(this.dropdownContained&&this.dropdownOwner)if(this.dropdownOwner.open)this.pendingFocus=focus,this.focusRoving(focus);else{const transition=this.dropdownOwner.show();this.dropdownOwner.open&&(this.pendingFocus=focus)}}openPresentation(focus="first"){if(this.dropdownContained&&this.dropdownOwner){this.focusContained(focus);return}this.pendingFocus=focus,this.presentationOpen?(!this.submenuAnchor||this.presentationPositioned)&&this.focusRoving(focus):(this.presentationOpen=!0,this.submenuStateChange?.(!0))}closePresentation(options){if(this.dropdownContained&&this.dropdownOwner){this.dropdownOwner.hide(options);return}this.presentationOpen&&(this.presentationOpen=!1,this.submenuStateChange?.(!1),options?.focusTrigger&&this.submenuAnchor&&resolveAccessibleTrigger(this.submenuAnchor).focus())}syncItemsFromSlot(slot){const assigned=slot.assignedElements({flatten:!0}).filter(isLyraMenuItemElement);if(assigned.length===this.items.length&&assigned.every((item,index)=>item===this.items[index]))return;this.itemStateObserver?.disconnect();const previousItems=this.items,previouslyActive=this.activeIndex>=0?this.items[this.activeIndex]:void 0,focusedBefore=safeDeepActiveElement(this.ownerDocument),activeItemLostFocus=!!previouslyActive&&(focusedBefore===null||focusedBefore===this.ownerDocument.body||focusedBefore===previouslyActive||composedContains(previouslyActive,focusedBefore));this.items=assigned;for(const item of previousItems)this.items.includes(item)||this.releaseItemOwner(item);for(const item of this.items)this.acquireItemOwner(item);this.applyDropdownSize();const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;if(MutationObserverCtor){const owner=this.ownerDocument;let observer;observer=new MutationObserverCtor(()=>{this.itemStateObserver!==observer||this.ownerDocument!==owner||this.onItemStateChange()}),this.itemStateObserver=observer;for(const item of this.items)this.itemStateObserver.observe(item,{attributes:!0,attributeFilter:["disabled","hidden","aria-hidden","inert"]})}if(this.activeIndex=previouslyActive?this.items.indexOf(previouslyActive):-1,this.syncPresentationState(),this.syncRegionState(),this.interactionOpen)if(this.activeIndex===-1){const successor=this.items.find(item=>this.isNavigable(item));previouslyActive&&successor?this.setActiveItem(successor,activeItemLostFocus):this.focusRoving(this.pendingFocus),activeItemLostFocus&&!this.items.some(item=>this.isNavigable(item))&&this.rehomeZeroSurvivorFocus()}else{const active=activeElementIn(this.ownerDocument);!(isUsableActiveElement(active)&&this.contains(active))&&activeItemLostFocus&&this.items[this.activeIndex].focus()}}acquireItemOwner(item){item[menuItemOwner]?.(this.owningMenu)}releaseItemOwner(item){item[menuItemOwner]?.(null,this.owningMenu)}uncheckRadioGroupSiblings(item,group){for(const sibling of this.items)sibling!==item&&sibling.type==="radio"&&sibling.group===group&&sibling.checked&&(sibling.checked=!1)}isNavigable(item){return!item.interactionDisabled&&isRovingTargetAvailable(item)}applyDropdownSize(){if(this.dropdownSize)for(const item of this.items)item.size=this.dropdownSize}rehomeZeroSurvivorFocus(){if(this.dropdownContained&&this.dropdownOwner){this.dropdownOwner.hide({focusTrigger:!0});return}if(this.submenuAnchor){this.closePresentation({focusTrigger:!0});return}const list=this.renderRoot.querySelector('[part~="list"]');list&&(list.tabIndex=-1,list.focus({preventScroll:!0}))}onOwnedItemSelect(item){if(!isLyraMenuItemElement(item)||!this.items.includes(item))return;!this.emit("lr-select",{item},{cancelable:!0}).defaultPrevented&&!this.dropdownStayOpenOnSelect&&this.dismissAfterSelection(!0)}dismissAfterSelection(focusTrigger){this.closeSubmenus(),this.dropdownContained?this.dropdownOwner&&this.dropdownOwner.hide({focusTrigger}):this.submenuAnchor&&this.closePresentation({focusTrigger})}applyRovingTabIndex(){this.items.forEach((item,i)=>{item.tabIndex=i===this.activeIndex?0:-1})}focusRoving(which){if(which==="none")return;const navigable=this.items.filter(i=>this.isNavigable(i));if(!navigable.length)return;const item=which==="first"?navigable[0]:navigable[navigable.length-1];item&&this.setActiveItem(item)}setActiveItem(item,moveFocus=!0){this.activeIndex=this.items.indexOf(item),this.applyRovingTabIndex(),this.closeSubmenus(item),moveFocus&&item.focus()}closeSubmenus(keep){for(const item of this.items)item!==keep&&item.submenuOpen&&item.closeSubmenu()}openSubmenuItem(){return this.items.find(item=>item.submenuOpen)}clearSubmenuTimers(){this.clearOwnedTimeout(this.submenuOpenTimer),this.clearOwnedTimeout(this.submenuCloseTimer),this.submenuOpenTimer=void 0,this.submenuCloseTimer=void 0}ownItemFromEvent(e){let owner;for(const node of e.composedPath()){if(node===this)break;isLyraMenuItemElement(node)&&(owner=node)}return owner}isForeignEvent(e){for(const node of e.composedPath()){if(node===this)return!1;if(isLyraMenuElement(node))return!0}return!1}scheduleSubmenuClose(item){this.submenuCloseTimer||(this.submenuCloseTimer=this.scheduleOwnedTimeout(()=>{this.submenuCloseTimer=void 0,item.submenuOpen&&(composedContains(item,safeDeepActiveElement(this.ownerDocument))||item.closeSubmenu())},SUBMENU_CLOSE_DELAY))}popupPart(name){return this.renderRoot.querySelector(`[part="${name}"]`)}tabWouldLeavePopup(e){const header=this.popupPart("header"),footer=this.popupPart("footer"),listEl=this.popupPart("list"),backwards=e.shiftKey,active=safeDeepActiveElement(this.ownerDocument),headerStops=header?collectFocusableElements(header):[],footerStops=footer?collectFocusableElements(footer):[],listStops=listEl?collectFocusableElements(listEl):[],hasNeighbor=stops=>{const index=active?stops.indexOf(active):-1;return index===-1?!1:backwards?index>0:index<stops.length-1},path=e.composedPath();return footer&&path.includes(footer)?hasNeighbor(footerStops)?!1:backwards?listStops.length===0&&headerStops.length===0:!0:header&&path.includes(header)?hasNeighbor(headerStops)?!1:backwards?!0:listStops.length===0&&footerStops.length===0:!isLyraMenuItemElement(e.target)&&hasNeighbor(listStops)?!1:backwards?headerStops.length===0:footerStops.length===0}typeAhead(char){this.typeBuffer.add(char,this.effectiveLocale);const navigable=this.items.filter(i=>this.isNavigable(i));if(!navigable.length)return;const current=this.activeIndex>=0?this.items[this.activeIndex]:void 0,currentIndex=current?navigable.indexOf(current):-1,match=this.typeBuffer.match(navigable,currentIndex,item=>item.getTextLabel(),this.effectiveLocale);match!==null&&this.setActiveItem(navigable[match])}resetTypeAhead(){this.typeBuffer.clear()}get effectiveLabel(){const hostLabel=this.getAttribute("aria-label");return hostLabel!==null?hostLabel:this.label!==void 0?this.label:this.dropdownLabel!==void 0?this.dropdownLabel:this.localize("menuLabel")}renderContents(bindPointerOver=!0){return html`
1
+ var _a;import{__decorate}from"tslib";import{maxCssTime}from"../../../internal/css-motion-time.js";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{deferredPlaceReady as place,syncTopLayerRelease,topLayerPlacement,waitForDeferredPlacement}from"../../../internal/anchored-overlay-runtime.js";import{TypeAheadBuffer}from"../../../internal/type-ahead-buffer.js";import{isRovingTargetAvailable,resolveListMove}from"../../../internal/list-navigation.js";import{PopupController}from"../../../internal/popup-controller.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{nextId,resolveAccessibleTrigger}from"../../../internal/a11y.js";import{collectFocusableElements,composedContains}from"../../../internal/overlay-manager.js";import{styles}from"./menu.styles.js";import{menuItemOwner,submenuPanelController}from"./menu-shared.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{tag}from"../../../internal/prefix.js";import{activeElementIn,isUsableActiveElement,safeDeepActiveElement}from"../../../internal/active-element.js";import{syncAriaDescribedByElements}from"../../../internal/aria-reflection.js";import"./menu-item.class.js";import{LYRA_DEFAULT_menuLabel}from"../../../internal/default-strings/shared.generated.js";const SUBMENU_PLACEMENT="right-start",SUBMENU_FALLBACK_PLACEMENTS=["right-end","left-start","left-end","bottom-start","top-start"],MENUBAR_PLACEMENT="bottom-start",SUBMENU_OPEN_DELAY=150,SUBMENU_CLOSE_DELAY=300;function isLyraMenuItemElement(value){return isHtmlElement(value)?value.localName===tag("menu-item")||value.localName===tag("dropdown-item"):!1}function isLyraMenuElement(value){return isHtmlElement(value)&&value.localName===tag("menu")}let menuWidthScaleRegistered=!1;function registerMenuWidthScale(){if(!menuWidthScaleRegistered&&(menuWidthScaleRegistered=!0,!(typeof CSS>"u"||typeof CSS.registerProperty!="function")))try{CSS.registerProperty({name:"--_lr-menu-max-inline-size",syntax:"<length-percentage>",inherits:!1,initialValue:"100%"})}catch{}}class LyraMenu extends LyraElement{constructor(){super(...arguments),this.presentationOpen=!1,this.presentationHidden=!0,this.submenuAnchor=null,this.submenuStateChange=null,this.dropdownContained=!1,this.dropdownOwner=null,this._dropdownOpen=!1,this.dropdownRendersMenuRole=!1,this.dropdownStayOpenOnSelect=!1,this.items=[],this.activeIndex=-1,this.presentationPositioned=!1,this.popupController=new PopupController({host:this,onPointer:event=>this.onDocPointer(event)}),this.menubarAnchored=!1,this.pendingFocus="first",this.listId=nextId("menu-list"),this.owningMenu={activate:item=>this.onOwnedItemSelect(item),uncheckRadioGroup:(item,group)=>this.uncheckRadioGroupSiblings(item,group)},this.typeBuffer=new TypeAheadBuffer(this),this[_a]=this.createSubmenuController(),this.onRegionSlotChange=()=>{this.syncRegionState()},this.onDocPointer=e=>{const path=e.composedPath();path.includes(this)||this.submenuAnchor&&path.includes(this.submenuAnchor)||this.closePresentation()},this.onItemsSlotChange=e=>{this.syncItemsFromSlot(e.target)},this.itemStateChangeReconciliationPending=!1,this.onItemStateChangeEvent=event=>{event.stopPropagation(),!this.itemStateChangeReconciliationPending&&(this.itemStateChangeReconciliationPending=!0,queueMicrotask(()=>{this.itemStateChangeReconciliationPending=!1,this.onItemStateChange()}))},this.onItemStateChange=()=>{const navigable=[];if(this.items.forEach((item,index)=>{this.isNavigable(item)&&navigable.push({item,index})}),this.activeIndex>=0&&!this.isNavigable(this.items[this.activeIndex])){const current=this.activeIndex,displaced=this.items[current],focused=safeDeepActiveElement(this.ownerDocument),displacedHadFocus=focused===null||focused===this.ownerDocument.body||focused===displaced||composedContains(displaced,focused),next=navigable.find(({index})=>index>current)?.item??navigable.find(({index})=>index<current)?.item;next?this.setActiveItem(next,displacedHadFocus):(this.activeIndex=-1,this.applyRovingTabIndex(),displacedHadFocus&&this.rehomeZeroSurvivorFocus());return}this.applyRovingTabIndex()},this.onListFocusIn=e=>{const target=e.target;if(!isLyraMenuItemElement(target))return;const index=this.items.indexOf(target);index===-1||index===this.activeIndex||!this.isNavigable(target)||(this.activeIndex=index,this.applyRovingTabIndex(),this.closeSubmenus(target))},this.onListKeyDown=e=>{if(this.isForeignEvent(e)||e.altKey||e.ctrlKey||e.metaKey||e.isComposing||e.keyCode===229)return;const isItemTarget=isLyraMenuItemElement(e.target);if(e.key==="Escape"&&isItemTarget&&!this.hasStandalonePresentation){e.preventDefault(),this.closePresentation({focusTrigger:!0});return}if(!isItemTarget)return;const navigable=this.items.filter(i=>this.isNavigable(i)),current=this.activeIndex>=0?this.items[this.activeIndex]:void 0,currentNavIndex=current?navigable.indexOf(current):-1,intoSubmenuKey=this.effectiveDirection==="rtl"?"ArrowLeft":"ArrowRight";switch(e.key){case"ArrowRight":case"ArrowLeft":e.key===intoSubmenuKey?current?.hasSubmenu&&this.isNavigable(current)&&(e.preventDefault(),this.closeSubmenus(current),current.openSubmenu("first")):this.submenuAnchor&&!this.menubarAnchored&&(e.preventDefault(),this.closePresentation({focusTrigger:!0}));break;case"ArrowDown":case"ArrowUp":case"Home":case"End":{e.preventDefault();const nextIndex=resolveListMove(e,{count:navigable.length,current:currentNavIndex,orientation:"vertical"});nextIndex!==null&&this.setActiveItem(navigable[nextIndex]);break}case"Enter":case" ":e.preventDefault(),current?.hasSubmenu?(this.closeSubmenus(current),current.openSubmenu("first")):current?.isLinkItem?current.click():current?.select();break;default:this.typeBuffer.accepts(e)&&this.typeAhead(e.key);return}},this.onPopupPointerOver=e=>{if(!this.interactionOpen)return;const hovered=this.ownItemFromEvent(e);this.clearOwnedTimeout(this.submenuOpenTimer),this.submenuOpenTimer=void 0;const opened=this.openSubmenuItem();opened&&opened===hovered?(this.clearOwnedTimeout(this.submenuCloseTimer),this.submenuCloseTimer=void 0):opened&&this.scheduleSubmenuClose(opened),!(!hovered||hovered===opened||!hovered.hasSubmenu||!this.isNavigable(hovered))&&(this.submenuOpenTimer=this.scheduleOwnedTimeout(()=>{this.submenuOpenTimer=void 0,!(!this.interactionOpen||!this.items.includes(hovered))&&(this.closeSubmenus(hovered),hovered.openSubmenu("none"))},SUBMENU_OPEN_DELAY))},this.onPopupPointerLeave=()=>{this.clearOwnedTimeout(this.submenuOpenTimer),this.submenuOpenTimer=void 0;const opened=this.openSubmenuItem();opened&&this.scheduleSubmenuClose(opened)},this.onNestedSelect=e=>{if(e.target===this)return;const event=e;this.dropdownStayOpenOnSelect&&event.preventDefault(),queueMicrotask(()=>{event.defaultPrevented||this.dismissAfterSelection(!0)})},this.onPopupKeyDown=e=>{const listEl=this.popupPart("list");if(e.key==="Escape"){if(listEl&&e.composedPath().includes(listEl)||this.hasStandalonePresentation)return;e.preventDefault(),this.closePresentation({focusTrigger:!0});return}e.key==="Tab"&&this.tabWouldLeavePopup(e)&&this.closePresentation()}}static{_a=submenuPanelController}static{this.defaultStrings={...super.defaultStrings,menuLabel:LYRA_DEFAULT_menuLabel}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-select"])}static{this.identityEventDetailProperties=Object.freeze({"lr-select":Object.freeze(["item"])})}static{this.styles=[LyraElement.styles,styles]}get dropdownOpen(){return this._dropdownOpen}set dropdownOpen(next){const normalized=!!next;if(normalized===this._dropdownOpen)return;const old=this._dropdownOpen;this._dropdownOpen=normalized,this.presentationOpen=normalized,this.requestUpdate("dropdownOpen",old)}createSubmenuController(){const menu=this;return{get open(){return menu.submenuAnchor!==null&&menu.presentationOpen},attach(anchor,onStateChange,options){menu.submenuAnchor&&menu.submenuAnchor!==anchor&&menu.closePresentation(),menu.menubarAnchored=options?.menubar===!0,menu.submenuAnchor=anchor,menu.submenuStateChange=onStateChange,menu.syncPresentationState(),menu.requestUpdate()},detach(anchor){menu.submenuAnchor===anchor&&(menu.closePresentation(),menu.submenuAnchor=null,menu.menubarAnchored=!1,menu.submenuStateChange=null,menu.cleanup?.(),menu.cleanup=void 0,menu.syncPresentationState(),menu.requestUpdate())},async show(focus="first"){menu.submenuAnchor&&(menu.openPresentation(focus),await menu.updateComplete,await menu.focusAfterPlacement(focus))},async hide(options){menu.closePresentation(options),await menu.updateComplete}}}connectedCallback(){if(super.connectedCallback(),registerMenuWidthScale(),this.hasUpdated){const slot=this.renderRoot.querySelector("slot:not([name])");slot&&this.syncItemsFromSlot(slot,!0)}}firstUpdated(changed){super.firstUpdated(changed),this.syncRegionState(),this.syncPresentationState();const slot=this.itemsSlot;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>this.syncItemsFromSlot(s))})}get hasStandalonePresentation(){return!this.dropdownContained&&!this.submenuAnchor}get interactionOpen(){return this.hasStandalonePresentation||this.presentationOpen}syncPresentationState(){const standalone=this.hasStandalonePresentation;if(this.toggleAttribute("data-inline",standalone),this.toggleAttribute("data-submenu",this.submenuAnchor!==null),this.toggleAttribute("data-contained",this.dropdownContained),standalone){const active=this.activeIndex>=0?this.items[this.activeIndex]:void 0;if(!active||!this.isNavigable(active)){const first=this.items.find(item=>this.isNavigable(item));this.activeIndex=first?this.items.indexOf(first):-1}}else this.presentationOpen||(this.activeIndex=-1);this.applyRovingTabIndex()}syncRegionState(){const assigned=selector=>this.renderRoot.querySelector(selector)?.assignedElements({flatten:!0}).length??0;this.toggleAttribute("data-has-header",assigned('slot[name="header"]')>0),this.toggleAttribute("data-has-footer",assigned('slot[name="footer"]')>0),this.toggleAttribute("data-list-empty",assigned("slot:not([name])")===0)}willUpdate(changed){super.willUpdate(changed),this.presentationOpen&&this.submenuAnchor&&(this.cancelPresentationHideWatch(),this.presentationHidden=!1)}updated(changed){super.updated(changed);const list=this.renderRoot.querySelector('[part~="list"]')??void 0;syncAriaDescribedByElements(this,list,this.getAttribute("aria-describedby")),(changed.has("presentationOpen")||changed.has("dropdownOpen")||changed.has("dropdownContained"))&&(this.cleanup?.(),this.cleanup=void 0,this.presentationPositioned=!1,this.presentationOpen?this.submenuAnchor?(this.popupController.bindPointer(),this.reposition()):(this.popupController.unbindPointer(),this.presentationPositioned=!0,this.focusRoving(this.pendingFocus)):(this.popupController.unbindPointer(),this.resetTypeAhead(),this.activeIndex=-1,this.applyRovingTabIndex(),this.clearSubmenuTimers(),this.closeSubmenus(),this.submenuAnchor&&this.schedulePresentationHide())),changed.has("dropdownContained")&&this.syncPresentationState(),changed.has("dropdownSize")&&this.applyDropdownSize()}reposition(){this.cleanup?.(),this.cleanup=void 0,this.presentationPositioned=!1;const popup=this.renderRoot.querySelector(".submenu-surface");if(this.submenuAnchor&&popup){const placement=this.menubarAnchored?MENUBAR_PLACEMENT:rtlAwarePlacement(SUBMENU_PLACEMENT,this),topLayer=this.submenuAnchor.closest(tag("menubar"))?.topLayer===!0;this.placedTopLayer=syncTopLayerRelease(popup,this.placedTopLayer,topLayer),this.cleanup=place(this.submenuAnchor,popup,{placement,flipFallbackPlacements:this.menubarAnchored?void 0:SUBMENU_FALLBACK_PLACEMENTS.map(candidate=>rtlAwarePlacement(candidate,this)),...topLayerPlacement(topLayer,resolveEffectivePositioningStrategy(this,void 0,"fixed"))})}}cancelPresentationHideWatch(){this.presentationHideWatcher?.(),this.presentationHideWatcher=void 0}schedulePresentationHide(){this.cancelPresentationHideWatch();const surface=this.renderRoot.querySelector(".submenu-surface"),view=this.ownerDocument.defaultView,transitionMs=surface&&view?maxCssTime(view.getComputedStyle(surface).transitionDuration)+maxCssTime(view.getComputedStyle(surface).transitionDelay):0,waitForEvent=!!(surface&&view&&transitionMs>0&&!prefersReducedMotion(this));let settled=!1,timeout;const finish=()=>{settled||(settled=!0,timeout!==void 0&&view?.clearTimeout(timeout),surface?.removeEventListener("transitionend",onEnd),this.presentationHideWatcher===cancel&&(this.presentationHideWatcher=void 0),this.presentationHidden=!0)},onEnd=event=>{event.target===surface&&finish()},cancel=()=>{settled=!0,timeout!==void 0&&view?.clearTimeout(timeout),surface?.removeEventListener("transitionend",onEnd)};this.presentationHideWatcher=cancel,waitForEvent&&surface&&view?(surface.addEventListener("transitionend",onEnd),timeout=view.setTimeout(finish,transitionMs+50)):queueMicrotask(finish)}async focusAfterPlacement(focus){if(!this.presentationOpen||!this.submenuAnchor)return;const positioned=this.cleanup!==void 0&&(this.presentationPositioned||await waitForDeferredPlacement(()=>this.cleanup));if(!(!this.presentationOpen||!this.submenuAnchor)){if(!positioned){this.closePresentation(),await this.updateComplete;return}this.presentationPositioned=!0,this.focusRoving(focus)}}disconnectedCallback(){super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.presentationPositioned=!1,this.resetTypeAhead(),this.clearSubmenuTimers(),this.itemStateObserver?.disconnect(),this.itemStateObserver=void 0,this.popupController.unbindPointer();for(const item of this.items)this.releaseItemOwner(item);this._dropdownOpen=!1,this.presentationOpen=!1,this.cancelPresentationHideWatch(),this.presentationHidden=!0,this.submenuStateChange?.(!1)}scheduleOwnedTimeout(callback,delay){const owner=this.ownerDocument.defaultView;if(owner)return{owner,handle:owner.setTimeout(callback,delay)}}clearOwnedTimeout(timer){timer&&timer.owner.clearTimeout(timer.handle)}focusContained(focus="first"){if(this.dropdownContained&&this.dropdownOwner)if(this.dropdownOwner.open)this.pendingFocus=focus,this.focusRoving(focus);else{const transition=this.dropdownOwner.show();this.dropdownOwner.open&&(this.pendingFocus=focus)}}openPresentation(focus="first"){if(this.dropdownContained&&this.dropdownOwner){this.focusContained(focus);return}this.pendingFocus=focus,this.presentationOpen?(!this.submenuAnchor||this.presentationPositioned)&&this.focusRoving(focus):(this.presentationOpen=!0,this.submenuStateChange?.(!0))}closePresentation(options){if(this.dropdownContained&&this.dropdownOwner){this.dropdownOwner.hide(options);return}this.presentationOpen&&(this.presentationOpen=!1,this.submenuStateChange?.(!1),options?.focusTrigger&&this.submenuAnchor&&resolveAccessibleTrigger(this.submenuAnchor).focus())}syncItemsFromSlot(slot,reconnect=!1){if(!this.isConnected)return;const assigned=slot.assignedElements({flatten:!0}).filter(isLyraMenuItemElement);if(assigned.length===this.items.length&&assigned.every((item,index)=>item===this.items[index])){reconnect&&(this.observeItems(),this.syncPresentationState());return}this.itemStateObserver?.disconnect();const previousItems=this.items,previouslyActive=this.activeIndex>=0?this.items[this.activeIndex]:void 0,focusedBefore=safeDeepActiveElement(this.ownerDocument),activeItemLostFocus=!!previouslyActive&&(focusedBefore===null||focusedBefore===this.ownerDocument.body||focusedBefore===previouslyActive||composedContains(previouslyActive,focusedBefore));this.items=assigned;const assignedItems=new Set(assigned);for(const item of previousItems)assignedItems.has(item)||this.releaseItemOwner(item);if(this.observeItems(),this.activeIndex=previouslyActive?this.items.indexOf(previouslyActive):-1,this.syncPresentationState(),this.syncRegionState(),this.interactionOpen)if(this.activeIndex===-1){const successor=this.items.find(item=>this.isNavigable(item));previouslyActive&&successor?this.setActiveItem(successor,activeItemLostFocus):this.focusRoving(this.pendingFocus),activeItemLostFocus&&!this.items.some(item=>this.isNavigable(item))&&this.rehomeZeroSurvivorFocus()}else{const active=activeElementIn(this.ownerDocument);!(isUsableActiveElement(active)&&this.contains(active))&&activeItemLostFocus&&this.items[this.activeIndex].focus()}}observeItems(){for(const item of this.items)this.acquireItemOwner(item);this.applyDropdownSize();const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;if(MutationObserverCtor){const owner=this.ownerDocument;let observer;observer=new MutationObserverCtor(()=>{this.itemStateObserver!==observer||this.ownerDocument!==owner||this.onItemStateChange()}),this.itemStateObserver=observer;for(const item of this.items)this.itemStateObserver.observe(item,{attributes:!0,attributeFilter:["disabled","hidden","aria-hidden","inert"]})}}acquireItemOwner(item){item[menuItemOwner]?.(this.owningMenu)}releaseItemOwner(item){item[menuItemOwner]?.(null,this.owningMenu)}uncheckRadioGroupSiblings(item,group){for(const sibling of this.items)sibling!==item&&sibling.type==="radio"&&sibling.group===group&&sibling.checked&&(sibling.checked=!1)}isNavigable(item){return!item.interactionDisabled&&isRovingTargetAvailable(item)}applyDropdownSize(){if(this.dropdownSize)for(const item of this.items)item.size=this.dropdownSize}rehomeZeroSurvivorFocus(){if(this.dropdownContained&&this.dropdownOwner){this.dropdownOwner.hide({focusTrigger:!0});return}if(this.submenuAnchor){this.closePresentation({focusTrigger:!0});return}const list=this.renderRoot.querySelector('[part~="list"]');list&&(list.tabIndex=-1,list.focus({preventScroll:!0}))}onOwnedItemSelect(item){if(!isLyraMenuItemElement(item)||!this.items.includes(item))return;!this.emit("lr-select",{item},{cancelable:!0}).defaultPrevented&&!this.dropdownStayOpenOnSelect&&this.dismissAfterSelection(!0)}dismissAfterSelection(focusTrigger){this.closeSubmenus(),this.dropdownContained?this.dropdownOwner&&this.dropdownOwner.hide({focusTrigger}):this.submenuAnchor&&this.closePresentation({focusTrigger})}applyRovingTabIndex(){this.items.forEach((item,i)=>{item.tabIndex=i===this.activeIndex?0:-1})}focusRoving(which){if(which==="none")return;const navigable=this.items.filter(i=>this.isNavigable(i));if(!navigable.length)return;const item=which==="first"?navigable[0]:navigable[navigable.length-1];item&&this.setActiveItem(item)}setActiveItem(item,moveFocus=!0){this.activeIndex=this.items.indexOf(item),this.applyRovingTabIndex(),this.closeSubmenus(item),moveFocus&&item.focus()}closeSubmenus(keep){for(const item of this.items)item!==keep&&item.submenuOpen&&item.closeSubmenu()}openSubmenuItem(){return this.items.find(item=>item.submenuOpen)}clearSubmenuTimers(){this.clearOwnedTimeout(this.submenuOpenTimer),this.clearOwnedTimeout(this.submenuCloseTimer),this.submenuOpenTimer=void 0,this.submenuCloseTimer=void 0}ownItemFromEvent(e){let owner;for(const node of e.composedPath()){if(node===this)break;isLyraMenuItemElement(node)&&(owner=node)}return owner}isForeignEvent(e){for(const node of e.composedPath()){if(node===this)return!1;if(isLyraMenuElement(node))return!0}return!1}scheduleSubmenuClose(item){this.submenuCloseTimer||(this.submenuCloseTimer=this.scheduleOwnedTimeout(()=>{this.submenuCloseTimer=void 0,item.submenuOpen&&(composedContains(item,safeDeepActiveElement(this.ownerDocument))||item.closeSubmenu())},SUBMENU_CLOSE_DELAY))}popupPart(name){return this.renderRoot.querySelector(`[part="${name}"]`)}tabWouldLeavePopup(e){const header=this.popupPart("header"),footer=this.popupPart("footer"),listEl=this.popupPart("list"),backwards=e.shiftKey,active=safeDeepActiveElement(this.ownerDocument),headerStops=header?collectFocusableElements(header):[],footerStops=footer?collectFocusableElements(footer):[],listStops=listEl?collectFocusableElements(listEl):[],hasNeighbor=stops=>{const index=active?stops.indexOf(active):-1;return index===-1?!1:backwards?index>0:index<stops.length-1},path=e.composedPath();return footer&&path.includes(footer)?hasNeighbor(footerStops)?!1:backwards?listStops.length===0&&headerStops.length===0:!0:header&&path.includes(header)?hasNeighbor(headerStops)?!1:backwards?!0:listStops.length===0&&footerStops.length===0:!isLyraMenuItemElement(e.target)&&hasNeighbor(listStops)?!1:backwards?headerStops.length===0:footerStops.length===0}typeAhead(char){this.typeBuffer.add(char,this.effectiveLocale);const navigable=this.items.filter(i=>this.isNavigable(i));if(!navigable.length)return;const current=this.activeIndex>=0?this.items[this.activeIndex]:void 0,currentIndex=current?navigable.indexOf(current):-1,match=this.typeBuffer.match(navigable,currentIndex,item=>item.getTextLabel(),this.effectiveLocale);match!==null&&this.setActiveItem(navigable[match])}resetTypeAhead(){this.typeBuffer.clear()}get effectiveLabel(){const hostLabel=this.getAttribute("aria-label");return hostLabel!==null?hostLabel:this.label!==void 0?this.label:this.dropdownLabel!==void 0?this.dropdownLabel:this.localize("menuLabel")}renderContents(bindPointerOver=!0){return html`
2
2
  <div part="header">
3
3
  <slot name="header" @slotchange=${this.onRegionSlotChange}></slot>
4
4
  </div>
@@ -1 +1 @@
1
- import{__decorate}from"tslib";import{html}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{TypeAheadBuffer}from"../../../internal/type-ahead-buffer.js";import{isRovingTargetAvailable,resolveListMove}from"../../../internal/list-navigation.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{activateNonmodalOverlay,composedContains,deepActiveElement}from"../../../internal/nonmodal-overlay-manager.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{keyEventOwnedByInnerControl}from"../../../internal/hotkey.js";import{sizes}from"../../../internal/sizes.styles.js";import{tag}from"../../../internal/prefix.js";import{menubarItemOwner}from"./menubar-shared.js";import{styles}from"./menubar.styles.js";import{LYRA_DEFAULT_menuLabel}from"../../../internal/default-strings/shared.generated.js";class LyraMenubar extends LyraElement{static{this.defaultStrings={...super.defaultStrings,menuLabel:LYRA_DEFAULT_menuLabel}}static{this.styles=[LyraElement.styles,sizes,styles]}constructor(){super(),this.topLayer=!1,this.size="m",this.frame="card",this.items=[],this.activeIndex=-1,this.expandedItem=null,this.typeBuffer=new TypeAheadBuffer(this),this.focusedItem=null,this.owner={menuStateChanged:(item,open)=>this.menuStateChanged(item,open),itemStateChanged:()=>this.syncItemState()},this.syncItems=()=>{const assigned=(this.renderRoot.querySelector("slot")?.assignedElements({flatten:!0})??[]).filter(element=>element.localName===tag("menubar-item"));if(assigned.length===this.items.length&&assigned.every((item,index)=>item===this.items[index]))return;const previous=this.items[this.activeIndex],oldIndex=this.activeIndex,active=deepActiveElement(this.ownerDocument),heldFocus=!!previous&&(active===previous||!!active&&composedContains(previous,active)||this.focusedItem===previous&&(!active||active===this.ownerDocument.body));for(const item of this.items)assigned.includes(item)||item[menubarItemOwner](null,this.owner);this.items=assigned;for(const item of this.items)item[menubarItemOwner](this.owner);this.observeItems(),previous&&assigned.includes(previous)&&this.isNavigable(previous)?this.setActive(previous):this.rehome(oldIndex,heldFocus),this.expandedItem&&!assigned.includes(this.expandedItem)&&this.collapse()},this.onDocumentFocus=()=>{const active=deepActiveElement(this.ownerDocument);(!active||!composedContains(this,active))&&(this.focusedItem=null,this.collapse())},this.onClick=event=>{const found=this.eventItem(event);if(!found||found.inMenu)return;const{item}=found;if(this.setActive(item,!0),!item.hasMenu){this.expandedItem&&this.collapse();return}this.expandedItem===item?this.collapse():this.expandedItem?this.carry(item):this.open(item,"none")},this.onPointerOver=event=>{if(!this.expandedItem||event.pointerType==="touch")return;const found=this.eventItem(event);found&&!found.inMenu&&found.item.hasMenu&&found.item!==this.expandedItem&&this.carry(found.item)},this.onKeyDown=event=>{if(event.defaultPrevented||event.isComposing||event.keyCode===229||event.altKey||event.ctrlKey||event.metaKey)return;const found=this.eventItem(event);if(!found)return;const{item,inMenu}=found;if(inMenu){if(!isHtmlElement(event.target)||![tag("menu-item"),tag("dropdown-item")].includes(event.target.localName)||keyEventOwnedByInnerControl(event,{container:event.target})||event.key!=="ArrowLeft"&&event.key!=="ArrowRight")return}else if(event.target!==item||keyEventOwnedByInnerControl(event,{container:item}))return;const navigable=this.items.filter(candidate=>this.isNavigable(candidate));if(!navigable.length)return;const index=navigable.indexOf(item);let next;const nextIndex=resolveListMove(event,{count:navigable.length,current:index,orientation:"horizontal",direction:this.effectiveDirection});if(nextIndex!==null)next=navigable[nextIndex];else if(["ArrowDown","ArrowUp","Enter"," "].includes(event.key)){item.hasMenu?(event.preventDefault(),this.open(item,event.key==="ArrowUp"?"last":"first")):(event.key==="Enter"||event.key===" ")&&(event.preventDefault(),item.click());return}else if(this.typeBuffer.accepts(event)){this.typeBuffer.add(event.key,this.effectiveLocale);const match=this.typeBuffer.match(navigable,index,item2=>item2.textLabel,this.effectiveLocale);match!==null&&(next=navigable[match])}next&&(event.preventDefault(),this.move(next))},this.addEventListener("keydown",this.onKeyDown),this.addEventListener("click",this.onClick),this.addEventListener("pointerover",this.onPointerOver),this.addEventListener("focusin",event=>{const item=this.items.find(candidate=>candidate===event.target);item&&this.isNavigable(item)&&(this.focusedItem=item,this.setActive(item))})}connectedCallback(){if(super.connectedCallback(),this.hasUpdated){for(const item of this.items)item[menubarItemOwner](this.owner);this.observeItems(),queueMicrotask(()=>{this.isConnected&&(this.syncItems(),this.syncItemState())})}}disconnectedCallback(){this.collapse(),this.typeBuffer.clear(),this.itemObserver?.disconnect(),this.itemObserver=void 0,this.ownerDocument.removeEventListener("focusin",this.onDocumentFocus,!0);for(const item of this.items)item[menubarItemOwner](null,this.owner);this.focusedItem=null,super.disconnectedCallback()}firstUpdated(changed){super.firstUpdated(changed),queueMicrotask(()=>{this.isConnected&&collectInitialSlotAssignment(this.renderRoot.querySelector("slot"),this.syncItems)})}isNavigable(item){return isRovingTargetAvailable(item)}observeItems(){this.itemObserver?.disconnect();const Observer=this.ownerDocument.defaultView?.MutationObserver;if(Observer){this.itemObserver=new Observer(()=>this.syncItemState());for(const item of this.items)this.itemObserver.observe(item,{attributes:!0,attributeFilter:["disabled","hidden","aria-hidden","inert"]})}}rehome(index,focus){const successor=this.items.find((item,current)=>current>=Math.max(0,index)&&this.isNavigable(item))??this.items.slice(0,Math.max(0,index)).reverse().find(item=>this.isNavigable(item));if(successor)this.setActive(successor,focus);else{this.activeIndex=-1;for(const item of this.items)item.tabIndex=-1}}syncItemState(){const active=this.items[this.activeIndex];if(!active||!this.isNavigable(active)){const focused=deepActiveElement(this.ownerDocument);this.rehome(this.activeIndex,!!active&&(focused===active||!!focused&&composedContains(active,focused)))}this.expandedItem&&(!this.isNavigable(this.expandedItem)||!this.expandedItem.hasMenu)&&this.collapse()}setActive(item,focus=!1){if(this.isNavigable(item)){this.activeIndex=this.items.indexOf(item);for(const candidate of this.items)candidate.tabIndex=candidate===item?0:-1;focus&&(this.focusedItem=item,item.focus({preventScroll:!0}))}}registerOverlay(){this.overlayHandle||(this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this,preferredInitialFocus:()=>this.expandedItem,onEscape:()=>this.collapse(),onTab:()=>this.collapse(),restoreFocusTo:()=>{const active=deepActiveElement(this.ownerDocument);return isHtmlElement(active)&&active!==this.ownerDocument.body&&active!==this.ownerDocument.documentElement?active:null}}),this.ownerDocument.addEventListener("focusin",this.onDocumentFocus,!0))}open(item,focus){const previous=this.expandedItem;this.expandedItem=item,previous&&previous!==item&&previous.closeMenu(),this.registerOverlay(),item.openMenu(focus)}carry(item){const previous=this.expandedItem;this.setActive(item,!0),item.hasMenu&&this.isNavigable(item)?(this.expandedItem=item,previous&&previous!==item&&previous.closeMenu(),item.openMenu("none")):this.collapse()}collapse(){const item=this.expandedItem;this.expandedItem=null,this.ownerDocument.removeEventListener("focusin",this.onDocumentFocus,!0);const handle=this.overlayHandle;this.overlayHandle=void 0,handle?.deactivate(),item&&item.closeMenu()}menuStateChanged(item,open){if(this.items.includes(item))if(open&&item!==this.expandedItem){const previous=this.expandedItem;this.expandedItem=item,previous&&previous.closeMenu(),this.registerOverlay()}else!open&&item===this.expandedItem&&this.collapse()}eventItem(event){const path=event.composedPath(),item=path.find(target=>this.items.includes(target));if(!item||!this.isNavigable(item))return;const preceding=path.slice(0,path.indexOf(item));return{item,path:preceding,inMenu:preceding.some(node=>isHtmlElement(node)&&node.localName===tag("menu"))}}move(item){this.expandedItem?this.carry(item):this.setActive(item,!0)}render(){return html`<div part="base" role="menubar" aria-label=${this.getAttribute("aria-label")??this.label??this.localize("menuLabel")}><slot @slotchange=${this.syncItems}></slot></div>`}}__decorate([property()],LyraMenubar.prototype,"label",void 0),__decorate([property({type:Boolean,attribute:"top-layer",reflect:!0})],LyraMenubar.prototype,"topLayer",void 0),__decorate([property({reflect:!0})],LyraMenubar.prototype,"size",void 0),__decorate([property({reflect:!0})],LyraMenubar.prototype,"frame",void 0);export{LyraMenubar};
1
+ import{__decorate}from"tslib";import{html}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{TypeAheadBuffer}from"../../../internal/type-ahead-buffer.js";import{isRovingTargetAvailable,resolveListMove}from"../../../internal/list-navigation.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{activateNonmodalOverlay,composedContains,deepActiveElement}from"../../../internal/nonmodal-overlay-manager.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{keyEventOwnedByInnerControl}from"../../../internal/hotkey.js";import{sizes}from"../../../internal/sizes.styles.js";import{tag}from"../../../internal/prefix.js";import{menubarItemOwner}from"./menubar-shared.js";import{styles}from"./menubar.styles.js";import{LYRA_DEFAULT_menuLabel}from"../../../internal/default-strings/shared.generated.js";class LyraMenubar extends LyraElement{static{this.defaultStrings={...super.defaultStrings,menuLabel:LYRA_DEFAULT_menuLabel}}static{this.styles=[LyraElement.styles,sizes,styles]}constructor(){super(),this.topLayer=!1,this.size="m",this.frame="card",this.items=[],this.activeIndex=-1,this.expandedItem=null,this.typeBuffer=new TypeAheadBuffer(this),this.focusedItem=null,this.owner={menuStateChanged:(item,open)=>this.menuStateChanged(item,open),itemStateChanged:()=>this.syncItemState()},this.syncItems=()=>{const assigned=(this.renderRoot.querySelector("slot")?.assignedElements({flatten:!0})??[]).filter(element=>element.localName===tag("menubar-item"));if(assigned.length===this.items.length&&assigned.every((item,index)=>item===this.items[index]))return;const previous=this.items[this.activeIndex],oldIndex=this.activeIndex,active=deepActiveElement(this.ownerDocument),heldFocus=!!previous&&(active===previous||!!active&&composedContains(previous,active)||this.focusedItem===previous&&(!active||active===this.ownerDocument.body)),assignedItems=new Set(assigned);for(const item of this.items)assignedItems.has(item)||item[menubarItemOwner](null,this.owner);this.items=assigned;for(const item of this.items)item[menubarItemOwner](this.owner);this.observeItems(),previous&&assignedItems.has(previous)&&this.isNavigable(previous)?this.setActive(previous):this.rehome(oldIndex,heldFocus),this.expandedItem&&!assignedItems.has(this.expandedItem)&&this.collapse()},this.onDocumentFocus=()=>{const active=deepActiveElement(this.ownerDocument);(!active||!composedContains(this,active))&&(this.focusedItem=null,this.collapse())},this.onClick=event=>{const found=this.eventItem(event);if(!found||found.inMenu)return;const{item}=found;if(this.setActive(item,!0),!item.hasMenu){this.expandedItem&&this.collapse();return}this.expandedItem===item?this.collapse():this.expandedItem?this.carry(item):this.open(item,"none")},this.onPointerOver=event=>{if(!this.expandedItem||event.pointerType==="touch")return;const found=this.eventItem(event);found&&!found.inMenu&&found.item.hasMenu&&found.item!==this.expandedItem&&this.carry(found.item)},this.onKeyDown=event=>{if(event.defaultPrevented||event.isComposing||event.keyCode===229||event.altKey||event.ctrlKey||event.metaKey)return;const found=this.eventItem(event);if(!found)return;const{item,inMenu}=found;if(inMenu){if(!isHtmlElement(event.target)||![tag("menu-item"),tag("dropdown-item")].includes(event.target.localName)||keyEventOwnedByInnerControl(event,{container:event.target})||event.key!=="ArrowLeft"&&event.key!=="ArrowRight")return}else if(event.target!==item||keyEventOwnedByInnerControl(event,{container:item}))return;const navigable=this.items.filter(candidate=>this.isNavigable(candidate));if(!navigable.length)return;const index=navigable.indexOf(item);let next;const nextIndex=resolveListMove(event,{count:navigable.length,current:index,orientation:"horizontal",direction:this.effectiveDirection});if(nextIndex!==null)next=navigable[nextIndex];else if(["ArrowDown","ArrowUp","Enter"," "].includes(event.key)){item.hasMenu?(event.preventDefault(),this.open(item,event.key==="ArrowUp"?"last":"first")):(event.key==="Enter"||event.key===" ")&&(event.preventDefault(),item.click());return}else if(this.typeBuffer.accepts(event)){this.typeBuffer.add(event.key,this.effectiveLocale);const match=this.typeBuffer.match(navigable,index,item2=>item2.textLabel,this.effectiveLocale);match!==null&&(next=navigable[match])}next&&(event.preventDefault(),this.move(next))},this.addEventListener("keydown",this.onKeyDown),this.addEventListener("click",this.onClick),this.addEventListener("pointerover",this.onPointerOver),this.addEventListener("focusin",event=>{const item=this.items.find(candidate=>candidate===event.target);item&&this.isNavigable(item)&&(this.focusedItem=item,this.setActive(item))})}connectedCallback(){if(super.connectedCallback(),this.hasUpdated){for(const item of this.items)item[menubarItemOwner](this.owner);this.observeItems(),queueMicrotask(()=>{this.isConnected&&(this.syncItems(),this.syncItemState())})}}disconnectedCallback(){this.collapse(),this.typeBuffer.clear(),this.itemObserver?.disconnect(),this.itemObserver=void 0,this.ownerDocument.removeEventListener("focusin",this.onDocumentFocus,!0);for(const item of this.items)item[menubarItemOwner](null,this.owner);this.focusedItem=null,super.disconnectedCallback()}firstUpdated(changed){super.firstUpdated(changed),queueMicrotask(()=>{this.isConnected&&collectInitialSlotAssignment(this.renderRoot.querySelector("slot"),this.syncItems)})}isNavigable(item){return isRovingTargetAvailable(item)}observeItems(){this.itemObserver?.disconnect();const Observer=this.ownerDocument.defaultView?.MutationObserver;if(Observer){this.itemObserver=new Observer(()=>this.syncItemState());for(const item of this.items)this.itemObserver.observe(item,{attributes:!0,attributeFilter:["disabled","hidden","aria-hidden","inert"]})}}rehome(index,focus){const successor=this.items.find((item,current)=>current>=Math.max(0,index)&&this.isNavigable(item))??this.items.slice(0,Math.max(0,index)).reverse().find(item=>this.isNavigable(item));if(successor)this.setActive(successor,focus);else{this.activeIndex=-1;for(const item of this.items)item.tabIndex=-1}}syncItemState(){const active=this.items[this.activeIndex];if(!active||!this.isNavigable(active)){const focused=deepActiveElement(this.ownerDocument);this.rehome(this.activeIndex,!!active&&(focused===active||!!focused&&composedContains(active,focused)))}this.expandedItem&&(!this.isNavigable(this.expandedItem)||!this.expandedItem.hasMenu)&&this.collapse()}setActive(item,focus=!1){if(this.isNavigable(item)){this.activeIndex=this.items.indexOf(item);for(const candidate of this.items)candidate.tabIndex=candidate===item?0:-1;focus&&(this.focusedItem=item,item.focus({preventScroll:!0}))}}registerOverlay(){this.overlayHandle||(this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this,preferredInitialFocus:()=>this.expandedItem,onEscape:()=>this.collapse(),onTab:()=>this.collapse(),restoreFocusTo:()=>{const active=deepActiveElement(this.ownerDocument);return isHtmlElement(active)&&active!==this.ownerDocument.body&&active!==this.ownerDocument.documentElement?active:null}}),this.ownerDocument.addEventListener("focusin",this.onDocumentFocus,!0))}open(item,focus){const previous=this.expandedItem;this.expandedItem=item,previous&&previous!==item&&previous.closeMenu(),this.registerOverlay(),item.openMenu(focus)}carry(item){const previous=this.expandedItem;this.setActive(item,!0),item.hasMenu&&this.isNavigable(item)?(this.expandedItem=item,previous&&previous!==item&&previous.closeMenu(),item.openMenu("none")):this.collapse()}collapse(){const item=this.expandedItem;this.expandedItem=null,this.ownerDocument.removeEventListener("focusin",this.onDocumentFocus,!0);const handle=this.overlayHandle;this.overlayHandle=void 0,handle?.deactivate(),item&&item.closeMenu()}menuStateChanged(item,open){if(this.items.includes(item))if(open&&item!==this.expandedItem){const previous=this.expandedItem;this.expandedItem=item,previous&&previous.closeMenu(),this.registerOverlay()}else!open&&item===this.expandedItem&&this.collapse()}eventItem(event){const path=event.composedPath(),item=path.find(target=>this.items.includes(target));if(!item||!this.isNavigable(item))return;const preceding=path.slice(0,path.indexOf(item));return{item,path:preceding,inMenu:preceding.some(node=>isHtmlElement(node)&&node.localName===tag("menu"))}}move(item){this.expandedItem?this.carry(item):this.setActive(item,!0)}render(){return html`<div part="base" role="menubar" aria-label=${this.getAttribute("aria-label")??this.label??this.localize("menuLabel")}><slot @slotchange=${this.syncItems}></slot></div>`}}__decorate([property()],LyraMenubar.prototype,"label",void 0),__decorate([property({type:Boolean,attribute:"top-layer",reflect:!0})],LyraMenubar.prototype,"topLayer",void 0),__decorate([property({reflect:!0})],LyraMenubar.prototype,"size",void 0),__decorate([property({reflect:!0})],LyraMenubar.prototype,"frame",void 0);export{LyraMenubar};
@@ -105,7 +105,7 @@ current:boolean;private _open;
105
105
  * time; opening one closes the other with an `lr-toggle` whose source is `peer`.
106
106
  * @default false
107
107
  */
108
- get open():boolean;set open(next:boolean);private browserResolved;private closing;private readonly slotPresence;private readonly panelId;private interactionMode?;private liveOpen;private placement?;private placementKey;private placedTopLayer?;private overlayHandle?;private pendingShow;private pendingMorph?;private hideAnimation?;private hideAnimationStarted;private transitionToken;private morphCleanup?;private focusInPanel;private semanticFocusOrigin?;constructor();private get ownerContext();private get isLink();private get isTrigger();private get floatingLayout();private get baseElement();private get panelElement();private get canDisclose();connectedCallback():void;disconnectedCallback():void;
108
+ get open():boolean;set open(next:boolean);private browserResolved;private closing;private readonly slotPresence;private readonly panelId;private interactionMode?;private liveOpen;private placement?;private placementKey;private placedTopLayer?;private overlayHandle?;private pendingShow;private pendingMorph?;private hideAnimation?;private hideAnimationStarted;private transitionToken;private morphCleanup?;private focusInPanel;private semanticFocusOrigin?;private hrefChangedThisUpdate;constructor();private get ownerContext();private get isLink();private get isTrigger();private get floatingLayout();private get baseElement();private get panelElement();private get canDisclose();connectedCallback():void;disconnectedCallback():void;
109
109
  /** Moves focus to the link or button. */
110
110
  focus(options?:FocusOptions):void;
111
111
  /** Activates the link or button, exactly like a user click. */
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{activeElementIn,shadowFocusTarget}from"../../../internal/active-element.js";import{deferredPlaceReady,loadAnchoredOverlayRuntime,syncTopLayerRelease,topLayerPlacement,waitForDeferredPlacement}from"../../../internal/anchored-overlay-runtime.js";import{maxCssTime}from"../../../internal/css-motion-time.js";import{chevronIcon}from"../../../internal/icons.js";import{resolveGuardedRel}from"../../../internal/link-rel.js";import{LyraElement}from"../../../internal/lyra-element.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{activateNonmodalOverlay,composedContains,deepActiveElement}from"../../../internal/nonmodal-overlay-manager.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{animateRegistered}from"../../../internal/registered-animation.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{safeLinkHref}from"../../../internal/safe-url.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{navigationMenuOwner,registerNavigationMenuItemController}from"../navigation-menu/navigation-menu-owner.js";import{styles}from"./navigation-menu-item.styles.js";const PLACEMENT_STYLE_PROPERTIES=["position","margin","left","top","--lr-positioner-available-inline-size","--lr-positioner-available-block-size"],SHOW_OFFSET="translateY(var(--lr-size-neg-0-25rem))";class LyraNavigationMenuItem extends LyraElement{static{this.styles=[LyraElement.styles,styles]}get open(){return this._open}set open(next){const value=!!next;if(value===this._open)return;const source=this.hasUpdated?"programmatic":null;value?this.openPanel("programmatic",source):this.closePanel(source)}constructor(){super(),this.href="",this.target="",this.rel="",this.current=!1,this._open=!1,this.browserResolved=!1,this.closing=!1,this.slotPresence=new SlotPresenceController(this),this.panelId=nextId("navigation-menu-panel"),this.liveOpen=!1,this.placementKey="",this.pendingShow=!1,this.hideAnimationStarted=!1,this.transitionToken=0,this.focusInPanel=!1,this.onFocusIn=event=>{const panel=this.panelElement,target=event.composedPath()[0];this.focusInPanel=panel!==null&&target!==void 0&&composedContains(panel,target)},this.onFocusOut=event=>{const next=event.relatedTarget;if(next===null)return;const panel=this.panelElement;(!panel||!composedContains(panel,next))&&(this.focusInPanel=!1)},this.onBaseClick=()=>{if(this.isLink)return;const context=this.ownerContext;if(context){context.activate(this);return}this.isTrigger&&(this._open?this.closePanel("user"):this.openPanel("programmatic","user"))},this.onHostKeyDown=event=>{event.key!=="Escape"||event.defaultPrevented||!this._open||this.ownerContext||(event.preventDefault(),this.onOverlayEscape())},new GlassScrollLayer(this,'[part="panel"]',()=>this.open),registerNavigationMenuItemController(this,{isTrigger:()=>this.isTrigger,isLink:()=>this.isLink,isOpen:()=>this._open,mode:()=>this._open?this.interactionMode:void 0,pin:()=>{this._open&&(this.interactionMode="pinned")},base:()=>this.baseElement,panel:()=>this.panelElement,open:(mode,source)=>this.openPanel(mode,source),close:(source,options)=>this.closePanel(source,options),isTopmost:()=>this.overlayHandle?.isTopmost()??!1,placementReady:()=>this.placementReady(),reposition:()=>{this.placementKey="",this.requestUpdate()}})}get ownerContext(){return navigationMenuOwner(this)}get isLink(){return!!safeLinkHref(this.href)}get isTrigger(){return!this.isLink&&this.slotPresence.has("panel")}get floatingLayout(){return this.ownerContext?.layout()==="bar"}get baseElement(){return this.renderRoot?.querySelector('[part~="base"]')??null}get panelElement(){return this.renderRoot?.querySelector('[part~="panel"]')??null}get canDisclose(){return this.isLink?!1:!this.browserResolved||this.slotPresence.has("panel")}connectedCallback(){super.connectedCallback(),this.addEventListener("focusin",this.onFocusIn),this.addEventListener("focusout",this.onFocusOut),this.addEventListener("keydown",this.onHostKeyDown),this.updateBrowserDerivedState(()=>{this.browserResolved=!0}),this.hasUpdated&&this._open&&(this.interactionMode="programmatic",this.requestUpdate())}disconnectedCallback(){this.removeEventListener("focusin",this.onFocusIn),this.removeEventListener("focusout",this.onFocusOut),this.removeEventListener("keydown",this.onHostKeyDown),this.cancelMorph(),this.stopPlacement(),this.releaseOverlay(!1),this.cancelHideAnimation(),this.closing=!1,this.focusInPanel=!1,this.semanticFocusOrigin=void 0,this._open&&this.interactionMode==="hover"?(this._open=!1,this.liveOpen=!1,this.interactionMode=void 0,this.requestUpdate("open",!0)):this._open&&(this.interactionMode="programmatic"),super.disconnectedCallback()}focus(options){const base=this.baseElement;base?base.focus(options):super.focus(options)}click(){this.baseElement?.click()}willUpdate(changed){if(super.willUpdate(changed),this._open&&!this.canDisclose&&(this.liveOpen?this.closePanel("programmatic",{repairFocus:!0,instant:!0}):(this._open=!1,this.interactionMode=void 0,this.pendingShow=!1,this.pendingMorph=void 0,this.requestUpdate("open",!0))),changed.has("href")){const previous=this.baseElement,nextKind=this.isLink?"a":"button";this.semanticFocusOrigin=previous&&previous.localName!==nextKind&&shadowFocusTarget(this)===previous?previous:void 0}}updated(changed){super.updated(changed),this.isConnected&&this.hasAttribute("open")!==this._open&&this.toggleAttribute("open",this._open),this.syncFloating(),this.syncHideAnimation();const focusOrigin=this.semanticFocusOrigin;if(this.semanticFocusOrigin=void 0,focusOrigin){const internalActive=shadowFocusTarget(this),documentActive=activeElementIn(this.ownerDocument);(internalActive===null||internalActive===focusOrigin)&&(documentActive===null||documentActive===this||documentActive===this.ownerDocument.body)&&this.baseElement?.focus()}}openPanel(mode,source){if(this._open)return mode==="pinned"&&this.interactionMode==="hover"&&(this.interactionMode="pinned"),!0;if(!this.canDisclose)return this.requestUpdate("open",!0),!1;const context=this.ownerContext,morph=context?.willOpen(this);return this.cancelHideAnimation(),this.closing=!1,this.interactionMode=mode,this.pendingMorph=morph,this.pendingShow=source!==null&&!morph,this._open=!0,this.requestUpdate("open",!1),this.queueToggle(!0,source),context?.changed(this,!0,source),!0}closePanel(source,options={}){if(!this._open)return;options.repairFocus!==!1&&this.panelHoldsFocus()&&(options.focusTarget??this.baseElement)?.focus({preventScroll:!0});const wasFloating=this.placement!==void 0||this.overlayHandle!==void 0;this.cancelMorph(),this.stopPlacement(),this.releaseOverlay(options.restoreFocus===!0);const animate=!options.instant&&wasFloating&&this.liveOpen&&this.isConnected&&this.floatingLayout;this.cancelHideAnimation(),this.closing=animate,this.pendingMorph=void 0,this.pendingShow=!1,this.interactionMode=void 0,this.liveOpen=!1,this.focusInPanel=!1,this._open=!1,this.requestUpdate("open",!0),this.queueToggle(!1,source),this.ownerContext?.changed(this,!1,source)}queueToggle(open,source){source!==null&&this.updateComplete.then(()=>{this.emit("lr-toggle",{expanded:open,source})})}panelHoldsFocus(){const panel=this.panelElement;if(!panel)return!1;const active=deepActiveElement(this.ownerDocument);return active&&composedContains(panel,active)?!0:this.focusInPanel&&(active===null||active===this.ownerDocument.body)}syncFloating(){const panel=this.panelElement,visible=this.isTrigger&&this.browserResolved&&this._open;if(visible&&(this.liveOpen=!0),!(visible&&this.isConnected&&this.floatingLayout)){this.stopPlacement(),this.overlayHandle&&this.releaseOverlay(!1),panel&&!this.closing&&(this.clearPlacementStyles(panel),visible&&panel.hasAttribute("data-lr-top-layer")&&loadAnchoredOverlayRuntime().then(runtime=>runtime.releaseTopLayer?.(panel),()=>{})),visible&&(this.pendingShow=!1,this.pendingMorph=void 0);return}if(!panel)return;const context=this.ownerContext,anchor=context.anchor(this);if(!anchor)return;const key=[anchor===this.baseElement?"item":"menu",context.distance(),context.topLayer(),this.effectiveDirection].join("|");(!this.placement||key!==this.placementKey)&&this.startPlacement(anchor,panel,key),this.overlayHandle?.isActive()||(this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.panelElement,onEscape:()=>this.onOverlayEscape(),restoreFocusTo:()=>this.baseElement}));const morph=this.pendingMorph,show=this.pendingShow;if(this.pendingMorph=void 0,this.pendingShow=!1,!morph&&!show)return;const handle=this.placement;handle?.ready.then(placed=>{!placed||handle!==this.placement||!this._open||(morph?this.runMorph(morph):this.runShowAnimation())})}startPlacement(anchor,panel,key){this.stopPlacement();const context=this.ownerContext,bridge=this.renderRoot.querySelector(".hover-bridge");this.placementKey=key;const topLayer=context.topLayer();this.placedTopLayer=syncTopLayerRelease(panel,this.placedTopLayer,topLayer),this.placement=deferredPlaceReady(anchor,panel,{placement:rtlAwarePlacement("bottom-start",this),...topLayerPlacement(topLayer,resolveEffectivePositioningStrategy(this,void 0,"fixed")),offset:context.distance(),hoverBridge:bridge??void 0})}stopPlacement(){const handle=this.placement;this.placement=void 0,this.placementKey="",handle?.()}releaseOverlay(restoreFocus){const handle=this.overlayHandle;this.overlayHandle=void 0,handle?.deactivate({restoreFocus})}clearPlacementStyles(panel){for(const property2 of PLACEMENT_STYLE_PROPERTIES)panel.style.removeProperty(property2)}onOverlayEscape(){const context=this.ownerContext;if(context){context.escape(this);return}const within=composedContains(this,deepActiveElement(this.ownerDocument));this.closePanel("user",{restoreFocus:within})}async placementReady(){return await this.updateComplete,this.placement?waitForDeferredPlacement(()=>this.placement):this._open}get registryHost(){return this.ownerContext?.owner??this}runShowAnimation(){const panel=this.panelElement;panel&&animateRegistered(this.registryHost,panel,"navigation-menu.show",this.effectiveDirection,{keyframes:[{opacity:0,transform:SHOW_OFFSET},{opacity:1,transform:"translateY(0)"}],durationProperties:["--lr-navigation-menu-show-duration","--lr-duration-fast"],easingProperties:["--lr-easing-standard"]})}syncHideAnimation(){if(!this.closing||this.hideAnimationStarted)return;this.hideAnimationStarted=!0;const token=this.transitionToken,panel=this.panelElement,animation=panel?animateRegistered(this.registryHost,panel,"navigation-menu.hide",this.effectiveDirection,{keyframes:[{opacity:1,transform:"translateY(0)"},{opacity:0,transform:SHOW_OFFSET}],durationProperties:["--lr-navigation-menu-hide-duration","--lr-duration-fast"],easingProperties:["--lr-easing-standard"]}):void 0;this.hideAnimation=animation;const settle=()=>{token===this.transitionToken&&(this.hideAnimation?.cancel(),this.hideAnimation=void 0,this.hideAnimationStarted=!1,this.closing=!1)};animation?animation.finished.then(settle,settle):queueMicrotask(settle)}cancelHideAnimation(){this.transitionToken++,this.hideAnimation?.cancel(),this.hideAnimation=void 0,this.hideAnimationStarted=!1}runMorph(morph){const panel=this.panelElement,content=panel?.querySelector(".panel-content");if(!panel||!content)return;const travel="var(--lr-size-1rem)",reversed=`calc(-1 * ${travel})`,from=morph.direction==="end"?travel:reversed,mirrored=morph.direction==="end"?reversed:travel;animateRegistered(this.registryHost,content,`navigation-menu.enter-from-${morph.direction}`,this.effectiveDirection,{keyframes:[{opacity:0,transform:`translateX(${from})`},{opacity:1,transform:"translateX(0)"}],rtlKeyframes:[{opacity:0,transform:`translateX(${mirrored})`},{opacity:1,transform:"translateX(0)"}],durationProperties:["--lr-navigation-menu-switch-duration","--lr-duration-base"],easingProperties:["--lr-easing-standard"]});const view=this.ownerDocument.defaultView;if(!view||prefersReducedMotion(this))return;const to=panel.getBoundingClientRect();if(Math.abs(to.width-morph.from.width)<1&&Math.abs(to.height-morph.from.height)<1)return;this.cancelMorph();const natural=content.getBoundingClientRect().width;panel.setAttribute("data-morphing",""),panel.style.inlineSize=`${morph.from.width}px`,panel.style.blockSize=`${morph.from.height}px`,content.style.inlineSize=`${natural}px`;const style=view.getComputedStyle(panel),total=maxCssTime(style.transitionDuration)+maxCssTime(style.transitionDelay);let frame,timer;const onEnd=event=>{event.target===panel&&["inline-size","block-size","width","height"].includes(event.propertyName)&&cleanup()},cleanup=()=>{this.morphCleanup===cleanup&&(this.morphCleanup=void 0,frame!==void 0&&view.cancelAnimationFrame(frame),timer!==void 0&&view.clearTimeout(timer),panel.removeEventListener("transitionend",onEnd),panel.removeAttribute("data-morphing"),panel.style.removeProperty("inline-size"),panel.style.removeProperty("block-size"),content.style.removeProperty("inline-size"))};this.morphCleanup=cleanup,panel.addEventListener("transitionend",onEnd),frame=view.requestAnimationFrame(()=>{frame=void 0,this.morphCleanup===cleanup&&(panel.style.inlineSize=`${to.width}px`,panel.style.blockSize=`${to.height}px`,timer=view.setTimeout(cleanup,total+50))})}cancelMorph(){this.morphCleanup?.()}render(){const isLink=this.isLink,isTrigger=this.isTrigger,floating=this.floatingLayout,stacked=this.ownerContext?.layout()==="stacked",expanded=this._open&&this.browserResolved,panelVisible=isTrigger&&this.browserResolved&&(this._open||this.closing),ariaLabel=hostAriaLabel(this),parts=["base"];this.current&&parts.push("base-current"),isTrigger&&expanded&&parts.push("base-open");const label=html`<span part="start" ?hidden=${!this.slotPresence.has("start")}
1
+ import{__decorate}from"tslib";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{activeElementIn,shadowFocusTarget}from"../../../internal/active-element.js";import{deferredPlaceReady,loadAnchoredOverlayRuntime,syncTopLayerRelease,topLayerPlacement,waitForDeferredPlacement}from"../../../internal/anchored-overlay-runtime.js";import{maxCssTime}from"../../../internal/css-motion-time.js";import{chevronIcon}from"../../../internal/icons.js";import{resolveGuardedRel}from"../../../internal/link-rel.js";import{LyraElement}from"../../../internal/lyra-element.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{activateNonmodalOverlay,composedContains,deepActiveElement}from"../../../internal/nonmodal-overlay-manager.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{animateRegistered}from"../../../internal/registered-animation.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{safeLinkHref}from"../../../internal/safe-url.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{navigationMenuOwner,registerNavigationMenuItemController}from"../navigation-menu/navigation-menu-owner.js";import{styles}from"./navigation-menu-item.styles.js";const PLACEMENT_STYLE_PROPERTIES=["position","margin","left","top","--lr-positioner-available-inline-size","--lr-positioner-available-block-size"],SHOW_OFFSET="translateY(var(--lr-size-neg-0-25rem))";class LyraNavigationMenuItem extends LyraElement{static{this.styles=[LyraElement.styles,styles]}get open(){return this._open}set open(next){const value=!!next;if(value===this._open)return;const source=this.hasUpdated?"programmatic":null;value?this.openPanel("programmatic",source):this.closePanel(source)}constructor(){super(),this.href="",this.target="",this.rel="",this.current=!1,this._open=!1,this.browserResolved=!1,this.closing=!1,this.slotPresence=new SlotPresenceController(this),this.panelId=nextId("navigation-menu-panel"),this.liveOpen=!1,this.placementKey="",this.pendingShow=!1,this.hideAnimationStarted=!1,this.transitionToken=0,this.focusInPanel=!1,this.hrefChangedThisUpdate=!1,this.onFocusIn=event=>{const panel=this.panelElement,target=event.composedPath()[0];this.focusInPanel=panel!==null&&target!==void 0&&composedContains(panel,target)},this.onFocusOut=event=>{const next=event.relatedTarget;if(next===null)return;const panel=this.panelElement;(!panel||!composedContains(panel,next))&&(this.focusInPanel=!1)},this.onBaseClick=()=>{if(this.isLink)return;const context=this.ownerContext;if(context){context.activate(this);return}this.isTrigger&&(this._open?this.closePanel("user"):this.openPanel("programmatic","user"))},this.onHostKeyDown=event=>{event.key!=="Escape"||event.defaultPrevented||!this._open||this.ownerContext||(event.preventDefault(),this.onOverlayEscape())},this.addController({hostUpdate:()=>{if(this._open&&!this.canDisclose&&(this.liveOpen?this.closePanel("programmatic",{repairFocus:!0,instant:!0}):(this._open=!1,this.interactionMode=void 0,this.pendingShow=!1,this.pendingMorph=void 0,this.requestUpdate("open",!0))),this.hrefChangedThisUpdate){const previous=this.baseElement,nextKind=this.isLink?"a":"button";this.semanticFocusOrigin=previous&&previous.localName!==nextKind&&shadowFocusTarget(this)===previous?previous:void 0}}}),new GlassScrollLayer(this,'[part="panel"]',()=>this.open),registerNavigationMenuItemController(this,{isTrigger:()=>this.isTrigger,isLink:()=>this.isLink,isOpen:()=>this._open,mode:()=>this._open?this.interactionMode:void 0,pin:()=>{this._open&&(this.interactionMode="pinned")},base:()=>this.baseElement,panel:()=>this.panelElement,open:(mode,source)=>this.openPanel(mode,source),close:(source,options)=>this.closePanel(source,options),isTopmost:()=>this.overlayHandle?.isTopmost()??!1,placementReady:()=>this.placementReady(),reposition:()=>{this.placementKey="",this.requestUpdate()}})}get ownerContext(){return navigationMenuOwner(this)}get isLink(){return!!safeLinkHref(this.href)}get isTrigger(){return!this.isLink&&this.slotPresence.has("panel")}get floatingLayout(){return this.ownerContext?.layout()==="bar"}get baseElement(){return this.renderRoot?.querySelector('[part~="base"]')??null}get panelElement(){return this.renderRoot?.querySelector('[part~="panel"]')??null}get canDisclose(){return this.isLink?!1:!this.browserResolved||this.slotPresence.has("panel")}connectedCallback(){super.connectedCallback(),this.addEventListener("focusin",this.onFocusIn),this.addEventListener("focusout",this.onFocusOut),this.addEventListener("keydown",this.onHostKeyDown),this.updateBrowserDerivedState(()=>{this.browserResolved=!0}),this.hasUpdated&&this._open&&(this.interactionMode="programmatic",this.requestUpdate())}disconnectedCallback(){this.removeEventListener("focusin",this.onFocusIn),this.removeEventListener("focusout",this.onFocusOut),this.removeEventListener("keydown",this.onHostKeyDown),this.cancelMorph(),this.stopPlacement(),this.releaseOverlay(!1),this.cancelHideAnimation(),this.closing=!1,this.focusInPanel=!1,this.semanticFocusOrigin=void 0,this._open&&this.interactionMode==="hover"?(this._open=!1,this.liveOpen=!1,this.interactionMode=void 0,this.requestUpdate("open",!0)):this._open&&(this.interactionMode="programmatic"),super.disconnectedCallback()}focus(options){const base=this.baseElement;base?base.focus(options):super.focus(options)}click(){this.baseElement?.click()}willUpdate(changed){super.willUpdate(changed),this.hrefChangedThisUpdate=changed.has("href")}updated(changed){super.updated(changed),this.isConnected&&this.hasAttribute("open")!==this._open&&this.toggleAttribute("open",this._open),this.syncFloating(),this.syncHideAnimation();const focusOrigin=this.semanticFocusOrigin;if(this.semanticFocusOrigin=void 0,focusOrigin){const internalActive=shadowFocusTarget(this),documentActive=activeElementIn(this.ownerDocument);(internalActive===null||internalActive===focusOrigin)&&(documentActive===null||documentActive===this||documentActive===this.ownerDocument.body)&&this.baseElement?.focus()}}openPanel(mode,source){if(this._open)return mode==="pinned"&&this.interactionMode==="hover"&&(this.interactionMode="pinned"),!0;if(!this.canDisclose)return this.requestUpdate("open",!0),!1;const context=this.ownerContext,morph=context?.willOpen(this);return this.cancelHideAnimation(),this.closing=!1,this.interactionMode=mode,this.pendingMorph=morph,this.pendingShow=source!==null&&!morph,this._open=!0,this.requestUpdate("open",!1),this.queueToggle(!0,source),context?.changed(this,!0,source),!0}closePanel(source,options={}){if(!this._open)return;options.repairFocus!==!1&&this.panelHoldsFocus()&&(options.focusTarget??this.baseElement)?.focus({preventScroll:!0});const wasFloating=this.placement!==void 0||this.overlayHandle!==void 0;this.cancelMorph(),this.stopPlacement(),this.releaseOverlay(options.restoreFocus===!0);const animate=!options.instant&&wasFloating&&this.liveOpen&&this.isConnected&&this.floatingLayout;this.cancelHideAnimation(),this.closing=animate,this.pendingMorph=void 0,this.pendingShow=!1,this.interactionMode=void 0,this.liveOpen=!1,this.focusInPanel=!1,this._open=!1,this.requestUpdate("open",!0),this.queueToggle(!1,source),this.ownerContext?.changed(this,!1,source)}queueToggle(open,source){source!==null&&this.updateComplete.then(()=>{this.emit("lr-toggle",{expanded:open,source})})}panelHoldsFocus(){const panel=this.panelElement;if(!panel)return!1;const active=deepActiveElement(this.ownerDocument);return active&&composedContains(panel,active)?!0:this.focusInPanel&&(active===null||active===this.ownerDocument.body)}syncFloating(){const panel=this.panelElement,visible=this.isTrigger&&this.browserResolved&&this._open;if(visible&&(this.liveOpen=!0),!(visible&&this.isConnected&&this.floatingLayout)){this.stopPlacement(),this.overlayHandle&&this.releaseOverlay(!1),panel&&!this.closing&&(this.clearPlacementStyles(panel),visible&&panel.hasAttribute("data-lr-top-layer")&&loadAnchoredOverlayRuntime().then(runtime=>runtime.releaseTopLayer?.(panel),()=>{})),visible&&(this.pendingShow=!1,this.pendingMorph=void 0);return}if(!panel)return;const context=this.ownerContext,anchor=context.anchor(this);if(!anchor)return;const key=[anchor===this.baseElement?"item":"menu",context.distance(),context.topLayer(),this.effectiveDirection].join("|");(!this.placement||key!==this.placementKey)&&this.startPlacement(anchor,panel,key),this.overlayHandle?.isActive()||(this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.panelElement,onEscape:()=>this.onOverlayEscape(),restoreFocusTo:()=>this.baseElement}));const morph=this.pendingMorph,show=this.pendingShow;if(this.pendingMorph=void 0,this.pendingShow=!1,!morph&&!show)return;const handle=this.placement;handle?.ready.then(placed=>{!placed||handle!==this.placement||!this._open||(morph?this.runMorph(morph):this.runShowAnimation())})}startPlacement(anchor,panel,key){this.stopPlacement();const context=this.ownerContext,bridge=this.renderRoot.querySelector(".hover-bridge");this.placementKey=key;const topLayer=context.topLayer();this.placedTopLayer=syncTopLayerRelease(panel,this.placedTopLayer,topLayer),this.placement=deferredPlaceReady(anchor,panel,{placement:rtlAwarePlacement("bottom-start",this),...topLayerPlacement(topLayer,resolveEffectivePositioningStrategy(this,void 0,"fixed")),offset:context.distance(),hoverBridge:bridge??void 0})}stopPlacement(){const handle=this.placement;this.placement=void 0,this.placementKey="",handle?.()}releaseOverlay(restoreFocus){const handle=this.overlayHandle;this.overlayHandle=void 0,handle?.deactivate({restoreFocus})}clearPlacementStyles(panel){for(const property2 of PLACEMENT_STYLE_PROPERTIES)panel.style.removeProperty(property2)}onOverlayEscape(){const context=this.ownerContext;if(context){context.escape(this);return}const within=composedContains(this,deepActiveElement(this.ownerDocument));this.closePanel("user",{restoreFocus:within})}async placementReady(){return await this.updateComplete,this.placement?waitForDeferredPlacement(()=>this.placement):this._open}get registryHost(){return this.ownerContext?.owner??this}runShowAnimation(){const panel=this.panelElement;panel&&animateRegistered(this.registryHost,panel,"navigation-menu.show",this.effectiveDirection,{keyframes:[{opacity:0,transform:SHOW_OFFSET},{opacity:1,transform:"translateY(0)"}],durationProperties:["--lr-navigation-menu-show-duration","--lr-duration-fast"],easingProperties:["--lr-easing-standard"]})}syncHideAnimation(){if(!this.closing||this.hideAnimationStarted)return;this.hideAnimationStarted=!0;const token=this.transitionToken,panel=this.panelElement,animation=panel?animateRegistered(this.registryHost,panel,"navigation-menu.hide",this.effectiveDirection,{keyframes:[{opacity:1,transform:"translateY(0)"},{opacity:0,transform:SHOW_OFFSET}],durationProperties:["--lr-navigation-menu-hide-duration","--lr-duration-fast"],easingProperties:["--lr-easing-standard"]}):void 0;this.hideAnimation=animation;const settle=()=>{token===this.transitionToken&&(this.hideAnimation?.cancel(),this.hideAnimation=void 0,this.hideAnimationStarted=!1,this.closing=!1)};animation?animation.finished.then(settle,settle):queueMicrotask(settle)}cancelHideAnimation(){this.transitionToken++,this.hideAnimation?.cancel(),this.hideAnimation=void 0,this.hideAnimationStarted=!1}runMorph(morph){const panel=this.panelElement,content=panel?.querySelector(".panel-content");if(!panel||!content)return;const travel="var(--lr-size-1rem)",reversed=`calc(-1 * ${travel})`,from=morph.direction==="end"?travel:reversed,mirrored=morph.direction==="end"?reversed:travel;animateRegistered(this.registryHost,content,`navigation-menu.enter-from-${morph.direction}`,this.effectiveDirection,{keyframes:[{opacity:0,transform:`translateX(${from})`},{opacity:1,transform:"translateX(0)"}],rtlKeyframes:[{opacity:0,transform:`translateX(${mirrored})`},{opacity:1,transform:"translateX(0)"}],durationProperties:["--lr-navigation-menu-switch-duration","--lr-duration-base"],easingProperties:["--lr-easing-standard"]});const view=this.ownerDocument.defaultView;if(!view||prefersReducedMotion(this))return;const to=panel.getBoundingClientRect();if(Math.abs(to.width-morph.from.width)<1&&Math.abs(to.height-morph.from.height)<1)return;this.cancelMorph();const natural=content.getBoundingClientRect().width;panel.setAttribute("data-morphing",""),panel.style.inlineSize=`${morph.from.width}px`,panel.style.blockSize=`${morph.from.height}px`,content.style.inlineSize=`${natural}px`;const style=view.getComputedStyle(panel),total=maxCssTime(style.transitionDuration)+maxCssTime(style.transitionDelay);let frame,timer;const onEnd=event=>{event.target===panel&&["inline-size","block-size","width","height"].includes(event.propertyName)&&cleanup()},cleanup=()=>{this.morphCleanup===cleanup&&(this.morphCleanup=void 0,frame!==void 0&&view.cancelAnimationFrame(frame),timer!==void 0&&view.clearTimeout(timer),panel.removeEventListener("transitionend",onEnd),panel.removeAttribute("data-morphing"),panel.style.removeProperty("inline-size"),panel.style.removeProperty("block-size"),content.style.removeProperty("inline-size"))};this.morphCleanup=cleanup,panel.addEventListener("transitionend",onEnd),frame=view.requestAnimationFrame(()=>{frame=void 0,this.morphCleanup===cleanup&&(panel.style.inlineSize=`${to.width}px`,panel.style.blockSize=`${to.height}px`,timer=view.setTimeout(cleanup,total+50))})}cancelMorph(){this.morphCleanup?.()}render(){const isLink=this.isLink,isTrigger=this.isTrigger,floating=this.floatingLayout,stacked=this.ownerContext?.layout()==="stacked",expanded=this._open&&this.browserResolved,panelVisible=isTrigger&&this.browserResolved&&(this._open||this.closing),ariaLabel=hostAriaLabel(this),parts=["base"];this.current&&parts.push("base-current"),isTrigger&&expanded&&parts.push("base-open");const label=html`<span part="start" ?hidden=${!this.slotPresence.has("start")}
2
2
  ><slot name="start"></slot></span
3
3
  ><span part="label"><slot></slot></span
4
4
  ><span part="end" ?hidden=${!this.slotPresence.has("end")}><slot name="end"></slot></span
@@ -145,7 +145,7 @@ mobileBreakpoint:string;
145
145
  /** Logical edge occupied by desktop navigation and the mobile drawer. */
146
146
  navigationPlacement:PageNavigationPlacement;
147
147
  /** Hides the default mobile toggle. Slotted `data-toggle-nav` controls remain available. */
148
- disableNavigationToggle:boolean;private accessibleLabel;private readonly mainId;private readonly navigationId;private readonly drawerId;private readonly skipTargetId;private readonly skipLabelId;private fragmentTargetId;private fragmentTabIndex;private resizeObserver?;private resizeView?;private overlayHandle?;private readonly nativeModal;private navigationTriggerOwner?;private navigationOpener;private customToggle?;private customToggles;private readonly customToggleOwnership;private mainElement?;private drawerElement?;connectedCallback():void;disconnectedCallback():void;protected firstUpdated(changed:PropertyValues):void;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues<this>):void;private observeAllocation;private readonly onWindowResize;private measureAllocation;private applyMeasuredInlineSize;private syncOverlay;private readonly navigationDeferredReturn;private readonly resolveNavigationRestoreTarget;private syncCustomToggle;private releaseCustomToggleA11y;private isUnavailableCustomToggle;private rememberTriggerAndToggle;private readonly onDefaultToggleClick;private readonly onToggleSlotClick;private readonly onPageClick;private readonly onBackdropClick;private readonly onSkipClick;private requestNavOpen;
148
+ disableNavigationToggle:boolean;private accessibleLabel;private readonly mainId;private readonly navigationId;private readonly drawerId;private readonly skipTargetId;private readonly skipLabelId;private fragmentTargetId;private fragmentTabIndex;private resizeObserver?;private readonly allocationFrame;private resizeView?;private overlayHandle?;private readonly nativeModal;private navigationTriggerOwner?;private navigationOpener;private customToggle?;private customToggles;private readonly customToggleOwnership;private mainElement?;private drawerElement?;connectedCallback():void;disconnectedCallback():void;protected firstUpdated(changed:PropertyValues):void;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues<this>):void;private observeAllocation;private readonly onWindowResize;private measureAllocation;private applyMeasuredInlineSize;private syncOverlay;private readonly navigationDeferredReturn;private readonly resolveNavigationRestoreTarget;private syncCustomToggle;private releaseCustomToggleA11y;private isUnavailableCustomToggle;private rememberTriggerAndToggle;private readonly onDefaultToggleClick;private readonly onToggleSlotClick;private readonly onPageClick;private readonly onBackdropClick;private readonly onSkipClick;private requestNavOpen;
149
149
  /** Open mobile navigation. Desktop navigation is already visible, but the state is retained so
150
150
  * an open drawer can move through desktop and back without replacing its content. */
151
151
  showNavigation():void;