@aceshooting/lyra-ui 14.3.1 → 14.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,29 @@
1
1
  # Changelog
2
2
 
3
+ ## 14.3.2
4
+
5
+ ### Patch Changes
6
+
7
+ - 0314633: Keep accessible names computed from slotted content independent of whether the component is
8
+ currently displayed. A row inside a closed dropdown, a tab in a hidden group, or a chip, tag, toast
9
+ or progress bar inside any `visibility: hidden` container previously computed an empty name, because
10
+ the shared accessible-text walk applied visibility inherited from the container to the content it
11
+ was naming.
12
+
13
+ `lr-menu-item` and `lr-dropdown-item` additionally wrote that empty result back as an authoritative
14
+ `aria-label=""`, which suppresses the row's own content-derived name and left it permanently
15
+ unnamed — most visibly on a dropdown that is already `open` on its first render. An empty computed
16
+ name now removes the attribute instead of emptying it, for both the row and its submenu's
17
+ `role="menu"`, so the browser falls back to the visible label. `getTextLabel()` returns that label
18
+ for a closed menu too, restoring type-ahead.
19
+
20
+ `lr-tag` also never named its remove button from an element-wrapped label, because its first sample
21
+ runs before layout exists; it now takes the same pre-layout reading `lr-chip` already did.
22
+
23
+ Authored `aria-label`, `aria-labelledby` and explicitly empty consumer labels stay authoritative,
24
+ and `display: none`, `aria-hidden`, `inert` and `hidden` branches are still excluded from every
25
+ computed name.
26
+
3
27
  ## 14.3.1
4
28
 
5
29
  ### Patch Changes
@@ -12,7 +12,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
12
12
  aria-hidden="true"
13
13
  focusable="false"
14
14
  ><polyline points="5 12.5 10 17.5 19 6.5"></polyline></svg>
15
- `}class LyraMenuItem extends LyraElement{constructor(){super(...arguments),this.value="",this.size="m",this.disabled=!1,this.variant="default",this.type="normal",this.checked=!1,this.loading=!1,this.hasIconSlot=!1,this.hasDetailsSlot=!1,this.hasSuffixSlot=!1,this.submenuAssigned=!1,this.submenuExpanded=!1,this.slottedLabel="",this.submenuPanel=null,this.submenuPanelAttached=!1,this.submenuPanelGeneration=0,this.labelObservationGeneration=0,this.announcedNativeState="",this.owningMenu=null,this.ownsAriaLabel=!1,this.ownedAriaLabelValue=null,this.ownsPanelAriaLabel=!1,this.ownedPanelAriaLabelValue=null,this.onNativeStateMutation=()=>{const signature=this.nativeStateSignature();signature!==this.announcedNativeState&&(this.announcedNativeState=signature,this.emitStateChange())},this.onIconSlotChange=()=>{this.hasIconSlot=[...this.renderRoot.querySelectorAll('slot[name="icon"], slot[name="prefix"]')].some(slot=>slot.assignedElements({flatten:!0}).length>0)},this.onDetailsSlotChange=e=>{this.hasDetailsSlot=e.target.assignedNodes({flatten:!0}).some(node=>(node.textContent??"").trim()!=="")},this.onSuffixSlotChange=e=>{this.hasSuffixSlot=e.target.assignedElements({flatten:!0}).length>0},this.onLabelSlotChange=event=>{this.observeLabelContent(),this.syncSlottedLabel(event.target)},this.onForwardedLabelSlotChange=event=>{const slot=event.target;this.labelForwardingSlots().includes(slot)&&(this.observeLabelContent(),this.syncSlottedLabel())},this.onSubmenuSlotChange=e=>{this.syncSubmenuSlot(e.target)},this.onPanelStateChange=open=>{this.submenuExpanded=open}}static{this.knownUnobservedAttributes=["submenu-open"]}static{this.styles=[LyraElement.styles,sizes,styles]}get hasSubmenu(){return this.submenuAssigned}get submenuOpen(){return this.submenuExpanded}[menuItemOwner](owner,expectedOwner){owner===null&&expectedOwner&&this.owningMenu!==expectedOwner||(this.owningMenu=owner)}set submenuOpen(next){!!next!==this.submenuExpanded&&(next?this.openSubmenu("none"):this.closeSubmenu())}get interactionDisabled(){return this.disabled||this.loading}connectedCallback(){super.connectedCallback();const initialLabel=this.readSlottedLabel(null,!1);initialLabel!==this.slottedLabel&&(this.slottedLabel=initialLabel),this.applyComputedName(),this.tabIndex!==0&&(this.tabIndex=-1),this.announcedNativeState=this.nativeStateSignature();const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;MutationObserverCtor&&(this.nativeStateObserver=new MutationObserverCtor(this.onNativeStateMutation),this.nativeStateObserver.observe(this,{attributes:!0,attributeFilter:["hidden","inert","aria-hidden"]}),this.labelObserver=new MutationObserverCtor(()=>{this.observeLabelContent(),this.syncSlottedLabel()}),this.observeLabelContent()),this.addEventListener("slotchange",this.onForwardedLabelSlotChange);const labelGeneration=++this.labelObservationGeneration;this.updateComplete.then(()=>{if(!this.isConnected||labelGeneration!==this.labelObservationGeneration)return;this.observeLabelContent(),this.syncSlottedLabel();const submenuSlot=this.renderRoot.querySelector('slot[name="submenu"]');submenuSlot&&this.syncSubmenuSlot(submenuSlot)})}disconnectedCallback(){super.disconnectedCallback(),this.submenuPanelGeneration+=1,this.submenuExpanded=!1,this.nativeStateObserver?.disconnect(),this.nativeStateObserver=void 0,this.labelObservationGeneration+=1,this.removeEventListener("slotchange",this.onForwardedLabelSlotChange),this.labelObserver?.disconnect(),this.labelObserver=void 0,this.submenuPanel&&this.submenuPanelAttached&&(this.submenuPanel[submenuPanelController].detach(this),this.submenuPanelAttached=!1)}nativeStateSignature(){return`${this.hidden}|${this.inert}|${this.getAttribute("aria-hidden")}`}emitStateChange(){this.emit("lr-menu-item-state-change",{disabled:this.interactionDisabled,hidden:!!this.hidden,inert:this.inert})}willUpdate(changed){super.willUpdate(changed);const isCheckbox=this.type==="checkbox"&&!this.submenuAssigned;this.setAttribute("role",isCheckbox?"menuitemcheckbox":"menuitem"),isCheckbox?this.setAttribute("aria-checked",this.checked?"true":"false"):this.removeAttribute("aria-checked"),this.submenuAssigned?(this.setAttribute("aria-haspopup","menu"),this.setAttribute("aria-expanded",this.submenuExpanded?"true":"false")):(this.removeAttribute("aria-haspopup"),this.removeAttribute("aria-expanded")),this.applyComputedName(),this.toggleAttribute("submenu-open",this.submenuExpanded),this.setAttribute("aria-disabled",String(this.interactionDisabled)),this.interactionDisabled&&(changed.has("disabled")||changed.has("loading"))&&(this.tabIndex=-1,activeElementIn(this.ownerDocument)===this&&this.blur()),(changed.has("disabled")||changed.has("loading"))&&this.emitStateChange()}click(){this.interactionDisabled||this.renderRoot.querySelector('[part~="base"]')?.click()}select(){if(!this.interactionDisabled){if(this.submenuPanel){this.openSubmenu("none");return}if(this.type==="checkbox"){const checked=!this.checked;this.emit("lr-menu-item-change",{value:this.value,checked},{cancelable:!0}).defaultPrevented||(this.checked=checked)}this.owningMenu?.activate(this)}}async openSubmenu(focus="first"){const panel=this.submenuPanel,generation=this.submenuPanelGeneration;if(!panel||this.interactionDisabled||!this.isCurrentSubmenuPanel(panel,generation))return;const controller=panel[submenuPanelController],shown=controller.show(focus);this.isCurrentSubmenuPanel(panel,generation)&&(this.submenuExpanded=controller.open,await shown,this.isCurrentSubmenuPanel(panel,generation)&&(panel.updateComplete&&await panel.updateComplete,this.isCurrentSubmenuPanel(panel,generation)&&(this.submenuExpanded=controller.open,await this.updateComplete)))}async closeSubmenu(){const panel=this.submenuPanel,generation=this.submenuPanelGeneration;if(!panel||!this.isCurrentSubmenuPanel(panel,generation))return;const controller=panel[submenuPanelController],hidden=controller.hide();this.isCurrentSubmenuPanel(panel,generation)&&(this.submenuExpanded=controller.open,await hidden,this.isCurrentSubmenuPanel(panel,generation)&&(panel.updateComplete&&await panel.updateComplete,this.isCurrentSubmenuPanel(panel,generation)&&(this.submenuExpanded=controller.open,await this.updateComplete)))}defaultLabelSlot(){return this.renderRoot?.querySelector("slot:not([name])")??null}isDefaultLabelBranch(node){let top=node;for(;top.parentNode&&top.parentNode!==this;)top=top.parentNode;return top.parentNode!==this?!1:top.nodeType!==1||(top.getAttribute("slot")??"")===""}labelForwardingSlots(){return Array.from(this.querySelectorAll("slot")).filter(slot=>this.isDefaultLabelBranch(slot))}composedParentForNode(node){const assignedSlot=node.assignedSlot;if(assignedSlot)return assignedSlot;if(node.parentElement)return node.parentElement;const root=node.getRootNode();return"host"in root&&root.host.nodeType===1?root.host:null}isLabelSubtreeExcluded(element){return!(element.getRootNode()===this.renderRoot&&element.matches('[part~="label"][aria-hidden="true"][inert]:not([hidden])'))&&isAccessibilitySubtreeExcluded(element)}readSlottedLabel(slot=this.defaultLabelSlot(),requireRendered=!0){const nodes=slot?slot.assignedNodes({flatten:!0}):Array.from(this.childNodes).filter(node=>this.isDefaultLabelBranch(node));return composedAccessibilityText(nodes,{ancestorBoundary:this,isSubtreeExcluded:element=>this.isLabelSubtreeExcluded(element),requireRendered}).replace(/\s+/g," ").trim()}observeLabelAncestors(node,options){const observer=this.labelObserver;if(!observer)return;let current=this.composedParentForNode(node);for(;current;)current!==this&&!this.contains(current)&&observer.observe(current,options),current=composedParentElement(current)}observeLabelContent(){const observer=this.labelObserver;if(!observer)return;observer.disconnect();const options={attributes:!0,attributeFilter:["aria-hidden","aria-label","aria-labelledby","alt","class","data-hidden","hidden","inert","id","label","open","slot","style"],characterData:!0,childList:!0,subtree:!0};observer.observe(this,options);const slot=this.defaultLabelSlot();for(const assigned of slot?.assignedNodes({flatten:!0})??[])this.contains(assigned)||observer.observe(assigned,options),this.observeLabelAncestors(assigned,{attributes:!0,attributeFilter:options.attributeFilter})}syncSlottedLabel(slot=this.defaultLabelSlot()){const next=this.readSlottedLabel(slot);next!==this.slottedLabel&&(this.slottedLabel=next),this.applyComputedName(),this.applyPanelName()}syncSubmenuSlot(submenuSlot){if(!submenuSlot.isConnected||submenuSlot.getRootNode()!==this.renderRoot)return;const assigned=submenuSlot.assignedElements({flatten:!0}),authoredPanel=assigned.find(element=>element.localName===tag("menu")),hasDirectItems=assigned.some(element=>element.localName===tag("menu-item")||element.localName===tag("dropdown-item")),kind=authoredPanel?"panel":hasDirectItems?"items":void 0;if(this.submenuKind=kind,this.submenuAssigned=kind!==void 0,kind==="items"){const generated=this.renderRoot.querySelector("[data-generated-submenu]");generated&&this.connectSubmenuPanel(generated);return}this.connectSubmenuPanel(authoredPanel??null)}connectSubmenuPanel(next){const samePanel=next===this.submenuPanel;if(samePanel&&(next===null||this.submenuPanelAttached))return;const previous=this.submenuPanel;if(++this.submenuPanelGeneration,previous&&this.submenuPanelAttached&&previous[submenuPanelController].detach(this),this.submenuPanelAttached=!1,samePanel||(this.submenuPanel=next,this.ownsPanelAriaLabel=!1,this.ownedPanelAriaLabelValue=null),!this.submenuPanel){this.submenuExpanded=!1;return}const controller=this.submenuPanel[submenuPanelController];controller.attach(this,this.onPanelStateChange),this.submenuPanelAttached=!0,this.submenuExpanded=controller.open,this.applyPanelName()}isCurrentSubmenuPanel(panel,generation){return this.isConnected&&this.submenuPanel===panel&&this.submenuPanelGeneration===generation}updated(changed){if(super.updated(changed),changed.has("submenuKind")&&this.submenuKind==="items"){const generated=this.renderRoot.querySelector("[data-generated-submenu]");this.connectSubmenuPanel(generated)}}applyComputedName(){if(this.ownsAriaLabel&&this.getAttribute("aria-label")!==this.ownedAriaLabelValue&&(this.ownsAriaLabel=!1,this.ownedAriaLabelValue=null),this.hasAttribute("aria-labelledby")){this.ownsAriaLabel&&this.removeAttribute("aria-label"),this.ownsAriaLabel=!1,this.ownedAriaLabelValue=null;return}this.hasAttribute("aria-label")&&!this.ownsAriaLabel||(this.ownsAriaLabel=!0,this.ownedAriaLabelValue=this.slottedLabel,this.getAttribute("aria-label")!==this.slottedLabel&&this.setAttribute("aria-label",this.slottedLabel))}applyPanelName(){const panel=this.submenuPanel;if(panel){if(this.ownsPanelAriaLabel&&panel.getAttribute("aria-label")!==this.ownedPanelAriaLabelValue&&(this.ownsPanelAriaLabel=!1,this.ownedPanelAriaLabelValue=null),panel.hasAttribute("label")){this.ownsPanelAriaLabel&&(panel.removeAttribute("aria-label"),this.ownsPanelAriaLabel=!1,this.ownedPanelAriaLabelValue=null);return}panel.hasAttribute("aria-label")&&!this.ownsPanelAriaLabel||(this.ownsPanelAriaLabel=!0,this.ownedPanelAriaLabelValue=this.slottedLabel,panel.getAttribute("aria-label")!==this.slottedLabel&&panel.setAttribute("aria-label",this.slottedLabel))}}getTextLabel(){return this.readSlottedLabel()}render(){return html`
15
+ `}class LyraMenuItem extends LyraElement{constructor(){super(...arguments),this.value="",this.size="m",this.disabled=!1,this.variant="default",this.type="normal",this.checked=!1,this.loading=!1,this.hasIconSlot=!1,this.hasDetailsSlot=!1,this.hasSuffixSlot=!1,this.submenuAssigned=!1,this.submenuExpanded=!1,this.slottedLabel="",this.submenuPanel=null,this.submenuPanelAttached=!1,this.submenuPanelGeneration=0,this.labelObservationGeneration=0,this.announcedNativeState="",this.owningMenu=null,this.ownsAriaLabel=!1,this.ownedAriaLabelValue=null,this.ownsPanelAriaLabel=!1,this.ownedPanelAriaLabelValue=null,this.onNativeStateMutation=()=>{const signature=this.nativeStateSignature();signature!==this.announcedNativeState&&(this.announcedNativeState=signature,this.emitStateChange())},this.onIconSlotChange=()=>{this.hasIconSlot=[...this.renderRoot.querySelectorAll('slot[name="icon"], slot[name="prefix"]')].some(slot=>slot.assignedElements({flatten:!0}).length>0)},this.onDetailsSlotChange=e=>{this.hasDetailsSlot=e.target.assignedNodes({flatten:!0}).some(node=>(node.textContent??"").trim()!=="")},this.onSuffixSlotChange=e=>{this.hasSuffixSlot=e.target.assignedElements({flatten:!0}).length>0},this.onLabelSlotChange=event=>{this.observeLabelContent(),this.syncSlottedLabel(event.target)},this.onForwardedLabelSlotChange=event=>{const slot=event.target;this.labelForwardingSlots().includes(slot)&&(this.observeLabelContent(),this.syncSlottedLabel())},this.onSubmenuSlotChange=e=>{this.syncSubmenuSlot(e.target)},this.onPanelStateChange=open=>{this.submenuExpanded=open}}static{this.knownUnobservedAttributes=["submenu-open"]}static{this.styles=[LyraElement.styles,sizes,styles]}get hasSubmenu(){return this.submenuAssigned}get submenuOpen(){return this.submenuExpanded}[menuItemOwner](owner,expectedOwner){owner===null&&expectedOwner&&this.owningMenu!==expectedOwner||(this.owningMenu=owner)}set submenuOpen(next){!!next!==this.submenuExpanded&&(next?this.openSubmenu("none"):this.closeSubmenu())}get interactionDisabled(){return this.disabled||this.loading}connectedCallback(){super.connectedCallback();const initialLabel=this.readSlottedLabel(null,!1);initialLabel!==this.slottedLabel&&(this.slottedLabel=initialLabel),this.applyComputedName(),this.tabIndex!==0&&(this.tabIndex=-1),this.announcedNativeState=this.nativeStateSignature();const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;MutationObserverCtor&&(this.nativeStateObserver=new MutationObserverCtor(this.onNativeStateMutation),this.nativeStateObserver.observe(this,{attributes:!0,attributeFilter:["hidden","inert","aria-hidden"]}),this.labelObserver=new MutationObserverCtor(()=>{this.observeLabelContent(),this.syncSlottedLabel()}),this.observeLabelContent()),this.addEventListener("slotchange",this.onForwardedLabelSlotChange);const labelGeneration=++this.labelObservationGeneration;this.updateComplete.then(()=>{if(!this.isConnected||labelGeneration!==this.labelObservationGeneration)return;this.observeLabelContent(),this.syncSlottedLabel();const submenuSlot=this.renderRoot.querySelector('slot[name="submenu"]');submenuSlot&&this.syncSubmenuSlot(submenuSlot)})}disconnectedCallback(){super.disconnectedCallback(),this.submenuPanelGeneration+=1,this.submenuExpanded=!1,this.nativeStateObserver?.disconnect(),this.nativeStateObserver=void 0,this.labelObservationGeneration+=1,this.removeEventListener("slotchange",this.onForwardedLabelSlotChange),this.labelObserver?.disconnect(),this.labelObserver=void 0,this.submenuPanel&&this.submenuPanelAttached&&(this.submenuPanel[submenuPanelController].detach(this),this.submenuPanelAttached=!1)}nativeStateSignature(){return`${this.hidden}|${this.inert}|${this.getAttribute("aria-hidden")}`}emitStateChange(){this.emit("lr-menu-item-state-change",{disabled:this.interactionDisabled,hidden:!!this.hidden,inert:this.inert})}willUpdate(changed){super.willUpdate(changed);const isCheckbox=this.type==="checkbox"&&!this.submenuAssigned;this.setAttribute("role",isCheckbox?"menuitemcheckbox":"menuitem"),isCheckbox?this.setAttribute("aria-checked",this.checked?"true":"false"):this.removeAttribute("aria-checked"),this.submenuAssigned?(this.setAttribute("aria-haspopup","menu"),this.setAttribute("aria-expanded",this.submenuExpanded?"true":"false")):(this.removeAttribute("aria-haspopup"),this.removeAttribute("aria-expanded")),this.applyComputedName(),this.toggleAttribute("submenu-open",this.submenuExpanded),this.setAttribute("aria-disabled",String(this.interactionDisabled)),this.interactionDisabled&&(changed.has("disabled")||changed.has("loading"))&&(this.tabIndex=-1,activeElementIn(this.ownerDocument)===this&&this.blur()),(changed.has("disabled")||changed.has("loading"))&&this.emitStateChange()}click(){this.interactionDisabled||this.renderRoot.querySelector('[part~="base"]')?.click()}select(){if(!this.interactionDisabled){if(this.submenuPanel){this.openSubmenu("none");return}if(this.type==="checkbox"){const checked=!this.checked;this.emit("lr-menu-item-change",{value:this.value,checked},{cancelable:!0}).defaultPrevented||(this.checked=checked)}this.owningMenu?.activate(this)}}async openSubmenu(focus="first"){const panel=this.submenuPanel,generation=this.submenuPanelGeneration;if(!panel||this.interactionDisabled||!this.isCurrentSubmenuPanel(panel,generation))return;const controller=panel[submenuPanelController],shown=controller.show(focus);this.isCurrentSubmenuPanel(panel,generation)&&(this.submenuExpanded=controller.open,await shown,this.isCurrentSubmenuPanel(panel,generation)&&(panel.updateComplete&&await panel.updateComplete,this.isCurrentSubmenuPanel(panel,generation)&&(this.submenuExpanded=controller.open,await this.updateComplete)))}async closeSubmenu(){const panel=this.submenuPanel,generation=this.submenuPanelGeneration;if(!panel||!this.isCurrentSubmenuPanel(panel,generation))return;const controller=panel[submenuPanelController],hidden=controller.hide();this.isCurrentSubmenuPanel(panel,generation)&&(this.submenuExpanded=controller.open,await hidden,this.isCurrentSubmenuPanel(panel,generation)&&(panel.updateComplete&&await panel.updateComplete,this.isCurrentSubmenuPanel(panel,generation)&&(this.submenuExpanded=controller.open,await this.updateComplete)))}defaultLabelSlot(){return this.renderRoot?.querySelector("slot:not([name])")??null}isDefaultLabelBranch(node){let top=node;for(;top.parentNode&&top.parentNode!==this;)top=top.parentNode;return top.parentNode!==this?!1:top.nodeType!==1||(top.getAttribute("slot")??"")===""}labelForwardingSlots(){return Array.from(this.querySelectorAll("slot")).filter(slot=>this.isDefaultLabelBranch(slot))}composedParentForNode(node){const assignedSlot=node.assignedSlot;if(assignedSlot)return assignedSlot;if(node.parentElement)return node.parentElement;const root=node.getRootNode();return"host"in root&&root.host.nodeType===1?root.host:null}isLabelSubtreeExcluded(element){return!(element.getRootNode()===this.renderRoot&&element.matches('[part~="label"][aria-hidden="true"][inert]:not([hidden])'))&&isAccessibilitySubtreeExcluded(element)}readSlottedLabel(slot=this.defaultLabelSlot(),requireRendered=!0){const nodes=slot?slot.assignedNodes({flatten:!0}):Array.from(this.childNodes).filter(node=>this.isDefaultLabelBranch(node));return composedAccessibilityText(nodes,{ancestorBoundary:this,isSubtreeExcluded:element=>this.isLabelSubtreeExcluded(element),requireRendered,ignoreInheritedVisibility:!0}).replace(/\s+/g," ").trim()}observeLabelAncestors(node,options){const observer=this.labelObserver;if(!observer)return;let current=this.composedParentForNode(node);for(;current;)current!==this&&!this.contains(current)&&observer.observe(current,options),current=composedParentElement(current)}observeLabelContent(){const observer=this.labelObserver;if(!observer)return;observer.disconnect();const options={attributes:!0,attributeFilter:["aria-hidden","aria-label","aria-labelledby","alt","class","data-hidden","hidden","inert","id","label","open","slot","style"],characterData:!0,childList:!0,subtree:!0};observer.observe(this,options);const slot=this.defaultLabelSlot();for(const assigned of slot?.assignedNodes({flatten:!0})??[])this.contains(assigned)||observer.observe(assigned,options),this.observeLabelAncestors(assigned,{attributes:!0,attributeFilter:options.attributeFilter})}syncSlottedLabel(slot=this.defaultLabelSlot()){const next=this.readSlottedLabel(slot);next!==this.slottedLabel&&(this.slottedLabel=next),this.applyComputedName(),this.applyPanelName()}syncSubmenuSlot(submenuSlot){if(!submenuSlot.isConnected||submenuSlot.getRootNode()!==this.renderRoot)return;const assigned=submenuSlot.assignedElements({flatten:!0}),authoredPanel=assigned.find(element=>element.localName===tag("menu")),hasDirectItems=assigned.some(element=>element.localName===tag("menu-item")||element.localName===tag("dropdown-item")),kind=authoredPanel?"panel":hasDirectItems?"items":void 0;if(this.submenuKind=kind,this.submenuAssigned=kind!==void 0,kind==="items"){const generated=this.renderRoot.querySelector("[data-generated-submenu]");generated&&this.connectSubmenuPanel(generated);return}this.connectSubmenuPanel(authoredPanel??null)}connectSubmenuPanel(next){const samePanel=next===this.submenuPanel;if(samePanel&&(next===null||this.submenuPanelAttached))return;const previous=this.submenuPanel;if(++this.submenuPanelGeneration,previous&&this.submenuPanelAttached&&previous[submenuPanelController].detach(this),this.submenuPanelAttached=!1,samePanel||(this.submenuPanel=next,this.ownsPanelAriaLabel=!1,this.ownedPanelAriaLabelValue=null),!this.submenuPanel){this.submenuExpanded=!1;return}const controller=this.submenuPanel[submenuPanelController];controller.attach(this,this.onPanelStateChange),this.submenuPanelAttached=!0,this.submenuExpanded=controller.open,this.applyPanelName()}isCurrentSubmenuPanel(panel,generation){return this.isConnected&&this.submenuPanel===panel&&this.submenuPanelGeneration===generation}updated(changed){if(super.updated(changed),changed.has("submenuKind")&&this.submenuKind==="items"){const generated=this.renderRoot.querySelector("[data-generated-submenu]");this.connectSubmenuPanel(generated)}}applyComputedName(){if(this.ownsAriaLabel&&this.getAttribute("aria-label")!==this.ownedAriaLabelValue&&(this.ownsAriaLabel=!1,this.ownedAriaLabelValue=null),this.hasAttribute("aria-labelledby")){this.ownsAriaLabel&&this.removeAttribute("aria-label"),this.ownsAriaLabel=!1,this.ownedAriaLabelValue=null;return}if(!(this.hasAttribute("aria-label")&&!this.ownsAriaLabel)){if(this.ownsAriaLabel=!0,this.slottedLabel===""){this.ownedAriaLabelValue=null,this.hasAttribute("aria-label")&&this.removeAttribute("aria-label");return}this.ownedAriaLabelValue=this.slottedLabel,this.getAttribute("aria-label")!==this.slottedLabel&&this.setAttribute("aria-label",this.slottedLabel)}}applyPanelName(){const panel=this.submenuPanel;if(panel){if(this.ownsPanelAriaLabel&&panel.getAttribute("aria-label")!==this.ownedPanelAriaLabelValue&&(this.ownsPanelAriaLabel=!1,this.ownedPanelAriaLabelValue=null),panel.hasAttribute("label")){this.ownsPanelAriaLabel&&(panel.removeAttribute("aria-label"),this.ownsPanelAriaLabel=!1,this.ownedPanelAriaLabelValue=null);return}if(!(panel.hasAttribute("aria-label")&&!this.ownsPanelAriaLabel)){if(this.ownsPanelAriaLabel=!0,this.slottedLabel===""){this.ownedPanelAriaLabelValue=null,panel.hasAttribute("aria-label")&&panel.removeAttribute("aria-label");return}this.ownedPanelAriaLabelValue=this.slottedLabel,panel.getAttribute("aria-label")!==this.slottedLabel&&panel.setAttribute("aria-label",this.slottedLabel)}}}getTextLabel(){return this.readSlottedLabel()}render(){return html`
16
16
  <span part="base" @click=${()=>this.select()}>
17
17
  <span part="icon" aria-hidden="true" inert ?hidden=${!this.hasIconSlot}>
18
18
  <slot name="icon" @slotchange=${this.onIconSlotChange}></slot>
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isRtl}from"../../../internal/rtl.js";import{nextId}from"../../../internal/a11y.js";import{composedAccessibilityText}from"../../../internal/accessibility-visibility.js";import{chevronIcon}from"../../../internal/icons.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{tag}from"../../../internal/prefix.js";import{observeScrollOverflow}from"../../../internal/scroll-overflow.js";import{styles}from"./tab-group.styles.js";import{activeElementIn}from"../../../internal/active-element.js";import{LYRA_DEFAULT_scrollNext,LYRA_DEFAULT_scrollPrevious}from"../../../internal/default-strings.generated.js";function isHtmlElement(child){return child.nodeType===1&&child.namespaceURI==="http://www.w3.org/1999/xhtml"}function isInertChild(child){return isHtmlElement(child)&&child.inert}function isTabLabelSubtreeExcludedWithoutInert(element){if(element.hasAttribute("hidden")||element.getAttribute("aria-hidden")?.trim().toLowerCase()==="true")return!0;const rendered=element.ownerDocument.defaultView?.getComputedStyle(element);return rendered?.display==="none"||rendered?.contentVisibility==="hidden"}const SYNTHETIC_PANEL_PREFIX="lr-tab-",SCROLL_STEP_RATIO=.8;class LyraTabGroup extends LyraElement{constructor(){super(...arguments),this.active="",this.accessibleLabel=null,this.placement="top",this.activation="auto",this.withoutScrollControls=!1,this.noScrollControls=!1,this.fixedScrollControls=!1,this.tabs=[],this.focusedTab="",this.baseId=nextId("tab-group"),this.nextOpaqueId=0,this.idsBySlot=new Map,this.mutationObserverGeneration=0,this.projectedSourceSnapshots=new Map,this.projectedSlotSnapshots=new Map,this.projectedSourceObserverGeneration=0,this.rehomeTabFocus=!1,this.scrollStartAvailable=!1,this.scrollEndAvailable=!1,this.scrollOverflow=observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part~="tablist"]'),()=>this.measureTabScrollEdges()),this.syncTabs=()=>{const children=Array.from(this.children);this.adoptProjectedSourceInertStates(),this.adoptProjectedSlotStates();const projectedSlots=new Set,next=this.readElementModel(children,projectedSlots);this.syncProjectedSlots(projectedSlots),this.syncProjectedSources(next);const liveSlots=new Set(next.map(tab=>tab.slotName));for(const slotName of this.idsBySlot.keys())liveSlots.has(slotName)||this.idsBySlot.delete(slotName);this.tabs=next},this.onTabListKeyDown=e=>{const navigable=this.tabs.filter(t=>this.isNavigable(t));if(navigable.length===0)return;const origin=this.keyboardOriginTab(e,navigable),currentIndex=origin?navigable.indexOf(origin):-1;if(e.key==="Delete"){if(!origin?.element.closable)return;e.preventDefault(),origin.element.requestCloseFromOwner();return}const rtl=isRtl(this),forwardKey=this.isVertical?"ArrowDown":rtl?"ArrowLeft":"ArrowRight",backwardKey=this.isVertical?"ArrowUp":rtl?"ArrowRight":"ArrowLeft";if(this.activation==="manual"&&(e.key==="Enter"||e.key===" "||e.key==="Spacebar")){if(!origin)return;e.preventDefault(),this.selectTab(origin);return}let targetIndex;switch(e.key){case forwardKey:targetIndex=currentIndex<0?0:(currentIndex+1)%navigable.length;break;case backwardKey:targetIndex=currentIndex<0?navigable.length-1:(currentIndex-1+navigable.length)%navigable.length;break;case"Home":targetIndex=0;break;case"End":targetIndex=navigable.length-1;break;default:return}e.preventDefault();const target=navigable[targetIndex];if(this.activation==="manual"){this.focusOnly(target);return}this.selectTab(target),this.focusTab(target.slotName)},this.onTabListScroll=()=>{this.measureTabScrollEdges()},this.onScrollControlMouseDown=event=>{event.preventDefault()},this.onScrollControlPointerDown=event=>{const control=event.currentTarget;control instanceof HTMLElement&&(control.setAttribute("data-pressed",""),control.setPointerCapture(event.pointerId))},this.onScrollControlPointerEnd=event=>{const control=event.currentTarget;control instanceof HTMLElement&&(control.removeAttribute("data-pressed"),control.hasPointerCapture(event.pointerId)&&control.releasePointerCapture(event.pointerId))}}static{this.defaultStrings={...super.defaultStrings,scrollNext:LYRA_DEFAULT_scrollNext,scrollPrevious:LYRA_DEFAULT_scrollPrevious}}static{this.styles=[LyraElement.styles,styles]}connectedCallback(){super.connectedCallback(),this.hasUpdated?this.syncTabs():this.seedFirstRenderState(this.syncTabs),this.resetMutationObserver();const ownerDocument=this.ownerDocument,MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.mutationObserverGeneration,observer=new MutationObserverCtor(records=>{if(this.mutationObserver!==observer||this.mutationObserverDocument!==ownerDocument||this.mutationObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument)return;const isDirectChild=node=>node.parentNode===this,isElementTabContent=node=>{let current=node.nodeType===1?node:node.parentElement;for(;current&&current!==this;){if(current.localName===tag("tab")&&current.parentNode===this)return!0;current=current.parentElement}return!1};records.some(record=>record.type==="childList"?record.target===this||isElementTabContent(record.target):record.type==="characterData"?isElementTabContent(record.target):record.attributeName==="inert"&&this.projectedSourceSnapshots.has(record.target)?!1:isDirectChild(record.target)||isElementTabContent(record.target))&&this.syncTabs()});this.mutationObserver=observer,this.mutationObserverDocument=ownerDocument,observer.observe(this,{childList:!0,subtree:!0,attributes:!0,characterData:!0,attributeFilter:["alt","aria-hidden","aria-label","aria-labelledby","class","closable","disabled","hidden","inert","id","label","name","open","panel","slot","style"]})}disconnectedCallback(){this.resetMutationObserver(),this.resetProjectedSourceObserver(),this.restoreProjectedSources(),this.restoreProjectedSlots(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resetMutationObserver(),this.resetProjectedSourceObserver()}resetMutationObserver(){this.mutationObserverGeneration+=1,this.mutationObserver?.disconnect(),this.mutationObserver=void 0,this.mutationObserverDocument=void 0}readElementModel(children,projectedSlots){const seen=new Set,next=[],panels=children.filter(child=>child.localName===tag("tab-panel")),authoredNames=new Set(children.flatMap(child=>{if(child.localName===tag("tab")){const name=child.getAttribute("panel");return name?[name]:[]}if(child.localName===tag("tab-panel")){const name=child.getAttribute("name");return name?[name]:[]}return[]}));let index=0;for(const child of children){if(child.localName!==tag("tab"))continue;const authoredPanel=child.getAttribute("panel")||void 0;let slotName=authoredPanel??`${SYNTHETIC_PANEL_PREFIX}${index}`;if(!authoredPanel){let collision=0;for(;authoredNames.has(slotName)||seen.has(slotName);)collision+=1,slotName=`${SYNTHETIC_PANEL_PREFIX}${index}-${collision}`}if(index+=1,!authoredPanel&&!this.readElementLabel(child,{allowUnprojected:!0})||seen.has(slotName))continue;seen.add(slotName);const tabSlot=this.tabSlotName(slotName);this.projectSlot(child,tabSlot,projectedSlots);const visibleLabel=this.readElementLabel(child);if(!authoredPanel&&!visibleLabel)continue;const label=visibleLabel||slotName,panel=panels.find(candidate=>candidate.getAttribute("name")===slotName);panel&&this.projectSlot(panel,slotName,projectedSlots),next.push({slotName,label,disabled:child.hasAttribute("disabled"),inert:isInertChild(child),element:child}),!this.active&&child.hasAttribute("active")&&(this.active=slotName)}return next}readElementLabel(tab,options={}){const labelNodes=Array.from(tab.childNodes).filter(node=>node.nodeType!==Node.ELEMENT_NODE||node.getAttribute("slot")===null||node.getAttribute("slot")==="");return composedAccessibilityText(labelNodes,{ancestorBoundary:tab,isSubtreeExcluded:element=>this.isTabLabelSubtreeExcluded(element),requireRendered:!options.allowUnprojected,skipRootAncestorValidation:options.allowUnprojected}).replace(/\s+/g," ").trim()}libraryOwnsSourceInert(element){return this.projectedSourceSnapshots.get(element)?.libraryOwnsInert===!0}isTabLabelSubtreeExcluded(element){return isTabLabelSubtreeExcludedWithoutInert(element)||element.hasAttribute("inert")&&!this.libraryOwnsSourceInert(element)}snapshotProjectedSource(source){const inert=source.getAttribute("inert");return{inert,appliedInert:inert,libraryOwnsInert:!1}}adoptProjectedSourceInert(source,snapshot){const current=source.getAttribute("inert");current!==snapshot.appliedInert&&(snapshot.inert=current,snapshot.libraryOwnsInert=!1)}makeProjectedSourceInert(source,snapshot){source.hasAttribute("inert")||(source.setAttribute("inert",""),snapshot.libraryOwnsInert=!0),snapshot.appliedInert=source.getAttribute("inert")}restoreProjectedSource(source,snapshot){this.adoptProjectedSourceInert(source,snapshot),snapshot.inert===null?source.removeAttribute("inert"):source.setAttribute("inert",snapshot.inert)}restoreProjectedSources(){for(const[source,snapshot]of this.projectedSourceSnapshots)this.restoreProjectedSource(source,snapshot);this.projectedSourceSnapshots.clear()}resetProjectedSourceObserver(){this.projectedSourceObserverGeneration+=1,this.projectedSourceObserver?.disconnect(),this.projectedSourceObserver=void 0,this.projectedSourceObserverDocument=void 0}observeProjectedSources(){this.resetProjectedSourceObserver();const ownerDocument=this.ownerDocument,MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor||!this.isConnected||this.projectedSourceSnapshots.size===0)return;const generation=this.projectedSourceObserverGeneration,observer=new MutationObserverCtor(records=>{this.projectedSourceObserver!==observer||this.projectedSourceObserverDocument!==ownerDocument||this.projectedSourceObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||records.some(record=>this.projectedSourceSnapshots.has(record.target))&&this.syncTabs()});this.projectedSourceObserver=observer,this.projectedSourceObserverDocument=ownerDocument;for(const source of this.projectedSourceSnapshots.keys())observer.observe(source,{attributes:!0,attributeFilter:["inert"]})}projectedSources(tabs){const sources=new Set;for(const tab of tabs)for(const child of Array.from(tab.element.children))(child.getAttribute("slot")??"")===""&&sources.add(child);return sources}syncProjectedSources(tabs){const sources=this.projectedSources(tabs);for(const[source,snapshot]of this.projectedSourceSnapshots)this.adoptProjectedSourceInert(source,snapshot),sources.has(source)||(this.restoreProjectedSource(source,snapshot),this.projectedSourceSnapshots.delete(source));for(const source of sources){const snapshot=this.projectedSourceSnapshots.get(source)??this.snapshotProjectedSource(source);this.projectedSourceSnapshots.set(source,snapshot),this.adoptProjectedSourceInert(source,snapshot),this.makeProjectedSourceInert(source,snapshot)}this.observeProjectedSources()}adoptProjectedSourceInertStates(){for(const[source,snapshot]of this.projectedSourceSnapshots)this.adoptProjectedSourceInert(source,snapshot)}snapshotProjectedSlot(source){const slot=source.getAttribute("slot");return{slot,appliedSlot:slot,libraryOwnsSlot:!1}}adoptProjectedSlot(source,snapshot){const current=source.getAttribute("slot");current!==snapshot.appliedSlot&&(snapshot.slot=current,snapshot.libraryOwnsSlot=!1)}projectSlot(source,slot,projectedSlots){const snapshot=this.projectedSlotSnapshots.get(source)??this.snapshotProjectedSlot(source);this.projectedSlotSnapshots.set(source,snapshot),this.adoptProjectedSlot(source,snapshot),source.getAttribute("slot")!==slot&&(source.setAttribute("slot",slot),snapshot.libraryOwnsSlot=!0),snapshot.appliedSlot=source.getAttribute("slot"),projectedSlots.add(source)}restoreProjectedSlot(source,snapshot){this.adoptProjectedSlot(source,snapshot),snapshot.slot===null?source.removeAttribute("slot"):source.setAttribute("slot",snapshot.slot)}syncProjectedSlots(projectedSlots){for(const[source,snapshot]of this.projectedSlotSnapshots)projectedSlots.has(source)||(this.restoreProjectedSlot(source,snapshot),this.projectedSlotSnapshots.delete(source))}restoreProjectedSlots(){for(const[source,snapshot]of this.projectedSlotSnapshots)this.restoreProjectedSlot(source,snapshot);this.projectedSlotSnapshots.clear()}adoptProjectedSlotStates(){for(const[source,snapshot]of this.projectedSlotSnapshots)this.adoptProjectedSlot(source,snapshot)}isNavigable(tab){return!tab.disabled&&!tab.inert}willUpdate(changed){if(super.willUpdate(changed),!changed.has("tabs")&&!changed.has("active"))return;const focused=activeElementIn(this.renderRoot),focusedSlot=focused?.getAttribute("part")==="tab"?focused.getAttribute("data-slot"):null;focusedSlot!==null&&!this.tabs.some(tab=>tab.slotName===focusedSlot&&this.isNavigable(tab))&&(this.rehomeTabFocus=!0,this.focusedTab=this.active);const current=this.tabs.find(t=>t.slotName===this.active);current&&this.isNavigable(current)||(this.rehomeTabFocus=this.rehomeTabFocus||focusedSlot!==null,this.active=this.tabs.find(t=>this.isNavigable(t))?.slotName??"",this.focusedTab=this.active)}updated(changed){super.updated(changed),(changed.has("active")||changed.has("tabs"))&&this.syncElementActiveState(),this.scrollOverflow.observeExtra(this.renderRoot.querySelectorAll('[part="tab"]')),this.measureTabScrollEdges(),this.rehomeTabFocus&&(this.rehomeTabFocus=!1,this.renderRoot.querySelector('[part="tab"][tabindex="0"]')?.focus())}selectTab(tab){if(!this.isNavigable(tab)||tab.slotName===this.active)return;const previous=this.active;this.active=tab.slotName,this.focusedTab=tab.slotName,previous&&this.emit("lr-tab-hide",{name:previous}),this.emit("lr-tab-show",{name:tab.slotName})}show(panel){const tab=this.tabs.find(candidate=>candidate.slotName===panel);tab&&this.selectTab(tab)}syncElementActiveState(){for(const child of Array.from(this.children))if(child.localName===tag("tab")){const definition=this.tabs.find(tab=>tab.element===child);child.toggleAttribute("active",definition?.slotName===this.active)}else child.localName===tag("tab-panel")&&child.toggleAttribute("active",child.getAttribute("name")===this.active)}focusOnly(tab){this.focusedTab=tab.slotName,this.focusTab(tab.slotName)}get rovingTab(){if(this.activation!=="manual")return this.active;const candidate=this.tabs.find(t=>t.slotName===this.focusedTab&&this.isNavigable(t));return candidate?candidate.slotName:this.active}keyboardOriginTab(event,navigable){const eventButton=event.composedPath().find(candidate=>candidate.nodeType===1&&candidate.getAttribute?.("part")==="tab"&&candidate.getRootNode()===this.renderRoot),focused=activeElementIn(this.renderRoot),owned=(eventButton??(focused?.getAttribute("part")==="tab"?focused:void 0))?.dataset.slot;return navigable.find(tab=>tab.slotName===owned)??navigable.find(tab=>tab.slotName===this.rovingTab)}focusTab(slotName){const buttons=this.renderRoot.querySelectorAll('[part="tab"]');for(const button of Array.from(buttons))if(button.dataset.slot===slotName){button.focus();return}}get isVertical(){return this.placement==="start"||this.placement==="end"}tabId(slotName){return this.idsFor(slotName).tab}panelId(slotName){return this.idsFor(slotName).panel}idsFor(slotName){const existing=this.idsBySlot.get(slotName);if(existing)return existing;const token=`${this.baseId}-${this.nextOpaqueId++}`,ids={tab:`${token}-tab`,panel:`${token}-panel`};return this.idsBySlot.set(slotName,ids),ids}tabSlotName(slotName){return`${slotName}-tab`}get scrollControlsSuppressed(){return this.withoutScrollControls||this.noScrollControls}measureTabScrollEdges(){const tablist=this.renderRoot.querySelector('[part~="tablist"]');if(!tablist||this.isVertical){this.setTabScrollEdges(!1,!1,tablist);return}const maximum=Math.max(0,tablist.scrollWidth-tablist.clientWidth),position=Math.max(0,Math.min(maximum,this.effectiveDirection==="rtl"?-tablist.scrollLeft:tablist.scrollLeft));this.setTabScrollEdges(position>1,position<maximum-1,tablist)}setTabScrollEdges(start,end,tablist){tablist?.toggleAttribute("data-scroll-start",start),tablist?.toggleAttribute("data-scroll-end",end),!(start===this.scrollStartAvailable&&end===this.scrollEndAvailable)&&(this.scrollStartAvailable=start,this.scrollEndAvailable=end)}scrollTabs(edge){const tablist=this.renderRoot.querySelector('[part~="tablist"]');if(!tablist||!isHtmlElement(tablist)||typeof tablist.scrollBy!="function")return;const step=Math.max(1,tablist.clientWidth*SCROLL_STEP_RATIO),towardEnd=edge==="end"?1:-1,physical=this.effectiveDirection==="rtl"?-towardEnd:towardEnd;tablist.scrollBy({left:step*physical,behavior:prefersReducedMotion(this.ownerDocument.defaultView)?"instant":"smooth"})}renderScrollControl(edge){if(this.isVertical||this.scrollControlsSuppressed)return nothing;const available=edge==="start"?this.scrollStartAvailable:this.scrollEndAvailable;return html`<button
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isRtl}from"../../../internal/rtl.js";import{nextId}from"../../../internal/a11y.js";import{composedAccessibilityText}from"../../../internal/accessibility-visibility.js";import{chevronIcon}from"../../../internal/icons.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{tag}from"../../../internal/prefix.js";import{observeScrollOverflow}from"../../../internal/scroll-overflow.js";import{styles}from"./tab-group.styles.js";import{activeElementIn}from"../../../internal/active-element.js";import{LYRA_DEFAULT_scrollNext,LYRA_DEFAULT_scrollPrevious}from"../../../internal/default-strings.generated.js";function isHtmlElement(child){return child.nodeType===1&&child.namespaceURI==="http://www.w3.org/1999/xhtml"}function isInertChild(child){return isHtmlElement(child)&&child.inert}function isTabLabelSubtreeExcludedWithoutInert(element){if(element.hasAttribute("hidden")||element.getAttribute("aria-hidden")?.trim().toLowerCase()==="true")return!0;const rendered=element.ownerDocument.defaultView?.getComputedStyle(element);return rendered?.display==="none"||rendered?.contentVisibility==="hidden"}const SYNTHETIC_PANEL_PREFIX="lr-tab-",SCROLL_STEP_RATIO=.8;class LyraTabGroup extends LyraElement{constructor(){super(...arguments),this.active="",this.accessibleLabel=null,this.placement="top",this.activation="auto",this.withoutScrollControls=!1,this.noScrollControls=!1,this.fixedScrollControls=!1,this.tabs=[],this.focusedTab="",this.baseId=nextId("tab-group"),this.nextOpaqueId=0,this.idsBySlot=new Map,this.mutationObserverGeneration=0,this.projectedSourceSnapshots=new Map,this.projectedSlotSnapshots=new Map,this.projectedSourceObserverGeneration=0,this.rehomeTabFocus=!1,this.scrollStartAvailable=!1,this.scrollEndAvailable=!1,this.scrollOverflow=observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part~="tablist"]'),()=>this.measureTabScrollEdges()),this.syncTabs=()=>{const children=Array.from(this.children);this.adoptProjectedSourceInertStates(),this.adoptProjectedSlotStates();const projectedSlots=new Set,next=this.readElementModel(children,projectedSlots);this.syncProjectedSlots(projectedSlots),this.syncProjectedSources(next);const liveSlots=new Set(next.map(tab=>tab.slotName));for(const slotName of this.idsBySlot.keys())liveSlots.has(slotName)||this.idsBySlot.delete(slotName);this.tabs=next},this.onTabListKeyDown=e=>{const navigable=this.tabs.filter(t=>this.isNavigable(t));if(navigable.length===0)return;const origin=this.keyboardOriginTab(e,navigable),currentIndex=origin?navigable.indexOf(origin):-1;if(e.key==="Delete"){if(!origin?.element.closable)return;e.preventDefault(),origin.element.requestCloseFromOwner();return}const rtl=isRtl(this),forwardKey=this.isVertical?"ArrowDown":rtl?"ArrowLeft":"ArrowRight",backwardKey=this.isVertical?"ArrowUp":rtl?"ArrowRight":"ArrowLeft";if(this.activation==="manual"&&(e.key==="Enter"||e.key===" "||e.key==="Spacebar")){if(!origin)return;e.preventDefault(),this.selectTab(origin);return}let targetIndex;switch(e.key){case forwardKey:targetIndex=currentIndex<0?0:(currentIndex+1)%navigable.length;break;case backwardKey:targetIndex=currentIndex<0?navigable.length-1:(currentIndex-1+navigable.length)%navigable.length;break;case"Home":targetIndex=0;break;case"End":targetIndex=navigable.length-1;break;default:return}e.preventDefault();const target=navigable[targetIndex];if(this.activation==="manual"){this.focusOnly(target);return}this.selectTab(target),this.focusTab(target.slotName)},this.onTabListScroll=()=>{this.measureTabScrollEdges()},this.onScrollControlMouseDown=event=>{event.preventDefault()},this.onScrollControlPointerDown=event=>{const control=event.currentTarget;control instanceof HTMLElement&&(control.setAttribute("data-pressed",""),control.setPointerCapture(event.pointerId))},this.onScrollControlPointerEnd=event=>{const control=event.currentTarget;control instanceof HTMLElement&&(control.removeAttribute("data-pressed"),control.hasPointerCapture(event.pointerId)&&control.releasePointerCapture(event.pointerId))}}static{this.defaultStrings={...super.defaultStrings,scrollNext:LYRA_DEFAULT_scrollNext,scrollPrevious:LYRA_DEFAULT_scrollPrevious}}static{this.styles=[LyraElement.styles,styles]}connectedCallback(){super.connectedCallback(),this.hasUpdated?this.syncTabs():this.seedFirstRenderState(this.syncTabs),this.resetMutationObserver();const ownerDocument=this.ownerDocument,MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.mutationObserverGeneration,observer=new MutationObserverCtor(records=>{if(this.mutationObserver!==observer||this.mutationObserverDocument!==ownerDocument||this.mutationObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument)return;const isDirectChild=node=>node.parentNode===this,isElementTabContent=node=>{let current=node.nodeType===1?node:node.parentElement;for(;current&&current!==this;){if(current.localName===tag("tab")&&current.parentNode===this)return!0;current=current.parentElement}return!1};records.some(record=>record.type==="childList"?record.target===this||isElementTabContent(record.target):record.type==="characterData"?isElementTabContent(record.target):record.attributeName==="inert"&&this.projectedSourceSnapshots.has(record.target)?!1:isDirectChild(record.target)||isElementTabContent(record.target))&&this.syncTabs()});this.mutationObserver=observer,this.mutationObserverDocument=ownerDocument,observer.observe(this,{childList:!0,subtree:!0,attributes:!0,characterData:!0,attributeFilter:["alt","aria-hidden","aria-label","aria-labelledby","class","closable","disabled","hidden","inert","id","label","name","open","panel","slot","style"]})}disconnectedCallback(){this.resetMutationObserver(),this.resetProjectedSourceObserver(),this.restoreProjectedSources(),this.restoreProjectedSlots(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resetMutationObserver(),this.resetProjectedSourceObserver()}resetMutationObserver(){this.mutationObserverGeneration+=1,this.mutationObserver?.disconnect(),this.mutationObserver=void 0,this.mutationObserverDocument=void 0}readElementModel(children,projectedSlots){const seen=new Set,next=[],panels=children.filter(child=>child.localName===tag("tab-panel")),authoredNames=new Set(children.flatMap(child=>{if(child.localName===tag("tab")){const name=child.getAttribute("panel");return name?[name]:[]}if(child.localName===tag("tab-panel")){const name=child.getAttribute("name");return name?[name]:[]}return[]}));let index=0;for(const child of children){if(child.localName!==tag("tab"))continue;const authoredPanel=child.getAttribute("panel")||void 0;let slotName=authoredPanel??`${SYNTHETIC_PANEL_PREFIX}${index}`;if(!authoredPanel){let collision=0;for(;authoredNames.has(slotName)||seen.has(slotName);)collision+=1,slotName=`${SYNTHETIC_PANEL_PREFIX}${index}-${collision}`}if(index+=1,!authoredPanel&&!this.readElementLabel(child,{allowUnprojected:!0})||seen.has(slotName))continue;seen.add(slotName);const tabSlot=this.tabSlotName(slotName);this.projectSlot(child,tabSlot,projectedSlots);const visibleLabel=this.readElementLabel(child);if(!authoredPanel&&!visibleLabel)continue;const label=visibleLabel||slotName,panel=panels.find(candidate=>candidate.getAttribute("name")===slotName);panel&&this.projectSlot(panel,slotName,projectedSlots),next.push({slotName,label,disabled:child.hasAttribute("disabled"),inert:isInertChild(child),element:child}),!this.active&&child.hasAttribute("active")&&(this.active=slotName)}return next}readElementLabel(tab,options={}){const labelNodes=Array.from(tab.childNodes).filter(node=>node.nodeType!==Node.ELEMENT_NODE||node.getAttribute("slot")===null||node.getAttribute("slot")==="");return composedAccessibilityText(labelNodes,{ancestorBoundary:tab,isSubtreeExcluded:element=>this.isTabLabelSubtreeExcluded(element),requireRendered:!options.allowUnprojected,skipRootAncestorValidation:options.allowUnprojected,ignoreInheritedVisibility:!0}).replace(/\s+/g," ").trim()}libraryOwnsSourceInert(element){return this.projectedSourceSnapshots.get(element)?.libraryOwnsInert===!0}isTabLabelSubtreeExcluded(element){return isTabLabelSubtreeExcludedWithoutInert(element)||element.hasAttribute("inert")&&!this.libraryOwnsSourceInert(element)}snapshotProjectedSource(source){const inert=source.getAttribute("inert");return{inert,appliedInert:inert,libraryOwnsInert:!1}}adoptProjectedSourceInert(source,snapshot){const current=source.getAttribute("inert");current!==snapshot.appliedInert&&(snapshot.inert=current,snapshot.libraryOwnsInert=!1)}makeProjectedSourceInert(source,snapshot){source.hasAttribute("inert")||(source.setAttribute("inert",""),snapshot.libraryOwnsInert=!0),snapshot.appliedInert=source.getAttribute("inert")}restoreProjectedSource(source,snapshot){this.adoptProjectedSourceInert(source,snapshot),snapshot.inert===null?source.removeAttribute("inert"):source.setAttribute("inert",snapshot.inert)}restoreProjectedSources(){for(const[source,snapshot]of this.projectedSourceSnapshots)this.restoreProjectedSource(source,snapshot);this.projectedSourceSnapshots.clear()}resetProjectedSourceObserver(){this.projectedSourceObserverGeneration+=1,this.projectedSourceObserver?.disconnect(),this.projectedSourceObserver=void 0,this.projectedSourceObserverDocument=void 0}observeProjectedSources(){this.resetProjectedSourceObserver();const ownerDocument=this.ownerDocument,MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor||!this.isConnected||this.projectedSourceSnapshots.size===0)return;const generation=this.projectedSourceObserverGeneration,observer=new MutationObserverCtor(records=>{this.projectedSourceObserver!==observer||this.projectedSourceObserverDocument!==ownerDocument||this.projectedSourceObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||records.some(record=>this.projectedSourceSnapshots.has(record.target))&&this.syncTabs()});this.projectedSourceObserver=observer,this.projectedSourceObserverDocument=ownerDocument;for(const source of this.projectedSourceSnapshots.keys())observer.observe(source,{attributes:!0,attributeFilter:["inert"]})}projectedSources(tabs){const sources=new Set;for(const tab of tabs)for(const child of Array.from(tab.element.children))(child.getAttribute("slot")??"")===""&&sources.add(child);return sources}syncProjectedSources(tabs){const sources=this.projectedSources(tabs);for(const[source,snapshot]of this.projectedSourceSnapshots)this.adoptProjectedSourceInert(source,snapshot),sources.has(source)||(this.restoreProjectedSource(source,snapshot),this.projectedSourceSnapshots.delete(source));for(const source of sources){const snapshot=this.projectedSourceSnapshots.get(source)??this.snapshotProjectedSource(source);this.projectedSourceSnapshots.set(source,snapshot),this.adoptProjectedSourceInert(source,snapshot),this.makeProjectedSourceInert(source,snapshot)}this.observeProjectedSources()}adoptProjectedSourceInertStates(){for(const[source,snapshot]of this.projectedSourceSnapshots)this.adoptProjectedSourceInert(source,snapshot)}snapshotProjectedSlot(source){const slot=source.getAttribute("slot");return{slot,appliedSlot:slot,libraryOwnsSlot:!1}}adoptProjectedSlot(source,snapshot){const current=source.getAttribute("slot");current!==snapshot.appliedSlot&&(snapshot.slot=current,snapshot.libraryOwnsSlot=!1)}projectSlot(source,slot,projectedSlots){const snapshot=this.projectedSlotSnapshots.get(source)??this.snapshotProjectedSlot(source);this.projectedSlotSnapshots.set(source,snapshot),this.adoptProjectedSlot(source,snapshot),source.getAttribute("slot")!==slot&&(source.setAttribute("slot",slot),snapshot.libraryOwnsSlot=!0),snapshot.appliedSlot=source.getAttribute("slot"),projectedSlots.add(source)}restoreProjectedSlot(source,snapshot){this.adoptProjectedSlot(source,snapshot),snapshot.slot===null?source.removeAttribute("slot"):source.setAttribute("slot",snapshot.slot)}syncProjectedSlots(projectedSlots){for(const[source,snapshot]of this.projectedSlotSnapshots)projectedSlots.has(source)||(this.restoreProjectedSlot(source,snapshot),this.projectedSlotSnapshots.delete(source))}restoreProjectedSlots(){for(const[source,snapshot]of this.projectedSlotSnapshots)this.restoreProjectedSlot(source,snapshot);this.projectedSlotSnapshots.clear()}adoptProjectedSlotStates(){for(const[source,snapshot]of this.projectedSlotSnapshots)this.adoptProjectedSlot(source,snapshot)}isNavigable(tab){return!tab.disabled&&!tab.inert}willUpdate(changed){if(super.willUpdate(changed),!changed.has("tabs")&&!changed.has("active"))return;const focused=activeElementIn(this.renderRoot),focusedSlot=focused?.getAttribute("part")==="tab"?focused.getAttribute("data-slot"):null;focusedSlot!==null&&!this.tabs.some(tab=>tab.slotName===focusedSlot&&this.isNavigable(tab))&&(this.rehomeTabFocus=!0,this.focusedTab=this.active);const current=this.tabs.find(t=>t.slotName===this.active);current&&this.isNavigable(current)||(this.rehomeTabFocus=this.rehomeTabFocus||focusedSlot!==null,this.active=this.tabs.find(t=>this.isNavigable(t))?.slotName??"",this.focusedTab=this.active)}updated(changed){super.updated(changed),(changed.has("active")||changed.has("tabs"))&&this.syncElementActiveState(),this.scrollOverflow.observeExtra(this.renderRoot.querySelectorAll('[part="tab"]')),this.measureTabScrollEdges(),this.rehomeTabFocus&&(this.rehomeTabFocus=!1,this.renderRoot.querySelector('[part="tab"][tabindex="0"]')?.focus())}selectTab(tab){if(!this.isNavigable(tab)||tab.slotName===this.active)return;const previous=this.active;this.active=tab.slotName,this.focusedTab=tab.slotName,previous&&this.emit("lr-tab-hide",{name:previous}),this.emit("lr-tab-show",{name:tab.slotName})}show(panel){const tab=this.tabs.find(candidate=>candidate.slotName===panel);tab&&this.selectTab(tab)}syncElementActiveState(){for(const child of Array.from(this.children))if(child.localName===tag("tab")){const definition=this.tabs.find(tab=>tab.element===child);child.toggleAttribute("active",definition?.slotName===this.active)}else child.localName===tag("tab-panel")&&child.toggleAttribute("active",child.getAttribute("name")===this.active)}focusOnly(tab){this.focusedTab=tab.slotName,this.focusTab(tab.slotName)}get rovingTab(){if(this.activation!=="manual")return this.active;const candidate=this.tabs.find(t=>t.slotName===this.focusedTab&&this.isNavigable(t));return candidate?candidate.slotName:this.active}keyboardOriginTab(event,navigable){const eventButton=event.composedPath().find(candidate=>candidate.nodeType===1&&candidate.getAttribute?.("part")==="tab"&&candidate.getRootNode()===this.renderRoot),focused=activeElementIn(this.renderRoot),owned=(eventButton??(focused?.getAttribute("part")==="tab"?focused:void 0))?.dataset.slot;return navigable.find(tab=>tab.slotName===owned)??navigable.find(tab=>tab.slotName===this.rovingTab)}focusTab(slotName){const buttons=this.renderRoot.querySelectorAll('[part="tab"]');for(const button of Array.from(buttons))if(button.dataset.slot===slotName){button.focus();return}}get isVertical(){return this.placement==="start"||this.placement==="end"}tabId(slotName){return this.idsFor(slotName).tab}panelId(slotName){return this.idsFor(slotName).panel}idsFor(slotName){const existing=this.idsBySlot.get(slotName);if(existing)return existing;const token=`${this.baseId}-${this.nextOpaqueId++}`,ids={tab:`${token}-tab`,panel:`${token}-panel`};return this.idsBySlot.set(slotName,ids),ids}tabSlotName(slotName){return`${slotName}-tab`}get scrollControlsSuppressed(){return this.withoutScrollControls||this.noScrollControls}measureTabScrollEdges(){const tablist=this.renderRoot.querySelector('[part~="tablist"]');if(!tablist||this.isVertical){this.setTabScrollEdges(!1,!1,tablist);return}const maximum=Math.max(0,tablist.scrollWidth-tablist.clientWidth),position=Math.max(0,Math.min(maximum,this.effectiveDirection==="rtl"?-tablist.scrollLeft:tablist.scrollLeft));this.setTabScrollEdges(position>1,position<maximum-1,tablist)}setTabScrollEdges(start,end,tablist){tablist?.toggleAttribute("data-scroll-start",start),tablist?.toggleAttribute("data-scroll-end",end),!(start===this.scrollStartAvailable&&end===this.scrollEndAvailable)&&(this.scrollStartAvailable=start,this.scrollEndAvailable=end)}scrollTabs(edge){const tablist=this.renderRoot.querySelector('[part~="tablist"]');if(!tablist||!isHtmlElement(tablist)||typeof tablist.scrollBy!="function")return;const step=Math.max(1,tablist.clientWidth*SCROLL_STEP_RATIO),towardEnd=edge==="end"?1:-1,physical=this.effectiveDirection==="rtl"?-towardEnd:towardEnd;tablist.scrollBy({left:step*physical,behavior:prefersReducedMotion(this.ownerDocument.defaultView)?"instant":"smooth"})}renderScrollControl(edge){if(this.isVertical||this.scrollControlsSuppressed)return nothing;const available=edge==="start"?this.scrollStartAvailable:this.scrollEndAvailable;return html`<button
2
2
  type="button"
3
3
  part=${edge==="start"?"scroll-button scroll-button__base scroll-button-start scroll-button--start":"scroll-button scroll-button__base scroll-button-end scroll-button--end"}
4
4
  tabindex="-1"
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{query,state}from"lit/decorators.js";import{bindAccessibleTextObserver,composedAccessibilityText,isAccessibilitySubtreeExcluded}from"../../../internal/accessibility-visibility.js";import{composedParentElement}from"../../../internal/active-element.js";import{applyComposedFocusRepair,captureComposedFocusRepair,collectComposedFocusTargets}from"../../../internal/focus-navigation.js";import{LyraElement}from"../../../internal/lyra-element.js";import{closeIcon}from"../../../internal/icons.js";import{variants}from"../../../internal/variants.styles.js";import{LyraBadge}from"./badge.class.js";import{styles as badgeStyles}from"./badge.styles.js";import{styles as tagStyles}from"./tag.styles.js";import{LYRA_DEFAULT_remove,LYRA_DEFAULT_removeWithContext}from"../../../internal/default-strings.generated.js";function isComposedWithin(owner,candidate){let current=candidate;for(;current;){if(current===owner)return!0;current=composedParentElement(current)}return!1}function nearestExternalFocusTarget(owner){const targets=collectComposedFocusTargets(owner.ownerDocument.documentElement,{mode:"programmatic"}).elements,owned=targets.map((target,index)=>isComposedWithin(owner,target)?index:-1).filter(index=>index>=0);if(owned.length===0)return null;const first=owned[0],last=owned[owned.length-1];return targets.slice(last+1).find(target=>!isComposedWithin(owner,target))??targets.slice(0,first).reverse().find(target=>!isComposedWithin(owner,target))??null}function sourceParent(node){if(node.parentElement)return node.parentElement;const root=node.getRootNode();return"host"in root?root.host:null}function isClosedSourceDetailsBranch(details,branch){return details.localName!=="details"||details.hasAttribute("open")||branch===null?!1:Array.from(details.children).find(child=>child.localName==="summary")!==branch}function isSourceLabelAvailable(node){const target=node.nodeType===1?node:sourceParent(node);if(!target?.isConnected)return!1;let branch=target,current=sourceParent(target);if(isAccessibilitySubtreeExcluded(target))return!1;for(;current;){if(isAccessibilitySubtreeExcluded(current)||isClosedSourceDetailsBranch(current,branch))return!1;branch=current,current=sourceParent(current)}return!0}class LyraTag extends LyraBadge{constructor(){super(...arguments),this.removeEnabled=!1,this.changingRemoveAliasAttribute=!1,this.managedActionGroupRole=!1,this.labelText="",this.onLabelSlotChange=event=>{const target=event.target;target?.nodeType!==1||target.localName!=="slot"||(this.bindLabelObserverTargets(),this.withRemove&&this.updateBrowserDerivedState(()=>this.recomputeLabelText()))},this.onRemoveClick=()=>{if(!this.withRemove)return;const repair=captureComposedFocusRepair(this,nearestExternalFocusTarget(this));this.emit("lr-remove"),repair&&(!this.isConnected||!this.withRemove)&&applyComposedFocusRepair(repair)}}static{this.defaultStrings={...super.defaultStrings,remove:LYRA_DEFAULT_remove,removeWithContext:LYRA_DEFAULT_removeWithContext}}static{this.styles=[LyraElement.styles,variants,badgeStyles,tagStyles]}static{this.properties={withRemove:{attribute:"with-remove",type:Boolean,noAccessor:!0},removable:{attribute:"removable",type:Boolean,noAccessor:!0}}}get semanticRole(){return null}get effectiveVariant(){return this.variant==="text"?"neutral":super.effectiveVariant}get withRemove(){return this.removeEnabled}set withRemove(next){this.setRemoveEnabled(!!next,"with-remove")}get removable(){return this.removeEnabled}set removable(next){this.setRemoveEnabled(!!next,"removable")}attributeChangedCallback(name,oldValue,value){const isRemoveAlias=name==="with-remove"||name==="removable";isRemoveAlias&&(this.changingRemoveAliasAttribute=!0);try{super.attributeChangedCallback(name,oldValue,value)}finally{isRemoveAlias&&(this.changingRemoveAliasAttribute=!1)}}setRemoveEnabled(next,preferredAttribute){const old=this.removeEnabled;this.changingRemoveAliasAttribute?this.removeEnabled=this.hasAttribute("with-remove")||this.hasAttribute("removable"):next?(this.setAttribute(preferredAttribute,""),this.removeEnabled=!0):(this.removeAttribute("with-remove"),this.removeAttribute("removable"),this.removeEnabled=!1),old!==this.removeEnabled&&(this.requestUpdate("withRemove",old),this.requestUpdate("removable",old))}connectedCallback(){super.connectedCallback(),this.addEventListener("slotchange",this.onLabelSlotChange),this.syncLabelObserver(),this.hasUpdated?this.withRemove&&this.recomputeLabelText():this.seedFirstRenderState(()=>this.recomputeLabelText())}disconnectedCallback(){this.removeEventListener("slotchange",this.onLabelSlotChange),this.labelObserver?.disconnect(),this.labelObserver=void 0,this.releaseHostActionRole(),super.disconnectedCallback()}syncLabelObserver(){const MutationObserverCtor=this.ownerDocument?.defaultView?.MutationObserver;if(!this.withRemove||!this.isConnected||!MutationObserverCtor){this.labelObserver?.disconnect(),this.labelObserver=void 0;return}this.labelObserver??=new MutationObserverCtor(()=>{this.bindLabelObserverTargets(),this.syncHostActionRole(),this.updateBrowserDerivedState(()=>this.recomputeLabelText())}),this.bindLabelObserverTargets()}bindLabelObserverTargets(){bindAccessibleTextObserver(this.labelObserver,this,["slot","role"])}recomputeLabelText(){const slot=this.renderRoot?.querySelector("slot:not([name])"),lightDomNodes=this.childNodes,nodes=slot?slot.assignedNodes({flatten:!0}):Array.from(lightDomNodes??[]).filter(node=>{if(node.nodeType!==1)return!0;const slotName=node.getAttribute("slot");return slotName!=="start"&&slotName!=="end"});this.labelText=nodes.map(node=>composedAccessibilityText(node,{ancestorBoundary:this,isSubtreeExcluded:element=>element.getRootNode()===this.renderRoot&&element.getAttribute("part")?.split(/\s+/).includes("content")?!1:isAccessibilitySubtreeExcluded(element),requireRendered:node.nodeType!==1||node.localName!=="slot",shouldPruneNode:candidate=>!this.contains(candidate)&&!isSourceLabelAvailable(candidate)})).join(" ").replace(/\s+/g," ").trim()}get accessibleRemoveLabel(){const text=this.labelText;return text?this.localize("removeWithContext",void 0,{label:text}):this.localize("remove")}focus(options){this.withRemove&&this.removeButtonEl?.focus(options)}blur(){this.removeButtonEl?.blur()}click(){if(!this.withRemove){super.click();return}this.removeButtonEl?.click()}willUpdate(changed){if(super.willUpdate(changed),changed.has("withRemove")){if(!this.withRemove){const repair=captureComposedFocusRepair(this,nearestExternalFocusTarget(this));repair&&applyComposedFocusRepair(repair)}this.syncLabelObserver(),this.withRemove&&this.hasUpdated&&this.recomputeLabelText()}}updated(changed){super.updated(changed),this.syncHostActionRole()}syncHostActionRole(){const needsGroup=this.withRemove&&this.hasAttribute("aria-label");needsGroup&&!this.hasAttribute("role")?(this.setAttribute("role","group"),this.managedActionGroupRole=!0):needsGroup||this.releaseHostActionRole()}releaseHostActionRole(){this.managedActionGroupRole&&this.getAttribute("role")==="group"&&this.removeAttribute("role"),this.managedActionGroupRole=!1}renderTrailing(){return this.withRemove?html`<button
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{query,state}from"lit/decorators.js";import{bindAccessibleTextObserver,composedAccessibilityText,isAccessibilitySubtreeExcluded}from"../../../internal/accessibility-visibility.js";import{composedParentElement}from"../../../internal/active-element.js";import{applyComposedFocusRepair,captureComposedFocusRepair,collectComposedFocusTargets}from"../../../internal/focus-navigation.js";import{LyraElement}from"../../../internal/lyra-element.js";import{closeIcon}from"../../../internal/icons.js";import{variants}from"../../../internal/variants.styles.js";import{LyraBadge}from"./badge.class.js";import{styles as badgeStyles}from"./badge.styles.js";import{styles as tagStyles}from"./tag.styles.js";import{LYRA_DEFAULT_remove,LYRA_DEFAULT_removeWithContext}from"../../../internal/default-strings.generated.js";function isComposedWithin(owner,candidate){let current=candidate;for(;current;){if(current===owner)return!0;current=composedParentElement(current)}return!1}function nearestExternalFocusTarget(owner){const targets=collectComposedFocusTargets(owner.ownerDocument.documentElement,{mode:"programmatic"}).elements,owned=targets.map((target,index)=>isComposedWithin(owner,target)?index:-1).filter(index=>index>=0);if(owned.length===0)return null;const first=owned[0],last=owned[owned.length-1];return targets.slice(last+1).find(target=>!isComposedWithin(owner,target))??targets.slice(0,first).reverse().find(target=>!isComposedWithin(owner,target))??null}function sourceParent(node){if(node.parentElement)return node.parentElement;const root=node.getRootNode();return"host"in root?root.host:null}function isClosedSourceDetailsBranch(details,branch){return details.localName!=="details"||details.hasAttribute("open")||branch===null?!1:Array.from(details.children).find(child=>child.localName==="summary")!==branch}function isSourceLabelAvailable(node){const target=node.nodeType===1?node:sourceParent(node);if(!target?.isConnected)return!1;let branch=target,current=sourceParent(target);if(isAccessibilitySubtreeExcluded(target))return!1;for(;current;){if(isAccessibilitySubtreeExcluded(current)||isClosedSourceDetailsBranch(current,branch))return!1;branch=current,current=sourceParent(current)}return!0}class LyraTag extends LyraBadge{constructor(){super(...arguments),this.removeEnabled=!1,this.changingRemoveAliasAttribute=!1,this.managedActionGroupRole=!1,this.labelText="",this.onLabelSlotChange=event=>{const target=event.target;target?.nodeType!==1||target.localName!=="slot"||(this.bindLabelObserverTargets(),this.withRemove&&this.updateBrowserDerivedState(()=>this.recomputeLabelText()))},this.onRemoveClick=()=>{if(!this.withRemove)return;const repair=captureComposedFocusRepair(this,nearestExternalFocusTarget(this));this.emit("lr-remove"),repair&&(!this.isConnected||!this.withRemove)&&applyComposedFocusRepair(repair)}}static{this.defaultStrings={...super.defaultStrings,remove:LYRA_DEFAULT_remove,removeWithContext:LYRA_DEFAULT_removeWithContext}}static{this.styles=[LyraElement.styles,variants,badgeStyles,tagStyles]}static{this.properties={withRemove:{attribute:"with-remove",type:Boolean,noAccessor:!0},removable:{attribute:"removable",type:Boolean,noAccessor:!0}}}get semanticRole(){return null}get effectiveVariant(){return this.variant==="text"?"neutral":super.effectiveVariant}get withRemove(){return this.removeEnabled}set withRemove(next){this.setRemoveEnabled(!!next,"with-remove")}get removable(){return this.removeEnabled}set removable(next){this.setRemoveEnabled(!!next,"removable")}attributeChangedCallback(name,oldValue,value){const isRemoveAlias=name==="with-remove"||name==="removable";isRemoveAlias&&(this.changingRemoveAliasAttribute=!0);try{super.attributeChangedCallback(name,oldValue,value)}finally{isRemoveAlias&&(this.changingRemoveAliasAttribute=!1)}}setRemoveEnabled(next,preferredAttribute){const old=this.removeEnabled;this.changingRemoveAliasAttribute?this.removeEnabled=this.hasAttribute("with-remove")||this.hasAttribute("removable"):next?(this.setAttribute(preferredAttribute,""),this.removeEnabled=!0):(this.removeAttribute("with-remove"),this.removeAttribute("removable"),this.removeEnabled=!1),old!==this.removeEnabled&&(this.requestUpdate("withRemove",old),this.requestUpdate("removable",old))}connectedCallback(){super.connectedCallback(),this.addEventListener("slotchange",this.onLabelSlotChange),this.syncLabelObserver(),this.hasUpdated?(this.withRemove&&this.recomputeLabelText(!0),this.ownerDocument.defaultView?.queueMicrotask(()=>{this.isConnected&&this.withRemove&&this.recomputeLabelText()})):this.seedFirstRenderState(()=>this.recomputeLabelText(!0))}disconnectedCallback(){this.removeEventListener("slotchange",this.onLabelSlotChange),this.labelObserver?.disconnect(),this.labelObserver=void 0,this.releaseHostActionRole(),super.disconnectedCallback()}syncLabelObserver(){const MutationObserverCtor=this.ownerDocument?.defaultView?.MutationObserver;if(!this.withRemove||!this.isConnected||!MutationObserverCtor){this.labelObserver?.disconnect(),this.labelObserver=void 0;return}this.labelObserver??=new MutationObserverCtor(()=>{this.bindLabelObserverTargets(),this.syncHostActionRole(),this.updateBrowserDerivedState(()=>this.recomputeLabelText())}),this.bindLabelObserverTargets()}bindLabelObserverTargets(){bindAccessibleTextObserver(this.labelObserver,this,["slot","role"])}recomputeLabelText(preferLightDom=!1){const slot=this.renderRoot?.querySelector("slot:not([name])"),lightDomNodes=this.childNodes,nodes=slot?slot.assignedNodes({flatten:!0}):Array.from(lightDomNodes??[]).filter(node=>{if(node.nodeType!==1)return!0;const slotName=node.getAttribute("slot");return slotName!=="start"&&slotName!=="end"});this.labelText=nodes.map(node=>composedAccessibilityText(node,{ancestorBoundary:this,isSubtreeExcluded:element=>element.getRootNode()===this.renderRoot&&element.getAttribute("part")?.split(/\s+/).includes("content")?!1:isAccessibilitySubtreeExcluded(element),requireRendered:preferLightDom?!1:node.nodeType!==1||node.localName!=="slot",shouldPruneNode:candidate=>!this.contains(candidate)&&!isSourceLabelAvailable(candidate),ignoreInheritedVisibility:!0})).join(" ").replace(/\s+/g," ").trim()}get accessibleRemoveLabel(){const text=this.labelText;return text?this.localize("removeWithContext",void 0,{label:text}):this.localize("remove")}focus(options){this.withRemove&&this.removeButtonEl?.focus(options)}blur(){this.removeButtonEl?.blur()}click(){if(!this.withRemove){super.click();return}this.removeButtonEl?.click()}willUpdate(changed){if(super.willUpdate(changed),changed.has("withRemove")){if(!this.withRemove){const repair=captureComposedFocusRepair(this,nearestExternalFocusTarget(this));repair&&applyComposedFocusRepair(repair)}this.syncLabelObserver(),this.withRemove&&this.hasUpdated&&this.recomputeLabelText()}}updated(changed){super.updated(changed),this.syncHostActionRole()}syncHostActionRole(){const needsGroup=this.withRemove&&this.hasAttribute("aria-label");needsGroup&&!this.hasAttribute("role")?(this.setAttribute("role","group"),this.managedActionGroupRole=!0):needsGroup||this.releaseHostActionRole()}releaseHostActionRole(){this.managedActionGroupRole&&this.getAttribute("role")==="group"&&this.removeAttribute("role"),this.managedActionGroupRole=!1}renderTrailing(){return this.withRemove?html`<button
2
2
  part="remove-button remove-button__base"
3
3
  type="button"
4
4
  aria-label=${this.accessibleRemoveLabel}
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{bindAccessibleTextObserver,composedAccessibilityText,isAccessibilitySubtreeExcluded}from"../../../internal/accessibility-visibility.js";import{composedParentElement}from"../../../internal/active-element.js";import{applyComposedFocusRepair,captureComposedFocusRepair,collectComposedFocusTargets}from"../../../internal/focus-navigation.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{LyraElement}from"../../../internal/lyra-element.js";import{closeIcon}from"../../../internal/icons.js";import{literalSetConverter}from"../../../internal/converters.js";import{variants}from"../../../internal/variants.styles.js";import{styles}from"./chip.styles.js";import{LYRA_DEFAULT_remove,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const CHIP_SIZE=literalSetConverter(["3xs","2xs","xs","s","m","l","xl","small","medium","large"],"m"),CHIP_VARIANT=literalSetConverter(["neutral","brand","success","warning","danger"],"neutral");function isComposedWithin(owner,candidate){let current=candidate;for(;current;){if(current===owner)return!0;current=composedParentElement(current)}return!1}function nearestExternalFocusTarget(owner){const targets=collectComposedFocusTargets(owner.ownerDocument.documentElement,{mode:"programmatic"}).elements,owned=targets.map((target,index)=>isComposedWithin(owner,target)?index:-1).filter(index=>index>=0);if(owned.length===0)return null;const first=owned[0],last=owned[owned.length-1];return targets.slice(last+1).find(target=>!isComposedWithin(owner,target))??targets.slice(0,first).reverse().find(target=>!isComposedWithin(owner,target))??null}function sourceParent(node){if(node.parentElement)return node.parentElement;const root=node.getRootNode();return"host"in root?root.host:null}function isClosedSourceDetailsBranch(details,branch){return details.localName!=="details"||details.hasAttribute("open")||branch===null?!1:Array.from(details.children).find(child=>child.localName==="summary")!==branch}function isSourceLabelAvailable(node){const target=node.nodeType===1?node:sourceParent(node);if(!target?.isConnected)return!1;let branch=target,current=sourceParent(target);if(isAccessibilitySubtreeExcluded(target))return!1;for(;current;){if(isAccessibilitySubtreeExcluded(current)||isClosedSourceDetailsBranch(current,branch))return!1;branch=current,current=sourceParent(current)}return!0}class LyraChip extends LyraElement{constructor(){super(...arguments),this._size="m",this._variant="neutral",this.removable=!1,this.disabled=!1,this.pill=!1,this.selected=!1,this.toggleable=!1,this.hasStartSlot=!1,this.hasEndSlot=!1,this.cachedLabelText="",this.managedActionGroupRole=!1,this.onLabelSlotChange=event=>{const target=event.target;target?.nodeType!==1||target.localName!=="slot"||this.tracksActionLabel&&(this.bindLabelObserverTargets(),this.updateBrowserDerivedState(()=>this.recomputeLabelText()))},this.onStartSlotChange=e=>{const slot=e.target,update=()=>{this.isConnected&&(this.hasStartSlot=slot.assignedElements({flatten:!0}).length>0)};this.updateBrowserDerivedState(update)},this.onEndSlotChange=e=>{const slot=e.target,update=()=>{this.isConnected&&(this.hasEndSlot=slot.assignedElements({flatten:!0}).length>0)};this.updateBrowserDerivedState(update)},this.onRemoveClick=()=>{if(this.disabled)return;const repair=captureComposedFocusRepair(this,nearestExternalFocusTarget(this));this.emit("lr-remove",{value:this.value}),repair&&(!this.isConnected||!this.removable)&&applyComposedFocusRepair(repair)},this.onToggleClick=()=>{if(this.disabled)return;const selected=!this.selected;this.emit("lr-chip-select",{value:this.value,selected},{cancelable:!0}).defaultPrevented||(this.selected=selected)}}static{this.defaultStrings={...super.defaultStrings,remove:LYRA_DEFAULT_remove,removeWithContext:LYRA_DEFAULT_removeWithContext,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,variants,styles]}get size(){return this._size}set size(next){const normalized=CHIP_SIZE.normalizeReflected(this,"size",next),old=this._size;old!==normalized&&(this._size=normalized,this.requestUpdate("size",old))}get variant(){return this._variant}set variant(next){const normalized=CHIP_VARIANT.normalizeReflected(this,"variant",next),old=this._variant;old!==normalized&&(this._variant=normalized,this.requestUpdate("variant",old))}connectedCallback(){super.connectedCallback(),this.addEventListener("slotchange",this.onLabelSlotChange),this.syncLabelObservation();const sampleBrowserState=()=>{this.recomputeHasStartSlot(),this.recomputeHasEndSlot(),this.tracksActionLabel&&this.recomputeLabelText(!0,!0)};this.hasUpdated?(sampleBrowserState(),this.ownerDocument.defaultView?.queueMicrotask(()=>{this.isConnected&&this.tracksActionLabel&&this.recomputeLabelText()})):this.seedFirstRenderState(sampleBrowserState)}get tracksActionLabel(){return this.toggleable||this.removable}syncLabelObservation(){if(this.labelObserver?.disconnect(),this.labelObserver=void 0,!this.isConnected||!this.tracksActionLabel)return;const MutationObserverCtor=this.ownerDocument?.defaultView?.MutationObserver;this.labelObserver=MutationObserverCtor?new MutationObserverCtor(()=>{this.bindLabelObserverTargets(),this.syncHostActionRole(),this.updateBrowserDerivedState(()=>this.recomputeLabelText())}):void 0,this.bindLabelObserverTargets()}bindLabelObserverTargets(){bindAccessibleTextObserver(this.labelObserver,this,["slot","role"])}disconnectedCallback(){this.removeEventListener("slotchange",this.onLabelSlotChange),this.labelObserver?.disconnect(),this.labelObserver=void 0,this.releaseHostActionRole(),this.pendingControlFocusRepair=void 0,super.disconnectedCallback()}recomputeHasStartSlot(){const children=this.children;children&&(this.hasStartSlot=Array.from(children).some(el=>el.getAttribute("slot")==="start"))}recomputeHasEndSlot(){const children=this.children;children&&(this.hasEndSlot=Array.from(children).some(el=>el.getAttribute("slot")==="end"))}computeLabelText(preferLightDom=!1){const slot=this.renderRoot?.querySelector("slot:not([name])"),lightDomNodes=this.childNodes,assigned=slot?.assignedNodes({flatten:!0})??[],direct=Array.from(lightDomNodes??[]).filter(node=>node.nodeType!==1||(node.getAttribute("slot")??"")==="");return(!preferLightDom&&assigned.length>0?assigned:direct).map(node=>composedAccessibilityText(node,{ancestorBoundary:this,isSubtreeExcluded:element=>element.getRootNode()===this.renderRoot&&element.getAttribute("part")?.split(/\s+/).includes("label")?!1:isAccessibilitySubtreeExcluded(element),requireRendered:preferLightDom?!1:node.nodeType!==1||node.localName!=="slot",shouldPruneNode:candidate=>!this.contains(candidate)&&!isSourceLabelAvailable(candidate)})).join(" ").replace(/\s+/g," ").trim()}recomputeLabelText(request=!0,preferLightDom=!1){const next=this.computeLabelText(preferLightDom);next!==this.cachedLabelText&&(this.cachedLabelText=next,request&&this.requestUpdate())}get accessibleToggleLabel(){return this.cachedLabelText||this.localize("select")}get accessibleRemoveLabel(){const text=this.cachedLabelText;return text?this.localize("removeWithContext",void 0,{label:text}):this.localize("remove")}get primaryControl(){return this.renderRoot.querySelector(this.removable?'[part="remove-button"]':'[part="toggle-button"]')}focus(options){this.primaryControl?.focus(options)}blur(){this.primaryControl?.blur()}click(){const control=this.primaryControl;control?control.click():super.click()}willUpdate(changed){if(super.willUpdate(changed),(changed.has("removable")||changed.has("toggleable"))&&(this.syncLabelObservation(),this.hasUpdated&&(this.tracksActionLabel?this.recomputeLabelText(!1):this.cachedLabelText="")),this.pendingControlFocusRepair)return;const oldRemovable=changed.get("removable")??this.removable,oldToggleable=changed.get("toggleable")??this.toggleable,oldDisabled=changed.get("disabled")??this.disabled,oldMode=oldRemovable?"remove":oldToggleable?"toggle":"passive",newMode=this.removable?"remove":this.toggleable?"toggle":"passive";oldMode===newMode&&!(oldDisabled===!1&&this.disabled)||(this.pendingControlFocusRepair=captureComposedFocusRepair(this,nearestExternalFocusTarget(this)??this.renderRoot.querySelector('[part="remove-button"], [part="toggle-button"]'))??void 0)}updated(changed){super.updated(changed),this.syncHostActionRole();const repair=this.pendingControlFocusRepair;if(this.pendingControlFocusRepair=void 0,!repair)return;const replacement=this.disabled?null:this.primaryControl;applyComposedFocusRepair(repair,replacement??repair.candidate)}syncHostActionRole(){const needsGroup=this.tracksActionLabel&&this.hasAttribute("aria-label");needsGroup&&!this.hasAttribute("role")?(this.setAttribute("role","group"),this.managedActionGroupRole=!0):needsGroup||this.releaseHostActionRole()}releaseHostActionRole(){this.managedActionGroupRole&&this.getAttribute("role")==="group"&&this.removeAttribute("role"),this.managedActionGroupRole=!1}render(){const toggleMode=this.toggleable&&!this.removable,pressed=this.selected&&!this.removable;return html`
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{bindAccessibleTextObserver,composedAccessibilityText,isAccessibilitySubtreeExcluded}from"../../../internal/accessibility-visibility.js";import{composedParentElement}from"../../../internal/active-element.js";import{applyComposedFocusRepair,captureComposedFocusRepair,collectComposedFocusTargets}from"../../../internal/focus-navigation.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{LyraElement}from"../../../internal/lyra-element.js";import{closeIcon}from"../../../internal/icons.js";import{literalSetConverter}from"../../../internal/converters.js";import{variants}from"../../../internal/variants.styles.js";import{styles}from"./chip.styles.js";import{LYRA_DEFAULT_remove,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const CHIP_SIZE=literalSetConverter(["3xs","2xs","xs","s","m","l","xl","small","medium","large"],"m"),CHIP_VARIANT=literalSetConverter(["neutral","brand","success","warning","danger"],"neutral");function isComposedWithin(owner,candidate){let current=candidate;for(;current;){if(current===owner)return!0;current=composedParentElement(current)}return!1}function nearestExternalFocusTarget(owner){const targets=collectComposedFocusTargets(owner.ownerDocument.documentElement,{mode:"programmatic"}).elements,owned=targets.map((target,index)=>isComposedWithin(owner,target)?index:-1).filter(index=>index>=0);if(owned.length===0)return null;const first=owned[0],last=owned[owned.length-1];return targets.slice(last+1).find(target=>!isComposedWithin(owner,target))??targets.slice(0,first).reverse().find(target=>!isComposedWithin(owner,target))??null}function sourceParent(node){if(node.parentElement)return node.parentElement;const root=node.getRootNode();return"host"in root?root.host:null}function isClosedSourceDetailsBranch(details,branch){return details.localName!=="details"||details.hasAttribute("open")||branch===null?!1:Array.from(details.children).find(child=>child.localName==="summary")!==branch}function isSourceLabelAvailable(node){const target=node.nodeType===1?node:sourceParent(node);if(!target?.isConnected)return!1;let branch=target,current=sourceParent(target);if(isAccessibilitySubtreeExcluded(target))return!1;for(;current;){if(isAccessibilitySubtreeExcluded(current)||isClosedSourceDetailsBranch(current,branch))return!1;branch=current,current=sourceParent(current)}return!0}class LyraChip extends LyraElement{constructor(){super(...arguments),this._size="m",this._variant="neutral",this.removable=!1,this.disabled=!1,this.pill=!1,this.selected=!1,this.toggleable=!1,this.hasStartSlot=!1,this.hasEndSlot=!1,this.cachedLabelText="",this.managedActionGroupRole=!1,this.onLabelSlotChange=event=>{const target=event.target;target?.nodeType!==1||target.localName!=="slot"||this.tracksActionLabel&&(this.bindLabelObserverTargets(),this.updateBrowserDerivedState(()=>this.recomputeLabelText()))},this.onStartSlotChange=e=>{const slot=e.target,update=()=>{this.isConnected&&(this.hasStartSlot=slot.assignedElements({flatten:!0}).length>0)};this.updateBrowserDerivedState(update)},this.onEndSlotChange=e=>{const slot=e.target,update=()=>{this.isConnected&&(this.hasEndSlot=slot.assignedElements({flatten:!0}).length>0)};this.updateBrowserDerivedState(update)},this.onRemoveClick=()=>{if(this.disabled)return;const repair=captureComposedFocusRepair(this,nearestExternalFocusTarget(this));this.emit("lr-remove",{value:this.value}),repair&&(!this.isConnected||!this.removable)&&applyComposedFocusRepair(repair)},this.onToggleClick=()=>{if(this.disabled)return;const selected=!this.selected;this.emit("lr-chip-select",{value:this.value,selected},{cancelable:!0}).defaultPrevented||(this.selected=selected)}}static{this.defaultStrings={...super.defaultStrings,remove:LYRA_DEFAULT_remove,removeWithContext:LYRA_DEFAULT_removeWithContext,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,variants,styles]}get size(){return this._size}set size(next){const normalized=CHIP_SIZE.normalizeReflected(this,"size",next),old=this._size;old!==normalized&&(this._size=normalized,this.requestUpdate("size",old))}get variant(){return this._variant}set variant(next){const normalized=CHIP_VARIANT.normalizeReflected(this,"variant",next),old=this._variant;old!==normalized&&(this._variant=normalized,this.requestUpdate("variant",old))}connectedCallback(){super.connectedCallback(),this.addEventListener("slotchange",this.onLabelSlotChange),this.syncLabelObservation();const sampleBrowserState=()=>{this.recomputeHasStartSlot(),this.recomputeHasEndSlot(),this.tracksActionLabel&&this.recomputeLabelText(!0,!0)};this.hasUpdated?(sampleBrowserState(),this.ownerDocument.defaultView?.queueMicrotask(()=>{this.isConnected&&this.tracksActionLabel&&this.recomputeLabelText()})):this.seedFirstRenderState(sampleBrowserState)}get tracksActionLabel(){return this.toggleable||this.removable}syncLabelObservation(){if(this.labelObserver?.disconnect(),this.labelObserver=void 0,!this.isConnected||!this.tracksActionLabel)return;const MutationObserverCtor=this.ownerDocument?.defaultView?.MutationObserver;this.labelObserver=MutationObserverCtor?new MutationObserverCtor(()=>{this.bindLabelObserverTargets(),this.syncHostActionRole(),this.updateBrowserDerivedState(()=>this.recomputeLabelText())}):void 0,this.bindLabelObserverTargets()}bindLabelObserverTargets(){bindAccessibleTextObserver(this.labelObserver,this,["slot","role"])}disconnectedCallback(){this.removeEventListener("slotchange",this.onLabelSlotChange),this.labelObserver?.disconnect(),this.labelObserver=void 0,this.releaseHostActionRole(),this.pendingControlFocusRepair=void 0,super.disconnectedCallback()}recomputeHasStartSlot(){const children=this.children;children&&(this.hasStartSlot=Array.from(children).some(el=>el.getAttribute("slot")==="start"))}recomputeHasEndSlot(){const children=this.children;children&&(this.hasEndSlot=Array.from(children).some(el=>el.getAttribute("slot")==="end"))}computeLabelText(preferLightDom=!1){const slot=this.renderRoot?.querySelector("slot:not([name])"),lightDomNodes=this.childNodes,assigned=slot?.assignedNodes({flatten:!0})??[],direct=Array.from(lightDomNodes??[]).filter(node=>node.nodeType!==1||(node.getAttribute("slot")??"")==="");return(!preferLightDom&&assigned.length>0?assigned:direct).map(node=>composedAccessibilityText(node,{ancestorBoundary:this,isSubtreeExcluded:element=>element.getRootNode()===this.renderRoot&&element.getAttribute("part")?.split(/\s+/).includes("label")?!1:isAccessibilitySubtreeExcluded(element),requireRendered:preferLightDom?!1:node.nodeType!==1||node.localName!=="slot",shouldPruneNode:candidate=>!this.contains(candidate)&&!isSourceLabelAvailable(candidate),ignoreInheritedVisibility:!0})).join(" ").replace(/\s+/g," ").trim()}recomputeLabelText(request=!0,preferLightDom=!1){const next=this.computeLabelText(preferLightDom);next!==this.cachedLabelText&&(this.cachedLabelText=next,request&&this.requestUpdate())}get accessibleToggleLabel(){return this.cachedLabelText||this.localize("select")}get accessibleRemoveLabel(){const text=this.cachedLabelText;return text?this.localize("removeWithContext",void 0,{label:text}):this.localize("remove")}get primaryControl(){return this.renderRoot.querySelector(this.removable?'[part="remove-button"]':'[part="toggle-button"]')}focus(options){this.primaryControl?.focus(options)}blur(){this.primaryControl?.blur()}click(){const control=this.primaryControl;control?control.click():super.click()}willUpdate(changed){if(super.willUpdate(changed),(changed.has("removable")||changed.has("toggleable"))&&(this.syncLabelObservation(),this.hasUpdated&&(this.tracksActionLabel?this.recomputeLabelText(!1):this.cachedLabelText="")),this.pendingControlFocusRepair)return;const oldRemovable=changed.get("removable")??this.removable,oldToggleable=changed.get("toggleable")??this.toggleable,oldDisabled=changed.get("disabled")??this.disabled,oldMode=oldRemovable?"remove":oldToggleable?"toggle":"passive",newMode=this.removable?"remove":this.toggleable?"toggle":"passive";oldMode===newMode&&!(oldDisabled===!1&&this.disabled)||(this.pendingControlFocusRepair=captureComposedFocusRepair(this,nearestExternalFocusTarget(this)??this.renderRoot.querySelector('[part="remove-button"], [part="toggle-button"]'))??void 0)}updated(changed){super.updated(changed),this.syncHostActionRole();const repair=this.pendingControlFocusRepair;if(this.pendingControlFocusRepair=void 0,!repair)return;const replacement=this.disabled?null:this.primaryControl;applyComposedFocusRepair(repair,replacement??repair.candidate)}syncHostActionRole(){const needsGroup=this.tracksActionLabel&&this.hasAttribute("aria-label");needsGroup&&!this.hasAttribute("role")?(this.setAttribute("role","group"),this.managedActionGroupRole=!0):needsGroup||this.releaseHostActionRole()}releaseHostActionRole(){this.managedActionGroupRole&&this.getAttribute("role")==="group"&&this.removeAttribute("role"),this.managedActionGroupRole=!1}render(){const toggleMode=this.toggleable&&!this.removable,pressed=this.selected&&!this.removable;return html`
2
2
  <span part="base">
3
3
  ${renderInertPresentation(html`<slot
4
4
  name="start"
@@ -17,8 +17,19 @@ isSubtreeExcluded?:(element:Element)=>boolean;
17
17
  ancestorBoundary?:Element|null;
18
18
  /** Whether connected candidates must participate in rendered layout. Defaults to true. */
19
19
  requireRendered?:boolean;
20
- /** Skips composed-ancestor validation for supplied roots; their own authored state still applies. */
21
- skipRootAncestorValidation?:boolean;}export interface ComposedAccessibilityTextResult{labelReferenceRoots:ReadonlySet<Document|ShadowRoot>;referencedElements:ReadonlySet<Element>;text:string;
20
+ /** Skips composed-ancestor validation for supplied roots; their own authored state still applies.
21
+ * This also implies `ignoreInheritedVisibility`, since a walk that ignores its ancestors entirely
22
+ * cannot meaningfully honor visibility inherited from them. Prefer `ignoreInheritedVisibility`
23
+ * alone when authored ancestor exclusion (`aria-hidden`, `inert`, `hidden`) must still prune. */
24
+ skipRootAncestorValidation?:boolean;
25
+ /** Computes a name that does not depend on where the roots currently sit. `visibility: hidden`
26
+ * inherited from outside the walk -- a closed overlay popup, an inactive slide -- stops
27
+ * suppressing text, for the roots and their descendants alike. Inherited and locally declared
28
+ * `hidden` are indistinguishable from computed style once a container is hidden, and an absent
29
+ * accessible name is the worse of the two failures. Unlike `skipRootAncestorValidation` this
30
+ * keeps full composed-ancestor validation, so `aria-hidden`, `inert`, `hidden` and
31
+ * `display: none` still prune exactly as before. */
32
+ ignoreInheritedVisibility?:boolean;}export interface ComposedAccessibilityTextResult{labelReferenceRoots:ReadonlySet<Document|ShadowRoot>;referencedElements:ReadonlySet<Element>;text:string;
22
33
  /** Open roots actually entered by the bounded walk, suitable for live-text observation. */
23
34
  traversedShadowRoots:ReadonlySet<ShadowRoot>;truncated:boolean;truncationReasons:readonly AccessibilityTextTruncationReason[];visitedNodes:number;}
24
35
  /** `aria-hidden` is an ASCII case-insensitive true/false token in HTML. */
@@ -1 +1 @@
1
- import{composedParentElement}from"./active-element.js";import{asciiWhitespaceTokens}from"./ascii-whitespace.js";import{imageMapImageFor}from"./dom-guards.js";import{composedParentElement as composedParentElement2}from"./active-element.js";const NON_CONTENT_ELEMENTS=new Set(["script","style","template"]),DEFAULT_ACCESSIBILITY_TEXT_MAX_CHARACTERS=4096,DEFAULT_ACCESSIBILITY_TEXT_MAX_DEPTH=256,DEFAULT_ACCESSIBILITY_TEXT_MAX_NODES=4096,DEFAULT_ACCESSIBILITY_VISIBILITY_MAX_NODES=512,MAX_CONFIGURED_ACCESSIBILITY_TEXT_LIMIT=1e5;function isAriaTrue(value){return value?.trim().toLowerCase()==="true"}function accessibilityElementState(element,imageMapImage=imageMapImageFor(element)){let rendered;try{rendered=element.ownerDocument.defaultView?.getComputedStyle(element)}catch{}const visibility=rendered?.visibility;return{display:rendered?.display,subtreeExcluded:element.hasAttribute("hidden")||element.hasAttribute("inert")||isAriaTrue(element.getAttribute("aria-hidden"))||!imageMapImage&&(rendered?.display==="none"||rendered?.contentVisibility==="hidden"),visibilityHidden:visibility==="hidden"||visibility==="collapse"}}function isAccessibilitySubtreeExcluded(element){return accessibilityElementState(element).subtreeExcluded}function isAccessibilityVisibilityHidden(element){return accessibilityElementState(element).visibilityHidden}function isAccessibilityExcluded(element){return isAccessibilitySubtreeExcluded(element)||isAccessibilityVisibilityHidden(element)}const CONTENT_NODE_ATTRIBUTES=["alt","aria-hidden","aria-label","aria-labelledby","class","hidden","id","inert","open","style"],ANCESTOR_ATTRIBUTES=["aria-hidden","class","hidden","inert","open","style"];function observeAccessibleTextNode(observer,node,extraAttributes){if(node.nodeType===3){observer.observe(node,{characterData:!0});return}node.nodeType===1&&observer.observe(node,{attributes:!0,attributeFilter:[...new Set([...CONTENT_NODE_ATTRIBUTES,...extraAttributes])],childList:!0,characterData:!0,subtree:!0})}function bindAccessibleTextObserver(observer,host,extraAttributes=[]){if(!observer)return;observer.disconnect(),observeAccessibleTextNode(observer,host,extraAttributes);let ancestor=composedParentElement(host);for(;ancestor;)observer.observe(ancestor,{attributes:!0,attributeFilter:ANCESTOR_ATTRIBUTES}),ancestor=composedParentElement(ancestor);for(const slot of host.querySelectorAll("slot"))for(const assigned of slot.assignedNodes({flatten:!0}))observeAccessibleTextNode(observer,assigned,extraAttributes)}function finiteTextLimit(value,fallback){return Number.isFinite(value)?Math.min(MAX_CONFIGURED_ACCESSIBILITY_TEXT_LIMIT,Math.max(0,Math.floor(value))):fallback}function isNodeValue(value){if(typeof value!="object"&&typeof value!="function"||value===null)return!1;try{return typeof value.nodeType=="number"&&typeof value.getRootNode=="function"}catch{return!1}}function consumeNodeWork(context){return context.workUnits>=context.maxNodes?(context.reasons.add("nodes"),!1):(context.workUnits+=1,!0)}function cachedElementState(context,element){let state=context.elementStates.get(element);return state||(state=accessibilityElementState(element,cachedImageMapImage(context,element)),context.elementStates.set(element,state)),state}function cachedImageMapImage(context,element){if(context.imageMapImages.has(element))return context.imageMapImages.get(element);const image=imageMapImageFor(element,{consume:()=>consumeNodeWork(context)});return context.imageMapImages.set(element,image),image}function cachedSubtreeExcluded(context,element){if(context.excludedElements.has(element))return context.excludedElements.get(element);const excluded=context.isSubtreeExcluded?context.isSubtreeExcluded(element):cachedElementState(context,element).subtreeExcluded;return context.excludedElements.set(element,excluded),excluded}function addLabelReferenceRoot(context,node){const root=node.getRootNode();(root.nodeType===9||root.nodeType===11&&"host"in root)&&context.labelReferenceRoots.add(root)}function appendBoundedText(context,value){if(value==="")return;if(context.outputLength>=context.maxCharacters){context.reasons.add("characters"),context.stack.length=0;return}const remaining=context.maxCharacters-context.outputLength;if(value.length>remaining){context.output.push(value.slice(0,remaining)),context.outputLength+=remaining,context.reasons.add("characters"),context.stack.length=0;return}context.output.push(value),context.outputLength+=value.length}function composedAncestorState(context,node){const slottable=node;let branch=node.nodeType===1?node:slottable.assignedSlot??node.parentElement,ancestor=node.nodeType===1?composedParentElement(node):slottable.assignedSlot??node.parentElement,depth=0,inheritedTextVisible=!0,firstAncestor=!0;for(;ancestor;){if(!consumeNodeWork(context))return{available:!1,inheritedTextVisible};const state=cachedElementState(context,ancestor);if(firstAncestor&&(inheritedTextVisible=!state.visibilityHidden,firstAncestor=!1),cachedSubtreeExcluded(context,ancestor)||isClosedDetailsContentBranchBounded(context,ancestor,branch))return{available:!1,inheritedTextVisible};if(ancestor===context.ancestorBoundary)return{available:!0,inheritedTextVisible};if(depth+=1,depth>context.maxDepth)return context.reasons.add("ancestors"),{available:!1,inheritedTextVisible};branch=ancestor,ancestor=composedParentElement(ancestor)}return{available:!0,inheritedTextVisible}}function scheduleNode(context,node,depth,inheritedTextVisible,referenced,available,workCharged=!1){return depth>context.maxDepth?(context.reasons.add("depth"),!1):(context.stack.push({available,depth,inheritedTextVisible,kind:"node",node,referenced,workCharged}),!0)}function scheduleNodeList(context,nodes,depth,inheritedTextVisible,referenced,available){if(nodes.length!==0){if(depth>context.maxDepth){context.reasons.add("depth");return}context.stack.push({available,depth,index:0,inheritedTextVisible,kind:"nodes",nodes,referenced})}}function scheduleRenderedChildNodes(context,element,depth,inheritedTextVisible,referenced,available){if(element.localName==="slot"){const slot=element,root=slot.getRootNode(),candidates=root.nodeType===11&&"host"in root?root.host.childNodes:[];if(depth>context.maxDepth){(candidates.length>0||slot.childNodes.length>0)&&context.reasons.add("depth");return}context.stack.push({available,candidates,depth,fallback:slot.childNodes,foundAssigned:!1,index:0,inheritedTextVisible,kind:"slot",referenced,slot});return}if(element.localName==="details"&&!element.hasAttribute("open")){for(const child of element.children){if(!consumeNodeWork(context))return;if(child.localName==="summary"){scheduleNode(context,child,depth,inheritedTextVisible,referenced,available,!0);return}}return}const shadowRoot=element.shadowRoot,childNodes=shadowRoot?.childNodes??element.childNodes;shadowRoot&&(childNodes.length===0||depth<=context.maxDepth)&&context.traversedShadowRoots.add(shadowRoot),scheduleNodeList(context,childNodes,depth,inheritedTextVisible,referenced,available)}function labelledByElements(context,element){const value=element.getAttribute("aria-labelledby");if(value===null)return{authoritative:!1,elements:[]};addLabelReferenceRoot(context,element);const root=element.getRootNode(),canResolveSerialized=typeof root.getElementById=="function",serializedReferences=[];let sawSerializedToken=!1;for(const id of asciiWhitespaceTokens(value,()=>consumeNodeWork(context))){if(sawSerializedToken=!0,!consumeNodeWork(context))return{authoritative:!0,elements:serializedReferences};const reference=canResolveSerialized?root.getElementById(id):null;reference&&serializedReferences.push(reference)}if(sawSerializedToken)return{authoritative:serializedReferences.length>0,elements:serializedReferences};if(context.workUnits>=context.maxNodes||!consumeNodeWork(context))return context.reasons.add("nodes"),{authoritative:!0,elements:[]};if(context.workUnits>=context.maxNodes)return context.reasons.add("nodes"),{authoritative:!0,elements:[]};try{const ElementConstructor=element.ownerDocument.defaultView?.Element,descriptor=ElementConstructor?Object.getOwnPropertyDescriptor(ElementConstructor.prototype,"ariaLabelledByElements"):void 0,reflected=typeof descriptor?.get=="function"?descriptor.get.call(element):void 0;if(reflected?.length){const result=[];for(let index=0;index<reflected.length&&consumeNodeWork(context);index+=1){const reference=reflected[index];!reference||reference.nodeType!==1||(result.push(reference),addLabelReferenceRoot(context,reference))}return{authoritative:!0,elements:result}}}catch{}return{authoritative:!1,elements:[]}}function isRenderedAccessibilityBranch(context,element,display){const imageMapImage=cachedImageMapImage(context,element);if(imageMapImage)return isRenderedAccessibilityBranch(context,imageMapImage,cachedElementState(context,imageMapImage).display);if(!element.isConnected||display==="contents")return!0;const candidate=element;if(typeof candidate.checkVisibility!="function")return!0;try{return candidate.checkVisibility({contentVisibilityAuto:!0})}catch{return!1}}function processAccessibilityTextWork(context){for(;context.stack.length>0;){const work=context.stack.pop();if(work.kind==="text"){appendBoundedText(context,work.value);continue}if(work.kind==="slot"){if(work.index>=work.candidates.length){work.foundAssigned||scheduleNodeList(context,work.fallback,work.depth,work.inheritedTextVisible,work.referenced,work.available);continue}if(!consumeNodeWork(context)){context.stack.length=0;break}const node=work.candidates[work.index],assigned=!!(node&&node.assignedSlot===work.slot);context.stack.push({...work,foundAssigned:work.foundAssigned||assigned,index:work.index+1}),node&&assigned&&(scheduleNode(context,node,work.depth,work.inheritedTextVisible,work.referenced,work.available,!0),work.foundAssigned&&context.stack.push({kind:"text",value:" "}));continue}if(work.kind==="nodes"){if(work.index>=work.nodes.length)continue;const node=work.nodes[work.index];if(!node)continue;context.stack.push({...work,index:work.index+1}),scheduleNode(context,node,work.depth,work.inheritedTextVisible,work.referenced,work.available),work.index>0&&context.stack.push({kind:"text",value:" "});continue}if(context.visited.has(work.node))continue;if(!work.workCharged&&!consumeNodeWork(context)){context.stack.length=0;break}if(context.visited.add(work.node),context.visitedNodes+=1,!work.referenced&&context.shouldPruneNode?.(work.node))continue;if(work.node.nodeType===3){(work.referenced||work.available&&work.inheritedTextVisible)&&appendBoundedText(context,work.node.textContent??"");continue}if(work.node.nodeType===11){"host"in work.node&&context.traversedShadowRoots.add(work.node),scheduleNodeList(context,work.node.childNodes,work.depth+1,work.inheritedTextVisible,work.referenced,work.available);continue}if(work.node.nodeType!==1)continue;const element=work.node;if(NON_CONTENT_ELEMENTS.has(element.localName)||context.shouldPrune?.(element))continue;const state=cachedElementState(context,element),excluded=cachedSubtreeExcluded(context,element),available=work.referenced||work.available&&!excluded;if(!available||!work.referenced&&context.requireRendered&&!isRenderedAccessibilityBranch(context,element,state.display))continue;const ownTextVisible=work.referenced||!state.visibilityHidden,labelledBy=ownTextVisible?labelledByElements(context,element):{authoritative:!1,elements:[]};if(labelledBy.elements.length>0){for(const reference of labelledBy.elements)context.referencedElements.add(reference);scheduleNodeList(context,labelledBy.elements,work.depth+1,!0,!0,!0);continue}if(labelledBy.authoritative)continue;const ariaLabel=ownTextVisible?element.getAttribute("aria-label"):null;if(ariaLabel?.trim()){appendBoundedText(context,ariaLabel.trim());continue}if(ownTextVisible&&(element.localName==="img"||element.localName==="area")){const alt=element.getAttribute("alt");if(alt?.trim()){appendBoundedText(context,alt.trim());continue}}scheduleRenderedChildNodes(context,element,work.depth+1,ownTextVisible,work.referenced,available)}}function normalizedTextOptions(options){const resolved=typeof options=="boolean"?{inheritedTextVisible:options}:options??{};return{...resolved,inheritedTextVisible:resolved.inheritedTextVisible??!0,maxCharacters:finiteTextLimit(resolved.maxCharacters,DEFAULT_ACCESSIBILITY_TEXT_MAX_CHARACTERS),maxDepth:finiteTextLimit(resolved.maxDepth,DEFAULT_ACCESSIBILITY_TEXT_MAX_DEPTH),maxNodes:finiteTextLimit(resolved.maxNodes,DEFAULT_ACCESSIBILITY_TEXT_MAX_NODES)}}function composedAccessibilityTextResult(input,options){const resolved=normalizedTextOptions(options),context={ancestorBoundary:resolved.ancestorBoundary??null,elementStates:new Map,excludedElements:new Map,imageMapImages:new Map,isSubtreeExcluded:resolved.isSubtreeExcluded,labelReferenceRoots:new Set,maxCharacters:resolved.maxCharacters,maxDepth:resolved.maxDepth,maxNodes:resolved.maxNodes,output:[],outputLength:0,reasons:new Set,referencedElements:new Set,requireRendered:resolved.requireRendered!==!1,shouldPrune:resolved.shouldPrune,shouldPruneNode:resolved.shouldPruneNode,stack:[],traversedShadowRoots:new Set,visited:new Set,visitedNodes:0,workUnits:0};if(context.maxNodes===0)return context.reasons.add("nodes"),{labelReferenceRoots:context.labelReferenceRoots,referencedElements:context.referencedElements,text:"",traversedShadowRoots:context.traversedShadowRoots,truncated:!0,truncationReasons:[...context.reasons],visitedNodes:0};const roots=isNodeValue(input)?[input]:input;let rootCount=0;for(const root of roots){if(!isNodeValue(root))continue;if(context.workUnits>=context.maxNodes){context.reasons.add("nodes");break}if(rootCount>0&&appendBoundedText(context," "),context.reasons.has("characters"))break;const ancestorState=resolved.skipRootAncestorValidation?{available:!0,inheritedTextVisible:!0}:composedAncestorState(context,root);if(scheduleNode(context,root,0,resolved.inheritedTextVisible&&ancestorState.inheritedTextVisible,!1,ancestorState.available),processAccessibilityTextWork(context),rootCount+=1,context.reasons.has("characters")||context.reasons.has("nodes")&&context.workUnits>=context.maxNodes)break}return{labelReferenceRoots:context.labelReferenceRoots,referencedElements:context.referencedElements,text:context.output.join(""),traversedShadowRoots:context.traversedShadowRoots,truncated:context.reasons.size>0,truncationReasons:[...context.reasons],visitedNodes:context.visitedNodes}}function composedAccessibilityText(input,options){return composedAccessibilityTextResult(input,options).text}function composedAccessibleVisibleText(node){return composedAccessibilityText(node)}function isClosedDetailsContentBranchWithin(details,branch,consume){if(details.localName!=="details"||details.hasAttribute("open")||branch===null)return!1;let summary=null;for(const child of details.children){if(!consume())return!0;if(child.localName==="summary"){summary=child;break}}return branch!==summary}function isClosedDetailsContentBranchBounded(context,details,branch){if(details.localName!=="details"||details.hasAttribute("open")||branch===null)return!1;for(const child of details.children){if(!consumeNodeWork(context))return!0;if(child.localName==="summary")return child!==branch}return!0}function isAccessibilityVisible(element,options={}){if(!element.isConnected)return!1;const maxDepth=finiteTextLimit(options.maxDepth,DEFAULT_ACCESSIBILITY_TEXT_MAX_DEPTH),maxNodes=finiteTextLimit(options.maxNodes,DEFAULT_ACCESSIBILITY_VISIBILITY_MAX_NODES);let workUnits=0;const consume=()=>workUnits>=maxNodes?!1:(workUnits+=1,!0);let current=element,composedChild=null,depth=0,targetState,renderedSource=element;for(;current;){if(depth>maxDepth||!consume())return!1;const imageMapImage=imageMapImageFor(current,{consume}),state=accessibilityElementState(current,imageMapImage);if(current===element&&(targetState=state,renderedSource=imageMapImage??element),!options.ignorePresentation?.(current)&&(state.subtreeExcluded||isClosedDetailsContentBranchWithin(current,composedChild,consume)||current===element&&state.visibilityHidden))return!1;composedChild=current,current=composedParentElement(current),depth+=1}if(renderedSource!==element)for(current=renderedSource,composedChild=null,depth=0;current;){if(depth>maxDepth||!consume())return!1;const state=accessibilityElementState(current,imageMapImageFor(current,{consume}));if(current===renderedSource&&(targetState=state),!options.ignorePresentation?.(current)&&(state.subtreeExcluded||isClosedDetailsContentBranchWithin(current,composedChild,consume)||current===renderedSource&&state.visibilityHidden))return!1;composedChild=current,current=composedParentElement(current),depth+=1}if(targetState?.display==="contents")return!0;const visibilityTarget=renderedSource;if(!consume())return!1;try{return typeof visibilityTarget.checkVisibility=="function"?visibilityTarget.checkVisibility({contentVisibilityAuto:!0}):!0}catch{return!1}}export{bindAccessibleTextObserver,composedAccessibilityText,composedAccessibilityTextResult,composedAccessibleVisibleText,composedParentElement2 as composedParentElement,isAccessibilityExcluded,isAccessibilitySubtreeExcluded,isAccessibilityVisibilityHidden,isAccessibilityVisible,isAriaTrue};
1
+ import{composedParentElement}from"./active-element.js";import{asciiWhitespaceTokens}from"./ascii-whitespace.js";import{imageMapImageFor}from"./dom-guards.js";import{composedParentElement as composedParentElement2}from"./active-element.js";const NON_CONTENT_ELEMENTS=new Set(["script","style","template"]),DEFAULT_ACCESSIBILITY_TEXT_MAX_CHARACTERS=4096,DEFAULT_ACCESSIBILITY_TEXT_MAX_DEPTH=256,DEFAULT_ACCESSIBILITY_TEXT_MAX_NODES=4096,DEFAULT_ACCESSIBILITY_VISIBILITY_MAX_NODES=512,MAX_CONFIGURED_ACCESSIBILITY_TEXT_LIMIT=1e5;function isAriaTrue(value){return value?.trim().toLowerCase()==="true"}function accessibilityElementState(element,imageMapImage=imageMapImageFor(element)){let rendered;try{rendered=element.ownerDocument.defaultView?.getComputedStyle(element)}catch{}const visibility=rendered?.visibility;return{display:rendered?.display,subtreeExcluded:element.hasAttribute("hidden")||element.hasAttribute("inert")||isAriaTrue(element.getAttribute("aria-hidden"))||!imageMapImage&&(rendered?.display==="none"||rendered?.contentVisibility==="hidden"),visibilityHidden:visibility==="hidden"||visibility==="collapse"}}function isAccessibilitySubtreeExcluded(element){return accessibilityElementState(element).subtreeExcluded}function isAccessibilityVisibilityHidden(element){return accessibilityElementState(element).visibilityHidden}function isAccessibilityExcluded(element){return isAccessibilitySubtreeExcluded(element)||isAccessibilityVisibilityHidden(element)}const CONTENT_NODE_ATTRIBUTES=["alt","aria-hidden","aria-label","aria-labelledby","class","hidden","id","inert","open","style"],ANCESTOR_ATTRIBUTES=["aria-hidden","class","hidden","inert","open","style"];function observeAccessibleTextNode(observer,node,extraAttributes){if(node.nodeType===3){observer.observe(node,{characterData:!0});return}node.nodeType===1&&observer.observe(node,{attributes:!0,attributeFilter:[...new Set([...CONTENT_NODE_ATTRIBUTES,...extraAttributes])],childList:!0,characterData:!0,subtree:!0})}function bindAccessibleTextObserver(observer,host,extraAttributes=[]){if(!observer)return;observer.disconnect(),observeAccessibleTextNode(observer,host,extraAttributes);let ancestor=composedParentElement(host);for(;ancestor;)observer.observe(ancestor,{attributes:!0,attributeFilter:ANCESTOR_ATTRIBUTES}),ancestor=composedParentElement(ancestor);for(const slot of host.querySelectorAll("slot"))for(const assigned of slot.assignedNodes({flatten:!0}))observeAccessibleTextNode(observer,assigned,extraAttributes)}function finiteTextLimit(value,fallback){return Number.isFinite(value)?Math.min(MAX_CONFIGURED_ACCESSIBILITY_TEXT_LIMIT,Math.max(0,Math.floor(value))):fallback}function isNodeValue(value){if(typeof value!="object"&&typeof value!="function"||value===null)return!1;try{return typeof value.nodeType=="number"&&typeof value.getRootNode=="function"}catch{return!1}}function consumeNodeWork(context){return context.workUnits>=context.maxNodes?(context.reasons.add("nodes"),!1):(context.workUnits+=1,!0)}function cachedElementState(context,element){let state=context.elementStates.get(element);return state||(state=accessibilityElementState(element,cachedImageMapImage(context,element)),context.elementStates.set(element,state)),state}function cachedImageMapImage(context,element){if(context.imageMapImages.has(element))return context.imageMapImages.get(element);const image=imageMapImageFor(element,{consume:()=>consumeNodeWork(context)});return context.imageMapImages.set(element,image),image}function cachedSubtreeExcluded(context,element){if(context.excludedElements.has(element))return context.excludedElements.get(element);const excluded=context.isSubtreeExcluded?context.isSubtreeExcluded(element):cachedElementState(context,element).subtreeExcluded;return context.excludedElements.set(element,excluded),excluded}function addLabelReferenceRoot(context,node){const root=node.getRootNode();(root.nodeType===9||root.nodeType===11&&"host"in root)&&context.labelReferenceRoots.add(root)}function appendBoundedText(context,value){if(value==="")return;if(context.outputLength>=context.maxCharacters){context.reasons.add("characters"),context.stack.length=0;return}const remaining=context.maxCharacters-context.outputLength;if(value.length>remaining){context.output.push(value.slice(0,remaining)),context.outputLength+=remaining,context.reasons.add("characters"),context.stack.length=0;return}context.output.push(value),context.outputLength+=value.length}function composedAncestorState(context,node){const slottable=node;let branch=node.nodeType===1?node:slottable.assignedSlot??node.parentElement,ancestor=node.nodeType===1?composedParentElement(node):slottable.assignedSlot??node.parentElement,depth=0,inheritedTextVisible=!0,firstAncestor=!0;for(;ancestor;){if(!consumeNodeWork(context))return{available:!1,inheritedTextVisible};const state=cachedElementState(context,ancestor);if(firstAncestor&&(inheritedTextVisible=!state.visibilityHidden,firstAncestor=!1),cachedSubtreeExcluded(context,ancestor)||isClosedDetailsContentBranchBounded(context,ancestor,branch))return{available:!1,inheritedTextVisible};if(ancestor===context.ancestorBoundary)return{available:!0,inheritedTextVisible};if(depth+=1,depth>context.maxDepth)return context.reasons.add("ancestors"),{available:!1,inheritedTextVisible};branch=ancestor,ancestor=composedParentElement(ancestor)}return{available:!0,inheritedTextVisible}}function inheritedVisibilityHidden(context,node){const slottable=node,ancestor=node.nodeType===1?composedParentElement(node):slottable.assignedSlot??node.parentElement;return ancestor?cachedElementState(context,ancestor).visibilityHidden:!1}function scheduleNode(context,node,depth,inheritedTextVisible,referenced,available,workCharged=!1){return depth>context.maxDepth?(context.reasons.add("depth"),!1):(context.stack.push({available,depth,inheritedTextVisible,kind:"node",node,referenced,workCharged}),!0)}function scheduleNodeList(context,nodes,depth,inheritedTextVisible,referenced,available){if(nodes.length!==0){if(depth>context.maxDepth){context.reasons.add("depth");return}context.stack.push({available,depth,index:0,inheritedTextVisible,kind:"nodes",nodes,referenced})}}function scheduleRenderedChildNodes(context,element,depth,inheritedTextVisible,referenced,available){if(element.localName==="slot"){const slot=element,root=slot.getRootNode(),candidates=root.nodeType===11&&"host"in root?root.host.childNodes:[];if(depth>context.maxDepth){(candidates.length>0||slot.childNodes.length>0)&&context.reasons.add("depth");return}context.stack.push({available,candidates,depth,fallback:slot.childNodes,foundAssigned:!1,index:0,inheritedTextVisible,kind:"slot",referenced,slot});return}if(element.localName==="details"&&!element.hasAttribute("open")){for(const child of element.children){if(!consumeNodeWork(context))return;if(child.localName==="summary"){scheduleNode(context,child,depth,inheritedTextVisible,referenced,available,!0);return}}return}const shadowRoot=element.shadowRoot,childNodes=shadowRoot?.childNodes??element.childNodes;shadowRoot&&(childNodes.length===0||depth<=context.maxDepth)&&context.traversedShadowRoots.add(shadowRoot),scheduleNodeList(context,childNodes,depth,inheritedTextVisible,referenced,available)}function labelledByElements(context,element){const value=element.getAttribute("aria-labelledby");if(value===null)return{authoritative:!1,elements:[]};addLabelReferenceRoot(context,element);const root=element.getRootNode(),canResolveSerialized=typeof root.getElementById=="function",serializedReferences=[];let sawSerializedToken=!1;for(const id of asciiWhitespaceTokens(value,()=>consumeNodeWork(context))){if(sawSerializedToken=!0,!consumeNodeWork(context))return{authoritative:!0,elements:serializedReferences};const reference=canResolveSerialized?root.getElementById(id):null;reference&&serializedReferences.push(reference)}if(sawSerializedToken)return{authoritative:serializedReferences.length>0,elements:serializedReferences};if(context.workUnits>=context.maxNodes||!consumeNodeWork(context))return context.reasons.add("nodes"),{authoritative:!0,elements:[]};if(context.workUnits>=context.maxNodes)return context.reasons.add("nodes"),{authoritative:!0,elements:[]};try{const ElementConstructor=element.ownerDocument.defaultView?.Element,descriptor=ElementConstructor?Object.getOwnPropertyDescriptor(ElementConstructor.prototype,"ariaLabelledByElements"):void 0,reflected=typeof descriptor?.get=="function"?descriptor.get.call(element):void 0;if(reflected?.length){const result=[];for(let index=0;index<reflected.length&&consumeNodeWork(context);index+=1){const reference=reflected[index];!reference||reference.nodeType!==1||(result.push(reference),addLabelReferenceRoot(context,reference))}return{authoritative:!0,elements:result}}}catch{}return{authoritative:!1,elements:[]}}function isRenderedAccessibilityBranch(context,element,display){const imageMapImage=cachedImageMapImage(context,element);if(imageMapImage)return isRenderedAccessibilityBranch(context,imageMapImage,cachedElementState(context,imageMapImage).display);if(!element.isConnected||display==="contents")return!0;const candidate=element;if(typeof candidate.checkVisibility!="function")return!0;try{return candidate.checkVisibility({contentVisibilityAuto:!0})}catch{return!1}}function processAccessibilityTextWork(context){for(;context.stack.length>0;){const work=context.stack.pop();if(work.kind==="text"){appendBoundedText(context,work.value);continue}if(work.kind==="slot"){if(work.index>=work.candidates.length){work.foundAssigned||scheduleNodeList(context,work.fallback,work.depth,work.inheritedTextVisible,work.referenced,work.available);continue}if(!consumeNodeWork(context)){context.stack.length=0;break}const node=work.candidates[work.index],assigned=!!(node&&node.assignedSlot===work.slot);context.stack.push({...work,foundAssigned:work.foundAssigned||assigned,index:work.index+1}),node&&assigned&&(scheduleNode(context,node,work.depth,work.inheritedTextVisible,work.referenced,work.available,!0),work.foundAssigned&&context.stack.push({kind:"text",value:" "}));continue}if(work.kind==="nodes"){if(work.index>=work.nodes.length)continue;const node=work.nodes[work.index];if(!node)continue;context.stack.push({...work,index:work.index+1}),scheduleNode(context,node,work.depth,work.inheritedTextVisible,work.referenced,work.available),work.index>0&&context.stack.push({kind:"text",value:" "});continue}if(context.visited.has(work.node))continue;if(!work.workCharged&&!consumeNodeWork(context)){context.stack.length=0;break}if(context.visited.add(work.node),context.visitedNodes+=1,!work.referenced&&context.shouldPruneNode?.(work.node))continue;if(work.node.nodeType===3){(work.referenced||work.available&&work.inheritedTextVisible)&&appendBoundedText(context,work.node.textContent??"");continue}if(work.node.nodeType===11){"host"in work.node&&context.traversedShadowRoots.add(work.node),scheduleNodeList(context,work.node.childNodes,work.depth+1,work.inheritedTextVisible,work.referenced,work.available);continue}if(work.node.nodeType!==1)continue;const element=work.node;if(NON_CONTENT_ELEMENTS.has(element.localName)||context.shouldPrune?.(element))continue;const state=cachedElementState(context,element),excluded=cachedSubtreeExcluded(context,element),available=work.referenced||work.available&&!excluded;if(!available||!work.referenced&&context.requireRendered&&!isRenderedAccessibilityBranch(context,element,state.display))continue;const ownTextVisible=work.referenced||!state.visibilityHidden||context.visibilityBaselineHidden,labelledBy=ownTextVisible?labelledByElements(context,element):{authoritative:!1,elements:[]};if(labelledBy.elements.length>0){for(const reference of labelledBy.elements)context.referencedElements.add(reference);scheduleNodeList(context,labelledBy.elements,work.depth+1,!0,!0,!0);continue}if(labelledBy.authoritative)continue;const ariaLabel=ownTextVisible?element.getAttribute("aria-label"):null;if(ariaLabel?.trim()){appendBoundedText(context,ariaLabel.trim());continue}if(ownTextVisible&&(element.localName==="img"||element.localName==="area")){const alt=element.getAttribute("alt");if(alt?.trim()){appendBoundedText(context,alt.trim());continue}}scheduleRenderedChildNodes(context,element,work.depth+1,ownTextVisible,work.referenced,available)}}function normalizedTextOptions(options){const resolved=typeof options=="boolean"?{inheritedTextVisible:options}:options??{};return{...resolved,inheritedTextVisible:resolved.inheritedTextVisible??!0,maxCharacters:finiteTextLimit(resolved.maxCharacters,DEFAULT_ACCESSIBILITY_TEXT_MAX_CHARACTERS),maxDepth:finiteTextLimit(resolved.maxDepth,DEFAULT_ACCESSIBILITY_TEXT_MAX_DEPTH),maxNodes:finiteTextLimit(resolved.maxNodes,DEFAULT_ACCESSIBILITY_TEXT_MAX_NODES)}}function composedAccessibilityTextResult(input,options){const resolved=normalizedTextOptions(options),context={ancestorBoundary:resolved.ancestorBoundary??null,elementStates:new Map,excludedElements:new Map,imageMapImages:new Map,isSubtreeExcluded:resolved.isSubtreeExcluded,labelReferenceRoots:new Set,maxCharacters:resolved.maxCharacters,maxDepth:resolved.maxDepth,maxNodes:resolved.maxNodes,output:[],outputLength:0,reasons:new Set,referencedElements:new Set,requireRendered:resolved.requireRendered!==!1,shouldPrune:resolved.shouldPrune,shouldPruneNode:resolved.shouldPruneNode,stack:[],traversedShadowRoots:new Set,visibilityBaselineHidden:!1,visited:new Set,visitedNodes:0,workUnits:0};if(context.maxNodes===0)return context.reasons.add("nodes"),{labelReferenceRoots:context.labelReferenceRoots,referencedElements:context.referencedElements,text:"",traversedShadowRoots:context.traversedShadowRoots,truncated:!0,truncationReasons:[...context.reasons],visitedNodes:0};const roots=isNodeValue(input)?[input]:input;let rootCount=0;for(const root of roots){if(!isNodeValue(root))continue;if(context.workUnits>=context.maxNodes){context.reasons.add("nodes");break}if(rootCount>0&&appendBoundedText(context," "),context.reasons.has("characters"))break;const validated=resolved.skipRootAncestorValidation?{available:!0,inheritedTextVisible:!0}:composedAncestorState(context,root),ignoreInheritedVisibility=resolved.skipRootAncestorValidation===!0||resolved.ignoreInheritedVisibility===!0;context.visibilityBaselineHidden=ignoreInheritedVisibility&&inheritedVisibilityHidden(context,root);const ancestorState=context.visibilityBaselineHidden?{available:validated.available,inheritedTextVisible:!0}:validated;if(scheduleNode(context,root,0,resolved.inheritedTextVisible&&ancestorState.inheritedTextVisible,!1,ancestorState.available),processAccessibilityTextWork(context),rootCount+=1,context.reasons.has("characters")||context.reasons.has("nodes")&&context.workUnits>=context.maxNodes)break}return{labelReferenceRoots:context.labelReferenceRoots,referencedElements:context.referencedElements,text:context.output.join(""),traversedShadowRoots:context.traversedShadowRoots,truncated:context.reasons.size>0,truncationReasons:[...context.reasons],visitedNodes:context.visitedNodes}}function composedAccessibilityText(input,options){return composedAccessibilityTextResult(input,options).text}function composedAccessibleVisibleText(node){return composedAccessibilityText(node)}function isClosedDetailsContentBranchWithin(details,branch,consume){if(details.localName!=="details"||details.hasAttribute("open")||branch===null)return!1;let summary=null;for(const child of details.children){if(!consume())return!0;if(child.localName==="summary"){summary=child;break}}return branch!==summary}function isClosedDetailsContentBranchBounded(context,details,branch){if(details.localName!=="details"||details.hasAttribute("open")||branch===null)return!1;for(const child of details.children){if(!consumeNodeWork(context))return!0;if(child.localName==="summary")return child!==branch}return!0}function isAccessibilityVisible(element,options={}){if(!element.isConnected)return!1;const maxDepth=finiteTextLimit(options.maxDepth,DEFAULT_ACCESSIBILITY_TEXT_MAX_DEPTH),maxNodes=finiteTextLimit(options.maxNodes,DEFAULT_ACCESSIBILITY_VISIBILITY_MAX_NODES);let workUnits=0;const consume=()=>workUnits>=maxNodes?!1:(workUnits+=1,!0);let current=element,composedChild=null,depth=0,targetState,renderedSource=element;for(;current;){if(depth>maxDepth||!consume())return!1;const imageMapImage=imageMapImageFor(current,{consume}),state=accessibilityElementState(current,imageMapImage);if(current===element&&(targetState=state,renderedSource=imageMapImage??element),!options.ignorePresentation?.(current)&&(state.subtreeExcluded||isClosedDetailsContentBranchWithin(current,composedChild,consume)||current===element&&state.visibilityHidden))return!1;composedChild=current,current=composedParentElement(current),depth+=1}if(renderedSource!==element)for(current=renderedSource,composedChild=null,depth=0;current;){if(depth>maxDepth||!consume())return!1;const state=accessibilityElementState(current,imageMapImageFor(current,{consume}));if(current===renderedSource&&(targetState=state),!options.ignorePresentation?.(current)&&(state.subtreeExcluded||isClosedDetailsContentBranchWithin(current,composedChild,consume)||current===renderedSource&&state.visibilityHidden))return!1;composedChild=current,current=composedParentElement(current),depth+=1}if(targetState?.display==="contents")return!0;const visibilityTarget=renderedSource;if(!consume())return!1;try{return typeof visibilityTarget.checkVisibility=="function"?visibilityTarget.checkVisibility({contentVisibilityAuto:!0}):!0}catch{return!1}}export{bindAccessibleTextObserver,composedAccessibilityText,composedAccessibilityTextResult,composedAccessibleVisibleText,composedParentElement2 as composedParentElement,isAccessibilityExcluded,isAccessibilitySubtreeExcluded,isAccessibilityVisibilityHidden,isAccessibilityVisible,isAriaTrue};
@@ -2,4 +2,4 @@
2
2
  * Generated from package.json by scripts/generate-package-metadata.mjs.
3
3
  * Run `pnpm package-metadata` after changing package identity or version.
4
4
  */
5
- export declare const LYRA_PACKAGE_NAME:'@aceshooting/lyra-ui';export declare const LYRA_PACKAGE_VERSION:'14.3.1';
5
+ export declare const LYRA_PACKAGE_NAME:'@aceshooting/lyra-ui';export declare const LYRA_PACKAGE_VERSION:'14.3.2';
@@ -1 +1 @@
1
- const LYRA_PACKAGE_NAME="@aceshooting/lyra-ui",LYRA_PACKAGE_VERSION="14.3.1";export{LYRA_PACKAGE_NAME,LYRA_PACKAGE_VERSION};
1
+ const LYRA_PACKAGE_NAME="@aceshooting/lyra-ui",LYRA_PACKAGE_VERSION="14.3.2";export{LYRA_PACKAGE_NAME,LYRA_PACKAGE_VERSION};
@@ -112,6 +112,13 @@ A focusable action row owned by `<lr-menu>`. The host itself carries `role="menu
112
112
  - `closeSubmenu(): Promise<void>`
113
113
  - `getTextLabel(): string` returns the accessibility-visible label used by type-ahead
114
114
 
115
+ The computed name is derived from the row's own visible label and does not depend on whether the
116
+ menu is currently displayed, so a row inside a closed dropdown — whose popup is `visibility:
117
+ hidden` — is named the same as an open one, and `getTextLabel()` drives type-ahead either way.
118
+ A row with no label text carries **no** `aria-label` attribute rather than an empty one, so the
119
+ browser falls back to the row's own content; an `aria-label` or `aria-labelledby` you set yourself,
120
+ including an explicitly empty value, still wins.
121
+
115
122
  A checkbox activation first emits cancelable `lr-menu-item-change` with the proposed
116
123
  `detail: { value, checked }`. Preventing that event retains the current checked state; the owning
117
124
  menu's canonical `lr-select` still follows. A submenu parent is a disclosure instead of an action:
@@ -112,6 +112,13 @@ A focusable action row owned by `<lr-menu>`. The host itself carries `role="menu
112
112
  - `closeSubmenu(): Promise<void>`
113
113
  - `getTextLabel(): string` returns the accessibility-visible label used by type-ahead
114
114
 
115
+ The computed name is derived from the row's own visible label and does not depend on whether the
116
+ menu is currently displayed, so a row inside a closed dropdown — whose popup is `visibility:
117
+ hidden` — is named the same as an open one, and `getTextLabel()` drives type-ahead either way.
118
+ A row with no label text carries **no** `aria-label` attribute rather than an empty one, so the
119
+ browser falls back to the row's own content; an `aria-label` or `aria-labelledby` you set yourself,
120
+ including an explicitly empty value, still wins.
121
+
115
122
  A checkbox activation first emits cancelable `lr-menu-item-change` with the proposed
116
123
  `detail: { value, checked }`. Preventing that event retains the current checked state; the owning
117
124
  menu's canonical `lr-select` still follows. A submenu parent is a disclosure instead of an action:
@@ -112,6 +112,13 @@ A focusable action row owned by `<lr-menu>`. The host itself carries `role="menu
112
112
  - `closeSubmenu(): Promise<void>`
113
113
  - `getTextLabel(): string` returns the accessibility-visible label used by type-ahead
114
114
 
115
+ The computed name is derived from the row's own visible label and does not depend on whether the
116
+ menu is currently displayed, so a row inside a closed dropdown — whose popup is `visibility:
117
+ hidden` — is named the same as an open one, and `getTextLabel()` drives type-ahead either way.
118
+ A row with no label text carries **no** `aria-label` attribute rather than an empty one, so the
119
+ browser falls back to the row's own content; an `aria-label` or `aria-labelledby` you set yourself,
120
+ including an explicitly empty value, still wins.
121
+
115
122
  A checkbox activation first emits cancelable `lr-menu-item-change` with the proposed
116
123
  `detail: { value, checked }`. Preventing that event retains the current checked state; the owning
117
124
  menu's canonical `lr-select` still follows. A submenu parent is a disclosure instead of an action:
package/llms-full.txt CHANGED
@@ -16833,6 +16833,13 @@ A focusable action row owned by `<lr-menu>`. The host itself carries `role="menu
16833
16833
  - `closeSubmenu(): Promise<void>`
16834
16834
  - `getTextLabel(): string` returns the accessibility-visible label used by type-ahead
16835
16835
 
16836
+ The computed name is derived from the row's own visible label and does not depend on whether the
16837
+ menu is currently displayed, so a row inside a closed dropdown — whose popup is `visibility:
16838
+ hidden` — is named the same as an open one, and `getTextLabel()` drives type-ahead either way.
16839
+ A row with no label text carries **no** `aria-label` attribute rather than an empty one, so the
16840
+ browser falls back to the row's own content; an `aria-label` or `aria-labelledby` you set yourself,
16841
+ including an explicitly empty value, still wins.
16842
+
16836
16843
  A checkbox activation first emits cancelable `lr-menu-item-change` with the proposed
16837
16844
  `detail: { value, checked }`. Preventing that event retains the current checked state; the owning
16838
16845
  menu's canonical `lr-select` still follows. A submenu parent is a disclosure instead of an action:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aceshooting/lyra-ui",
3
- "version": "14.3.1",
3
+ "version": "14.3.2",
4
4
  "description": "Free, independent Lit web components: an open-source alternative to Shoelace and Web Awesome with accessible forms, dashboards, charts, and agent UI.",
5
5
  "keywords": [
6
6
  "web-components",