@aceshooting/lyra-ui 8.1.0 → 8.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +39 -0
- package/custom-elements.json +1 -1
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.d.ts +5 -0
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +1 -1
- package/dist/components/charts/chart/chart.class.js +1 -1
- package/dist/components/conversation/chat-composer/chat-composer.class.js +1 -1
- package/dist/components/conversation/model-select/model-select.class.js +1 -1
- package/dist/components/conversation/voice-picker/voice-picker.class.js +1 -1
- package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +4 -0
- package/dist/components/data/graph-query-builder/graph-query-builder.class.js +1 -1
- package/dist/components/forms/checkbox/checkbox.class.js +1 -1
- package/dist/components/forms/checkbox-group/checkbox-group.class.d.ts +3 -0
- package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
- package/dist/components/forms/code-editor/code-editor.class.js +1 -1
- package/dist/components/forms/combobox/combobox.class.js +1 -1
- package/dist/components/forms/date-picker/date-input.class.js +1 -1
- package/dist/components/forms/emoji-picker/emoji-picker.class.js +1 -1
- package/dist/components/forms/input/input.class.js +1 -1
- package/dist/components/forms/input/time-input.class.js +1 -1
- package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
- package/dist/components/forms/otp-input/otp-input.class.js +1 -1
- package/dist/components/forms/phone-input/phone-input.class.js +1 -1
- package/dist/components/forms/radio/radio-group.class.d.ts +3 -0
- package/dist/components/forms/radio/radio-group.class.js +1 -1
- package/dist/components/forms/rubric-form/rubric-form.class.d.ts +3 -0
- package/dist/components/forms/rubric-form/rubric-form.class.js +1 -1
- package/dist/components/forms/select/select.class.js +1 -1
- package/dist/components/forms/switch/switch.class.js +1 -1
- package/dist/components/forms/textarea/textarea.class.js +1 -1
- package/dist/components/forms/token-input/token-input.class.js +1 -1
- package/dist/components/media/file-input/file-input.class.js +1 -1
- package/dist/components/utility/known-date/known-date.class.js +1 -1
- package/dist/internal/form-associated.js +1 -1
- package/dist/internal/localization-runtime.d.ts +13 -0
- package/dist/internal/localization-runtime.js +1 -1
- package/dist/internal/lyra-element.d.ts +15 -0
- package/dist/internal/lyra-element.js +1 -1
- package/dist/internal/package-metadata.d.ts +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/testing/happy-dom-shims.d.ts +1 -1
- package/dist/testing/happy-dom-shims.js +1 -1
- package/llms/components/lr-checkbox-group.md +2 -0
- package/llms/components/lr-graph-query-builder.md +3 -1
- package/llms/components/lr-radio-group.md +3 -1
- package/llms/components/lr-rubric-form.md +2 -0
- package/llms/components/lr-tool-param-form.md +3 -0
- package/llms/peers.md +1 -1
- package/llms-full.txt +13 -2
- package/package.json +4 -4
- package/web-types.json +1 -1
|
@@ -221,6 +221,11 @@ export declare class LyraToolParamForm extends LyraElement<LyraToolParamFormEven
|
|
|
221
221
|
private firstInvalidField;
|
|
222
222
|
private get missingRequiredKeys();
|
|
223
223
|
private firstMissingPropertyError;
|
|
224
|
+
private focusFirstControl;
|
|
225
|
+
/** Forwards host clicks to the first rendered form field so the component behaves like a regular
|
|
226
|
+
* control from caller code and event re-dispatch paths.
|
|
227
|
+
*/
|
|
228
|
+
click(): void;
|
|
224
229
|
connectedCallback(): void;
|
|
225
230
|
disconnectedCallback(): void;
|
|
226
231
|
/** `value`, with any property missing from it filled in from `schema`'s own `default` — see the class doc. */
|
|
@@ -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{state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId}from"../../../internal/a11y.js";import{AnchoredValidityController,resolveValidityAnchor,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{styles}from"./tool-param-form.styles.js";import"../../forms/select/select.class.js";import"../../forms/combobox/option.class.js";import"../../forms/checkbox/checkbox.class.js";import{getListFormat}from"../../../internal/intl-cache.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldMustBeBoolean,LYRA_DEFAULT_fieldMustBeInteger,LYRA_DEFAULT_fieldMustBeNumber,LYRA_DEFAULT_fieldMustBeOneOf,LYRA_DEFAULT_fieldMustBeString,LYRA_DEFAULT_fieldMustEqual,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_restore,LYRA_DEFAULT_schemaMustBeObject,LYRA_DEFAULT_schemaPropertiesMustBeFlat,LYRA_DEFAULT_toolParamMissingProperty,LYRA_DEFAULT_unsupportedFieldType,LYRA_DEFAULT_valueMustBeSerializable}from"../../../internal/default-strings.generated.js";const EMPTY_SCHEMA={type:"object",properties:{}};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 LyraToolParamForm extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldMustBeBoolean:LYRA_DEFAULT_fieldMustBeBoolean,fieldMustBeInteger:LYRA_DEFAULT_fieldMustBeInteger,fieldMustBeNumber:LYRA_DEFAULT_fieldMustBeNumber,fieldMustBeOneOf:LYRA_DEFAULT_fieldMustBeOneOf,fieldMustBeString:LYRA_DEFAULT_fieldMustBeString,fieldMustEqual:LYRA_DEFAULT_fieldMustEqual,fieldRequired:LYRA_DEFAULT_fieldRequired,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore,schemaMustBeObject:LYRA_DEFAULT_schemaMustBeObject,schemaPropertiesMustBeFlat:LYRA_DEFAULT_schemaPropertiesMustBeFlat,toolParamMissingProperty:LYRA_DEFAULT_toolParamMissingProperty,unsupportedFieldType:LYRA_DEFAULT_unsupportedFieldType,valueMustBeSerializable:LYRA_DEFAULT_valueMustBeSerializable}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},name:{reflect:true,noAccessor:true},schema:{attribute:false,noAccessor:true},value:{attribute:false,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true}}}constructor(){super();this._errors={};this._formError="";this.showFormError=false;this.touchedFields=new Set;this.baseId=nextId("tool-param-form");this._fieldsetDisabled=false;this._name="";this._schema=EMPTY_SCHEMA;this._value={};this._effectiveValue={};this._validityFlags={};this._disabled=false;this.hasInteracted=false;this.visibleErrorSnapshot=new Map;this.suppressNextErrorAnnouncement=true;this.stopNestedControlEvent=e=>{e.stopPropagation()};this.onFieldFocus=()=>{this.emit("focus")};this.onFieldBlur=()=>{this.emit("blur")};this.internals=createInternalsSafely(this);this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);installInvalidEventAlias(this,()=>this.emit("lr-invalid"));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](){const field=this.firstInvalidField();if(field){const input=field.querySelector("input.control");if(input)return input;for(const child of field.children){const anchor=resolveValidityAnchor(child);if(anchor)return anchor}}return this.firstMissingPropertyError()}firstInvalidField(){if(!this.renderRoot)return void 0;const fields=Array.from(this.renderRoot.querySelectorAll('[part="field"]'));for(const key of Object.keys(this._errors)){const field=fields.find(candidate=>candidate.dataset["key"]===key);if(field)return field}return void 0}get missingRequiredKeys(){const properties=this.schemaProperties;return this.requiredKeys.filter(key=>!Object.prototype.hasOwnProperty.call(properties,key)&&Boolean(this._errors[key]))}firstMissingPropertyError(){if(!this.renderRoot)return void 0;const errors=Array.from(this.renderRoot.querySelectorAll('[part="error"][data-missing-property]'));for(const key of Object.keys(this._errors)){const error=errors.find(candidate=>candidate.dataset["key"]===key);if(error)return error}return void 0}connectedCallback(){super.connectedCallback();if(this.errorAnnouncementSink?.element.ownerDocument!==this.ownerDocument){this.errorAnnouncementSink?.release();this.errorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}if(this.hasUpdated){this.suppressNextErrorAnnouncement=true;this.requestUpdate()}this.syncFormState()}disconnectedCallback(){super.disconnectedCallback();this.errorAnnouncementSink?.release();this.errorAnnouncementSink=void 0;this.suppressNextErrorAnnouncement=true}get effectiveValue(){return{...this._effectiveValue}}get schemaProperties(){const properties=this.schema?.properties;return properties!==null&&typeof properties==="object"&&!Array.isArray(properties)?properties:{}}get requiredKeys(){const required=this.schema?.required;return Array.isArray(required)?required.filter(key=>typeof key==="string"):[]}resolveEffectiveValue(){const props=this.schemaProperties;const out={...this.value};for(const[key,prop]of Object.entries(props)){if(!Object.prototype.hasOwnProperty.call(this.value,key)&&prop.default!==void 0){Object.defineProperty(out,key,{configurable:true,enumerable:true,writable:true,value:prop.default})}}return out}get schema(){return this._schema}set schema(next){const old=this._schema;this._schema=next??EMPTY_SCHEMA;this.syncFormState();this.requestUpdate("schema",old)}get value(){return this._value}set value(next){const old=this._value;this._value=next??{};this.syncFormState();this.requestUpdate("value",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 disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);this.applyValidity();this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get errors(){return{...this._errors}}get formError(){return this._formError}computeValidation(effective){const props=this.schemaProperties;const required=new Set(this.requiredKeys);const out={};const flags={};const addError=(key,message)=>{Object.defineProperty(out,key,{configurable:true,enumerable:true,writable:true,value:message})};for(const[key,prop]of Object.entries(props)){const type=prop?.type;if(type!=="string"&&type!=="number"&&type!=="integer"&&type!=="boolean"){addError(key,this.localize("unsupportedFieldType",void 0,{type:String(type)}));flags.customError=true;continue}const present=Object.prototype.hasOwnProperty.call(effective,key)&&effective[key]!==void 0;if(!present){if(required.has(key)){addError(key,this.localize("fieldRequired"));flags.valueMissing=true}continue}const v=effective[key];if(type==="string"&&typeof v!=="string"){addError(key,this.localize("fieldMustBeString"));flags.typeMismatch=true;continue}if(type==="number"&&(typeof v!=="number"||!Number.isFinite(v))){addError(key,this.localize("fieldMustBeNumber"));flags.typeMismatch=true;continue}if(type==="integer"&&(typeof v!=="number"||!Number.isFinite(v))){addError(key,this.localize("fieldMustBeInteger"));flags.typeMismatch=true;continue}if(type==="integer"&&!Number.isInteger(v)){addError(key,this.localize("fieldMustBeInteger"));flags.stepMismatch=true;continue}if(type==="boolean"&&typeof v!=="boolean"){addError(key,this.localize("fieldMustBeBoolean"));flags.typeMismatch=true;continue}if(type==="string"&&Array.isArray(prop.enum)&&!prop.enum.includes(v)){addError(key,this.localize("fieldMustBeOneOf",void 0,{values:getListFormat(this.effectiveLocale,{style:"long",type:"disjunction"}).format(prop.enum)}));flags.customError=true;continue}if(prop.const!==void 0&&v!==prop.const){addError(key,this.localize("fieldMustEqual",void 0,{value:JSON.stringify(prop.const)}));flags.customError=true}}for(const key of required){if(Object.prototype.hasOwnProperty.call(props,key))continue;if(!Object.prototype.hasOwnProperty.call(effective,key)||effective[key]===void 0){addError(key,this.localize("fieldRequired"));flags.valueMissing=true}}return{errors:out,flags}}checkValidity(){this.syncFormState();return this.internals.checkValidity()}reportValidity(){this.hasInteracted=true;this.syncFormState();if(Object.keys(this._errors).length>0){this.touchedFields=new Set([...this.touchedFields,...Object.keys(this._errors)])}if(this._formError)this.showFormError=true;const valid=this.internals.reportValidity();if(!valid&&!this.firstInvalidField()&&this.missingRequiredKeys.length>0){void this.updateComplete.then(()=>{const error=this.firstMissingPropertyError();this.validityController.refreshAnchor();error?.focus()})}return valid}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.syncValidityCustomStates()}formResetCallback(){this.hasInteracted=false;this.value={};this.touchedFields=new Set;this.showFormError=false}formStateRestoreCallback(state2,_mode){let restored={};if(typeof state2==="string"){try{const parsed=JSON.parse(state2);if(parsed!==null&&typeof parsed==="object"&&!Array.isArray(parsed)){restored=parsed}}catch{}}this.value=restored}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;this.applyValidity();this.requestUpdate()}schemaShapeError(){const schema=this.schema;if(schema===null||typeof schema!=="object"||schema.type!=="object"){return this.localize("schemaMustBeObject")}const properties=schema.properties;if(properties===null||typeof properties!=="object"||Array.isArray(properties)){return this.localize("schemaPropertiesMustBeFlat")}return""}serializeEffectiveValue(effective){const serialized=JSON.stringify(effective,(_key,value)=>{if(typeof value==="number"&&!Number.isFinite(value)){throw new TypeError("Non-finite numbers are not JSON values.")}return value});if(typeof serialized!=="string")throw new TypeError("Value did not serialize to JSON.");return serialized}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}syncInternals(formValue){this.internals.setFormValue(formValue,formValue);this.applyValidity()}applyValidity(){if(!this.validityController)return;if(this.barredFromValidation||Object.keys(this._validityFlags).length===0){this.validityController.setValidity({})}else{const firstMessage=Object.values(this._errors)[0]??this._formError;this.validityController.setValidity(this._validityFlags,firstMessage)}this.syncValidityCustomStates()}syncValidityCustomStates(){syncValidityStates(this.internals,{required:this.requiredKeys.length>0,hasInteracted:this.hasInteracted,barred:this.barredFromValidation})}syncFormState(){let effective={};let errors={};let flags={};let formError="";let formValue=null;try{formError=this.schemaShapeError();effective=this.resolveEffectiveValue();const validation=this.computeValidation(effective);errors=validation.errors;flags=validation.flags;formValue=this.serializeEffectiveValue(effective)}catch{formError=this.localize("valueMustBeSerializable");formValue=null}if(formError){flags.customError=true;formValue=null}this._effectiveValue=effective;if(JSON.stringify(this._errors)!==JSON.stringify(errors))this._errors=errors;this._formError=formError;this._validityFlags=flags;this.syncInternals(formValue)}updated(changed){if(changed.has("value")||changed.has("schema")||changed.has("_errors")||changed.has("_formError")){const valid=Object.keys(this._errors).length===0&&this._formError==="";const key=JSON.stringify({valid,errors:this._errors,formError:this._formError});if(key!==this.lastValidityKey){this.lastValidityKey=key;this.emit("lr-validity-change",{valid,errors:{...this._errors}})}const nestedUpdates=Array.from(this.firstInvalidField()?.children??[]).filter(element=>typeof element[VALIDITY_ANCHOR]==="function").map(element=>element.updateComplete).filter(update=>update!==void 0);if(nestedUpdates.length>0){void Promise.all(nestedUpdates).then(()=>this.validityController.refreshAnchor())}}const currentErrors=new Map;for(const node of this.renderRoot.querySelectorAll('[part="error"]')){const fieldKey=node.closest('[part~="field"]')?.dataset["key"];const key=node.dataset["key"]??fieldKey??"form";const text=node.textContent?.trim()??"";if(text)currentErrors.set(key,text)}if(!this.suppressNextErrorAnnouncement){const freshMessages=[];for(const[key,text]of currentErrors){if(this.visibleErrorSnapshot.get(key)!==text&&!freshMessages.includes(text)){freshMessages.push(text)}}if(freshMessages.length>0)this.errorAnnouncementSink?.announce(freshMessages.join(" "))}this.visibleErrorSnapshot=currentErrors;this.suppressNextErrorAnnouncement=false}setFieldValue(key,val){if(this.effectiveDisabled)return;this.hasInteracted=true;this.value={...this.value,[key]:val};this.emit("lr-input",{value:this.effectiveValue})}markTouched(key){this.hasInteracted=true;this.syncValidityCustomStates();if(this.touchedFields.has(key))return;this.touchedFields=new Set(this.touchedFields).add(key)}onTextInput(key,e){this.setFieldValue(key,e.target.value)}onNumberInput(key,e){const raw=e.target;const n=raw.valueAsNumber;this.setFieldValue(key,Number.isNaN(n)?void 0:n)}onSelectChange(key,e){e.stopPropagation();this.setFieldValue(key,e.target.value)}onCheckboxChange(key,e){e.stopPropagation();this.setFieldValue(key,e.detail.checked)}renderControl(key,prop,fieldId,label,required,describedBy,errorMessage,effective){if(prop.type==="string"&&prop.enum&&prop.enum.length>0){return html`<lr-select
|
|
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{state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId}from"../../../internal/a11y.js";import{AnchoredValidityController,resolveValidityAnchor,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{styles}from"./tool-param-form.styles.js";import"../../forms/select/select.class.js";import"../../forms/combobox/option.class.js";import"../../forms/checkbox/checkbox.class.js";import{getListFormat}from"../../../internal/intl-cache.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldMustBeBoolean,LYRA_DEFAULT_fieldMustBeInteger,LYRA_DEFAULT_fieldMustBeNumber,LYRA_DEFAULT_fieldMustBeOneOf,LYRA_DEFAULT_fieldMustBeString,LYRA_DEFAULT_fieldMustEqual,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_restore,LYRA_DEFAULT_schemaMustBeObject,LYRA_DEFAULT_schemaPropertiesMustBeFlat,LYRA_DEFAULT_toolParamMissingProperty,LYRA_DEFAULT_unsupportedFieldType,LYRA_DEFAULT_valueMustBeSerializable}from"../../../internal/default-strings.generated.js";const EMPTY_SCHEMA={type:"object",properties:{}};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 LyraToolParamForm extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldMustBeBoolean:LYRA_DEFAULT_fieldMustBeBoolean,fieldMustBeInteger:LYRA_DEFAULT_fieldMustBeInteger,fieldMustBeNumber:LYRA_DEFAULT_fieldMustBeNumber,fieldMustBeOneOf:LYRA_DEFAULT_fieldMustBeOneOf,fieldMustBeString:LYRA_DEFAULT_fieldMustBeString,fieldMustEqual:LYRA_DEFAULT_fieldMustEqual,fieldRequired:LYRA_DEFAULT_fieldRequired,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore,schemaMustBeObject:LYRA_DEFAULT_schemaMustBeObject,schemaPropertiesMustBeFlat:LYRA_DEFAULT_schemaPropertiesMustBeFlat,toolParamMissingProperty:LYRA_DEFAULT_toolParamMissingProperty,unsupportedFieldType:LYRA_DEFAULT_unsupportedFieldType,valueMustBeSerializable:LYRA_DEFAULT_valueMustBeSerializable}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},name:{reflect:true,noAccessor:true},schema:{attribute:false,noAccessor:true},value:{attribute:false,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true}}}constructor(){super();this._errors={};this._formError="";this.showFormError=false;this.touchedFields=new Set;this.baseId=nextId("tool-param-form");this._fieldsetDisabled=false;this._name="";this._schema=EMPTY_SCHEMA;this._value={};this._effectiveValue={};this._validityFlags={};this._disabled=false;this.hasInteracted=false;this.visibleErrorSnapshot=new Map;this.suppressNextErrorAnnouncement=true;this.stopNestedControlEvent=e=>{e.stopPropagation()};this.onFieldFocus=()=>{this.emit("focus")};this.onFieldBlur=()=>{this.emit("blur")};this.internals=createInternalsSafely(this);this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);installInvalidEventAlias(this,()=>this.emit("lr-invalid"));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](){const field=this.firstInvalidField();if(field){const input=field.querySelector("input.control");if(input)return input;for(const child of field.children){const anchor=resolveValidityAnchor(child);if(anchor)return anchor}}return this.firstMissingPropertyError()}firstInvalidField(){if(!this.renderRoot)return void 0;const fields=Array.from(this.renderRoot.querySelectorAll('[part="field"]'));for(const key of Object.keys(this._errors)){const field=fields.find(candidate=>candidate.dataset["key"]===key);if(field)return field}return void 0}get missingRequiredKeys(){const properties=this.schemaProperties;return this.requiredKeys.filter(key=>!Object.prototype.hasOwnProperty.call(properties,key)&&Boolean(this._errors[key]))}firstMissingPropertyError(){if(!this.renderRoot)return void 0;const errors=Array.from(this.renderRoot.querySelectorAll('[part="error"][data-missing-property]'));for(const key of Object.keys(this._errors)){const error=errors.find(candidate=>candidate.dataset["key"]===key);if(error)return error}return void 0}focusFirstControl(){if(!this.renderRoot)return;const firstField=this.renderRoot.querySelector('[part="field"]');if(!firstField)return;const control=firstField.querySelector("input.control")||firstField.querySelector("lr-select")||firstField.querySelector("lr-checkbox");control?.focus()}click(){if(this.effectiveDisabled)return;this.focusFirstControl()}connectedCallback(){super.connectedCallback();if(this.errorAnnouncementSink?.element.ownerDocument!==this.ownerDocument){this.errorAnnouncementSink?.release();this.errorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}if(this.hasUpdated){this.suppressNextErrorAnnouncement=true;this.requestUpdate()}this.syncFormState()}disconnectedCallback(){super.disconnectedCallback();this.errorAnnouncementSink?.release();this.errorAnnouncementSink=void 0;this.suppressNextErrorAnnouncement=true}get effectiveValue(){return{...this._effectiveValue}}get schemaProperties(){const properties=this.schema?.properties;return properties!==null&&typeof properties==="object"&&!Array.isArray(properties)?properties:{}}get requiredKeys(){const required=this.schema?.required;return Array.isArray(required)?required.filter(key=>typeof key==="string"):[]}resolveEffectiveValue(){const props=this.schemaProperties;const out={...this.value};for(const[key,prop]of Object.entries(props)){if(!Object.prototype.hasOwnProperty.call(this.value,key)&&prop.default!==void 0){Object.defineProperty(out,key,{configurable:true,enumerable:true,writable:true,value:prop.default})}}return out}get schema(){return this._schema}set schema(next){const old=this._schema;this._schema=next??EMPTY_SCHEMA;this.syncFormState();this.requestUpdate("schema",old)}get value(){return this._value}set value(next){const old=this._value;this._value=next??{};this.syncFormState();this.requestUpdate("value",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 disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);this.applyValidity();this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get errors(){return{...this._errors}}get formError(){return this._formError}computeValidation(effective){const props=this.schemaProperties;const required=new Set(this.requiredKeys);const out={};const flags={};const addError=(key,message)=>{Object.defineProperty(out,key,{configurable:true,enumerable:true,writable:true,value:message})};for(const[key,prop]of Object.entries(props)){const type=prop?.type;if(type!=="string"&&type!=="number"&&type!=="integer"&&type!=="boolean"){addError(key,this.localize("unsupportedFieldType",void 0,{type:String(type)}));flags.customError=true;continue}const present=Object.prototype.hasOwnProperty.call(effective,key)&&effective[key]!==void 0;if(!present){if(required.has(key)){addError(key,this.localize("fieldRequired"));flags.valueMissing=true}continue}const v=effective[key];if(type==="string"&&typeof v!=="string"){addError(key,this.localize("fieldMustBeString"));flags.typeMismatch=true;continue}if(type==="number"&&(typeof v!=="number"||!Number.isFinite(v))){addError(key,this.localize("fieldMustBeNumber"));flags.typeMismatch=true;continue}if(type==="integer"&&(typeof v!=="number"||!Number.isFinite(v))){addError(key,this.localize("fieldMustBeInteger"));flags.typeMismatch=true;continue}if(type==="integer"&&!Number.isInteger(v)){addError(key,this.localize("fieldMustBeInteger"));flags.stepMismatch=true;continue}if(type==="boolean"&&typeof v!=="boolean"){addError(key,this.localize("fieldMustBeBoolean"));flags.typeMismatch=true;continue}if(type==="string"&&Array.isArray(prop.enum)&&!prop.enum.includes(v)){addError(key,this.localize("fieldMustBeOneOf",void 0,{values:getListFormat(this.effectiveLocale,{style:"long",type:"disjunction"}).format(prop.enum)}));flags.customError=true;continue}if(prop.const!==void 0&&v!==prop.const){addError(key,this.localize("fieldMustEqual",void 0,{value:JSON.stringify(prop.const)}));flags.customError=true}}for(const key of required){if(Object.prototype.hasOwnProperty.call(props,key))continue;if(!Object.prototype.hasOwnProperty.call(effective,key)||effective[key]===void 0){addError(key,this.localize("fieldRequired"));flags.valueMissing=true}}return{errors:out,flags}}checkValidity(){this.syncFormState();return this.internals.checkValidity()}reportValidity(){this.hasInteracted=true;this.syncFormState();if(Object.keys(this._errors).length>0){this.touchedFields=new Set([...this.touchedFields,...Object.keys(this._errors)])}if(this._formError)this.showFormError=true;const valid=this.internals.reportValidity();if(!valid&&!this.firstInvalidField()&&this.missingRequiredKeys.length>0){void this.updateComplete.then(()=>{const error=this.firstMissingPropertyError();this.validityController.refreshAnchor();error?.focus()})}return valid}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.syncValidityCustomStates()}formResetCallback(){this.hasInteracted=false;this.value={};this.touchedFields=new Set;this.showFormError=false}formStateRestoreCallback(state2,_mode){let restored={};if(typeof state2==="string"){try{const parsed=JSON.parse(state2);if(parsed!==null&&typeof parsed==="object"&&!Array.isArray(parsed)){restored=parsed}}catch{}}this.value=restored}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;this.applyValidity();this.requestUpdate()}schemaShapeError(){const schema=this.schema;if(schema===null||typeof schema!=="object"||schema.type!=="object"){return this.localize("schemaMustBeObject")}const properties=schema.properties;if(properties===null||typeof properties!=="object"||Array.isArray(properties)){return this.localize("schemaPropertiesMustBeFlat")}return""}serializeEffectiveValue(effective){const serialized=JSON.stringify(effective,(_key,value)=>{if(typeof value==="number"&&!Number.isFinite(value)){throw new TypeError("Non-finite numbers are not JSON values.")}return value});if(typeof serialized!=="string")throw new TypeError("Value did not serialize to JSON.");return serialized}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}syncInternals(formValue){this.internals.setFormValue(formValue,formValue);this.applyValidity()}applyValidity(){if(!this.validityController)return;if(this.barredFromValidation||Object.keys(this._validityFlags).length===0){this.validityController.setValidity({})}else{const firstMessage=Object.values(this._errors)[0]??this._formError;this.validityController.setValidity(this._validityFlags,firstMessage)}this.syncValidityCustomStates()}syncValidityCustomStates(){syncValidityStates(this.internals,{required:this.requiredKeys.length>0,hasInteracted:this.hasInteracted,barred:this.barredFromValidation})}syncFormState(){let effective={};let errors={};let flags={};let formError="";let formValue=null;try{formError=this.schemaShapeError();effective=this.resolveEffectiveValue();const validation=this.computeValidation(effective);errors=validation.errors;flags=validation.flags;formValue=this.serializeEffectiveValue(effective)}catch{formError=this.localize("valueMustBeSerializable");formValue=null}if(formError){flags.customError=true;formValue=null}this._effectiveValue=effective;if(JSON.stringify(this._errors)!==JSON.stringify(errors))this._errors=errors;this._formError=formError;this._validityFlags=flags;this.syncInternals(formValue)}updated(changed){if(changed.has("value")||changed.has("schema")||changed.has("_errors")||changed.has("_formError")){const valid=Object.keys(this._errors).length===0&&this._formError==="";const key=JSON.stringify({valid,errors:this._errors,formError:this._formError});if(key!==this.lastValidityKey){this.lastValidityKey=key;this.emit("lr-validity-change",{valid,errors:{...this._errors}})}const nestedUpdates=Array.from(this.firstInvalidField()?.children??[]).filter(element=>typeof element[VALIDITY_ANCHOR]==="function").map(element=>element.updateComplete).filter(update=>update!==void 0);if(nestedUpdates.length>0){void Promise.all(nestedUpdates).then(()=>this.validityController.refreshAnchor())}}const currentErrors=new Map;for(const node of this.renderRoot.querySelectorAll('[part="error"]')){const fieldKey=node.closest('[part~="field"]')?.dataset["key"];const key=node.dataset["key"]??fieldKey??"form";const text=node.textContent?.trim()??"";if(text)currentErrors.set(key,text)}if(!this.suppressNextErrorAnnouncement){const freshMessages=[];for(const[key,text]of currentErrors){if(this.visibleErrorSnapshot.get(key)!==text&&!freshMessages.includes(text)){freshMessages.push(text)}}if(freshMessages.length>0)this.errorAnnouncementSink?.announce(freshMessages.join(" "))}this.visibleErrorSnapshot=currentErrors;this.suppressNextErrorAnnouncement=false}setFieldValue(key,val){if(this.effectiveDisabled)return;this.hasInteracted=true;this.value={...this.value,[key]:val};this.emit("lr-input",{value:this.effectiveValue})}markTouched(key){this.hasInteracted=true;this.syncValidityCustomStates();if(this.touchedFields.has(key))return;this.touchedFields=new Set(this.touchedFields).add(key)}onTextInput(key,e){this.setFieldValue(key,e.target.value)}onNumberInput(key,e){const raw=e.target;const n=raw.valueAsNumber;this.setFieldValue(key,Number.isNaN(n)?void 0:n)}onSelectChange(key,e){e.stopPropagation();this.setFieldValue(key,e.target.value)}onCheckboxChange(key,e){e.stopPropagation();this.setFieldValue(key,e.detail.checked)}renderControl(key,prop,fieldId,label,required,describedBy,errorMessage,effective){if(prop.type==="string"&&prop.enum&&prop.enum.length>0){return html`<lr-select
|
|
2
2
|
id=${fieldId}
|
|
3
3
|
.label=${label}
|
|
4
4
|
.hint=${prop.description??""}
|
|
@@ -92,4 +92,4 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
92
92
|
${this.hasCustomDataTable()?nothing:this.renderDataTable()}
|
|
93
93
|
</div>
|
|
94
94
|
</div>
|
|
95
|
-
`}get showsLegend(){return this.legend&&!this.withoutLegend}}__decorate([property({converter:{fromAttribute:value=>normalizeChartType(value)}})],LyraChart.prototype,"type",void 0);__decorate([property({attribute:false})],LyraChart.prototype,"labels",void 0);__decorate([property({attribute:false})],LyraChart.prototype,"datasets",void 0);__decorate([property({type:Boolean})],LyraChart.prototype,"legend",void 0);__decorate([property()],LyraChart.prototype,"description",void 0);__decorate([property()],LyraChart.prototype,"grid",void 0);__decorate([property({attribute:"index-axis"})],LyraChart.prototype,"indexAxis",void 0);__decorate([property()],LyraChart.prototype,"label",void 0);__decorate([property({attribute:"legend-position"})],LyraChart.prototype,"legendPosition",void 0);__decorate([property({type:Number})],LyraChart.prototype,"max",void 0);__decorate([property({type:Number})],LyraChart.prototype,"min",void 0);__decorate([property({type:Array})],LyraChart.prototype,"plugins",void 0);__decorate([property({attribute:false})],LyraChart.prototype,"valueFormatter",void 0);__decorate([property({type:Boolean})],LyraChart.prototype,"area",void 0);__decorate([property({type:Boolean})],LyraChart.prototype,"zoom",void 0);__decorate([property()],LyraChart.prototype,"height",void 0);__decorate([property({attribute:"x-label"})],LyraChart.prototype,"xLabel",void 0);__decorate([property({attribute:"y-label"})],LyraChart.prototype,"yLabel",void 0);__decorate([property({attribute:"y2-label"})],LyraChart.prototype,"y2Label",void 0);__decorate([property({type:Boolean,attribute:"begin-at-zero",converter:trueDefaultBooleanConverter})],LyraChart.prototype,"beginAtZero",void 0);__decorate([property({attribute:"accessible-label"})],LyraChart.prototype,"accessibleLabel",void 0);__decorate([property({attribute:"accessible-description"})],LyraChart.prototype,"accessibleDescription",void 0);__decorate([property({type:Boolean,attribute:"show-data-table"})],LyraChart.prototype,"showDataTable",void 0);__decorate([property({type:Boolean})],LyraChart.prototype,"horizontal",void 0);__decorate([property({type:Boolean})],LyraChart.prototype,"stacked",void 0);__decorate([property({type:Boolean,attribute:"without-animation",reflect:true})],LyraChart.prototype,"withoutAnimation",void 0);__decorate([property({type:Boolean,attribute:"without-legend",reflect:true})],LyraChart.prototype,"withoutLegend",void 0);__decorate([property({type:Boolean,attribute:"without-tooltip",reflect:true})],LyraChart.prototype,"withoutTooltip",void 0);__decorate([property({type:Boolean,attribute:"data-labels"})],LyraChart.prototype,"dataLabels",void 0);__decorate([property({type:Boolean,attribute:"stack-totals"})],LyraChart.prototype,"stackTotals",void 0);__decorate([property({attribute:false})],LyraChart.prototype,"config",void 0);__decorate([state()],LyraChart.prototype,"slottedConfig",void 0);__decorate([state()],LyraChart.prototype,"loading",void 0);__decorate([state()],LyraChart.prototype,"loadFailed",void 0);__decorate([state()],LyraChart.prototype,"zoomed",void 0);__decorate([state()],LyraChart.prototype,"visible",void 0);__decorate([query("canvas")],LyraChart.prototype,"canvasEl",void 0);__decorate([state()],LyraChart.prototype,"autoLegendPosition",void 0);__decorate([state()],LyraChart.prototype,"keyboardDatumAnnouncement",void 0);function lockChartType(ctor,value){Object.defineProperty(ctor.prototype,"type",{configurable:true,enumerable:true,get(){return value},set(_v){}})}export{LyraChart,lockChartType,seriesPalette2 as seriesPalette};
|
|
95
|
+
`}get showsLegend(){return this.legend&&!this.withoutLegend}}__decorate([property({converter:{fromAttribute:value=>normalizeChartType(value)}})],LyraChart.prototype,"type",void 0);__decorate([property({attribute:false})],LyraChart.prototype,"labels",void 0);__decorate([property({attribute:false})],LyraChart.prototype,"datasets",void 0);__decorate([property({type:Boolean,converter:trueDefaultBooleanConverter})],LyraChart.prototype,"legend",void 0);__decorate([property()],LyraChart.prototype,"description",void 0);__decorate([property()],LyraChart.prototype,"grid",void 0);__decorate([property({attribute:"index-axis"})],LyraChart.prototype,"indexAxis",void 0);__decorate([property()],LyraChart.prototype,"label",void 0);__decorate([property({attribute:"legend-position"})],LyraChart.prototype,"legendPosition",void 0);__decorate([property({type:Number})],LyraChart.prototype,"max",void 0);__decorate([property({type:Number})],LyraChart.prototype,"min",void 0);__decorate([property({type:Array})],LyraChart.prototype,"plugins",void 0);__decorate([property({attribute:false})],LyraChart.prototype,"valueFormatter",void 0);__decorate([property({type:Boolean})],LyraChart.prototype,"area",void 0);__decorate([property({type:Boolean})],LyraChart.prototype,"zoom",void 0);__decorate([property()],LyraChart.prototype,"height",void 0);__decorate([property({attribute:"x-label"})],LyraChart.prototype,"xLabel",void 0);__decorate([property({attribute:"y-label"})],LyraChart.prototype,"yLabel",void 0);__decorate([property({attribute:"y2-label"})],LyraChart.prototype,"y2Label",void 0);__decorate([property({type:Boolean,attribute:"begin-at-zero",converter:trueDefaultBooleanConverter})],LyraChart.prototype,"beginAtZero",void 0);__decorate([property({attribute:"accessible-label"})],LyraChart.prototype,"accessibleLabel",void 0);__decorate([property({attribute:"accessible-description"})],LyraChart.prototype,"accessibleDescription",void 0);__decorate([property({type:Boolean,attribute:"show-data-table"})],LyraChart.prototype,"showDataTable",void 0);__decorate([property({type:Boolean})],LyraChart.prototype,"horizontal",void 0);__decorate([property({type:Boolean})],LyraChart.prototype,"stacked",void 0);__decorate([property({type:Boolean,attribute:"without-animation",reflect:true})],LyraChart.prototype,"withoutAnimation",void 0);__decorate([property({type:Boolean,attribute:"without-legend",reflect:true})],LyraChart.prototype,"withoutLegend",void 0);__decorate([property({type:Boolean,attribute:"without-tooltip",reflect:true})],LyraChart.prototype,"withoutTooltip",void 0);__decorate([property({type:Boolean,attribute:"data-labels"})],LyraChart.prototype,"dataLabels",void 0);__decorate([property({type:Boolean,attribute:"stack-totals"})],LyraChart.prototype,"stackTotals",void 0);__decorate([property({attribute:false})],LyraChart.prototype,"config",void 0);__decorate([state()],LyraChart.prototype,"slottedConfig",void 0);__decorate([state()],LyraChart.prototype,"loading",void 0);__decorate([state()],LyraChart.prototype,"loadFailed",void 0);__decorate([state()],LyraChart.prototype,"zoomed",void 0);__decorate([state()],LyraChart.prototype,"visible",void 0);__decorate([query("canvas")],LyraChart.prototype,"canvasEl",void 0);__decorate([state()],LyraChart.prototype,"autoLegendPosition",void 0);__decorate([state()],LyraChart.prototype,"keyboardDatumAnnouncement",void 0);function lockChartType(ctor,value){Object.defineProperty(ctor.prototype,"type",{configurable:true,enumerable:true,get(){return value},set(_v){}})}export{LyraChart,lockChartType,seriesPalette2 as seriesPalette};
|
|
@@ -21,7 +21,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
21
21
|
aria-hidden="true"
|
|
22
22
|
focusable="false"
|
|
23
23
|
><rect x="6" y="6" width="12" height="12" rx="1.5"></rect></svg>
|
|
24
|
-
`}class LyraChatComposerBase extends LyraElement{}class LyraChatComposer extends FormAssociated(LyraChatComposerBase){static{this.defaultStrings={...super.defaultStrings,composerLabel:LYRA_DEFAULT_composerLabel,fieldRequired:LYRA_DEFAULT_fieldRequired,restore:LYRA_DEFAULT_restore,sendMessage:LYRA_DEFAULT_sendMessage,stopGenerating:LYRA_DEFAULT_stopGenerating}}static{this.styles=[LyraElement.styles,styles]}get effectiveMinRows(){return finiteInteger(this.minRows,1,1)}get effectiveMaxRows(){return Math.max(this.effectiveMinRows,finiteInteger(this.maxRows,this.effectiveMinRows,1))}constructor(){super();this.placeholder="";this.minRows=1;this.maxRows=8;this.status="idle";this.frame="card";this.submitOnEnter=true;this.submitDisabled=false;this.stoppable=true;this.accessibleLabel=null;this.spellcheck=true;this.autocapitalize="";this.autoCorrect="";this.wrap="soft";this.autocomplete="";this.inputMode="";this.enterKeyHint="";this.hasLeadingSlot=false;this.hasChipsSlot=false;this.hasTrailingSlot=false;this.touched=false;this.textareaResizeGeneration=0;this.onTextareaInput=e=>{this.value=e.target.value;this.emit("lr-input",{value:this.value})};this.onTextareaKeyDown=e=>{if(e.key!=="Enter")return;if(e.shiftKey)return;if(!this.submitOnEnter)return;if(e.isComposing||e.keyCode===229)return;if(this.status!=="idle")return;e.preventDefault();this.submit()};this.onActionClick=()=>{if(this.effectiveDisabled)return;if(this.status==="idle"){this.submit()}else if(this.stoppable){this.emit("lr-stop")}};this.onLeadingSlotChange=e=>{this.hasLeadingSlot=e.target.assignedElements({flatten:true}).length>0};this.onChipsSlotChange=e=>{this.hasChipsSlot=e.target.assignedElements({flatten:true}).length>0};this.onTrailingSlotChange=e=>{this.hasTrailingSlot=e.target.assignedElements({flatten:true}).length>0};this.onTextareaBlur=()=>{this.touched=true;this.emit("blur")};this.onTextareaFocus=()=>{this.emit("focus")};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"}focus(options){this.textareaEl?.focus(options)}blur(){this.textareaEl?.blur()}click(){if(!this.effectiveDisabled)this.textareaEl?.focus()}select(){this.textareaEl?.select()}setSelectionRange(start,end,direction){this.textareaEl?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){const textarea=this.textareaEl;if(!textarea)return;if(start===void 0||end===void 0){textarea.setRangeText(replacement)}else{textarea.setRangeText(replacement,start,end,selectMode)}this.value=textarea.value;this.resizeTextarea()}willUpdate(changed){super.willUpdate(changed);this.seedFirstRenderState(()=>{this.hasLeadingSlot=this.hasSlotted("leading");this.hasChipsSlot=this.hasSlotted("chips");this.hasTrailingSlot=this.hasSlotted("trailing")})}firstUpdated(changed){super.firstUpdated(changed);this.resizeTextarea();this.armTextareaResizeObserver()}connectedCallback(){super.connectedCallback();if(this.hasUpdated){this.armTextareaResizeObserver();this.resizeTextarea()}}disconnectedCallback(){super.disconnectedCallback();this.resetTextareaResizeWork()}adoptedCallback(){this.resetTextareaResizeWork()}updated(changed){super.updated(changed);if(changed.has("value")||changed.has("minRows")||changed.has("maxRows")){this.resizeTextarea()}}formResetCallback(){super.formResetCallback();this.touched=false}hasSlotted(name){return Array.from(this.children).some(el=>el.getAttribute("slot")===name)}resizeTextarea(){const ta=this.textareaEl;if(!ta)return;const cs=this.ownerDocument.defaultView?.getComputedStyle(ta)??ta.style;const lineHeight=parseFloat(cs.lineHeight)||parseFloat(cs.fontSize)*1.2;const paddingBlock=parseFloat(cs.paddingTop)+parseFloat(cs.paddingBottom);const borderBlock=parseFloat(cs.borderTopWidth)+parseFloat(cs.borderBottomWidth);const minRows=this.effectiveMinRows;const maxRows=this.effectiveMaxRows;const minHeight=lineHeight*minRows+paddingBlock+borderBlock;const maxHeight=lineHeight*maxRows+paddingBlock+borderBlock;ta.style.height="auto";const contentHeight=ta.scrollHeight+borderBlock;const next=Math.min(Math.max(contentHeight,minHeight),maxHeight);ta.style.height=`${next}px`;ta.style.overflowY=contentHeight>maxHeight?"auto":"hidden"}armTextareaResizeObserver(){const ta=this.textareaEl;const ownerDocument=this.ownerDocument;const ownerWindow=ownerDocument.defaultView;if(!ta||!this.isConnected||!ownerWindow?.ResizeObserver)return;if(this.textareaResizeObserver&&this.textareaResizeObserverDocument===ownerDocument&&this.textareaResizeObserverTarget===ta){return}this.resetTextareaResizeWork();const generation=this.textareaResizeGeneration;let lastWidth=ta.getBoundingClientRect().width;const observer=new ownerWindow.ResizeObserver(entries=>{if(this.textareaResizeObserver!==observer||this.textareaResizeObserverDocument!==ownerDocument||this.textareaResizeObserverTarget!==ta||this.textareaResizeGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument){return}const box=entries[0]?.contentBoxSize?.[0];const width=box?box.inlineSize:entries[0]?.contentRect.width??lastWidth;if(Math.abs(width-lastWidth)<.5)return;lastWidth=width;if(this.textareaResizeRaf!==void 0){this.textareaResizeRafOwner?.cancelAnimationFrame(this.textareaResizeRaf)}const handle=ownerWindow.requestAnimationFrame(()=>{if(this.textareaResizeRaf!==handle||this.textareaResizeRafOwner!==ownerWindow||this.textareaResizeRafDocument!==ownerDocument||this.textareaResizeGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.textareaResizeObserverTarget!==ta){return}this.textareaResizeRaf=void 0;this.textareaResizeRafOwner=void 0;this.textareaResizeRafDocument=void 0;this.resizeTextarea()});this.textareaResizeRaf=handle;this.textareaResizeRafOwner=ownerWindow;this.textareaResizeRafDocument=ownerDocument});this.textareaResizeObserver=observer;this.textareaResizeObserverDocument=ownerDocument;this.textareaResizeObserverTarget=ta;observer.observe(ta)}resetTextareaResizeWork(){this.textareaResizeGeneration+=1;this.textareaResizeObserver?.disconnect();this.textareaResizeObserver=void 0;this.textareaResizeObserverDocument=void 0;this.textareaResizeObserverTarget=void 0;if(this.textareaResizeRaf!==void 0){this.textareaResizeRafOwner?.cancelAnimationFrame(this.textareaResizeRaf)}this.textareaResizeRaf=void 0;this.textareaResizeRafOwner=void 0;this.textareaResizeRafDocument=void 0}submit(){if(this.submitDisabled||this.effectiveDisabled||this.status!=="idle")return;this.emit("lr-submit",{value:this.value})}renderActionButton(){const busy=this.status!=="idle";const showStop=busy&&this.stoppable;return html`
|
|
24
|
+
`}class LyraChatComposerBase extends LyraElement{}class LyraChatComposer extends FormAssociated(LyraChatComposerBase){static{this.defaultStrings={...super.defaultStrings,composerLabel:LYRA_DEFAULT_composerLabel,fieldRequired:LYRA_DEFAULT_fieldRequired,restore:LYRA_DEFAULT_restore,sendMessage:LYRA_DEFAULT_sendMessage,stopGenerating:LYRA_DEFAULT_stopGenerating}}static{this.styles=[LyraElement.styles,styles]}get effectiveMinRows(){return finiteInteger(this.minRows,1,1)}get effectiveMaxRows(){return Math.max(this.effectiveMinRows,finiteInteger(this.maxRows,this.effectiveMinRows,1))}constructor(){super();this.placeholder="";this.minRows=1;this.maxRows=8;this.status="idle";this.frame="card";this.submitOnEnter=true;this.submitDisabled=false;this.stoppable=true;this.accessibleLabel=null;this.spellcheck=true;this.autocapitalize="";this.autoCorrect="";this.wrap="soft";this.autocomplete="";this.inputMode="";this.enterKeyHint="";this.hasLeadingSlot=false;this.hasChipsSlot=false;this.hasTrailingSlot=false;this.touched=false;this.textareaResizeGeneration=0;this.onTextareaInput=e=>{this.value=e.target.value;this.emit("lr-input",{value:this.value})};this.onTextareaKeyDown=e=>{if(e.key!=="Enter")return;if(e.shiftKey)return;if(!this.submitOnEnter)return;if(e.isComposing||e.keyCode===229)return;if(this.status!=="idle")return;e.preventDefault();this.submit()};this.onActionClick=()=>{if(this.effectiveDisabled)return;if(this.status==="idle"){this.submit()}else if(this.stoppable){this.emit("lr-stop")}};this.onLeadingSlotChange=e=>{this.hasLeadingSlot=e.target.assignedElements({flatten:true}).length>0};this.onChipsSlotChange=e=>{this.hasChipsSlot=e.target.assignedElements({flatten:true}).length>0};this.onTrailingSlotChange=e=>{this.hasTrailingSlot=e.target.assignedElements({flatten:true}).length>0};this.onTextareaBlur=()=>{if(!this.effectiveDisabled)this.touched=true;this.emit("blur")};this.onTextareaFocus=()=>{this.emit("focus")};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"}focus(options){this.textareaEl?.focus(options)}blur(){this.textareaEl?.blur()}click(){if(!this.effectiveDisabled)this.textareaEl?.focus()}select(){this.textareaEl?.select()}setSelectionRange(start,end,direction){this.textareaEl?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){const textarea=this.textareaEl;if(!textarea)return;if(start===void 0||end===void 0){textarea.setRangeText(replacement)}else{textarea.setRangeText(replacement,start,end,selectMode)}this.value=textarea.value;this.resizeTextarea()}willUpdate(changed){super.willUpdate(changed);this.seedFirstRenderState(()=>{this.hasLeadingSlot=this.hasSlotted("leading");this.hasChipsSlot=this.hasSlotted("chips");this.hasTrailingSlot=this.hasSlotted("trailing")})}firstUpdated(changed){super.firstUpdated(changed);this.resizeTextarea();this.armTextareaResizeObserver()}connectedCallback(){super.connectedCallback();if(this.hasUpdated){this.armTextareaResizeObserver();this.resizeTextarea()}}disconnectedCallback(){super.disconnectedCallback();this.resetTextareaResizeWork()}adoptedCallback(){this.resetTextareaResizeWork()}updated(changed){super.updated(changed);if(changed.has("value")||changed.has("minRows")||changed.has("maxRows")){this.resizeTextarea()}}formResetCallback(){super.formResetCallback();this.touched=false}hasSlotted(name){return Array.from(this.children).some(el=>el.getAttribute("slot")===name)}resizeTextarea(){const ta=this.textareaEl;if(!ta)return;const cs=this.ownerDocument.defaultView?.getComputedStyle(ta)??ta.style;const lineHeight=parseFloat(cs.lineHeight)||parseFloat(cs.fontSize)*1.2;const paddingBlock=parseFloat(cs.paddingTop)+parseFloat(cs.paddingBottom);const borderBlock=parseFloat(cs.borderTopWidth)+parseFloat(cs.borderBottomWidth);const minRows=this.effectiveMinRows;const maxRows=this.effectiveMaxRows;const minHeight=lineHeight*minRows+paddingBlock+borderBlock;const maxHeight=lineHeight*maxRows+paddingBlock+borderBlock;ta.style.height="auto";const contentHeight=ta.scrollHeight+borderBlock;const next=Math.min(Math.max(contentHeight,minHeight),maxHeight);ta.style.height=`${next}px`;ta.style.overflowY=contentHeight>maxHeight?"auto":"hidden"}armTextareaResizeObserver(){const ta=this.textareaEl;const ownerDocument=this.ownerDocument;const ownerWindow=ownerDocument.defaultView;if(!ta||!this.isConnected||!ownerWindow?.ResizeObserver)return;if(this.textareaResizeObserver&&this.textareaResizeObserverDocument===ownerDocument&&this.textareaResizeObserverTarget===ta){return}this.resetTextareaResizeWork();const generation=this.textareaResizeGeneration;let lastWidth=ta.getBoundingClientRect().width;const observer=new ownerWindow.ResizeObserver(entries=>{if(this.textareaResizeObserver!==observer||this.textareaResizeObserverDocument!==ownerDocument||this.textareaResizeObserverTarget!==ta||this.textareaResizeGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument){return}const box=entries[0]?.contentBoxSize?.[0];const width=box?box.inlineSize:entries[0]?.contentRect.width??lastWidth;if(Math.abs(width-lastWidth)<.5)return;lastWidth=width;if(this.textareaResizeRaf!==void 0){this.textareaResizeRafOwner?.cancelAnimationFrame(this.textareaResizeRaf)}const handle=ownerWindow.requestAnimationFrame(()=>{if(this.textareaResizeRaf!==handle||this.textareaResizeRafOwner!==ownerWindow||this.textareaResizeRafDocument!==ownerDocument||this.textareaResizeGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.textareaResizeObserverTarget!==ta){return}this.textareaResizeRaf=void 0;this.textareaResizeRafOwner=void 0;this.textareaResizeRafDocument=void 0;this.resizeTextarea()});this.textareaResizeRaf=handle;this.textareaResizeRafOwner=ownerWindow;this.textareaResizeRafDocument=ownerDocument});this.textareaResizeObserver=observer;this.textareaResizeObserverDocument=ownerDocument;this.textareaResizeObserverTarget=ta;observer.observe(ta)}resetTextareaResizeWork(){this.textareaResizeGeneration+=1;this.textareaResizeObserver?.disconnect();this.textareaResizeObserver=void 0;this.textareaResizeObserverDocument=void 0;this.textareaResizeObserverTarget=void 0;if(this.textareaResizeRaf!==void 0){this.textareaResizeRafOwner?.cancelAnimationFrame(this.textareaResizeRaf)}this.textareaResizeRaf=void 0;this.textareaResizeRafOwner=void 0;this.textareaResizeRafDocument=void 0}submit(){if(this.submitDisabled||this.effectiveDisabled||this.status!=="idle")return;this.emit("lr-submit",{value:this.value})}renderActionButton(){const busy=this.status!=="idle";const showStop=busy&&this.stoppable;return html`
|
|
25
25
|
<button
|
|
26
26
|
part="action-button"
|
|
27
27
|
type="button"
|
|
@@ -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{sizes}from"../../../internal/sizes.styles.js";import{AnchoredPopoverController}from"../../../internal/anchored-popover-controller.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{styles}from"./model-select.styles.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{spellcheckFromAttributeConverter as spellcheckConverter}from"../../../internal/converters.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{filterCatalogEntries,normalizeCatalog,withSyntheticCatalogValue}from"../../../internal/catalog-picker.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_model,LYRA_DEFAULT_modelSelectNoModels,LYRA_DEFAULT_modelSelectRequired,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_notInCatalog,LYRA_DEFAULT_open,LYRA_DEFAULT_restore}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 LyraModelSelect extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,model:LYRA_DEFAULT_model,modelSelectNoModels:LYRA_DEFAULT_modelSelectNoModels,modelSelectRequired:LYRA_DEFAULT_modelSelectRequired,noMatches:LYRA_DEFAULT_noMatches,notInCatalog:LYRA_DEFAULT_notInCatalog,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},required:{type:Boolean,reflect:true,noAccessor:true},value:{attribute:false,noAccessor:true},defaultValue:{attribute:"value",reflect:true,useDefault:true,noAccessor:true},name:{reflect:true,noAccessor:true}}}constructor(){super();this.provider="";this.allowCustom=false;this.label="";this.hint="";this.errorText="";this.placeholder="";this.spellcheck=true;this.autocapitalize="";this.autoCorrect="";this.autocomplete="off";this.inputMode="";this.enterKeyHint="";this.open=false;this.size="m";this.activeIndex=-1;this.query="";this.touched=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.listId=nextId("model-select-list");this.controlId=nextId("model-select-control");this.popupPosition=new AnchoredPopoverController;this._value="";this._fieldsetDisabled=false;this._name="";this._disabled=false;this._required=false;this.suppressControlBlur=false;this._defaultValue="";this._valueDirty=false;this.settingDefaultValue=false;this.reflectingDefaultValue=false;this.onDocPointer=e=>{if(!e.composedPath().includes(this))this.hide()};this.onTriggerClick=()=>{if(this.effectiveDisabled)return;this.open?this.hide():this.show()};this.onTriggerBlur=event=>{if(this.suppressControlBlur){event.stopImmediatePropagation();return}this.touched=true;this.hide();relayNativeEvent(this,event);this.emit("lr-blur")};this.onTriggerFocus=event=>{relayNativeEvent(this,event);this.emit("lr-focus")};this.onTriggerKeyDown=e=>{const rows=this.effectiveEntries;switch(e.key){case"ArrowDown":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.min(rows.length-1,this.activeIndex+1);break;case"ArrowUp":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":case" ":if(this.open){e.preventDefault();const active=rows[this.activeIndex];if(this.activeIndex>=0&&active){this.selectEntry(active)}else{this.hide()}}break;case"Escape":if(this.open){e.preventDefault();this.hide()}break;case"Home":if(this.open){e.preventDefault();this.activeIndex=0}break;case"End":if(this.open){e.preventDefault();this.activeIndex=rows.length-1}break}};this.onComboMouseDown=e=>{if(this.effectiveDisabled)return;e.preventDefault();this.renderRoot.querySelector('[part="combobox-input"]')?.focus()};this.onInputFocus=event=>{if(!this.open)this.query=this.labelFor(this.value);this.show();relayNativeEvent(this,event);this.emit("lr-focus")};this.onInput=e=>{this.query=e.target.value;this.activeIndex=-1;this.show();relayNativeEvent(this,e)};this.onInputBlur=event=>{if(this.suppressControlBlur){event.stopImmediatePropagation();return}this.touched=true;this.hide();relayNativeEvent(this,event);this.emit("lr-blur")};this.onInputKeyDown=e=>{const rows=this.filteredEntries;switch(e.key){case"ArrowDown":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.min(rows.length-1,this.activeIndex+1);break;case"ArrowUp":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":if(this.open){e.preventDefault();this.commitFreeText()}break;case"Escape":if(this.open){e.preventDefault();this.query=this.labelFor(this.value);this.hide()}break;case"Home":if(this.open){e.preventDefault();this.activeIndex=0}break;case"End":if(this.open){e.preventDefault();this.activeIndex=rows.length-1}break}};this.onListboxMouseDown=e=>{if(e.target.closest('[part="option"]'))e.preventDefault()};this.onListboxClick=e=>{if(this.effectiveDisabled)return;const optionEl=e.target.closest('[part="option"]');const value=optionEl?.dataset["value"];if(value===void 0)return;const entry=(this.closedMode?this.effectiveEntries:this.filteredEntries).find(e2=>e2.id===value);if(entry)this.selectEntry(entry)};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));this.internals.setFormValue("")}click(){if(this.effectiveDisabled)return;const trigger=this.renderRoot?.querySelector('[part="trigger"]');if(trigger){trigger.click();return}const input=this.renderRoot?.querySelector('[part="combobox-input"]');input?.click();input?.focus()}focus(options){if(!this.effectiveDisabled)this[VALIDITY_ANCHOR]()?.focus(options)}blur(){this[VALIDITY_ANCHOR]()?.blur()}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"], [part="combobox-input"]')??null}connectedCallback(){super.connectedCallback();this.updateValidity();if(this.hasUpdated&&this.open)queueMicrotask(()=>this.syncPopup())}willUpdate(changed){let modeChanged=false;if(this.hasUpdated){const renderedClosedMode=this.renderRoot.querySelector('[part="trigger"]')!==null;modeChanged=renderedClosedMode!==this.closedMode;this.suppressControlBlur=modeChanged}if(this.open&&(changed.has("catalog")||changed.has("value")||changed.has("allowCustom"))){this.activeIndex=-1;if(changed.has("value")||changed.has("allowCustom")||modeChanged){this.query=this.labelFor(this._value)}}if(!this.hasUpdated){this.hasHintSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="hint");this.hasErrorSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="error")}}disconnectedCallback(){super.disconnectedCallback();this.popupPosition.disconnect();this.unbindDocumentPointer();this.open=false}adoptedCallback(){this.popupPosition.disconnect();this.unbindDocumentPointer()}get value(){return this._value}set value(next){const old=this._value;if(!this.settingDefaultValue)this._valueDirty=true;this._value=next??"";this.internals.setFormValue(this._value);this.updateValidity();this.requestUpdate("value",old)}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next??"";this.reflectingDefaultValue=true;try{if(this._defaultValue)this.setAttribute("value",this._defaultValue);else this.removeAttribute("value")}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.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);if(this._disabled)this.hide();this.updateValidity();this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=Boolean(next);this.toggleAttribute("required",this._required);this.updateValidity();this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({})}else if(this.required&&!this._value){this.validityController.setValidity({valueMissing:true},this.localize("modelSelectRequired"))}else{this.validityController.setValidity({})}this.publishValidityStates()}publishValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation})}formResetCallback(){this.touched=false;this.restoreLiveValueFromDefault()}restoreLiveValueFromDefault(){this.settingDefaultValue=true;try{this.value=this._defaultValue}finally{this.settingDefaultValue=false}this._valueDirty=false}formStateRestoreCallback(state2,_mode){this.value=typeof state2==="string"?state2:""}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;if(disabled)this.hide();this.updateValidity();this.requestUpdate()}checkValidity(){return this.internals.checkValidity()}reportValidity(){this.touched=true;this.publishValidityStates();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.publishValidityStates()}get normalizedCatalog(){return normalizeCatalog(this.catalog)}get closedMode(){return this.normalizedCatalog.length>0&&!this.allowCustom}get effectiveEntries(){return withSyntheticCatalogValue(this.normalizedCatalog,this._value)}get filteredEntries(){return filterCatalogEntries(this.effectiveEntries,this.query,this.effectiveLocale,entry=>[entry.id,entry.label])}labelFor(id){if(!id)return"";return this.effectiveEntries.find(e=>e.id===id)?.label??id}show(){if(this.open||this.effectiveDisabled)return;this.open=true}hide(){if(!this.open)return;this.open=false;this.activeIndex=-1}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}syncPopup(){this.popupPosition.disconnect();if(!this.open||!this.isConnected){this.unbindDocumentPointer();return}this.bindDocumentPointer();const anchor=this.renderRoot.querySelector(this.closedMode?'[part="trigger"]':'[part="combobox"]');const listbox=this.renderRoot.querySelector('[part="listbox"]');if(anchor&&listbox)this.popupPosition.reposition(anchor,listbox)}updated(changed){const reposition=changed.has("open")||this.open&&(changed.has("catalog")||changed.has("allowCustom"));if(reposition){this.syncPopup()}if(changed.has("required")||changed.has("touched")||changed.has("value")){this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}this.publishValidityStates();this.suppressControlBlur=false}commitValue(next){const inCatalog=this.normalizedCatalog.some(e=>e.id===next);this.value=next;this.hide();this.emit("lr-change",{value:next,inCatalog});this.emitValueEvents()}emitValueEvents(){dispatchNativeEvent(this,"input");dispatchNativeEvent(this,"change")}selectEntry(entry){this.commitValue(entry.id)}commitFreeText(){const rows=this.filteredEntries;const active=rows[this.activeIndex];if(this.activeIndex>=0&&active){this.commitValue(active.id);return}this.commitValue(this.query.trim())}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`;const selected=entry.id===this._value;return 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,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{sizes}from"../../../internal/sizes.styles.js";import{AnchoredPopoverController}from"../../../internal/anchored-popover-controller.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{styles}from"./model-select.styles.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{spellcheckFromAttributeConverter as spellcheckConverter}from"../../../internal/converters.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{filterCatalogEntries,normalizeCatalog,withSyntheticCatalogValue}from"../../../internal/catalog-picker.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_model,LYRA_DEFAULT_modelSelectNoModels,LYRA_DEFAULT_modelSelectRequired,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_notInCatalog,LYRA_DEFAULT_open,LYRA_DEFAULT_restore}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 LyraModelSelect extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,model:LYRA_DEFAULT_model,modelSelectNoModels:LYRA_DEFAULT_modelSelectNoModels,modelSelectRequired:LYRA_DEFAULT_modelSelectRequired,noMatches:LYRA_DEFAULT_noMatches,notInCatalog:LYRA_DEFAULT_notInCatalog,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},required:{type:Boolean,reflect:true,noAccessor:true},value:{attribute:false,noAccessor:true},defaultValue:{attribute:"value",reflect:true,useDefault:true,noAccessor:true},name:{reflect:true,noAccessor:true}}}constructor(){super();this.provider="";this.allowCustom=false;this.label="";this.hint="";this.errorText="";this.placeholder="";this.spellcheck=true;this.autocapitalize="";this.autoCorrect="";this.autocomplete="off";this.inputMode="";this.enterKeyHint="";this.open=false;this.size="m";this.activeIndex=-1;this.query="";this.touched=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.listId=nextId("model-select-list");this.controlId=nextId("model-select-control");this.popupPosition=new AnchoredPopoverController;this._value="";this._fieldsetDisabled=false;this._name="";this._disabled=false;this._required=false;this.suppressControlBlur=false;this._defaultValue="";this._valueDirty=false;this.settingDefaultValue=false;this.reflectingDefaultValue=false;this.onDocPointer=e=>{if(!e.composedPath().includes(this))this.hide()};this.onTriggerClick=()=>{if(this.effectiveDisabled)return;this.open?this.hide():this.show()};this.onTriggerBlur=event=>{if(this.suppressControlBlur){event.stopImmediatePropagation();return}if(!this.effectiveDisabled)this.touched=true;this.hide();relayNativeEvent(this,event);this.emit("lr-blur")};this.onTriggerFocus=event=>{relayNativeEvent(this,event);this.emit("lr-focus")};this.onTriggerKeyDown=e=>{const rows=this.effectiveEntries;switch(e.key){case"ArrowDown":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.min(rows.length-1,this.activeIndex+1);break;case"ArrowUp":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":case" ":if(this.open){e.preventDefault();const active=rows[this.activeIndex];if(this.activeIndex>=0&&active){this.selectEntry(active)}else{this.hide()}}break;case"Escape":if(this.open){e.preventDefault();this.hide()}break;case"Home":if(this.open){e.preventDefault();this.activeIndex=0}break;case"End":if(this.open){e.preventDefault();this.activeIndex=rows.length-1}break}};this.onComboMouseDown=e=>{if(this.effectiveDisabled)return;e.preventDefault();this.renderRoot.querySelector('[part="combobox-input"]')?.focus()};this.onInputFocus=event=>{if(!this.open)this.query=this.labelFor(this.value);this.show();relayNativeEvent(this,event);this.emit("lr-focus")};this.onInput=e=>{this.query=e.target.value;this.activeIndex=-1;this.show();relayNativeEvent(this,e)};this.onInputBlur=event=>{if(this.suppressControlBlur){event.stopImmediatePropagation();return}if(!this.effectiveDisabled)this.touched=true;this.hide();relayNativeEvent(this,event);this.emit("lr-blur")};this.onInputKeyDown=e=>{const rows=this.filteredEntries;switch(e.key){case"ArrowDown":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.min(rows.length-1,this.activeIndex+1);break;case"ArrowUp":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":if(this.open){e.preventDefault();this.commitFreeText()}break;case"Escape":if(this.open){e.preventDefault();this.query=this.labelFor(this.value);this.hide()}break;case"Home":if(this.open){e.preventDefault();this.activeIndex=0}break;case"End":if(this.open){e.preventDefault();this.activeIndex=rows.length-1}break}};this.onListboxMouseDown=e=>{if(e.target.closest('[part="option"]'))e.preventDefault()};this.onListboxClick=e=>{if(this.effectiveDisabled)return;const optionEl=e.target.closest('[part="option"]');const value=optionEl?.dataset["value"];if(value===void 0)return;const entry=(this.closedMode?this.effectiveEntries:this.filteredEntries).find(e2=>e2.id===value);if(entry)this.selectEntry(entry)};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));this.internals.setFormValue("")}click(){if(this.effectiveDisabled)return;const trigger=this.renderRoot?.querySelector('[part="trigger"]');if(trigger){trigger.click();return}const input=this.renderRoot?.querySelector('[part="combobox-input"]');input?.click();input?.focus()}focus(options){if(!this.effectiveDisabled)this[VALIDITY_ANCHOR]()?.focus(options)}blur(){this[VALIDITY_ANCHOR]()?.blur()}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"], [part="combobox-input"]')??null}connectedCallback(){super.connectedCallback();this.updateValidity();if(this.hasUpdated&&this.open)queueMicrotask(()=>this.syncPopup())}willUpdate(changed){let modeChanged=false;if(this.hasUpdated){const renderedClosedMode=this.renderRoot.querySelector('[part="trigger"]')!==null;modeChanged=renderedClosedMode!==this.closedMode;this.suppressControlBlur=modeChanged}if(this.open&&(changed.has("catalog")||changed.has("value")||changed.has("allowCustom"))){this.activeIndex=-1;if(changed.has("value")||changed.has("allowCustom")||modeChanged){this.query=this.labelFor(this._value)}}if(!this.hasUpdated){this.hasHintSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="hint");this.hasErrorSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="error")}}disconnectedCallback(){super.disconnectedCallback();this.popupPosition.disconnect();this.unbindDocumentPointer();this.open=false}adoptedCallback(){this.popupPosition.disconnect();this.unbindDocumentPointer()}get value(){return this._value}set value(next){const old=this._value;if(!this.settingDefaultValue)this._valueDirty=true;this._value=next??"";this.internals.setFormValue(this._value);this.updateValidity();this.requestUpdate("value",old)}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next??"";this.reflectingDefaultValue=true;try{if(this._defaultValue)this.setAttribute("value",this._defaultValue);else this.removeAttribute("value")}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.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);if(this._disabled)this.hide();this.updateValidity();this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=Boolean(next);this.toggleAttribute("required",this._required);this.updateValidity();this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({})}else if(this.required&&!this._value){this.validityController.setValidity({valueMissing:true},this.localize("modelSelectRequired"))}else{this.validityController.setValidity({})}this.publishValidityStates()}publishValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation})}formResetCallback(){this.touched=false;this.restoreLiveValueFromDefault()}restoreLiveValueFromDefault(){this.settingDefaultValue=true;try{this.value=this._defaultValue}finally{this.settingDefaultValue=false}this._valueDirty=false}formStateRestoreCallback(state2,_mode){this.value=typeof state2==="string"?state2:""}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;if(disabled)this.hide();this.updateValidity();this.requestUpdate()}checkValidity(){return this.internals.checkValidity()}reportValidity(){this.touched=true;this.publishValidityStates();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.publishValidityStates()}get normalizedCatalog(){return normalizeCatalog(this.catalog)}get closedMode(){return this.normalizedCatalog.length>0&&!this.allowCustom}get effectiveEntries(){return withSyntheticCatalogValue(this.normalizedCatalog,this._value)}get filteredEntries(){return filterCatalogEntries(this.effectiveEntries,this.query,this.effectiveLocale,entry=>[entry.id,entry.label])}labelFor(id){if(!id)return"";return this.effectiveEntries.find(e=>e.id===id)?.label??id}show(){if(this.open||this.effectiveDisabled)return;this.open=true}hide(){if(!this.open)return;this.open=false;this.activeIndex=-1}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}syncPopup(){this.popupPosition.disconnect();if(!this.open||!this.isConnected){this.unbindDocumentPointer();return}this.bindDocumentPointer();const anchor=this.renderRoot.querySelector(this.closedMode?'[part="trigger"]':'[part="combobox"]');const listbox=this.renderRoot.querySelector('[part="listbox"]');if(anchor&&listbox)this.popupPosition.reposition(anchor,listbox)}updated(changed){const reposition=changed.has("open")||this.open&&(changed.has("catalog")||changed.has("allowCustom"));if(reposition){this.syncPopup()}if(changed.has("required")||changed.has("touched")||changed.has("value")){this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}this.publishValidityStates();this.suppressControlBlur=false}commitValue(next){const inCatalog=this.normalizedCatalog.some(e=>e.id===next);this.value=next;this.hide();this.emit("lr-change",{value:next,inCatalog});this.emitValueEvents()}emitValueEvents(){dispatchNativeEvent(this,"input");dispatchNativeEvent(this,"change")}selectEntry(entry){this.commitValue(entry.id)}commitFreeText(){const rows=this.filteredEntries;const active=rows[this.activeIndex];if(this.activeIndex>=0&&active){this.commitValue(active.id);return}this.commitValue(this.query.trim())}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`;const selected=entry.id===this._value;return 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{AnchoredPopoverController}from"../../../internal/anchored-popover-controller.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon,playIcon,pauseIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./voice-picker.styles.js";import{trueDefaultBooleanConverter,trueDefaultSpellcheckConverter as spellcheckConverter}from"../../../internal/converters.js";import{filterCatalogEntries,normalizeCatalog,withSyntheticCatalogValue}from"../../../internal/catalog-picker.js";import{activeElementIn}from"../../../internal/active-element.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_notInCatalog,LYRA_DEFAULT_open,LYRA_DEFAULT_restore,LYRA_DEFAULT_voice,LYRA_DEFAULT_voicePickerNoVoices,LYRA_DEFAULT_voicePickerPreview,LYRA_DEFAULT_voicePickerRequired,LYRA_DEFAULT_voicePickerStopPreview}from"../../../internal/default-strings.generated.js";class LyraVoicePicker extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,noMatches:LYRA_DEFAULT_noMatches,notInCatalog:LYRA_DEFAULT_notInCatalog,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore,voice:LYRA_DEFAULT_voice,voicePickerNoVoices:LYRA_DEFAULT_voicePickerNoVoices,voicePickerPreview:LYRA_DEFAULT_voicePickerPreview,voicePickerRequired:LYRA_DEFAULT_voicePickerRequired,voicePickerStopPreview:LYRA_DEFAULT_voicePickerStopPreview}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},required:{type:Boolean,reflect:true,noAccessor:true},value:{attribute:false,noAccessor:true},defaultValue:{attribute:"value",reflect:true,useDefault:true,noAccessor:true},name:{reflect:true,noAccessor:true}}}constructor(){super();this.provider="";this.allowCustom=false;this.preview=true;this.label="";this.hint="";this.errorText="";this.placeholder="";this.spellcheck=true;this.autocapitalize="";this.autoCorrect="";this.autocomplete="off";this.inputMode="";this.enterKeyHint="";this.open=false;this.activeIndex=-1;this.query="";this.touched=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.previewingId=null;this.listId=nextId("voice-picker-list");this.controlId=nextId("voice-picker-control");this.popupPosition=new AnchoredPopoverController;this._value="";this._fieldsetDisabled=false;this._name="";this._disabled=false;this._required=false;this._defaultValue="";this._valueDirty=false;this.settingDefaultValue=false;this.reflectingDefaultValue=false;this.suppressControlEvents=false;this.transferControlFocus=false;this.onDocPointer=e=>{if(!e.composedPath().includes(this))this.hide()};this.onAudioEnded=event=>{if(event.currentTarget!==this.audioEl)return;this.stopInternalPreview()};this.onAudioLoadFailure=eventOrAudio=>{const direct=eventOrAudio;const candidate=direct.localName==="audio"?eventOrAudio:eventOrAudio.currentTarget;const audioLike=candidate;const failedAudio=audioLike?.localName==="audio"&&typeof audioLike.pause==="function"&&typeof audioLike.removeEventListener==="function"?audioLike:void 0;if(!failedAudio)return;failedAudio.removeEventListener("ended",this.onAudioEnded);failedAudio.removeEventListener("error",this.onAudioLoadFailure);failedAudio.pause();if(failedAudio!==this.audioEl)return;this.audioEl=void 0;if(this.previewingId!==null){this.previewingId=null;this.emit("lr-preview-change",{voiceId:null})}};this.onPreviewButtonClick=()=>{const candidate=this.previewCandidateId;if(!candidate)return;if(this.previewingId===candidate)this.stopInternalPreview();else this.requestPreview(candidate)};this.onOptionPreviewClick=(e,entry)=>{e.stopPropagation();if(this.previewingId===entry.id)this.stopInternalPreview();else this.requestPreview(entry.id)};this.onTriggerClick=()=>{if(this.effectiveDisabled)return;this.open?this.hide():this.show()};this.onTriggerBlur=()=>{if(this.suppressControlEvents)return;this.touched=true;this.hide();this.emit("blur")};this.onTriggerFocus=()=>{if(!this.suppressControlEvents)this.emit("focus")};this.onTriggerKeyDown=e=>{const rows=this.effectiveEntries;switch(e.key){case"ArrowDown":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.min(rows.length-1,this.activeIndex+1);break;case"ArrowUp":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":case" ":if(this.open){e.preventDefault();const activeRow=rows[this.activeIndex];if(this.activeIndex>=0&&activeRow)this.selectEntry(activeRow);else this.hide()}break;case"Escape":if(this.open){e.preventDefault();this.hide()}break;case"Home":if(this.open){e.preventDefault();this.activeIndex=0}break;case"End":if(this.open){e.preventDefault();this.activeIndex=rows.length-1}break}};this.onComboMouseDown=e=>{if(this.effectiveDisabled)return;e.preventDefault();this.renderRoot.querySelector('[part="combobox-input"]')?.focus()};this.onInputFocus=()=>{if(!this.open)this.query=this.labelFor(this.value);this.show();if(!this.suppressControlEvents)this.emit("focus")};this.onInput=e=>{this.query=e.target.value;this.activeIndex=-1;this.show()};this.onInputBlur=()=>{if(this.suppressControlEvents)return;this.touched=true;this.hide();this.emit("blur")};this.onInputKeyDown=e=>{const rows=this.filteredEntries;switch(e.key){case"ArrowDown":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.min(rows.length-1,this.activeIndex+1);break;case"ArrowUp":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":if(this.open){e.preventDefault();this.commitFreeText()}break;case"Escape":if(this.open){e.preventDefault();this.query=this.labelFor(this.value);this.hide()}break;case"Home":if(this.open){e.preventDefault();this.activeIndex=0}break;case"End":if(this.open){e.preventDefault();this.activeIndex=rows.length-1}break}};this.onListboxMouseDown=e=>{if(e.target.closest('[part="option"]'))e.preventDefault()};this.onListboxClick=e=>{if(this.effectiveDisabled)return;const optionEl=e.target.closest('[part="option"]');const value=optionEl?.dataset["value"];if(value===void 0)return;const entry=(this.closedMode?this.effectiveEntries:this.filteredEntries).find(e2=>e2.id===value);if(entry)this.selectEntry(entry)};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=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("")}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"], [part="combobox-input"]')??null}click(){const trigger=this.renderRoot?.querySelector('[part="trigger"]');if(trigger){trigger.click();return}this.renderRoot?.querySelector('[part="combobox-input"]')?.focus()}focus(options){this.renderRoot.querySelector('[part="trigger"], [part="combobox-input"]')?.focus(options)}blur(){this.renderRoot.querySelector('[part="trigger"], [part="combobox-input"]')?.blur()}connectedCallback(){super.connectedCallback();this.updateValidity();if(this.hasUpdated&&this.open)queueMicrotask(()=>this.syncPopup())}willUpdate(changed){if(this.hasUpdated){const renderedClosedMode=this.renderRoot.querySelector('[part="trigger"]')!==null;const switchingMode=renderedClosedMode!==this.closedMode;const focused=activeElementIn(this.shadowRoot??this.ownerDocument);this.suppressControlEvents=switchingMode;this.transferControlFocus=switchingMode&&focused?.nodeType===1&&focused.matches('[part="trigger"], [part="combobox-input"]')}if(!this.hasUpdated){this.hasHintSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="hint");this.hasErrorSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="error")}if(this.hasUpdated&&(changed.has("catalog")||changed.has("allowCustom")||changed.has("value"))){const activeValue=this.renderRoot.querySelector('[part="option"][data-active]')?.dataset["value"];const rows=this.closedMode?this.effectiveEntries:this.filteredEntries;const remapped=activeValue?rows.findIndex(entry=>entry.id===activeValue):-1;this.activeIndex=remapped>=0?remapped:Math.min(this.activeIndex,Math.max(-1,rows.length-1))}if(changed.has("preview")&&!this.preview)this.stopInternalPreview()}disconnectedCallback(){super.disconnectedCallback();this.popupPosition.disconnect();this.unbindDocumentPointer();this.stopInternalPreview();this.open=false}adoptedCallback(){this.popupPosition.disconnect();this.unbindDocumentPointer();this.stopInternalPreview()}get value(){return this._value}set value(next){const old=this._value;if(!this.settingDefaultValue)this._valueDirty=true;this._value=next??"";this.internals.setFormValue(this._value);this.updateValidity();this.requestUpdate("value",old)}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next??"";this.reflectingDefaultValue=true;try{if(this._defaultValue)this.setAttribute("value",this._defaultValue);else this.removeAttribute("value")}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.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);if(this._disabled){this.hide();this.stopInternalPreview()}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 barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({})}else if(this.required&&!this._value){this.validityController.setValidity({valueMissing:true},this.localize("voicePickerRequired"))}else{this.validityController.setValidity({})}this.publishValidityStates()}publishValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation})}formResetCallback(){this.touched=false;this.restoreLiveValueFromDefault()}restoreLiveValueFromDefault(){this.settingDefaultValue=true;try{this.value=this._defaultValue}finally{this.settingDefaultValue=false}this._valueDirty=false}formStateRestoreCallback(state2,_mode){this.value=typeof state2==="string"?state2:""}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;if(disabled){this.hide();this.stopInternalPreview()}this.updateValidity();this.requestUpdate()}checkValidity(){return this.internals.checkValidity()}reportValidity(){this.touched=true;this.publishValidityStates();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.publishValidityStates()}get normalizedCatalog(){return normalizeCatalog(this.catalog)}get closedMode(){return this.normalizedCatalog.length>0&&!this.allowCustom}get effectiveEntries(){return withSyntheticCatalogValue(this.normalizedCatalog,this._value)}get filteredEntries(){return filterCatalogEntries(this.effectiveEntries,this.query,this.effectiveLocale,entry=>[entry.id,entry.label,entry.language??"",entry.description??""])}labelFor(id){if(!id)return"";return this.effectiveEntries.find(e=>e.id===id)?.label??id}show(){if(this.open||this.effectiveDisabled)return;this.open=true}hide(){if(!this.open)return;this.open=false;this.activeIndex=-1}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}syncPopup(){this.popupPosition.disconnect();if(!this.open||!this.isConnected){this.unbindDocumentPointer();return}this.bindDocumentPointer();const anchor=this.renderRoot.querySelector(this.closedMode?'[part="trigger"]':'[part="combobox"]');const listbox=this.renderRoot.querySelector('[part="listbox"]');if(anchor&&listbox)this.popupPosition.reposition(anchor,listbox)}updated(changed){const reposition=changed.has("open")||this.open&&(changed.has("catalog")||changed.has("allowCustom"));if(reposition){this.syncPopup()}if(changed.has("required")||changed.has("touched")||changed.has("value")){this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}this.publishValidityStates();if(this.transferControlFocus){this.transferControlFocus=false;this.renderRoot.querySelector('[part="trigger"], [part="combobox-input"]')?.focus()}this.suppressControlEvents=false}commitValue(next){const inCatalog=this.normalizedCatalog.some(e=>e.id===next);this.value=next;this.hide();this.emit("lr-change",{value:next,inCatalog});this.emitValueEvents()}emitValueEvents(){const EventConstructor=this.ownerDocument.defaultView?.Event??Event;const init={bubbles:true,composed:true};this.dispatchEvent(new EventConstructor("input",init));this.dispatchEvent(new EventConstructor("change",init))}selectEntry(entry){this.commitValue(entry.id)}commitFreeText(){const rows=this.filteredEntries;const activeRow=rows[this.activeIndex];if(this.activeIndex>=0&&activeRow){this.commitValue(activeRow.id);return}this.commitValue(this.query.trim())}get previewCandidateId(){if(this.open&&this.activeIndex>=0){const rows=this.closedMode?this.effectiveEntries:this.filteredEntries;return rows[this.activeIndex]?.id??this._value}return this._value}requestPreview(voiceId){if(!voiceId)return;const entry=this.effectiveEntries.find(e=>e.id===voiceId);const previewUrl=entry?.previewUrl;const event=this.emit("lr-preview-request",{voiceId,previewUrl},{cancelable:true});if(!event.defaultPrevented&&previewUrl)this.playInternal(voiceId,previewUrl)}playInternal(voiceId,url){const safe=safeMediaSrc(url);if(!safe)return;this.stopInternalPreview();const audio=this.ownerDocument.createElement("audio");audio.src=safe;audio.addEventListener("ended",this.onAudioEnded);audio.addEventListener("error",this.onAudioLoadFailure);this.audioEl=audio;this.previewingId=voiceId;void audio.play().catch(()=>this.onAudioLoadFailure(audio));this.emit("lr-preview-change",{voiceId})}stopInternalPreview(){if(this.audioEl){this.audioEl.removeEventListener("ended",this.onAudioEnded);this.audioEl.removeEventListener("error",this.onAudioLoadFailure);this.audioEl.pause();this.audioEl=void 0}if(this.previewingId!==null){this.previewingId=null;this.emit("lr-preview-change",{voiceId:null})}}get previewButtonLabel(){const candidate=this.previewCandidateId;const playing=this.previewingId!==null&&this.previewingId===candidate;const name=this.labelFor(candidate)||candidate;return playing?this.localize("voicePickerStopPreview"):this.localize("voicePickerPreview",void 0,{name})}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`;const selected=entry.id===this._value;const meta=[entry.language,entry.description].filter(Boolean).join(" \xB7 ");return 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,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AnchoredPopoverController}from"../../../internal/anchored-popover-controller.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon,playIcon,pauseIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./voice-picker.styles.js";import{trueDefaultBooleanConverter,trueDefaultSpellcheckConverter as spellcheckConverter}from"../../../internal/converters.js";import{filterCatalogEntries,normalizeCatalog,withSyntheticCatalogValue}from"../../../internal/catalog-picker.js";import{activeElementIn}from"../../../internal/active-element.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_notInCatalog,LYRA_DEFAULT_open,LYRA_DEFAULT_restore,LYRA_DEFAULT_voice,LYRA_DEFAULT_voicePickerNoVoices,LYRA_DEFAULT_voicePickerPreview,LYRA_DEFAULT_voicePickerRequired,LYRA_DEFAULT_voicePickerStopPreview}from"../../../internal/default-strings.generated.js";class LyraVoicePicker extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,noMatches:LYRA_DEFAULT_noMatches,notInCatalog:LYRA_DEFAULT_notInCatalog,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore,voice:LYRA_DEFAULT_voice,voicePickerNoVoices:LYRA_DEFAULT_voicePickerNoVoices,voicePickerPreview:LYRA_DEFAULT_voicePickerPreview,voicePickerRequired:LYRA_DEFAULT_voicePickerRequired,voicePickerStopPreview:LYRA_DEFAULT_voicePickerStopPreview}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},required:{type:Boolean,reflect:true,noAccessor:true},value:{attribute:false,noAccessor:true},defaultValue:{attribute:"value",reflect:true,useDefault:true,noAccessor:true},name:{reflect:true,noAccessor:true}}}constructor(){super();this.provider="";this.allowCustom=false;this.preview=true;this.label="";this.hint="";this.errorText="";this.placeholder="";this.spellcheck=true;this.autocapitalize="";this.autoCorrect="";this.autocomplete="off";this.inputMode="";this.enterKeyHint="";this.open=false;this.activeIndex=-1;this.query="";this.touched=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.previewingId=null;this.listId=nextId("voice-picker-list");this.controlId=nextId("voice-picker-control");this.popupPosition=new AnchoredPopoverController;this._value="";this._fieldsetDisabled=false;this._name="";this._disabled=false;this._required=false;this._defaultValue="";this._valueDirty=false;this.settingDefaultValue=false;this.reflectingDefaultValue=false;this.suppressControlEvents=false;this.transferControlFocus=false;this.onDocPointer=e=>{if(!e.composedPath().includes(this))this.hide()};this.onAudioEnded=event=>{if(event.currentTarget!==this.audioEl)return;this.stopInternalPreview()};this.onAudioLoadFailure=eventOrAudio=>{const direct=eventOrAudio;const candidate=direct.localName==="audio"?eventOrAudio:eventOrAudio.currentTarget;const audioLike=candidate;const failedAudio=audioLike?.localName==="audio"&&typeof audioLike.pause==="function"&&typeof audioLike.removeEventListener==="function"?audioLike:void 0;if(!failedAudio)return;failedAudio.removeEventListener("ended",this.onAudioEnded);failedAudio.removeEventListener("error",this.onAudioLoadFailure);failedAudio.pause();if(failedAudio!==this.audioEl)return;this.audioEl=void 0;if(this.previewingId!==null){this.previewingId=null;this.emit("lr-preview-change",{voiceId:null})}};this.onPreviewButtonClick=()=>{const candidate=this.previewCandidateId;if(!candidate)return;if(this.previewingId===candidate)this.stopInternalPreview();else this.requestPreview(candidate)};this.onOptionPreviewClick=(e,entry)=>{e.stopPropagation();if(this.previewingId===entry.id)this.stopInternalPreview();else this.requestPreview(entry.id)};this.onTriggerClick=()=>{if(this.effectiveDisabled)return;this.open?this.hide():this.show()};this.onTriggerBlur=()=>{if(this.suppressControlEvents)return;if(!this.effectiveDisabled)this.touched=true;this.hide();this.emit("blur")};this.onTriggerFocus=()=>{if(!this.suppressControlEvents)this.emit("focus")};this.onTriggerKeyDown=e=>{const rows=this.effectiveEntries;switch(e.key){case"ArrowDown":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.min(rows.length-1,this.activeIndex+1);break;case"ArrowUp":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":case" ":if(this.open){e.preventDefault();const activeRow=rows[this.activeIndex];if(this.activeIndex>=0&&activeRow)this.selectEntry(activeRow);else this.hide()}break;case"Escape":if(this.open){e.preventDefault();this.hide()}break;case"Home":if(this.open){e.preventDefault();this.activeIndex=0}break;case"End":if(this.open){e.preventDefault();this.activeIndex=rows.length-1}break}};this.onComboMouseDown=e=>{if(this.effectiveDisabled)return;e.preventDefault();this.renderRoot.querySelector('[part="combobox-input"]')?.focus()};this.onInputFocus=()=>{if(!this.open)this.query=this.labelFor(this.value);this.show();if(!this.suppressControlEvents)this.emit("focus")};this.onInput=e=>{this.query=e.target.value;this.activeIndex=-1;this.show()};this.onInputBlur=()=>{if(this.suppressControlEvents)return;if(!this.effectiveDisabled)this.touched=true;this.hide();this.emit("blur")};this.onInputKeyDown=e=>{const rows=this.filteredEntries;switch(e.key){case"ArrowDown":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.min(rows.length-1,this.activeIndex+1);break;case"ArrowUp":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":if(this.open){e.preventDefault();this.commitFreeText()}break;case"Escape":if(this.open){e.preventDefault();this.query=this.labelFor(this.value);this.hide()}break;case"Home":if(this.open){e.preventDefault();this.activeIndex=0}break;case"End":if(this.open){e.preventDefault();this.activeIndex=rows.length-1}break}};this.onListboxMouseDown=e=>{if(e.target.closest('[part="option"]'))e.preventDefault()};this.onListboxClick=e=>{if(this.effectiveDisabled)return;const optionEl=e.target.closest('[part="option"]');const value=optionEl?.dataset["value"];if(value===void 0)return;const entry=(this.closedMode?this.effectiveEntries:this.filteredEntries).find(e2=>e2.id===value);if(entry)this.selectEntry(entry)};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=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("")}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"], [part="combobox-input"]')??null}click(){const trigger=this.renderRoot?.querySelector('[part="trigger"]');if(trigger){trigger.click();return}this.renderRoot?.querySelector('[part="combobox-input"]')?.focus()}focus(options){this.renderRoot.querySelector('[part="trigger"], [part="combobox-input"]')?.focus(options)}blur(){this.renderRoot.querySelector('[part="trigger"], [part="combobox-input"]')?.blur()}connectedCallback(){super.connectedCallback();this.updateValidity();if(this.hasUpdated&&this.open)queueMicrotask(()=>this.syncPopup())}willUpdate(changed){if(this.hasUpdated){const renderedClosedMode=this.renderRoot.querySelector('[part="trigger"]')!==null;const switchingMode=renderedClosedMode!==this.closedMode;const focused=activeElementIn(this.shadowRoot??this.ownerDocument);this.suppressControlEvents=switchingMode;this.transferControlFocus=switchingMode&&focused?.nodeType===1&&focused.matches('[part="trigger"], [part="combobox-input"]')}if(!this.hasUpdated){this.hasHintSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="hint");this.hasErrorSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="error")}if(this.hasUpdated&&(changed.has("catalog")||changed.has("allowCustom")||changed.has("value"))){const activeValue=this.renderRoot.querySelector('[part="option"][data-active]')?.dataset["value"];const rows=this.closedMode?this.effectiveEntries:this.filteredEntries;const remapped=activeValue?rows.findIndex(entry=>entry.id===activeValue):-1;this.activeIndex=remapped>=0?remapped:Math.min(this.activeIndex,Math.max(-1,rows.length-1))}if(changed.has("preview")&&!this.preview)this.stopInternalPreview()}disconnectedCallback(){super.disconnectedCallback();this.popupPosition.disconnect();this.unbindDocumentPointer();this.stopInternalPreview();this.open=false}adoptedCallback(){this.popupPosition.disconnect();this.unbindDocumentPointer();this.stopInternalPreview()}get value(){return this._value}set value(next){const old=this._value;if(!this.settingDefaultValue)this._valueDirty=true;this._value=next??"";this.internals.setFormValue(this._value);this.updateValidity();this.requestUpdate("value",old)}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next??"";this.reflectingDefaultValue=true;try{if(this._defaultValue)this.setAttribute("value",this._defaultValue);else this.removeAttribute("value")}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.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);if(this._disabled){this.hide();this.stopInternalPreview()}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 barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({})}else if(this.required&&!this._value){this.validityController.setValidity({valueMissing:true},this.localize("voicePickerRequired"))}else{this.validityController.setValidity({})}this.publishValidityStates()}publishValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation})}formResetCallback(){this.touched=false;this.restoreLiveValueFromDefault()}restoreLiveValueFromDefault(){this.settingDefaultValue=true;try{this.value=this._defaultValue}finally{this.settingDefaultValue=false}this._valueDirty=false}formStateRestoreCallback(state2,_mode){this.value=typeof state2==="string"?state2:""}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;if(disabled){this.hide();this.stopInternalPreview()}this.updateValidity();this.requestUpdate()}checkValidity(){return this.internals.checkValidity()}reportValidity(){this.touched=true;this.publishValidityStates();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.publishValidityStates()}get normalizedCatalog(){return normalizeCatalog(this.catalog)}get closedMode(){return this.normalizedCatalog.length>0&&!this.allowCustom}get effectiveEntries(){return withSyntheticCatalogValue(this.normalizedCatalog,this._value)}get filteredEntries(){return filterCatalogEntries(this.effectiveEntries,this.query,this.effectiveLocale,entry=>[entry.id,entry.label,entry.language??"",entry.description??""])}labelFor(id){if(!id)return"";return this.effectiveEntries.find(e=>e.id===id)?.label??id}show(){if(this.open||this.effectiveDisabled)return;this.open=true}hide(){if(!this.open)return;this.open=false;this.activeIndex=-1}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}syncPopup(){this.popupPosition.disconnect();if(!this.open||!this.isConnected){this.unbindDocumentPointer();return}this.bindDocumentPointer();const anchor=this.renderRoot.querySelector(this.closedMode?'[part="trigger"]':'[part="combobox"]');const listbox=this.renderRoot.querySelector('[part="listbox"]');if(anchor&&listbox)this.popupPosition.reposition(anchor,listbox)}updated(changed){const reposition=changed.has("open")||this.open&&(changed.has("catalog")||changed.has("allowCustom"));if(reposition){this.syncPopup()}if(changed.has("required")||changed.has("touched")||changed.has("value")){this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}this.publishValidityStates();if(this.transferControlFocus){this.transferControlFocus=false;this.renderRoot.querySelector('[part="trigger"], [part="combobox-input"]')?.focus()}this.suppressControlEvents=false}commitValue(next){const inCatalog=this.normalizedCatalog.some(e=>e.id===next);this.value=next;this.hide();this.emit("lr-change",{value:next,inCatalog});this.emitValueEvents()}emitValueEvents(){const EventConstructor=this.ownerDocument.defaultView?.Event??Event;const init={bubbles:true,composed:true};this.dispatchEvent(new EventConstructor("input",init));this.dispatchEvent(new EventConstructor("change",init))}selectEntry(entry){this.commitValue(entry.id)}commitFreeText(){const rows=this.filteredEntries;const activeRow=rows[this.activeIndex];if(this.activeIndex>=0&&activeRow){this.commitValue(activeRow.id);return}this.commitValue(this.query.trim())}get previewCandidateId(){if(this.open&&this.activeIndex>=0){const rows=this.closedMode?this.effectiveEntries:this.filteredEntries;return rows[this.activeIndex]?.id??this._value}return this._value}requestPreview(voiceId){if(!voiceId)return;const entry=this.effectiveEntries.find(e=>e.id===voiceId);const previewUrl=entry?.previewUrl;const event=this.emit("lr-preview-request",{voiceId,previewUrl},{cancelable:true});if(!event.defaultPrevented&&previewUrl)this.playInternal(voiceId,previewUrl)}playInternal(voiceId,url){const safe=safeMediaSrc(url);if(!safe)return;this.stopInternalPreview();const audio=this.ownerDocument.createElement("audio");audio.src=safe;audio.addEventListener("ended",this.onAudioEnded);audio.addEventListener("error",this.onAudioLoadFailure);this.audioEl=audio;this.previewingId=voiceId;void audio.play().catch(()=>this.onAudioLoadFailure(audio));this.emit("lr-preview-change",{voiceId})}stopInternalPreview(){if(this.audioEl){this.audioEl.removeEventListener("ended",this.onAudioEnded);this.audioEl.removeEventListener("error",this.onAudioLoadFailure);this.audioEl.pause();this.audioEl=void 0}if(this.previewingId!==null){this.previewingId=null;this.emit("lr-preview-change",{voiceId:null})}}get previewButtonLabel(){const candidate=this.previewCandidateId;const playing=this.previewingId!==null&&this.previewingId===candidate;const name=this.labelFor(candidate)||candidate;return playing?this.localize("voicePickerStopPreview"):this.localize("voicePickerPreview",void 0,{name})}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`;const selected=entry.id===this._value;const meta=[entry.language,entry.description].filter(Boolean).join(" \xB7 ");return html`<div
|
|
2
2
|
part="option"
|
|
3
3
|
id=${id}
|
|
4
4
|
role="option"
|
|
@@ -308,6 +308,10 @@ export declare class LyraGraphQueryBuilder extends LyraElement<LyraGraphQueryBui
|
|
|
308
308
|
formResetCallback(): void;
|
|
309
309
|
formStateRestoreCallback(state: string | File | FormData | null, _mode?: 'restore' | 'autocomplete'): void;
|
|
310
310
|
formDisabledCallback(disabled: boolean): void;
|
|
311
|
+
private focusFirstControl;
|
|
312
|
+
/** Forwards host clicks to the first rendered control so callers can interact with this wrapper
|
|
313
|
+
* as if it exposed a single root control. */
|
|
314
|
+
click(): void;
|
|
311
315
|
private setValue;
|
|
312
316
|
private addRelationshipType;
|
|
313
317
|
private removeRelationshipType;
|
|
@@ -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{closeIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{finiteInteger}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{nextId}from"../../../internal/a11y.js";import{styles}from"./graph-query-builder.styles.js";import"../../forms/select/select.class.js";import"../../forms/combobox/option.class.js";import"../../forms/input/input.class.js";import"../../overlays/chip/chip.class.js";import"../../overlays/chip/chip-group.class.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,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_graphQueryBuilderLabel,LYRA_DEFAULT_graphQueryDeleteWithContext,LYRA_DEFAULT_graphQueryDirectionLabel,LYRA_DEFAULT_graphQueryEndLabel,LYRA_DEFAULT_graphQueryHopRangeInvalid,LYRA_DEFAULT_graphQueryLoadWithContext,LYRA_DEFAULT_graphQueryMaxHopsLabel,LYRA_DEFAULT_graphQueryMinHopsLabel,LYRA_DEFAULT_graphQueryNodeTypeLabel,LYRA_DEFAULT_graphQueryRelationshipTypeLabel,LYRA_DEFAULT_graphQueryRun,LYRA_DEFAULT_graphQuerySaveButton,LYRA_DEFAULT_graphQuerySaveNameLabel,LYRA_DEFAULT_graphQuerySavedQueriesLabel,LYRA_DEFAULT_graphQueryStartLabel,LYRA_DEFAULT_neighborDirectionBoth,LYRA_DEFAULT_neighborDirectionIn,LYRA_DEFAULT_neighborDirectionOut,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const EMPTY_VALUE={startId:"",endId:"",relationshipTypes:[],nodeTypes:[],direction:"both",minHops:1,maxHops:1};const EMPTY_OPTIONS=[];const EMPTY_SAVED=[];function stringArray(value){if(!Array.isArray(value))return[];return[...new Set(value.filter(entry=>typeof entry==="string"))]}function normalizeGraphQuery(value){const record=value!==null&&typeof value==="object"&&!Array.isArray(value)?value:{};const direction=record["direction"];return{startId:typeof record["startId"]==="string"?record["startId"]:"",endId:typeof record["endId"]==="string"?record["endId"]:"",relationshipTypes:stringArray(record["relationshipTypes"]),nodeTypes:stringArray(record["nodeTypes"]),direction:direction==="out"||direction==="in"||direction==="both"?direction:"both",minHops:finiteInteger(typeof record["minHops"]==="number"?record["minHops"]:EMPTY_VALUE.minHops,EMPTY_VALUE.minHops,1,20),maxHops:finiteInteger(typeof record["maxHops"]==="number"?record["maxHops"]:EMPTY_VALUE.maxHops,EMPTY_VALUE.maxHops,1,20)}}class LyraGraphQueryBuilder extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,graphQueryBuilderLabel:LYRA_DEFAULT_graphQueryBuilderLabel,graphQueryDeleteWithContext:LYRA_DEFAULT_graphQueryDeleteWithContext,graphQueryDirectionLabel:LYRA_DEFAULT_graphQueryDirectionLabel,graphQueryEndLabel:LYRA_DEFAULT_graphQueryEndLabel,graphQueryHopRangeInvalid:LYRA_DEFAULT_graphQueryHopRangeInvalid,graphQueryLoadWithContext:LYRA_DEFAULT_graphQueryLoadWithContext,graphQueryMaxHopsLabel:LYRA_DEFAULT_graphQueryMaxHopsLabel,graphQueryMinHopsLabel:LYRA_DEFAULT_graphQueryMinHopsLabel,graphQueryNodeTypeLabel:LYRA_DEFAULT_graphQueryNodeTypeLabel,graphQueryRelationshipTypeLabel:LYRA_DEFAULT_graphQueryRelationshipTypeLabel,graphQueryRun:LYRA_DEFAULT_graphQueryRun,graphQuerySaveButton:LYRA_DEFAULT_graphQuerySaveButton,graphQuerySaveNameLabel:LYRA_DEFAULT_graphQuerySaveNameLabel,graphQuerySavedQueriesLabel:LYRA_DEFAULT_graphQuerySavedQueriesLabel,graphQueryStartLabel:LYRA_DEFAULT_graphQueryStartLabel,neighborDirectionBoth:LYRA_DEFAULT_neighborDirectionBoth,neighborDirectionIn:LYRA_DEFAULT_neighborDirectionIn,neighborDirectionOut:LYRA_DEFAULT_neighborDirectionOut,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},name:{reflect:true,noAccessor:true},value:{attribute:false,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true}}}constructor(){super();this.relationshipTypeOptions=EMPTY_OPTIONS;this.nodeTypeOptions=EMPTY_OPTIONS;this.savedQueries=EMPTY_SAVED;this.hopLimit=6;this.label="";this.hint="";this.errorText="";this._errors={};this.touchedFields=new Set;this.saveName="";this.hasHintSlot=false;this.hasErrorSlot=false;this.labelId=nextId("graph-query-builder-label");this.hintId=nextId("graph-query-builder-hint");this.errorId=nextId("graph-query-builder-error");this._fieldsetDisabled=false;this._name="";this._value=EMPTY_VALUE;this._disabled=false;this.hasInteracted=false;this.onChromeSlotChange=event=>{const slot=event.currentTarget;const hasContent=slot.assignedNodes({flatten:true}).some(node=>node.nodeType===Node.TEXT_NODE?Boolean(node.textContent?.trim()):true);if(slot.name==="hint")this.hasHintSlot=hasContent;else if(slot.name==="error")this.hasErrorSlot=hasContent};this.internals=this.safeAttachInternals();this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);installInvalidEventAlias(this,()=>this.emit("lr-invalid"));this.syncFormState()}safeAttachInternals(){if(typeof globalThis.ElementInternals==="undefined"){return this.inertInternals()}try{return this.attachInternals()}catch{return this.inertInternals()}}inertInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:false,setFormValue:()=>{},setValidity:()=>{},checkValidity:()=>true,reportValidity:()=>true,states:new Set}}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 value(){return this._value}set value(next){const old=this._value;this._value=normalizeGraphQuery(next);this.syncFormState();this.requestUpdate("value",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 disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);if(this.validityController)this.syncFormState();this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get errors(){return{...this._errors}}[VALIDITY_ANCHOR](){const firstInvalidPart=Object.keys(this._errors)[0];if(!firstInvalidPart||!this.renderRoot)return void 0;return this.renderRoot.querySelector(`[part="${firstInvalidPart}"]`)??void 0}computeValidation(){const errors={};const flags={};if(!this._value.startId.trim()){errors["start-input"]=this.localize("fieldRequired");flags.valueMissing=true}if(this._value.minHops>this._value.maxHops){errors["max-hops"]=this.localize("graphQueryHopRangeInvalid");flags.rangeUnderflow=true}return{errors,flags}}syncFormState(){const{errors,flags}=this.computeValidation();this._errors=errors;let formValue=null;try{formValue=JSON.stringify(this._value)}catch{formValue=null}this.internals.setFormValue(formValue,formValue);if(this.barredFromValidation||Object.keys(flags).length===0){this.validityController.setValidity({})}else{const message=Object.values(errors)[0]??"";this.validityController.setValidity(flags,message)}this.syncValidityCustomStates()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}syncValidityCustomStates(){syncValidityStates(this.internals,{required:true,hasInteracted:this.hasInteracted,barred:this.barredFromValidation})}checkValidity(){this.syncFormState();return this.internals.checkValidity()}reportValidity(){this.hasInteracted=true;this.syncFormState();if(Object.keys(this._errors).length>0){this.touchedFields=new Set([...this.touchedFields,...Object.keys(this._errors)])}return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.syncValidityCustomStates()}formResetCallback(){this.hasInteracted=false;this.value=EMPTY_VALUE;this.touchedFields=new Set;this.saveName=""}formStateRestoreCallback(state2,_mode){let restored=EMPTY_VALUE;if(typeof state2==="string"){try{const parsed=JSON.parse(state2);if(parsed!==null&&typeof parsed==="object"&&!Array.isArray(parsed)){restored=normalizeGraphQuery(parsed)}}catch{}}this.value=restored}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;this.syncFormState();this.requestUpdate()}setValue(next){if(this.effectiveDisabled)return;this.hasInteracted=true;this.value=next;this.emit("lr-input",{value:{...this._value}})}addRelationshipType(type){if(!type||this._value.relationshipTypes.includes(type))return;this.setValue({...this._value,relationshipTypes:[...this._value.relationshipTypes,type]})}removeRelationshipType(type){this.setValue({...this._value,relationshipTypes:this._value.relationshipTypes.filter(t=>t!==type)})}addNodeType(type){if(!type||this._value.nodeTypes.includes(type))return;this.setValue({...this._value,nodeTypes:[...this._value.nodeTypes,type]})}removeNodeType(type){this.setValue({...this._value,nodeTypes:this._value.nodeTypes.filter(t=>t!==type)})}markTouched(part){this.hasInteracted=true;this.syncValidityCustomStates();if(this.touchedFields.has(part))return;this.touchedFields=new Set(this.touchedFields).add(part)}runQuery(){if(this.effectiveDisabled)return;if(!this.reportValidity())return;this.emit("lr-query-run",{query:{...this._value}})}saveQuery(){if(this.effectiveDisabled)return;const name=this.saveName.trim();if(!name)return;this.emit("lr-query-save",{name,query:{...this._value}});this.saveName=""}loadQuery(item){if(this.effectiveDisabled)return;this.setValue({...EMPTY_VALUE,...item.query});this.emit("lr-query-load",{id:item.id,query:{...this._value}})}deleteQuery(item){if(this.effectiveDisabled)return;this.emit("lr-query-delete",{id:item.id})}updated(changed){if(changed.has("value")||changed.has("_errors")){const valid=Object.keys(this._errors).length===0;const key=JSON.stringify({valid,errors:this._errors});if(key!==this.lastValidityKey){this.lastValidityKey=key;this.emit("lr-validity-change",{valid,errors:{...this._errors}})}}}hopOptions(){const limit=finiteInteger(this.hopLimit,6,1,20);const options=new Set(Array.from({length:limit},(_,i)=>i+1));options.add(this._value.minHops);options.add(this._value.maxHops);return[...options].sort((a,b)=>a-b)}labelForType(options,value){return options.find(o=>o.value===value)?.label??value}renderTypeFilter(kind,options,selected,add,remove,disabled){const pickerPart=kind==="relationship"?"relationship-picker":"node-type-picker";const chipsPart=kind==="relationship"?"relationship-chips":"node-type-chips";const pickerLabel=kind==="relationship"?this.localize("graphQueryRelationshipTypeLabel"):this.localize("graphQueryNodeTypeLabel");const available=options.filter(o=>!selected.includes(o.value));return html`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{closeIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{finiteInteger}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{nextId}from"../../../internal/a11y.js";import{styles}from"./graph-query-builder.styles.js";import"../../forms/select/select.class.js";import"../../forms/combobox/option.class.js";import"../../forms/input/input.class.js";import"../../overlays/chip/chip.class.js";import"../../overlays/chip/chip-group.class.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,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_graphQueryBuilderLabel,LYRA_DEFAULT_graphQueryDeleteWithContext,LYRA_DEFAULT_graphQueryDirectionLabel,LYRA_DEFAULT_graphQueryEndLabel,LYRA_DEFAULT_graphQueryHopRangeInvalid,LYRA_DEFAULT_graphQueryLoadWithContext,LYRA_DEFAULT_graphQueryMaxHopsLabel,LYRA_DEFAULT_graphQueryMinHopsLabel,LYRA_DEFAULT_graphQueryNodeTypeLabel,LYRA_DEFAULT_graphQueryRelationshipTypeLabel,LYRA_DEFAULT_graphQueryRun,LYRA_DEFAULT_graphQuerySaveButton,LYRA_DEFAULT_graphQuerySaveNameLabel,LYRA_DEFAULT_graphQuerySavedQueriesLabel,LYRA_DEFAULT_graphQueryStartLabel,LYRA_DEFAULT_neighborDirectionBoth,LYRA_DEFAULT_neighborDirectionIn,LYRA_DEFAULT_neighborDirectionOut,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const EMPTY_VALUE={startId:"",endId:"",relationshipTypes:[],nodeTypes:[],direction:"both",minHops:1,maxHops:1};const EMPTY_OPTIONS=[];const EMPTY_SAVED=[];function stringArray(value){if(!Array.isArray(value))return[];return[...new Set(value.filter(entry=>typeof entry==="string"))]}function normalizeGraphQuery(value){const record=value!==null&&typeof value==="object"&&!Array.isArray(value)?value:{};const direction=record["direction"];return{startId:typeof record["startId"]==="string"?record["startId"]:"",endId:typeof record["endId"]==="string"?record["endId"]:"",relationshipTypes:stringArray(record["relationshipTypes"]),nodeTypes:stringArray(record["nodeTypes"]),direction:direction==="out"||direction==="in"||direction==="both"?direction:"both",minHops:finiteInteger(typeof record["minHops"]==="number"?record["minHops"]:EMPTY_VALUE.minHops,EMPTY_VALUE.minHops,1,20),maxHops:finiteInteger(typeof record["maxHops"]==="number"?record["maxHops"]:EMPTY_VALUE.maxHops,EMPTY_VALUE.maxHops,1,20)}}class LyraGraphQueryBuilder extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,graphQueryBuilderLabel:LYRA_DEFAULT_graphQueryBuilderLabel,graphQueryDeleteWithContext:LYRA_DEFAULT_graphQueryDeleteWithContext,graphQueryDirectionLabel:LYRA_DEFAULT_graphQueryDirectionLabel,graphQueryEndLabel:LYRA_DEFAULT_graphQueryEndLabel,graphQueryHopRangeInvalid:LYRA_DEFAULT_graphQueryHopRangeInvalid,graphQueryLoadWithContext:LYRA_DEFAULT_graphQueryLoadWithContext,graphQueryMaxHopsLabel:LYRA_DEFAULT_graphQueryMaxHopsLabel,graphQueryMinHopsLabel:LYRA_DEFAULT_graphQueryMinHopsLabel,graphQueryNodeTypeLabel:LYRA_DEFAULT_graphQueryNodeTypeLabel,graphQueryRelationshipTypeLabel:LYRA_DEFAULT_graphQueryRelationshipTypeLabel,graphQueryRun:LYRA_DEFAULT_graphQueryRun,graphQuerySaveButton:LYRA_DEFAULT_graphQuerySaveButton,graphQuerySaveNameLabel:LYRA_DEFAULT_graphQuerySaveNameLabel,graphQuerySavedQueriesLabel:LYRA_DEFAULT_graphQuerySavedQueriesLabel,graphQueryStartLabel:LYRA_DEFAULT_graphQueryStartLabel,neighborDirectionBoth:LYRA_DEFAULT_neighborDirectionBoth,neighborDirectionIn:LYRA_DEFAULT_neighborDirectionIn,neighborDirectionOut:LYRA_DEFAULT_neighborDirectionOut,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},name:{reflect:true,noAccessor:true},value:{attribute:false,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true}}}constructor(){super();this.relationshipTypeOptions=EMPTY_OPTIONS;this.nodeTypeOptions=EMPTY_OPTIONS;this.savedQueries=EMPTY_SAVED;this.hopLimit=6;this.label="";this.hint="";this.errorText="";this._errors={};this.touchedFields=new Set;this.saveName="";this.hasHintSlot=false;this.hasErrorSlot=false;this.labelId=nextId("graph-query-builder-label");this.hintId=nextId("graph-query-builder-hint");this.errorId=nextId("graph-query-builder-error");this._fieldsetDisabled=false;this._name="";this._value=EMPTY_VALUE;this._disabled=false;this.hasInteracted=false;this.onChromeSlotChange=event=>{const slot=event.currentTarget;const hasContent=slot.assignedNodes({flatten:true}).some(node=>node.nodeType===Node.TEXT_NODE?Boolean(node.textContent?.trim()):true);if(slot.name==="hint")this.hasHintSlot=hasContent;else if(slot.name==="error")this.hasErrorSlot=hasContent};this.internals=this.safeAttachInternals();this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);installInvalidEventAlias(this,()=>this.emit("lr-invalid"));this.syncFormState()}safeAttachInternals(){if(typeof globalThis.ElementInternals==="undefined"){return this.inertInternals()}try{return this.attachInternals()}catch{return this.inertInternals()}}inertInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:false,setFormValue:()=>{},setValidity:()=>{},checkValidity:()=>true,reportValidity:()=>true,states:new Set}}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 value(){return this._value}set value(next){const old=this._value;this._value=normalizeGraphQuery(next);this.syncFormState();this.requestUpdate("value",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 disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);if(this.validityController)this.syncFormState();this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get errors(){return{...this._errors}}[VALIDITY_ANCHOR](){const firstInvalidPart=Object.keys(this._errors)[0];if(!firstInvalidPart||!this.renderRoot)return void 0;return this.renderRoot.querySelector(`[part="${firstInvalidPart}"]`)??void 0}computeValidation(){const errors={};const flags={};if(!this._value.startId.trim()){errors["start-input"]=this.localize("fieldRequired");flags.valueMissing=true}if(this._value.minHops>this._value.maxHops){errors["max-hops"]=this.localize("graphQueryHopRangeInvalid");flags.rangeUnderflow=true}return{errors,flags}}syncFormState(){const{errors,flags}=this.computeValidation();this._errors=errors;let formValue=null;try{formValue=JSON.stringify(this._value)}catch{formValue=null}this.internals.setFormValue(formValue,formValue);if(this.barredFromValidation||Object.keys(flags).length===0){this.validityController.setValidity({})}else{const message=Object.values(errors)[0]??"";this.validityController.setValidity(flags,message)}this.syncValidityCustomStates()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}syncValidityCustomStates(){syncValidityStates(this.internals,{required:true,hasInteracted:this.hasInteracted,barred:this.barredFromValidation})}checkValidity(){this.syncFormState();return this.internals.checkValidity()}reportValidity(){this.hasInteracted=true;this.syncFormState();if(Object.keys(this._errors).length>0){this.touchedFields=new Set([...this.touchedFields,...Object.keys(this._errors)])}return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.syncValidityCustomStates()}formResetCallback(){this.hasInteracted=false;this.value=EMPTY_VALUE;this.touchedFields=new Set;this.saveName=""}formStateRestoreCallback(state2,_mode){let restored=EMPTY_VALUE;if(typeof state2==="string"){try{const parsed=JSON.parse(state2);if(parsed!==null&&typeof parsed==="object"&&!Array.isArray(parsed)){restored=normalizeGraphQuery(parsed)}}catch{}}this.value=restored}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;this.syncFormState();this.requestUpdate()}focusFirstControl(){if(!this.renderRoot||this.effectiveDisabled)return;const control=this.renderRoot.querySelector('[part="start-input"]')||this.renderRoot.querySelector('[part="end-input"]')||this.renderRoot.querySelector('[part="min-hops"]')||this.renderRoot.querySelector('[part="max-hops"]')||this.renderRoot.querySelector('[part="direction"]')||this.renderRoot.querySelector('[part="save-name-input"]');control?.focus()}click(){this.focusFirstControl()}setValue(next){if(this.effectiveDisabled)return;this.hasInteracted=true;this.value=next;this.emit("lr-input",{value:{...this._value}})}addRelationshipType(type){if(!type||this._value.relationshipTypes.includes(type))return;this.setValue({...this._value,relationshipTypes:[...this._value.relationshipTypes,type]})}removeRelationshipType(type){this.setValue({...this._value,relationshipTypes:this._value.relationshipTypes.filter(t=>t!==type)})}addNodeType(type){if(!type||this._value.nodeTypes.includes(type))return;this.setValue({...this._value,nodeTypes:[...this._value.nodeTypes,type]})}removeNodeType(type){this.setValue({...this._value,nodeTypes:this._value.nodeTypes.filter(t=>t!==type)})}markTouched(part){this.hasInteracted=true;this.syncValidityCustomStates();if(this.touchedFields.has(part))return;this.touchedFields=new Set(this.touchedFields).add(part)}runQuery(){if(this.effectiveDisabled)return;if(!this.reportValidity())return;this.emit("lr-query-run",{query:{...this._value}})}saveQuery(){if(this.effectiveDisabled)return;const name=this.saveName.trim();if(!name)return;this.emit("lr-query-save",{name,query:{...this._value}});this.saveName=""}loadQuery(item){if(this.effectiveDisabled)return;this.setValue({...EMPTY_VALUE,...item.query});this.emit("lr-query-load",{id:item.id,query:{...this._value}})}deleteQuery(item){if(this.effectiveDisabled)return;this.emit("lr-query-delete",{id:item.id})}updated(changed){if(changed.has("value")||changed.has("_errors")){const valid=Object.keys(this._errors).length===0;const key=JSON.stringify({valid,errors:this._errors});if(key!==this.lastValidityKey){this.lastValidityKey=key;this.emit("lr-validity-change",{valid,errors:{...this._errors}})}}}hopOptions(){const limit=finiteInteger(this.hopLimit,6,1,20);const options=new Set(Array.from({length:limit},(_,i)=>i+1));options.add(this._value.minHops);options.add(this._value.maxHops);return[...options].sort((a,b)=>a-b)}labelForType(options,value){return options.find(o=>o.value===value)?.label??value}renderTypeFilter(kind,options,selected,add,remove,disabled){const pickerPart=kind==="relationship"?"relationship-picker":"node-type-picker";const chipsPart=kind==="relationship"?"relationship-chips":"node-type-chips";const pickerLabel=kind==="relationship"?this.localize("graphQueryRelationshipTypeLabel"):this.localize("graphQueryNodeTypeLabel");const available=options.filter(o=>!selected.includes(o.value));return html`
|
|
2
2
|
<div part="filter-group" data-kind=${kind}>
|
|
3
3
|
<lr-select
|
|
4
4
|
part=${pickerPart}
|
|
@@ -26,7 +26,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
26
26
|
aria-hidden="true"
|
|
27
27
|
focusable="false"
|
|
28
28
|
><line x1="5" y1="12" x2="19" y2="12"></line></svg>
|
|
29
|
-
`}class LyraCheckbox extends LyraElement{static{this.defaultStrings={...super.defaultStrings,checkboxRequired:LYRA_DEFAULT_checkboxRequired,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore}}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},indeterminate:{type:Boolean,reflect: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||this._groupDisabled}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 indeterminate(){return this._indeterminate}set indeterminate(next){const old=this._indeterminate;this._indeterminate=Boolean(next);this.syncFormState();this.requestUpdate("indeterminate",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.shoelaceDefaultChecked=false;this.hasLabelSlot=false;this.hasHintSlot=false;this.hasHelpTextSlot=false;this.touched=false;this.hasInteracted=false;this.hasSyncedDescribedByElements=false;this._defaultChecked=false;this._checkedDirty=false;this.settingDefaultChecked=false;this.reflectingDefaultChecked=false;this.hadShoelaceDefaultChecked=false;this._fieldsetDisabled=false;this._groupDisabled=false;this._name="";this._checked=false;this._indeterminate=false;this._disabled=false;this._required=false;this._value="on";this.onClick=()=>{this.toggle()};this.onKeyDown=e=>{if(this.effectiveDisabled)return;if(e.key===" "||e.key==="Spacebar"){e.preventDefault();this.toggle()}};this.onSlotChange=event=>this.handleLabelSlotChange(event);this.onHintSlotChange=event=>{this.hasHintSlot=event.target.assignedElements({flatten:true}).length>0};this.onHelpTextSlotChange=event=>{this.hasHelpTextSlot=event.target.assignedElements({flatten:true}).length>0};this.onLabelSlotChange=event=>this.handleLabelSlotChange(event);this.onBlur=event=>{this.touched=true;this.hasInteracted=true;this.reflectInvalid();relayNativeEvent(this,event);this.emit("lr-blur")};this.onFocus=event=>{relayNativeEvent(this,event);this.emit("lr-focus")};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}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.recomputeHasLabelSlot()}else{this.seedFirstRenderState(()=>{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")})}}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")}}updated(changed){super.updated(changed);const describedBy=this.getAttribute("aria-describedby");const hint=this.renderRoot.querySelector("#checkbox-hint");if(!describedBy&&!this.hasSyncedDescribedByElements&&(!hint||hint.hidden))return;const control=this.renderRoot.querySelector('[part~="base"]')??void 0;this.hasSyncedDescribedByElements=syncAriaDescribedByElements(this,control,describedBy);if(hint&&!hint.hidden&&control&&"ariaDescribedByElements"in control){const reflected=control;const current=reflected.ariaDescribedByElements??[];reflected.ariaDescribedByElements=[...current.filter(element=>element!==hint),hint]}}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("checkboxRequired"))}else{this.validityController.setValidity({})}this.reflectInvalid()}reflectInvalid(){const barred=this.barredFromValidation;this.toggleAttribute("data-invalid",!barred&&this.touched&&!this.internals.validity.valid);syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred});setCustomState(this.internals,"checked",this.checked);setCustomState(this.internals,"indeterminate",this.indeterminate);setCustomState(this.internals,"disabled",this.effectiveDisabled)}syncFormState(){const state2=`${this.checked?"checked":"unchecked"}${this.indeterminate?"/indeterminate":""}`;this.internals.setFormValue(this.checked?this.value:null,state2);this.updateValidity()}formResetCallback(){this.restoreCheckedFromDefault();this.touched=false;this.hasInteracted=false;this.reflectInvalid()}formStateRestoreCallback(state2,reason){void reason;const oldChecked=this._checked;const oldIndeterminate=this._indeterminate;this._checked=state2==="checked"||state2==="checked/indeterminate";this._checkedDirty=true;this._indeterminate=state2==="checked/indeterminate"||state2==="unchecked/indeterminate";this.syncFormState();this.requestUpdate("checked",oldChecked);this.requestUpdate("indeterminate",oldIndeterminate)}resetFromGroup(){this.restoreCheckedFromDefault()}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()}setGroupDisabled(value){if(this._groupDisabled===value)return;this._groupDisabled=value;this.updateValidity();this.requestUpdate()}checkValidity(){this.updateValidity();return this.internals.checkValidity()}reportValidity(){this.updateValidity();this.hasInteracted=true;this.reflectInvalid();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.reflectInvalid();this.requestUpdate()}resetValidity(){this.setCustomValidity("")}click(){if(!this.effectiveDisabled)this[VALIDITY_ANCHOR]()?.click()}focus(options){if(!this.effectiveDisabled)this[VALIDITY_ANCHOR]()?.focus(options)}blur(){this[VALIDITY_ANCHOR]()?.blur()}toggle(){if(this.effectiveDisabled)return;this.hasInteracted=true;this.checked=!this.checked;this.indeterminate=false;dispatchNativeEvent(this,"input");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)}}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()}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)}render(){const mixed=this.indeterminate;const hasHint=this.hasHintSlot||this.hasHelpTextSlot||Boolean(this.hint||this.helpText);const controlParts=["box","control",this.checked?"checked control--checked":"",mixed?"indeterminate control--indeterminate":""].filter(Boolean).join(" ");const describedBy=[this.getAttribute("aria-describedby")??"",hasHint?"checkbox-hint":""].filter(Boolean).join(" ");return html`
|
|
29
|
+
`}class LyraCheckbox extends LyraElement{static{this.defaultStrings={...super.defaultStrings,checkboxRequired:LYRA_DEFAULT_checkboxRequired,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore}}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},indeterminate:{type:Boolean,reflect: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||this._groupDisabled}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 indeterminate(){return this._indeterminate}set indeterminate(next){const old=this._indeterminate;this._indeterminate=Boolean(next);this.syncFormState();this.requestUpdate("indeterminate",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.shoelaceDefaultChecked=false;this.hasLabelSlot=false;this.hasHintSlot=false;this.hasHelpTextSlot=false;this.touched=false;this.hasInteracted=false;this.hasSyncedDescribedByElements=false;this._defaultChecked=false;this._checkedDirty=false;this.settingDefaultChecked=false;this.reflectingDefaultChecked=false;this.hadShoelaceDefaultChecked=false;this._fieldsetDisabled=false;this._groupDisabled=false;this._name="";this._checked=false;this._indeterminate=false;this._disabled=false;this._required=false;this._value="on";this.onClick=()=>{this.toggle()};this.onKeyDown=e=>{if(this.effectiveDisabled)return;if(e.key===" "||e.key==="Spacebar"){e.preventDefault();this.toggle()}};this.onSlotChange=event=>this.handleLabelSlotChange(event);this.onHintSlotChange=event=>{this.hasHintSlot=event.target.assignedElements({flatten:true}).length>0};this.onHelpTextSlotChange=event=>{this.hasHelpTextSlot=event.target.assignedElements({flatten:true}).length>0};this.onLabelSlotChange=event=>this.handleLabelSlotChange(event);this.onBlur=event=>{if(!this.effectiveDisabled&&!this.matches(":disabled")){this.touched=true;this.hasInteracted=true;this.reflectInvalid()}relayNativeEvent(this,event);this.emit("lr-blur")};this.onFocus=event=>{relayNativeEvent(this,event);this.emit("lr-focus")};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}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.recomputeHasLabelSlot()}else{this.seedFirstRenderState(()=>{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")})}}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")}}updated(changed){super.updated(changed);const describedBy=this.getAttribute("aria-describedby");const hint=this.renderRoot.querySelector("#checkbox-hint");if(!describedBy&&!this.hasSyncedDescribedByElements&&(!hint||hint.hidden))return;const control=this.renderRoot.querySelector('[part~="base"]')??void 0;this.hasSyncedDescribedByElements=syncAriaDescribedByElements(this,control,describedBy);if(hint&&!hint.hidden&&control&&"ariaDescribedByElements"in control){const reflected=control;const current=reflected.ariaDescribedByElements??[];reflected.ariaDescribedByElements=[...current.filter(element=>element!==hint),hint]}}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("checkboxRequired"))}else{this.validityController.setValidity({})}this.reflectInvalid()}reflectInvalid(){const barred=this.barredFromValidation;this.toggleAttribute("data-invalid",!barred&&this.touched&&!this.internals.validity.valid);syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred});setCustomState(this.internals,"checked",this.checked);setCustomState(this.internals,"indeterminate",this.indeterminate);setCustomState(this.internals,"disabled",this.effectiveDisabled)}syncFormState(){const state2=`${this.checked?"checked":"unchecked"}${this.indeterminate?"/indeterminate":""}`;this.internals.setFormValue(this.checked?this.value:null,state2);this.updateValidity()}formResetCallback(){this.restoreCheckedFromDefault();this.touched=false;this.hasInteracted=false;this.reflectInvalid()}formStateRestoreCallback(state2,reason){void reason;const oldChecked=this._checked;const oldIndeterminate=this._indeterminate;this._checked=state2==="checked"||state2==="checked/indeterminate";this._checkedDirty=true;this._indeterminate=state2==="checked/indeterminate"||state2==="unchecked/indeterminate";this.syncFormState();this.requestUpdate("checked",oldChecked);this.requestUpdate("indeterminate",oldIndeterminate)}resetFromGroup(){this.restoreCheckedFromDefault()}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()}setGroupDisabled(value){if(this._groupDisabled===value)return;this._groupDisabled=value;this.updateValidity();this.requestUpdate()}checkValidity(){this.updateValidity();return this.internals.checkValidity()}reportValidity(){this.updateValidity();this.hasInteracted=true;this.reflectInvalid();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.reflectInvalid();this.requestUpdate()}resetValidity(){this.setCustomValidity("")}click(){if(!this.effectiveDisabled)this[VALIDITY_ANCHOR]()?.click()}focus(options){if(!this.effectiveDisabled)this[VALIDITY_ANCHOR]()?.focus(options)}blur(){this[VALIDITY_ANCHOR]()?.blur()}toggle(){if(this.effectiveDisabled)return;this.hasInteracted=true;this.checked=!this.checked;this.indeterminate=false;dispatchNativeEvent(this,"input");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)}}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()}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)}render(){const mixed=this.indeterminate;const hasHint=this.hasHintSlot||this.hasHelpTextSlot||Boolean(this.hint||this.helpText);const controlParts=["box","control",this.checked?"checked control--checked":"",mixed?"indeterminate control--indeterminate":""].filter(Boolean).join(" ");const describedBy=[this.getAttribute("aria-describedby")??"",hasHint?"checkbox-hint":""].filter(Boolean).join(" ");return html`
|
|
30
30
|
<div>
|
|
31
31
|
<span
|
|
32
32
|
part="base checkbox"
|
|
@@ -229,6 +229,9 @@ export declare class LyraCheckboxGroup extends LyraElement<LyraCheckboxGroupEven
|
|
|
229
229
|
* The message is caller-supplied content, so it is used verbatim and never localized here.
|
|
230
230
|
*/
|
|
231
231
|
setCustomValidity(message: string): void;
|
|
232
|
+
private focusFirstControl;
|
|
233
|
+
/** Forwards host clicks to the first enabled checkbox in the group. */
|
|
234
|
+
click(): void;
|
|
232
235
|
formResetCallback(): void;
|
|
233
236
|
formStateRestoreCallback(state: string | File | FormData | null, _mode?: 'restore' | 'autocomplete'): void;
|
|
234
237
|
formDisabledCallback(disabled: boolean): void;
|
|
@@ -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{syncValidityStates}from"../../../internal/custom-states.js";import{nextId}from"../../../internal/a11y.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./checkbox-group.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_checkboxGroupRequired,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_restore}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}}}function warnValueAssigned(group){console.warn(`<lr-checkbox-group> \`value\` is derived from its <lr-checkbox> children and is overwritten by the next sync (any child toggle, a slot change, a \`name\`/\`required\` change, blur, or form reset), so assigning it has no lasting effect${group.name?` (name="${group.name}")`:""}. Set \`checked\` on the children instead.`)}function warnDuplicateValue(group,value){console.warn(`<lr-checkbox-group> has more than one <lr-checkbox> child with value="${value}"${group.name?` (name="${group.name}")`:""}; every checked one contributes an identical FormData entry, so the submitted data cannot say which was checked. Give each child a distinct \`value\`.`)}class LyraCheckboxGroup extends LyraElement{static{this.defaultStrings={...super.defaultStrings,checkboxGroupRequired:LYRA_DEFAULT_checkboxGroupRequired,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore}}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},size:{reflect:true},orientation:{reflect:true},value:{attribute:false,noAccessor:true}}}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.sync();this.requestUpdate("name",old)}get value(){return this._value}set value(next){if(!this._writingValue&&!this._warnedValueAssigned){this._warnedValueAssigned=true;warnValueAssigned(this)}const old=this._value;this._value=Array.isArray(next)?next:[];this.requestUpdate("value",old)}get required(){return this._required}set required(next){const old=this._required;this._required=Boolean(next);this.toggleAttribute("required",this._required);this.sync();this.requestUpdate("required",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);this.propagateDisabled();this.sync();this.requestUpdate("disabled",old)}constructor(){super();this.size="m";this.orientation="vertical";this.label="";this.hint="";this.withLabel=false;this.withHint=false;this.errorText="";this.accessibleLabel="";this.touched=false;this.hasInteracted=false;this.hasLabelSlot=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.labelId=nextId("checkbox-group-label");this.hintId=nextId("checkbox-group-hint");this.errorId=nextId("checkbox-group-error");this._fieldsetDisabled=false;this._name="";this._required=false;this._disabled=false;this._value=[];this._writingValue=false;this._warnedValueAssigned=false;this._warnedDuplicateValues=new Set;this.childObserverGeneration=0;this.childControllers=new Map;this.onChildEvent=event=>{if(!this.isOwnedCheckbox(event.target))return;event.stopImmediatePropagation();if(event.type!=="change"||this.effectiveDisabled)return;this.hasInteracted=true;this.sync();this.emit("input",{value:this.value});this.emit("change",{value:this.value});this.emit("lr-change",{value:this.value})};this.onChildMutations=records=>{if(records.some(record=>record.type==="childList"||record.attributeName==="slot")){this.onSlotChange();return}if(records.some(record=>record.attributeName==="size"&&this.isOwnedCheckbox(record.target))){this.propagateSize()}if(records.some(record=>this.isOwnedCheckbox(record.target)))this.sync()};this.onSlotChange=()=>{this.hasLabelSlot=this.hasDirectSupportSlot("label");this.hasHintSlot=this.hasDirectSupportSlot("hint");this.hasErrorSlot=this.hasDirectSupportSlot("error");this.reconcileChildControllers();if(!this.applyPendingRestore())this.sync();this.propagateDisabled();this.propagateSize()};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))}checkboxGroupOwner(element){const group=element.closest("lr-checkbox-group");if(!group)return null;let topLevelChild=element;while(topLevelChild.parentElement&&topLevelChild.parentElement!==group){topLevelChild=topLevelChild.parentElement}if(topLevelChild.parentElement!==group)return null;const slot=topLevelChild.getAttribute("slot");return slot==="label"||slot==="hint"||slot==="error"?null:group}ownsCheckbox(element){return element.localName==="lr-checkbox"&&this.checkboxGroupOwner(element)===this}get boxes(){const querySelectorAll=this.querySelectorAll;if(typeof querySelectorAll!=="function")return[];return Array.from(querySelectorAll.call(this,"lr-checkbox")).filter(box=>this.ownsCheckbox(box))}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}propagateDisabled(){const effective=this.effectiveDisabled;this.boxes.forEach(box=>box.setGroupDisabled?.(effective))}propagateSize(){this.boxes.forEach(box=>{box.size=this.size})}readValue(){return this.boxes.filter(box=>box.checked).map(box=>box.value??"on")}warnOnDuplicateValues(){const seen=new Set;for(const box of this.boxes){const value=box.value??box.getAttribute("value")??"on";if(!seen.has(value)){seen.add(value);continue}if(this._warnedDuplicateValues.has(value))continue;this._warnedDuplicateValues.add(value);warnDuplicateValue(this,value)}}sync(){const next=this.readValue();this.warnOnDuplicateValues();this._writingValue=true;try{this.value=next}finally{this._writingValue=false}const data=new FormData;if(this.name)next.forEach(value=>data.append(this.name,value));this.internals.setFormValue(this.name?data:null,createStringArrayFormDataState(this.name,next));if(!this.barredFromValidation&&this.required&&next.length===0)this.validityController.setValidity({valueMissing:true},this.localize("checkboxGroupRequired"));else this.validityController.setValidity({});this.reflectValidityStates()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}reflectValidityStates(){const barred=this.barredFromValidation;this.toggleAttribute("data-invalid",!barred&&this.touched&&!this.internals.validity.valid);syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred})}isOwnedCheckbox(target){return target?.nodeType===1&&this.ownsCheckbox(target)}reconcileChildControllers(){const current=new Set(this.boxes);for(const[box,controller]of this.childControllers){if(current.has(box))continue;box.removeController(controller);this.childControllers.delete(box);const nextOwner=this.checkboxGroupOwner(box);if(!nextOwner||nextOwner===this)box.setGroupDisabled?.(false)}for(const box of current){if(this.childControllers.has(box)||typeof box.addController!=="function")continue;const controller={hostUpdated:()=>{if(this.isConnected&&this.ownsCheckbox(box))this.sync()}};box.addController(controller);this.childControllers.set(box,controller)}}hasDirectSupportSlot(name){return Array.from(this.children).some(child=>child.getAttribute("slot")===name)}applyPendingRestore(){if(this.pendingRestoreValues===void 0||this.boxes.length===0)return false;const remaining=[...this.pendingRestoreValues];this.pendingRestoreValues=void 0;for(const box of this.boxes){const value=box.value??"on";const index=remaining.indexOf(value);box.checked=index>=0;if(index>=0)remaining.splice(index,1)}this.touched=false;this.hasInteracted=false;this.sync();return true}connectedCallback(){super.connectedCallback();this.addEventListener("input",this.onChildEvent);this.addEventListener("change",this.onChildEvent);this.addEventListener("lr-change",this.onChildEvent);this.onSlotChange();this.armChildObserver()}armChildObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected)return;if(this.childObserver&&this.childObserverDocument===ownerDocument)return;this.resetChildObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.childObserverGeneration;const observer=new MutationObserverCtor(records=>{if(this.childObserver!==observer||this.childObserverDocument!==ownerDocument||this.childObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.onChildMutations(records)});this.childObserver=observer;this.childObserverDocument=ownerDocument;observer.observe(this,{attributes:true,childList:true,subtree:true,attributeFilter:["checked","value","disabled","size","slot"]})}disconnectedCallback(){this.removeEventListener("input",this.onChildEvent);this.removeEventListener("change",this.onChildEvent);this.removeEventListener("lr-change",this.onChildEvent);this.resetChildObserver();for(const[box,controller]of this.childControllers){box.removeController(controller);box.setGroupDisabled?.(false)}this.childControllers.clear();super.disconnectedCallback()}adoptedCallback(){this.resetChildObserver()}resetChildObserver(){this.childObserverGeneration+=1;this.childObserver?.disconnect();this.childObserver=void 0;this.childObserverDocument=void 0}firstUpdated(){this.addEventListener("blur",()=>{this.touched=true;this.hasInteracted=true;this.sync()},true)}updated(changed){super.updated(changed);if(changed.has("size"))this.propagateSize()}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part~="options"]')??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}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()}formResetCallback(){this.boxes.forEach(box=>box.resetFromGroup());this.touched=false;this.hasInteracted=false;this.sync()}formStateRestoreCallback(state2,_mode){this.pendingRestoreValues=readStringArrayFormDataState(state2);this.applyPendingRestore()}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;this.propagateDisabled();this.sync();this.requestUpdate()}render(){const hasLabel=this.hasLabelSlot||Boolean(this.label)||this.withLabel;const hasHint=this.hasHintSlot||Boolean(this.hint)||this.withHint;const described=[hasHint?this.hintId:"",this.hasErrorSlot||this.errorText?this.errorId:""].filter(Boolean).join(" ")||nothing;return html`<fieldset
|
|
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{syncValidityStates}from"../../../internal/custom-states.js";import{nextId}from"../../../internal/a11y.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./checkbox-group.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_checkboxGroupRequired,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_restore}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}}}function warnValueAssigned(group){console.warn(`<lr-checkbox-group> \`value\` is derived from its <lr-checkbox> children and is overwritten by the next sync (any child toggle, a slot change, a \`name\`/\`required\` change, blur, or form reset), so assigning it has no lasting effect${group.name?` (name="${group.name}")`:""}. Set \`checked\` on the children instead.`)}function warnDuplicateValue(group,value){console.warn(`<lr-checkbox-group> has more than one <lr-checkbox> child with value="${value}"${group.name?` (name="${group.name}")`:""}; every checked one contributes an identical FormData entry, so the submitted data cannot say which was checked. Give each child a distinct \`value\`.`)}class LyraCheckboxGroup extends LyraElement{static{this.defaultStrings={...super.defaultStrings,checkboxGroupRequired:LYRA_DEFAULT_checkboxGroupRequired,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore}}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},size:{reflect:true},orientation:{reflect:true},value:{attribute:false,noAccessor:true}}}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.sync();this.requestUpdate("name",old)}get value(){return this._value}set value(next){if(!this._writingValue&&!this._warnedValueAssigned){this._warnedValueAssigned=true;warnValueAssigned(this)}const old=this._value;this._value=Array.isArray(next)?next:[];this.requestUpdate("value",old)}get required(){return this._required}set required(next){const old=this._required;this._required=Boolean(next);this.toggleAttribute("required",this._required);this.sync();this.requestUpdate("required",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);this.propagateDisabled();this.sync();this.requestUpdate("disabled",old)}constructor(){super();this.size="m";this.orientation="vertical";this.label="";this.hint="";this.withLabel=false;this.withHint=false;this.errorText="";this.accessibleLabel="";this.touched=false;this.hasInteracted=false;this.hasLabelSlot=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.labelId=nextId("checkbox-group-label");this.hintId=nextId("checkbox-group-hint");this.errorId=nextId("checkbox-group-error");this._fieldsetDisabled=false;this._name="";this._required=false;this._disabled=false;this._value=[];this._writingValue=false;this._warnedValueAssigned=false;this._warnedDuplicateValues=new Set;this.childObserverGeneration=0;this.childControllers=new Map;this.onChildEvent=event=>{if(!this.isOwnedCheckbox(event.target))return;event.stopImmediatePropagation();if(event.type!=="change"||this.effectiveDisabled)return;this.hasInteracted=true;this.sync();this.emit("input",{value:this.value});this.emit("change",{value:this.value});this.emit("lr-change",{value:this.value})};this.onChildMutations=records=>{if(records.some(record=>record.type==="childList"||record.attributeName==="slot")){this.onSlotChange();return}if(records.some(record=>record.attributeName==="size"&&this.isOwnedCheckbox(record.target))){this.propagateSize()}if(records.some(record=>this.isOwnedCheckbox(record.target)))this.sync()};this.onSlotChange=()=>{this.hasLabelSlot=this.hasDirectSupportSlot("label");this.hasHintSlot=this.hasDirectSupportSlot("hint");this.hasErrorSlot=this.hasDirectSupportSlot("error");this.reconcileChildControllers();if(!this.applyPendingRestore())this.sync();this.propagateDisabled();this.propagateSize()};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))}checkboxGroupOwner(element){const group=element.closest("lr-checkbox-group");if(!group)return null;let topLevelChild=element;while(topLevelChild.parentElement&&topLevelChild.parentElement!==group){topLevelChild=topLevelChild.parentElement}if(topLevelChild.parentElement!==group)return null;const slot=topLevelChild.getAttribute("slot");return slot==="label"||slot==="hint"||slot==="error"?null:group}ownsCheckbox(element){return element.localName==="lr-checkbox"&&this.checkboxGroupOwner(element)===this}get boxes(){const querySelectorAll=this.querySelectorAll;if(typeof querySelectorAll!=="function")return[];return Array.from(querySelectorAll.call(this,"lr-checkbox")).filter(box=>this.ownsCheckbox(box))}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}propagateDisabled(){const effective=this.effectiveDisabled;this.boxes.forEach(box=>box.setGroupDisabled?.(effective))}propagateSize(){this.boxes.forEach(box=>{box.size=this.size})}readValue(){return this.boxes.filter(box=>box.checked).map(box=>box.value??"on")}warnOnDuplicateValues(){const seen=new Set;for(const box of this.boxes){const value=box.value??box.getAttribute("value")??"on";if(!seen.has(value)){seen.add(value);continue}if(this._warnedDuplicateValues.has(value))continue;this._warnedDuplicateValues.add(value);warnDuplicateValue(this,value)}}sync(){const next=this.readValue();this.warnOnDuplicateValues();this._writingValue=true;try{this.value=next}finally{this._writingValue=false}const data=new FormData;if(this.name)next.forEach(value=>data.append(this.name,value));this.internals.setFormValue(this.name?data:null,createStringArrayFormDataState(this.name,next));if(!this.barredFromValidation&&this.required&&next.length===0)this.validityController.setValidity({valueMissing:true},this.localize("checkboxGroupRequired"));else this.validityController.setValidity({});this.reflectValidityStates()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}reflectValidityStates(){const barred=this.barredFromValidation;this.toggleAttribute("data-invalid",!barred&&this.touched&&!this.internals.validity.valid);syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred})}isOwnedCheckbox(target){return target?.nodeType===1&&this.ownsCheckbox(target)}reconcileChildControllers(){const current=new Set(this.boxes);for(const[box,controller]of this.childControllers){if(current.has(box))continue;box.removeController(controller);this.childControllers.delete(box);const nextOwner=this.checkboxGroupOwner(box);if(!nextOwner||nextOwner===this)box.setGroupDisabled?.(false)}for(const box of current){if(this.childControllers.has(box)||typeof box.addController!=="function")continue;const controller={hostUpdated:()=>{if(this.isConnected&&this.ownsCheckbox(box))this.sync()}};box.addController(controller);this.childControllers.set(box,controller)}}hasDirectSupportSlot(name){return Array.from(this.children).some(child=>child.getAttribute("slot")===name)}applyPendingRestore(){if(this.pendingRestoreValues===void 0||this.boxes.length===0)return false;const remaining=[...this.pendingRestoreValues];this.pendingRestoreValues=void 0;for(const box of this.boxes){const value=box.value??"on";const index=remaining.indexOf(value);box.checked=index>=0;if(index>=0)remaining.splice(index,1)}this.touched=false;this.hasInteracted=false;this.sync();return true}connectedCallback(){super.connectedCallback();this.addEventListener("input",this.onChildEvent);this.addEventListener("change",this.onChildEvent);this.addEventListener("lr-change",this.onChildEvent);this.onSlotChange();this.armChildObserver()}armChildObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected)return;if(this.childObserver&&this.childObserverDocument===ownerDocument)return;this.resetChildObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.childObserverGeneration;const observer=new MutationObserverCtor(records=>{if(this.childObserver!==observer||this.childObserverDocument!==ownerDocument||this.childObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.onChildMutations(records)});this.childObserver=observer;this.childObserverDocument=ownerDocument;observer.observe(this,{attributes:true,childList:true,subtree:true,attributeFilter:["checked","value","disabled","size","slot"]})}disconnectedCallback(){this.removeEventListener("input",this.onChildEvent);this.removeEventListener("change",this.onChildEvent);this.removeEventListener("lr-change",this.onChildEvent);this.resetChildObserver();for(const[box,controller]of this.childControllers){box.removeController(controller);box.setGroupDisabled?.(false)}this.childControllers.clear();super.disconnectedCallback()}adoptedCallback(){this.resetChildObserver()}resetChildObserver(){this.childObserverGeneration+=1;this.childObserver?.disconnect();this.childObserver=void 0;this.childObserverDocument=void 0}firstUpdated(){this.addEventListener("blur",event=>{const blurredControl=event.target;const disabled=typeof blurredControl?.matches==="function"?blurredControl.matches(":disabled"):this.effectiveDisabled;if(!disabled){this.touched=true;this.hasInteracted=true}this.sync()},true)}updated(changed){super.updated(changed);if(changed.has("size"))this.propagateSize()}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part~="options"]')??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}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()}focusFirstControl(){const first=this.boxes.find(box=>!box.effectiveDisabled);first?.focus()}click(){this.focusFirstControl()}formResetCallback(){this.boxes.forEach(box=>box.resetFromGroup());this.touched=false;this.hasInteracted=false;this.sync()}formStateRestoreCallback(state2,_mode){this.pendingRestoreValues=readStringArrayFormDataState(state2);this.applyPendingRestore()}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;this.propagateDisabled();this.sync();this.requestUpdate()}render(){const hasLabel=this.hasLabelSlot||Boolean(this.label)||this.withLabel;const hasHint=this.hasHintSlot||Boolean(this.hint)||this.withHint;const described=[hasHint?this.hintId:"",this.hasErrorSlot||this.errorText?this.errorId:""].filter(Boolean).join(" ")||nothing;return html`<fieldset
|
|
2
2
|
part="form-control"
|
|
3
3
|
?disabled=${this.effectiveDisabled}
|
|
4
4
|
aria-label=${this.accessibleLabel||nothing}
|