@aceshooting/lyra-ui 28.0.0 → 28.1.1
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 +51 -0
- package/dist/components/agent-tools/commit-card/commit-card.class.d.ts +2 -2
- package/dist/components/agent-tools/commit-card/commit-card.class.js +7 -8
- package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +1 -1
- package/dist/components/agent-tools/schema-viewer/schema-viewer.class.js +1 -1
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +4 -4
- package/dist/components/charts/chart/box-plot.class.d.ts +5 -3
- package/dist/components/charts/chart/box-plot.class.js +18 -17
- package/dist/components/charts/chart/chart.class.d.ts +6 -4
- package/dist/components/charts/chart/chart.class.js +19 -18
- package/dist/components/charts/chart/lite-chart.class.d.ts +1 -1
- package/dist/components/charts/chart/lite-chart.class.js +8 -8
- package/dist/components/conversation/message-feedback/message-feedback.class.js +2 -2
- package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
- package/dist/components/data/data-grid/data-grid-processing.js +1 -1
- package/dist/components/data/gauge/gauge.class.js +1 -1
- package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +1 -1
- package/dist/components/data/graph-query-builder/graph-query-builder.class.js +2 -2
- package/dist/components/data/heatmap/heatmap-label-cache.js +1 -0
- package/dist/components/data/heatmap/heatmap.class.d.ts +3 -2
- package/dist/components/data/heatmap/heatmap.class.js +2 -2
- package/dist/components/data/heatmap/heatmap.styles.js +1 -1
- package/dist/components/data/stat/stat.class.d.ts +11 -9
- package/dist/components/data/stat/stat.class.js +4 -2
- package/dist/components/data/tree/tree.class.js +1 -1
- package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
- package/dist/components/forms/color-picker/color-picker.class.js +3 -3
- package/dist/components/forms/combobox/combobox.class.d.ts +2 -4
- package/dist/components/forms/combobox/combobox.class.js +1 -1
- package/dist/components/forms/emoji-picker/emoji-picker.class.js +5 -5
- package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
- package/dist/components/forms/select/select.class.js +4 -3
- package/dist/components/forms/toggle-group/toggle-group.class.js +1 -1
- package/dist/components/layout/command-palette/command-palette.styles.js +1 -1
- package/dist/components/layout/filter-bar/filter-bar.class.js +3 -3
- package/dist/components/layout/menu/menu.class.js +1 -1
- package/dist/components/layout/menubar/menubar.class.js +1 -1
- package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.d.ts +1 -1
- package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.js +1 -1
- package/dist/components/layout/page/page.class.js +1 -1
- package/dist/components/layout/tab-group/tab-group.class.js +1 -1
- package/dist/components/media/attachment-trigger/attachment-trigger.class.js +1 -1
- package/dist/components/media/file-input/file-input.class.js +1 -1
- package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
- package/dist/components/retrieval/chunk-inspector/chunk-inspector.class.d.ts +1 -1
- package/dist/components/retrieval/chunk-inspector/chunk-inspector.class.js +2 -2
- package/dist/components/retrieval/citation-badge/citation-badge.class.js +1 -1
- package/dist/components/retrieval/entity-chip/entity-chip.class.js +1 -1
- package/dist/components/retrieval/graph/graph-canvas.js +1 -1
- package/dist/components/retrieval/graph-legend/graph-legend.class.js +2 -2
- package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.js +1 -1
- package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +1 -1
- package/dist/components/retrieval/retrieval-results/retrieval-results.class.d.ts +1 -1
- package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +4 -4
- package/dist/components/retrieval/source-picker/source-picker.class.d.ts +1 -1
- package/dist/components/retrieval/source-picker/source-picker.class.js +1 -1
- package/dist/components/viewers/email-viewer/email-viewer.class.js +1 -1
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +1 -1
- package/dist/framework-types.d.ts +1 -1
- package/dist/internal/default-strings/charts.generated.js +1 -1
- package/dist/internal/localization-types.d.ts +1 -1
- package/dist/internal/localization.js +1 -1
- package/dist/internal/native-modal-carrier.js +2 -2
- package/dist/internal/nonmodal-overlay-manager.js +1 -1
- package/dist/internal/open-overlay-ancestors.js +1 -0
- package/dist/internal/open-overlay-raise.styles.js +1 -1
- package/dist/internal/overlay-manager.d.ts +2 -0
- package/dist/internal/overlay-manager.js +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/testing/happy-dom-shims.d.ts +3 -1
- package/dist/testing/happy-dom-shims.js +1 -1
- package/llms/components/lr-box-plot.md +5 -0
- package/llms/components/lr-chart.md +6 -0
- package/llms/components/lr-color-picker.md +2 -0
- package/llms/components/lr-commit-card.md +3 -2
- package/llms/components/lr-heatmap.md +10 -2
- package/llms/components/lr-select.md +2 -0
- package/llms/components/lr-stat.md +4 -0
- package/llms/peers.md +1 -1
- package/llms/shared/ai-and-peers.md +44 -0
- package/llms/shared/testing-and-utilities.md +14 -1
- package/llms/shared.md +58 -1
- package/locales.json +138 -138
- package/package.json +7 -6
- package/registrations.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";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,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_noData,LYRA_DEFAULT_treeNodeMoved}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){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>=TREE_MAX_RENDER_NODES||inspected>=TREE_MAX_INSPECTED_POSITIONS){truncated=!0,limitReached=accepted>=TREE_MAX_RENDER_NODES;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._data=EMPTY_TREE_DATA,this.lastDataInput=void 0,this.declaredChildrenAtPath=new Map,this.declaredRootCount=0,this._dataTruncated=!1,this._limitReached=!1,this.label="",this.reorderable=!1,this._selection="single",this.activeId=null,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.activeId=item.nodeId)},this.contextSyncPending=!0,this.bulkExpansions=0,this.syncRequested=!1,this.syncRunning=!1,this.requestContextSync=()=>{this.contextSyncPending=!0,this.scheduleTreeSync()},this.onChildrenChanged=()=>{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.requestUpdate();const expanded=e.detail?.expanded===!0;(this.focusIsWithin(node)||!expanded&&this.activeId!==node.nodeId&&this.subtreeHasId(node,this.activeId))&&(this.activeId=node.nodeId)},this.onNodeSelect=event=>{const node=this.eventNode(event);!node||node.isDisabled||(this.activeId=node.nodeId,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,noData:LYRA_DEFAULT_noData,treeLimit:LYRA_DEFAULT_treeLimit,treeNodeMoved:LYRA_DEFAULT_treeNodeMoved}}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]}get data(){return this._data}set data(value){if(value===this._data||value===this.lastDataInput)return;this.lastDataInput=value,this.hasUpdated&&this.selectionBeforeRefresh===void 0&&(this.selectionBeforeRefresh=this.selectedItems.map(item=>item.nodeId));const previous=this._data,normalized=normalizeTreeData(value,this._data);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 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 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<TREE_MAX_RENDER_NODES;){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 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<TREE_MAX_RENDER_NODES;){const frame=stack.pop();if(seen.has(frame.node)||(seen.add(frame.node),configureTreeItemOwner(frame.node,{...treeItemOwnerContext(frame.node),activeId:this.activeId,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],seen=new Set;for(;stack.length>0&&seen.size<TREE_MAX_RENDER_NODES;){const current=stack.pop();if(seen.has(current)||current.isDisabled)continue;seen.add(current);const children=this.childrenOf(current).filter(child=>!child.isDisabled);!leavesOnly||children.length===0?this.setSelection(current,leavesOnly&¤t.hasChildren?!1:selected,!1):this.setSelection(current,!1,!1);for(let index=children.length-1;index>=0;index--)stack.push(children[index])}}deriveMultipleSelection(node,leavesOnly){const states=new Map,stack=[{item:node,visited:!1}],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>=TREE_MAX_RENDER_NODES||queued.has(entry.item))continue;queued.add(entry.item),stack.push({item:entry.item,visited:!0});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})}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<TREE_MAX_RENDER_NODES;){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();if(visible.some(node=>node.nodeId===this.activeId))return;const displaced=this.activeId;if(this.activeId=visible[0]?.nodeId??null,!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)}willUpdate(changed){if(super.willUpdate(changed),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){super.updated(changed);const targeted=changed.size===0&&this.hasAuthoredItems&&this.dirtyConfigureRoots.size>0;if(targeted){const nodes=this.nodeElements,count=nodes.length;for(const node of this.dirtyConfigureRoots){const i=nodes.indexOf(node);i<0||configureTreeItemOwner(node,{...treeItemOwnerContext(node),activeId:this.activeId,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:this.activeId,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.syncRequested=!0,!(this.syncRunning||this.bulkExpansions>0)&&(this.syncRunning=!0,this.syncTask=this.runTreeSync())}async runTreeSync(){try{for(;this.syncRequested;)this.syncRequested=!1,await super.getUpdateComplete(),await cascadeUpdateComplete(this.nodeElements),this.contextSyncPending&&(this.contextSyncPending=!1,this.applyTreeContext()),this.selectionSyncPending&&(this.selectionSyncPending=!1,this.normalizeSelection()),await cascadeUpdateComplete(this.nodeElements),this.reportRefreshSelectionChange(),this.confirmPendingReorder(),this.restorePendingFocus()}finally{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.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.pendingReorder=void 0,this.resetChildObserver()}adoptedCallback(){super.adoptedCallback(),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.activeId=node.nodeId,node.focus())}subtreeHasId(root,id){if(id==null)return!1;const stack=[...this.childrenOf(root)];for(let visited=0;stack.length>0&&visited<TREE_MAX_RENDER_NODES;visited++){const item=stack.pop();if(item.nodeId===id)return!0;stack.push(...this.childrenOf(item))}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();for(;this.syncRunning||this.isUpdatePending;)this.syncRunning&&await this.syncTask,result=await super.getUpdateComplete();return 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(){const queue=this.nodeElements.map(node=>({node,depth:0})),seen=new Set;this.bulkExpansions+=1;try{for(let index=0;index<queue.length&&seen.size<TREE_MAX_RENDER_NODES;index++){const{node,depth}=queue[index];seen.has(node)||(seen.add(node),node.isDisabled?node.expanded=!1:node.hasChildren&&node.expand(),await node.updateComplete,depth<TREE_MAX_RENDER_DEPTH&&queue.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(){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 html`
|
|
1
|
+
import{__decorate}from"tslib";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,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_noData,LYRA_DEFAULT_treeNodeMoved}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){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>=TREE_MAX_RENDER_NODES||inspected>=TREE_MAX_INSPECTED_POSITIONS){truncated=!0,limitReached=accepted>=TREE_MAX_RENDER_NODES;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._data=EMPTY_TREE_DATA,this.lastDataInput=void 0,this.declaredChildrenAtPath=new Map,this.declaredRootCount=0,this._dataTruncated=!1,this._limitReached=!1,this.label="",this.reorderable=!1,this._selection="single",this.activeId=null,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.activeId=item.nodeId)},this.contextSyncPending=!0,this.bulkExpansions=0,this.syncRequested=!1,this.syncRunning=!1,this.requestContextSync=()=>{this.contextSyncPending=!0,this.scheduleTreeSync()},this.onChildrenChanged=()=>{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.requestUpdate();const expanded=e.detail?.expanded===!0;(this.focusIsWithin(node)||!expanded&&this.activeId!==node.nodeId&&this.subtreeHasId(node,this.activeId))&&(this.activeId=node.nodeId)},this.onNodeSelect=event=>{const node=this.eventNode(event);!node||node.isDisabled||(this.activeId=node.nodeId,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,noData:LYRA_DEFAULT_noData,treeLimit:LYRA_DEFAULT_treeLimit,treeNodeMoved:LYRA_DEFAULT_treeNodeMoved}}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]}get data(){return this._data}set data(value){if(value===this._data||value===this.lastDataInput)return;this.lastDataInput=value,this.hasUpdated&&this.selectionBeforeRefresh===void 0&&(this.selectionBeforeRefresh=this.selectedItems.map(item=>item.nodeId));const previous=this._data,normalized=normalizeTreeData(value,this._data);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 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 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<TREE_MAX_RENDER_NODES;){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 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<TREE_MAX_RENDER_NODES;){const frame=stack.pop();if(seen.has(frame.node)||(seen.add(frame.node),configureTreeItemOwner(frame.node,{...treeItemOwnerContext(frame.node),activeId:this.activeId,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],seen=new Set;for(;stack.length>0&&seen.size<TREE_MAX_RENDER_NODES;){const current=stack.pop();if(seen.has(current)||current.isDisabled)continue;seen.add(current);const children=this.childrenOf(current).filter(child=>!child.isDisabled);!leavesOnly||children.length===0?this.setSelection(current,leavesOnly&¤t.hasChildren?!1:selected,!1):this.setSelection(current,!1,!1);for(let index=children.length-1;index>=0;index--)stack.push(children[index])}}deriveMultipleSelection(node,leavesOnly){const states=new Map,stack=[{item:node,visited:!1}],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>=TREE_MAX_RENDER_NODES||queued.has(entry.item))continue;queued.add(entry.item),stack.push({item:entry.item,visited:!0});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})}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<TREE_MAX_RENDER_NODES;){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();if(visible.some(node=>node.nodeId===this.activeId))return;const displaced=this.activeId;if(this.activeId=visible[0]?.nodeId??null,!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)}willUpdate(changed){if(super.willUpdate(changed),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){super.updated(changed);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:this.activeId,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:this.activeId,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.syncRequested=!0,!(this.syncRunning||this.bulkExpansions>0)&&(this.syncRunning=!0,this.syncTask=this.runTreeSync())}async runTreeSync(){try{for(;this.syncRequested;)this.syncRequested=!1,await super.getUpdateComplete(),await cascadeUpdateComplete(this.nodeElements),this.contextSyncPending&&(this.contextSyncPending=!1,this.applyTreeContext()),this.selectionSyncPending&&(this.selectionSyncPending=!1,this.normalizeSelection()),await cascadeUpdateComplete(this.nodeElements),this.reportRefreshSelectionChange(),this.confirmPendingReorder(),this.restorePendingFocus()}finally{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.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.pendingReorder=void 0,this.resetChildObserver()}adoptedCallback(){super.adoptedCallback(),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.activeId=node.nodeId,node.focus())}subtreeHasId(root,id){if(id==null)return!1;const stack=[...this.childrenOf(root)];for(let visited=0;stack.length>0&&visited<TREE_MAX_RENDER_NODES;visited++){const item=stack.pop();if(item.nodeId===id)return!0;stack.push(...this.childrenOf(item))}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();for(;this.syncRunning||this.isUpdatePending;)this.syncRunning&&await this.syncTask,result=await super.getUpdateComplete();return 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(){const queue=this.nodeElements.map(node=>({node,depth:0})),seen=new Set;this.bulkExpansions+=1;try{for(let index=0;index<queue.length&&seen.size<TREE_MAX_RENDER_NODES;index++){const{node,depth}=queue[index];seen.has(node)||(seen.add(node),node.isDisabled?node.expanded=!1:node.hasChildren&&node.expand(),await node.updateComplete,depth<TREE_MAX_RENDER_DEPTH&&queue.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(){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 html`
|
|
2
2
|
<div
|
|
3
3
|
part="base tree"
|
|
4
4
|
role="tree"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{emitValueEvents}from"../../../internal/value-events.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{FormControlController,reflectFormName}from"../../../internal/form-control-controller.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{tag}from"../../../internal/prefix.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{resolveValidityAnchor,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{hostAriaLabel,nextId,srOnly}from"../../../internal/a11y.js";import{acquireAriaDescription,acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./checkbox-group.styles.js";import{createStringArrayFormDataState,getFormOwner,isBarredFromValidation,readStringArrayFormDataState,setFormOwner}from"../../../internal/form-associated.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{LYRA_DEFAULT_checkboxGroupRequired}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();const DUPLICATE_VALUE_WARNING_KEY="lyra-checkbox-group-duplicate-child-values",DUPLICATE_VALUE_WARNING="<lr-checkbox-group>: duplicate child values make submitted FormData ambiguous; give each child a distinct value.";class LyraCheckboxGroup extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,checkboxGroupRequired:LYRA_DEFAULT_checkboxGroupRequired,fieldRequired:LYRA_DEFAULT_fieldRequired}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-checkbox-group-toggle-request"])}static{this.identityEventDetailProperties=Object.freeze({"lr-checkbox-group-toggle-request":Object.freeze(["option"])})}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},size:{reflect:!0},orientation:{reflect:!0},value:{attribute:!1,noAccessor:!0}}}get hasLabelSlot(){return this.slotPresence.has("label")}get hasHintSlot(){return this.slotPresence.has("hint")}get hasErrorSlot(){return this.slotPresence.has("error")}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",reflectFormName(this,this._name),this.sync(),this.requestUpdate("name",old)}get value(){return Object.freeze([...this._value])}set value(next){markVetoGuardWrite(this.toggleGuard);const requested=Array.isArray(next)?next.filter(entry=>typeof entry=="string"):[];if(this.boxes.length===0){this.pendingValues=requested;return}this.pendingValues=void 0,this.applyValues(requested)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.sync(),this.requestUpdate("required",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this.propagateDisabled(),this.sync(),this.requestUpdate("disabled",old)}constructor(){super(),this.orientation="vertical",this.label="",this.hint="",this.withLabel=!1,this.withHint=!1,this.errorText="",this.accessibleLabel="",this.hasInteracted=!1,this.slotPresence=new SlotPresenceController(this),this.labelId=nextId("checkbox-group-label"),this.hintId=nextId("checkbox-group-hint"),this.errorId=nextId("checkbox-group-error"),this.requiredDescriptionId=nextId("checkbox-group-required"),this._fieldsetDisabled=!1,this._name="",this._required=!1,this._disabled=!1,this._value=[],this.childObserverGeneration=0,this.childControllers=new Map,this.toggleGuard=new VetoWriteGuard,this.authoredChildSizes=new Map,this.markInteracted=()=>{this.hasInteracted||(this.hasInteracted=!0,this.reflectValidityStates())},this.syncQueued=!1,this.suppressCheckboxSync=!1,this.onChildEvent=event=>{if(!this.isOwnedCheckbox(event.target)||(event.stopImmediatePropagation(),event.type!=="change"||this.effectiveDisabled))return;this.hasInteracted=!0,this.sync();const value=this.value,detail=()=>Object.freeze({value:Object.freeze([...value])});emitValueEvents(this,"input",detail(),detail2=>this.emit("lr-input",detail2)),emitValueEvents(this,"change",detail(),detail2=>this.emit("lr-change",detail2))},this.onChildToggleRequest=event=>{if(!this.isOwnedCheckbox(event.target)||(event.stopImmediatePropagation(),this.effectiveDisabled))return;const option=event.target,proposed=event.detail.checked;let allowed=!1;requestThenCommit({requestDetail:{value:this.projectedValue(option,proposed),previousValue:this.value,option},emitRequest:(detail,init)=>this.emit("lr-checkbox-group-toggle-request",detail,init),guard:this.toggleGuard,commit:()=>{allowed=!0}}),allowed||event.preventDefault()},this.onChildMutations=records=>{if(records.some(record=>record.type==="childList"||record.attributeName==="slot")){this.onSlotChange();return}for(const record of records){if(record.attributeName!=="size"||!this.isOwnedCheckbox(record.target))continue;const box=record.target;this.size!==void 0&&box.size!==this.size&&this.authoredChildSizes.set(box,box.size)}records.some(record=>record.attributeName==="size"&&this.isOwnedCheckbox(record.target))&&this.propagateSize(),records.some(record=>this.isOwnedCheckbox(record.target))&&this.sync()},this.onSlotChange=()=>{this.cachedBoxes=void 0,this.reconcileChildControllers(),!this.applyPendingRestore()&&!this.applyPendingValues()&&this.sync(),this.propagateDisabled(),this.propagateSize()},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}checkboxGroupOwner(element){const group=element.closest(tag("checkbox-group"));if(!group)return null;let topLevelChild=element;for(;topLevelChild.parentElement&&topLevelChild.parentElement!==group;)topLevelChild=topLevelChild.parentElement;if(topLevelChild.parentElement!==group)return null;const slot=topLevelChild.getAttribute("slot");return slot==="label"||slot==="hint"||slot==="error"?null:group}ownsCheckbox(element){return element.localName===tag("checkbox")&&this.checkboxGroupOwner(element)===this}get boxes(){const querySelectorAll=this.querySelectorAll;return typeof querySelectorAll!="function"?[]:Array.from(querySelectorAll.call(this,"lr-checkbox")).filter(box=>this.ownsCheckbox(box))}syncBoxes(){return this.cachedBoxes||(this.cachedBoxes=this.boxes,queueMicrotask(()=>{this.cachedBoxes=void 0})),this.cachedBoxes}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}propagateDisabled(){const effective=this.effectiveDisabled;this.boxes.forEach(box=>box.setGroupDisabled?.(effective))}propagateSize(){for(const box of this.boxes)if(this.authoredChildSizes.has(box)||this.authoredChildSizes.set(box,box.size),this.size===void 0||this.size===null){const authored=this.authoredChildSizes.get(box);authored!==void 0&&box.size!==authored&&(box.size=authored),this.authoredChildSizes.delete(box)}else box.size!==this.size&&(box.size=this.size)}sync(){const next=[],seen=new Set;for(const box of this.syncBoxes()){const value=box.value??box.getAttribute("value")??"on";seen.has(value)&&devWarnOnce(DUPLICATE_VALUE_WARNING_KEY,DUPLICATE_VALUE_WARNING),seen.add(value),box.checked&&next.push(value)}const old=this._value;this._value=next,this.requestUpdate("value",old);const data=new FormData;this.name&&next.forEach(value=>data.append(this.name,value)),this.internals.setFormValue(this.name?data:null,createStringArrayFormDataState(this.name,next)),!this.barredFromValidation&&this.required&&next.length===0?this.validityController.setValidity({valueMissing:!0},this.localize("checkboxGroupRequired")):this.validityController.setValidity({}),this.reflectValidityStates()}scheduleSync(){this.syncQueued||(this.syncQueued=!0,queueMicrotask(()=>{this.syncQueued=!1,this.isConnected&&this.sync()}))}notifyCheckboxStateChange(checkbox){this.suppressCheckboxSync||this.isConnected&&this.ownsCheckbox(checkbox)&&this.sync()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}reflectValidityStates(){const barred=this.barredFromValidation;this.toggleAttribute("data-invalid",!barred&&this.hasInteracted&&!this.internals.validity.valid),syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred})}isOwnedCheckbox(target){return target?.nodeType===1&&this.ownsCheckbox(target)}projectedValue(option,proposed){return Object.freeze(this.boxes.filter(box=>box===option?proposed:box.checked).map(box=>box.value??"on"))}reconcileChildControllers(){const current=new Set(this.boxes);for(const[box,controller]of this.childControllers){if(current.has(box))continue;box.removeController(controller),this.childControllers.delete(box);const authoredSize=this.authoredChildSizes.get(box);authoredSize!==void 0&&box.size!==authoredSize&&(box.size=authoredSize),this.authoredChildSizes.delete(box);const nextOwner=this.checkboxGroupOwner(box);(!nextOwner||nextOwner===this)&&box.setGroupDisabled?.(!1)}for(const box of current){if(this.childControllers.has(box)||typeof box.addController!="function")continue;const controller={hostUpdated:()=>{this.isConnected&&this.ownsCheckbox(box)&&this.scheduleSync()}};box.addController(controller),this.childControllers.set(box,controller)}}applyValues(values){const remaining=[...values];this.suppressCheckboxSync=!0;try{for(const box of this.boxes){const value=box.value??"on",index=remaining.indexOf(value);box.checked=index>=0,index>=0&&remaining.splice(index,1)}}finally{this.suppressCheckboxSync=!1}this.sync()}applyPendingRestore(){if(this.pendingRestoreValues===void 0||this.boxes.length===0)return!1;const values=this.pendingRestoreValues;return this.pendingRestoreValues=void 0,this.hasInteracted=!1,this.applyValues(values),!0}applyPendingValues(){if(this.pendingValues===void 0||this.boxes.length===0)return!1;const values=this.pendingValues;return this.pendingValues=void 0,this.applyValues(values),!0}connectedCallback(){super.connectedCallback(),this.cachedBoxes=void 0,this.addEventListener("input",this.onChildEvent,{capture:!0}),this.addEventListener("lr-input",this.onChildEvent,{capture:!0}),this.addEventListener("change",this.onChildEvent,{capture:!0}),this.addEventListener("lr-change",this.onChildEvent,{capture:!0}),this.addEventListener("lr-checkbox-toggle-request",this.onChildToggleRequest,{capture:!0}),this.hasUpdated?this.onSlotChange():(this.reconcileChildControllers(),!this.applyPendingRestore()&&!this.applyPendingValues()&&this.sync(),this.propagateDisabled(),this.propagateSize()),this.armChildObserver(),this.hasUpdated&&(this.syncRequiredDescription(),this.syncExternalDescription())}armChildObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected||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,{attributes:!0,childList:!0,subtree:!0,attributeFilter:["checked","value","disabled","size","slot"]})}disconnectedCallback(){this.releaseExternalDescription(),this.releaseRequiredDescription(),this.cachedBoxes=void 0,this.removeEventListener("input",this.onChildEvent,{capture:!0}),this.removeEventListener("lr-input",this.onChildEvent,{capture:!0}),this.removeEventListener("change",this.onChildEvent,{capture:!0}),this.removeEventListener("lr-change",this.onChildEvent,{capture:!0}),this.removeEventListener("lr-checkbox-toggle-request",this.onChildToggleRequest,{capture:!0}),this.resetChildObserver();for(const[box,controller]of this.childControllers){box.removeController(controller),box.setGroupDisabled?.(!1);const authoredSize=this.authoredChildSizes.get(box);authoredSize!==void 0&&box.size!==authoredSize&&(box.size=authoredSize)}this.childControllers.clear(),this.authoredChildSizes.clear(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.releaseRequiredDescription(),this.resetChildObserver(),this.isConnected&&this.hasUpdated&&(this.syncRequiredDescription(),this.syncExternalDescription())}resetChildObserver(){this.childObserverGeneration+=1,this.childObserver?.disconnect(),this.childObserver=void 0,this.childObserverDocument=void 0}firstUpdated(changed){super.firstUpdated(changed),this.addEventListener("blur",event=>{const blurredControl=event.target;(typeof blurredControl?.matches=="function"?blurredControl.matches(":disabled"):this.effectiveDisabled)||(this.hasInteracted=!0),this.sync()},!0)}updated(changed){super.updated(changed),changed.has("size")&&this.propagateSize(),this.syncRequiredDescription(),this.syncExternalDescription()}syncExternalDescription(){const target=this.renderRoot.querySelector("fieldset");if(!target){this.releaseExternalDescription();return}if(!this.externalDescriptionLease){this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby");return}this.externalDescriptionLease.update(target)}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}syncRequiredDescription(){const target=this.renderRoot.querySelector("fieldset"),description=this.renderRoot.querySelector(`#${this.requiredDescriptionId}`);if(!this.required||!target||!description){this.releaseRequiredDescription();return}if(this.requiredDescriptionTarget!==target){this.releaseRequiredDescription(),this.requiredDescriptionTarget=target,this.requiredDescriptionLease=acquireAriaDescription(target,[description]);return}this.requiredDescriptionLease?.update([description])}releaseRequiredDescription(){this.requiredDescriptionLease?.release(),this.requiredDescriptionLease=void 0,this.requiredDescriptionTarget=void 0}[VALIDITY_ANCHOR](){const first=this.firstEnabledBox();return resolveValidityAnchor(first)??first??null}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}checkValidity(){return this.validityController.checkValidity()}reportValidity(){return this.validityController.syncConstraints(),this.hasInteracted=!0,this.reflectValidityStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.reflectValidityStates(),this.requestUpdate()}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}firstEnabledBox(){return this.boxes.find(box=>!box.effectiveDisabled&&!box.matches(":disabled"))}focus(options){this.liveDisabled||this.firstEnabledBox()?.focus(options)}blur(){this.boxes.find(box=>box.matches(":focus-within"))?.blur()}click(){this.liveDisabled||this.firstEnabledBox()?.click()}formResetCallback(){this.suppressCheckboxSync=!0;try{this.boxes.forEach(box=>box.resetFromGroup())}finally{this.suppressCheckboxSync=!1}this.hasInteracted=!1,this.sync()}formStateRestoreCallback(state2,_mode){this.pendingRestoreValues=readStringArrayFormDataState(state2),this.applyPendingRestore()}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(this.propagateDisabled(),this.sync(),this.requestUpdate())}render(){const hasLabel=this.hasLabelSlot||!!this.label||this.withLabel,hasHint=this.hasHintSlot||!!this.hint||this.withHint,hasError=this.hasErrorSlot||!!this.errorText,described=[hasHint?this.hintId:"",hasError?this.errorId:""].filter(Boolean).join(" ")||nothing,invalid=hasError||this.hasInteracted&&!this.internals.validity.valid;return html`<fieldset
|
|
1
|
+
import{__decorate}from"tslib";import{emitValueEvents}from"../../../internal/value-events.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{FormControlController,reflectFormName}from"../../../internal/form-control-controller.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{tag}from"../../../internal/prefix.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{resolveValidityAnchor,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{hostAriaLabel,nextId,srOnly}from"../../../internal/a11y.js";import{acquireAriaDescription,acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./checkbox-group.styles.js";import{createStringArrayFormDataState,getFormOwner,isBarredFromValidation,readStringArrayFormDataState,setFormOwner}from"../../../internal/form-associated.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{LYRA_DEFAULT_checkboxGroupRequired}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();const DUPLICATE_VALUE_WARNING_KEY="lyra-checkbox-group-duplicate-child-values",DUPLICATE_VALUE_WARNING="<lr-checkbox-group>: duplicate child values make submitted FormData ambiguous; give each child a distinct value.";class LyraCheckboxGroup extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,checkboxGroupRequired:LYRA_DEFAULT_checkboxGroupRequired,fieldRequired:LYRA_DEFAULT_fieldRequired}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-checkbox-group-toggle-request"])}static{this.identityEventDetailProperties=Object.freeze({"lr-checkbox-group-toggle-request":Object.freeze(["option"])})}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},size:{reflect:!0},orientation:{reflect:!0},value:{attribute:!1,noAccessor:!0}}}get hasLabelSlot(){return this.slotPresence.has("label")}get hasHintSlot(){return this.slotPresence.has("hint")}get hasErrorSlot(){return this.slotPresence.has("error")}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",reflectFormName(this,this._name),this.sync(),this.requestUpdate("name",old)}get value(){return Object.freeze([...this._value])}set value(next){markVetoGuardWrite(this.toggleGuard);const requested=Array.isArray(next)?next.filter(entry=>typeof entry=="string"):[];if(this.boxes.length===0){this.pendingValues=requested;return}this.pendingValues=void 0,this.applyValues(requested)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.sync(),this.requestUpdate("required",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this.propagateDisabled(),this.sync(),this.requestUpdate("disabled",old)}constructor(){super(),this.orientation="vertical",this.label="",this.hint="",this.withLabel=!1,this.withHint=!1,this.errorText="",this.accessibleLabel="",this.hasInteracted=!1,this.slotPresence=new SlotPresenceController(this),this.labelId=nextId("checkbox-group-label"),this.hintId=nextId("checkbox-group-hint"),this.errorId=nextId("checkbox-group-error"),this.requiredDescriptionId=nextId("checkbox-group-required"),this._fieldsetDisabled=!1,this._name="",this._required=!1,this._disabled=!1,this._value=[],this.childObserverGeneration=0,this.childControllers=new Map,this.toggleGuard=new VetoWriteGuard,this.authoredChildSizes=new Map,this.markInteracted=()=>{this.hasInteracted||(this.hasInteracted=!0,this.reflectValidityStates())},this.syncQueued=!1,this.suppressCheckboxSync=!1,this.onChildEvent=event=>{if(!this.isOwnedCheckbox(event.target)||(event.stopImmediatePropagation(),event.type!=="change"||this.effectiveDisabled))return;this.hasInteracted=!0,this.sync();const value=this.value,detail=()=>Object.freeze({value:Object.freeze([...value])});emitValueEvents(this,"input",detail(),detail2=>this.emit("lr-input",detail2)),emitValueEvents(this,"change",detail(),detail2=>this.emit("lr-change",detail2))},this.onChildToggleRequest=event=>{if(!this.isOwnedCheckbox(event.target)||(event.stopImmediatePropagation(),this.effectiveDisabled))return;const option=event.target,proposed=event.detail.checked;let allowed=!1;requestThenCommit({requestDetail:{value:this.projectedValue(option,proposed),previousValue:this.value,option},emitRequest:(detail,init)=>this.emit("lr-checkbox-group-toggle-request",detail,init),guard:this.toggleGuard,commit:()=>{allowed=!0}}),allowed||event.preventDefault()},this.onChildMutations=records=>{if(records.some(record=>record.type==="childList"||record.attributeName==="slot")){this.onSlotChange();return}for(const record of records){if(record.attributeName!=="size"||!this.isOwnedCheckbox(record.target))continue;const box=record.target;this.size!==void 0&&box.size!==this.size&&this.authoredChildSizes.set(box,box.size)}records.some(record=>record.attributeName==="size"&&this.isOwnedCheckbox(record.target))&&this.propagateSize(),records.some(record=>this.isOwnedCheckbox(record.target))&&this.sync()},this.onSlotChange=()=>{this.cachedBoxes=void 0,this.reconcileChildControllers(),!this.applyPendingRestore()&&!this.applyPendingValues()&&this.sync(),this.propagateDisabled(),this.propagateSize()},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}checkboxGroupOwner(element){const group=element.closest(tag("checkbox-group"));if(!group)return null;let topLevelChild=element;for(;topLevelChild.parentElement&&topLevelChild.parentElement!==group;)topLevelChild=topLevelChild.parentElement;if(topLevelChild.parentElement!==group)return null;const slot=topLevelChild.getAttribute("slot");return slot==="label"||slot==="hint"||slot==="error"?null:group}ownsCheckbox(element){return element.localName===tag("checkbox")&&this.checkboxGroupOwner(element)===this}get boxes(){const querySelectorAll=this.querySelectorAll;return typeof querySelectorAll!="function"?[]:Array.from(querySelectorAll.call(this,"lr-checkbox")).filter(box=>this.ownsCheckbox(box))}syncBoxes(){return this.cachedBoxes||(this.cachedBoxes=this.boxes,queueMicrotask(()=>{this.cachedBoxes=void 0})),this.cachedBoxes}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}propagateDisabled(){const effective=this.effectiveDisabled;this.boxes.forEach(box=>box.setGroupDisabled?.(effective))}propagateSize(){for(const box of this.boxes)if(this.authoredChildSizes.has(box)||this.authoredChildSizes.set(box,box.size),this.size===void 0||this.size===null){const authored=this.authoredChildSizes.get(box);authored!==void 0&&box.size!==authored&&(box.size=authored),this.authoredChildSizes.delete(box)}else box.size!==this.size&&(box.size=this.size)}sync(){const next=[],seen=new Set;for(const box of this.syncBoxes()){const value=box.value??box.getAttribute("value")??"on";seen.has(value)&&devWarnOnce(DUPLICATE_VALUE_WARNING_KEY,DUPLICATE_VALUE_WARNING),seen.add(value),box.checked&&next.push(value)}const old=this._value;this._value=next,this.requestUpdate("value",old);const data=new FormData;this.name&&next.forEach(value=>data.append(this.name,value)),this.internals.setFormValue(this.name?data:null,createStringArrayFormDataState(this.name,next)),!this.barredFromValidation&&this.required&&next.length===0?this.validityController.setValidity({valueMissing:!0},this.localize("checkboxGroupRequired")):this.validityController.setValidity({}),this.reflectValidityStates()}scheduleSync(){this.syncQueued||(this.syncQueued=!0,queueMicrotask(()=>{this.syncQueued=!1,this.isConnected&&this.sync()}))}notifyCheckboxStateChange(checkbox){this.suppressCheckboxSync||this.isConnected&&this.ownsCheckbox(checkbox)&&this.sync()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}reflectValidityStates(){const barred=this.barredFromValidation;this.toggleAttribute("data-invalid",!barred&&this.hasInteracted&&!this.internals.validity.valid),syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred})}isOwnedCheckbox(target){return target?.nodeType===1&&this.ownsCheckbox(target)}projectedValue(option,proposed){return Object.freeze(this.boxes.filter(box=>box===option?proposed:box.checked).map(box=>box.value??"on"))}reconcileChildControllers(){const current=new Set(this.boxes);for(const[box,controller]of this.childControllers){if(current.has(box))continue;box.removeController(controller),this.childControllers.delete(box);const authoredSize=this.authoredChildSizes.get(box);authoredSize!==void 0&&box.size!==authoredSize&&(box.size=authoredSize),this.authoredChildSizes.delete(box);const nextOwner=this.checkboxGroupOwner(box);(!nextOwner||nextOwner===this)&&box.setGroupDisabled?.(!1)}for(const box of current){if(this.childControllers.has(box)||typeof box.addController!="function")continue;const controller={hostUpdated:()=>{this.isConnected&&this.ownsCheckbox(box)&&this.scheduleSync()}};box.addController(controller),this.childControllers.set(box,controller)}}applyValues(values){const remaining=new Map;for(const value of values)remaining.set(value,(remaining.get(value)??0)+1);this.suppressCheckboxSync=!0;try{for(const box of this.boxes){const value=box.value??"on",count=remaining.get(value)??0;box.checked=count>0,count>0&&remaining.set(value,count-1)}}finally{this.suppressCheckboxSync=!1}this.sync()}applyPendingRestore(){if(this.pendingRestoreValues===void 0||this.boxes.length===0)return!1;const values=this.pendingRestoreValues;return this.pendingRestoreValues=void 0,this.hasInteracted=!1,this.applyValues(values),!0}applyPendingValues(){if(this.pendingValues===void 0||this.boxes.length===0)return!1;const values=this.pendingValues;return this.pendingValues=void 0,this.applyValues(values),!0}connectedCallback(){super.connectedCallback(),this.cachedBoxes=void 0,this.addEventListener("input",this.onChildEvent,{capture:!0}),this.addEventListener("lr-input",this.onChildEvent,{capture:!0}),this.addEventListener("change",this.onChildEvent,{capture:!0}),this.addEventListener("lr-change",this.onChildEvent,{capture:!0}),this.addEventListener("lr-checkbox-toggle-request",this.onChildToggleRequest,{capture:!0}),this.hasUpdated?this.onSlotChange():(this.reconcileChildControllers(),!this.applyPendingRestore()&&!this.applyPendingValues()&&this.sync(),this.propagateDisabled(),this.propagateSize()),this.armChildObserver(),this.hasUpdated&&(this.syncRequiredDescription(),this.syncExternalDescription())}armChildObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected||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,{attributes:!0,childList:!0,subtree:!0,attributeFilter:["checked","value","disabled","size","slot"]})}disconnectedCallback(){this.releaseExternalDescription(),this.releaseRequiredDescription(),this.cachedBoxes=void 0,this.removeEventListener("input",this.onChildEvent,{capture:!0}),this.removeEventListener("lr-input",this.onChildEvent,{capture:!0}),this.removeEventListener("change",this.onChildEvent,{capture:!0}),this.removeEventListener("lr-change",this.onChildEvent,{capture:!0}),this.removeEventListener("lr-checkbox-toggle-request",this.onChildToggleRequest,{capture:!0}),this.resetChildObserver();for(const[box,controller]of this.childControllers){box.removeController(controller),box.setGroupDisabled?.(!1);const authoredSize=this.authoredChildSizes.get(box);authoredSize!==void 0&&box.size!==authoredSize&&(box.size=authoredSize)}this.childControllers.clear(),this.authoredChildSizes.clear(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.releaseRequiredDescription(),this.resetChildObserver(),this.isConnected&&this.hasUpdated&&(this.syncRequiredDescription(),this.syncExternalDescription())}resetChildObserver(){this.childObserverGeneration+=1,this.childObserver?.disconnect(),this.childObserver=void 0,this.childObserverDocument=void 0}firstUpdated(changed){super.firstUpdated(changed),this.addEventListener("blur",event=>{const blurredControl=event.target;(typeof blurredControl?.matches=="function"?blurredControl.matches(":disabled"):this.effectiveDisabled)||(this.hasInteracted=!0),this.sync()},!0)}updated(changed){super.updated(changed),changed.has("size")&&this.propagateSize(),this.syncRequiredDescription(),this.syncExternalDescription()}syncExternalDescription(){const target=this.renderRoot.querySelector("fieldset");if(!target){this.releaseExternalDescription();return}if(!this.externalDescriptionLease){this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby");return}this.externalDescriptionLease.update(target)}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}syncRequiredDescription(){const target=this.renderRoot.querySelector("fieldset"),description=this.renderRoot.querySelector(`#${this.requiredDescriptionId}`);if(!this.required||!target||!description){this.releaseRequiredDescription();return}if(this.requiredDescriptionTarget!==target){this.releaseRequiredDescription(),this.requiredDescriptionTarget=target,this.requiredDescriptionLease=acquireAriaDescription(target,[description]);return}this.requiredDescriptionLease?.update([description])}releaseRequiredDescription(){this.requiredDescriptionLease?.release(),this.requiredDescriptionLease=void 0,this.requiredDescriptionTarget=void 0}[VALIDITY_ANCHOR](){const first=this.firstEnabledBox();return resolveValidityAnchor(first)??first??null}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}checkValidity(){return this.validityController.checkValidity()}reportValidity(){return this.validityController.syncConstraints(),this.hasInteracted=!0,this.reflectValidityStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.reflectValidityStates(),this.requestUpdate()}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}firstEnabledBox(){return this.boxes.find(box=>!box.effectiveDisabled&&!box.matches(":disabled"))}focus(options){this.liveDisabled||this.firstEnabledBox()?.focus(options)}blur(){this.boxes.find(box=>box.matches(":focus-within"))?.blur()}click(){this.liveDisabled||this.firstEnabledBox()?.click()}formResetCallback(){this.suppressCheckboxSync=!0;try{this.boxes.forEach(box=>box.resetFromGroup())}finally{this.suppressCheckboxSync=!1}this.hasInteracted=!1,this.sync()}formStateRestoreCallback(state2,_mode){this.pendingRestoreValues=readStringArrayFormDataState(state2),this.applyPendingRestore()}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(this.propagateDisabled(),this.sync(),this.requestUpdate())}render(){const hasLabel=this.hasLabelSlot||!!this.label||this.withLabel,hasHint=this.hasHintSlot||!!this.hint||this.withHint,hasError=this.hasErrorSlot||!!this.errorText,described=[hasHint?this.hintId:"",hasError?this.errorId:""].filter(Boolean).join(" ")||nothing,invalid=hasError||this.hasInteracted&&!this.internals.validity.valid;return html`<fieldset
|
|
2
2
|
part="form-control"
|
|
3
3
|
?disabled=${this.effectiveDisabled}
|
|
4
4
|
aria-label=${hostAriaLabel(this)??nothing}
|
|
@@ -141,7 +141,7 @@ import{__decorate}from"tslib";import{GlassScrollLayer}from"../../../internal/gla
|
|
|
141
141
|
><span part="eyedropper-button__caret eye-dropper-button__caret"></span></button>`:nothing}
|
|
142
142
|
</div>
|
|
143
143
|
${entries.length>0?this.renderSwatches(entries):nothing}
|
|
144
|
-
</div>`}render(){const hasLabel=this.withLabel||this.hasLabel||!!this.label,hasHint=this.withHint||this.hasHint||!!this.hint,hasError=this.hasError||!!this.errorText,name=hostAriaLabel(this)??(hasLabel?"":this.localize("colorPicker")),labelledBy=!this.accessibleLabel&&hasLabel?this.labelId:"",userInvalid=hasCustomState(this.internals,"user-invalid"),invalid=hasError||userInvalid,describedBy=
|
|
144
|
+
</div>`}render(){const hasLabel=this.withLabel||this.hasLabel||!!this.label,hasHint=this.withHint||this.hasHint||!!this.hint,hasError=this.hasError||!!this.errorText,name=hostAriaLabel(this)??(hasLabel?"":this.localize("colorPicker")),labelledBy=!this.accessibleLabel&&hasLabel?this.labelId:"",userInvalid=hasCustomState(this.internals,"user-invalid"),invalid=hasError||userInvalid,describedBy=[hasError?this.errorId:"",hasHint?this.hintId:"",this.valueTextId].filter(Boolean).join(" "),requiredTextId=`${this.triggerId}-required`,triggerDescribedBy=this.localDescriptionIds=[this.required&&!this.inline?requiredTextId:"",describedBy].filter(Boolean).join(" ");return html`<div
|
|
145
145
|
part="form-control base color-picker"
|
|
146
146
|
@focus=${this.controlFocusListener}
|
|
147
147
|
@blur=${this.controlBlurListener}
|
|
@@ -159,14 +159,14 @@ import{__decorate}from"tslib";import{GlassScrollLayer}from"../../../internal/gla
|
|
|
159
159
|
aria-haspopup="dialog"
|
|
160
160
|
aria-expanded=${this.open?"true":"false"}
|
|
161
161
|
aria-controls=${this.panelId}
|
|
162
|
-
aria-describedby=${
|
|
163
|
-
aria-required=${this.required?"true":"false"}
|
|
162
|
+
aria-describedby=${triggerDescribedBy}
|
|
164
163
|
aria-invalid=${invalid?"true":"false"}
|
|
165
164
|
?disabled=${this.effectiveDisabled}
|
|
166
165
|
style=${styleMap({"--lr-color-picker-swatch-color":cssColor(this.color)})}
|
|
167
166
|
@click=${this.onTriggerClick}
|
|
168
167
|
></button>
|
|
169
168
|
</div>`}
|
|
169
|
+
${this.required&&!this.inline?html`<span id=${requiredTextId} class="sr-only">${this.localize("fieldRequired")}</span>`:nothing}
|
|
170
170
|
<span id=${this.valueTextId} class="sr-only"
|
|
171
171
|
>${this.localize("colorPickerCurrentValue",void 0,{color:this.value||this.getFormattedValue(this.activeFormat())})}</span
|
|
172
172
|
>
|
|
@@ -588,7 +588,7 @@ get sourceTruncated():boolean;
|
|
|
588
588
|
* first row, and the write is silent like `value`. A property binding that arrives before local
|
|
589
589
|
* options or async rows is deferred until that source resolves. Read rows remain detached
|
|
590
590
|
* snapshots. */
|
|
591
|
-
get selectedRows():ComboboxSourceRow[];private resolveSelectedRowSlots;private get committed();private rowsByValue;set selectedRows(next:readonly ComboboxSourceRow[]);private get barredFromValidation();private validatorResult;private syncValidatorAttributeObserver;private disconnectValidatorAttributeObserver;private updateValidity;private syncCustomStates;private syncFormValue;
|
|
591
|
+
get selectedRows():ComboboxSourceRow[];private resolveSelectedRowSlots;private get committed();private rowsByValue;private localRowsByValue;set selectedRows(next:readonly ComboboxSourceRow[]);private get barredFromValidation();private validatorResult;private syncValidatorAttributeObserver;private disconnectValidatorAttributeObserver;private updateValidity;private syncCustomStates;private syncFormValue;
|
|
592
592
|
/** Effective disabled state: this element's own `disabled` OR an ancestor
|
|
593
593
|
* `<fieldset disabled>`'s inherited state -- mirrors native `<input>`, whose
|
|
594
594
|
* own `disabled` IDL property/attribute is never mutated by a fieldset. */
|
|
@@ -614,9 +614,7 @@ formDisabledCallback(disabled:boolean):void;private markInteracted;checkValidity
|
|
|
614
614
|
*
|
|
615
615
|
* The message is caller-supplied content, so it is used verbatim and never localized here.
|
|
616
616
|
*/
|
|
617
|
-
setCustomValidity(message:string):void;disconnectedCallback():void;private collectOptions;private collectOptionsFromSlot;private refreshOptionDefaults;private optionRefreshPending;private onOptionChange;private reflectSelected;private labelFor;private isUnknownValue;
|
|
618
|
-
/** The current row set in a source-agnostic shape, before capping. */
|
|
619
|
-
private adornmentClones;private adornmentMarkup;private adornmentsFor;private rowForOption;private get selectionSourceRows();private applySelectedRowValues;private applyPendingSelectedRows;private get effectiveRows();private get unknownRows();private get createRow();private get renderedRows();private normalizeActiveIndex;private get filtered();private get displayValue();private announceOpenTransition;
|
|
617
|
+
setCustomValidity(message:string):void;disconnectedCallback():void;private collectOptions;private collectOptionsFromSlot;private refreshOptionDefaults;private optionRefreshPending;private onOptionChange;private reflectSelected;private labelFor;private isUnknownValue;private adornmentClones;private adornmentMarkup;private adornmentsFor;private rowForOption;private get hasSelectionSourceRows();private applySelectedRowValues;private applyPendingSelectedRows;private get unknownRows();private get createRow();private capRows;private get renderedRows();private normalizeActiveIndex;private get filtered();private get displayValue();private announceOpenTransition;
|
|
620
618
|
/** Opens the listbox and resolves after `lr-after-show`. */
|
|
621
619
|
show():Promise<void>;
|
|
622
620
|
/** Closes the listbox and resolves after `lr-after-hide`. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{emitValueEvents}from"../../../internal/value-events.js";import{setNativeRangeText,nativeAutocorrectAttribute}from"../../../internal/native-text-control.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{loadAnchoredOverlayRuntime,syncTopLayerRelease,topLayerPlacement}from"../../../internal/anchored-overlay-runtime.js";import{hostAriaLabel,nextId,srOnly}from"../../../internal/a11y.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{submitOnEnter}from"../../../internal/submit-on-enter.js";import{finiteCount,finiteDuration}from"../../../internal/numbers.js";import{PopupController,emitPopupEvent}from"../../../internal/popup-controller.js";import{revealRow}from"../../../internal/reveal-row.js";import{DebounceController}from"../../../internal/debounce-controller.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./combobox.styles.js";import{autocorrectConverter,literalSetConverter,omittedEmptyStringConverter,optionalLiteralSetConverter,spellcheckConverter}from"../../../internal/converters.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{tag}from"../../../internal/prefix.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{renderDataState}from"../../../internal/data-state-renderer.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.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{relayNativeEvent}from"../../../internal/native-event-relay.js";import{LYRA_DEFAULT_comboboxCreate,LYRA_DEFAULT_comboboxLabel,LYRA_DEFAULT_comboboxLoadError,LYRA_DEFAULT_comboboxOverflow,LYRA_DEFAULT_comboboxRequired,LYRA_DEFAULT_comboboxSelectedOverflow}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noData,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_notInCatalog,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_retry,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_tableLoadFailed,LYRA_DEFAULT_valueInvalid}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"]),APPEARANCE=literalSetConverter(["accent","filled","outlined","filled-outlined","plain"],"outlined"),VALIDITY_FLAG_KEYS=new Set(["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"]),comboboxSpellcheckConverter={...spellcheckConverter,fromAttribute:(value,type)=>value===null?void 0:spellcheckConverter.fromAttribute?.(value,type)};function adornmentContent(value){return typeof value=="string"||typeof value=="number"?html`<span>${value}</span>`:value}function isValidityFlagKey(value){return typeof value=="string"&&VALIDITY_FLAG_KEYS.has(value)}const MAX_SOURCE_ROWS=2e3,MAX_SOURCE_TEXT_UNITS=25e4,MAX_SOURCE_FIELD_UNITS=4096,MAX_RENDER_ROWS=1e3;function isRenderable(value,nested=!1){if(typeof value=="string"||typeof value=="number")return!0;if(typeof value!="object"||value===null)return!1;if(Array.isArray(value))return!nested&&value.every(item=>isRenderable(item,!0));const{nodeType,cloneNode,strings}=value;return typeof nodeType=="number"&&typeof cloneNode=="function"||Array.isArray(strings)&&Object.hasOwn(strings,"raw")}function normalizeSourceResult(input){let candidateRows,candidateTotal;try{Array.isArray(input)?candidateRows=input:typeof input=="object"&&input!==null&&(candidateRows=input.rows,candidateTotal=input.total)}catch{throw new TypeError("Invalid combobox source result")}if(!Array.isArray(candidateRows))throw new TypeError("Invalid combobox source result");const providerTotal=typeof candidateTotal=="number"&&Number.isFinite(candidateTotal)&&candidateTotal>=0?Math.trunc(candidateTotal):candidateRows.length,rows=[];let textUnits=0;const limit=Math.min(candidateRows.length,MAX_SOURCE_ROWS);for(let index=0;index<limit;index++)try{const value=candidateRows[index]?.value,label=candidateRows[index]?.label;if(typeof value!="string"||typeof label!="string"||value.length>MAX_SOURCE_FIELD_UNITS||label.length>MAX_SOURCE_FIELD_UNITS)continue;const source=candidateRows[index],optionalText=key=>{const candidate=source[key];return typeof candidate=="string"&&candidate.length<=MAX_SOURCE_FIELD_UNITS?candidate:void 0},content=key=>{const candidate=source[key];return isRenderable(candidate)?candidate:void 0},icon=content("icon"),start=content("start"),end=content("end"),sub=optionalText("sub"),accessibleLabel=optionalText("accessibleLabel"),dotColor=optionalText("dotColor"),title=optionalText("title"),group=optionalText("group"),badgeCandidate=source.badge,badge=typeof badgeCandidate=="string"&&badgeCandidate.length<=MAX_SOURCE_FIELD_UNITS||typeof badgeCandidate=="number"&&Number.isFinite(badgeCandidate)?badgeCandidate:void 0,units=value.length+label.length+(sub?.length??0)+(accessibleLabel?.length??0)+(dotColor?.length??0)+(title?.length??0)+(group?.length??0)+(typeof badge=="string"?badge.length:0);if(textUnits+units>MAX_SOURCE_TEXT_UNITS)break;textUnits+=units,rows.push({value,label,...sub===void 0?{}:{sub},...icon===void 0?{}:{icon},...start===void 0?{}:{start},...end===void 0?{}:{end},...badge===void 0?{}:{badge},...accessibleLabel===void 0?{}:{accessibleLabel},...source.data===void 0?{}:{data:source.data},...dotColor===void 0?{}:{dotColor},...title===void 0?{}:{title},...group===void 0?{}:{group},...typeof source.disabled=="boolean"?{disabled:source.disabled}:{}})}catch{}const total=Math.max(providerTotal,candidateRows.length);return{rows,total,truncated:total>rows.length}}class LyraCombobox extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,collapse:LYRA_DEFAULT_collapse,comboboxCreate:LYRA_DEFAULT_comboboxCreate,comboboxLabel:LYRA_DEFAULT_comboboxLabel,comboboxLoadError:LYRA_DEFAULT_comboboxLoadError,comboboxOverflow:LYRA_DEFAULT_comboboxOverflow,comboboxRequired:LYRA_DEFAULT_comboboxRequired,comboboxSelectedOverflow:LYRA_DEFAULT_comboboxSelectedOverflow,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,noData:LYRA_DEFAULT_noData,noMatches:LYRA_DEFAULT_noMatches,notInCatalog:LYRA_DEFAULT_notInCatalog,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,retry:LYRA_DEFAULT_retry,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,tableLoadFailed:LYRA_DEFAULT_tableLoadFailed,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-input","lr-change"])}static{this.identityEventDetailCollectionItems=Object.freeze({"lr-input":Object.freeze(["data"]),"lr-change":Object.freeze(["data"])})}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},readonly:{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},maxRender:{type:Number,attribute:"max-render",noAccessor:!0},sourceDelay:{type:Number,attribute:"source-delay",noAccessor:!0}}}get open(){return this._open}set open(next){const old=this._open,liveDisabled=this.effectiveDisabled||typeof this.matches=="function"&&this.matches(":disabled");if(this._open=!!next&&!this.readonly&&!liveDisabled,this._open===old){next&&!this._open&&this.hasAttribute("open")&&this.removeAttribute("open");return}this.requestUpdate("open",old)}get appearance(){return this._appearance}set appearance(next){const normalized=APPEARANCE.normalizeReflected(this,"appearance",next),old=this._appearance;this._appearance=normalized,normalized!==old&&this.requestUpdate("appearance",old)}get positioningStrategy(){return this._positioningStrategy??"fixed"}set positioningStrategy(next){const normalized=POSITIONING_STRATEGY.normalize(next)??"fixed",old=this.positioningStrategy;this._positioningStrategy=normalized,normalized!==old&&this.requestUpdate("positioningStrategy",old)}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=!!next,this.requestUpdate()}get inputmode(){return this.inputMode}set inputmode(next){this.inputMode=next??""}get enterkeyhint(){return this.enterKeyHint}set enterkeyhint(next){this.enterKeyHint=next??""}get inputValue(){return this.query}set inputValue(next){this.explicitInputValue=!0,this.query=next??"",this.activeIndex=-1,this.source&&this.runSource(this.query),this.requestUpdate()}constructor(){super(),this.placeholder="",this.label="",this.hint="",this.errorText="",this.allowCreate=!1,this.allowCustomValue=!1,this.withUnknownOption=!1,this.loading=!1,this._appearance="outlined",this.placement="bottom",this.topLayer=!1,this.size="m",this.pill=!1,this.clearable=!1,this.withClear=!1,this.withLabel=!1,this.withHint=!1,this.validators=[],this.autocomplete="off",this.inputMode="",this.enterKeyHint="",this.spellcheck=!1,this.autocapitalize="",this.autocorrectValue=!0,this.filter=null,this.source=null,this.query="",this.explicitInputValue=!1,this.activeIndex=-1,this.options=[],this.optionsObserved=!1,this.touched=!1,this.validityRevision=0,this.slotPresence=new SlotPresenceController(this),this.sourceLoading=!1,this.sourceFailed=!1,this.sourceEverSettled=!1,this.asyncRows=[],this._sourceTotal=0,this._sourceTruncated=!1,this.sourceErrorAnnouncements=new AnnouncementSinkController(this,{eager:["assertive"]}),this.sourceDebounce=new DebounceController(0,request=>this.runSourceRequest(request),()=>this.ownerDocument.defaultView),this.sourceToken=0,this.refreshQueued=!1,this._sourceWarmed=!1,this._selectedLabelCache=new Map,this._selectedRowCache=new Map,this._renderedRows=[],this._open=!1,this._fieldsetDisabled=!1,this.listId=nextId("combobox-list"),this.inputId=nextId("combobox-input"),this.listboxPositioned=!1,this.positioningGeneration=0,this.positioningReady=Promise.resolve(!1),this.restoreFocusOnClose=!0,this.restoringOverlayFocus=!1,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._isFirstUpdate=!0,this.openVetoed=!1,this.closeAfterPositioningFailure=!1,this.closeCleanupPending=!1,this._selected=[],this.sourceOptionsByRow=new WeakMap,this._valueDirty=!1,this._multiple=!1,this._disabled=!1,this._required=!1,this._readonly=!1,this._defaultSelected=[],this._defaultCaptured=!1,this._restoredStateActive=!1,this._name="",this._maxOptionsVisible=3,this._maxRender=200,this._sourceDelay=200,this.localDescriptionIds="",this.previousSelection=[],this.markInteracted=()=>{this.touched||(this.touched=!0,this.updateValidity(),this.syncCustomStates())},this.collectOptions=e=>{this.collectOptionsFromSlot(e.target)},this.optionRefreshPending=!1,this.onOptionChange=e=>{e.stopPropagation();const option=e.composedPath().find(isLyraOptionElement);if(isLyraOptionElement(option)&&this.options.includes(option)&&isOptionSelectedWrite(e)){if(this.multiple){const next=option.selected?this._selected.includes(option.value)?this._selected:[...this._selected,option.value]:this._selected.filter(value=>value!==option.value);this.assignValue(next)}else{if(this._valueDirty=!0,this._restoredStateActive=!1,!option.selected&&this.singleSelectedOption!==option)return;this.setValue(option.selected?option.value:[],!0,option.selected?option:void 0)}return}isLyraOptionElement(option)&&this.adornmentClones.get(option)?.markup!==this.adornmentMarkup(option)&&this.adornmentClones.delete(option),!this.optionRefreshPending&&(this.optionRefreshPending=!0,queueMicrotask(()=>{this.optionRefreshPending=!1,this.refreshOptionDefaults(),this.reflectSelected(),this.options=[...this.options],this.normalizeActiveIndex()}))},this.adornmentClones=new WeakMap,this.onDocPointer=e=>{if(!e.composedPath().includes(this)){if(this.overlayHandle?.isActive()){this.overlayHandle.dismissBackdrop();return}this.restoreFocusOnClose=!1,this.hide()}},this.onInput=e=>{this.liveDisabled||this.readonly||(this.explicitInputValue=!1,this.query=e.target.value,this.activeIndex=-1,this.show(),this.source&&this.runSource(this.query),this.emit("lr-filter",{value:this.query}))},this.onInputBlur=event=>{this.liveDisabled||(this.touched=!0),this.syncCustomStates(),this.onComboFocusOut(event),relayNativeEvent(this,event)},this.onComboFocusOut=event=>{const trigger=this.renderRoot.querySelector('[part="combobox"]'),target=event.relatedTarget;target&&typeof target.nodeType=="number"&&trigger?.contains(target)||(this.restoreFocusOnClose=!1,this.hide())},this.onInputFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}this.restoringOverlayFocus||this.show(),relayNativeEvent(this,event)},this.onKeyDown=e=>{if(e.isComposing||e.keyCode===229||this.liveDisabled||this.readonly)return;const navigable=["ArrowDown","ArrowUp","Enter","End"].includes(e.key)?this.renderedRows.rows.filter(r=>!r.disabled):[];switch(e.key){case"ArrowDown":case"ArrowUp":if(e.preventDefault(),!this.open){this.activeIndex=navigable.findIndex(row=>this.committed.includes(row.value)),this.show();return}if(e.key==="ArrowDown"){this.activeIndex=Math.min(navigable.length-1,this.activeIndex+1);break}this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":{const activeRow=navigable[this.activeIndex];if(this.open&&this.activeIndex>=0&&activeRow){e.preventDefault(),this.pickRow(activeRow);break}const create=this.createRow;if(this.open&&create){e.preventDefault(),this.createOption(create.createInput);break}if(this.open&&this.allowCustomValue&&!this.multiple&&this.query.trim()){e.preventDefault(),this.commitCustomValue(this.query.trim());break}submitOnEnter(this,e);break}case"Escape":this.open&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(e.preventDefault(),this.hide());break;case"Home":this.open&&(e.preventDefault(),this.activeIndex=0);break;case"End":this.open&&(e.preventDefault(),this.activeIndex=navigable.length-1);break;case"Backspace":this.multiple&&!this.query&&this._selected.length&&this.removeValueAt(this._selected.length-1);break}},this.onComboMouseDown=e=>{this.liveDisabled||e.composedPath()[0]!==this.inputEl&&(e.target.closest("button")||(e.preventDefault(),this.inputEl?.focus(),this.show()))},this.onListboxMouseDown=e=>{e.preventDefault()},this.onListboxClick=e=>{const optionEl=e.target.closest('[part="option"]'),row=this._renderedRows[Number(optionEl?.dataset.index)];row&&this.pickRow(row)},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)}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}get validationTarget(){return this.validationTargetOverride??this.inputEl??void 0}set validationTarget(next){this.validationTargetOverride=next??void 0,this.validityController.refreshAnchor()}resetValidity(){this.validityController.setCustomValidity(""),this.updateValidity()}get input(){return this.inputEl??null}get selectionStart(){return this.inputEl?.selectionStart??null}set selectionStart(value){this.inputEl&&(this.inputEl.selectionStart=value)}get selectionEnd(){return this.inputEl?.selectionEnd??null}set selectionEnd(value){this.inputEl&&(this.inputEl.selectionEnd=value)}get selectionDirection(){return this.inputEl?.selectionDirection}set selectionDirection(value){this.inputEl&&(this.inputEl.selectionDirection=value)}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}get interactionBarred(){return this.liveDisabled||this.readonly}focus(options){this.liveDisabled||this.inputEl?.focus(options)}blur(){this.inputEl?.blur()}click(){this.liveDisabled||(this.inputEl?.focus(),this.show())}select(){this.inputEl?.select()}setSelectionRange(start,end,direction){this.inputEl?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){const input=this.inputEl;input&&(setNativeRangeText(input,replacement,start,end,selectMode),this.explicitInputValue=!0,this.query=input.value,this.activeIndex=-1,this.source&&this.runSource(this.query))}[VALIDITY_ANCHOR](){return this.validationTarget}syncExternalDescription(){if(!this.isConnected)return;const target=this.renderRoot.querySelector('[part="combobox-input"]');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.syncValidatorAttributeObserver(),this.hasUpdated&&queueMicrotask(()=>{this.open?this.reconnectOpenPopup():this.source&&this._selected.length&&this.asyncRows.length===0&&this.runSource("")})}adoptedCallback(){super.adoptedCallback(),this.popupController.cancel(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription(),this.listboxPositioned=!1,this.invalidateListboxPositioning(),this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.popupController.unbindPointer(),this.clearSourceTimer(),this.sourceToken+=1,this.sourceAbort?.abort(),this.sourceAbort=void 0,this.sourceErrorAnnouncements.adopted()}willUpdate(changed){super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,this.announceOpenTransition(changed),this.open?(this.listboxHidden=!1,this.listboxRendered=!0):changed.has("open")&&this.interactionBarred&&(this.listboxHidden=!0),changed.has("open")&&!this.openVetoed&&(this.listboxPositioned=!1),changed.has("open")&&this.openVetoed?this.closeCleanupPending=!1:changed.has("open")&&!this.open&&this.finalizeCloseState(),changed.has("source")&&(this.clearSourceTimer(),this.sourceAbort?.abort(),this.sourceAbort=void 0,this.sourceToken++,this.sourceLoading=!1,this.sourceFailed=!1,this.sourceEverSettled=!1,this.asyncRows=[],this._sourceTotal=0,this._sourceTruncated=!1,this.activeIndex=-1,this._sourceWarmed=!1,this.source&&this.open&&this.runSource(this.query)),!this._sourceWarmed&&this.source&&(this._selected.length>0||(this.pendingSelectedRowValues?.length??0)>0)&&this.asyncRows.length===0&&(this._sourceWarmed=!0,this.runSource(""))}firstUpdated(changed){super.firstUpdated(changed);const slot=this.optionsSlot;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>{this.optionsObserved=!0,s.assignedElements({flatten:!0}).some(isLyraOptionElement)&&this.collectOptionsFromSlot(s)})})}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){const old=this._multiple;this._multiple=!!next,this.toggleAttribute("multiple",this._multiple),this.reflectSelected(),this.syncFormValue(),this.requestUpdate("multiple",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this._disabled&&this.hide(),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 readonly(){return this._readonly}set readonly(next){const old=this._readonly;this._readonly=!!next,this.toggleAttribute("readonly",this._readonly),this._readonly&&this.hide(),this.updateValidity(),this.requestUpdate("readonly",old)}get value(){return this.multiple?[...this._selected]:this._selected[0]??""}set value(next){this.setValue(next,!0)}setValue(next,dirty,preferred){const old=this._selected;this.previousSelection=old,this.singleSelectedOption=preferred,dirty&&(this._restoredStateActive=!1,this._valueDirty=!0),this._selected=normalizeSelectionValues(next);const selected=new Set(this._selected);if(selected.size>0){const rows=this.rowsByValue();for(const value of selected){const row=rows.get(value);row&&this._selectedRowCache.set(value,row)}}for(const value of this._selectedRowCache.keys())selected.has(value)||this._selectedRowCache.delete(value);for(const value of this._selectedLabelCache.keys())selected.has(value)||this._selectedLabelCache.delete(value);this.syncFormValue(),this.reflectSelected(),this.updateValidity(),this.requestUpdate("value",old)}get maxOptionsVisible(){return this._maxOptionsVisible}set maxOptionsVisible(next){const old=this._maxOptionsVisible;this._maxOptionsVisible=finiteCount(next,3),this.requestUpdate("maxOptionsVisible",old)}get maxRender(){return this._maxRender}get sourceDelay(){return this._sourceDelay}set sourceDelay(next){const old=this._sourceDelay;this._sourceDelay=finiteDuration(next,200),this.requestUpdate("sourceDelay",old)}set maxRender(next){const old=this._maxRender;this._maxRender=Math.min(finiteCount(next,200),MAX_RENDER_ROWS),this.requestUpdate("maxRender",old)}get sourceTotal(){return this._sourceTotal}get sourceTruncated(){return this._sourceTruncated}get selectedRows(){return this.resolveSelectedRowSlots().filter(row=>row!=null).map(row=>({...row}))}resolveSelectedRowSlots(){let rows;return this.committed.map(value=>this._selectedRowCache.get(value)??(rows??=this.rowsByValue()).get(value))}get committed(){return this.multiple?this._selected:this._selected.slice(0,1)}rowsByValue(){const rows=new Map;for(const row of[...this.effectiveRows,...this.asyncRows])rows.has(row.value)||rows.set(row.value,row);return rows}set selectedRows(next){const values=[],seen=new Set;if(Array.isArray(next))for(const candidate of next){let value;try{value=candidate?.value}catch{continue}typeof value!="string"||seen.has(value)||(seen.add(value),values.push(value))}if(values.length>0&&this.selectionSourceRows.length===0){this.pendingSelectedRowValues=values,this.source&&this.isConnected&&(this._sourceWarmed=!0,this.runSource(""));return}this.pendingSelectedRowValues=void 0,this.applySelectedRowValues(values)}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}validatorResult(){const self=this,current=self.value;for(const validator of Array.isArray(this.validators)?this.validators:[]){let result;try{if(typeof validator=="object"&&validator!==null&&"checkValidity"in validator){const checked=validator.checkValidity(this);if(checked?.isValid===!0)continue;const flags={};for(const key of Array.isArray(checked?.invalidKeys)?checked.invalidKeys:[])isValidityFlagKey(key)&&(flags[key]=!0);Object.values(flags).some(Boolean)||(flags.customError=!0);let message=typeof checked?.message=="string"?checked.message:"";return!message&&typeof validator.message=="string"&&(message=validator.message),!message&&typeof validator.message=="function"&&(message=validator.message(this)),{flags,message:message||this.localize("valueInvalid")}}result=typeof validator=="function"?validator(current,self):validator?.validate(current,self)}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}if(!(result===void 0||result===!0)){if(typeof result=="string")return{flags:{customError:!0},message:result};if(result===!1)return{flags:{customError:!0},message:this.localize("valueInvalid")};if(result&&typeof result=="object"&&Object.values(result).some(Boolean))return{flags:result,message:this.localize("valueInvalid")}}}return{}}syncValidatorAttributeObserver(){this.disconnectValidatorAttributeObserver();const owner=this.ownerDocument.defaultView,MutationObserverCtor=owner?.MutationObserver;if(!this.isConnected||!owner||typeof MutationObserverCtor!="function")return;const attributes=new Set;for(const validator of Array.isArray(this.validators)?this.validators:[]){if(typeof validator!="object"||validator===null||!("checkValidity"in validator))continue;let observed;try{observed=validator.observedAttributes}catch{continue}if(Array.isArray(observed))for(const name of observed)typeof name=="string"&&name.length>0&&attributes.add(name)}if(attributes.size===0)return;const binding={},observer=new MutationObserverCtor(()=>{this.validatorAttributeObserver!==binding||!this.isConnected||this.ownerDocument.defaultView!==owner||(this.updateValidity(),this.validityRevision++)});binding.observer=observer,binding.owner=owner;try{observer.observe(this,{attributes:!0,attributeFilter:[...attributes]}),this.validatorAttributeObserver=binding}catch{observer.disconnect()}}disconnectValidatorAttributeObserver(){const binding=this.validatorAttributeObserver;this.validatorAttributeObserver=void 0,binding?.observer.disconnect()}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({}),this.syncCustomStates();return}const flags={};let message="";this.required&&this._selected.length===0&&(flags.valueMissing=!0,message=this.localize("comboboxRequired"));const configured=this.validatorResult();configured.flags&&Object.assign(flags,configured.flags),configured.message&&(message=configured.message),this.validityController.setValidity(flags,message),this.syncCustomStates()}syncCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",this._selected.length===0),setCustomState(this.internals,"disabled",this.effectiveDisabled)}syncFormValue(){const state2=JSON.stringify(this._selected);if(this.multiple){if(!this.name){this.internals.setFormValue(null,state2);return}const fd=new FormData;for(const v of this._selected)fd.append(this.name,v);this.internals.setFormValue(fd,state2)}else this.internals.setFormValue(this._selected[0]??"",state2)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formResetCallback(){this.touched=!1,this._restoredStateActive=!1,this._valueDirty=!1;const resetValues=this._defaultSelected.length>0?this._defaultSelected:this.options.filter(option=>wasOptionInitiallySelected(option)).map(option=>option.value);this._defaultSelected.length===0&&resetValues.length>0&&(this._defaultSelected=[...resetValues]);const defaults=new Set(resetValues);for(const option of this.options)option[RESET_OPTION_SELECTED_FROM_OWNER](defaults.has(option.value));this.setValue(this.multiple?[...resetValues]:resetValues.slice(0,1),!1),this.query="",this.explicitInputValue=!1}formStateRestoreCallback(state2,reason){let selected=[];if(typeof state2=="string")try{const parsed=JSON.parse(state2);Array.isArray(parsed)&&parsed.every(value=>typeof value=="string")&&(selected=parsed)}catch{}this.assignValue(this.multiple?selected:selected.slice(0,1)),this._restoredStateActive=!0}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(disabled&&this.hide(),this.updateValidity(),this.requestUpdate())}checkValidity(){return this.validityController.checkValidity(()=>this.updateValidity())}reportValidity(){return this.validityController.syncConstraints(),this.touched=!0,this.updateValidity(),this.syncCustomStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncCustomStates()}disconnectedCallback(){this.listboxHidden=!0,this.releaseExternalDescription(),this.popupController.cancel(),this.listboxPositioned=!1,this.disconnectValidatorAttributeObserver(),super.disconnectedCallback(),this.invalidateListboxPositioning(),this.clearSourceTimer(),this.sourceToken+=1,this.sourceAbort?.abort(),this.sourceAbort=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.popupController.unbindPointer(),this.open=!1}collectOptionsFromSlot(slot){const previous=new Set(this.options);if(this.optionsObserved=!0,this.options=slot.assignedElements({flatten:!0}).filter(isLyraOptionElement),this.adornmentClones=new WeakMap,this.normalizeActiveIndex(),this.applyPendingSelectedRows(),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){const values=eligible.map(option=>option.value),next=this.multiple?[...new Set([...this._selected,...values])]:values[values.length-1];newLive.length>0?this.assignValue(next):this.setValue(next,!1);return}}else{this._defaultCaptured=!0;const allDefaults=this.options.filter(option=>option.defaultSelected).map(option=>option.value),allLive=this.options.filter(option=>option.selected).map(option=>option.value),defaults=this.multiple?allDefaults:allDefaults.slice(0,1),live=this.multiple?allLive:allLive.slice(0,1),initialLive=this.options.filter(option=>wasOptionInitiallySelected(option)).map(option=>option.value),optionDirty=this.options.some(option=>isOptionSelectedDirty(option)),dirtyValues=this.options.filter(option=>isOptionSelectedDirty(option)&&option.selected).map(option=>option.value);this._defaultSelected=[...defaults.length>0?defaults:initialLive.length>0?initialLive:live];const fromDefaults=defaults.length>0,initial=optionDirty?this.multiple?allLive:dirtyValues.slice(-1)[0]?dirtyValues.slice(-1):live:fromDefaults?defaults:live;if(initial.length&&!this._restoredStateActive&&!this._valueDirty){const next=this.multiple?initial:initial[0];fromDefaults&&!optionDirty?this.setValue(next,!1):this.assignValue(next);return}optionDirty&&(this._valueDirty=!0)}this.reflectSelected()}refreshOptionDefaults(){const declared=this.options.filter(option=>option.defaultSelected).map(option=>option.value);this._defaultSelected=this.multiple?declared:declared.slice(0,1),!this._valueDirty&&!this._restoredStateActive&&this.setValue([...this._defaultSelected],!1)}reflectSelected(){const value=this._selected[0];(!this.singleSelectedOption||!this.options.includes(this.singleSelectedOption)||this.singleSelectedOption.value!==value)&&(this.singleSelectedOption=this.options.find(option=>option.value===value));const selected=new Set(this._selected);for(const option of this.options)option[SET_OPTION_SELECTED_FROM_OWNER](this.multiple?selected.has(option.value):option===this.singleSelectedOption)}labelFor(value){const nonBlank=label=>label!==void 0&&label.trim().length>0?label:void 0;if(this.getUnknownLabel&&this.isUnknownValue(value)){const override=nonBlank(this.getUnknownLabel(value));if(override!==void 0)return override}return(!this.source&&!this.multiple&&this.singleSelectedOption?.value===value?nonBlank(this.singleSelectedOption.label):void 0)??nonBlank(this._selectedLabelCache.get(value))??nonBlank(this.options.find(o=>o.value===value)?.label)??nonBlank(this.asyncRows.find(r=>r.value===value)?.label)??(this.loading||this.source&&!this.sourceEverSettled?this.statusText("loading",this.loadingText):void 0)??value}isUnknownValue(value){return!this.source&&!this.optionsObserved||this.loading||this.source&&!this.sourceEverSettled?!1:!(!this.source&&!this.multiple&&this.singleSelectedOption?.value===value||this._selectedLabelCache.has(value)||this.options.some(option=>option.value===value)||this.asyncRows.some(row=>row.value===value))}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}rowForOption(option){const adornments=this.adornmentsFor(option),row={value:option.value,label:option.label||option.value,sub:option.sub||void 0,dotColor:option.dotColor||void 0,title:option.title||void 0,group:option.group||void 0,disabled:option.disabled||option.inert||option.closest("[inert]")!==null,data:option.data,...adornments.start===void 0?{}:{start:adornments.start},...adornments.end===void 0?{}:{end:adornments.end}};return this.sourceOptionsByRow.set(row,option),row}get selectionSourceRows(){return this.source?this.asyncRows:this.options.map(option=>this.rowForOption(option))}applySelectedRowValues(values){const rowsByValue=new Map;for(const row of this.selectionSourceRows)rowsByValue.has(row.value)||rowsByValue.set(row.value,row);const rows=values.map(value=>rowsByValue.get(value)).filter(row=>row!==void 0),limited=this.multiple?rows:rows.slice(0,1);this.assignValue(limited.map(row=>row.value));for(const row of limited)this._selectedRowCache.set(row.value,row)}applyPendingSelectedRows(acceptEmptySource=!1){if(this.pendingSelectedRowValues===void 0||!acceptEmptySource&&this.selectionSourceRows.length===0)return!1;const values=this.pendingSelectedRowValues;return this.pendingSelectedRowValues=void 0,this.applySelectedRowValues(values),!0}get effectiveRows(){return this.source?this.asyncRows:this.filtered.map(option=>this.rowForOption(option))}get unknownRows(){if(!this.withUnknownOption)return[];const locale=this.effectiveLocale,query2=this.query.trim().toLocaleLowerCase(locale);return this.committed.filter(value=>this.isUnknownValue(value)).map(value=>({value,label:this.labelFor(value),badge:this.localize("notInCatalog"),unknownValue:value})).filter(row=>!query2||row.label.toLocaleLowerCase(locale).includes(query2)||row.value.toLocaleLowerCase(locale).includes(query2))}get createRow(){if(!this.allowCreate)return;const inputValue=this.query.trim();if(!inputValue)return;const locale=this.effectiveLocale,folded=inputValue.toLocaleLowerCase(locale);if(!(this.source?this.asyncRows:this.options.map(option=>({value:option.value,label:option.label}))).some(row=>row.value.toLocaleLowerCase(locale)===folded||row.label.toLocaleLowerCase(locale)===folded))return{value:inputValue,label:this.localize("comboboxCreate",void 0,{value:inputValue}),createInput:inputValue}}get renderedRows(){const all=this.effectiveRows,create=this.createRow,sourceOverflow=this.source?Math.max(0,this._sourceTotal-all.length):0,unknown=this.unknownRows;if(all.length<=this.maxRender)return{rows:[...all,...unknown,...create?[create]:[]],overflow:sourceOverflow};const originalIndex=new Map(all.map((r,i)=>[r,i])),capped=all.slice(0,this.maxRender),cappedValues=new Set(capped.map(r=>r.value));let appendedOutOfCap=!1;for(const v of this.committed)if(!cappedValues.has(v)){const selectedRow=all.find(r=>r.value===v);selectedRow&&(capped.push(selectedRow),appendedOutOfCap=!0)}return appendedOutOfCap&&capped.sort((a,b)=>originalIndex.get(a)-originalIndex.get(b)),capped.push(...unknown),create&&capped.push(create),{rows:capped,overflow:all.length-capped.length+unknown.length+(create?1:0)+sourceOverflow}}normalizeActiveIndex(){if(this.activeIndex<0)return;const navigableCount=this.renderedRows.rows.filter(row=>!row.disabled).length,next=navigableCount>0?Math.min(this.activeIndex,navigableCount-1):-1;next!==this.activeIndex&&(this.activeIndex=next)}get filtered(){const locale=this.effectiveLocale,q=this.query.trim().toLocaleLowerCase(locale),selectedLabel=this.multiple?"":this.labelFor(this._selected[0]??"")??"",effective=q&&q===selectedLabel.toLocaleLowerCase(locale)?"":q;if(!effective)return this.options;const fn=this.filter??((o,query2)=>o.label.toLocaleLowerCase(locale).includes(query2)||o.searchText.toLocaleLowerCase(locale).includes(query2));return this.options.filter(o=>fn(o,effective))}get displayValue(){return this.multiple||this.open||this.explicitInputValue?this.query:this._selected[0]?this.labelFor(this._selected[0]):""}announceOpenTransition(changed){this.openVetoed=!1;const closeAfterPositioningFailure=!this.open&&this.closeAfterPositioningFailure;if(this.closeAfterPositioningFailure=!1,!(!changed.has("open")||this._isFirstUpdate||!this.open&&this.interactionBarred)){if(!this.isConnected||closeAfterPositioningFailure){emitPopupEvent(this,"lr-hide",!1);return}this.openVetoed=this.popupController.announce(this.open,()=>{this.open=!this.open})}}show(){if(this.open||this.interactionBarred)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.closeCleanupPending=!0,this.open=!1,settled}finalizeCloseState(){if(this.closeCleanupPending&&(this.closeCleanupPending=!1,this.activeIndex=-1,!this.multiple)){const queryChanged=this.query!=="";this.query="",this.explicitInputValue=!1,queryChanged&&this.source&&(this.asyncRows=[],this.sourceFailed=!1,this._sourceTotal=0,this._sourceTruncated=!1)}}activateListboxOverlay(){this.invalidateListboxPositioning(),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.inputEl??null}),this.popupController.bindPointer(),this.beginListboxPositioning()}beginListboxPositioning(){const anchor=this.renderRoot.querySelector('[part="combobox"]'),listbox=this.renderRoot.querySelector('[part="listbox"]');if(anchor&&listbox){const generation=this.positioningGeneration;this.positioningReady=new Promise(resolve=>{this.resolvePositioningReady=resolve}),this.startListboxPositioning(generation,anchor,listbox)}}invalidateListboxPositioning(){this.positioningGeneration++,this.cleanup?.(),this.cleanup=void 0,this.resolvePositioningReady?.(!1),this.resolvePositioningReady=void 0}resolveCurrentPositioning(positioned){const resolve=this.resolvePositioningReady;this.resolvePositioningReady=void 0,resolve?.(positioned)}async startListboxPositioning(generation,anchor,listbox){try{const runtime=await loadAnchoredOverlayRuntime(),{place}=runtime;if(generation!==this.positioningGeneration||!this.open||!this.isConnected||this.renderRoot.querySelector('[part="combobox"]')!==anchor||this.renderRoot.querySelector('[part="listbox"]')!==listbox)return;this.placedTopLayer=syncTopLayerRelease(listbox,this.placedTopLayer,this.topLayer,runtime);const cleanup=place(anchor,listbox,{placement:`${this.placement}-start`,...topLayerPlacement(this.topLayer,resolveEffectivePositioningStrategy(this,this._positioningStrategy,"fixed")),sync:this.sync,onPlaced:()=>{generation===this.positioningGeneration&&(this.listboxPositioned=!0,this.updateComplete.then(()=>{generation!==this.positioningGeneration||!this.open||this.resolveCurrentPositioning(!0)}))}});generation!==this.positioningGeneration?cleanup():this.cleanup=cleanup}catch{if(generation!==this.positioningGeneration||!this.open)return;this.resolveCurrentPositioning(!1),this.closeAfterPositioningFailure=!0,this.hide()}}teardownListboxOverlay(restoreFocus=this.restoreFocusOnClose){this.invalidateListboxPositioning(),this.restoringOverlayFocus=restoreFocus;try{this.overlayHandle?.deactivate({restoreFocus})}finally{this.restoringOverlayFocus=!1}this.overlayHandle=void 0,this.popupController.unbindPointer(),this.restoreFocusOnClose=!0}reconnectOpenPopup(){!this.isConnected||!this.open||(this.activateListboxOverlay(),this.source&&this.asyncRows.length===0&&this.runSource(this.query))}syncVisibleOptionsCap(){const listbox=this.renderRoot?.querySelector('[part="listbox"]');if(!listbox)return;const clear=()=>{listbox.style.removeProperty("max-block-size")},requested=typeof this.visibleOptions=="number"?finiteCount(this.visibleOptions,0):0;if(requested<=0)return clear();const rows=listbox.querySelectorAll('[part="option"]');if(rows.length<=requested)return clear();const boundary=rows[requested];if(!boundary)return clear();const cap=boundary.getBoundingClientRect().top-listbox.getBoundingClientRect().top;if(!Number.isFinite(cap)||cap<=0)return clear();listbox.style.setProperty("max-block-size",`min(${Math.ceil(cap)}px, var(--lr-positioner-available-block-size, var(--lr-size-18rem)))`)}updated(changed){if(super.updated(changed),this.syncExternalDescription(),this.syncVisibleOptionsCap(),changed.has("open")&&!this.openVetoed?this.open&&this.isConnected?(this.activateListboxOverlay(),this._isFirstUpdate||this.settleTransition("lr-after-show"),this.refreshQueued?(this.refreshQueued=!1,this.runSource(this.query)):this.source&&this.asyncRows.length===0&&this.runSource(this.query)):this.open?this.teardownListboxOverlay(!1):(this.teardownListboxOverlay(),this.interactionBarred?this.popupController.cancel():this._isFirstUpdate||this.settleTransition("lr-after-hide")):changed.has("open")&&this.openVetoed&&(this.restoreFocusOnClose=!0),changed.has("topLayer")&&!changed.has("open")&&this.open&&this.isConnected&&(this.invalidateListboxPositioning(),this.beginListboxPositioning()),changed.has("name")&&this.syncFormValue(),changed.has("validators")&&(this.updateValidity(),this.syncValidatorAttributeObserver()),(changed.has("touched")||changed.has("required")||changed.has("value")||changed.has("validators")||changed.has("validityRevision"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),changed.has("activeIndex")||changed.has("listboxPositioned")){const listbox=this.renderRoot.querySelector('[part="listbox"]'),row=listbox?.querySelector('[part="option"][data-active]');listbox&&row&&revealRow(listbox,row)}}settleTransition(event){return this.popupController.settle(event,{waitForPosition:async stale=>{for(;this.open&&!this.listboxPositioned;){const readiness=this.positioningReady,positioned=await readiness;if(stale())return!1;if(positioned)break;if(readiness===this.positioningReady)return!1}return!0},conceal:()=>{this.listboxHidden=!0}})}emitValueEvents(){const self=this,data=this.resolveSelectedRowSlots().map(row=>row?.data),previousValue=this.multiple?[...this.previousSelection]:this.previousSelection[0]??"",detail={value:self.value,previousValue,data};emitValueEvents(self,"input",detail,detail2=>self.emit("lr-input",detail2)),emitValueEvents(self,"change",detail,detail2=>self.emit("lr-change",detail2))}assignValue(next){this.value=next}createOption(inputValue){if(this.liveDisabled||this.readonly||this.emit("lr-create",{inputValue},{cancelable:!0}).defaultPrevented)return;const option=this.ownerDocument.createElement(tag("option"));option.setAttribute("value",inputValue),option.textContent=inputValue,this.append(option),this.pickRow({value:inputValue,label:inputValue})}commitCustomValue(inputValue){if(this.liveDisabled||this.readonly||this.multiple||!inputValue)return;const selectionChanged=this._selected[0]!==inputValue;this.touched=!0,this._selectedLabelCache.set(inputValue,inputValue),this.assignValue(inputValue),this.query="",this.explicitInputValue=!1,this.hide(),selectionChanged&&this.emitValueEvents()}pickRow(row){const sourceOption=this.sourceOptionsByRow.get(row);if(this.liveDisabled||this.readonly||row.disabled||sourceOption&&(sourceOption.disabled||sourceOption.closest("[inert]")))return;if(row.createInput!==void 0){this.createOption(row.createInput);return}this.touched=!0;const synthetic=row.unknownValue!==void 0,selectionChanged=this.multiple||this._selected[0]!==row.value;if(this.multiple){const set=new Set(this._selected);set.has(row.value)?(set.delete(row.value),this._selectedRowCache.delete(row.value)):(set.add(row.value),synthetic||(this._selectedLabelCache.set(row.value,row.label),this._selectedRowCache.set(row.value,row))),this.assignValue([...set]),this.query="",this.explicitInputValue=!1}else synthetic||(this._selectedLabelCache.set(row.value,row.label),this._selectedRowCache.clear(),this._selectedRowCache.set(row.value,row)),this.setValue(row.value,!0,sourceOption),this.query="",this.explicitInputValue=!1,this.hide();this.source&&this.runSource(this.query),selectionChanged&&this.emitValueEvents(),this.emit("lr-activate",{value:row.value})}removeValueAt(index){if(this.liveDisabled||this.readonly||index<0||index>=this._selected.length)return;const next=this._selected.filter((_,i)=>i!==index);this.touched=!0,this.assignValue(next),this.emitValueEvents()}clear(){if(this.liveDisabled||this.readonly)return;const hadSelection=this._selected.length>0,queryChanged=this.query!=="";!hadSelection&&!queryChanged||(hadSelection&&(this.touched=!0,this.assignValue([])),this.query="",this.explicitInputValue=!1,this.source&&this.runSource(this.query),hadSelection&&(this.emitValueEvents(),this.emit("lr-clear")),queryChanged&&this.emit("lr-filter",{value:this.query}))}refresh(){if(this.source){if(!this.open){this.refreshQueued=!0;return}this.refreshQueued=!1,this.runSource(this.query,{immediate:!0})}}runSource(query2,options){const source=this.source;if(!source)return;this.clearSourceTimer(),this.sourceAbort?.abort(),this.sourceAbort=void 0;const token=++this.sourceToken,ownerWindow=this.ownerDocument.defaultView;if(!this.isConnected||!ownerWindow)return;const request={query:query2,token,owner:ownerWindow,source};if(options?.immediate){this.runSourceRequest(request);return}this.sourceDebounce.delayMs=this._sourceDelay,this.sourceDebounce.push(request)}runSourceRequest({query:query2,token,owner:ownerWindow,source}){if(token!==this.sourceToken||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow)return;const controller=new ownerWindow.AbortController;this.sourceAbort=controller,this.sourceLoading=!0,this.sourceFailed=!1,Promise.resolve().then(()=>source(query2,{signal:controller.signal,limit:MAX_SOURCE_ROWS})).then(result=>{if(token!==this.sourceToken||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow)return;const normalized=normalizeSourceResult(result);this._sourceTotal=normalized.total,this._sourceTruncated=normalized.truncated,this.asyncRows=normalized.rows,this.sourceFailed=!1,this.sourceEverSettled=!0,this.normalizeActiveIndex(),this.applyPendingSelectedRows(!0);const selected=new Set(this._selected);for(const row of normalized.rows)selected.has(row.value)&&this._selectedRowCache.set(row.value,row)}).catch(err=>{token!==this.sourceToken||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow||typeof err=="object"&&err!==null&&"name"in err&&err.name==="AbortError"||(this.asyncRows=[],this._sourceTotal=0,this._sourceTruncated=!1,this.activeIndex=-1,this.sourceFailed=!0,this.sourceEverSettled=!0,this.sourceErrorAnnouncements.announceAssertive(this.localize("comboboxLoadError")),this.emit("lr-source-error",{error:err,query:query2}),console.warn("<lr-combobox> source() rejected:",err))}).finally(()=>{token===this.sourceToken&&(this.sourceLoading=!1)})}clearSourceTimer(){this.sourceDebounce.cancel()}renderRows(rows,activeId){const out=[];let currentGroup,currentGroupRows=[],groupIndex=0;const selectedSet=new Set(this.committed),flushGroup=()=>{if(currentGroupRows.length){if(currentGroup){const labelId=`${this.listId}-group-${groupIndex++}`;out.push(html`<div role="group" aria-labelledby=${labelId}>
|
|
1
|
+
import{__decorate}from"tslib";import{emitValueEvents}from"../../../internal/value-events.js";import{setNativeRangeText,nativeAutocorrectAttribute}from"../../../internal/native-text-control.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{loadAnchoredOverlayRuntime,syncTopLayerRelease,topLayerPlacement}from"../../../internal/anchored-overlay-runtime.js";import{hostAriaLabel,nextId,srOnly}from"../../../internal/a11y.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{submitOnEnter}from"../../../internal/submit-on-enter.js";import{finiteCount,finiteDuration}from"../../../internal/numbers.js";import{PopupController,emitPopupEvent}from"../../../internal/popup-controller.js";import{revealRow}from"../../../internal/reveal-row.js";import{DebounceController}from"../../../internal/debounce-controller.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./combobox.styles.js";import{autocorrectConverter,literalSetConverter,omittedEmptyStringConverter,optionalLiteralSetConverter,spellcheckConverter}from"../../../internal/converters.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{tag}from"../../../internal/prefix.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{renderDataState}from"../../../internal/data-state-renderer.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.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{relayNativeEvent}from"../../../internal/native-event-relay.js";import{LYRA_DEFAULT_comboboxCreate,LYRA_DEFAULT_comboboxLabel,LYRA_DEFAULT_comboboxLoadError,LYRA_DEFAULT_comboboxOverflow,LYRA_DEFAULT_comboboxRequired,LYRA_DEFAULT_comboboxSelectedOverflow}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noData,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_notInCatalog,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_retry,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_tableLoadFailed,LYRA_DEFAULT_valueInvalid}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"]),APPEARANCE=literalSetConverter(["accent","filled","outlined","filled-outlined","plain"],"outlined"),VALIDITY_FLAG_KEYS=new Set(["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"]),comboboxSpellcheckConverter={...spellcheckConverter,fromAttribute:(value,type)=>value===null?void 0:spellcheckConverter.fromAttribute?.(value,type)};function adornmentContent(value){return typeof value=="string"||typeof value=="number"?html`<span>${value}</span>`:value}function isValidityFlagKey(value){return typeof value=="string"&&VALIDITY_FLAG_KEYS.has(value)}const MAX_SOURCE_ROWS=2e3,MAX_SOURCE_TEXT_UNITS=25e4,MAX_SOURCE_FIELD_UNITS=4096,MAX_RENDER_ROWS=1e3;function isRenderable(value,nested=!1){if(typeof value=="string"||typeof value=="number")return!0;if(typeof value!="object"||value===null)return!1;if(Array.isArray(value))return!nested&&value.every(item=>isRenderable(item,!0));const{nodeType,cloneNode,strings}=value;return typeof nodeType=="number"&&typeof cloneNode=="function"||Array.isArray(strings)&&Object.hasOwn(strings,"raw")}function normalizeSourceResult(input){let candidateRows,candidateTotal;try{Array.isArray(input)?candidateRows=input:typeof input=="object"&&input!==null&&(candidateRows=input.rows,candidateTotal=input.total)}catch{throw new TypeError("Invalid combobox source result")}if(!Array.isArray(candidateRows))throw new TypeError("Invalid combobox source result");const providerTotal=typeof candidateTotal=="number"&&Number.isFinite(candidateTotal)&&candidateTotal>=0?Math.trunc(candidateTotal):candidateRows.length,rows=[];let textUnits=0;const limit=Math.min(candidateRows.length,MAX_SOURCE_ROWS);for(let index=0;index<limit;index++)try{const value=candidateRows[index]?.value,label=candidateRows[index]?.label;if(typeof value!="string"||typeof label!="string"||value.length>MAX_SOURCE_FIELD_UNITS||label.length>MAX_SOURCE_FIELD_UNITS)continue;const source=candidateRows[index],optionalText=key=>{const candidate=source[key];return typeof candidate=="string"&&candidate.length<=MAX_SOURCE_FIELD_UNITS?candidate:void 0},content=key=>{const candidate=source[key];return isRenderable(candidate)?candidate:void 0},icon=content("icon"),start=content("start"),end=content("end"),sub=optionalText("sub"),accessibleLabel=optionalText("accessibleLabel"),dotColor=optionalText("dotColor"),title=optionalText("title"),group=optionalText("group"),badgeCandidate=source.badge,badge=typeof badgeCandidate=="string"&&badgeCandidate.length<=MAX_SOURCE_FIELD_UNITS||typeof badgeCandidate=="number"&&Number.isFinite(badgeCandidate)?badgeCandidate:void 0,units=value.length+label.length+(sub?.length??0)+(accessibleLabel?.length??0)+(dotColor?.length??0)+(title?.length??0)+(group?.length??0)+(typeof badge=="string"?badge.length:0);if(textUnits+units>MAX_SOURCE_TEXT_UNITS)break;textUnits+=units,rows.push({value,label,...sub===void 0?{}:{sub},...icon===void 0?{}:{icon},...start===void 0?{}:{start},...end===void 0?{}:{end},...badge===void 0?{}:{badge},...accessibleLabel===void 0?{}:{accessibleLabel},...source.data===void 0?{}:{data:source.data},...dotColor===void 0?{}:{dotColor},...title===void 0?{}:{title},...group===void 0?{}:{group},...typeof source.disabled=="boolean"?{disabled:source.disabled}:{}})}catch{}const total=Math.max(providerTotal,candidateRows.length);return{rows,total,truncated:total>rows.length}}class LyraCombobox extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,collapse:LYRA_DEFAULT_collapse,comboboxCreate:LYRA_DEFAULT_comboboxCreate,comboboxLabel:LYRA_DEFAULT_comboboxLabel,comboboxLoadError:LYRA_DEFAULT_comboboxLoadError,comboboxOverflow:LYRA_DEFAULT_comboboxOverflow,comboboxRequired:LYRA_DEFAULT_comboboxRequired,comboboxSelectedOverflow:LYRA_DEFAULT_comboboxSelectedOverflow,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,noData:LYRA_DEFAULT_noData,noMatches:LYRA_DEFAULT_noMatches,notInCatalog:LYRA_DEFAULT_notInCatalog,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,retry:LYRA_DEFAULT_retry,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,tableLoadFailed:LYRA_DEFAULT_tableLoadFailed,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-input","lr-change"])}static{this.identityEventDetailCollectionItems=Object.freeze({"lr-input":Object.freeze(["data"]),"lr-change":Object.freeze(["data"])})}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},readonly:{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},maxRender:{type:Number,attribute:"max-render",noAccessor:!0},sourceDelay:{type:Number,attribute:"source-delay",noAccessor:!0}}}get open(){return this._open}set open(next){const old=this._open,liveDisabled=this.effectiveDisabled||typeof this.matches=="function"&&this.matches(":disabled");if(this._open=!!next&&!this.readonly&&!liveDisabled,this._open===old){next&&!this._open&&this.hasAttribute("open")&&this.removeAttribute("open");return}this.requestUpdate("open",old)}get appearance(){return this._appearance}set appearance(next){const normalized=APPEARANCE.normalizeReflected(this,"appearance",next),old=this._appearance;this._appearance=normalized,normalized!==old&&this.requestUpdate("appearance",old)}get positioningStrategy(){return this._positioningStrategy??"fixed"}set positioningStrategy(next){const normalized=POSITIONING_STRATEGY.normalize(next)??"fixed",old=this.positioningStrategy;this._positioningStrategy=normalized,normalized!==old&&this.requestUpdate("positioningStrategy",old)}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=!!next,this.requestUpdate()}get inputmode(){return this.inputMode}set inputmode(next){this.inputMode=next??""}get enterkeyhint(){return this.enterKeyHint}set enterkeyhint(next){this.enterKeyHint=next??""}get inputValue(){return this.query}set inputValue(next){this.explicitInputValue=!0,this.query=next??"",this.activeIndex=-1,this.source&&this.runSource(this.query),this.requestUpdate()}constructor(){super(),this.placeholder="",this.label="",this.hint="",this.errorText="",this.allowCreate=!1,this.allowCustomValue=!1,this.withUnknownOption=!1,this.loading=!1,this._appearance="outlined",this.placement="bottom",this.topLayer=!1,this.size="m",this.pill=!1,this.clearable=!1,this.withClear=!1,this.withLabel=!1,this.withHint=!1,this.validators=[],this.autocomplete="off",this.inputMode="",this.enterKeyHint="",this.spellcheck=!1,this.autocapitalize="",this.autocorrectValue=!0,this.filter=null,this.source=null,this.query="",this.explicitInputValue=!1,this.activeIndex=-1,this.options=[],this.optionsObserved=!1,this.touched=!1,this.validityRevision=0,this.slotPresence=new SlotPresenceController(this),this.sourceLoading=!1,this.sourceFailed=!1,this.sourceEverSettled=!1,this.asyncRows=[],this._sourceTotal=0,this._sourceTruncated=!1,this.sourceErrorAnnouncements=new AnnouncementSinkController(this,{eager:["assertive"]}),this.sourceDebounce=new DebounceController(0,request=>this.runSourceRequest(request),()=>this.ownerDocument.defaultView),this.sourceToken=0,this.refreshQueued=!1,this._sourceWarmed=!1,this._selectedLabelCache=new Map,this._selectedRowCache=new Map,this._renderedRows=[],this._open=!1,this._fieldsetDisabled=!1,this.listId=nextId("combobox-list"),this.inputId=nextId("combobox-input"),this.listboxPositioned=!1,this.positioningGeneration=0,this.positioningReady=Promise.resolve(!1),this.restoreFocusOnClose=!0,this.restoringOverlayFocus=!1,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._isFirstUpdate=!0,this.openVetoed=!1,this.closeAfterPositioningFailure=!1,this.closeCleanupPending=!1,this._selected=[],this.sourceOptionsByRow=new WeakMap,this._valueDirty=!1,this._multiple=!1,this._disabled=!1,this._required=!1,this._readonly=!1,this._defaultSelected=[],this._defaultCaptured=!1,this._restoredStateActive=!1,this._name="",this._maxOptionsVisible=3,this._maxRender=200,this._sourceDelay=200,this.localDescriptionIds="",this.previousSelection=[],this.markInteracted=()=>{this.touched||(this.touched=!0,this.updateValidity(),this.syncCustomStates())},this.collectOptions=e=>{this.collectOptionsFromSlot(e.target)},this.optionRefreshPending=!1,this.onOptionChange=e=>{e.stopPropagation();const option=e.composedPath().find(isLyraOptionElement);if(isOptionSelectedWrite(e)&&isLyraOptionElement(option)&&this.options.includes(option)){if(this.multiple){const next=option.selected?this._selected.includes(option.value)?this._selected:[...this._selected,option.value]:this._selected.filter(value=>value!==option.value);this.assignValue(next)}else{if(this._valueDirty=!0,this._restoredStateActive=!1,!option.selected&&this.singleSelectedOption!==option)return;this.setValue(option.selected?option.value:[],!0,option.selected?option:void 0)}return}if(isLyraOptionElement(option)){const cached=this.adornmentClones.get(option);cached&&cached.markup!==this.adornmentMarkup(option)&&this.adornmentClones.delete(option)}this.optionRefreshPending||(this.optionRefreshPending=!0,queueMicrotask(()=>{this.optionRefreshPending=!1,this.refreshOptionDefaults(),this.reflectSelected(),this.options=[...this.options],this.normalizeActiveIndex()}))},this.adornmentClones=new WeakMap,this.onDocPointer=e=>{if(!e.composedPath().includes(this)){if(this.overlayHandle?.isActive()){this.overlayHandle.dismissBackdrop();return}this.restoreFocusOnClose=!1,this.hide()}},this.onInput=e=>{this.liveDisabled||this.readonly||(this.explicitInputValue=!1,this.query=e.target.value,this.activeIndex=-1,this.show(),this.source&&this.runSource(this.query),this.emit("lr-filter",{value:this.query}))},this.onInputBlur=event=>{this.liveDisabled||(this.touched=!0),this.syncCustomStates(),this.onComboFocusOut(event),relayNativeEvent(this,event)},this.onComboFocusOut=event=>{const trigger=this.renderRoot.querySelector('[part="combobox"]'),target=event.relatedTarget;target&&typeof target.nodeType=="number"&&trigger?.contains(target)||(this.restoreFocusOnClose=!1,this.hide())},this.onInputFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}this.restoringOverlayFocus||this.show(),relayNativeEvent(this,event)},this.onKeyDown=e=>{if(e.isComposing||e.keyCode===229||this.liveDisabled||this.readonly)return;const navigable=["ArrowDown","ArrowUp","Enter","End"].includes(e.key)?this.renderedRows.rows.filter(r=>!r.disabled):[];switch(e.key){case"ArrowDown":case"ArrowUp":if(e.preventDefault(),!this.open){this.activeIndex=navigable.findIndex(row=>this.committed.includes(row.value)),this.show();return}if(e.key==="ArrowDown"){this.activeIndex=Math.min(navigable.length-1,this.activeIndex+1);break}this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":{const activeRow=navigable[this.activeIndex];if(this.open&&this.activeIndex>=0&&activeRow){e.preventDefault(),this.pickRow(activeRow);break}const create=this.createRow;if(this.open&&create){e.preventDefault(),this.createOption(create.createInput);break}if(this.open&&this.allowCustomValue&&!this.multiple&&this.query.trim()){e.preventDefault(),this.commitCustomValue(this.query.trim());break}submitOnEnter(this,e);break}case"Escape":this.open&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(e.preventDefault(),this.hide());break;case"Home":this.open&&(e.preventDefault(),this.activeIndex=0);break;case"End":this.open&&(e.preventDefault(),this.activeIndex=navigable.length-1);break;case"Backspace":this.multiple&&!this.query&&this._selected.length&&this.removeValueAt(this._selected.length-1);break}},this.onComboMouseDown=e=>{this.liveDisabled||e.composedPath()[0]!==this.inputEl&&(e.target.closest("button")||(e.preventDefault(),this.inputEl?.focus(),this.show()))},this.onListboxMouseDown=e=>{e.preventDefault()},this.onListboxClick=e=>{const optionEl=e.target.closest('[part="option"]'),row=this._renderedRows[Number(optionEl?.dataset.index)];row&&this.pickRow(row)},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)}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}get validationTarget(){return this.validationTargetOverride??this.inputEl??void 0}set validationTarget(next){this.validationTargetOverride=next??void 0,this.validityController.refreshAnchor()}resetValidity(){this.validityController.setCustomValidity(""),this.updateValidity()}get input(){return this.inputEl??null}get selectionStart(){return this.inputEl?.selectionStart??null}set selectionStart(value){this.inputEl&&(this.inputEl.selectionStart=value)}get selectionEnd(){return this.inputEl?.selectionEnd??null}set selectionEnd(value){this.inputEl&&(this.inputEl.selectionEnd=value)}get selectionDirection(){return this.inputEl?.selectionDirection}set selectionDirection(value){this.inputEl&&(this.inputEl.selectionDirection=value)}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}get interactionBarred(){return this.liveDisabled||this.readonly}focus(options){this.liveDisabled||this.inputEl?.focus(options)}blur(){this.inputEl?.blur()}click(){this.liveDisabled||(this.inputEl?.focus(),this.show())}select(){this.inputEl?.select()}setSelectionRange(start,end,direction){this.inputEl?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){const input=this.inputEl;input&&(setNativeRangeText(input,replacement,start,end,selectMode),this.explicitInputValue=!0,this.query=input.value,this.activeIndex=-1,this.source&&this.runSource(this.query))}[VALIDITY_ANCHOR](){return this.validationTarget}syncExternalDescription(){if(!this.isConnected)return;const target=this.renderRoot.querySelector('[part="combobox-input"]');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.syncValidatorAttributeObserver(),this.hasUpdated&&queueMicrotask(()=>{this.open?this.reconnectOpenPopup():this.source&&this._selected.length&&this.asyncRows.length===0&&this.runSource("")})}adoptedCallback(){super.adoptedCallback(),this.popupController.cancel(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription(),this.listboxPositioned=!1,this.invalidateListboxPositioning(),this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.popupController.unbindPointer(),this.clearSourceTimer(),this.sourceToken+=1,this.sourceAbort?.abort(),this.sourceAbort=void 0,this.sourceErrorAnnouncements.adopted()}willUpdate(changed){super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,this.announceOpenTransition(changed),this.open?(this.listboxHidden=!1,this.listboxRendered=!0):changed.has("open")&&this.interactionBarred&&(this.listboxHidden=!0),changed.has("open")&&!this.openVetoed&&(this.listboxPositioned=!1),changed.has("open")&&this.openVetoed?this.closeCleanupPending=!1:changed.has("open")&&!this.open&&this.finalizeCloseState(),changed.has("source")&&(this.clearSourceTimer(),this.sourceAbort?.abort(),this.sourceAbort=void 0,this.sourceToken++,this.sourceLoading=!1,this.sourceFailed=!1,this.sourceEverSettled=!1,this.asyncRows=[],this._sourceTotal=0,this._sourceTruncated=!1,this.activeIndex=-1,this._sourceWarmed=!1,this.source&&this.open&&this.runSource(this.query)),!this._sourceWarmed&&this.source&&(this._selected.length>0||(this.pendingSelectedRowValues?.length??0)>0)&&this.asyncRows.length===0&&(this._sourceWarmed=!0,this.runSource(""))}firstUpdated(changed){super.firstUpdated(changed);const slot=this.optionsSlot;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>{this.optionsObserved=!0,s.assignedElements({flatten:!0}).some(isLyraOptionElement)&&this.collectOptionsFromSlot(s)})})}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){const old=this._multiple;this._multiple=!!next,this.toggleAttribute("multiple",this._multiple),this.reflectSelected(),this.syncFormValue(),this.requestUpdate("multiple",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this._disabled&&this.hide(),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 readonly(){return this._readonly}set readonly(next){const old=this._readonly;this._readonly=!!next,this.toggleAttribute("readonly",this._readonly),this._readonly&&this.hide(),this.updateValidity(),this.requestUpdate("readonly",old)}get value(){return this.multiple?[...this._selected]:this._selected[0]??""}set value(next){this.setValue(next,!0)}setValue(next,dirty,preferred){const old=this._selected;this.previousSelection=old,this.singleSelectedOption=preferred,dirty&&(this._restoredStateActive=!1,this._valueDirty=!0),this._selected=normalizeSelectionValues(next);const selected=new Set(this._selected);if(selected.size>0){const rows=this.rowsByValue(selected);for(const value of selected){const row=rows.get(value);row&&this._selectedRowCache.set(value,row)}}for(const value of this._selectedRowCache.keys())selected.has(value)||this._selectedRowCache.delete(value);for(const value of this._selectedLabelCache.keys())selected.has(value)||this._selectedLabelCache.delete(value);this.syncFormValue(),this.reflectSelected(),this.updateValidity(),this.requestUpdate("value",old)}get maxOptionsVisible(){return this._maxOptionsVisible}set maxOptionsVisible(next){const old=this._maxOptionsVisible;this._maxOptionsVisible=finiteCount(next,3),this.requestUpdate("maxOptionsVisible",old)}get maxRender(){return this._maxRender}get sourceDelay(){return this._sourceDelay}set sourceDelay(next){const old=this._sourceDelay;this._sourceDelay=finiteDuration(next,200),this.requestUpdate("sourceDelay",old)}set maxRender(next){const old=this._maxRender;this._maxRender=Math.min(finiteCount(next,200),MAX_RENDER_ROWS),this.requestUpdate("maxRender",old)}get sourceTotal(){return this._sourceTotal}get sourceTruncated(){return this._sourceTruncated}get selectedRows(){return this.resolveSelectedRowSlots().filter(row=>row!=null).map(row=>({...row}))}resolveSelectedRowSlots(){let rows;return this.committed.map(value=>this._selectedRowCache.get(value)??(rows??=this.rowsByValue(new Set(this.committed))).get(value))}get committed(){return this.multiple?this._selected:this._selected.slice(0,1)}rowsByValue(values){const rows=this.source?new Map:this.localRowsByValue(values,this.options);for(const row of this.asyncRows)values.has(row.value)&&!rows.has(row.value)&&rows.set(row.value,row);return rows}localRowsByValue(values,options){const rows=new Map;if(values.size===0)return rows;for(const option of options){const value=option.value;values.has(value)&&!rows.has(value)&&rows.set(value,this.rowForOption(option))}return rows}set selectedRows(next){const values=[],seen=new Set;if(Array.isArray(next))for(const candidate of next){let value;try{value=candidate?.value}catch{continue}typeof value!="string"||seen.has(value)||(seen.add(value),values.push(value))}if(values.length>0&&!this.hasSelectionSourceRows){this.pendingSelectedRowValues=values,this.source&&this.isConnected&&(this._sourceWarmed=!0,this.runSource(""));return}this.pendingSelectedRowValues=void 0,this.applySelectedRowValues(values)}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}validatorResult(){const self=this,current=self.value;for(const validator of Array.isArray(this.validators)?this.validators:[]){let result;try{if(typeof validator=="object"&&validator!==null&&"checkValidity"in validator){const checked=validator.checkValidity(this);if(checked?.isValid===!0)continue;const flags={};for(const key of Array.isArray(checked?.invalidKeys)?checked.invalidKeys:[])isValidityFlagKey(key)&&(flags[key]=!0);Object.values(flags).some(Boolean)||(flags.customError=!0);let message=typeof checked?.message=="string"?checked.message:"";return!message&&typeof validator.message=="string"&&(message=validator.message),!message&&typeof validator.message=="function"&&(message=validator.message(this)),{flags,message:message||this.localize("valueInvalid")}}result=typeof validator=="function"?validator(current,self):validator?.validate(current,self)}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}if(!(result===void 0||result===!0)){if(typeof result=="string")return{flags:{customError:!0},message:result};if(result===!1)return{flags:{customError:!0},message:this.localize("valueInvalid")};if(result&&typeof result=="object"&&Object.values(result).some(Boolean))return{flags:result,message:this.localize("valueInvalid")}}}return{}}syncValidatorAttributeObserver(){this.disconnectValidatorAttributeObserver();const owner=this.ownerDocument.defaultView,MutationObserverCtor=owner?.MutationObserver;if(!this.isConnected||!owner||typeof MutationObserverCtor!="function")return;const attributes=new Set;for(const validator of Array.isArray(this.validators)?this.validators:[]){if(typeof validator!="object"||validator===null||!("checkValidity"in validator))continue;let observed;try{observed=validator.observedAttributes}catch{continue}if(Array.isArray(observed))for(const name of observed)typeof name=="string"&&name.length>0&&attributes.add(name)}if(attributes.size===0)return;const binding={},observer=new MutationObserverCtor(()=>{this.validatorAttributeObserver!==binding||!this.isConnected||this.ownerDocument.defaultView!==owner||(this.updateValidity(),this.validityRevision++)});binding.observer=observer,binding.owner=owner;try{observer.observe(this,{attributes:!0,attributeFilter:[...attributes]}),this.validatorAttributeObserver=binding}catch{observer.disconnect()}}disconnectValidatorAttributeObserver(){const binding=this.validatorAttributeObserver;this.validatorAttributeObserver=void 0,binding?.observer.disconnect()}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({}),this.syncCustomStates();return}const flags={};let message="";this.required&&this._selected.length===0&&(flags.valueMissing=!0,message=this.localize("comboboxRequired"));const configured=this.validatorResult();configured.flags&&Object.assign(flags,configured.flags),configured.message&&(message=configured.message),this.validityController.setValidity(flags,message),this.syncCustomStates()}syncCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",this._selected.length===0),setCustomState(this.internals,"disabled",this.effectiveDisabled)}syncFormValue(){const state2=JSON.stringify(this._selected);if(this.multiple){if(!this.name){this.internals.setFormValue(null,state2);return}const fd=new FormData;for(const v of this._selected)fd.append(this.name,v);this.internals.setFormValue(fd,state2)}else this.internals.setFormValue(this._selected[0]??"",state2)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formResetCallback(){this.touched=!1,this._restoredStateActive=!1,this._valueDirty=!1;const resetValues=this._defaultSelected.length>0?this._defaultSelected:this.options.filter(option=>wasOptionInitiallySelected(option)).map(option=>option.value);this._defaultSelected.length===0&&resetValues.length>0&&(this._defaultSelected=[...resetValues]);const defaults=new Set(resetValues);for(const option of this.options)option[RESET_OPTION_SELECTED_FROM_OWNER](defaults.has(option.value));this.setValue(this.multiple?[...resetValues]:resetValues.slice(0,1),!1),this.query="",this.explicitInputValue=!1}formStateRestoreCallback(state2,reason){let selected=[];if(typeof state2=="string")try{const parsed=JSON.parse(state2);Array.isArray(parsed)&&parsed.every(value=>typeof value=="string")&&(selected=parsed)}catch{}this.assignValue(this.multiple?selected:selected.slice(0,1)),this._restoredStateActive=!0}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(disabled&&this.hide(),this.updateValidity(),this.requestUpdate())}checkValidity(){return this.validityController.checkValidity(()=>this.updateValidity())}reportValidity(){return this.validityController.syncConstraints(),this.touched=!0,this.updateValidity(),this.syncCustomStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncCustomStates()}disconnectedCallback(){this.listboxHidden=!0,this.releaseExternalDescription(),this.popupController.cancel(),this.listboxPositioned=!1,this.disconnectValidatorAttributeObserver(),super.disconnectedCallback(),this.invalidateListboxPositioning(),this.clearSourceTimer(),this.sourceToken+=1,this.sourceAbort?.abort(),this.sourceAbort=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.popupController.unbindPointer(),this.open=!1}collectOptionsFromSlot(slot){const previous=new Set(this.options);if(this.optionsObserved=!0,this.options=slot.assignedElements({flatten:!0}).filter(isLyraOptionElement),this.adornmentClones=new WeakMap,this.normalizeActiveIndex(),this.applyPendingSelectedRows(),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){const values=eligible.map(option=>option.value),next=this.multiple?[...new Set([...this._selected,...values])]:values[values.length-1];newLive.length>0?this.assignValue(next):this.setValue(next,!1);return}}else{this._defaultCaptured=!0;const allDefaults=this.options.filter(option=>option.defaultSelected).map(option=>option.value),allLive=this.options.filter(option=>option.selected).map(option=>option.value),defaults=this.multiple?allDefaults:allDefaults.slice(0,1),live=this.multiple?allLive:allLive.slice(0,1),initialLive=this.options.filter(option=>wasOptionInitiallySelected(option)).map(option=>option.value),optionDirty=this.options.some(option=>isOptionSelectedDirty(option)),dirtyValues=this.options.filter(option=>isOptionSelectedDirty(option)&&option.selected).map(option=>option.value);this._defaultSelected=[...defaults.length>0?defaults:initialLive.length>0?initialLive:live];const fromDefaults=defaults.length>0,initial=optionDirty?this.multiple?allLive:dirtyValues.slice(-1)[0]?dirtyValues.slice(-1):live:fromDefaults?defaults:live;if(initial.length&&!this._restoredStateActive&&!this._valueDirty){const next=this.multiple?initial:initial[0];fromDefaults&&!optionDirty?this.setValue(next,!1):this.assignValue(next);return}optionDirty&&(this._valueDirty=!0)}this.reflectSelected()}refreshOptionDefaults(){const declared=this.options.filter(option=>option.defaultSelected).map(option=>option.value);this._defaultSelected=this.multiple?declared:declared.slice(0,1),!this._valueDirty&&!this._restoredStateActive&&this.setValue([...this._defaultSelected],!1)}reflectSelected(){const value=this._selected[0];(!this.singleSelectedOption||!this.options.includes(this.singleSelectedOption)||this.singleSelectedOption.value!==value)&&(this.singleSelectedOption=this.options.find(option=>option.value===value));const selected=new Set(this._selected);for(const option of this.options)option[SET_OPTION_SELECTED_FROM_OWNER](this.multiple?selected.has(option.value):option===this.singleSelectedOption)}labelFor(value){const nonBlank=label=>label!==void 0&&label.trim().length>0?label:void 0;if(this.getUnknownLabel&&this.isUnknownValue(value)){const override=nonBlank(this.getUnknownLabel(value));if(override!==void 0)return override}return(!this.source&&!this.multiple&&this.singleSelectedOption?.value===value?nonBlank(this.singleSelectedOption.label):void 0)??nonBlank(this._selectedLabelCache.get(value))??nonBlank(this.options.find(o=>o.value===value)?.label)??nonBlank(this.asyncRows.find(r=>r.value===value)?.label)??(this.loading||this.source&&!this.sourceEverSettled?this.statusText("loading",this.loadingText):void 0)??value}isUnknownValue(value){return!this.source&&!this.optionsObserved||this.loading||this.source&&!this.sourceEverSettled?!1:!(!this.source&&!this.multiple&&this.singleSelectedOption?.value===value||this._selectedLabelCache.has(value)||this.options.some(option=>option.value===value)||this.asyncRows.some(row=>row.value===value))}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}rowForOption(option){const adornments=this.adornmentsFor(option),row={value:option.value,label:option.label||option.value,sub:option.sub||void 0,dotColor:option.dotColor||void 0,title:option.title||void 0,group:option.group||void 0,disabled:option.disabled||option.inert||option.closest("[inert]")!==null,data:option.data,...adornments.start===void 0?{}:{start:adornments.start},...adornments.end===void 0?{}:{end:adornments.end}};return this.sourceOptionsByRow.set(row,option),row}get hasSelectionSourceRows(){return(this.source?this.asyncRows.length:this.options.length)>0}applySelectedRowValues(values){const requested=new Set(values),rowsByValue=this.source?this.rowsByValue(requested):this.localRowsByValue(requested,this.options),rows=values.map(value=>rowsByValue.get(value)).filter(row=>row!==void 0),limited=this.multiple?rows:rows.slice(0,1);this.assignValue(limited.map(row=>row.value));for(const row of limited)this._selectedRowCache.set(row.value,row)}applyPendingSelectedRows(acceptEmptySource=!1){if(this.pendingSelectedRowValues===void 0||!acceptEmptySource&&!this.hasSelectionSourceRows)return!1;const values=this.pendingSelectedRowValues;return this.pendingSelectedRowValues=void 0,this.applySelectedRowValues(values),!0}get unknownRows(){if(!this.withUnknownOption)return[];const locale=this.effectiveLocale,query2=this.query.trim().toLocaleLowerCase(locale);return this.committed.filter(value=>this.isUnknownValue(value)).map(value=>({value,label:this.labelFor(value),badge:this.localize("notInCatalog"),unknownValue:value})).filter(row=>!query2||row.label.toLocaleLowerCase(locale).includes(query2)||row.value.toLocaleLowerCase(locale).includes(query2))}get createRow(){if(!this.allowCreate)return;const inputValue=this.query.trim();if(!inputValue)return;const locale=this.effectiveLocale,folded=inputValue.toLocaleLowerCase(locale);if(!(this.source?this.asyncRows:this.options.map(option=>({value:option.value,label:option.label}))).some(row=>row.value.toLocaleLowerCase(locale)===folded||row.label.toLocaleLowerCase(locale)===folded))return{value:inputValue,label:this.localize("comboboxCreate",void 0,{value:inputValue}),createInput:inputValue}}capRows(all){if(all.length<=this.maxRender)return{rows:[...all],overflow:0};const originalIndex=new Map(all.map((r,i)=>[r,i])),capped=all.slice(0,this.maxRender),cappedValues=new Set(capped.map(r=>r.value));let appendedOutOfCap=!1;for(const v of this.committed)if(!cappedValues.has(v)){const selectedRow=all.find(r=>r.value===v);selectedRow&&(capped.push(selectedRow),appendedOutOfCap=!0)}return appendedOutOfCap&&capped.sort((a,b)=>originalIndex.get(a)-originalIndex.get(b)),{rows:capped,overflow:all.length-capped.length}}get renderedRows(){let rows,overflow;if(this.source)({rows,overflow}=this.capRows(this.asyncRows)),overflow+=Math.max(0,this._sourceTotal-this.asyncRows.length);else{const capped=this.capRows(this.filtered);rows=capped.rows.map(option=>this.rowForOption(option)),overflow=capped.overflow}const create=this.createRow;return rows.push(...this.unknownRows),create&&rows.push(create),{rows,overflow}}normalizeActiveIndex(){if(this.activeIndex<0)return;const navigableCount=this.renderedRows.rows.filter(row=>!row.disabled).length,next=navigableCount>0?Math.min(this.activeIndex,navigableCount-1):-1;next!==this.activeIndex&&(this.activeIndex=next)}get filtered(){const locale=this.effectiveLocale,q=this.query.trim().toLocaleLowerCase(locale),selectedLabel=this.multiple?"":this.labelFor(this._selected[0]??"")??"",effective=q&&q===selectedLabel.toLocaleLowerCase(locale)?"":q;if(!effective)return this.options;const fn=this.filter??((o,query2)=>o.label.toLocaleLowerCase(locale).includes(query2)||o.searchText.toLocaleLowerCase(locale).includes(query2));return this.options.filter(o=>fn(o,effective))}get displayValue(){return this.multiple||this.open||this.explicitInputValue?this.query:this._selected[0]?this.labelFor(this._selected[0]):""}announceOpenTransition(changed){this.openVetoed=!1;const closeAfterPositioningFailure=!this.open&&this.closeAfterPositioningFailure;if(this.closeAfterPositioningFailure=!1,!(!changed.has("open")||this._isFirstUpdate||!this.open&&this.interactionBarred)){if(!this.isConnected||closeAfterPositioningFailure){emitPopupEvent(this,"lr-hide",!1);return}this.openVetoed=this.popupController.announce(this.open,()=>{this.open=!this.open})}}show(){if(this.open||this.interactionBarred)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.closeCleanupPending=!0,this.open=!1,settled}finalizeCloseState(){if(this.closeCleanupPending&&(this.closeCleanupPending=!1,this.activeIndex=-1,!this.multiple)){const queryChanged=this.query!=="";this.query="",this.explicitInputValue=!1,queryChanged&&this.source&&(this.asyncRows=[],this.sourceFailed=!1,this._sourceTotal=0,this._sourceTruncated=!1)}}activateListboxOverlay(){this.invalidateListboxPositioning(),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.inputEl??null}),this.popupController.bindPointer(),this.beginListboxPositioning()}beginListboxPositioning(){const anchor=this.renderRoot.querySelector('[part="combobox"]'),listbox=this.renderRoot.querySelector('[part="listbox"]');if(anchor&&listbox){const generation=this.positioningGeneration;this.positioningReady=new Promise(resolve=>{this.resolvePositioningReady=resolve}),this.startListboxPositioning(generation,anchor,listbox)}}invalidateListboxPositioning(){this.positioningGeneration++,this.cleanup?.(),this.cleanup=void 0,this.resolvePositioningReady?.(!1),this.resolvePositioningReady=void 0}resolveCurrentPositioning(positioned){const resolve=this.resolvePositioningReady;this.resolvePositioningReady=void 0,resolve?.(positioned)}async startListboxPositioning(generation,anchor,listbox){try{const runtime=await loadAnchoredOverlayRuntime(),{place}=runtime;if(generation!==this.positioningGeneration||!this.open||!this.isConnected||this.renderRoot.querySelector('[part="combobox"]')!==anchor||this.renderRoot.querySelector('[part="listbox"]')!==listbox)return;this.placedTopLayer=syncTopLayerRelease(listbox,this.placedTopLayer,this.topLayer,runtime);const cleanup=place(anchor,listbox,{placement:`${this.placement}-start`,...topLayerPlacement(this.topLayer,resolveEffectivePositioningStrategy(this,this._positioningStrategy,"fixed")),sync:this.sync,onPlaced:()=>{generation===this.positioningGeneration&&(this.listboxPositioned=!0,this.updateComplete.then(()=>{generation!==this.positioningGeneration||!this.open||this.resolveCurrentPositioning(!0)}))}});generation!==this.positioningGeneration?cleanup():this.cleanup=cleanup}catch{if(generation!==this.positioningGeneration||!this.open)return;this.resolveCurrentPositioning(!1),this.closeAfterPositioningFailure=!0,this.hide()}}teardownListboxOverlay(restoreFocus=this.restoreFocusOnClose){this.invalidateListboxPositioning(),this.restoringOverlayFocus=restoreFocus;try{this.overlayHandle?.deactivate({restoreFocus})}finally{this.restoringOverlayFocus=!1}this.overlayHandle=void 0,this.popupController.unbindPointer(),this.restoreFocusOnClose=!0}reconnectOpenPopup(){!this.isConnected||!this.open||(this.activateListboxOverlay(),this.source&&this.asyncRows.length===0&&this.runSource(this.query))}syncVisibleOptionsCap(){const listbox=this.renderRoot?.querySelector('[part="listbox"]');if(!listbox)return;const clear=()=>{listbox.style.removeProperty("max-block-size")},requested=typeof this.visibleOptions=="number"?finiteCount(this.visibleOptions,0):0;if(requested<=0)return clear();const rows=listbox.querySelectorAll('[part="option"]');if(rows.length<=requested)return clear();const boundary=rows[requested];if(!boundary)return clear();const cap=boundary.getBoundingClientRect().top-listbox.getBoundingClientRect().top;if(!Number.isFinite(cap)||cap<=0)return clear();listbox.style.setProperty("max-block-size",`min(${Math.ceil(cap)}px, var(--lr-positioner-available-block-size, var(--lr-size-18rem)))`)}updated(changed){if(super.updated(changed),this.syncExternalDescription(),this.syncVisibleOptionsCap(),changed.has("open")&&!this.openVetoed?this.open&&this.isConnected?(this.activateListboxOverlay(),this._isFirstUpdate||this.settleTransition("lr-after-show"),this.refreshQueued?(this.refreshQueued=!1,this.runSource(this.query)):this.source&&this.asyncRows.length===0&&this.runSource(this.query)):this.open?this.teardownListboxOverlay(!1):(this.teardownListboxOverlay(),this.interactionBarred?this.popupController.cancel():this._isFirstUpdate||this.settleTransition("lr-after-hide")):changed.has("open")&&this.openVetoed&&(this.restoreFocusOnClose=!0),changed.has("topLayer")&&!changed.has("open")&&this.open&&this.isConnected&&(this.invalidateListboxPositioning(),this.beginListboxPositioning()),changed.has("name")&&this.syncFormValue(),changed.has("validators")&&(this.updateValidity(),this.syncValidatorAttributeObserver()),(changed.has("touched")||changed.has("required")||changed.has("value")||changed.has("validators")||changed.has("validityRevision"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),changed.has("activeIndex")||changed.has("listboxPositioned")){const listbox=this.renderRoot.querySelector('[part="listbox"]'),row=listbox?.querySelector('[part="option"][data-active]');listbox&&row&&revealRow(listbox,row)}}settleTransition(event){return this.popupController.settle(event,{waitForPosition:async stale=>{for(;this.open&&!this.listboxPositioned;){const readiness=this.positioningReady,positioned=await readiness;if(stale())return!1;if(positioned)break;if(readiness===this.positioningReady)return!1}return!0},conceal:()=>{this.listboxHidden=!0}})}emitValueEvents(){const self=this,data=this.resolveSelectedRowSlots().map(row=>row?.data),previousValue=this.multiple?[...this.previousSelection]:this.previousSelection[0]??"",detail={value:self.value,previousValue,data};emitValueEvents(self,"input",detail,detail2=>self.emit("lr-input",detail2)),emitValueEvents(self,"change",detail,detail2=>self.emit("lr-change",detail2))}assignValue(next){this.value=next}createOption(inputValue){if(this.liveDisabled||this.readonly||this.emit("lr-create",{inputValue},{cancelable:!0}).defaultPrevented)return;const option=this.ownerDocument.createElement(tag("option"));option.setAttribute("value",inputValue),option.textContent=inputValue,this.append(option),this.pickRow({value:inputValue,label:inputValue})}commitCustomValue(inputValue){if(this.liveDisabled||this.readonly||this.multiple||!inputValue)return;const selectionChanged=this._selected[0]!==inputValue;this.touched=!0,this._selectedLabelCache.set(inputValue,inputValue),this.assignValue(inputValue),this.query="",this.explicitInputValue=!1,this.hide(),selectionChanged&&this.emitValueEvents()}pickRow(row){const sourceOption=this.sourceOptionsByRow.get(row);if(this.liveDisabled||this.readonly||row.disabled||sourceOption&&(sourceOption.disabled||sourceOption.closest("[inert]")))return;if(row.createInput!==void 0){this.createOption(row.createInput);return}this.touched=!0;const synthetic=row.unknownValue!==void 0,selectionChanged=this.multiple||this._selected[0]!==row.value;if(this.multiple){const set=new Set(this._selected);set.has(row.value)?(set.delete(row.value),this._selectedRowCache.delete(row.value)):(set.add(row.value),synthetic||(this._selectedLabelCache.set(row.value,row.label),this._selectedRowCache.set(row.value,row))),this.assignValue([...set]),this.query="",this.explicitInputValue=!1}else synthetic||(this._selectedLabelCache.set(row.value,row.label),this._selectedRowCache.clear(),this._selectedRowCache.set(row.value,row)),this.setValue(row.value,!0,sourceOption),this.query="",this.explicitInputValue=!1,this.hide();this.source&&this.runSource(this.query),selectionChanged&&this.emitValueEvents(),this.emit("lr-activate",{value:row.value})}removeValueAt(index){if(this.liveDisabled||this.readonly||index<0||index>=this._selected.length)return;const next=this._selected.filter((_,i)=>i!==index);this.touched=!0,this.assignValue(next),this.emitValueEvents()}clear(){if(this.liveDisabled||this.readonly)return;const hadSelection=this._selected.length>0,queryChanged=this.query!=="";!hadSelection&&!queryChanged||(hadSelection&&(this.touched=!0,this.assignValue([])),this.query="",this.explicitInputValue=!1,this.source&&this.runSource(this.query),hadSelection&&(this.emitValueEvents(),this.emit("lr-clear")),queryChanged&&this.emit("lr-filter",{value:this.query}))}refresh(){if(this.source){if(!this.open){this.refreshQueued=!0;return}this.refreshQueued=!1,this.runSource(this.query,{immediate:!0})}}runSource(query2,options){const source=this.source;if(!source)return;this.clearSourceTimer(),this.sourceAbort?.abort(),this.sourceAbort=void 0;const token=++this.sourceToken,ownerWindow=this.ownerDocument.defaultView;if(!this.isConnected||!ownerWindow)return;const request={query:query2,token,owner:ownerWindow,source};if(options?.immediate){this.runSourceRequest(request);return}this.sourceDebounce.delayMs=this._sourceDelay,this.sourceDebounce.push(request)}runSourceRequest({query:query2,token,owner:ownerWindow,source}){if(token!==this.sourceToken||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow)return;const controller=new ownerWindow.AbortController;this.sourceAbort=controller,this.sourceLoading=!0,this.sourceFailed=!1,Promise.resolve().then(()=>source(query2,{signal:controller.signal,limit:MAX_SOURCE_ROWS})).then(result=>{if(token!==this.sourceToken||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow)return;const normalized=normalizeSourceResult(result);this._sourceTotal=normalized.total,this._sourceTruncated=normalized.truncated,this.asyncRows=normalized.rows,this.sourceFailed=!1,this.sourceEverSettled=!0,this.normalizeActiveIndex(),this.applyPendingSelectedRows(!0);const selected=new Set(this._selected);for(const row of normalized.rows)selected.has(row.value)&&this._selectedRowCache.set(row.value,row)}).catch(err=>{token!==this.sourceToken||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow||typeof err=="object"&&err!==null&&"name"in err&&err.name==="AbortError"||(this.asyncRows=[],this._sourceTotal=0,this._sourceTruncated=!1,this.activeIndex=-1,this.sourceFailed=!0,this.sourceEverSettled=!0,this.sourceErrorAnnouncements.announceAssertive(this.localize("comboboxLoadError")),this.emit("lr-source-error",{error:err,query:query2}),console.warn("<lr-combobox> source() rejected:",err))}).finally(()=>{token===this.sourceToken&&(this.sourceLoading=!1)})}clearSourceTimer(){this.sourceDebounce.cancel()}renderRows(rows,activeId){const out=[];let currentGroup,currentGroupRows=[],groupIndex=0;const selectedSet=new Set(this.committed),flushGroup=()=>{if(currentGroupRows.length){if(currentGroup){const labelId=`${this.listId}-group-${groupIndex++}`;out.push(html`<div role="group" aria-labelledby=${labelId}>
|
|
2
2
|
<div id=${labelId} part="group-label" class="group-label">${currentGroup}</div>
|
|
3
3
|
${currentGroupRows}
|
|
4
4
|
</div>`)}else out.push(...currentGroupRows);currentGroupRows=[]}};return rows.forEach((o,i)=>{o.group!==currentGroup&&(flushGroup(),currentGroup=o.group);const id=`${this.listId}-opt-${i}`,selected=this.multiple||this.source?selectedSet.has(o.value):this.singleSelectedOption!==void 0&&this.sourceOptionsByRow.get(o)===this.singleSelectedOption;selected&&!this.multiple&&selectedSet.delete(o.value),currentGroupRows.push(html`<div
|