@aceshooting/lyra-ui 8.1.0 → 8.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +39 -0
- package/custom-elements.json +1 -1
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.d.ts +5 -0
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +1 -1
- package/dist/components/charts/chart/chart.class.js +1 -1
- package/dist/components/conversation/chat-composer/chat-composer.class.js +1 -1
- package/dist/components/conversation/model-select/model-select.class.js +1 -1
- package/dist/components/conversation/voice-picker/voice-picker.class.js +1 -1
- package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +4 -0
- package/dist/components/data/graph-query-builder/graph-query-builder.class.js +1 -1
- package/dist/components/forms/checkbox/checkbox.class.js +1 -1
- package/dist/components/forms/checkbox-group/checkbox-group.class.d.ts +3 -0
- package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
- package/dist/components/forms/code-editor/code-editor.class.js +1 -1
- package/dist/components/forms/combobox/combobox.class.js +1 -1
- package/dist/components/forms/date-picker/date-input.class.js +1 -1
- package/dist/components/forms/emoji-picker/emoji-picker.class.js +1 -1
- package/dist/components/forms/input/input.class.js +1 -1
- package/dist/components/forms/input/time-input.class.js +1 -1
- package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
- package/dist/components/forms/otp-input/otp-input.class.js +1 -1
- package/dist/components/forms/phone-input/phone-input.class.js +1 -1
- package/dist/components/forms/radio/radio-group.class.d.ts +3 -0
- package/dist/components/forms/radio/radio-group.class.js +1 -1
- package/dist/components/forms/rubric-form/rubric-form.class.d.ts +3 -0
- package/dist/components/forms/rubric-form/rubric-form.class.js +1 -1
- package/dist/components/forms/select/select.class.js +1 -1
- package/dist/components/forms/switch/switch.class.js +1 -1
- package/dist/components/forms/textarea/textarea.class.js +1 -1
- package/dist/components/forms/token-input/token-input.class.js +1 -1
- package/dist/components/media/file-input/file-input.class.js +1 -1
- package/dist/components/utility/known-date/known-date.class.js +1 -1
- package/dist/internal/form-associated.js +1 -1
- package/dist/internal/localization-runtime.d.ts +13 -0
- package/dist/internal/localization-runtime.js +1 -1
- package/dist/internal/lyra-element.d.ts +15 -0
- package/dist/internal/lyra-element.js +1 -1
- package/dist/internal/package-metadata.d.ts +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/testing/happy-dom-shims.d.ts +1 -1
- package/dist/testing/happy-dom-shims.js +1 -1
- package/llms/components/lr-checkbox-group.md +2 -0
- package/llms/components/lr-graph-query-builder.md +3 -1
- package/llms/components/lr-radio-group.md +3 -1
- package/llms/components/lr-rubric-form.md +2 -0
- package/llms/components/lr-tool-param-form.md +3 -0
- package/llms/peers.md +1 -1
- package/llms-full.txt +13 -2
- package/package.json +4 -4
- package/web-types.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated}from"../../../internal/form-associated.js";import{finiteInteger}from"../../../internal/numbers.js";import{styles}from"./code-editor.styles.js";import{presenceTrueDefaultBooleanConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{sanitizeCssResize}from"../../../internal/safe-css.js";import{LYRA_DEFAULT_codeEditorLabel,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_restore}from"../../../internal/default-strings.generated.js";class LyraCodeEditorBase extends LyraElement{}class LyraCodeEditor extends FormAssociated(LyraCodeEditorBase){constructor(){super(...arguments);this.language="";this.lineNumbers=true;this._tabSize=2;this.tabSizeAssigned=false;this.label="";this.hint="";this.errorText="";this.placeholder="";this.readonly=false;this.resize="both";this.wrap="off";this.spellcheck=false;this.autocapitalize="off";this.autoCorrect="off";this.accessibleLabel="";this.touched=false;this.hasLabelSlot=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.onInput=event=>{this.value=event.target.value;this.emit("input",{value:this.value})};this.onChange=()=>{this.emit("change",{value:this.value})};this.onFocus=()=>{this.emit("focus")};this.onBlur=()=>{this.touched=true;this.tabBypassArmed=false;this.emit("blur")};this.tabBypassArmed=false;this.onKeyDown=event=>{if(event.key==="Escape"){this.tabBypassArmed=true;return}if(event.key==="Tab"){if(event.shiftKey)return;if(this.tabBypassArmed){this.tabBypassArmed=false;return}if(this.readonly)return;event.preventDefault();const target=event.target;const start=target.selectionStart;target.setRangeText(" ".repeat(this.indentWidth),start,target.selectionEnd,"end");this.value=target.value;this.emit("input",{value:this.value});return}this.tabBypassArmed=false};this.onLabelSlotChange=e=>{this.hasLabelSlot=e.target.assignedElements({flatten:true}).length>0};this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:true}).length>0};this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:true}).length>0}}static{this.defaultStrings={...super.defaultStrings,codeEditorLabel:LYRA_DEFAULT_codeEditorLabel,fieldRequired:LYRA_DEFAULT_fieldRequired,restore:LYRA_DEFAULT_restore}}static{this.styles=[LyraElement.styles,styles]}get tabSize(){return this._tabSize}set tabSize(value){const old=this._tabSize;this.tabSizeAssigned=value!=null;this._tabSize=finiteInteger(value,2,1,16);this.requestUpdate("tabSize",old)}get indentWidth(){if(this.tabSizeAssigned||!this.textarea)return this._tabSize;const resolved=getComputedStyle(this.textarea).tabSize.trim();if(!/^\d+(?:\.\d+)?$/.test(resolved))return this._tabSize;return finiteInteger(Number(resolved),this._tabSize,1,16)}click(){if(!this.effectiveDisabled)this.textarea?.click()}focus(options){this.textarea?.focus(options)}blur(){this.textarea?.blur()}select(){this.textarea?.select()}get selectionStart(){return this.textarea?.selectionStart??0}set selectionStart(value){if(this.textarea)this.textarea.selectionStart=value}get selectionEnd(){return this.textarea?.selectionEnd??0}set selectionEnd(value){if(this.textarea)this.textarea.selectionEnd=value}get selectionDirection(){return this.textarea?.selectionDirection??"none"}set selectionDirection(value){if(this.textarea)this.textarea.selectionDirection=value}setSelectionRange(start,end,direction){this.textarea?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectionMode){const textarea=this.textarea;if(!textarea)return;textarea.setRangeText(replacement,start??textarea.selectionStart,end??textarea.selectionEnd,selectionMode);this.value=textarea.value}willUpdate(changed){super.willUpdate(changed);if(!this.hasUpdated){this.hasLabelSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="label");this.hasHintSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="hint");this.hasErrorSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="error")}}updated(changed){super.updated(changed);if(this.textarea&&this.textarea.value!==this.value)this.textarea.value=this.value;if(changed.has("touched")||changed.has("required")||changed.has("value")){this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}}render(){const lineCount=Math.max(1,this.value.split("\n").length);const textareaStyle={resize:sanitizeCssResize(this.resize,"both"),...this.tabSizeAssigned?{"--lr-code-editor-tab-size":String(this._tabSize)}:{}};const hasLabel=this.hasLabelSlot||this.label.length>0;const hasHint=this.hasHintSlot||this.hint.length>0;const hasError=this.hasErrorSlot||this.errorText.length>0;const describedBy=[hasError?"textarea-error":"",hasHint?"textarea-hint":""].filter(Boolean).join(" ");const label=this.accessibleLabel||(hasLabel?nothing:this.localize("codeEditorLabel"));return html`<div part="form-control">
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated}from"../../../internal/form-associated.js";import{finiteInteger}from"../../../internal/numbers.js";import{styles}from"./code-editor.styles.js";import{presenceTrueDefaultBooleanConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{sanitizeCssResize}from"../../../internal/safe-css.js";import{LYRA_DEFAULT_codeEditorLabel,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_restore}from"../../../internal/default-strings.generated.js";class LyraCodeEditorBase extends LyraElement{}class LyraCodeEditor extends FormAssociated(LyraCodeEditorBase){constructor(){super(...arguments);this.language="";this.lineNumbers=true;this._tabSize=2;this.tabSizeAssigned=false;this.label="";this.hint="";this.errorText="";this.placeholder="";this.readonly=false;this.resize="both";this.wrap="off";this.spellcheck=false;this.autocapitalize="off";this.autoCorrect="off";this.accessibleLabel="";this.touched=false;this.hasLabelSlot=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.onInput=event=>{this.value=event.target.value;this.emit("input",{value:this.value})};this.onChange=()=>{this.emit("change",{value:this.value})};this.onFocus=()=>{this.emit("focus")};this.onBlur=()=>{if(!this.effectiveDisabled)this.touched=true;this.tabBypassArmed=false;this.emit("blur")};this.tabBypassArmed=false;this.onKeyDown=event=>{if(event.key==="Escape"){this.tabBypassArmed=true;return}if(event.key==="Tab"){if(event.shiftKey)return;if(this.tabBypassArmed){this.tabBypassArmed=false;return}if(this.readonly)return;event.preventDefault();const target=event.target;const start=target.selectionStart;target.setRangeText(" ".repeat(this.indentWidth),start,target.selectionEnd,"end");this.value=target.value;this.emit("input",{value:this.value});return}this.tabBypassArmed=false};this.onLabelSlotChange=e=>{this.hasLabelSlot=e.target.assignedElements({flatten:true}).length>0};this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:true}).length>0};this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:true}).length>0}}static{this.defaultStrings={...super.defaultStrings,codeEditorLabel:LYRA_DEFAULT_codeEditorLabel,fieldRequired:LYRA_DEFAULT_fieldRequired,restore:LYRA_DEFAULT_restore}}static{this.styles=[LyraElement.styles,styles]}get tabSize(){return this._tabSize}set tabSize(value){const old=this._tabSize;this.tabSizeAssigned=value!=null;this._tabSize=finiteInteger(value,2,1,16);this.requestUpdate("tabSize",old)}get indentWidth(){if(this.tabSizeAssigned||!this.textarea)return this._tabSize;const resolved=getComputedStyle(this.textarea).tabSize.trim();if(!/^\d+(?:\.\d+)?$/.test(resolved))return this._tabSize;return finiteInteger(Number(resolved),this._tabSize,1,16)}click(){if(!this.effectiveDisabled)this.textarea?.click()}focus(options){this.textarea?.focus(options)}blur(){this.textarea?.blur()}select(){this.textarea?.select()}get selectionStart(){return this.textarea?.selectionStart??0}set selectionStart(value){if(this.textarea)this.textarea.selectionStart=value}get selectionEnd(){return this.textarea?.selectionEnd??0}set selectionEnd(value){if(this.textarea)this.textarea.selectionEnd=value}get selectionDirection(){return this.textarea?.selectionDirection??"none"}set selectionDirection(value){if(this.textarea)this.textarea.selectionDirection=value}setSelectionRange(start,end,direction){this.textarea?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectionMode){const textarea=this.textarea;if(!textarea)return;textarea.setRangeText(replacement,start??textarea.selectionStart,end??textarea.selectionEnd,selectionMode);this.value=textarea.value}willUpdate(changed){super.willUpdate(changed);if(!this.hasUpdated){this.hasLabelSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="label");this.hasHintSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="hint");this.hasErrorSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="error")}}updated(changed){super.updated(changed);if(this.textarea&&this.textarea.value!==this.value)this.textarea.value=this.value;if(changed.has("touched")||changed.has("required")||changed.has("value")){this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}}render(){const lineCount=Math.max(1,this.value.split("\n").length);const textareaStyle={resize:sanitizeCssResize(this.resize,"both"),...this.tabSizeAssigned?{"--lr-code-editor-tab-size":String(this._tabSize)}:{}};const hasLabel=this.hasLabelSlot||this.label.length>0;const hasHint=this.hasHintSlot||this.hint.length>0;const hasError=this.hasErrorSlot||this.errorText.length>0;const describedBy=[hasError?"textarea-error":"",hasHint?"textarea-hint":""].filter(Boolean).join(" ");const label=this.accessibleLabel||(hasLabel?nothing:this.localize("codeEditorLabel"));return html`<div part="form-control">
|
|
2
2
|
<label part="label form-control-label" for="textarea" ?hidden=${!hasLabel}>${this.label}<slot name="label" @slotchange=${this.onLabelSlotChange}></slot></label>
|
|
3
3
|
<div part="editor" data-language=${this.language}>
|
|
4
4
|
${this.lineNumbers?html`<div part="gutter" aria-hidden="true">${lineCount<=1e3?Array.from({length:lineCount},(_v,i)=>html`<div>${i+1}</div>`):html`<span>${Array.from({length:lineCount},(_v,i)=>i+1).join("\n")}</span>`}</div>`:nothing}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{place}from"../../../internal/positioner.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon,closeIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{finiteCount,finiteDuration}from"../../../internal/numbers.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./combobox.styles.js";import{LyraOption}from"./option.class.js";import"./option.class.js";import{autocorrectConverter,omittedEmptyStringConverter,spellcheckConverter}from"../../../internal/converters.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{tag}from"../../../internal/prefix.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{isOptionSelectedDirty,wasOptionInitiallySelected,RESET_OPTION_SELECTED_FROM_OWNER,SET_OPTION_SELECTED_FROM_OWNER}from"../../../internal/option-selection.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_collapse,LYRA_DEFAULT_comboboxCreate,LYRA_DEFAULT_comboboxLabel,LYRA_DEFAULT_comboboxLoadError,LYRA_DEFAULT_comboboxOverflow,LYRA_DEFAULT_comboboxRequired,LYRA_DEFAULT_comboboxSelectedOverflow,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_loading,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_open,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_search}from"../../../internal/default-strings.generated.js";function createInternalsSafely(host){if(typeof host.attachInternals!=="function")return createNoopInternals();try{return host.attachInternals()}catch{return createNoopInternals()}}function createNoopInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:false,setFormValue(){},setValidity(){},checkValidity(){return true},reportValidity(){return true}}}class LyraCombobox extends LyraElement{static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,collapse:LYRA_DEFAULT_collapse,comboboxCreate:LYRA_DEFAULT_comboboxCreate,comboboxLabel:LYRA_DEFAULT_comboboxLabel,comboboxLoadError:LYRA_DEFAULT_comboboxLoadError,comboboxOverflow:LYRA_DEFAULT_comboboxOverflow,comboboxRequired:LYRA_DEFAULT_comboboxRequired,comboboxSelectedOverflow:LYRA_DEFAULT_comboboxSelectedOverflow,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,loading:LYRA_DEFAULT_loading,noMatches:LYRA_DEFAULT_noMatches,open:LYRA_DEFAULT_open,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},multiple:{type:Boolean,reflect:true,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},required:{type:Boolean,reflect:true,noAccessor:true},value:{noAccessor:true},name:{reflect:true,noAccessor:true,converter:omittedEmptyStringConverter},maxOptionsVisible:{type:Number,attribute:"max-options-visible",noAccessor:true},maxRender:{type:Number,attribute:"max-render",noAccessor:true},sourceDelay:{type:Number,attribute:"source-delay",noAccessor:true}}}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=Boolean(next);this.requestUpdate()}get inputmode(){return this.inputMode}set inputmode(next){this.inputMode=next??""}get enterkeyhint(){return this.enterKeyHint}set enterkeyhint(next){this.enterKeyHint=next??""}get inputValue(){return this.query}set inputValue(next){this.explicitInputValue=true;this.query=next??"";this.activeIndex=-1;if(this.source)this.runSource(this.query);this.requestUpdate()}constructor(){super();this.placeholder="";this.label="";this.hint="";this.errorText="";this.open=false;this.allowCreate=false;this.allowCustomValue=false;this.appearance="outlined";this.placement="bottom";this.size="m";this.pill=false;this.clearable=false;this.withClear=false;this.withLabel=false;this.withHint=false;this.validators=[];this.autocomplete="off";this.inputMode="";this.enterKeyHint="";this.spellcheck=false;this.autocapitalize="";this.autocorrectValue=true;this.emptyText="";this.loadingText="";this.overflowText="";this.filter=null;this.source=null;this.query="";this.explicitInputValue=false;this.activeIndex=-1;this.options=[];this.touched=false;this.slotPresence=new SlotPresenceController(this);this.loading=false;this.sourceFailed=false;this.asyncRows=[];this.sourceToken=0;this._sourceWarmed=false;this._selectedLabelCache=new Map;this._selectedRowCache=new Map;this._rowsByValue=new Map;this._fieldsetDisabled=false;this.listId=nextId("combobox-list");this.inputId=nextId("combobox-input");this._isFirstUpdate=true;this.openVetoed=false;this.transitionToken=0;this.transitionWaiters=new Map;this._selected=[];this._valueDirty=false;this._multiple=false;this._disabled=false;this._required=false;this._defaultSelected=[];this._defaultCaptured=false;this._restoredStateActive=false;this._name="";this._maxOptionsVisible=3;this._maxRender=200;this._sourceDelay=200;this.collectOptions=e=>{const slot=e.target;const previous=new Set(this.options);this.options=slot.assignedElements({flatten:true}).filter(el=>el instanceof LyraOption);if(!this._defaultCaptured){this._defaultCaptured=true;const allDefaults=this.options.filter(option=>option.defaultSelected).map(option=>option.value);const allLive=this.options.filter(option=>option.selected).map(option=>option.value);const defaults=this.multiple?allDefaults:allDefaults.slice(0,1);const live=this.multiple?allLive:allLive.slice(0,1);const initialLive=this.options.filter(option=>wasOptionInitiallySelected(option)).map(option=>option.value);const optionDirty=this.options.some(option=>isOptionSelectedDirty(option));const dirtySelected=this.options.filter(option=>isOptionSelectedDirty(option)&&option.selected);const dirtyValues=dirtySelected.map(option=>option.value);this._defaultSelected=[...defaults.length>0?defaults:initialLive.length>0?initialLive:live];const fromDefaults=defaults.length>0;const initial=optionDirty?this.multiple?allLive:dirtyValues.slice(-1)[0]?dirtyValues.slice(-1):live:fromDefaults?defaults:live;if(initial.length&&!this._restoredStateActive&&!this._valueDirty){const next=this.multiple?initial:initial[0];if(fromDefaults&&!optionDirty)this.setValue(next,false);else this.value=next;return}if(optionDirty)this._valueDirty=true}else{const newDefaults=this.options.filter(option=>!previous.has(option)&&option.defaultSelected);const newLive=this.options.filter(option=>!previous.has(option)&&option.selected&&!option.defaultSelected);this.refreshOptionDefaults();const eligible=[...!this._restoredStateActive&&!this._valueDirty?newDefaults:[],...!this._restoredStateActive?newLive:[]];if(eligible.length){const values=eligible.map(option=>option.value);const next=this.multiple?[...new Set([...this._selected,...values])]:values[values.length-1];if(newLive.length>0)this.value=next;else this.setValue(next,false);return}}this.reflectSelected()};this.onOptionChange=()=>{queueMicrotask(()=>{this.refreshOptionDefaults();this.reflectSelected();this.options=[...this.options]})};this.onDocPointer=e=>{if(!e.composedPath().includes(this))this.hide()};this.onInput=e=>{this.explicitInputValue=false;this.query=e.target.value;this.activeIndex=-1;this.show();if(this.source)this.runSource(this.query);this.emit("lr-filter",{value:this.query})};this.onInputBlur=()=>{this.touched=true;this.syncCustomStates();this.hide();this.emit("blur")};this.onInputFocus=()=>{this.show();this.emit("focus")};this.onKeyDown=e=>{const navigable=this.renderedRows.rows.filter(r=>!r.disabled);switch(e.key){case"ArrowDown":e.preventDefault();if(!this.open){void this.show();return}this.activeIndex=Math.min(navigable.length-1,this.activeIndex+1);break;case"ArrowUp":e.preventDefault();if(!this.open){void this.show();return}this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":{const activeRow=navigable[this.activeIndex];if(this.open&&this.activeIndex>=0&&activeRow){e.preventDefault();this.pickRow(activeRow);break}const create=this.createRow;if(this.open&&create){e.preventDefault();this.createOption(create.createInput);break}if(this.open&&this.allowCustomValue&&!this.multiple&&this.query.trim()){e.preventDefault();this.commitCustomValue(this.query.trim());break}if(this.effectiveDisabled)break;submitOnEnter(this,e);break}case"Escape":if(this.open){e.preventDefault();this.hide()}break;case"Home":if(this.open){e.preventDefault();this.activeIndex=0}break;case"End":if(this.open){e.preventDefault();this.activeIndex=navigable.length-1}break;case"Backspace":if(this.multiple&&!this.query&&this._selected.length){this.removeValue(this._selected[this._selected.length-1])}break}};this.onComboMouseDown=e=>{if(this.effectiveDisabled)return;if(e.target.closest("button"))return;e.preventDefault();this.renderRoot.querySelector('[part="combobox-input"]')?.focus();this.show()};this.onListboxMouseDown=e=>{e.preventDefault()};this.onListboxClick=e=>{const optionEl=e.target.closest('[part="option"]');const value=optionEl?.dataset["value"];if(value===void 0)return;const row=this._rowsByValue.get(value);if(row)this.pickRow(row)};this.internals=createInternalsSafely(this);this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);installInvalidEventAlias(this,init=>this.emit("lr-invalid",void 0,init))}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}get validationTarget(){return this.validationTargetOverride??this.inputEl??void 0}set validationTarget(next){this.validationTargetOverride=next??void 0;this.validityController.refreshAnchor()}resetValidity(){this.validityController.setCustomValidity("");this.updateValidity()}get input(){return this.inputEl??null}get selectionStart(){return this.inputEl?.selectionStart??null}set selectionStart(value){if(this.inputEl)this.inputEl.selectionStart=value}get selectionEnd(){return this.inputEl?.selectionEnd??null}set selectionEnd(value){if(this.inputEl)this.inputEl.selectionEnd=value}get selectionDirection(){return this.inputEl?.selectionDirection}set selectionDirection(value){if(this.inputEl)this.inputEl.selectionDirection=value}focus(options){this.inputEl?.focus(options)}blur(){this.inputEl?.blur()}click(){if(this.effectiveDisabled)return;this.inputEl?.focus();this.show()}select(){this.inputEl?.select()}setSelectionRange(start,end,direction){this.inputEl?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){const input=this.inputEl;if(!input)return;if(start===void 0||end===void 0){input.setRangeText(replacement)}else{input.setRangeText(replacement,start,end,selectMode)}this.explicitInputValue=true;this.query=input.value;this.activeIndex=-1;if(this.source)this.runSource(this.query)}[VALIDITY_ANCHOR](){return this.validationTarget}connectedCallback(){super.connectedCallback();this.syncSourceErrorAnnouncementSink();this.updateValidity();if(this.hasUpdated){queueMicrotask(()=>{if(this.open)this.reconnectOpenPopup();else if(this.source&&this._selected.length&&this.asyncRows.length===0){this.runSource("")}})}}adoptedCallback(){this.cleanup?.();this.cleanup=void 0;this.unbindDocumentPointer();this.clearSourceTimer();this.sourceToken+=1;this.sourceAbort?.abort();this.sourceAbort=void 0;this.releaseSourceErrorAnnouncementSink();this.syncSourceErrorAnnouncementSink()}syncSourceErrorAnnouncementSink(){if(!this.isConnected)return;if(this.sourceErrorAnnouncementSink?.element.ownerDocument===this.ownerDocument)return;this.releaseSourceErrorAnnouncementSink();this.sourceErrorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}releaseSourceErrorAnnouncementSink(){this.sourceErrorAnnouncementSink?.release();this.sourceErrorAnnouncementSink=void 0}willUpdate(changed){super.willUpdate(changed);this._isFirstUpdate=!this.hasUpdated;this.announceOpenTransition(changed);if(changed.has("source")){this.clearSourceTimer();this.sourceAbort?.abort();this.sourceAbort=void 0;this.sourceToken++;this.loading=false;this.sourceFailed=false;this.asyncRows=[];this.activeIndex=-1;this._sourceWarmed=false;if(this.source&&this.open)this.runSource(this.query)}if(!this._sourceWarmed&&this.source&&this._selected.length&&this.asyncRows.length===0){this._sourceWarmed=true;this.runSource("")}}get name(){return this._name}set name(next){const old=this._name;this._name=next??"";if(this._name){this.setAttribute("name",this._name)}else{this.removeAttribute("name")}this.syncFormValue();this.requestUpdate("name",old)}get multiple(){return this._multiple}set multiple(next){const old=this._multiple;this._multiple=Boolean(next);this.toggleAttribute("multiple",this._multiple);this.syncFormValue();this.requestUpdate("multiple",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);if(this._disabled)this.hide();this.updateValidity();this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=Boolean(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.setValue(next,true)}setValue(next,dirty){const old=this._selected;if(dirty){this._restoredStateActive=false;this._valueDirty=true}this._selected=Array.isArray(next)?[...next]:next?[next]:[];const selected=new Set(this._selected);for(const value of selected){const row=this.effectiveRows.find(candidate=>candidate.value===value)??this.asyncRows.find(candidate=>candidate.value===value);if(row)this._selectedRowCache.set(value,row)}for(const value of this._selectedRowCache.keys()){if(!selected.has(value))this._selectedRowCache.delete(value)}for(const value of this._selectedLabelCache.keys()){if(!selected.has(value))this._selectedLabelCache.delete(value)}this.syncFormValue();this.reflectSelected();this.updateValidity();this.requestUpdate("value",old)}get maxOptionsVisible(){return this._maxOptionsVisible}set maxOptionsVisible(next){const old=this._maxOptionsVisible;this._maxOptionsVisible=finiteCount(next,3);this.requestUpdate("maxOptionsVisible",old)}get maxRender(){return this._maxRender}get sourceDelay(){return this._sourceDelay}set sourceDelay(next){const old=this._sourceDelay;this._sourceDelay=finiteDuration(next,200);this.requestUpdate("sourceDelay",old)}set maxRender(next){const old=this._maxRender;this._maxRender=finiteCount(next,200);this.requestUpdate("maxRender",old)}get selectedRows(){return this._selected.map(value=>this._selectedRowCache.get(value)??this.effectiveRows.find(row=>row.value===value)??this.asyncRows.find(row=>row.value===value)).filter(row=>row!=null)}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({})}else if(this.required&&this._selected.length===0){this.validityController.setValidity({valueMissing:true},this.localize("comboboxRequired"))}else{this.validityController.setValidity({})}this.syncCustomStates()}syncCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation});setCustomState(this.internals,"blank",this._selected.length===0);setCustomState(this.internals,"disabled",this.effectiveDisabled)}syncFormValue(){const state2=JSON.stringify(this._selected);if(this.multiple){if(!this.name){this.internals.setFormValue(null,state2);return}const fd=new FormData;for(const v of this._selected)fd.append(this.name,v);this.internals.setFormValue(fd,state2)}else{this.internals.setFormValue(this._selected[0]??"",state2)}}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formResetCallback(){this.touched=false;this._restoredStateActive=false;this._valueDirty=false;const resetValues=this._defaultSelected.length>0?this._defaultSelected:this.options.filter(option=>wasOptionInitiallySelected(option)).map(option=>option.value);if(this._defaultSelected.length===0&&resetValues.length>0)this._defaultSelected=[...resetValues];const defaults=new Set(resetValues);for(const option of this.options){option[RESET_OPTION_SELECTED_FROM_OWNER](defaults.has(option.value))}this.setValue(this.multiple?[...resetValues]:resetValues[0]??"",false);this.query="";this.explicitInputValue=false}formStateRestoreCallback(state2,reason){void reason;let selected=[];if(typeof state2==="string"){try{const parsed=JSON.parse(state2);if(Array.isArray(parsed)&&parsed.every(value=>typeof value==="string"))selected=parsed}catch{}}this.value=this.multiple?selected:selected[0]??"";this._restoredStateActive=true}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;if(disabled)this.hide();this.updateValidity();this.requestUpdate()}checkValidity(){return this.internals.checkValidity()}reportValidity(){this.touched=true;this.syncCustomStates();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.syncCustomStates()}disconnectedCallback(){this.transitionToken++;this.releaseSourceErrorAnnouncementSink();super.disconnectedCallback();this.cleanup?.();this.cleanup=void 0;this.clearSourceTimer();this.sourceToken+=1;this.sourceAbort?.abort();this.sourceAbort=void 0;this.unbindDocumentPointer();this.resolveTransitionWaiters("lr-after-show");this.resolveTransitionWaiters("lr-after-hide");this.open=false}refreshOptionDefaults(){const declared=this.options.filter(option=>option.defaultSelected).map(option=>option.value);this._defaultSelected=this.multiple?declared:declared.slice(0,1);if(!this._valueDirty&&!this._restoredStateActive){this.setValue(this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??"",false)}}reflectSelected(){const sel=new Set(this._selected);for(const option of this.options){option[SET_OPTION_SELECTED_FROM_OWNER](sel.has(option.value))}}labelFor(value){return this._selectedLabelCache.get(value)??this.options.find(o=>o.value===value)?.label??this.asyncRows.find(r=>r.value===value)?.label??value}get effectiveRows(){if(this.source)return this.asyncRows;return this.filtered.map(o=>({value:o.value,label:o.label,sub:o.sub||void 0,dotColor:o.dotColor||void 0,group:o.group||void 0,disabled:o.disabled}))}get createRow(){if(!this.allowCreate)return void 0;const inputValue=this.query.trim();if(!inputValue)return void 0;const locale=this.effectiveLocale;const folded=inputValue.toLocaleLowerCase(locale);const rows=this.source?this.asyncRows:this.options.map(option=>({value:option.value,label:option.label}));if(rows.some(row=>row.value.toLocaleLowerCase(locale)===folded||row.label.toLocaleLowerCase(locale)===folded)){return void 0}return{value:inputValue,label:this.localize("comboboxCreate",void 0,{value:inputValue}),createInput:inputValue}}get renderedRows(){const all=this.effectiveRows;const create=this.createRow;if(all.length<=this.maxRender)return{rows:create?[...all,create]:all,overflow:0};const originalIndex=new Map(all.map((r,i)=>[r,i]));const capped=all.slice(0,this.maxRender);const cappedValues=new Set(capped.map(r=>r.value));let appendedOutOfCap=false;for(const v of this._selected){if(!cappedValues.has(v)){const selectedRow=all.find(r=>r.value===v);if(selectedRow){capped.push(selectedRow);appendedOutOfCap=true}}}if(appendedOutOfCap){capped.sort((a,b)=>originalIndex.get(a)-originalIndex.get(b))}if(create)capped.push(create);return{rows:capped,overflow:all.length-capped.length+(create?1:0)}}get filtered(){const locale=this.effectiveLocale;const q=this.query.trim().toLocaleLowerCase(locale);const selectedLabel=!this.multiple?this.labelFor(this._selected[0]??"")??"":"";const effective=q&&q===selectedLabel.toLocaleLowerCase(locale)?"":q;if(!effective)return this.options;const fn=this.filter??((o,query2)=>o.label.toLocaleLowerCase(locale).includes(query2)||o.searchText.toLocaleLowerCase(locale).includes(query2));return this.options.filter(o=>fn(o,effective))}get displayValue(){if(this.multiple||this.open||this.explicitInputValue)return this.query;return this._selected[0]?this.labelFor(this._selected[0]):""}announceOpenTransition(changed){this.openVetoed=false;if(!changed.has("open")||this._isFirstUpdate)return;const name=this.open?"lr-show":"lr-hide";if(!this.isConnected){this.emit("lr-hide");return}if(!this.emit(name,void 0,{cancelable:true}).defaultPrevented)return;this.openVetoed=true;this.open=!this.open;this.resolveTransitionWaiters(this.open?"lr-after-hide":"lr-after-show")}show(){if(this.open||this.effectiveDisabled)return Promise.resolve();this.resolveTransitionWaiters("lr-after-hide");const settled=this.waitForTransition("lr-after-show");this.open=true;return settled}hide(){if(!this.open)return Promise.resolve();this.resolveTransitionWaiters("lr-after-show");const settled=this.waitForTransition("lr-after-hide");this.open=false;this.activeIndex=-1;if(!this.multiple){const queryChanged=this.query!=="";this.query="";this.explicitInputValue=false;if(queryChanged&&this.source){this.asyncRows=[];this.sourceFailed=false}}return settled}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{if(this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument;this.pointerListener=listener;ownerDocument.addEventListener("pointerdown",listener)}unbindDocumentPointer(){if(this.pointerListenerDocument&&this.pointerListener){this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener)}this.pointerListenerDocument=void 0;this.pointerListener=void 0}reconnectOpenPopup(){if(!this.isConnected||!this.open)return;this.cleanup?.();this.bindDocumentPointer();const anchor=this.renderRoot.querySelector('[part="combobox"]');const listbox=this.renderRoot.querySelector('[part="listbox"]');if(anchor&&listbox){this.cleanup=place(anchor,listbox,{placement:`${this.placement}-start`})}if(this.source&&this.asyncRows.length===0)this.runSource(this.query)}updated(changed){super.updated(changed);if(changed.has("open")&&!this.openVetoed){this.cleanup?.();this.cleanup=void 0;if(this.open&&this.isConnected){this.bindDocumentPointer();if(!this._isFirstUpdate){void this.settleTransition("lr-after-show")}const anchor=this.renderRoot.querySelector('[part="combobox"]');const listbox=this.renderRoot.querySelector('[part="listbox"]');if(anchor&&listbox){this.cleanup=place(anchor,listbox,{placement:`${this.placement}-start`})}if(this.source&&this.asyncRows.length===0)this.runSource(this.query)}else if(!this.open){this.unbindDocumentPointer();if(!this._isFirstUpdate){void this.settleTransition("lr-after-hide")}}else{this.unbindDocumentPointer()}}if(changed.has("name"))this.syncFormValue();if(changed.has("touched")||changed.has("required")||changed.has("value")){this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}if(changed.has("activeIndex")){this.renderRoot.querySelector('[part="option"][data-active]')?.scrollIntoView({block:"nearest"})}}async settleTransition(event){const token=++this.transitionToken;await this.updateComplete;if(this.transitionToken!==token)return;if(this.isConnected){const view=this.ownerDocument.defaultView;if(view)await new Promise(resolve=>view.requestAnimationFrame(()=>resolve()));if(this.transitionToken!==token)return;const listbox=this.renderRoot.querySelector('[part="listbox"]');const animations=listbox?.getAnimations({subtree:true})??[];await Promise.all(animations.map(animation=>animation.finished.catch(()=>void 0)));if(this.transitionToken!==token)return}this.emit(event);this.resolveTransitionWaiters(event)}waitForTransition(event){return new Promise(resolve=>{const waiters=this.transitionWaiters.get(event)??new Set;waiters.add(resolve);this.transitionWaiters.set(event,waiters)})}resolveTransitionWaiters(event){const waiters=this.transitionWaiters.get(event);if(!waiters)return;this.transitionWaiters.delete(event);for(const resolve of waiters)resolve()}emitValueEvents(){this.emit("input",{value:this.value});this.emit("change",{value:this.value});this.emit("lr-change",{value:this.value})}createOption(inputValue){if(this.effectiveDisabled)return;const event=this.emit("lr-create",{inputValue},{cancelable:true});if(event.defaultPrevented)return;const option=this.ownerDocument.createElement(tag("option"));option.setAttribute("value",inputValue);option.textContent=inputValue;this.append(option);this.pickRow({value:inputValue,label:inputValue})}commitCustomValue(inputValue){if(this.effectiveDisabled||this.multiple||!inputValue)return;const selectionChanged=this._selected[0]!==inputValue;this._selectedLabelCache.set(inputValue,inputValue);this.value=inputValue;this.query="";this.explicitInputValue=false;void this.hide();if(selectionChanged)this.emitValueEvents()}pickRow(row){if(this.effectiveDisabled||row.disabled)return;if(row.createInput!==void 0){this.createOption(row.createInput);return}const selectionChanged=this.multiple||this._selected[0]!==row.value;if(this.multiple){const set=new Set(this._selected);if(set.has(row.value)){set.delete(row.value);this._selectedRowCache.delete(row.value)}else{set.add(row.value);this._selectedLabelCache.set(row.value,row.label);this._selectedRowCache.set(row.value,row)}this.value=[...set];this.query="";this.explicitInputValue=false}else{this._selectedLabelCache.set(row.value,row.label);this._selectedRowCache.clear();this._selectedRowCache.set(row.value,row);this.value=row.value;this.query="";this.explicitInputValue=false;this.hide()}if(this.source)this.runSource(this.query);if(selectionChanged)this.emitValueEvents()}removeValue(value){const next=this._selected.filter(v=>v!==value);if(next.length===this._selected.length)return;this.value=next;this.emitValueEvents()}clear(){const hadSelection=this._selected.length>0;const queryChanged=this.query!=="";if(!hadSelection&&!queryChanged)return;if(hadSelection)this.value=[];this.query="";this.explicitInputValue=false;if(this.source)this.runSource(this.query);if(hadSelection){this.emitValueEvents();this.emit("lr-clear")}if(queryChanged)this.emit("lr-filter",{value:this.query})}runSource(query2){const source=this.source;if(!source)return;this.clearSourceTimer();this.sourceAbort?.abort();this.sourceAbort=void 0;const token=++this.sourceToken;const ownerWindow=this.ownerDocument.defaultView;if(!this.isConnected||!ownerWindow)return;const timer={owner:ownerWindow,handle:0,token};timer.handle=ownerWindow.setTimeout(()=>{if(this.sourceTimer!==timer||token!==this.sourceToken||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow){return}this.sourceTimer=void 0;const controller=new ownerWindow.AbortController;this.sourceAbort=controller;this.loading=true;this.sourceFailed=false;Promise.resolve().then(()=>source(query2,{signal:controller.signal})).then(rows=>{if(token!==this.sourceToken||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow){return}this.asyncRows=rows;this.sourceFailed=false;const navigableCount=rows.filter(row=>!row.disabled).length;if(this.activeIndex>=navigableCount){this.activeIndex=navigableCount?navigableCount-1:-1}const selected=new Set(this._selected);for(const row of rows){if(selected.has(row.value))this._selectedRowCache.set(row.value,row)}}).catch(err=>{if(token!==this.sourceToken||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow){return}if(typeof err==="object"&&err!==null&&"name"in err&&err.name==="AbortError"){return}this.asyncRows=[];this.activeIndex=-1;this.sourceFailed=true;this.sourceErrorAnnouncementSink?.announce(this.localize("comboboxLoadError"));console.warn("<lr-combobox> source() rejected:",err)}).finally(()=>{if(token===this.sourceToken)this.loading=false})},this._sourceDelay);this.sourceTimer=timer}clearSourceTimer(){const timer=this.sourceTimer;this.sourceTimer=void 0;if(timer)timer.owner.clearTimeout(timer.handle)}renderRows(rows,activeId){const out=[];let currentGroup;let currentGroupRows=[];let groupIndex=0;const selectedSet=new Set(this._selected);const flushGroup=()=>{if(!currentGroupRows.length)return;if(currentGroup){const labelId=`${this.listId}-group-${groupIndex++}`;out.push(html`<div role="group" aria-labelledby=${labelId}>
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{place}from"../../../internal/positioner.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon,closeIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{finiteCount,finiteDuration}from"../../../internal/numbers.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./combobox.styles.js";import{LyraOption}from"./option.class.js";import"./option.class.js";import{autocorrectConverter,omittedEmptyStringConverter,spellcheckConverter}from"../../../internal/converters.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{tag}from"../../../internal/prefix.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{isOptionSelectedDirty,wasOptionInitiallySelected,RESET_OPTION_SELECTED_FROM_OWNER,SET_OPTION_SELECTED_FROM_OWNER}from"../../../internal/option-selection.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_collapse,LYRA_DEFAULT_comboboxCreate,LYRA_DEFAULT_comboboxLabel,LYRA_DEFAULT_comboboxLoadError,LYRA_DEFAULT_comboboxOverflow,LYRA_DEFAULT_comboboxRequired,LYRA_DEFAULT_comboboxSelectedOverflow,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_loading,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_open,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_search}from"../../../internal/default-strings.generated.js";function createInternalsSafely(host){if(typeof host.attachInternals!=="function")return createNoopInternals();try{return host.attachInternals()}catch{return createNoopInternals()}}function createNoopInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:false,setFormValue(){},setValidity(){},checkValidity(){return true},reportValidity(){return true}}}class LyraCombobox extends LyraElement{static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,collapse:LYRA_DEFAULT_collapse,comboboxCreate:LYRA_DEFAULT_comboboxCreate,comboboxLabel:LYRA_DEFAULT_comboboxLabel,comboboxLoadError:LYRA_DEFAULT_comboboxLoadError,comboboxOverflow:LYRA_DEFAULT_comboboxOverflow,comboboxRequired:LYRA_DEFAULT_comboboxRequired,comboboxSelectedOverflow:LYRA_DEFAULT_comboboxSelectedOverflow,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,loading:LYRA_DEFAULT_loading,noMatches:LYRA_DEFAULT_noMatches,open:LYRA_DEFAULT_open,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},multiple:{type:Boolean,reflect:true,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},required:{type:Boolean,reflect:true,noAccessor:true},value:{noAccessor:true},name:{reflect:true,noAccessor:true,converter:omittedEmptyStringConverter},maxOptionsVisible:{type:Number,attribute:"max-options-visible",noAccessor:true},maxRender:{type:Number,attribute:"max-render",noAccessor:true},sourceDelay:{type:Number,attribute:"source-delay",noAccessor:true}}}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=Boolean(next);this.requestUpdate()}get inputmode(){return this.inputMode}set inputmode(next){this.inputMode=next??""}get enterkeyhint(){return this.enterKeyHint}set enterkeyhint(next){this.enterKeyHint=next??""}get inputValue(){return this.query}set inputValue(next){this.explicitInputValue=true;this.query=next??"";this.activeIndex=-1;if(this.source)this.runSource(this.query);this.requestUpdate()}constructor(){super();this.placeholder="";this.label="";this.hint="";this.errorText="";this.open=false;this.allowCreate=false;this.allowCustomValue=false;this.appearance="outlined";this.placement="bottom";this.size="m";this.pill=false;this.clearable=false;this.withClear=false;this.withLabel=false;this.withHint=false;this.validators=[];this.autocomplete="off";this.inputMode="";this.enterKeyHint="";this.spellcheck=false;this.autocapitalize="";this.autocorrectValue=true;this.emptyText="";this.loadingText="";this.overflowText="";this.filter=null;this.source=null;this.query="";this.explicitInputValue=false;this.activeIndex=-1;this.options=[];this.touched=false;this.slotPresence=new SlotPresenceController(this);this.loading=false;this.sourceFailed=false;this.asyncRows=[];this.sourceToken=0;this._sourceWarmed=false;this._selectedLabelCache=new Map;this._selectedRowCache=new Map;this._rowsByValue=new Map;this._fieldsetDisabled=false;this.listId=nextId("combobox-list");this.inputId=nextId("combobox-input");this._isFirstUpdate=true;this.openVetoed=false;this.transitionToken=0;this.transitionWaiters=new Map;this._selected=[];this._valueDirty=false;this._multiple=false;this._disabled=false;this._required=false;this._defaultSelected=[];this._defaultCaptured=false;this._restoredStateActive=false;this._name="";this._maxOptionsVisible=3;this._maxRender=200;this._sourceDelay=200;this.collectOptions=e=>{const slot=e.target;const previous=new Set(this.options);this.options=slot.assignedElements({flatten:true}).filter(el=>el instanceof LyraOption);if(!this._defaultCaptured){this._defaultCaptured=true;const allDefaults=this.options.filter(option=>option.defaultSelected).map(option=>option.value);const allLive=this.options.filter(option=>option.selected).map(option=>option.value);const defaults=this.multiple?allDefaults:allDefaults.slice(0,1);const live=this.multiple?allLive:allLive.slice(0,1);const initialLive=this.options.filter(option=>wasOptionInitiallySelected(option)).map(option=>option.value);const optionDirty=this.options.some(option=>isOptionSelectedDirty(option));const dirtySelected=this.options.filter(option=>isOptionSelectedDirty(option)&&option.selected);const dirtyValues=dirtySelected.map(option=>option.value);this._defaultSelected=[...defaults.length>0?defaults:initialLive.length>0?initialLive:live];const fromDefaults=defaults.length>0;const initial=optionDirty?this.multiple?allLive:dirtyValues.slice(-1)[0]?dirtyValues.slice(-1):live:fromDefaults?defaults:live;if(initial.length&&!this._restoredStateActive&&!this._valueDirty){const next=this.multiple?initial:initial[0];if(fromDefaults&&!optionDirty)this.setValue(next,false);else this.value=next;return}if(optionDirty)this._valueDirty=true}else{const newDefaults=this.options.filter(option=>!previous.has(option)&&option.defaultSelected);const newLive=this.options.filter(option=>!previous.has(option)&&option.selected&&!option.defaultSelected);this.refreshOptionDefaults();const eligible=[...!this._restoredStateActive&&!this._valueDirty?newDefaults:[],...!this._restoredStateActive?newLive:[]];if(eligible.length){const values=eligible.map(option=>option.value);const next=this.multiple?[...new Set([...this._selected,...values])]:values[values.length-1];if(newLive.length>0)this.value=next;else this.setValue(next,false);return}}this.reflectSelected()};this.onOptionChange=()=>{queueMicrotask(()=>{this.refreshOptionDefaults();this.reflectSelected();this.options=[...this.options]})};this.onDocPointer=e=>{if(!e.composedPath().includes(this))this.hide()};this.onInput=e=>{this.explicitInputValue=false;this.query=e.target.value;this.activeIndex=-1;this.show();if(this.source)this.runSource(this.query);this.emit("lr-filter",{value:this.query})};this.onInputBlur=()=>{if(!this.effectiveDisabled)this.touched=true;this.syncCustomStates();this.hide();this.emit("blur")};this.onInputFocus=()=>{this.show();this.emit("focus")};this.onKeyDown=e=>{const navigable=this.renderedRows.rows.filter(r=>!r.disabled);switch(e.key){case"ArrowDown":e.preventDefault();if(!this.open){void this.show();return}this.activeIndex=Math.min(navigable.length-1,this.activeIndex+1);break;case"ArrowUp":e.preventDefault();if(!this.open){void this.show();return}this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":{const activeRow=navigable[this.activeIndex];if(this.open&&this.activeIndex>=0&&activeRow){e.preventDefault();this.pickRow(activeRow);break}const create=this.createRow;if(this.open&&create){e.preventDefault();this.createOption(create.createInput);break}if(this.open&&this.allowCustomValue&&!this.multiple&&this.query.trim()){e.preventDefault();this.commitCustomValue(this.query.trim());break}if(this.effectiveDisabled)break;submitOnEnter(this,e);break}case"Escape":if(this.open){e.preventDefault();this.hide()}break;case"Home":if(this.open){e.preventDefault();this.activeIndex=0}break;case"End":if(this.open){e.preventDefault();this.activeIndex=navigable.length-1}break;case"Backspace":if(this.multiple&&!this.query&&this._selected.length){this.removeValue(this._selected[this._selected.length-1])}break}};this.onComboMouseDown=e=>{if(this.effectiveDisabled)return;if(e.target.closest("button"))return;e.preventDefault();this.renderRoot.querySelector('[part="combobox-input"]')?.focus();this.show()};this.onListboxMouseDown=e=>{e.preventDefault()};this.onListboxClick=e=>{const optionEl=e.target.closest('[part="option"]');const value=optionEl?.dataset["value"];if(value===void 0)return;const row=this._rowsByValue.get(value);if(row)this.pickRow(row)};this.internals=createInternalsSafely(this);this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);installInvalidEventAlias(this,init=>this.emit("lr-invalid",void 0,init))}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}get validationTarget(){return this.validationTargetOverride??this.inputEl??void 0}set validationTarget(next){this.validationTargetOverride=next??void 0;this.validityController.refreshAnchor()}resetValidity(){this.validityController.setCustomValidity("");this.updateValidity()}get input(){return this.inputEl??null}get selectionStart(){return this.inputEl?.selectionStart??null}set selectionStart(value){if(this.inputEl)this.inputEl.selectionStart=value}get selectionEnd(){return this.inputEl?.selectionEnd??null}set selectionEnd(value){if(this.inputEl)this.inputEl.selectionEnd=value}get selectionDirection(){return this.inputEl?.selectionDirection}set selectionDirection(value){if(this.inputEl)this.inputEl.selectionDirection=value}focus(options){this.inputEl?.focus(options)}blur(){this.inputEl?.blur()}click(){if(this.effectiveDisabled)return;this.inputEl?.focus();this.show()}select(){this.inputEl?.select()}setSelectionRange(start,end,direction){this.inputEl?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){const input=this.inputEl;if(!input)return;if(start===void 0||end===void 0){input.setRangeText(replacement)}else{input.setRangeText(replacement,start,end,selectMode)}this.explicitInputValue=true;this.query=input.value;this.activeIndex=-1;if(this.source)this.runSource(this.query)}[VALIDITY_ANCHOR](){return this.validationTarget}connectedCallback(){super.connectedCallback();this.syncSourceErrorAnnouncementSink();this.updateValidity();if(this.hasUpdated){queueMicrotask(()=>{if(this.open)this.reconnectOpenPopup();else if(this.source&&this._selected.length&&this.asyncRows.length===0){this.runSource("")}})}}adoptedCallback(){this.cleanup?.();this.cleanup=void 0;this.unbindDocumentPointer();this.clearSourceTimer();this.sourceToken+=1;this.sourceAbort?.abort();this.sourceAbort=void 0;this.releaseSourceErrorAnnouncementSink();this.syncSourceErrorAnnouncementSink()}syncSourceErrorAnnouncementSink(){if(!this.isConnected)return;if(this.sourceErrorAnnouncementSink?.element.ownerDocument===this.ownerDocument)return;this.releaseSourceErrorAnnouncementSink();this.sourceErrorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}releaseSourceErrorAnnouncementSink(){this.sourceErrorAnnouncementSink?.release();this.sourceErrorAnnouncementSink=void 0}willUpdate(changed){super.willUpdate(changed);this._isFirstUpdate=!this.hasUpdated;this.announceOpenTransition(changed);if(changed.has("source")){this.clearSourceTimer();this.sourceAbort?.abort();this.sourceAbort=void 0;this.sourceToken++;this.loading=false;this.sourceFailed=false;this.asyncRows=[];this.activeIndex=-1;this._sourceWarmed=false;if(this.source&&this.open)this.runSource(this.query)}if(!this._sourceWarmed&&this.source&&this._selected.length&&this.asyncRows.length===0){this._sourceWarmed=true;this.runSource("")}}get name(){return this._name}set name(next){const old=this._name;this._name=next??"";if(this._name){this.setAttribute("name",this._name)}else{this.removeAttribute("name")}this.syncFormValue();this.requestUpdate("name",old)}get multiple(){return this._multiple}set multiple(next){const old=this._multiple;this._multiple=Boolean(next);this.toggleAttribute("multiple",this._multiple);this.syncFormValue();this.requestUpdate("multiple",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);if(this._disabled)this.hide();this.updateValidity();this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=Boolean(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.setValue(next,true)}setValue(next,dirty){const old=this._selected;if(dirty){this._restoredStateActive=false;this._valueDirty=true}this._selected=Array.isArray(next)?[...next]:next?[next]:[];const selected=new Set(this._selected);for(const value of selected){const row=this.effectiveRows.find(candidate=>candidate.value===value)??this.asyncRows.find(candidate=>candidate.value===value);if(row)this._selectedRowCache.set(value,row)}for(const value of this._selectedRowCache.keys()){if(!selected.has(value))this._selectedRowCache.delete(value)}for(const value of this._selectedLabelCache.keys()){if(!selected.has(value))this._selectedLabelCache.delete(value)}this.syncFormValue();this.reflectSelected();this.updateValidity();this.requestUpdate("value",old)}get maxOptionsVisible(){return this._maxOptionsVisible}set maxOptionsVisible(next){const old=this._maxOptionsVisible;this._maxOptionsVisible=finiteCount(next,3);this.requestUpdate("maxOptionsVisible",old)}get maxRender(){return this._maxRender}get sourceDelay(){return this._sourceDelay}set sourceDelay(next){const old=this._sourceDelay;this._sourceDelay=finiteDuration(next,200);this.requestUpdate("sourceDelay",old)}set maxRender(next){const old=this._maxRender;this._maxRender=finiteCount(next,200);this.requestUpdate("maxRender",old)}get selectedRows(){return this._selected.map(value=>this._selectedRowCache.get(value)??this.effectiveRows.find(row=>row.value===value)??this.asyncRows.find(row=>row.value===value)).filter(row=>row!=null)}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({})}else if(this.required&&this._selected.length===0){this.validityController.setValidity({valueMissing:true},this.localize("comboboxRequired"))}else{this.validityController.setValidity({})}this.syncCustomStates()}syncCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation});setCustomState(this.internals,"blank",this._selected.length===0);setCustomState(this.internals,"disabled",this.effectiveDisabled)}syncFormValue(){const state2=JSON.stringify(this._selected);if(this.multiple){if(!this.name){this.internals.setFormValue(null,state2);return}const fd=new FormData;for(const v of this._selected)fd.append(this.name,v);this.internals.setFormValue(fd,state2)}else{this.internals.setFormValue(this._selected[0]??"",state2)}}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formResetCallback(){this.touched=false;this._restoredStateActive=false;this._valueDirty=false;const resetValues=this._defaultSelected.length>0?this._defaultSelected:this.options.filter(option=>wasOptionInitiallySelected(option)).map(option=>option.value);if(this._defaultSelected.length===0&&resetValues.length>0)this._defaultSelected=[...resetValues];const defaults=new Set(resetValues);for(const option of this.options){option[RESET_OPTION_SELECTED_FROM_OWNER](defaults.has(option.value))}this.setValue(this.multiple?[...resetValues]:resetValues[0]??"",false);this.query="";this.explicitInputValue=false}formStateRestoreCallback(state2,reason){void reason;let selected=[];if(typeof state2==="string"){try{const parsed=JSON.parse(state2);if(Array.isArray(parsed)&&parsed.every(value=>typeof value==="string"))selected=parsed}catch{}}this.value=this.multiple?selected:selected[0]??"";this._restoredStateActive=true}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;if(disabled)this.hide();this.updateValidity();this.requestUpdate()}checkValidity(){return this.internals.checkValidity()}reportValidity(){this.touched=true;this.syncCustomStates();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.syncCustomStates()}disconnectedCallback(){this.transitionToken++;this.releaseSourceErrorAnnouncementSink();super.disconnectedCallback();this.cleanup?.();this.cleanup=void 0;this.clearSourceTimer();this.sourceToken+=1;this.sourceAbort?.abort();this.sourceAbort=void 0;this.unbindDocumentPointer();this.resolveTransitionWaiters("lr-after-show");this.resolveTransitionWaiters("lr-after-hide");this.open=false}refreshOptionDefaults(){const declared=this.options.filter(option=>option.defaultSelected).map(option=>option.value);this._defaultSelected=this.multiple?declared:declared.slice(0,1);if(!this._valueDirty&&!this._restoredStateActive){this.setValue(this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??"",false)}}reflectSelected(){const sel=new Set(this._selected);for(const option of this.options){option[SET_OPTION_SELECTED_FROM_OWNER](sel.has(option.value))}}labelFor(value){return this._selectedLabelCache.get(value)??this.options.find(o=>o.value===value)?.label??this.asyncRows.find(r=>r.value===value)?.label??value}get effectiveRows(){if(this.source)return this.asyncRows;return this.filtered.map(o=>({value:o.value,label:o.label,sub:o.sub||void 0,dotColor:o.dotColor||void 0,group:o.group||void 0,disabled:o.disabled}))}get createRow(){if(!this.allowCreate)return void 0;const inputValue=this.query.trim();if(!inputValue)return void 0;const locale=this.effectiveLocale;const folded=inputValue.toLocaleLowerCase(locale);const rows=this.source?this.asyncRows:this.options.map(option=>({value:option.value,label:option.label}));if(rows.some(row=>row.value.toLocaleLowerCase(locale)===folded||row.label.toLocaleLowerCase(locale)===folded)){return void 0}return{value:inputValue,label:this.localize("comboboxCreate",void 0,{value:inputValue}),createInput:inputValue}}get renderedRows(){const all=this.effectiveRows;const create=this.createRow;if(all.length<=this.maxRender)return{rows:create?[...all,create]:all,overflow:0};const originalIndex=new Map(all.map((r,i)=>[r,i]));const capped=all.slice(0,this.maxRender);const cappedValues=new Set(capped.map(r=>r.value));let appendedOutOfCap=false;for(const v of this._selected){if(!cappedValues.has(v)){const selectedRow=all.find(r=>r.value===v);if(selectedRow){capped.push(selectedRow);appendedOutOfCap=true}}}if(appendedOutOfCap){capped.sort((a,b)=>originalIndex.get(a)-originalIndex.get(b))}if(create)capped.push(create);return{rows:capped,overflow:all.length-capped.length+(create?1:0)}}get filtered(){const locale=this.effectiveLocale;const q=this.query.trim().toLocaleLowerCase(locale);const selectedLabel=!this.multiple?this.labelFor(this._selected[0]??"")??"":"";const effective=q&&q===selectedLabel.toLocaleLowerCase(locale)?"":q;if(!effective)return this.options;const fn=this.filter??((o,query2)=>o.label.toLocaleLowerCase(locale).includes(query2)||o.searchText.toLocaleLowerCase(locale).includes(query2));return this.options.filter(o=>fn(o,effective))}get displayValue(){if(this.multiple||this.open||this.explicitInputValue)return this.query;return this._selected[0]?this.labelFor(this._selected[0]):""}announceOpenTransition(changed){this.openVetoed=false;if(!changed.has("open")||this._isFirstUpdate)return;const name=this.open?"lr-show":"lr-hide";if(!this.isConnected){this.emit("lr-hide");return}if(!this.emit(name,void 0,{cancelable:true}).defaultPrevented)return;this.openVetoed=true;this.open=!this.open;this.resolveTransitionWaiters(this.open?"lr-after-hide":"lr-after-show")}show(){if(this.open||this.effectiveDisabled)return Promise.resolve();this.resolveTransitionWaiters("lr-after-hide");const settled=this.waitForTransition("lr-after-show");this.open=true;return settled}hide(){if(!this.open)return Promise.resolve();this.resolveTransitionWaiters("lr-after-show");const settled=this.waitForTransition("lr-after-hide");this.open=false;this.activeIndex=-1;if(!this.multiple){const queryChanged=this.query!=="";this.query="";this.explicitInputValue=false;if(queryChanged&&this.source){this.asyncRows=[];this.sourceFailed=false}}return settled}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{if(this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument;this.pointerListener=listener;ownerDocument.addEventListener("pointerdown",listener)}unbindDocumentPointer(){if(this.pointerListenerDocument&&this.pointerListener){this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener)}this.pointerListenerDocument=void 0;this.pointerListener=void 0}reconnectOpenPopup(){if(!this.isConnected||!this.open)return;this.cleanup?.();this.bindDocumentPointer();const anchor=this.renderRoot.querySelector('[part="combobox"]');const listbox=this.renderRoot.querySelector('[part="listbox"]');if(anchor&&listbox){this.cleanup=place(anchor,listbox,{placement:`${this.placement}-start`})}if(this.source&&this.asyncRows.length===0)this.runSource(this.query)}updated(changed){super.updated(changed);if(changed.has("open")&&!this.openVetoed){this.cleanup?.();this.cleanup=void 0;if(this.open&&this.isConnected){this.bindDocumentPointer();if(!this._isFirstUpdate){void this.settleTransition("lr-after-show")}const anchor=this.renderRoot.querySelector('[part="combobox"]');const listbox=this.renderRoot.querySelector('[part="listbox"]');if(anchor&&listbox){this.cleanup=place(anchor,listbox,{placement:`${this.placement}-start`})}if(this.source&&this.asyncRows.length===0)this.runSource(this.query)}else if(!this.open){this.unbindDocumentPointer();if(!this._isFirstUpdate){void this.settleTransition("lr-after-hide")}}else{this.unbindDocumentPointer()}}if(changed.has("name"))this.syncFormValue();if(changed.has("touched")||changed.has("required")||changed.has("value")){this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}if(changed.has("activeIndex")){this.renderRoot.querySelector('[part="option"][data-active]')?.scrollIntoView({block:"nearest"})}}async settleTransition(event){const token=++this.transitionToken;await this.updateComplete;if(this.transitionToken!==token)return;if(this.isConnected){const view=this.ownerDocument.defaultView;if(view)await new Promise(resolve=>view.requestAnimationFrame(()=>resolve()));if(this.transitionToken!==token)return;const listbox=this.renderRoot.querySelector('[part="listbox"]');const animations=listbox?.getAnimations({subtree:true})??[];await Promise.all(animations.map(animation=>animation.finished.catch(()=>void 0)));if(this.transitionToken!==token)return}this.emit(event);this.resolveTransitionWaiters(event)}waitForTransition(event){return new Promise(resolve=>{const waiters=this.transitionWaiters.get(event)??new Set;waiters.add(resolve);this.transitionWaiters.set(event,waiters)})}resolveTransitionWaiters(event){const waiters=this.transitionWaiters.get(event);if(!waiters)return;this.transitionWaiters.delete(event);for(const resolve of waiters)resolve()}emitValueEvents(){this.emit("input",{value:this.value});this.emit("change",{value:this.value});this.emit("lr-change",{value:this.value})}createOption(inputValue){if(this.effectiveDisabled)return;const event=this.emit("lr-create",{inputValue},{cancelable:true});if(event.defaultPrevented)return;const option=this.ownerDocument.createElement(tag("option"));option.setAttribute("value",inputValue);option.textContent=inputValue;this.append(option);this.pickRow({value:inputValue,label:inputValue})}commitCustomValue(inputValue){if(this.effectiveDisabled||this.multiple||!inputValue)return;const selectionChanged=this._selected[0]!==inputValue;this._selectedLabelCache.set(inputValue,inputValue);this.value=inputValue;this.query="";this.explicitInputValue=false;void this.hide();if(selectionChanged)this.emitValueEvents()}pickRow(row){if(this.effectiveDisabled||row.disabled)return;if(row.createInput!==void 0){this.createOption(row.createInput);return}const selectionChanged=this.multiple||this._selected[0]!==row.value;if(this.multiple){const set=new Set(this._selected);if(set.has(row.value)){set.delete(row.value);this._selectedRowCache.delete(row.value)}else{set.add(row.value);this._selectedLabelCache.set(row.value,row.label);this._selectedRowCache.set(row.value,row)}this.value=[...set];this.query="";this.explicitInputValue=false}else{this._selectedLabelCache.set(row.value,row.label);this._selectedRowCache.clear();this._selectedRowCache.set(row.value,row);this.value=row.value;this.query="";this.explicitInputValue=false;this.hide()}if(this.source)this.runSource(this.query);if(selectionChanged)this.emitValueEvents()}removeValue(value){const next=this._selected.filter(v=>v!==value);if(next.length===this._selected.length)return;this.value=next;this.emitValueEvents()}clear(){const hadSelection=this._selected.length>0;const queryChanged=this.query!=="";if(!hadSelection&&!queryChanged)return;if(hadSelection)this.value=[];this.query="";this.explicitInputValue=false;if(this.source)this.runSource(this.query);if(hadSelection){this.emitValueEvents();this.emit("lr-clear")}if(queryChanged)this.emit("lr-filter",{value:this.query})}runSource(query2){const source=this.source;if(!source)return;this.clearSourceTimer();this.sourceAbort?.abort();this.sourceAbort=void 0;const token=++this.sourceToken;const ownerWindow=this.ownerDocument.defaultView;if(!this.isConnected||!ownerWindow)return;const timer={owner:ownerWindow,handle:0,token};timer.handle=ownerWindow.setTimeout(()=>{if(this.sourceTimer!==timer||token!==this.sourceToken||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow){return}this.sourceTimer=void 0;const controller=new ownerWindow.AbortController;this.sourceAbort=controller;this.loading=true;this.sourceFailed=false;Promise.resolve().then(()=>source(query2,{signal:controller.signal})).then(rows=>{if(token!==this.sourceToken||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow){return}this.asyncRows=rows;this.sourceFailed=false;const navigableCount=rows.filter(row=>!row.disabled).length;if(this.activeIndex>=navigableCount){this.activeIndex=navigableCount?navigableCount-1:-1}const selected=new Set(this._selected);for(const row of rows){if(selected.has(row.value))this._selectedRowCache.set(row.value,row)}}).catch(err=>{if(token!==this.sourceToken||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow){return}if(typeof err==="object"&&err!==null&&"name"in err&&err.name==="AbortError"){return}this.asyncRows=[];this.activeIndex=-1;this.sourceFailed=true;this.sourceErrorAnnouncementSink?.announce(this.localize("comboboxLoadError"));console.warn("<lr-combobox> source() rejected:",err)}).finally(()=>{if(token===this.sourceToken)this.loading=false})},this._sourceDelay);this.sourceTimer=timer}clearSourceTimer(){const timer=this.sourceTimer;this.sourceTimer=void 0;if(timer)timer.owner.clearTimeout(timer.handle)}renderRows(rows,activeId){const out=[];let currentGroup;let currentGroupRows=[];let groupIndex=0;const selectedSet=new Set(this._selected);const flushGroup=()=>{if(!currentGroupRows.length)return;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">${currentGroup}</div>
|
|
3
3
|
${currentGroupRows}
|
|
4
4
|
</div>`)}else{out.push(...currentGroupRows)}currentGroupRows=[]};rows.forEach((o,i)=>{if(o.group!==currentGroup){flushGroup();currentGroup=o.group}const id=`${this.listId}-opt-${i}`;const selected=selectedSet.has(o.value);currentGroupRows.push(html`<div
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{place}from"../../../internal/positioner.js";import{nextId}from"../../../internal/a11y.js";import{closeIcon,calendarIcon,chevronIcon}from"../../../internal/icons.js";import{activateOverlay}from"../../../internal/overlay-manager.js";import{setCustomState}from"../../../internal/custom-states.js";import{finiteCount,finiteNumber}from"../../../internal/numbers.js";import{dateTimeFormat,parseISO,formatISO,normalizeCalendarMonths,normalizeWeekdayFormat}from"./calendar-core.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./date-input.styles.js";import{LyraDatePicker}from"./date-picker.class.js";import"./date-picker.class.js";import{getDateTimeFormat}from"../../../internal/intl-cache.js";import{spellcheckFromAttributeConverter as spellcheckConverter}from"../../../internal/converters.js";import{isImplicitSubmission,submitOnEnter}from"../../../internal/submit-on-enter.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{LYRA_DEFAULT_chooseDate,LYRA_DEFAULT_clear,LYRA_DEFAULT_collapse,LYRA_DEFAULT_date,LYRA_DEFAULT_dateInputFutureDisabled,LYRA_DEFAULT_dateInputInvalid,LYRA_DEFAULT_dateInputMaxMessage,LYRA_DEFAULT_dateInputMinMessage,LYRA_DEFAULT_dateInputPastDisabled,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_openCalendar,LYRA_DEFAULT_restore,LYRA_DEFAULT_search}from"../../../internal/default-strings.generated.js";function localeDateOrder(locale){try{const parts=getDateTimeFormat(locale||void 0,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2026,0,2));const order=parts.filter(p=>p.type==="day"||p.type==="month"||p.type==="year").map(p=>p.type);return order.length===3?order:["month","day","year"]}catch{return["month","day","year"]}}const monthsConverter={fromAttribute:normalizeCalendarMonths,toAttribute:normalizeCalendarMonths};const weekdayFormatConverter={fromAttribute:normalizeWeekdayFormat,toAttribute:normalizeWeekdayFormat};function normalizeDateInputAppearance(value){return value==="filled"||value==="filled-outlined"?value:"outlined"}const appearanceConverter={fromAttribute:normalizeDateInputAppearance,toAttribute:normalizeDateInputAppearance};const placements=new Set(["top","top-start","top-end","right","right-start","right-end","bottom","bottom-start","bottom-end","left","left-start","left-end"]);function normalizeDateInputPlacement(value){return typeof value==="string"&&placements.has(value)?value:"bottom-start"}const placementConverter={fromAttribute:normalizeDateInputPlacement,toAttribute:normalizeDateInputPlacement};function normalizeDateInputPageBy(value){return value==="single"?"single":"months"}const pageByConverter={fromAttribute:normalizeDateInputPageBy,toAttribute:normalizeDateInputPageBy};const VALIDITY_FLAG_KEYS=new Set(["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"]);function isValidityFlagKey(value){return typeof value==="string"&&VALIDITY_FLAG_KEYS.has(value)}class LyraDateInputBase extends LyraElement{}class LyraDateInput extends FormAssociated(LyraDateInputBase){static{this.defaultStrings={...super.defaultStrings,chooseDate:LYRA_DEFAULT_chooseDate,clear:LYRA_DEFAULT_clear,collapse:LYRA_DEFAULT_collapse,date:LYRA_DEFAULT_date,dateInputFutureDisabled:LYRA_DEFAULT_dateInputFutureDisabled,dateInputInvalid:LYRA_DEFAULT_dateInputInvalid,dateInputMaxMessage:LYRA_DEFAULT_dateInputMaxMessage,dateInputMinMessage:LYRA_DEFAULT_dateInputMinMessage,dateInputPastDisabled:LYRA_DEFAULT_dateInputPastDisabled,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,openCalendar:LYRA_DEFAULT_openCalendar,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search}}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={mode:{reflect:true,noAccessor:true},min:{reflect:true,noAccessor:true},max:{reflect:true,noAccessor:true},readonly:{type:Boolean,reflect:true,noAccessor:true},disablePast:{type:Boolean,attribute:"disable-past",reflect:true,noAccessor:true},disableFuture:{type:Boolean,attribute:"disable-future",reflect:true,noAccessor:true}}}constructor(){super();this.appearance="outlined";this.open=false;this.withClear=false;this.withHint=false;this.withLabel=false;this.size="m";this.pill=false;this.label="";this.hint="";this.errorText="";this.placeholder="";this.spellcheck=true;this.autocapitalize="";this.autoCorrect="";this.autocomplete="";this.inputMode="";this.enterKeyHint="";this.accessibleLabel=null;this.locale="";this.months=1;this.firstDayOfWeek="auto";this.weekdayFormat="short";this.withOutsideDays=false;this.withWeekNumbers=false;this.disabledDates="";this.disabledDaysOfWeek="";this.minRange=0;this.maxRange=0;this.pageBy="months";this.today="";this.distance=0;this.placement="bottom-start";this.assumeInteractionOn=["input"];this.validators=[];this.clearLabel="";this.openLabel="";this.dialogLabel="Choose date";this.enterCommittedText=null;this.inputRelayedSinceCommit=false;this.restorePopupFocusOnClose=false;this.transitionToken=0;this.transitionWaiters=new Map;this.interactionListeners=new Map;this.inputId=nextId("date-input");this.popupId=nextId("date-popup");this.touched=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.hasLabelSlot=false;this.hasStartSlot=false;this.hasEndSlot=false;this.validityRevision=0;this._mode="single";this._min="";this._max="";this._readonly=false;this._disablePast=false;this._disableFuture=false;this.typedBadInput=false;this.now=()=>new Date;this.onVisibilityChange=()=>{if(this.ownerDocument.visibilityState!=="visible")return;this.updateValidity();this.validityRevision++};this.onDocPointer=e=>{if(!e.composedPath().includes(this))void this.hide(false)};this.onInputChange=e=>{e.stopPropagation();const raw=e.target.value;if(this.enterCommittedText!==null&&(raw===this.enterCommittedText||raw===this.displayText)){return}this.enterCommittedText=null;const committed=this.applyTypedText(raw);if(committed){if(!this.inputRelayedSinceCommit){dispatchNativeInputEvent(this,{inputType:"insertReplacementText"})}this.inputRelayedSinceCommit=false;relayNativeEvent(this,e)}else{this.inputRelayedSinceCommit=false}};this.onInput=event=>{this.inputRelayedSinceCommit=true;relayNativeEvent(this,event)};this.onInputKey=e=>{if(e.altKey&&e.key==="ArrowDown"){e.preventDefault();this.show();return}if(this.effectiveDisabled||this.readonly)return;if(!isImplicitSubmission(e))return;const input=this.inputElement;if(input&&input.value!==this.displayText){const raw=input.value;if(this.applyTypedText(raw)){if(!this.inputRelayedSinceCommit){dispatchNativeInputEvent(this,{inputType:"insertReplacementText"})}this.inputRelayedSinceCommit=false;dispatchNativeEvent(this,"change")}else{this.inputRelayedSinceCommit=false}this.enterCommittedText=raw}submitOnEnter(this,e)};this.onInputBlur=event=>{this.touched=true;relayNativeEvent(this,event)};this.onInputFocus=event=>{relayNativeEvent(this,event)};this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:true}).length>0};this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:true}).length>0};this.onLabelSlotChange=e=>{this.hasLabelSlot=e.target.assignedElements({flatten:true}).length>0};this.onStartSlotChange=e=>{this.hasStartSlot=e.target.assignedElements({flatten:true}).length>0};this.onEndSlotChange=e=>{this.hasEndSlot=e.target.assignedElements({flatten:true}).length>0};this.onPickerInput=e=>{const picker=e.target;this.value=picker.value;this.inputRelayedSinceCommit=false;relayNativeEvent(this,e)};this.onPickerChange=e=>{const picker=e.target;this.value=picker.value;relayNativeEvent(this,e);this.hide(true)};this.addEventListener("invalid",()=>{this.touched=true})}get mode(){return this._mode}set mode(next){const old=this._mode;this._mode=next==="range"?"range":"single";this.internals.setFormValue(this.isIncompleteRangeValue(this.value)?"":this.value);this.updateValidity();this.syncCustomStates();this.requestUpdate("mode",old)}get min(){return this._min}set min(next){const old=this._min;this._min=next??"";this.updateValidity();this.requestUpdate("min",old)}get max(){return this._max}set max(next){const old=this._max;this._max=next??"";this.updateValidity();this.requestUpdate("max",old)}get readonly(){return this._readonly}set readonly(next){const old=this._readonly;this._readonly=Boolean(next);this.toggleAttribute("readonly",this._readonly);if(this._readonly)void this.hide();this.updateValidity();this.requestUpdate("readonly",old)}get disabled(){return super.disabled}set disabled(next){super.disabled=next;if(next)void this.hide();this.syncCustomStates()}get disablePast(){return this._disablePast}set disablePast(next){const old=this._disablePast;this._disablePast=Boolean(next);this.updateValidity();this.requestUpdate("disablePast",old)}get disableFuture(){return this._disableFuture}set disableFuture(next){const old=this._disableFuture;this._disableFuture=Boolean(next);this.updateValidity();this.requestUpdate("disableFuture",old)}get input(){return this.inputElement}get selectionStart(){return this.inputElement?.selectionStart??null}set selectionStart(value){if(this.inputElement)this.inputElement.selectionStart=value??0}get selectionEnd(){return this.inputElement?.selectionEnd??null}set selectionEnd(value){if(this.inputElement)this.inputElement.selectionEnd=value??0}get selectionDirection(){return this.inputElement?.selectionDirection??null}set selectionDirection(value){if(this.inputElement)this.inputElement.selectionDirection=value??"none"}get value(){return super.value}set value(next){this.setTypedBadInput(false);const normalized=this.normalizeCommittedValue(next??"");super.value=normalized;this.internals.setFormValue(this.isIncompleteRangeValue(normalized)?"":normalized);this.syncCustomStates()}get valueAsDate(){return this.mode==="single"?this.parseStrictISO(this.value):null}set valueAsDate(next){this.value=next instanceof Date&&Number.isFinite(next.getTime())?formatISO(next):""}get valueAsRange(){if(this.mode!=="range")return{from:null,to:null};const[from="",to=""]=this.value.split("/");return{from:this.parseStrictISO(from),to:this.parseStrictISO(to)}}set valueAsRange(next){let from=next?.from instanceof Date&&Number.isFinite(next.from.getTime())?next.from:null;let to=next?.to instanceof Date&&Number.isFinite(next.to.getTime())?next.to:null;if(from&&to&&to<from)[from,to]=[to,from];this.value=from?to?`${formatISO(from)}/${formatISO(to)}`:formatISO(from):""}get validationTarget(){return this.validationTargetOverride??this.inputElement}set validationTarget(next){const old=this.validationTarget;this.validationTargetOverride=next??void 0;this.requestUpdate("validationTarget",old)}[VALIDITY_ANCHOR](){return this.validationTarget}resetValidity(){this.setCustomValidity("");this.updateValidity()}setTypedBadInput(next){const old=this.typedBadInput;this.typedBadInput=next;if(old!==next)this.requestUpdate("typedBadInput",old)}parseStrictISO(value){if(!/^\d{4}-\d{2}-\d{2}$/.test(value))return null;return parseISO(value)}normalizeCommittedValue(value){if(value==="")return"";const parts=value.split("/");if(parts.length!==1&&parts.length!==2)return"";const dates=parts.map(part=>this.parseStrictISO(part));if(dates.some(date=>date===null))return"";if(parts.length===2&&dates[0]>dates[1])return`${parts[1]}/${parts[0]}`;return value}isIncompleteRangeValue(value){return this.mode==="range"&&value!==""&&!value.includes("/")}valueDates(value){const parts=value.split("/");const expectedParts=this.mode==="range"&&parts.length===2?2:1;if(parts.length!==expectedParts)return null;const dates=parts.map(part=>this.parseStrictISO(part));return dates.some(date=>date===null)?null:dates}configuredDisabledDateKeys(){const values=Array.isArray(this.disabledDates)?this.disabledDates:String(this.disabledDates||"").split(/[\s,]+/);return new Set(values.map(value=>value instanceof Date?value:parseISO(String(value))).filter(value=>value instanceof Date&&Number.isFinite(value.getTime())).map(value=>formatISO(value)))}configuredDisabledWeekdays(){const names={sun:0,sunday:0,mon:1,monday:1,tue:2,tues:2,tuesday:2,wed:3,wednesday:3,thu:4,thur:4,thurs:4,thursday:4,fri:5,friday:5,sat:6,saturday:6};return new Set(String(this.disabledDaysOfWeek||"").toLowerCase().split(/[\s,]+/).filter(Boolean).map(value=>names[value]??(/^[0-6]$/.test(value)?Number(value):-1)).filter(value=>value>=0))}rangeLength(from,to){const fromUtc=Date.UTC(from.getFullYear(),from.getMonth(),from.getDate());const toUtc=Date.UTC(to.getFullYear(),to.getMonth(),to.getDate());return Math.round(Math.abs(toUtc-fromUtc)/864e5)+1}validatorResult(){for(const validator of Array.isArray(this.validators)?this.validators:[]){let result;try{if(typeof validator==="object"&&validator!==null&&"checkValidity"in validator){const checked=validator.checkValidity(this);if(checked?.isValid===true)continue;const flags={};for(const key of Array.isArray(checked?.invalidKeys)?checked.invalidKeys:[]){if(isValidityFlagKey(key))flags[key]=true}if(!Object.values(flags).some(Boolean))flags.customError=true;let message=typeof checked?.message==="string"?checked.message:"";if(!message&&typeof validator.message==="string")message=validator.message;if(!message&&typeof validator.message==="function"){message=validator.message(this)}return{flags,message:message||this.localize("dateInputInvalid")}}result=typeof validator==="function"?validator(this.value,this):validator?.validate(this.value,this)}catch{return{flags:{customError:true},message:this.localize("dateInputInvalid")}}if(result===void 0||result===true)continue;if(typeof result==="string")return{flags:{customError:true},message:result};if(result===false)return{flags:{customError:true},message:this.localize("dateInputInvalid")};if(result&&typeof result==="object"&&Object.values(result).some(Boolean)){return{flags:result,message:this.localize("dateInputInvalid")}}}return{}}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let underflowMessage="";let overflowMessage="";const incompleteRange=this.isIncompleteRangeValue(this.value);if(this.required&&(this.value===""||incompleteRange))flags.valueMissing=true;if(this.typedBadInput)flags.badInput=true;if(this.value!==""){const dates=this.valueDates(this.value);if(!dates){flags.badInput=true}else{const min=this.parseStrictISO(this.min);const max=this.parseStrictISO(this.max);const configuredToday=this.parseStrictISO(this.today);const now=configuredToday??this.now();const today=new Date(now.getFullYear(),now.getMonth(),now.getDate());if(min!==null&&dates.some(date=>date<min)){flags.rangeUnderflow=true;underflowMessage=this.localize("dateInputMinMessage",void 0,{min:this.min})}if(this.disablePast&&dates.some(date=>date<today)){flags.rangeUnderflow=true;underflowMessage||=this.localize("dateInputPastDisabled")}if(max!==null&&dates.some(date=>date>max)){flags.rangeOverflow=true;overflowMessage=this.localize("dateInputMaxMessage",void 0,{max:this.max})}if(this.disableFuture&&dates.some(date=>date>today)){flags.rangeOverflow=true;overflowMessage||=this.localize("dateInputFutureDisabled")}const disabledDates=this.configuredDisabledDateKeys();const disabledWeekdays=this.configuredDisabledWeekdays();let configuredDisabled=dates.some(date=>disabledDates.has(formatISO(date))||disabledWeekdays.has(date.getDay()));if(!configuredDisabled&&this.isDateDisabled){try{configuredDisabled=dates.some(date=>Boolean(this.isDateDisabled?.(new Date(date.getTime()))))}catch{configuredDisabled=false}}if(configuredDisabled)flags.customError=true;if(this.mode==="range"&&dates.length===2){const length=this.rangeLength(dates[0],dates[1]);const minimum=finiteCount(this.minRange,0);const maximum=finiteCount(this.maxRange,0);if(minimum>0&&length<minimum){flags.rangeUnderflow=true;underflowMessage||=this.localize("dateInputInvalid")}if(maximum>0&&length>maximum){flags.rangeOverflow=true;overflowMessage||=this.localize("dateInputInvalid")}}}}const configured=this.validatorResult();if(configured.flags)Object.assign(flags,configured.flags);let message="";if(configured.message)message=configured.message;else if(flags.badInput||flags.customError)message=this.localize("dateInputInvalid");else if(flags.rangeUnderflow)message=underflowMessage;else if(flags.rangeOverflow)message=overflowMessage;else if(flags.valueMissing)message=this.localize("fieldRequired");this[SET_ANCHORED_VALIDITY](flags,message)}checkValidity(){this.updateValidity();return super.checkValidity()}reportValidity(){this.updateValidity();return super.reportValidity()}bindVisibilityListener(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.visibilityListenerDocument===ownerDocument&&this.visibilityListener)return;this.unbindVisibilityListener();const listener=()=>{if(this.visibilityListener!==listener||this.visibilityListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.onVisibilityChange()};this.visibilityListenerDocument=ownerDocument;this.visibilityListener=listener;ownerDocument.addEventListener("visibilitychange",listener)}unbindVisibilityListener(){if(this.visibilityListenerDocument&&this.visibilityListener){this.visibilityListenerDocument.removeEventListener("visibilitychange",this.visibilityListener)}this.visibilityListenerDocument=void 0;this.visibilityListener=void 0}get displayText(){const parts=this.value.split("/");const from=parseISO(parts[0]);const to=parseISO(parts[1]??"");if(!from)return"";const formatter=dateTimeFormat(this.effectiveLocale,{});const fmt=d=>formatter.format(d);return this.mode==="range"&&to?`${fmt(from)} \u2013 ${fmt(to)}`:fmt(from)}willUpdate(changed){if(!this.hasUpdated){this.hasHintSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="hint");this.hasErrorSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="error");this.hasLabelSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="label");this.hasStartSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="start");this.hasEndSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="end")}if(changed.has("open")){if(this.open&&this.isConnected){this.bindDocumentPointer()}else{this.unbindDocumentPointer()}}}show(){if(this.open||this.effectiveDisabled||this.readonly)return Promise.resolve();const request=this.emit("lr-show",void 0,{cancelable:true});if(request.defaultPrevented)return Promise.resolve();this.resolveTransitionWaiters("lr-after-hide");const settled=this.waitForTransition("lr-after-show");this.open=true;void this.settleTransition("lr-after-show");return settled}hide(restoreFocus=false){if(!this.open)return Promise.resolve();const request=this.emit("lr-hide",void 0,{cancelable:true});if(request.defaultPrevented)return Promise.resolve();this.resolveTransitionWaiters("lr-after-show");const settled=this.waitForTransition("lr-after-hide");this.restorePopupFocusOnClose||=restoreFocus;this.open=false;void this.settleTransition("lr-after-hide");return settled}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{if(this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument;this.pointerListener=listener;ownerDocument.addEventListener("pointerdown",listener)}unbindDocumentPointer(){if(this.pointerListenerDocument&&this.pointerListener){this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener)}this.pointerListenerDocument=void 0;this.pointerListener=void 0}reconnectOpenPopup(){if(!this.isConnected||!this.open)return;this.bindDocumentPointer();this.cleanupFn?.();const anchor=this.renderRoot.querySelector('[part="input-wrapper"]');const popup=this.renderRoot.querySelector('[part="popup"]');if(!anchor||!popup)return;this.cleanupFn=place(anchor,popup,{placement:normalizeDateInputPlacement(this.placement),offset:finiteNumber(this.distance,0)});this.overlayHandle?.deactivate({restoreFocus:false});this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="popup"]'),onEscape:()=>{void this.hide(true)},modal:false,trapFocus:false})}async settleTransition(event){const token=++this.transitionToken;await this.updateComplete;if(this.transitionToken!==token)return;if(this.isConnected){const view=this.ownerDocument.defaultView;if(view)await new Promise(resolve=>view.requestAnimationFrame(()=>resolve()));if(this.transitionToken!==token)return;const popup=this.renderRoot.querySelector('[part="popup"]');const animations=popup?.getAnimations({subtree:true})??[];await Promise.all(animations.map(animation=>animation.finished.catch(()=>void 0)));if(this.transitionToken!==token)return}this.emit(event);this.resolveTransitionWaiters(event)}waitForTransition(event){return new Promise(resolve=>{const waiters=this.transitionWaiters.get(event)??new Set;waiters.add(resolve);this.transitionWaiters.set(event,waiters)})}resolveTransitionWaiters(event){const waiters=this.transitionWaiters.get(event);if(!waiters)return;this.transitionWaiters.delete(event);for(const resolve of waiters)resolve()}connectedCallback(){super.connectedCallback();this.bindVisibilityListener();this.syncInteractionListeners();this.syncValidatorAttributeObserver();this.syncCustomStates();if(this.hasUpdated&&this.open)queueMicrotask(()=>this.reconnectOpenPopup())}clear(){if(!this.value||this.effectiveDisabled||this.readonly)return;this.touched=true;this.value="";this.emit("lr-clear");this.inputRelayedSinceCommit=false;dispatchNativeInputEvent(this,{inputType:"deleteContentBackward"});dispatchNativeEvent(this,"change")}syncInteractionListeners(){const requested=new Set((Array.isArray(this.assumeInteractionOn)?this.assumeInteractionOn:[]).filter(name=>typeof name==="string"&&name.length>0));for(const[name,listener]of this.interactionListeners){if(requested.has(name))continue;this.removeEventListener(name,listener);this.interactionListeners.delete(name)}for(const name of requested){if(this.interactionListeners.has(name))continue;const listener=()=>{this.touched=true;this.syncCustomStates()};this.addEventListener(name,listener);this.interactionListeners.set(name,listener)}}syncValidatorAttributeObserver(){this.disconnectValidatorAttributeObserver();const owner=this.ownerDocument.defaultView;const MutationObserverCtor=owner?.MutationObserver;if(!this.isConnected||!owner||typeof MutationObserverCtor!=="function")return;const attributes=new Set;for(const validator of Array.isArray(this.validators)?this.validators:[]){if(typeof validator!=="object"||validator===null||!("checkValidity"in validator))continue;let observed;try{observed=validator.observedAttributes}catch{continue}if(!Array.isArray(observed))continue;for(const name of observed){if(typeof name==="string"&&name.length>0)attributes.add(name)}}if(attributes.size===0)return;const binding={};const observer=new MutationObserverCtor(()=>{if(this.validatorAttributeObserver!==binding||!this.isConnected||this.ownerDocument.defaultView!==owner)return;this.updateValidity();this.validityRevision++});binding.observer=observer;binding.owner=owner;try{observer.observe(this,{attributes:true,attributeFilter:[...attributes]});this.validatorAttributeObserver=binding}catch{observer.disconnect()}}disconnectValidatorAttributeObserver(){const binding=this.validatorAttributeObserver;this.validatorAttributeObserver=void 0;binding?.observer.disconnect()}syncCustomStates(){setCustomState(this.internals,"blank",this.value==="");setCustomState(this.internals,"disabled",this.effectiveDisabled);setCustomState(this.internals,"open",this.open);setCustomState(this.internals,"range",this.mode==="range")}disconnectedCallback(){this.transitionToken++;this.cleanupFn?.();this.cleanupFn=void 0;this.overlayHandle?.deactivate({restoreFocus:false});this.overlayHandle=void 0;this.unbindVisibilityListener();this.unbindDocumentPointer();this.disconnectValidatorAttributeObserver();this.restorePopupFocusOnClose=false;this.resolveTransitionWaiters("lr-after-show");this.resolveTransitionWaiters("lr-after-hide");for(const[name,listener]of this.interactionListeners)this.removeEventListener(name,listener);this.interactionListeners.clear();this.enterCommittedText=null;this.inputRelayedSinceCommit=false;this.open=false;super.disconnectedCallback()}adoptedCallback(){this.cleanupFn?.();this.cleanupFn=void 0;this.overlayHandle?.deactivate({restoreFocus:false});this.overlayHandle=void 0;this.unbindVisibilityListener();this.unbindDocumentPointer();this.disconnectValidatorAttributeObserver()}updated(changed){super.updated(changed);if(changed.has("disabledDates")||changed.has("disabledDaysOfWeek")||changed.has("isDateDisabled")||changed.has("minRange")||changed.has("maxRange")||changed.has("today")||changed.has("validators")){this.updateValidity()}if(changed.has("open")||this.open&&(changed.has("placement")||changed.has("distance"))){this.cleanupFn?.();this.cleanupFn=void 0;if(this.open&&this.isConnected){const anchor=this.renderRoot.querySelector('[part="input-wrapper"]');const popup=this.renderRoot.querySelector('[part="popup"]');if(anchor&&popup){this.cleanupFn=place(anchor,popup,{placement:normalizeDateInputPlacement(this.placement),offset:finiteNumber(this.distance,0)})}}}if(changed.has("open")){if(this.open&&this.isConnected){const popup=this.renderRoot.querySelector('[part="popup"]');if(popup){this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="popup"]'),onEscape:()=>{void this.hide(true)},modal:false,trapFocus:false})}}else if(!this.open){this.overlayHandle?.deactivate({restoreFocus:this.restorePopupFocusOnClose});this.overlayHandle=void 0;this.restorePopupFocusOnClose=false}}if(changed.has("assumeInteractionOn"))this.syncInteractionListeners();if(changed.has("validators"))this.syncValidatorAttributeObserver();this.syncCustomStates();if(changed.has("touched")||changed.has("required")||changed.has("value")||changed.has("mode")||changed.has("min")||changed.has("max")||changed.has("readonly")||changed.has("disablePast")||changed.has("disableFuture")||changed.has("disabledDates")||changed.has("disabledDaysOfWeek")||changed.has("minRange")||changed.has("maxRange")||changed.has("validators")||changed.has("typedBadInput")||changed.has("validityRevision")){this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}}applyTypedText(raw){this.enterCommittedText=null;const trimmed=raw.trim();if(!trimmed){this.value="";return true}const parsed=this.mode==="range"?this.parseRangeText(trimmed):this.parseSingleText(trimmed);if(parsed){this.value=parsed;return true}if(this.inputElement)this.inputElement.value=this.displayText;this.setTypedBadInput(true);this.updateValidity();return false}parseOneDate(raw){const looksLikeISO=/^\d{4}-\d{2}-\d{2}$/.test(raw);if(looksLikeISO)return parseISO(raw);const ambiguous=/^(\d{1,4})[/.-](\d{1,4})[/.-](\d{1,4})$/.exec(raw);if(ambiguous){const[,g1,g2,g3]=ambiguous;if(g1.length===4){return parseISO(`${g1}-${g2.padStart(2,"0")}-${g3.padStart(2,"0")}`)}const order=localeDateOrder(this.effectiveLocale);const values=[Number(g1),Number(g2),Number(g3)];const fields={};order.forEach((type,i)=>{fields[type]=values[i]});if(fields.day!=null&&fields.month!=null&&fields.year!=null){const year=fields.year<100?2e3+fields.year:fields.year;return parseISO(`${String(year).padStart(4,"0")}-${String(fields.month).padStart(2,"0")}-${String(fields.day).padStart(2,"0")}`)}}const timestamp=Date.parse(raw);return Number.isNaN(timestamp)?null:new Date(timestamp)}parseSingleText(raw){const parsed=this.parseOneDate(raw);return parsed?formatISO(parsed):null}parseRangeText(raw){if(/^\d{4}-\d{2}-\d{2}\/\d{4}-\d{2}-\d{2}$/.test(raw)){const[a,b]=raw.split("/");const from2=parseISO(a);const to2=parseISO(b);if(!from2||!to2)return null;return from2<=to2?raw:`${b}/${a}`}const separator=" \u2013 ";const idx=raw.indexOf(separator);if(idx===-1)return null;const from=this.parseOneDate(raw.slice(0,idx).trim());const to=this.parseOneDate(raw.slice(idx+separator.length).trim());if(!from||!to)return null;return from<=to?`${formatISO(from)}/${formatISO(to)}`:`${formatISO(to)}/${formatISO(from)}`}click(){if(!this.effectiveDisabled)this.inputElement?.click()}focus(options){this.inputElement?.focus(options)}blur(){this.inputElement?.blur()}select(){this.inputElement?.select()}setSelectionRange(start,end,direction){this.inputElement?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){const input=this.inputElement;if(!input)return;if(start===void 0||end===void 0){input.setRangeText(replacement)}else{input.setRangeText(replacement,start,end,selectMode)}this.applyTypedText(input.value)}formStateRestoreCallback(state2,_mode){this.value=typeof state2==="string"?state2:""}formResetCallback(){super.formResetCallback();this.touched=false}formDisabledCallback(disabled){const parent=Object.getPrototypeOf(LyraDateInput.prototype);parent.formDisabledCallback.call(this,disabled);if(disabled)void this.hide();this.syncCustomStates()}render(){const hasValue=this.value.length>0;const hasHint=this.withHint||this.hasHintSlot||this.hint.length>0;const hasError=this.hasErrorSlot||this.errorText.length>0;const hasLabel=this.withLabel||this.hasLabelSlot||this.label.length>0;const invalid=this.touched&&!this.internals.validity.valid;const describedBy=[hasError?"date-input-error":"",hasHint?"date-input-hint":""].filter(Boolean).join(" ");const dynamicDaySlots=[...new Set(Array.from(this.children).map(child=>child.getAttribute("slot")??"").filter(name=>/^day-\d{4}-\d{2}-\d{2}$/.test(name)))];return html`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{place}from"../../../internal/positioner.js";import{nextId}from"../../../internal/a11y.js";import{closeIcon,calendarIcon,chevronIcon}from"../../../internal/icons.js";import{activateOverlay}from"../../../internal/overlay-manager.js";import{setCustomState}from"../../../internal/custom-states.js";import{finiteCount,finiteNumber}from"../../../internal/numbers.js";import{dateTimeFormat,parseISO,formatISO,normalizeCalendarMonths,normalizeWeekdayFormat}from"./calendar-core.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./date-input.styles.js";import{LyraDatePicker}from"./date-picker.class.js";import"./date-picker.class.js";import{getDateTimeFormat}from"../../../internal/intl-cache.js";import{spellcheckFromAttributeConverter as spellcheckConverter}from"../../../internal/converters.js";import{isImplicitSubmission,submitOnEnter}from"../../../internal/submit-on-enter.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{LYRA_DEFAULT_chooseDate,LYRA_DEFAULT_clear,LYRA_DEFAULT_collapse,LYRA_DEFAULT_date,LYRA_DEFAULT_dateInputFutureDisabled,LYRA_DEFAULT_dateInputInvalid,LYRA_DEFAULT_dateInputMaxMessage,LYRA_DEFAULT_dateInputMinMessage,LYRA_DEFAULT_dateInputPastDisabled,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_openCalendar,LYRA_DEFAULT_restore,LYRA_DEFAULT_search}from"../../../internal/default-strings.generated.js";function localeDateOrder(locale){try{const parts=getDateTimeFormat(locale||void 0,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2026,0,2));const order=parts.filter(p=>p.type==="day"||p.type==="month"||p.type==="year").map(p=>p.type);return order.length===3?order:["month","day","year"]}catch{return["month","day","year"]}}const monthsConverter={fromAttribute:normalizeCalendarMonths,toAttribute:normalizeCalendarMonths};const weekdayFormatConverter={fromAttribute:normalizeWeekdayFormat,toAttribute:normalizeWeekdayFormat};function normalizeDateInputAppearance(value){return value==="filled"||value==="filled-outlined"?value:"outlined"}const appearanceConverter={fromAttribute:normalizeDateInputAppearance,toAttribute:normalizeDateInputAppearance};const placements=new Set(["top","top-start","top-end","right","right-start","right-end","bottom","bottom-start","bottom-end","left","left-start","left-end"]);function normalizeDateInputPlacement(value){return typeof value==="string"&&placements.has(value)?value:"bottom-start"}const placementConverter={fromAttribute:normalizeDateInputPlacement,toAttribute:normalizeDateInputPlacement};function normalizeDateInputPageBy(value){return value==="single"?"single":"months"}const pageByConverter={fromAttribute:normalizeDateInputPageBy,toAttribute:normalizeDateInputPageBy};const VALIDITY_FLAG_KEYS=new Set(["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"]);function isValidityFlagKey(value){return typeof value==="string"&&VALIDITY_FLAG_KEYS.has(value)}class LyraDateInputBase extends LyraElement{}class LyraDateInput extends FormAssociated(LyraDateInputBase){static{this.defaultStrings={...super.defaultStrings,chooseDate:LYRA_DEFAULT_chooseDate,clear:LYRA_DEFAULT_clear,collapse:LYRA_DEFAULT_collapse,date:LYRA_DEFAULT_date,dateInputFutureDisabled:LYRA_DEFAULT_dateInputFutureDisabled,dateInputInvalid:LYRA_DEFAULT_dateInputInvalid,dateInputMaxMessage:LYRA_DEFAULT_dateInputMaxMessage,dateInputMinMessage:LYRA_DEFAULT_dateInputMinMessage,dateInputPastDisabled:LYRA_DEFAULT_dateInputPastDisabled,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,openCalendar:LYRA_DEFAULT_openCalendar,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search}}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={mode:{reflect:true,noAccessor:true},min:{reflect:true,noAccessor:true},max:{reflect:true,noAccessor:true},readonly:{type:Boolean,reflect:true,noAccessor:true},disablePast:{type:Boolean,attribute:"disable-past",reflect:true,noAccessor:true},disableFuture:{type:Boolean,attribute:"disable-future",reflect:true,noAccessor:true}}}constructor(){super();this.appearance="outlined";this.open=false;this.withClear=false;this.withHint=false;this.withLabel=false;this.size="m";this.pill=false;this.label="";this.hint="";this.errorText="";this.placeholder="";this.spellcheck=true;this.autocapitalize="";this.autoCorrect="";this.autocomplete="";this.inputMode="";this.enterKeyHint="";this.accessibleLabel=null;this.locale="";this.months=1;this.firstDayOfWeek="auto";this.weekdayFormat="short";this.withOutsideDays=false;this.withWeekNumbers=false;this.disabledDates="";this.disabledDaysOfWeek="";this.minRange=0;this.maxRange=0;this.pageBy="months";this.today="";this.distance=0;this.placement="bottom-start";this.assumeInteractionOn=["input"];this.validators=[];this.clearLabel="";this.openLabel="";this.dialogLabel="Choose date";this.enterCommittedText=null;this.inputRelayedSinceCommit=false;this.restorePopupFocusOnClose=false;this.transitionToken=0;this.transitionWaiters=new Map;this.interactionListeners=new Map;this.inputId=nextId("date-input");this.popupId=nextId("date-popup");this.touched=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.hasLabelSlot=false;this.hasStartSlot=false;this.hasEndSlot=false;this.validityRevision=0;this._mode="single";this._min="";this._max="";this._readonly=false;this._disablePast=false;this._disableFuture=false;this.typedBadInput=false;this.now=()=>new Date;this.onVisibilityChange=()=>{if(this.ownerDocument.visibilityState!=="visible")return;this.updateValidity();this.validityRevision++};this.onDocPointer=e=>{if(!e.composedPath().includes(this))void this.hide(false)};this.onInputChange=e=>{e.stopPropagation();const raw=e.target.value;if(this.enterCommittedText!==null&&(raw===this.enterCommittedText||raw===this.displayText)){return}this.enterCommittedText=null;const committed=this.applyTypedText(raw);if(committed){if(!this.inputRelayedSinceCommit){dispatchNativeInputEvent(this,{inputType:"insertReplacementText"})}this.inputRelayedSinceCommit=false;relayNativeEvent(this,e)}else{this.inputRelayedSinceCommit=false}};this.onInput=event=>{this.inputRelayedSinceCommit=true;relayNativeEvent(this,event)};this.onInputKey=e=>{if(e.altKey&&e.key==="ArrowDown"){e.preventDefault();this.show();return}if(this.effectiveDisabled||this.readonly)return;if(!isImplicitSubmission(e))return;const input=this.inputElement;if(input&&input.value!==this.displayText){const raw=input.value;if(this.applyTypedText(raw)){if(!this.inputRelayedSinceCommit){dispatchNativeInputEvent(this,{inputType:"insertReplacementText"})}this.inputRelayedSinceCommit=false;dispatchNativeEvent(this,"change")}else{this.inputRelayedSinceCommit=false}this.enterCommittedText=raw}submitOnEnter(this,e)};this.onInputBlur=event=>{if(!this.effectiveDisabled)this.touched=true;relayNativeEvent(this,event)};this.onInputFocus=event=>{relayNativeEvent(this,event)};this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:true}).length>0};this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:true}).length>0};this.onLabelSlotChange=e=>{this.hasLabelSlot=e.target.assignedElements({flatten:true}).length>0};this.onStartSlotChange=e=>{this.hasStartSlot=e.target.assignedElements({flatten:true}).length>0};this.onEndSlotChange=e=>{this.hasEndSlot=e.target.assignedElements({flatten:true}).length>0};this.onPickerInput=e=>{const picker=e.target;this.value=picker.value;this.inputRelayedSinceCommit=false;relayNativeEvent(this,e)};this.onPickerChange=e=>{const picker=e.target;this.value=picker.value;relayNativeEvent(this,e);this.hide(true)};this.addEventListener("invalid",()=>{this.touched=true})}get mode(){return this._mode}set mode(next){const old=this._mode;this._mode=next==="range"?"range":"single";this.internals.setFormValue(this.isIncompleteRangeValue(this.value)?"":this.value);this.updateValidity();this.syncCustomStates();this.requestUpdate("mode",old)}get min(){return this._min}set min(next){const old=this._min;this._min=next??"";this.updateValidity();this.requestUpdate("min",old)}get max(){return this._max}set max(next){const old=this._max;this._max=next??"";this.updateValidity();this.requestUpdate("max",old)}get readonly(){return this._readonly}set readonly(next){const old=this._readonly;this._readonly=Boolean(next);this.toggleAttribute("readonly",this._readonly);if(this._readonly)void this.hide();this.updateValidity();this.requestUpdate("readonly",old)}get disabled(){return super.disabled}set disabled(next){super.disabled=next;if(next)void this.hide();this.syncCustomStates()}get disablePast(){return this._disablePast}set disablePast(next){const old=this._disablePast;this._disablePast=Boolean(next);this.updateValidity();this.requestUpdate("disablePast",old)}get disableFuture(){return this._disableFuture}set disableFuture(next){const old=this._disableFuture;this._disableFuture=Boolean(next);this.updateValidity();this.requestUpdate("disableFuture",old)}get input(){return this.inputElement}get selectionStart(){return this.inputElement?.selectionStart??null}set selectionStart(value){if(this.inputElement)this.inputElement.selectionStart=value??0}get selectionEnd(){return this.inputElement?.selectionEnd??null}set selectionEnd(value){if(this.inputElement)this.inputElement.selectionEnd=value??0}get selectionDirection(){return this.inputElement?.selectionDirection??null}set selectionDirection(value){if(this.inputElement)this.inputElement.selectionDirection=value??"none"}get value(){return super.value}set value(next){this.setTypedBadInput(false);const normalized=this.normalizeCommittedValue(next??"");super.value=normalized;this.internals.setFormValue(this.isIncompleteRangeValue(normalized)?"":normalized);this.syncCustomStates()}get valueAsDate(){return this.mode==="single"?this.parseStrictISO(this.value):null}set valueAsDate(next){this.value=next instanceof Date&&Number.isFinite(next.getTime())?formatISO(next):""}get valueAsRange(){if(this.mode!=="range")return{from:null,to:null};const[from="",to=""]=this.value.split("/");return{from:this.parseStrictISO(from),to:this.parseStrictISO(to)}}set valueAsRange(next){let from=next?.from instanceof Date&&Number.isFinite(next.from.getTime())?next.from:null;let to=next?.to instanceof Date&&Number.isFinite(next.to.getTime())?next.to:null;if(from&&to&&to<from)[from,to]=[to,from];this.value=from?to?`${formatISO(from)}/${formatISO(to)}`:formatISO(from):""}get validationTarget(){return this.validationTargetOverride??this.inputElement}set validationTarget(next){const old=this.validationTarget;this.validationTargetOverride=next??void 0;this.requestUpdate("validationTarget",old)}[VALIDITY_ANCHOR](){return this.validationTarget}resetValidity(){this.setCustomValidity("");this.updateValidity()}setTypedBadInput(next){const old=this.typedBadInput;this.typedBadInput=next;if(old!==next)this.requestUpdate("typedBadInput",old)}parseStrictISO(value){if(!/^\d{4}-\d{2}-\d{2}$/.test(value))return null;return parseISO(value)}normalizeCommittedValue(value){if(value==="")return"";const parts=value.split("/");if(parts.length!==1&&parts.length!==2)return"";const dates=parts.map(part=>this.parseStrictISO(part));if(dates.some(date=>date===null))return"";if(parts.length===2&&dates[0]>dates[1])return`${parts[1]}/${parts[0]}`;return value}isIncompleteRangeValue(value){return this.mode==="range"&&value!==""&&!value.includes("/")}valueDates(value){const parts=value.split("/");const expectedParts=this.mode==="range"&&parts.length===2?2:1;if(parts.length!==expectedParts)return null;const dates=parts.map(part=>this.parseStrictISO(part));return dates.some(date=>date===null)?null:dates}configuredDisabledDateKeys(){const values=Array.isArray(this.disabledDates)?this.disabledDates:String(this.disabledDates||"").split(/[\s,]+/);return new Set(values.map(value=>value instanceof Date?value:parseISO(String(value))).filter(value=>value instanceof Date&&Number.isFinite(value.getTime())).map(value=>formatISO(value)))}configuredDisabledWeekdays(){const names={sun:0,sunday:0,mon:1,monday:1,tue:2,tues:2,tuesday:2,wed:3,wednesday:3,thu:4,thur:4,thurs:4,thursday:4,fri:5,friday:5,sat:6,saturday:6};return new Set(String(this.disabledDaysOfWeek||"").toLowerCase().split(/[\s,]+/).filter(Boolean).map(value=>names[value]??(/^[0-6]$/.test(value)?Number(value):-1)).filter(value=>value>=0))}rangeLength(from,to){const fromUtc=Date.UTC(from.getFullYear(),from.getMonth(),from.getDate());const toUtc=Date.UTC(to.getFullYear(),to.getMonth(),to.getDate());return Math.round(Math.abs(toUtc-fromUtc)/864e5)+1}validatorResult(){for(const validator of Array.isArray(this.validators)?this.validators:[]){let result;try{if(typeof validator==="object"&&validator!==null&&"checkValidity"in validator){const checked=validator.checkValidity(this);if(checked?.isValid===true)continue;const flags={};for(const key of Array.isArray(checked?.invalidKeys)?checked.invalidKeys:[]){if(isValidityFlagKey(key))flags[key]=true}if(!Object.values(flags).some(Boolean))flags.customError=true;let message=typeof checked?.message==="string"?checked.message:"";if(!message&&typeof validator.message==="string")message=validator.message;if(!message&&typeof validator.message==="function"){message=validator.message(this)}return{flags,message:message||this.localize("dateInputInvalid")}}result=typeof validator==="function"?validator(this.value,this):validator?.validate(this.value,this)}catch{return{flags:{customError:true},message:this.localize("dateInputInvalid")}}if(result===void 0||result===true)continue;if(typeof result==="string")return{flags:{customError:true},message:result};if(result===false)return{flags:{customError:true},message:this.localize("dateInputInvalid")};if(result&&typeof result==="object"&&Object.values(result).some(Boolean)){return{flags:result,message:this.localize("dateInputInvalid")}}}return{}}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let underflowMessage="";let overflowMessage="";const incompleteRange=this.isIncompleteRangeValue(this.value);if(this.required&&(this.value===""||incompleteRange))flags.valueMissing=true;if(this.typedBadInput)flags.badInput=true;if(this.value!==""){const dates=this.valueDates(this.value);if(!dates){flags.badInput=true}else{const min=this.parseStrictISO(this.min);const max=this.parseStrictISO(this.max);const configuredToday=this.parseStrictISO(this.today);const now=configuredToday??this.now();const today=new Date(now.getFullYear(),now.getMonth(),now.getDate());if(min!==null&&dates.some(date=>date<min)){flags.rangeUnderflow=true;underflowMessage=this.localize("dateInputMinMessage",void 0,{min:this.min})}if(this.disablePast&&dates.some(date=>date<today)){flags.rangeUnderflow=true;underflowMessage||=this.localize("dateInputPastDisabled")}if(max!==null&&dates.some(date=>date>max)){flags.rangeOverflow=true;overflowMessage=this.localize("dateInputMaxMessage",void 0,{max:this.max})}if(this.disableFuture&&dates.some(date=>date>today)){flags.rangeOverflow=true;overflowMessage||=this.localize("dateInputFutureDisabled")}const disabledDates=this.configuredDisabledDateKeys();const disabledWeekdays=this.configuredDisabledWeekdays();let configuredDisabled=dates.some(date=>disabledDates.has(formatISO(date))||disabledWeekdays.has(date.getDay()));if(!configuredDisabled&&this.isDateDisabled){try{configuredDisabled=dates.some(date=>Boolean(this.isDateDisabled?.(new Date(date.getTime()))))}catch{configuredDisabled=false}}if(configuredDisabled)flags.customError=true;if(this.mode==="range"&&dates.length===2){const length=this.rangeLength(dates[0],dates[1]);const minimum=finiteCount(this.minRange,0);const maximum=finiteCount(this.maxRange,0);if(minimum>0&&length<minimum){flags.rangeUnderflow=true;underflowMessage||=this.localize("dateInputInvalid")}if(maximum>0&&length>maximum){flags.rangeOverflow=true;overflowMessage||=this.localize("dateInputInvalid")}}}}const configured=this.validatorResult();if(configured.flags)Object.assign(flags,configured.flags);let message="";if(configured.message)message=configured.message;else if(flags.badInput||flags.customError)message=this.localize("dateInputInvalid");else if(flags.rangeUnderflow)message=underflowMessage;else if(flags.rangeOverflow)message=overflowMessage;else if(flags.valueMissing)message=this.localize("fieldRequired");this[SET_ANCHORED_VALIDITY](flags,message)}checkValidity(){this.updateValidity();return super.checkValidity()}reportValidity(){this.updateValidity();return super.reportValidity()}bindVisibilityListener(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.visibilityListenerDocument===ownerDocument&&this.visibilityListener)return;this.unbindVisibilityListener();const listener=()=>{if(this.visibilityListener!==listener||this.visibilityListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.onVisibilityChange()};this.visibilityListenerDocument=ownerDocument;this.visibilityListener=listener;ownerDocument.addEventListener("visibilitychange",listener)}unbindVisibilityListener(){if(this.visibilityListenerDocument&&this.visibilityListener){this.visibilityListenerDocument.removeEventListener("visibilitychange",this.visibilityListener)}this.visibilityListenerDocument=void 0;this.visibilityListener=void 0}get displayText(){const parts=this.value.split("/");const from=parseISO(parts[0]);const to=parseISO(parts[1]??"");if(!from)return"";const formatter=dateTimeFormat(this.effectiveLocale,{});const fmt=d=>formatter.format(d);return this.mode==="range"&&to?`${fmt(from)} \u2013 ${fmt(to)}`:fmt(from)}willUpdate(changed){if(!this.hasUpdated){this.hasHintSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="hint");this.hasErrorSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="error");this.hasLabelSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="label");this.hasStartSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="start");this.hasEndSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="end")}if(changed.has("open")){if(this.open&&this.isConnected){this.bindDocumentPointer()}else{this.unbindDocumentPointer()}}}show(){if(this.open||this.effectiveDisabled||this.readonly)return Promise.resolve();const request=this.emit("lr-show",void 0,{cancelable:true});if(request.defaultPrevented)return Promise.resolve();this.resolveTransitionWaiters("lr-after-hide");const settled=this.waitForTransition("lr-after-show");this.open=true;void this.settleTransition("lr-after-show");return settled}hide(restoreFocus=false){if(!this.open)return Promise.resolve();const request=this.emit("lr-hide",void 0,{cancelable:true});if(request.defaultPrevented)return Promise.resolve();this.resolveTransitionWaiters("lr-after-show");const settled=this.waitForTransition("lr-after-hide");this.restorePopupFocusOnClose||=restoreFocus;this.open=false;void this.settleTransition("lr-after-hide");return settled}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{if(this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument;this.pointerListener=listener;ownerDocument.addEventListener("pointerdown",listener)}unbindDocumentPointer(){if(this.pointerListenerDocument&&this.pointerListener){this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener)}this.pointerListenerDocument=void 0;this.pointerListener=void 0}reconnectOpenPopup(){if(!this.isConnected||!this.open)return;this.bindDocumentPointer();this.cleanupFn?.();const anchor=this.renderRoot.querySelector('[part="input-wrapper"]');const popup=this.renderRoot.querySelector('[part="popup"]');if(!anchor||!popup)return;this.cleanupFn=place(anchor,popup,{placement:normalizeDateInputPlacement(this.placement),offset:finiteNumber(this.distance,0)});this.overlayHandle?.deactivate({restoreFocus:false});this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="popup"]'),onEscape:()=>{void this.hide(true)},modal:false,trapFocus:false})}async settleTransition(event){const token=++this.transitionToken;await this.updateComplete;if(this.transitionToken!==token)return;if(this.isConnected){const view=this.ownerDocument.defaultView;if(view)await new Promise(resolve=>view.requestAnimationFrame(()=>resolve()));if(this.transitionToken!==token)return;const popup=this.renderRoot.querySelector('[part="popup"]');const animations=popup?.getAnimations({subtree:true})??[];await Promise.all(animations.map(animation=>animation.finished.catch(()=>void 0)));if(this.transitionToken!==token)return}this.emit(event);this.resolveTransitionWaiters(event)}waitForTransition(event){return new Promise(resolve=>{const waiters=this.transitionWaiters.get(event)??new Set;waiters.add(resolve);this.transitionWaiters.set(event,waiters)})}resolveTransitionWaiters(event){const waiters=this.transitionWaiters.get(event);if(!waiters)return;this.transitionWaiters.delete(event);for(const resolve of waiters)resolve()}connectedCallback(){super.connectedCallback();this.bindVisibilityListener();this.syncInteractionListeners();this.syncValidatorAttributeObserver();this.syncCustomStates();if(this.hasUpdated&&this.open)queueMicrotask(()=>this.reconnectOpenPopup())}clear(){if(!this.value||this.effectiveDisabled||this.readonly)return;this.touched=true;this.value="";this.emit("lr-clear");this.inputRelayedSinceCommit=false;dispatchNativeInputEvent(this,{inputType:"deleteContentBackward"});dispatchNativeEvent(this,"change")}syncInteractionListeners(){const requested=new Set((Array.isArray(this.assumeInteractionOn)?this.assumeInteractionOn:[]).filter(name=>typeof name==="string"&&name.length>0));for(const[name,listener]of this.interactionListeners){if(requested.has(name))continue;this.removeEventListener(name,listener);this.interactionListeners.delete(name)}for(const name of requested){if(this.interactionListeners.has(name))continue;const listener=()=>{this.touched=true;this.syncCustomStates()};this.addEventListener(name,listener);this.interactionListeners.set(name,listener)}}syncValidatorAttributeObserver(){this.disconnectValidatorAttributeObserver();const owner=this.ownerDocument.defaultView;const MutationObserverCtor=owner?.MutationObserver;if(!this.isConnected||!owner||typeof MutationObserverCtor!=="function")return;const attributes=new Set;for(const validator of Array.isArray(this.validators)?this.validators:[]){if(typeof validator!=="object"||validator===null||!("checkValidity"in validator))continue;let observed;try{observed=validator.observedAttributes}catch{continue}if(!Array.isArray(observed))continue;for(const name of observed){if(typeof name==="string"&&name.length>0)attributes.add(name)}}if(attributes.size===0)return;const binding={};const observer=new MutationObserverCtor(()=>{if(this.validatorAttributeObserver!==binding||!this.isConnected||this.ownerDocument.defaultView!==owner)return;this.updateValidity();this.validityRevision++});binding.observer=observer;binding.owner=owner;try{observer.observe(this,{attributes:true,attributeFilter:[...attributes]});this.validatorAttributeObserver=binding}catch{observer.disconnect()}}disconnectValidatorAttributeObserver(){const binding=this.validatorAttributeObserver;this.validatorAttributeObserver=void 0;binding?.observer.disconnect()}syncCustomStates(){setCustomState(this.internals,"blank",this.value==="");setCustomState(this.internals,"disabled",this.effectiveDisabled);setCustomState(this.internals,"open",this.open);setCustomState(this.internals,"range",this.mode==="range")}disconnectedCallback(){this.transitionToken++;this.cleanupFn?.();this.cleanupFn=void 0;this.overlayHandle?.deactivate({restoreFocus:false});this.overlayHandle=void 0;this.unbindVisibilityListener();this.unbindDocumentPointer();this.disconnectValidatorAttributeObserver();this.restorePopupFocusOnClose=false;this.resolveTransitionWaiters("lr-after-show");this.resolveTransitionWaiters("lr-after-hide");for(const[name,listener]of this.interactionListeners)this.removeEventListener(name,listener);this.interactionListeners.clear();this.enterCommittedText=null;this.inputRelayedSinceCommit=false;this.open=false;super.disconnectedCallback()}adoptedCallback(){this.cleanupFn?.();this.cleanupFn=void 0;this.overlayHandle?.deactivate({restoreFocus:false});this.overlayHandle=void 0;this.unbindVisibilityListener();this.unbindDocumentPointer();this.disconnectValidatorAttributeObserver()}updated(changed){super.updated(changed);if(changed.has("disabledDates")||changed.has("disabledDaysOfWeek")||changed.has("isDateDisabled")||changed.has("minRange")||changed.has("maxRange")||changed.has("today")||changed.has("validators")){this.updateValidity()}if(changed.has("open")||this.open&&(changed.has("placement")||changed.has("distance"))){this.cleanupFn?.();this.cleanupFn=void 0;if(this.open&&this.isConnected){const anchor=this.renderRoot.querySelector('[part="input-wrapper"]');const popup=this.renderRoot.querySelector('[part="popup"]');if(anchor&&popup){this.cleanupFn=place(anchor,popup,{placement:normalizeDateInputPlacement(this.placement),offset:finiteNumber(this.distance,0)})}}}if(changed.has("open")){if(this.open&&this.isConnected){const popup=this.renderRoot.querySelector('[part="popup"]');if(popup){this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="popup"]'),onEscape:()=>{void this.hide(true)},modal:false,trapFocus:false})}}else if(!this.open){this.overlayHandle?.deactivate({restoreFocus:this.restorePopupFocusOnClose});this.overlayHandle=void 0;this.restorePopupFocusOnClose=false}}if(changed.has("assumeInteractionOn"))this.syncInteractionListeners();if(changed.has("validators"))this.syncValidatorAttributeObserver();this.syncCustomStates();if(changed.has("touched")||changed.has("required")||changed.has("value")||changed.has("mode")||changed.has("min")||changed.has("max")||changed.has("readonly")||changed.has("disablePast")||changed.has("disableFuture")||changed.has("disabledDates")||changed.has("disabledDaysOfWeek")||changed.has("minRange")||changed.has("maxRange")||changed.has("validators")||changed.has("typedBadInput")||changed.has("validityRevision")){this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}}applyTypedText(raw){this.enterCommittedText=null;const trimmed=raw.trim();if(!trimmed){this.value="";return true}const parsed=this.mode==="range"?this.parseRangeText(trimmed):this.parseSingleText(trimmed);if(parsed){this.value=parsed;return true}if(this.inputElement)this.inputElement.value=this.displayText;this.setTypedBadInput(true);this.updateValidity();return false}parseOneDate(raw){const looksLikeISO=/^\d{4}-\d{2}-\d{2}$/.test(raw);if(looksLikeISO)return parseISO(raw);const ambiguous=/^(\d{1,4})[/.-](\d{1,4})[/.-](\d{1,4})$/.exec(raw);if(ambiguous){const[,g1,g2,g3]=ambiguous;if(g1.length===4){return parseISO(`${g1}-${g2.padStart(2,"0")}-${g3.padStart(2,"0")}`)}const order=localeDateOrder(this.effectiveLocale);const values=[Number(g1),Number(g2),Number(g3)];const fields={};order.forEach((type,i)=>{fields[type]=values[i]});if(fields.day!=null&&fields.month!=null&&fields.year!=null){const year=fields.year<100?2e3+fields.year:fields.year;return parseISO(`${String(year).padStart(4,"0")}-${String(fields.month).padStart(2,"0")}-${String(fields.day).padStart(2,"0")}`)}}const timestamp=Date.parse(raw);return Number.isNaN(timestamp)?null:new Date(timestamp)}parseSingleText(raw){const parsed=this.parseOneDate(raw);return parsed?formatISO(parsed):null}parseRangeText(raw){if(/^\d{4}-\d{2}-\d{2}\/\d{4}-\d{2}-\d{2}$/.test(raw)){const[a,b]=raw.split("/");const from2=parseISO(a);const to2=parseISO(b);if(!from2||!to2)return null;return from2<=to2?raw:`${b}/${a}`}const separator=" \u2013 ";const idx=raw.indexOf(separator);if(idx===-1)return null;const from=this.parseOneDate(raw.slice(0,idx).trim());const to=this.parseOneDate(raw.slice(idx+separator.length).trim());if(!from||!to)return null;return from<=to?`${formatISO(from)}/${formatISO(to)}`:`${formatISO(to)}/${formatISO(from)}`}click(){if(!this.effectiveDisabled)this.inputElement?.click()}focus(options){this.inputElement?.focus(options)}blur(){this.inputElement?.blur()}select(){this.inputElement?.select()}setSelectionRange(start,end,direction){this.inputElement?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){const input=this.inputElement;if(!input)return;if(start===void 0||end===void 0){input.setRangeText(replacement)}else{input.setRangeText(replacement,start,end,selectMode)}this.applyTypedText(input.value)}formStateRestoreCallback(state2,_mode){this.value=typeof state2==="string"?state2:""}formResetCallback(){super.formResetCallback();this.touched=false}formDisabledCallback(disabled){const parent=Object.getPrototypeOf(LyraDateInput.prototype);parent.formDisabledCallback.call(this,disabled);if(disabled)void this.hide();this.syncCustomStates()}render(){const hasValue=this.value.length>0;const hasHint=this.withHint||this.hasHintSlot||this.hint.length>0;const hasError=this.hasErrorSlot||this.errorText.length>0;const hasLabel=this.withLabel||this.hasLabelSlot||this.label.length>0;const invalid=this.touched&&!this.internals.validity.valid;const describedBy=[hasError?"date-input-error":"",hasHint?"date-input-hint":""].filter(Boolean).join(" ");const dynamicDaySlots=[...new Set(Array.from(this.children).map(child=>child.getAttribute("slot")??"").filter(name=>/^day-\d{4}-\d{2}-\d{2}$/.test(name)))];return html`
|
|
2
2
|
<div part="date-input">
|
|
3
3
|
<div part="base">
|
|
4
4
|
<div part="form-control">
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state,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{nextId}from"../../../internal/a11y.js";import{styles}from"./emoji-picker.styles.js";import{loadEmojiDataCached}from"./emoji-data-loader.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,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_emojiPickerSearchLabel,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_item,LYRA_DEFAULT_open,LYRA_DEFAULT_restore}from"../../../internal/default-strings.generated.js";const VIRTUALIZE_AT=200;const ITEM_SIZE_FALLBACK=40;const GAP_FALLBACK=2;const VIRTUAL_ROW_HEIGHT_FALLBACK=56;const MAX_VIRTUAL_COLUMNS=20;function probePixels(probe,fallback,allowZero=false){const computed=probe.ownerDocument.defaultView?.getComputedStyle(probe);if(!computed)return fallback;const px=Number.parseFloat(computed.inlineSize);if(!Number.isFinite(px)||px<0)return fallback;return px>0||allowZero?px:fallback}class EmojiPickerBase extends LyraElement{}class LyraEmojiPicker extends FormAssociated(EmojiPickerBase){constructor(){super(...arguments);this._groups=[];this.groupsWereSet=false;this.accessibleLabel="";this.size="m";this.label="";this.hint="";this.errorText="";this.hasLabelSlot=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.touched=false;this.labelId=nextId("emoji-picker-label");this.hintId=nextId("emoji-picker-hint");this.errorId=nextId("emoji-picker-error");this.loadGroups=loadEmojiDataCached;this.queryText="";this.activeIndex=0;this.virtualScrollTop=0;this.observedGridVirtualized=false;this.ownerRealmGeneration=0;this.gridId=nextId("emoji-picker-grid");this.haystacks=new WeakMap;this.onGeometryResize=()=>{const previous=this.geometryCache;this.geometryCache=void 0;if(!previous)return;const next=this.geometry();if(next.itemSize===previous.itemSize&&next.gap===previous.gap&&next.rowHeight===previous.rowHeight){return}this.requestUpdate()};this.onSearchInput=event=>{this.queryText=event.target.value;this.activeIndex=0};this.onSearchFocus=()=>{this.emit("focus")};this.onSearchBlur=()=>{this.touched=true;this.emit("blur")};this.onLabelSlotChange=event=>{this.hasLabelSlot=event.target.assignedElements({flatten:true}).length>0};this.onHintSlotChange=event=>{this.hasHintSlot=event.target.assignedElements({flatten:true}).length>0};this.onErrorSlotChange=event=>{this.hasErrorSlot=event.target.assignedElements({flatten:true}).length>0};this.onNavigationKeyDown=event=>{if(this.effectiveDisabled)return;const items=this.flatItems;if(items.length===0)return;const inSearch=event.currentTarget===this.searchEl;const forwardKey=this.effectiveDirection==="rtl"?"ArrowLeft":"ArrowRight";const 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];if(item)this.pick(item);return}else{return}event.preventDefault();this.setActiveIndex(target,!inSearch)};this.onGridFocusIn=event=>{const button=event.target;if(button?.nodeType!==1||button.localName!=="button"){return}const option=button;const indexed=Number(option.dataset["index"]);const index=Number.isInteger(indexed)?indexed:this.optionButtons().indexOf(option);if(index>=0&&index!==this.activeIndex)this.setActiveIndex(index,false)};this.onGridScroll=event=>{if(!this.isVirtualized)return;const grid=event.currentTarget;this.virtualScrollTop=grid.scrollTop;const ownerDocument=this.ownerDocument;const ownerWindow=ownerDocument.defaultView;if(!ownerWindow)return;if(this.virtualScrollRaf!==void 0&&this.virtualScrollRafWindow===ownerWindow&&this.virtualScrollRafDocument===ownerDocument){return}this.cancelVirtualScrollFrame();const generation=this.ownerRealmGeneration;let handle=0;handle=ownerWindow.requestAnimationFrame(()=>{if(this.virtualScrollRaf!==handle||this.virtualScrollRafWindow!==ownerWindow||this.virtualScrollRafDocument!==ownerDocument||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument){return}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,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,emojiPickerSearchLabel:LYRA_DEFAULT_emojiPickerSearchLabel,fieldRequired:LYRA_DEFAULT_fieldRequired,item:LYRA_DEFAULT_item,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore}}static{this.styles=[LyraElement.styles,styles]}get groups(){return this._groups}set groups(value){const old=this._groups;this.groupsWereSet=true;this._groups=Array.isArray(value)?value:[];this.requestUpdate("groups",old)}connectedCallback(){super.connectedCallback();this.observeGeometryProbe();this.syncGridObserver();if(this.groupsWereSet)return;const ownerDocument=this.ownerDocument;const generation=this.ownerRealmGeneration;void this.loadGroups().then(loaded=>{if(this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||!loaded||this.groupsWereSet){return}this.groups=loaded})}haystackFor(item){const locale=this.effectiveLocale;let cached=this.haystacks.get(item);if(cached===void 0||cached.locale!==locale){cached={locale,value:[item.name,...item.shortcodes??[]].join(" ").toLocaleLowerCase(locale)};this.haystacks.set(item,cached)}return cached.value}get filteredGroups(){const q=this.queryText.trim().toLocaleLowerCase(this.effectiveLocale);if(!q)return this.groups;return this.groups.map(group=>({...group,emojis:group.emojis.filter(item=>this.haystackFor(item).includes(q))})).filter(group=>group.emojis.length>0)}get flatItems(){return this.filteredGroups.flatMap(group=>group.emojis)}get isVirtualized(){return this.flatItems.length>=VIRTUALIZE_AT}geometry(){if(this.geometryCache)return this.geometryCache;const probe=this.geometryProbe;if(!probe){return{itemSize:ITEM_SIZE_FALLBACK,gap:GAP_FALLBACK,rowHeight:VIRTUAL_ROW_HEIGHT_FALLBACK}}this.geometryCache={itemSize:probePixels(probe.item,ITEM_SIZE_FALLBACK),gap:probePixels(probe.gap,GAP_FALLBACK,true),rowHeight:probePixels(probe.row,VIRTUAL_ROW_HEIGHT_FALLBACK)};return this.geometryCache}syncGeometryProbe(){if(this.geometryProbe||!this.isVirtualized)return;const makeProbe=name=>{const probe=this.ownerDocument.createElement("div");probe.dataset["probe"]=name;return probe};const root=makeProbe("root");root.setAttribute("aria-hidden","true");const item=makeProbe("item");const gap=makeProbe("gap");const row=makeProbe("row");root.append(item,gap,row);this.renderRoot.append(root);this.geometryProbe={root,item,gap,row};this.observeGeometryProbe()}observeGeometryProbe(){const probe=this.geometryProbe;const ownerDocument=this.ownerDocument;if(!probe||!this.isConnected)return;if(this.geometryObserver&&this.geometryObserverDocument===ownerDocument&&this.geometryObserverRoot===probe.root){return}this.resetGeometryObserver();const ResizeObserverCtor=ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverCtor)return;const generation=this.ownerRealmGeneration;const observer=new ResizeObserverCtor(()=>{if(this.geometryObserver!==observer||this.geometryObserverDocument!==ownerDocument||this.geometryObserverRoot!==probe.root||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument){return}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){return group.labelKey?this.localize(group.labelKey):group.label}virtualRows(){const columns=this.columnsPerRow();let index=0;const rows=[];for(const group of this.filteredGroups){for(let offset=0;offset<group.emojis.length;offset+=columns){rows.push({label:offset===0?this.groupLabel(group):void 0,items:group.emojis.slice(offset,offset+columns).map(item=>({item,index:index++}))})}}return rows}optionButtons(){return[...this.renderRoot.querySelectorAll('[part="emoji"]')]}columnsPerRow(){if(this.isVirtualized){const grid=this.renderRoot.querySelector('[part="grid"]');const width=grid?.clientWidth??0;const{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));const target=this.isVirtualized?this.renderRoot.querySelector(`[part="emoji"][data-index="${this.activeIndex}"]`):buttons[this.activeIndex];const previous=this.renderRoot.querySelector('[part="emoji"][data-active]');if(previous&&previous!==target){previous.tabIndex=-1;previous.setAttribute("aria-selected","false");previous.removeAttribute("data-active")}if(target){target.tabIndex=0;target.setAttribute("aria-selected","true");target.setAttribute("data-active","");this.searchEl?.setAttribute("aria-activedescendant",target.id);target.scrollIntoView({block:"nearest"})}else if(this.isVirtualized){this.searchEl?.setAttribute("aria-activedescendant",`${this.gridId}-item-${this.activeIndex}`);const rowIndex=this.virtualRows().findIndex(row=>row.items.some(({index})=>index===this.activeIndex));const grid=this.renderRoot.querySelector('[part="grid"]');if(rowIndex>=0&&grid){grid.scrollTop=rowIndex*this.geometry().rowHeight;this.virtualScrollTop=grid.scrollTop;this.requestUpdate()}}if(focusTarget)target?.focus()}pick(item){if(this.effectiveDisabled)return;this.value=item.emoji;this.emit("input");this.emit("change");this.emit("lr-change",{emoji:item.emoji})}cancelVirtualScrollFrame(){if(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"]');const virtualized=this.isVirtualized;const ownerDocument=this.ownerDocument;if(grid===this.observedGrid&&virtualized===this.observedGridVirtualized&&(!virtualized||this.gridResizeObserverDocument===ownerDocument)){return}this.resetGridObserver();if(!this.isConnected)return;this.observedGrid=grid??void 0;this.observedGridVirtualized=virtualized;if(!grid||!virtualized)return;grid.addEventListener("scroll",this.onGridScroll,{passive:true});const ResizeObserverCtor=ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverCtor)return;const generation=this.ownerRealmGeneration;const observer=new ResizeObserverCtor(()=>{if(this.gridResizeObserver!==observer||this.gridResizeObserverDocument!==ownerDocument||this.observedGrid!==grid||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument){return}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=false;this.cancelVirtualScrollFrame()}willUpdate(changed){super.willUpdate(changed);this.syncGeometryProbe();if(!this.hasUpdated){this.hasLabelSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="label");this.hasHintSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="hint");this.hasErrorSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="error")}}updated(changed){this.syncGridObserver();if(!changed.has("queryText")&&!changed.has("groups"))return;const buttons=this.optionButtons();if(buttons.length===0){this.searchEl?.removeAttribute("aria-activedescendant");return}if(!this.isVirtualized&&this.activeIndex>=buttons.length)this.activeIndex=0;this.setActiveIndex(this.activeIndex,false)}disconnectedCallback(){super.disconnectedCallback();this.resetOwnerRealmResources()}adoptedCallback(){this.resetOwnerRealmResources()}resetOwnerRealmResources(){this.ownerRealmGeneration+=1;this.resetGridObserver();this.resetGeometryObserver()}renderEmojiButton(item,itemIndex,total){return html`<button
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state,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{nextId}from"../../../internal/a11y.js";import{styles}from"./emoji-picker.styles.js";import{loadEmojiDataCached}from"./emoji-data-loader.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,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_emojiPickerSearchLabel,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_item,LYRA_DEFAULT_open,LYRA_DEFAULT_restore}from"../../../internal/default-strings.generated.js";const VIRTUALIZE_AT=200;const ITEM_SIZE_FALLBACK=40;const GAP_FALLBACK=2;const VIRTUAL_ROW_HEIGHT_FALLBACK=56;const MAX_VIRTUAL_COLUMNS=20;function probePixels(probe,fallback,allowZero=false){const computed=probe.ownerDocument.defaultView?.getComputedStyle(probe);if(!computed)return fallback;const px=Number.parseFloat(computed.inlineSize);if(!Number.isFinite(px)||px<0)return fallback;return px>0||allowZero?px:fallback}class EmojiPickerBase extends LyraElement{}class LyraEmojiPicker extends FormAssociated(EmojiPickerBase){constructor(){super(...arguments);this._groups=[];this.groupsWereSet=false;this.accessibleLabel="";this.size="m";this.label="";this.hint="";this.errorText="";this.hasLabelSlot=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.touched=false;this.labelId=nextId("emoji-picker-label");this.hintId=nextId("emoji-picker-hint");this.errorId=nextId("emoji-picker-error");this.loadGroups=loadEmojiDataCached;this.queryText="";this.activeIndex=0;this.virtualScrollTop=0;this.observedGridVirtualized=false;this.ownerRealmGeneration=0;this.gridId=nextId("emoji-picker-grid");this.haystacks=new WeakMap;this.onGeometryResize=()=>{const previous=this.geometryCache;this.geometryCache=void 0;if(!previous)return;const next=this.geometry();if(next.itemSize===previous.itemSize&&next.gap===previous.gap&&next.rowHeight===previous.rowHeight){return}this.requestUpdate()};this.onSearchInput=event=>{this.queryText=event.target.value;this.activeIndex=0};this.onSearchFocus=()=>{this.emit("focus")};this.onSearchBlur=()=>{if(!this.effectiveDisabled)this.touched=true;this.emit("blur")};this.onLabelSlotChange=event=>{this.hasLabelSlot=event.target.assignedElements({flatten:true}).length>0};this.onHintSlotChange=event=>{this.hasHintSlot=event.target.assignedElements({flatten:true}).length>0};this.onErrorSlotChange=event=>{this.hasErrorSlot=event.target.assignedElements({flatten:true}).length>0};this.onNavigationKeyDown=event=>{if(this.effectiveDisabled)return;const items=this.flatItems;if(items.length===0)return;const inSearch=event.currentTarget===this.searchEl;const forwardKey=this.effectiveDirection==="rtl"?"ArrowLeft":"ArrowRight";const 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];if(item)this.pick(item);return}else{return}event.preventDefault();this.setActiveIndex(target,!inSearch)};this.onGridFocusIn=event=>{const button=event.target;if(button?.nodeType!==1||button.localName!=="button"){return}const option=button;const indexed=Number(option.dataset["index"]);const index=Number.isInteger(indexed)?indexed:this.optionButtons().indexOf(option);if(index>=0&&index!==this.activeIndex)this.setActiveIndex(index,false)};this.onGridScroll=event=>{if(!this.isVirtualized)return;const grid=event.currentTarget;this.virtualScrollTop=grid.scrollTop;const ownerDocument=this.ownerDocument;const ownerWindow=ownerDocument.defaultView;if(!ownerWindow)return;if(this.virtualScrollRaf!==void 0&&this.virtualScrollRafWindow===ownerWindow&&this.virtualScrollRafDocument===ownerDocument){return}this.cancelVirtualScrollFrame();const generation=this.ownerRealmGeneration;let handle=0;handle=ownerWindow.requestAnimationFrame(()=>{if(this.virtualScrollRaf!==handle||this.virtualScrollRafWindow!==ownerWindow||this.virtualScrollRafDocument!==ownerDocument||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument){return}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,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,emojiPickerSearchLabel:LYRA_DEFAULT_emojiPickerSearchLabel,fieldRequired:LYRA_DEFAULT_fieldRequired,item:LYRA_DEFAULT_item,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore}}static{this.styles=[LyraElement.styles,styles]}get groups(){return this._groups}set groups(value){const old=this._groups;this.groupsWereSet=true;this._groups=Array.isArray(value)?value:[];this.requestUpdate("groups",old)}connectedCallback(){super.connectedCallback();this.observeGeometryProbe();this.syncGridObserver();if(this.groupsWereSet)return;const ownerDocument=this.ownerDocument;const generation=this.ownerRealmGeneration;void this.loadGroups().then(loaded=>{if(this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||!loaded||this.groupsWereSet){return}this.groups=loaded})}haystackFor(item){const locale=this.effectiveLocale;let cached=this.haystacks.get(item);if(cached===void 0||cached.locale!==locale){cached={locale,value:[item.name,...item.shortcodes??[]].join(" ").toLocaleLowerCase(locale)};this.haystacks.set(item,cached)}return cached.value}get filteredGroups(){const q=this.queryText.trim().toLocaleLowerCase(this.effectiveLocale);if(!q)return this.groups;return this.groups.map(group=>({...group,emojis:group.emojis.filter(item=>this.haystackFor(item).includes(q))})).filter(group=>group.emojis.length>0)}get flatItems(){return this.filteredGroups.flatMap(group=>group.emojis)}get isVirtualized(){return this.flatItems.length>=VIRTUALIZE_AT}geometry(){if(this.geometryCache)return this.geometryCache;const probe=this.geometryProbe;if(!probe){return{itemSize:ITEM_SIZE_FALLBACK,gap:GAP_FALLBACK,rowHeight:VIRTUAL_ROW_HEIGHT_FALLBACK}}this.geometryCache={itemSize:probePixels(probe.item,ITEM_SIZE_FALLBACK),gap:probePixels(probe.gap,GAP_FALLBACK,true),rowHeight:probePixels(probe.row,VIRTUAL_ROW_HEIGHT_FALLBACK)};return this.geometryCache}syncGeometryProbe(){if(this.geometryProbe||!this.isVirtualized)return;const makeProbe=name=>{const probe=this.ownerDocument.createElement("div");probe.dataset["probe"]=name;return probe};const root=makeProbe("root");root.setAttribute("aria-hidden","true");const item=makeProbe("item");const gap=makeProbe("gap");const row=makeProbe("row");root.append(item,gap,row);this.renderRoot.append(root);this.geometryProbe={root,item,gap,row};this.observeGeometryProbe()}observeGeometryProbe(){const probe=this.geometryProbe;const ownerDocument=this.ownerDocument;if(!probe||!this.isConnected)return;if(this.geometryObserver&&this.geometryObserverDocument===ownerDocument&&this.geometryObserverRoot===probe.root){return}this.resetGeometryObserver();const ResizeObserverCtor=ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverCtor)return;const generation=this.ownerRealmGeneration;const observer=new ResizeObserverCtor(()=>{if(this.geometryObserver!==observer||this.geometryObserverDocument!==ownerDocument||this.geometryObserverRoot!==probe.root||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument){return}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){return group.labelKey?this.localize(group.labelKey):group.label}virtualRows(){const columns=this.columnsPerRow();let index=0;const rows=[];for(const group of this.filteredGroups){for(let offset=0;offset<group.emojis.length;offset+=columns){rows.push({label:offset===0?this.groupLabel(group):void 0,items:group.emojis.slice(offset,offset+columns).map(item=>({item,index:index++}))})}}return rows}optionButtons(){return[...this.renderRoot.querySelectorAll('[part="emoji"]')]}columnsPerRow(){if(this.isVirtualized){const grid=this.renderRoot.querySelector('[part="grid"]');const width=grid?.clientWidth??0;const{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));const target=this.isVirtualized?this.renderRoot.querySelector(`[part="emoji"][data-index="${this.activeIndex}"]`):buttons[this.activeIndex];const previous=this.renderRoot.querySelector('[part="emoji"][data-active]');if(previous&&previous!==target){previous.tabIndex=-1;previous.setAttribute("aria-selected","false");previous.removeAttribute("data-active")}if(target){target.tabIndex=0;target.setAttribute("aria-selected","true");target.setAttribute("data-active","");this.searchEl?.setAttribute("aria-activedescendant",target.id);target.scrollIntoView({block:"nearest"})}else if(this.isVirtualized){this.searchEl?.setAttribute("aria-activedescendant",`${this.gridId}-item-${this.activeIndex}`);const rowIndex=this.virtualRows().findIndex(row=>row.items.some(({index})=>index===this.activeIndex));const grid=this.renderRoot.querySelector('[part="grid"]');if(rowIndex>=0&&grid){grid.scrollTop=rowIndex*this.geometry().rowHeight;this.virtualScrollTop=grid.scrollTop;this.requestUpdate()}}if(focusTarget)target?.focus()}pick(item){if(this.effectiveDisabled)return;this.value=item.emoji;this.emit("input");this.emit("change");this.emit("lr-change",{emoji:item.emoji})}cancelVirtualScrollFrame(){if(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"]');const virtualized=this.isVirtualized;const ownerDocument=this.ownerDocument;if(grid===this.observedGrid&&virtualized===this.observedGridVirtualized&&(!virtualized||this.gridResizeObserverDocument===ownerDocument)){return}this.resetGridObserver();if(!this.isConnected)return;this.observedGrid=grid??void 0;this.observedGridVirtualized=virtualized;if(!grid||!virtualized)return;grid.addEventListener("scroll",this.onGridScroll,{passive:true});const ResizeObserverCtor=ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverCtor)return;const generation=this.ownerRealmGeneration;const observer=new ResizeObserverCtor(()=>{if(this.gridResizeObserver!==observer||this.gridResizeObserverDocument!==ownerDocument||this.observedGrid!==grid||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument){return}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=false;this.cancelVirtualScrollFrame()}willUpdate(changed){super.willUpdate(changed);this.syncGeometryProbe();if(!this.hasUpdated){this.hasLabelSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="label");this.hasHintSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="hint");this.hasErrorSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="error")}}updated(changed){this.syncGridObserver();if(!changed.has("queryText")&&!changed.has("groups"))return;const buttons=this.optionButtons();if(buttons.length===0){this.searchEl?.removeAttribute("aria-activedescendant");return}if(!this.isVirtualized&&this.activeIndex>=buttons.length)this.activeIndex=0;this.setActiveIndex(this.activeIndex,false)}disconnectedCallback(){super.disconnectedCallback();this.resetOwnerRealmResources()}adoptedCallback(){this.resetOwnerRealmResources()}resetOwnerRealmResources(){this.ownerRealmGeneration+=1;this.resetGridObserver();this.resetGeometryObserver()}renderEmojiButton(item,itemIndex,total){return html`<button
|
|
2
2
|
type="button"
|
|
3
3
|
part="emoji"
|
|
4
4
|
id=${`${this.gridId}-item-${itemIndex}`}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY}from"../../../internal/anchored-validity.js";import{lengthViolations}from"../../../internal/length-constraints.js";import{closeIcon,eyeIcon,eyeOffIcon}from"../../../internal/icons.js";import{styles}from"./input.styles.js";import{sizes}from"../../../internal/sizes.styles.js";import{autocorrectConverter,normalizeAutocorrect,spellcheckConverter}from"../../../internal/converters.js";import{finiteCount}from"../../../internal/numbers.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_collapse,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_hidePassword,LYRA_DEFAULT_inputLabel,LYRA_DEFAULT_open,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_showPassword,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";const LENGTH_CONSTRAINED_TYPES=["text","password","email","search","tel","url"];class LyraInputBase extends LyraElement{}class LyraInput extends FormAssociated(LyraInputBase){static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,collapse:LYRA_DEFAULT_collapse,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,hidePassword:LYRA_DEFAULT_hidePassword,inputLabel:LYRA_DEFAULT_inputLabel,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,showPassword:LYRA_DEFAULT_showPassword,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.styles=[LyraElement.styles,sizes,styles]}get value(){return super.value}set value(next){super.value=next??""}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.type="text";this.size="m";this.appearance="outlined";this.filled=false;this.pill=false;this.placeholder="";this.clearable=false;this.withClear=false;this.readonly=false;this.label="";this.hint="";this.helpText="";this.withLabel=false;this.withHint=false;this.errorText="";this.accessibleLabel=null;this.autocomplete="";this.title="";this.autofocus=false;this.spellcheck=true;this.autocapitalize="";this.autocorrectValue=true;this.inputMode="";this.enterKeyHint="";this.passwordToggle=false;this.passwordVisible=false;this.withoutSpinButtons=false;this.noSpinButtons=false;this.touched=false;this.slotPresence=new SlotPresenceController(this);this.onInput=event=>{if(!this.inputEl)return;this.value=this.inputEl.value;relayNativeEvent(this,event);this.emit("lr-input",{value:this.value})};this.onChange=event=>{if(!this.inputEl)return;this.value=this.inputEl.value;relayNativeEvent(this,event);this.emit("lr-change",{value:this.value})};this.onFocus=event=>{relayNativeEvent(this,event);this.emit("lr-focus")};this.onBlur=event=>{this.touched=true;relayNativeEvent(this,event);this.emit("lr-blur")};this.onKeyDown=event=>{if(this.effectiveDisabled||this.readonly)return;submitOnEnter(this,event)};this.onTogglePasswordVisible=()=>{this.passwordVisible=!this.passwordVisible};this.onClear=()=>{if(this.effectiveDisabled||this.readonly||this.value==="")return;this.value="";if(this.inputEl)this.inputEl.value="";dispatchNativeInputEvent(this,{inputType:"deleteContentBackward"});this.emit("lr-input",{value:this.value});dispatchNativeEvent(this,"change");this.emit("lr-change",{value:this.value});this.emit("lr-clear");this.inputEl?.focus()};this.addEventListener("invalid",()=>{this.touched=true})}formResetCallback(){super.formResetCallback();this.touched=false}get input(){return this.inputEl??null}click(){if(!this.effectiveDisabled)this.inputEl?.click()}focus(options){if(!this.effectiveDisabled)this.inputEl?.focus(options)}blur(){this.inputEl?.blur()}select(){this.inputEl?.select()}get valueAsDate(){const native=this.inputEl;if(!native)return null;if(native.value!==this.value)native.value=this.value;return native.valueAsDate}set valueAsDate(next){const native=this.inputEl;if(!native)return;native.valueAsDate=next;this.value=native.value}get valueAsNumber(){const native=this.inputEl;if(!native)return Number.NaN;if(native.value!==this.value)native.value=this.value;return native.valueAsNumber}set valueAsNumber(next){const native=this.inputEl;if(!native)return;native.valueAsNumber=next;this.value=native.value}showPicker(){const native=this.inputEl;if(!native||this.effectiveDisabled||this.readonly)return;if(!("showPicker"in HTMLInputElement.prototype))return;try{native.showPicker()}catch{}}stepUp(steps=1){this.applyStep("up",steps)}stepDown(steps=1){this.applyStep("down",steps)}applyStep(direction,steps){const native=this.inputEl;if(!native||this.effectiveDisabled||this.readonly)return;const count=finiteCount(steps,1);if(count===0)return;try{if(direction==="up")native.stepUp(count);else native.stepDown(count)}catch{return}if(this.value!==native.value)this.value=native.value}get selectionStart(){return this.inputEl?.selectionStart??null}set selectionStart(value){if(this.inputEl)this.inputEl.selectionStart=value??0}get selectionEnd(){return this.inputEl?.selectionEnd??null}set selectionEnd(value){if(this.inputEl)this.inputEl.selectionEnd=value??0}setSelectionRange(selectionStart,selectionEnd,selectionDirection="none"){this.inputEl?.setSelectionRange(selectionStart,selectionEnd,selectionDirection)}setRangeText(replacement,start,end,selectMode="preserve"){const input=this.inputEl;if(!input)return;if(start===void 0||end===void 0){input.setRangeText(replacement)}else{input.setRangeText(replacement,start,end,selectMode)}this.value=input.value}updateValidity(){const native=this.inputEl;if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}if(!native){if(this.required&&this.value===""){this[SET_ANCHORED_VALIDITY]({valueMissing:true},this.localize("fieldRequired"))}else{this[SET_ANCHORED_VALIDITY]({})}return}if(native.value!==this.value)native.value=this.value;const sanitizedAway=this.value!==""&&native.value==="";const v=native.validity;const own=LENGTH_CONSTRAINED_TYPES.includes(this.type)?lengthViolations(this.value,this.minlength,this.maxlength):{tooShort:false,tooLong:false};const tooShort=v.tooShort||own.tooShort;const tooLong=v.tooLong||own.tooLong;if(v.valid&&!tooShort&&!tooLong){if(sanitizedAway){this[SET_ANCHORED_VALIDITY]({badInput:true},this.localize("valueInvalid"));return}this[SET_ANCHORED_VALIDITY]({});return}this[SET_ANCHORED_VALIDITY]({valueMissing:v.valueMissing,typeMismatch:v.typeMismatch,rangeUnderflow:v.rangeUnderflow,rangeOverflow:v.rangeOverflow,stepMismatch:v.stepMismatch,tooShort,tooLong,patternMismatch:v.patternMismatch,badInput:v.badInput},native.validationMessage||this.localize("valueInvalid"))}updated(changed){super.updated(changed);if(changed.has("value")){if(this.value==="")this.internals.states.add("blank");else this.internals.states.delete("blank")}if(changed.has("type")||changed.has("min")||changed.has("max")||changed.has("step")||changed.has("minlength")||changed.has("maxlength")||changed.has("pattern")||changed.has("readonly")){this.updateValidity()}}renderControls(){return nothing}get inputWrapperParts(){return"base form-control-input input-wrapper"}render(){const hasHint=this.slotPresence.has("hint")||this.slotPresence.has("help-text")||this.hint.length>0||this.helpText.length>0||this.withHint;const hasError=this.slotPresence.has("error")||this.errorText.length>0;const hasLabel=this.slotPresence.has("label")||this.label.length>0||this.withLabel;const describedBy=[hasError?"input-error":"",hasHint?"input-hint":""].filter(Boolean).join(" ");const isPassword=this.type==="password";const showPasswordToggle=isPassword&&this.passwordToggle;const nativeType=isPassword&&this.passwordVisible?"text":this.type;const canClear=(this.clearable||this.withClear)&&(this.type==="text"||this.type==="search")&&this.value!=="";return html`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY}from"../../../internal/anchored-validity.js";import{lengthViolations}from"../../../internal/length-constraints.js";import{closeIcon,eyeIcon,eyeOffIcon}from"../../../internal/icons.js";import{styles}from"./input.styles.js";import{sizes}from"../../../internal/sizes.styles.js";import{autocorrectConverter,normalizeAutocorrect,spellcheckConverter}from"../../../internal/converters.js";import{finiteCount}from"../../../internal/numbers.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_collapse,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_hidePassword,LYRA_DEFAULT_inputLabel,LYRA_DEFAULT_open,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_showPassword,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";const LENGTH_CONSTRAINED_TYPES=["text","password","email","search","tel","url"];class LyraInputBase extends LyraElement{}class LyraInput extends FormAssociated(LyraInputBase){static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,collapse:LYRA_DEFAULT_collapse,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,hidePassword:LYRA_DEFAULT_hidePassword,inputLabel:LYRA_DEFAULT_inputLabel,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,showPassword:LYRA_DEFAULT_showPassword,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.styles=[LyraElement.styles,sizes,styles]}get value(){return super.value}set value(next){super.value=next??""}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.type="text";this.size="m";this.appearance="outlined";this.filled=false;this.pill=false;this.placeholder="";this.clearable=false;this.withClear=false;this.readonly=false;this.label="";this.hint="";this.helpText="";this.withLabel=false;this.withHint=false;this.errorText="";this.accessibleLabel=null;this.autocomplete="";this.title="";this.autofocus=false;this.spellcheck=true;this.autocapitalize="";this.autocorrectValue=true;this.inputMode="";this.enterKeyHint="";this.passwordToggle=false;this.passwordVisible=false;this.withoutSpinButtons=false;this.noSpinButtons=false;this.touched=false;this.slotPresence=new SlotPresenceController(this);this.onInput=event=>{if(!this.inputEl)return;this.value=this.inputEl.value;relayNativeEvent(this,event);this.emit("lr-input",{value:this.value})};this.onChange=event=>{if(!this.inputEl)return;this.value=this.inputEl.value;relayNativeEvent(this,event);this.emit("lr-change",{value:this.value})};this.onFocus=event=>{relayNativeEvent(this,event);this.emit("lr-focus")};this.onBlur=event=>{if(!this.effectiveDisabled)this.touched=true;relayNativeEvent(this,event);this.emit("lr-blur")};this.onKeyDown=event=>{if(this.effectiveDisabled||this.readonly)return;submitOnEnter(this,event)};this.onTogglePasswordVisible=()=>{this.passwordVisible=!this.passwordVisible};this.onClear=()=>{if(this.effectiveDisabled||this.readonly||this.value==="")return;this.value="";if(this.inputEl)this.inputEl.value="";dispatchNativeInputEvent(this,{inputType:"deleteContentBackward"});this.emit("lr-input",{value:this.value});dispatchNativeEvent(this,"change");this.emit("lr-change",{value:this.value});this.emit("lr-clear");this.inputEl?.focus()};this.addEventListener("invalid",()=>{this.touched=true})}formResetCallback(){super.formResetCallback();this.touched=false}get input(){return this.inputEl??null}click(){if(!this.effectiveDisabled)this.inputEl?.click()}focus(options){if(!this.effectiveDisabled)this.inputEl?.focus(options)}blur(){this.inputEl?.blur()}select(){this.inputEl?.select()}get valueAsDate(){const native=this.inputEl;if(!native)return null;if(native.value!==this.value)native.value=this.value;return native.valueAsDate}set valueAsDate(next){const native=this.inputEl;if(!native)return;native.valueAsDate=next;this.value=native.value}get valueAsNumber(){const native=this.inputEl;if(!native)return Number.NaN;if(native.value!==this.value)native.value=this.value;return native.valueAsNumber}set valueAsNumber(next){const native=this.inputEl;if(!native)return;native.valueAsNumber=next;this.value=native.value}showPicker(){const native=this.inputEl;if(!native||this.effectiveDisabled||this.readonly)return;if(!("showPicker"in HTMLInputElement.prototype))return;try{native.showPicker()}catch{}}stepUp(steps=1){this.applyStep("up",steps)}stepDown(steps=1){this.applyStep("down",steps)}applyStep(direction,steps){const native=this.inputEl;if(!native||this.effectiveDisabled||this.readonly)return;const count=finiteCount(steps,1);if(count===0)return;try{if(direction==="up")native.stepUp(count);else native.stepDown(count)}catch{return}if(this.value!==native.value)this.value=native.value}get selectionStart(){return this.inputEl?.selectionStart??null}set selectionStart(value){if(this.inputEl)this.inputEl.selectionStart=value??0}get selectionEnd(){return this.inputEl?.selectionEnd??null}set selectionEnd(value){if(this.inputEl)this.inputEl.selectionEnd=value??0}setSelectionRange(selectionStart,selectionEnd,selectionDirection="none"){this.inputEl?.setSelectionRange(selectionStart,selectionEnd,selectionDirection)}setRangeText(replacement,start,end,selectMode="preserve"){const input=this.inputEl;if(!input)return;if(start===void 0||end===void 0){input.setRangeText(replacement)}else{input.setRangeText(replacement,start,end,selectMode)}this.value=input.value}updateValidity(){const native=this.inputEl;if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}if(!native){if(this.required&&this.value===""){this[SET_ANCHORED_VALIDITY]({valueMissing:true},this.localize("fieldRequired"))}else{this[SET_ANCHORED_VALIDITY]({})}return}if(native.value!==this.value)native.value=this.value;const sanitizedAway=this.value!==""&&native.value==="";const v=native.validity;const own=LENGTH_CONSTRAINED_TYPES.includes(this.type)?lengthViolations(this.value,this.minlength,this.maxlength):{tooShort:false,tooLong:false};const tooShort=v.tooShort||own.tooShort;const tooLong=v.tooLong||own.tooLong;if(v.valid&&!tooShort&&!tooLong){if(sanitizedAway){this[SET_ANCHORED_VALIDITY]({badInput:true},this.localize("valueInvalid"));return}this[SET_ANCHORED_VALIDITY]({});return}this[SET_ANCHORED_VALIDITY]({valueMissing:v.valueMissing,typeMismatch:v.typeMismatch,rangeUnderflow:v.rangeUnderflow,rangeOverflow:v.rangeOverflow,stepMismatch:v.stepMismatch,tooShort,tooLong,patternMismatch:v.patternMismatch,badInput:v.badInput},native.validationMessage||this.localize("valueInvalid"))}updated(changed){super.updated(changed);if(changed.has("value")){if(this.value==="")this.internals.states.add("blank");else this.internals.states.delete("blank")}if(changed.has("type")||changed.has("min")||changed.has("max")||changed.has("step")||changed.has("minlength")||changed.has("maxlength")||changed.has("pattern")||changed.has("readonly")){this.updateValidity()}}renderControls(){return nothing}get inputWrapperParts(){return"base form-control-input input-wrapper"}render(){const hasHint=this.slotPresence.has("hint")||this.slotPresence.has("help-text")||this.hint.length>0||this.helpText.length>0||this.withHint;const hasError=this.slotPresence.has("error")||this.errorText.length>0;const hasLabel=this.slotPresence.has("label")||this.label.length>0||this.withLabel;const describedBy=[hasError?"input-error":"",hasHint?"input-hint":""].filter(Boolean).join(" ");const isPassword=this.type==="password";const showPasswordToggle=isPassword&&this.passwordToggle;const nativeType=isPassword&&this.passwordVisible?"text":this.type;const canClear=(this.clearable||this.withClear)&&(this.type==="text"||this.type==="search")&&this.value!=="";return html`
|
|
2
2
|
<div part="form-control">
|
|
3
3
|
<label part="form-control-label" for="input" ?hidden=${!hasLabel}>
|
|
4
4
|
<span part="label">${this.label}<slot name="label"></slot></span>
|