@aceshooting/lyra-ui 28.1.0 → 28.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +65 -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/span-waterfall/span-waterfall.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 +2 -2
- package/dist/components/charts/chart/box-plot.class.js +14 -14
- package/dist/components/charts/chart/chart.class.d.ts +2 -2
- package/dist/components/charts/chart/chart.class.js +14 -14
- 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/push-to-talk/push-to-talk.class.d.ts +2 -1
- package/dist/components/conversation/push-to-talk/push-to-talk.class.js +1 -1
- 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/flow-canvas/flow-canvas.class.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 +2 -2
- package/dist/components/data/heatmap/heatmap.class.js +2 -2
- 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/textarea/textarea.class.js +1 -1
- 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/details/accordion.class.js +1 -1
- package/dist/components/layout/filter-bar/filter-bar.class.js +3 -3
- package/dist/components/layout/menu/menu.class.d.ts +1 -1
- 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.d.ts +1 -1
- package/dist/components/layout/page/page.class.js +1 -1
- package/dist/components/layout/responsive-panel/responsive-panel.class.js +1 -1
- package/dist/components/layout/tab-group/tab-group.class.js +1 -1
- package/dist/components/layout/widget/widget.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/image-viewer/image-viewer.class.js +1 -1
- package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
- package/dist/components/overlays/overlay/dropdown.class.js +1 -1
- package/dist/components/overlays/overlay/popover.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/graph.class.d.ts +1 -1
- package/dist/components/retrieval/graph/graph.class.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/utility/tour/tour.class.js +4 -4
- 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/internal/dev-mode-attribute-warning.development.js +1 -1
- package/dist/internal/native-modal-carrier.js +2 -2
- 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/llms/components/lr-color-picker.md +2 -0
- package/llms/components/lr-commit-card.md +3 -2
- package/llms/components/lr-push-to-talk.md +3 -0
- 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.md +44 -0
- package/package.json +5 -5
- package/registrations.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{live}from"lit/directives/live.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated}from"../../../internal/form-associated.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{deepActiveElementIn,shadowFocusTarget}from"../../../internal/active-element.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{closeIcon}from"../../../internal/icons.js";import{revealRange,revealRow}from"../../../internal/reveal-row.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{styles}from"./emoji-picker.styles.js";import{loadEmojiDataOutcomeCached}from"./emoji-data-loader.js";import{LYRA_DEFAULT_emojiPickerEmpty,LYRA_DEFAULT_emojiPickerGridLabel,LYRA_DEFAULT_emojiPickerGroupActivities,LYRA_DEFAULT_emojiPickerGroupAnimalsNature,LYRA_DEFAULT_emojiPickerGroupComponent,LYRA_DEFAULT_emojiPickerGroupFlags,LYRA_DEFAULT_emojiPickerGroupFoodDrink,LYRA_DEFAULT_emojiPickerGroupObjects,LYRA_DEFAULT_emojiPickerGroupPeopleBody,LYRA_DEFAULT_emojiPickerGroupSmileysEmotion,LYRA_DEFAULT_emojiPickerGroupSymbols,LYRA_DEFAULT_emojiPickerGroupTravelPlaces,LYRA_DEFAULT_emojiPickerGroupUnknown,LYRA_DEFAULT_emojiPickerLoadError,LYRA_DEFAULT_emojiPickerPeerMissing,LYRA_DEFAULT_emojiPickerSearchLabel,LYRA_DEFAULT_emojiPickerSearchPlaceholder}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_item,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_restore,LYRA_DEFAULT_retry,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";const VIRTUALIZE_AT=200,ITEM_SIZE_FALLBACK=40,GAP_FALLBACK=2,VIRTUAL_ROW_HEIGHT_FALLBACK=56,MAX_VIRTUAL_COLUMNS=20,BUILT_IN_GROUP_LABEL_KEYS={0:"emojiPickerGroupSmileysEmotion",1:"emojiPickerGroupPeopleBody",2:"emojiPickerGroupComponent",3:"emojiPickerGroupAnimalsNature",4:"emojiPickerGroupFoodDrink",5:"emojiPickerGroupTravelPlaces",6:"emojiPickerGroupActivities",7:"emojiPickerGroupObjects",8:"emojiPickerGroupSymbols",9:"emojiPickerGroupFlags"},MAX_EMOJI_GROUPS=64,MAX_EMOJIS=2e4,MAX_SHORTCODES_PER_EMOJI=64;function snapshotEmojiGroups(source,itemSnapshots,replacements){if(!Array.isArray(source))return Object.freeze([]);const groups=[];let remaining=MAX_EMOJIS;for(let groupIndex=0;groupIndex<Math.min(source.length,MAX_EMOJI_GROUPS)&&remaining>0;groupIndex+=1)try{const rawGroup=source[groupIndex];if(rawGroup===null||typeof rawGroup!="object")continue;const group=rawGroup,key=group.key,label=group.label,rawEmojis=group.emojis;if(typeof key!="string"||typeof label!="string"||!Array.isArray(rawEmojis))continue;const emojis=[],length=Math.min(rawEmojis.length,remaining);for(let itemIndex=0;itemIndex<length;itemIndex+=1)try{const rawItem=rawEmojis[itemIndex];if(rawItem===null||typeof rawItem!="object")continue;const item=rawItem,emoji=item.emoji,name=item.name,rawShortcodes=item.shortcodes;if(typeof emoji!="string"||typeof name!="string"||rawShortcodes!==void 0&&!Array.isArray(rawShortcodes))continue;const shortcodes=rawShortcodes===void 0?void 0:Object.freeze(rawShortcodes.slice(0,MAX_SHORTCODES_PER_EMOJI).filter(entry=>typeof entry=="string")),cached=itemSnapshots.get(rawItem),snapshot=cached?.emoji===emoji&&cached.name===name&&(shortcodes===void 0?cached.shortcodes===void 0:cached.shortcodes!==void 0&&cached.shortcodes.length===shortcodes.length&&shortcodes.every((shortcode,index)=>shortcode===cached.shortcodes?.[index]))?cached:Object.freeze({emoji,name,...shortcodes===void 0?{}:{shortcodes}});cached&&cached!==snapshot&&replacements.set(cached,snapshot),itemSnapshots.set(rawItem,snapshot),emojis.push(snapshot)}catch{}remaining-=emojis.length,groups.push(Object.freeze({key,label,emojis:Object.freeze(emojis)}))}catch{}return Object.freeze(groups)}function probePixels(probe,fallback,allowZero=!1){const computed=probe.ownerDocument.defaultView?.getComputedStyle(probe);if(!computed)return fallback;const px=Number.parseFloat(computed.inlineSize);return!Number.isFinite(px)||px<0?fallback:px>0||allowZero?px:fallback}class EmojiPickerBase extends LyraElement{}class LyraEmojiPicker extends FormAssociated(EmojiPickerBase){constructor(){super(...arguments),this._groups=Object.freeze([]),this.itemSnapshots=new WeakMap,this.builtInGroups=new WeakSet,this.groupsWereSet=!1,this.applyingBuiltInGroups=!1,this.peerErrorAnnouncements=new AnnouncementSinkController(this),this.accessibleLabel="",this.size="m",this.label="",this.hint="",this.errorText="",this.slotPresence=new SlotPresenceController(this),this.touched=!1,this.labelId=nextId("emoji-picker-label"),this.hintId=nextId("emoji-picker-hint"),this.errorId=nextId("emoji-picker-error"),this.loadGroups=loadEmojiDataOutcomeCached,this.retryLoad=()=>{this.peerLoadFailure=void 0,this.builtInGroupsLocale=void 0,this.loadBuiltInGroups()},this.queryText="",this.activeIndex=0,this.virtualScrollTop=0,this.observedGridVirtualized=!1,this.liveGeometryReady=!1,this.ownerRealmGeneration=0,this.gridId=nextId("emoji-picker-grid"),this.haystacks=new WeakMap,this.onGeometryResize=()=>{const previous=this.geometryCache;if(this.geometryCache=void 0,!previous)return;const next=this.geometry();next.itemSize===previous.itemSize&&next.gap===previous.gap&&next.rowHeight===previous.rowHeight||this.requestUpdate()},this.onSearchInput=event=>{event.stopPropagation(),!this.liveDisabled&&(this.pendingGridFocus=void 0,this.queryText=event.target.value,this.activeIndex=0)},this.onClearSearch=()=>{this.liveDisabled||this.queryText===""||(this.pendingGridFocus=void 0,this.queryText="",this.activeIndex=0,this.searchEl?.focus())},this.onSearchFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onSearchBlur=event=>{this.liveDisabled||(this.touched=!0),relayNativeEvent(this,event)},this.onNavigationKeyDown=event=>{if(this.liveDisabled||event.isComposing||event.keyCode===229)return;const items=this.flatItems;if(items.length===0)return;const inSearch=event.currentTarget===this.searchEl,forwardKey=this.effectiveDirection==="rtl"?"ArrowLeft":"ArrowRight",backwardKey=this.effectiveDirection==="rtl"?"ArrowRight":"ArrowLeft";let target;if(event.key===forwardKey)target=this.activeIndex+1;else if(event.key===backwardKey)target=this.activeIndex-1;else if(event.key==="ArrowDown")target=this.activeIndex+this.columnsPerRow();else if(event.key==="ArrowUp")target=this.activeIndex-this.columnsPerRow();else if(event.key==="Home"&&!inSearch)target=0;else if(event.key==="End"&&!inSearch)target=items.length-1;else if(event.key==="Enter"||event.key===" "&&!inSearch){event.preventDefault();const item=items[this.activeIndex];item&&this.pick(item);return}else return;event.preventDefault(),inSearch&&(this.pendingGridFocus=void 0),this.setActiveIndex(target,!inSearch)},this.onGridFocusIn=event=>{const button=event.target;if(button?.nodeType!==1||button.localName!=="button")return;const option=button,indexed=Number(option.dataset.index),index=Number.isInteger(indexed)?indexed:this.optionButtons().indexOf(option);this.pendingGridFocus||(this.focusedGridItem=this.flatItems[index],index>=0&&index!==this.activeIndex&&this.setActiveIndex(index,!1))},this.onGridScroll=event=>{if(!this.isVirtualized)return;const grid=event.currentTarget;this.virtualScrollTop=grid.scrollTop;const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||this.virtualScrollRaf!==void 0&&this.virtualScrollRafWindow===ownerWindow&&this.virtualScrollRafDocument===ownerDocument)return;this.cancelVirtualScrollFrame();const generation=this.ownerRealmGeneration;let handle=0;handle=ownerWindow.requestAnimationFrame(()=>{this.virtualScrollRaf!==handle||this.virtualScrollRafWindow!==ownerWindow||this.virtualScrollRafDocument!==ownerDocument||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.virtualScrollRaf=void 0,this.virtualScrollRafWindow=void 0,this.virtualScrollRafDocument=void 0,this.requestUpdate())}),this.virtualScrollRaf=handle,this.virtualScrollRafWindow=ownerWindow,this.virtualScrollRafDocument=ownerDocument}}static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,emojiPickerEmpty:LYRA_DEFAULT_emojiPickerEmpty,emojiPickerGridLabel:LYRA_DEFAULT_emojiPickerGridLabel,emojiPickerGroupActivities:LYRA_DEFAULT_emojiPickerGroupActivities,emojiPickerGroupAnimalsNature:LYRA_DEFAULT_emojiPickerGroupAnimalsNature,emojiPickerGroupComponent:LYRA_DEFAULT_emojiPickerGroupComponent,emojiPickerGroupFlags:LYRA_DEFAULT_emojiPickerGroupFlags,emojiPickerGroupFoodDrink:LYRA_DEFAULT_emojiPickerGroupFoodDrink,emojiPickerGroupObjects:LYRA_DEFAULT_emojiPickerGroupObjects,emojiPickerGroupPeopleBody:LYRA_DEFAULT_emojiPickerGroupPeopleBody,emojiPickerGroupSmileysEmotion:LYRA_DEFAULT_emojiPickerGroupSmileysEmotion,emojiPickerGroupSymbols:LYRA_DEFAULT_emojiPickerGroupSymbols,emojiPickerGroupTravelPlaces:LYRA_DEFAULT_emojiPickerGroupTravelPlaces,emojiPickerGroupUnknown:LYRA_DEFAULT_emojiPickerGroupUnknown,emojiPickerLoadError:LYRA_DEFAULT_emojiPickerLoadError,emojiPickerPeerMissing:LYRA_DEFAULT_emojiPickerPeerMissing,emojiPickerSearchLabel:LYRA_DEFAULT_emojiPickerSearchLabel,emojiPickerSearchPlaceholder:LYRA_DEFAULT_emojiPickerSearchPlaceholder,fieldRequired:LYRA_DEFAULT_fieldRequired,item:LYRA_DEFAULT_item,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,restore:LYRA_DEFAULT_restore,retry:LYRA_DEFAULT_retry,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}get groups(){return this._groups}set groups(value){const old=this._groups,focused=shadowFocusTarget(this),focusedIndex=Number(focused?.dataset?.index);this.pendingGridFocus=typeof focused?.getAttribute=="function"&&focused.getAttribute("part")?.split(/\s+/).includes("emoji")&&Number.isInteger(focusedIndex)?{item:this.focusedGridItem??this.flatItems[focusedIndex],index:focusedIndex}:void 0,this.applyingBuiltInGroups||(this.groupsWereSet=!0),this.peerLoadFailure=void 0,this.builtInGroups=new WeakSet;const replacements=new Map;this._groups=snapshotEmojiGroups(value,this.itemSnapshots,replacements),this.pendingGridFocus?.item&&(this.pendingGridFocus.item=replacements.get(this.pendingGridFocus.item)??this.pendingGridFocus.item),this.requestUpdate("groups",old)}connectedCallback(){super.connectedCallback(),this.hasUpdated&&(this.syncGeometryProbe(),this.syncExternalDescription()),this.observeGeometryProbe(),this.syncGridObserver(),this.loadBuiltInGroups()}loadBuiltInGroups(){if(this.groupsWereSet)return;const locale=this.effectiveLocale;if(this.builtInGroupsLocale===locale)return;this.builtInGroupsLocale=locale;const ownerDocument=this.ownerDocument,generation=this.ownerRealmGeneration;this.loadGroups(locale).then(loaded=>{if(!(this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.groupsWereSet||this.builtInGroupsLocale!==locale)){if(!Array.isArray(loaded)){this.peerLoadFailure=loaded?.reason??"failed",this.announcePeerLoadFailure(),this.emit("lr-load-error");return}this.applyingBuiltInGroups=!0;try{this.groups=loaded}finally{this.applyingBuiltInGroups=!1}this.builtInGroups=new WeakSet(this._groups)}})}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}focus(options){this.liveDisabled||this.searchEl?.focus(options)}blur(){const active=deepActiveElementIn(this.isConnected?this.shadowRoot:null);active&&typeof active.blur=="function"&&active.blur()}click(){this.liveDisabled||this.searchEl?.click()}syncExternalDescription(){if(!this.isConnected)return;const owner=this.renderRoot.querySelector('[part="grid"]');owner&&(this.externalDescriptionLease?this.externalDescriptionLease.update(owner):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,owner,"aria-describedby"))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}formResetCallback(){super.formResetCallback(),this.touched=!1}haystackFor(item){const locale=this.effectiveLocale;let cached=this.haystacks.get(item);return(cached===void 0||cached.locale!==locale)&&(cached={locale,value:[item.name,...item.shortcodes??[]].join(" ").toLocaleLowerCase(locale)},this.haystacks.set(item,cached)),cached.value}projection(){const locale=this.effectiveLocale,query2=this.queryText.trim().toLocaleLowerCase(locale),cached=this.projectionCache;if(cached?.source===this._groups&&cached.query===query2&&cached.locale===locale)return cached;const groups=query2?this._groups.map(group=>{const filtered={...group,emojis:group.emojis.filter(item=>this.haystackFor(item).includes(query2))};return this.builtInGroups.has(group)&&this.builtInGroups.add(filtered),filtered}).filter(group=>group.emojis.length>0):this._groups,next={source:this._groups,query:query2,locale,groups,items:groups.flatMap(group=>group.emojis)};return this.projectionCache=next,next}get filteredGroups(){return this.projection().groups}get flatItems(){return this.projection().items}get isVirtualized(){return this.flatItems.length>=VIRTUALIZE_AT}geometry(){if(this.geometryCache)return this.geometryCache;const probe=this.geometryProbe;return probe?(this.geometryCache={itemSize:probePixels(probe.item,ITEM_SIZE_FALLBACK),gap:probePixels(probe.gap,GAP_FALLBACK,!0),rowHeight:probePixels(probe.row,VIRTUAL_ROW_HEIGHT_FALLBACK)},this.geometryCache):{itemSize:ITEM_SIZE_FALLBACK,gap:GAP_FALLBACK,rowHeight:VIRTUAL_ROW_HEIGHT_FALLBACK}}syncGeometryProbe(){if(this.geometryProbe||!this.isVirtualized||!this.ownerDocument)return;const makeProbe=name=>{const probe=this.ownerDocument.createElement("div");return probe.dataset.probe=name,probe},root=makeProbe("root");root.setAttribute("aria-hidden","true");const item=makeProbe("item"),gap=makeProbe("gap"),row=makeProbe("row");root.append(item,gap,row),this.renderRoot.append(root),this.geometryProbe={root,item,gap,row},this.geometry(),root.remove(),this.geometryProbe=void 0}bindRenderedGeometryProbe(){const root=this.renderRoot?.querySelector('[data-probe="root"]'),item=root?.querySelector('[data-probe="item"]'),gap=root?.querySelector('[data-probe="gap"]'),row=root?.querySelector('[data-probe="row"]');if(!root||!item||!gap||!row)return;if(this.geometryProbe?.root===root){this.observeGeometryProbe();return}const prior=this.geometryCache??{itemSize:ITEM_SIZE_FALLBACK,gap:GAP_FALLBACK,rowHeight:VIRTUAL_ROW_HEIGHT_FALLBACK};this.geometryProbe={root,item,gap,row},this.geometryCache=void 0;const next=this.geometry();this.liveGeometryReady=!0,this.observeGeometryProbe(),(prior.itemSize!==next.itemSize||prior.gap!==next.gap||prior.rowHeight!==next.rowHeight)&&this.ownerDocument.defaultView?.requestAnimationFrame(()=>{this.isConnected&&this.geometryProbe?.root===root&&this.requestUpdate()})}observeGeometryProbe(){const probe=this.geometryProbe,ownerDocument=this.ownerDocument;if(!probe||!this.isConnected||this.geometryObserver&&this.geometryObserverDocument===ownerDocument&&this.geometryObserverRoot===probe.root)return;this.resetGeometryObserver();const ResizeObserverCtor=ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverCtor)return;const generation=this.ownerRealmGeneration,observer=new ResizeObserverCtor(()=>{this.geometryObserver!==observer||this.geometryObserverDocument!==ownerDocument||this.geometryObserverRoot!==probe.root||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.onGeometryResize()});this.geometryObserver=observer,this.geometryObserverDocument=ownerDocument,this.geometryObserverRoot=probe.root,observer.observe(probe.item),observer.observe(probe.gap),observer.observe(probe.row)}resetGeometryObserver(){this.geometryObserver?.disconnect(),this.geometryObserver=void 0,this.geometryObserverDocument=void 0,this.geometryObserverRoot=void 0}groupLabel(group){if(!this.builtInGroups.has(group))return group.label;const labelKey=BUILT_IN_GROUP_LABEL_KEYS[group.key];return labelKey?this.localize(labelKey):this.localize("emojiPickerGroupUnknown",void 0,{group:group.key})}virtualRows(){const projection=this.projection(),columns=this.columnsPerRow();if(this.rowCache?.projection===projection&&this.rowCache.columns===columns)return this.rowCache.rows;let index=0;const rows=[];for(const group of projection.groups)for(let offset=0;offset<group.emojis.length;offset+=columns)rows.push({heading:group,group:offset===0?group:void 0,items:group.emojis.slice(offset,offset+columns).map(item=>({item,index:index++}))});return this.rowCache={projection,columns,rows},rows}optionButtons(){return[...this.renderRoot.querySelectorAll('[part="emoji"]')]}get selectedIndex(){return this.value?this.flatItems.findIndex(item=>item.emoji===this.value):-1}syncSelectedProjection(){const selectedIndex=this.selectedIndex;for(const button of this.optionButtons())button.setAttribute("aria-selected",Number(button.dataset.index)===selectedIndex?"true":"false")}columnsPerRow(){if(this.isVirtualized){const width=(this.liveGeometryReady?this.renderRoot?.querySelector('[part="grid"]'):void 0)?.clientWidth??0,{itemSize,gap}=this.geometry();return Math.min(MAX_VIRTUAL_COLUMNS,Math.max(1,Math.floor((Math.max(width,itemSize)+gap)/(itemSize+gap))))}const buttons=this.optionButtons();if(buttons.length===0)return 1;const firstTop=buttons[0].offsetTop;let columns=0;for(const button of buttons){if(button.offsetTop!==firstTop)break;columns+=1}return Math.max(1,columns)}setActiveIndex(next,focusTarget){const buttons=this.optionButtons();if(buttons.length===0&&!this.isVirtualized)return;this.activeIndex=Math.max(0,Math.min(next,this.flatItems.length-1)),focusTarget&&(this.pendingGridFocus={item:this.flatItems[this.activeIndex],index:this.activeIndex});const target=this.isVirtualized?this.renderRoot.querySelector(`[part="emoji"][data-index="${this.activeIndex}"]`):buttons[this.activeIndex],previous=this.renderRoot.querySelector('[part="emoji"][data-active]');previous&&previous!==target&&(previous.tabIndex=-1,previous.removeAttribute("data-active")),target?(target.tabIndex=0,target.setAttribute("data-active",""),this.searchEl?.setAttribute("aria-activedescendant",target.id)):this.isVirtualized&&this.searchEl?.setAttribute("aria-activedescendant",`${this.gridId}-item-${this.activeIndex}`);const grid=this.renderRoot.querySelector('[part="grid"]');if(grid&&this.isVirtualized){const rowIndex=this.virtualRows().findIndex(row=>row.items.some(({index})=>index===this.activeIndex));if(rowIndex>=0){const{rowHeight}=this.geometry(),before=grid.scrollTop;revealRange(grid,rowIndex*rowHeight,rowHeight),grid.scrollTop!==before&&(this.virtualScrollTop=grid.scrollTop,this.requestUpdate())}}else grid&&target&&revealRow(grid,target);focusTarget&&target&&(this.pendingGridFocus=void 0,target.focus())}pick(item){if(this.liveDisabled)return;const detail={value:item.emoji,previousValue:this.value};this.value=item.emoji,this.syncSelectedProjection(),dispatchNativeInputEvent(this),this.emit("lr-input",detail),dispatchNativeEvent(this,"change"),this.emit("lr-change",detail)}cancelVirtualScrollFrame(){this.virtualScrollRaf!==void 0&&this.virtualScrollRafWindow?.cancelAnimationFrame(this.virtualScrollRaf),this.virtualScrollRaf=void 0,this.virtualScrollRafWindow=void 0,this.virtualScrollRafDocument=void 0}syncGridObserver(){const grid=this.renderRoot?.querySelector('[part="grid"]'),virtualized=this.isVirtualized,ownerDocument=this.ownerDocument;if(grid===this.observedGrid&&virtualized===this.observedGridVirtualized&&(!virtualized||this.gridResizeObserverDocument===ownerDocument)||(this.resetGridObserver(),!this.isConnected)||(this.observedGrid=grid??void 0,this.observedGridVirtualized=virtualized,!grid||!virtualized))return;grid.addEventListener("scroll",this.onGridScroll,{passive:!0});const ResizeObserverCtor=ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverCtor)return;const generation=this.ownerRealmGeneration,observer=new ResizeObserverCtor(()=>{this.gridResizeObserver!==observer||this.gridResizeObserverDocument!==ownerDocument||this.observedGrid!==grid||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.requestUpdate()});this.gridResizeObserver=observer,this.gridResizeObserverDocument=ownerDocument,observer.observe(grid)}resetGridObserver(){this.observedGrid?.removeEventListener("scroll",this.onGridScroll),this.gridResizeObserver?.disconnect(),this.gridResizeObserver=void 0,this.gridResizeObserverDocument=void 0,this.observedGrid=void 0,this.observedGridVirtualized=!1,this.cancelVirtualScrollFrame()}willUpdate(changed){super.willUpdate(changed),this.isVirtualized&&this.geometryProbe&&(this.geometryCache=void 0),this.syncGeometryProbe()}updated(changed){if(super.updated(changed),this.bindRenderedGeometryProbe(),this.syncGridObserver(),this.syncExternalDescription(),this.loadBuiltInGroups(),!changed.has("queryText")&&!changed.has("groups")){this.restorePendingGridFocus();return}const buttons=this.optionButtons();if(buttons.length===0){this.searchEl?.removeAttribute("aria-activedescendant"),this.pendingGridFocus&&(this.pendingGridFocus=void 0,this.searchEl?.focus());return}if(this.pendingGridFocus){const retainedIndex=this.pendingGridFocus.item?this.flatItems.indexOf(this.pendingGridFocus.item):-1;this.activeIndex=retainedIndex>=0?retainedIndex:Math.max(0,Math.min(this.pendingGridFocus.index,this.flatItems.length-1)),this.pendingGridFocus={item:this.flatItems[this.activeIndex],index:this.activeIndex}}else!this.isVirtualized&&this.activeIndex>=buttons.length&&(this.activeIndex=0);this.setActiveIndex(this.activeIndex,!1),this.syncSelectedProjection(),this.restorePendingGridFocus()}restorePendingGridFocus(){if(!this.pendingGridFocus)return;const target=this.renderRoot.querySelector(`[part="emoji"][data-index="${this.activeIndex}"]`);target&&(this.pendingGridFocus=void 0,target.focus())}disconnectedCallback(){this.releaseExternalDescription(),super.disconnectedCallback(),this.resetOwnerRealmResources()}peerLoadMessage(){return this.localize(this.peerLoadFailure==="missing"?"emojiPickerPeerMissing":"emojiPickerLoadError")}announcePeerLoadFailure(){this.isConnected&&this.peerErrorAnnouncements.announceAssertive(this.peerLoadMessage())}adoptedCallback(){super.adoptedCallback(),this.peerErrorAnnouncements.adopted(),this.releaseExternalDescription(),this.resetOwnerRealmResources(),this.isConnected&&this.hasUpdated&&this.syncExternalDescription()}resetOwnerRealmResources(){this.ownerRealmGeneration+=1,this.pendingGridFocus=void 0,this.resetGridObserver(),this.resetGeometryObserver()}renderEmojiButton(item,itemIndex,total,selectedIndex){return html`<button
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{live}from"lit/directives/live.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated}from"../../../internal/form-associated.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{deepActiveElementIn,shadowFocusTarget}from"../../../internal/active-element.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{closeIcon}from"../../../internal/icons.js";import{revealRange,revealRow}from"../../../internal/reveal-row.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{styles}from"./emoji-picker.styles.js";import{loadEmojiDataOutcomeCached}from"./emoji-data-loader.js";import{LYRA_DEFAULT_emojiPickerEmpty,LYRA_DEFAULT_emojiPickerGridLabel,LYRA_DEFAULT_emojiPickerGroupActivities,LYRA_DEFAULT_emojiPickerGroupAnimalsNature,LYRA_DEFAULT_emojiPickerGroupComponent,LYRA_DEFAULT_emojiPickerGroupFlags,LYRA_DEFAULT_emojiPickerGroupFoodDrink,LYRA_DEFAULT_emojiPickerGroupObjects,LYRA_DEFAULT_emojiPickerGroupPeopleBody,LYRA_DEFAULT_emojiPickerGroupSmileysEmotion,LYRA_DEFAULT_emojiPickerGroupSymbols,LYRA_DEFAULT_emojiPickerGroupTravelPlaces,LYRA_DEFAULT_emojiPickerGroupUnknown,LYRA_DEFAULT_emojiPickerLoadError,LYRA_DEFAULT_emojiPickerPeerMissing,LYRA_DEFAULT_emojiPickerSearchLabel,LYRA_DEFAULT_emojiPickerSearchPlaceholder}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_item,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_restore,LYRA_DEFAULT_retry,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";const VIRTUALIZE_AT=200,ITEM_SIZE_FALLBACK=40,GAP_FALLBACK=2,VIRTUAL_ROW_HEIGHT_FALLBACK=56,MAX_VIRTUAL_COLUMNS=20,BUILT_IN_GROUP_LABEL_KEYS={0:"emojiPickerGroupSmileysEmotion",1:"emojiPickerGroupPeopleBody",2:"emojiPickerGroupComponent",3:"emojiPickerGroupAnimalsNature",4:"emojiPickerGroupFoodDrink",5:"emojiPickerGroupTravelPlaces",6:"emojiPickerGroupActivities",7:"emojiPickerGroupObjects",8:"emojiPickerGroupSymbols",9:"emojiPickerGroupFlags"},MAX_EMOJI_GROUPS=64,MAX_EMOJIS=2e4,MAX_SHORTCODES_PER_EMOJI=64;function snapshotEmojiGroups(source,itemSnapshots,replacements){if(!Array.isArray(source))return Object.freeze([]);const groups=[];let remaining=MAX_EMOJIS;for(let groupIndex=0;groupIndex<Math.min(source.length,MAX_EMOJI_GROUPS)&&remaining>0;groupIndex+=1)try{const rawGroup=source[groupIndex];if(rawGroup===null||typeof rawGroup!="object")continue;const group=rawGroup,key=group.key,label=group.label,rawEmojis=group.emojis;if(typeof key!="string"||typeof label!="string"||!Array.isArray(rawEmojis))continue;const emojis=[],length=Math.min(rawEmojis.length,remaining);for(let itemIndex=0;itemIndex<length;itemIndex+=1)try{const rawItem=rawEmojis[itemIndex];if(rawItem===null||typeof rawItem!="object")continue;const item=rawItem,emoji=item.emoji,name=item.name,rawShortcodes=item.shortcodes;if(typeof emoji!="string"||typeof name!="string"||rawShortcodes!==void 0&&!Array.isArray(rawShortcodes))continue;const shortcodes=rawShortcodes===void 0?void 0:Object.freeze(rawShortcodes.slice(0,MAX_SHORTCODES_PER_EMOJI).filter(entry=>typeof entry=="string")),cached=itemSnapshots.get(rawItem),snapshot=cached?.emoji===emoji&&cached.name===name&&(shortcodes===void 0?cached.shortcodes===void 0:cached.shortcodes!==void 0&&cached.shortcodes.length===shortcodes.length&&shortcodes.every((shortcode,index)=>shortcode===cached.shortcodes?.[index]))?cached:Object.freeze({emoji,name,...shortcodes===void 0?{}:{shortcodes}});cached&&cached!==snapshot&&replacements.set(cached,snapshot),itemSnapshots.set(rawItem,snapshot),emojis.push(snapshot)}catch{}remaining-=emojis.length,groups.push(Object.freeze({key,label,emojis:Object.freeze(emojis)}))}catch{}return Object.freeze(groups)}function probePixels(probe,fallback,allowZero=!1){const computed=probe.ownerDocument.defaultView?.getComputedStyle(probe);if(!computed)return fallback;const px=Number.parseFloat(computed.inlineSize);return!Number.isFinite(px)||px<0?fallback:px>0||allowZero?px:fallback}class EmojiPickerBase extends LyraElement{}class LyraEmojiPicker extends FormAssociated(EmojiPickerBase){constructor(){super(...arguments),this._groups=Object.freeze([]),this.itemSnapshots=new WeakMap,this.builtInGroups=new WeakSet,this.groupsWereSet=!1,this.applyingBuiltInGroups=!1,this.peerErrorAnnouncements=new AnnouncementSinkController(this),this.accessibleLabel="",this.size="m",this.label="",this.hint="",this.errorText="",this.slotPresence=new SlotPresenceController(this),this.touched=!1,this.labelId=nextId("emoji-picker-label"),this.hintId=nextId("emoji-picker-hint"),this.errorId=nextId("emoji-picker-error"),this.loadGroups=loadEmojiDataOutcomeCached,this.retryLoad=()=>{this.peerLoadFailure=void 0,this.builtInGroupsLocale=void 0,this.loadBuiltInGroups()},this.queryText="",this.activeIndex=0,this.virtualScrollTop=0,this.observedGridVirtualized=!1,this.liveGeometryReady=!1,this.ownerRealmGeneration=0,this.gridId=nextId("emoji-picker-grid"),this.haystacks=new WeakMap,this.onGeometryResize=()=>{const previous=this.geometryCache;if(this.geometryCache=void 0,!previous)return;const next=this.geometry();next.itemSize===previous.itemSize&&next.gap===previous.gap&&next.rowHeight===previous.rowHeight||this.requestUpdate()},this.onSearchInput=event=>{event.stopPropagation(),!this.liveDisabled&&(this.pendingGridFocus=void 0,this.queryText=event.target.value,this.activeIndex=0)},this.onClearSearch=()=>{this.liveDisabled||this.queryText===""||(this.pendingGridFocus=void 0,this.queryText="",this.activeIndex=0,this.searchEl?.focus())},this.onSearchFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onSearchBlur=event=>{this.liveDisabled||(this.touched=!0),relayNativeEvent(this,event)},this.onNavigationKeyDown=event=>{if(this.liveDisabled||event.isComposing||event.keyCode===229)return;const items=this.flatItems;if(items.length===0)return;const inSearch=event.currentTarget===this.searchEl,forwardKey=this.effectiveDirection==="rtl"?"ArrowLeft":"ArrowRight",backwardKey=this.effectiveDirection==="rtl"?"ArrowRight":"ArrowLeft";let target;if(event.key===forwardKey)target=this.activeIndex+1;else if(event.key===backwardKey)target=this.activeIndex-1;else if(event.key==="ArrowDown")target=this.activeIndex+this.columnsPerRow();else if(event.key==="ArrowUp")target=this.activeIndex-this.columnsPerRow();else if(event.key==="Home"&&!inSearch)target=0;else if(event.key==="End"&&!inSearch)target=items.length-1;else if(event.key==="Enter"||event.key===" "&&!inSearch){event.preventDefault();const item=items[this.activeIndex];item&&this.pick(item);return}else return;event.preventDefault(),inSearch&&(this.pendingGridFocus=void 0),this.setActiveIndex(target,!inSearch)},this.onGridFocusIn=event=>{const button=event.target;if(button?.nodeType!==1||button.localName!=="button")return;const option=button,indexed=Number(option.dataset.index),index=Number.isInteger(indexed)?indexed:this.optionButtons().indexOf(option);this.pendingGridFocus||(this.focusedGridItem=this.flatItems[index],index>=0&&index!==this.activeIndex&&this.setActiveIndex(index,!1))},this.onGridScroll=event=>{if(!this.isVirtualized)return;const grid=event.currentTarget;this.virtualScrollTop=grid.scrollTop;const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||this.virtualScrollRaf!==void 0&&this.virtualScrollRafWindow===ownerWindow&&this.virtualScrollRafDocument===ownerDocument)return;this.cancelVirtualScrollFrame();const generation=this.ownerRealmGeneration;let handle=0;handle=ownerWindow.requestAnimationFrame(()=>{this.virtualScrollRaf!==handle||this.virtualScrollRafWindow!==ownerWindow||this.virtualScrollRafDocument!==ownerDocument||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.virtualScrollRaf=void 0,this.virtualScrollRafWindow=void 0,this.virtualScrollRafDocument=void 0,this.requestUpdate())}),this.virtualScrollRaf=handle,this.virtualScrollRafWindow=ownerWindow,this.virtualScrollRafDocument=ownerDocument}}static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,emojiPickerEmpty:LYRA_DEFAULT_emojiPickerEmpty,emojiPickerGridLabel:LYRA_DEFAULT_emojiPickerGridLabel,emojiPickerGroupActivities:LYRA_DEFAULT_emojiPickerGroupActivities,emojiPickerGroupAnimalsNature:LYRA_DEFAULT_emojiPickerGroupAnimalsNature,emojiPickerGroupComponent:LYRA_DEFAULT_emojiPickerGroupComponent,emojiPickerGroupFlags:LYRA_DEFAULT_emojiPickerGroupFlags,emojiPickerGroupFoodDrink:LYRA_DEFAULT_emojiPickerGroupFoodDrink,emojiPickerGroupObjects:LYRA_DEFAULT_emojiPickerGroupObjects,emojiPickerGroupPeopleBody:LYRA_DEFAULT_emojiPickerGroupPeopleBody,emojiPickerGroupSmileysEmotion:LYRA_DEFAULT_emojiPickerGroupSmileysEmotion,emojiPickerGroupSymbols:LYRA_DEFAULT_emojiPickerGroupSymbols,emojiPickerGroupTravelPlaces:LYRA_DEFAULT_emojiPickerGroupTravelPlaces,emojiPickerGroupUnknown:LYRA_DEFAULT_emojiPickerGroupUnknown,emojiPickerLoadError:LYRA_DEFAULT_emojiPickerLoadError,emojiPickerPeerMissing:LYRA_DEFAULT_emojiPickerPeerMissing,emojiPickerSearchLabel:LYRA_DEFAULT_emojiPickerSearchLabel,emojiPickerSearchPlaceholder:LYRA_DEFAULT_emojiPickerSearchPlaceholder,fieldRequired:LYRA_DEFAULT_fieldRequired,item:LYRA_DEFAULT_item,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,restore:LYRA_DEFAULT_restore,retry:LYRA_DEFAULT_retry,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}get groups(){return this._groups}set groups(value){const old=this._groups,focused=shadowFocusTarget(this),focusedIndex=Number(focused?.dataset?.index);this.pendingGridFocus=typeof focused?.getAttribute=="function"&&focused.getAttribute("part")?.split(/\s+/).includes("emoji")&&Number.isInteger(focusedIndex)?{item:this.focusedGridItem??this.flatItems[focusedIndex],index:focusedIndex}:void 0,this.applyingBuiltInGroups||(this.groupsWereSet=!0),this.peerLoadFailure=void 0,this.builtInGroups=new WeakSet;const replacements=new Map;this._groups=snapshotEmojiGroups(value,this.itemSnapshots,replacements),this.pendingGridFocus?.item&&(this.pendingGridFocus.item=replacements.get(this.pendingGridFocus.item)??this.pendingGridFocus.item),this.requestUpdate("groups",old)}connectedCallback(){super.connectedCallback(),this.hasUpdated&&(this.syncGeometryProbe(),this.syncExternalDescription()),this.observeGeometryProbe(),this.syncGridObserver(),this.loadBuiltInGroups()}loadBuiltInGroups(){if(this.groupsWereSet)return;const locale=this.effectiveLocale;if(this.builtInGroupsLocale===locale)return;this.builtInGroupsLocale=locale;const ownerDocument=this.ownerDocument,generation=this.ownerRealmGeneration;this.loadGroups(locale).then(loaded=>{if(!(this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.groupsWereSet||this.builtInGroupsLocale!==locale)){if(!Array.isArray(loaded)){this.peerLoadFailure=loaded?.reason??"failed",this.announcePeerLoadFailure(),this.emit("lr-load-error");return}this.applyingBuiltInGroups=!0;try{this.groups=loaded}finally{this.applyingBuiltInGroups=!1}this.builtInGroups=new WeakSet(this._groups)}})}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}focus(options){this.liveDisabled||this.searchEl?.focus(options)}blur(){const active=deepActiveElementIn(this.isConnected?this.shadowRoot:null);active&&typeof active.blur=="function"&&active.blur()}click(){this.liveDisabled||this.searchEl?.click()}syncExternalDescription(){if(!this.isConnected)return;const owner=this.renderRoot.querySelector('[part="grid"]');owner&&(this.externalDescriptionLease?this.externalDescriptionLease.update(owner):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,owner,"aria-describedby"))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}formResetCallback(){super.formResetCallback(),this.touched=!1}haystackFor(item){const locale=this.effectiveLocale;let cached=this.haystacks.get(item);return(cached===void 0||cached.locale!==locale)&&(cached={locale,value:[item.name,...item.shortcodes??[]].join(" ").toLocaleLowerCase(locale)},this.haystacks.set(item,cached)),cached.value}projection(){const locale=this.effectiveLocale,query2=this.queryText.trim().toLocaleLowerCase(locale),cached=this.projectionCache;if(cached?.source===this._groups&&cached.query===query2&&cached.locale===locale)return cached;const groups=query2?this._groups.map(group=>{const filtered={...group,emojis:group.emojis.filter(item=>this.haystackFor(item).includes(query2))};return this.builtInGroups.has(group)&&this.builtInGroups.add(filtered),filtered}).filter(group=>group.emojis.length>0):this._groups,next={source:this._groups,query:query2,locale,groups,items:groups.flatMap(group=>group.emojis)};return this.projectionCache=next,next}get filteredGroups(){return this.projection().groups}get flatItems(){return this.projection().items}get isVirtualized(){return this.flatItems.length>=VIRTUALIZE_AT}geometry(){if(this.geometryCache)return this.geometryCache;const probe=this.geometryProbe;return probe?(this.geometryCache={itemSize:probePixels(probe.item,ITEM_SIZE_FALLBACK),gap:probePixels(probe.gap,GAP_FALLBACK,!0),rowHeight:probePixels(probe.row,VIRTUAL_ROW_HEIGHT_FALLBACK)},this.geometryCache):{itemSize:ITEM_SIZE_FALLBACK,gap:GAP_FALLBACK,rowHeight:VIRTUAL_ROW_HEIGHT_FALLBACK}}syncGeometryProbe(){if(this.geometryProbe||!this.isVirtualized||!this.ownerDocument)return;const makeProbe=name=>{const probe=this.ownerDocument.createElement("div");return probe.dataset.probe=name,probe},root=makeProbe("root");root.setAttribute("aria-hidden","true");const item=makeProbe("item"),gap=makeProbe("gap"),row=makeProbe("row");root.append(item,gap,row),this.renderRoot.append(root),this.geometryProbe={root,item,gap,row},this.geometry(),root.remove(),this.geometryProbe=void 0}bindRenderedGeometryProbe(){const root=this.renderRoot?.querySelector('[data-probe="root"]'),item=root?.querySelector('[data-probe="item"]'),gap=root?.querySelector('[data-probe="gap"]'),row=root?.querySelector('[data-probe="row"]');if(!root||!item||!gap||!row)return;if(this.geometryProbe?.root===root){this.observeGeometryProbe();return}const prior=this.geometryCache??{itemSize:ITEM_SIZE_FALLBACK,gap:GAP_FALLBACK,rowHeight:VIRTUAL_ROW_HEIGHT_FALLBACK};this.geometryProbe={root,item,gap,row},this.geometryCache=void 0;const next=this.geometry();this.liveGeometryReady=!0,this.observeGeometryProbe(),(prior.itemSize!==next.itemSize||prior.gap!==next.gap||prior.rowHeight!==next.rowHeight)&&this.ownerDocument.defaultView?.requestAnimationFrame(()=>{this.isConnected&&this.geometryProbe?.root===root&&this.requestUpdate()})}observeGeometryProbe(){const probe=this.geometryProbe,ownerDocument=this.ownerDocument;if(!probe||!this.isConnected||this.geometryObserver&&this.geometryObserverDocument===ownerDocument&&this.geometryObserverRoot===probe.root)return;this.resetGeometryObserver();const ResizeObserverCtor=ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverCtor)return;const generation=this.ownerRealmGeneration,observer=new ResizeObserverCtor(()=>{this.geometryObserver!==observer||this.geometryObserverDocument!==ownerDocument||this.geometryObserverRoot!==probe.root||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.onGeometryResize()});this.geometryObserver=observer,this.geometryObserverDocument=ownerDocument,this.geometryObserverRoot=probe.root,observer.observe(probe.item),observer.observe(probe.gap),observer.observe(probe.row)}resetGeometryObserver(){this.geometryObserver?.disconnect(),this.geometryObserver=void 0,this.geometryObserverDocument=void 0,this.geometryObserverRoot=void 0}groupLabel(group){if(!this.builtInGroups.has(group))return group.label;const labelKey=BUILT_IN_GROUP_LABEL_KEYS[group.key];return labelKey?this.localize(labelKey):this.localize("emojiPickerGroupUnknown",void 0,{group:group.key})}virtualRows(){const projection=this.projection(),columns=this.columnsPerRow();if(this.rowCache?.projection===projection&&this.rowCache.columns===columns)return this.rowCache.rows;let index=0;const rows=[];for(const group of projection.groups)for(let offset=0;offset<group.emojis.length;offset+=columns)rows.push({heading:group,group:offset===0?group:void 0,items:group.emojis.slice(offset,offset+columns).map(item=>({item,index:index++}))});return this.rowCache={projection,columns,rows},rows}optionButtons(){return[...this.renderRoot.querySelectorAll('[part="emoji"]')]}get selectedIndex(){return this.value?this.flatItems.findIndex(item=>item.emoji===this.value):-1}syncSelectedProjection(){const selectedIndex=this.selectedIndex;for(const button of this.optionButtons())button.setAttribute("aria-selected",Number(button.dataset.index)===selectedIndex?"true":"false")}columnsPerRow(){if(this.isVirtualized){const width=(this.liveGeometryReady?this.renderRoot?.querySelector('[part="grid"]'):void 0)?.clientWidth??0,{itemSize,gap}=this.geometry();return Math.min(MAX_VIRTUAL_COLUMNS,Math.max(1,Math.floor((Math.max(width,itemSize)+gap)/(itemSize+gap))))}const buttons=this.optionButtons();if(buttons.length===0)return 1;const firstTop=buttons[0].offsetTop;let columns=0;for(const button of buttons){if(button.offsetTop!==firstTop)break;columns+=1}return Math.max(1,columns)}setActiveIndex(next,focusTarget){const buttons=this.optionButtons();if(buttons.length===0&&!this.isVirtualized)return;this.activeIndex=Math.max(0,Math.min(next,this.flatItems.length-1)),focusTarget&&(this.pendingGridFocus={item:this.flatItems[this.activeIndex],index:this.activeIndex});const target=this.isVirtualized?this.renderRoot.querySelector(`[part="emoji"][data-index="${this.activeIndex}"]`):buttons[this.activeIndex],previous=this.renderRoot.querySelector('[part="emoji"][data-active]');previous&&previous!==target&&(previous.tabIndex=-1,previous.removeAttribute("data-active")),target?(target.tabIndex=0,target.setAttribute("data-active",""),this.searchEl?.setAttribute("aria-activedescendant",target.id)):this.isVirtualized&&this.searchEl?.setAttribute("aria-activedescendant",`${this.gridId}-item-${this.activeIndex}`);const grid=this.renderRoot.querySelector('[part="grid"]');if(grid&&this.isVirtualized){const rowIndex=this.virtualRows().findIndex(row=>row.items.some(({index})=>index===this.activeIndex));if(rowIndex>=0){const{rowHeight}=this.geometry(),before=grid.scrollTop;revealRange(grid,rowIndex*rowHeight,rowHeight),grid.scrollTop!==before&&(this.virtualScrollTop=grid.scrollTop,this.requestUpdate())}}else grid&&target&&revealRow(grid,target);focusTarget&&target&&(this.pendingGridFocus=void 0,target.focus())}pick(item){if(this.liveDisabled)return;const detail={value:item.emoji,previousValue:this.value};this.value=item.emoji,this.syncSelectedProjection(),dispatchNativeInputEvent(this),this.emit("lr-input",detail),dispatchNativeEvent(this,"change"),this.emit("lr-change",detail)}cancelVirtualScrollFrame(){this.virtualScrollRaf!==void 0&&this.virtualScrollRafWindow?.cancelAnimationFrame(this.virtualScrollRaf),this.virtualScrollRaf=void 0,this.virtualScrollRafWindow=void 0,this.virtualScrollRafDocument=void 0}syncGridObserver(){const grid=this.renderRoot?.querySelector('[part="grid"]'),virtualized=this.isVirtualized,ownerDocument=this.ownerDocument;if(grid===this.observedGrid&&virtualized===this.observedGridVirtualized&&(!virtualized||this.gridResizeObserverDocument===ownerDocument)||(this.resetGridObserver(),!this.isConnected)||(this.observedGrid=grid??void 0,this.observedGridVirtualized=virtualized,!grid||!virtualized))return;grid.addEventListener("scroll",this.onGridScroll,{passive:!0});const ResizeObserverCtor=ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverCtor)return;const generation=this.ownerRealmGeneration,observer=new ResizeObserverCtor(()=>{this.gridResizeObserver!==observer||this.gridResizeObserverDocument!==ownerDocument||this.observedGrid!==grid||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.requestUpdate()});this.gridResizeObserver=observer,this.gridResizeObserverDocument=ownerDocument,observer.observe(grid)}resetGridObserver(){this.observedGrid?.removeEventListener("scroll",this.onGridScroll),this.gridResizeObserver?.disconnect(),this.gridResizeObserver=void 0,this.gridResizeObserverDocument=void 0,this.observedGrid=void 0,this.observedGridVirtualized=!1,this.cancelVirtualScrollFrame()}willUpdate(changed){super.willUpdate(changed),this.isVirtualized&&this.geometryProbe&&(this.geometryCache=void 0),this.syncGeometryProbe()}updated(changed){if(super.updated(changed),this.bindRenderedGeometryProbe(),this.syncGridObserver(),this.syncExternalDescription(),this.loadBuiltInGroups(),!changed.has("queryText")&&!changed.has("groups")){this.restorePendingGridFocus();return}const buttons=this.optionButtons();if(buttons.length===0){this.searchEl?.removeAttribute("aria-activedescendant"),this.pendingGridFocus&&(this.pendingGridFocus=void 0,this.searchEl?.focus());return}if(this.pendingGridFocus){const retainedIndex=this.pendingGridFocus.item?this.flatItems.indexOf(this.pendingGridFocus.item):-1;this.activeIndex=retainedIndex>=0?retainedIndex:Math.max(0,Math.min(this.pendingGridFocus.index,this.flatItems.length-1)),this.pendingGridFocus={item:this.flatItems[this.activeIndex],index:this.activeIndex}}else!this.isVirtualized&&this.activeIndex>=buttons.length&&(this.activeIndex=0);this.setActiveIndex(this.activeIndex,!1),this.syncSelectedProjection(),this.restorePendingGridFocus()}restorePendingGridFocus(){if(!this.pendingGridFocus)return;const target=this.renderRoot.querySelector(`[part="emoji"][data-index="${this.activeIndex}"]`);target&&(this.pendingGridFocus=void 0,target.focus())}disconnectedCallback(){this.releaseExternalDescription(),super.disconnectedCallback(),this.resetOwnerRealmResources()}peerLoadMessage(){return this.localize(this.peerLoadFailure==="missing"?"emojiPickerPeerMissing":"emojiPickerLoadError")}announcePeerLoadFailure(){this.isConnected&&this.peerErrorAnnouncements.announceAssertive(this.peerLoadMessage())}adoptedCallback(){super.adoptedCallback(),this.peerErrorAnnouncements.adopted(),this.releaseExternalDescription(),this.resetOwnerRealmResources(),this.isConnected&&this.hasUpdated&&this.syncExternalDescription()}resetOwnerRealmResources(){this.ownerRealmGeneration+=1,this.pendingGridFocus=void 0,this.resetGridObserver(),this.resetGeometryObserver()}renderEmojiButton(item,itemIndex,total,selectedIndex){return html`<button
|
|
2
2
|
type="button"
|
|
3
3
|
part="emoji"
|
|
4
4
|
id=${`${this.gridId}-item-${itemIndex}`}
|
|
@@ -13,13 +13,13 @@ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,stat
|
|
|
13
13
|
?disabled=${this.effectiveDisabled}
|
|
14
14
|
@click=${()=>this.pick(item)}
|
|
15
15
|
@focusin=${this.onGridFocusIn}
|
|
16
|
-
>${item.emoji}</button>`}renderVirtualRows(){const rows=this.virtualRows(),rowHeight=this.geometry().rowHeight,viewportHeight=(this.liveGeometryReady?this.renderRoot?.querySelector('[part="grid"]'):void 0)?.clientHeight||256,start=Math.max(0,Math.floor(this.virtualScrollTop/rowHeight)-3),end=Math.min(rows.length,Math.ceil((this.virtualScrollTop+viewportHeight)/rowHeight)+3),total=this.flatItems.length,selectedIndex=this.selectedIndex;return html`
|
|
16
|
+
>${item.emoji}</button>`}renderVirtualRows(){const rows=this.virtualRows(),rowHeight=this.geometry().rowHeight,viewportHeight=(this.liveGeometryReady?this.renderRoot?.querySelector('[part="grid"]'):void 0)?.clientHeight||256,start=Math.max(0,Math.floor(this.virtualScrollTop/rowHeight)-3),end=Math.min(rows.length,Math.ceil((this.virtualScrollTop+viewportHeight)/rowHeight)+3),total=this.flatItems.length,selectedIndex=this.selectedIndex,visibleRows=rows.slice(start,end).map((row,offset)=>({row,index:start+offset}));let low=0,high=rows.length;for(;low<high;){const middle=low+high>>>1;rows[middle].items.at(-1).index<this.activeIndex?low=middle+1:high=middle}const activeRow=low<rows.length&&rows[low].items[0].index<=this.activeIndex?low:-1;return activeRow>=0&&activeRow<start?visibleRows.unshift({row:rows[activeRow],index:activeRow}):activeRow>=end&&visibleRows.push({row:rows[activeRow],index:activeRow}),html`
|
|
17
17
|
<div part="virtual-spacer" style=${`block-size: ${rows.length*rowHeight}px`}>
|
|
18
|
-
${
|
|
19
|
-
<div part="virtual-row" role="group" aria-label=${this.groupLabel(row.heading)} style=${`transform: translateY(${
|
|
18
|
+
${repeat(visibleRows,({index})=>index,({row,index})=>html`
|
|
19
|
+
<div part="virtual-row" role="group" aria-label=${this.groupLabel(row.heading)} style=${`transform: translateY(${index*rowHeight}px)`}>
|
|
20
20
|
${row.group?html`<div part="group-label">${this.groupLabel(row.group)}</div>`:html`<div part="virtual-label" aria-hidden="true"></div>`}
|
|
21
21
|
<div part="virtual-items">
|
|
22
|
-
${row.items.map(({item,index})=>this.renderEmojiButton(item,
|
|
22
|
+
${row.items.map(({item,index:index2})=>this.renderEmojiButton(item,index2,total,selectedIndex))}
|
|
23
23
|
</div>
|
|
24
24
|
</div>
|
|
25
25
|
`)}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{emitValueEvents}from"../../../internal/value-events.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{acquireAnnouncementSink}from"../../../internal/announcer.js";import{acquireNativeControlDescription}from"../../../internal/native-control-description.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{deferredPlace as place,awaitPopupAnimations,syncTopLayerRelease,topLayerPlacement}from"../../../internal/anchored-overlay-runtime.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{hostAriaLabel,nextId,srOnly}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{TypeAheadBuffer}from"../../../internal/type-ahead-buffer.js";import{resolveListMove}from"../../../internal/list-navigation.js";import{getDisplayNames,resolveIntlLocale}from"../../../internal/intl-cache.js";import{activeElementIn,shadowFocusTarget}from"../../../internal/active-element.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{getLyraLocale,getLyraLocaleDirection,getRegisteredLyraLocales,subscribeLyraLocaleRegistry,setLyraLocale}from"../../../internal/localization-runtime.js";import{localeNativeName}from"../../media/flag/language-map.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./locale-picker.styles.js";import{autocorrectConverter,declaredDefaultConverter,spellcheckConverter}from"../../../internal/converters.js";import{getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{PopupController,emitPopupEvent}from"../../../internal/popup-controller.js";import{revealRow}from"../../../internal/reveal-row.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{LYRA_DEFAULT_localePickerEmpty,LYRA_DEFAULT_localePickerLabel,LYRA_DEFAULT_localePickerRequired,LYRA_DEFAULT_localePickerSearchLabel}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_loading,LYRA_DEFAULT_retry,LYRA_DEFAULT_statusError}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();const MAX_LOCALE_ENTRIES=512,localeSpellcheckConverter={...spellcheckConverter,fromAttribute:(value,type)=>value===null?void 0:spellcheckConverter.fromAttribute?.(value,type)};function snapshotLocaleCatalog(source){if(!Array.isArray(source))return Object.freeze([]);const rows=[];for(let index=0;index<Math.min(source.length,MAX_LOCALE_ENTRIES);index+=1)try{const raw=source[index];if(typeof raw=="string"){raw.length>0&&rows.push(raw);continue}if(raw===null||typeof raw!="object")continue;const candidate=raw,tag=candidate.tag,label=candidate.label,country=candidate.country;if(typeof tag!="string"||tag.length===0||label!==void 0&&typeof label!="string"||country!==void 0&&typeof country!="string")continue;rows.push(Object.freeze({tag,...label===void 0?{}:{label},...country===void 0?{}:{country}}))}catch{}return Object.freeze(rows)}class LyraLocalePicker extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,loading:LYRA_DEFAULT_loading,localePickerEmpty:LYRA_DEFAULT_localePickerEmpty,localePickerLabel:LYRA_DEFAULT_localePickerLabel,localePickerRequired:LYRA_DEFAULT_localePickerRequired,localePickerSearchLabel:LYRA_DEFAULT_localePickerSearchLabel,retry:LYRA_DEFAULT_retry,statusError:LYRA_DEFAULT_statusError}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:"value",reflect:!0,useDefault:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0}}}get localeLoader(){return this._localeLoader}set localeLoader(next){const previous=this._localeLoader;previous!==next&&(this.cancelLocaleLoad(),this._localeLoader=next,this.requestUpdate("localeLoader",previous))}get locales(){return this._locales}set locales(next){this.cancelLocaleLoad();const previous=this._locales;this._locales=next===void 0?void 0:snapshotLocaleCatalog(next),this.requestUpdate("locales",previous)}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=!!next,this.requestUpdate()}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&&!liveDisabled,this._open===old){next&&!this._open&&this.hasAttribute("open")&&this.removeAttribute("open");return}this._open||(this.activeIndex=-1,this.clearSearch()),this.requestUpdate("open",old)}constructor(){super(),this.withoutFlags=!1,this.topLayer=!1,this.triggerDisplay="flag-label",this.optionDisplay="label-tag",this.searchable=!1,this.autocomplete="off",this.inputMode="",this.enterKeyHint="",this.spellcheck=!1,this.autocapitalize="",this.autocorrectValue=!0,this.label="",this.hint="",this.errorText="",this.size="m",this.activeIndex=-1,this.searchQuery="",this.touched=!1,this.slotPresence=new SlotPresenceController(this),this.registryTick=0,this.searchFocusGeneration=0,this.listId=nextId("locale-picker-list"),this.controlId=nextId("locale-picker-control"),this.listboxHidden=!0,this.closeSettleToken=0,this.popupController=new PopupController({host:this,popup:()=>this.renderRoot.querySelector('[part="listbox"]'),emit:(name,cancelable)=>emitPopupEvent(this,name,cancelable),onPointer:event=>this.onDocPointer(event)}),this._value="",this._open=!1,this._fieldsetDisabled=!1,this._name="",this._disabled=!1,this._required=!1,this._defaultValue="",this._valueDirty=!1,this.settingDefaultValue=!1,this.reflectingDefaultValue=!1,this.typeBuffer=new TypeAheadBuffer(this),this.activeScrollGeneration=0,this.localizedValidityLocale="",this.localizedIntrinsicMessage="",this.localDescriptionIds="",this.markInteracted=()=>{this.touched||(this.touched=!0,this.syncCustomStates())},this.onDocPointer=e=>{if(!e.composedPath().includes(this)){if(this.overlayHandle?.isActive()){this.overlayHandle.dismissBackdrop();return}this.hide()}},this.commitDispatching=!1,this.valueWriteVersion=0,this.loadGeneration=0,this.retryLocaleLoad=()=>{const restoreFocus=shadowFocusTarget(this)?.getAttribute("part")==="load-retry";this.loadFailureTag!==void 0&&this.commit(this.loadFailureTag),restoreFocus&&this.loadFailureTag===void 0&&this.isConnected&&shadowFocusTarget(this)?.getAttribute("part")==="load-retry"&&this.focus()},this.onTriggerClick=()=>{this.liveDisabled||(this.open?this.hide():this.show())},this.onTriggerBlur=event=>{if(this.isSearchFocusTransfer(event)){event.stopPropagation();return}this.liveDisabled||(this.touched=!0),this.syncCustomStates(),this.hide(),relayNativeEvent(this,event)},this.onTriggerFocus=event=>{if(this.isSearchFocusTransfer(event)){event.stopPropagation();return}if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onSearchInput=event=>{event.stopPropagation(),!(!this.searchable||!this.open||this.liveDisabled)&&(this.searchQuery=event.currentTarget.value,this.setActiveIndex(this.visibleEntries.length?0:-1))},this.onSearchChange=event=>{event.stopPropagation()},this.onSearchKeyDown=event=>{if(this.liveDisabled||!this.open||event.isComposing||event.keyCode===229)return;const rows=this.visibleEntries;if(event.key==="ArrowDown"||event.key==="ArrowUp")event.preventDefault(),this.setActiveIndex(event.key==="ArrowDown"?Math.min(rows.length-1,this.activeIndex+1):Math.max(0,this.activeIndex-1));else if(event.key==="Enter"){event.preventDefault();const row=rows[this.activeIndex];row&&this.commit(row.tag)}else event.key==="Escape"&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(event.preventDefault(),this.dismissFromEscape())},this.onKeyDown=e=>{if(this.liveDisabled||e.isComposing||e.keyCode===229)return;const rows=this.visibleEntries,move=()=>resolveListMove(e,{count:rows.length,current:this.activeIndex,orientation:"vertical",wrap:!1,clamp:!0,backwardFromMissing:"first"});switch(e.key){case"ArrowDown":if(e.preventDefault(),!this.open)return this.show();this.setActiveIndex(move()??-1),this.queueSearchFocus();break;case"ArrowUp":if(e.preventDefault(),!this.open)return this.show();this.setActiveIndex(move()??-1),this.queueSearchFocus();break;case"Enter":case" ":if(this.open){e.preventDefault();const activeRow=rows[this.activeIndex];this.activeIndex>=0&&activeRow?this.commit(activeRow.tag):this.hide()}break;case"Escape":this.open&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(e.preventDefault(),this.dismissFromEscape());break;case"Home":this.open&&(e.preventDefault(),this.setActiveIndex(move()??-1));break;case"End":this.open&&(e.preventDefault(),this.setActiveIndex(move()??-1));break;default:this.typeBuffer.accepts(e)&&(this.searchable?(e.preventDefault(),this.show(),this.searchQuery+=e.key,this.setActiveIndex(this.visibleEntries.length?0:-1),this.queueSearchFocus()):this.typeAhead(e.key));break}},this.onListboxMouseDown=e=>{e.composedPath()[0]!==this.searchElement&&e.preventDefault()},this.onListboxClick=e=>{if(this.liveDisabled)return;const tag=e.target.closest('[part="option"]')?.dataset.value;tag!==void 0&&this.commit(tag)},this.validityController=new FormControlController(this,{invalid:init=>this.emit("lr-invalid",null,init),interacted:this.markInteracted,customError:()=>this.validityController.customValidityMessage}),this.internals=this.validityController.formInternals,new GlassScrollLayer(this,'[part="listbox"]',()=>this.open),this.internals.setFormValue("")}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}focus(options){this.liveDisabled||this.triggerElement?.focus(options)}blur(){this.searchElement&&shadowFocusTarget(this)===this.searchElement?this.searchElement.blur():this.triggerElement?.blur()}click(){this.liveDisabled||this.triggerElement?.click()}get input(){return this.searchable?this.searchElement??null:null}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"]')??null}syncExternalDescription(){if(!this.isConnected)return;const target=this.triggerElement??null;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.syncLocaleAttributeForLocalization(),this.updateValidity(),this.stopRegistrySubscription=subscribeLyraLocaleRegistry(()=>{this.registryTick+=1}),this.hasUpdated&&this.open&&queueMicrotask(()=>this.syncPopup())}disconnectedCallback(){this.clearSearch(),this.cancelLocaleLoad(),this.loadAnnouncements?.release(),this.loadAnnouncements=void 0,this.closeSettleToken++,this.listboxHidden=!0,this.releaseExternalDescription(),super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.deactivatePopupOverlay(!1),this.stopRegistrySubscription?.(),this.stopRegistrySubscription=void 0,this.typeBuffer.clear(),this.activeScrollGeneration+=1,this.open=!1}adoptedCallback(){this.closeSettleToken++,this.clearSearch(),this.cancelLocaleLoad(),this.loadAnnouncements?.release(),this.loadAnnouncements=void 0,super.adoptedCallback(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription(),this.cleanup?.(),this.cleanup=void 0,this.popupController.unbindPointer(),this.overlayHandle?.suspend(),this.typeBuffer.clear(),this.open&&queueMicrotask(()=>this.syncPopup())}willUpdate(changed){super.willUpdate(changed),changed.has("locale")&&this.syncLocaleAttributeForLocalization(),this.hasUpdated&&this.refreshLocalizedIntrinsicValidity(changed),changed.has("searchable")&&!this.searchable&&(this.clearSearch(),this.searchElement&&shadowFocusTarget(this)===this.searchElement&&this.focus()),changed.has("open")&&this.open&&this.setActiveIndex(this.visibleEntries.findIndex(row=>row.tag===this._value)),this.open&&(this.searchable||changed.has("locales")||changed.has("registryTick"))&&this.activeIndex>=0&&(this.activeIndex=Math.min(this.activeIndex,this.visibleEntries.length-1),this.queueActiveScroll()),this.open&&(this.listboxHidden=!1)}get value(){return this._value}set value(next){this.cancelLocaleLoad(),this.valueWriteVersion++;const old=this._value;this.settingDefaultValue||(this._valueDirty=!0),this._value=next??"",this.internals.setFormValue(this._value),this.updateValidity(),this.requestUpdate("value",old)}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next??"",this.reflectingDefaultValue=!0;try{this._defaultValue?this.setAttribute("value",this._defaultValue):this.removeAttribute("value")}finally{this.reflectingDefaultValue=!1}this._valueDirty||this.restoreLiveValueFromDefault(),this.requestUpdate("defaultValue",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",reflectFormName(this,this._name),this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){next&&this.cancelLocaleLoad();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 effectiveDisabled(){return this.disabled||this._fieldsetDisabled}updateValidity(){this.localizedValidityLocale=this.effectiveMessageLocale;const valueMissing=this.hasMissingRequiredValue(),message=valueMissing?this.localize("localePickerRequired"):"";this.localizedIntrinsicMessage=message,valueMissing?this.validityController.setValidity({valueMissing:!0},message):this.validityController.setValidity({}),this.syncCustomStates()}refreshLocalizedIntrinsicValidity(changed){const locale=this.effectiveMessageLocale,message=this.hasMissingRequiredValue()?this.localize("localePickerRequired"):"";(changed.has("strings")||locale!==this.localizedValidityLocale||message!==this.localizedIntrinsicMessage)&&this.updateValidity()}hasMissingRequiredValue(){return!this.isBarred()&&this.required&&!this._value}syncLocaleAttributeForLocalization(){this.locale?this.getAttribute("locale")!==this.locale&&this.setAttribute("locale",this.locale):this.hasAttribute("locale")&&this.removeAttribute("locale")}isBarred(){return isBarredFromValidation(this,this.internals)}syncCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.isBarred()})}formResetCallback(){this.touched=!1,this.clearSearch(),this.restoreLiveValueFromDefault()}restoreLiveValueFromDefault(){this.settingDefaultValue=!0;try{this.value=this._defaultValue}finally{this.settingDefaultValue=!1}this._valueDirty=!1}formStateRestoreCallback(state2,_mode){this.value=typeof state2=="string"?state2:""}formDisabledCallback(disabled){this.validityController?.reflectingDisabled||(disabled&&this.cancelLocaleLoad(),this._fieldsetDisabled=disabled,disabled&&this.hide(),this.updateValidity(),this.requestUpdate())}checkValidity(){return this.validityController.checkValidity()}reportValidity(){return this.validityController.syncConstraints(),this.touched=!0,this.syncCustomStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncCustomStates(),this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),this.requestUpdate()}get normalizedEntries(){const raw=this.locales,cached=this.entriesCache;if(cached&&cached.raw===raw&&cached.tick===this.registryTick)return cached.rows;const rows=raw!==void 0?raw.map(entry=>typeof entry=="string"?{tag:entry,label:localeNativeName(entry)}:{tag:entry.tag,label:entry.label!==void 0&&entry.label.trim().length>0?entry.label:localeNativeName(entry.tag),country:entry.country}):getRegisteredLyraLocales().map(tag=>({tag,label:localeNativeName(tag)}));return this.entriesCache={raw,tick:this.registryTick,rows},rows}normalizeSearch(text,locale=this.effectiveLocale){return text.toLocaleLowerCase(resolveIntlLocale(locale)).normalize("NFKD").replace(/\p{M}/gu,"").trim()}get visibleEntries(){const rows=this.normalizedEntries,query2=this.searchable?this.normalizeSearch(this.searchQuery):"";if(!query2)return rows;const cached=this.visibleCache;if(cached&&cached.rows===rows&&cached.query===this.searchQuery&&cached.locale===this.effectiveLocale)return cached.result;let names;try{names=getDisplayNames(this.effectiveLocale,{type:"language"})}catch{}let englishNames;try{englishNames=getDisplayNames("en",{type:"language"})}catch{}const invariantQuery=this.normalizeSearch(this.searchQuery,"en"),result=rows.filter(row=>{let localizedName="";try{localizedName=names?.of(row.tag)??""}catch{}let englishName="";try{englishName=englishNames?.of(row.tag)??""}catch{}return[row.label,localeNativeName(row.tag),localizedName].some(text=>this.normalizeSearch(text).includes(query2))||[row.tag,englishName].some(text=>this.normalizeSearch(text,"en").includes(invariantQuery))});return this.visibleCache={rows,query:this.searchQuery,locale:this.effectiveLocale,result},result}clearSearch(){this.searchQuery="",this.searchFocusGeneration++,this.searchAnnouncements?.release(),this.searchAnnouncements=void 0}queueSearchFocus(){if(!this.searchable||!this.open||this.liveDisabled)return;const generation=++this.searchFocusGeneration,ownerDocument=this.ownerDocument,outerFocus=activeElementIn(ownerDocument),innerFocus=shadowFocusTarget(this);this.updateComplete.then(()=>{generation!==this.searchFocusGeneration||!this.isConnected||!this.open||!this.searchable||this.liveDisabled||this.ownerDocument!==ownerDocument||activeElementIn(ownerDocument)!==outerFocus||shadowFocusTarget(this)!==innerFocus||this.searchElement?.focus()})}get previewTag(){return this._value||this.effectiveLocale}entryFor(tag){return this.normalizedEntries.find(e=>e.tag===tag)}labelFor(tag){return this.entryFor(tag)?.label??localeNativeName(tag)}show(){this.open||this.liveDisabled||(this.open=!0,this.queueSearchFocus())}hide(){this.open&&(this.open=!1,this.setActiveIndex(-1))}dismissFromEscape(){if(this.open){if(this.searchable&&this.searchQuery.length){this.clearSearch(),this.setActiveIndex(this.visibleEntries.length?0:-1);return}this.deactivatePopupOverlay(!0),this.hide()}}activatePopupOverlay(){if(this.overlayHandle?.isActive()){this.overlayHandle.resume();return}this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="listbox"]'),onEscape:()=>this.dismissFromEscape(),onBackdrop:()=>this.hide(),restoreFocusTo:()=>this.renderRoot.querySelector('[part="trigger"]')})}deactivatePopupOverlay(restoreFocus){const overlay=this.overlayHandle;this.overlayHandle=void 0,overlay?.deactivate({restoreFocus}),this.popupController.unbindPointer()}syncPopup(){if(this.cleanup?.(),this.cleanup=void 0,!this.open||!this.isConnected){this.deactivatePopupOverlay(!1);return}this.activatePopupOverlay(),this.popupController.bindPointer();const anchor=this.renderRoot.querySelector(this.loadFailureTag!==void 0?'[part="form-control"]':'[part="trigger"]'),listbox=this.renderRoot.querySelector('[part="listbox"]');anchor&&listbox&&(this.placedTopLayer=syncTopLayerRelease(listbox,this.placedTopLayer,this.topLayer),this.cleanup=place(anchor,listbox,topLayerPlacement(this.topLayer,resolveEffectivePositioningStrategy(this,void 0,"fixed"))))}async settleClosedLayout(){const token=++this.closeSettleToken;await awaitPopupAnimations(this,()=>this.renderRoot.querySelector('[part="listbox"]'),()=>this.closeSettleToken===token)&&(this.listboxHidden=!0)}updated(changed){super.updated(changed),this.syncExternalDescription(),(changed.has("open")||this.open&&(changed.has("locales")||changed.has("registryTick")||changed.has("locale")||changed.has("searchQuery")||changed.has("searchable")||changed.has("loadFailureTag")||changed.has("topLayer")))&&this.syncPopup(),changed.has("open")&&(this.open?this.closeSettleToken++:this.settleClosedLayout()),this.open&&this.searchable&&changed.has("searchQuery")&&this.searchQuery.trim()&&this.visibleEntries.length===0&&(this.searchAnnouncements??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.searchAnnouncements.announce(this.localize("localePickerEmpty"))),changed.has("searchable")&&this.searchable&&shadowFocusTarget(this)===this.triggerElement&&this.queueSearchFocus(),(changed.has("touched")||changed.has("required")||changed.has("value"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}cancelLocaleLoad(){this.loadAnnouncements?.release(),this.loadAnnouncements=void 0,this.loadGeneration++,this.loadingTag=void 0,this.loadFailureTag=void 0}announceLoad(key){this.loadAnnouncements??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.loadAnnouncements.announce(key==="loading"?this.localize("loading"):this.localize("statusError"))}commit(tag){if(!(this.commitDispatching||this.liveDisabled||!this.entryFor(tag))){if(tag===this._value&&tag===getLyraLocale()){this.hide();return}this.commitDispatching=!0;try{const previousValue=this._value,version=this.valueWriteVersion,loader=this.localeLoader,generation=this.loadGeneration,detail=Object.freeze({value:tag,previousValue,direction:getLyraLocaleDirection(tag)});if(this.emit("lr-change-request",detail,{cancelable:!0}).defaultPrevented||this.liveDisabled||this.valueWriteVersion!==version||this.loadGeneration!==generation||this.localeLoader!==loader||!this.entryFor(tag))return;const commitValue=()=>{const searchFocus=this.searchElement&&shadowFocusTarget(this)===this.searchElement?this.searchElement:void 0;this.value=tag,this.hide(),setLyraLocale(tag);const committed=Object.freeze({...detail,direction:getLyraLocaleDirection(tag)});emitValueEvents(this,"input",committed,detail2=>this.emit("lr-input",detail2)),emitValueEvents(this,"change",committed,detail2=>this.emit("lr-change",detail2)),searchFocus&&this.isConnected&&this.searchable&&shadowFocusTarget(this)===searchFocus&&this.focus()};if(loader===void 0){commitValue();return}this.cancelLocaleLoad();const operation=this.loadGeneration,ownerDocument=this.ownerDocument;this.loadingTag=tag,this.announceLoad("loading");const ownsSelection=()=>this.isConnected&&this.ownerDocument===ownerDocument&&this.loadGeneration===operation&&this.valueWriteVersion===version&&this.localeLoader===loader&&!this.liveDisabled&&this.entryFor(tag)!==void 0;Promise.resolve().then(()=>{if(ownsSelection())return loader(tag)}).then(()=>{ownsSelection()&&commitValue()},()=>{ownsSelection()&&(this.loadingTag=void 0,this.loadFailureTag=tag,this.announceLoad("statusError"))})}finally{this.commitDispatching=!1}}}isSearchFocusTransfer(event){const related=event.relatedTarget;return(this.searchable||event.currentTarget===this.searchElement||related===this.searchElement)&&related!==null&&"nodeType"in related&&this.renderRoot.contains(related)}typeAhead(char){this.typeBuffer.add(char,this.effectiveLocale);const rows=this.normalizedEntries;if(!rows.length)return;const currentTag=this.open?rows[this.activeIndex]?.tag:this.previewTag,currentIndex=rows.findIndex(r=>r.tag===currentTag),match=this.typeBuffer.match(rows,currentIndex,row=>row.label,this.effectiveLocale);match!==null&&(this.open?this.setActiveIndex(match):this.commit(rows[match].tag))}setActiveIndex(index){const last=this.visibleEntries.length-1,next=last<0||index<0?-1:Math.min(last,index);this.activeIndex=next,this.queueActiveScroll()}queueActiveScroll(){const generation=++this.activeScrollGeneration,index=this.activeIndex;index<0||!this.open||this.updateComplete.then(()=>{if(generation!==this.activeScrollGeneration||!this.isConnected||!this.open||this.activeIndex!==index)return;const row=this.shadowRoot?.getElementById(`${this.listId}-opt-${index}`),popup=this.renderRoot.querySelector('[part="listbox"]');row&&popup&&revealRow(popup,row,this.searchElement?.offsetHeight)})}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`,selected=entry.tag===this._value;return html`<div
|
|
1
|
+
import{__decorate}from"tslib";import{emitValueEvents}from"../../../internal/value-events.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{acquireAnnouncementSink}from"../../../internal/announcer.js";import{acquireNativeControlDescription}from"../../../internal/native-control-description.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{deferredPlace as place,awaitPopupAnimations,syncTopLayerRelease,topLayerPlacement}from"../../../internal/anchored-overlay-runtime.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{hostAriaLabel,nextId,srOnly}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{TypeAheadBuffer}from"../../../internal/type-ahead-buffer.js";import{resolveListMove}from"../../../internal/list-navigation.js";import{getDisplayNames,resolveIntlLocale}from"../../../internal/intl-cache.js";import{activeElementIn,shadowFocusTarget}from"../../../internal/active-element.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{getLyraLocale,getLyraLocaleDirection,getRegisteredLyraLocales,subscribeLyraLocaleRegistry,setLyraLocale}from"../../../internal/localization-runtime.js";import{localeNativeName}from"../../media/flag/language-map.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./locale-picker.styles.js";import{autocorrectConverter,declaredDefaultConverter,spellcheckConverter}from"../../../internal/converters.js";import{getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{PopupController,emitPopupEvent}from"../../../internal/popup-controller.js";import{revealRow}from"../../../internal/reveal-row.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{LYRA_DEFAULT_localePickerEmpty,LYRA_DEFAULT_localePickerLabel,LYRA_DEFAULT_localePickerRequired,LYRA_DEFAULT_localePickerSearchLabel}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_loading,LYRA_DEFAULT_retry,LYRA_DEFAULT_statusError}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();const MAX_LOCALE_ENTRIES=512,localeSpellcheckConverter={...spellcheckConverter,fromAttribute:(value,type)=>value===null?void 0:spellcheckConverter.fromAttribute?.(value,type)};function snapshotLocaleCatalog(source){if(!Array.isArray(source))return Object.freeze([]);const rows=[];for(let index=0;index<Math.min(source.length,MAX_LOCALE_ENTRIES);index+=1)try{const raw=source[index];if(typeof raw=="string"){raw.length>0&&rows.push(raw);continue}if(raw===null||typeof raw!="object")continue;const candidate=raw,tag=candidate.tag,label=candidate.label,country=candidate.country;if(typeof tag!="string"||tag.length===0||label!==void 0&&typeof label!="string"||country!==void 0&&typeof country!="string")continue;rows.push(Object.freeze({tag,...label===void 0?{}:{label},...country===void 0?{}:{country}}))}catch{}return Object.freeze(rows)}class LyraLocalePicker extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,loading:LYRA_DEFAULT_loading,localePickerEmpty:LYRA_DEFAULT_localePickerEmpty,localePickerLabel:LYRA_DEFAULT_localePickerLabel,localePickerRequired:LYRA_DEFAULT_localePickerRequired,localePickerSearchLabel:LYRA_DEFAULT_localePickerSearchLabel,retry:LYRA_DEFAULT_retry,statusError:LYRA_DEFAULT_statusError}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:"value",reflect:!0,useDefault:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0}}}get localeLoader(){return this._localeLoader}set localeLoader(next){const previous=this._localeLoader;previous!==next&&(this.cancelLocaleLoad(),this._localeLoader=next,this.requestUpdate("localeLoader",previous))}get locales(){return this._locales}set locales(next){this.cancelLocaleLoad();const previous=this._locales;this._locales=next===void 0?void 0:snapshotLocaleCatalog(next),this.requestUpdate("locales",previous)}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=!!next,this.requestUpdate()}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&&!liveDisabled,this._open===old){next&&!this._open&&this.hasAttribute("open")&&this.removeAttribute("open");return}this._open||(this.activeIndex=-1,this.clearSearch()),this.requestUpdate("open",old)}constructor(){super(),this.withoutFlags=!1,this.topLayer=!1,this.triggerDisplay="flag-label",this.optionDisplay="label-tag",this.searchable=!1,this.autocomplete="off",this.inputMode="",this.enterKeyHint="",this.spellcheck=!1,this.autocapitalize="",this.autocorrectValue=!0,this.label="",this.hint="",this.errorText="",this.size="m",this.activeIndex=-1,this.searchQuery="",this.touched=!1,this.slotPresence=new SlotPresenceController(this),this.registryTick=0,this.searchFocusGeneration=0,this.listId=nextId("locale-picker-list"),this.controlId=nextId("locale-picker-control"),this.listboxHidden=!0,this.closeSettleToken=0,this.popupController=new PopupController({host:this,popup:()=>this.renderRoot.querySelector('[part="listbox"]'),emit:(name,cancelable)=>emitPopupEvent(this,name,cancelable),onPointer:event=>this.onDocPointer(event)}),this._value="",this._open=!1,this._fieldsetDisabled=!1,this._name="",this._disabled=!1,this._required=!1,this._defaultValue="",this._valueDirty=!1,this.settingDefaultValue=!1,this.reflectingDefaultValue=!1,this.typeBuffer=new TypeAheadBuffer(this),this.activeScrollGeneration=0,this.localizedValidityLocale="",this.localizedIntrinsicMessage="",this.localDescriptionIds="",this.markInteracted=()=>{this.touched||(this.touched=!0,this.syncCustomStates())},this.onDocPointer=e=>{if(!e.composedPath().includes(this)){if(this.overlayHandle?.isActive()){this.overlayHandle.dismissBackdrop();return}this.hide()}},this.commitDispatching=!1,this.valueWriteVersion=0,this.loadGeneration=0,this.retryLocaleLoad=()=>{const restoreFocus=shadowFocusTarget(this)?.getAttribute("part")==="load-retry";this.loadFailureTag!==void 0&&this.commit(this.loadFailureTag),restoreFocus&&this.loadFailureTag===void 0&&this.isConnected&&shadowFocusTarget(this)?.getAttribute("part")==="load-retry"&&this.focus()},this.onTriggerClick=()=>{this.liveDisabled||(this.open?this.hide():this.show())},this.onTriggerBlur=event=>{if(this.isSearchFocusTransfer(event)){event.stopPropagation();return}this.liveDisabled||(this.touched=!0),this.syncCustomStates(),this.hide(),relayNativeEvent(this,event)},this.onTriggerFocus=event=>{if(this.isSearchFocusTransfer(event)){event.stopPropagation();return}if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onSearchInput=event=>{event.stopPropagation(),!(!this.searchable||!this.open||this.liveDisabled)&&(this.searchQuery=event.currentTarget.value,this.setActiveIndex(this.visibleEntries.length?0:-1))},this.onSearchChange=event=>{event.stopPropagation()},this.onSearchKeyDown=event=>{if(this.liveDisabled||!this.open||event.isComposing||event.keyCode===229)return;const rows=this.visibleEntries;if(event.key==="ArrowDown"||event.key==="ArrowUp")event.preventDefault(),this.setActiveIndex(event.key==="ArrowDown"?Math.min(rows.length-1,this.activeIndex+1):Math.max(0,this.activeIndex-1));else if(event.key==="Enter"){event.preventDefault();const row=rows[this.activeIndex];row&&this.commit(row.tag)}else event.key==="Escape"&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(event.preventDefault(),this.dismissFromEscape())},this.onKeyDown=e=>{if(this.liveDisabled||e.isComposing||e.keyCode===229)return;const rows=this.visibleEntries,move=()=>resolveListMove(e,{count:rows.length,current:this.activeIndex,orientation:"vertical",wrap:!1,clamp:!0,backwardFromMissing:"first"});switch(e.key){case"ArrowDown":if(e.preventDefault(),!this.open)return this.show();this.setActiveIndex(move()??-1),this.queueSearchFocus();break;case"ArrowUp":if(e.preventDefault(),!this.open)return this.show();this.setActiveIndex(move()??-1),this.queueSearchFocus();break;case"Enter":case" ":if(this.open){e.preventDefault();const activeRow=rows[this.activeIndex];this.activeIndex>=0&&activeRow?this.commit(activeRow.tag):this.hide()}break;case"Escape":this.open&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(e.preventDefault(),this.dismissFromEscape());break;case"Home":this.open&&(e.preventDefault(),this.setActiveIndex(move()??-1));break;case"End":this.open&&(e.preventDefault(),this.setActiveIndex(move()??-1));break;default:this.typeBuffer.accepts(e)&&(this.searchable?(e.preventDefault(),this.show(),this.searchQuery+=e.key,this.setActiveIndex(this.visibleEntries.length?0:-1),this.queueSearchFocus()):this.typeAhead(e.key));break}},this.onListboxMouseDown=e=>{e.composedPath()[0]!==this.searchElement&&e.preventDefault()},this.onListboxClick=e=>{if(this.liveDisabled)return;const tag=e.target.closest('[part="option"]')?.dataset.value;tag!==void 0&&this.commit(tag)},this.validityController=new FormControlController(this,{invalid:init=>this.emit("lr-invalid",null,init),interacted:this.markInteracted,customError:()=>this.validityController.customValidityMessage}),this.internals=this.validityController.formInternals,new GlassScrollLayer(this,'[part="listbox"]',()=>this.open),this.internals.setFormValue("")}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}focus(options){this.liveDisabled||this.triggerElement?.focus(options)}blur(){this.searchElement&&shadowFocusTarget(this)===this.searchElement?this.searchElement.blur():this.triggerElement?.blur()}click(){this.liveDisabled||this.triggerElement?.click()}get input(){return this.searchable?this.searchElement??null:null}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"]')??null}syncExternalDescription(){if(!this.isConnected)return;const target=this.triggerElement??null;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.syncLocaleAttributeForLocalization(),this.updateValidity(),this.stopRegistrySubscription=subscribeLyraLocaleRegistry(()=>{this.registryTick+=1}),this.hasUpdated&&this.open&&queueMicrotask(()=>this.syncPopup())}disconnectedCallback(){this.clearSearch(),this.cancelLocaleLoad(),this.loadAnnouncements?.release(),this.loadAnnouncements=void 0,this.closeSettleToken++,this.listboxHidden=!0,this.releaseExternalDescription(),super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.deactivatePopupOverlay(!1),this.stopRegistrySubscription?.(),this.stopRegistrySubscription=void 0,this.typeBuffer.clear(),this.activeScrollGeneration+=1,this.open=!1}adoptedCallback(){this.closeSettleToken++,this.clearSearch(),this.cancelLocaleLoad(),this.loadAnnouncements?.release(),this.loadAnnouncements=void 0,super.adoptedCallback(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription(),this.cleanup?.(),this.cleanup=void 0,this.popupController.unbindPointer(),this.overlayHandle?.suspend(),this.typeBuffer.clear(),this.open&&queueMicrotask(()=>this.syncPopup())}willUpdate(changed){super.willUpdate(changed),changed.has("locale")&&this.syncLocaleAttributeForLocalization(),this.hasUpdated&&this.refreshLocalizedIntrinsicValidity(changed),changed.has("searchable")&&!this.searchable&&(this.clearSearch(),this.searchElement&&shadowFocusTarget(this)===this.searchElement&&this.focus()),changed.has("open")&&this.open&&this.setActiveIndex(this.visibleEntries.findIndex(row=>row.tag===this._value)),this.open&&(this.searchable||changed.has("locales")||changed.has("registryTick"))&&this.activeIndex>=0&&(this.activeIndex=Math.min(this.activeIndex,this.visibleEntries.length-1),this.queueActiveScroll()),this.open&&(this.listboxHidden=!1)}get value(){return this._value}set value(next){this.cancelLocaleLoad(),this.valueWriteVersion++;const old=this._value;this.settingDefaultValue||(this._valueDirty=!0),this._value=next??"",this.internals.setFormValue(this._value),this.updateValidity(),this.requestUpdate("value",old)}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next??"",this.reflectingDefaultValue=!0;try{this._defaultValue?this.setAttribute("value",this._defaultValue):this.removeAttribute("value")}finally{this.reflectingDefaultValue=!1}this._valueDirty||this.restoreLiveValueFromDefault(),this.requestUpdate("defaultValue",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",reflectFormName(this,this._name),this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){next&&this.cancelLocaleLoad();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 effectiveDisabled(){return this.disabled||this._fieldsetDisabled}updateValidity(){this.localizedValidityLocale=this.effectiveMessageLocale;const valueMissing=this.hasMissingRequiredValue(),message=valueMissing?this.localize("localePickerRequired"):"";this.localizedIntrinsicMessage=message,valueMissing?this.validityController.setValidity({valueMissing:!0},message):this.validityController.setValidity({}),this.syncCustomStates()}refreshLocalizedIntrinsicValidity(changed){const locale=this.effectiveMessageLocale,message=this.hasMissingRequiredValue()?this.localize("localePickerRequired"):"";(changed.has("strings")||locale!==this.localizedValidityLocale||message!==this.localizedIntrinsicMessage)&&this.updateValidity()}hasMissingRequiredValue(){return!this.isBarred()&&this.required&&!this._value}syncLocaleAttributeForLocalization(){this.locale?this.getAttribute("locale")!==this.locale&&this.setAttribute("locale",this.locale):this.hasAttribute("locale")&&this.removeAttribute("locale")}isBarred(){return isBarredFromValidation(this,this.internals)}syncCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.isBarred()})}formResetCallback(){this.touched=!1,this.clearSearch(),this.restoreLiveValueFromDefault()}restoreLiveValueFromDefault(){this.settingDefaultValue=!0;try{this.value=this._defaultValue}finally{this.settingDefaultValue=!1}this._valueDirty=!1}formStateRestoreCallback(state2,_mode){this.value=typeof state2=="string"?state2:""}formDisabledCallback(disabled){this.validityController?.reflectingDisabled||(disabled&&this.cancelLocaleLoad(),this._fieldsetDisabled=disabled,disabled&&this.hide(),this.updateValidity(),this.requestUpdate())}checkValidity(){return this.validityController.checkValidity()}reportValidity(){return this.validityController.syncConstraints(),this.touched=!0,this.syncCustomStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncCustomStates(),this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),this.requestUpdate()}get normalizedEntries(){const raw=this.locales,cached=this.entriesCache;if(cached&&cached.raw===raw&&cached.tick===this.registryTick)return cached.rows;const rows=raw!==void 0?raw.map(entry=>typeof entry=="string"?{tag:entry,label:localeNativeName(entry)}:{tag:entry.tag,label:entry.label!==void 0&&entry.label.trim().length>0?entry.label:localeNativeName(entry.tag),country:entry.country}):getRegisteredLyraLocales().map(tag=>({tag,label:localeNativeName(tag)}));return this.entriesCache={raw,tick:this.registryTick,rows},rows}normalizeSearch(text,locale){return text.toLocaleLowerCase(resolveIntlLocale(locale)).normalize("NFKD").replace(/\p{M}/gu,"").trim()}get visibleEntries(){const rows=this.normalizedEntries;if(!this.searchable)return rows;const locale=this.effectiveLocale,query2=this.normalizeSearch(this.searchQuery,locale);if(!query2)return rows;const cached=this.visibleCache;if(cached&&cached.rows===rows&&cached.query===this.searchQuery&&cached.locale===locale)return cached.result;let names;try{names=getDisplayNames(locale,{type:"language"})}catch{}let englishNames;try{englishNames=getDisplayNames("en",{type:"language"})}catch{}const invariantQuery=this.normalizeSearch(this.searchQuery,"en"),result=rows.filter(row=>{let localizedName="";try{localizedName=names?.of(row.tag)??""}catch{}let englishName="";try{englishName=englishNames?.of(row.tag)??""}catch{}return[row.label,localeNativeName(row.tag),localizedName].some(text=>this.normalizeSearch(text,locale).includes(query2))||[row.tag,englishName].some(text=>this.normalizeSearch(text,"en").includes(invariantQuery))});return this.visibleCache={rows,query:this.searchQuery,locale,result},result}clearSearch(){this.searchQuery="",this.searchFocusGeneration++,this.searchAnnouncements?.release(),this.searchAnnouncements=void 0}queueSearchFocus(){if(!this.searchable||!this.open||this.liveDisabled)return;const generation=++this.searchFocusGeneration,ownerDocument=this.ownerDocument,outerFocus=activeElementIn(ownerDocument),innerFocus=shadowFocusTarget(this);this.updateComplete.then(()=>{generation!==this.searchFocusGeneration||!this.isConnected||!this.open||!this.searchable||this.liveDisabled||this.ownerDocument!==ownerDocument||activeElementIn(ownerDocument)!==outerFocus||shadowFocusTarget(this)!==innerFocus||this.searchElement?.focus()})}get previewTag(){return this._value||this.effectiveLocale}entryFor(tag){return this.normalizedEntries.find(e=>e.tag===tag)}labelFor(tag){return this.entryFor(tag)?.label??localeNativeName(tag)}show(){this.open||this.liveDisabled||(this.open=!0,this.queueSearchFocus())}hide(){this.open&&(this.open=!1,this.setActiveIndex(-1))}dismissFromEscape(){if(this.open){if(this.searchable&&this.searchQuery.length){this.clearSearch(),this.setActiveIndex(this.visibleEntries.length?0:-1);return}this.deactivatePopupOverlay(!0),this.hide()}}activatePopupOverlay(){if(this.overlayHandle?.isActive()){this.overlayHandle.resume();return}this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="listbox"]'),onEscape:()=>this.dismissFromEscape(),onBackdrop:()=>this.hide(),restoreFocusTo:()=>this.renderRoot.querySelector('[part="trigger"]')})}deactivatePopupOverlay(restoreFocus){const overlay=this.overlayHandle;this.overlayHandle=void 0,overlay?.deactivate({restoreFocus}),this.popupController.unbindPointer()}syncPopup(){if(this.cleanup?.(),this.cleanup=void 0,!this.open||!this.isConnected){this.deactivatePopupOverlay(!1);return}this.activatePopupOverlay(),this.popupController.bindPointer();const anchor=this.renderRoot.querySelector(this.loadFailureTag!==void 0?'[part="form-control"]':'[part="trigger"]'),listbox=this.renderRoot.querySelector('[part="listbox"]');anchor&&listbox&&(this.placedTopLayer=syncTopLayerRelease(listbox,this.placedTopLayer,this.topLayer),this.cleanup=place(anchor,listbox,topLayerPlacement(this.topLayer,resolveEffectivePositioningStrategy(this,void 0,"fixed"))))}async settleClosedLayout(){const token=++this.closeSettleToken;await awaitPopupAnimations(this,()=>this.renderRoot.querySelector('[part="listbox"]'),()=>this.closeSettleToken===token)&&(this.listboxHidden=!0)}updated(changed){super.updated(changed),this.syncExternalDescription(),(changed.has("open")||this.open&&(changed.has("locales")||changed.has("registryTick")||changed.has("locale")||changed.has("searchQuery")||changed.has("searchable")||changed.has("loadFailureTag")||changed.has("topLayer")))&&this.syncPopup(),changed.has("open")&&(this.open?this.closeSettleToken++:this.settleClosedLayout()),this.open&&this.searchable&&changed.has("searchQuery")&&this.searchQuery.trim()&&this.visibleEntries.length===0&&(this.searchAnnouncements??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.searchAnnouncements.announce(this.localize("localePickerEmpty"))),changed.has("searchable")&&this.searchable&&shadowFocusTarget(this)===this.triggerElement&&this.queueSearchFocus(),(changed.has("touched")||changed.has("required")||changed.has("value"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}cancelLocaleLoad(){this.loadAnnouncements?.release(),this.loadAnnouncements=void 0,this.loadGeneration++,this.loadingTag=void 0,this.loadFailureTag=void 0}announceLoad(key){this.loadAnnouncements??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.loadAnnouncements.announce(key==="loading"?this.localize("loading"):this.localize("statusError"))}commit(tag){if(!(this.commitDispatching||this.liveDisabled||!this.entryFor(tag))){if(tag===this._value&&tag===getLyraLocale()){this.hide();return}this.commitDispatching=!0;try{const previousValue=this._value,version=this.valueWriteVersion,loader=this.localeLoader,generation=this.loadGeneration,detail=Object.freeze({value:tag,previousValue,direction:getLyraLocaleDirection(tag)});if(this.emit("lr-change-request",detail,{cancelable:!0}).defaultPrevented||this.liveDisabled||this.valueWriteVersion!==version||this.loadGeneration!==generation||this.localeLoader!==loader||!this.entryFor(tag))return;const commitValue=()=>{const searchFocus=this.searchElement&&shadowFocusTarget(this)===this.searchElement?this.searchElement:void 0;this.value=tag,this.hide(),setLyraLocale(tag);const committed=Object.freeze({...detail,direction:getLyraLocaleDirection(tag)});emitValueEvents(this,"input",committed,detail2=>this.emit("lr-input",detail2)),emitValueEvents(this,"change",committed,detail2=>this.emit("lr-change",detail2)),searchFocus&&this.isConnected&&this.searchable&&shadowFocusTarget(this)===searchFocus&&this.focus()};if(loader===void 0){commitValue();return}this.cancelLocaleLoad();const operation=this.loadGeneration,ownerDocument=this.ownerDocument;this.loadingTag=tag,this.announceLoad("loading");const ownsSelection=()=>this.isConnected&&this.ownerDocument===ownerDocument&&this.loadGeneration===operation&&this.valueWriteVersion===version&&this.localeLoader===loader&&!this.liveDisabled&&this.entryFor(tag)!==void 0;Promise.resolve().then(()=>{if(ownsSelection())return loader(tag)}).then(()=>{ownsSelection()&&commitValue()},()=>{ownsSelection()&&(this.loadingTag=void 0,this.loadFailureTag=tag,this.announceLoad("statusError"))})}finally{this.commitDispatching=!1}}}isSearchFocusTransfer(event){const related=event.relatedTarget;return(this.searchable||event.currentTarget===this.searchElement||related===this.searchElement)&&related!==null&&"nodeType"in related&&this.renderRoot.contains(related)}typeAhead(char){this.typeBuffer.add(char,this.effectiveLocale);const rows=this.normalizedEntries;if(!rows.length)return;const currentTag=this.open?rows[this.activeIndex]?.tag:this.previewTag,currentIndex=rows.findIndex(r=>r.tag===currentTag),match=this.typeBuffer.match(rows,currentIndex,row=>row.label,this.effectiveLocale);match!==null&&(this.open?this.setActiveIndex(match):this.commit(rows[match].tag))}setActiveIndex(index){const last=this.visibleEntries.length-1,next=last<0||index<0?-1:Math.min(last,index);this.activeIndex=next,this.queueActiveScroll()}queueActiveScroll(){const generation=++this.activeScrollGeneration,index=this.activeIndex;index<0||!this.open||this.updateComplete.then(()=>{if(generation!==this.activeScrollGeneration||!this.isConnected||!this.open||this.activeIndex!==index)return;const row=this.shadowRoot?.getElementById(`${this.listId}-opt-${index}`),popup=this.renderRoot.querySelector('[part="listbox"]');row&&popup&&revealRow(popup,row,this.searchElement?.offsetHeight)})}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`,selected=entry.tag===this._value;return html`<div
|
|
2
2
|
part="option"
|
|
3
3
|
id=${id}
|
|
4
4
|
role="option"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{requestThenCommit}from"../../../internal/request-commit.js";import{VetoWriteGuard,markVetoGuardWrite}from"../../../internal/veto-write-guard.js";import{renderFormControlHintError}from"../../../internal/form-control-template.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{FormControlController,reflectFormName}from"../../../internal/form-control-controller.js";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{acquireNativeControlDescription}from"../../../internal/native-control-description.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{deferredPlaceReady as place,syncTopLayerRelease,topLayerPlacement}from"../../../internal/anchored-overlay-runtime.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{chevronIcon,closeIcon}from"../../../internal/icons.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{PopupController,emitPopupEvent}from"../../../internal/popup-controller.js";import{revealRow}from"../../../internal/reveal-row.js";import{TypeAheadBuffer}from"../../../internal/type-ahead-buffer.js";import{resolveListMove}from"../../../internal/list-navigation.js";import{finiteCount}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{styles}from"./select.styles.js";import{sizes}from"../../../internal/sizes.styles.js";import"../combobox/option.class.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{omittedEmptyStringConverter,optionalLiteralSetConverter}from"../../../internal/converters.js";import{getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{isOptionSelectedDirty,isOptionSelectedWrite,wasOptionInitiallySelected,RESET_OPTION_SELECTED_FROM_OWNER,SET_OPTION_SELECTED_FROM_OWNER}from"../../../internal/option-selection.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{tag}from"../../../internal/prefix.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_selectSelectedOverflow,LYRA_DEFAULT_selectValueMissing}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_loading,LYRA_DEFAULT_notInCatalog,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();function isLyraOptionElement(value){return isHtmlElement(value)&&value.localName===tag("option")}function normalizeSelectionValues(next){return Array.isArray(next)?next.filter(value=>typeof value=="string"):typeof next=="string"?[next]:[]}const POSITIONING_STRATEGY=optionalLiteralSetConverter(["absolute","fixed"]);class LyraSelect extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,loading:LYRA_DEFAULT_loading,notInCatalog:LYRA_DEFAULT_notInCatalog,removeWithContext:LYRA_DEFAULT_removeWithContext,select:LYRA_DEFAULT_select,selectSelectedOverflow:LYRA_DEFAULT_selectSelectedOverflow,selectValueMissing:LYRA_DEFAULT_selectValueMissing}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-input","lr-change","lr-change-request"])}static{this.identityEventDetailCollectionItems=Object.freeze({"lr-input":Object.freeze(["data"]),"lr-change":Object.freeze(["data"]),"lr-change-request":Object.freeze(["data"])})}static get validators(){return[currentValidityValidator("required","disabled","value","multiple")]}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles,srOnly]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},multiple:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},value:{noAccessor:!0},name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},maxOptionsVisible:{type:Number,attribute:"max-options-visible",noAccessor:!0},defaultValue:{attribute:"default-value",noAccessor:!0}}}get open(){return this._open}set open(next){const requested=!!next,normalized=requested&&!this.effectiveDisabled;if(normalized===this._open){requested!==normalized&&this.hasAttribute("open")&&this.removeAttribute("open");return}this.applyOpenState(normalized)}get positioningStrategy(){return this._positioningStrategy??"absolute"}set positioningStrategy(next){const normalized=POSITIONING_STRATEGY.normalize(next)??"absolute",old=this.positioningStrategy;this._positioningStrategy=normalized,normalized!==old&&(this.requestUpdate("positioningStrategy",old),old==="fixed"!=(normalized==="fixed")&&this.requestUpdate("hoist",old==="fixed"))}get hoist(){return this.positioningStrategy==="fixed"}set hoist(next){this.positioningStrategy=next?"fixed":"absolute"}focus(options){this.effectiveDisabled||this.triggerElement?.focus(options)}blur(){this.triggerElement?.blur()}click(){this.effectiveDisabled||this.triggerElement?.click()}constructor(){super(),this.placeholder="",this.label="",this.hint="",this.helpText="",this.withLabel=!1,this.withHint=!1,this.errorText="",this.autofocus=!1,this.title="",this._open=!1,this.size="m",this.appearance="outlined",this.pill=!1,this.placement="bottom",this.topLayer=!1,this.filled=!1,this.withClear=!1,this.clearable=!1,this.withUnknownOption=!1,this.loading=!1,this.autoCommitSingleOption=!1,this.activeIndex=-1,this.options=[],this.optionsObserved=!1,this.touched=!1,this.hasInteracted=!1,this.slotPresence=new SlotPresenceController(this),this._fieldsetDisabled=!1,this.listId=nextId("select-list"),this.triggerId=nextId("select-trigger"),this.valueTextId=nextId("select-value"),this.positioningReady=Promise.resolve(!1),this.restoreFocusOnClose=!0,this.popupController=new PopupController({host:this,popup:()=>this.renderRoot.querySelector('[part="listbox"]'),emit:(name,cancelable)=>emitPopupEvent(this,name,cancelable),onPointer:event=>this.onDocPointer(event)}),this.listboxHidden=!0,this.listboxRendered=!1,this.listboxPositioned=!1,this._isFirstUpdate=!0,this.openVetoed=!1,this.previousValue="",this.openStateGeneration=0,this._selected=[],this._selectedOptions=[],this._selectedValuesByOption=new Map,this.adornmentClones=new WeakMap,this._multiple=!1,this._disabled=!1,this._required=!1,this._defaultSelected=[],this._defaultSelectedOptions=[],this._defaultCaptured=!1,this._valueDirty=!1,this._restoredStateActive=!1,this._resolvingPendingInitialSelection=!1,this._defaultValueDirty=!1,this.typeBuffer=new TypeAheadBuffer(this),this._name="",this._maxOptionsVisible=3,this.localDescriptionIds="",this.markInteracted=()=>{this.hasInteracted||(this.hasInteracted=!0,this.reflectValidityStates())},this.collectOptions=e=>{this.collectOptionsFromSlot(e.target)},this.unknownOptionCache=new Map,this.optionRefreshPending=!1,this.onOptionChange=e=>{e.stopPropagation();const option=e.composedPath().find(isLyraOptionElement);if(isLyraOptionElement(option)&&this.options.includes(option)&&isOptionSelectedWrite(e)){markVetoGuardWrite(this.selectionWriteGuard),this._valueDirty=!0,this._restoredStateActive=!1;const selected=this._selectedOptions.includes(option);if(option.selected===selected&&(!selected||this._selectedValuesByOption.get(option)===option.value))return;if(option.selected&&!this.multiple){this.setSelection([option.value],[option]);return}const remaining=[...this._selectedOptions],preferred=this._selected.map(value=>{const index2=remaining.findIndex(candidate=>this._selectedValuesByOption.get(candidate)===value);return index2<0?void 0:remaining.splice(index2,1)[0]}),values=[...this._selected],index=preferred.indexOf(option);if(option.selected)index<0?(values.push(option.value),preferred.push(option)):values[index]=option.value;else{if(index<0)return;values.splice(index,1),preferred.splice(index,1)}this.setSelection(values,preferred);return}if(isLyraOptionElement(option)&&this.adornmentClones.get(option)?.markup!==this.adornmentMarkup(option)&&this.adornmentClones.delete(option),this.optionRefreshPending)return;this.optionRefreshPending=!0;const previousActive=this.activeOption,previousActiveRawIndex=previousActive?this.options.indexOf(previousActive):this.activeIndex;queueMicrotask(()=>{this.optionRefreshPending=!1,this.refreshOptionDefaults(),this.reflectSelected(),this.options=[...this.options],this.reconcileActiveOption(previousActive,previousActiveRawIndex)})},this.onDocPointer=e=>{if(!e.composedPath().includes(this)){if(this.overlayHandle?.isActive()){this.overlayHandle.dismissBackdrop();return}this.restoreFocusOnClose=!1,this.hide()}},this.selectionWriteGuard=new VetoWriteGuard,this.selectionRequestDispatching=!1,this.onTriggerClick=()=>{if(!this.effectiveDisabled){if(this.onlyOption)return this.selectOption(this.onlyOption);this.open?this.hide():this.show()}},this.onTriggerBlur=event=>{this.effectiveDisabled||(this.touched=!0,this.hasInteracted=!0,this.reflectValidityStates()),this.open&&(this.restoreFocusOnClose=!1),this.hide(),relayNativeEvent(this,event)},this.onTriggerFocus=event=>{relayNativeEvent(this,event)},this.onKeyDown=e=>{if(e.isComposing||e.keyCode===229)return;const navigable=this.navigableOptions(),move=()=>resolveListMove(e,{count:navigable.length,current:this.activeIndex,orientation:"vertical",wrap:!1,clamp:!0,backwardFromMissing:"first"});switch(e.key){case"ArrowDown":if(e.preventDefault(),this.onlyOption)return this.selectOption(this.onlyOption);if(!this.open){this.show();return}this.setActiveIndex(move()??-1,navigable);break;case"ArrowUp":if(e.preventDefault(),this.onlyOption)return this.selectOption(this.onlyOption);if(!this.open){this.show();return}this.setActiveIndex(move()??-1,navigable);break;case"Enter":case" ":if(this.open){e.preventDefault();const active=navigable[this.activeIndex];this.activeIndex>=0&&active?this.selectOption(active):this.hide()}break;case"Escape":this.open&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(e.preventDefault(),this.hide());break;case"Home":this.open&&(e.preventDefault(),this.setActiveIndex(move()??-1,navigable));break;case"End":this.open&&(e.preventDefault(),this.setActiveIndex(move()??-1,navigable));break;case"Backspace":case"Delete":this.multiple&&this._selected.length>0&&(e.preventDefault(),this.removeValueAt(this._selected.length-1));break;default:this.typeBuffer.accepts(e)&&this.typeAhead(e.key);break}},this.onListboxMouseDown=e=>{e.preventDefault()},this.onListboxClick=e=>{const optionEl=e.target.closest('[part="option"]'),index=Number(optionEl?.dataset.index);if(!Number.isInteger(index))return;const option=this.listboxOptions[index];option&&this.selectOption(option)},this.validityController=new FormControlController(this,{invalid:init=>this.emit("lr-invalid",null,init),interacted:this.markInteracted,customError:()=>this.validityController.customValidityMessage}),this.internals=this.validityController.formInternals,new GlassScrollLayer(this,'[part="listbox"]',()=>this.open),this.syncFormValue()}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"]')??null}syncExternalDescription(){if(!this.isConnected)return;const target=this.renderRoot.querySelector('[part="trigger"]');target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireNativeControlDescription(this,target,()=>this.localDescriptionIds))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.updateValidity(),this.hasUpdated&&this.open&&queueMicrotask(()=>this.reconnectOpenPopup())}willUpdate(changed){if(super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,this._isFirstUpdate&&(this._pendingInitialDefaultValue!==void 0||this._pendingInitialValue!==void 0||this._pendingInitialSelectedOptions!==void 0)){this._resolvingPendingInitialSelection=!0;try{if(this._pendingInitialDefaultValue!==void 0){const pending=this._pendingInitialDefaultValue;this._pendingInitialDefaultValue=void 0,this.assignDefaultValue(pending)}if(this._pendingInitialValue!==void 0){const pending=this._pendingInitialValue;this._pendingInitialValue=void 0,this.assignValue(pending)}if(this._pendingInitialSelectedOptions!==void 0){const pending=this._pendingInitialSelectedOptions;this._pendingInitialSelectedOptions=void 0,this.selectedOptions=pending}}finally{this._resolvingPendingInitialSelection=!1}}if(this.announceOpenTransition(changed),changed.has("open")&&!this.openVetoed&&(this.listboxPositioned=!1),this.open&&(this.listboxHidden=!1,this.listboxRendered=!0),changed.has("open")&&!this.openVetoed){const navigable=this.navigableOptions();this.setActiveIndex(this.open?navigable.findIndex(option=>this._selectedOptions.includes(option)):-1,navigable)}}firstUpdated(changed){super.firstUpdated(changed);const slot=this.optionsSlot;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>{const assigned=s.assignedElements({flatten:!0});this.optionsObserved=!0,assigned.some(isLyraOptionElement)&&this.collectOptionsFromSlot(s)})})}applyOpenState(next){const old=this._open;this.pendingOpenTransitionStart===void 0&&(this.pendingOpenTransitionStart=old),this.openStateGeneration++,this._open=next,this.requestUpdate("open",old)}forceCloseOpenState(){this.listboxHidden=!0;const isClosing=this._open||this.pendingOpenTransitionStart===!0;if(this.popupController.cancel(),!this._open){isClosing&&(this.suppressedOpenLifecycleGeneration=this.openStateGeneration),this.hasAttribute("open")&&this.removeAttribute("open");return}this.applyOpenState(!1),this.suppressedOpenLifecycleGeneration=this.openStateGeneration}announceOpenTransition(changed){if(this.openVetoed=!1,!(!changed.has("open")||this._isFirstUpdate||this.suppressedOpenLifecycleGeneration===this.openStateGeneration)){if(!this.isConnected){emitPopupEvent(this,"lr-hide",!1);return}this.openVetoed=this.popupController.announce(this.open,()=>{this.open=!this.open})}}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",reflectFormName(this,this._name),this.syncFormValue(),this.requestUpdate("name",old)}get multiple(){return this._multiple}set multiple(next){markVetoGuardWrite(this.selectionWriteGuard);const old=this._multiple;this._multiple=!!next,this.toggleAttribute("multiple",this._multiple),!this._multiple&&this._selected.length>1?this.setSelection(this._selected.slice(0,1),this._selectedOptions.slice(0,1)):this.syncFormValue(),this.requestUpdate("multiple",old)}get maxOptionsVisible(){return this._maxOptionsVisible}set maxOptionsVisible(next){const old=this._maxOptionsVisible;this._maxOptionsVisible=finiteCount(next,3),this.requestUpdate("maxOptionsVisible",old)}get disabled(){return this._disabled}set disabled(next){markVetoGuardWrite(this.selectionWriteGuard);const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this._disabled&&this.forceCloseOpenState(),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get value(){return this.multiple?[...this._selected]:this._selected[0]??""}set value(next){!this.hasUpdated&&!this._resolvingPendingInitialSelection&&(this._pendingInitialValue=next),this._restoredStateActive=!1,this._valueDirty=!0;const values=normalizeSelectionValues(next);this.setSelection(values,values.map(value=>this.options.find(option=>option.value===value)))}get defaultValue(){return this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??""}set defaultValue(next){!this.hasUpdated&&!this._resolvingPendingInitialSelection&&(this._pendingInitialDefaultValue=next),this._defaultValueDirty=!0;const old=this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??"",values=normalizeSelectionValues(next);this._defaultSelected=this.multiple?[...values]:values.slice(0,1),this._defaultSelectedOptions=this.resolveOccurrences(this._defaultSelected),!this._valueDirty&&!this._restoredStateActive&&this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions]),this.requestUpdate("defaultValue",old)}get selectedOptions(){return[...this._selectedOptions]}set selectedOptions(next){!this.hasUpdated&&!this._resolvingPendingInitialSelection&&(this._pendingInitialSelectedOptions=next),this._restoredStateActive=!1,this._valueDirty=!0;const candidates=Array.isArray(next)?next:[],live=candidates.filter((option,index)=>isLyraOptionElement(option)&&this.contains(option)&&this.options.includes(option)&&candidates.indexOf(option)===index),selected=this.multiple?live:live.slice(0,1);this.setSelection(selected.map(option=>option.value),selected)}get selectedData(){return this.resolveOccurrenceSlots(this._selected,this._selectedOptions).map(option=>option?.data)}setSelection(next,preferred=[]){markVetoGuardWrite(this.selectionWriteGuard);const values=this.multiple?[...next]:next.slice(0,1),previousValues=this._selected,previousOptions=this._selectedOptions,old=this.multiple?[...previousValues]:previousValues[0]??"";this.previousValue=old,this._selected=values,this._selectedOptions=this.resolveOccurrences(values,preferred),this.syncFormValue(),this.reflectSelected(),this.updateValidity(),this.requestUpdate("value",old);const sameValues=previousValues.length===values.length&&previousValues.every((value,i)=>value===values[i]),sameOptions=previousOptions.length===this._selectedOptions.length&&previousOptions.every((option,i)=>option===this._selectedOptions[i]);sameValues&&!sameOptions&&this.requestUpdate()}resolveOccurrences(values,preferred=[]){return this.resolveOccurrenceSlots(values,preferred).filter(option=>option!==void 0)}resolveOccurrenceSlots(values,preferred=[]){const claimed=new Set;return values.map((value,index)=>{const hint=preferred.length===values.length?preferred[index]:preferred.find(option=>option?.value===value&&!claimed.has(option)),match=hint&&hint.value===value&&this.options.includes(hint)&&!claimed.has(hint)?hint:this.options.find(option=>option.value===value&&!claimed.has(option));if(match)return claimed.add(match),match})}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){this.barredFromValidation?this.validityController.setValidity({}):this.required&&this._selected.length===0?this.validityController.setValidity({valueMissing:!0},this.localize("selectValueMissing")):this.validityController.setValidity({}),this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",this._selected.length===0)}syncFormValue(){if(!this.multiple){this.internals.setFormValue(this._selected[0]??"");return}const state2=JSON.stringify(this._selected);if(!this.name){this.internals.setFormValue(null,state2);return}const data=new FormData;for(const value of this._selected)data.append(this.name,value);this.internals.setFormValue(data,state2)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formResetCallback(){this.touched=!1,this.hasInteracted=!1,this._restoredStateActive=!1,this._valueDirty=!1;const resetOptions=this._defaultSelectedOptions.length>0?this._defaultSelectedOptions:this.options.filter(option=>wasOptionInitiallySelected(option));this._defaultSelectedOptions.length===0&&resetOptions.length>0&&(this._defaultSelectedOptions=[...resetOptions],this._defaultSelected=resetOptions.map(option=>option.value));const defaults=new Set(resetOptions);for(const option of this.options)option[RESET_OPTION_SELECTED_FROM_OWNER](defaults.has(option));this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}formStateRestoreCallback(state2,reason){if(!this.multiple)this.assignValue(typeof state2=="string"?state2:void 0);else{let restored=[];if(typeof state2=="string")try{const parsed=JSON.parse(state2);Array.isArray(parsed)&&parsed.every(entry=>typeof entry=="string")&&(restored=parsed)}catch{}this.assignValue(restored)}this._restoredStateActive=!0,this._valueDirty=!0}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;markVetoGuardWrite(this.selectionWriteGuard);const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(disabled&&this.forceCloseOpenState(),this.updateValidity(),this.requestUpdate())}checkValidity(){return this.validityController.checkValidity(()=>this.updateValidity())}reportValidity(){return this.validityController.syncConstraints(),this.updateValidity(),this.hasInteracted=!0,this.reflectValidityStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.reflectValidityStates()}resetValidity(){this.setCustomValidity("")}disconnectedCallback(){markVetoGuardWrite(this.selectionWriteGuard),this.listboxHidden=!0,this.releaseExternalDescription(),this.popupController.cancel(),super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.typeBuffer.clear(),this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.popupController.unbindPointer(),this.open=!1}adoptedCallback(){markVetoGuardWrite(this.selectionWriteGuard),super.adoptedCallback(),this.popupController.cancel(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription(),this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.popupController.unbindPointer(),this.typeBuffer.clear(),queueMicrotask(()=>this.reconnectOpenPopup())}collectOptionsFromSlot(slot){const previous=new Set(this.options),previousActive=this.activeOption,previousActiveRawIndex=previousActive?this.options.indexOf(previousActive):this.activeIndex;if(this.options=slot.assignedElements({flatten:!0}).filter(isLyraOptionElement),this.optionsObserved=!0,this.adornmentClones=new WeakMap,this.reconcileActiveOption(previousActive,previousActiveRawIndex),this._defaultCaptured){const newDefaults=this.options.filter(option=>!previous.has(option)&&option.defaultSelected),newLive=this.options.filter(option=>!previous.has(option)&&option.selected&&!option.defaultSelected);this.refreshOptionDefaults();const eligible=[...!this._restoredStateActive&&!this._valueDirty?newDefaults:[],...this._restoredStateActive?[]:newLive];if(eligible.length>0){const added=this.multiple?eligible:eligible.slice(-1),occurrences=this.multiple?[...new Set([...this._selectedOptions,...added])]:added;newLive.length>0&&(this._valueDirty=!0),this.setSelection(occurrences.map(option=>option.value),occurrences);return}}else{this._defaultCaptured=!0;const explicitDefault=this.hasAttribute("default-value")||this._defaultValueDirty,allDefaults=this.options.filter(option=>option.defaultSelected),defaults=this.multiple?allDefaults:allDefaults.slice(0,1),allLive=this.options.filter(option=>option.selected),live=this.multiple?allLive:allLive.slice(0,1),initialLive=this.options.filter(option=>wasOptionInitiallySelected(option)),optionDirty=this.options.some(option=>isOptionSelectedDirty(option)),dirtySelected=this.options.filter(option=>isOptionSelectedDirty(option)&&option.selected);if(explicitDefault)this._defaultSelectedOptions=this.resolveOccurrences(this._defaultSelected);else{const resetOptions=defaults.length>0?defaults:initialLive.length>0?initialLive:live;this._defaultSelected=resetOptions.map(option=>option.value),this._defaultSelectedOptions=[...resetOptions]}const fromDefaults=explicitDefault||defaults.length>0,initial=optionDirty?this.multiple?allLive:dirtySelected.slice(-1)[0]?dirtySelected.slice(-1):live:explicitDefault?this._defaultSelectedOptions:fromDefaults?defaults:live;if(initial.length>0&&!this._restoredStateActive&&!this._valueDirty){(!fromDefaults||optionDirty)&&(this._valueDirty=!0),this.setSelection(initial.map(option=>option.value),[...initial]);return}if(optionDirty&&(this._valueDirty=!0),explicitDefault&&!this._valueDirty&&!this._restoredStateActive){this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions]);return}}this.reflectSelected()}refreshOptionDefaults(){if(this.hasAttribute("default-value")||this._defaultValueDirty)return;const declared=this.options.filter(option=>option.defaultSelected),defaults=this.multiple?declared:declared.slice(0,1);this._defaultSelected=defaults.map(option=>option.value),this._defaultSelectedOptions=[...defaults],!this._valueDirty&&!this._restoredStateActive&&this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}reflectSelected(){this._selectedOptions=this.resolveOccurrences(this._selected,this._selectedOptions),this._selectedValuesByOption=new Map(this._selectedOptions.map(option=>[option,option.value]));const chosen=new Set(this._selectedOptions);for(const option of this.options)option[SET_OPTION_SELECTED_FROM_OWNER](chosen.has(option))}selectUnknownValue(value){if(!(this.selectionRequestDispatching||this.effectiveDisabled)){if(this.multiple){const index=this._selected.indexOf(value),values=index>=0?this._selected.filter((_,position)=>position!==index):[...this._selected,value];this.requestSelection(values,this.resolveOccurrenceSlots(values,this._selectedOptions),()=>{this.emitValueEvents(),this.emit("lr-activate",{value})});return}this.hide(),this.emit("lr-activate",{value})}}resolvedLabelFor(value,occurrenceIndex=0){const option=(this._selectedOptions[occurrenceIndex]?.value===value?this._selectedOptions[occurrenceIndex]:void 0)??this._selectedOptions.find(candidate=>candidate.value===value)??this.options.find(candidate=>candidate.value===value);return option&&(option.label||option.value)}labelFor(value,occurrenceIndex=0){const resolved=this.resolvedLabelFor(value,occurrenceIndex);if(resolved!==void 0)return resolved;if(this.loading)return this.localize("loading");const override=this.optionsObserved?this.getUnknownLabel?.(value):void 0;return override!==void 0&&override.trim().length>0?override:value}isUnknownValue(value,occurrenceIndex=0){return!this.optionsObserved||this.loading||value===""?!1:this.resolvedLabelFor(value,occurrenceIndex)===void 0}get onlyOption(){if(!this.autoCommitSingleOption)return;const navigable=this.navigableOptions(this.options);return navigable.length===1?navigable[0]:void 0}isOptionAvailable(option){return!option.disabled&&!option.inert&&!option.closest("[inert]")}navigableOptions(options=this.listboxOptions){return options.filter(option=>this.isOptionAvailable(option))}get unknownValues(){return this.withUnknownOption?this._selected.filter((value,index)=>this.isUnknownValue(value,index)):[]}get unknownOptions(){const values=this.unknownValues;if(values.length===0)return this.unknownOptionCache.clear(),[];for(const key of[...this.unknownOptionCache.keys()])values.includes(key)||this.unknownOptionCache.delete(key);return values.map(value=>{let option=this.unknownOptionCache.get(value);return option||(option=this.ownerDocument.createElement(tag("option")),this.unknownOptionCache.set(value,option)),option.value=value,option.label=this.labelFor(value),option})}get listboxOptions(){const unknown=this.unknownOptions;return unknown.length===0?this.options:[...this.options,...unknown]}setActiveIndex(next,navigable=this.navigableOptions()){if(next<0||navigable.length===0){this.activeIndex=-1,this.activeOption=void 0;return}const index=Math.min(next,navigable.length-1);this.activeIndex=index,this.activeOption=navigable[index]}reconcileActiveOption(previousActive,previousRawIndex){if(!previousActive&&this.activeIndex<0)return;const navigable=this.navigableOptions();if(previousActive){const preservedIndex=navigable.indexOf(previousActive);if(preservedIndex>=0){this.setActiveIndex(preservedIndex,navigable);return}}if(navigable.length===0){this.setActiveIndex(-1,navigable);return}const pivot=Math.max(0,previousRawIndex);let nearestIndex=0,nearestDistance=Number.POSITIVE_INFINITY,nearestRawIndex=-1;navigable.forEach((option,index)=>{const rawIndex=this.listboxOptions.indexOf(option),distance=Math.abs(rawIndex-pivot);(distance<nearestDistance||distance===nearestDistance&&rawIndex>=pivot&&nearestRawIndex<pivot)&&(nearestIndex=index,nearestDistance=distance,nearestRawIndex=rawIndex)}),this.setActiveIndex(nearestIndex,navigable)}show(){if(this.open||this.effectiveDisabled)return Promise.resolve();const settled=this.popupController.wait(!0);return this.open=!0,settled}hide(){if(!this.open)return Promise.resolve();const settled=this.popupController.wait(!1);return this.open=!1,settled}positionListbox(){this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=this.effectiveDirection;const anchor=this.renderRoot.querySelector('[part="trigger"]'),listbox=this.renderRoot.querySelector('[part="listbox"]');if(!anchor||!listbox)return;this.placedTopLayer=syncTopLayerRelease(listbox,this.placedTopLayer,this.topLayer),this.cleanup=place(anchor,listbox,{placement:rtlAwarePlacement(this.placement,this),...topLayerPlacement(this.topLayer,resolveEffectivePositioningStrategy(this,this._positioningStrategy,"absolute")),sync:this.sync});const operation=this.cleanup;this.positioningReady=operation.ready.then(positioned=>(positioned&&this.cleanup===operation&&this.open&&this.isConnected&&(this.listboxPositioned=!0,this.revealActiveOption()),positioned))}revealActiveOption(){if(!this.isConnected||!this.open||!this.listboxPositioned||!this.cleanup)return;const listbox=this.renderRoot.querySelector('[part="listbox"]'),activeId=this.triggerElement?.getAttribute("aria-activedescendant"),row=listbox?.querySelector('[part="option"][data-active]');listbox&&row&&activeId&&row.id===activeId&&revealRow(listbox,row)}activateListboxOverlay(){this.cleanup?.(),this.cleanup=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.restoreFocusOnClose=!0,this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="listbox"]'),onEscape:()=>{this.hide()},onBackdrop:()=>{this.restoreFocusOnClose=!1,this.hide()},restoreFocusTo:this.triggerElement??null}),this.popupController.bindPointer(),this.positionListbox()}teardownListboxOverlay(restoreFocus=this.restoreFocusOnClose){this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.overlayHandle?.deactivate({restoreFocus}),this.overlayHandle=void 0,this.popupController.unbindPointer(),this.restoreFocusOnClose=!0}reconnectOpenPopup(){!this.isConnected||!this.open||this.activateListboxOverlay()}updated(changed){super.updated(changed),this.syncExternalDescription();const suppressOpenLifecycle=changed.has("open")&&this.suppressedOpenLifecycleGeneration===this.openStateGeneration,shouldRefreshPosition=this.open&&this.isConnected&&(changed.has("placement")||changed.has("positioningStrategy")||changed.has("topLayer")||changed.has("sync")||this.positionedDirection!==this.effectiveDirection);changed.has("open")&&!this.openVetoed?this.open&&this.isConnected?(this.activateListboxOverlay(),!this._isFirstUpdate&&!suppressOpenLifecycle&&this.settleTransition("lr-after-show")):this.open?this.teardownListboxOverlay(!1):(this.teardownListboxOverlay(),!this._isFirstUpdate&&!suppressOpenLifecycle&&this.settleTransition("lr-after-hide")):changed.has("open")&&this.openVetoed?(this.restoreFocusOnClose=!0,shouldRefreshPosition&&this.positionListbox()):shouldRefreshPosition&&this.positionListbox(),(changed.has("activeIndex")||changed.has("options")||changed.has("listboxPositioned"))&&this.revealActiveOption(),(changed.has("touched")||changed.has("required")||changed.has("value"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),changed.has("open")&&(this.pendingOpenTransitionStart=void 0,this.suppressedOpenLifecycleGeneration=void 0)}settleTransition(event){return this.popupController.settle(event,{waitForPosition:async stale=>{for(;this.open;){const readiness=this.positioningReady,positioned=await readiness;if(stale())return!1;if(positioned)break;if(readiness===this.positioningReady)return this.forceCloseOpenState(),!1}return!0},conceal:()=>{this.listboxHidden=!0}})}emitValueEvents(){const self=this,data=this.selectedData,value=self.value,previousValue=this.previousValue;dispatchNativeInputEvent(this),self.emit("lr-input",{value,previousValue,data}),dispatchNativeEvent(this,"change"),self.emit("lr-change",{value,previousValue,data})}assignValue(next){this.value=next}assignDefaultValue(next){this.defaultValue=next}requestSelection(values,preferred,afterCommit,available=()=>!0){if(this.selectionRequestDispatching||this.effectiveDisabled)return!1;const multiple=this.multiple,document=this.ownerDocument,connected=this.isConnected,open=this.open,slots=this.resolveOccurrenceSlots(values,preferred),data=slots.map(option=>option?.data),value=multiple?[...values]:values[0]??"",previousValue=this.value,self=this;let committed=!1;this.selectionRequestDispatching=!0;try{requestThenCommit({requestDetail:{value,previousValue,data},guard:this.selectionWriteGuard,emitRequest:(detail,init)=>self.emit("lr-change-request",detail,init),commit:()=>{const liveOptions=new Set(this.renderRoot.querySelector("slot:not([name])")?.assignedElements({flatten:!0})??[]);this.effectiveDisabled||this.multiple!==multiple||this.ownerDocument!==document||this.isConnected!==connected||this.open!==open||!available(liveOptions)||slots.some((option,index)=>option&&(!liveOptions.has(option)||option.value!==values[index]||!Object.is(option.data,data[index])))||(this.hasInteracted=!0,this._restoredStateActive=!1,this._valueDirty=!0,this.setSelection(values,preferred),committed=!0,afterCommit())}})}finally{this.selectionRequestDispatching=!1}return committed}selectOption(option){if(this.selectionRequestDispatching||this.effectiveDisabled||!this.isOptionAvailable(option))return;if(this.unknownOptionCache.get(option.value)===option){this.selectUnknownValue(option.value);return}const value=option.value,available=liveOptions=>liveOptions.has(option)&&option.value===value&&this.isOptionAvailable(option);if(this.multiple){const currentSlots=this.resolveOccurrenceSlots(this._selected,this._selectedOptions),selectedIndex=currentSlots.indexOf(option),selected=selectedIndex>=0,occurrences=selected?currentSlots.filter((_,index)=>index!==selectedIndex):[...currentSlots,option],values=selected?this._selected.filter((_,index)=>index!==selectedIndex):[...this._selected,value];this.requestSelection(values,occurrences,()=>{this.emitValueEvents(),this.emit("lr-activate",{value})},available);return}if(!(option!==this._selectedOptions[0]||value!==this._selected[0])){this.hide(),this.emit("lr-activate",{value});return}this.requestSelection([value],[option],()=>{this.hide(),this.emitValueEvents(),this.emit("lr-activate",{value})},available)}removeValueAt(index){return this.effectiveDisabled||index<0||index>=this._selected.length?!1:this.requestSelection(this._selected.filter((_,candidateIndex)=>candidateIndex!==index),this.resolveOccurrenceSlots(this._selected,this._selectedOptions).filter((_,candidateIndex)=>candidateIndex!==index),()=>this.emitValueEvents())}clear(){this.effectiveDisabled||this._selected.length===0||this.requestSelection([],[],()=>{this.emitValueEvents(),this.emit("lr-clear")})}removeTag(value,index,event){event.stopPropagation(),this._selected[index]===value&&this.removeValueAt(index)&&this.updateComplete.then(()=>{const buttons=[...this.renderRoot.querySelectorAll('[part~="tag__remove-button"]')];(buttons[Math.min(index,buttons.length-1)]??this.triggerElement)?.focus()})}typeAhead(char){this.typeBuffer.add(char,this.effectiveLocale);const navigable=this.navigableOptions();if(!navigable.length)return;const currentOption=this.open?navigable[this.activeIndex]:this._selectedOptions[this._selectedOptions.length-1],currentIndex=navigable.indexOf(currentOption),match=this.typeBuffer.match(navigable,currentIndex,option=>option.label,this.effectiveLocale,option=>this.open||!this.multiple||!this._selectedOptions.includes(option));if(match===null)return;const candidate=navigable[match];this.open?this.setActiveIndex(match,navigable):this.selectOption(candidate)}adornmentMarkup(option){return Array.from(option.children).filter(child=>["start","end","prefix","suffix"].includes(child.getAttribute("slot")??"")).map(child=>child.outerHTML).join("")}adornmentsFor(option){const cached=this.adornmentClones.get(option);if(cached)return cached;const cloneSlot=selector=>{const nodes=Array.from(option.querySelectorAll(selector));if(nodes.length!==0)return nodes.map(node=>node.cloneNode(!0))},resolved={markup:this.adornmentMarkup(option),start:cloneSlot(':scope > [slot="start"], :scope > [slot="prefix"]'),end:cloneSlot(':scope > [slot="end"], :scope > [slot="suffix"]')};return this.adornmentClones.set(option,resolved),resolved}renderRows(options,activeId){const out=[],chosen=new Set(this._selectedOptions);let currentGroup,groupRows=[],groupIndex=0;const flushGroup=()=>{if(groupRows.length!==0){if(currentGroup){const labelId=`${this.listId}-group-${groupIndex++}`;out.push(html`<div role="group" aria-labelledby=${labelId}>
|
|
1
|
+
import{__decorate}from"tslib";import{requestThenCommit}from"../../../internal/request-commit.js";import{VetoWriteGuard,markVetoGuardWrite}from"../../../internal/veto-write-guard.js";import{renderFormControlHintError}from"../../../internal/form-control-template.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{FormControlController,reflectFormName}from"../../../internal/form-control-controller.js";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{acquireNativeControlDescription}from"../../../internal/native-control-description.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{deferredPlaceReady as place,syncTopLayerRelease,topLayerPlacement}from"../../../internal/anchored-overlay-runtime.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{chevronIcon,closeIcon}from"../../../internal/icons.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{PopupController,emitPopupEvent}from"../../../internal/popup-controller.js";import{revealRow}from"../../../internal/reveal-row.js";import{TypeAheadBuffer}from"../../../internal/type-ahead-buffer.js";import{resolveListMove}from"../../../internal/list-navigation.js";import{finiteCount}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{styles}from"./select.styles.js";import{sizes}from"../../../internal/sizes.styles.js";import"../combobox/option.class.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{omittedEmptyStringConverter,optionalLiteralSetConverter}from"../../../internal/converters.js";import{getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{isOptionSelectedDirty,isOptionSelectedWrite,wasOptionInitiallySelected,RESET_OPTION_SELECTED_FROM_OWNER,SET_OPTION_SELECTED_FROM_OWNER}from"../../../internal/option-selection.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{tag}from"../../../internal/prefix.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_selectSelectedOverflow,LYRA_DEFAULT_selectValueMissing}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_loading,LYRA_DEFAULT_notInCatalog,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();function isLyraOptionElement(value){return isHtmlElement(value)&&value.localName===tag("option")}function normalizeSelectionValues(next){return Array.isArray(next)?next.filter(value=>typeof value=="string"):typeof next=="string"?[next]:[]}const POSITIONING_STRATEGY=optionalLiteralSetConverter(["absolute","fixed"]);class LyraSelect extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,fieldRequired:LYRA_DEFAULT_fieldRequired,loading:LYRA_DEFAULT_loading,notInCatalog:LYRA_DEFAULT_notInCatalog,removeWithContext:LYRA_DEFAULT_removeWithContext,select:LYRA_DEFAULT_select,selectSelectedOverflow:LYRA_DEFAULT_selectSelectedOverflow,selectValueMissing:LYRA_DEFAULT_selectValueMissing}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-input","lr-change","lr-change-request"])}static{this.identityEventDetailCollectionItems=Object.freeze({"lr-input":Object.freeze(["data"]),"lr-change":Object.freeze(["data"]),"lr-change-request":Object.freeze(["data"])})}static get validators(){return[currentValidityValidator("required","disabled","value","multiple")]}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles,srOnly]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},multiple:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},value:{noAccessor:!0},name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},maxOptionsVisible:{type:Number,attribute:"max-options-visible",noAccessor:!0},defaultValue:{attribute:"default-value",noAccessor:!0}}}get open(){return this._open}set open(next){const requested=!!next,normalized=requested&&!this.effectiveDisabled;if(normalized===this._open){requested!==normalized&&this.hasAttribute("open")&&this.removeAttribute("open");return}this.applyOpenState(normalized)}get positioningStrategy(){return this._positioningStrategy??"absolute"}set positioningStrategy(next){const normalized=POSITIONING_STRATEGY.normalize(next)??"absolute",old=this.positioningStrategy;this._positioningStrategy=normalized,normalized!==old&&(this.requestUpdate("positioningStrategy",old),old==="fixed"!=(normalized==="fixed")&&this.requestUpdate("hoist",old==="fixed"))}get hoist(){return this.positioningStrategy==="fixed"}set hoist(next){this.positioningStrategy=next?"fixed":"absolute"}focus(options){this.effectiveDisabled||this.triggerElement?.focus(options)}blur(){this.triggerElement?.blur()}click(){this.effectiveDisabled||this.triggerElement?.click()}constructor(){super(),this.placeholder="",this.label="",this.hint="",this.helpText="",this.withLabel=!1,this.withHint=!1,this.errorText="",this.autofocus=!1,this.title="",this._open=!1,this.size="m",this.appearance="outlined",this.pill=!1,this.placement="bottom",this.topLayer=!1,this.filled=!1,this.withClear=!1,this.clearable=!1,this.withUnknownOption=!1,this.loading=!1,this.autoCommitSingleOption=!1,this.activeIndex=-1,this.options=[],this.optionsObserved=!1,this.touched=!1,this.hasInteracted=!1,this.slotPresence=new SlotPresenceController(this),this._fieldsetDisabled=!1,this.listId=nextId("select-list"),this.triggerId=nextId("select-trigger"),this.valueTextId=nextId("select-value"),this.positioningReady=Promise.resolve(!1),this.restoreFocusOnClose=!0,this.popupController=new PopupController({host:this,popup:()=>this.renderRoot.querySelector('[part="listbox"]'),emit:(name,cancelable)=>emitPopupEvent(this,name,cancelable),onPointer:event=>this.onDocPointer(event)}),this.listboxHidden=!0,this.listboxRendered=!1,this.listboxPositioned=!1,this._isFirstUpdate=!0,this.openVetoed=!1,this.previousValue="",this.openStateGeneration=0,this._selected=[],this._selectedOptions=[],this._selectedValuesByOption=new Map,this.adornmentClones=new WeakMap,this._multiple=!1,this._disabled=!1,this._required=!1,this._defaultSelected=[],this._defaultSelectedOptions=[],this._defaultCaptured=!1,this._valueDirty=!1,this._restoredStateActive=!1,this._resolvingPendingInitialSelection=!1,this._defaultValueDirty=!1,this.typeBuffer=new TypeAheadBuffer(this),this._name="",this._maxOptionsVisible=3,this.localDescriptionIds="",this.markInteracted=()=>{this.hasInteracted||(this.hasInteracted=!0,this.reflectValidityStates())},this.collectOptions=e=>{this.collectOptionsFromSlot(e.target)},this.unknownOptionCache=new Map,this.optionRefreshPending=!1,this.onOptionChange=e=>{e.stopPropagation();const option=e.composedPath().find(isLyraOptionElement);if(isOptionSelectedWrite(e)&&isLyraOptionElement(option)&&this.options.includes(option)){markVetoGuardWrite(this.selectionWriteGuard),this._valueDirty=!0,this._restoredStateActive=!1;const selected=this._selectedOptions.includes(option);if(option.selected===selected&&(!selected||this._selectedValuesByOption.get(option)===option.value))return;if(option.selected&&!this.multiple){this.setSelection([option.value],[option]);return}const remaining=[...this._selectedOptions],preferred=this._selected.map(value=>{const index2=remaining.findIndex(candidate=>this._selectedValuesByOption.get(candidate)===value);return index2<0?void 0:remaining.splice(index2,1)[0]}),values=[...this._selected],index=preferred.indexOf(option);if(option.selected)index<0?(values.push(option.value),preferred.push(option)):values[index]=option.value;else{if(index<0)return;values.splice(index,1),preferred.splice(index,1)}this.setSelection(values,preferred);return}if(isLyraOptionElement(option)){const cached=this.adornmentClones.get(option);cached&&cached.markup!==this.adornmentMarkup(option)&&this.adornmentClones.delete(option)}if(this.optionRefreshPending)return;this.optionRefreshPending=!0;const previousActive=this.activeOption,previousActiveRawIndex=previousActive?this.options.indexOf(previousActive):this.activeIndex;queueMicrotask(()=>{this.optionRefreshPending=!1,this.refreshOptionDefaults(),this.reflectSelected(),this.options=[...this.options],this.reconcileActiveOption(previousActive,previousActiveRawIndex)})},this.onDocPointer=e=>{if(!e.composedPath().includes(this)){if(this.overlayHandle?.isActive()){this.overlayHandle.dismissBackdrop();return}this.restoreFocusOnClose=!1,this.hide()}},this.selectionWriteGuard=new VetoWriteGuard,this.selectionRequestDispatching=!1,this.onTriggerClick=()=>{if(!this.effectiveDisabled){if(this.onlyOption)return this.selectOption(this.onlyOption);this.open?this.hide():this.show()}},this.onTriggerBlur=event=>{this.effectiveDisabled||(this.touched=!0,this.hasInteracted=!0,this.reflectValidityStates()),this.open&&(this.restoreFocusOnClose=!1),this.hide(),relayNativeEvent(this,event)},this.onTriggerFocus=event=>{relayNativeEvent(this,event)},this.onKeyDown=e=>{if(e.isComposing||e.keyCode===229)return;const navigable=this.navigableOptions(),move=()=>resolveListMove(e,{count:navigable.length,current:this.activeIndex,orientation:"vertical",wrap:!1,clamp:!0,backwardFromMissing:"first"});switch(e.key){case"ArrowDown":if(e.preventDefault(),this.onlyOption)return this.selectOption(this.onlyOption);if(!this.open){this.show();return}this.setActiveIndex(move()??-1,navigable);break;case"ArrowUp":if(e.preventDefault(),this.onlyOption)return this.selectOption(this.onlyOption);if(!this.open){this.show();return}this.setActiveIndex(move()??-1,navigable);break;case"Enter":case" ":if(this.open){e.preventDefault();const active=navigable[this.activeIndex];this.activeIndex>=0&&active?this.selectOption(active):this.hide()}break;case"Escape":this.open&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(e.preventDefault(),this.hide());break;case"Home":this.open&&(e.preventDefault(),this.setActiveIndex(move()??-1,navigable));break;case"End":this.open&&(e.preventDefault(),this.setActiveIndex(move()??-1,navigable));break;case"Backspace":case"Delete":this.multiple&&this._selected.length>0&&(e.preventDefault(),this.removeValueAt(this._selected.length-1));break;default:this.typeBuffer.accepts(e)&&this.typeAhead(e.key);break}},this.onListboxMouseDown=e=>{e.preventDefault()},this.onListboxClick=e=>{const optionEl=e.target.closest('[part="option"]'),index=Number(optionEl?.dataset.index);if(!Number.isInteger(index))return;const option=this.listboxOptions[index];option&&this.selectOption(option)},this.validityController=new FormControlController(this,{invalid:init=>this.emit("lr-invalid",null,init),interacted:this.markInteracted,customError:()=>this.validityController.customValidityMessage}),this.internals=this.validityController.formInternals,new GlassScrollLayer(this,'[part="listbox"]',()=>this.open),this.syncFormValue()}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"]')??null}syncExternalDescription(){if(!this.isConnected)return;const target=this.renderRoot.querySelector('[part="trigger"]');target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireNativeControlDescription(this,target,()=>this.localDescriptionIds))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.updateValidity(),this.hasUpdated&&this.open&&queueMicrotask(()=>this.reconnectOpenPopup())}willUpdate(changed){if(super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,this._isFirstUpdate&&(this._pendingInitialDefaultValue!==void 0||this._pendingInitialValue!==void 0||this._pendingInitialSelectedOptions!==void 0)){this._resolvingPendingInitialSelection=!0;try{if(this._pendingInitialDefaultValue!==void 0){const pending=this._pendingInitialDefaultValue;this._pendingInitialDefaultValue=void 0,this.assignDefaultValue(pending)}if(this._pendingInitialValue!==void 0){const pending=this._pendingInitialValue;this._pendingInitialValue=void 0,this.assignValue(pending)}if(this._pendingInitialSelectedOptions!==void 0){const pending=this._pendingInitialSelectedOptions;this._pendingInitialSelectedOptions=void 0,this.selectedOptions=pending}}finally{this._resolvingPendingInitialSelection=!1}}if(this.announceOpenTransition(changed),changed.has("open")&&!this.openVetoed&&(this.listboxPositioned=!1),this.open&&(this.listboxHidden=!1,this.listboxRendered=!0),changed.has("open")&&!this.openVetoed){const navigable=this.navigableOptions();this.setActiveIndex(this.open?navigable.findIndex(option=>this._selectedOptions.includes(option)):-1,navigable)}}firstUpdated(changed){super.firstUpdated(changed);const slot=this.optionsSlot;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>{const assigned=s.assignedElements({flatten:!0});this.optionsObserved=!0,assigned.some(isLyraOptionElement)&&this.collectOptionsFromSlot(s)})})}applyOpenState(next){const old=this._open;this.pendingOpenTransitionStart===void 0&&(this.pendingOpenTransitionStart=old),this.openStateGeneration++,this._open=next,this.requestUpdate("open",old)}forceCloseOpenState(){this.listboxHidden=!0;const isClosing=this._open||this.pendingOpenTransitionStart===!0;if(this.popupController.cancel(),!this._open){isClosing&&(this.suppressedOpenLifecycleGeneration=this.openStateGeneration),this.hasAttribute("open")&&this.removeAttribute("open");return}this.applyOpenState(!1),this.suppressedOpenLifecycleGeneration=this.openStateGeneration}announceOpenTransition(changed){if(this.openVetoed=!1,!(!changed.has("open")||this._isFirstUpdate||this.suppressedOpenLifecycleGeneration===this.openStateGeneration)){if(!this.isConnected){emitPopupEvent(this,"lr-hide",!1);return}this.openVetoed=this.popupController.announce(this.open,()=>{this.open=!this.open})}}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",reflectFormName(this,this._name),this.syncFormValue(),this.requestUpdate("name",old)}get multiple(){return this._multiple}set multiple(next){markVetoGuardWrite(this.selectionWriteGuard);const old=this._multiple;this._multiple=!!next,this.toggleAttribute("multiple",this._multiple),!this._multiple&&this._selected.length>1?this.setSelection(this._selected.slice(0,1),this._selectedOptions.slice(0,1)):this.syncFormValue(),this.requestUpdate("multiple",old)}get maxOptionsVisible(){return this._maxOptionsVisible}set maxOptionsVisible(next){const old=this._maxOptionsVisible;this._maxOptionsVisible=finiteCount(next,3),this.requestUpdate("maxOptionsVisible",old)}get disabled(){return this._disabled}set disabled(next){markVetoGuardWrite(this.selectionWriteGuard);const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this._disabled&&this.forceCloseOpenState(),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get value(){return this.multiple?[...this._selected]:this._selected[0]??""}set value(next){!this.hasUpdated&&!this._resolvingPendingInitialSelection&&(this._pendingInitialValue=next),this._restoredStateActive=!1,this._valueDirty=!0;const values=normalizeSelectionValues(next);this.setSelection(values)}get defaultValue(){return this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??""}set defaultValue(next){!this.hasUpdated&&!this._resolvingPendingInitialSelection&&(this._pendingInitialDefaultValue=next),this._defaultValueDirty=!0;const old=this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??"",values=normalizeSelectionValues(next);this._defaultSelected=this.multiple?[...values]:values.slice(0,1),this._defaultSelectedOptions=this.resolveOccurrences(this._defaultSelected),!this._valueDirty&&!this._restoredStateActive&&this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions]),this.requestUpdate("defaultValue",old)}get selectedOptions(){return[...this._selectedOptions]}set selectedOptions(next){!this.hasUpdated&&!this._resolvingPendingInitialSelection&&(this._pendingInitialSelectedOptions=next),this._restoredStateActive=!1,this._valueDirty=!0;const candidates=Array.isArray(next)?next:[],catalog=candidates.length>1?new Set(this.options):void 0,seen=new Set,live=candidates.filter(option=>seen.has(option)?!1:(seen.add(option),isLyraOptionElement(option)&&this.contains(option)&&(catalog?catalog.has(option):this.options.includes(option)))),selected=this.multiple?live:live.slice(0,1);this.setSelection(selected.map(option=>option.value),selected)}get selectedData(){return this.resolveOccurrenceSlots(this._selected,this._selectedOptions).map(option=>option?.data)}setSelection(next,preferred=[]){markVetoGuardWrite(this.selectionWriteGuard);const values=this.multiple?[...next]:next.slice(0,1),previousValues=this._selected,previousOptions=this._selectedOptions,old=this.multiple?[...previousValues]:previousValues[0]??"";this.previousValue=old,this._selected=values,this._selectedOptions=this.resolveOccurrences(values,preferred),this.syncFormValue(),this.reflectSelected(),this.updateValidity(),this.requestUpdate("value",old);const sameValues=previousValues.length===values.length&&previousValues.every((value,i)=>value===values[i]),sameOptions=previousOptions.length===this._selectedOptions.length&&previousOptions.every((option,i)=>option===this._selectedOptions[i]);sameValues&&!sameOptions&&this.requestUpdate()}resolveOccurrences(values,preferred=[]){return this.resolveOccurrenceSlots(values,preferred).filter(option=>option!==void 0)}resolveOccurrenceSlots(values,preferred=[]){if(values.length===0)return[];if(values.length===1){const value=values[0],hint=preferred.length===1?preferred[0]:preferred.find(option=>option?.value===value);return[hint&&hint.value===value&&this.options.includes(hint)?hint:this.options.find(option=>option.value===value)]}const requested=new Set(values),catalog=new Set(this.options),claimed=new Set,queuesFor=options=>{const queues=new Map;for(const option of options){if(!option)continue;const value=option.value;if(!requested.has(value))continue;let queue=queues.get(value);queue||queues.set(value,queue={options:[],next:0}),queue.options.push(option)}return queues},firstUnclaimed=(queues,value)=>{const queue=queues.get(value);if(queue){for(;queue.next<queue.options.length&&claimed.has(queue.options[queue.next]);)queue.next++;return queue.options[queue.next]}},preferredQueues=preferred.length===values.length?void 0:queuesFor(preferred);let fallbackQueues;return values.map((value,index)=>{const hint=preferredQueues?firstUnclaimed(preferredQueues,value):preferred[index],match=hint&&hint.value===value&&catalog.has(hint)&&!claimed.has(hint)?hint:firstUnclaimed(fallbackQueues??=queuesFor(this.options),value);if(match)return claimed.add(match),match})}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){this.barredFromValidation?this.validityController.setValidity({}):this.required&&this._selected.length===0?this.validityController.setValidity({valueMissing:!0},this.localize("selectValueMissing")):this.validityController.setValidity({}),this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",this._selected.length===0)}syncFormValue(){if(!this.multiple){this.internals.setFormValue(this._selected[0]??"");return}const state2=JSON.stringify(this._selected);if(!this.name){this.internals.setFormValue(null,state2);return}const data=new FormData;for(const value of this._selected)data.append(this.name,value);this.internals.setFormValue(data,state2)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formResetCallback(){this.touched=!1,this.hasInteracted=!1,this._restoredStateActive=!1,this._valueDirty=!1;const resetOptions=this._defaultSelectedOptions.length>0?this._defaultSelectedOptions:this.options.filter(option=>wasOptionInitiallySelected(option));this._defaultSelectedOptions.length===0&&resetOptions.length>0&&(this._defaultSelectedOptions=[...resetOptions],this._defaultSelected=resetOptions.map(option=>option.value));const defaults=new Set(resetOptions);for(const option of this.options)option[RESET_OPTION_SELECTED_FROM_OWNER](defaults.has(option));this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}formStateRestoreCallback(state2,reason){if(!this.multiple)this.assignValue(typeof state2=="string"?state2:void 0);else{let restored=[];if(typeof state2=="string")try{const parsed=JSON.parse(state2);Array.isArray(parsed)&&parsed.every(entry=>typeof entry=="string")&&(restored=parsed)}catch{}this.assignValue(restored)}this._restoredStateActive=!0,this._valueDirty=!0}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;markVetoGuardWrite(this.selectionWriteGuard);const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(disabled&&this.forceCloseOpenState(),this.updateValidity(),this.requestUpdate())}checkValidity(){return this.validityController.checkValidity(()=>this.updateValidity())}reportValidity(){return this.validityController.syncConstraints(),this.updateValidity(),this.hasInteracted=!0,this.reflectValidityStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.reflectValidityStates()}resetValidity(){this.setCustomValidity("")}disconnectedCallback(){markVetoGuardWrite(this.selectionWriteGuard),this.listboxHidden=!0,this.releaseExternalDescription(),this.popupController.cancel(),super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.typeBuffer.clear(),this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.popupController.unbindPointer(),this.open=!1}adoptedCallback(){markVetoGuardWrite(this.selectionWriteGuard),super.adoptedCallback(),this.popupController.cancel(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription(),this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.popupController.unbindPointer(),this.typeBuffer.clear(),queueMicrotask(()=>this.reconnectOpenPopup())}collectOptionsFromSlot(slot){const previous=new Set(this.options),previousActive=this.activeOption,previousActiveRawIndex=previousActive?this.options.indexOf(previousActive):this.activeIndex;if(this.options=slot.assignedElements({flatten:!0}).filter(isLyraOptionElement),this.optionsObserved=!0,this.adornmentClones=new WeakMap,this.reconcileActiveOption(previousActive,previousActiveRawIndex),this._defaultCaptured){const newDefaults=this.options.filter(option=>!previous.has(option)&&option.defaultSelected),newLive=this.options.filter(option=>!previous.has(option)&&option.selected&&!option.defaultSelected);this.refreshOptionDefaults();const eligible=[...!this._restoredStateActive&&!this._valueDirty?newDefaults:[],...this._restoredStateActive?[]:newLive];if(eligible.length>0){const added=this.multiple?eligible:eligible.slice(-1),occurrences=this.multiple?[...new Set([...this._selectedOptions,...added])]:added;newLive.length>0&&(this._valueDirty=!0),this.setSelection(occurrences.map(option=>option.value),occurrences);return}}else{this._defaultCaptured=!0;const explicitDefault=this.hasAttribute("default-value")||this._defaultValueDirty,allDefaults=this.options.filter(option=>option.defaultSelected),defaults=this.multiple?allDefaults:allDefaults.slice(0,1),allLive=this.options.filter(option=>option.selected),live=this.multiple?allLive:allLive.slice(0,1),initialLive=this.options.filter(option=>wasOptionInitiallySelected(option)),optionDirty=this.options.some(option=>isOptionSelectedDirty(option)),dirtySelected=this.options.filter(option=>isOptionSelectedDirty(option)&&option.selected);if(explicitDefault)this._defaultSelectedOptions=this.resolveOccurrences(this._defaultSelected);else{const resetOptions=defaults.length>0?defaults:initialLive.length>0?initialLive:live;this._defaultSelected=resetOptions.map(option=>option.value),this._defaultSelectedOptions=[...resetOptions]}const fromDefaults=explicitDefault||defaults.length>0,initial=optionDirty?this.multiple?allLive:dirtySelected.slice(-1)[0]?dirtySelected.slice(-1):live:explicitDefault?this._defaultSelectedOptions:fromDefaults?defaults:live;if(initial.length>0&&!this._restoredStateActive&&!this._valueDirty){(!fromDefaults||optionDirty)&&(this._valueDirty=!0),this.setSelection(initial.map(option=>option.value),[...initial]);return}if(optionDirty&&(this._valueDirty=!0),explicitDefault&&!this._valueDirty&&!this._restoredStateActive){this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions]);return}}this.reflectSelected()}refreshOptionDefaults(){if(this.hasAttribute("default-value")||this._defaultValueDirty)return;const declared=this.options.filter(option=>option.defaultSelected),defaults=this.multiple?declared:declared.slice(0,1);this._defaultSelected=defaults.map(option=>option.value),this._defaultSelectedOptions=[...defaults],!this._valueDirty&&!this._restoredStateActive&&this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}reflectSelected(){this._selectedOptions=this.resolveOccurrences(this._selected,this._selectedOptions),this._selectedValuesByOption=new Map(this._selectedOptions.map(option=>[option,option.value]));const chosen=new Set(this._selectedOptions);for(const option of this.options)option[SET_OPTION_SELECTED_FROM_OWNER](chosen.has(option))}selectUnknownValue(value){if(!(this.selectionRequestDispatching||this.effectiveDisabled)){if(this.multiple){const index=this._selected.indexOf(value),values=index>=0?this._selected.filter((_,position)=>position!==index):[...this._selected,value];this.requestSelection(values,this.resolveOccurrenceSlots(values,this._selectedOptions),()=>{this.emitValueEvents(),this.emit("lr-activate",{value})});return}this.hide(),this.emit("lr-activate",{value})}}resolvedLabelFor(value,occurrenceIndex=0){const option=(this._selectedOptions[occurrenceIndex]?.value===value?this._selectedOptions[occurrenceIndex]:void 0)??this._selectedOptions.find(candidate=>candidate.value===value)??this.options.find(candidate=>candidate.value===value);return option&&(option.label||option.value)}labelFor(value,occurrenceIndex=0){const resolved=this.resolvedLabelFor(value,occurrenceIndex);if(resolved!==void 0)return resolved;if(this.loading)return this.localize("loading");const override=this.optionsObserved?this.getUnknownLabel?.(value):void 0;return override!==void 0&&override.trim().length>0?override:value}isUnknownValue(value,occurrenceIndex=0){return!this.optionsObserved||this.loading||value===""?!1:this.resolvedLabelFor(value,occurrenceIndex)===void 0}get onlyOption(){if(!this.autoCommitSingleOption)return;const navigable=this.navigableOptions(this.options);return navigable.length===1?navigable[0]:void 0}isOptionAvailable(option){return!option.disabled&&!option.inert&&!option.closest("[inert]")}navigableOptions(options=this.listboxOptions){return options.filter(option=>this.isOptionAvailable(option))}get unknownValues(){return this.withUnknownOption?this._selected.filter((value,index)=>this.isUnknownValue(value,index)):[]}get unknownOptions(){const values=this.unknownValues;if(values.length===0)return this.unknownOptionCache.clear(),[];for(const key of[...this.unknownOptionCache.keys()])values.includes(key)||this.unknownOptionCache.delete(key);return values.map(value=>{let option=this.unknownOptionCache.get(value);return option||(option=this.ownerDocument.createElement(tag("option")),this.unknownOptionCache.set(value,option)),option.value=value,option.label=this.labelFor(value),option})}get listboxOptions(){const unknown=this.unknownOptions;return unknown.length===0?this.options:[...this.options,...unknown]}setActiveIndex(next,navigable=this.navigableOptions()){if(next<0||navigable.length===0){this.activeIndex=-1,this.activeOption=void 0;return}const index=Math.min(next,navigable.length-1);this.activeIndex=index,this.activeOption=navigable[index]}reconcileActiveOption(previousActive,previousRawIndex){if(!previousActive&&this.activeIndex<0)return;const navigable=this.navigableOptions();if(previousActive){const preservedIndex=navigable.indexOf(previousActive);if(preservedIndex>=0){this.setActiveIndex(preservedIndex,navigable);return}}if(navigable.length===0){this.setActiveIndex(-1,navigable);return}const pivot=Math.max(0,previousRawIndex);let nearestIndex=0,nearestDistance=Number.POSITIVE_INFINITY,nearestRawIndex=-1;navigable.forEach((option,index)=>{const rawIndex=this.listboxOptions.indexOf(option),distance=Math.abs(rawIndex-pivot);(distance<nearestDistance||distance===nearestDistance&&rawIndex>=pivot&&nearestRawIndex<pivot)&&(nearestIndex=index,nearestDistance=distance,nearestRawIndex=rawIndex)}),this.setActiveIndex(nearestIndex,navigable)}show(){if(this.open||this.effectiveDisabled)return Promise.resolve();const settled=this.popupController.wait(!0);return this.open=!0,settled}hide(){if(!this.open)return Promise.resolve();const settled=this.popupController.wait(!1);return this.open=!1,settled}positionListbox(){this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=this.effectiveDirection;const anchor=this.renderRoot.querySelector('[part="trigger"]'),listbox=this.renderRoot.querySelector('[part="listbox"]');if(!anchor||!listbox)return;this.placedTopLayer=syncTopLayerRelease(listbox,this.placedTopLayer,this.topLayer),this.cleanup=place(anchor,listbox,{placement:rtlAwarePlacement(this.placement,this),...topLayerPlacement(this.topLayer,resolveEffectivePositioningStrategy(this,this._positioningStrategy,"absolute")),sync:this.sync});const operation=this.cleanup;this.positioningReady=operation.ready.then(positioned=>(positioned&&this.cleanup===operation&&this.open&&this.isConnected&&(this.listboxPositioned=!0,this.revealActiveOption()),positioned))}revealActiveOption(){if(!this.isConnected||!this.open||!this.listboxPositioned||!this.cleanup)return;const listbox=this.renderRoot.querySelector('[part="listbox"]'),activeId=this.triggerElement?.getAttribute("aria-activedescendant"),row=listbox?.querySelector('[part="option"][data-active]');listbox&&row&&activeId&&row.id===activeId&&revealRow(listbox,row)}activateListboxOverlay(){this.cleanup?.(),this.cleanup=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.restoreFocusOnClose=!0,this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="listbox"]'),onEscape:()=>{this.hide()},onBackdrop:()=>{this.restoreFocusOnClose=!1,this.hide()},restoreFocusTo:this.triggerElement??null}),this.popupController.bindPointer(),this.positionListbox()}teardownListboxOverlay(restoreFocus=this.restoreFocusOnClose){this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.overlayHandle?.deactivate({restoreFocus}),this.overlayHandle=void 0,this.popupController.unbindPointer(),this.restoreFocusOnClose=!0}reconnectOpenPopup(){!this.isConnected||!this.open||this.activateListboxOverlay()}updated(changed){super.updated(changed),this.syncExternalDescription();const suppressOpenLifecycle=changed.has("open")&&this.suppressedOpenLifecycleGeneration===this.openStateGeneration,shouldRefreshPosition=this.open&&this.isConnected&&(changed.has("placement")||changed.has("positioningStrategy")||changed.has("topLayer")||changed.has("sync")||this.positionedDirection!==this.effectiveDirection);changed.has("open")&&!this.openVetoed?this.open&&this.isConnected?(this.activateListboxOverlay(),!this._isFirstUpdate&&!suppressOpenLifecycle&&this.settleTransition("lr-after-show")):this.open?this.teardownListboxOverlay(!1):(this.teardownListboxOverlay(),!this._isFirstUpdate&&!suppressOpenLifecycle&&this.settleTransition("lr-after-hide")):changed.has("open")&&this.openVetoed?(this.restoreFocusOnClose=!0,shouldRefreshPosition&&this.positionListbox()):shouldRefreshPosition&&this.positionListbox(),(changed.has("activeIndex")||changed.has("options")||changed.has("listboxPositioned"))&&this.revealActiveOption(),(changed.has("touched")||changed.has("required")||changed.has("value"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),changed.has("open")&&(this.pendingOpenTransitionStart=void 0,this.suppressedOpenLifecycleGeneration=void 0)}settleTransition(event){return this.popupController.settle(event,{waitForPosition:async stale=>{for(;this.open;){const readiness=this.positioningReady,positioned=await readiness;if(stale())return!1;if(positioned)break;if(readiness===this.positioningReady)return this.forceCloseOpenState(),!1}return!0},conceal:()=>{this.listboxHidden=!0}})}emitValueEvents(){const self=this,data=this.selectedData,value=self.value,previousValue=this.previousValue;dispatchNativeInputEvent(this),self.emit("lr-input",{value,previousValue,data}),dispatchNativeEvent(this,"change"),self.emit("lr-change",{value,previousValue,data})}assignValue(next){this.value=next}assignDefaultValue(next){this.defaultValue=next}requestSelection(values,preferred,afterCommit,available=()=>!0){if(this.selectionRequestDispatching||this.effectiveDisabled)return!1;const multiple=this.multiple,document=this.ownerDocument,connected=this.isConnected,open=this.open,slots=this.resolveOccurrenceSlots(values,preferred),data=slots.map(option=>option?.data),value=multiple?[...values]:values[0]??"",previousValue=this.value,self=this;let committed=!1;this.selectionRequestDispatching=!0;try{requestThenCommit({requestDetail:{value,previousValue,data},guard:this.selectionWriteGuard,emitRequest:(detail,init)=>self.emit("lr-change-request",detail,init),commit:()=>{const liveOptions=new Set(this.renderRoot.querySelector("slot:not([name])")?.assignedElements({flatten:!0})??[]);this.effectiveDisabled||this.multiple!==multiple||this.ownerDocument!==document||this.isConnected!==connected||this.open!==open||!available(liveOptions)||slots.some((option,index)=>option&&(!liveOptions.has(option)||option.value!==values[index]||!Object.is(option.data,data[index])))||(this.hasInteracted=!0,this._restoredStateActive=!1,this._valueDirty=!0,this.setSelection(values,preferred),committed=!0,afterCommit())}})}finally{this.selectionRequestDispatching=!1}return committed}selectOption(option){if(this.selectionRequestDispatching||this.effectiveDisabled||!this.isOptionAvailable(option))return;if(this.unknownOptionCache.get(option.value)===option){this.selectUnknownValue(option.value);return}const value=option.value,available=liveOptions=>liveOptions.has(option)&&option.value===value&&this.isOptionAvailable(option);if(this.multiple){const currentSlots=this.resolveOccurrenceSlots(this._selected,this._selectedOptions),selectedIndex=currentSlots.indexOf(option),selected=selectedIndex>=0,occurrences=selected?currentSlots.filter((_,index)=>index!==selectedIndex):[...currentSlots,option],values=selected?this._selected.filter((_,index)=>index!==selectedIndex):[...this._selected,value];this.requestSelection(values,occurrences,()=>{this.emitValueEvents(),this.emit("lr-activate",{value})},available);return}if(!(option!==this._selectedOptions[0]||value!==this._selected[0])){this.hide(),this.emit("lr-activate",{value});return}this.requestSelection([value],[option],()=>{this.hide(),this.emitValueEvents(),this.emit("lr-activate",{value})},available)}removeValueAt(index){return this.effectiveDisabled||index<0||index>=this._selected.length?!1:this.requestSelection(this._selected.filter((_,candidateIndex)=>candidateIndex!==index),this.resolveOccurrenceSlots(this._selected,this._selectedOptions).filter((_,candidateIndex)=>candidateIndex!==index),()=>this.emitValueEvents())}clear(){this.effectiveDisabled||this._selected.length===0||this.requestSelection([],[],()=>{this.emitValueEvents(),this.emit("lr-clear")})}removeTag(value,index,event){event.stopPropagation(),this._selected[index]===value&&this.removeValueAt(index)&&this.updateComplete.then(()=>{const buttons=[...this.renderRoot.querySelectorAll('[part~="tag__remove-button"]')];(buttons[Math.min(index,buttons.length-1)]??this.triggerElement)?.focus()})}typeAhead(char){this.typeBuffer.add(char,this.effectiveLocale);const navigable=this.navigableOptions();if(!navigable.length)return;const currentOption=this.open?navigable[this.activeIndex]:this._selectedOptions[this._selectedOptions.length-1],currentIndex=navigable.indexOf(currentOption),match=this.typeBuffer.match(navigable,currentIndex,option=>option.label,this.effectiveLocale,option=>this.open||!this.multiple||!this._selectedOptions.includes(option));if(match===null)return;const candidate=navigable[match];this.open?this.setActiveIndex(match,navigable):this.selectOption(candidate)}adornmentMarkup(option){return Array.from(option.children).filter(child=>["start","end","prefix","suffix"].includes(child.getAttribute("slot")??"")).map(child=>child.outerHTML).join("")}adornmentsFor(option){const cached=this.adornmentClones.get(option);if(cached)return cached;const cloneSlot=selector=>{const nodes=Array.from(option.querySelectorAll(selector));if(nodes.length!==0)return nodes.map(node=>node.cloneNode(!0))},resolved={markup:this.adornmentMarkup(option),start:cloneSlot(':scope > [slot="start"], :scope > [slot="prefix"]'),end:cloneSlot(':scope > [slot="end"], :scope > [slot="suffix"]')};return this.adornmentClones.set(option,resolved),resolved}renderRows(options,activeId){const out=[],chosen=new Set(this._selectedOptions);let currentGroup,groupRows=[],groupIndex=0;const flushGroup=()=>{if(groupRows.length!==0){if(currentGroup){const labelId=`${this.listId}-group-${groupIndex++}`;out.push(html`<div role="group" aria-labelledby=${labelId}>
|
|
2
2
|
<div id=${labelId} class="group-label" part="group-label">${currentGroup}</div>
|
|
3
3
|
${groupRows}
|
|
4
4
|
</div>`)}else out.push(...groupRows);groupRows=[]}};return options.forEach((o,i)=>{o.group!==currentGroup&&(flushGroup(),currentGroup=o.group);const id=`${this.listId}-opt-${i}`,unknown=this.unknownOptionCache.get(o.value)===o,selected=unknown||chosen.has(o),adornments=this.adornmentsFor(o);groupRows.push(html`<div
|
|
@@ -38,7 +38,7 @@ import{__decorate}from"tslib";import{requestThenCommit}from"../../../internal/re
|
|
|
38
38
|
>
|
|
39
39
|
${closeIcon()}
|
|
40
40
|
</button>
|
|
41
|
-
</span>`}render(){const options=this.listboxOptions,navigable=this.navigableOptions(options),active=this.activeIndex>=0?navigable[this.activeIndex]:void 0,activeId=active?`${this.listId}-opt-${options.indexOf(active)}`:"",selectedLabel=this._selected.length>0?this.labelFor(this._selected[0]):"",selectedLabels=this._selected.map((value,index)=>this.labelFor(value,index)).join(", "),hasValue=this._selected.length>0&&(this.multiple||this._selected[0]!==""||this.resolvedLabelFor("",0)!==void 0),emptyDisplayText=this.loading?this.localize("loading"):this.placeholder,singleValueUnknown=hasValue&&!this.multiple&&this.isUnknownValue(this._selected[0]),shownValues=this.maxOptionsVisible>0?this._selected.slice(0,this.maxOptionsVisible):this._selected,overflow=this._selected.length-shownValues.length,showClear=(this.withClear||this.clearable)&&hasValue,hasHint=this.slotPresence.has("hint")||this.slotPresence.has("help-text")||(this.hint??"").length>0||(this.helpText??"").length>0||this.withHint,hasError=this.slotPresence.has("error")||(this.errorText??"").length>0,hasLabel=this.slotPresence.has("label")||(this.label??"").length>0||this.withLabel,describedBy=this.localDescriptionIds=[this.multiple&&hasValue?this.valueTextId:"",hasError?"select-error":"",hasHint?"select-hint":""].filter(Boolean).join(" ")
|
|
41
|
+
</span>`}render(){const options=this.listboxOptions,navigable=this.navigableOptions(options),active=this.activeIndex>=0?navigable[this.activeIndex]:void 0,activeId=active?`${this.listId}-opt-${options.indexOf(active)}`:"",selectedLabel=this._selected.length>0?this.labelFor(this._selected[0]):"",selectedLabels=this._selected.map((value,index)=>this.labelFor(value,index)).join(", "),hasValue=this._selected.length>0&&(this.multiple||this._selected[0]!==""||this.resolvedLabelFor("",0)!==void 0),emptyDisplayText=this.loading?this.localize("loading"):this.placeholder,singleValueUnknown=hasValue&&!this.multiple&&this.isUnknownValue(this._selected[0]),shownValues=this.maxOptionsVisible>0?this._selected.slice(0,this.maxOptionsVisible):this._selected,overflow=this._selected.length-shownValues.length,showClear=(this.withClear||this.clearable)&&hasValue,hasHint=this.slotPresence.has("hint")||this.slotPresence.has("help-text")||(this.hint??"").length>0||(this.helpText??"").length>0||this.withHint,hasError=this.slotPresence.has("error")||(this.errorText??"").length>0,hasLabel=this.slotPresence.has("label")||(this.label??"").length>0||this.withLabel,isSingleOption=this.autoCommitSingleOption&&navigable.length===1,requiredTextId=`${this.triggerId}-required`,describedBy=this.localDescriptionIds=[this.required&&isSingleOption?requiredTextId:"",this.multiple&&hasValue?this.valueTextId:"",hasError?"select-error":"",hasHint?"select-hint":""].filter(Boolean).join(" ");return html`
|
|
42
42
|
<div part="form-control">
|
|
43
43
|
<label
|
|
44
44
|
part="form-control-label"
|
|
@@ -47,6 +47,7 @@ import{__decorate}from"tslib";import{requestThenCommit}from"../../../internal/re
|
|
|
47
47
|
>
|
|
48
48
|
<span part="label">${this.label}<slot name="label"></slot></span>
|
|
49
49
|
</label>
|
|
50
|
+
${this.required&&isSingleOption?html`<span id=${requiredTextId} class="sr-only">${this.localize("fieldRequired")}</span>`:nothing}
|
|
50
51
|
<div
|
|
51
52
|
class="control"
|
|
52
53
|
part="combobox form-control-input"
|
|
@@ -65,7 +66,7 @@ import{__decorate}from"tslib";import{requestThenCommit}from"../../../internal/re
|
|
|
65
66
|
aria-activedescendant=${isSingleOption?nothing:activeId}
|
|
66
67
|
aria-label=${this.getAttribute("aria-label")??(hasLabel?nothing:this.placeholder||this.localize("select"))}
|
|
67
68
|
aria-describedby=${describedBy||nothing}
|
|
68
|
-
aria-required=${this.required?"true":"false"}
|
|
69
|
+
aria-required=${isSingleOption?nothing:this.required?"true":"false"}
|
|
69
70
|
aria-invalid=${this.touched&&!this.internals.validity.valid?"true":"false"}
|
|
70
71
|
?disabled=${this.effectiveDisabled}
|
|
71
72
|
?autofocus=${this.autofocus}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{setNativeRangeText,nativeAutocorrectAttribute}from"../../../internal/native-text-control.js";import{renderFormControlHintError}from"../../../internal/form-control-template.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{isAccessibilityVisible}from"../../../internal/accessibility-visibility.js";import{LyraElement}from"../../../internal/lyra-element.js";import{OwnedFrame,OwnedTimeout}from"../../../internal/owned-timer.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY}from"../../../internal/anchored-validity.js";import{setCustomState}from"../../../internal/custom-states.js";import{lengthLimitConverter,lengthViolations,normalizeLengthLimit}from"../../../internal/length-constraints.js";import{styles}from"./textarea.styles.js";import{sizes}from"../../../internal/sizes.styles.js";import{autocorrectConverter,normalizeAutocorrect,spellcheckConverter}from"../../../internal/converters.js";import{sanitizeCssResize}from"../../../internal/safe-css.js";import{finiteDuration,finiteNumber}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{DebounceController}from"../../../internal/debounce-controller.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_textareaCharacterCount,LYRA_DEFAULT_textareaCharactersRemaining,LYRA_DEFAULT_textareaLabel}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings/shared.generated.js";const COUNT_ANNOUNCE_DELAY_MS=1e3;class LyraTextareaBase extends LyraElement{}class LyraTextarea extends FormAssociated(LyraTextareaBase){static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,textareaCharacterCount:LYRA_DEFAULT_textareaCharacterCount,textareaCharactersRemaining:LYRA_DEFAULT_textareaCharactersRemaining,textareaLabel:LYRA_DEFAULT_textareaLabel,valueInvalid:LYRA_DEFAULT_valueInvalid}}static get validators(){return[currentValidityValidator("required","disabled","readonly","value","minlength","maxlength")]}static{this.styles=[LyraElement.styles,sizes,styles]}get value(){return super.value}set value(next){const normalized=next??"";super.value=normalized,this.settlingValueFromInput||this.settledDebounce.cancelIfChanged(normalized)}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=normalizeAutocorrect(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 defaultValueAlias(){return this.defaultValue}set defaultValueAlias(next){this.defaultValue=next??""}constructor(){super(),this.rows=4,this.resize="vertical",this.size="m",this.appearance="outlined",this.filled=!1,this.pill=!1,this.withCount=!1,this.placeholder="",this.readonly=!1,this.label="",this.hint="",this.helpText="",this.withLabel=!1,this.withHint=!1,this.errorText="",this.accessibleLabel=null,this.spellcheck=!0,this.autofocus=!1,this.title="",this.autocapitalize="",this.autocorrectValue=!0,this.wrap="soft",this.autocomplete="",this.inputMode="",this.enterKeyHint="",this.touched=!1,this.countAnnounceDelay=COUNT_ANNOUNCE_DELAY_MS,this.announcedCountText="",this.slotPresence=new SlotPresenceController(this),this.settlingValueFromInput=!1,this.settledDebounce=new DebounceController(0,value=>{this.emit("lr-input-settled",{value})}),this.resizeRaf=new OwnedFrame(this),this.countAnnounceTimer=new OwnedTimeout(this),this.hostDescription=new HostDescriptionController(this,()=>this.textareaEl??null),this.onInput=event=>{if(this.liveDisabled){event.stopPropagation();return}this.textareaEl&&(this.settlingValueFromInput=!0,this.value=this.textareaEl.value,this.settlingValueFromInput=!1,this.resize==="auto"&&this.fitToContent(),this.scheduleCountAnnouncement(),relayNativeEvent(this,event),this.emit("lr-input",{value:this.value}),this.isDebounced()?(this.settledDebounce.delayMs=this.effectiveDebounceMs,this.settledDebounce.push(this.value)):this.settledDebounce.cancel())},this.onChange=event=>{if(this.liveDisabled){event.stopPropagation();return}this.textareaEl&&(this.settledDebounce.flush(),this.value=this.textareaEl.value,relayNativeEvent(this,event),this.emit("lr-change",{value:this.value}))},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onBlur=event=>{this.liveDisabled||(this.touched=!0),this.settledDebounce.flush(),relayNativeEvent(this,event)},this.onKeyDown=event=>{if(this.liveDisabled){event.stopPropagation();return}event.key==="Enter"&&this.settledDebounce.flush()},this.addEventListener("invalid",()=>{this.touched=!0})}get input(){return this.textareaEl??null}get selectionStart(){return this.textareaEl?.selectionStart??null}set selectionStart(value){this.textareaEl&&(this.textareaEl.selectionStart=value??0)}get selectionEnd(){return this.textareaEl?.selectionEnd??null}set selectionEnd(value){this.textareaEl&&(this.textareaEl.selectionEnd=value??0)}get selectionDirection(){return this.textareaEl?.selectionDirection}set selectionDirection(value){this.textareaEl&&(this.textareaEl.selectionDirection=value??"none")}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}click(){this.liveDisabled||this.textareaEl?.click()}focus(options){this.liveDisabled||this.textareaEl?.focus(options)}blur(){this.textareaEl?.blur()}select(){this.textareaEl?.select()}setSelectionRange(selectionStart,selectionEnd,selectionDirection="none"){this.textareaEl?.setSelectionRange(selectionStart,selectionEnd,selectionDirection)}scrollPosition(position){const ta=this.textareaEl;if(ta){if(position){position.top!==void 0&&(ta.scrollTop=finiteNumber(position.top,ta.scrollTop)),position.left!==void 0&&(ta.scrollLeft=finiteNumber(position.left,ta.scrollLeft));return}return{top:ta.scrollTop,left:ta.scrollLeft}}}setRangeText(replacement,start,end,selectMode="preserve"){const ta=this.textareaEl;ta&&(setNativeRangeText(ta,replacement,start,end,selectMode),this.value=ta.value,this.fitToContent())}connectedCallback(){super.connectedCallback(),this.countAnnouncementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.resize==="auto"&&this.hasUpdated&&(this.armResizeObserver(),this.fitToContent())}disconnectedCallback(){this.settledDebounce.cancel(),this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeRaf.cancel(),this.countAnnounceTimer.cancel(),this.countAnnouncementSink?.release(),this.countAnnouncementSink=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted()}countText(){const format=getNumberFormat(this.effectiveLocale),max=normalizeLengthLimit(this.maxlength);if(max!==void 0){const remaining=Math.max(0,max-this.value.length);return this.localize("textareaCharactersRemaining",void 0,{count:format.format(remaining),pluralCount:remaining})}const length=this.value.length;return this.localize("textareaCharacterCount",void 0,{count:format.format(length),pluralCount:length})}scheduleCountAnnouncement(){this.countAnnounceTimer.cancel(),this.withCount&&this.countAnnounceTimer.schedule(this.countAnnounceDelay,()=>{if(!this.withCount||!isAccessibilityVisible(this))return;const text=this.countText();this.announcedCountText=text,this.countAnnouncementSink?.announce(text)})}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}if(this.required&&this.value===""){this[SET_ANCHORED_VALIDITY]({valueMissing:!0},this.localize("fieldRequired"));return}const native=this.textareaEl;native&&native.value!==this.value&&(native.value=this.value);const own=lengthViolations(this.value,this.minlength,this.maxlength),tooShort=!!native?.validity.tooShort||own.tooShort,tooLong=!!native?.validity.tooLong||own.tooLong;if(!tooShort&&!tooLong){this[SET_ANCHORED_VALIDITY]({});return}this[SET_ANCHORED_VALIDITY]({tooShort,tooLong},native?.validationMessage||this.localize("valueInvalid"))}updated(changed){super.updated(changed),changed.has("value")&&setCustomState(this.internals,"blank",this.value===""),this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),(changed.has("minlength")||changed.has("maxlength")||changed.has("readonly"))&&this.updateValidity(),changed.has("resize")&&(this.resize==="auto"?this.armResizeObserver():changed.get("resize")==="auto"&&(this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeRaf.cancel(),this.textareaEl&&(this.textareaEl.style.blockSize="",this.textareaEl.style.overflowY=""))),this.resize==="auto"&&(this.armResizeObserver(),(changed.has("value")||changed.has("rows")||changed.has("resize"))&&this.fitToContent())}formResetCallback(){super.formResetCallback(),this.touched=!1}armResizeObserver(){const textarea=this.textareaEl;if(this.resizeObserver||!textarea)return;const view=this.ownerDocument.defaultView,ResizeObserverCtor=view?.ResizeObserver;!view||!ResizeObserverCtor||(this.lastObservedWidth=textarea.getBoundingClientRect().width,this.resizeObserver=new ResizeObserverCtor(entries=>{if(!this.isConnected||this.ownerDocument.defaultView!==view)return;const width=entries[0]?.contentRect.width;width===void 0||this.lastObservedWidth!==void 0&&Math.abs(width-this.lastObservedWidth)<.5||(this.lastObservedWidth=width,this.resizeRaf.schedule(()=>{this.fitToContent()}))}),this.resizeObserver.observe(textarea))}fitToContent(){const ta=this.textareaEl;if(!ta||this.resize!=="auto")return;ta.style.blockSize="auto";const computed=ta.ownerDocument.defaultView?.getComputedStyle(ta);if(!computed)return;const borderBlock=parseFloat(computed.borderBlockStartWidth)+parseFloat(computed.borderBlockEndWidth),parsedMax=parseFloat(computed.maxBlockSize),maxBlockSize=Number.isFinite(parsedMax)?parsedMax:Number.POSITIVE_INFINITY,contentBlockSize=ta.scrollHeight+borderBlock;ta.style.blockSize=`${Math.min(contentBlockSize,maxBlockSize)}px`,ta.style.overflowY="auto"}get effectiveDebounceMs(){return finiteDuration(this.debounce??0,0)}isDebounced(){return this.effectiveDebounceMs>0}render(){const hasHint=this.slotPresence.has("hint")||this.slotPresence.has("help-text")||(this.hint??"").length>0||(this.helpText??"").length>0||this.withHint,hasError=this.slotPresence.has("error")||(this.errorText??"").length>0,hasLabel=this.slotPresence.has("label")||(this.label??"").length>0||this.withLabel,describedBy=[hasError?"textarea-error":"",hasHint?"textarea-hint":""].filter(Boolean).join(" "),cssResize=this.resize==="auto"?"none":sanitizeCssResize(this.resize,"vertical");return html`
|
|
1
|
+
import{__decorate}from"tslib";import{setNativeRangeText,nativeAutocorrectAttribute}from"../../../internal/native-text-control.js";import{renderFormControlHintError}from"../../../internal/form-control-template.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{isAccessibilityVisible}from"../../../internal/accessibility-visibility.js";import{LyraElement}from"../../../internal/lyra-element.js";import{OwnedFrame,OwnedTimeout}from"../../../internal/owned-timer.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY}from"../../../internal/anchored-validity.js";import{setCustomState}from"../../../internal/custom-states.js";import{lengthLimitConverter,lengthViolations,normalizeLengthLimit}from"../../../internal/length-constraints.js";import{styles}from"./textarea.styles.js";import{sizes}from"../../../internal/sizes.styles.js";import{autocorrectConverter,normalizeAutocorrect,spellcheckConverter}from"../../../internal/converters.js";import{sanitizeCssResize}from"../../../internal/safe-css.js";import{finiteDuration,finiteNumber}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{DebounceController}from"../../../internal/debounce-controller.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_textareaCharacterCount,LYRA_DEFAULT_textareaCharactersRemaining,LYRA_DEFAULT_textareaLabel}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings/shared.generated.js";const COUNT_ANNOUNCE_DELAY_MS=1e3;class LyraTextareaBase extends LyraElement{}class LyraTextarea extends FormAssociated(LyraTextareaBase){static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,textareaCharacterCount:LYRA_DEFAULT_textareaCharacterCount,textareaCharactersRemaining:LYRA_DEFAULT_textareaCharactersRemaining,textareaLabel:LYRA_DEFAULT_textareaLabel,valueInvalid:LYRA_DEFAULT_valueInvalid}}static get validators(){return[currentValidityValidator("required","disabled","readonly","value","minlength","maxlength")]}static{this.styles=[LyraElement.styles,sizes,styles]}get value(){return super.value}set value(next){const normalized=next??"";super.value=normalized,this.settlingValueFromInput||this.settledDebounce.cancelIfChanged(normalized)}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=normalizeAutocorrect(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 defaultValueAlias(){return this.defaultValue}set defaultValueAlias(next){this.defaultValue=next??""}constructor(){super(),this.rows=4,this.resize="vertical",this.size="m",this.appearance="outlined",this.filled=!1,this.pill=!1,this.withCount=!1,this.placeholder="",this.readonly=!1,this.label="",this.hint="",this.helpText="",this.withLabel=!1,this.withHint=!1,this.errorText="",this.accessibleLabel=null,this.spellcheck=!0,this.autofocus=!1,this.title="",this.autocapitalize="",this.autocorrectValue=!0,this.wrap="soft",this.autocomplete="",this.inputMode="",this.enterKeyHint="",this.touched=!1,this.countAnnounceDelay=COUNT_ANNOUNCE_DELAY_MS,this.announcedCountText="",this.slotPresence=new SlotPresenceController(this),this.settlingValueFromInput=!1,this.settledDebounce=new DebounceController(0,value=>{this.emit("lr-input-settled",{value})}),this.resizeRaf=new OwnedFrame(this),this.countAnnounceTimer=new OwnedTimeout(this),this.hostDescription=new HostDescriptionController(this,()=>this.textareaEl??null),this.onInput=event=>{if(this.liveDisabled){event.stopPropagation();return}this.textareaEl&&(this.settlingValueFromInput=!0,this.value=this.textareaEl.value,this.settlingValueFromInput=!1,this.resize==="auto"&&this.fitToContent(),this.scheduleCountAnnouncement(),relayNativeEvent(this,event),this.emit("lr-input",{value:this.value}),this.isDebounced()?(this.settledDebounce.delayMs=this.effectiveDebounceMs,this.settledDebounce.push(this.value)):this.settledDebounce.cancel())},this.onChange=event=>{if(this.liveDisabled){event.stopPropagation();return}this.textareaEl&&(this.settledDebounce.flush(),this.value=this.textareaEl.value,relayNativeEvent(this,event),this.emit("lr-change",{value:this.value}))},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onBlur=event=>{this.liveDisabled||(this.touched=!0),this.settledDebounce.flush(),relayNativeEvent(this,event)},this.onKeyDown=event=>{if(this.liveDisabled){event.stopPropagation();return}event.key==="Enter"&&this.settledDebounce.flush()},this.addEventListener("invalid",()=>{this.touched=!0})}get input(){return this.textareaEl??null}get selectionStart(){return this.textareaEl?.selectionStart??null}set selectionStart(value){this.textareaEl&&(this.textareaEl.selectionStart=value??0)}get selectionEnd(){return this.textareaEl?.selectionEnd??null}set selectionEnd(value){this.textareaEl&&(this.textareaEl.selectionEnd=value??0)}get selectionDirection(){return this.textareaEl?.selectionDirection}set selectionDirection(value){this.textareaEl&&(this.textareaEl.selectionDirection=value??"none")}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}click(){this.liveDisabled||this.textareaEl?.click()}focus(options){this.liveDisabled||this.textareaEl?.focus(options)}blur(){this.textareaEl?.blur()}select(){this.textareaEl?.select()}setSelectionRange(selectionStart,selectionEnd,selectionDirection="none"){this.textareaEl?.setSelectionRange(selectionStart,selectionEnd,selectionDirection)}scrollPosition(position){const ta=this.textareaEl;if(ta){if(position){position.top!==void 0&&(ta.scrollTop=finiteNumber(position.top,ta.scrollTop)),position.left!==void 0&&(ta.scrollLeft=finiteNumber(position.left,ta.scrollLeft));return}return{top:ta.scrollTop,left:ta.scrollLeft}}}setRangeText(replacement,start,end,selectMode="preserve"){const ta=this.textareaEl;ta&&(setNativeRangeText(ta,replacement,start,end,selectMode),this.value=ta.value,this.fitToContent())}connectedCallback(){super.connectedCallback(),this.countAnnouncementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.resize==="auto"&&this.hasUpdated&&(this.armResizeObserver(),this.fitToContent())}disconnectedCallback(){this.settledDebounce.cancel(),this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeRaf.cancel(),this.countAnnounceTimer.cancel(),this.countAnnouncementSink?.release(),this.countAnnouncementSink=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted()}countText(){const format=getNumberFormat(this.effectiveLocale),max=normalizeLengthLimit(this.maxlength);if(max!==void 0){const remaining=Math.max(0,max-this.value.length);return this.localize("textareaCharactersRemaining",void 0,{count:format.format(remaining),pluralCount:remaining})}const length=this.value.length;return this.localize("textareaCharacterCount",void 0,{count:format.format(length),pluralCount:length})}scheduleCountAnnouncement(){this.countAnnounceTimer.cancel(),this.withCount&&this.countAnnounceTimer.schedule(this.countAnnounceDelay,()=>{if(!this.withCount||!isAccessibilityVisible(this))return;const text=this.countText();this.announcedCountText=text,this.countAnnouncementSink?.announce(text)})}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}if(this.required&&this.value===""){this[SET_ANCHORED_VALIDITY]({valueMissing:!0},this.localize("fieldRequired"));return}const native=this.textareaEl;native&&native.value!==this.value&&(native.value=this.value);const own=lengthViolations(this.value,this.minlength,this.maxlength),tooShort=!!native?.validity.tooShort||own.tooShort,tooLong=!!native?.validity.tooLong||own.tooLong;if(!tooShort&&!tooLong){this[SET_ANCHORED_VALIDITY]({});return}this[SET_ANCHORED_VALIDITY]({tooShort,tooLong},native?.validationMessage||this.localize("valueInvalid"))}updated(changed){super.updated(changed),changed.has("value")&&setCustomState(this.internals,"blank",this.value===""),this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),(changed.has("minlength")||changed.has("maxlength")||changed.has("readonly"))&&this.updateValidity(),changed.has("resize")&&(this.resize==="auto"?this.armResizeObserver():changed.get("resize")==="auto"&&(this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeRaf.cancel(),this.textareaEl&&(this.textareaEl.style.blockSize="",this.textareaEl.style.overflowY=""))),this.resize==="auto"&&(this.armResizeObserver(),(changed.has("value")||changed.has("rows")||changed.has("resize"))&&this.fitToContent())}formResetCallback(){super.formResetCallback(),this.touched=!1}armResizeObserver(){if(!this.isConnected)return;const textarea=this.textareaEl;if(this.resizeObserver||!textarea)return;const view=this.ownerDocument.defaultView,ResizeObserverCtor=view?.ResizeObserver;if(!view||!ResizeObserverCtor)return;this.lastObservedWidth=textarea.getBoundingClientRect().width;const observer=new ResizeObserverCtor(entries=>{if(!this.isConnected||this.ownerDocument.defaultView!==view||this.resizeObserver!==observer)return;const width=entries[0]?.contentRect.width;width===void 0||this.lastObservedWidth!==void 0&&Math.abs(width-this.lastObservedWidth)<.5||(this.lastObservedWidth=width,this.resizeRaf.schedule(()=>{this.fitToContent()}))});this.resizeObserver=observer,observer.observe(textarea)}fitToContent(){const ta=this.textareaEl;if(!this.isConnected||!ta||this.resize!=="auto")return;ta.style.blockSize="auto";const computed=ta.ownerDocument.defaultView?.getComputedStyle(ta);if(!computed)return;const borderBlock=parseFloat(computed.borderBlockStartWidth)+parseFloat(computed.borderBlockEndWidth),parsedMax=parseFloat(computed.maxBlockSize),maxBlockSize=Number.isFinite(parsedMax)?parsedMax:Number.POSITIVE_INFINITY,contentBlockSize=ta.scrollHeight+borderBlock;ta.style.blockSize=`${Math.min(contentBlockSize,maxBlockSize)}px`,ta.style.overflowY="auto"}get effectiveDebounceMs(){return finiteDuration(this.debounce??0,0)}isDebounced(){return this.effectiveDebounceMs>0}render(){const hasHint=this.slotPresence.has("hint")||this.slotPresence.has("help-text")||(this.hint??"").length>0||(this.helpText??"").length>0||this.withHint,hasError=this.slotPresence.has("error")||(this.errorText??"").length>0,hasLabel=this.slotPresence.has("label")||(this.label??"").length>0||this.withLabel,describedBy=[hasError?"textarea-error":"",hasHint?"textarea-hint":""].filter(Boolean).join(" "),cssResize=this.resize==="auto"?"none":sanitizeCssResize(this.resize,"vertical");return html`
|
|
2
2
|
<div part="form-control">
|
|
3
3
|
<label part="form-control-label" for="textarea" ?hidden=${!hasLabel}>
|
|
4
4
|
<span part="label">${this.label}<slot name="label"></slot></span>
|