@aceshooting/lyra-ui 31.1.1 → 31.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/dist/components/data/tree/tree-data-expansion.js +1 -0
- package/dist/components/data/tree/tree-item.class.d.ts +10 -4
- package/dist/components/data/tree/tree-item.class.js +5 -2
- package/dist/components/data/tree/tree-item.styles.js +1 -1
- package/dist/components/data/tree/tree-owner-controller.js +1 -1
- package/dist/components/data/tree/tree-pointer-reorder.js +1 -0
- package/dist/components/data/tree/tree-types.d.ts +5 -1
- package/dist/components/data/tree/tree.class.d.ts +27 -9
- package/dist/components/data/tree/tree.class.js +5 -3
- package/dist/components/data/tree/tree.styles.js +1 -1
- package/dist/components/forms/select/select.class.js +1 -1
- package/dist/events.d.ts +10 -1
- package/dist/framework-types.d.ts +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/sizes.styles.js +1 -1
- package/dist/lyra.d.ts +1 -1
- package/llms/components/lr-tree-item.md +1 -1
- package/llms/components/lr-tree.md +59 -7
- package/llms/peers.md +1 -1
- package/llms/shared/ai-and-peers.md +10 -1
- package/llms/shared.md +10 -1
- package/locales.json +1 -1
- package/package.json +3 -3
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{HierarchySourceController,hierarchyField,hierarchyKey,hierarchyText}from"../../../internal/hierarchy-source-controller.js";import{hierarchySourceView}from"../../../internal/hierarchy-source-view.js";import{hierarchySourceStyles}from"../../../internal/hierarchy-source-view.styles.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{inheritedPreference,preferenceMediaMatches}from"../../../internal/preferences.js";import{finiteCount}from"../../../internal/numbers.js";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{tag}from"../../../internal/prefix.js";import{resolveListMove}from"../../../internal/list-navigation.js";import{styles}from"./tree.styles.js";import{cascadeUpdateComplete}from"./update-cascade.js";import{configureTreeItemOwner,withTreeItemMotionPreference,fromInteractiveDescendant,setTreeItemSelection,treeItemOwnerContext}from"./tree-owner-controller.js";import"./tree-item.class.js";import{TREE_MAX_RENDER_DEPTH,TREE_MAX_RENDER_NODES}from"./tree-types.js";import{composedParentElement,deepActiveElementIn}from"../../../internal/active-element.js";import{LYRA_DEFAULT_treeLimit}from"../../../internal/default-strings/data.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_expand,LYRA_DEFAULT_loading,LYRA_DEFAULT_noData,LYRA_DEFAULT_retry,LYRA_DEFAULT_treeNodeMoved,LYRA_DEFAULT_treeSourceError,LYRA_DEFAULT_treeSourceSummary}from"../../../internal/default-strings/shared.generated.js";const TREE_SELECTIONS=new Set(["single","multiple","leaf","leaf-multiple"]),TREE_BADGE_LIMIT=100,TREE_MAX_INSPECTED_POSITIONS=1e4,EMPTY_TREE_DATA=Object.freeze([]);function ownValue(record,key){try{const descriptor=Object.getOwnPropertyDescriptor(record,key);return descriptor&&"value"in descriptor?descriptor.value:void 0}catch{return}}function arrayLength(value){if(!Array.isArray(value))return 0;try{return Math.max(0,Math.min(Number.MAX_SAFE_INTEGER,Math.trunc(value.length)))}catch{return 0}}function normalizeBadges(value){if(!Array.isArray(value))return{truncated:value!==void 0};const badges=[],length=arrayLength(value);for(let index=0;index<Math.min(length,TREE_BADGE_LIMIT);index++){const raw=ownValue(value,String(index));if(!raw||typeof raw!="object"||Array.isArray(raw))continue;const text=ownValue(raw,"text");if(typeof text!="string")continue;const rawTone=ownValue(raw,"tone"),tone=rawTone==="brand"||rawTone==="success"||rawTone==="warning"||rawTone==="danger"?rawTone:"neutral",rawLabel=ownValue(raw,"label");badges.push(Object.freeze({text,tone,...typeof rawLabel=="string"?{label:rawLabel}:{}}))}return{badges:Object.freeze(badges),truncated:length>TREE_BADGE_LIMIT}}function sameIcon(left,right){if(Object.is(left,right))return!0;const a=left,b=right;if(!a||!b||typeof a!="object"||typeof b!="object"||a._$litType$===void 0||a._$litType$!==b._$litType$||a.strings!==b.strings)return!1;const leftValues=a.values??[],rightValues=b.values??[];return leftValues.length===rightValues.length&&leftValues.every((value,index)=>Object.is(value,rightValues[index]))}function sameBadges(left,right){return left===right?!0:!left||!right||left.length!==right.length?!1:left.every((badge,index)=>{const other=right[index];return badge.text===other.text&&badge.tone===other.tone&&badge.label===other.label})}function sameTreeNode(next,previous){if(next.id!==previous.id||next.label!==previous.label||next.selected!==previous.selected||next.disabled!==previous.disabled||next.lazy!==previous.lazy||next.description!==previous.description||next.accessibleLabel!==previous.accessibleLabel||!sameIcon(next.icon,previous.icon)||!sameBadges(next.badges,previous.badges))return!1;const children=next.children,previousChildren=previous.children;return!children||!previousChildren?children===void 0&&previousChildren===void 0:children.length===previousChildren.length&&children.every((child,index)=>child===previousChildren[index])}function indexTreeNodes(nodes){const byId=new Map,stack=[...nodes];for(;stack.length>0;){const node=stack.pop();byId.set(node.id,node),node.children&&stack.push(...node.children)}return byId}function normalizeTreeData(input,previous=EMPTY_TREE_DATA,limit=TREE_MAX_RENDER_NODES){if(!Array.isArray(input))return{data:EMPTY_TREE_DATA,declaredChildrenAtPath:new Map,declaredRootCount:0,truncated:input!=null,limitReached:!1};const root=[],declaredChildrenAtPath=new Map,created=[],rootLength=arrayLength(input);let truncated=!1,limitReached=!1,accepted=0,inspected=0;const seenIds=new Set,identityFilteredCollections=new Set,jobs=[{source:input,index:0,length:rootLength,target:root,parentPath:"",depth:0,ancestors:new Set}];for(;jobs.length>0;){const job=jobs[jobs.length-1];if(job.index>=job.length){jobs.pop();continue}if(accepted>=limit||inspected>=TREE_MAX_INSPECTED_POSITIONS){truncated=!0,limitReached=accepted>=limit;break}const raw=ownValue(job.source,String(job.index++));if(inspected++,inspected===TREE_MAX_INSPECTED_POSITIONS&&(truncated=!0),!raw||typeof raw!="object"||Array.isArray(raw)){truncated=!0,identityFilteredCollections.add(job.target);continue}const id=ownValue(raw,"id"),label=ownValue(raw,"label");if(typeof id!="string"||id.trim()===""||seenIds.has(id)||typeof label!="string"){truncated=!0,identityFilteredCollections.add(job.target);continue}seenIds.add(id);const node={id,label},selected=ownValue(raw,"selected"),disabled=ownValue(raw,"disabled"),lazy=ownValue(raw,"lazy");typeof selected=="boolean"&&(node.selected=selected),typeof disabled=="boolean"&&(node.disabled=disabled),typeof lazy=="boolean"&&(node.lazy=lazy);const icon=ownValue(raw,"icon");icon!==void 0&&(node.icon=icon);const description=ownValue(raw,"description");typeof description=="string"&&(node.description=description);const accessibleLabel=ownValue(raw,"accessibleLabel");typeof accessibleLabel=="string"&&(node.accessibleLabel=accessibleLabel);const normalizedBadges=normalizeBadges(ownValue(raw,"badges"));normalizedBadges.badges?.length&&(node.badges=normalizedBadges.badges),truncated||=normalizedBadges.truncated;const ownIndex=job.target.length,path=job.parentPath===""?String(ownIndex):`${job.parentPath}/${ownIndex}`;job.target.push(node),created.push(node),accepted++;const rawChildren=ownValue(raw,"children"),childCount=arrayLength(rawChildren);if(childCount===0)continue;if(declaredChildrenAtPath.set(path,childCount),job.depth>=TREE_MAX_RENDER_DEPTH||job.ancestors.has(raw)){truncated=!0;continue}const children=[];node.children=children;const ancestors=new Set(job.ancestors);ancestors.add(raw),jobs.push({source:rawChildren,index:0,length:childCount,target:children,parentPath:path,depth:job.depth+1,ancestors})}const previousById=previous.length>0?indexTreeNodes(previous):void 0,resolved=new Map,resolve=node=>resolved.get(node)??node;for(let index=created.length-1;index>=0;index--){const node=created[index];if(node.children){for(let child=0;child<node.children.length;child++)node.children[child]=resolve(node.children[child]);Object.freeze(node.children)}Object.freeze(node);const prior=previousById?.get(node.id);prior&&!(node.children&&identityFilteredCollections.has(node.children))&&sameTreeNode(node,prior)&&resolved.set(node,prior)}for(let index=0;index<root.length;index++)root[index]=resolve(root[index]);const normalizedJobs=root.map((node,index)=>({node,path:String(index)}));for(;normalizedJobs.length>0;){const{node,path}=normalizedJobs.pop(),children=node.children??[];identityFilteredCollections.has(children)&&declaredChildrenAtPath.set(path,children.length);for(let index=children.length-1;index>=0;index--)normalizedJobs.push({node:children[index],path:`${path}/${index}`})}return{data:Object.freeze(root),declaredChildrenAtPath,declaredRootCount:identityFilteredCollections.has(root)?root.length:rootLength,truncated,limitReached}}function isInertWithin(node,root){for(let current=node;current&¤t!==root;current=current.parentElement)if(current.hasAttribute("inert"))return!0;return!1}class LyraTree extends LyraElement{constructor(){super(...arguments),this._treeSource=void 0,this.sourceMode=!1,this.sourcePaintVersion=0,this.sourceAnnouncer=new AnnouncementSinkController(this),this.hierarchy=new HierarchySourceController(this,{normalize:(value,key)=>this.normalizeSourceValue(value,key),onChange:()=>{const previous=this.sourcePaintVersion++;this.requestUpdate("sourcePaintVersion",previous)},accepted:(action,_row,state2)=>{action.type==="select"&&this.emit("lr-source-selection-change",Object.freeze({key:action.key,selected:action.selected,scope:action.scope,state:state2}))}}),this._data=EMPTY_TREE_DATA,this.lastDataInput=void 0,this.lastDataLimit=0,this.declaredChildrenAtPath=new Map,this.declaredRootCount=0,this._dataTruncated=!1,this._limitReached=!1,this.label="",this.maxNodes=1e3,this.reorderable=!1,this._selection="single",this._activeId=null,this.readActiveId=()=>this._activeId,this.hasAuthoredItems=!1,this.pendingFocusId=null,this.generatedNodes=new WeakSet,this.dataIdOwnerPaths=new Map,this.dataIdCollisions=new Set,this.selectionSyncPending=!0,this.dataSyncPending=!1,this.inertMutationPending=!1,this.dirtyConfigureRoots=new Set,this.lastFocusedNodeId=null,this.onTreeFocusIn=e=>{const path=e.composedPath(),owner=path.find(target=>target.localName===tag("tree"));if(owner&&owner!==this)return;const item=path.find(target=>target.nodeType===1&&target.localName===tag("tree-item"));item&&this.onItemFocus(item)},this.onItemFocus=element=>{const item=element;this.isNavigable(item)&&(this.lastFocusedNodeId=item.nodeId,this.setActiveNode(item))},this.contextSyncPending=!0,this.bulkExpansions=0,this.syncGeneration=0,this.syncRequested=!1,this.syncRunning=!1,this.requestContextSync=()=>{this.contextSyncPending=!0,this.scheduleTreeSync()},this.onChildrenChanged=()=>{if(this.treeSource!==void 0)return;const wasAuthored=this.hasAuthoredItems;this.refreshAuthoredItems(),wasAuthored&&!this.hasAuthoredItems&&(this.dataSyncPending=!0),this.selectionSyncPending=!0,this.requestUpdate()},this.childObserverGeneration=0,this.onChildMutations=allRecords=>{const records=allRecords.filter(record=>record.type!=="attributes"||record.oldValue!==null!==record.target.hasAttribute(record.attributeName??""));if(records.length!==0){if(records.some(record=>record.attributeName==="inert")&&(this.inertMutationPending=!0),records.every(record=>record.type==="attributes")){const itemTag=tag("tree-item");for(const record of records){const target=record.target;if(!(target instanceof Element)||target.localName!==itemTag)continue;const root=this.rootTreeItemAncestor(target);root&&this.dirtyConfigureRoots.add(root)}}else this.dirtyConfigureRoots.clear();this.onChildrenChanged()}},this.onNodeActivate=e=>{const node=this.eventNode(e);if(!node||node.isDisabled)return;this.selectionSyncPending=!0,this.bulkExpansions>0?this.syncRequested=!0:this.requestUpdate();const expanded=e.detail?.expanded===!0;(this.focusIsWithin(node)||!expanded&&this.activeId!==node.nodeId&&this.subtreeHasId(node,this.activeId))&&this.setActiveNode(node)},this.onNodeSelect=event=>{const node=this.eventNode(event);!node||node.isDisabled||(this.setActiveNode(node),this.updateSelectionFrom(node)&&this.emit("lr-selection-change",Object.freeze({selection:this.selectedItems})))},this.onTreeKeyDown=e=>{const itemTag=tag("tree-item");if(fromInteractiveDescendant(e,target=>target.localName===itemTag))return;const visible=this.visibleNodeElements();if(visible.length===0)return;const currentIndex=visible.findIndex(n=>n.nodeId===this.activeId),current=currentIndex>=0?visible[currentIndex]:visible[0];if(!current)return;if(this.reorderable&&(e.ctrlKey||e.metaKey)&&(e.key==="ArrowUp"||e.key==="ArrowDown")){e.preventDefault(),this.requestReorder(current,e.key==="ArrowDown"?1:-1);return}if(e.altKey)return;const rtl=this.effectiveDirection==="rtl",expandKey=rtl?"ArrowLeft":"ArrowRight",collapseKey=rtl?"ArrowRight":"ArrowLeft",moved=resolveListMove(e.key,{count:visible.length,current:Math.max(currentIndex,0),orientation:"vertical",wrap:!1,clamp:!0});if(moved!==null){e.preventDefault(),this.focusNode(visible[moved]);return}switch(e.key){case expandKey:if(e.preventDefault(),!current.hasChildren)break;if(!current.expanded)current.expand();else{const child=visible[currentIndex+1];child&&treeItemOwnerContext(child).depth>treeItemOwnerContext(current).depth&&this.focusNode(child)}break;case collapseKey:if(e.preventDefault(),current.hasChildren&¤t.expanded)current.collapse();else for(let i=currentIndex-1;i>=0;i--){const sibling=visible[i];if(sibling&&treeItemOwnerContext(sibling).depth<treeItemOwnerContext(current).depth){this.focusNode(sibling);break}}break;case"Enter":case" ":e.preventDefault(),current.select();break;default:return}}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,expand:LYRA_DEFAULT_expand,loading:LYRA_DEFAULT_loading,noData:LYRA_DEFAULT_noData,retry:LYRA_DEFAULT_retry,treeLimit:LYRA_DEFAULT_treeLimit,treeNodeMoved:LYRA_DEFAULT_treeNodeMoved,treeSourceError:LYRA_DEFAULT_treeSourceError,treeSourceSummary:LYRA_DEFAULT_treeSourceSummary}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-selection-change"])}static{this.identityEventDetailProperties=Object.freeze({"lr-selection-change":Object.freeze(["selection"])})}static{this.styles=[LyraElement.styles,styles,hierarchySourceStyles]}get treeSource(){return this._treeSource}set treeSource(value){const previous=this._treeSource;this._treeSource=value,this.hierarchy?.update(value,this.effectiveLocale,!0),this.requestUpdate("treeSource",previous)}revealSourceKey(key){return this.treeSource===void 0?Promise.resolve(!1):this.hierarchy.reveal(key)}normalizeSourceValue(value,key){const id=hierarchyKey(hierarchyField(value,"id"));if(id!==key)throw new TypeError("Hierarchy domain key mismatch");const label=hierarchyText(hierarchyField(value,"label")),description=hierarchyText(hierarchyField(value,"description")),accessibleLabel=hierarchyText(hierarchyField(value,"accessibleLabel")),normalized=normalizeBadges(hierarchyField(value,"badges"));let units=label.length+description.length+accessibleLabel.length;for(const badge of normalized.badges??[])units+=badge.text.length+(badge.label?.length??0);if(normalized.truncated||units>65536)throw new RangeError("Hierarchy display value exceeds its row budget");return Object.freeze({id,label,description,accessibleLabel,icon:hierarchyField(value,"icon"),badges:normalized.badges})}announceSource(){const status=this.hierarchy.error?this.localize("treeSourceError"):this.hierarchy.loading?this.localize("loading"):this.sourceSummary();this.sourceAnnouncement!==void 0&&status!==this.sourceAnnouncement&&this.sourceAnnouncer.announce(status),this.sourceAnnouncement=status,this.hierarchy.rowsObserved&&this.sourceAnnouncer.transition("source-rows",this.hierarchy.rowError?"error":"ready",this.hierarchy.rowError?this.localize("treeSourceError"):"")}sourceSummary(){const projection=this.hierarchy.projection;return projection?this.localize("treeSourceSummary",void 0,{visible:getNumberFormat(this.effectiveLocale).format(projection.rows.count),total:getNumberFormat(this.effectiveLocale).format(projection.total)}):""}get data(){return this._data}set data(value){if((value===this._data||value===this.lastDataInput)&&this.lastDataLimit===this.effectiveMaxNodes)return;this.lastDataInput=value,this.lastDataLimit=this.effectiveMaxNodes,this.hasUpdated&&this.selectionBeforeRefresh===void 0&&(this.selectionBeforeRefresh=this.selectedItems.map(item=>item.nodeId));const previous=this._data,normalized=normalizeTreeData(value,this._data,this.effectiveMaxNodes);this._data=normalized.data,this.declaredChildrenAtPath=normalized.declaredChildrenAtPath,this.declaredRootCount=normalized.declaredRootCount,this._dataTruncated=normalized.truncated,this._limitReached=normalized.limitReached,this.requestUpdate("data",previous)}get dataTruncated(){return this._dataTruncated}get effectiveMaxNodes(){return Math.max(1,Math.min(1e4,finiteCount(this.maxNodes,1e3)))}get selection(){return this._selection}set selection(value){const old=this._selection,normalized=TREE_SELECTIONS.has(value)?value:"single";old!==normalized&&(this._selection=normalized,this.selectionSyncPending=!0,this.requestUpdate("selection",old))}get activeId(){return this._activeId}set activeId(value){value!==this._activeId&&(this.activeNode&&(this.activeNode.tabIndex=-1),this.activeNode=void 0,this._activeId=value)}setActiveNode(node){this.activeId=node?.nodeId??null,this.activeNode!==node&&this.activeNode&&(this.activeNode.tabIndex=-1),this.activeNode=node,node&&(node.tabIndex=this.isNavigable(node)?0:-1)}get nodeWalkLimit(){return this.hasAuthoredItems?Number.POSITIVE_INFINITY:this.effectiveMaxNodes}get nodeElements(){return[...this.querySelectorAll(`:scope > ${tag("tree-item")}`)]}childrenOf(node){return node.childItems()}isNavigable(node){return!node.isDisabled&&!isInertWithin(node,this)}allNodeElements(){const result=[],seen=new Set,stack=this.nodeElements.map(node=>({node,depth:0})).reverse();for(;stack.length>0&&result.length<this.nodeWalkLimit;){const{node,depth}=stack.pop();if(seen.has(node)||(seen.add(node),result.push(node),depth>=TREE_MAX_RENDER_DEPTH))continue;const children=this.childrenOf(node);for(let index=children.length-1;index>=0;index--)stack.push({node:children[index],depth:depth+1})}return result}get selectedItems(){return this.treeSource!==void 0?Object.freeze([]):Object.freeze(this.allNodeElements().filter(node=>node.selected))}iconSource(name){return this.querySelector(`:scope > [slot="${name}"]`)}applyTreeContext(){const expandIcon=this.iconSource("expand-icon"),collapseIcon=this.iconSource("collapse-icon"),roots=this.nodeElements,rootCount=this.hasAuthoredItems?roots.length:this.declaredRootCount,stack=[];for(let index=roots.length-1;index>=0;index--)stack.push({node:roots[index],ancestry:[],depth:0,setSize:rootCount,posInSet:index+1,identity:this.hasAuthoredItems?void 0:this.treeIdentityAt(String(index))});const seen=new Set;for(;stack.length>0&&seen.size<this.nodeWalkLimit;){const frame=stack.pop();if(seen.has(frame.node)||(seen.add(frame.node),frame.node.nodeId===this.activeId&&this.setActiveNode(frame.node),configureTreeItemOwner(frame.node,{...treeItemOwnerContext(frame.node),activeId:null,activeNodeId:this.readActiveId,ancestry:frame.ancestry,depth:frame.depth,setSize:frame.setSize,posInSet:frame.posInSet,selection:this.selection,ownsSelection:!0,identity:frame.identity,expandIcon,collapseIcon,syncOwner:this.requestContextSync,focusOwner:this.onItemFocus}),frame.depth>=TREE_MAX_RENDER_DEPTH))continue;const children=this.childrenOf(frame.node),declaredCount=frame.identity?.declaredChildrenAtPath.get(frame.identity.path)??frame.node.item?.children?.length??children.length,childAncestry=frame.node.item?[...frame.ancestry,frame.node.item]:frame.ancestry;for(let index=children.length-1;index>=0;index--){const identity=frame.identity?{path:`${frame.identity.path}/${index}`,ownerPaths:frame.identity.ownerPaths,collisionIds:frame.identity.collisionIds,declaredChildrenAtPath:frame.identity.declaredChildrenAtPath}:void 0;stack.push({node:children[index],ancestry:childAncestry,depth:frame.depth+1,setSize:declaredCount,posInSet:index+1,identity})}}}selectableInSingleMode(node){return!node.isDisabled&&(this.selection!=="leaf"||!node.hasChildren)}normalizeSingleSelection(){let kept=!1;for(const node of this.allNodeElements()){const selected=!kept&&node.selected&&this.selectableInSingleMode(node);this.setSelection(node,selected,!1),selected&&(kept=!0)}}setBranchSelection(node,selected,leavesOnly){const stack=[{node,depth:treeItemOwnerContext(node).depth}],seen=new Set;for(;stack.length>0&&seen.size<this.nodeWalkLimit;){const{node:current,depth}=stack.pop();if(seen.has(current)||current.isDisabled)continue;seen.add(current);const children=this.childrenOf(current).filter(child=>!child.isDisabled);if(!leavesOnly||children.length===0?this.setSelection(current,leavesOnly&¤t.hasChildren?!1:selected,!1):this.setSelection(current,!1,!1),depth<TREE_MAX_RENDER_DEPTH)for(let index=children.length-1;index>=0;index--)stack.push({node:children[index],depth:depth+1})}}deriveMultipleSelection(node,leavesOnly){const states=new Map,stack=[{item:node,visited:!1,depth:0}],queued=new Set;for(;stack.length>0;){const entry=stack.pop();if(entry.visited){const current=entry.item;if(current.isDisabled){this.setSelection(current,!1,!1),states.set(current,"ignored");continue}const children2=this.childrenOf(current).filter(child=>!child.isDisabled);if(children2.length===0){leavesOnly&¤t.hasChildren?(this.setSelection(current,!1,!1),states.set(current,"none")):(this.setSelection(current,current.selected,!1),states.set(current,current.selected?"all":"none"));continue}const childStates=children2.map(child=>states.get(child)??"ignored").filter(state2=>state2!=="ignored");if(childStates.length===0){this.setSelection(current,!1,!1),states.set(current,"none");continue}const all=childStates.every(state2=>state2==="all"),none=childStates.every(state2=>state2==="none");this.setSelection(current,all,!all&&!none),states.set(current,all?"all":none?"none":"some");continue}if(queued.size>=this.nodeWalkLimit||queued.has(entry.item)||(queued.add(entry.item),stack.push({...entry,visited:!0}),entry.depth>=TREE_MAX_RENDER_DEPTH))continue;const children=this.childrenOf(entry.item);for(let index=children.length-1;index>=0;index--)queued.has(children[index])||stack.push({item:children[index],visited:!1,depth:entry.depth+1})}return states.get(node)??"none"}normalizeMultipleSelection(){const leavesOnly=this.selection==="leaf-multiple";for(const node of this.allNodeElements())node.selected&&this.childrenOf(node).length>0&&this.setBranchSelection(node,!0,leavesOnly);for(const root of this.nodeElements)this.deriveMultipleSelection(root,leavesOnly)}normalizeSelection(){this.selection==="single"||this.selection==="leaf"?this.normalizeSingleSelection():this.normalizeMultipleSelection()}setSelection(node,selected,indeterminate){this.selectionBefore&&!this.selectionBefore.has(node)&&this.selectionBefore.set(node,[node.selected,node.indeterminate]),setTreeItemSelection(node,selected,indeterminate)}updateSelectionFrom(node){if(node.isDisabled||(this.selection==="single"||this.selection==="leaf")&&!this.selectableInSingleMode(node))return!1;const before=new Map;this.selectionBefore=before;try{if(this.selection==="single"||this.selection==="leaf")for(const candidate of this.allNodeElements())this.setSelection(candidate,candidate===node,!1);else{const select=node.indeterminate||!node.selected;this.setBranchSelection(node,select,this.selection==="leaf-multiple");for(const root of this.nodeElements)this.deriveMultipleSelection(root,this.selection==="leaf-multiple")}}finally{this.selectionBefore=void 0}for(const[candidate,[selected,indeterminate]]of before)if(candidate.selected!==selected||candidate.indeterminate!==indeterminate)return!0;return!1}refreshAuthoredItems(){const nodes=this.nodeElements;for(const node of nodes)node.hasAttribute("slot")&&node.removeAttribute("slot");const authored=nodes.some(node=>!this.generatedNodes.has(node));if(authored)for(const node of nodes)this.generatedNodes.has(node)&&node.remove();this.hasAuthoredItems=authored}visibleNodeElements(){const acc=[],seen=new Set,stack=this.nodeElements.map(node=>({node,depth:0})).reverse();for(;stack.length>0&&acc.length<this.nodeWalkLimit;){const{node,depth}=stack.pop();if(seen.has(node)||(seen.add(node),!this.isNavigable(node))||(acc.push(node),!node.expanded||depth>=TREE_MAX_RENDER_DEPTH))continue;const children=this.childrenOf(node);for(let index=children.length-1;index>=0;index--)stack.push({node:children[index],depth:depth+1})}return acc}findItem(items,id){const stack=[...items].reverse(),seen=new Set;for(;stack.length>0;){const item=stack.pop();if(!seen.has(item)){if(seen.add(item),item.id===id)return item;if(item.children)for(let i=item.children.length-1;i>=0;i--){const child=item.children[i];child&&stack.push(child)}}}}isDuplicateDataPath(item,path){return this.dataIdCollisions.has(item.id)&&this.dataIdOwnerPaths.get(item.id)!==path}rebuildDataIdentity(){const ownerPaths=new Map,collisionIds=new Set,ancestry=new Set,stack=[{items:this.data,index:0,parentPath:"",depth:0}];for(;stack.length>0;){const frame=stack[stack.length-1];if(frame.index>=frame.items.length){frame.owner&&ancestry.delete(frame.owner),stack.pop();continue}const index=frame.index++,item=frame.items[index];if(!item)continue;const path=frame.parentPath===""?String(index):`${frame.parentPath}/${index}`;ownerPaths.has(item.id)?collisionIds.add(item.id):ownerPaths.set(item.id,path),!(frame.depth>=TREE_MAX_RENDER_DEPTH||ancestry.has(item)||!item.children?.length)&&(ancestry.add(item),stack.push({items:item.children,index:0,parentPath:path,depth:frame.depth+1,owner:item}))}this.dataIdOwnerPaths=ownerPaths,this.dataIdCollisions=collisionIds}treeIdentityAt(path){return{path,ownerPaths:this.dataIdOwnerPaths,collisionIds:this.dataIdCollisions,declaredChildrenAtPath:this.declaredChildrenAtPath}}firstEnabledId(items){for(let index=0;index<items.length;index++){const item=items[index];if(!(!item||item.disabled||this.isDuplicateDataPath(item,String(index))))return item.id}return null}isEnabledReachableId(items,id){const stack=items.map((item,index)=>({item,path:String(index)})).reverse(),seen=new Set;for(;stack.length>0;){const{item,path}=stack.pop();if(!seen.has(item)&&(seen.add(item),!(item.disabled||this.isDuplicateDataPath(item,path)))){if(item.id===id)return!0;if(item.children)for(let i=item.children.length-1;i>=0;i--){const child=item.children[i];child&&stack.push({item:child,path:`${path}/${i}`})}}}return!1}findRenderedSiblings(node){const root=node.getRootNode(),shadowHost="host"in root?root.host:null,shadowParent=shadowHost?.localName===tag("tree-item")?shadowHost:null,lightParent=node.parentElement?.localName===tag("tree-item")?node.parentElement:null,parentItem=shadowParent??lightParent,siblings=parentItem?parentItem.childItems():this.nodeElements,index=siblings.indexOf(node);if(!(index<0))return{parent:parentItem,siblings,index}}deepFocusedNode(){const active=deepActiveElementIn(this.ownerDocument);if(!active||active.localName!==tag("tree-item"))return null;const node=active;return this.visibleNodeElements().some(n=>n.nodeId===node.nodeId)?node:null}resolveActiveFromDom(){const inertMutation=this.inertMutationPending;this.inertMutationPending=!1;const visible=this.visibleNodeElements(),current=visible.find(node=>node.nodeId===this.activeId);if(current){this.setActiveNode(current);return}const displaced=this.activeId;if(this.setActiveNode(visible[0]),!inertMutation||this.activeId==null||displaced==null||displaced!==this.lastFocusedNodeId)return;const ownerDocument=this.ownerDocument,active=deepActiveElementIn(ownerDocument),strandedOnDisplaced=active?.nodeType===1&&active.localName===tag("tree-item")&&active.nodeId===displaced;active!==null&&active!==ownerDocument.body&&!strandedOnDisplaced||(this.pendingFocusId=this.activeId)}requestUpdate(name,oldValue){name===void 0&&this._treeSource!==void 0&&this.hierarchy?.update(this._treeSource,this.effectiveLocale,!0),super.requestUpdate(name,oldValue)}willUpdate(changed){if(super.willUpdate(changed),this.hierarchy.update(this.treeSource,this.effectiveLocale),this.treeSource!==void 0){if(!this.sourceMode){this.sourceMode=!0,this.resetChildObserver(),this.pendingFocusId=null,this.pendingReorder=void 0,this.selectionBeforeRefresh=void 0,this.syncRequested=!1,this.syncGeneration++,this.syncRunning=!1,this.syncTask=void 0;for(const node of this.nodeElements)this.generatedNodes.has(node)&&node.remove()}return}if(this.sourceMode&&(this.sourceMode=!1,this.sourceAnnouncement=void 0,this.dataSyncPending=!0,this.selectionSyncPending=!0,this.armChildObserver()),changed.has("maxNodes")&&this.hasUpdated&&!changed.has("data")&&(this.data=this.data),this.refreshAuthoredItems(),(changed.has("data")||changed.has("selection"))&&(this.selectionSyncPending=!0),this.hasAuthoredItems){this.resolveActiveFromDom();return}if(changed.has("data")||this.dataSyncPending){this.dataSyncPending=!1;const focused=this.deepFocusedNode(),focusedId=focused?.nodeId??null;this.rebuildDataIdentity(),this.syncNodes();const activeItem=this.activeId?this.findItem(this.data,this.activeId):void 0;(!this.activeId||!activeItem||activeItem.disabled||!this.isEnabledReachableId(this.data,this.activeId))&&(this.activeId=this.firstEnabledId(this.data)),this.pendingFocusId=focused==null?null:focusedId!=null&&this.findItem(this.data,focusedId)?focusedId:this.activeId}this.inertMutationPending&&this.resolveActiveFromDom()}firstUpdated(changed){super.firstUpdated(changed),hostAriaLabel(this)==null&&!this.label&&devWarnOnce("lyra-tree-missing-accessible-name","<lr-tree> has no accessible name: set `label` or a host `aria-label`.")}updated(changed){if(super.updated(changed),this.treeSource!==void 0){this.announceSource();return}const targeted=changed.size===0&&this.hasAuthoredItems&&this.dirtyConfigureRoots.size>0;if(targeted){const nodes=this.nodeElements,count=nodes.length,positions=this.dirtyConfigureRoots.size>1?new Map(nodes.map((node,index)=>[node,index])):void 0;for(const node of this.dirtyConfigureRoots){const i=positions?positions.get(node)??-1:nodes.indexOf(node);i<0||configureTreeItemOwner(node,{...treeItemOwnerContext(node),activeId:null,activeNodeId:this.readActiveId,ancestry:[],depth:0,setSize:count,posInSet:i+1,selection:this.selection,ownsSelection:!0,identity:void 0,expandIcon:this.iconSource("expand-icon"),collapseIcon:this.iconSource("collapse-icon"),syncOwner:this.requestContextSync,focusOwner:this.onItemFocus})}}else if(changed.has("activeId")||changed.has("data")||this.hasAuthoredItems){const nodes=this.nodeElements,count=this.hasAuthoredItems?nodes.length:this.declaredRootCount;nodes.forEach((node,i)=>{configureTreeItemOwner(node,{...treeItemOwnerContext(node),activeId:null,activeNodeId:this.readActiveId,ancestry:[],depth:0,setSize:count,posInSet:i+1,selection:this.selection,ownsSelection:!0,identity:this.hasAuthoredItems?void 0:this.treeIdentityAt(String(i)),expandIcon:this.iconSource("expand-icon"),collapseIcon:this.iconSource("collapse-icon"),syncOwner:this.requestContextSync,focusOwner:this.onItemFocus})})}targeted||(this.contextSyncPending=!0),this.dirtyConfigureRoots.clear(),this.scheduleTreeSync()}scheduleTreeSync(){this.treeSource===void 0&&(this.syncRequested=!0,!(this.syncRunning||this.bulkExpansions>0)&&(this.syncRunning=!0,this.syncTask=this.runTreeSync()))}async runTreeSync(){const generation=this.syncGeneration;try{for(;this.syncRequested&&(this.syncRequested=!1,await super.getUpdateComplete(),!(this.treeSource!==void 0||generation!==this.syncGeneration||(await cascadeUpdateComplete(this.nodeElements),this.treeSource!==void 0||generation!==this.syncGeneration)||(this.contextSyncPending&&(this.contextSyncPending=!1,this.applyTreeContext()),this.selectionSyncPending&&(this.selectionSyncPending=!1,this.normalizeSelection()),await cascadeUpdateComplete(this.nodeElements),this.treeSource!==void 0||generation!==this.syncGeneration)));)this.reportRefreshSelectionChange(),this.confirmPendingReorder(),this.restorePendingFocus()}finally{generation===this.syncGeneration&&(this.syncRunning=!1)}}rootTreeItemAncestor(node){const itemTag=tag("tree-item");let current=node;for(;current&¤t.parentElement&¤t.parentElement!==this;)current=current.parentElement;return current&¤t.parentElement===this&¤t.localName===itemTag?current:null}connectedCallback(){super.connectedCallback(),this.armChildObserver()}armChildObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected||this.treeSource!==void 0||this.childObserver&&this.childObserverDocument===ownerDocument)return;this.resetChildObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.childObserverGeneration,observer=new MutationObserverCtor(records=>{this.childObserver!==observer||this.childObserverDocument!==ownerDocument||this.childObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.onChildMutations(records)});this.childObserver=observer,this.childObserverDocument=ownerDocument,observer.observe(this,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0,attributeFilter:["selected","disabled","inert","lazy"]})}disconnectedCallback(){super.disconnectedCallback(),this.sourceAnnouncement=void 0,this.pendingReorder=void 0,this.activeNode=void 0,this.resetChildObserver()}adoptedCallback(){super.adoptedCallback(),this.hierarchy.adopted(),this.resetChildObserver()}resetChildObserver(){this.childObserverGeneration+=1,this.childObserver?.disconnect(),this.childObserver=void 0,this.childObserverDocument=void 0}syncNodes(){const existingById=new Map;for(const node of this.nodeElements){if(!node.item)continue;const matches=existingById.get(node.item.id)??[];matches.push(node),existingById.set(node.item.id,matches)}let previousSibling=null;for(let index=0;index<this.data.length;index++){const item=this.data[index];let node=existingById.get(item.id)?.shift();node||(node=this.ownerDocument.createElement(tag("tree-item")),this.generatedNodes.add(node)),node.item=item,configureTreeItemOwner(node,{...treeItemOwnerContext(node),ancestry:[],depth:0,setSize:this.declaredRootCount,posInSet:index+1,selection:this.selection,ownsSelection:!0,identity:this.treeIdentityAt(String(index)),expandIcon:this.iconSource("expand-icon"),collapseIcon:this.iconSource("collapse-icon"),syncOwner:this.requestContextSync,focusOwner:this.onItemFocus});const targetPosition=previousSibling?previousSibling.nextElementSibling:this.firstElementChild;targetPosition!==node&&this.insertBefore(node,targetPosition),previousSibling=node}for(const nodes of existingById.values())for(const node of nodes)node.remove()}focusNode(node){node&&(this.setActiveNode(node),node.focus())}subtreeHasId(root,id){if(id==null)return!1;const stack=this.childrenOf(root).map(item=>({item,depth:treeItemOwnerContext(root).depth+1}));for(let visited=0;stack.length>0&&visited<this.nodeWalkLimit;visited++){const{item,depth}=stack.pop();if(!(depth>TREE_MAX_RENDER_DEPTH)){if(item.nodeId===id)return!0;depth<TREE_MAX_RENDER_DEPTH&&stack.push(...this.childrenOf(item).map(child=>({item:child,depth:depth+1})))}}return!1}focusIsWithin(node){for(let current=deepActiveElementIn(this.ownerDocument);current;current=composedParentElement(current)){if(current===node)return!0;if(current===this)return!1}return!1}eventNode(e){const path=e.composedPath(),origin=path[0];if(origin?.nodeType===1&&origin.localName===tag("tree-item")){const treeTag=tag("tree");for(const target of path){if(target===this)return origin;if(target.localName===treeTag)return}return}const id=e.detail?.nodeId;return this.allNodeElements().find(candidate=>candidate.nodeId===id)}async getUpdateComplete(){let result=await super.getUpdateComplete();if(this.treeSource!==void 0)return result;for(;this.syncRunning||this.isUpdatePending;)this.syncRunning&&await this.syncTask,result=await super.getUpdateComplete();return this.treeSource===void 0&&await cascadeUpdateComplete(this.nodeElements),result}reportRefreshSelectionChange(){const before=this.selectionBeforeRefresh;if(before===void 0||this.isUpdatePending)return;this.selectionBeforeRefresh=void 0;const selection=this.selectedItems;selection.length===before.length&&selection.every((item,index)=>item.nodeId===before[index])||this.emit("lr-selection-change",Object.freeze({selection}))}restorePendingFocus(){if(this.pendingFocusId==null)return;const id=this.pendingFocusId;this.pendingFocusId=null;const visible=this.visibleNodeElements();(visible.find(n=>n.nodeId===id)??visible.find(n=>n.nodeId===this.activeId))?.focus()}requestReorder(node,delta){const id=node.nodeId,found=this.findRenderedSiblings(node);if(!found)return;const{parent,siblings,index}=found,total=siblings.length,toIndex=index+delta;toIndex<0||toIndex>=total||(this.pendingReorder={node,parent,originalSiblings:[...siblings],targetSibling:siblings[toIndex],fromIndex:index,toIndex},this.emit("lr-reorder",{nodeId:id,parentNodeId:parent?.nodeId??null,fromIndex:index,toIndex}))}confirmPendingReorder(){const pending=this.pendingReorder;if(!pending)return;const found=this.findRenderedSiblings(pending.node);if(!found){this.pendingReorder=void 0;return}(found.siblings.length!==pending.originalSiblings.length||found.siblings.some((node,index)=>node!==pending.originalSiblings[index]))&&(this.pendingReorder=void 0,!(found.parent!==pending.parent||found.index!==pending.toIndex||found.siblings[pending.fromIndex]!==pending.targetSibling)&&this.liveRegion?.announce(this.localize("treeNodeMoved",void 0,{label:pending.node.nodeLabel,index:this.formatCount(found.index+1),total:this.formatCount(found.siblings.length)}),{force:!0}))}async expandAll(){if(this.treeSource!==void 0)return;let level=this.nodeElements.map(node=>({node,depth:0}));const seen=new Set,systemReduced=preferenceMediaMatches(this.ownerDocument.defaultView,"(prefers-reduced-motion: reduce)");this.bulkExpansions+=1;try{for(;level.length>0&&seen.size<this.nodeWalkLimit;){const current=[];for(const entry of level){const{node}=entry;if(!(seen.has(node)||seen.size>=this.nodeWalkLimit)){if(seen.add(node),current.push(entry),node.isDisabled)node.expanded=!1;else if(node.hasChildren){const reduced=systemReduced||inheritedPreference(node,"data-lr-motion","reduce")==="reduce";withTreeItemMotionPreference(node,reduced,()=>node.expand())}}}await Promise.all(current.map(({node})=>node.updateComplete)),level=[];for(const{node,depth}of current)depth<TREE_MAX_RENDER_DEPTH&&level.push(...this.childrenOf(node).map(child=>({node:child,depth:depth+1})))}}finally{this.bulkExpansions-=1}this.bulkExpansions===0&&this.syncRequested&&this.scheduleTreeSync(),await this.updateComplete}async collapseAll(){if(this.treeSource!==void 0)return;const focused=this.deepFocusedNode(),topLevel=this.nodeElements,nodes=this.allNodeElements();for(let index=nodes.length-1;index>=0;index--){const node=nodes[index];node.isDisabled?node.expanded=!1:node.collapse()}(this.hasAuthoredItems?topLevel.some(node=>this.isNavigable(node)&&node.nodeId===this.activeId):this.data.some(item=>!item.disabled&&item.id===this.activeId))||(this.activeId=this.hasAuthoredItems?topLevel.find(node=>this.isNavigable(node))?.nodeId??null:this.firstEnabledId(this.data)),focused&&(this.pendingFocusId=this.activeId),await cascadeUpdateComplete(topLevel)}render(){return this.treeSource!==void 0?hierarchySourceView(this.hierarchy,{label:hostAriaLabel(this)??this.label,rtl:this.effectiveDirection==="rtl",multiple:this.selection==="multiple"||this.selection==="leaf-multiple",loading:this.localize("loading"),error:this.localize("treeSourceError"),empty:this.localize("noData"),retry:this.localize("retry"),expand:this.localize("expand"),collapse:this.localize("collapse"),summary:this.sourceSummary(),name:value=>value.accessibleLabel||[value.label,value.description,...(value.badges??[]).map(badge=>badge.label?.trim()?badge.label:badge.text)].filter(text=>text?.trim()).join(" ")||value.id,content:value=>html`${value.icon??nothing}${value.label}${value.description?html` <span>${value.description}</span>`:nothing}${value.badges?.map(badge=>html` <span role=${badge.label?.trim()?"img":nothing} aria-label=${badge.label?.trim()?badge.label:nothing}>${badge.text}</span>`)}`,select:row=>{if((this.selection==="leaf"||this.selection==="leaf-multiple")&&row.childCount>0)return;const multiple=this.selection==="multiple"||this.selection==="leaf-multiple";this.hierarchy.project({type:"select",key:row.key,selected:multiple?!row.selected:!0,scope:multiple&&row.childCount>0?"subtree":"item"},!0,row)}}):html`
|
|
1
|
+
import{__decorate}from"tslib";import{HierarchySourceController,hierarchyField,hierarchyKey,hierarchyText}from"../../../internal/hierarchy-source-controller.js";import{hierarchySourceView}from"../../../internal/hierarchy-source-view.js";import{hierarchySourceStyles}from"../../../internal/hierarchy-source-view.styles.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{inheritedPreference,preferenceMediaMatches}from"../../../internal/preferences.js";import{finiteCount}from"../../../internal/numbers.js";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{normalizeReflectedOptionalSize,optionalSizeConverter}from"../../../internal/variants.js";import{tag}from"../../../internal/prefix.js";import{resolveListMove}from"../../../internal/list-navigation.js";import{TreePointerReorder}from"./tree-pointer-reorder.js";import{styles}from"./tree.styles.js";import{TreeDataExpansion}from"./tree-data-expansion.js";import{cascadeUpdateComplete}from"./update-cascade.js";import{configureTreeItemOwner,withTreeItemMotionPreference,fromInteractiveDescendant,setTreeItemSelection,treeItemOwnerContext}from"./tree-owner-controller.js";import"./tree-item.class.js";import{TREE_MAX_RENDER_DEPTH,TREE_MAX_RENDER_NODES}from"./tree-types.js";import{composedParentElement,deepActiveElementIn}from"../../../internal/active-element.js";import{LYRA_DEFAULT_treeLimit}from"../../../internal/default-strings/data.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_expand,LYRA_DEFAULT_loading,LYRA_DEFAULT_noData,LYRA_DEFAULT_retry,LYRA_DEFAULT_treeNodeMoved,LYRA_DEFAULT_treeSourceError,LYRA_DEFAULT_treeSourceSummary}from"../../../internal/default-strings/shared.generated.js";const TREE_SELECTIONS=new Set(["single","multiple","leaf","leaf-multiple"]),TREE_BADGE_LIMIT=100,TREE_MAX_INSPECTED_POSITIONS=1e4,EMPTY_TREE_DATA=Object.freeze([]);function ownValue(record,key){try{const descriptor=Object.getOwnPropertyDescriptor(record,key);return descriptor&&"value"in descriptor?descriptor.value:void 0}catch{return}}function arrayLength(value){if(!Array.isArray(value))return 0;try{return Math.max(0,Math.min(Number.MAX_SAFE_INTEGER,Math.trunc(value.length)))}catch{return 0}}function normalizeBadges(value){if(!Array.isArray(value))return{truncated:value!==void 0};const badges=[],length=arrayLength(value);for(let index=0;index<Math.min(length,TREE_BADGE_LIMIT);index++){const raw=ownValue(value,String(index));if(!raw||typeof raw!="object"||Array.isArray(raw))continue;const text=ownValue(raw,"text");if(typeof text!="string")continue;const rawTone=ownValue(raw,"tone"),tone=rawTone==="brand"||rawTone==="success"||rawTone==="warning"||rawTone==="danger"?rawTone:"neutral",rawLabel=ownValue(raw,"label");badges.push(Object.freeze({text,tone,...typeof rawLabel=="string"?{label:rawLabel}:{}}))}return{badges:Object.freeze(badges),truncated:length>TREE_BADGE_LIMIT}}function sameIcon(left,right){if(Object.is(left,right))return!0;const a=left,b=right;if(!a||!b||typeof a!="object"||typeof b!="object"||a._$litType$===void 0||a._$litType$!==b._$litType$||a.strings!==b.strings)return!1;const leftValues=a.values??[],rightValues=b.values??[];return leftValues.length===rightValues.length&&leftValues.every((value,index)=>Object.is(value,rightValues[index]))}function sameBadges(left,right){return left===right?!0:!left||!right||left.length!==right.length?!1:left.every((badge,index)=>{const other=right[index];return badge.text===other.text&&badge.tone===other.tone&&badge.label===other.label})}function sameTreeNode(next,previous){if(next.id!==previous.id||next.label!==previous.label||next.selected!==previous.selected||next.expanded!==previous.expanded||next.disabled!==previous.disabled||next.lazy!==previous.lazy||next.description!==previous.description||next.accessibleLabel!==previous.accessibleLabel||!sameIcon(next.icon,previous.icon)||!sameBadges(next.badges,previous.badges))return!1;const children=next.children,previousChildren=previous.children;return!children||!previousChildren?children===void 0&&previousChildren===void 0:children.length===previousChildren.length&&children.every((child,index)=>child===previousChildren[index])}function indexTreeNodes(nodes){const byId=new Map,stack=[...nodes];for(;stack.length>0;){const node=stack.pop();byId.set(node.id,node),node.children&&stack.push(...node.children)}return byId}function normalizeTreeData(input,previous=EMPTY_TREE_DATA,limit=TREE_MAX_RENDER_NODES){if(!Array.isArray(input))return{data:EMPTY_TREE_DATA,declaredChildrenAtPath:new Map,declaredRootCount:0,truncated:input!=null,limitReached:!1};const root=[],declaredChildrenAtPath=new Map,created=[],rootLength=arrayLength(input);let truncated=!1,limitReached=!1,accepted=0,inspected=0;const seenIds=new Set,identityFilteredCollections=new Set,jobs=[{source:input,index:0,length:rootLength,target:root,parentPath:"",depth:0,ancestors:new Set}];for(;jobs.length>0;){const job=jobs[jobs.length-1];if(job.index>=job.length){jobs.pop();continue}if(accepted>=limit||inspected>=TREE_MAX_INSPECTED_POSITIONS){truncated=!0,limitReached=accepted>=limit;break}const raw=ownValue(job.source,String(job.index++));if(inspected++,inspected===TREE_MAX_INSPECTED_POSITIONS&&(truncated=!0),!raw||typeof raw!="object"||Array.isArray(raw)){truncated=!0,identityFilteredCollections.add(job.target);continue}const id=ownValue(raw,"id"),label=ownValue(raw,"label");if(typeof id!="string"||id.trim()===""||seenIds.has(id)||typeof label!="string"){truncated=!0,identityFilteredCollections.add(job.target);continue}seenIds.add(id);const node={id,label},selected=ownValue(raw,"selected"),expanded=ownValue(raw,"expanded"),disabled=ownValue(raw,"disabled"),lazy=ownValue(raw,"lazy");typeof selected=="boolean"&&(node.selected=selected),typeof expanded=="boolean"&&(node.expanded=expanded),typeof disabled=="boolean"&&(node.disabled=disabled),typeof lazy=="boolean"&&(node.lazy=lazy);const icon=ownValue(raw,"icon");icon!==void 0&&(node.icon=icon);const description=ownValue(raw,"description");typeof description=="string"&&(node.description=description);const accessibleLabel=ownValue(raw,"accessibleLabel");typeof accessibleLabel=="string"&&(node.accessibleLabel=accessibleLabel);const normalizedBadges=normalizeBadges(ownValue(raw,"badges"));normalizedBadges.badges?.length&&(node.badges=normalizedBadges.badges),truncated||=normalizedBadges.truncated;const ownIndex=job.target.length,path=job.parentPath===""?String(ownIndex):`${job.parentPath}/${ownIndex}`;job.target.push(node),created.push(node),accepted++;const rawChildren=ownValue(raw,"children"),childCount=arrayLength(rawChildren);if(childCount===0)continue;if(declaredChildrenAtPath.set(path,childCount),job.depth>=TREE_MAX_RENDER_DEPTH||job.ancestors.has(raw)){truncated=!0;continue}const children=[];node.children=children;const ancestors=new Set(job.ancestors);ancestors.add(raw),jobs.push({source:rawChildren,index:0,length:childCount,target:children,parentPath:path,depth:job.depth+1,ancestors})}const previousById=previous.length>0?indexTreeNodes(previous):void 0,resolved=new Map,resolve=node=>resolved.get(node)??node;for(let index=created.length-1;index>=0;index--){const node=created[index];if(node.children){for(let child=0;child<node.children.length;child++)node.children[child]=resolve(node.children[child]);Object.freeze(node.children)}Object.freeze(node);const prior=previousById?.get(node.id);prior&&!(node.children&&identityFilteredCollections.has(node.children))&&sameTreeNode(node,prior)&&resolved.set(node,prior)}for(let index=0;index<root.length;index++)root[index]=resolve(root[index]);const normalizedJobs=root.map((node,index)=>({node,path:String(index)}));for(;normalizedJobs.length>0;){const{node,path}=normalizedJobs.pop(),children=node.children??[];identityFilteredCollections.has(children)&&declaredChildrenAtPath.set(path,children.length);for(let index=children.length-1;index>=0;index--)normalizedJobs.push({node:children[index],path:`${path}/${index}`})}return{data:Object.freeze(root),declaredChildrenAtPath,declaredRootCount:identityFilteredCollections.has(root)?root.length:rootLength,truncated,limitReached}}function isInertWithin(node,root){for(let current=node;current&¤t!==root;current=current.parentElement)if(current.hasAttribute("inert"))return!0;return!1}class LyraTree extends LyraElement{constructor(){super(...arguments),this._treeSource=void 0,this.sourceMode=!1,this.sourcePaintVersion=0,this.sourceAnnouncer=new AnnouncementSinkController(this),this.hierarchy=new HierarchySourceController(this,{normalize:(value,key)=>this.normalizeSourceValue(value,key),onChange:()=>{const previous=this.sourcePaintVersion++;this.requestUpdate("sourcePaintVersion",previous)},accepted:(action,_row,state2)=>{action.type==="select"&&this.emit("lr-source-selection-change",Object.freeze({key:action.key,selected:action.selected,scope:action.scope,state:state2}))}}),this._data=EMPTY_TREE_DATA,this.dataExpansion=new TreeDataExpansion(()=>this.treeSource===void 0),this.lastDataInput=void 0,this.lastDataLimit=0,this.declaredChildrenAtPath=new Map,this.declaredRootCount=0,this._dataTruncated=!1,this._limitReached=!1,this.label="",this.maxNodes=1e3,this.reorderable=!1,this.pointerReorderable=!1,this.allowCrossParentReorder=!1,this._selection="single",this._activeId=null,this.readActiveId=()=>this._activeId,this.hasAuthoredItems=!1,this.pendingFocusId=null,this.generatedNodes=new WeakSet,this.dataIdOwnerPaths=new Map,this.dataIdCollisions=new Set,this.selectionSyncPending=!0,this.dataSyncPending=!1,this.inertMutationPending=!1,this.dirtyConfigureRoots=new Set,this.lastFocusedNodeId=null,this.pointerOrder=new TreePointerReorder(this,node=>this.findRenderedSiblings(node),ids=>{if(!this.hasAuthoredItems)return!0;const seen=new Set;for(const node of this.allNodeElements())if(ids.has(node.nodeId)){if(seen.has(node.nodeId))return!1;seen.add(node.nodeId)}return seen.size===ids.size},detail=>{const nodes=this.visibleNodeElements(),sourceOrder=this.pointerSiblingIds(detail.fromParentNodeId,nodes),targetOrder=detail.fromParentNodeId===detail.toParentNodeId?sourceOrder:this.pointerSiblingIds(detail.toParentNodeId,nodes);this.pendingPointerReorder={detail,sourceOrder,targetOrder},this.emit("lr-pointer-reorder",detail)}),this.onTreeFocusIn=e=>{const path=e.composedPath(),owner=path.find(target=>target.localName===tag("tree"));if(owner&&owner!==this)return;const item=path.find(target=>target.nodeType===1&&target.localName===tag("tree-item"));item&&this.onItemFocus(item)},this.onItemFocus=element=>{const item=element;this.isNavigable(item)&&(this.lastFocusedNodeId=item.nodeId,this.setActiveNode(item))},this.contextSyncPending=!0,this.bulkExpansions=0,this.bulkExpansionGeneration=0,this.syncGeneration=0,this.syncRequested=!1,this.syncRunning=!1,this.requestContextSync=closedBy=>{if(closedBy){const node=closedBy;this.activeId!==node.nodeId&&this.isNavigable(node)&&this.subtreeHasId(node,this.activeId)&&this.setActiveNode(node)}this.contextSyncPending=!0,this.scheduleTreeSync()},this.onChildrenChanged=()=>{if(this.treeSource!==void 0)return;const wasAuthored=this.hasAuthoredItems;this.refreshAuthoredItems(),wasAuthored&&!this.hasAuthoredItems&&(this.dataSyncPending=!0),this.selectionSyncPending=!0,this.requestUpdate()},this.childObserverGeneration=0,this.onChildMutations=allRecords=>{const records=allRecords.filter(record=>record.type!=="attributes"||record.oldValue!==null!==record.target.hasAttribute(record.attributeName??""));if(records.length!==0){if(records.some(record=>record.attributeName==="inert")&&(this.inertMutationPending=!0),records.every(record=>record.type==="attributes")){const itemTag=tag("tree-item");for(const record of records){const target=record.target;if(!(target instanceof Element)||target.localName!==itemTag)continue;const root=this.rootTreeItemAncestor(target);root&&this.dirtyConfigureRoots.add(root)}}else this.dirtyConfigureRoots.clear();this.onChildrenChanged()}},this.onNodeActivate=e=>{const node=this.eventNode(e);if(!node||node.isDisabled)return;this.selectionSyncPending=!0,this.bulkExpansions>0?this.syncRequested=!0:this.requestUpdate();const expanded=e.detail?.expanded===!0;(this.focusIsWithin(node)||!expanded&&this.activeId!==node.nodeId&&this.subtreeHasId(node,this.activeId))&&this.setActiveNode(node)},this.onNodeSelect=event=>{const node=this.eventNode(event);!node||node.isDisabled||(this.setActiveNode(node),this.updateSelectionFrom(node)&&this.emit("lr-selection-change",Object.freeze({selection:this.selectedItems})))},this.onTreeKeyDown=e=>{const itemTag=tag("tree-item");if(fromInteractiveDescendant(e,target=>target.localName===itemTag))return;const visible=this.visibleNodeElements();if(visible.length===0)return;const currentIndex=visible.findIndex(n=>n.nodeId===this.activeId),current=currentIndex>=0?visible[currentIndex]:visible[0];if(!current)return;if(this.reorderable&&(e.ctrlKey||e.metaKey)&&(e.key==="ArrowUp"||e.key==="ArrowDown")){e.preventDefault(),this.requestReorder(current,e.key==="ArrowDown"?1:-1);return}if(e.altKey)return;const rtl=this.effectiveDirection==="rtl",expandKey=rtl?"ArrowLeft":"ArrowRight",collapseKey=rtl?"ArrowRight":"ArrowLeft",moved=resolveListMove(e.key,{count:visible.length,current:Math.max(currentIndex,0),orientation:"vertical",wrap:!1,clamp:!0});if(moved!==null){e.preventDefault(),this.focusNode(visible[moved]);return}switch(e.key){case expandKey:if(e.preventDefault(),!current.hasChildren)break;if(!current.expanded)current.expand();else{const child=visible[currentIndex+1];child&&treeItemOwnerContext(child).depth>treeItemOwnerContext(current).depth&&this.focusNode(child)}break;case collapseKey:if(e.preventDefault(),current.hasChildren&¤t.expanded)current.collapse();else for(let i=currentIndex-1;i>=0;i--){const sibling=visible[i];if(sibling&&treeItemOwnerContext(sibling).depth<treeItemOwnerContext(current).depth){this.focusNode(sibling);break}}break;case"Enter":case" ":e.preventDefault(),current.select();break;default:return}}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,expand:LYRA_DEFAULT_expand,loading:LYRA_DEFAULT_loading,noData:LYRA_DEFAULT_noData,retry:LYRA_DEFAULT_retry,treeLimit:LYRA_DEFAULT_treeLimit,treeNodeMoved:LYRA_DEFAULT_treeNodeMoved,treeSourceError:LYRA_DEFAULT_treeSourceError,treeSourceSummary:LYRA_DEFAULT_treeSourceSummary}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-selection-change"])}static{this.identityEventDetailProperties=Object.freeze({"lr-selection-change":Object.freeze(["selection"])})}static{this.styles=[LyraElement.styles,styles,hierarchySourceStyles]}get size(){return this._size}set size(next){const normalized=normalizeReflectedOptionalSize(this,next),old=this._size;old!==normalized&&(this._size=normalized,this.requestUpdate("size",old))}get treeSource(){return this._treeSource}set treeSource(value){const previous=this._treeSource;this._treeSource=value,value!==void 0&&this.bulkExpansionGeneration++,this.hierarchy?.update(value,this.effectiveLocale,!0),this.requestUpdate("treeSource",previous)}revealSourceKey(key){return this.treeSource===void 0?Promise.resolve(!1):this.hierarchy.reveal(key)}normalizeSourceValue(value,key){const id=hierarchyKey(hierarchyField(value,"id"));if(id!==key)throw new TypeError("Hierarchy domain key mismatch");const label=hierarchyText(hierarchyField(value,"label")),description=hierarchyText(hierarchyField(value,"description")),accessibleLabel=hierarchyText(hierarchyField(value,"accessibleLabel")),normalized=normalizeBadges(hierarchyField(value,"badges"));let units=label.length+description.length+accessibleLabel.length;for(const badge of normalized.badges??[])units+=badge.text.length+(badge.label?.length??0);if(normalized.truncated||units>65536)throw new RangeError("Hierarchy display value exceeds its row budget");return Object.freeze({id,label,description,accessibleLabel,icon:hierarchyField(value,"icon"),badges:normalized.badges})}announceSource(){const status=this.hierarchy.error?this.localize("treeSourceError"):this.hierarchy.loading?this.localize("loading"):this.sourceSummary();this.sourceAnnouncement!==void 0&&status!==this.sourceAnnouncement&&this.sourceAnnouncer.announce(status),this.sourceAnnouncement=status,this.hierarchy.rowsObserved&&this.sourceAnnouncer.transition("source-rows",this.hierarchy.rowError?"error":"ready",this.hierarchy.rowError?this.localize("treeSourceError"):"")}sourceSummary(){const projection=this.hierarchy.projection;return projection?this.localize("treeSourceSummary",void 0,{visible:getNumberFormat(this.effectiveLocale).format(projection.rows.count),total:getNumberFormat(this.effectiveLocale).format(projection.total)}):""}get data(){return this._data}set data(value){if((value===this._data||value===this.lastDataInput)&&this.lastDataLimit===this.effectiveMaxNodes)return;this.lastDataInput=value,this.lastDataLimit=this.effectiveMaxNodes,this.hasUpdated&&this.selectionBeforeRefresh===void 0&&(this.selectionBeforeRefresh=this.selectedItems.map(item=>item.nodeId));const previous=this._data,normalized=normalizeTreeData(value,this._data,this.effectiveMaxNodes);this._data=normalized.data,this.dataExpansion.replace(normalized.data),this.declaredChildrenAtPath=normalized.declaredChildrenAtPath,this.declaredRootCount=normalized.declaredRootCount,this._dataTruncated=normalized.truncated,this._limitReached=normalized.limitReached,this.requestUpdate("data",previous)}get dataTruncated(){return this._dataTruncated}get effectiveMaxNodes(){return Math.max(1,Math.min(1e4,finiteCount(this.maxNodes,1e3)))}get selection(){return this._selection}set selection(value){const old=this._selection,normalized=TREE_SELECTIONS.has(value)?value:"single";old!==normalized&&(this._selection=normalized,this.selectionSyncPending=!0,this.requestUpdate("selection",old))}get activeId(){return this._activeId}set activeId(value){value!==this._activeId&&(this.activeNode&&(this.activeNode.tabIndex=-1),this.activeNode=void 0,this._activeId=value)}setActiveNode(node){this.activeId=node?.nodeId??null,this.activeNode!==node&&this.activeNode&&(this.activeNode.tabIndex=-1),this.activeNode=node,node&&(node.tabIndex=this.isNavigable(node)?0:-1)}get nodeWalkLimit(){return this.hasAuthoredItems?Number.POSITIVE_INFINITY:this.effectiveMaxNodes}get nodeElements(){return[...this.querySelectorAll(`:scope > ${tag("tree-item")}`)]}childrenOf(node){return node.childItems()}isNavigable(node){return!node.isDisabled&&!isInertWithin(node,this)}allNodeElements(){const result=[],seen=new Set,stack=this.nodeElements.map(node=>({node,depth:0})).reverse();for(;stack.length>0&&result.length<this.nodeWalkLimit;){const{node,depth}=stack.pop();if(seen.has(node)||(seen.add(node),result.push(node),depth>=TREE_MAX_RENDER_DEPTH))continue;const children=this.childrenOf(node);for(let index=children.length-1;index>=0;index--)stack.push({node:children[index],depth:depth+1})}return result}get selectedItems(){return this.treeSource!==void 0?Object.freeze([]):Object.freeze(this.allNodeElements().filter(node=>node.selected))}iconSource(name){return this.querySelector(`:scope > [slot="${name}"]`)}applyTreeContext(){const expandIcon=this.iconSource("expand-icon"),collapseIcon=this.iconSource("collapse-icon"),roots=this.nodeElements,rootCount=this.hasAuthoredItems?roots.length:this.declaredRootCount,stack=[];for(let index=roots.length-1;index>=0;index--)stack.push({node:roots[index],ancestry:[],depth:0,setSize:rootCount,posInSet:index+1,identity:this.hasAuthoredItems?void 0:this.treeIdentityAt(String(index)),expansionVisible:!0});const seen=new Set;for(;stack.length>0&&seen.size<this.nodeWalkLimit;){const frame=stack.pop();if(seen.has(frame.node)||(seen.add(frame.node),frame.node.nodeId===this.activeId&&this.setActiveNode(frame.node),configureTreeItemOwner(frame.node,{...treeItemOwnerContext(frame.node),activeId:null,activeNodeId:this.readActiveId,ancestry:frame.ancestry,depth:frame.depth,setSize:frame.setSize,posInSet:frame.posInSet,selection:this.selection,ownsSelection:!0,identity:frame.identity,dataExpansion:frame.identity?this.dataExpansion:void 0,expansionVisible:frame.expansionVisible,expandIcon,collapseIcon,pointerReorderable:this.pointerReorderable,syncOwner:this.requestContextSync,focusOwner:this.onItemFocus}),frame.depth>=TREE_MAX_RENDER_DEPTH))continue;const children=this.childrenOf(frame.node),declaredCount=frame.identity?.declaredChildrenAtPath.get(frame.identity.path)??frame.node.item?.children?.length??children.length,childAncestry=frame.node.item?[...frame.ancestry,frame.node.item]:frame.ancestry,expansionVisible=frame.expansionVisible&&frame.node.expanded&&!frame.node.isDisabled;for(let index=children.length-1;index>=0;index--){const identity=frame.identity?{path:`${frame.identity.path}/${index}`,ownerPaths:frame.identity.ownerPaths,collisionIds:frame.identity.collisionIds,declaredChildrenAtPath:frame.identity.declaredChildrenAtPath}:void 0;stack.push({node:children[index],ancestry:childAncestry,depth:frame.depth+1,setSize:declaredCount,posInSet:index+1,identity,expansionVisible})}}}selectableInSingleMode(node){return!node.isDisabled&&(this.selection!=="leaf"||!node.hasChildren)}normalizeSingleSelection(){let kept=!1;for(const node of this.allNodeElements()){const selected=!kept&&node.selected&&this.selectableInSingleMode(node);this.setSelection(node,selected,!1),selected&&(kept=!0)}}setBranchSelection(node,selected,leavesOnly){const stack=[{node,depth:treeItemOwnerContext(node).depth}],seen=new Set;for(;stack.length>0&&seen.size<this.nodeWalkLimit;){const{node:current,depth}=stack.pop();if(seen.has(current)||current.isDisabled)continue;seen.add(current);const children=this.childrenOf(current).filter(child=>!child.isDisabled);if(!leavesOnly||children.length===0?this.setSelection(current,leavesOnly&¤t.hasChildren?!1:selected,!1):this.setSelection(current,!1,!1),depth<TREE_MAX_RENDER_DEPTH)for(let index=children.length-1;index>=0;index--)stack.push({node:children[index],depth:depth+1})}}deriveMultipleSelection(node,leavesOnly){const states=new Map,stack=[{item:node,visited:!1,depth:0}],queued=new Set;for(;stack.length>0;){const entry=stack.pop();if(entry.visited){const current=entry.item;if(current.isDisabled){this.setSelection(current,!1,!1),states.set(current,"ignored");continue}const children2=this.childrenOf(current).filter(child=>!child.isDisabled);if(children2.length===0){leavesOnly&¤t.hasChildren?(this.setSelection(current,!1,!1),states.set(current,"none")):(this.setSelection(current,current.selected,!1),states.set(current,current.selected?"all":"none"));continue}const childStates=children2.map(child=>states.get(child)??"ignored").filter(state2=>state2!=="ignored");if(childStates.length===0){this.setSelection(current,!1,!1),states.set(current,"none");continue}const all=childStates.every(state2=>state2==="all"),none=childStates.every(state2=>state2==="none");this.setSelection(current,all,!all&&!none),states.set(current,all?"all":none?"none":"some");continue}if(queued.size>=this.nodeWalkLimit||queued.has(entry.item)||(queued.add(entry.item),stack.push({...entry,visited:!0}),entry.depth>=TREE_MAX_RENDER_DEPTH))continue;const children=this.childrenOf(entry.item);for(let index=children.length-1;index>=0;index--)queued.has(children[index])||stack.push({item:children[index],visited:!1,depth:entry.depth+1})}return states.get(node)??"none"}normalizeMultipleSelection(){const leavesOnly=this.selection==="leaf-multiple";for(const node of this.allNodeElements())node.selected&&this.childrenOf(node).length>0&&this.setBranchSelection(node,!0,leavesOnly);for(const root of this.nodeElements)this.deriveMultipleSelection(root,leavesOnly)}normalizeSelection(){this.selection==="single"||this.selection==="leaf"?this.normalizeSingleSelection():this.normalizeMultipleSelection()}setSelection(node,selected,indeterminate){this.selectionBefore&&!this.selectionBefore.has(node)&&this.selectionBefore.set(node,[node.selected,node.indeterminate]),setTreeItemSelection(node,selected,indeterminate)}updateSelectionFrom(node){if(node.isDisabled||(this.selection==="single"||this.selection==="leaf")&&!this.selectableInSingleMode(node))return!1;const before=new Map;this.selectionBefore=before;try{if(this.selection==="single"||this.selection==="leaf")for(const candidate of this.allNodeElements())this.setSelection(candidate,candidate===node,!1);else{const select=node.indeterminate||!node.selected;this.setBranchSelection(node,select,this.selection==="leaf-multiple");for(const root of this.nodeElements)this.deriveMultipleSelection(root,this.selection==="leaf-multiple")}}finally{this.selectionBefore=void 0}for(const[candidate,[selected,indeterminate]]of before)if(candidate.selected!==selected||candidate.indeterminate!==indeterminate)return!0;return!1}refreshAuthoredItems(){const nodes=this.nodeElements;for(const node of nodes)node.hasAttribute("slot")&&node.removeAttribute("slot");const authored=nodes.some(node=>!this.generatedNodes.has(node));if(authored)for(const node of nodes)this.generatedNodes.has(node)&&node.remove();this.hasAuthoredItems=authored}visibleNodeElements(){const acc=[],seen=new Set,stack=this.nodeElements.map(node=>({node,depth:0})).reverse();for(;stack.length>0&&acc.length<this.nodeWalkLimit;){const{node,depth}=stack.pop();if(seen.has(node)||(seen.add(node),!this.isNavigable(node))||(acc.push(node),!node.expanded||depth>=TREE_MAX_RENDER_DEPTH))continue;const children=this.childrenOf(node);for(let index=children.length-1;index>=0;index--)stack.push({node:children[index],depth:depth+1})}return acc}findItem(items,id){const stack=[...items].reverse(),seen=new Set;for(;stack.length>0;){const item=stack.pop();if(!seen.has(item)){if(seen.add(item),item.id===id)return item;if(item.children)for(let i=item.children.length-1;i>=0;i--){const child=item.children[i];child&&stack.push(child)}}}}isDuplicateDataPath(item,path){return this.dataIdCollisions.has(item.id)&&this.dataIdOwnerPaths.get(item.id)!==path}rebuildDataIdentity(){const ownerPaths=new Map,collisionIds=new Set,ancestry=new Set,stack=[{items:this.data,index:0,parentPath:"",depth:0}];for(;stack.length>0;){const frame=stack[stack.length-1];if(frame.index>=frame.items.length){frame.owner&&ancestry.delete(frame.owner),stack.pop();continue}const index=frame.index++,item=frame.items[index];if(!item)continue;const path=frame.parentPath===""?String(index):`${frame.parentPath}/${index}`;ownerPaths.has(item.id)?collisionIds.add(item.id):ownerPaths.set(item.id,path),!(frame.depth>=TREE_MAX_RENDER_DEPTH||ancestry.has(item)||!item.children?.length)&&(ancestry.add(item),stack.push({items:item.children,index:0,parentPath:path,depth:frame.depth+1,owner:item}))}this.dataIdOwnerPaths=ownerPaths,this.dataIdCollisions=collisionIds}treeIdentityAt(path){return{path,ownerPaths:this.dataIdOwnerPaths,collisionIds:this.dataIdCollisions,declaredChildrenAtPath:this.declaredChildrenAtPath}}firstEnabledId(items){for(let index=0;index<items.length;index++){const item=items[index];if(!(!item||item.disabled||this.isDuplicateDataPath(item,String(index))))return item.id}return null}isEnabledReachableId(items,id){const stack=items.map((item,index)=>({item,path:String(index)})).reverse(),seen=new Set;for(;stack.length>0;){const{item,path}=stack.pop();if(!seen.has(item)&&(seen.add(item),!(item.disabled||this.isDuplicateDataPath(item,path)))){if(item.id===id)return!0;if(item.children)for(let i=item.children.length-1;i>=0;i--){const child=item.children[i];child&&stack.push({item:child,path:`${path}/${i}`})}}}return!1}findRenderedSiblings(node){const root=node.getRootNode(),shadowHost="host"in root?root.host:null,shadowParent=shadowHost?.localName===tag("tree-item")?shadowHost:null,lightParent=node.parentElement?.localName===tag("tree-item")?node.parentElement:null,parentItem=shadowParent??lightParent,siblings=parentItem?parentItem.childItems():this.nodeElements,index=siblings.indexOf(node);if(!(index<0))return{parent:parentItem,siblings,index}}deepFocusedNode(){const active=deepActiveElementIn(this.ownerDocument);if(!active||active.localName!==tag("tree-item"))return null;const node=active;return this.visibleNodeElements().some(n=>n.nodeId===node.nodeId)?node:null}resolveActiveFromDom(){const inertMutation=this.inertMutationPending;this.inertMutationPending=!1;const visible=this.visibleNodeElements(),current=visible.find(node=>node.nodeId===this.activeId);if(current){this.setActiveNode(current);return}const displaced=this.activeId;if(this.setActiveNode(visible[0]),!inertMutation||this.activeId==null||displaced==null||displaced!==this.lastFocusedNodeId)return;const ownerDocument=this.ownerDocument,active=deepActiveElementIn(ownerDocument),strandedOnDisplaced=active?.nodeType===1&&active.localName===tag("tree-item")&&active.nodeId===displaced;active!==null&&active!==ownerDocument.body&&!strandedOnDisplaced||(this.pendingFocusId=this.activeId)}requestUpdate(name,oldValue){name===void 0&&this._treeSource!==void 0&&this.hierarchy?.update(this._treeSource,this.effectiveLocale,!0),super.requestUpdate(name,oldValue)}willUpdate(changed){if(super.willUpdate(changed),(!this.pointerReorderable||this.treeSource!==void 0)&&(this.pointerOrder.cancel(),this.pendingPointerReorder=void 0),this.hierarchy.update(this.treeSource,this.effectiveLocale),this.treeSource!==void 0){if(!this.sourceMode){this.sourceMode=!0,this.resetChildObserver(),this.pendingFocusId=null,this.pendingReorder=void 0,this.selectionBeforeRefresh=void 0,this.syncRequested=!1,this.syncGeneration++,this.syncRunning=!1,this.syncTask=void 0;for(const node of this.nodeElements)this.generatedNodes.has(node)&&node.remove()}return}if(this.sourceMode&&(this.sourceMode=!1,this.sourceAnnouncement=void 0,this.dataSyncPending=!0,this.selectionSyncPending=!0,this.armChildObserver()),changed.has("maxNodes")&&this.hasUpdated&&!changed.has("data")&&(this.data=this.data),this.refreshAuthoredItems(),(changed.has("data")||changed.has("selection"))&&(this.selectionSyncPending=!0),this.hasAuthoredItems){this.resolveActiveFromDom();return}if(changed.has("data")||this.dataSyncPending){this.dataSyncPending=!1;const focused=this.deepFocusedNode(),focusedId=focused?.nodeId??null;this.rebuildDataIdentity(),this.syncNodes();const activeItem=this.activeId?this.findItem(this.data,this.activeId):void 0;(!this.activeId||!activeItem||activeItem.disabled||!this.isEnabledReachableId(this.data,this.activeId))&&(this.activeId=this.firstEnabledId(this.data)),this.pendingFocusId=focused==null?null:focusedId!=null&&this.findItem(this.data,focusedId)?focusedId:this.activeId}this.inertMutationPending&&this.resolveActiveFromDom()}firstUpdated(changed){super.firstUpdated(changed),hostAriaLabel(this)==null&&!this.label&&devWarnOnce("lyra-tree-missing-accessible-name","<lr-tree> has no accessible name: set `label` or a host `aria-label`.")}updated(changed){if(super.updated(changed),this.treeSource!==void 0){this.announceSource();return}const targeted=changed.size===0&&this.hasAuthoredItems&&this.dirtyConfigureRoots.size>0;if(targeted){const nodes=this.nodeElements,count=nodes.length,positions=this.dirtyConfigureRoots.size>1?new Map(nodes.map((node,index)=>[node,index])):void 0;for(const node of this.dirtyConfigureRoots){const i=positions?positions.get(node)??-1:nodes.indexOf(node);i<0||configureTreeItemOwner(node,{...treeItemOwnerContext(node),activeId:null,activeNodeId:this.readActiveId,ancestry:[],depth:0,setSize:count,posInSet:i+1,selection:this.selection,ownsSelection:!0,identity:void 0,expandIcon:this.iconSource("expand-icon"),collapseIcon:this.iconSource("collapse-icon"),pointerReorderable:this.pointerReorderable,syncOwner:this.requestContextSync,focusOwner:this.onItemFocus})}}else if(changed.has("activeId")||changed.has("data")||this.hasAuthoredItems){const nodes=this.nodeElements,count=this.hasAuthoredItems?nodes.length:this.declaredRootCount;nodes.forEach((node,i)=>{configureTreeItemOwner(node,{...treeItemOwnerContext(node),activeId:null,activeNodeId:this.readActiveId,ancestry:[],depth:0,setSize:count,posInSet:i+1,selection:this.selection,ownsSelection:!0,identity:this.hasAuthoredItems?void 0:this.treeIdentityAt(String(i)),expandIcon:this.iconSource("expand-icon"),collapseIcon:this.iconSource("collapse-icon"),pointerReorderable:this.pointerReorderable,syncOwner:this.requestContextSync,focusOwner:this.onItemFocus})})}targeted||(this.contextSyncPending=!0),this.dirtyConfigureRoots.clear(),this.scheduleTreeSync()}scheduleTreeSync(){this.treeSource===void 0&&(this.syncRequested=!0,!(this.syncRunning||this.bulkExpansions>0)&&(this.syncRunning=!0,this.syncTask=this.runTreeSync()))}async runTreeSync(){const generation=this.syncGeneration;try{for(;this.syncRequested&&(this.syncRequested=!1,await super.getUpdateComplete(),!(this.treeSource!==void 0||generation!==this.syncGeneration||(await cascadeUpdateComplete(this.nodeElements),this.treeSource!==void 0||generation!==this.syncGeneration)||(this.contextSyncPending&&(this.contextSyncPending=!1,this.applyTreeContext()),this.selectionSyncPending&&(this.selectionSyncPending=!1,this.normalizeSelection()),await cascadeUpdateComplete(this.nodeElements),this.treeSource!==void 0||generation!==this.syncGeneration)));)this.reportRefreshSelectionChange(),this.confirmPendingReorder(),this.confirmPointerReorder(),this.restorePendingFocus()}finally{generation===this.syncGeneration&&(this.syncRunning=!1)}}rootTreeItemAncestor(node){const itemTag=tag("tree-item");let current=node;for(;current&¤t.parentElement&¤t.parentElement!==this;)current=current.parentElement;return current&¤t.parentElement===this&¤t.localName===itemTag?current:null}connectedCallback(){super.connectedCallback(),this.armChildObserver()}armChildObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected||this.treeSource!==void 0||this.childObserver&&this.childObserverDocument===ownerDocument)return;this.resetChildObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.childObserverGeneration,observer=new MutationObserverCtor(records=>{this.childObserver!==observer||this.childObserverDocument!==ownerDocument||this.childObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.onChildMutations(records)});this.childObserver=observer,this.childObserverDocument=ownerDocument,observer.observe(this,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0,attributeFilter:["selected","disabled","inert","lazy"]})}disconnectedCallback(){this.pointerOrder.cancel(),this.pointerOrder.clearClick(),this.pendingPointerReorder=void 0,super.disconnectedCallback(),this.sourceAnnouncement=void 0,this.bulkExpansionGeneration++,this.pendingReorder=void 0,this.activeNode=void 0,this.resetChildObserver()}adoptedCallback(){super.adoptedCallback(),this.hierarchy.adopted(),this.resetChildObserver()}resetChildObserver(){this.childObserverGeneration+=1,this.childObserver?.disconnect(),this.childObserver=void 0,this.childObserverDocument=void 0}syncNodes(){const existingById=new Map;for(const node of this.nodeElements){if(!node.item)continue;const matches=existingById.get(node.item.id)??[];matches.push(node),existingById.set(node.item.id,matches)}let previousSibling=null;for(let index=0;index<this.data.length;index++){const item=this.data[index];let node=existingById.get(item.id)?.shift();node||(node=this.ownerDocument.createElement(tag("tree-item")),this.generatedNodes.add(node)),node.item=item,configureTreeItemOwner(node,{...treeItemOwnerContext(node),ancestry:[],depth:0,setSize:this.declaredRootCount,posInSet:index+1,selection:this.selection,ownsSelection:!0,identity:this.treeIdentityAt(String(index)),dataExpansion:this.dataExpansion,expansionVisible:!0,expandIcon:this.iconSource("expand-icon"),collapseIcon:this.iconSource("collapse-icon"),pointerReorderable:this.pointerReorderable,syncOwner:this.requestContextSync,focusOwner:this.onItemFocus});const targetPosition=previousSibling?previousSibling.nextElementSibling:this.firstElementChild;targetPosition!==node&&this.insertBefore(node,targetPosition),previousSibling=node}for(const nodes of existingById.values())for(const node of nodes)node.remove()}focusNode(node){node&&(this.setActiveNode(node),node.focus())}subtreeHasId(root,id){if(id==null)return!1;const stack=this.childrenOf(root).map(item=>({item,depth:treeItemOwnerContext(root).depth+1}));for(let visited=0;stack.length>0&&visited<this.nodeWalkLimit;visited++){const{item,depth}=stack.pop();if(!(depth>TREE_MAX_RENDER_DEPTH)){if(item.nodeId===id)return!0;depth<TREE_MAX_RENDER_DEPTH&&stack.push(...this.childrenOf(item).map(child=>({item:child,depth:depth+1})))}}return!1}focusIsWithin(node){for(let current=deepActiveElementIn(this.ownerDocument);current;current=composedParentElement(current)){if(current===node)return!0;if(current===this)return!1}return!1}eventNode(e){const path=e.composedPath(),origin=path[0];if(origin?.nodeType===1&&origin.localName===tag("tree-item")){const treeTag=tag("tree");for(const target of path){if(target===this)return origin;if(target.localName===treeTag)return}return}const id=e.detail?.nodeId;return this.allNodeElements().find(candidate=>candidate.nodeId===id)}async getUpdateComplete(){let result=await super.getUpdateComplete();if(this.treeSource!==void 0)return result;for(;this.syncRunning||this.isUpdatePending;)this.syncRunning&&await this.syncTask,result=await super.getUpdateComplete();return this.treeSource===void 0&&await cascadeUpdateComplete(this.nodeElements),result}reportRefreshSelectionChange(){const before=this.selectionBeforeRefresh;if(before===void 0||this.isUpdatePending)return;this.selectionBeforeRefresh=void 0;const selection=this.selectedItems;selection.length===before.length&&selection.every((item,index)=>item.nodeId===before[index])||this.emit("lr-selection-change",Object.freeze({selection}))}restorePendingFocus(){if(this.pendingFocusId==null)return;const id=this.pendingFocusId;this.pendingFocusId=null;const visible=this.visibleNodeElements();(visible.find(n=>n.nodeId===id)??visible.find(n=>n.nodeId===this.activeId))?.focus()}requestReorder(node,delta){const id=node.nodeId,found=this.findRenderedSiblings(node);if(!found)return;const{parent,siblings,index}=found,total=siblings.length,toIndex=index+delta;toIndex<0||toIndex>=total||(this.pendingReorder={node,parent,originalSiblings:[...siblings],targetSibling:siblings[toIndex],fromIndex:index,toIndex},this.emit("lr-reorder",{nodeId:id,parentNodeId:parent?.nodeId??null,fromIndex:index,toIndex}))}confirmPendingReorder(){const pending=this.pendingReorder;if(!pending)return;const found=this.findRenderedSiblings(pending.node);if(!found){this.pendingReorder=void 0;return}(found.siblings.length!==pending.originalSiblings.length||found.siblings.some((node,index)=>node!==pending.originalSiblings[index]))&&(this.pendingReorder=void 0,!(found.parent!==pending.parent||found.index!==pending.toIndex||found.siblings[pending.fromIndex]!==pending.targetSibling)&&this.liveRegion?.announce(this.localize("treeNodeMoved",void 0,{label:pending.node.nodeLabel,index:this.formatCount(found.index+1),total:this.formatCount(found.siblings.length)}),{force:!0}))}pointerSiblingIds(parentId,nodes){return parentId===null?this.nodeElements.map(node=>node.nodeId):nodes.find(node=>node.nodeId===parentId)?.childItems().map(node=>node.nodeId)??[]}confirmPointerReorder(){const request=this.pendingPointerReorder;if(!request)return;const pending=request.detail,nodes=this.visibleNodeElements(),node=nodes.find(item=>item.nodeId===pending.nodeId),anchor=nodes.find(item=>item.nodeId===pending.targetNodeId),location=node&&this.findRenderedSiblings(node);if(!node||!anchor||!location){this.pendingPointerReorder=void 0;return}const parentId=location.parent?.nodeId??null,source=this.pointerSiblingIds(pending.fromParentNodeId,nodes),sameParent=pending.fromParentNodeId===pending.toParentNodeId,target=sameParent?source:this.pointerSiblingIds(pending.toParentNodeId,nodes),sameOrder=(left,right)=>left.length===right.length&&left.every((id,index)=>right[index]===id);if(sameOrder(source,request.sourceOrder)&&sameOrder(target,request.targetOrder))return;this.pendingPointerReorder=void 0;const removed=request.sourceOrder.filter(id=>id!==pending.nodeId),expected=[...sameParent?removed:request.targetOrder];if(expected.splice(pending.toIndex,0,pending.nodeId),!sameOrder(target,expected)||!sameParent&&!sameOrder(source,removed))return;const anchorIndex=location.index+(pending.position==="before"?1:-1);parentId!==pending.toParentNodeId||location.index!==pending.toIndex||location.siblings[anchorIndex]!==anchor||this.liveRegion?.announce(this.localize("treeNodeMoved",void 0,{label:node.nodeLabel,index:this.formatCount(location.index+1),total:this.formatCount(location.siblings.length)}),{force:!0})}async expandAll(){if(this.treeSource!==void 0)return;const generation=this.bulkExpansionGeneration,changed=new Set;let level=this.nodeElements.map(node=>({node,depth:0}));const seen=new Set,systemReduced=preferenceMediaMatches(this.ownerDocument.defaultView,"(prefers-reduced-motion: reduce)");this.bulkExpansions+=1;try{for(;level.length>0&&seen.size<this.nodeWalkLimit&&generation===this.bulkExpansionGeneration;){const current=[];for(const entry of level){const{node}=entry;if(generation!==this.bulkExpansionGeneration)break;if(!(!node.isConnected||seen.has(node)||seen.size>=this.nodeWalkLimit)){if(seen.add(node),current.push(entry),node.isDisabled)node.expanded=!1;else if(node.hasChildren){const reduced=systemReduced||inheritedPreference(node,"data-lr-motion","reduce")==="reduce",wasExpanded=node.expanded;withTreeItemMotionPreference(node,reduced,()=>node.expand()),!wasExpanded&&node.expanded&&changed.add(node.nodeId)}}}await Promise.all(current.map(({node})=>node.updateComplete)),level=[];for(const{node,depth}of current)depth<TREE_MAX_RENDER_DEPTH&&level.push(...this.childrenOf(node).map(child=>({node:child,depth:depth+1})))}}finally{this.bulkExpansions-=1}this.bulkExpansions===0&&this.syncRequested&&this.scheduleTreeSync(),await this.updateComplete,generation===this.bulkExpansionGeneration&&this.emitBulkToggle(!0,changed)}async collapseAll(){if(this.treeSource!==void 0)return;this.bulkExpansionGeneration++;const changed=new Set,focused=this.deepFocusedNode(),topLevel=this.nodeElements,nodes=this.allNodeElements();if(!this.hasAuthoredItems){const mounted=new Set;for(const node of nodes)node.item&&mounted.add(node.item);this.dataExpansion.closeAll(changed,mounted)}for(let index=nodes.length-1;index>=0;index--){if(this.treeSource!==void 0)return;const node=nodes[index];if(node.isDisabled)node.expanded=!1;else{const counted=node.expanded&&node.hasChildren;node.collapse(),counted&&!node.expanded&&changed.add(node.nodeId)}}(this.hasAuthoredItems?topLevel.some(node=>this.isNavigable(node)&&node.nodeId===this.activeId):this.data.some(item=>!item.disabled&&item.id===this.activeId))||(this.activeId=this.hasAuthoredItems?topLevel.find(node=>this.isNavigable(node))?.nodeId??null:this.firstEnabledId(this.data)),focused&&(this.pendingFocusId=this.activeId),await cascadeUpdateComplete(topLevel),this.isConnected&&this.treeSource===void 0&&this.emitBulkToggle(!1,changed)}emitBulkToggle(expanded,changed){changed.size>0&&this.emit("lr-bulk-toggle",Object.freeze({expanded,nodeIds:Object.freeze([...changed])}))}render(){return this.treeSource!==void 0?hierarchySourceView(this.hierarchy,{label:hostAriaLabel(this)??this.label,rtl:this.effectiveDirection==="rtl",multiple:this.selection==="multiple"||this.selection==="leaf-multiple",loading:this.localize("loading"),error:this.localize("treeSourceError"),empty:this.localize("noData"),retry:this.localize("retry"),expand:this.localize("expand"),collapse:this.localize("collapse"),summary:this.sourceSummary(),name:value=>value.accessibleLabel||[value.label,value.description,...(value.badges??[]).map(badge=>badge.label?.trim()?badge.label:badge.text)].filter(text=>text?.trim()).join(" ")||value.id,content:value=>html`${value.icon??nothing}${value.label}${value.description?html` <span>${value.description}</span>`:nothing}${value.badges?.map(badge=>html` <span role=${badge.label?.trim()?"img":nothing} aria-label=${badge.label?.trim()?badge.label:nothing}>${badge.text}</span>`)}`,select:row=>{if((this.selection==="leaf"||this.selection==="leaf-multiple")&&row.childCount>0)return;const multiple=this.selection==="multiple"||this.selection==="leaf-multiple";this.hierarchy.project({type:"select",key:row.key,selected:multiple?!row.selected:!0,scope:multiple&&row.childCount>0?"subtree":"item"},!0,row)}}):html`
|
|
2
2
|
<div
|
|
3
3
|
part="base tree"
|
|
4
4
|
role="tree"
|
|
5
5
|
aria-label=${hostAriaLabel(this)??(this.label||nothing)}
|
|
6
6
|
aria-multiselectable=${String(this.selection==="multiple"||this.selection==="leaf-multiple")}
|
|
7
|
+
@pointerdown=${this.pointerOrder.start}
|
|
7
8
|
@focusin=${this.onTreeFocusIn}
|
|
8
9
|
@keydown=${this.onTreeKeyDown}
|
|
9
10
|
@lr-node-toggle=${this.onNodeActivate}
|
|
@@ -11,9 +12,10 @@ import{__decorate}from"tslib";import{HierarchySourceController,hierarchyField,hi
|
|
|
11
12
|
>
|
|
12
13
|
${this.data.length===0&&!this.hasAuthoredItems?html`<lr-empty part="empty" heading=${this.localize("noData")}></lr-empty>`:nothing}
|
|
13
14
|
<slot @slotchange=${this.onChildrenChanged}></slot>
|
|
15
|
+
${this.pointerReorderable?html`<span part="drop-indicator" aria-hidden="true" hidden></span>`:nothing}
|
|
14
16
|
<slot name="expand-icon" hidden @slotchange=${this.onChildrenChanged}></slot>
|
|
15
17
|
<slot name="collapse-icon" hidden @slotchange=${this.onChildrenChanged}></slot>
|
|
16
18
|
</div>
|
|
17
19
|
${this._limitReached?html`<div part="limit">${this.localize("treeLimit",void 0,{count:this.formatCount(this.effectiveMaxNodes)})}</div>`:nothing}
|
|
18
|
-
${this.reorderable?html`<lr-live-region></lr-live-region>`:nothing}
|
|
19
|
-
`}formatCount(value){return getNumberFormat(this.effectiveLocale).format(value)}}__decorate([property({attribute:!1})],LyraTree.prototype,"treeSource",null),__decorate([property({attribute:!1})],LyraTree.prototype,"data",null),__decorate([property()],LyraTree.prototype,"label",void 0),__decorate([property({type:Number,attribute:"max-nodes"})],LyraTree.prototype,"maxNodes",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraTree.prototype,"reorderable",void 0),__decorate([property()],LyraTree.prototype,"selection",null),__decorate([state()],LyraTree.prototype,"hasAuthoredItems",void 0),__decorate([query("lr-live-region")],LyraTree.prototype,"liveRegion",void 0);export{LyraTree};
|
|
20
|
+
${this.reorderable||this.pointerReorderable?html`<lr-live-region></lr-live-region>`:nothing}
|
|
21
|
+
`}formatCount(value){return getNumberFormat(this.effectiveLocale).format(value)}}__decorate([property({reflect:!0,converter:optionalSizeConverter})],LyraTree.prototype,"size",null),__decorate([property({attribute:!1})],LyraTree.prototype,"treeSource",null),__decorate([property({attribute:!1})],LyraTree.prototype,"data",null),__decorate([property()],LyraTree.prototype,"label",void 0),__decorate([property({type:Number,attribute:"max-nodes"})],LyraTree.prototype,"maxNodes",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraTree.prototype,"reorderable",void 0),__decorate([property({type:Boolean,attribute:"pointer-reorderable",reflect:!0})],LyraTree.prototype,"pointerReorderable",void 0),__decorate([property({type:Boolean,attribute:"allow-cross-parent-reorder",reflect:!0})],LyraTree.prototype,"allowCrossParentReorder",void 0),__decorate([property({attribute:!1})],LyraTree.prototype,"canDrop",void 0),__decorate([property()],LyraTree.prototype,"selection",null),__decorate([state()],LyraTree.prototype,"hasAuthoredItems",void 0),__decorate([query("lr-live-region")],LyraTree.prototype,"liveRegion",void 0);export{LyraTree};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{css}from"lit";const styles=css`:host{display:block}[part~=base]{flex-direction:column;display:flex;overflow:auto hidden}[part=limit]{padding:var(--lr-space-s);color:var(--lr-color-text-quiet);font-size:var(--lr-font-size-sm)}`;export{styles};
|
|
1
|
+
import{css}from"lit";const styles=css`:host{--_lr-tree-tier-row-height:initial;--_lr-tree-tier-row-padding:initial;--_lr-tree-tier-toggle-size:calc(var(--_lr-tree-tier-row-height) - var(--lr-space-xs));display:block}:host([size]){--_lr-tree-tier-row-padding:0}:host([size="2xs"]){--_lr-tree-tier-row-height:var(--lr-size-1-25rem)}:host([size=xs]){--_lr-tree-tier-row-height:var(--lr-size-1-5rem)}:host([size=s]),:host([size=small]){--_lr-tree-tier-row-height:var(--lr-size-2rem)}:host([size=m]),:host([size=medium]){--_lr-tree-tier-row-height:var(--lr-size-2-25rem)}:host([size=l]),:host([size=large]){--_lr-tree-tier-row-height:var(--lr-size-2-5rem)}:host([size=xl]){--_lr-tree-tier-row-height:var(--lr-size-3-5rem)}[part=drop-indicator]{z-index:var(--lr-layer-content);pointer-events:none;block-size:var(--lr-border-width-medium);background:var(--lr-tree-drop-indicator-color,var(--lr-color-brand));position:absolute;transform:translateY(-50%)}[part~=base]{flex-direction:column;display:flex;position:relative;overflow:auto hidden}[part=limit]{padding:var(--lr-space-s);color:var(--lr-color-text-quiet);font-size:var(--lr-font-size-sm)}`;export{styles};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{capOptionRows}from"../../../internal/option-selection.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{VetoWriteGuard,markVetoGuardWrite}from"../../../internal/veto-write-guard.js";import{renderFormControlHintError}from"../../../internal/form-control-template.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{FormControlController,reflectFormName}from"../../../internal/form-control-controller.js";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{acquireNativeControlDescription}from"../../../internal/native-control-description.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{deferredPlaceReady as place,syncTopLayerRelease,topLayerPlacement}from"../../../internal/anchored-overlay-runtime.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{chevronIcon,closeIcon}from"../../../internal/icons.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{PopupController,emitPopupEvent}from"../../../internal/popup-controller.js";import{revealRow}from"../../../internal/reveal-row.js";import{TypeAheadBuffer}from"../../../internal/type-ahead-buffer.js";import{resolveListMove}from"../../../internal/list-navigation.js";import{finiteCount}from"../../../internal/numbers.js";import{getNumberFormat,resolveIntlLocale}from"../../../internal/intl-cache.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{styles}from"./select.styles.js";import{sizes}from"../../../internal/sizes.styles.js";import"../combobox/option.class.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{omittedEmptyStringConverter,optionalLiteralSetConverter}from"../../../internal/converters.js";import{getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{isOptionSelectedDirty,isOptionSelectedWrite,wasOptionInitiallySelected,RESET_OPTION_SELECTED_FROM_OWNER,SET_OPTION_SELECTED_FROM_OWNER}from"../../../internal/option-selection.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{tag}from"../../../internal/prefix.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_selectSelectedOverflow,LYRA_DEFAULT_selectValueMissing}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_loading,LYRA_DEFAULT_notInCatalog,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();function isLyraOptionElement(value){return isHtmlElement(value)&&value.localName===tag("option")}function normalizeSelectionValues(next){return Array.isArray(next)?next.filter(value=>typeof value=="string"):typeof next=="string"?[next]:[]}const POSITIONING_STRATEGY=optionalLiteralSetConverter(["absolute","fixed"]);class LyraSelect extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,fieldRequired:LYRA_DEFAULT_fieldRequired,loading:LYRA_DEFAULT_loading,notInCatalog:LYRA_DEFAULT_notInCatalog,removeWithContext:LYRA_DEFAULT_removeWithContext,select:LYRA_DEFAULT_select,selectSelectedOverflow:LYRA_DEFAULT_selectSelectedOverflow,selectValueMissing:LYRA_DEFAULT_selectValueMissing}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-input","lr-change","lr-change-request"])}static{this.identityEventDetailCollectionItems=Object.freeze({"lr-input":Object.freeze(["data"]),"lr-change":Object.freeze(["data"]),"lr-change-request":Object.freeze(["data"])})}static get validators(){return[currentValidityValidator("required","disabled","value","multiple")]}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles,srOnly]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},multiple:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},value:{noAccessor:!0},name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},maxOptionsVisible:{type:Number,attribute:"max-options-visible",noAccessor:!0},defaultValue:{attribute:"default-value",noAccessor:!0}}}get open(){return this._open}set open(next){const requested=!!next,normalized=requested&&!this.effectiveDisabled;if(normalized===this._open){requested!==normalized&&this.hasAttribute("open")&&this.removeAttribute("open");return}this.applyOpenState(normalized)}get positioningStrategy(){return this._positioningStrategy??"absolute"}set positioningStrategy(next){const normalized=POSITIONING_STRATEGY.normalize(next)??"absolute",old=this.positioningStrategy;this._positioningStrategy=normalized,normalized!==old&&(this.requestUpdate("positioningStrategy",old),old==="fixed"!=(normalized==="fixed")&&this.requestUpdate("hoist",old==="fixed"))}get hoist(){return this.positioningStrategy==="fixed"}set hoist(next){this.positioningStrategy=next?"fixed":"absolute"}requestUpdate(...args){args[0]===void 0&&(this.callbackRefreshEpoch=(this.callbackRefreshEpoch??0)+1),super.requestUpdate(...args)}memoOption(key,inputs,compute){const previous=this.optionMemo.get(key);if(previous&&previous.inputs.length===inputs.length&&previous.inputs.every((input,index)=>Object.is(input,inputs[index])))return previous.value;const value=compute();return this.optionMemo.set(key,{inputs,value}),value}get optionIndex(){return this.memoOption("index",[this.options],()=>{const values=new Map,positions=new Map;return this.options.forEach((option,index)=>{positions.set(option,index),values.has(option.value)||values.set(option.value,option)}),{values,positions,members:new Set(this.options)}})}get selectedIndex(){return this.memoOption("selectedIndex",[this._selectedOptions,this.options],()=>{const values=new Map;for(const option of this._selectedOptions)values.has(option.value)||values.set(option.value,option);return{values,members:new Set(this._selectedOptions)}})}focus(options){this.effectiveDisabled||this.triggerElement?.focus(options)}blur(){this.triggerElement?.blur()}click(){this.effectiveDisabled||this.triggerElement?.click()}constructor(){super(),this.placeholder="",this.label="",this.labelDisplay="visible",this.hint="",this.helpText="",this.withLabel=!1,this.withHint=!1,this.errorText="",this.autofocus=!1,this.title="",this._open=!1,this.size="m",this.appearance="outlined",this.pill=!1,this.placement="bottom",this.topLayer=!1,this.filled=!1,this.withClear=!1,this.clearable=!1,this.withUnknownOption=!1,this.loading=!1,this.autoCommitSingleOption=!1,this.activeIndex=-1,this.maxRender=200,this.options=[],this.callbackRefreshEpoch=0,this.optionMemo=new Map,this.optionsObserved=!1,this.touched=!1,this.hasInteracted=!1,this.slotPresence=new SlotPresenceController(this),this._fieldsetDisabled=!1,this.listId=nextId("select-list"),this.triggerId=nextId("select-trigger"),this.valueTextId=nextId("select-value"),this.positioningReady=Promise.resolve(!1),this.restoreFocusOnClose=!0,this.popupController=new PopupController({host:this,popup:()=>this.renderRoot.querySelector('[part="listbox"]'),emit:(name,cancelable)=>emitPopupEvent(this,name,cancelable),onPointer:event=>this.onDocPointer(event)}),this.listboxHidden=!0,this.listboxRendered=!1,this.listboxPositioned=!1,this._isFirstUpdate=!0,this.openVetoed=!1,this.previousValue="",this.openStateGeneration=0,this._selected=[],this._selectedOptions=[],this._selectedValuesByOption=new Map,this.adornmentClones=new WeakMap,this._multiple=!1,this._disabled=!1,this._required=!1,this._defaultSelected=[],this._defaultSelectedOptions=[],this._defaultCaptured=!1,this._valueDirty=!1,this._restoredStateActive=!1,this._resolvingPendingInitialSelection=!1,this._defaultValueDirty=!1,this.typeBuffer=new TypeAheadBuffer(this),this._name="",this._maxOptionsVisible=3,this.localDescriptionIds="",this.markInteracted=()=>{this.touched=!0,!this.hasInteracted&&(this.hasInteracted=!0,this.reflectValidityStates())},this.collectOptions=e=>{this.collectOptionsFromSlot(e.target)},this.unknownOptionCache=new Map,this.pendingSelectedWrites=new Map,this.selectedWritesQueued=!1,this.optionRefreshPending=!1,this.onOptionChange=e=>{e.stopPropagation();const option=e.composedPath().find(isLyraOptionElement);if(isOptionSelectedWrite(e)&&isLyraOptionElement(option)&&this.optionIndex.members.has(option)){markVetoGuardWrite(this.selectionWriteGuard),this._valueDirty=!0,this._restoredStateActive=!1,this.pendingSelectedWrites.delete(option),this.pendingSelectedWrites.set(option,{selected:option.selected,value:option.value}),this.selectedWritesQueued||(this.selectedWritesQueued=!0,queueMicrotask(()=>this.flushSelectedWrites()));return}if(isLyraOptionElement(option)){const cached=this.adornmentClones.get(option);cached&&cached.markup!==this.adornmentMarkup(option)&&this.adornmentClones.delete(option)}if(this.optionRefreshPending)return;this.optionRefreshPending=!0;const previousActive=this.activeOption,previousActiveRawIndex=previousActive?this.options.indexOf(previousActive):this.activeIndex;queueMicrotask(()=>{this.optionRefreshPending=!1,this.refreshOptionDefaults(),this.reflectSelected(),this.options=[...this.options],this.reconcileActiveOption(previousActive,previousActiveRawIndex)})},this.onDocPointer=e=>{if(!e.composedPath().includes(this)){if(this.overlayHandle?.isActive()){this.overlayHandle.dismissBackdrop();return}this.restoreFocusOnClose=!1,this.hide()}},this.selectionWriteGuard=new VetoWriteGuard,this.selectionRequestDispatching=!1,this.onTriggerClick=()=>{if(!this.effectiveDisabled){if(this.onlyOption)return this.selectOption(this.onlyOption);this.open?this.hide():this.show()}},this.onTriggerBlur=event=>{this.effectiveDisabled||(this.touched=!0,this.hasInteracted=!0,this.reflectValidityStates()),this.open&&(this.restoreFocusOnClose=!1),this.hide(),relayNativeEvent(this,event)},this.onTriggerFocus=event=>{relayNativeEvent(this,event)},this.onKeyDown=e=>{if(e.isComposing||e.keyCode===229)return;const navigable=this.navigableOptions(),move=()=>resolveListMove(e,{count:navigable.length,current:this.activeIndex,orientation:"vertical",wrap:!1,clamp:!0,backwardFromMissing:"first"});switch(e.key){case"ArrowDown":if(e.preventDefault(),this.onlyOption)return this.selectOption(this.onlyOption);if(!this.open){this.show();return}this.setActiveIndex(move()??-1,navigable);break;case"ArrowUp":if(e.preventDefault(),this.onlyOption)return this.selectOption(this.onlyOption);if(!this.open){this.show();return}this.setActiveIndex(move()??-1,navigable);break;case"Enter":case" ":if(this.open){e.preventDefault();const active=navigable[this.activeIndex];this.activeIndex>=0&&active?this.selectOption(active):this.hide()}break;case"Escape":this.open&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(e.preventDefault(),this.hide());break;case"Home":this.open&&(e.preventDefault(),this.setActiveIndex(move()??-1,navigable));break;case"End":this.open&&(e.preventDefault(),this.setActiveIndex(move()??-1,navigable));break;case"Backspace":case"Delete":this.multiple&&this._selected.length>0&&(e.preventDefault(),this.removeValueAt(this._selected.length-1));break;default:this.typeBuffer.accepts(e)&&this.typeAhead(e.key);break}},this.onListboxMouseDown=e=>{e.preventDefault()},this.onListboxClick=e=>{const optionEl=e.target.closest('[part="option"]'),index=Number(optionEl?.dataset.index);if(!Number.isInteger(index))return;const option=this.listboxOptions[index];option&&this.selectOption(option)},this.validityController=new FormControlController(this,{invalid:init=>this.emit("lr-invalid",null,init),interacted:this.markInteracted,customError:()=>this.validityController.customValidityMessage}),this.internals=this.validityController.formInternals,new GlassScrollLayer(this,'[part="listbox"]',()=>this.open),this.syncFormValue()}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"]')??null}syncExternalDescription(){if(!this.isConnected)return;const target=this.renderRoot.querySelector('[part="trigger"]');target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireNativeControlDescription(this,target,()=>this.localDescriptionIds))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.updateValidity(),this.hasUpdated&&this.open&&queueMicrotask(()=>this.reconnectOpenPopup())}willUpdate(changed){if(super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,this._isFirstUpdate&&(this._pendingInitialDefaultValue!==void 0||this._pendingInitialValue!==void 0)){this._resolvingPendingInitialSelection=!0;try{if(this._pendingInitialDefaultValue!==void 0){const pending=this._pendingInitialDefaultValue;this._pendingInitialDefaultValue=void 0,this.assignDefaultValue(pending)}if(this._pendingInitialValue!==void 0){const pending=this._pendingInitialValue;this._pendingInitialValue=void 0,this.assignValue(pending)}}finally{this._resolvingPendingInitialSelection=!1}}if(this.announceOpenTransition(changed),changed.has("open")&&!this.openVetoed&&(this.listboxPositioned=!1),this.open&&(this.listboxHidden=!1,this.listboxRendered=!0),changed.has("open")&&!this.openVetoed){const navigable=this.navigableOptions();this.setActiveIndex(this.open?navigable.findIndex(option=>this.selectedIndex.members.has(option)):-1,navigable)}}firstUpdated(changed){super.firstUpdated(changed);const slot=this.optionsSlot;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>{const assigned=s.assignedElements({flatten:!0});this.optionsObserved=!0,assigned.some(isLyraOptionElement)&&this.collectOptionsFromSlot(s)})})}applyOpenState(next){const old=this._open;this.pendingOpenTransitionStart===void 0&&(this.pendingOpenTransitionStart=old),this.openStateGeneration++,this._open=next,this.requestUpdate("open",old)}forceCloseOpenState(){this.listboxHidden=!0;const isClosing=this._open||this.pendingOpenTransitionStart===!0;if(this.popupController.cancel(),!this._open){isClosing&&(this.suppressedOpenLifecycleGeneration=this.openStateGeneration),this.hasAttribute("open")&&this.removeAttribute("open");return}this.applyOpenState(!1),this.suppressedOpenLifecycleGeneration=this.openStateGeneration}announceOpenTransition(changed){if(this.openVetoed=!1,!(!changed.has("open")||this._isFirstUpdate||this.suppressedOpenLifecycleGeneration===this.openStateGeneration)){if(!this.isConnected){emitPopupEvent(this,"lr-hide",!1);return}this.openVetoed=this.popupController.announce(this.open,()=>{this.open=!this.open})}}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",reflectFormName(this,this._name),this.syncFormValue(),this.requestUpdate("name",old)}get multiple(){return this._multiple}set multiple(next){markVetoGuardWrite(this.selectionWriteGuard);const old=this._multiple;this._multiple=!!next,this.toggleAttribute("multiple",this._multiple),!this._multiple&&this._selected.length>1?this.setSelection(this._selected.slice(0,1),this._selectedOptions.slice(0,1)):this.syncFormValue(),this.requestUpdate("multiple",old)}get maxOptionsVisible(){return this._maxOptionsVisible}set maxOptionsVisible(next){const old=this._maxOptionsVisible;this._maxOptionsVisible=finiteCount(next,3),this.requestUpdate("maxOptionsVisible",old)}get disabled(){return this._disabled}set disabled(next){markVetoGuardWrite(this.selectionWriteGuard);const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this._disabled&&this.forceCloseOpenState(),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get value(){return this.multiple?[...this._selected]:this._selected[0]??""}set value(next){this._resolvingPendingInitialSelection||(this._pendingInitialSelectedOptions=void 0,this.hasUpdated||(this._pendingInitialValue=next)),this._restoredStateActive=!1,this._valueDirty=!0;const values=normalizeSelectionValues(next);this.setSelection(values)}get defaultValue(){return this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??""}set defaultValue(next){!this.hasUpdated&&!this._resolvingPendingInitialSelection&&(this._pendingInitialDefaultValue=next),this._defaultValueDirty=!0;const old=this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??"",values=normalizeSelectionValues(next);this._defaultSelected=this.multiple?[...values]:values.slice(0,1),this._defaultSelectedOptions=this.resolveOccurrences(this._defaultSelected),!this._valueDirty&&!this._restoredStateActive&&this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions]),this.requestUpdate("defaultValue",old)}get selectedOptions(){return[...this._selectedOptions]}set selectedOptions(next){const candidates=Array.isArray(next)?next:[];this._resolvingPendingInitialSelection||(this._pendingInitialValue=void 0,this._pendingInitialSelectedOptions=this.hasUpdated?void 0:candidates.filter(option=>isLyraOptionElement(option)&&this.contains(option))),this._restoredStateActive=!1,this._valueDirty=!0;const catalog=candidates.length>1?new Set(this.options):void 0,seen=new Set,live=candidates.filter(option=>seen.has(option)?!1:(seen.add(option),isLyraOptionElement(option)&&this.contains(option)&&(catalog?catalog.has(option):this.options.includes(option)))),selected=this.multiple?live:live.slice(0,1);this.setSelection(selected.map(option=>option.value),selected)}get selectedData(){return this.resolveOccurrenceSlots(this._selected,this._selectedOptions).map(option=>option?.data)}setSelection(next,preferred=[]){this.pendingSelectedWrites.clear(),markVetoGuardWrite(this.selectionWriteGuard);const values=this.multiple?[...next]:next.slice(0,1),previousValues=this._selected,previousOptions=this._selectedOptions,old=this.multiple?[...previousValues]:previousValues[0]??"";this.previousValue=old,this._selected=values,this._selectedOptions=this.resolveOccurrences(values,preferred),this.syncFormValue(),this.reflectSelected(),this.updateValidity(),this.requestUpdate("value",old);const sameValues=previousValues.length===values.length&&previousValues.every((value,i)=>value===values[i]),sameOptions=previousOptions.length===this._selectedOptions.length&&previousOptions.every((option,i)=>option===this._selectedOptions[i]);sameValues&&!sameOptions&&this.requestUpdate()}resolveOccurrences(values,preferred=[]){return this.resolveOccurrenceSlots(values,preferred).filter(option=>option!==void 0)}resolveOccurrenceSlots(values,preferred=[]){if(values.length===0)return[];if(values.length===1){const value=values[0],hint=preferred.length===1?preferred[0]:preferred.find(option=>option?.value===value);return[hint&&hint.value===value&&this.options.includes(hint)?hint:this.options.find(option=>option.value===value)]}const requested=new Set(values),catalog=new Set(this.options),claimed=new Set,queuesFor=options=>{const queues=new Map;for(const option of options){if(!option)continue;const value=option.value;if(!requested.has(value))continue;let queue=queues.get(value);queue||queues.set(value,queue={options:[],next:0}),queue.options.push(option)}return queues},firstUnclaimed=(queues,value)=>{const queue=queues.get(value);if(queue){for(;queue.next<queue.options.length&&claimed.has(queue.options[queue.next]);)queue.next++;return queue.options[queue.next]}},preferredQueues=preferred.length===values.length?void 0:queuesFor(preferred);let fallbackQueues;return values.map((value,index)=>{const hint=preferredQueues?firstUnclaimed(preferredQueues,value):preferred[index],match=hint&&hint.value===value&&catalog.has(hint)&&!claimed.has(hint)?hint:firstUnclaimed(fallbackQueues??=queuesFor(this.options),value);if(match)return claimed.add(match),match})}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){this.barredFromValidation?this.validityController.setValidity({}):this.required&&this._selected.length===0?this.validityController.setValidity({valueMissing:!0},this.localize("selectValueMissing")):this.validityController.setValidity({}),this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",this._selected.length===0)}syncFormValue(){if(!this.multiple){this.internals.setFormValue(this._selected[0]??"");return}const state2=JSON.stringify(this._selected);if(!this.name){this.internals.setFormValue(null,state2);return}const data=new FormData;for(const value of this._selected)data.append(this.name,value);this.internals.setFormValue(data,state2)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formResetCallback(){this._pendingInitialValue=void 0,this._pendingInitialSelectedOptions=void 0,this.touched=!1,this.hasInteracted=!1,this._restoredStateActive=!1,this._valueDirty=!1;const resetOptions=this._defaultSelectedOptions.length>0?this._defaultSelectedOptions:this.options.filter(option=>wasOptionInitiallySelected(option));this._defaultSelectedOptions.length===0&&resetOptions.length>0&&(this._defaultSelectedOptions=[...resetOptions],this._defaultSelected=resetOptions.map(option=>option.value));const defaults=new Set(resetOptions);for(const option of this.options)option[RESET_OPTION_SELECTED_FROM_OWNER](defaults.has(option));this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}formStateRestoreCallback(state2,reason){if(!this.multiple)this.assignValue(typeof state2=="string"?state2:void 0);else{let restored=[];if(typeof state2=="string")try{const parsed=JSON.parse(state2);Array.isArray(parsed)&&parsed.every(entry=>typeof entry=="string")&&(restored=parsed)}catch{}this.assignValue(restored)}this._restoredStateActive=!0,this._valueDirty=!0}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;markVetoGuardWrite(this.selectionWriteGuard);const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(disabled&&this.forceCloseOpenState(),this.updateValidity(),this.requestUpdate())}checkValidity(){return this.validityController.checkValidity(()=>this.updateValidity())}reportValidity(){return this.validityController.syncConstraints(),this.updateValidity(),this.markInteracted(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.reflectValidityStates()}resetValidity(){this.setCustomValidity("")}disconnectedCallback(){this.pendingSelectedWrites.clear(),markVetoGuardWrite(this.selectionWriteGuard),this.listboxHidden=!0,this.releaseExternalDescription(),this.popupController.cancel(),super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.typeBuffer.clear(),this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.popupController.unbindPointer(),this.open=!1}adoptedCallback(){markVetoGuardWrite(this.selectionWriteGuard),super.adoptedCallback(),this.popupController.cancel(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription(),this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.popupController.unbindPointer(),this.typeBuffer.clear(),queueMicrotask(()=>this.reconnectOpenPopup())}collectOptionsFromSlot(slot){const previous=new Set(this.options),previousActive=this.activeOption,previousActiveRawIndex=previousActive?this.options.indexOf(previousActive):this.activeIndex;if(this.options=slot.assignedElements({flatten:!0}).filter(isLyraOptionElement),this.optionsObserved=!0,this.adornmentClones=new WeakMap,this.reconcileActiveOption(previousActive,previousActiveRawIndex),this._defaultCaptured){const newDefaults=this.options.filter(option=>!previous.has(option)&&option.defaultSelected),newLive=this.options.filter(option=>!previous.has(option)&&option.selected&&!option.defaultSelected);this.refreshOptionDefaults();const eligible=[...!this._restoredStateActive&&!this._valueDirty?newDefaults:[],...this._restoredStateActive?[]:newLive];if(eligible.length>0){const added=this.multiple?eligible:eligible.slice(-1),occurrences=this.multiple?[...new Set([...this._selectedOptions,...added])]:added;newLive.length>0&&(this._valueDirty=!0),this.setSelection(occurrences.map(option=>option.value),occurrences);return}}else{this._defaultCaptured=!0;const explicitDefault=this.hasAttribute("default-value")||this._defaultValueDirty,allDefaults=this.options.filter(option=>option.defaultSelected),defaults=this.multiple?allDefaults:allDefaults.slice(0,1),allLive=this.options.filter(option=>option.selected),live=this.multiple?allLive:allLive.slice(0,1),initialLive=this.options.filter(option=>wasOptionInitiallySelected(option)),optionDirty=this.options.some(option=>isOptionSelectedDirty(option)),dirtySelected=this.options.filter(option=>isOptionSelectedDirty(option)&&option.selected);if(explicitDefault)this._defaultSelectedOptions=this.resolveOccurrences(this._defaultSelected);else{const resetOptions=defaults.length>0?defaults:initialLive.length>0?initialLive:live;this._defaultSelected=resetOptions.map(option=>option.value),this._defaultSelectedOptions=[...resetOptions]}const fromDefaults=explicitDefault||defaults.length>0,initial=optionDirty?this.multiple?allLive:dirtySelected.slice(-1)[0]?dirtySelected.slice(-1):live:explicitDefault?this._defaultSelectedOptions:fromDefaults?defaults:live;if(initial.length>0&&!this._restoredStateActive&&!this._valueDirty){(!fromDefaults||optionDirty)&&(this._valueDirty=!0),this.setSelection(initial.map(option=>option.value),[...initial]);return}if(optionDirty&&(this._valueDirty=!0),explicitDefault&&!this._valueDirty&&!this._restoredStateActive){this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions]);return}}if(this._pendingInitialSelectedOptions!==void 0){const pending=this._pendingInitialSelectedOptions;this._pendingInitialSelectedOptions=void 0;const resolving=this._resolvingPendingInitialSelection;this._resolvingPendingInitialSelection=!0;try{this.selectedOptions=pending}finally{this._resolvingPendingInitialSelection=resolving}return}this.reflectSelected()}refreshOptionDefaults(){if(this.hasAttribute("default-value")||this._defaultValueDirty)return;const declared=this.options.filter(option=>option.defaultSelected),defaults=this.multiple?declared:declared.slice(0,1);this._defaultSelected=defaults.map(option=>option.value),this._defaultSelectedOptions=[...defaults],!this._valueDirty&&!this._restoredStateActive&&this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}reflectSelected(){this._selectedOptions=this.resolveOccurrences(this._selected,this._selectedOptions),this._selectedValuesByOption=new Map(this._selectedOptions.map(option=>[option,option.value]));const chosen=new Set(this._selectedOptions);for(const option of this.options)option[SET_OPTION_SELECTED_FROM_OWNER](chosen.has(option))}selectUnknownValue(value){if(!(this.selectionRequestDispatching||this.effectiveDisabled)){if(this.multiple){const index=this._selected.indexOf(value),values=index>=0?this._selected.filter((_,position)=>position!==index):[...this._selected,value];this.requestSelection(values,this.resolveOccurrenceSlots(values,this._selectedOptions),()=>{this.emitValueEvents(),this.emit("lr-activate",{value})});return}this.hide(),this.emit("lr-activate",{value})}}resolvedLabelFor(value,occurrenceIndex=0){const option=(this._selectedOptions[occurrenceIndex]?.value===value?this._selectedOptions[occurrenceIndex]:void 0)??this.selectedIndex.values.get(value)??this.optionIndex.values.get(value);return option&&(option.label||option.value)}labelFor(value,occurrenceIndex=0){const resolved=this.resolvedLabelFor(value,occurrenceIndex);if(resolved!==void 0)return resolved;if(this.loading)return this.localize("loading");const override=this.optionsObserved?this.getUnknownLabel?.(value):void 0;return override!==void 0&&override.trim().length>0?override:value}isUnknownValue(value,occurrenceIndex=0){return!this.optionsObserved||this.loading||value===""?!1:this.resolvedLabelFor(value,occurrenceIndex)===void 0}get onlyOption(){if(!this.autoCommitSingleOption)return;const navigable=this.navigableOptions(this.options);return navigable.length===1?navigable[0]:void 0}isOptionAvailable(option){return!option.disabled&&!option.inert&&!option.closest("[inert]")}navigableOptions(options=this.listboxOptions){return this.memoOption("navigable",[options],()=>options.filter(option=>this.isOptionAvailable(option)))}get unknownValues(){return this.withUnknownOption?this._selected.filter((value,index)=>this.isUnknownValue(value,index)):[]}get unknownOptions(){const values=this.unknownValues;if(values.length===0)return this.unknownOptionCache.clear(),[];for(const key of[...this.unknownOptionCache.keys()])values.includes(key)||this.unknownOptionCache.delete(key);return values.map(value=>{let option=this.unknownOptionCache.get(value);return option||(option=this.ownerDocument.createElement(tag("option")),this.unknownOptionCache.set(value,option)),option.value=value,option.label=this.labelFor(value),option})}get optionWindow(){return this.memoOption("window",[this.callbackRefreshEpoch,this.options,this._selected,this._selectedOptions,this.activeOption,this.maxRender,this.withUnknownOption,this.loading,this.optionsObserved,this.getUnknownLabel,this.effectiveLocale,this.strings],()=>{const unknown=this.unknownOptions,all=unknown.length?[...this.options,...unknown]:this.options;return capOptionRows(all,this.maxRender,[...this.activeOption?[this.activeOption]:[],...this._selectedOptions,...unknown])})}get listboxOptions(){return this.optionWindow.rows}setActiveIndex(next,navigable=this.navigableOptions()){if(next<0||navigable.length===0){this.activeIndex=-1,this.activeOption=void 0;return}const index=Math.min(next,navigable.length-1);this.activeIndex=index,this.activeOption=navigable[index]}reconcileActiveOption(previousActive,previousRawIndex){if(!previousActive&&this.activeIndex<0)return;const navigable=this.navigableOptions();if(previousActive){const preservedIndex=navigable.indexOf(previousActive);if(preservedIndex>=0){this.setActiveIndex(preservedIndex,navigable);return}}if(navigable.length===0){this.setActiveIndex(-1,navigable);return}const pivot=Math.max(0,previousRawIndex);let nearestIndex=0,nearestDistance=Number.POSITIVE_INFINITY,nearestRawIndex=-1;const rawPositions=new Map(this.listboxOptions.map((option,index)=>[option,index]));navigable.forEach((option,index)=>{const rawIndex=rawPositions.get(option),distance=Math.abs(rawIndex-pivot);(distance<nearestDistance||distance===nearestDistance&&rawIndex>=pivot&&nearestRawIndex<pivot)&&(nearestIndex=index,nearestDistance=distance,nearestRawIndex=rawIndex)}),this.setActiveIndex(nearestIndex,navigable)}flushSelectedWrites(){this.selectedWritesQueued=!1;const writes=[...this.pendingSelectedWrites];if(this.pendingSelectedWrites.clear(),!this.isConnected||writes.length===0)return;if(!this.multiple){let value=this._selected[0],option=this._selectedOptions[0];for(const[candidate,write]of writes)this.optionIndex.members.has(candidate)&&(write.selected?(value=write.value,option=candidate):candidate===option&&(value=void 0,option=void 0));this.setSelection(value===void 0?[]:[value],option?[option]:[]);return}const queues=new Map;for(const option of this._selectedOptions){const value=this._selectedValuesByOption.get(option)??option.value;let queue=queues.get(value);queue||queues.set(value,queue={options:[],next:0}),queue.options.push(option)}const entries=this._selected.map(value=>{const queue=queues.get(value);return{value,option:queue?.options[queue.next++]}}),byOption=new Map(entries.flatMap(entry=>entry.option?[[entry.option,entry]]:[]));for(const[option,write]of writes){if(!this.optionIndex.members.has(option))continue;const entry=byOption.get(option);if(!write.selected)entry&&(entry.removed=!0);else if(entry&&!entry.removed)entry.value=write.value;else{const added={value:write.value,option};entries.push(added),byOption.set(option,added)}}const retained=entries.filter(entry=>!entry.removed);this.setSelection(retained.map(entry=>entry.value),retained.map(entry=>entry.option))}show(){if(this.open||this.effectiveDisabled)return Promise.resolve();const settled=this.popupController.wait(!0);return this.open=!0,settled}hide(){if(!this.open)return Promise.resolve();const settled=this.popupController.wait(!1);return this.open=!1,settled}positionListbox(){this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=this.effectiveDirection;const anchor=this.renderRoot.querySelector('[part="trigger"]'),listbox=this.renderRoot.querySelector('[part="listbox"]');if(!anchor||!listbox)return;this.placedTopLayer=syncTopLayerRelease(listbox,this.placedTopLayer,this.topLayer),this.cleanup=place(anchor,listbox,{placement:rtlAwarePlacement(this.placement,this),...topLayerPlacement(this.topLayer,resolveEffectivePositioningStrategy(this,this._positioningStrategy,"absolute")),sync:this.sync});const operation=this.cleanup;this.positioningReady=operation.ready.then(positioned=>(positioned&&this.cleanup===operation&&this.open&&this.isConnected&&(this.listboxPositioned=!0,this.revealActiveOption()),positioned))}revealActiveOption(){if(!this.isConnected||!this.open||!this.listboxPositioned||!this.cleanup)return;const listbox=this.renderRoot.querySelector('[part="listbox"]'),activeId=this.triggerElement?.getAttribute("aria-activedescendant"),row=listbox?.querySelector('[part="option"][data-active]');listbox&&row&&activeId&&row.id===activeId&&revealRow(listbox,row)}activateListboxOverlay(){this.cleanup?.(),this.cleanup=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.restoreFocusOnClose=!0,this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="listbox"]'),onEscape:()=>{this.hide()},onBackdrop:()=>{this.restoreFocusOnClose=!1,this.hide()},restoreFocusTo:this.triggerElement??null}),this.popupController.bindPointer(),this.positionListbox()}teardownListboxOverlay(restoreFocus=this.restoreFocusOnClose){this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.overlayHandle?.deactivate({restoreFocus}),this.overlayHandle=void 0,this.popupController.unbindPointer(),this.restoreFocusOnClose=!0}reconnectOpenPopup(){!this.isConnected||!this.open||this.activateListboxOverlay()}updated(changed){super.updated(changed),this.syncExternalDescription();const suppressOpenLifecycle=changed.has("open")&&this.suppressedOpenLifecycleGeneration===this.openStateGeneration,shouldRefreshPosition=this.open&&this.isConnected&&(changed.has("placement")||changed.has("positioningStrategy")||changed.has("topLayer")||changed.has("sync")||this.positionedDirection!==this.effectiveDirection);changed.has("open")&&!this.openVetoed?this.open&&this.isConnected?(this.activateListboxOverlay(),!this._isFirstUpdate&&!suppressOpenLifecycle&&this.settleTransition("lr-after-show")):this.open?this.teardownListboxOverlay(!1):(this.teardownListboxOverlay(),!this._isFirstUpdate&&!suppressOpenLifecycle&&this.settleTransition("lr-after-hide")):changed.has("open")&&this.openVetoed?(this.restoreFocusOnClose=!0,shouldRefreshPosition&&this.positionListbox()):shouldRefreshPosition&&this.positionListbox(),(changed.has("activeIndex")||changed.has("options")||changed.has("listboxPositioned"))&&this.revealActiveOption(),(changed.has("touched")||changed.has("required")||changed.has("value"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),changed.has("open")&&(this.pendingOpenTransitionStart=void 0,this.suppressedOpenLifecycleGeneration=void 0)}settleTransition(event){return this.popupController.settle(event,{waitForPosition:async stale=>{for(;this.open;){const readiness=this.positioningReady,positioned=await readiness;if(stale())return!1;if(positioned)break;if(readiness===this.positioningReady)return this.forceCloseOpenState(),!1}return!0},conceal:()=>{this.listboxHidden=!0,this.listboxRendered=!1}})}emitValueEvents(){const self=this,data=this.selectedData,value=self.value,previousValue=this.previousValue;dispatchNativeInputEvent(this),self.emit("lr-input",{value,previousValue,data}),dispatchNativeEvent(this,"change"),self.emit("lr-change",{value,previousValue,data})}assignValue(next){this.value=next}assignDefaultValue(next){this.defaultValue=next}requestSelection(values,preferred,afterCommit,available=()=>!0){if(this.selectionRequestDispatching||this.effectiveDisabled)return!1;const multiple=this.multiple,document=this.ownerDocument,connected=this.isConnected,open=this.open,slots=this.resolveOccurrenceSlots(values,preferred),data=slots.map(option=>option?.data),value=multiple?[...values]:values[0]??"",previousValue=this.value,self=this;let committed=!1;this.selectionRequestDispatching=!0;try{requestThenCommit({requestDetail:{value,previousValue,data},guard:this.selectionWriteGuard,emitRequest:(detail,init)=>self.emit("lr-change-request",detail,init),commit:()=>{const liveOptions=new Set(this.renderRoot.querySelector("slot:not([name])")?.assignedElements({flatten:!0})??[]);this.effectiveDisabled||this.multiple!==multiple||this.ownerDocument!==document||this.isConnected!==connected||this.open!==open||!available(liveOptions)||slots.some((option,index)=>option&&(!liveOptions.has(option)||option.value!==values[index]||!Object.is(option.data,data[index])))||(this.hasInteracted=!0,this._restoredStateActive=!1,this._valueDirty=!0,this.setSelection(values,preferred),committed=!0,afterCommit())}})}finally{this.selectionRequestDispatching=!1}return committed}selectOption(option){if(this.selectionRequestDispatching||this.effectiveDisabled||!this.isOptionAvailable(option))return;if(this.unknownOptionCache.get(option.value)===option){this.selectUnknownValue(option.value);return}const value=option.value,available=liveOptions=>liveOptions.has(option)&&option.value===value&&this.isOptionAvailable(option);if(this.multiple){const currentSlots=this.resolveOccurrenceSlots(this._selected,this._selectedOptions),selectedIndex=currentSlots.indexOf(option),selected=selectedIndex>=0,occurrences=selected?currentSlots.filter((_,index)=>index!==selectedIndex):[...currentSlots,option],values=selected?this._selected.filter((_,index)=>index!==selectedIndex):[...this._selected,value];this.requestSelection(values,occurrences,()=>{this.emitValueEvents(),this.emit("lr-activate",{value})},available);return}if(!(option!==this._selectedOptions[0]||value!==this._selected[0])){this.hide(),this.emit("lr-activate",{value});return}this.requestSelection([value],[option],()=>{this.hide(),this.emitValueEvents(),this.emit("lr-activate",{value})},available)}removeValueAt(index){return this.effectiveDisabled||index<0||index>=this._selected.length?!1:this.requestSelection(this._selected.filter((_,candidateIndex)=>candidateIndex!==index),this.resolveOccurrenceSlots(this._selected,this._selectedOptions).filter((_,candidateIndex)=>candidateIndex!==index),()=>this.emitValueEvents())}clear(){this.effectiveDisabled||this._selected.length===0||this.requestSelection([],[],()=>{this.emitValueEvents(),this.emit("lr-clear")})}removeTag(value,index,event){event.stopPropagation(),this._selected[index]===value&&this.removeValueAt(index)&&this.updateComplete.then(()=>{const buttons=[...this.renderRoot.querySelectorAll('[part~="tag__remove-button"]')];(buttons[Math.min(index,buttons.length-1)]??this.triggerElement)?.focus()})}typeAhead(char){this.typeBuffer.add(char,this.effectiveLocale);const navigable=this.navigableOptions();if(!navigable.length)return;const currentOption=this.open?navigable[this.activeIndex]:this._selectedOptions[this._selectedOptions.length-1],currentIndex=navigable.indexOf(currentOption),labels=this.memoOption("typeAheadLabels",[navigable,this.effectiveLocale],()=>{const locale=resolveIntlLocale(this.effectiveLocale);return new Map(navigable.map(option=>[option,option.label.toLocaleLowerCase(locale)]))});let match=null;for(let step=1;step<=navigable.length;step++){const index=(currentIndex+step+navigable.length)%navigable.length,option=navigable[index];if((this.open||!this.multiple||!this.selectedIndex.members.has(option))&&labels.get(option)?.startsWith(this.typeBuffer.text)){match=index;break}}if(match===null)return;const candidate=navigable[match];this.open?this.setActiveIndex(match,navigable):this.selectOption(candidate)}adornmentMarkup(option){return Array.from(option.children).filter(child=>["start","end","prefix","suffix"].includes(child.getAttribute("slot")??"")).map(child=>child.outerHTML).join("")}adornmentsFor(option){const cached=this.adornmentClones.get(option);if(cached)return cached;const cloneSlot=selector=>{const nodes=Array.from(option.querySelectorAll(selector));if(nodes.length!==0)return nodes.map(node=>node.cloneNode(!0))},resolved={markup:this.adornmentMarkup(option),start:cloneSlot(':scope > [slot="start"], :scope > [slot="prefix"]'),end:cloneSlot(':scope > [slot="end"], :scope > [slot="suffix"]')};return this.adornmentClones.set(option,resolved),resolved}renderRows(options,activeId){const out=[],chosen=new Set(this._selectedOptions);let currentGroup,groupRows=[],groupIndex=0;const flushGroup=()=>{if(groupRows.length!==0){if(currentGroup){const labelId=`${this.listId}-group-${groupIndex++}`;out.push(html`<div role="group" aria-labelledby=${labelId}>
|
|
1
|
+
import{__decorate}from"tslib";import{capOptionRows}from"../../../internal/option-selection.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{VetoWriteGuard,markVetoGuardWrite}from"../../../internal/veto-write-guard.js";import{renderFormControlHintError}from"../../../internal/form-control-template.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{FormControlController,reflectFormName}from"../../../internal/form-control-controller.js";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{acquireNativeControlDescription}from"../../../internal/native-control-description.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{deferredPlaceReady as place,syncTopLayerRelease,topLayerPlacement}from"../../../internal/anchored-overlay-runtime.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{chevronIcon,closeIcon}from"../../../internal/icons.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{PopupController,emitPopupEvent}from"../../../internal/popup-controller.js";import{revealRow}from"../../../internal/reveal-row.js";import{TypeAheadBuffer}from"../../../internal/type-ahead-buffer.js";import{resolveListMove}from"../../../internal/list-navigation.js";import{finiteCount}from"../../../internal/numbers.js";import{getNumberFormat,resolveIntlLocale}from"../../../internal/intl-cache.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{styles}from"./select.styles.js";import{sizes}from"../../../internal/sizes.styles.js";import"../combobox/option.class.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{omittedEmptyStringConverter,optionalLiteralSetConverter}from"../../../internal/converters.js";import{getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{isOptionSelectedDirty,isOptionSelectedWrite,wasOptionInitiallySelected,RESET_OPTION_SELECTED_FROM_OWNER,SET_OPTION_SELECTED_FROM_OWNER}from"../../../internal/option-selection.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{tag}from"../../../internal/prefix.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_selectSelectedOverflow,LYRA_DEFAULT_selectValueMissing}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_loading,LYRA_DEFAULT_notInCatalog,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();function isLyraOptionElement(value){return isHtmlElement(value)&&value.localName===tag("option")}function normalizeSelectionValues(next){return Array.isArray(next)?next.filter(value=>typeof value=="string"):typeof next=="string"?[next]:[]}const POSITIONING_STRATEGY=optionalLiteralSetConverter(["absolute","fixed"]);class LyraSelect extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,fieldRequired:LYRA_DEFAULT_fieldRequired,loading:LYRA_DEFAULT_loading,notInCatalog:LYRA_DEFAULT_notInCatalog,removeWithContext:LYRA_DEFAULT_removeWithContext,select:LYRA_DEFAULT_select,selectSelectedOverflow:LYRA_DEFAULT_selectSelectedOverflow,selectValueMissing:LYRA_DEFAULT_selectValueMissing}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-input","lr-change","lr-change-request"])}static{this.identityEventDetailCollectionItems=Object.freeze({"lr-input":Object.freeze(["data"]),"lr-change":Object.freeze(["data"]),"lr-change-request":Object.freeze(["data"])})}static get validators(){return[currentValidityValidator("required","disabled","value","multiple")]}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles,srOnly]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},multiple:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},value:{noAccessor:!0},name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},maxOptionsVisible:{type:Number,attribute:"max-options-visible",noAccessor:!0},defaultValue:{attribute:"default-value",noAccessor:!0}}}get open(){return this._open}set open(next){const requested=!!next,normalized=requested&&!this.effectiveDisabled;if(normalized===this._open){requested!==normalized&&this.hasAttribute("open")&&this.removeAttribute("open");return}this.applyOpenState(normalized)}get positioningStrategy(){return this._positioningStrategy??"absolute"}set positioningStrategy(next){const normalized=POSITIONING_STRATEGY.normalize(next)??"absolute",old=this.positioningStrategy;this._positioningStrategy=normalized,normalized!==old&&(this.requestUpdate("positioningStrategy",old),old==="fixed"!=(normalized==="fixed")&&this.requestUpdate("hoist",old==="fixed"))}get hoist(){return this.positioningStrategy==="fixed"}set hoist(next){this.positioningStrategy=next?"fixed":"absolute"}requestUpdate(...args){args[0]===void 0&&(this.callbackRefreshEpoch=(this.callbackRefreshEpoch??0)+1),super.requestUpdate(...args)}memoOption(key,inputs,compute){const previous=this.optionMemo.get(key);if(previous&&previous.inputs.length===inputs.length&&previous.inputs.every((input,index)=>Object.is(input,inputs[index])))return previous.value;const value=compute();return this.optionMemo.set(key,{inputs,value}),value}get optionIndex(){return this.memoOption("index",[this.options],()=>{const values=new Map,positions=new Map;return this.options.forEach((option,index)=>{positions.set(option,index),values.has(option.value)||values.set(option.value,option)}),{values,positions,members:new Set(this.options)}})}get selectedIndex(){return this.memoOption("selectedIndex",[this._selectedOptions,this.options],()=>{const values=new Map;for(const option of this._selectedOptions)values.has(option.value)||values.set(option.value,option);return{values,members:new Set(this._selectedOptions)}})}focus(options){this.effectiveDisabled||this.triggerElement?.focus(options)}blur(){this.triggerElement?.blur()}click(){this.effectiveDisabled||this.triggerElement?.click()}constructor(){super(),this.placeholder="",this.label="",this.labelDisplay="visible",this.hint="",this.helpText="",this.withLabel=!1,this.withHint=!1,this.errorText="",this.autofocus=!1,this.title="",this._open=!1,this.size="m",this.appearance="outlined",this.pill=!1,this.placement="bottom",this.topLayer=!1,this.filled=!1,this.withClear=!1,this.clearable=!1,this.withUnknownOption=!1,this.loading=!1,this.autoCommitSingleOption=!1,this.activeIndex=-1,this.maxRender=200,this.options=[],this.callbackRefreshEpoch=0,this.optionMemo=new Map,this.optionsObserved=!1,this.touched=!1,this.hasInteracted=!1,this.slotPresence=new SlotPresenceController(this),this._fieldsetDisabled=!1,this.listId=nextId("select-list"),this.triggerId=nextId("select-trigger"),this.valueTextId=nextId("select-value"),this.positioningReady=Promise.resolve(!1),this.restoreFocusOnClose=!0,this.popupController=new PopupController({host:this,popup:()=>this.renderRoot.querySelector('[part="listbox"]'),emit:(name,cancelable)=>emitPopupEvent(this,name,cancelable),onPointer:event=>this.onDocPointer(event)}),this.listboxHidden=!0,this.listboxRendered=!1,this.listboxPositioned=!1,this._isFirstUpdate=!0,this.openVetoed=!1,this.previousValue="",this.openStateGeneration=0,this._selected=[],this._selectedOptions=[],this._selectedValuesByOption=new Map,this.adornmentClones=new WeakMap,this._multiple=!1,this._disabled=!1,this._required=!1,this._defaultSelected=[],this._defaultSelectedOptions=[],this._defaultCaptured=!1,this._valueDirty=!1,this._restoredStateActive=!1,this._resolvingPendingInitialSelection=!1,this._defaultValueDirty=!1,this.typeBuffer=new TypeAheadBuffer(this),this._name="",this._maxOptionsVisible=3,this.localDescriptionIds="",this.markInteracted=()=>{this.touched=!0,!this.hasInteracted&&(this.hasInteracted=!0,this.reflectValidityStates())},this.collectOptions=e=>{this.collectOptionsFromSlot(e.target)},this.unknownOptionCache=new Map,this.pendingSelectedWrites=new Map,this.selectedWritesQueued=!1,this.optionRefreshPending=!1,this.onOptionChange=e=>{e.stopPropagation();const option=e.composedPath().find(isLyraOptionElement);if(isOptionSelectedWrite(e)&&isLyraOptionElement(option)&&this.optionIndex.members.has(option)){markVetoGuardWrite(this.selectionWriteGuard),this._valueDirty=!0,this._restoredStateActive=!1,this.pendingSelectedWrites.delete(option),this.pendingSelectedWrites.set(option,{selected:option.selected,value:option.value}),this.selectedWritesQueued||(this.selectedWritesQueued=!0,queueMicrotask(()=>this.flushSelectedWrites()));return}if(isLyraOptionElement(option)){const cached=this.adornmentClones.get(option);cached&&cached.markup!==this.adornmentMarkup(option)&&this.adornmentClones.delete(option)}if(this.optionRefreshPending)return;this.optionRefreshPending=!0;const previousActive=this.activeOption,previousActiveRawIndex=previousActive?this.options.indexOf(previousActive):this.activeIndex;queueMicrotask(()=>{this.optionRefreshPending=!1,this.refreshOptionDefaults(),this.reflectSelected(),this.options=[...this.options],this.reconcileActiveOption(previousActive,previousActiveRawIndex)})},this.onDocPointer=e=>{if(!e.composedPath().includes(this)){if(this.overlayHandle?.isActive()){this.overlayHandle.dismissBackdrop();return}this.restoreFocusOnClose=!1,this.hide()}},this.selectionWriteGuard=new VetoWriteGuard,this.selectionRequestDispatching=!1,this.onTriggerClick=()=>{if(!this.effectiveDisabled){if(this.onlyOption)return this.selectOption(this.onlyOption);this.open?this.hide():this.show()}},this.onTriggerBlur=event=>{this.effectiveDisabled||(this.touched=!0,this.hasInteracted=!0,this.reflectValidityStates()),this.open&&(this.restoreFocusOnClose=!1),this.hide(),relayNativeEvent(this,event)},this.onTriggerFocus=event=>{relayNativeEvent(this,event)},this.onKeyDown=e=>{if(e.isComposing||e.keyCode===229)return;const navigable=this.navigableOptions(),move=()=>resolveListMove(e,{count:navigable.length,current:this.activeIndex,orientation:"vertical",wrap:!1,clamp:!0,backwardFromMissing:"first"});switch(e.key){case"ArrowDown":if(e.preventDefault(),this.onlyOption)return this.selectOption(this.onlyOption);if(!this.open){this.show();return}this.setActiveIndex(move()??-1,navigable);break;case"ArrowUp":if(e.preventDefault(),this.onlyOption)return this.selectOption(this.onlyOption);if(!this.open){this.show();return}this.setActiveIndex(move()??-1,navigable);break;case"Enter":case" ":if(this.open){e.preventDefault();const active=navigable[this.activeIndex];this.activeIndex>=0&&active?this.selectOption(active):this.hide()}break;case"Escape":this.open&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(e.preventDefault(),this.hide());break;case"Home":this.open&&(e.preventDefault(),this.setActiveIndex(move()??-1,navigable));break;case"End":this.open&&(e.preventDefault(),this.setActiveIndex(move()??-1,navigable));break;case"Backspace":case"Delete":this.multiple&&this._selected.length>0&&(e.preventDefault(),this.removeValueAt(this._selected.length-1));break;default:this.typeBuffer.accepts(e)&&(e.preventDefault(),this.typeAhead(e.key));break}},this.onListboxMouseDown=e=>{e.preventDefault()},this.onListboxClick=e=>{const optionEl=e.target.closest('[part="option"]'),index=Number(optionEl?.dataset.index);if(!Number.isInteger(index))return;const option=this.listboxOptions[index];option&&this.selectOption(option)},this.validityController=new FormControlController(this,{invalid:init=>this.emit("lr-invalid",null,init),interacted:this.markInteracted,customError:()=>this.validityController.customValidityMessage}),this.internals=this.validityController.formInternals,new GlassScrollLayer(this,'[part="listbox"]',()=>this.open),this.syncFormValue()}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"]')??null}syncExternalDescription(){if(!this.isConnected)return;const target=this.renderRoot.querySelector('[part="trigger"]');target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireNativeControlDescription(this,target,()=>this.localDescriptionIds))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.updateValidity(),this.hasUpdated&&this.open&&queueMicrotask(()=>this.reconnectOpenPopup())}willUpdate(changed){if(super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,this._isFirstUpdate&&(this._pendingInitialDefaultValue!==void 0||this._pendingInitialValue!==void 0)){this._resolvingPendingInitialSelection=!0;try{if(this._pendingInitialDefaultValue!==void 0){const pending=this._pendingInitialDefaultValue;this._pendingInitialDefaultValue=void 0,this.assignDefaultValue(pending)}if(this._pendingInitialValue!==void 0){const pending=this._pendingInitialValue;this._pendingInitialValue=void 0,this.assignValue(pending)}}finally{this._resolvingPendingInitialSelection=!1}}if(this.announceOpenTransition(changed),changed.has("open")&&!this.openVetoed&&(this.listboxPositioned=!1),this.open&&(this.listboxHidden=!1,this.listboxRendered=!0),changed.has("open")&&!this.openVetoed){const navigable=this.navigableOptions();this.setActiveIndex(this.open?navigable.findIndex(option=>this.selectedIndex.members.has(option)):-1,navigable)}}firstUpdated(changed){super.firstUpdated(changed);const slot=this.optionsSlot;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>{const assigned=s.assignedElements({flatten:!0});this.optionsObserved=!0,assigned.some(isLyraOptionElement)&&this.collectOptionsFromSlot(s)})})}applyOpenState(next){const old=this._open;this.pendingOpenTransitionStart===void 0&&(this.pendingOpenTransitionStart=old),this.openStateGeneration++,this._open=next,this.requestUpdate("open",old)}forceCloseOpenState(){this.listboxHidden=!0;const isClosing=this._open||this.pendingOpenTransitionStart===!0;if(this.popupController.cancel(),!this._open){isClosing&&(this.suppressedOpenLifecycleGeneration=this.openStateGeneration),this.hasAttribute("open")&&this.removeAttribute("open");return}this.applyOpenState(!1),this.suppressedOpenLifecycleGeneration=this.openStateGeneration}announceOpenTransition(changed){if(this.openVetoed=!1,!(!changed.has("open")||this._isFirstUpdate||this.suppressedOpenLifecycleGeneration===this.openStateGeneration)){if(!this.isConnected){emitPopupEvent(this,"lr-hide",!1);return}this.openVetoed=this.popupController.announce(this.open,()=>{this.open=!this.open})}}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",reflectFormName(this,this._name),this.syncFormValue(),this.requestUpdate("name",old)}get multiple(){return this._multiple}set multiple(next){markVetoGuardWrite(this.selectionWriteGuard);const old=this._multiple;this._multiple=!!next,this.toggleAttribute("multiple",this._multiple),!this._multiple&&this._selected.length>1?this.setSelection(this._selected.slice(0,1),this._selectedOptions.slice(0,1)):this.syncFormValue(),this.requestUpdate("multiple",old)}get maxOptionsVisible(){return this._maxOptionsVisible}set maxOptionsVisible(next){const old=this._maxOptionsVisible;this._maxOptionsVisible=finiteCount(next,3),this.requestUpdate("maxOptionsVisible",old)}get disabled(){return this._disabled}set disabled(next){markVetoGuardWrite(this.selectionWriteGuard);const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this._disabled&&this.forceCloseOpenState(),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get value(){return this.multiple?[...this._selected]:this._selected[0]??""}set value(next){this._resolvingPendingInitialSelection||(this._pendingInitialSelectedOptions=void 0,this.hasUpdated||(this._pendingInitialValue=next)),this._restoredStateActive=!1,this._valueDirty=!0;const values=normalizeSelectionValues(next);this.setSelection(values)}get defaultValue(){return this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??""}set defaultValue(next){!this.hasUpdated&&!this._resolvingPendingInitialSelection&&(this._pendingInitialDefaultValue=next),this._defaultValueDirty=!0;const old=this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??"",values=normalizeSelectionValues(next);this._defaultSelected=this.multiple?[...values]:values.slice(0,1),this._defaultSelectedOptions=this.resolveOccurrences(this._defaultSelected),!this._valueDirty&&!this._restoredStateActive&&this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions]),this.requestUpdate("defaultValue",old)}get selectedOptions(){return[...this._selectedOptions]}set selectedOptions(next){const candidates=Array.isArray(next)?next:[];this._resolvingPendingInitialSelection||(this._pendingInitialValue=void 0,this._pendingInitialSelectedOptions=this.hasUpdated?void 0:candidates.filter(option=>isLyraOptionElement(option)&&this.contains(option))),this._restoredStateActive=!1,this._valueDirty=!0;const catalog=candidates.length>1?new Set(this.options):void 0,seen=new Set,live=candidates.filter(option=>seen.has(option)?!1:(seen.add(option),isLyraOptionElement(option)&&this.contains(option)&&(catalog?catalog.has(option):this.options.includes(option)))),selected=this.multiple?live:live.slice(0,1);this.setSelection(selected.map(option=>option.value),selected)}get selectedData(){return this.resolveOccurrenceSlots(this._selected,this._selectedOptions).map(option=>option?.data)}setSelection(next,preferred=[]){this.pendingSelectedWrites.clear(),markVetoGuardWrite(this.selectionWriteGuard);const values=this.multiple?[...next]:next.slice(0,1),previousValues=this._selected,previousOptions=this._selectedOptions,old=this.multiple?[...previousValues]:previousValues[0]??"";this.previousValue=old,this._selected=values,this._selectedOptions=this.resolveOccurrences(values,preferred),this.syncFormValue(),this.reflectSelected(),this.updateValidity(),this.requestUpdate("value",old);const sameValues=previousValues.length===values.length&&previousValues.every((value,i)=>value===values[i]),sameOptions=previousOptions.length===this._selectedOptions.length&&previousOptions.every((option,i)=>option===this._selectedOptions[i]);sameValues&&!sameOptions&&this.requestUpdate()}resolveOccurrences(values,preferred=[]){return this.resolveOccurrenceSlots(values,preferred).filter(option=>option!==void 0)}resolveOccurrenceSlots(values,preferred=[]){if(values.length===0)return[];if(values.length===1){const value=values[0],hint=preferred.length===1?preferred[0]:preferred.find(option=>option?.value===value);return[hint&&hint.value===value&&this.options.includes(hint)?hint:this.options.find(option=>option.value===value)]}const requested=new Set(values),catalog=new Set(this.options),claimed=new Set,queuesFor=options=>{const queues=new Map;for(const option of options){if(!option)continue;const value=option.value;if(!requested.has(value))continue;let queue=queues.get(value);queue||queues.set(value,queue={options:[],next:0}),queue.options.push(option)}return queues},firstUnclaimed=(queues,value)=>{const queue=queues.get(value);if(queue){for(;queue.next<queue.options.length&&claimed.has(queue.options[queue.next]);)queue.next++;return queue.options[queue.next]}},preferredQueues=preferred.length===values.length?void 0:queuesFor(preferred);let fallbackQueues;return values.map((value,index)=>{const hint=preferredQueues?firstUnclaimed(preferredQueues,value):preferred[index],match=hint&&hint.value===value&&catalog.has(hint)&&!claimed.has(hint)?hint:firstUnclaimed(fallbackQueues??=queuesFor(this.options),value);if(match)return claimed.add(match),match})}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){this.barredFromValidation?this.validityController.setValidity({}):this.required&&this._selected.length===0?this.validityController.setValidity({valueMissing:!0},this.localize("selectValueMissing")):this.validityController.setValidity({}),this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",this._selected.length===0)}syncFormValue(){if(!this.multiple){this.internals.setFormValue(this._selected[0]??"");return}const state2=JSON.stringify(this._selected);if(!this.name){this.internals.setFormValue(null,state2);return}const data=new FormData;for(const value of this._selected)data.append(this.name,value);this.internals.setFormValue(data,state2)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formResetCallback(){this._pendingInitialValue=void 0,this._pendingInitialSelectedOptions=void 0,this.touched=!1,this.hasInteracted=!1,this._restoredStateActive=!1,this._valueDirty=!1;const resetOptions=this._defaultSelectedOptions.length>0?this._defaultSelectedOptions:this.options.filter(option=>wasOptionInitiallySelected(option));this._defaultSelectedOptions.length===0&&resetOptions.length>0&&(this._defaultSelectedOptions=[...resetOptions],this._defaultSelected=resetOptions.map(option=>option.value));const defaults=new Set(resetOptions);for(const option of this.options)option[RESET_OPTION_SELECTED_FROM_OWNER](defaults.has(option));this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}formStateRestoreCallback(state2,reason){if(!this.multiple)this.assignValue(typeof state2=="string"?state2:void 0);else{let restored=[];if(typeof state2=="string")try{const parsed=JSON.parse(state2);Array.isArray(parsed)&&parsed.every(entry=>typeof entry=="string")&&(restored=parsed)}catch{}this.assignValue(restored)}this._restoredStateActive=!0,this._valueDirty=!0}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;markVetoGuardWrite(this.selectionWriteGuard);const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(disabled&&this.forceCloseOpenState(),this.updateValidity(),this.requestUpdate())}checkValidity(){return this.validityController.checkValidity(()=>this.updateValidity())}reportValidity(){return this.validityController.syncConstraints(),this.updateValidity(),this.markInteracted(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.reflectValidityStates()}resetValidity(){this.setCustomValidity("")}disconnectedCallback(){this.pendingSelectedWrites.clear(),markVetoGuardWrite(this.selectionWriteGuard),this.listboxHidden=!0,this.releaseExternalDescription(),this.popupController.cancel(),super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.typeBuffer.clear(),this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.popupController.unbindPointer(),this.open=!1}adoptedCallback(){markVetoGuardWrite(this.selectionWriteGuard),super.adoptedCallback(),this.popupController.cancel(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription(),this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.popupController.unbindPointer(),this.typeBuffer.clear(),queueMicrotask(()=>this.reconnectOpenPopup())}collectOptionsFromSlot(slot){const previous=new Set(this.options),previousActive=this.activeOption,previousActiveRawIndex=previousActive?this.options.indexOf(previousActive):this.activeIndex;if(this.options=slot.assignedElements({flatten:!0}).filter(isLyraOptionElement),this.optionsObserved=!0,this.adornmentClones=new WeakMap,this.reconcileActiveOption(previousActive,previousActiveRawIndex),this._defaultCaptured){const newDefaults=this.options.filter(option=>!previous.has(option)&&option.defaultSelected),newLive=this.options.filter(option=>!previous.has(option)&&option.selected&&!option.defaultSelected);this.refreshOptionDefaults();const eligible=[...!this._restoredStateActive&&!this._valueDirty?newDefaults:[],...this._restoredStateActive?[]:newLive];if(eligible.length>0){const added=this.multiple?eligible:eligible.slice(-1),occurrences=this.multiple?[...new Set([...this._selectedOptions,...added])]:added;newLive.length>0&&(this._valueDirty=!0),this.setSelection(occurrences.map(option=>option.value),occurrences);return}}else{this._defaultCaptured=!0;const explicitDefault=this.hasAttribute("default-value")||this._defaultValueDirty,allDefaults=this.options.filter(option=>option.defaultSelected),defaults=this.multiple?allDefaults:allDefaults.slice(0,1),allLive=this.options.filter(option=>option.selected),live=this.multiple?allLive:allLive.slice(0,1),initialLive=this.options.filter(option=>wasOptionInitiallySelected(option)),optionDirty=this.options.some(option=>isOptionSelectedDirty(option)),dirtySelected=this.options.filter(option=>isOptionSelectedDirty(option)&&option.selected);if(explicitDefault)this._defaultSelectedOptions=this.resolveOccurrences(this._defaultSelected);else{const resetOptions=defaults.length>0?defaults:initialLive.length>0?initialLive:live;this._defaultSelected=resetOptions.map(option=>option.value),this._defaultSelectedOptions=[...resetOptions]}const fromDefaults=explicitDefault||defaults.length>0,initial=optionDirty?this.multiple?allLive:dirtySelected.slice(-1)[0]?dirtySelected.slice(-1):live:explicitDefault?this._defaultSelectedOptions:fromDefaults?defaults:live;if(initial.length>0&&!this._restoredStateActive&&!this._valueDirty){(!fromDefaults||optionDirty)&&(this._valueDirty=!0),this.setSelection(initial.map(option=>option.value),[...initial]);return}if(optionDirty&&(this._valueDirty=!0),explicitDefault&&!this._valueDirty&&!this._restoredStateActive){this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions]);return}}if(this._pendingInitialSelectedOptions!==void 0){const pending=this._pendingInitialSelectedOptions;this._pendingInitialSelectedOptions=void 0;const resolving=this._resolvingPendingInitialSelection;this._resolvingPendingInitialSelection=!0;try{this.selectedOptions=pending}finally{this._resolvingPendingInitialSelection=resolving}return}this.reflectSelected()}refreshOptionDefaults(){if(this.hasAttribute("default-value")||this._defaultValueDirty)return;const declared=this.options.filter(option=>option.defaultSelected),defaults=this.multiple?declared:declared.slice(0,1);this._defaultSelected=defaults.map(option=>option.value),this._defaultSelectedOptions=[...defaults],!this._valueDirty&&!this._restoredStateActive&&this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}reflectSelected(){this._selectedOptions=this.resolveOccurrences(this._selected,this._selectedOptions),this._selectedValuesByOption=new Map(this._selectedOptions.map(option=>[option,option.value]));const chosen=new Set(this._selectedOptions);for(const option of this.options)option[SET_OPTION_SELECTED_FROM_OWNER](chosen.has(option))}selectUnknownValue(value){if(!(this.selectionRequestDispatching||this.effectiveDisabled)){if(this.multiple){const index=this._selected.indexOf(value),values=index>=0?this._selected.filter((_,position)=>position!==index):[...this._selected,value];this.requestSelection(values,this.resolveOccurrenceSlots(values,this._selectedOptions),()=>{this.emitValueEvents(),this.emit("lr-activate",{value})});return}this.hide(),this.emit("lr-activate",{value})}}resolvedLabelFor(value,occurrenceIndex=0){const option=(this._selectedOptions[occurrenceIndex]?.value===value?this._selectedOptions[occurrenceIndex]:void 0)??this.selectedIndex.values.get(value)??this.optionIndex.values.get(value);return option&&(option.label||option.value)}labelFor(value,occurrenceIndex=0){const resolved=this.resolvedLabelFor(value,occurrenceIndex);if(resolved!==void 0)return resolved;if(this.loading)return this.localize("loading");const override=this.optionsObserved?this.getUnknownLabel?.(value):void 0;return override!==void 0&&override.trim().length>0?override:value}isUnknownValue(value,occurrenceIndex=0){return!this.optionsObserved||this.loading||value===""?!1:this.resolvedLabelFor(value,occurrenceIndex)===void 0}get onlyOption(){if(!this.autoCommitSingleOption)return;const navigable=this.navigableOptions(this.options);return navigable.length===1?navigable[0]:void 0}isOptionAvailable(option){return!option.disabled&&!option.inert&&!option.closest("[inert]")}navigableOptions(options=this.listboxOptions){return this.memoOption("navigable",[options],()=>options.filter(option=>this.isOptionAvailable(option)))}get unknownValues(){return this.withUnknownOption?this._selected.filter((value,index)=>this.isUnknownValue(value,index)):[]}get unknownOptions(){const values=this.unknownValues;if(values.length===0)return this.unknownOptionCache.clear(),[];for(const key of[...this.unknownOptionCache.keys()])values.includes(key)||this.unknownOptionCache.delete(key);return values.map(value=>{let option=this.unknownOptionCache.get(value);return option||(option=this.ownerDocument.createElement(tag("option")),this.unknownOptionCache.set(value,option)),option.value=value,option.label=this.labelFor(value),option})}get optionWindow(){return this.memoOption("window",[this.callbackRefreshEpoch,this.options,this._selected,this._selectedOptions,this.activeOption,this.maxRender,this.withUnknownOption,this.loading,this.optionsObserved,this.getUnknownLabel,this.effectiveLocale,this.strings],()=>{const unknown=this.unknownOptions,all=unknown.length?[...this.options,...unknown]:this.options;return capOptionRows(all,this.maxRender,[...this.activeOption?[this.activeOption]:[],...this._selectedOptions,...unknown])})}get listboxOptions(){return this.optionWindow.rows}setActiveIndex(next,navigable=this.navigableOptions()){if(next<0||navigable.length===0){this.activeIndex=-1,this.activeOption=void 0;return}const index=Math.min(next,navigable.length-1);this.activeIndex=index,this.activeOption=navigable[index]}reconcileActiveOption(previousActive,previousRawIndex){if(!previousActive&&this.activeIndex<0)return;const navigable=this.navigableOptions();if(previousActive){const preservedIndex=navigable.indexOf(previousActive);if(preservedIndex>=0){this.setActiveIndex(preservedIndex,navigable);return}}if(navigable.length===0){this.setActiveIndex(-1,navigable);return}const pivot=Math.max(0,previousRawIndex);let nearestIndex=0,nearestDistance=Number.POSITIVE_INFINITY,nearestRawIndex=-1;const rawPositions=new Map(this.listboxOptions.map((option,index)=>[option,index]));navigable.forEach((option,index)=>{const rawIndex=rawPositions.get(option),distance=Math.abs(rawIndex-pivot);(distance<nearestDistance||distance===nearestDistance&&rawIndex>=pivot&&nearestRawIndex<pivot)&&(nearestIndex=index,nearestDistance=distance,nearestRawIndex=rawIndex)}),this.setActiveIndex(nearestIndex,navigable)}flushSelectedWrites(){this.selectedWritesQueued=!1;const writes=[...this.pendingSelectedWrites];if(this.pendingSelectedWrites.clear(),!this.isConnected||writes.length===0)return;if(!this.multiple){let value=this._selected[0],option=this._selectedOptions[0];for(const[candidate,write]of writes)this.optionIndex.members.has(candidate)&&(write.selected?(value=write.value,option=candidate):candidate===option&&(value=void 0,option=void 0));this.setSelection(value===void 0?[]:[value],option?[option]:[]);return}const queues=new Map;for(const option of this._selectedOptions){const value=this._selectedValuesByOption.get(option)??option.value;let queue=queues.get(value);queue||queues.set(value,queue={options:[],next:0}),queue.options.push(option)}const entries=this._selected.map(value=>{const queue=queues.get(value);return{value,option:queue?.options[queue.next++]}}),byOption=new Map(entries.flatMap(entry=>entry.option?[[entry.option,entry]]:[]));for(const[option,write]of writes){if(!this.optionIndex.members.has(option))continue;const entry=byOption.get(option);if(!write.selected)entry&&(entry.removed=!0);else if(entry&&!entry.removed)entry.value=write.value;else{const added={value:write.value,option};entries.push(added),byOption.set(option,added)}}const retained=entries.filter(entry=>!entry.removed);this.setSelection(retained.map(entry=>entry.value),retained.map(entry=>entry.option))}show(){if(this.open||this.effectiveDisabled)return Promise.resolve();const settled=this.popupController.wait(!0);return this.open=!0,settled}hide(){if(!this.open)return Promise.resolve();const settled=this.popupController.wait(!1);return this.open=!1,settled}positionListbox(){this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=this.effectiveDirection;const anchor=this.renderRoot.querySelector('[part="trigger"]'),listbox=this.renderRoot.querySelector('[part="listbox"]');if(!anchor||!listbox)return;this.placedTopLayer=syncTopLayerRelease(listbox,this.placedTopLayer,this.topLayer),this.cleanup=place(anchor,listbox,{placement:rtlAwarePlacement(this.placement,this),...topLayerPlacement(this.topLayer,resolveEffectivePositioningStrategy(this,this._positioningStrategy,"absolute")),sync:this.sync});const operation=this.cleanup;this.positioningReady=operation.ready.then(positioned=>(positioned&&this.cleanup===operation&&this.open&&this.isConnected&&(this.listboxPositioned=!0,this.revealActiveOption()),positioned))}revealActiveOption(){if(!this.isConnected||!this.open||!this.listboxPositioned||!this.cleanup)return;const listbox=this.renderRoot.querySelector('[part="listbox"]'),activeId=this.triggerElement?.getAttribute("aria-activedescendant"),row=listbox?.querySelector('[part="option"][data-active]');listbox&&row&&activeId&&row.id===activeId&&revealRow(listbox,row)}activateListboxOverlay(){this.cleanup?.(),this.cleanup=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.restoreFocusOnClose=!0,this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="listbox"]'),onEscape:()=>{this.hide()},onBackdrop:()=>{this.restoreFocusOnClose=!1,this.hide()},restoreFocusTo:this.triggerElement??null}),this.popupController.bindPointer(),this.positionListbox()}teardownListboxOverlay(restoreFocus=this.restoreFocusOnClose){this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.overlayHandle?.deactivate({restoreFocus}),this.overlayHandle=void 0,this.popupController.unbindPointer(),this.restoreFocusOnClose=!0}reconnectOpenPopup(){!this.isConnected||!this.open||this.activateListboxOverlay()}updated(changed){super.updated(changed),this.syncExternalDescription();const suppressOpenLifecycle=changed.has("open")&&this.suppressedOpenLifecycleGeneration===this.openStateGeneration,shouldRefreshPosition=this.open&&this.isConnected&&(changed.has("placement")||changed.has("positioningStrategy")||changed.has("topLayer")||changed.has("sync")||this.positionedDirection!==this.effectiveDirection);changed.has("open")&&!this.openVetoed?this.open&&this.isConnected?(this.activateListboxOverlay(),!this._isFirstUpdate&&!suppressOpenLifecycle&&this.settleTransition("lr-after-show")):this.open?this.teardownListboxOverlay(!1):(this.teardownListboxOverlay(),!this._isFirstUpdate&&!suppressOpenLifecycle&&this.settleTransition("lr-after-hide")):changed.has("open")&&this.openVetoed?(this.restoreFocusOnClose=!0,shouldRefreshPosition&&this.positionListbox()):shouldRefreshPosition&&this.positionListbox(),(changed.has("activeIndex")||changed.has("options")||changed.has("listboxPositioned"))&&this.revealActiveOption(),(changed.has("touched")||changed.has("required")||changed.has("value"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),changed.has("open")&&(this.pendingOpenTransitionStart=void 0,this.suppressedOpenLifecycleGeneration=void 0)}settleTransition(event){return this.popupController.settle(event,{waitForPosition:async stale=>{for(;this.open;){const readiness=this.positioningReady,positioned=await readiness;if(stale())return!1;if(positioned)break;if(readiness===this.positioningReady)return this.forceCloseOpenState(),!1}return!0},conceal:()=>{this.listboxHidden=!0,this.listboxRendered=!1}})}emitValueEvents(){const self=this,data=this.selectedData,value=self.value,previousValue=this.previousValue;dispatchNativeInputEvent(this),self.emit("lr-input",{value,previousValue,data}),dispatchNativeEvent(this,"change"),self.emit("lr-change",{value,previousValue,data})}assignValue(next){this.value=next}assignDefaultValue(next){this.defaultValue=next}requestSelection(values,preferred,afterCommit,available=()=>!0){if(this.selectionRequestDispatching||this.effectiveDisabled)return!1;const multiple=this.multiple,document=this.ownerDocument,connected=this.isConnected,open=this.open,slots=this.resolveOccurrenceSlots(values,preferred),data=slots.map(option=>option?.data),value=multiple?[...values]:values[0]??"",previousValue=this.value,self=this;let committed=!1;this.selectionRequestDispatching=!0;try{requestThenCommit({requestDetail:{value,previousValue,data},guard:this.selectionWriteGuard,emitRequest:(detail,init)=>self.emit("lr-change-request",detail,init),commit:()=>{const liveOptions=new Set(this.renderRoot.querySelector("slot:not([name])")?.assignedElements({flatten:!0})??[]);this.effectiveDisabled||this.multiple!==multiple||this.ownerDocument!==document||this.isConnected!==connected||this.open!==open||!available(liveOptions)||slots.some((option,index)=>option&&(!liveOptions.has(option)||option.value!==values[index]||!Object.is(option.data,data[index])))||(this.hasInteracted=!0,this._restoredStateActive=!1,this._valueDirty=!0,this.setSelection(values,preferred),committed=!0,afterCommit())}})}finally{this.selectionRequestDispatching=!1}return committed}selectOption(option){if(this.selectionRequestDispatching||this.effectiveDisabled||!this.isOptionAvailable(option))return;if(this.unknownOptionCache.get(option.value)===option){this.selectUnknownValue(option.value);return}const value=option.value,available=liveOptions=>liveOptions.has(option)&&option.value===value&&this.isOptionAvailable(option);if(this.multiple){const currentSlots=this.resolveOccurrenceSlots(this._selected,this._selectedOptions),selectedIndex=currentSlots.indexOf(option),selected=selectedIndex>=0,occurrences=selected?currentSlots.filter((_,index)=>index!==selectedIndex):[...currentSlots,option],values=selected?this._selected.filter((_,index)=>index!==selectedIndex):[...this._selected,value];this.requestSelection(values,occurrences,()=>{this.emitValueEvents(),this.emit("lr-activate",{value})},available);return}if(!(option!==this._selectedOptions[0]||value!==this._selected[0])){this.hide(),this.emit("lr-activate",{value});return}this.requestSelection([value],[option],()=>{this.hide(),this.emitValueEvents(),this.emit("lr-activate",{value})},available)}removeValueAt(index){return this.effectiveDisabled||index<0||index>=this._selected.length?!1:this.requestSelection(this._selected.filter((_,candidateIndex)=>candidateIndex!==index),this.resolveOccurrenceSlots(this._selected,this._selectedOptions).filter((_,candidateIndex)=>candidateIndex!==index),()=>this.emitValueEvents())}clear(){this.effectiveDisabled||this._selected.length===0||this.requestSelection([],[],()=>{this.emitValueEvents(),this.emit("lr-clear")})}removeTag(value,index,event){event.stopPropagation(),this._selected[index]===value&&this.removeValueAt(index)&&this.updateComplete.then(()=>{const buttons=[...this.renderRoot.querySelectorAll('[part~="tag__remove-button"]')];(buttons[Math.min(index,buttons.length-1)]??this.triggerElement)?.focus()})}typeAhead(char){this.typeBuffer.add(char,this.effectiveLocale);const navigable=this.navigableOptions();if(!navigable.length)return;const currentOption=this.open?navigable[this.activeIndex]:this._selectedOptions[this._selectedOptions.length-1],currentIndex=navigable.indexOf(currentOption),labels=this.memoOption("typeAheadLabels",[navigable,this.effectiveLocale],()=>{const locale=resolveIntlLocale(this.effectiveLocale);return new Map(navigable.map(option=>[option,option.label.toLocaleLowerCase(locale)]))});let match=null;for(let step=1;step<=navigable.length;step++){const index=(currentIndex+step+navigable.length)%navigable.length,option=navigable[index];if((this.open||!this.multiple||!this.selectedIndex.members.has(option))&&labels.get(option)?.startsWith(this.typeBuffer.text)){match=index;break}}if(match===null)return;const candidate=navigable[match];this.open?this.setActiveIndex(match,navigable):this.selectOption(candidate)}adornmentMarkup(option){return Array.from(option.children).filter(child=>["start","end","prefix","suffix"].includes(child.getAttribute("slot")??"")).map(child=>child.outerHTML).join("")}adornmentsFor(option){const cached=this.adornmentClones.get(option);if(cached)return cached;const cloneSlot=selector=>{const nodes=Array.from(option.querySelectorAll(selector));if(nodes.length!==0)return nodes.map(node=>node.cloneNode(!0))},resolved={markup:this.adornmentMarkup(option),start:cloneSlot(':scope > [slot="start"], :scope > [slot="prefix"]'),end:cloneSlot(':scope > [slot="end"], :scope > [slot="suffix"]')};return this.adornmentClones.set(option,resolved),resolved}renderRows(options,activeId){const out=[],chosen=new Set(this._selectedOptions);let currentGroup,groupRows=[],groupIndex=0;const flushGroup=()=>{if(groupRows.length!==0){if(currentGroup){const labelId=`${this.listId}-group-${groupIndex++}`;out.push(html`<div role="group" aria-labelledby=${labelId}>
|
|
2
2
|
<div id=${labelId} class="group-label" part="group-label">${currentGroup}</div>
|
|
3
3
|
${groupRows}
|
|
4
4
|
</div>`)}else out.push(...groupRows);groupRows=[]}};return options.forEach((o,i)=>{o.group!==currentGroup&&(flushGroup(),currentGroup=o.group);const id=`${this.listId}-opt-${i}`,unknown=this.unknownOptionCache.get(o.value)===o,selected=unknown||chosen.has(o),adornments=this.adornmentsFor(o);groupRows.push(html`<div
|