@aceshooting/lyra-ui 8.2.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 +28 -0
- 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/forms/checkbox/checkbox.class.js +1 -1
- 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/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/package.json +2 -2
- 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{nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{getDisplayNames}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./phone-input.styles.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{trueDefaultSpellcheckConverter as spellcheckConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_phoneInputIncomplete,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";async function loadLibphonenumberAdapter(loader){const module=await loader();const countries=module.getCountries().map(code=>({code:normalizeCountry(code),callingCode:module.getCountryCallingCode(code)}));return{countries,parse(input,country){const raw=input.trim();if(!raw)return{status:"empty"};const normalizedCountry=country?normalizeCountry(country):void 0;const phone=module.parsePhoneNumberFromString(raw,normalizedCountry);if(!phone){const length2=module.validatePhoneNumberLength?.(raw,normalizedCountry);return{status:length2==="TOO_SHORT"||isDialLike(raw)?"incomplete":"invalid",formatted:raw}}const formatted=raw.startsWith("+")?phone.formatInternational():phone.formatNational();if(phone.isValid()){return{status:"valid",e164:phone.number,formatted,country:phone.country?normalizeCountry(phone.country):normalizedCountry}}const length=module.validatePhoneNumberLength?.(raw,normalizedCountry);return{status:length==="TOO_SHORT"||!length&&!phone.isPossible()?"incomplete":"invalid",formatted,country:phone.country?normalizeCountry(phone.country):normalizedCountry}}}}class LyraPhoneInputBase extends LyraElement{}const E164_RE=/^\+[1-9]\d{1,14}$/;const DIAL_LIKE_RE=/^[+\d\s().-]+$/;function normalizeCountry(country){return country.trim().toUpperCase()}function isDialLike(value){return DIAL_LIKE_RE.test(value.trim())}function digitsBefore(value,index){let count=0;for(let i=0;i<index&&i<value.length;i++){if(/\d/.test(value[i]))count++}return count}function indexAfterDigits(value,digitCount){if(digitCount<=0)return 0;let count=0;for(let i=0;i<value.length;i++){if(/\d/.test(value[i])){count++;if(count===digitCount)return i+1}}return value.length}function fallbackParse(input){const raw=input.trim();if(!raw)return{status:"empty"};const compact=raw.replace(/[\s().-]/g,"");if(E164_RE.test(compact))return{status:"valid",e164:compact,formatted:raw};if(isDialLike(raw))return{status:"incomplete",formatted:raw};return{status:"invalid",formatted:raw}}class LyraPhoneInput extends FormAssociated(LyraPhoneInputBase){constructor(){super(...arguments);this.flags=false;this.countries=[];this.defaultCountry="";this.label="";this.hint="";this.errorText="";this.placeholder="";this.size="m";this.pill=false;this.accessibleLabel=null;this.countryLabel="Select";this.phoneLabel="";this.incompleteText="This phone number is incomplete.";this.invalidText="The value is invalid.";this.autocomplete="tel";this.inputmode="tel";this.enterkeyhint="";this.spellcheck=true;this.autocapitalize="";this.autoCorrect="";this.editableValue="";this.status="empty";this.touched=false;this.hasLabelSlot=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.hasCountryPrefixSlot=false;this.inputId=nextId("phone-input");this.hintId=nextId("phone-hint");this.errorId=nextId("phone-error");this.explicitCountry="";this.catalogCountryResolved=false;this.onInput=event=>{event.stopPropagation();const input=event.currentTarget;const caret=input.selectionStart;const digitsBeforeCaret=caret==null?null:digitsBefore(input.value,caret);this.applyParsed(input.value,this.parse(input.value));this.syncFormattedValue(input,digitsBeforeCaret);this.emit("input",this.eventDetail)};this.onChange=event=>{event.stopPropagation();this.touched=true;this.emit("change",this.eventDetail)};this.onCountryChange=event=>{event.stopPropagation();this.country=normalizeCountry(event.currentTarget.value);this.applyParsed(this.editableValue,this.parse(this.editableValue));this.emit("input",this.eventDetail);this.emit("change",this.eventDetail)};this.onKeyDown=event=>{if(this.effectiveDisabled)return;submitOnEnter(this,event)};this.onFocus=event=>{event.stopPropagation();this.emit("focus")};this.onBlur=event=>{event.stopPropagation();this.touched=true;this.emit("blur")};this.onLabelSlotChange=event=>{this.hasLabelSlot=event.currentTarget.assignedElements({flatten:true}).length>0};this.onHintSlotChange=event=>{this.hasHintSlot=event.currentTarget.assignedElements({flatten:true}).length>0};this.onErrorSlotChange=event=>{this.hasErrorSlot=event.currentTarget.assignedElements({flatten:true}).length>0};this.onCountryPrefixSlotChange=event=>{this.hasCountryPrefixSlot=event.currentTarget.assignedElements({flatten:true}).length>0}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,phoneInputIncomplete:LYRA_DEFAULT_phoneInputIncomplete,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={country:{noAccessor:true}}}get country(){if(this.catalogCountryResolved)return normalizeCountry(this.explicitCountry);const firstCountry=this.countries[0]?.code??this.adapter?.countries?.[0]?.code??"";return normalizeCountry(this.explicitCountry||this.defaultCountry||firstCountry)}set country(next){const old=this.country;this.catalogCountryResolved=false;this.explicitCountry=normalizeCountry(next??"");this.requestUpdate("country",old)}get input(){return this.inputElement}get inputValue(){return this.editableValue}get phoneStatus(){return this.status}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}set selectionDirection(value){if(this.inputElement)this.inputElement.selectionDirection=value??"none"}[VALIDITY_ANCHOR](){return this.inputElement??null}get value(){return super.value}set value(next){const raw=next??"";const parsed=this.parse(raw);this.applyParsed(raw,parsed)}get availableCountries(){const source=this.countries.length?this.countries:this.adapter?.countries??[];const seen=new Set;const rows=[];for(const item of source){const code=normalizeCountry(item.code);if(!/^[A-Z]{2}$/.test(code)||seen.has(code))continue;seen.add(code);rows.push({...item,code,callingCode:item.callingCode.replace(/^\+/,"")})}if(rows.length===0&&this.country){rows.push({code:this.country,callingCode:""})}return rows}parse(input){if(!this.adapter)return fallbackParse(input);try{const parsed=this.adapter.parse(input,this.country||void 0);if(parsed.status==="valid"&&(!parsed.e164||!E164_RE.test(parsed.e164))){return{status:"invalid",formatted:parsed.formatted??input,country:parsed.country}}return parsed}catch{return fallbackParse(input)}}reconcileCountryCatalog(){const source=this.countries.length?this.countries:this.adapter?.countries??[];const codes=source.map(item=>normalizeCountry(item.code)).filter((code,index,values)=>/^[A-Z]{2}$/.test(code)&&values.indexOf(code)===index);const old=this.country;const preferred=normalizeCountry(this.defaultCountry);const next=codes.includes(old)?old:codes.includes(preferred)?preferred:codes[0]??"";this.explicitCountry=next;this.catalogCountryResolved=true;if(old!==next)this.requestUpdate("country",old)}applyParsed(raw,parsed){this.editableValue=parsed.formatted??raw;this.status=parsed.status;if(parsed.country)this.country=normalizeCountry(parsed.country);super.value=parsed.status==="valid"?parsed.e164:"";this.setAttribute("data-phone-status",parsed.status)}syncFormattedValue(input,digitsBeforeCaret){if(input.value===this.editableValue)return;input.value=this.editableValue;if(digitsBeforeCaret!=null){const position=indexAfterDigits(this.editableValue,digitsBeforeCaret);input.setSelectionRange(position,position)}}get eventDetail(){return{value:super.value,inputValue:this.editableValue,country:this.country,valid:this.internals.validity.valid,status:this.status}}get effectiveCountryLabel(){return this.localize("select",this.countryLabel==="Select"?void 0:this.countryLabel)}get effectivePhoneLabel(){return this.accessibleLabel||this.phoneLabel||this.label||this.placeholder||void 0}get incompleteMessage(){return this.localize("phoneInputIncomplete",this.incompleteText==="This phone number is incomplete."?void 0:this.incompleteText)}get invalidMessage(){return this.localize("valueInvalid",this.invalidText==="The value is invalid."?void 0:this.invalidText)}countryName(row){if(row.label)return row.label;try{return getDisplayNames(this.effectiveLocale,{type:"region"}).of(row.code)??row.code}catch{return row.code}}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let message="";if(this.required&&this.status==="empty"){flags.valueMissing=true;message=this.localize("fieldRequired")}else if(this.status==="incomplete"){flags.badInput=true;message=this.incompleteMessage}else if(this.status==="invalid"){flags.typeMismatch=true;message=this.invalidMessage}this[SET_ANCHORED_VALIDITY](flags,message)}willUpdate(changed){super.willUpdate(changed);if(this.flags&&!LyraPhoneInput.flagRegistration){LyraPhoneInput.flagRegistration=import("../../media/flag/flag.js").catch(error=>{console.warn("<lr-phone-input> failed to register <lr-flag> for its flags option:",error)})}if(!this.hasUpdated){this.hasLabelSlot=Array.from(this.children).some(child=>child.getAttribute("slot")==="label");this.hasHintSlot=Array.from(this.children).some(child=>child.getAttribute("slot")==="hint");this.hasErrorSlot=Array.from(this.children).some(child=>child.getAttribute("slot")==="error");this.hasCountryPrefixSlot=Array.from(this.children).some(child=>child.getAttribute("slot")==="country-prefix")}if(this.hasUpdated&&(changed.has("countries")||changed.has("adapter"))){this.reconcileCountryCatalog()}if((changed.has("adapter")||changed.has("countries")||changed.has("country")||changed.has("defaultCountry"))&&this.editableValue){this.applyParsed(this.editableValue,this.parse(this.editableValue))}}updated(changed){super.updated(changed);if(changed.has("touched")||changed.has("required")||changed.has("value")||changed.has("status")){const invalid=this.touched&&!this.internals.validity.valid;this.toggleAttribute("data-invalid",invalid);if(invalid)this.setAttribute("aria-invalid","true");else this.removeAttribute("aria-invalid")}}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)}const caret=input.selectionStart;const digitsBeforeCaret=caret==null?null:digitsBefore(input.value,caret);this.applyParsed(input.value,this.parse(input.value));this.syncFormattedValue(input,digitsBeforeCaret)}formResetCallback(){this.country=normalizeCountry(this.defaultCountry||this.availableCountries[0]?.code||"");super.formResetCallback();this.touched=false}render(){const hasLabel=Boolean(this.label||this.hasLabelSlot);const validationError=this.touched?this.validationMessage:"";const renderedError=this.errorText||validationError;const hasHint=Boolean(this.hint||this.hasHintSlot);const hasError=Boolean(renderedError||this.hasErrorSlot);const describedBy=[hasHint?this.hintId:"",hasError?this.errorId:""].filter(Boolean).join(" ");const rows=this.availableCountries;const current=rows.find(row=>row.code===this.country);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{nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{getDisplayNames}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./phone-input.styles.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{trueDefaultSpellcheckConverter as spellcheckConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_phoneInputIncomplete,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";async function loadLibphonenumberAdapter(loader){const module=await loader();const countries=module.getCountries().map(code=>({code:normalizeCountry(code),callingCode:module.getCountryCallingCode(code)}));return{countries,parse(input,country){const raw=input.trim();if(!raw)return{status:"empty"};const normalizedCountry=country?normalizeCountry(country):void 0;const phone=module.parsePhoneNumberFromString(raw,normalizedCountry);if(!phone){const length2=module.validatePhoneNumberLength?.(raw,normalizedCountry);return{status:length2==="TOO_SHORT"||isDialLike(raw)?"incomplete":"invalid",formatted:raw}}const formatted=raw.startsWith("+")?phone.formatInternational():phone.formatNational();if(phone.isValid()){return{status:"valid",e164:phone.number,formatted,country:phone.country?normalizeCountry(phone.country):normalizedCountry}}const length=module.validatePhoneNumberLength?.(raw,normalizedCountry);return{status:length==="TOO_SHORT"||!length&&!phone.isPossible()?"incomplete":"invalid",formatted,country:phone.country?normalizeCountry(phone.country):normalizedCountry}}}}class LyraPhoneInputBase extends LyraElement{}const E164_RE=/^\+[1-9]\d{1,14}$/;const DIAL_LIKE_RE=/^[+\d\s().-]+$/;function normalizeCountry(country){return country.trim().toUpperCase()}function isDialLike(value){return DIAL_LIKE_RE.test(value.trim())}function digitsBefore(value,index){let count=0;for(let i=0;i<index&&i<value.length;i++){if(/\d/.test(value[i]))count++}return count}function indexAfterDigits(value,digitCount){if(digitCount<=0)return 0;let count=0;for(let i=0;i<value.length;i++){if(/\d/.test(value[i])){count++;if(count===digitCount)return i+1}}return value.length}function fallbackParse(input){const raw=input.trim();if(!raw)return{status:"empty"};const compact=raw.replace(/[\s().-]/g,"");if(E164_RE.test(compact))return{status:"valid",e164:compact,formatted:raw};if(isDialLike(raw))return{status:"incomplete",formatted:raw};return{status:"invalid",formatted:raw}}class LyraPhoneInput extends FormAssociated(LyraPhoneInputBase){constructor(){super(...arguments);this.flags=false;this.countries=[];this.defaultCountry="";this.label="";this.hint="";this.errorText="";this.placeholder="";this.size="m";this.pill=false;this.accessibleLabel=null;this.countryLabel="Select";this.phoneLabel="";this.incompleteText="This phone number is incomplete.";this.invalidText="The value is invalid.";this.autocomplete="tel";this.inputmode="tel";this.enterkeyhint="";this.spellcheck=true;this.autocapitalize="";this.autoCorrect="";this.editableValue="";this.status="empty";this.touched=false;this.hasLabelSlot=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.hasCountryPrefixSlot=false;this.inputId=nextId("phone-input");this.hintId=nextId("phone-hint");this.errorId=nextId("phone-error");this.explicitCountry="";this.catalogCountryResolved=false;this.onInput=event=>{event.stopPropagation();const input=event.currentTarget;const caret=input.selectionStart;const digitsBeforeCaret=caret==null?null:digitsBefore(input.value,caret);this.applyParsed(input.value,this.parse(input.value));this.syncFormattedValue(input,digitsBeforeCaret);this.emit("input",this.eventDetail)};this.onChange=event=>{event.stopPropagation();this.touched=true;this.emit("change",this.eventDetail)};this.onCountryChange=event=>{event.stopPropagation();this.country=normalizeCountry(event.currentTarget.value);this.applyParsed(this.editableValue,this.parse(this.editableValue));this.emit("input",this.eventDetail);this.emit("change",this.eventDetail)};this.onKeyDown=event=>{if(this.effectiveDisabled)return;submitOnEnter(this,event)};this.onFocus=event=>{event.stopPropagation();this.emit("focus")};this.onBlur=event=>{event.stopPropagation();if(!this.effectiveDisabled)this.touched=true;this.emit("blur")};this.onLabelSlotChange=event=>{this.hasLabelSlot=event.currentTarget.assignedElements({flatten:true}).length>0};this.onHintSlotChange=event=>{this.hasHintSlot=event.currentTarget.assignedElements({flatten:true}).length>0};this.onErrorSlotChange=event=>{this.hasErrorSlot=event.currentTarget.assignedElements({flatten:true}).length>0};this.onCountryPrefixSlotChange=event=>{this.hasCountryPrefixSlot=event.currentTarget.assignedElements({flatten:true}).length>0}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,phoneInputIncomplete:LYRA_DEFAULT_phoneInputIncomplete,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={country:{noAccessor:true}}}get country(){if(this.catalogCountryResolved)return normalizeCountry(this.explicitCountry);const firstCountry=this.countries[0]?.code??this.adapter?.countries?.[0]?.code??"";return normalizeCountry(this.explicitCountry||this.defaultCountry||firstCountry)}set country(next){const old=this.country;this.catalogCountryResolved=false;this.explicitCountry=normalizeCountry(next??"");this.requestUpdate("country",old)}get input(){return this.inputElement}get inputValue(){return this.editableValue}get phoneStatus(){return this.status}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}set selectionDirection(value){if(this.inputElement)this.inputElement.selectionDirection=value??"none"}[VALIDITY_ANCHOR](){return this.inputElement??null}get value(){return super.value}set value(next){const raw=next??"";const parsed=this.parse(raw);this.applyParsed(raw,parsed)}get availableCountries(){const source=this.countries.length?this.countries:this.adapter?.countries??[];const seen=new Set;const rows=[];for(const item of source){const code=normalizeCountry(item.code);if(!/^[A-Z]{2}$/.test(code)||seen.has(code))continue;seen.add(code);rows.push({...item,code,callingCode:item.callingCode.replace(/^\+/,"")})}if(rows.length===0&&this.country){rows.push({code:this.country,callingCode:""})}return rows}parse(input){if(!this.adapter)return fallbackParse(input);try{const parsed=this.adapter.parse(input,this.country||void 0);if(parsed.status==="valid"&&(!parsed.e164||!E164_RE.test(parsed.e164))){return{status:"invalid",formatted:parsed.formatted??input,country:parsed.country}}return parsed}catch{return fallbackParse(input)}}reconcileCountryCatalog(){const source=this.countries.length?this.countries:this.adapter?.countries??[];const codes=source.map(item=>normalizeCountry(item.code)).filter((code,index,values)=>/^[A-Z]{2}$/.test(code)&&values.indexOf(code)===index);const old=this.country;const preferred=normalizeCountry(this.defaultCountry);const next=codes.includes(old)?old:codes.includes(preferred)?preferred:codes[0]??"";this.explicitCountry=next;this.catalogCountryResolved=true;if(old!==next)this.requestUpdate("country",old)}applyParsed(raw,parsed){this.editableValue=parsed.formatted??raw;this.status=parsed.status;if(parsed.country)this.country=normalizeCountry(parsed.country);super.value=parsed.status==="valid"?parsed.e164:"";this.setAttribute("data-phone-status",parsed.status)}syncFormattedValue(input,digitsBeforeCaret){if(input.value===this.editableValue)return;input.value=this.editableValue;if(digitsBeforeCaret!=null){const position=indexAfterDigits(this.editableValue,digitsBeforeCaret);input.setSelectionRange(position,position)}}get eventDetail(){return{value:super.value,inputValue:this.editableValue,country:this.country,valid:this.internals.validity.valid,status:this.status}}get effectiveCountryLabel(){return this.localize("select",this.countryLabel==="Select"?void 0:this.countryLabel)}get effectivePhoneLabel(){return this.accessibleLabel||this.phoneLabel||this.label||this.placeholder||void 0}get incompleteMessage(){return this.localize("phoneInputIncomplete",this.incompleteText==="This phone number is incomplete."?void 0:this.incompleteText)}get invalidMessage(){return this.localize("valueInvalid",this.invalidText==="The value is invalid."?void 0:this.invalidText)}countryName(row){if(row.label)return row.label;try{return getDisplayNames(this.effectiveLocale,{type:"region"}).of(row.code)??row.code}catch{return row.code}}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let message="";if(this.required&&this.status==="empty"){flags.valueMissing=true;message=this.localize("fieldRequired")}else if(this.status==="incomplete"){flags.badInput=true;message=this.incompleteMessage}else if(this.status==="invalid"){flags.typeMismatch=true;message=this.invalidMessage}this[SET_ANCHORED_VALIDITY](flags,message)}willUpdate(changed){super.willUpdate(changed);if(this.flags&&!LyraPhoneInput.flagRegistration){LyraPhoneInput.flagRegistration=import("../../media/flag/flag.js").catch(error=>{console.warn("<lr-phone-input> failed to register <lr-flag> for its flags option:",error)})}if(!this.hasUpdated){this.hasLabelSlot=Array.from(this.children).some(child=>child.getAttribute("slot")==="label");this.hasHintSlot=Array.from(this.children).some(child=>child.getAttribute("slot")==="hint");this.hasErrorSlot=Array.from(this.children).some(child=>child.getAttribute("slot")==="error");this.hasCountryPrefixSlot=Array.from(this.children).some(child=>child.getAttribute("slot")==="country-prefix")}if(this.hasUpdated&&(changed.has("countries")||changed.has("adapter"))){this.reconcileCountryCatalog()}if((changed.has("adapter")||changed.has("countries")||changed.has("country")||changed.has("defaultCountry"))&&this.editableValue){this.applyParsed(this.editableValue,this.parse(this.editableValue))}}updated(changed){super.updated(changed);if(changed.has("touched")||changed.has("required")||changed.has("value")||changed.has("status")){const invalid=this.touched&&!this.internals.validity.valid;this.toggleAttribute("data-invalid",invalid);if(invalid)this.setAttribute("aria-invalid","true");else this.removeAttribute("aria-invalid")}}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)}const caret=input.selectionStart;const digitsBeforeCaret=caret==null?null:digitsBefore(input.value,caret);this.applyParsed(input.value,this.parse(input.value));this.syncFormattedValue(input,digitsBeforeCaret)}formResetCallback(){this.country=normalizeCountry(this.defaultCountry||this.availableCountries[0]?.code||"");super.formResetCallback();this.touched=false}render(){const hasLabel=Boolean(this.label||this.hasLabelSlot);const validationError=this.touched?this.validationMessage:"";const renderedError=this.errorText||validationError;const hasHint=Boolean(this.hint||this.hasHintSlot);const hasError=Boolean(renderedError||this.hasErrorSlot);const describedBy=[hasHint?this.hintId:"",hasError?this.errorId:""].filter(Boolean).join(" ");const rows=this.availableCountries;const current=rows.find(row=>row.code===this.country);return html`
|
|
2
2
|
<div part="form-control">
|
|
3
3
|
<label part="form-control-label" for=${this.inputId} ?hidden=${!hasLabel}>
|
|
4
4
|
<slot name="label" @slotchange=${this.onLabelSlotChange}>${this.label}</slot>
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)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{rtlAwarePlacement}from"../../../internal/rtl.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon,closeIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{finiteCount}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./select.styles.js";import{sizes}from"../../../internal/sizes.styles.js";import{LyraOption}from"../combobox/option.class.js";import"../combobox/option.class.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{omittedEmptyStringConverter}from"../../../internal/converters.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.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_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_select,LYRA_DEFAULT_selectSelectedOverflow,LYRA_DEFAULT_selectValueMissing}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 LyraSelect extends LyraElement{static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,select:LYRA_DEFAULT_select,selectSelectedOverflow:LYRA_DEFAULT_selectSelectedOverflow,selectValueMissing:LYRA_DEFAULT_selectValueMissing}}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},defaultValue:{attribute:"default-value",noAccessor:true}}}focus(options){if(!this.effectiveDisabled)this.triggerElement?.focus(options)}blur(){this.triggerElement?.blur()}click(){if(!this.effectiveDisabled)this.triggerElement?.click()}constructor(){super();this.placeholder="";this.label="";this.hint="";this.helpText="";this.withLabel=false;this.withHint=false;this.errorText="";this.autofocus=false;this.title="";this.open=false;this.size="m";this.appearance="outlined";this.pill=false;this.placement="bottom";this.hoist=false;this.filled=false;this.withClear=false;this.clearable=false;this.autoCommitSingleOption=false;this.activeIndex=-1;this.options=[];this.touched=false;this.hasInteracted=false;this.slotPresence=new SlotPresenceController(this);this._fieldsetDisabled=false;this.listId=nextId("select-list");this.triggerId=nextId("select-trigger");this._isFirstUpdate=true;this.openVetoed=false;this.transitionToken=0;this.transitionWaiters=new Map;this._selected=[];this._selectedOptions=[];this._multiple=false;this._disabled=false;this._required=false;this._defaultSelected=[];this._defaultSelectedOptions=[];this._defaultCaptured=false;this._valueDirty=false;this._restoredStateActive=false;this.typeAheadBuffer="";this.typeAheadTimerGeneration=0;this._name="";this._maxOptionsVisible=3;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 hasDefaultValue=this.hasAttribute("default-value");const allDefaults=this.options.filter(option=>option.defaultSelected);const defaults=this.multiple?allDefaults:allDefaults.slice(0,1);const allLive=this.options.filter(option=>option.selected);const live=this.multiple?allLive:allLive.slice(0,1);const initialLive=this.options.filter(option=>wasOptionInitiallySelected(option));const optionDirty=this.options.some(option=>isOptionSelectedDirty(option));const dirtySelected=this.options.filter(option=>isOptionSelectedDirty(option)&&option.selected);if(!hasDefaultValue){const resetOptions=defaults.length>0?defaults:initialLive.length>0?initialLive:live;this._defaultSelected=resetOptions.map(option=>option.value);this._defaultSelectedOptions=[...resetOptions]}else{this._defaultSelectedOptions=this.resolveOccurrences(this._defaultSelected)}const fromDefaults=hasDefaultValue||defaults.length>0;const initial=optionDirty?this.multiple?allLive:dirtySelected.slice(-1)[0]?dirtySelected.slice(-1):live:hasDefaultValue?this._defaultSelectedOptions:fromDefaults?defaults:live;if(initial.length>0&&!this._restoredStateActive&&!this._valueDirty){if(!fromDefaults||optionDirty)this._valueDirty=true;this.setSelection(initial.map(option=>option.value),[...initial]);return}if(optionDirty)this._valueDirty=true;if(hasDefaultValue&&!this._valueDirty&&!this._restoredStateActive){this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions]);return}}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>0){const added=this.multiple?eligible:eligible.slice(-1);const occurrences=this.multiple?[...new Set([...this._selectedOptions,...added])]:added;if(newLive.length>0)this._valueDirty=true;this.setSelection(occurrences.map(option=>option.value),occurrences);return}}this.reflectSelected()};this.onOptionChange=()=>{queueMicrotask(()=>{this.refreshOptionDefaults();this.reflectSelected();this.options=[...this.options]})};this.onDocPointer=e=>{if(!e.composedPath().includes(this))void this.hide()};this.onTriggerClick=()=>{if(this.effectiveDisabled)return;if(this.onlyOption)return this.selectOption(this.onlyOption);if(this.open)void this.hide();else void this.show()};this.onTriggerBlur=event=>{this.touched=true;this.hasInteracted=true;this.reflectValidityStates();void this.hide();relayNativeEvent(this,event);this.emit("lr-blur")};this.onTriggerFocus=event=>{relayNativeEvent(this,event);this.emit("lr-focus")};this.onKeyDown=e=>{const navigable=this.navigableOptions();switch(e.key){case"ArrowDown":e.preventDefault();if(this.onlyOption)return this.selectOption(this.onlyOption);if(!this.open){void this.show();return}this.activeIndex=Math.min(navigable.length-1,this.activeIndex+1);break;case"ArrowUp":e.preventDefault();if(this.onlyOption)return this.selectOption(this.onlyOption);if(!this.open){void this.show();return}this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":case" ":if(this.open){e.preventDefault();const active=navigable[this.activeIndex];if(this.activeIndex>=0&&active){this.selectOption(active)}else{void this.hide()}}break;case"Escape":if(this.open){e.preventDefault();void 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":case"Delete":if(this.multiple&&this._selected.length>0){e.preventDefault();this.removeValue(this._selected[this._selected.length-1])}break;default:if(e.key.length===1&&!e.altKey&&!e.ctrlKey&&!e.metaKey){this.typeAhead(e.key)}break}};this.onListboxMouseDown=e=>{if(e.target.closest('[part="option"]'))e.preventDefault()};this.onListboxClick=e=>{const optionEl=e.target.closest('[part="option"]');const index=Number(optionEl?.dataset["index"]);if(!Number.isInteger(index))return;const option=this.options[index];if(option)this.selectOption(option)};installInvalidEventAlias(this,init=>this.emit("lr-invalid",void 0,init));this.internals=createInternalsSafely(this);this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);this.syncFormValue()}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}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"]')??null}connectedCallback(){super.connectedCallback();this.updateValidity();if(this.hasUpdated&&this.open)queueMicrotask(()=>this.reconnectOpenPopup())}willUpdate(changed){super.willUpdate(changed);this._isFirstUpdate=!this.hasUpdated;this.announceOpenTransition(changed)}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")}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);if(!this._multiple&&this._selected.length>1){this.setSelection(this._selected.slice(0,1),this._selectedOptions.slice(0,1))}else{this.syncFormValue()}this.requestUpdate("multiple",old)}get maxOptionsVisible(){return this._maxOptionsVisible}set maxOptionsVisible(next){const old=this._maxOptionsVisible;this._maxOptionsVisible=finiteCount(next,3);this.requestUpdate("maxOptionsVisible",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);if(this._disabled)void 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._restoredStateActive=false;this._valueDirty=true;const values=(Array.isArray(next)?next:next?[next]:[]).filter(value=>typeof value==="string");this.setSelection(values,values.map(value=>this.options.find(option=>option.value===value)))}get defaultValue(){return this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??""}set defaultValue(next){const old=this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??"";const values=(Array.isArray(next)?next:next?[next]:[]).filter(value=>typeof value==="string");this._defaultSelected=this.multiple?[...new Set(values)]:values.slice(0,1);this._defaultSelectedOptions=this.resolveOccurrences(this._defaultSelected);if(!this._valueDirty&&!this._restoredStateActive){this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}this.requestUpdate("defaultValue",old)}get selectedOptions(){return[...this._selectedOptions]}set selectedOptions(next){this._restoredStateActive=false;this._valueDirty=true;const candidates=Array.isArray(next)?next:[];const live=candidates.filter((option,index)=>option instanceof LyraOption&&this.contains(option)&&this.options.includes(option)&&candidates.indexOf(option)===index);const selected=this.multiple?live:live.slice(0,1);this.setSelection(selected.map(option=>option.value),selected)}setSelection(next,preferred=[]){const values=this.multiple?[...new Set(next)]:next.slice(0,1);const previousValues=this._selected;const previousOptions=this._selectedOptions;const old=this.multiple?[...previousValues]:previousValues[0]??"";this._selected=values;this._selectedOptions=this.resolveOccurrences(values,preferred);this.syncFormValue();this.reflectSelected();this.updateValidity();this.requestUpdate("value",old);const sameValues=previousValues.length===values.length&&previousValues.every((value,i)=>value===values[i]);const sameOptions=previousOptions.length===this._selectedOptions.length&&previousOptions.every((option,i)=>option===this._selectedOptions[i]);if(sameValues&&!sameOptions)this.requestUpdate()}resolveOccurrences(values,preferred=[]){const claimed=new Set;const resolved=[];values.forEach((value,index)=>{const hint=preferred[index];const match=hint&&hint.value===value&&this.options.includes(hint)&&!claimed.has(hint)?hint:this.options.find(option=>option.value===value&&!claimed.has(option));if(!match)return;claimed.add(match);resolved.push(match)});return resolved}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("selectValueMissing"))}else{this.validityController.setValidity({})}this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred:this.barredFromValidation});if(this._selected.length===0)this.internals.states?.add("blank");else this.internals.states?.delete("blank")}syncFormValue(){if(!this.multiple){this.internals.setFormValue(this._selected[0]??"");return}const state2=JSON.stringify(this._selected);if(!this.name){this.internals.setFormValue(null,state2);return}const data=new FormData;for(const value of this._selected)data.append(this.name,value);this.internals.setFormValue(data,state2)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formResetCallback(){this.touched=false;this.hasInteracted=false;this._restoredStateActive=false;this._valueDirty=false;const resetOptions=this._defaultSelectedOptions.length>0?this._defaultSelectedOptions:this.options.filter(option=>wasOptionInitiallySelected(option));if(this._defaultSelectedOptions.length===0&&resetOptions.length>0){this._defaultSelectedOptions=[...resetOptions];this._defaultSelected=resetOptions.map(option=>option.value)}const defaults=new Set(resetOptions);for(const option of this.options){option[RESET_OPTION_SELECTED_FROM_OWNER](defaults.has(option))}this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}formStateRestoreCallback(state2,reason){void reason;if(!this.multiple){this.value=typeof state2==="string"?state2:""}else{let restored=[];if(typeof state2==="string"){try{const parsed=JSON.parse(state2);if(Array.isArray(parsed)&&parsed.every(entry=>typeof entry==="string"))restored=parsed}catch{}}this.value=restored}this._restoredStateActive=true;this._valueDirty=true}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;if(disabled)void this.hide();this.updateValidity();this.requestUpdate()}checkValidity(){this.updateValidity();return this.internals.checkValidity()}reportValidity(){this.updateValidity();this.hasInteracted=true;this.reflectValidityStates();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.reflectValidityStates()}resetValidity(){this.setCustomValidity("")}disconnectedCallback(){this.transitionToken++;super.disconnectedCallback();this.cleanup?.();this.cleanup=void 0;this.clearTypeAheadTimer();this.typeAheadBuffer="";this.unbindDocumentPointer();this.resolveTransitionWaiters("lr-after-show");this.resolveTransitionWaiters("lr-after-hide");this.open=false}adoptedCallback(){this.cleanup?.();this.cleanup=void 0;this.unbindDocumentPointer();this.clearTypeAheadTimer()}refreshOptionDefaults(){if(this.hasAttribute("default-value"))return;const declared=this.options.filter(option=>option.defaultSelected);const defaults=this.multiple?declared:declared.slice(0,1);this._defaultSelected=defaults.map(option=>option.value);this._defaultSelectedOptions=[...defaults];if(!this._valueDirty&&!this._restoredStateActive){this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}}reflectSelected(){this._selectedOptions=this.resolveOccurrences(this._selected,this._selectedOptions);const chosen=new Set(this._selectedOptions);for(const option of this.options){option[SET_OPTION_SELECTED_FROM_OWNER](chosen.has(option))}}labelFor(value){return this._selectedOptions.find(option=>option.value===value)?.label??this.options.find(option=>option.value===value)?.label??value}get onlyOption(){if(!this.autoCommitSingleOption)return void 0;const navigable=this.navigableOptions();return navigable.length===1?navigable[0]:void 0}navigableOptions(options=this.options){return options.filter(o=>!o.disabled&&!o.inert&&!o.closest("[inert]"))}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;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="trigger"]');const listbox=this.renderRoot.querySelector('[part="listbox"]');if(anchor&&listbox){this.cleanup=place(anchor,listbox,{placement:rtlAwarePlacement(this.placement,this),strategy:this.hoist?"fixed":"absolute"})}}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="trigger"]');const listbox=this.renderRoot.querySelector('[part="listbox"]');if(anchor&&listbox){this.cleanup=place(anchor,listbox,{placement:rtlAwarePlacement(this.placement,this),strategy:this.hoist?"fixed":"absolute"})}}else if(!this.open){this.unbindDocumentPointer();if(!this._isFirstUpdate){void this.settleTransition("lr-after-hide")}}else{this.unbindDocumentPointer()}}if(changed.has("touched")||changed.has("required")||changed.has("value")){this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}}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(){dispatchNativeInputEvent(this);this.emit("lr-input",{value:this.value});dispatchNativeEvent(this,"change");this.emit("lr-change",{value:this.value})}selectOption(option){if(this.effectiveDisabled||option.disabled)return;this.hasInteracted=true;this._restoredStateActive=false;this._valueDirty=true;if(this.multiple){const selected=this._selected.includes(option.value);const occurrences=selected?this._selectedOptions.filter(candidate=>candidate.value!==option.value):[...this._selectedOptions,option];const values=selected?this._selected.filter(value=>value!==option.value):[...this._selected,option.value];this.setSelection(values,occurrences);this.emitValueEvents();return}const changed=option!==this._selectedOptions[0]||option.value!==this._selected[0];this.setSelection([option.value],[option]);void this.hide();if(changed)this.emitValueEvents()}removeValue(value){if(this.effectiveDisabled||!this._selected.includes(value))return;this._restoredStateActive=false;this._valueDirty=true;this.setSelection(this._selected.filter(candidate=>candidate!==value),this._selectedOptions.filter(option=>option.value!==value));this.emitValueEvents()}clear(){if(this.effectiveDisabled||this._selected.length===0)return;this._restoredStateActive=false;this._valueDirty=true;this.setSelection([],[]);this.emitValueEvents();this.emit("lr-clear")}removeTag(value,index,event){event.stopPropagation();this.removeValue(value);void this.updateComplete.then(()=>{const buttons=[...this.renderRoot.querySelectorAll('[part~="tag__remove-button"]')];(buttons[Math.min(index,buttons.length-1)]??this.triggerElement)?.focus()})}typeAhead(char){this.clearTypeAheadTimer();this.typeAheadBuffer+=char.toLocaleLowerCase(this.effectiveLocale);const ownerWindow=this.ownerDocument.defaultView;if(this.isConnected&&ownerWindow){const generation=this.typeAheadTimerGeneration;this.typeAheadTimerWindow=ownerWindow;this.typeAheadTimer=ownerWindow.setTimeout(()=>{if(this.typeAheadTimerGeneration!==generation||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow){return}this.typeAheadTimer=void 0;this.typeAheadTimerWindow=void 0;this.typeAheadBuffer=""},500)}const navigable=this.navigableOptions();if(!navigable.length)return;const currentOption=this.open?navigable[this.activeIndex]:this._selectedOptions[this._selectedOptions.length-1];const currentIndex=navigable.indexOf(currentOption);const n=navigable.length;for(let step=1;step<=n;step++){const idx=(currentIndex+step+n)%n;const candidate=navigable[idx];if(candidate===void 0)continue;if(candidate.label.toLocaleLowerCase(this.effectiveLocale).startsWith(this.typeAheadBuffer)){if(this.open){this.activeIndex=idx}else if(!(this.multiple&&this._selected.includes(candidate.value))){this.selectOption(candidate)}return}}}clearTypeAheadTimer(){this.typeAheadTimerGeneration+=1;if(this.typeAheadTimer!==void 0){this.typeAheadTimerWindow?.clearTimeout(this.typeAheadTimer)}this.typeAheadTimer=void 0;this.typeAheadTimerWindow=void 0}renderRows(options,activeId){const out=[];const chosen=new Set(this._selectedOptions);let currentGroup;options.forEach((o,i)=>{if(o.group!==currentGroup){currentGroup=o.group;if(currentGroup)out.push(html`<div class="group-label" part="group-label">${currentGroup}</div>`)}const id=`${this.listId}-opt-${i}`;const selected=chosen.has(o);out.push(html`<div
|
|
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{rtlAwarePlacement}from"../../../internal/rtl.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon,closeIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{finiteCount}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./select.styles.js";import{sizes}from"../../../internal/sizes.styles.js";import{LyraOption}from"../combobox/option.class.js";import"../combobox/option.class.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{omittedEmptyStringConverter}from"../../../internal/converters.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.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_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_select,LYRA_DEFAULT_selectSelectedOverflow,LYRA_DEFAULT_selectValueMissing}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 LyraSelect extends LyraElement{static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,select:LYRA_DEFAULT_select,selectSelectedOverflow:LYRA_DEFAULT_selectSelectedOverflow,selectValueMissing:LYRA_DEFAULT_selectValueMissing}}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},defaultValue:{attribute:"default-value",noAccessor:true}}}focus(options){if(!this.effectiveDisabled)this.triggerElement?.focus(options)}blur(){this.triggerElement?.blur()}click(){if(!this.effectiveDisabled)this.triggerElement?.click()}constructor(){super();this.placeholder="";this.label="";this.hint="";this.helpText="";this.withLabel=false;this.withHint=false;this.errorText="";this.autofocus=false;this.title="";this.open=false;this.size="m";this.appearance="outlined";this.pill=false;this.placement="bottom";this.hoist=false;this.filled=false;this.withClear=false;this.clearable=false;this.autoCommitSingleOption=false;this.activeIndex=-1;this.options=[];this.touched=false;this.hasInteracted=false;this.slotPresence=new SlotPresenceController(this);this._fieldsetDisabled=false;this.listId=nextId("select-list");this.triggerId=nextId("select-trigger");this._isFirstUpdate=true;this.openVetoed=false;this.transitionToken=0;this.transitionWaiters=new Map;this._selected=[];this._selectedOptions=[];this._multiple=false;this._disabled=false;this._required=false;this._defaultSelected=[];this._defaultSelectedOptions=[];this._defaultCaptured=false;this._valueDirty=false;this._restoredStateActive=false;this.typeAheadBuffer="";this.typeAheadTimerGeneration=0;this._name="";this._maxOptionsVisible=3;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 hasDefaultValue=this.hasAttribute("default-value");const allDefaults=this.options.filter(option=>option.defaultSelected);const defaults=this.multiple?allDefaults:allDefaults.slice(0,1);const allLive=this.options.filter(option=>option.selected);const live=this.multiple?allLive:allLive.slice(0,1);const initialLive=this.options.filter(option=>wasOptionInitiallySelected(option));const optionDirty=this.options.some(option=>isOptionSelectedDirty(option));const dirtySelected=this.options.filter(option=>isOptionSelectedDirty(option)&&option.selected);if(!hasDefaultValue){const resetOptions=defaults.length>0?defaults:initialLive.length>0?initialLive:live;this._defaultSelected=resetOptions.map(option=>option.value);this._defaultSelectedOptions=[...resetOptions]}else{this._defaultSelectedOptions=this.resolveOccurrences(this._defaultSelected)}const fromDefaults=hasDefaultValue||defaults.length>0;const initial=optionDirty?this.multiple?allLive:dirtySelected.slice(-1)[0]?dirtySelected.slice(-1):live:hasDefaultValue?this._defaultSelectedOptions:fromDefaults?defaults:live;if(initial.length>0&&!this._restoredStateActive&&!this._valueDirty){if(!fromDefaults||optionDirty)this._valueDirty=true;this.setSelection(initial.map(option=>option.value),[...initial]);return}if(optionDirty)this._valueDirty=true;if(hasDefaultValue&&!this._valueDirty&&!this._restoredStateActive){this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions]);return}}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>0){const added=this.multiple?eligible:eligible.slice(-1);const occurrences=this.multiple?[...new Set([...this._selectedOptions,...added])]:added;if(newLive.length>0)this._valueDirty=true;this.setSelection(occurrences.map(option=>option.value),occurrences);return}}this.reflectSelected()};this.onOptionChange=()=>{queueMicrotask(()=>{this.refreshOptionDefaults();this.reflectSelected();this.options=[...this.options]})};this.onDocPointer=e=>{if(!e.composedPath().includes(this))void this.hide()};this.onTriggerClick=()=>{if(this.effectiveDisabled)return;if(this.onlyOption)return this.selectOption(this.onlyOption);if(this.open)void this.hide();else void this.show()};this.onTriggerBlur=event=>{if(!this.effectiveDisabled){this.touched=true;this.hasInteracted=true;this.reflectValidityStates()}void this.hide();relayNativeEvent(this,event);this.emit("lr-blur")};this.onTriggerFocus=event=>{relayNativeEvent(this,event);this.emit("lr-focus")};this.onKeyDown=e=>{const navigable=this.navigableOptions();switch(e.key){case"ArrowDown":e.preventDefault();if(this.onlyOption)return this.selectOption(this.onlyOption);if(!this.open){void this.show();return}this.activeIndex=Math.min(navigable.length-1,this.activeIndex+1);break;case"ArrowUp":e.preventDefault();if(this.onlyOption)return this.selectOption(this.onlyOption);if(!this.open){void this.show();return}this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":case" ":if(this.open){e.preventDefault();const active=navigable[this.activeIndex];if(this.activeIndex>=0&&active){this.selectOption(active)}else{void this.hide()}}break;case"Escape":if(this.open){e.preventDefault();void 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":case"Delete":if(this.multiple&&this._selected.length>0){e.preventDefault();this.removeValue(this._selected[this._selected.length-1])}break;default:if(e.key.length===1&&!e.altKey&&!e.ctrlKey&&!e.metaKey){this.typeAhead(e.key)}break}};this.onListboxMouseDown=e=>{if(e.target.closest('[part="option"]'))e.preventDefault()};this.onListboxClick=e=>{const optionEl=e.target.closest('[part="option"]');const index=Number(optionEl?.dataset["index"]);if(!Number.isInteger(index))return;const option=this.options[index];if(option)this.selectOption(option)};installInvalidEventAlias(this,init=>this.emit("lr-invalid",void 0,init));this.internals=createInternalsSafely(this);this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);this.syncFormValue()}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}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"]')??null}connectedCallback(){super.connectedCallback();this.updateValidity();if(this.hasUpdated&&this.open)queueMicrotask(()=>this.reconnectOpenPopup())}willUpdate(changed){super.willUpdate(changed);this._isFirstUpdate=!this.hasUpdated;this.announceOpenTransition(changed)}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")}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);if(!this._multiple&&this._selected.length>1){this.setSelection(this._selected.slice(0,1),this._selectedOptions.slice(0,1))}else{this.syncFormValue()}this.requestUpdate("multiple",old)}get maxOptionsVisible(){return this._maxOptionsVisible}set maxOptionsVisible(next){const old=this._maxOptionsVisible;this._maxOptionsVisible=finiteCount(next,3);this.requestUpdate("maxOptionsVisible",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);if(this._disabled)void 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._restoredStateActive=false;this._valueDirty=true;const values=(Array.isArray(next)?next:next?[next]:[]).filter(value=>typeof value==="string");this.setSelection(values,values.map(value=>this.options.find(option=>option.value===value)))}get defaultValue(){return this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??""}set defaultValue(next){const old=this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??"";const values=(Array.isArray(next)?next:next?[next]:[]).filter(value=>typeof value==="string");this._defaultSelected=this.multiple?[...new Set(values)]:values.slice(0,1);this._defaultSelectedOptions=this.resolveOccurrences(this._defaultSelected);if(!this._valueDirty&&!this._restoredStateActive){this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}this.requestUpdate("defaultValue",old)}get selectedOptions(){return[...this._selectedOptions]}set selectedOptions(next){this._restoredStateActive=false;this._valueDirty=true;const candidates=Array.isArray(next)?next:[];const live=candidates.filter((option,index)=>option instanceof LyraOption&&this.contains(option)&&this.options.includes(option)&&candidates.indexOf(option)===index);const selected=this.multiple?live:live.slice(0,1);this.setSelection(selected.map(option=>option.value),selected)}setSelection(next,preferred=[]){const values=this.multiple?[...new Set(next)]:next.slice(0,1);const previousValues=this._selected;const previousOptions=this._selectedOptions;const old=this.multiple?[...previousValues]:previousValues[0]??"";this._selected=values;this._selectedOptions=this.resolveOccurrences(values,preferred);this.syncFormValue();this.reflectSelected();this.updateValidity();this.requestUpdate("value",old);const sameValues=previousValues.length===values.length&&previousValues.every((value,i)=>value===values[i]);const sameOptions=previousOptions.length===this._selectedOptions.length&&previousOptions.every((option,i)=>option===this._selectedOptions[i]);if(sameValues&&!sameOptions)this.requestUpdate()}resolveOccurrences(values,preferred=[]){const claimed=new Set;const resolved=[];values.forEach((value,index)=>{const hint=preferred[index];const match=hint&&hint.value===value&&this.options.includes(hint)&&!claimed.has(hint)?hint:this.options.find(option=>option.value===value&&!claimed.has(option));if(!match)return;claimed.add(match);resolved.push(match)});return resolved}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("selectValueMissing"))}else{this.validityController.setValidity({})}this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred:this.barredFromValidation});if(this._selected.length===0)this.internals.states?.add("blank");else this.internals.states?.delete("blank")}syncFormValue(){if(!this.multiple){this.internals.setFormValue(this._selected[0]??"");return}const state2=JSON.stringify(this._selected);if(!this.name){this.internals.setFormValue(null,state2);return}const data=new FormData;for(const value of this._selected)data.append(this.name,value);this.internals.setFormValue(data,state2)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formResetCallback(){this.touched=false;this.hasInteracted=false;this._restoredStateActive=false;this._valueDirty=false;const resetOptions=this._defaultSelectedOptions.length>0?this._defaultSelectedOptions:this.options.filter(option=>wasOptionInitiallySelected(option));if(this._defaultSelectedOptions.length===0&&resetOptions.length>0){this._defaultSelectedOptions=[...resetOptions];this._defaultSelected=resetOptions.map(option=>option.value)}const defaults=new Set(resetOptions);for(const option of this.options){option[RESET_OPTION_SELECTED_FROM_OWNER](defaults.has(option))}this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}formStateRestoreCallback(state2,reason){void reason;if(!this.multiple){this.value=typeof state2==="string"?state2:""}else{let restored=[];if(typeof state2==="string"){try{const parsed=JSON.parse(state2);if(Array.isArray(parsed)&&parsed.every(entry=>typeof entry==="string"))restored=parsed}catch{}}this.value=restored}this._restoredStateActive=true;this._valueDirty=true}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;if(disabled)void this.hide();this.updateValidity();this.requestUpdate()}checkValidity(){this.updateValidity();return this.internals.checkValidity()}reportValidity(){this.updateValidity();this.hasInteracted=true;this.reflectValidityStates();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.reflectValidityStates()}resetValidity(){this.setCustomValidity("")}disconnectedCallback(){this.transitionToken++;super.disconnectedCallback();this.cleanup?.();this.cleanup=void 0;this.clearTypeAheadTimer();this.typeAheadBuffer="";this.unbindDocumentPointer();this.resolveTransitionWaiters("lr-after-show");this.resolveTransitionWaiters("lr-after-hide");this.open=false}adoptedCallback(){this.cleanup?.();this.cleanup=void 0;this.unbindDocumentPointer();this.clearTypeAheadTimer()}refreshOptionDefaults(){if(this.hasAttribute("default-value"))return;const declared=this.options.filter(option=>option.defaultSelected);const defaults=this.multiple?declared:declared.slice(0,1);this._defaultSelected=defaults.map(option=>option.value);this._defaultSelectedOptions=[...defaults];if(!this._valueDirty&&!this._restoredStateActive){this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}}reflectSelected(){this._selectedOptions=this.resolveOccurrences(this._selected,this._selectedOptions);const chosen=new Set(this._selectedOptions);for(const option of this.options){option[SET_OPTION_SELECTED_FROM_OWNER](chosen.has(option))}}labelFor(value){return this._selectedOptions.find(option=>option.value===value)?.label??this.options.find(option=>option.value===value)?.label??value}get onlyOption(){if(!this.autoCommitSingleOption)return void 0;const navigable=this.navigableOptions();return navigable.length===1?navigable[0]:void 0}navigableOptions(options=this.options){return options.filter(o=>!o.disabled&&!o.inert&&!o.closest("[inert]"))}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;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="trigger"]');const listbox=this.renderRoot.querySelector('[part="listbox"]');if(anchor&&listbox){this.cleanup=place(anchor,listbox,{placement:rtlAwarePlacement(this.placement,this),strategy:this.hoist?"fixed":"absolute"})}}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="trigger"]');const listbox=this.renderRoot.querySelector('[part="listbox"]');if(anchor&&listbox){this.cleanup=place(anchor,listbox,{placement:rtlAwarePlacement(this.placement,this),strategy:this.hoist?"fixed":"absolute"})}}else if(!this.open){this.unbindDocumentPointer();if(!this._isFirstUpdate){void this.settleTransition("lr-after-hide")}}else{this.unbindDocumentPointer()}}if(changed.has("touched")||changed.has("required")||changed.has("value")){this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}}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(){dispatchNativeInputEvent(this);this.emit("lr-input",{value:this.value});dispatchNativeEvent(this,"change");this.emit("lr-change",{value:this.value})}selectOption(option){if(this.effectiveDisabled||option.disabled)return;this.hasInteracted=true;this._restoredStateActive=false;this._valueDirty=true;if(this.multiple){const selected=this._selected.includes(option.value);const occurrences=selected?this._selectedOptions.filter(candidate=>candidate.value!==option.value):[...this._selectedOptions,option];const values=selected?this._selected.filter(value=>value!==option.value):[...this._selected,option.value];this.setSelection(values,occurrences);this.emitValueEvents();return}const changed=option!==this._selectedOptions[0]||option.value!==this._selected[0];this.setSelection([option.value],[option]);void this.hide();if(changed)this.emitValueEvents()}removeValue(value){if(this.effectiveDisabled||!this._selected.includes(value))return;this._restoredStateActive=false;this._valueDirty=true;this.setSelection(this._selected.filter(candidate=>candidate!==value),this._selectedOptions.filter(option=>option.value!==value));this.emitValueEvents()}clear(){if(this.effectiveDisabled||this._selected.length===0)return;this._restoredStateActive=false;this._valueDirty=true;this.setSelection([],[]);this.emitValueEvents();this.emit("lr-clear")}removeTag(value,index,event){event.stopPropagation();this.removeValue(value);void this.updateComplete.then(()=>{const buttons=[...this.renderRoot.querySelectorAll('[part~="tag__remove-button"]')];(buttons[Math.min(index,buttons.length-1)]??this.triggerElement)?.focus()})}typeAhead(char){this.clearTypeAheadTimer();this.typeAheadBuffer+=char.toLocaleLowerCase(this.effectiveLocale);const ownerWindow=this.ownerDocument.defaultView;if(this.isConnected&&ownerWindow){const generation=this.typeAheadTimerGeneration;this.typeAheadTimerWindow=ownerWindow;this.typeAheadTimer=ownerWindow.setTimeout(()=>{if(this.typeAheadTimerGeneration!==generation||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow){return}this.typeAheadTimer=void 0;this.typeAheadTimerWindow=void 0;this.typeAheadBuffer=""},500)}const navigable=this.navigableOptions();if(!navigable.length)return;const currentOption=this.open?navigable[this.activeIndex]:this._selectedOptions[this._selectedOptions.length-1];const currentIndex=navigable.indexOf(currentOption);const n=navigable.length;for(let step=1;step<=n;step++){const idx=(currentIndex+step+n)%n;const candidate=navigable[idx];if(candidate===void 0)continue;if(candidate.label.toLocaleLowerCase(this.effectiveLocale).startsWith(this.typeAheadBuffer)){if(this.open){this.activeIndex=idx}else if(!(this.multiple&&this._selected.includes(candidate.value))){this.selectOption(candidate)}return}}}clearTypeAheadTimer(){this.typeAheadTimerGeneration+=1;if(this.typeAheadTimer!==void 0){this.typeAheadTimerWindow?.clearTimeout(this.typeAheadTimer)}this.typeAheadTimer=void 0;this.typeAheadTimerWindow=void 0}renderRows(options,activeId){const out=[];const chosen=new Set(this._selectedOptions);let currentGroup;options.forEach((o,i)=>{if(o.group!==currentGroup){currentGroup=o.group;if(currentGroup)out.push(html`<div class="group-label" part="group-label">${currentGroup}</div>`)}const id=`${this.listId}-opt-${i}`;const selected=chosen.has(o);out.push(html`<div
|
|
2
2
|
part="option"
|
|
3
3
|
id=${id}
|
|
4
4
|
role="option"
|
|
@@ -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}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./switch.styles.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{omittedEmptyStringConverter}from"../../../internal/converters.js";import{hasRealContent}from"../../../internal/a11y.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_restore,LYRA_DEFAULT_switchRequired}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 LyraSwitch extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore,switchRequired:LYRA_DEFAULT_switchRequired}}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.formAssociated=true}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},checked:{attribute:false,noAccessor:true},defaultChecked:{attribute:"checked",type:Boolean,reflect:true,useDefault:true,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},name:{reflect:true,noAccessor:true,converter:omittedEmptyStringConverter},required:{type:Boolean,reflect:true,noAccessor:true},size:{reflect:true},value:{reflect:true,noAccessor:true}}}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get checked(){return this._checked}set checked(next){const old=this._checked;if(!this.settingDefaultChecked)this._checkedDirty=true;this._checked=Boolean(next);this.syncFormState();this.requestUpdate("checked",old)}get defaultChecked(){return this._defaultChecked}set defaultChecked(next){if(this.reflectingDefaultChecked)return;const old=this._defaultChecked;this._defaultChecked=Boolean(next);this.reflectingDefaultChecked=true;try{this.toggleAttribute("checked",this._defaultChecked)}finally{this.reflectingDefaultChecked=false}if(!this._checkedDirty)this.restoreCheckedFromDefault();this.requestUpdate("defaultChecked",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);this.updateValidity();this.requestUpdate("disabled",old)}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.requestUpdate("name",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._value}set value(next){const old=this._value;this._value=next??"on";if(next==null){if(this.hasAttribute("value"))this.removeAttribute("value")}else if(this.getAttribute("value")!==this._value){this.setAttribute("value",this._value)}this.syncFormState();this.requestUpdate("value",old,{reflect:false})}constructor(){super();this.size="m";this.hint="";this.helpText="";this.withHint=false;this.shoelaceDefaultChecked=false;this.errorText="";this.hasLabelSlot=false;this.hasHintSlot=false;this.hasHelpTextSlot=false;this.hasErrorSlot=false;this.touched=false;this.hasInteracted=false;this._defaultChecked=false;this._checkedDirty=false;this.settingDefaultChecked=false;this.reflectingDefaultChecked=false;this.hadShoelaceDefaultChecked=false;this._fieldsetDisabled=false;this._name="";this._checked=false;this._disabled=false;this._required=false;this._value="on";this.onClick=()=>{this.setFromUser(!this.checked)};this.onBlur=event=>{this.touched=true;this.hasInteracted=true;this.reflectValidityStates();relayNativeEvent(this,event);this.emit("lr-blur")};this.onFocus=event=>{relayNativeEvent(this,event);this.emit("lr-focus")};this.onKeyDown=e=>{if(this.effectiveDisabled)return;if(e.key===" "||e.key==="Spacebar"){e.preventDefault();this.setFromUser(!this.checked);return}if(e.key==="ArrowLeft"||e.key==="ArrowRight"){e.preventDefault();const turnsOn=this.effectiveDirection==="rtl"?e.key==="ArrowLeft":e.key==="ArrowRight";this.setFromUser(turnsOn)}};this.onLabelSlotChange=event=>this.handleLabelSlotChange(event);this.onSlotChange=event=>this.handleLabelSlotChange(event);this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:true}).length>0};this.onHelpTextSlotChange=e=>{this.hasHelpTextSlot=e.target.assignedElements({flatten:true}).length>0};this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:true}).length>0};installInvalidEventAlias(this,init=>this.emit("lr-invalid",void 0,init));this.internals=createInternalsSafely(this);this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);this.syncFormState()}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}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part~="base"]')??null}click(){if(!this.effectiveDisabled)this[VALIDITY_ANCHOR]()?.click()}focus(options){if(!this.effectiveDisabled)this[VALIDITY_ANCHOR]()?.focus(options)}blur(){this[VALIDITY_ANCHOR]()?.blur()}connectedCallback(){super.connectedCallback();this.updateValidity();const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;this.labelObserver=MutationObserverCtor?new MutationObserverCtor(()=>{this.bindLabelObserverTargets();this.recomputeHasLabelSlot()}):void 0;this.addEventListener("slotchange",this.onLabelSlotChange);this.bindLabelObserverTargets();if(this.hasUpdated){this.recomputeLightDomSlotState()}else{this.seedFirstRenderState(()=>this.recomputeLightDomSlotState())}}disconnectedCallback(){this.removeEventListener("slotchange",this.onLabelSlotChange);this.labelObserver?.disconnect();this.labelObserver=void 0;super.disconnectedCallback()}willUpdate(changed){super.willUpdate(changed);if(changed.has("shoelaceDefaultChecked")&&(this.hasAttribute("default-checked")||this.hadShoelaceDefaultChecked)){this.defaultChecked=this.shoelaceDefaultChecked;this.hadShoelaceDefaultChecked=this.hasAttribute("default-checked")}}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({})}else if(this.required&&!this.checked){this.validityController.setValidity({valueMissing:true},this.localize("switchRequired"))}else{this.validityController.setValidity({})}this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred:this.barredFromValidation});setCustomState(this.internals,"checked",this.checked);setCustomState(this.internals,"disabled",this.effectiveDisabled)}syncFormState(){this.internals.setFormValue(this.checked?this.value:null,this.checked?"checked":"unchecked");this.updateValidity()}formResetCallback(){this.touched=false;this.hasInteracted=false;this.restoreCheckedFromDefault();this.reflectValidityStates()}formStateRestoreCallback(state2,reason){void reason;this.checked=state2==="checked"}restoreCheckedFromDefault(){this.settingDefaultChecked=true;try{this.checked=this._defaultChecked}finally{this.settingDefaultChecked=false}this._checkedDirty=false}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;this.updateValidity();this.requestUpdate()}checkValidity(){return this.internals.checkValidity()}reportValidity(){this.hasInteracted=true;this.reflectValidityStates();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.reflectValidityStates();this.requestUpdate()}resetValidity(){this.setCustomValidity("")}setFromUser(next){if(this.effectiveDisabled)return;if(this.checked===next)return;this.hasInteracted=true;this.checked=next;dispatchNativeInputEvent(this);this.emit("lr-input",{checked:this.checked});dispatchNativeEvent(this,"change");this.emit("lr-change",{checked:this.checked})}isDefaultLabelNode(node){if(node.nodeType!==1)return true;const slotName=node.getAttribute("slot");return slotName===null||slotName===""}labelForwardingSlots(){return Array.from(this.querySelectorAll("slot")).filter(slot=>{let top=slot;while(top.parentNode&&top.parentNode!==this)top=top.parentNode;return top.parentNode===this&&this.isDefaultLabelNode(top)})}observeLabelNode(node){if(!this.labelObserver)return;if(node.nodeType===3){this.labelObserver.observe(node,{characterData:true});return}if(node.nodeType!==1)return;this.labelObserver.observe(node,{attributes:true,attributeFilter:["aria-hidden","aria-label","class","hidden","inert","slot","style"],childList:true,characterData:true,subtree:true})}bindLabelObserverTargets(){if(!this.labelObserver)return;this.labelObserver.disconnect();this.observeLabelNode(this);for(const slot of this.labelForwardingSlots()){if(slot.assignedNodes().length===0)continue;for(const assigned of slot.assignedNodes({flatten:true}))this.observeLabelNode(assigned)}}recomputeHasLabelSlot(){const renderRoot=this.renderRoot;const childNodes=this.childNodes;if(!renderRoot||!childNodes)return;const slot=renderRoot.querySelector("slot:not([name])");const nodes=slot?slot.assignedNodes({flatten:true}):Array.from(childNodes).filter(node=>this.isDefaultLabelNode(node)).flatMap(node=>{if(node.nodeType!==1||node.localName!=="slot")return[node];const forwardingSlot=node;return forwardingSlot.assignedNodes().length>0?forwardingSlot.assignedNodes({flatten:true}):Array.from(forwardingSlot.childNodes)});this.hasLabelSlot=hasRealContent(nodes)}recomputeLightDomSlotState(){this.recomputeHasLabelSlot();const children=this.children;if(!children)return;this.hasHintSlot=Array.from(children).some(element=>element.getAttribute("slot")==="hint");this.hasHelpTextSlot=Array.from(children).some(element=>element.getAttribute("slot")==="help-text");this.hasErrorSlot=Array.from(children).some(element=>element.getAttribute("slot")==="error")}handleLabelSlotChange(event){const target=event.target;if(target?.nodeType!==1||target.localName!=="slot")return;if(target.getRootNode()!==this.renderRoot&&!this.labelForwardingSlots().includes(target))return;this.bindLabelObserverTargets();this.recomputeHasLabelSlot()}render(){const hasHint=this.withHint||this.hasHintSlot||this.hasHelpTextSlot||this.hint.length>0||this.helpText.length>0;const hasError=this.hasErrorSlot||this.errorText.length>0;const describedBy=[hasError?"switch-error":"",hasHint?"switch-hint":""].filter(Boolean).join(" ");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}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./switch.styles.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{omittedEmptyStringConverter}from"../../../internal/converters.js";import{hasRealContent}from"../../../internal/a11y.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_restore,LYRA_DEFAULT_switchRequired}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 LyraSwitch extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore,switchRequired:LYRA_DEFAULT_switchRequired}}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.formAssociated=true}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},checked:{attribute:false,noAccessor:true},defaultChecked:{attribute:"checked",type:Boolean,reflect:true,useDefault:true,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},name:{reflect:true,noAccessor:true,converter:omittedEmptyStringConverter},required:{type:Boolean,reflect:true,noAccessor:true},size:{reflect:true},value:{reflect:true,noAccessor:true}}}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get checked(){return this._checked}set checked(next){const old=this._checked;if(!this.settingDefaultChecked)this._checkedDirty=true;this._checked=Boolean(next);this.syncFormState();this.requestUpdate("checked",old)}get defaultChecked(){return this._defaultChecked}set defaultChecked(next){if(this.reflectingDefaultChecked)return;const old=this._defaultChecked;this._defaultChecked=Boolean(next);this.reflectingDefaultChecked=true;try{this.toggleAttribute("checked",this._defaultChecked)}finally{this.reflectingDefaultChecked=false}if(!this._checkedDirty)this.restoreCheckedFromDefault();this.requestUpdate("defaultChecked",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);this.updateValidity();this.requestUpdate("disabled",old)}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.requestUpdate("name",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._value}set value(next){const old=this._value;this._value=next??"on";if(next==null){if(this.hasAttribute("value"))this.removeAttribute("value")}else if(this.getAttribute("value")!==this._value){this.setAttribute("value",this._value)}this.syncFormState();this.requestUpdate("value",old,{reflect:false})}constructor(){super();this.size="m";this.hint="";this.helpText="";this.withHint=false;this.shoelaceDefaultChecked=false;this.errorText="";this.hasLabelSlot=false;this.hasHintSlot=false;this.hasHelpTextSlot=false;this.hasErrorSlot=false;this.touched=false;this.hasInteracted=false;this._defaultChecked=false;this._checkedDirty=false;this.settingDefaultChecked=false;this.reflectingDefaultChecked=false;this.hadShoelaceDefaultChecked=false;this._fieldsetDisabled=false;this._name="";this._checked=false;this._disabled=false;this._required=false;this._value="on";this.onClick=()=>{this.setFromUser(!this.checked)};this.onBlur=event=>{if(!this.effectiveDisabled)this.touched=true;this.hasInteracted=true;this.reflectValidityStates();relayNativeEvent(this,event);this.emit("lr-blur")};this.onFocus=event=>{relayNativeEvent(this,event);this.emit("lr-focus")};this.onKeyDown=e=>{if(this.effectiveDisabled)return;if(e.key===" "||e.key==="Spacebar"){e.preventDefault();this.setFromUser(!this.checked);return}if(e.key==="ArrowLeft"||e.key==="ArrowRight"){e.preventDefault();const turnsOn=this.effectiveDirection==="rtl"?e.key==="ArrowLeft":e.key==="ArrowRight";this.setFromUser(turnsOn)}};this.onLabelSlotChange=event=>this.handleLabelSlotChange(event);this.onSlotChange=event=>this.handleLabelSlotChange(event);this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:true}).length>0};this.onHelpTextSlotChange=e=>{this.hasHelpTextSlot=e.target.assignedElements({flatten:true}).length>0};this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:true}).length>0};installInvalidEventAlias(this,init=>this.emit("lr-invalid",void 0,init));this.internals=createInternalsSafely(this);this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);this.syncFormState()}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}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part~="base"]')??null}click(){if(!this.effectiveDisabled)this[VALIDITY_ANCHOR]()?.click()}focus(options){if(!this.effectiveDisabled)this[VALIDITY_ANCHOR]()?.focus(options)}blur(){this[VALIDITY_ANCHOR]()?.blur()}connectedCallback(){super.connectedCallback();this.updateValidity();const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;this.labelObserver=MutationObserverCtor?new MutationObserverCtor(()=>{this.bindLabelObserverTargets();this.recomputeHasLabelSlot()}):void 0;this.addEventListener("slotchange",this.onLabelSlotChange);this.bindLabelObserverTargets();if(this.hasUpdated){this.recomputeLightDomSlotState()}else{this.seedFirstRenderState(()=>this.recomputeLightDomSlotState())}}disconnectedCallback(){this.removeEventListener("slotchange",this.onLabelSlotChange);this.labelObserver?.disconnect();this.labelObserver=void 0;super.disconnectedCallback()}willUpdate(changed){super.willUpdate(changed);if(changed.has("shoelaceDefaultChecked")&&(this.hasAttribute("default-checked")||this.hadShoelaceDefaultChecked)){this.defaultChecked=this.shoelaceDefaultChecked;this.hadShoelaceDefaultChecked=this.hasAttribute("default-checked")}}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({})}else if(this.required&&!this.checked){this.validityController.setValidity({valueMissing:true},this.localize("switchRequired"))}else{this.validityController.setValidity({})}this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred:this.barredFromValidation});setCustomState(this.internals,"checked",this.checked);setCustomState(this.internals,"disabled",this.effectiveDisabled)}syncFormState(){this.internals.setFormValue(this.checked?this.value:null,this.checked?"checked":"unchecked");this.updateValidity()}formResetCallback(){this.touched=false;this.hasInteracted=false;this.restoreCheckedFromDefault();this.reflectValidityStates()}formStateRestoreCallback(state2,reason){void reason;this.checked=state2==="checked"}restoreCheckedFromDefault(){this.settingDefaultChecked=true;try{this.checked=this._defaultChecked}finally{this.settingDefaultChecked=false}this._checkedDirty=false}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;this.updateValidity();this.requestUpdate()}checkValidity(){return this.internals.checkValidity()}reportValidity(){this.hasInteracted=true;this.reflectValidityStates();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.reflectValidityStates();this.requestUpdate()}resetValidity(){this.setCustomValidity("")}setFromUser(next){if(this.effectiveDisabled)return;if(this.checked===next)return;this.hasInteracted=true;this.checked=next;dispatchNativeInputEvent(this);this.emit("lr-input",{checked:this.checked});dispatchNativeEvent(this,"change");this.emit("lr-change",{checked:this.checked})}isDefaultLabelNode(node){if(node.nodeType!==1)return true;const slotName=node.getAttribute("slot");return slotName===null||slotName===""}labelForwardingSlots(){return Array.from(this.querySelectorAll("slot")).filter(slot=>{let top=slot;while(top.parentNode&&top.parentNode!==this)top=top.parentNode;return top.parentNode===this&&this.isDefaultLabelNode(top)})}observeLabelNode(node){if(!this.labelObserver)return;if(node.nodeType===3){this.labelObserver.observe(node,{characterData:true});return}if(node.nodeType!==1)return;this.labelObserver.observe(node,{attributes:true,attributeFilter:["aria-hidden","aria-label","class","hidden","inert","slot","style"],childList:true,characterData:true,subtree:true})}bindLabelObserverTargets(){if(!this.labelObserver)return;this.labelObserver.disconnect();this.observeLabelNode(this);for(const slot of this.labelForwardingSlots()){if(slot.assignedNodes().length===0)continue;for(const assigned of slot.assignedNodes({flatten:true}))this.observeLabelNode(assigned)}}recomputeHasLabelSlot(){const renderRoot=this.renderRoot;const childNodes=this.childNodes;if(!renderRoot||!childNodes)return;const slot=renderRoot.querySelector("slot:not([name])");const nodes=slot?slot.assignedNodes({flatten:true}):Array.from(childNodes).filter(node=>this.isDefaultLabelNode(node)).flatMap(node=>{if(node.nodeType!==1||node.localName!=="slot")return[node];const forwardingSlot=node;return forwardingSlot.assignedNodes().length>0?forwardingSlot.assignedNodes({flatten:true}):Array.from(forwardingSlot.childNodes)});this.hasLabelSlot=hasRealContent(nodes)}recomputeLightDomSlotState(){this.recomputeHasLabelSlot();const children=this.children;if(!children)return;this.hasHintSlot=Array.from(children).some(element=>element.getAttribute("slot")==="hint");this.hasHelpTextSlot=Array.from(children).some(element=>element.getAttribute("slot")==="help-text");this.hasErrorSlot=Array.from(children).some(element=>element.getAttribute("slot")==="error")}handleLabelSlotChange(event){const target=event.target;if(target?.nodeType!==1||target.localName!=="slot")return;if(target.getRootNode()!==this.renderRoot&&!this.labelForwardingSlots().includes(target))return;this.bindLabelObserverTargets();this.recomputeHasLabelSlot()}render(){const hasHint=this.withHint||this.hasHintSlot||this.hasHelpTextSlot||this.hint.length>0||this.helpText.length>0;const hasError=this.hasErrorSlot||this.errorText.length>0;const describedBy=[hasError?"switch-error":"",hasHint?"switch-hint":""].filter(Boolean).join(" ");return html`
|
|
2
2
|
<div part="form-control">
|
|
3
3
|
<span
|
|
4
4
|
part="base switch wrapper"
|
|
@@ -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{acquireAnnouncementSink}from"../../../internal/announcer.js";import{isAccessibilityVisible}from"../../../internal/accessibility-visibility.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{styles}from"./textarea.styles.js";import{sizes}from"../../../internal/sizes.styles.js";import{autocorrectConverter,normalizeAutocorrect,spellcheckConverter}from"../../../internal/converters.js";import{sanitizeCssResize}from"../../../internal/safe-css.js";import{finiteCount,finiteNumber}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_restore,LYRA_DEFAULT_select,LYRA_DEFAULT_textareaCharacterCount,LYRA_DEFAULT_textareaCharactersRemaining,LYRA_DEFAULT_textareaLabel,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";const COUNT_ANNOUNCE_DELAY_MS=1e3;class LyraTextareaBase extends LyraElement{}class LyraTextarea extends FormAssociated(LyraTextareaBase){static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore,select:LYRA_DEFAULT_select,textareaCharacterCount:LYRA_DEFAULT_textareaCharacterCount,textareaCharactersRemaining:LYRA_DEFAULT_textareaCharactersRemaining,textareaLabel:LYRA_DEFAULT_textareaLabel,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.styles=[LyraElement.styles,sizes,styles]}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=normalizeAutocorrect(next);this.requestUpdate()}get inputmode(){return this.inputMode}set inputmode(next){this.inputMode=next??""}get enterkeyhint(){return this.enterKeyHint}set enterkeyhint(next){this.enterKeyHint=next??""}get defaultValueAlias(){return this.defaultValue}set defaultValueAlias(next){this.defaultValue=next??""}constructor(){super();this.rows=4;this.resize="vertical";this.size="m";this.appearance="outlined";this.filled=false;this.pill=false;this.withCount=false;this.placeholder="";this.readonly=false;this.label="";this.hint="";this.helpText="";this.withLabel=false;this.withHint=false;this.errorText="";this.accessibleLabel=null;this.spellcheck=true;this.autofocus=false;this.title="";this.autocapitalize="";this.autocorrectValue=true;this.wrap="soft";this.autocomplete="";this.inputMode="";this.enterKeyHint="";this.touched=false;this.announcedCountText="";this.slotPresence=new SlotPresenceController(this);this.onInput=event=>{if(!this.textareaEl)return;this.value=this.textareaEl.value;if(this.resize==="auto")this.fitToContent();this.scheduleCountAnnouncement();relayNativeEvent(this,event);this.emit("lr-input",{value:this.value})};this.onChange=event=>{if(!this.textareaEl)return;this.value=this.textareaEl.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.addEventListener("invalid",()=>{this.touched=true})}get input(){return this.textareaEl??null}get selectionStart(){return this.textareaEl?.selectionStart??null}set selectionStart(value){if(this.textareaEl)this.textareaEl.selectionStart=value??0}get selectionEnd(){return this.textareaEl?.selectionEnd??null}set selectionEnd(value){if(this.textareaEl)this.textareaEl.selectionEnd=value??0}get selectionDirection(){return this.textareaEl?.selectionDirection}set selectionDirection(value){if(this.textareaEl)this.textareaEl.selectionDirection=value??"none"}click(){if(!this.effectiveDisabled)this.textareaEl?.click()}focus(options){if(!this.effectiveDisabled)this.textareaEl?.focus(options)}blur(){this.textareaEl?.blur()}select(){this.textareaEl?.select()}setSelectionRange(selectionStart,selectionEnd,selectionDirection="none"){this.textareaEl?.setSelectionRange(selectionStart,selectionEnd,selectionDirection)}scrollPosition(position){const ta=this.textareaEl;if(!ta)return void 0;if(position){if(position.top!==void 0)ta.scrollTop=finiteNumber(position.top,ta.scrollTop);if(position.left!==void 0)ta.scrollLeft=finiteNumber(position.left,ta.scrollLeft);return void 0}return{top:ta.scrollTop,left:ta.scrollLeft}}setRangeText(replacement,start,end,selectMode="preserve"){const ta=this.textareaEl;if(!ta)return;if(start===void 0||end===void 0){ta.setRangeText(replacement)}else{ta.setRangeText(replacement,start,end,selectMode)}this.value=ta.value;this.fitToContent()}connectedCallback(){super.connectedCallback();this.countAnnouncementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this});if(this.resize==="auto"&&this.hasUpdated){this.armResizeObserver();this.fitToContent()}}disconnectedCallback(){this.resizeObserver?.disconnect();this.resizeObserver=void 0;if(this.resizeRaf!==void 0)this.resizeRafOwner?.cancelAnimationFrame(this.resizeRaf);this.resizeRaf=void 0;this.resizeRafOwner=void 0;if(this.countAnnounceTimer!==void 0){this.countAnnounceTimerOwner?.clearTimeout(this.countAnnounceTimer)}this.countAnnounceTimer=void 0;this.countAnnounceTimerOwner=void 0;this.countAnnouncementSink?.release();this.countAnnouncementSink=void 0;super.disconnectedCallback()}countMaxlength(){const declared=this.maxlength;if(declared===void 0||!Number.isFinite(declared))return void 0;return finiteCount(declared,0)}countText(){const format=getNumberFormat(this.effectiveLocale);const max=this.countMaxlength();if(max!==void 0){const remaining=Math.max(0,max-this.value.length);return this.localize("textareaCharactersRemaining",void 0,{count:format.format(remaining),pluralCount:remaining})}const length=this.value.length;return this.localize("textareaCharacterCount",void 0,{count:format.format(length),pluralCount:length})}scheduleCountAnnouncement(){if(this.countAnnounceTimer!==void 0){this.countAnnounceTimerOwner?.clearTimeout(this.countAnnounceTimer)}this.countAnnounceTimer=void 0;this.countAnnounceTimerOwner=void 0;if(!this.withCount)return;const view=this.ownerDocument.defaultView;if(!view)return;this.countAnnounceTimerOwner=view;this.countAnnounceTimer=view.setTimeout(()=>{this.countAnnounceTimer=void 0;this.countAnnounceTimerOwner=void 0;if(!this.isConnected||this.ownerDocument.defaultView!==view||!this.withCount)return;if(!isAccessibilityVisible(this))return;const text=this.countText();this.announcedCountText=text;this.countAnnouncementSink?.announce(text)},COUNT_ANNOUNCE_DELAY_MS)}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}if(this.required&&this.value===""){this[SET_ANCHORED_VALIDITY]({valueMissing:true},this.localize("fieldRequired"));return}const native=this.textareaEl;if(native&&native.value!==this.value)native.value=this.value;const own=lengthViolations(this.value,this.minlength,this.maxlength);const tooShort=Boolean(native?.validity.tooShort)||own.tooShort;const tooLong=Boolean(native?.validity.tooLong)||own.tooLong;if(!tooShort&&!tooLong){this[SET_ANCHORED_VALIDITY]({});return}this[SET_ANCHORED_VALIDITY]({tooShort,tooLong},native?.validationMessage||this.localize("valueInvalid"))}updated(changed){super.updated(changed);if(changed.has("value")){if(this.value==="")this.internals.states.add("blank");else this.internals.states.delete("blank")}if(changed.has("minlength")||changed.has("maxlength")||changed.has("readonly")){this.updateValidity()}if(changed.has("resize")){if(this.resize==="auto"){this.armResizeObserver()}else if(changed.get("resize")==="auto"){this.resizeObserver?.disconnect();this.resizeObserver=void 0;if(this.resizeRaf!==void 0)this.resizeRafOwner?.cancelAnimationFrame(this.resizeRaf);this.resizeRaf=void 0;this.resizeRafOwner=void 0;if(this.textareaEl){this.textareaEl.style.blockSize="";this.textareaEl.style.overflowY=""}}}if(this.resize==="auto"){this.armResizeObserver();if(changed.has("value")||changed.has("rows")||changed.has("resize"))this.fitToContent()}}formResetCallback(){super.formResetCallback();this.touched=false}armResizeObserver(){const textarea=this.textareaEl;if(this.resizeObserver||!textarea)return;const view=this.ownerDocument.defaultView;const ResizeObserverCtor=view?.ResizeObserver;if(!view||!ResizeObserverCtor)return;this.lastObservedWidth=textarea.getBoundingClientRect().width;this.resizeObserver=new ResizeObserverCtor(entries=>{if(!this.isConnected||this.ownerDocument.defaultView!==view)return;const width=entries[0]?.contentRect.width;if(width===void 0||this.lastObservedWidth!==void 0&&Math.abs(width-this.lastObservedWidth)<.5){return}this.lastObservedWidth=width;if(this.resizeRaf!==void 0)this.resizeRafOwner?.cancelAnimationFrame(this.resizeRaf);this.resizeRafOwner=view;this.resizeRaf=view.requestAnimationFrame(()=>{this.resizeRaf=void 0;this.resizeRafOwner=void 0;if(!this.isConnected||this.ownerDocument.defaultView!==view)return;this.fitToContent()})});this.resizeObserver.observe(textarea)}fitToContent(){const ta=this.textareaEl;if(!ta||this.resize!=="auto")return;ta.style.blockSize="auto";const computed=ta.ownerDocument.defaultView?.getComputedStyle(ta);if(!computed)return;const borderBlock=parseFloat(computed.borderBlockStartWidth)+parseFloat(computed.borderBlockEndWidth);const parsedMax=parseFloat(computed.maxBlockSize);const maxBlockSize=Number.isFinite(parsedMax)?parsedMax:Number.POSITIVE_INFINITY;const contentBlockSize=ta.scrollHeight+borderBlock;ta.style.blockSize=`${Math.min(contentBlockSize,maxBlockSize)}px`;ta.style.overflowY=contentBlockSize>maxBlockSize?"auto":"hidden"}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?"textarea-error":"",hasHint?"textarea-hint":""].filter(Boolean).join(" ");const cssResize=this.resize==="auto"?"none":sanitizeCssResize(this.resize,"vertical");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{styleMap}from"lit/directives/style-map.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{isAccessibilityVisible}from"../../../internal/accessibility-visibility.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{styles}from"./textarea.styles.js";import{sizes}from"../../../internal/sizes.styles.js";import{autocorrectConverter,normalizeAutocorrect,spellcheckConverter}from"../../../internal/converters.js";import{sanitizeCssResize}from"../../../internal/safe-css.js";import{finiteCount,finiteNumber}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_restore,LYRA_DEFAULT_select,LYRA_DEFAULT_textareaCharacterCount,LYRA_DEFAULT_textareaCharactersRemaining,LYRA_DEFAULT_textareaLabel,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";const COUNT_ANNOUNCE_DELAY_MS=1e3;class LyraTextareaBase extends LyraElement{}class LyraTextarea extends FormAssociated(LyraTextareaBase){static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore,select:LYRA_DEFAULT_select,textareaCharacterCount:LYRA_DEFAULT_textareaCharacterCount,textareaCharactersRemaining:LYRA_DEFAULT_textareaCharactersRemaining,textareaLabel:LYRA_DEFAULT_textareaLabel,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.styles=[LyraElement.styles,sizes,styles]}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=normalizeAutocorrect(next);this.requestUpdate()}get inputmode(){return this.inputMode}set inputmode(next){this.inputMode=next??""}get enterkeyhint(){return this.enterKeyHint}set enterkeyhint(next){this.enterKeyHint=next??""}get defaultValueAlias(){return this.defaultValue}set defaultValueAlias(next){this.defaultValue=next??""}constructor(){super();this.rows=4;this.resize="vertical";this.size="m";this.appearance="outlined";this.filled=false;this.pill=false;this.withCount=false;this.placeholder="";this.readonly=false;this.label="";this.hint="";this.helpText="";this.withLabel=false;this.withHint=false;this.errorText="";this.accessibleLabel=null;this.spellcheck=true;this.autofocus=false;this.title="";this.autocapitalize="";this.autocorrectValue=true;this.wrap="soft";this.autocomplete="";this.inputMode="";this.enterKeyHint="";this.touched=false;this.announcedCountText="";this.slotPresence=new SlotPresenceController(this);this.onInput=event=>{if(!this.textareaEl)return;this.value=this.textareaEl.value;if(this.resize==="auto")this.fitToContent();this.scheduleCountAnnouncement();relayNativeEvent(this,event);this.emit("lr-input",{value:this.value})};this.onChange=event=>{if(!this.textareaEl)return;this.value=this.textareaEl.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.addEventListener("invalid",()=>{this.touched=true})}get input(){return this.textareaEl??null}get selectionStart(){return this.textareaEl?.selectionStart??null}set selectionStart(value){if(this.textareaEl)this.textareaEl.selectionStart=value??0}get selectionEnd(){return this.textareaEl?.selectionEnd??null}set selectionEnd(value){if(this.textareaEl)this.textareaEl.selectionEnd=value??0}get selectionDirection(){return this.textareaEl?.selectionDirection}set selectionDirection(value){if(this.textareaEl)this.textareaEl.selectionDirection=value??"none"}click(){if(!this.effectiveDisabled)this.textareaEl?.click()}focus(options){if(!this.effectiveDisabled)this.textareaEl?.focus(options)}blur(){this.textareaEl?.blur()}select(){this.textareaEl?.select()}setSelectionRange(selectionStart,selectionEnd,selectionDirection="none"){this.textareaEl?.setSelectionRange(selectionStart,selectionEnd,selectionDirection)}scrollPosition(position){const ta=this.textareaEl;if(!ta)return void 0;if(position){if(position.top!==void 0)ta.scrollTop=finiteNumber(position.top,ta.scrollTop);if(position.left!==void 0)ta.scrollLeft=finiteNumber(position.left,ta.scrollLeft);return void 0}return{top:ta.scrollTop,left:ta.scrollLeft}}setRangeText(replacement,start,end,selectMode="preserve"){const ta=this.textareaEl;if(!ta)return;if(start===void 0||end===void 0){ta.setRangeText(replacement)}else{ta.setRangeText(replacement,start,end,selectMode)}this.value=ta.value;this.fitToContent()}connectedCallback(){super.connectedCallback();this.countAnnouncementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this});if(this.resize==="auto"&&this.hasUpdated){this.armResizeObserver();this.fitToContent()}}disconnectedCallback(){this.resizeObserver?.disconnect();this.resizeObserver=void 0;if(this.resizeRaf!==void 0)this.resizeRafOwner?.cancelAnimationFrame(this.resizeRaf);this.resizeRaf=void 0;this.resizeRafOwner=void 0;if(this.countAnnounceTimer!==void 0){this.countAnnounceTimerOwner?.clearTimeout(this.countAnnounceTimer)}this.countAnnounceTimer=void 0;this.countAnnounceTimerOwner=void 0;this.countAnnouncementSink?.release();this.countAnnouncementSink=void 0;super.disconnectedCallback()}countMaxlength(){const declared=this.maxlength;if(declared===void 0||!Number.isFinite(declared))return void 0;return finiteCount(declared,0)}countText(){const format=getNumberFormat(this.effectiveLocale);const max=this.countMaxlength();if(max!==void 0){const remaining=Math.max(0,max-this.value.length);return this.localize("textareaCharactersRemaining",void 0,{count:format.format(remaining),pluralCount:remaining})}const length=this.value.length;return this.localize("textareaCharacterCount",void 0,{count:format.format(length),pluralCount:length})}scheduleCountAnnouncement(){if(this.countAnnounceTimer!==void 0){this.countAnnounceTimerOwner?.clearTimeout(this.countAnnounceTimer)}this.countAnnounceTimer=void 0;this.countAnnounceTimerOwner=void 0;if(!this.withCount)return;const view=this.ownerDocument.defaultView;if(!view)return;this.countAnnounceTimerOwner=view;this.countAnnounceTimer=view.setTimeout(()=>{this.countAnnounceTimer=void 0;this.countAnnounceTimerOwner=void 0;if(!this.isConnected||this.ownerDocument.defaultView!==view||!this.withCount)return;if(!isAccessibilityVisible(this))return;const text=this.countText();this.announcedCountText=text;this.countAnnouncementSink?.announce(text)},COUNT_ANNOUNCE_DELAY_MS)}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}if(this.required&&this.value===""){this[SET_ANCHORED_VALIDITY]({valueMissing:true},this.localize("fieldRequired"));return}const native=this.textareaEl;if(native&&native.value!==this.value)native.value=this.value;const own=lengthViolations(this.value,this.minlength,this.maxlength);const tooShort=Boolean(native?.validity.tooShort)||own.tooShort;const tooLong=Boolean(native?.validity.tooLong)||own.tooLong;if(!tooShort&&!tooLong){this[SET_ANCHORED_VALIDITY]({});return}this[SET_ANCHORED_VALIDITY]({tooShort,tooLong},native?.validationMessage||this.localize("valueInvalid"))}updated(changed){super.updated(changed);if(changed.has("value")){if(this.value==="")this.internals.states.add("blank");else this.internals.states.delete("blank")}if(changed.has("minlength")||changed.has("maxlength")||changed.has("readonly")){this.updateValidity()}if(changed.has("resize")){if(this.resize==="auto"){this.armResizeObserver()}else if(changed.get("resize")==="auto"){this.resizeObserver?.disconnect();this.resizeObserver=void 0;if(this.resizeRaf!==void 0)this.resizeRafOwner?.cancelAnimationFrame(this.resizeRaf);this.resizeRaf=void 0;this.resizeRafOwner=void 0;if(this.textareaEl){this.textareaEl.style.blockSize="";this.textareaEl.style.overflowY=""}}}if(this.resize==="auto"){this.armResizeObserver();if(changed.has("value")||changed.has("rows")||changed.has("resize"))this.fitToContent()}}formResetCallback(){super.formResetCallback();this.touched=false}armResizeObserver(){const textarea=this.textareaEl;if(this.resizeObserver||!textarea)return;const view=this.ownerDocument.defaultView;const ResizeObserverCtor=view?.ResizeObserver;if(!view||!ResizeObserverCtor)return;this.lastObservedWidth=textarea.getBoundingClientRect().width;this.resizeObserver=new ResizeObserverCtor(entries=>{if(!this.isConnected||this.ownerDocument.defaultView!==view)return;const width=entries[0]?.contentRect.width;if(width===void 0||this.lastObservedWidth!==void 0&&Math.abs(width-this.lastObservedWidth)<.5){return}this.lastObservedWidth=width;if(this.resizeRaf!==void 0)this.resizeRafOwner?.cancelAnimationFrame(this.resizeRaf);this.resizeRafOwner=view;this.resizeRaf=view.requestAnimationFrame(()=>{this.resizeRaf=void 0;this.resizeRafOwner=void 0;if(!this.isConnected||this.ownerDocument.defaultView!==view)return;this.fitToContent()})});this.resizeObserver.observe(textarea)}fitToContent(){const ta=this.textareaEl;if(!ta||this.resize!=="auto")return;ta.style.blockSize="auto";const computed=ta.ownerDocument.defaultView?.getComputedStyle(ta);if(!computed)return;const borderBlock=parseFloat(computed.borderBlockStartWidth)+parseFloat(computed.borderBlockEndWidth);const parsedMax=parseFloat(computed.maxBlockSize);const maxBlockSize=Number.isFinite(parsedMax)?parsedMax:Number.POSITIVE_INFINITY;const contentBlockSize=ta.scrollHeight+borderBlock;ta.style.blockSize=`${Math.min(contentBlockSize,maxBlockSize)}px`;ta.style.overflowY=contentBlockSize>maxBlockSize?"auto":"hidden"}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?"textarea-error":"",hasHint?"textarea-hint":""].filter(Boolean).join(" ");const cssResize=this.resize==="auto"?"none":sanitizeCssResize(this.resize,"vertical");return html`
|
|
2
2
|
<div part="form-control">
|
|
3
3
|
<label part="form-control-label" for="textarea" ?hidden=${!hasLabel}>
|
|
4
4
|
<span part="label">${this.label}<slot name="label"></slot></span>
|
|
@@ -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{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{nextId}from"../../../internal/a11y.js";import{closeIcon}from"../../../internal/icons.js";import{spellcheckConverter}from"../../../internal/converters.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./token-input.styles.js";import{createStringArrayFormDataState,getFormOwner,installCustomErrorProperty,isBarredFromValidation,readStringArrayFormDataState,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_remove,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_tokenInputEditWithContext,LYRA_DEFAULT_tokenInputRequired}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}}}const delimiterConverter={fromAttribute:value=>{if(value===null)return",";return value===""||value==="none"?null:value},toAttribute:value=>value===null?"none":value};const stringArrayConverter={fromAttribute:value=>{if(value===null)return null;try{const parsed=JSON.parse(value);return Array.isArray(parsed)&&parsed.every(entry=>typeof entry==="string")?parsed:[]}catch{return[]}},toAttribute:value=>value==null?null:JSON.stringify(value)};class LyraTokenInput extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,remove:LYRA_DEFAULT_remove,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,tokenInputEditWithContext:LYRA_DEFAULT_tokenInputEditWithContext,tokenInputRequired:LYRA_DEFAULT_tokenInputRequired}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},name:{reflect:true,noAccessor:true},required:{type:Boolean,reflect:true,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},defaultValue:{attribute:"value",reflect:true,useDefault:true,converter:stringArrayConverter,noAccessor:true}}}get editable(){return this._editable}set editable(next){const old=this._editable;this._editable=Boolean(next);if(!this._editable)this.discardTransientState(false);this.requestUpdate("editable",old)}get value(){return this._value}set value(next){const old=this._value;if(!this.settingDefaultValue)this._valueDirty=true;const normalized=Array.isArray(next)?[...next]:[];if(this.editingIndex>=0&&normalized!==old){this.editingIndex=-1;this.editDraft="";this.focusEditorPending=false}this._value=normalized;this.requestUpdate("value",old);if(this.internals)this.syncValidity()}get defaultValue(){return[...this._defaultValue]}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=Array.isArray(next)?[...next]:[];this.reflectingDefaultValue=true;try{if(next==null)this.removeAttribute("value");else this.setAttribute("value",JSON.stringify(this._defaultValue))}finally{this.reflectingDefaultValue=false}if(!this._valueDirty)this.restoreLiveValueFromDefault();this.requestUpdate("defaultValue",old)}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.syncValidity();this.requestUpdate("name",old)}get required(){return this._required}set required(next){const old=this._required;this._required=Boolean(next);this.toggleAttribute("required",this._required);this.syncValidity();this.requestUpdate("required",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);if(this._disabled)this.discardTransientState(true);this.toggleAttribute("disabled",this._disabled);this.syncValidity();this.requestUpdate("disabled",old)}constructor(){super();this.label="";this.hint="";this.errorText="";this.placeholder="";this.spellcheck=true;this.autocapitalize="";this.autoCorrect="";this.accessibleLabel="";this.size="m";this.pill=false;this.allowDuplicates=false;this._editable=false;this.delimiter=",";this.draft="";this.touched=false;this.editingIndex=-1;this.editDraft="";this.rovingIndex=0;this.focusEditorPending=false;this.focusTokenPending=-1;this.hasLabelSlot=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.labelId=nextId("token-input-label");this.hintId=nextId("token-input-hint");this.errorId=nextId("token-input-error");this._value=[];this._defaultValue=[];this._valueDirty=false;this.settingDefaultValue=false;this.reflectingDefaultValue=false;this._fieldsetDisabled=false;this._name="";this._required=false;this._disabled=false;this.onEditInput=event=>{this.editDraft=event.target.value};this.onEditKeyDown=event=>{if(event.key==="Enter"){event.preventDefault();this.commitEdit(true)}else if(event.key==="Escape"){event.preventDefault();event.stopPropagation();this.cancelEdit()}};this.onEditBlur=()=>{queueMicrotask(()=>{if(!this.isConnected||!this.editable||this.effectiveDisabled||this.matches(":disabled")){this.discardTransientState(false);return}this.commitEdit(false)})};this.onInput=event=>{this.draft=event.target.value};this.onKeyDown=event=>{if(this.effectiveDisabled)return;if(event.key==="Enter"||this.delimiter!==null&&event.key===this.delimiter){if(this.draft.trim()){event.preventDefault();this.addDraft()}else if(event.key==="Enter")submitOnEnter(this,event)}else if(event.key==="Tab"){if(this.draft.trim())this.addDraft()}else if(event.key==="Backspace"&&!this.draft&&this.value.length&&this.editingIndex<0){this.removeToken(this.value.length-1)}};this.onBlur=()=>{if(this.draft.trim())this.addDraft();this.touched=true;this.syncValidity();this.emit("blur")};this.onFocus=()=>{this.emit("focus")};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};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))}connectedCallback(){super.connectedCallback();this.syncValidity()}disconnectedCallback(){this.discardTransientState(true);super.disconnectedCallback()}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 effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;if(disabled)this.discardTransientState(true);this.syncValidity();this.requestUpdate()}[VALIDITY_ANCHOR](){return this.inputEl??this.renderRoot?.querySelector('[part="input-wrapper"]')??null}checkValidity(){return this.internals.checkValidity()}reportValidity(){this.touched=true;this.syncValidity();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.syncValidity()}focus(options){this.inputEl?.focus(options)}blur(){this.inputEl?.blur()}click(){if(this.effectiveDisabled)return;this.inputEl?.focus()}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")}}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}syncValidity(){const barred=this.barredFromValidation;const missing=!barred&&this.required&&this.value.length===0;this.validityController.setValidity(missing?{valueMissing:true}:{},missing?this.localize("tokenInputRequired"):"");this.toggleAttribute("data-invalid",!barred&&this.touched&&!this.internals.validity.valid);syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred});const data=new FormData;if(this.name)this.value.forEach(token=>data.append(this.name,token));this.internals.setFormValue(this.name?data:null,createStringArrayFormDataState(this.name,this.value))}updateValue(next,event){this.value=next;this.syncValidity();this.emit("input",{value:this.value});this.emit("change",{value:this.value});if(event==="add"){const added=next[next.length-1];if(added!==void 0)this.emit("lr-add",{value:added})}}addDraft(){if(this.effectiveDisabled)return;const parts=this.delimiter?this.draft.split(this.delimiter):[this.draft];const candidates=parts.map(token=>token.trim()).filter(Boolean);for(const token of candidates){if(!this.allowDuplicates&&this.value.includes(token))continue;this.updateValue([...this.value,token],"add")}this.draft=""}discardTransientState(clearDraft){this.editingIndex=-1;this.editDraft="";this.focusEditorPending=false;this.focusTokenPending=-1;if(clearDraft){this.draft="";if(this.inputEl)this.inputEl.value=""}}removeToken(index){const removed=this.value[index];if(removed===void 0)return;const event=this.emit("lr-remove",{value:removed,index},{cancelable:true});if(event.defaultPrevented)return;if(this.editingIndex>=0){this.editingIndex=-1;this.editDraft=""}this.updateValue(this.value.filter((_token,i)=>i!==index))}get activeTokenIndex(){if(!this.value.length)return-1;return Math.min(Math.max(this.rovingIndex,0),this.value.length-1)}startEdit(index){if(this.effectiveDisabled||!this.editable)return;if(index<0||index>=this.value.length)return;this.editingIndex=index;this.editDraft=this.value[index];this.rovingIndex=index;this.focusEditorPending=true}cancelEdit(){if(this.editingIndex<0)return;this.focusTokenPending=this.editingIndex;this.editingIndex=-1;this.editDraft=""}commitEdit(restoreFocus){const index=this.editingIndex;if(index<0)return;const previousValue=this.value[index];const next=this.editDraft.trim();if(restoreFocus)this.focusTokenPending=index;this.editingIndex=-1;this.editDraft="";if(previousValue===void 0)return;if(!next||next===previousValue)return;if(!this.allowDuplicates&&this.value.some((token,i)=>i!==index&&token===next))return;this.updateValue(this.value.map((token,i)=>i===index?next:token));this.emit("lr-token-edit",{value:next,previousValue,index})}moveRovingFocus(index){if(!this.value.length)return;const clamped=Math.min(Math.max(index,0),this.value.length-1);this.rovingIndex=clamped;this.focusTokenPending=clamped}onTokenKeyDown(event,index){if(this.effectiveDisabled)return;const rtl=this.effectiveDirection==="rtl";const forward=rtl?"ArrowLeft":"ArrowRight";const backward=rtl?"ArrowRight":"ArrowLeft";if(event.key==="Enter"||event.key===" "||event.key==="F2"){event.preventDefault();this.startEdit(index)}else if(event.key===forward){event.preventDefault();this.moveRovingFocus(index+1)}else if(event.key===backward){event.preventDefault();this.moveRovingFocus(index-1)}else if(event.key==="Home"){event.preventDefault();this.moveRovingFocus(0)}else if(event.key==="End"){event.preventDefault();this.moveRovingFocus(this.value.length-1)}}formResetCallback(){this.restoreLiveValueFromDefault();this.discardTransientState(true);this.rovingIndex=0;this.touched=false;this.syncValidity()}restoreLiveValueFromDefault(){this.settingDefaultValue=true;try{this.value=[...this._defaultValue]}finally{this.settingDefaultValue=false}this._valueDirty=false}formStateRestoreCallback(state2,_mode){this.value=readStringArrayFormDataState(state2);this.discardTransientState(true);this.rovingIndex=0;this.touched=false;this.syncValidity()}updated(changed){super.updated(changed);if(this.focusEditorPending){this.focusEditorPending=false;const editor=this.renderRoot?.querySelector('[part="token-editor"]');editor?.focus();editor?.select()}if(this.focusTokenPending>=0){const index=this.focusTokenPending;this.focusTokenPending=-1;const labels=this.renderRoot?.querySelectorAll('[part="token-label"]');labels?.[index]?.focus()}}renderRemoveButton(token,index){return html`<button part="remove" type="button" aria-label=${this.localize("removeWithContext",void 0,{label:token})} ?disabled=${this.effectiveDisabled} @click=${()=>this.removeToken(index)}>${closeIcon()}</button>`}renderEditableToken(token,index){if(this.editingIndex===index){return html`<span part="token"><input part="token-editor" .value=${this.editDraft} aria-label=${this.localize("tokenInputEditWithContext",void 0,{label:token})} ?disabled=${this.effectiveDisabled} spellcheck=${this.spellcheck} autocapitalize=${this.autocapitalize||nothing} autocorrect=${this.autoCorrect||nothing} @input=${this.onEditInput} @keydown=${this.onEditKeyDown} @blur=${this.onEditBlur} />${this.renderRemoveButton(token,index)}</span>`}return html`<span part="token"><span part="token-label" role="button" tabindex=${index===this.activeTokenIndex?0:-1} aria-label=${this.localize("tokenInputEditWithContext",void 0,{label:token})} @click=${()=>this.startEdit(index)} @focus=${()=>{if(this.rovingIndex!==index)this.rovingIndex=index}} @keydown=${event=>this.onTokenKeyDown(event,index)}>${token}</span>${this.renderRemoveButton(token,index)}</span>`}render(){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 described=[hasHint?this.hintId:"",hasError?this.errorId:""].filter(Boolean).join(" ")||nothing;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{LyraElement}from"../../../internal/lyra-element.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{nextId}from"../../../internal/a11y.js";import{closeIcon}from"../../../internal/icons.js";import{spellcheckConverter}from"../../../internal/converters.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./token-input.styles.js";import{createStringArrayFormDataState,getFormOwner,installCustomErrorProperty,isBarredFromValidation,readStringArrayFormDataState,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_remove,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_tokenInputEditWithContext,LYRA_DEFAULT_tokenInputRequired}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}}}const delimiterConverter={fromAttribute:value=>{if(value===null)return",";return value===""||value==="none"?null:value},toAttribute:value=>value===null?"none":value};const stringArrayConverter={fromAttribute:value=>{if(value===null)return null;try{const parsed=JSON.parse(value);return Array.isArray(parsed)&&parsed.every(entry=>typeof entry==="string")?parsed:[]}catch{return[]}},toAttribute:value=>value==null?null:JSON.stringify(value)};class LyraTokenInput extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,remove:LYRA_DEFAULT_remove,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,tokenInputEditWithContext:LYRA_DEFAULT_tokenInputEditWithContext,tokenInputRequired:LYRA_DEFAULT_tokenInputRequired}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},name:{reflect:true,noAccessor:true},required:{type:Boolean,reflect:true,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},defaultValue:{attribute:"value",reflect:true,useDefault:true,converter:stringArrayConverter,noAccessor:true}}}get editable(){return this._editable}set editable(next){const old=this._editable;this._editable=Boolean(next);if(!this._editable)this.discardTransientState(false);this.requestUpdate("editable",old)}get value(){return this._value}set value(next){const old=this._value;if(!this.settingDefaultValue)this._valueDirty=true;const normalized=Array.isArray(next)?[...next]:[];if(this.editingIndex>=0&&normalized!==old){this.editingIndex=-1;this.editDraft="";this.focusEditorPending=false}this._value=normalized;this.requestUpdate("value",old);if(this.internals)this.syncValidity()}get defaultValue(){return[...this._defaultValue]}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=Array.isArray(next)?[...next]:[];this.reflectingDefaultValue=true;try{if(next==null)this.removeAttribute("value");else this.setAttribute("value",JSON.stringify(this._defaultValue))}finally{this.reflectingDefaultValue=false}if(!this._valueDirty)this.restoreLiveValueFromDefault();this.requestUpdate("defaultValue",old)}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.syncValidity();this.requestUpdate("name",old)}get required(){return this._required}set required(next){const old=this._required;this._required=Boolean(next);this.toggleAttribute("required",this._required);this.syncValidity();this.requestUpdate("required",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);if(this._disabled)this.discardTransientState(true);this.toggleAttribute("disabled",this._disabled);this.syncValidity();this.requestUpdate("disabled",old)}constructor(){super();this.label="";this.hint="";this.errorText="";this.placeholder="";this.spellcheck=true;this.autocapitalize="";this.autoCorrect="";this.accessibleLabel="";this.size="m";this.pill=false;this.allowDuplicates=false;this._editable=false;this.delimiter=",";this.draft="";this.touched=false;this.editingIndex=-1;this.editDraft="";this.rovingIndex=0;this.focusEditorPending=false;this.focusTokenPending=-1;this.hasLabelSlot=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.labelId=nextId("token-input-label");this.hintId=nextId("token-input-hint");this.errorId=nextId("token-input-error");this._value=[];this._defaultValue=[];this._valueDirty=false;this.settingDefaultValue=false;this.reflectingDefaultValue=false;this._fieldsetDisabled=false;this._name="";this._required=false;this._disabled=false;this.onEditInput=event=>{this.editDraft=event.target.value};this.onEditKeyDown=event=>{if(event.key==="Enter"){event.preventDefault();this.commitEdit(true)}else if(event.key==="Escape"){event.preventDefault();event.stopPropagation();this.cancelEdit()}};this.onEditBlur=()=>{queueMicrotask(()=>{if(!this.isConnected||!this.editable||this.effectiveDisabled||this.matches(":disabled")){this.discardTransientState(false);return}this.commitEdit(false)})};this.onInput=event=>{this.draft=event.target.value};this.onKeyDown=event=>{if(this.effectiveDisabled)return;if(event.key==="Enter"||this.delimiter!==null&&event.key===this.delimiter){if(this.draft.trim()){event.preventDefault();this.addDraft()}else if(event.key==="Enter")submitOnEnter(this,event)}else if(event.key==="Tab"){if(this.draft.trim())this.addDraft()}else if(event.key==="Backspace"&&!this.draft&&this.value.length&&this.editingIndex<0){this.removeToken(this.value.length-1)}};this.onBlur=()=>{if(!this.effectiveDisabled){if(this.draft.trim())this.addDraft();this.touched=true}this.syncValidity();this.emit("blur")};this.onFocus=()=>{this.emit("focus")};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};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))}connectedCallback(){super.connectedCallback();this.syncValidity()}disconnectedCallback(){this.discardTransientState(true);super.disconnectedCallback()}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 effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;if(disabled)this.discardTransientState(true);this.syncValidity();this.requestUpdate()}[VALIDITY_ANCHOR](){return this.inputEl??this.renderRoot?.querySelector('[part="input-wrapper"]')??null}checkValidity(){return this.internals.checkValidity()}reportValidity(){this.touched=true;this.syncValidity();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.syncValidity()}focus(options){this.inputEl?.focus(options)}blur(){this.inputEl?.blur()}click(){if(this.effectiveDisabled)return;this.inputEl?.focus()}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")}}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}syncValidity(){const barred=this.barredFromValidation;const missing=!barred&&this.required&&this.value.length===0;this.validityController.setValidity(missing?{valueMissing:true}:{},missing?this.localize("tokenInputRequired"):"");this.toggleAttribute("data-invalid",!barred&&this.touched&&!this.internals.validity.valid);syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred});const data=new FormData;if(this.name)this.value.forEach(token=>data.append(this.name,token));this.internals.setFormValue(this.name?data:null,createStringArrayFormDataState(this.name,this.value))}updateValue(next,event){this.value=next;this.syncValidity();this.emit("input",{value:this.value});this.emit("change",{value:this.value});if(event==="add"){const added=next[next.length-1];if(added!==void 0)this.emit("lr-add",{value:added})}}addDraft(){if(this.effectiveDisabled)return;const parts=this.delimiter?this.draft.split(this.delimiter):[this.draft];const candidates=parts.map(token=>token.trim()).filter(Boolean);for(const token of candidates){if(!this.allowDuplicates&&this.value.includes(token))continue;this.updateValue([...this.value,token],"add")}this.draft=""}discardTransientState(clearDraft){this.editingIndex=-1;this.editDraft="";this.focusEditorPending=false;this.focusTokenPending=-1;if(clearDraft){this.draft="";if(this.inputEl)this.inputEl.value=""}}removeToken(index){const removed=this.value[index];if(removed===void 0)return;const event=this.emit("lr-remove",{value:removed,index},{cancelable:true});if(event.defaultPrevented)return;if(this.editingIndex>=0){this.editingIndex=-1;this.editDraft=""}this.updateValue(this.value.filter((_token,i)=>i!==index))}get activeTokenIndex(){if(!this.value.length)return-1;return Math.min(Math.max(this.rovingIndex,0),this.value.length-1)}startEdit(index){if(this.effectiveDisabled||!this.editable)return;if(index<0||index>=this.value.length)return;this.editingIndex=index;this.editDraft=this.value[index];this.rovingIndex=index;this.focusEditorPending=true}cancelEdit(){if(this.editingIndex<0)return;this.focusTokenPending=this.editingIndex;this.editingIndex=-1;this.editDraft=""}commitEdit(restoreFocus){const index=this.editingIndex;if(index<0)return;const previousValue=this.value[index];const next=this.editDraft.trim();if(restoreFocus)this.focusTokenPending=index;this.editingIndex=-1;this.editDraft="";if(previousValue===void 0)return;if(!next||next===previousValue)return;if(!this.allowDuplicates&&this.value.some((token,i)=>i!==index&&token===next))return;this.updateValue(this.value.map((token,i)=>i===index?next:token));this.emit("lr-token-edit",{value:next,previousValue,index})}moveRovingFocus(index){if(!this.value.length)return;const clamped=Math.min(Math.max(index,0),this.value.length-1);this.rovingIndex=clamped;this.focusTokenPending=clamped}onTokenKeyDown(event,index){if(this.effectiveDisabled)return;const rtl=this.effectiveDirection==="rtl";const forward=rtl?"ArrowLeft":"ArrowRight";const backward=rtl?"ArrowRight":"ArrowLeft";if(event.key==="Enter"||event.key===" "||event.key==="F2"){event.preventDefault();this.startEdit(index)}else if(event.key===forward){event.preventDefault();this.moveRovingFocus(index+1)}else if(event.key===backward){event.preventDefault();this.moveRovingFocus(index-1)}else if(event.key==="Home"){event.preventDefault();this.moveRovingFocus(0)}else if(event.key==="End"){event.preventDefault();this.moveRovingFocus(this.value.length-1)}}formResetCallback(){this.restoreLiveValueFromDefault();this.discardTransientState(true);this.rovingIndex=0;this.touched=false;this.syncValidity()}restoreLiveValueFromDefault(){this.settingDefaultValue=true;try{this.value=[...this._defaultValue]}finally{this.settingDefaultValue=false}this._valueDirty=false}formStateRestoreCallback(state2,_mode){this.value=readStringArrayFormDataState(state2);this.discardTransientState(true);this.rovingIndex=0;this.touched=false;this.syncValidity()}updated(changed){super.updated(changed);if(this.focusEditorPending){this.focusEditorPending=false;const editor=this.renderRoot?.querySelector('[part="token-editor"]');editor?.focus();editor?.select()}if(this.focusTokenPending>=0){const index=this.focusTokenPending;this.focusTokenPending=-1;const labels=this.renderRoot?.querySelectorAll('[part="token-label"]');labels?.[index]?.focus()}}renderRemoveButton(token,index){return html`<button part="remove" type="button" aria-label=${this.localize("removeWithContext",void 0,{label:token})} ?disabled=${this.effectiveDisabled} @click=${()=>this.removeToken(index)}>${closeIcon()}</button>`}renderEditableToken(token,index){if(this.editingIndex===index){return html`<span part="token"><input part="token-editor" .value=${this.editDraft} aria-label=${this.localize("tokenInputEditWithContext",void 0,{label:token})} ?disabled=${this.effectiveDisabled} spellcheck=${this.spellcheck} autocapitalize=${this.autocapitalize||nothing} autocorrect=${this.autoCorrect||nothing} @input=${this.onEditInput} @keydown=${this.onEditKeyDown} @blur=${this.onEditBlur} />${this.renderRemoveButton(token,index)}</span>`}return html`<span part="token"><span part="token-label" role="button" tabindex=${index===this.activeTokenIndex?0:-1} aria-label=${this.localize("tokenInputEditWithContext",void 0,{label:token})} @click=${()=>this.startEdit(index)} @focus=${()=>{if(this.rovingIndex!==index)this.rovingIndex=index}} @keydown=${event=>this.onTokenKeyDown(event,index)}>${token}</span>${this.renderRemoveButton(token,index)}</span>`}render(){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 described=[hasHint?this.hintId:"",hasError?this.errorId:""].filter(Boolean).join(" ")||nothing;return html`<div part="form-control">
|
|
2
2
|
<label part="form-control-label" ?hidden=${!hasLabel} for="input" id=${this.labelId}>${this.label}<slot name="label" @slotchange=${this.onLabelSlotChange}></slot></label>
|
|
3
3
|
<div part="input-wrapper" role="group" aria-labelledby=${this.accessibleLabel?nothing:hasLabel?this.labelId:nothing} aria-label=${this.accessibleLabel||nothing}>
|
|
4
4
|
${this.value.map((token,index)=>this.editable?this.renderEditableToken(token,index):html`<span part="token"><span>${token}</span><button part="remove" type="button" aria-label=${this.localize("removeWithContext",void 0,{label:token})} ?disabled=${this.effectiveDisabled} @click=${()=>this.removeToken(index)}>${closeIcon()}</button></span>`)}
|
|
@@ -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{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{finiteCount,finiteRange}from"../../../internal/numbers.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{sizes}from"../../../internal/sizes.styles.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{closeIcon,fileIcon}from"../../../internal/icons.js";import{styles}from"./file-input.styles.js";import{matchesAccept}from"./accept.js";import{presenceTrueDefaultBooleanConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize}from"../attachment-chip/file-size.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_dropzoneRejectedType,LYRA_DEFAULT_dropzoneReleaseToAdd,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_fileInputAcceptedMany,LYRA_DEFAULT_fileInputAcceptedOne,LYRA_DEFAULT_fileInputDefaultLabel,LYRA_DEFAULT_fileInputFolderRejected,LYRA_DEFAULT_fileInputRejectedCount,LYRA_DEFAULT_fileInputRejectedMany,LYRA_DEFAULT_fileInputRejectedOne,LYRA_DEFAULT_fileInputRejectedSize,LYRA_DEFAULT_fileInputRejectedType,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_open,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore}from"../../../internal/default-strings.generated.js";const DEFAULT_MAX_FILE_SIZE_BYTES=25*1024*1024;const INTERACTIVE_CONTENT_SELECTOR='a[href], area[href], button, input, select, textarea, summary, [contenteditable]:not([contenteditable="false"]), [role="button"], [role="link"], [tabindex]:not([tabindex="-1"])';function isElementTarget(value){const candidate=value;return candidate.nodeType===1&&typeof candidate.matches==="function"}function isFileValue(value){if(value===null||typeof value!=="object")return false;try{const candidate=value;return Object.prototype.toString.call(value)==="[object File]"&&typeof candidate.name==="string"&&typeof candidate.lastModified==="number"&&typeof candidate.size==="number"&&typeof candidate.type==="string"&&typeof candidate.slice==="function"}catch{return false}}function isFormDataValue(value){if(value===null||typeof value!=="object")return false;try{const candidate=value;return Object.prototype.toString.call(value)==="[object FormData]"&&typeof candidate.append==="function"&&typeof candidate.values==="function"}catch{return false}}class LyraFileInput extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,dropzoneRejectedType:LYRA_DEFAULT_dropzoneRejectedType,dropzoneReleaseToAdd:LYRA_DEFAULT_dropzoneReleaseToAdd,fieldRequired:LYRA_DEFAULT_fieldRequired,fileInputAcceptedMany:LYRA_DEFAULT_fileInputAcceptedMany,fileInputAcceptedOne:LYRA_DEFAULT_fileInputAcceptedOne,fileInputDefaultLabel:LYRA_DEFAULT_fileInputDefaultLabel,fileInputFolderRejected:LYRA_DEFAULT_fileInputFolderRejected,fileInputRejectedCount:LYRA_DEFAULT_fileInputRejectedCount,fileInputRejectedMany:LYRA_DEFAULT_fileInputRejectedMany,fileInputRejectedOne:LYRA_DEFAULT_fileInputRejectedOne,fileInputRejectedSize:LYRA_DEFAULT_fileInputRejectedSize,fileInputRejectedType:LYRA_DEFAULT_fileInputRejectedType,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,open:LYRA_DEFAULT_open,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,sizes,styles,srOnly]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},name:{reflect:true,noAccessor:true},files:{attribute:false,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},required:{type:Boolean,reflect:true,noAccessor:true}}}constructor(){super();this.multiple=false;this.compact=false;this.accept="";this.capture="";this.allowedMimeTypes=[];this.forbiddenMimeTypes=[];this.maxFileSize=0;this.directory=false;this.paste=true;this.label="";this.hint="";this.withLabel=false;this.withHint=false;this.size="m";this.validators=[];this.accessibleLabel="";this.acceptedMessage="{count} file(s) added.";this.rejectedMessage="{count} file(s) rejected.";this.dragState="default";this.resultStatus="";this.rejectedFiles=[];this.touched=false;this.slotPresence=new SlotPresenceController(this);this.dragCounter=0;this.dropToken=0;this.announcementsArmed=false;this._name=null;this._files=[];this._fileCount=0;this._disabled=false;this._required=false;this._fieldsetDisabled=false;this.thumbnailUrls=new Map;this.onDragEnter=e=>{e.preventDefault();if(this.effectiveDisabled)return;this.dragCounter++;const items=e.dataTransfer?[...e.dataTransfer.items].filter(i=>i.kind==="file"):[];this.dragState=items.length?this.previewState(items):"default";this.publishCustomStates()};this.onDragOver=e=>{e.preventDefault();if(this.effectiveDisabled)return};this.onDragLeave=e=>{if(this.effectiveDisabled)return;e.preventDefault();this.dragCounter=Math.max(0,this.dragCounter-1);if(this.dragCounter===0){this.dragState="default";this.publishCustomStates()}};this.onDrop=e=>{e.preventDefault();if(this.effectiveDisabled)return;this.resetDragSession();const token=++this.dropToken;const files=[...e.dataTransfer?.files??[]];const folders=[...e.dataTransfer?.items??[]].map(item=>item.webkitGetAsEntry?.()).filter(entry=>!!entry&&entry.isDirectory);if(folders.length&&this.multiple){void Promise.all(folders.map(folder=>this.readDroppedEntry(folder))).then(nested=>{if(token!==this.dropToken||!this.isConnected||this.effectiveDisabled)return;const allFiles=[...files,...nested.flat()];if(allFiles.length)this.emitFiles(allFiles)});return}const FileCtor=this.ownerDocument.defaultView?.File??globalThis.File;const rejectedFolders=folders.map(folder=>({file:new FileCtor([],folder.name),reason:"directory"}));if(files.length||rejectedFolders.length)this.emitFiles(files,rejectedFolders)};this.onPaste=e=>{if(!this.paste||this.effectiveDisabled)return;const files=[...e.clipboardData?.files??[]];if(files.length){e.preventDefault();this.emitFiles(files)}};this.onInputChange=e=>{const input=e.target;const files=[...input.files??[]];input.value="";if(!this.effectiveDisabled&&files.length)this.emitFiles(files)};this.onFocus=event=>{relayNativeEvent(this,event)};this.onBlur=event=>{this.touched=true;this.publishCustomStates();relayNativeEvent(this,event)};this.onKeyDown=e=>{if(this.effectiveDisabled)return;if(e.key==="Enter"||e.key===" "||e.key==="Spacebar"){e.preventDefault();this.openPicker()}};this.onDropzoneClick=event=>{const path=event.composedPath();if(path.includes(this.baseEl)||path.some(node=>isElementTarget(node)&&node.matches(INTERACTIVE_CONTENT_SELECTOR))){return}this.openPicker()};this.internals=attachInternalsSafely(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));this.internals.setFormValue(null)}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 name(){return this._name}set name(next){const old=this._name;this._name=next==null||next===""?null:String(next);if(this._name==null)this.removeAttribute("name");else this.setAttribute("name",this._name);this.syncFormValue();this.requestUpdate("name",old)}get files(){return[...this._files]}set files(next){const old=this._files;const valid=Array.isArray(next)?next.filter(isFileValue):[];this._files=this.multiple?[...valid]:valid.slice(0,1);this.fileCount=this._files.length;this.syncThumbnailUrls();this.syncFormValue();this.updateValidity();this.requestUpdate("files",old)}get fileCount(){return this._fileCount}set fileCount(next){const old=this._fileCount;this._fileCount=finiteCount(next,this._files.length);this.requestUpdate("fileCount",old)}get dragging(){return this.dragState!=="default"}set dragging(next){const active=Boolean(next);if(active===this.dragging)return;this.dragState=active?"accept":"default";this.publishCustomStates()}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.dropToken++;this.resetDragSession()}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 effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get validationTarget(){return this.validationTargetOverride??this.baseEl}set validationTarget(next){this.validationTargetOverride=next??void 0;this.validityController.refreshAnchor()}[VALIDITY_ANCHOR](){return this.validationTarget??null}willUpdate(changed){super.willUpdate(changed);if(changed.has("multiple")){if(!this.multiple&&this._files.length>1)this.files=this._files;else this.syncFormValue()}}connectedCallback(){super.connectedCallback();this.syncThumbnailUrls();this.updateValidity();this.politeSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this});this.assertiveSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.dropToken++;this.resetDragSession();for(const thumbnail of this.thumbnailUrls.values())thumbnail.revoke();this.thumbnailUrls.clear();this.politeSink?.release();this.politeSink=void 0;this.assertiveSink?.release();this.assertiveSink=void 0;this.announcementsArmed=false;super.disconnectedCallback()}updated(changed){if(this.announcementsArmed){if(changed.has("dragState")||changed.has("resultStatus")){this.politeSink?.announce(this.statusText())}if(changed.has("rejectedFiles")&&this.rejectedFiles.length>0){this.assertiveSink?.announce(this.rejectedFiles.map(rejected=>this.rejectionMessage(rejected)).join(" "))}}this.announcementsArmed=true}syncFormValue(){if(!this.name||this._files.length===0){const state2=this.multiple?this.createFormData():this._files[0]??null;this.internals.setFormValue(null,state2);return}if(this.multiple){const submitted=this.createFormData();const state2=this.createFormData();if(!submitted||!state2){this.internals.setFormValue(null);return}for(const file2 of this._files){submitted.append(this.name,file2);state2.append("file",file2)}this.internals.setFormValue(submitted,state2);return}const file=this._files[0]??null;this.internals.setFormValue(file,file)}createFormData(){const FormDataCtor=this.ownerDocument?.defaultView?.FormData;return FormDataCtor?new FormDataCtor:null}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({})}else if(this.required&&this._files.length===0){this.validityController.setValidity({valueMissing:true},this.localize("fieldRequired"))}else{this.validityController.setValidity({})}this.publishCustomStates()}publishCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation});setCustomState(this.internals,"blank",this._files.length===0);setCustomState(this.internals,"dragging",this.dragging);this.toggleAttribute("dragging",this.dragging)}checkValidity(){return this.internals.checkValidity()}reportValidity(){this.touched=true;this.publishCustomStates();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.publishCustomStates()}resetValidity(){this.validityController.setCustomValidity("");this.updateValidity()}formResetCallback(){this.touched=false;this.files=[];this.rejectedFiles=[];this.resultStatus=""}formStateRestoreCallback(state2,reason){void reason;if(isFileValue(state2)){this.files=[state2];return}if(isFormDataValue(state2)){this.files=[...state2.values()].filter(isFileValue);return}this.files=[]}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;if(disabled){this.dropToken++;this.resetDragSession()}this.updateValidity();this.requestUpdate()}syncThumbnailUrls(){const urlApi=this.ownerDocument.defaultView?.URL??globalThis.URL;const canCreate=typeof urlApi.createObjectURL==="function";const canRevoke=typeof urlApi.revokeObjectURL==="function";let changed=false;for(const[file,thumbnail]of this.thumbnailUrls){if(!this._files.includes(file)||thumbnail.owner!==urlApi){thumbnail.revoke();this.thumbnailUrls.delete(file);changed=true}}if(canCreate){for(const file of this._files){if(!file.type.startsWith("image/")||this.thumbnailUrls.has(file))continue;const url=urlApi.createObjectURL(file);this.thumbnailUrls.set(file,{url,owner:urlApi,revoke:canRevoke?()=>urlApi.revokeObjectURL(url):()=>void 0});changed=true}}if(changed)this.requestUpdate()}get effectiveMaxFileSize(){const maxFileSize=this.maxFileSize;if(maxFileSize===0||maxFileSize===Infinity)return null;return finiteRange(maxFileSize>0?maxFileSize:NaN,DEFAULT_MAX_FILE_SIZE_BYTES,1)}isAllowed(file,isPreview=false){if(this.forbiddenMimeTypes.includes(file.type))return"type";if(this.allowedMimeTypes.length>0&&!this.allowedMimeTypes.includes(file.type))return"type";if(this.accept&&!matchesAccept(file,this.accept,isPreview))return"type";const maxFileSize=this.effectiveMaxFileSize;if(maxFileSize!==null&&file.size>maxFileSize)return"size";return"ok"}classify(fileList,isPreview=false){if(!this.multiple&&fileList.length>1){return{files:[],rejected:fileList.map(file=>({file,reason:"count"}))}}const files=[];const rejected=[];for(const f of fileList){const reason=this.isAllowed(f,isPreview);if(reason==="ok")files.push(f);else rejected.push({file:f,reason})}return{files,rejected}}rejectionMessage(rejected){const filename=rejected.file.name;switch(rejected.reason){case"type":return this.localize("fileInputRejectedType",void 0,{filename});case"size":return this.localize("fileInputRejectedSize",void 0,{filename});case"count":return this.localize("fileInputRejectedCount",void 0,{filename});case"directory":return this.localize("fileInputFolderRejected",void 0,{filename})}}emitFiles(fileList,additionalRejected=[]){const{files,rejected}=this.classify(fileList);rejected.push(...additionalRejected);this.rejectedFiles=rejected;const messages=[];const numberFormat=getNumberFormat(this.effectiveLocale);if(files.length){messages.push(this.localize(files.length===1?"fileInputAcceptedOne":"fileInputAcceptedMany",this.acceptedMessage==="{count} file(s) added."?void 0:this.acceptedMessage,{count:numberFormat.format(files.length)}))}if(rejected.length){messages.push(this.localize(rejected.length===1?"fileInputRejectedOne":"fileInputRejectedMany",this.rejectedMessage==="{count} file(s) rejected."?void 0:this.rejectedMessage,{count:numberFormat.format(rejected.length)}))}this.resultStatus=messages.join(" ");if(files.length){this.touched=true;this.files=this.multiple?[...this._files,...files]:files;dispatchNativeEvent(this,"input");dispatchNativeEvent(this,"change")}this.emit("lr-files",{files,rejected})}openPicker(){if(this.effectiveDisabled)return;this.inputEl?.click()}focus(options){this.baseEl?.focus(options)}blur(){this.baseEl?.blur()}click(){this.openPicker()}resetDragSession(){this.dragCounter=0;this.dragState="default";this.publishCustomStates()}previewState(fileList){const{rejected}=this.classify(fileList,true);return rejected.length>0?"reject":"accept"}readDroppedEntry(entry){if(entry.isFile){return new Promise(resolve=>{entry.file(file=>resolve([file]),()=>resolve([]))})}if(!entry.isDirectory)return Promise.resolve([]);const reader=entry.createReader();return new Promise(resolve=>{const files=[];const readBatch=()=>{reader.readEntries(entries=>{if(entries.length===0){resolve(files);return}void Promise.all(entries.map(child=>this.readDroppedEntry(child))).then(nested=>{files.push(...nested.flat());readBatch()})},()=>resolve(files))};readBatch()})}statusText(){if(this.dragState==="accept")return this.localize("dropzoneReleaseToAdd");if(this.dragState==="reject")return this.localize("dropzoneRejectedType");return this.resultStatus}get effectiveLabel(){return this.label||this.localize("fileInputDefaultLabel")}removeFile(index){if(this.effectiveDisabled||index<0||index>=this._files.length)return;this.touched=true;this.files=this._files.filter((_,candidate)=>candidate!==index);dispatchNativeEvent(this,"input");dispatchNativeEvent(this,"change")}fileSize(file){return formatFileSize(file.size,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),(value,fractionDigits)=>getNumberFormat(this.effectiveLocale,{minimumFractionDigits:fractionDigits,maximumFractionDigits:fractionDigits}).format(value))}renderFile(file,index){const thumbnail=this.thumbnailUrls.get(file)?.url;return html`<div part="file">
|
|
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{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{finiteCount,finiteRange}from"../../../internal/numbers.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{sizes}from"../../../internal/sizes.styles.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{closeIcon,fileIcon}from"../../../internal/icons.js";import{styles}from"./file-input.styles.js";import{matchesAccept}from"./accept.js";import{presenceTrueDefaultBooleanConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize}from"../attachment-chip/file-size.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_dropzoneRejectedType,LYRA_DEFAULT_dropzoneReleaseToAdd,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_fileInputAcceptedMany,LYRA_DEFAULT_fileInputAcceptedOne,LYRA_DEFAULT_fileInputDefaultLabel,LYRA_DEFAULT_fileInputFolderRejected,LYRA_DEFAULT_fileInputRejectedCount,LYRA_DEFAULT_fileInputRejectedMany,LYRA_DEFAULT_fileInputRejectedOne,LYRA_DEFAULT_fileInputRejectedSize,LYRA_DEFAULT_fileInputRejectedType,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_open,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore}from"../../../internal/default-strings.generated.js";const DEFAULT_MAX_FILE_SIZE_BYTES=25*1024*1024;const INTERACTIVE_CONTENT_SELECTOR='a[href], area[href], button, input, select, textarea, summary, [contenteditable]:not([contenteditable="false"]), [role="button"], [role="link"], [tabindex]:not([tabindex="-1"])';function isElementTarget(value){const candidate=value;return candidate.nodeType===1&&typeof candidate.matches==="function"}function isFileValue(value){if(value===null||typeof value!=="object")return false;try{const candidate=value;return Object.prototype.toString.call(value)==="[object File]"&&typeof candidate.name==="string"&&typeof candidate.lastModified==="number"&&typeof candidate.size==="number"&&typeof candidate.type==="string"&&typeof candidate.slice==="function"}catch{return false}}function isFormDataValue(value){if(value===null||typeof value!=="object")return false;try{const candidate=value;return Object.prototype.toString.call(value)==="[object FormData]"&&typeof candidate.append==="function"&&typeof candidate.values==="function"}catch{return false}}class LyraFileInput extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,dropzoneRejectedType:LYRA_DEFAULT_dropzoneRejectedType,dropzoneReleaseToAdd:LYRA_DEFAULT_dropzoneReleaseToAdd,fieldRequired:LYRA_DEFAULT_fieldRequired,fileInputAcceptedMany:LYRA_DEFAULT_fileInputAcceptedMany,fileInputAcceptedOne:LYRA_DEFAULT_fileInputAcceptedOne,fileInputDefaultLabel:LYRA_DEFAULT_fileInputDefaultLabel,fileInputFolderRejected:LYRA_DEFAULT_fileInputFolderRejected,fileInputRejectedCount:LYRA_DEFAULT_fileInputRejectedCount,fileInputRejectedMany:LYRA_DEFAULT_fileInputRejectedMany,fileInputRejectedOne:LYRA_DEFAULT_fileInputRejectedOne,fileInputRejectedSize:LYRA_DEFAULT_fileInputRejectedSize,fileInputRejectedType:LYRA_DEFAULT_fileInputRejectedType,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,open:LYRA_DEFAULT_open,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,sizes,styles,srOnly]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},name:{reflect:true,noAccessor:true},files:{attribute:false,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},required:{type:Boolean,reflect:true,noAccessor:true}}}constructor(){super();this.multiple=false;this.compact=false;this.accept="";this.capture="";this.allowedMimeTypes=[];this.forbiddenMimeTypes=[];this.maxFileSize=0;this.directory=false;this.paste=true;this.label="";this.hint="";this.withLabel=false;this.withHint=false;this.size="m";this.validators=[];this.accessibleLabel="";this.acceptedMessage="{count} file(s) added.";this.rejectedMessage="{count} file(s) rejected.";this.dragState="default";this.resultStatus="";this.rejectedFiles=[];this.touched=false;this.slotPresence=new SlotPresenceController(this);this.dragCounter=0;this.dropToken=0;this.announcementsArmed=false;this._name=null;this._files=[];this._fileCount=0;this._disabled=false;this._required=false;this._fieldsetDisabled=false;this.thumbnailUrls=new Map;this.onDragEnter=e=>{e.preventDefault();if(this.effectiveDisabled)return;this.dragCounter++;const items=e.dataTransfer?[...e.dataTransfer.items].filter(i=>i.kind==="file"):[];this.dragState=items.length?this.previewState(items):"default";this.publishCustomStates()};this.onDragOver=e=>{e.preventDefault();if(this.effectiveDisabled)return};this.onDragLeave=e=>{if(this.effectiveDisabled)return;e.preventDefault();this.dragCounter=Math.max(0,this.dragCounter-1);if(this.dragCounter===0){this.dragState="default";this.publishCustomStates()}};this.onDrop=e=>{e.preventDefault();if(this.effectiveDisabled)return;this.resetDragSession();const token=++this.dropToken;const files=[...e.dataTransfer?.files??[]];const folders=[...e.dataTransfer?.items??[]].map(item=>item.webkitGetAsEntry?.()).filter(entry=>!!entry&&entry.isDirectory);if(folders.length&&this.multiple){void Promise.all(folders.map(folder=>this.readDroppedEntry(folder))).then(nested=>{if(token!==this.dropToken||!this.isConnected||this.effectiveDisabled)return;const allFiles=[...files,...nested.flat()];if(allFiles.length)this.emitFiles(allFiles)});return}const FileCtor=this.ownerDocument.defaultView?.File??globalThis.File;const rejectedFolders=folders.map(folder=>({file:new FileCtor([],folder.name),reason:"directory"}));if(files.length||rejectedFolders.length)this.emitFiles(files,rejectedFolders)};this.onPaste=e=>{if(!this.paste||this.effectiveDisabled)return;const files=[...e.clipboardData?.files??[]];if(files.length){e.preventDefault();this.emitFiles(files)}};this.onInputChange=e=>{const input=e.target;const files=[...input.files??[]];input.value="";if(!this.effectiveDisabled&&files.length)this.emitFiles(files)};this.onFocus=event=>{relayNativeEvent(this,event)};this.onBlur=event=>{if(!this.effectiveDisabled)this.touched=true;this.publishCustomStates();relayNativeEvent(this,event)};this.onKeyDown=e=>{if(this.effectiveDisabled)return;if(e.key==="Enter"||e.key===" "||e.key==="Spacebar"){e.preventDefault();this.openPicker()}};this.onDropzoneClick=event=>{const path=event.composedPath();if(path.includes(this.baseEl)||path.some(node=>isElementTarget(node)&&node.matches(INTERACTIVE_CONTENT_SELECTOR))){return}this.openPicker()};this.internals=attachInternalsSafely(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));this.internals.setFormValue(null)}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 name(){return this._name}set name(next){const old=this._name;this._name=next==null||next===""?null:String(next);if(this._name==null)this.removeAttribute("name");else this.setAttribute("name",this._name);this.syncFormValue();this.requestUpdate("name",old)}get files(){return[...this._files]}set files(next){const old=this._files;const valid=Array.isArray(next)?next.filter(isFileValue):[];this._files=this.multiple?[...valid]:valid.slice(0,1);this.fileCount=this._files.length;this.syncThumbnailUrls();this.syncFormValue();this.updateValidity();this.requestUpdate("files",old)}get fileCount(){return this._fileCount}set fileCount(next){const old=this._fileCount;this._fileCount=finiteCount(next,this._files.length);this.requestUpdate("fileCount",old)}get dragging(){return this.dragState!=="default"}set dragging(next){const active=Boolean(next);if(active===this.dragging)return;this.dragState=active?"accept":"default";this.publishCustomStates()}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.dropToken++;this.resetDragSession()}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 effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get validationTarget(){return this.validationTargetOverride??this.baseEl}set validationTarget(next){this.validationTargetOverride=next??void 0;this.validityController.refreshAnchor()}[VALIDITY_ANCHOR](){return this.validationTarget??null}willUpdate(changed){super.willUpdate(changed);if(changed.has("multiple")){if(!this.multiple&&this._files.length>1)this.files=this._files;else this.syncFormValue()}}connectedCallback(){super.connectedCallback();this.syncThumbnailUrls();this.updateValidity();this.politeSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this});this.assertiveSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.dropToken++;this.resetDragSession();for(const thumbnail of this.thumbnailUrls.values())thumbnail.revoke();this.thumbnailUrls.clear();this.politeSink?.release();this.politeSink=void 0;this.assertiveSink?.release();this.assertiveSink=void 0;this.announcementsArmed=false;super.disconnectedCallback()}updated(changed){if(this.announcementsArmed){if(changed.has("dragState")||changed.has("resultStatus")){this.politeSink?.announce(this.statusText())}if(changed.has("rejectedFiles")&&this.rejectedFiles.length>0){this.assertiveSink?.announce(this.rejectedFiles.map(rejected=>this.rejectionMessage(rejected)).join(" "))}}this.announcementsArmed=true}syncFormValue(){if(!this.name||this._files.length===0){const state2=this.multiple?this.createFormData():this._files[0]??null;this.internals.setFormValue(null,state2);return}if(this.multiple){const submitted=this.createFormData();const state2=this.createFormData();if(!submitted||!state2){this.internals.setFormValue(null);return}for(const file2 of this._files){submitted.append(this.name,file2);state2.append("file",file2)}this.internals.setFormValue(submitted,state2);return}const file=this._files[0]??null;this.internals.setFormValue(file,file)}createFormData(){const FormDataCtor=this.ownerDocument?.defaultView?.FormData;return FormDataCtor?new FormDataCtor:null}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({})}else if(this.required&&this._files.length===0){this.validityController.setValidity({valueMissing:true},this.localize("fieldRequired"))}else{this.validityController.setValidity({})}this.publishCustomStates()}publishCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation});setCustomState(this.internals,"blank",this._files.length===0);setCustomState(this.internals,"dragging",this.dragging);this.toggleAttribute("dragging",this.dragging)}checkValidity(){return this.internals.checkValidity()}reportValidity(){this.touched=true;this.publishCustomStates();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.publishCustomStates()}resetValidity(){this.validityController.setCustomValidity("");this.updateValidity()}formResetCallback(){this.touched=false;this.files=[];this.rejectedFiles=[];this.resultStatus=""}formStateRestoreCallback(state2,reason){void reason;if(isFileValue(state2)){this.files=[state2];return}if(isFormDataValue(state2)){this.files=[...state2.values()].filter(isFileValue);return}this.files=[]}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;if(disabled){this.dropToken++;this.resetDragSession()}this.updateValidity();this.requestUpdate()}syncThumbnailUrls(){const urlApi=this.ownerDocument.defaultView?.URL??globalThis.URL;const canCreate=typeof urlApi.createObjectURL==="function";const canRevoke=typeof urlApi.revokeObjectURL==="function";let changed=false;for(const[file,thumbnail]of this.thumbnailUrls){if(!this._files.includes(file)||thumbnail.owner!==urlApi){thumbnail.revoke();this.thumbnailUrls.delete(file);changed=true}}if(canCreate){for(const file of this._files){if(!file.type.startsWith("image/")||this.thumbnailUrls.has(file))continue;const url=urlApi.createObjectURL(file);this.thumbnailUrls.set(file,{url,owner:urlApi,revoke:canRevoke?()=>urlApi.revokeObjectURL(url):()=>void 0});changed=true}}if(changed)this.requestUpdate()}get effectiveMaxFileSize(){const maxFileSize=this.maxFileSize;if(maxFileSize===0||maxFileSize===Infinity)return null;return finiteRange(maxFileSize>0?maxFileSize:NaN,DEFAULT_MAX_FILE_SIZE_BYTES,1)}isAllowed(file,isPreview=false){if(this.forbiddenMimeTypes.includes(file.type))return"type";if(this.allowedMimeTypes.length>0&&!this.allowedMimeTypes.includes(file.type))return"type";if(this.accept&&!matchesAccept(file,this.accept,isPreview))return"type";const maxFileSize=this.effectiveMaxFileSize;if(maxFileSize!==null&&file.size>maxFileSize)return"size";return"ok"}classify(fileList,isPreview=false){if(!this.multiple&&fileList.length>1){return{files:[],rejected:fileList.map(file=>({file,reason:"count"}))}}const files=[];const rejected=[];for(const f of fileList){const reason=this.isAllowed(f,isPreview);if(reason==="ok")files.push(f);else rejected.push({file:f,reason})}return{files,rejected}}rejectionMessage(rejected){const filename=rejected.file.name;switch(rejected.reason){case"type":return this.localize("fileInputRejectedType",void 0,{filename});case"size":return this.localize("fileInputRejectedSize",void 0,{filename});case"count":return this.localize("fileInputRejectedCount",void 0,{filename});case"directory":return this.localize("fileInputFolderRejected",void 0,{filename})}}emitFiles(fileList,additionalRejected=[]){const{files,rejected}=this.classify(fileList);rejected.push(...additionalRejected);this.rejectedFiles=rejected;const messages=[];const numberFormat=getNumberFormat(this.effectiveLocale);if(files.length){messages.push(this.localize(files.length===1?"fileInputAcceptedOne":"fileInputAcceptedMany",this.acceptedMessage==="{count} file(s) added."?void 0:this.acceptedMessage,{count:numberFormat.format(files.length)}))}if(rejected.length){messages.push(this.localize(rejected.length===1?"fileInputRejectedOne":"fileInputRejectedMany",this.rejectedMessage==="{count} file(s) rejected."?void 0:this.rejectedMessage,{count:numberFormat.format(rejected.length)}))}this.resultStatus=messages.join(" ");if(files.length){this.touched=true;this.files=this.multiple?[...this._files,...files]:files;dispatchNativeEvent(this,"input");dispatchNativeEvent(this,"change")}this.emit("lr-files",{files,rejected})}openPicker(){if(this.effectiveDisabled)return;this.inputEl?.click()}focus(options){this.baseEl?.focus(options)}blur(){this.baseEl?.blur()}click(){this.openPicker()}resetDragSession(){this.dragCounter=0;this.dragState="default";this.publishCustomStates()}previewState(fileList){const{rejected}=this.classify(fileList,true);return rejected.length>0?"reject":"accept"}readDroppedEntry(entry){if(entry.isFile){return new Promise(resolve=>{entry.file(file=>resolve([file]),()=>resolve([]))})}if(!entry.isDirectory)return Promise.resolve([]);const reader=entry.createReader();return new Promise(resolve=>{const files=[];const readBatch=()=>{reader.readEntries(entries=>{if(entries.length===0){resolve(files);return}void Promise.all(entries.map(child=>this.readDroppedEntry(child))).then(nested=>{files.push(...nested.flat());readBatch()})},()=>resolve(files))};readBatch()})}statusText(){if(this.dragState==="accept")return this.localize("dropzoneReleaseToAdd");if(this.dragState==="reject")return this.localize("dropzoneRejectedType");return this.resultStatus}get effectiveLabel(){return this.label||this.localize("fileInputDefaultLabel")}removeFile(index){if(this.effectiveDisabled||index<0||index>=this._files.length)return;this.touched=true;this.files=this._files.filter((_,candidate)=>candidate!==index);dispatchNativeEvent(this,"input");dispatchNativeEvent(this,"change")}fileSize(file){return formatFileSize(file.size,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),(value,fractionDigits)=>getNumberFormat(this.effectiveLocale,{minimumFractionDigits:fractionDigits,maximumFractionDigits:fractionDigits}).format(value))}renderFile(file,index){const thumbnail=this.thumbnailUrls.get(file)?.url;return html`<div part="file">
|
|
2
2
|
<span part="file-thumbnail" aria-hidden="true">
|
|
3
3
|
${thumbnail?html`<img part="file-image" src=${thumbnail} alt="" />`:html`<span part="file-icon">${fileIcon()}</span>`}
|
|
4
4
|
</span>
|