@aceshooting/lyra-ui 30.5.0 → 30.8.0
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 +93 -0
- package/README.md +1 -1
- package/dist/components/agent-tools/artifact-panel/artifact-panel.class.d.ts +7 -4
- package/dist/components/agent-tools/artifact-panel/artifact-panel.class.js +5 -5
- package/dist/components/conversation/code-block/onig.provenance.json +1 -1
- package/dist/components/conversation/markdown/markdown-base.class.d.ts +1 -1
- package/dist/components/conversation/markdown/markdown-base.class.js +1 -1
- package/dist/components/conversation/markdown/markdown-core.class.d.ts +11 -1
- package/dist/components/conversation/markdown/markdown-core.class.js +1 -1
- package/dist/components/conversation/markdown/markdown-progressive.js +2 -2
- package/dist/components/conversation/markdown/markdown-shared.d.ts +7 -2
- package/dist/components/conversation/markdown/markdown-shared.js +3 -3
- package/dist/components/conversation/markdown/markdown.class.d.ts +11 -1
- package/dist/components/conversation/markdown/markdown.class.js +1 -1
- package/dist/components/conversation/message-parts/message-parts.class.d.ts +1 -1
- package/dist/components/conversation/message-parts/message-parts.class.js +1 -1
- package/dist/components/conversation/message-parts/message-parts.d.ts +1 -1
- package/dist/components/conversation/model-select/model-select.class.d.ts +8 -1
- package/dist/components/conversation/model-select/model-select.class.js +2 -2
- package/dist/components/conversation/streaming-text/streaming-text-base.class.d.ts +5 -0
- package/dist/components/conversation/streaming-text/streaming-text-base.class.js +2 -2
- package/dist/components/conversation/streaming-text/streaming-text-core.class.d.ts +1 -1
- package/dist/components/conversation/streaming-text/streaming-text-core.class.js +1 -0
- package/dist/components/conversation/streaming-text/streaming-text.class.d.ts +1 -1
- package/dist/components/conversation/streaming-text/streaming-text.class.js +1 -0
- package/dist/components/conversation/suggestion-chips/suggestion-chips.class.d.ts +6 -0
- package/dist/components/conversation/suggestion-chips/suggestion-chips.styles.js +1 -1
- package/dist/components/conversation/voice-picker/voice-picker.class.d.ts +9 -2
- package/dist/components/conversation/voice-picker/voice-picker.class.js +2 -2
- package/dist/components/conversation/widget-renderer/default-registry.js +1 -1
- package/dist/components/conversation/widget-renderer/registry.d.ts +1 -27
- package/dist/components/conversation/widget-renderer/registry.js +1 -1
- package/dist/components/conversation/widget-renderer/resolve.d.ts +1 -29
- package/dist/components/conversation/widget-renderer/resolve.js +1 -1
- package/dist/components/conversation/widget-renderer/widget-renderer.class.d.ts +1 -1
- package/dist/components/conversation/widget-renderer/widget-renderer.class.js +1 -1
- package/dist/components/forms/catalog-picker-base.d.ts +3 -1
- package/dist/components/forms/catalog-picker-base.js +3 -3
- package/dist/components/forms/combobox/combobox.class.d.ts +9 -2
- package/dist/components/forms/combobox/combobox.class.js +2 -2
- package/dist/components/forms/date-picker/date-input.class.d.ts +9 -2
- package/dist/components/forms/date-picker/date-input.class.js +2 -2
- package/dist/components/forms/input/input-shared.d.ts +9 -2
- package/dist/components/forms/input/input-shared.js +2 -2
- package/dist/components/forms/input/time-input.class.d.ts +9 -2
- package/dist/components/forms/input/time-input.class.js +2 -2
- package/dist/components/forms/input/time-input.styles.js +1 -1
- package/dist/components/forms/locale-picker/locale-picker.class.d.ts +18 -3
- package/dist/components/forms/locale-picker/locale-picker.class.js +2 -2
- package/dist/components/forms/phone-input/phone-input.class.d.ts +9 -2
- package/dist/components/forms/phone-input/phone-input.class.js +2 -2
- package/dist/components/forms/phone-input/phone-input.styles.js +1 -1
- package/dist/components/forms/select/select.class.d.ts +9 -2
- package/dist/components/forms/select/select.class.js +2 -2
- package/dist/components/forms/textarea/textarea.class.d.ts +9 -2
- package/dist/components/forms/textarea/textarea.class.js +2 -2
- package/dist/components/forms/token-input/token-input.class.d.ts +9 -2
- package/dist/components/forms/token-input/token-input.class.js +2 -2
- package/dist/components/forms/token-input/token-input.styles.js +1 -1
- package/dist/components/layout/dock-panel/dock-panel.class.d.ts +35 -7
- package/dist/components/layout/dock-panel/dock-panel.class.js +8 -5
- package/dist/components/layout/dock-panel/dock-panel.styles.js +1 -1
- package/dist/components/layout/menu/menu-item.class.d.ts +7 -4
- package/dist/components/layout/menu/menu-item.class.js +3 -2
- package/dist/components/layout/multi-split/multi-split.class.d.ts +73 -6
- package/dist/components/layout/multi-split/multi-split.class.js +4 -4
- package/dist/components/layout/multi-split/multi-split.styles.js +1 -1
- package/dist/components/layout/page/page.class.d.ts +7 -0
- package/dist/components/layout/page/page.styles.js +1 -1
- package/dist/components/media/flag/language-map.js +1 -1
- package/dist/components/media/image-viewer/image-viewer-panorama.d.ts +1 -5
- package/dist/components/media/image-viewer/image-viewer-panorama.js +1 -8
- package/dist/components/media/image-viewer/image-viewer.class.d.ts +1 -1
- package/dist/components/media/image-viewer/image-viewer.class.js +1 -1
- package/dist/components/media/map/map-control-options.d.ts +7 -3
- package/dist/components/media/map/map-control-options.js +1 -1
- package/dist/components/media/map/map-controls-lifecycle.js +1 -1
- package/dist/components/media/map/map-feature-loader.js +1 -1
- package/dist/components/media/map/map-loader.d.ts +10 -4
- package/dist/components/media/map/map-loader.js +1 -1
- package/dist/components/media/map/map-scene-admission.js +1 -0
- package/dist/components/media/map/map-scene-completion-adapter.js +1 -0
- package/dist/components/media/map/map-scene-completion-camera.js +1 -0
- package/dist/components/media/map/map-scene-configuration-controller.js +1 -0
- package/dist/components/media/map/map-scene-configuration.d.ts +15 -0
- package/dist/components/media/map/map-scene-configuration.js +1 -0
- package/dist/components/media/map/map-scene-controls.js +1 -0
- package/dist/components/media/map/map-scene-elevated-lines.js +36 -0
- package/dist/components/media/map/map-scene-errors.js +1 -0
- package/dist/components/media/map/map-scene-line-encoding.js +1 -0
- package/dist/components/media/map/map-scene-line-layer.js +1 -0
- package/dist/components/media/map/map-scene-lines.js +1 -0
- package/dist/components/media/map/map-scene-owner.js +1 -0
- package/dist/components/media/map/map-scene-position-registry.js +1 -0
- package/dist/components/media/map/map-scene-render-controller.js +1 -0
- package/dist/components/media/map/map-scene-render-input.js +1 -0
- package/dist/components/media/map/map-scene-source-snapshot.js +1 -0
- package/dist/components/media/map/map-scene-status.js +1 -0
- package/dist/components/media/map/map-scene-types.d.ts +60 -0
- package/dist/components/media/map/map.class.d.ts +60 -12
- package/dist/components/media/map/map.class.js +23 -6
- package/dist/components/media/map/map.styles.js +1 -1
- package/dist/components/media/sequence-playback/sequence-playback.class.d.ts +1 -1
- package/dist/components/media/sequence-playback/sequence-playback.class.js +1 -1
- package/dist/components/media/video/video.class.d.ts +1 -1
- package/dist/components/media/video/video.class.js +1 -1
- package/dist/components/retrieval/graph/graph-builtin-3d-engine.js +1 -1
- package/dist/components/retrieval/graph/graph-curvature.js +1 -0
- package/dist/components/retrieval/graph/graph-engine-columns.js +1 -1
- package/dist/components/retrieval/graph/graph-model.d.ts +4 -0
- package/dist/components/retrieval/graph/graph-node-renderer.d.ts +13 -0
- package/dist/components/retrieval/graph/graph-node-renderer.js +1 -0
- package/dist/components/retrieval/graph/graph-source-controller.js +1 -1
- package/dist/components/retrieval/graph/graph-spatial-controller.js +3 -1
- package/dist/components/retrieval/graph/graph-spatial.js +1 -1
- package/dist/components/retrieval/graph/graph-webgl-engine.js +1 -1
- package/dist/components/retrieval/graph/graph.class.d.ts +11 -3
- package/dist/components/retrieval/graph/graph.class.js +4 -4
- package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.d.ts +8 -2
- package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.js +4 -2
- package/dist/events.d.ts +36 -1
- package/dist/framework-types.d.ts +1 -1
- package/dist/internal/collection-policy.js +1 -0
- package/dist/internal/collection-snapshot.js +1 -1
- package/dist/internal/default-strings/media.generated.js +1 -1
- package/dist/internal/default-strings/retrieval.generated.js +1 -1
- package/dist/internal/engine-3d-loader.d.ts +8 -2
- package/dist/internal/engine-3d-loader.js +1 -1
- package/dist/internal/form-control.styles.js +1 -1
- package/dist/internal/locale-loaders.generated.js +1 -1
- package/dist/internal/localization-runtime.js +1 -1
- package/dist/internal/localization-types.d.ts +1 -1
- package/dist/internal/localization.js +1 -1
- package/dist/internal/map-camera-follow-controller.d.ts +9 -0
- package/dist/internal/map-camera-follow-controller.js +1 -0
- package/dist/internal/map-camera-follow-data.js +1 -0
- package/dist/internal/map-camera-follow-scene.js +1 -0
- package/dist/internal/map-camera-session-controller.d.ts +59 -0
- package/dist/internal/map-camera-session-controller.js +1 -0
- package/dist/internal/map-camera-session-data.d.ts +16 -0
- package/dist/internal/map-camera-session-data.js +1 -0
- package/dist/internal/map-camera-session.js +1 -0
- package/dist/internal/map-custom-layer-attachment.js +1 -0
- package/dist/internal/map-custom-layer-controller.js +1 -0
- package/dist/internal/map-custom-layer-types.d.ts +63 -0
- package/dist/internal/map-scene-layer-runtime.js +1 -0
- package/dist/internal/map-scene-session.js +1 -0
- package/dist/internal/media-panorama.d.ts +5 -0
- package/dist/internal/media-panorama.js +8 -0
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/sequence-playback-binding.js +1 -0
- package/dist/internal/typed-columns.d.ts +3 -1
- package/dist/internal/typed-columns.js +1 -1
- package/dist/internal/variants.d.ts +7 -0
- package/dist/internal/widget-default-registry.js +1 -0
- package/dist/internal/widget-document.d.ts +29 -0
- package/dist/internal/widget-document.js +1 -0
- package/dist/internal/widget-type-registry.d.ts +27 -0
- package/dist/internal/widget-type-registry.js +1 -0
- package/dist/lyra.d.ts +1 -1
- package/dist/lyra.js +1 -1
- package/dist/map-camera-session.d.ts +10 -0
- package/dist/map-camera-session.js +1 -0
- package/dist/map-custom-layers.d.ts +16 -0
- package/dist/map-custom-layers.js +1 -0
- package/dist/sequence-time-binding.d.ts +3 -0
- package/dist/sequence-time-binding.js +1 -0
- package/dist/simulation-clock.d.ts +3 -0
- package/dist/simulation-clock.js +1 -0
- package/dist/time-index.d.ts +3 -0
- package/dist/time-index.js +1 -0
- package/llms/components/lr-artifact-panel.md +8 -3
- package/llms/components/lr-combobox.md +2 -0
- package/llms/components/lr-country-picker.md +2 -0
- package/llms/components/lr-currency-picker.md +2 -0
- package/llms/components/lr-date-picker.md +2 -0
- package/llms/components/lr-dock-panel.md +28 -10
- package/llms/components/lr-graph.md +121 -3
- package/llms/components/lr-input.md +2 -0
- package/llms/components/lr-knowledge-graph-explorer.md +6 -1
- package/llms/components/lr-locale-picker.md +8 -1
- package/llms/components/lr-map.md +401 -7
- package/llms/components/lr-markdown-core.md +2 -1
- package/llms/components/lr-markdown.md +12 -1
- package/llms/components/lr-menu.md +5 -2
- package/llms/components/lr-model-select.md +2 -0
- package/llms/components/lr-multi-split.md +53 -4
- package/llms/components/lr-native-time-input.md +2 -0
- package/llms/components/lr-number-input.md +2 -0
- package/llms/components/lr-page.md +9 -1
- package/llms/components/lr-phone-input.md +2 -0
- package/llms/components/lr-select.md +2 -0
- package/llms/components/lr-sequence-playback.md +44 -0
- package/llms/components/lr-streaming-text-core.md +3 -2
- package/llms/components/lr-streaming-text.md +4 -1
- package/llms/components/lr-suggestion-chips.md +6 -2
- package/llms/components/lr-textarea.md +2 -0
- package/llms/components/lr-time-input.md +2 -0
- package/llms/components/lr-time-zone-picker.md +2 -0
- package/llms/components/lr-token-input.md +2 -0
- package/llms/components/lr-unit-picker.md +2 -0
- package/llms/components/lr-voice-picker.md +2 -0
- package/llms/peers.md +7 -7
- package/llms/shared/imports-and-registration.md +1 -1
- package/llms/shared/localization-and-rtl.md +15 -1
- package/llms/shared/testing-and-utilities.md +261 -0
- package/llms/shared.md +277 -2
- package/locales.json +1 -1
- package/package.json +41 -21
- package/registrations.json +1 -1
- package/skills/lyra-ui/lyra-gen.md +2 -0
- /package/dist/{components/media/image-viewer/image-viewer-panorama.styles.js → internal/media-panorama.styles.js} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY}from"../../../internal/anchored-validity.js";import{setCustomState}from"../../../internal/custom-states.js";import{lengthLimitConverter,lengthViolations}from"../../../internal/length-constraints.js";import{MatchConstraintController}from"../../../internal/match-constraint.js";import{closeIcon,eyeIcon,eyeOffIcon}from"../../../internal/icons.js";import{styles}from"./input.styles.js";import{isDateObject}from"../../../internal/dom-guards.js";import{sizes}from"../../../internal/sizes.styles.js";import{srOnly}from"../../../internal/a11y.js";import{autocorrectConverter,normalizeAutocorrect,spellcheckConverter}from"../../../internal/converters.js";import{finiteCount,finiteDuration}from"../../../internal/numbers.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{DebounceController}from"../../../internal/debounce-controller.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_hidePassword,LYRA_DEFAULT_inputLabel,LYRA_DEFAULT_matchMismatch,LYRA_DEFAULT_showPassword}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings/shared.generated.js";const boundConverter={fromAttribute:value=>value==null?null:/^\s*[-+]?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?\s*$/i.test(value)?Number(value):value};let temporalProbe;function temporalProbeFor(doc,type){if(!(type!=="date"&&type!=="time"&&type!=="datetime-local"))return temporalProbe??=doc.createElement("input"),temporalProbe.type=type,temporalProbe}const INPUT_TYPES=new Set(["text","password","email","number","time","search","date","datetime-local","tel","url"]),LENGTH_CONSTRAINED_TYPES=["text","password","email","search","tel","url"];class LyraInputBase extends LyraElement{}class LyraInputShared extends FormAssociated(LyraInputBase){static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,fieldRequired:LYRA_DEFAULT_fieldRequired,hidePassword:LYRA_DEFAULT_hidePassword,inputLabel:LYRA_DEFAULT_inputLabel,matchMismatch:LYRA_DEFAULT_matchMismatch,showPassword:LYRA_DEFAULT_showPassword,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}get value(){return super.value}set value(next){const normalized=next??"";super.value=normalized,this.settlingValueFromInput||this.settledDebounce.cancelIfChanged(normalized)}get type(){return this._type}set type(next){const old=this._type;this._type=INPUT_TYPES.has(next)?next:"text",old!==this._type&&this.requestUpdate("type",old)}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=normalizeAutocorrect(next),this.requestUpdate()}get inputmode(){return this.inputMode}set inputmode(next){this.inputMode=next??""}get enterkeyhint(){return this.enterKeyHint}set enterkeyhint(next){this.enterKeyHint=next??""}get hidesSpinButtons(){return this.withoutSpinButtons}get defaultValueAlias(){return this.defaultValue}set defaultValueAlias(next){this.defaultValue=next??""}get inputId(){return this.id||"input"}constructor(){super(),this._type="text",this.size="m",this.appearance="outlined",this.filled=!1,this.pill=!1,this.placeholder="",this.clearable=!1,this.withClear=!1,this.readonly=!1,this.label="",this.hint="",this.helpText="",this.withLabel=!1,this.withHint=!1,this.errorText="",this.accessibleLabel=null,this.autocomplete="",this.title="",this.autofocus=!1,this.spellcheck=!0,this.autocapitalize="",this.autocorrectValue=!0,this.inputMode="",this.enterKeyHint="",this.passwordToggle=!1,this.passwordVisible=!1,this.withoutSpinButtons=!1,this.match=null,this.touched=!1,this.slotPresence=new SlotPresenceController(this),this.settlingValueFromInput=!1,this.settledDebounce=new DebounceController(0,value=>{this.emit("lr-input-settled",{value})}),this.matchController=new MatchConstraintController(this,()=>this.match,()=>this.updateValidity()),this.hostDescription=new HostDescriptionController(this,()=>this.inputEl??null,()=>{const description=this.renderRoot.querySelector("#input-required");return this.required&&description?[description]:[]}),this.onInput=event=>{this.inputEl&&(this.settlingValueFromInput=!0,this.value=this.inputEl.value,this.settlingValueFromInput=!1,relayNativeEvent(this,event),this.emit("lr-input",{value:this.value}),this.isDebounced()?(this.settledDebounce.delayMs=this.effectiveDebounceMs,this.settledDebounce.push(this.value)):this.settledDebounce.cancel())},this.onChange=event=>{this.inputEl&&(this.settledDebounce.flush(),this.value=this.inputEl.value,relayNativeEvent(this,event),this.emit("lr-change",{value:this.value}))},this.onFocus=event=>{relayNativeEvent(this,event)},this.onBlur=event=>{this.effectiveDisabled||(this.touched=!0),this.settledDebounce.flush(),relayNativeEvent(this,event)},this.onKeyDown=event=>{this.effectiveDisabled||this.readonly||(event.key==="Enter"&&this.settledDebounce.flush(),submitOnEnter(this,event))},this.onTogglePasswordVisible=()=>{this.passwordVisible=!this.passwordVisible},this.onClear=()=>{this.effectiveDisabled||this.readonly||this.value===""||(this.value="",this.inputEl&&(this.inputEl.value=""),dispatchNativeInputEvent(this,{inputType:"deleteContentBackward"}),this.emit("lr-input",{value:this.value}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value}),this.emit("lr-clear"),this.inputEl?.focus())},this.addEventListener("invalid",()=>{this.touched=!0})}disconnectedCallback(){this.settledDebounce.cancel(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted()}formResetCallback(){super.formResetCallback(),this.touched=!1}get input(){return this.inputEl??null}click(){this.effectiveDisabled||this.inputEl?.click()}focus(options){this.effectiveDisabled||this.inputEl?.focus(options)}blur(){this.inputEl?.blur()}select(){this.inputEl?.select()}get valueAsDate(){const native=this.inputEl;return native?(native.value!==this.value&&(native.value=this.value),native.valueAsDate):null}set valueAsDate(next){const native=this.inputEl;native&&(native.valueAsDate=next,this.value=native.value)}get valueAsLocalDate(){const utc=this.valueAsUTCDate;if(!utc)return null;const local=new Date;return this.type!=="time"&&local.setFullYear(utc.getUTCFullYear(),utc.getUTCMonth(),utc.getUTCDate()),local.setHours(utc.getUTCHours(),utc.getUTCMinutes(),utc.getUTCSeconds(),utc.getUTCMilliseconds()),local}set valueAsLocalDate(next){this.valueAsUTCDate=isDateObject(next)?new Date(next.getTime()-next.getTimezoneOffset()*6e4):null}get valueAsUTCDate(){const probe=temporalProbeFor(this.ownerDocument,this.type);return probe?(probe.value=this.value,Number.isNaN(probe.valueAsNumber)?null:new Date(probe.valueAsNumber)):null}set valueAsUTCDate(next){const probe=temporalProbeFor(this.ownerDocument,this.type);if(!probe)return;const ms=isDateObject(next)?next.getTime():NaN;probe.value="",Number.isNaN(ms)||(probe.valueAsNumber=this.type==="time"?(ms%864e5+864e5)%864e5:ms),this.value=probe.value}get valueAsNumber(){const native=this.inputEl;return native?(native.value!==this.value&&(native.value=this.value),native.valueAsNumber):Number.NaN}set valueAsNumber(next){const native=this.inputEl;native&&(native.valueAsNumber=next,this.value=native.value)}showPicker(){const native=this.inputEl;if(!(!native||this.effectiveDisabled||this.readonly)&&"showPicker"in HTMLInputElement.prototype)try{native.showPicker()}catch{}}stepUp(steps=1){this.applyStep("up",steps)}stepDown(steps=1){this.applyStep("down",steps)}applyStep(direction,steps){const native=this.inputEl;if(!native||this.effectiveDisabled||this.readonly)return;const count=finiteCount(steps,1);if(count!==0){native.type=this.type,native.min=this.min==null?"":String(this.min),native.max=this.max==null?"":String(this.max),native.step=this.step==null?"":String(this.step),native.value=this.value;try{direction==="up"?native.stepUp(count):native.stepDown(count)}catch{return}this.value!==native.value&&(this.value=native.value)}}get selectionStart(){return this.inputEl?.selectionStart??null}set selectionStart(value){this.inputEl&&(this.inputEl.selectionStart=value??0)}get selectionEnd(){return this.inputEl?.selectionEnd??null}set selectionEnd(value){this.inputEl&&(this.inputEl.selectionEnd=value??0)}get selectionDirection(){return this.inputEl?.selectionDirection??null}set selectionDirection(value){this.inputEl&&(this.inputEl.selectionDirection=value??"none")}setSelectionRange(selectionStart,selectionEnd,selectionDirection="none"){this.inputEl?.setSelectionRange(selectionStart,selectionEnd,selectionDirection)}setRangeText(replacement,start,end,selectMode="preserve"){const input=this.inputEl;input&&(start===void 0||end===void 0?input.setRangeText(replacement):input.setRangeText(replacement,start,end,selectMode),this.value=input.value)}updateValidity(){const native=this.inputEl;if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}if(!native){this.required&&this.value===""?this[SET_ANCHORED_VALIDITY]({valueMissing:!0},this.localize("fieldRequired")):this.matchMismatches()?this[SET_ANCHORED_VALIDITY]({customError:!0},this.localize("matchMismatch")):this[SET_ANCHORED_VALIDITY]({});return}native.value!==this.value&&(native.value=this.value);const sanitizedAway=this.value!==""&&native.value==="",v=native.validity,own=LENGTH_CONSTRAINED_TYPES.includes(this.type)?lengthViolations(this.value,this.minlength,this.maxlength):{tooShort:!1,tooLong:!1},tooShort=v.tooShort||own.tooShort,tooLong=v.tooLong||own.tooLong;if(v.valid&&!tooShort&&!tooLong){if(sanitizedAway){this[SET_ANCHORED_VALIDITY]({badInput:!0},this.localize("valueInvalid"));return}if(this.matchMismatches()){this[SET_ANCHORED_VALIDITY]({customError:!0},this.localize("matchMismatch"));return}this[SET_ANCHORED_VALIDITY]({});return}this[SET_ANCHORED_VALIDITY]({valueMissing:v.valueMissing,typeMismatch:v.typeMismatch,rangeUnderflow:v.rangeUnderflow,rangeOverflow:v.rangeOverflow,stepMismatch:v.stepMismatch,tooShort,tooLong,patternMismatch:v.patternMismatch,badInput:v.badInput},native.validationMessage||this.localize("valueInvalid"))}matchMismatches(){if(!this.match)return!1;const targetValue=this.matchController.targetValue;return targetValue!==null&&targetValue!==this.value}updated(changed){super.updated(changed),changed.has("value")&&setCustomState(this.internals,"blank",this.value===""),this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),(changed.has("type")||changed.has("min")||changed.has("max")||changed.has("step")||changed.has("minlength")||changed.has("maxlength")||changed.has("pattern")||changed.has("match")||changed.has("readonly"))&&this.updateValidity()}get effectiveDebounceMs(){return finiteDuration(this.debounce??0,0)}isDebounced(){return this.effectiveDebounceMs>0}renderControls(){return nothing}get inputWrapperParts(){return"base form-control-input input-wrapper"}render(){const hasHint=this.slotPresence.has("hint")||this.slotPresence.has("help-text")||(this.hint??"").length>0||(this.helpText??"").length>0||this.withHint,hasError=this.slotPresence.has("error")||(this.errorText??"").length>0,hasLabel=this.slotPresence.has("label")||(this.label??"").length>0||this.withLabel,describedBy=[hasError?"input-error":"",hasHint?"input-hint":""].filter(Boolean).join(" "),isPassword=this.type==="password",showPasswordToggle=isPassword&&this.passwordToggle,nativeType=isPassword&&this.passwordVisible?"text":this.type,canClear=(this.clearable||this.withClear)&&(this.type==="text"||this.type==="search")&&this.value!=="";return html`
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY}from"../../../internal/anchored-validity.js";import{setCustomState}from"../../../internal/custom-states.js";import{lengthLimitConverter,lengthViolations}from"../../../internal/length-constraints.js";import{MatchConstraintController}from"../../../internal/match-constraint.js";import{closeIcon,eyeIcon,eyeOffIcon}from"../../../internal/icons.js";import{styles}from"./input.styles.js";import{isDateObject}from"../../../internal/dom-guards.js";import{sizes}from"../../../internal/sizes.styles.js";import{srOnly}from"../../../internal/a11y.js";import{autocorrectConverter,normalizeAutocorrect,spellcheckConverter}from"../../../internal/converters.js";import{finiteCount,finiteDuration}from"../../../internal/numbers.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{DebounceController}from"../../../internal/debounce-controller.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_hidePassword,LYRA_DEFAULT_inputLabel,LYRA_DEFAULT_matchMismatch,LYRA_DEFAULT_showPassword}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings/shared.generated.js";const boundConverter={fromAttribute:value=>value==null?null:/^\s*[-+]?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?\s*$/i.test(value)?Number(value):value};let temporalProbe;function temporalProbeFor(doc,type){if(!(type!=="date"&&type!=="time"&&type!=="datetime-local"))return temporalProbe??=doc.createElement("input"),temporalProbe.type=type,temporalProbe}const INPUT_TYPES=new Set(["text","password","email","number","time","search","date","datetime-local","tel","url"]),LENGTH_CONSTRAINED_TYPES=["text","password","email","search","tel","url"];class LyraInputBase extends LyraElement{}class LyraInputShared extends FormAssociated(LyraInputBase){static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,fieldRequired:LYRA_DEFAULT_fieldRequired,hidePassword:LYRA_DEFAULT_hidePassword,inputLabel:LYRA_DEFAULT_inputLabel,matchMismatch:LYRA_DEFAULT_matchMismatch,showPassword:LYRA_DEFAULT_showPassword,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}get value(){return super.value}set value(next){const normalized=next??"";super.value=normalized,this.settlingValueFromInput||this.settledDebounce.cancelIfChanged(normalized)}get type(){return this._type}set type(next){const old=this._type;this._type=INPUT_TYPES.has(next)?next:"text",old!==this._type&&this.requestUpdate("type",old)}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=normalizeAutocorrect(next),this.requestUpdate()}get inputmode(){return this.inputMode}set inputmode(next){this.inputMode=next??""}get enterkeyhint(){return this.enterKeyHint}set enterkeyhint(next){this.enterKeyHint=next??""}get hidesSpinButtons(){return this.withoutSpinButtons}get defaultValueAlias(){return this.defaultValue}set defaultValueAlias(next){this.defaultValue=next??""}get inputId(){return this.id||"input"}constructor(){super(),this._type="text",this.size="m",this.appearance="outlined",this.filled=!1,this.pill=!1,this.placeholder="",this.clearable=!1,this.withClear=!1,this.readonly=!1,this.label="",this.labelDisplay="visible",this.hint="",this.helpText="",this.withLabel=!1,this.withHint=!1,this.errorText="",this.accessibleLabel=null,this.autocomplete="",this.title="",this.autofocus=!1,this.spellcheck=!0,this.autocapitalize="",this.autocorrectValue=!0,this.inputMode="",this.enterKeyHint="",this.passwordToggle=!1,this.passwordVisible=!1,this.withoutSpinButtons=!1,this.match=null,this.touched=!1,this.slotPresence=new SlotPresenceController(this),this.settlingValueFromInput=!1,this.settledDebounce=new DebounceController(0,value=>{this.emit("lr-input-settled",{value})}),this.matchController=new MatchConstraintController(this,()=>this.match,()=>this.updateValidity()),this.hostDescription=new HostDescriptionController(this,()=>this.inputEl??null,()=>{const description=this.renderRoot.querySelector("#input-required");return this.required&&description?[description]:[]}),this.onInput=event=>{this.inputEl&&(this.settlingValueFromInput=!0,this.value=this.inputEl.value,this.settlingValueFromInput=!1,relayNativeEvent(this,event),this.emit("lr-input",{value:this.value}),this.isDebounced()?(this.settledDebounce.delayMs=this.effectiveDebounceMs,this.settledDebounce.push(this.value)):this.settledDebounce.cancel())},this.onChange=event=>{this.inputEl&&(this.settledDebounce.flush(),this.value=this.inputEl.value,relayNativeEvent(this,event),this.emit("lr-change",{value:this.value}))},this.onFocus=event=>{relayNativeEvent(this,event)},this.onBlur=event=>{this.effectiveDisabled||(this.touched=!0),this.settledDebounce.flush(),relayNativeEvent(this,event)},this.onKeyDown=event=>{this.effectiveDisabled||this.readonly||(event.key==="Enter"&&this.settledDebounce.flush(),submitOnEnter(this,event))},this.onTogglePasswordVisible=()=>{this.passwordVisible=!this.passwordVisible},this.onClear=()=>{this.effectiveDisabled||this.readonly||this.value===""||(this.value="",this.inputEl&&(this.inputEl.value=""),dispatchNativeInputEvent(this,{inputType:"deleteContentBackward"}),this.emit("lr-input",{value:this.value}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value}),this.emit("lr-clear"),this.inputEl?.focus())},this.addEventListener("invalid",()=>{this.touched=!0})}disconnectedCallback(){this.settledDebounce.cancel(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted()}formResetCallback(){super.formResetCallback(),this.touched=!1}get input(){return this.inputEl??null}click(){this.effectiveDisabled||this.inputEl?.click()}focus(options){this.effectiveDisabled||this.inputEl?.focus(options)}blur(){this.inputEl?.blur()}select(){this.inputEl?.select()}get valueAsDate(){const native=this.inputEl;return native?(native.value!==this.value&&(native.value=this.value),native.valueAsDate):null}set valueAsDate(next){const native=this.inputEl;native&&(native.valueAsDate=next,this.value=native.value)}get valueAsLocalDate(){const utc=this.valueAsUTCDate;if(!utc)return null;const local=new Date;return this.type!=="time"&&local.setFullYear(utc.getUTCFullYear(),utc.getUTCMonth(),utc.getUTCDate()),local.setHours(utc.getUTCHours(),utc.getUTCMinutes(),utc.getUTCSeconds(),utc.getUTCMilliseconds()),local}set valueAsLocalDate(next){this.valueAsUTCDate=isDateObject(next)?new Date(next.getTime()-next.getTimezoneOffset()*6e4):null}get valueAsUTCDate(){const probe=temporalProbeFor(this.ownerDocument,this.type);return probe?(probe.value=this.value,Number.isNaN(probe.valueAsNumber)?null:new Date(probe.valueAsNumber)):null}set valueAsUTCDate(next){const probe=temporalProbeFor(this.ownerDocument,this.type);if(!probe)return;const ms=isDateObject(next)?next.getTime():NaN;probe.value="",Number.isNaN(ms)||(probe.valueAsNumber=this.type==="time"?(ms%864e5+864e5)%864e5:ms),this.value=probe.value}get valueAsNumber(){const native=this.inputEl;return native?(native.value!==this.value&&(native.value=this.value),native.valueAsNumber):Number.NaN}set valueAsNumber(next){const native=this.inputEl;native&&(native.valueAsNumber=next,this.value=native.value)}showPicker(){const native=this.inputEl;if(!(!native||this.effectiveDisabled||this.readonly)&&"showPicker"in HTMLInputElement.prototype)try{native.showPicker()}catch{}}stepUp(steps=1){this.applyStep("up",steps)}stepDown(steps=1){this.applyStep("down",steps)}applyStep(direction,steps){const native=this.inputEl;if(!native||this.effectiveDisabled||this.readonly)return;const count=finiteCount(steps,1);if(count!==0){native.type=this.type,native.min=this.min==null?"":String(this.min),native.max=this.max==null?"":String(this.max),native.step=this.step==null?"":String(this.step),native.value=this.value;try{direction==="up"?native.stepUp(count):native.stepDown(count)}catch{return}this.value!==native.value&&(this.value=native.value)}}get selectionStart(){return this.inputEl?.selectionStart??null}set selectionStart(value){this.inputEl&&(this.inputEl.selectionStart=value??0)}get selectionEnd(){return this.inputEl?.selectionEnd??null}set selectionEnd(value){this.inputEl&&(this.inputEl.selectionEnd=value??0)}get selectionDirection(){return this.inputEl?.selectionDirection??null}set selectionDirection(value){this.inputEl&&(this.inputEl.selectionDirection=value??"none")}setSelectionRange(selectionStart,selectionEnd,selectionDirection="none"){this.inputEl?.setSelectionRange(selectionStart,selectionEnd,selectionDirection)}setRangeText(replacement,start,end,selectMode="preserve"){const input=this.inputEl;input&&(start===void 0||end===void 0?input.setRangeText(replacement):input.setRangeText(replacement,start,end,selectMode),this.value=input.value)}updateValidity(){const native=this.inputEl;if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}if(!native){this.required&&this.value===""?this[SET_ANCHORED_VALIDITY]({valueMissing:!0},this.localize("fieldRequired")):this.matchMismatches()?this[SET_ANCHORED_VALIDITY]({customError:!0},this.localize("matchMismatch")):this[SET_ANCHORED_VALIDITY]({});return}native.value!==this.value&&(native.value=this.value);const sanitizedAway=this.value!==""&&native.value==="",v=native.validity,own=LENGTH_CONSTRAINED_TYPES.includes(this.type)?lengthViolations(this.value,this.minlength,this.maxlength):{tooShort:!1,tooLong:!1},tooShort=v.tooShort||own.tooShort,tooLong=v.tooLong||own.tooLong;if(v.valid&&!tooShort&&!tooLong){if(sanitizedAway){this[SET_ANCHORED_VALIDITY]({badInput:!0},this.localize("valueInvalid"));return}if(this.matchMismatches()){this[SET_ANCHORED_VALIDITY]({customError:!0},this.localize("matchMismatch"));return}this[SET_ANCHORED_VALIDITY]({});return}this[SET_ANCHORED_VALIDITY]({valueMissing:v.valueMissing,typeMismatch:v.typeMismatch,rangeUnderflow:v.rangeUnderflow,rangeOverflow:v.rangeOverflow,stepMismatch:v.stepMismatch,tooShort,tooLong,patternMismatch:v.patternMismatch,badInput:v.badInput},native.validationMessage||this.localize("valueInvalid"))}matchMismatches(){if(!this.match)return!1;const targetValue=this.matchController.targetValue;return targetValue!==null&&targetValue!==this.value}updated(changed){super.updated(changed),changed.has("value")&&setCustomState(this.internals,"blank",this.value===""),this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),(changed.has("type")||changed.has("min")||changed.has("max")||changed.has("step")||changed.has("minlength")||changed.has("maxlength")||changed.has("pattern")||changed.has("match")||changed.has("readonly"))&&this.updateValidity()}get effectiveDebounceMs(){return finiteDuration(this.debounce??0,0)}isDebounced(){return this.effectiveDebounceMs>0}renderControls(){return nothing}get inputWrapperParts(){return"base form-control-input input-wrapper"}render(){const hasHint=this.slotPresence.has("hint")||this.slotPresence.has("help-text")||(this.hint??"").length>0||(this.helpText??"").length>0||this.withHint,hasError=this.slotPresence.has("error")||(this.errorText??"").length>0,hasLabel=this.slotPresence.has("label")||(this.label??"").length>0||this.withLabel,describedBy=[hasError?"input-error":"",hasHint?"input-hint":""].filter(Boolean).join(" "),isPassword=this.type==="password",showPasswordToggle=isPassword&&this.passwordToggle,nativeType=isPassword&&this.passwordVisible?"text":this.type,canClear=(this.clearable||this.withClear)&&(this.type==="text"||this.type==="search")&&this.value!=="";return html`
|
|
2
2
|
<div part="form-control">
|
|
3
3
|
<label
|
|
4
4
|
part="form-control-label"
|
|
@@ -103,4 +103,4 @@ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,quer
|
|
|
103
103
|
?hidden=${!this.required}
|
|
104
104
|
>${this.localize("fieldRequired")}</span>
|
|
105
105
|
</div>
|
|
106
|
-
`}}__decorate([property({reflect:!0})],LyraInputShared.prototype,"type",null),__decorate([property({reflect:!0})],LyraInputShared.prototype,"size",void 0),__decorate([property({reflect:!0})],LyraInputShared.prototype,"appearance",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraInputShared.prototype,"filled",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraInputShared.prototype,"pill",void 0),__decorate([property()],LyraInputShared.prototype,"placeholder",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraInputShared.prototype,"clearable",void 0),__decorate([property({type:Boolean,attribute:"with-clear"})],LyraInputShared.prototype,"withClear",void 0),__decorate([property({type:Number})],LyraInputShared.prototype,"debounce",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraInputShared.prototype,"readonly",void 0),__decorate([property()],LyraInputShared.prototype,"label",void 0),__decorate([property()],LyraInputShared.prototype,"hint",void 0),__decorate([property({attribute:"help-text"})],LyraInputShared.prototype,"helpText",void 0),__decorate([property({type:Boolean,attribute:"with-label"})],LyraInputShared.prototype,"withLabel",void 0),__decorate([property({type:Boolean,attribute:"with-hint"})],LyraInputShared.prototype,"withHint",void 0),__decorate([property({attribute:"error-text"})],LyraInputShared.prototype,"errorText",void 0),__decorate([property({attribute:"aria-label"})],LyraInputShared.prototype,"accessibleLabel",void 0),__decorate([property()],LyraInputShared.prototype,"autocomplete",void 0),__decorate([property()],LyraInputShared.prototype,"title",void 0),__decorate([property({type:Boolean})],LyraInputShared.prototype,"autofocus",void 0),__decorate([property({converter:spellcheckConverter})],LyraInputShared.prototype,"spellcheck",void 0),__decorate([property()],LyraInputShared.prototype,"autocapitalize",void 0),__decorate([property({attribute:"inputmode"})],LyraInputShared.prototype,"inputMode",void 0),__decorate([property({attribute:"enterkeyhint"})],LyraInputShared.prototype,"enterKeyHint",void 0),__decorate([property({converter:autocorrectConverter})],LyraInputShared.prototype,"autocorrect",null),__decorate([property({converter:boundConverter})],LyraInputShared.prototype,"min",void 0),__decorate([property({converter:boundConverter})],LyraInputShared.prototype,"max",void 0),__decorate([property()],LyraInputShared.prototype,"step",void 0),__decorate([property({converter:lengthLimitConverter})],LyraInputShared.prototype,"minlength",void 0),__decorate([property({converter:lengthLimitConverter})],LyraInputShared.prototype,"maxlength",void 0),__decorate([property()],LyraInputShared.prototype,"pattern",void 0),__decorate([property({type:Boolean,attribute:"password-toggle",reflect:!0})],LyraInputShared.prototype,"passwordToggle",void 0),__decorate([property({type:Boolean,attribute:"password-visible"})],LyraInputShared.prototype,"passwordVisible",void 0),__decorate([property({type:Boolean,attribute:"without-spin-buttons",reflect:!0})],LyraInputShared.prototype,"withoutSpinButtons",void 0),__decorate([property({attribute:"match"})],LyraInputShared.prototype,"match",void 0),__decorate([property({attribute:"default-value"})],LyraInputShared.prototype,"defaultValueAlias",null),__decorate([state()],LyraInputShared.prototype,"touched",void 0),__decorate([query("input")],LyraInputShared.prototype,"inputEl",void 0);function createInputValidators(){return[currentValidityValidator("required","disabled","readonly","value","type","pattern","min","max","step","minlength","maxlength")]}export{LyraInputShared,createInputValidators};
|
|
106
|
+
`}}__decorate([property({reflect:!0})],LyraInputShared.prototype,"type",null),__decorate([property({reflect:!0})],LyraInputShared.prototype,"size",void 0),__decorate([property({reflect:!0})],LyraInputShared.prototype,"appearance",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraInputShared.prototype,"filled",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraInputShared.prototype,"pill",void 0),__decorate([property()],LyraInputShared.prototype,"placeholder",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraInputShared.prototype,"clearable",void 0),__decorate([property({type:Boolean,attribute:"with-clear"})],LyraInputShared.prototype,"withClear",void 0),__decorate([property({type:Number})],LyraInputShared.prototype,"debounce",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraInputShared.prototype,"readonly",void 0),__decorate([property()],LyraInputShared.prototype,"label",void 0),__decorate([property({attribute:"label-display",reflect:!0})],LyraInputShared.prototype,"labelDisplay",void 0),__decorate([property()],LyraInputShared.prototype,"hint",void 0),__decorate([property({attribute:"help-text"})],LyraInputShared.prototype,"helpText",void 0),__decorate([property({type:Boolean,attribute:"with-label"})],LyraInputShared.prototype,"withLabel",void 0),__decorate([property({type:Boolean,attribute:"with-hint"})],LyraInputShared.prototype,"withHint",void 0),__decorate([property({attribute:"error-text"})],LyraInputShared.prototype,"errorText",void 0),__decorate([property({attribute:"aria-label"})],LyraInputShared.prototype,"accessibleLabel",void 0),__decorate([property()],LyraInputShared.prototype,"autocomplete",void 0),__decorate([property()],LyraInputShared.prototype,"title",void 0),__decorate([property({type:Boolean})],LyraInputShared.prototype,"autofocus",void 0),__decorate([property({converter:spellcheckConverter})],LyraInputShared.prototype,"spellcheck",void 0),__decorate([property()],LyraInputShared.prototype,"autocapitalize",void 0),__decorate([property({attribute:"inputmode"})],LyraInputShared.prototype,"inputMode",void 0),__decorate([property({attribute:"enterkeyhint"})],LyraInputShared.prototype,"enterKeyHint",void 0),__decorate([property({converter:autocorrectConverter})],LyraInputShared.prototype,"autocorrect",null),__decorate([property({converter:boundConverter})],LyraInputShared.prototype,"min",void 0),__decorate([property({converter:boundConverter})],LyraInputShared.prototype,"max",void 0),__decorate([property()],LyraInputShared.prototype,"step",void 0),__decorate([property({converter:lengthLimitConverter})],LyraInputShared.prototype,"minlength",void 0),__decorate([property({converter:lengthLimitConverter})],LyraInputShared.prototype,"maxlength",void 0),__decorate([property()],LyraInputShared.prototype,"pattern",void 0),__decorate([property({type:Boolean,attribute:"password-toggle",reflect:!0})],LyraInputShared.prototype,"passwordToggle",void 0),__decorate([property({type:Boolean,attribute:"password-visible"})],LyraInputShared.prototype,"passwordVisible",void 0),__decorate([property({type:Boolean,attribute:"without-spin-buttons",reflect:!0})],LyraInputShared.prototype,"withoutSpinButtons",void 0),__decorate([property({attribute:"match"})],LyraInputShared.prototype,"match",void 0),__decorate([property({attribute:"default-value"})],LyraInputShared.prototype,"defaultValueAlias",null),__decorate([state()],LyraInputShared.prototype,"touched",void 0),__decorate([query("input")],LyraInputShared.prototype,"inputEl",void 0);function createInputValidators(){return[currentValidityValidator("required","disabled","readonly","value","type","pattern","min","max","step","minlength","maxlength")]}export{LyraInputShared,createInputValidators};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{type ComplexAttributeConverter,type PropertyValues,type TemplateResult}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';import type{LyraAppearance,LyraSize}from'../../../internal/variants.js';import{type TimeHourFormat}from'./time-input-shared.js';import{type LyraFormValidator}from'../form-validator.js';export type LyraTimeInputHourFormat=TimeHourFormat;export type LyraTimeInputStep=number|'any';export type LyraTimeInputPlacement='top'|'top-start'|'top-end'|'right'|'right-start'|'right-end'|'bottom'|'bottom-start'|'bottom-end'|'left'|'left-start'|'left-end';export interface LyraTimeInputEventMap{input:InputEvent;change:Event;focus:FocusEvent;blur:FocusEvent;'lr-input':CustomEvent<{value:string;}>;'lr-change':CustomEvent<{value:string;}>;'lr-clear':CustomEvent<null>;'lr-show':CustomEvent<null>;'lr-after-show':CustomEvent<null>;'lr-hide':CustomEvent<null>;'lr-after-hide':CustomEvent<null>;'lr-invalid':CustomEvent<null>;}declare class LyraTimeInputBase extends LyraElement<LyraTimeInputEventMap>{}declare const LyraTimeInput_base:typeof LyraTimeInputBase&(new(...args:any[])=>import("../../../lyra.js").FormAssociatedInterface<string> &import("../../../internal/form-associated.js").FormAssociatedSubclassInterface<string>);
|
|
1
|
+
import{type ComplexAttributeConverter,type PropertyValues,type TemplateResult}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';import type{LyraAppearance,LyraSize,LyraLabelDisplay}from'../../../internal/variants.js';import{type TimeHourFormat}from'./time-input-shared.js';import{type LyraFormValidator}from'../form-validator.js';export type LyraTimeInputHourFormat=TimeHourFormat;export type LyraTimeInputStep=number|'any';export type LyraTimeInputPlacement='top'|'top-start'|'top-end'|'right'|'right-start'|'right-end'|'bottom'|'bottom-start'|'bottom-end'|'left'|'left-start'|'left-end';export interface LyraTimeInputEventMap{input:InputEvent;change:Event;focus:FocusEvent;blur:FocusEvent;'lr-input':CustomEvent<{value:string;}>;'lr-change':CustomEvent<{value:string;}>;'lr-clear':CustomEvent<null>;'lr-show':CustomEvent<null>;'lr-after-show':CustomEvent<null>;'lr-hide':CustomEvent<null>;'lr-after-hide':CustomEvent<null>;'lr-invalid':CustomEvent<null>;}declare class LyraTimeInputBase extends LyraElement<LyraTimeInputEventMap>{}declare const LyraTimeInput_base:typeof LyraTimeInputBase&(new(...args:any[])=>import("../../../lyra.js").FormAssociatedInterface<string> &import("../../../internal/form-associated.js").FormAssociatedSubclassInterface<string>);
|
|
2
2
|
/**
|
|
3
3
|
* `<lr-time-input>` — a locale-aware segmented time field with an attached column picker.
|
|
4
4
|
*
|
|
@@ -156,7 +156,14 @@ import{type ComplexAttributeConverter,type PropertyValues,type TemplateResult}fr
|
|
|
156
156
|
*/
|
|
157
157
|
export declare class LyraTimeInput extends LyraTimeInput_base{
|
|
158
158
|
/** Public WA-compatible intrinsic validator catalog.*/
|
|
159
|
-
static get validators():LyraFormValidator<LyraTimeInput>[];static styles:import("lit").CSSResultGroup[];static properties:{open:{type:BooleanConstructor;reflect:boolean;noAccessor:boolean;};readonly:{type:BooleanConstructor;reflect:boolean;noAccessor:boolean;};step:{converter:ComplexAttributeConverter<LyraTimeInputStep,unknown>;reflect:boolean;noAccessor:boolean;};};appearance:LyraAppearance;autocomplete:string;distance:number;hint:string;hourFormat:LyraTimeInputHourFormat;label:string;
|
|
159
|
+
static get validators():LyraFormValidator<LyraTimeInput>[];static styles:import("lit").CSSResultGroup[];static properties:{open:{type:BooleanConstructor;reflect:boolean;noAccessor:boolean;};readonly:{type:BooleanConstructor;reflect:boolean;noAccessor:boolean;};step:{converter:ComplexAttributeConverter<LyraTimeInputStep,unknown>;reflect:boolean;noAccessor:boolean;};};appearance:LyraAppearance;autocomplete:string;distance:number;hint:string;hourFormat:LyraTimeInputHourFormat;label:string;
|
|
160
|
+
/**
|
|
161
|
+
* Whether the `label` renders on screen. `hidden` keeps the label as the accessible name but
|
|
162
|
+
* removes it visually (compact toolbars, table cells); hint, error and required semantics are
|
|
163
|
+
* unaffected. Reflected so styles and `[label-display]` selectors match.
|
|
164
|
+
* @attr label-display
|
|
165
|
+
*/
|
|
166
|
+
labelDisplay:LyraLabelDisplay;min:string;max:string;pill:boolean;placement:LyraTimeInputPlacement;size:LyraSize;
|
|
160
167
|
/** Shows the clear action while there is a value; same as `withClear`.*/
|
|
161
168
|
clearable:boolean;
|
|
162
169
|
/** Alias of {@link clearable}.*/
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{sizes}from"../../../internal/sizes.styles.js";import{closeIcon,chevronIcon}from"../../../internal/icons.js";import{finiteNumber}from"../../../internal/numbers.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{deferredPlaceReady as place,waitForDeferredPlacement}from"../../../internal/anchored-overlay-runtime.js";import{PopupController,emitPopupEvent}from"../../../internal/popup-controller.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{activateNonmodalOverlay,composedContains}from"../../../internal/nonmodal-overlay-manager.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{setCustomState}from"../../../internal/custom-states.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{dayPeriodLabels,hasTimeStepMismatch,isTimeInRange,localeTimePattern,normalizeTimeValue,parseTimeValue,timeValueFromMilliseconds,timeStepBaseMilliseconds,to24Hour,wrapTimeMilliseconds}from"./time-input-shared.js";import{styles}from"./time-input.styles.js";import{isDateObject}from"../../../internal/dom-guards.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_timeInputDayPeriod,LYRA_DEFAULT_timeInputEmptySegment,LYRA_DEFAULT_timeInputHour,LYRA_DEFAULT_timeInputInvalid,LYRA_DEFAULT_timeInputLabel,LYRA_DEFAULT_timeInputMaxMessage,LYRA_DEFAULT_timeInputMinMessage,LYRA_DEFAULT_timeInputMinute,LYRA_DEFAULT_timeInputNow,LYRA_DEFAULT_timeInputOpen,LYRA_DEFAULT_timeInputPopup,LYRA_DEFAULT_timeInputRangeMessage,LYRA_DEFAULT_timeInputSecond,LYRA_DEFAULT_timeInputStepMessage}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings/shared.generated.js";class LyraTimeInputBase extends LyraElement{}const stepConverter={fromAttribute(value){if(value==="any")return"any";const parsed=Number(value);return Number.isFinite(parsed)&&parsed>0?parsed:60},toAttribute(value){return String(value)}},hourFormatConverter={fromAttribute(value){return value==="12"||value==="24"?value:"auto"},toAttribute(value){return value}},PLACEMENTS=new Set(["top","top-start","top-end","right","right-start","right-end","bottom","bottom-start","bottom-end","left","left-start","left-end"]),placementConverter={fromAttribute(value){return PLACEMENTS.has(value)?value:"bottom-start"},toAttribute(value){return value}},blankDraft=()=>({hour:null,minute:null,second:null,dayPeriod:null}),pad=value=>String(value).padStart(2,"0");function isElementNode(value){if(value===null||typeof value!="object")return!1;const candidate=value;return candidate.nodeType===1&&typeof candidate.getRootNode=="function"&&typeof candidate.contains=="function"}function containsElement(container,value){if(!container||!isElementNode(value))return!1;try{return container.contains(value)}catch{return!1}}class LyraTimeInput extends FormAssociated(LyraTimeInputBase){static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,fieldRequired:LYRA_DEFAULT_fieldRequired,timeInputDayPeriod:LYRA_DEFAULT_timeInputDayPeriod,timeInputEmptySegment:LYRA_DEFAULT_timeInputEmptySegment,timeInputHour:LYRA_DEFAULT_timeInputHour,timeInputInvalid:LYRA_DEFAULT_timeInputInvalid,timeInputLabel:LYRA_DEFAULT_timeInputLabel,timeInputMaxMessage:LYRA_DEFAULT_timeInputMaxMessage,timeInputMinMessage:LYRA_DEFAULT_timeInputMinMessage,timeInputMinute:LYRA_DEFAULT_timeInputMinute,timeInputNow:LYRA_DEFAULT_timeInputNow,timeInputOpen:LYRA_DEFAULT_timeInputOpen,timeInputPopup:LYRA_DEFAULT_timeInputPopup,timeInputRangeMessage:LYRA_DEFAULT_timeInputRangeMessage,timeInputSecond:LYRA_DEFAULT_timeInputSecond,timeInputStepMessage:LYRA_DEFAULT_timeInputStepMessage}}static get validators(){return[currentValidityValidator("required","disabled","readonly","value","min","max","step")]}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}static{this.properties={open:{type:Boolean,reflect:!0,noAccessor:!0},readonly:{type:Boolean,reflect:!0,noAccessor:!0},step:{converter:stepConverter,reflect:!0,noAccessor:!0}}}get hasLabelSlot(){return this.slotPresence.has("label")}get hasHintSlot(){return this.slotPresence.has("hint")}get hasErrorSlot(){return this.slotPresence.has("error")}get hasStartSlot(){return this.slotPresence.has("start")}get hasEndSlot(){return this.slotPresence.has("end")}get hasFooterSlot(){return this.slotPresence.has("footer")}constructor(){super(),this.appearance="outlined",this.autocomplete="",this.distance=0,this.hint="",this.hourFormat="auto",this.label="",this.min="",this.max="",this.pill=!1,this.placement="bottom-start",this.size="m",this.clearable=!1,this.withClear=!1,this.withHint=!1,this.withLabel=!1,this.withNow=!1,this.errorText="",this.activeSegment="hour",this.touched=!1,this.slotPresence=new SlotPresenceController(this),this.popupHidden=!0,this.popupPositioned=!1,this._open=!1,this._readonly=!1,this._step=60,this.draft=blankDraft(),this.partial=!1,this.secondsVisible=!1,this.genuineValue="",this.digitBuffer="",this.inputDigitLocale="",this.restoringSegmentFocus=!1,this.restoringPopupFocus=!1,this.restoreFocusOnClose=!0,this.popupController=new PopupController({host:this,popup:()=>this.renderRoot.querySelector('[part="popup"]'),emit:(name,cancelable)=>emitPopupEvent(this,name,cancelable),onPointer:event=>this.onDocumentPointerDown(event)}),this.visibilityPromise=Promise.resolve(),this.segmentOrderKey="",this.pickerGridKey="",this.pickerGridMilliseconds=[],this.inputId=nextId("time-input"),this.labelId=nextId("time-input-label"),this.hintId=nextId("time-input-hint"),this.errorId=nextId("time-input-error"),this.requiredDescriptionId=nextId("time-input-required"),this.popupId=nextId("time-input-popup"),this.hostDescription=new HostDescriptionController(this,()=>this.renderRoot.querySelector('[part~="input"]'),()=>{const description=this.renderRoot.querySelector(`#${this.requiredDescriptionId}`);return this.required&&description?[description]:[]}),this.now=()=>new Date,this.onSegmentKeyDown=event=>{const name=event.currentTarget.dataset.segment;if(this.liveDisabled)return;if(event.altKey&&event.key==="ArrowDown"){event.preventDefault(),this.show();return}const digit=this.inputDigit(event.key);if(digit!==void 0&&!event.ctrlKey&&!event.metaKey&&!event.altKey&&!this.readonly){event.preventDefault(),this.acceptDigit(name,digit);return}if(name==="dayPeriod"&&!this.readonly&&(event.key.toLowerCase()==="a"||event.key.toLowerCase()==="p")){event.preventDefault(),this.setDraftSegment(name,event.key.toLowerCase()==="a"?"am":"pm");return}if(event.key==="ArrowLeft"||event.key==="ArrowRight"){event.preventDefault();const physical=event.key==="ArrowRight"?1:-1;this.resetDigitBuffer(),this.moveSegment(name,this.effectiveDirection==="rtl"?-physical:physical);return}if((event.key==="ArrowUp"||event.key==="ArrowDown")&&!this.readonly){event.preventDefault(),this.resetDigitBuffer(),this.stepSegment(name,event.key==="ArrowUp"?1:-1);return}if((event.key==="Home"||event.key==="End")&&!this.readonly){event.preventDefault();const bounds=this.segmentBounds(name),next=event.key==="Home"?bounds.min:bounds.max;this.setDraftSegment(name,name==="dayPeriod"?next===0?"am":"pm":next);return}if((event.key==="Backspace"||event.key==="Delete")&&!this.readonly){event.preventDefault(),this.resetDigitBuffer(),this.setDraftSegment(name,null);return}event.key==="Enter"&&(this.open?this.hide():this.readonly||submitOnEnter(this,event))},this.onSegmentPaste=event=>{if(this.liveDisabled||this.readonly)return;const pasted=normalizeTimeValue(event.clipboardData?.getData("text").trim()??"");pasted&&(event.preventDefault(),this.resetDigitBuffer(),this.commitUserValue(pasted,"insertFromPaste",!0))},this.onSegmentFocus=event=>{if(event.stopPropagation(),this.liveDisabled)return;const target=event.target,focusedSegment=target.dataset.segment??this.activeSegment;if(this.restoringSegmentFocus||this.restoringPopupFocus){if(queueMicrotask(()=>{this.isConnected&&this.segmentOrder.includes(focusedSegment)&&shadowFocusTarget(this)===target&&(this.activeSegment=focusedSegment)}),this.restoringSegmentFocus)return}else this.activeSegment=focusedSegment;const related=event.relatedTarget;containsElement(this.renderRoot.querySelector('[part="input"]'),related)||relayNativeEvent(this,event)},this.onSegmentBlur=event=>{if(event.stopPropagation(),this.pendingSegmentFocus){this.resetDigitBuffer();return}const related=event.relatedTarget;containsElement(this.renderRoot.querySelector('[part="input"]'),related)||(this.liveDisabled||(this.touched=!0),this.resetDigitBuffer(),relayNativeEvent(this,event))},this.onDocumentPointerDown=event=>{const target=event.composedPath()[0];isElementNode(target)&&composedContains(this,target)||this.requestVisibility(!1,!0,!1)},this.onExpand=()=>{this.liveDisabled||(this.open?this.hide():this.show())},this.onClear=()=>{this.liveDisabled||this.readonly||!this.draftHasAny&&this.value===""||(this.touched=!0,this.commitUserValue("","deleteContentBackward",!0),this.emit("lr-clear"),this.focus())},this.onNow=()=>{if(this.liveDisabled||this.readonly)return;const now=this.now();let value=`${pad(now.getHours())}:${pad(now.getMinutes())}`;this.includeSeconds&&(value+=`:${pad(now.getSeconds())}`),this.commitUserValue(value)},this.onPopupPointerDown=event=>{event.preventDefault()},this.onAutofillInput=event=>{event.stopPropagation();const input=event.currentTarget,normalized=normalizeTimeValue(input.value),intentionalClear=input.value===""&&(event.isTrusted||event.inputType.startsWith("delete")||event.inputType==="insertReplacementText");if(input.value===""&&this.value!==""&&!intentionalClear){input.value=this.value;return}input.value!==""&&!normalized||this.readonly||this.liveDisabled||(this.value=normalized,dispatchNativeInputEvent(this,{data:event.data,inputType:event.inputType||"insertReplacementText"}),this.emit("lr-input",{value:this.value}))},this.onAutofillChange=event=>{event.stopPropagation();const input=event.currentTarget,normalized=normalizeTimeValue(input.value);input.value!==""&&!normalized||this.readonly||this.liveDisabled||(this.value=normalized,dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value}))},this.onColumnKeyDown=event=>{if(this.liveDisabled||!["ArrowUp","ArrowDown","Home","End"].includes(event.key))return;const current=event.currentTarget,column=current.closest('[role="listbox"]'),options=Array.from(column?.querySelectorAll('[role="option"]')??[]).filter(option=>!option.disabled);if(options.length===0)return;event.preventDefault();const index=Math.max(0,options.indexOf(current)),nextIndex=event.key==="Home"?0:event.key==="End"?options.length-1:(index+(event.key==="ArrowDown"?1:-1)+options.length)%options.length;for(const option of options)option.tabIndex=option===options[nextIndex]?0:-1;options[nextIndex].focus(),options[nextIndex].scrollIntoView({block:"nearest"})},new GlassScrollLayer(this,'[part="popup"]',()=>this.open),this.addEventListener("invalid",()=>{this.touched=!0})}get open(){return this._open}set open(next){this.requestVisibility(!!next,this.isConnected&&this.hasUpdated,!0)}get readonly(){return this._readonly}set readonly(next){const old=this._readonly;this._readonly=!!next,this.toggleAttribute("readonly",this._readonly),this._readonly&&this.forceClose(!1),this.updateValidity(),this.requestUpdate("readonly",old)}get step(){return this._step}set step(next){const old=this._step;if(next==="any")this._step=next;else{const numeric=finiteNumber(Number(next),60);this._step=numeric>0?numeric:60}const genuinePrecision=parseTimeValue(this.genuineValue)?.precision;this.secondsVisible=this.numericStep<60||genuinePrecision!==void 0&&genuinePrecision!=="minute";const committed=this.committedValue;committed!==this.value&&(super.value=committed),this.updateValidity(),this.requestUpdate("step",old)}get disabled(){return super.disabled}set disabled(next){super.disabled=next,next&&this.forceClose(!1),this.syncComponentStates()}get value(){return super.value}set value(next){this.genuineValue=normalizeTimeValue(next);const normalized=this.committedValue;this.partial=!1,this.resetDigitBuffer(),this.syncDraft(normalized),super.value=normalized,this.syncComponentStates()}get valueAsNumber(){return parseTimeValue(this.value)?.milliseconds??Number.NaN}set valueAsNumber(next){this.value=timeValueFromMilliseconds(next)}get valueAsDate(){const parsed=parseTimeValue(this.value);if(!parsed)return null;const result=this.now();return result.setHours(parsed.hour,parsed.minute,parsed.second,parsed.millisecond),result}set valueAsDate(next){this.value=normalizeTimeValue(next)}get valueAsLocalDate(){return this.valueAsDate}set valueAsLocalDate(next){this.valueAsDate=next}get valueAsUTCDate(){const parsed=parseTimeValue(this.value);return parsed?new Date(parsed.milliseconds):null}set valueAsUTCDate(next){this.value=timeValueFromMilliseconds(wrapTimeMilliseconds(isDateObject(next)?next.getTime():NaN))}get numericStep(){return this.step==="any"?60:finiteNumber(this.step,60)}padToStepPrecision(value){return value&&this.numericStep<60&&parseTimeValue(value)?.precision==="minute"?`${value}:00`:value}get committedValue(){return this.padToStepPrecision(this.genuineValue)}get includeSeconds(){return this.numericStep<60||this.secondsVisible}get segmentModel(){const locale=this.effectiveLocale,key=`${locale}|${this.hourFormat}|${this.includeSeconds}`;if(this.segmentModelCache?.key!==key){const pattern=localeTimePattern(locale,this.hourFormat,this.includeSeconds),order=pattern.filter(part=>part.type!=="literal").map(part=>part.type);this.segmentModelCache={key,pattern,order,twelveHour:order.includes("dayPeriod")}}return this.segmentModelCache}get pattern(){return this.segmentModel.pattern}get segmentOrder(){return this.segmentModel.order}get periodLabels(){const model=this.segmentModel;return model.labels??=dayPeriodLabels(this.effectiveLocale)}get liveDisabled(){const matches=this.matches;return this.effectiveDisabled||typeof matches=="function"&&matches.call(this,":disabled")}activeSegmentFor(order=this.segmentOrder){return order.includes(this.activeSegment)?this.activeSegment:order[0]??"hour"}get usesTwelveHour(){return this.segmentModel.twelveHour}get draftComplete(){return this.draft.hour!==null&&this.draft.minute!==null&&(!this.includeSeconds||this.draft.second!==null)&&(!this.usesTwelveHour||this.draft.dayPeriod!==null)}get draftHasAny(){return Object.values(this.draft).some(value=>value!==null)}syncDraft(value){const parsed=parseTimeValue(value);if(!parsed){this.draft=blankDraft(),this.secondsVisible=this.numericStep<60;return}this.draft={hour:parsed.hour,minute:parsed.minute,second:parsed.second,dayPeriod:parsed.hour>=12?"pm":"am"};const genuinePrecision=parseTimeValue(this.genuineValue)?.precision;this.secondsVisible=this.numericStep<60||genuinePrecision!==void 0&&genuinePrecision!=="minute"}canonicalDraftValue(){if(!this.draftComplete)return"";const value=`${pad(this.draft.hour)}:${pad(this.draft.minute)}`;return this.includeSeconds?`${value}:${pad(this.draft.second)}`:value}syncComponentStates(){setCustomState(this.internals,"blank",this.value===""),setCustomState(this.internals,"disabled",this.effectiveDisabled),setCustomState(this.internals,"open",this.open)}formattedNumber(value,minimumIntegerDigits){return this.numberFormatter(minimumIntegerDigits)(value)}numberFormatter(minimumIntegerDigits){try{const formatter=getNumberFormat(this.effectiveLocale,{minimumIntegerDigits,useGrouping:!1});return value=>formatter.format(value)}catch{return value=>String(value).padStart(minimumIntegerDigits,"0")}}inputDigit(key){if(/^[0-9]$/.test(key))return key;const locale=this.effectiveLocale;if(this.inputDigitMap&&this.inputDigitLocale===locale)return this.inputDigitMap.get(key);const digits=new Map;try{const formatter=getNumberFormat(locale,{useGrouping:!1});for(let value=0;value<=9;value++){const integer=formatter.formatToParts(value).find(part=>part.type==="integer")?.value;integer!==void 0&&!digits.has(integer)&&digits.set(integer,String(value))}this.inputDigitLocale=locale,this.inputDigitMap=digits}catch{}return digits.get(key)}displayTime(value){const parsed=parseTimeValue(value);if(!parsed)return value;const includeSeconds=parsed.precision!=="minute",labels=this.periodLabels;return localeTimePattern(this.effectiveLocale,this.hourFormat,includeSeconds).map(part=>{if(part.type==="literal")return part.value;if(part.type==="hour"){const hour=this.usesTwelveHour?parsed.hour%12||12:parsed.hour;return this.formattedNumber(hour,this.usesTwelveHour?1:2)}return part.type==="minute"?this.formattedNumber(parsed.minute,2):part.type==="second"?this.formattedNumber(parsed.second,2):parsed.hour>=12?labels.pm:labels.am}).join("")}segmentNumericValue(name){return name==="hour"?this.draft.hour===null?null:this.usesTwelveHour?this.draft.hour%12||12:this.draft.hour:name==="minute"?this.draft.minute:name==="second"?this.draft.second:this.draft.dayPeriod==="am"?0:this.draft.dayPeriod==="pm"?1:null}segmentText(name){if(this.digitSegment===name&&this.digitBuffer)return this.formattedNumber(Number(this.digitBuffer),this.digitBuffer.length);if(name==="dayPeriod")return this.draft.dayPeriod?this.periodLabels[this.draft.dayPeriod]:"--";const value=this.segmentNumericValue(name);if(value===null)return"--";const minimumDigits=name==="hour"&&this.usesTwelveHour?1:2;return this.formattedNumber(value,minimumDigits)}segmentLabel(name){const keys={hour:"timeInputHour",minute:"timeInputMinute",second:"timeInputSecond",dayPeriod:"timeInputDayPeriod"};return this.localize(keys[name])}segmentBounds(name){return name==="hour"?this.usesTwelveHour?{min:1,max:12}:{min:0,max:23}:name==="dayPeriod"?{min:0,max:1}:{min:0,max:59}}setDraftSegment(name,value,user=!0){if(!(this.liveDisabled||user&&this.readonly)){if(name==="hour")if(value===null)this.draft.hour=null;else{const numeric=Number(value);this.draft.hour=this.usesTwelveHour?to24Hour(numeric,this.draft.dayPeriod??"am"):numeric}else if(name==="dayPeriod"){const period=value==="pm"?"pm":value==="am"?"am":null;if(period&&this.draft.hour!==null){const displayHour=this.draft.hour%12||12;this.draft.hour=to24Hour(displayHour,period)}this.draft.dayPeriod=period}else this.draft[name]=value===null?null:Number(value);if(!user){this.requestUpdate();return}this.publishDraftEdit()}}publishDraftEdit(){const before=super.value,next=this.canonicalDraftValue();this.partial=this.draftHasAny&&!this.draftComplete,this.genuineValue=next,super.value=next,this.syncComponentStates(),dispatchNativeInputEvent(this,{inputType:"insertReplacementText"}),this.emit("lr-input",{value:this.value}),next!==""&&next!==before&&(dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value})),this.requestUpdate()}commitUserValue(value,inputType="insertReplacementText",forceChange=!1){const before=this.value;this.value=value,dispatchNativeInputEvent(this,{inputType}),this.emit("lr-input",{value:this.value}),(forceChange||this.value!==before)&&(dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value}))}resetDigitBuffer(){this.digitBuffer="",this.digitSegment=void 0}moveSegment(from,direction){const order=this.segmentOrder,current=Math.max(0,order.indexOf(from)),next=Math.min(order.length-1,Math.max(0,current+direction));this.activeSegment=order[next]??"hour",this.segmentElement(this.activeSegment)?.focus()}acceptDigit(name,digit){if(name==="dayPeriod")return;this.digitSegment!==name&&(this.digitSegment=name,this.digitBuffer="");const bounds=this.segmentBounds(name);let candidateText=`${this.digitBuffer}${digit}`.slice(-2),candidate=Number(candidateText);(candidate>bounds.max||candidateText.length===2&&candidate<bounds.min)&&(candidateText=digit,candidate=Number(digit)),this.digitBuffer=candidateText,candidate>=bounds.min&&candidate<=bounds.max?this.setDraftSegment(name,candidate):this.requestUpdate();const cannotAcceptAnother=candidate*10>bounds.max;(candidateText.length===2||cannotAcceptAnother)&&(this.resetDigitBuffer(),this.moveSegment(name,1))}stepSegment(name,delta){const bounds=this.segmentBounds(name),current=this.segmentNumericValue(name),next=current===null?bounds.min:(current-bounds.min+delta+(bounds.max-bounds.min+1))%(bounds.max-bounds.min+1)+bounds.min;name==="dayPeriod"?this.setDraftSegment(name,next===0?"am":"pm"):this.setDraftSegment(name,next)}segmentElement(name){return this.renderRoot?.querySelector(`[data-segment="${name}"]`)}focus(options){if(this.liveDisabled)return;const order=this.segmentOrder,activeSegment=this.activeSegmentFor(order);activeSegment!==this.activeSegment&&(this.activeSegment=activeSegment),this.segmentElement(activeSegment)?.focus(options)}blur(){const active=shadowFocusTarget(this);active&&typeof active.blur=="function"&&active.blur()}click(){this.liveDisabled||this.focus()}setOpen(next){if(this._open===next)return;const old=this._open;this._open=next,this.syncComponentStates(),this.requestUpdate("open",old)}syncOpenAttribute(){this.toggleAttribute("open",this._open)}requestVisibility(next,announce,restoreFocus){return this._open===next?this.visibilityPromise:next&&(this.liveDisabled||this.readonly)?(this.syncOpenAttribute(),Promise.resolve()):announce&&this.emit(next?"lr-show":"lr-hide",null,{cancelable:!0}).defaultPrevented?(this.syncOpenAttribute(),Promise.resolve()):(this.restoreFocusOnClose=restoreFocus,this.setOpen(next),this.visibilityPromise=announce?this.settleTransition(next?"lr-after-show":"lr-after-hide"):Promise.resolve(),this.visibilityPromise)}show(){return this.requestVisibility(!0,!0,!0)}hide(){return this.requestVisibility(!1,!0,!0)}forceClose(restoreFocus){this._open&&(this.restoreFocusOnClose=restoreFocus,this.setOpen(!1))}settleTransition(event){return this.popupController.settle(event,{waitForPosition:async stale=>{const positioned=await waitForDeferredPlacement(()=>this.cleanupPositioner);return stale()||!this.open?!1:positioned?(this.popupPositioned=!0,!0):(this.forceClose(!1),!1)},conceal:()=>{this.popupHidden=!0}})}positionPopup(){this.cleanupPositioner?.(),this.cleanupPositioner=void 0;const anchor=this.renderRoot.querySelector('[part~="time-input"]'),popup=this.renderRoot.querySelector('[part="popup"]');if(!anchor||!popup)return;this.cleanupPositioner=place(anchor,popup,{placement:rtlAwarePlacement(this.placement,this),offset:finiteNumber(this.distance,0),sync:"width",strategy:resolveEffectivePositioningStrategy(this,void 0,"fixed")});const operation=this.cleanupPositioner;operation.ready.then(positioned=>{positioned&&this.cleanupPositioner===operation&&this.open&&this.isConnected&&(this.popupPositioned=!0)})}activatePopup(){this.isConnected&&(this.positionPopup(),this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="popup"]'),onEscape:()=>{this.hide()},restoreFocusTo:this.segmentElement(this.activeSegment)}),this.popupController.bindPointer(),this.updateComplete.then(()=>{const option=this.renderRoot.querySelector('[part~="column-item-selected"]'),column=option?.closest('[part="column"]');if(!option||!column)return;const offset=option.getBoundingClientRect().top-column.getBoundingClientRect().top;column.scrollTop+=offset-(column.clientHeight-option.offsetHeight)/2}))}teardownPopup(){this.cleanupPositioner?.(),this.cleanupPositioner=void 0;const restoringPopupFocus=this.restoringPopupFocus;this.restoringPopupFocus=!0;try{this.overlayHandle?.deactivate({restoreFocus:this.restoreFocusOnClose})}finally{this.restoringPopupFocus=restoringPopupFocus}this.overlayHandle=void 0,this.popupController.unbindPointer(),this.restoreFocusOnClose=!0}onColumnSelect(name,value){this.readonly||this.liveDisabled||(this.resetDigitBuffer(),this.setDraftSegment(name,value),this.activeSegment=name,this.updateComplete.then(()=>this.segmentElement(name)?.focus()))}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let message="";this.required&&this.value===""&&(flags.valueMissing=!0),this.partial&&(flags.badInput=!0);const parsed=parseTimeValue(this.value);if(this.value!==""&&!parsed&&(flags.badInput=!0),parsed&&!isTimeInRange(this.value,this.min,this.max)){const parsedMin=parseTimeValue(this.min),parsedMax=parseTimeValue(this.max);parsedMin&&parsedMax&&parsedMin.milliseconds>parsedMax.milliseconds?(flags.rangeUnderflow=!0,message=this.localize("timeInputRangeMessage",void 0,{min:this.displayTime(this.min),max:this.displayTime(this.max)})):parsedMin&&parsed.milliseconds<parsedMin.milliseconds?(flags.rangeUnderflow=!0,message=this.localize("timeInputMinMessage",void 0,{min:this.displayTime(this.min)})):(flags.rangeOverflow=!0,message=this.localize("timeInputMaxMessage",void 0,{max:this.displayTime(this.max)}))}parsed&&hasTimeStepMismatch(this.value,this.step,this.min,this.defaultValue)&&(flags.stepMismatch=!0,message||=this.localize("timeInputStepMessage")),flags.badInput?message=this.localize("timeInputInvalid"):flags.valueMissing&&(message=this.localize("fieldRequired")),this[SET_ANCHORED_VALIDITY](flags,message)}checkValidity(){return this.updateValidity(),super.checkValidity()}reportValidity(){return this.touched=!0,this.updateValidity(),super.reportValidity()}[VALIDITY_ANCHOR](){return this.segmentElement(this.activeSegmentFor())}formResetCallback(){super.formResetCallback(),this.touched=!1,this.partial=!1,this.resetDigitBuffer()}formStateRestoreCallback(state2,reason="restore"){super.formStateRestoreCallback(state2,reason)}willUpdate(changed){super.willUpdate(changed),this.open&&this.effectiveDisabled&&this.forceClose(!1);const order=this.segmentOrder,orderKey=order.join("|"),focused=orderKey!==this.segmentOrderKey?shadowFocusTarget(this):null,focusedSegment=typeof focused?.getAttribute=="function"?focused.getAttribute("data-segment"):null,nextActiveSegment=focusedSegment&&order.includes(focusedSegment)?focusedSegment:this.activeSegmentFor(order);focusedSegment&&(this.pendingSegmentFocus=order.includes(focusedSegment)?focusedSegment:nextActiveSegment),this.segmentOrderKey=orderKey,changed.has("open")&&(this.popupPositioned=!1),this.open&&(this.popupHidden=!1)}updated(changed){super.updated(changed),changed.has("open")?this.open?this.activatePopup():this.teardownPopup():this.open&&(changed.has("placement")||changed.has("distance"))&&this.positionPopup(),(changed.has("value")||changed.has("required")||changed.has("readonly")||changed.has("min")||changed.has("max")||changed.has("step"))&&this.updateValidity(),this.syncComponentStates(),this.toggleAttribute("data-invalid",this.touched&&!this.validity.valid);const pendingSegmentFocus=this.pendingSegmentFocus;if(this.pendingSegmentFocus=void 0,pendingSegmentFocus&&!this.effectiveDisabled){this.restoringSegmentFocus=!0;try{this.segmentElement(pendingSegmentFocus)?.focus()}finally{this.restoringSegmentFocus=!1}}}disconnectedCallback(){this.popupHidden=!0,this.popupController.cancel(),this.forceClose(!1),this.teardownPopup(),this.syncOpenAttribute(),this.pendingSegmentFocus=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted()}renderSegment(name,invalid){const value=this.segmentNumericValue(name),bounds=this.segmentBounds(name),empty=value===null;return html`
|
|
1
|
+
import{__decorate}from"tslib";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{sizes}from"../../../internal/sizes.styles.js";import{closeIcon,chevronIcon}from"../../../internal/icons.js";import{finiteNumber}from"../../../internal/numbers.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{deferredPlaceReady as place,waitForDeferredPlacement}from"../../../internal/anchored-overlay-runtime.js";import{PopupController,emitPopupEvent}from"../../../internal/popup-controller.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{activateNonmodalOverlay,composedContains}from"../../../internal/nonmodal-overlay-manager.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{setCustomState}from"../../../internal/custom-states.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{dayPeriodLabels,hasTimeStepMismatch,isTimeInRange,localeTimePattern,normalizeTimeValue,parseTimeValue,timeValueFromMilliseconds,timeStepBaseMilliseconds,to24Hour,wrapTimeMilliseconds}from"./time-input-shared.js";import{styles}from"./time-input.styles.js";import{isDateObject}from"../../../internal/dom-guards.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_timeInputDayPeriod,LYRA_DEFAULT_timeInputEmptySegment,LYRA_DEFAULT_timeInputHour,LYRA_DEFAULT_timeInputInvalid,LYRA_DEFAULT_timeInputLabel,LYRA_DEFAULT_timeInputMaxMessage,LYRA_DEFAULT_timeInputMinMessage,LYRA_DEFAULT_timeInputMinute,LYRA_DEFAULT_timeInputNow,LYRA_DEFAULT_timeInputOpen,LYRA_DEFAULT_timeInputPopup,LYRA_DEFAULT_timeInputRangeMessage,LYRA_DEFAULT_timeInputSecond,LYRA_DEFAULT_timeInputStepMessage}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings/shared.generated.js";class LyraTimeInputBase extends LyraElement{}const stepConverter={fromAttribute(value){if(value==="any")return"any";const parsed=Number(value);return Number.isFinite(parsed)&&parsed>0?parsed:60},toAttribute(value){return String(value)}},hourFormatConverter={fromAttribute(value){return value==="12"||value==="24"?value:"auto"},toAttribute(value){return value}},PLACEMENTS=new Set(["top","top-start","top-end","right","right-start","right-end","bottom","bottom-start","bottom-end","left","left-start","left-end"]),placementConverter={fromAttribute(value){return PLACEMENTS.has(value)?value:"bottom-start"},toAttribute(value){return value}},blankDraft=()=>({hour:null,minute:null,second:null,dayPeriod:null}),pad=value=>String(value).padStart(2,"0");function isElementNode(value){if(value===null||typeof value!="object")return!1;const candidate=value;return candidate.nodeType===1&&typeof candidate.getRootNode=="function"&&typeof candidate.contains=="function"}function containsElement(container,value){if(!container||!isElementNode(value))return!1;try{return container.contains(value)}catch{return!1}}class LyraTimeInput extends FormAssociated(LyraTimeInputBase){static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,fieldRequired:LYRA_DEFAULT_fieldRequired,timeInputDayPeriod:LYRA_DEFAULT_timeInputDayPeriod,timeInputEmptySegment:LYRA_DEFAULT_timeInputEmptySegment,timeInputHour:LYRA_DEFAULT_timeInputHour,timeInputInvalid:LYRA_DEFAULT_timeInputInvalid,timeInputLabel:LYRA_DEFAULT_timeInputLabel,timeInputMaxMessage:LYRA_DEFAULT_timeInputMaxMessage,timeInputMinMessage:LYRA_DEFAULT_timeInputMinMessage,timeInputMinute:LYRA_DEFAULT_timeInputMinute,timeInputNow:LYRA_DEFAULT_timeInputNow,timeInputOpen:LYRA_DEFAULT_timeInputOpen,timeInputPopup:LYRA_DEFAULT_timeInputPopup,timeInputRangeMessage:LYRA_DEFAULT_timeInputRangeMessage,timeInputSecond:LYRA_DEFAULT_timeInputSecond,timeInputStepMessage:LYRA_DEFAULT_timeInputStepMessage}}static get validators(){return[currentValidityValidator("required","disabled","readonly","value","min","max","step")]}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}static{this.properties={open:{type:Boolean,reflect:!0,noAccessor:!0},readonly:{type:Boolean,reflect:!0,noAccessor:!0},step:{converter:stepConverter,reflect:!0,noAccessor:!0}}}get hasLabelSlot(){return this.slotPresence.has("label")}get hasHintSlot(){return this.slotPresence.has("hint")}get hasErrorSlot(){return this.slotPresence.has("error")}get hasStartSlot(){return this.slotPresence.has("start")}get hasEndSlot(){return this.slotPresence.has("end")}get hasFooterSlot(){return this.slotPresence.has("footer")}constructor(){super(),this.appearance="outlined",this.autocomplete="",this.distance=0,this.hint="",this.hourFormat="auto",this.label="",this.labelDisplay="visible",this.min="",this.max="",this.pill=!1,this.placement="bottom-start",this.size="m",this.clearable=!1,this.withClear=!1,this.withHint=!1,this.withLabel=!1,this.withNow=!1,this.errorText="",this.activeSegment="hour",this.touched=!1,this.slotPresence=new SlotPresenceController(this),this.popupHidden=!0,this.popupPositioned=!1,this._open=!1,this._readonly=!1,this._step=60,this.draft=blankDraft(),this.partial=!1,this.secondsVisible=!1,this.genuineValue="",this.digitBuffer="",this.inputDigitLocale="",this.restoringSegmentFocus=!1,this.restoringPopupFocus=!1,this.restoreFocusOnClose=!0,this.popupController=new PopupController({host:this,popup:()=>this.renderRoot.querySelector('[part="popup"]'),emit:(name,cancelable)=>emitPopupEvent(this,name,cancelable),onPointer:event=>this.onDocumentPointerDown(event)}),this.visibilityPromise=Promise.resolve(),this.segmentOrderKey="",this.pickerGridKey="",this.pickerGridMilliseconds=[],this.inputId=nextId("time-input"),this.labelId=nextId("time-input-label"),this.hintId=nextId("time-input-hint"),this.errorId=nextId("time-input-error"),this.requiredDescriptionId=nextId("time-input-required"),this.popupId=nextId("time-input-popup"),this.hostDescription=new HostDescriptionController(this,()=>this.renderRoot.querySelector('[part~="input"]'),()=>{const description=this.renderRoot.querySelector(`#${this.requiredDescriptionId}`);return this.required&&description?[description]:[]}),this.now=()=>new Date,this.onSegmentKeyDown=event=>{const name=event.currentTarget.dataset.segment;if(this.liveDisabled)return;if(event.altKey&&event.key==="ArrowDown"){event.preventDefault(),this.show();return}const digit=this.inputDigit(event.key);if(digit!==void 0&&!event.ctrlKey&&!event.metaKey&&!event.altKey&&!this.readonly){event.preventDefault(),this.acceptDigit(name,digit);return}if(name==="dayPeriod"&&!this.readonly&&(event.key.toLowerCase()==="a"||event.key.toLowerCase()==="p")){event.preventDefault(),this.setDraftSegment(name,event.key.toLowerCase()==="a"?"am":"pm");return}if(event.key==="ArrowLeft"||event.key==="ArrowRight"){event.preventDefault();const physical=event.key==="ArrowRight"?1:-1;this.resetDigitBuffer(),this.moveSegment(name,this.effectiveDirection==="rtl"?-physical:physical);return}if((event.key==="ArrowUp"||event.key==="ArrowDown")&&!this.readonly){event.preventDefault(),this.resetDigitBuffer(),this.stepSegment(name,event.key==="ArrowUp"?1:-1);return}if((event.key==="Home"||event.key==="End")&&!this.readonly){event.preventDefault();const bounds=this.segmentBounds(name),next=event.key==="Home"?bounds.min:bounds.max;this.setDraftSegment(name,name==="dayPeriod"?next===0?"am":"pm":next);return}if((event.key==="Backspace"||event.key==="Delete")&&!this.readonly){event.preventDefault(),this.resetDigitBuffer(),this.setDraftSegment(name,null);return}event.key==="Enter"&&(this.open?this.hide():this.readonly||submitOnEnter(this,event))},this.onSegmentPaste=event=>{if(this.liveDisabled||this.readonly)return;const pasted=normalizeTimeValue(event.clipboardData?.getData("text").trim()??"");pasted&&(event.preventDefault(),this.resetDigitBuffer(),this.commitUserValue(pasted,"insertFromPaste",!0))},this.onSegmentFocus=event=>{if(event.stopPropagation(),this.liveDisabled)return;const target=event.target,focusedSegment=target.dataset.segment??this.activeSegment;if(this.restoringSegmentFocus||this.restoringPopupFocus){if(queueMicrotask(()=>{this.isConnected&&this.segmentOrder.includes(focusedSegment)&&shadowFocusTarget(this)===target&&(this.activeSegment=focusedSegment)}),this.restoringSegmentFocus)return}else this.activeSegment=focusedSegment;const related=event.relatedTarget;containsElement(this.renderRoot.querySelector('[part="input"]'),related)||relayNativeEvent(this,event)},this.onSegmentBlur=event=>{if(event.stopPropagation(),this.pendingSegmentFocus){this.resetDigitBuffer();return}const related=event.relatedTarget;containsElement(this.renderRoot.querySelector('[part="input"]'),related)||(this.liveDisabled||(this.touched=!0),this.resetDigitBuffer(),relayNativeEvent(this,event))},this.onDocumentPointerDown=event=>{const target=event.composedPath()[0];isElementNode(target)&&composedContains(this,target)||this.requestVisibility(!1,!0,!1)},this.onExpand=()=>{this.liveDisabled||(this.open?this.hide():this.show())},this.onClear=()=>{this.liveDisabled||this.readonly||!this.draftHasAny&&this.value===""||(this.touched=!0,this.commitUserValue("","deleteContentBackward",!0),this.emit("lr-clear"),this.focus())},this.onNow=()=>{if(this.liveDisabled||this.readonly)return;const now=this.now();let value=`${pad(now.getHours())}:${pad(now.getMinutes())}`;this.includeSeconds&&(value+=`:${pad(now.getSeconds())}`),this.commitUserValue(value)},this.onPopupPointerDown=event=>{event.preventDefault()},this.onAutofillInput=event=>{event.stopPropagation();const input=event.currentTarget,normalized=normalizeTimeValue(input.value),intentionalClear=input.value===""&&(event.isTrusted||event.inputType.startsWith("delete")||event.inputType==="insertReplacementText");if(input.value===""&&this.value!==""&&!intentionalClear){input.value=this.value;return}input.value!==""&&!normalized||this.readonly||this.liveDisabled||(this.value=normalized,dispatchNativeInputEvent(this,{data:event.data,inputType:event.inputType||"insertReplacementText"}),this.emit("lr-input",{value:this.value}))},this.onAutofillChange=event=>{event.stopPropagation();const input=event.currentTarget,normalized=normalizeTimeValue(input.value);input.value!==""&&!normalized||this.readonly||this.liveDisabled||(this.value=normalized,dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value}))},this.onColumnKeyDown=event=>{if(this.liveDisabled||!["ArrowUp","ArrowDown","Home","End"].includes(event.key))return;const current=event.currentTarget,column=current.closest('[role="listbox"]'),options=Array.from(column?.querySelectorAll('[role="option"]')??[]).filter(option=>!option.disabled);if(options.length===0)return;event.preventDefault();const index=Math.max(0,options.indexOf(current)),nextIndex=event.key==="Home"?0:event.key==="End"?options.length-1:(index+(event.key==="ArrowDown"?1:-1)+options.length)%options.length;for(const option of options)option.tabIndex=option===options[nextIndex]?0:-1;options[nextIndex].focus(),options[nextIndex].scrollIntoView({block:"nearest"})},new GlassScrollLayer(this,'[part="popup"]',()=>this.open),this.addEventListener("invalid",()=>{this.touched=!0})}get open(){return this._open}set open(next){this.requestVisibility(!!next,this.isConnected&&this.hasUpdated,!0)}get readonly(){return this._readonly}set readonly(next){const old=this._readonly;this._readonly=!!next,this.toggleAttribute("readonly",this._readonly),this._readonly&&this.forceClose(!1),this.updateValidity(),this.requestUpdate("readonly",old)}get step(){return this._step}set step(next){const old=this._step;if(next==="any")this._step=next;else{const numeric=finiteNumber(Number(next),60);this._step=numeric>0?numeric:60}const genuinePrecision=parseTimeValue(this.genuineValue)?.precision;this.secondsVisible=this.numericStep<60||genuinePrecision!==void 0&&genuinePrecision!=="minute";const committed=this.committedValue;committed!==this.value&&(super.value=committed),this.updateValidity(),this.requestUpdate("step",old)}get disabled(){return super.disabled}set disabled(next){super.disabled=next,next&&this.forceClose(!1),this.syncComponentStates()}get value(){return super.value}set value(next){this.genuineValue=normalizeTimeValue(next);const normalized=this.committedValue;this.partial=!1,this.resetDigitBuffer(),this.syncDraft(normalized),super.value=normalized,this.syncComponentStates()}get valueAsNumber(){return parseTimeValue(this.value)?.milliseconds??Number.NaN}set valueAsNumber(next){this.value=timeValueFromMilliseconds(next)}get valueAsDate(){const parsed=parseTimeValue(this.value);if(!parsed)return null;const result=this.now();return result.setHours(parsed.hour,parsed.minute,parsed.second,parsed.millisecond),result}set valueAsDate(next){this.value=normalizeTimeValue(next)}get valueAsLocalDate(){return this.valueAsDate}set valueAsLocalDate(next){this.valueAsDate=next}get valueAsUTCDate(){const parsed=parseTimeValue(this.value);return parsed?new Date(parsed.milliseconds):null}set valueAsUTCDate(next){this.value=timeValueFromMilliseconds(wrapTimeMilliseconds(isDateObject(next)?next.getTime():NaN))}get numericStep(){return this.step==="any"?60:finiteNumber(this.step,60)}padToStepPrecision(value){return value&&this.numericStep<60&&parseTimeValue(value)?.precision==="minute"?`${value}:00`:value}get committedValue(){return this.padToStepPrecision(this.genuineValue)}get includeSeconds(){return this.numericStep<60||this.secondsVisible}get segmentModel(){const locale=this.effectiveLocale,key=`${locale}|${this.hourFormat}|${this.includeSeconds}`;if(this.segmentModelCache?.key!==key){const pattern=localeTimePattern(locale,this.hourFormat,this.includeSeconds),order=pattern.filter(part=>part.type!=="literal").map(part=>part.type);this.segmentModelCache={key,pattern,order,twelveHour:order.includes("dayPeriod")}}return this.segmentModelCache}get pattern(){return this.segmentModel.pattern}get segmentOrder(){return this.segmentModel.order}get periodLabels(){const model=this.segmentModel;return model.labels??=dayPeriodLabels(this.effectiveLocale)}get liveDisabled(){const matches=this.matches;return this.effectiveDisabled||typeof matches=="function"&&matches.call(this,":disabled")}activeSegmentFor(order=this.segmentOrder){return order.includes(this.activeSegment)?this.activeSegment:order[0]??"hour"}get usesTwelveHour(){return this.segmentModel.twelveHour}get draftComplete(){return this.draft.hour!==null&&this.draft.minute!==null&&(!this.includeSeconds||this.draft.second!==null)&&(!this.usesTwelveHour||this.draft.dayPeriod!==null)}get draftHasAny(){return Object.values(this.draft).some(value=>value!==null)}syncDraft(value){const parsed=parseTimeValue(value);if(!parsed){this.draft=blankDraft(),this.secondsVisible=this.numericStep<60;return}this.draft={hour:parsed.hour,minute:parsed.minute,second:parsed.second,dayPeriod:parsed.hour>=12?"pm":"am"};const genuinePrecision=parseTimeValue(this.genuineValue)?.precision;this.secondsVisible=this.numericStep<60||genuinePrecision!==void 0&&genuinePrecision!=="minute"}canonicalDraftValue(){if(!this.draftComplete)return"";const value=`${pad(this.draft.hour)}:${pad(this.draft.minute)}`;return this.includeSeconds?`${value}:${pad(this.draft.second)}`:value}syncComponentStates(){setCustomState(this.internals,"blank",this.value===""),setCustomState(this.internals,"disabled",this.effectiveDisabled),setCustomState(this.internals,"open",this.open)}formattedNumber(value,minimumIntegerDigits){return this.numberFormatter(minimumIntegerDigits)(value)}numberFormatter(minimumIntegerDigits){try{const formatter=getNumberFormat(this.effectiveLocale,{minimumIntegerDigits,useGrouping:!1});return value=>formatter.format(value)}catch{return value=>String(value).padStart(minimumIntegerDigits,"0")}}inputDigit(key){if(/^[0-9]$/.test(key))return key;const locale=this.effectiveLocale;if(this.inputDigitMap&&this.inputDigitLocale===locale)return this.inputDigitMap.get(key);const digits=new Map;try{const formatter=getNumberFormat(locale,{useGrouping:!1});for(let value=0;value<=9;value++){const integer=formatter.formatToParts(value).find(part=>part.type==="integer")?.value;integer!==void 0&&!digits.has(integer)&&digits.set(integer,String(value))}this.inputDigitLocale=locale,this.inputDigitMap=digits}catch{}return digits.get(key)}displayTime(value){const parsed=parseTimeValue(value);if(!parsed)return value;const includeSeconds=parsed.precision!=="minute",labels=this.periodLabels;return localeTimePattern(this.effectiveLocale,this.hourFormat,includeSeconds).map(part=>{if(part.type==="literal")return part.value;if(part.type==="hour"){const hour=this.usesTwelveHour?parsed.hour%12||12:parsed.hour;return this.formattedNumber(hour,this.usesTwelveHour?1:2)}return part.type==="minute"?this.formattedNumber(parsed.minute,2):part.type==="second"?this.formattedNumber(parsed.second,2):parsed.hour>=12?labels.pm:labels.am}).join("")}segmentNumericValue(name){return name==="hour"?this.draft.hour===null?null:this.usesTwelveHour?this.draft.hour%12||12:this.draft.hour:name==="minute"?this.draft.minute:name==="second"?this.draft.second:this.draft.dayPeriod==="am"?0:this.draft.dayPeriod==="pm"?1:null}segmentText(name){if(this.digitSegment===name&&this.digitBuffer)return this.formattedNumber(Number(this.digitBuffer),this.digitBuffer.length);if(name==="dayPeriod")return this.draft.dayPeriod?this.periodLabels[this.draft.dayPeriod]:"--";const value=this.segmentNumericValue(name);if(value===null)return"--";const minimumDigits=name==="hour"&&this.usesTwelveHour?1:2;return this.formattedNumber(value,minimumDigits)}segmentLabel(name){const keys={hour:"timeInputHour",minute:"timeInputMinute",second:"timeInputSecond",dayPeriod:"timeInputDayPeriod"};return this.localize(keys[name])}segmentBounds(name){return name==="hour"?this.usesTwelveHour?{min:1,max:12}:{min:0,max:23}:name==="dayPeriod"?{min:0,max:1}:{min:0,max:59}}setDraftSegment(name,value,user=!0){if(!(this.liveDisabled||user&&this.readonly)){if(name==="hour")if(value===null)this.draft.hour=null;else{const numeric=Number(value);this.draft.hour=this.usesTwelveHour?to24Hour(numeric,this.draft.dayPeriod??"am"):numeric}else if(name==="dayPeriod"){const period=value==="pm"?"pm":value==="am"?"am":null;if(period&&this.draft.hour!==null){const displayHour=this.draft.hour%12||12;this.draft.hour=to24Hour(displayHour,period)}this.draft.dayPeriod=period}else this.draft[name]=value===null?null:Number(value);if(!user){this.requestUpdate();return}this.publishDraftEdit()}}publishDraftEdit(){const before=super.value,next=this.canonicalDraftValue();this.partial=this.draftHasAny&&!this.draftComplete,this.genuineValue=next,super.value=next,this.syncComponentStates(),dispatchNativeInputEvent(this,{inputType:"insertReplacementText"}),this.emit("lr-input",{value:this.value}),next!==""&&next!==before&&(dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value})),this.requestUpdate()}commitUserValue(value,inputType="insertReplacementText",forceChange=!1){const before=this.value;this.value=value,dispatchNativeInputEvent(this,{inputType}),this.emit("lr-input",{value:this.value}),(forceChange||this.value!==before)&&(dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value}))}resetDigitBuffer(){this.digitBuffer="",this.digitSegment=void 0}moveSegment(from,direction){const order=this.segmentOrder,current=Math.max(0,order.indexOf(from)),next=Math.min(order.length-1,Math.max(0,current+direction));this.activeSegment=order[next]??"hour",this.segmentElement(this.activeSegment)?.focus()}acceptDigit(name,digit){if(name==="dayPeriod")return;this.digitSegment!==name&&(this.digitSegment=name,this.digitBuffer="");const bounds=this.segmentBounds(name);let candidateText=`${this.digitBuffer}${digit}`.slice(-2),candidate=Number(candidateText);(candidate>bounds.max||candidateText.length===2&&candidate<bounds.min)&&(candidateText=digit,candidate=Number(digit)),this.digitBuffer=candidateText,candidate>=bounds.min&&candidate<=bounds.max?this.setDraftSegment(name,candidate):this.requestUpdate();const cannotAcceptAnother=candidate*10>bounds.max;(candidateText.length===2||cannotAcceptAnother)&&(this.resetDigitBuffer(),this.moveSegment(name,1))}stepSegment(name,delta){const bounds=this.segmentBounds(name),current=this.segmentNumericValue(name),next=current===null?bounds.min:(current-bounds.min+delta+(bounds.max-bounds.min+1))%(bounds.max-bounds.min+1)+bounds.min;name==="dayPeriod"?this.setDraftSegment(name,next===0?"am":"pm"):this.setDraftSegment(name,next)}segmentElement(name){return this.renderRoot?.querySelector(`[data-segment="${name}"]`)}focus(options){if(this.liveDisabled)return;const order=this.segmentOrder,activeSegment=this.activeSegmentFor(order);activeSegment!==this.activeSegment&&(this.activeSegment=activeSegment),this.segmentElement(activeSegment)?.focus(options)}blur(){const active=shadowFocusTarget(this);active&&typeof active.blur=="function"&&active.blur()}click(){this.liveDisabled||this.focus()}setOpen(next){if(this._open===next)return;const old=this._open;this._open=next,this.syncComponentStates(),this.requestUpdate("open",old)}syncOpenAttribute(){this.toggleAttribute("open",this._open)}requestVisibility(next,announce,restoreFocus){return this._open===next?this.visibilityPromise:next&&(this.liveDisabled||this.readonly)?(this.syncOpenAttribute(),Promise.resolve()):announce&&this.emit(next?"lr-show":"lr-hide",null,{cancelable:!0}).defaultPrevented?(this.syncOpenAttribute(),Promise.resolve()):(this.restoreFocusOnClose=restoreFocus,this.setOpen(next),this.visibilityPromise=announce?this.settleTransition(next?"lr-after-show":"lr-after-hide"):Promise.resolve(),this.visibilityPromise)}show(){return this.requestVisibility(!0,!0,!0)}hide(){return this.requestVisibility(!1,!0,!0)}forceClose(restoreFocus){this._open&&(this.restoreFocusOnClose=restoreFocus,this.setOpen(!1))}settleTransition(event){return this.popupController.settle(event,{waitForPosition:async stale=>{const positioned=await waitForDeferredPlacement(()=>this.cleanupPositioner);return stale()||!this.open?!1:positioned?(this.popupPositioned=!0,!0):(this.forceClose(!1),!1)},conceal:()=>{this.popupHidden=!0}})}positionPopup(){this.cleanupPositioner?.(),this.cleanupPositioner=void 0;const anchor=this.renderRoot.querySelector('[part~="time-input"]'),popup=this.renderRoot.querySelector('[part="popup"]');if(!anchor||!popup)return;this.cleanupPositioner=place(anchor,popup,{placement:rtlAwarePlacement(this.placement,this),offset:finiteNumber(this.distance,0),sync:"width",strategy:resolveEffectivePositioningStrategy(this,void 0,"fixed")});const operation=this.cleanupPositioner;operation.ready.then(positioned=>{positioned&&this.cleanupPositioner===operation&&this.open&&this.isConnected&&(this.popupPositioned=!0)})}activatePopup(){this.isConnected&&(this.positionPopup(),this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="popup"]'),onEscape:()=>{this.hide()},restoreFocusTo:this.segmentElement(this.activeSegment)}),this.popupController.bindPointer(),this.updateComplete.then(()=>{const option=this.renderRoot.querySelector('[part~="column-item-selected"]'),column=option?.closest('[part="column"]');if(!option||!column)return;const offset=option.getBoundingClientRect().top-column.getBoundingClientRect().top;column.scrollTop+=offset-(column.clientHeight-option.offsetHeight)/2}))}teardownPopup(){this.cleanupPositioner?.(),this.cleanupPositioner=void 0;const restoringPopupFocus=this.restoringPopupFocus;this.restoringPopupFocus=!0;try{this.overlayHandle?.deactivate({restoreFocus:this.restoreFocusOnClose})}finally{this.restoringPopupFocus=restoringPopupFocus}this.overlayHandle=void 0,this.popupController.unbindPointer(),this.restoreFocusOnClose=!0}onColumnSelect(name,value){this.readonly||this.liveDisabled||(this.resetDigitBuffer(),this.setDraftSegment(name,value),this.activeSegment=name,this.updateComplete.then(()=>this.segmentElement(name)?.focus()))}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let message="";this.required&&this.value===""&&(flags.valueMissing=!0),this.partial&&(flags.badInput=!0);const parsed=parseTimeValue(this.value);if(this.value!==""&&!parsed&&(flags.badInput=!0),parsed&&!isTimeInRange(this.value,this.min,this.max)){const parsedMin=parseTimeValue(this.min),parsedMax=parseTimeValue(this.max);parsedMin&&parsedMax&&parsedMin.milliseconds>parsedMax.milliseconds?(flags.rangeUnderflow=!0,message=this.localize("timeInputRangeMessage",void 0,{min:this.displayTime(this.min),max:this.displayTime(this.max)})):parsedMin&&parsed.milliseconds<parsedMin.milliseconds?(flags.rangeUnderflow=!0,message=this.localize("timeInputMinMessage",void 0,{min:this.displayTime(this.min)})):(flags.rangeOverflow=!0,message=this.localize("timeInputMaxMessage",void 0,{max:this.displayTime(this.max)}))}parsed&&hasTimeStepMismatch(this.value,this.step,this.min,this.defaultValue)&&(flags.stepMismatch=!0,message||=this.localize("timeInputStepMessage")),flags.badInput?message=this.localize("timeInputInvalid"):flags.valueMissing&&(message=this.localize("fieldRequired")),this[SET_ANCHORED_VALIDITY](flags,message)}checkValidity(){return this.updateValidity(),super.checkValidity()}reportValidity(){return this.touched=!0,this.updateValidity(),super.reportValidity()}[VALIDITY_ANCHOR](){return this.segmentElement(this.activeSegmentFor())}formResetCallback(){super.formResetCallback(),this.touched=!1,this.partial=!1,this.resetDigitBuffer()}formStateRestoreCallback(state2,reason="restore"){super.formStateRestoreCallback(state2,reason)}willUpdate(changed){super.willUpdate(changed),this.open&&this.effectiveDisabled&&this.forceClose(!1);const order=this.segmentOrder,orderKey=order.join("|"),focused=orderKey!==this.segmentOrderKey?shadowFocusTarget(this):null,focusedSegment=typeof focused?.getAttribute=="function"?focused.getAttribute("data-segment"):null,nextActiveSegment=focusedSegment&&order.includes(focusedSegment)?focusedSegment:this.activeSegmentFor(order);focusedSegment&&(this.pendingSegmentFocus=order.includes(focusedSegment)?focusedSegment:nextActiveSegment),this.segmentOrderKey=orderKey,changed.has("open")&&(this.popupPositioned=!1),this.open&&(this.popupHidden=!1)}updated(changed){super.updated(changed),changed.has("open")?this.open?this.activatePopup():this.teardownPopup():this.open&&(changed.has("placement")||changed.has("distance"))&&this.positionPopup(),(changed.has("value")||changed.has("required")||changed.has("readonly")||changed.has("min")||changed.has("max")||changed.has("step"))&&this.updateValidity(),this.syncComponentStates(),this.toggleAttribute("data-invalid",this.touched&&!this.validity.valid);const pendingSegmentFocus=this.pendingSegmentFocus;if(this.pendingSegmentFocus=void 0,pendingSegmentFocus&&!this.effectiveDisabled){this.restoringSegmentFocus=!0;try{this.segmentElement(pendingSegmentFocus)?.focus()}finally{this.restoringSegmentFocus=!1}}}disconnectedCallback(){this.popupHidden=!0,this.popupController.cancel(),this.forceClose(!1),this.teardownPopup(),this.syncOpenAttribute(),this.pendingSegmentFocus=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted()}renderSegment(name,invalid){const value=this.segmentNumericValue(name),bounds=this.segmentBounds(name),empty=value===null;return html`
|
|
2
2
|
<span
|
|
3
3
|
part="segment"
|
|
4
4
|
role="spinbutton"
|
|
@@ -129,4 +129,4 @@ import{__decorate}from"tslib";import{SlotPresenceController}from"../../../intern
|
|
|
129
129
|
@change=${this.onAutofillChange}
|
|
130
130
|
/>
|
|
131
131
|
</div>
|
|
132
|
-
`}}__decorate([property({reflect:!0})],LyraTimeInput.prototype,"appearance",void 0),__decorate([property()],LyraTimeInput.prototype,"autocomplete",void 0),__decorate([property({type:Number,reflect:!0})],LyraTimeInput.prototype,"distance",void 0),__decorate([property()],LyraTimeInput.prototype,"hint",void 0),__decorate([property({attribute:"hour-format",converter:hourFormatConverter,reflect:!0})],LyraTimeInput.prototype,"hourFormat",void 0),__decorate([property()],LyraTimeInput.prototype,"label",void 0),__decorate([property({reflect:!0})],LyraTimeInput.prototype,"min",void 0),__decorate([property({reflect:!0})],LyraTimeInput.prototype,"max",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraTimeInput.prototype,"pill",void 0),__decorate([property({converter:placementConverter,reflect:!0})],LyraTimeInput.prototype,"placement",void 0),__decorate([property({reflect:!0})],LyraTimeInput.prototype,"size",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraTimeInput.prototype,"clearable",void 0),__decorate([property({type:Boolean,attribute:"with-clear"})],LyraTimeInput.prototype,"withClear",void 0),__decorate([property({type:Boolean,attribute:"with-hint"})],LyraTimeInput.prototype,"withHint",void 0),__decorate([property({type:Boolean,attribute:"with-label"})],LyraTimeInput.prototype,"withLabel",void 0),__decorate([property({type:Boolean,attribute:"with-now"})],LyraTimeInput.prototype,"withNow",void 0),__decorate([property({attribute:"error-text"})],LyraTimeInput.prototype,"errorText",void 0),__decorate([state()],LyraTimeInput.prototype,"activeSegment",void 0),__decorate([state()],LyraTimeInput.prototype,"touched",void 0),__decorate([state()],LyraTimeInput.prototype,"popupHidden",void 0),__decorate([state()],LyraTimeInput.prototype,"popupPositioned",void 0);export{LyraTimeInput};
|
|
132
|
+
`}}__decorate([property({reflect:!0})],LyraTimeInput.prototype,"appearance",void 0),__decorate([property()],LyraTimeInput.prototype,"autocomplete",void 0),__decorate([property({type:Number,reflect:!0})],LyraTimeInput.prototype,"distance",void 0),__decorate([property()],LyraTimeInput.prototype,"hint",void 0),__decorate([property({attribute:"hour-format",converter:hourFormatConverter,reflect:!0})],LyraTimeInput.prototype,"hourFormat",void 0),__decorate([property()],LyraTimeInput.prototype,"label",void 0),__decorate([property({attribute:"label-display",reflect:!0})],LyraTimeInput.prototype,"labelDisplay",void 0),__decorate([property({reflect:!0})],LyraTimeInput.prototype,"min",void 0),__decorate([property({reflect:!0})],LyraTimeInput.prototype,"max",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraTimeInput.prototype,"pill",void 0),__decorate([property({converter:placementConverter,reflect:!0})],LyraTimeInput.prototype,"placement",void 0),__decorate([property({reflect:!0})],LyraTimeInput.prototype,"size",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraTimeInput.prototype,"clearable",void 0),__decorate([property({type:Boolean,attribute:"with-clear"})],LyraTimeInput.prototype,"withClear",void 0),__decorate([property({type:Boolean,attribute:"with-hint"})],LyraTimeInput.prototype,"withHint",void 0),__decorate([property({type:Boolean,attribute:"with-label"})],LyraTimeInput.prototype,"withLabel",void 0),__decorate([property({type:Boolean,attribute:"with-now"})],LyraTimeInput.prototype,"withNow",void 0),__decorate([property({attribute:"error-text"})],LyraTimeInput.prototype,"errorText",void 0),__decorate([state()],LyraTimeInput.prototype,"activeSegment",void 0),__decorate([state()],LyraTimeInput.prototype,"touched",void 0),__decorate([state()],LyraTimeInput.prototype,"popupHidden",void 0),__decorate([state()],LyraTimeInput.prototype,"popupPositioned",void 0);export{LyraTimeInput};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{iconHitTarget,focusRing}from"../../../internal/interactive-control.styles.js";import{css}from"lit";import{compactContainerQuery}from"../../../internal/container-breakpoints.styles.js";import{glassSurface}from"../../../internal/glass-surface.styles.js";import{glassScrollLayerStyles}from"../../../internal/glass-scroll-layer.styles.js";import{glassIndependentRootStyles}from"../../../internal/glass-independent-root.styles.js";import{formControlAppearance,formControlFocusHalo,formControlRequiredMarker}from"../../../internal/form-control.styles.js";const styles=css` :host { display: block; container-type: inline-size; contain-intrinsic-inline-size: var(--lr-size-12rem); --_lr-time-input-border-color-default: var(--_lr-form-control-border-color); --_lr-time-input-fill-default: var(--_lr-form-control-fill); --_lr-time-input-color-default: var(--lr-color-text); --_lr-time-input-control-min-height-default: var(--lr-form-control-height); --_lr-form-control-focus-shadow: var(--lr-form-control-focus-shadow, none); } [part~='form-control-label'] { display: block; min-inline-size: 0; max-inline-size: 100%; margin-block-end: var(--lr-space-xs); font-size: var(--lr-font-size-md-sm); font-weight: var(--lr-font-weight-semibold); overflow-wrap: anywhere; } [part~='form-control-label'][hidden] { display: none; } ${formControlRequiredMarker} [part~='time-input'] { display: flex; align-items: center; box-sizing: border-box; inline-size: 100%; min-block-size: var( --lr-time-input-control-height, var( --lr-time-input-control-min-height, var(--_lr-time-input-control-min-height-default) ) ); block-size: var(--lr-time-input-control-height, auto); gap: var(--lr-time-input-gap, var(--lr-form-control-gap)); padding-inline: var(--lr-form-control-padding-inline); border: var(--lr-border-width-thin) solid var(--lr-time-input-border-color, var(--_lr-time-input-border-color-default)); border-radius: var(--lr-time-input-radius, var(--lr-form-control-radius)); background: var(--lr-time-input-fill, var(--_lr-time-input-fill-default)); color: var(--lr-time-input-color, var(--_lr-time-input-color-default)); font: inherit; font-size: var(--lr-form-control-font-size); } ${formControlAppearance} :host([pill]) [part~='time-input'] { border-radius: var(--lr-time-input-radius, var(--lr-radius-pill)); } :host([open]) [part~='time-input'], [part~='time-input']:focus-within { border-color: var(--lr-time-input-focus-border-color, var(--lr-color-brand)); ${formControlFocusHalo} } :host(:disabled) [part~='time-input'] { opacity: var(--lr-opacity-disabled); cursor: not-allowed; } [part='start'], [part='end'] { flex: 0 1 auto; display: inline-flex; align-items: center; min-inline-size: 0; max-inline-size: 50%; overflow: hidden; color: var(--lr-color-text-quiet); } [part='start'] slot, [part='end'] slot, [part='start'] slot::slotted(*), [part='end'] slot::slotted(*) { min-inline-size: 0; max-inline-size: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } [part='start'][hidden], [part='end'][hidden] { display: none; } [part='input'] { flex: 1 1 auto; display: inline-flex; align-items: baseline; min-inline-size: 0; outline: none; } [part='segment'] { display: inline-flex; justify-content: center; min-inline-size: var(--lr-size-2-5ch); padding-block: var(--lr-space-2xs); padding-inline: var(--lr-space-2xs); border-radius: var(--lr-radius-xs); color: inherit; cursor: text; font-variant-numeric: tabular-nums; user-select: none; } :host(:not(:disabled)) [part='segment']:hover { background: var(--lr-time-input-segment-hover-bg, var(--lr-color-brand-quiet)); } :host(:not(:disabled)) [part='segment']:active { background: var( --lr-time-input-segment-active-bg, color-mix( in oklab, var(--lr-time-input-segment-hover-bg, var(--lr-color-brand-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ) ); } [part='segment']:focus-visible { ${focusRing} background: var(--lr-time-input-segment-focus-bg, var(--lr-time-input-segment-hover-bg, var(--lr-color-brand-quiet))); } [part='segment'][data-empty] { color: var(--lr-time-input-placeholder-color, var(--lr-time-input-action-color, var(--lr-color-text-quiet))); } :host(:disabled) [part='segment'] { cursor: not-allowed; } [part='segment-literal'] { color: var(--lr-color-text-quiet); user-select: none; } [part='clear-button'], [part='expand-button'] { flex: 0 0 auto; display: inline-flex; align-items: center; justify-content: center; box-sizing: border-box; ${iconHitTarget} padding: var(--lr-space-2xs); border: none; border-radius: var(--lr-form-control-radius); background: transparent; color: var(--lr-time-input-action-color, var(--lr-color-text-quiet)); cursor: pointer; font: inherit; line-height: var(--lr-line-height-none); } [part='clear-button']:not(:disabled):hover, [part='expand-button']:not(:disabled):hover { color: var(--lr-time-input-action-hover-color, var(--lr-color-text)); background: var(--lr-time-input-action-hover-bg, var(--lr-color-brand-quiet)); } [part='clear-button']:not(:disabled):active, [part='expand-button']:not(:disabled):active { background: var( --lr-time-input-action-active-bg, color-mix( in oklab, var(--lr-time-input-action-hover-bg, var(--lr-color-brand-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ) ); } [part='clear-button']:focus-visible, [part='expand-button']:focus-visible { ${focusRing} } [part='clear-button']:disabled, [part='expand-button']:disabled { opacity: var(--lr-opacity-disabled); cursor: not-allowed; } [part='expand-icon'] { display: inline-flex; transform: rotate(90deg); transition: transform var(--lr-transition-fast); } :host([open]) [part='expand-icon'] { transform: rotate(-90deg); } [part='popup'][hidden] { display: none; } [part='popup'] { position: fixed; z-index: var(--lr-overlay-stack-index, var(--lr-layer-dropdown)); box-sizing: border-box; max-block-size: var(--lr-positioner-available-block-size); overflow: auto; padding: var(--lr-space-s); border: var(--lr-border-width-thin) solid var(--lr-overlay-border, var(--lr-color-border)); border-radius: var(--lr-overlay-radius, var(--lr-radius)); background: var(--lr-overlay-surface, var(--lr-color-surface-raised)); box-shadow: var(--lr-overlay-shadow-anchored, var(--lr-shadow-m)); color: var(--lr-color-text); opacity: 1; transform: translateY(0); visibility: visible; transition-property: opacity, transform, visibility; transition-duration: var(--_lr-motion-duration, var(--show-duration, var(--lr-duration-fast))); transition-timing-function: var(--lr-easing-standard); } [part='popup'][data-hidden] { opacity: 0; transform: translateY(var(--lr-size-neg-0-25rem)); visibility: hidden; pointer-events: none; transition-duration: var(--_lr-motion-duration, var(--hide-duration, var(--lr-duration-fast))); } [part='columns'] { display: flex; align-items: stretch; gap: var(--lr-space-xs); } [part='column'] { display: flex; flex-direction: column; inline-size: var(--column-width, calc(var(--lr-size-1em) * 3)); max-block-size: calc(var(--column-item-height, calc(var(--lr-size-1em) * 2.25)) * 6); overflow-block: auto; overflow-inline: hidden; overscroll-behavior: contain; scrollbar-width: var(--lr-theme-scrollbar-width, thin); scrollbar-gutter: var(--lr-theme-scrollbar-gutter, auto); } [part~='column-item'] { flex: 0 0 var(--column-item-height, calc(var(--lr-size-1em) * 2.25)); display: flex; align-items: center; justify-content: center; box-sizing: border-box; ${iconHitTarget} padding-inline: var(--lr-space-xs); border: none; border-radius: var(--lr-radius-xs); background: transparent; color: inherit; cursor: pointer; font: inherit; font-variant-numeric: tabular-nums; } :where([part~='column-item']):hover { background: var(--lr-time-input-column-hover-bg, var(--lr-color-brand-quiet)); } :where([part~='column-item']):active { background: var( --lr-time-input-column-active-bg, color-mix( in oklab, var(--lr-time-input-column-hover-bg, var(--lr-color-brand-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ) ); } :where([part~='column-item']):focus-visible { outline: var(--lr-focus-ring-width) solid var(--lr-focus-ring-color); outline-offset: calc(-1 * max(var(--lr-focus-ring-width), calc(var(--lr-focus-ring-width) + var(--lr-focus-ring-offset)))); } [part~='column-item-selected'] { background: var(--lr-time-input-column-selected-bg, var(--lr-color-brand)); color: var(--lr-time-input-column-selected-color, var(--lr-color-on-brand)); font-weight: var(--lr-time-input-column-selected-font-weight, var(--lr-font-weight-semibold)); } :where([part~='column-item-selected']):hover { background: var( --lr-time-input-column-selected-hover-bg, color-mix( in oklab, var(--lr-time-input-column-selected-bg, var(--lr-color-brand)), var(--lr-color-mix-partner) var(--lr-color-mix-hover) ) ); } :where([part~='column-item-selected']):active { background: var( --lr-time-input-column-selected-active-bg, color-mix( in oklab, var(--lr-time-input-column-selected-bg, var(--lr-color-brand)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ) ); } [part='now-button'] { inline-size: 100%; min-block-size: var(--lr-icon-button-size); margin-block-start: var(--lr-space-s); padding-block: var(--lr-space-xs); padding-inline: var(--lr-space-s); border: var(--lr-border-width-thin) solid var(--lr-color-border); border-radius: var(--lr-radius); background: transparent; color: inherit; cursor: pointer; font: inherit; } [part='now-button']:hover { background: var(--lr-time-input-action-hover-bg, var(--lr-color-brand-quiet)); } [part='now-button']:active { background: var( --lr-time-input-action-active-bg, color-mix( in oklab, var(--lr-time-input-action-hover-bg, var(--lr-color-brand-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ) ); } [part='now-button']:focus-visible { ${focusRing} } [part='hint'], [part='error'] { margin-block-start: var(--lr-space-xs); min-inline-size: 0; max-inline-size: 100%; font-size: var(--lr-font-size-sm); overflow-wrap: anywhere; } [part='hint'] { color: var(--lr-color-text-quiet); } [part='error'] { color: var(--lr-color-danger); } [part='hint'][hidden], [part='error'][hidden] { display: none; } @container ${compactContainerQuery} { [part='popup'] { max-inline-size: var(--lr-positioner-available-inline-size); } [part='columns'] { gap: var(--lr-space-2xs); } } @media (prefers-reduced-motion: reduce) { [part='popup'], [part='expand-icon'] { transition-duration: var(--_lr-motion-duration, var(--lr-duration-fast)); } } ${glassScrollLayerStyles} ${glassIndependentRootStyles} ${glassSurface('[part="popup"]',css`var(--lr-overlay-surface, var(--lr-color-surface-raised))`,void 0,!0)} `;export{styles};
|
|
1
|
+
import{iconHitTarget,focusRing}from"../../../internal/interactive-control.styles.js";import{css}from"lit";import{compactContainerQuery}from"../../../internal/container-breakpoints.styles.js";import{glassSurface}from"../../../internal/glass-surface.styles.js";import{glassScrollLayerStyles}from"../../../internal/glass-scroll-layer.styles.js";import{glassIndependentRootStyles}from"../../../internal/glass-independent-root.styles.js";import{formControlAppearance,formControlFocusHalo,formControlRequiredMarker,formControlLabelDisplay}from"../../../internal/form-control.styles.js";const styles=css` :host { display: block; container-type: inline-size; contain-intrinsic-inline-size: var(--lr-size-12rem); --_lr-time-input-border-color-default: var(--_lr-form-control-border-color); --_lr-time-input-fill-default: var(--_lr-form-control-fill); --_lr-time-input-color-default: var(--lr-color-text); --_lr-time-input-control-min-height-default: var(--lr-form-control-height); --_lr-form-control-focus-shadow: var(--lr-form-control-focus-shadow, none); } [part~='form-control-label'] { display: block; min-inline-size: 0; max-inline-size: 100%; margin-block-end: var(--lr-space-xs); font-size: var(--lr-font-size-md-sm); font-weight: var(--lr-font-weight-semibold); overflow-wrap: anywhere; } [part~='form-control-label'][hidden] { display: none; } ${formControlRequiredMarker} ${formControlLabelDisplay} [part~='time-input'] { display: flex; align-items: center; box-sizing: border-box; inline-size: 100%; min-block-size: var( --lr-time-input-control-height, var( --lr-time-input-control-min-height, var(--_lr-time-input-control-min-height-default) ) ); block-size: var(--lr-time-input-control-height, auto); gap: var(--lr-time-input-gap, var(--lr-form-control-gap)); padding-inline: var(--lr-form-control-padding-inline); border: var(--lr-border-width-thin) solid var(--lr-time-input-border-color, var(--_lr-time-input-border-color-default)); border-radius: var(--lr-time-input-radius, var(--lr-form-control-radius)); background: var(--lr-time-input-fill, var(--_lr-time-input-fill-default)); color: var(--lr-time-input-color, var(--_lr-time-input-color-default)); font: inherit; font-size: var(--lr-form-control-font-size); } ${formControlAppearance} :host([pill]) [part~='time-input'] { border-radius: var(--lr-time-input-radius, var(--lr-radius-pill)); } :host([open]) [part~='time-input'], [part~='time-input']:focus-within { border-color: var(--lr-time-input-focus-border-color, var(--lr-color-brand)); ${formControlFocusHalo} } :host(:disabled) [part~='time-input'] { opacity: var(--lr-opacity-disabled); cursor: not-allowed; } [part='start'], [part='end'] { flex: 0 1 auto; display: inline-flex; align-items: center; min-inline-size: 0; max-inline-size: 50%; overflow: hidden; color: var(--lr-color-text-quiet); } [part='start'] slot, [part='end'] slot, [part='start'] slot::slotted(*), [part='end'] slot::slotted(*) { min-inline-size: 0; max-inline-size: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } [part='start'][hidden], [part='end'][hidden] { display: none; } [part='input'] { flex: 1 1 auto; display: inline-flex; align-items: baseline; min-inline-size: 0; outline: none; } [part='segment'] { display: inline-flex; justify-content: center; min-inline-size: var(--lr-size-2-5ch); padding-block: var(--lr-space-2xs); padding-inline: var(--lr-space-2xs); border-radius: var(--lr-radius-xs); color: inherit; cursor: text; font-variant-numeric: tabular-nums; user-select: none; } :host(:not(:disabled)) [part='segment']:hover { background: var(--lr-time-input-segment-hover-bg, var(--lr-color-brand-quiet)); } :host(:not(:disabled)) [part='segment']:active { background: var( --lr-time-input-segment-active-bg, color-mix( in oklab, var(--lr-time-input-segment-hover-bg, var(--lr-color-brand-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ) ); } [part='segment']:focus-visible { ${focusRing} background: var(--lr-time-input-segment-focus-bg, var(--lr-time-input-segment-hover-bg, var(--lr-color-brand-quiet))); } [part='segment'][data-empty] { color: var(--lr-time-input-placeholder-color, var(--lr-time-input-action-color, var(--lr-color-text-quiet))); } :host(:disabled) [part='segment'] { cursor: not-allowed; } [part='segment-literal'] { color: var(--lr-color-text-quiet); user-select: none; } [part='clear-button'], [part='expand-button'] { flex: 0 0 auto; display: inline-flex; align-items: center; justify-content: center; box-sizing: border-box; ${iconHitTarget} padding: var(--lr-space-2xs); border: none; border-radius: var(--lr-form-control-radius); background: transparent; color: var(--lr-time-input-action-color, var(--lr-color-text-quiet)); cursor: pointer; font: inherit; line-height: var(--lr-line-height-none); } [part='clear-button']:not(:disabled):hover, [part='expand-button']:not(:disabled):hover { color: var(--lr-time-input-action-hover-color, var(--lr-color-text)); background: var(--lr-time-input-action-hover-bg, var(--lr-color-brand-quiet)); } [part='clear-button']:not(:disabled):active, [part='expand-button']:not(:disabled):active { background: var( --lr-time-input-action-active-bg, color-mix( in oklab, var(--lr-time-input-action-hover-bg, var(--lr-color-brand-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ) ); } [part='clear-button']:focus-visible, [part='expand-button']:focus-visible { ${focusRing} } [part='clear-button']:disabled, [part='expand-button']:disabled { opacity: var(--lr-opacity-disabled); cursor: not-allowed; } [part='expand-icon'] { display: inline-flex; transform: rotate(90deg); transition: transform var(--lr-transition-fast); } :host([open]) [part='expand-icon'] { transform: rotate(-90deg); } [part='popup'][hidden] { display: none; } [part='popup'] { position: fixed; z-index: var(--lr-overlay-stack-index, var(--lr-layer-dropdown)); box-sizing: border-box; max-block-size: var(--lr-positioner-available-block-size); overflow: auto; padding: var(--lr-space-s); border: var(--lr-border-width-thin) solid var(--lr-overlay-border, var(--lr-color-border)); border-radius: var(--lr-overlay-radius, var(--lr-radius)); background: var(--lr-overlay-surface, var(--lr-color-surface-raised)); box-shadow: var(--lr-overlay-shadow-anchored, var(--lr-shadow-m)); color: var(--lr-color-text); opacity: 1; transform: translateY(0); visibility: visible; transition-property: opacity, transform, visibility; transition-duration: var(--_lr-motion-duration, var(--show-duration, var(--lr-duration-fast))); transition-timing-function: var(--lr-easing-standard); } [part='popup'][data-hidden] { opacity: 0; transform: translateY(var(--lr-size-neg-0-25rem)); visibility: hidden; pointer-events: none; transition-duration: var(--_lr-motion-duration, var(--hide-duration, var(--lr-duration-fast))); } [part='columns'] { display: flex; align-items: stretch; gap: var(--lr-space-xs); } [part='column'] { display: flex; flex-direction: column; inline-size: var(--column-width, calc(var(--lr-size-1em) * 3)); max-block-size: calc(var(--column-item-height, calc(var(--lr-size-1em) * 2.25)) * 6); overflow-block: auto; overflow-inline: hidden; overscroll-behavior: contain; scrollbar-width: var(--lr-theme-scrollbar-width, thin); scrollbar-gutter: var(--lr-theme-scrollbar-gutter, auto); } [part~='column-item'] { flex: 0 0 var(--column-item-height, calc(var(--lr-size-1em) * 2.25)); display: flex; align-items: center; justify-content: center; box-sizing: border-box; ${iconHitTarget} padding-inline: var(--lr-space-xs); border: none; border-radius: var(--lr-radius-xs); background: transparent; color: inherit; cursor: pointer; font: inherit; font-variant-numeric: tabular-nums; } :where([part~='column-item']):hover { background: var(--lr-time-input-column-hover-bg, var(--lr-color-brand-quiet)); } :where([part~='column-item']):active { background: var( --lr-time-input-column-active-bg, color-mix( in oklab, var(--lr-time-input-column-hover-bg, var(--lr-color-brand-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ) ); } :where([part~='column-item']):focus-visible { outline: var(--lr-focus-ring-width) solid var(--lr-focus-ring-color); outline-offset: calc(-1 * max(var(--lr-focus-ring-width), calc(var(--lr-focus-ring-width) + var(--lr-focus-ring-offset)))); } [part~='column-item-selected'] { background: var(--lr-time-input-column-selected-bg, var(--lr-color-brand)); color: var(--lr-time-input-column-selected-color, var(--lr-color-on-brand)); font-weight: var(--lr-time-input-column-selected-font-weight, var(--lr-font-weight-semibold)); } :where([part~='column-item-selected']):hover { background: var( --lr-time-input-column-selected-hover-bg, color-mix( in oklab, var(--lr-time-input-column-selected-bg, var(--lr-color-brand)), var(--lr-color-mix-partner) var(--lr-color-mix-hover) ) ); } :where([part~='column-item-selected']):active { background: var( --lr-time-input-column-selected-active-bg, color-mix( in oklab, var(--lr-time-input-column-selected-bg, var(--lr-color-brand)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ) ); } [part='now-button'] { inline-size: 100%; min-block-size: var(--lr-icon-button-size); margin-block-start: var(--lr-space-s); padding-block: var(--lr-space-xs); padding-inline: var(--lr-space-s); border: var(--lr-border-width-thin) solid var(--lr-color-border); border-radius: var(--lr-radius); background: transparent; color: inherit; cursor: pointer; font: inherit; } [part='now-button']:hover { background: var(--lr-time-input-action-hover-bg, var(--lr-color-brand-quiet)); } [part='now-button']:active { background: var( --lr-time-input-action-active-bg, color-mix( in oklab, var(--lr-time-input-action-hover-bg, var(--lr-color-brand-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ) ); } [part='now-button']:focus-visible { ${focusRing} } [part='hint'], [part='error'] { margin-block-start: var(--lr-space-xs); min-inline-size: 0; max-inline-size: 100%; font-size: var(--lr-font-size-sm); overflow-wrap: anywhere; } [part='hint'] { color: var(--lr-color-text-quiet); } [part='error'] { color: var(--lr-color-danger); } [part='hint'][hidden], [part='error'][hidden] { display: none; } @container ${compactContainerQuery} { [part='popup'] { max-inline-size: var(--lr-positioner-available-inline-size); } [part='columns'] { gap: var(--lr-space-2xs); } } @media (prefers-reduced-motion: reduce) { [part='popup'], [part='expand-icon'] { transition-duration: var(--_lr-motion-duration, var(--lr-duration-fast)); } } ${glassScrollLayerStyles} ${glassIndependentRootStyles} ${glassSurface('[part="popup"]',css`var(--lr-overlay-surface, var(--lr-color-surface-raised))`,void 0,!0)} `;export{styles};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import type{LyraLocaleLoader}from'../../../internal/locale-loader.js';import{type TemplateResult,type PropertyValues}from'lit';import{LyraFormControlElement}from'../../../internal/form-control-element.js';import type{LyraLocaleDirection}from'../../../internal/localization.js';import type{LyraSize}from'../../../internal/variants.js';import{type FormOwnerValue}from'../../../internal/form-associated.js';
|
|
1
|
+
import type{LyraLocaleLoader}from'../../../internal/locale-loader.js';import{type TemplateResult,type PropertyValues}from'lit';import{LyraFormControlElement}from'../../../internal/form-control-element.js';import type{LyraLocaleDirection}from'../../../internal/localization.js';import type{LyraSize,LyraLabelDisplay}from'../../../internal/variants.js';import{type FormOwnerValue}from'../../../internal/form-associated.js';
|
|
2
2
|
/** One offered locale row. `label` overrides the derived `localeNativeName(tag)` endonym when
|
|
3
|
-
* given -- e.g. offering a locale before its strings are registered ("Français (bientôt)")
|
|
3
|
+
* given -- e.g. offering a locale before its strings are registered ("Français (bientôt)"), or
|
|
4
|
+
* supplying names the host already has so the row never resolves one through `Intl`.
|
|
4
5
|
* `country` overrides the row's derived flag country when given -- e.g. showing Lebanon's flag
|
|
5
6
|
* for an `'ar'` row instead of the library's default Saudi Arabia mapping. */
|
|
6
7
|
export interface LyraLocaleEntry{
|
|
@@ -36,6 +37,13 @@ export interface LyraLocaleChangeDetail{value:string;previousValue:string;direct
|
|
|
36
37
|
* overrides the auto-discovered list entirely: a curated subset, a custom order, custom labels,
|
|
37
38
|
* or a locale the host wants to offer before its strings are registered.
|
|
38
39
|
*
|
|
40
|
+
* Derived endonyms resolve on demand, never all at once while closed: the closed trigger resolves
|
|
41
|
+
* only the locale it shows, and every other row resolves when the listbox opens, when closed
|
|
42
|
+
* typeahead or the search filter needs it, then stays cached until `locales` or the registry
|
|
43
|
+
* changes. A row with a non-blank `label` never resolves an endonym for display, so a catalog of
|
|
44
|
+
* labelled `{ tag, label }` rows renders its closed trigger without constructing any
|
|
45
|
+
* `Intl.DisplayNames`. Row order is always the catalog's own order; names never sort it.
|
|
46
|
+
*
|
|
39
47
|
* `value` is the *committed* selection (form-submitted, drives `lr-change`) and starts `''`.
|
|
40
48
|
* While unset, the trigger displays `effectiveLocale` (the same ancestor-`lang`/registry
|
|
41
49
|
* resolution every other component already uses) as a live preview — but that preview is never a
|
|
@@ -240,7 +248,14 @@ spellcheck:boolean;
|
|
|
240
248
|
autocapitalize:string;private autocorrectValue;
|
|
241
249
|
/** Native filter autocorrection. HTML accepts on/off; omission defaults to true.
|
|
242
250
|
* @default true */
|
|
243
|
-
get autocorrect():boolean;set autocorrect(next:boolean);label:string;
|
|
251
|
+
get autocorrect():boolean;set autocorrect(next:boolean);label:string;
|
|
252
|
+
/**
|
|
253
|
+
* Whether the `label` renders on screen. `hidden` keeps the label as the accessible name but
|
|
254
|
+
* removes it visually (compact toolbars, table cells); hint, error and required semantics are
|
|
255
|
+
* unaffected. Reflected so styles and `[label-display]` selectors match.
|
|
256
|
+
* @attr label-display
|
|
257
|
+
*/
|
|
258
|
+
labelDisplay:LyraLabelDisplay;hint:string;errorText:string;
|
|
244
259
|
/** Whether the option popup is open. Disabled controls reject direct reopen attempts, including
|
|
245
260
|
* the synchronous fieldset cascade before `formDisabledCallback()` runs. */
|
|
246
261
|
get open():boolean;set open(next:boolean);
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{guard}from"lit/directives/guard.js";import{emitValueEvents}from"../../../internal/value-events.js";import{renderFormControlHintError}from"../../../internal/form-control-template.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{FormControlController,reflectFormName}from"../../../internal/form-control-controller.js";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{acquireNativeControlDescription}from"../../../internal/native-control-description.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{deferredPlaceReady as place,waitForDeferredPlacement,syncTopLayerRelease,topLayerPlacement}from"../../../internal/anchored-overlay-runtime.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{hostAriaLabel,nextId,srOnly}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{TypeAheadBuffer}from"../../../internal/type-ahead-buffer.js";import{resolveListMove}from"../../../internal/list-navigation.js";import{getDisplayNames,resolveIntlLocale}from"../../../internal/intl-cache.js";import{activeElementIn,shadowFocusTarget}from"../../../internal/active-element.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{getLyraLocale,getLyraLocaleDirection,getRegisteredLyraLocales,subscribeLyraLocaleRegistry,setLyraLocale}from"../../../internal/localization-runtime.js";import{localeNativeName}from"../../media/flag/language-map.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./locale-picker.styles.js";import{autocorrectConverter,declaredDefaultConverter,spellcheckConverter}from"../../../internal/converters.js";import{getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{PopupController,emitPopupEvent}from"../../../internal/popup-controller.js";import{revealRow}from"../../../internal/reveal-row.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{LYRA_DEFAULT_localePickerEmpty,LYRA_DEFAULT_localePickerInputLimit,LYRA_DEFAULT_localePickerLabel,LYRA_DEFAULT_localePickerRequired,LYRA_DEFAULT_localePickerSearchLabel}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_loading,LYRA_DEFAULT_retry,LYRA_DEFAULT_statusError}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();const MAX_LOCALE_ENTRIES=512,localeSpellcheckConverter={...spellcheckConverter,fromAttribute:(value,type)=>value===null?void 0:spellcheckConverter.fromAttribute?.(value,type)};function snapshotLocaleCatalog(source){if(!Array.isArray(source))return Object.freeze([]);const rows=[];for(let index=0;index<Math.min(source.length,MAX_LOCALE_ENTRIES);index+=1)try{const raw=source[index];if(typeof raw=="string"){raw.length>0&&rows.push(raw);continue}if(raw===null||typeof raw!="object")continue;const candidate=raw,tag=candidate.tag,label=candidate.label,country=candidate.country;if(typeof tag!="string"||tag.length===0||label!==void 0&&typeof label!="string"||country!==void 0&&typeof country!="string")continue;rows.push(Object.freeze({tag,...label===void 0?{}:{label},...country===void 0?{}:{country}}))}catch{}return Object.freeze(rows)}class LyraLocalePicker extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,loading:LYRA_DEFAULT_loading,localePickerEmpty:LYRA_DEFAULT_localePickerEmpty,localePickerInputLimit:LYRA_DEFAULT_localePickerInputLimit,localePickerLabel:LYRA_DEFAULT_localePickerLabel,localePickerRequired:LYRA_DEFAULT_localePickerRequired,localePickerSearchLabel:LYRA_DEFAULT_localePickerSearchLabel,retry:LYRA_DEFAULT_retry,statusError:LYRA_DEFAULT_statusError}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:"value",reflect:!0,useDefault:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0}}}get localeLoader(){return this._localeLoader}set localeLoader(next){const previous=this._localeLoader;previous!==next&&(this.cancelLocaleLoad(),this._localeLoader=next,this.requestUpdate("localeLoader",previous))}get locales(){return this._locales}set locales(next){this.cancelLocaleLoad();const previous=this._locales;this.inputLimited=Array.isArray(next)&&next.length>MAX_LOCALE_ENTRIES,this._locales=next===void 0?void 0:snapshotLocaleCatalog(next),this.requestUpdate("locales",previous)}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=!!next,this.requestUpdate()}get open(){return this._open}set open(next){const old=this._open,liveDisabled=this.effectiveDisabled||typeof this.matches=="function"&&this.matches(":disabled");if(this._open=!!next&&!liveDisabled,this._open===old){next&&!this._open&&this.hasAttribute("open")&&this.removeAttribute("open");return}this.openGeneration++,this.requestUpdate("open",old)}constructor(){super(),this.withoutFlags=!1,this.topLayer=!1,this.triggerDisplay="flag-label",this.optionDisplay="label-tag",this.searchable=!1,this.autocomplete="off",this.inputMode="",this.enterKeyHint="",this.spellcheck=!1,this.autocapitalize="",this.autocorrectValue=!0,this.label="",this.hint="",this.errorText="",this.size="m",this.activeIndex=-1,this.searchQuery="",this.touched=!1,this.slotPresence=new SlotPresenceController(this),this.registryTick=0,this.searchFocusGeneration=0,this.listId=nextId("locale-picker-list"),this.controlId=nextId("locale-picker-control"),this.listboxHidden=!0,this.openGeneration=0,this.openVetoed=!1,this.lifecycleMounted=!1,this.lastRenderedOpen=!1,this.announcingHide=!1,this.restoreFocusOnClose=!1,this.popupController=new PopupController({host:this,popup:()=>this.renderRoot.querySelector('[part="listbox"]'),emit:(name,cancelable)=>emitPopupEvent(this,name,cancelable),onPointer:event=>this.onDocPointer(event)}),this._value="",this._open=!1,this._fieldsetDisabled=!1,this._name="",this._disabled=!1,this._required=!1,this._defaultValue="",this._valueDirty=!1,this.settingDefaultValue=!1,this.reflectingDefaultValue=!1,this.typeBuffer=new TypeAheadBuffer(this),this.activeScrollGeneration=0,this.localizedValidityLocale="",this.localizedIntrinsicMessage="",this.localDescriptionIds="",this.markInteracted=()=>{this.touched||(this.touched=!0,this.syncCustomStates())},this.onDocPointer=e=>{if(!e.composedPath().includes(this)){if(this.overlayHandle?.isActive()){this.overlayHandle.dismissBackdrop();return}this.hide()}},this.inputLimited=!1,this.limitAnnouncements=new AnnouncementSinkController(this),this.limitMounted=!1,this.commitDispatching=!1,this.valueWriteVersion=0,this.loadGeneration=0,this.retryLocaleLoad=()=>{const restoreFocus=shadowFocusTarget(this)?.getAttribute("part")==="load-retry";this.loadFailureTag!==void 0&&this.commit(this.loadFailureTag),restoreFocus&&this.loadFailureTag===void 0&&this.isConnected&&shadowFocusTarget(this)?.getAttribute("part")==="load-retry"&&this.focus()},this.onTriggerClick=()=>{this.liveDisabled||(this.open?this.hide():this.show())},this.onTriggerBlur=event=>{if(this.isSearchFocusTransfer(event)){event.stopPropagation();return}this.liveDisabled||(this.touched=!0),this.syncCustomStates(),this.hide(),relayNativeEvent(this,event)},this.onTriggerFocus=event=>{if(this.isSearchFocusTransfer(event)){event.stopPropagation();return}if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onSearchInput=event=>{event.stopPropagation(),!(!this.searchable||!this.open||this.liveDisabled)&&(this.searchQuery=event.currentTarget.value,this.setActiveIndex(this.visibleEntries.length?0:-1))},this.onSearchChange=event=>{event.stopPropagation()},this.onSearchKeyDown=event=>{if(this.liveDisabled||!this.open||event.isComposing||event.keyCode===229)return;const rows=this.visibleEntries;if(event.key==="ArrowDown"||event.key==="ArrowUp")event.preventDefault(),this.setActiveIndex(event.key==="ArrowDown"?Math.min(rows.length-1,this.activeIndex+1):Math.max(0,this.activeIndex-1));else if(event.key==="Enter"){event.preventDefault();const row=rows[this.activeIndex];row&&this.commit(row.tag)}else event.key==="Escape"&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(event.preventDefault(),this.dismissFromEscape())},this.onKeyDown=e=>{if(this.liveDisabled||e.isComposing||e.keyCode===229)return;const rows=this.visibleEntries,move=()=>resolveListMove(e,{count:rows.length,current:this.activeIndex,orientation:"vertical",wrap:!1,clamp:!0,backwardFromMissing:"first"});switch(e.key){case"ArrowDown":if(e.preventDefault(),!this.open)return this.show();this.setActiveIndex(move()??-1),this.queueSearchFocus();break;case"ArrowUp":if(e.preventDefault(),!this.open)return this.show();this.setActiveIndex(move()??-1),this.queueSearchFocus();break;case"Enter":case" ":if(this.open){e.preventDefault();const activeRow=rows[this.activeIndex];this.activeIndex>=0&&activeRow?this.commit(activeRow.tag):this.hide()}break;case"Escape":this.open&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(e.preventDefault(),this.dismissFromEscape());break;case"Home":this.open&&(e.preventDefault(),this.setActiveIndex(move()??-1));break;case"End":this.open&&(e.preventDefault(),this.setActiveIndex(move()??-1));break;default:this.typeBuffer.accepts(e)&&(this.searchable?(e.preventDefault(),this.show(),this.searchQuery+=e.key,this.setActiveIndex(this.visibleEntries.length?0:-1),this.queueSearchFocus()):this.typeAhead(e.key));break}},this.onListboxMouseDown=e=>{e.composedPath()[0]!==this.searchElement&&e.preventDefault()},this.onListboxClick=e=>{if(this.liveDisabled)return;const tag=e.target.closest('[part="option"]')?.dataset.value;tag!==void 0&&this.commit(tag)},this.validityController=new FormControlController(this,{invalid:init=>this.emit("lr-invalid",null,init),interacted:this.markInteracted,customError:()=>this.validityController.customValidityMessage}),this.internals=this.validityController.formInternals,new GlassScrollLayer(this,'[part="listbox"]',()=>this.open),this.internals.setFormValue("")}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}focus(options){this.liveDisabled||this.triggerElement?.focus(options)}blur(){this.searchElement&&shadowFocusTarget(this)===this.searchElement?this.searchElement.blur():this.triggerElement?.blur()}click(){this.liveDisabled||this.triggerElement?.click()}get input(){return this.searchable?this.searchElement??null:null}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"]')??null}syncExternalDescription(){if(!this.isConnected)return;const target=this.triggerElement??null;target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireNativeControlDescription(this,target,()=>this.localDescriptionIds))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.syncLocaleAttributeForLocalization(),this.updateValidity(),this.stopRegistrySubscription=subscribeLyraLocaleRegistry(()=>{this.registryTick+=1}),this.hasUpdated&&this.open&&queueMicrotask(()=>this.syncPopup())}disconnectedCallback(){this.popupController.cancel(),(this.open||this.lastRenderedOpen)&&this.hasUpdated&&!this.announcingHide&&emitPopupEvent(this,"lr-hide",!1),this.lastRenderedOpen=!1,this.clearSearch(),this.cancelLocaleLoad(),this.loadAnnouncements?.release(),this.loadAnnouncements=void 0,this.listboxHidden=!0,this.releaseExternalDescription(),super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.deactivatePopupOverlay(!1),this.stopRegistrySubscription?.(),this.stopRegistrySubscription=void 0,this.typeBuffer.clear(),this.activeScrollGeneration+=1,this.open=!1,this.suppressedOpenGeneration=this.openGeneration}adoptedCallback(){this.popupController.cancel(),this.clearSearch(),this.cancelLocaleLoad(),this.loadAnnouncements?.release(),this.loadAnnouncements=void 0,super.adoptedCallback(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription(),this.cleanup?.(),this.cleanup=void 0,this.popupController.unbindPointer(),this.overlayHandle?.suspend(),this.typeBuffer.clear(),this.open&&queueMicrotask(()=>this.syncPopup())}willUpdate(changed){super.willUpdate(changed),changed.has("locale")&&this.syncLocaleAttributeForLocalization(),this.hasUpdated&&this.refreshLocalizedIntrinsicValidity(changed),changed.has("searchable")&&!this.searchable&&(this.clearSearch(),this.searchElement&&shadowFocusTarget(this)===this.searchElement&&this.focus()),this.announceOpenTransition(changed),!this.openVetoed&&changed.has("open")&&!this.open&&(this.activeIndex=-1,this.clearSearch()),!this.openVetoed&&changed.has("open")&&this.open&&this.setActiveIndex(this.visibleEntries.findIndex(row=>row.tag===this._value)),this.open&&(this.searchable||changed.has("locales")||changed.has("registryTick"))&&this.activeIndex>=0&&(this.activeIndex=Math.min(this.activeIndex,this.visibleEntries.length-1),this.queueActiveScroll()),this.open&&(this.listboxHidden=!1)}get value(){return this._value}set value(next){this.cancelLocaleLoad(),this.valueWriteVersion++;const old=this._value;this.settingDefaultValue||(this._valueDirty=!0),this._value=next??"",this.internals.setFormValue(this._value),this.updateValidity(),this.requestUpdate("value",old)}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next??"",this.reflectingDefaultValue=!0;try{this._defaultValue?this.setAttribute("value",this._defaultValue):this.removeAttribute("value")}finally{this.reflectingDefaultValue=!1}this._valueDirty||this.restoreLiveValueFromDefault(),this.requestUpdate("defaultValue",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",reflectFormName(this,this._name),this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){next&&this.cancelLocaleLoad();const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this._disabled&&this.hide(),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}updateValidity(){this.localizedValidityLocale=this.effectiveMessageLocale;const valueMissing=this.hasMissingRequiredValue(),message=valueMissing?this.localize("localePickerRequired"):"";this.localizedIntrinsicMessage=message,valueMissing?this.validityController.setValidity({valueMissing:!0},message):this.validityController.setValidity({}),this.syncCustomStates()}refreshLocalizedIntrinsicValidity(changed){const locale=this.effectiveMessageLocale,message=this.hasMissingRequiredValue()?this.localize("localePickerRequired"):"";(changed.has("strings")||locale!==this.localizedValidityLocale||message!==this.localizedIntrinsicMessage)&&this.updateValidity()}hasMissingRequiredValue(){return!this.isBarred()&&this.required&&!this._value}syncLocaleAttributeForLocalization(){this.locale?this.getAttribute("locale")!==this.locale&&this.setAttribute("locale",this.locale):this.hasAttribute("locale")&&this.removeAttribute("locale")}isBarred(){return isBarredFromValidation(this,this.internals)}syncCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.isBarred()})}formResetCallback(){this.touched=!1,this.clearSearch(),this.restoreLiveValueFromDefault()}restoreLiveValueFromDefault(){this.settingDefaultValue=!0;try{this.value=this._defaultValue}finally{this.settingDefaultValue=!1}this._valueDirty=!1}formStateRestoreCallback(state2,_mode){this.value=typeof state2=="string"?state2:""}formDisabledCallback(disabled){this.validityController?.reflectingDisabled||(disabled&&this.cancelLocaleLoad(),this._fieldsetDisabled=disabled,disabled&&this.hide(),this.updateValidity(),this.requestUpdate())}checkValidity(){return this.validityController.checkValidity()}reportValidity(){return this.validityController.syncConstraints(),this.touched=!0,this.syncCustomStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncCustomStates(),this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),this.requestUpdate()}get normalizedEntries(){const raw=this.locales,cached=this.entriesCache;if(cached&&cached.raw===raw&&cached.tick===this.registryTick)return cached.rows;const rows=raw!==void 0?raw.map(entry=>typeof entry=="string"?{tag:entry,label:localeNativeName(entry)}:{tag:entry.tag,label:entry.label!==void 0&&entry.label.trim().length>0?entry.label:localeNativeName(entry.tag),country:entry.country}):getRegisteredLyraLocales().map(tag=>({tag,label:localeNativeName(tag)}));return this.entriesCache={raw,tick:this.registryTick,rows},rows}normalizeSearch(text,locale){return text.toLocaleLowerCase(resolveIntlLocale(locale)).normalize("NFKD").replace(/\p{M}/gu,"").trim()}get visibleEntries(){const rows=this.normalizedEntries;if(!this.searchable)return rows;const locale=this.effectiveLocale,query2=this.normalizeSearch(this.searchQuery,locale);if(!query2)return rows;const cached=this.visibleCache;if(cached&&cached.rows===rows&&cached.query===this.searchQuery&&cached.locale===locale)return cached.result;let keys=this.searchKeys;if(!keys||keys.rows!==rows||keys.locale!==locale){let names,englishNames;try{names=getDisplayNames(locale,{type:"language"})}catch{}try{englishNames=getDisplayNames("en",{type:"language"})}catch{}keys={rows,locale,values:rows.map(row=>{let localizedName="",englishName="";try{localizedName=names?.of(row.tag)??""}catch{}try{englishName=englishNames?.of(row.tag)??""}catch{}return{local:[row.label,localeNativeName(row.tag),localizedName].map(text=>this.normalizeSearch(text,locale)),invariant:[row.tag,englishName].map(text=>this.normalizeSearch(text,"en"))}})},this.searchKeys=keys}const invariantQuery=this.normalizeSearch(this.searchQuery,"en"),result=rows.filter((_,index)=>keys.values[index].local.some(text=>text.includes(query2))||keys.values[index].invariant.some(text=>text.includes(invariantQuery)));return this.visibleCache={rows,query:this.searchQuery,locale,result},result}clearSearch(){this.searchQuery="",this.searchFocusGeneration++,this.searchAnnouncements?.release(),this.searchAnnouncements=void 0}queueSearchFocus(){if(!this.searchable||!this.open||this.liveDisabled)return;const generation=++this.searchFocusGeneration,ownerDocument=this.ownerDocument,outerFocus=activeElementIn(ownerDocument),innerFocus=shadowFocusTarget(this);this.updateComplete.then(()=>{generation!==this.searchFocusGeneration||!this.isConnected||!this.open||!this.searchable||this.liveDisabled||this.ownerDocument!==ownerDocument||activeElementIn(ownerDocument)!==outerFocus||shadowFocusTarget(this)!==innerFocus||this.searchElement?.focus()})}get previewTag(){return this._value||this.effectiveLocale}entryFor(tag){const rows=this.normalizedEntries;if(this.entryIndex?.rows!==rows){const byTag=new Map;for(const row of rows)byTag.has(row.tag)||byTag.set(row.tag,row);this.entryIndex={rows,byTag}}return this.entryIndex.byTag.get(tag)}labelFor(tag){return this.entryFor(tag)?.label??localeNativeName(tag)}show(){this.open||this.liveDisabled||(this.open=!0,this.queueSearchFocus())}hide(){this.open&&(this.open=!1)}dismissFromEscape(){if(this.open){if(this.searchable&&this.searchQuery.length){this.clearSearch(),this.setActiveIndex(this.visibleEntries.length?0:-1);return}this.restoreFocusOnClose=!0,this.hide()}}activatePopupOverlay(){if(this.overlayHandle?.isActive()){this.overlayHandle.resume();return}this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="listbox"]'),onEscape:()=>this.dismissFromEscape(),onBackdrop:()=>this.hide(),restoreFocusTo:()=>this.renderRoot.querySelector('[part="trigger"]')})}deactivatePopupOverlay(restoreFocus){const overlay=this.overlayHandle;this.overlayHandle=void 0,overlay?.deactivate({restoreFocus}),this.popupController.unbindPointer()}syncPopup(){if(this.cleanup?.(),this.cleanup=void 0,!this.open||!this.isConnected){this.deactivatePopupOverlay(this.isConnected&&this.restoreFocusOnClose),this.restoreFocusOnClose=!1;return}this.activatePopupOverlay(),this.popupController.bindPointer();const anchor=this.renderRoot.querySelector(this.loadFailureTag!==void 0?'[part="form-control"]':'[part="trigger"]'),listbox=this.renderRoot.querySelector('[part="listbox"]');anchor&&listbox&&(this.placedTopLayer=syncTopLayerRelease(listbox,this.placedTopLayer,this.topLayer),this.cleanup=place(anchor,listbox,topLayerPlacement(this.topLayer,resolveEffectivePositioningStrategy(this,void 0,"fixed"))))}announceOpenTransition(changed){if(this.openVetoed=!1,this.openTransition=void 0,!changed.has("open")||!this.lifecycleMounted||!this.isConnected||this.suppressedOpenGeneration===this.openGeneration||changed.get("open")===this.open)return;const opening=this.open,generation=this.openGeneration;this.announcingHide=!opening;try{!opening&&this.liveDisabled?emitPopupEvent(this,"lr-hide",!1):this.openVetoed=this.popupController.announce(opening,()=>{this.isConnected&&this.openGeneration===generation&&(opening||!this.liveDisabled)&&(this._open=!opening)})}finally{this.announcingHide=!1}if(!this.isConnected||generation!==this.openGeneration||opening!==this.open){this.openVetoed=this.open===changed.get("open");return}this.openVetoed&&this.liveDisabled&&!this.open&&(this.openVetoed=!1),this.openVetoed||(this.popupController.cancel(),this.openTransition=opening)}updated(changed){super.updated(changed),this.limitMounted&&changed.has("inputLimited")&&this.inputLimited&&this.limitAnnouncements.announcePolite(this.localize("localePickerInputLimit")),this.limitMounted=!0,this.syncExternalDescription();const activeId=this.open&&this.activeIndex>=0?`${this.listId}-opt-${this.activeIndex}`:"",previous=this.renderRoot.querySelector('[part="option"][data-active]');previous?.id!==activeId&&previous?.removeAttribute("data-active"),activeId&&this.renderRoot.querySelector(`[id="${activeId}"]`)?.setAttribute("data-active",""),(changed.has("open")&&!this.openVetoed||this.open&&(changed.has("locales")||changed.has("registryTick")||changed.has("locale")||changed.has("searchQuery")||changed.has("searchable")||changed.has("loadFailureTag")||changed.has("topLayer")))&&this.syncPopup(),this.openTransition!==void 0&&this.isConnected&&this.popupController.settle(this.openTransition?"lr-after-show":"lr-after-hide",{waitForPosition:()=>waitForDeferredPlacement(()=>this.cleanup),conceal:()=>{this.listboxHidden=!0}}),this.openVetoed&&(this.restoreFocusOnClose=!1),this.lastRenderedOpen=this.open&&this.isConnected,this.lifecycleMounted=!0,this.suppressedOpenGeneration=void 0,this.open&&this.searchable&&changed.has("searchQuery")&&this.searchQuery.trim()&&this.visibleEntries.length===0&&(this.searchAnnouncements??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.searchAnnouncements.announce(this.localize("localePickerEmpty"))),changed.has("searchable")&&this.searchable&&shadowFocusTarget(this)===this.triggerElement&&this.queueSearchFocus(),(changed.has("touched")||changed.has("required")||changed.has("value"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}cancelLocaleLoad(){this.loadAnnouncements?.release(),this.loadAnnouncements=void 0,this.loadGeneration++,this.loadingTag=void 0,this.loadFailureTag=void 0}announceLoad(key){this.loadAnnouncements??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.loadAnnouncements.announce(key==="loading"?this.localize("loading"):this.localize("statusError"))}commit(tag){if(!(this.commitDispatching||this.liveDisabled||!this.entryFor(tag))){if(tag===this._value&&tag===getLyraLocale()){this.hide();return}this.commitDispatching=!0;try{const previousValue=this._value,version=this.valueWriteVersion,loader=this.localeLoader,generation=this.loadGeneration,detail=Object.freeze({value:tag,previousValue,direction:getLyraLocaleDirection(tag)});if(this.emit("lr-change-request",detail,{cancelable:!0}).defaultPrevented||this.liveDisabled||this.valueWriteVersion!==version||this.loadGeneration!==generation||this.localeLoader!==loader||!this.entryFor(tag))return;const commitValue=()=>{const searchFocus=this.searchElement&&shadowFocusTarget(this)===this.searchElement?this.searchElement:void 0;this.value=tag,this.hide(),setLyraLocale(tag);const committed=Object.freeze({...detail,direction:getLyraLocaleDirection(tag)});emitValueEvents(this,"input",committed,detail2=>this.emit("lr-input",detail2)),emitValueEvents(this,"change",committed,detail2=>this.emit("lr-change",detail2)),searchFocus&&this.isConnected&&this.searchable&&shadowFocusTarget(this)===searchFocus&&this.focus()};if(loader===void 0){commitValue();return}this.cancelLocaleLoad();const operation=this.loadGeneration,ownerDocument=this.ownerDocument;this.loadingTag=tag,this.announceLoad("loading");const ownsSelection=()=>this.isConnected&&this.ownerDocument===ownerDocument&&this.loadGeneration===operation&&this.valueWriteVersion===version&&this.localeLoader===loader&&!this.liveDisabled&&this.entryFor(tag)!==void 0;Promise.resolve().then(()=>{if(ownsSelection())return loader(tag)}).then(()=>{ownsSelection()&&commitValue()},()=>{ownsSelection()&&(this.loadingTag=void 0,this.loadFailureTag=tag,this.announceLoad("statusError"))})}finally{this.commitDispatching=!1}}}isSearchFocusTransfer(event){const related=event.relatedTarget;return(this.searchable||event.currentTarget===this.searchElement||related===this.searchElement)&&related!==null&&"nodeType"in related&&this.renderRoot.contains(related)}typeAhead(char){this.typeBuffer.add(char,this.effectiveLocale);const rows=this.normalizedEntries;if(!rows.length)return;const currentTag=this.open?rows[this.activeIndex]?.tag:this.previewTag,currentIndex=rows.findIndex(r=>r.tag===currentTag),match=this.typeBuffer.match(rows,currentIndex,row=>row.label,this.effectiveLocale);match!==null&&(this.open?this.setActiveIndex(match):this.commit(rows[match].tag))}setActiveIndex(index){const last=this.visibleEntries.length-1,next=last<0||index<0?-1:Math.min(last,index);this.activeIndex=next,this.queueActiveScroll()}queueActiveScroll(){const generation=++this.activeScrollGeneration,index=this.activeIndex;index<0||!this.open||this.updateComplete.then(()=>{if(generation!==this.activeScrollGeneration||!this.isConnected||!this.open||this.activeIndex!==index)return;const row=this.shadowRoot?.getElementById(`${this.listId}-opt-${index}`),popup=this.renderRoot.querySelector('[part="listbox"]');row&&popup&&revealRow(popup,row,this.searchElement?.offsetHeight)})}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`,selected=entry.tag===this._value;return html`<div
|
|
1
|
+
import{__decorate}from"tslib";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{guard}from"lit/directives/guard.js";import{emitValueEvents}from"../../../internal/value-events.js";import{renderFormControlHintError}from"../../../internal/form-control-template.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{FormControlController,reflectFormName}from"../../../internal/form-control-controller.js";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{acquireNativeControlDescription}from"../../../internal/native-control-description.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{deferredPlaceReady as place,waitForDeferredPlacement,syncTopLayerRelease,topLayerPlacement}from"../../../internal/anchored-overlay-runtime.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{hostAriaLabel,nextId,srOnly}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{TypeAheadBuffer}from"../../../internal/type-ahead-buffer.js";import{resolveListMove}from"../../../internal/list-navigation.js";import{getDisplayNames,resolveIntlLocale}from"../../../internal/intl-cache.js";import{activeElementIn,shadowFocusTarget}from"../../../internal/active-element.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{getLyraLocale,getLyraLocaleDirection,getRegisteredLyraLocales,subscribeLyraLocaleRegistry,setLyraLocale}from"../../../internal/localization-runtime.js";import{localeNativeName}from"../../media/flag/language-map.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./locale-picker.styles.js";import{autocorrectConverter,declaredDefaultConverter,spellcheckConverter}from"../../../internal/converters.js";import{getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{PopupController,emitPopupEvent}from"../../../internal/popup-controller.js";import{revealRow}from"../../../internal/reveal-row.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{LYRA_DEFAULT_localePickerEmpty,LYRA_DEFAULT_localePickerInputLimit,LYRA_DEFAULT_localePickerLabel,LYRA_DEFAULT_localePickerRequired,LYRA_DEFAULT_localePickerSearchLabel}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_loading,LYRA_DEFAULT_retry,LYRA_DEFAULT_statusError}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();const MAX_LOCALE_ENTRIES=512,localeSpellcheckConverter={...spellcheckConverter,fromAttribute:(value,type)=>value===null?void 0:spellcheckConverter.fromAttribute?.(value,type)};function snapshotLocaleCatalog(source){if(!Array.isArray(source))return Object.freeze([]);const rows=[];for(let index=0;index<Math.min(source.length,MAX_LOCALE_ENTRIES);index+=1)try{const raw=source[index];if(typeof raw=="string"){raw.length>0&&rows.push(raw);continue}if(raw===null||typeof raw!="object")continue;const candidate=raw,tag=candidate.tag,label=candidate.label,country=candidate.country;if(typeof tag!="string"||tag.length===0||label!==void 0&&typeof label!="string"||country!==void 0&&typeof country!="string")continue;rows.push(Object.freeze({tag,...label===void 0?{}:{label},...country===void 0?{}:{country}}))}catch{}return Object.freeze(rows)}function normalizeLocaleEntry(tag,label,country){if(label!==void 0&&label.trim().length>0)return country===void 0?{tag,label}:{tag,label,country};let resolved;return{tag,get label(){return resolved??=localeNativeName(tag)},...country===void 0?{}:{country}}}class LyraLocalePicker extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,loading:LYRA_DEFAULT_loading,localePickerEmpty:LYRA_DEFAULT_localePickerEmpty,localePickerInputLimit:LYRA_DEFAULT_localePickerInputLimit,localePickerLabel:LYRA_DEFAULT_localePickerLabel,localePickerRequired:LYRA_DEFAULT_localePickerRequired,localePickerSearchLabel:LYRA_DEFAULT_localePickerSearchLabel,retry:LYRA_DEFAULT_retry,statusError:LYRA_DEFAULT_statusError}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:"value",reflect:!0,useDefault:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0}}}get localeLoader(){return this._localeLoader}set localeLoader(next){const previous=this._localeLoader;previous!==next&&(this.cancelLocaleLoad(),this._localeLoader=next,this.requestUpdate("localeLoader",previous))}get locales(){return this._locales}set locales(next){this.cancelLocaleLoad();const previous=this._locales;this.inputLimited=Array.isArray(next)&&next.length>MAX_LOCALE_ENTRIES,this._locales=next===void 0?void 0:snapshotLocaleCatalog(next),this.requestUpdate("locales",previous)}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=!!next,this.requestUpdate()}get open(){return this._open}set open(next){const old=this._open,liveDisabled=this.effectiveDisabled||typeof this.matches=="function"&&this.matches(":disabled");if(this._open=!!next&&!liveDisabled,this._open===old){next&&!this._open&&this.hasAttribute("open")&&this.removeAttribute("open");return}this.openGeneration++,this.requestUpdate("open",old)}constructor(){super(),this.withoutFlags=!1,this.topLayer=!1,this.triggerDisplay="flag-label",this.optionDisplay="label-tag",this.searchable=!1,this.autocomplete="off",this.inputMode="",this.enterKeyHint="",this.spellcheck=!1,this.autocapitalize="",this.autocorrectValue=!0,this.label="",this.labelDisplay="visible",this.hint="",this.errorText="",this.size="m",this.activeIndex=-1,this.searchQuery="",this.touched=!1,this.slotPresence=new SlotPresenceController(this),this.registryTick=0,this.searchFocusGeneration=0,this.listId=nextId("locale-picker-list"),this.controlId=nextId("locale-picker-control"),this.listboxHidden=!0,this.openGeneration=0,this.openVetoed=!1,this.lifecycleMounted=!1,this.lastRenderedOpen=!1,this.announcingHide=!1,this.restoreFocusOnClose=!1,this.popupController=new PopupController({host:this,popup:()=>this.renderRoot.querySelector('[part="listbox"]'),emit:(name,cancelable)=>emitPopupEvent(this,name,cancelable),onPointer:event=>this.onDocPointer(event)}),this._value="",this._open=!1,this._fieldsetDisabled=!1,this._name="",this._disabled=!1,this._required=!1,this._defaultValue="",this._valueDirty=!1,this.settingDefaultValue=!1,this.reflectingDefaultValue=!1,this.typeBuffer=new TypeAheadBuffer(this),this.activeScrollGeneration=0,this.localizedValidityLocale="",this.localizedIntrinsicMessage="",this.localDescriptionIds="",this.markInteracted=()=>{this.touched||(this.touched=!0,this.syncCustomStates())},this.onDocPointer=e=>{if(!e.composedPath().includes(this)){if(this.overlayHandle?.isActive()){this.overlayHandle.dismissBackdrop();return}this.hide()}},this.inputLimited=!1,this.limitAnnouncements=new AnnouncementSinkController(this),this.limitMounted=!1,this.commitDispatching=!1,this.valueWriteVersion=0,this.loadGeneration=0,this.retryLocaleLoad=()=>{const restoreFocus=shadowFocusTarget(this)?.getAttribute("part")==="load-retry";this.loadFailureTag!==void 0&&this.commit(this.loadFailureTag),restoreFocus&&this.loadFailureTag===void 0&&this.isConnected&&shadowFocusTarget(this)?.getAttribute("part")==="load-retry"&&this.focus()},this.onTriggerClick=()=>{this.liveDisabled||(this.open?this.hide():this.show())},this.onTriggerBlur=event=>{if(this.isSearchFocusTransfer(event)){event.stopPropagation();return}this.liveDisabled||(this.touched=!0),this.syncCustomStates(),this.hide(),relayNativeEvent(this,event)},this.onTriggerFocus=event=>{if(this.isSearchFocusTransfer(event)){event.stopPropagation();return}if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onSearchInput=event=>{event.stopPropagation(),!(!this.searchable||!this.open||this.liveDisabled)&&(this.searchQuery=event.currentTarget.value,this.setActiveIndex(this.visibleEntries.length?0:-1))},this.onSearchChange=event=>{event.stopPropagation()},this.onSearchKeyDown=event=>{if(this.liveDisabled||!this.open||event.isComposing||event.keyCode===229)return;const rows=this.visibleEntries;if(event.key==="ArrowDown"||event.key==="ArrowUp")event.preventDefault(),this.setActiveIndex(event.key==="ArrowDown"?Math.min(rows.length-1,this.activeIndex+1):Math.max(0,this.activeIndex-1));else if(event.key==="Enter"){event.preventDefault();const row=rows[this.activeIndex];row&&this.commit(row.tag)}else event.key==="Escape"&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(event.preventDefault(),this.dismissFromEscape())},this.onKeyDown=e=>{if(this.liveDisabled||e.isComposing||e.keyCode===229)return;const rows=this.visibleEntries,move=()=>resolveListMove(e,{count:rows.length,current:this.activeIndex,orientation:"vertical",wrap:!1,clamp:!0,backwardFromMissing:"first"});switch(e.key){case"ArrowDown":if(e.preventDefault(),!this.open)return this.show();this.setActiveIndex(move()??-1),this.queueSearchFocus();break;case"ArrowUp":if(e.preventDefault(),!this.open)return this.show();this.setActiveIndex(move()??-1),this.queueSearchFocus();break;case"Enter":case" ":if(this.open){e.preventDefault();const activeRow=rows[this.activeIndex];this.activeIndex>=0&&activeRow?this.commit(activeRow.tag):this.hide()}break;case"Escape":this.open&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(e.preventDefault(),this.dismissFromEscape());break;case"Home":this.open&&(e.preventDefault(),this.setActiveIndex(move()??-1));break;case"End":this.open&&(e.preventDefault(),this.setActiveIndex(move()??-1));break;default:this.typeBuffer.accepts(e)&&(this.searchable?(e.preventDefault(),this.show(),this.searchQuery+=e.key,this.setActiveIndex(this.visibleEntries.length?0:-1),this.queueSearchFocus()):this.typeAhead(e.key));break}},this.onListboxMouseDown=e=>{e.composedPath()[0]!==this.searchElement&&e.preventDefault()},this.onListboxClick=e=>{if(this.liveDisabled)return;const tag=e.target.closest('[part="option"]')?.dataset.value;tag!==void 0&&this.commit(tag)},this.validityController=new FormControlController(this,{invalid:init=>this.emit("lr-invalid",null,init),interacted:this.markInteracted,customError:()=>this.validityController.customValidityMessage}),this.internals=this.validityController.formInternals,new GlassScrollLayer(this,'[part="listbox"]',()=>this.open),this.internals.setFormValue("")}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}focus(options){this.liveDisabled||this.triggerElement?.focus(options)}blur(){this.searchElement&&shadowFocusTarget(this)===this.searchElement?this.searchElement.blur():this.triggerElement?.blur()}click(){this.liveDisabled||this.triggerElement?.click()}get input(){return this.searchable?this.searchElement??null:null}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"]')??null}syncExternalDescription(){if(!this.isConnected)return;const target=this.triggerElement??null;target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireNativeControlDescription(this,target,()=>this.localDescriptionIds))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.syncLocaleAttributeForLocalization(),this.updateValidity(),this.stopRegistrySubscription=subscribeLyraLocaleRegistry(()=>{this.registryTick+=1}),this.hasUpdated&&this.open&&queueMicrotask(()=>this.syncPopup())}disconnectedCallback(){this.popupController.cancel(),(this.open||this.lastRenderedOpen)&&this.hasUpdated&&!this.announcingHide&&emitPopupEvent(this,"lr-hide",!1),this.lastRenderedOpen=!1,this.clearSearch(),this.cancelLocaleLoad(),this.loadAnnouncements?.release(),this.loadAnnouncements=void 0,this.listboxHidden=!0,this.releaseExternalDescription(),super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.deactivatePopupOverlay(!1),this.stopRegistrySubscription?.(),this.stopRegistrySubscription=void 0,this.typeBuffer.clear(),this.activeScrollGeneration+=1,this.open=!1,this.suppressedOpenGeneration=this.openGeneration}adoptedCallback(){this.popupController.cancel(),this.clearSearch(),this.cancelLocaleLoad(),this.loadAnnouncements?.release(),this.loadAnnouncements=void 0,super.adoptedCallback(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription(),this.cleanup?.(),this.cleanup=void 0,this.popupController.unbindPointer(),this.overlayHandle?.suspend(),this.typeBuffer.clear(),this.open&&queueMicrotask(()=>this.syncPopup())}willUpdate(changed){super.willUpdate(changed),changed.has("locale")&&this.syncLocaleAttributeForLocalization(),this.hasUpdated&&this.refreshLocalizedIntrinsicValidity(changed),changed.has("searchable")&&!this.searchable&&(this.clearSearch(),this.searchElement&&shadowFocusTarget(this)===this.searchElement&&this.focus()),this.announceOpenTransition(changed),!this.openVetoed&&changed.has("open")&&!this.open&&(this.activeIndex=-1,this.clearSearch()),!this.openVetoed&&changed.has("open")&&this.open&&this.setActiveIndex(this.visibleEntries.findIndex(row=>row.tag===this._value)),this.open&&(this.searchable||changed.has("locales")||changed.has("registryTick"))&&this.activeIndex>=0&&(this.activeIndex=Math.min(this.activeIndex,this.visibleEntries.length-1),this.queueActiveScroll()),this.open&&(this.listboxHidden=!1)}get value(){return this._value}set value(next){this.cancelLocaleLoad(),this.valueWriteVersion++;const old=this._value;this.settingDefaultValue||(this._valueDirty=!0),this._value=next??"",this.internals.setFormValue(this._value),this.updateValidity(),this.requestUpdate("value",old)}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next??"",this.reflectingDefaultValue=!0;try{this._defaultValue?this.setAttribute("value",this._defaultValue):this.removeAttribute("value")}finally{this.reflectingDefaultValue=!1}this._valueDirty||this.restoreLiveValueFromDefault(),this.requestUpdate("defaultValue",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",reflectFormName(this,this._name),this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){next&&this.cancelLocaleLoad();const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this._disabled&&this.hide(),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}updateValidity(){this.localizedValidityLocale=this.effectiveMessageLocale;const valueMissing=this.hasMissingRequiredValue(),message=valueMissing?this.localize("localePickerRequired"):"";this.localizedIntrinsicMessage=message,valueMissing?this.validityController.setValidity({valueMissing:!0},message):this.validityController.setValidity({}),this.syncCustomStates()}refreshLocalizedIntrinsicValidity(changed){const locale=this.effectiveMessageLocale,message=this.hasMissingRequiredValue()?this.localize("localePickerRequired"):"";(changed.has("strings")||locale!==this.localizedValidityLocale||message!==this.localizedIntrinsicMessage)&&this.updateValidity()}hasMissingRequiredValue(){return!this.isBarred()&&this.required&&!this._value}syncLocaleAttributeForLocalization(){this.locale?this.getAttribute("locale")!==this.locale&&this.setAttribute("locale",this.locale):this.hasAttribute("locale")&&this.removeAttribute("locale")}isBarred(){return isBarredFromValidation(this,this.internals)}syncCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.isBarred()})}formResetCallback(){this.touched=!1,this.clearSearch(),this.restoreLiveValueFromDefault()}restoreLiveValueFromDefault(){this.settingDefaultValue=!0;try{this.value=this._defaultValue}finally{this.settingDefaultValue=!1}this._valueDirty=!1}formStateRestoreCallback(state2,_mode){this.value=typeof state2=="string"?state2:""}formDisabledCallback(disabled){this.validityController?.reflectingDisabled||(disabled&&this.cancelLocaleLoad(),this._fieldsetDisabled=disabled,disabled&&this.hide(),this.updateValidity(),this.requestUpdate())}checkValidity(){return this.validityController.checkValidity()}reportValidity(){return this.validityController.syncConstraints(),this.touched=!0,this.syncCustomStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncCustomStates(),this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),this.requestUpdate()}get normalizedEntries(){const raw=this.locales,cached=this.entriesCache;if(cached&&cached.raw===raw&&cached.tick===this.registryTick)return cached.rows;const rows=raw!==void 0?raw.map(entry=>typeof entry=="string"?normalizeLocaleEntry(entry):normalizeLocaleEntry(entry.tag,entry.label,entry.country)):getRegisteredLyraLocales().map(tag=>normalizeLocaleEntry(tag));return this.entriesCache={raw,tick:this.registryTick,rows},rows}normalizeSearch(text,locale){return text.toLocaleLowerCase(resolveIntlLocale(locale)).normalize("NFKD").replace(/\p{M}/gu,"").trim()}get visibleEntries(){const rows=this.normalizedEntries;if(!this.searchable)return rows;const locale=this.effectiveLocale,query2=this.normalizeSearch(this.searchQuery,locale);if(!query2)return rows;const cached=this.visibleCache;if(cached&&cached.rows===rows&&cached.query===this.searchQuery&&cached.locale===locale)return cached.result;let keys=this.searchKeys;if(!keys||keys.rows!==rows||keys.locale!==locale){let names,englishNames;try{names=getDisplayNames(locale,{type:"language"})}catch{}try{englishNames=getDisplayNames("en",{type:"language"})}catch{}keys={rows,locale,values:rows.map(row=>{let localizedName="",englishName="";try{localizedName=names?.of(row.tag)??""}catch{}try{englishName=englishNames?.of(row.tag)??""}catch{}return{local:[row.label,localeNativeName(row.tag),localizedName].map(text=>this.normalizeSearch(text,locale)),invariant:[row.tag,englishName].map(text=>this.normalizeSearch(text,"en"))}})},this.searchKeys=keys}const invariantQuery=this.normalizeSearch(this.searchQuery,"en"),result=rows.filter((_,index)=>keys.values[index].local.some(text=>text.includes(query2))||keys.values[index].invariant.some(text=>text.includes(invariantQuery)));return this.visibleCache={rows,query:this.searchQuery,locale,result},result}clearSearch(){this.searchQuery="",this.searchFocusGeneration++,this.searchAnnouncements?.release(),this.searchAnnouncements=void 0}queueSearchFocus(){if(!this.searchable||!this.open||this.liveDisabled)return;const generation=++this.searchFocusGeneration,ownerDocument=this.ownerDocument,outerFocus=activeElementIn(ownerDocument),innerFocus=shadowFocusTarget(this);this.updateComplete.then(()=>{generation!==this.searchFocusGeneration||!this.isConnected||!this.open||!this.searchable||this.liveDisabled||this.ownerDocument!==ownerDocument||activeElementIn(ownerDocument)!==outerFocus||shadowFocusTarget(this)!==innerFocus||this.searchElement?.focus()})}get previewTag(){return this._value||this.effectiveLocale}entryFor(tag){const rows=this.normalizedEntries;if(this.entryIndex?.rows!==rows){const byTag=new Map;for(const row of rows)byTag.has(row.tag)||byTag.set(row.tag,row);this.entryIndex={rows,byTag}}return this.entryIndex.byTag.get(tag)}labelFor(tag){return this.entryFor(tag)?.label??localeNativeName(tag)}show(){this.open||this.liveDisabled||(this.open=!0,this.queueSearchFocus())}hide(){this.open&&(this.open=!1)}dismissFromEscape(){if(this.open){if(this.searchable&&this.searchQuery.length){this.clearSearch(),this.setActiveIndex(this.visibleEntries.length?0:-1);return}this.restoreFocusOnClose=!0,this.hide()}}activatePopupOverlay(){if(this.overlayHandle?.isActive()){this.overlayHandle.resume();return}this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="listbox"]'),onEscape:()=>this.dismissFromEscape(),onBackdrop:()=>this.hide(),restoreFocusTo:()=>this.renderRoot.querySelector('[part="trigger"]')})}deactivatePopupOverlay(restoreFocus){const overlay=this.overlayHandle;this.overlayHandle=void 0,overlay?.deactivate({restoreFocus}),this.popupController.unbindPointer()}syncPopup(){if(this.cleanup?.(),this.cleanup=void 0,!this.open||!this.isConnected){this.deactivatePopupOverlay(this.isConnected&&this.restoreFocusOnClose),this.restoreFocusOnClose=!1;return}this.activatePopupOverlay(),this.popupController.bindPointer();const anchor=this.renderRoot.querySelector(this.loadFailureTag!==void 0?'[part="form-control"]':'[part="trigger"]'),listbox=this.renderRoot.querySelector('[part="listbox"]');anchor&&listbox&&(this.placedTopLayer=syncTopLayerRelease(listbox,this.placedTopLayer,this.topLayer),this.cleanup=place(anchor,listbox,topLayerPlacement(this.topLayer,resolveEffectivePositioningStrategy(this,void 0,"fixed"))))}announceOpenTransition(changed){if(this.openVetoed=!1,this.openTransition=void 0,!changed.has("open")||!this.lifecycleMounted||!this.isConnected||this.suppressedOpenGeneration===this.openGeneration||changed.get("open")===this.open)return;const opening=this.open,generation=this.openGeneration;this.announcingHide=!opening;try{!opening&&this.liveDisabled?emitPopupEvent(this,"lr-hide",!1):this.openVetoed=this.popupController.announce(opening,()=>{this.isConnected&&this.openGeneration===generation&&(opening||!this.liveDisabled)&&(this._open=!opening)})}finally{this.announcingHide=!1}if(!this.isConnected||generation!==this.openGeneration||opening!==this.open){this.openVetoed=this.open===changed.get("open");return}this.openVetoed&&this.liveDisabled&&!this.open&&(this.openVetoed=!1),this.openVetoed||(this.popupController.cancel(),this.openTransition=opening)}updated(changed){super.updated(changed),this.limitMounted&&changed.has("inputLimited")&&this.inputLimited&&this.limitAnnouncements.announcePolite(this.localize("localePickerInputLimit")),this.limitMounted=!0,this.syncExternalDescription();const activeId=this.open&&this.activeIndex>=0?`${this.listId}-opt-${this.activeIndex}`:"",previous=this.renderRoot.querySelector('[part="option"][data-active]');previous?.id!==activeId&&previous?.removeAttribute("data-active"),activeId&&this.renderRoot.querySelector(`[id="${activeId}"]`)?.setAttribute("data-active",""),(changed.has("open")&&!this.openVetoed||this.open&&(changed.has("locales")||changed.has("registryTick")||changed.has("locale")||changed.has("searchQuery")||changed.has("searchable")||changed.has("loadFailureTag")||changed.has("topLayer")))&&this.syncPopup(),this.openTransition!==void 0&&this.isConnected&&this.popupController.settle(this.openTransition?"lr-after-show":"lr-after-hide",{waitForPosition:()=>waitForDeferredPlacement(()=>this.cleanup),conceal:()=>{this.listboxHidden=!0}}),this.openVetoed&&(this.restoreFocusOnClose=!1),this.lastRenderedOpen=this.open&&this.isConnected,this.lifecycleMounted=!0,this.suppressedOpenGeneration=void 0,this.open&&this.searchable&&changed.has("searchQuery")&&this.searchQuery.trim()&&this.visibleEntries.length===0&&(this.searchAnnouncements??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.searchAnnouncements.announce(this.localize("localePickerEmpty"))),changed.has("searchable")&&this.searchable&&shadowFocusTarget(this)===this.triggerElement&&this.queueSearchFocus(),(changed.has("touched")||changed.has("required")||changed.has("value"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}cancelLocaleLoad(){this.loadAnnouncements?.release(),this.loadAnnouncements=void 0,this.loadGeneration++,this.loadingTag=void 0,this.loadFailureTag=void 0}announceLoad(key){this.loadAnnouncements??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.loadAnnouncements.announce(key==="loading"?this.localize("loading"):this.localize("statusError"))}commit(tag){if(!(this.commitDispatching||this.liveDisabled||!this.entryFor(tag))){if(tag===this._value&&tag===getLyraLocale()){this.hide();return}this.commitDispatching=!0;try{const previousValue=this._value,version=this.valueWriteVersion,loader=this.localeLoader,generation=this.loadGeneration,detail=Object.freeze({value:tag,previousValue,direction:getLyraLocaleDirection(tag)});if(this.emit("lr-change-request",detail,{cancelable:!0}).defaultPrevented||this.liveDisabled||this.valueWriteVersion!==version||this.loadGeneration!==generation||this.localeLoader!==loader||!this.entryFor(tag))return;const commitValue=()=>{const searchFocus=this.searchElement&&shadowFocusTarget(this)===this.searchElement?this.searchElement:void 0;this.value=tag,this.hide(),setLyraLocale(tag);const committed=Object.freeze({...detail,direction:getLyraLocaleDirection(tag)});emitValueEvents(this,"input",committed,detail2=>this.emit("lr-input",detail2)),emitValueEvents(this,"change",committed,detail2=>this.emit("lr-change",detail2)),searchFocus&&this.isConnected&&this.searchable&&shadowFocusTarget(this)===searchFocus&&this.focus()};if(loader===void 0){commitValue();return}this.cancelLocaleLoad();const operation=this.loadGeneration,ownerDocument=this.ownerDocument;this.loadingTag=tag,this.announceLoad("loading");const ownsSelection=()=>this.isConnected&&this.ownerDocument===ownerDocument&&this.loadGeneration===operation&&this.valueWriteVersion===version&&this.localeLoader===loader&&!this.liveDisabled&&this.entryFor(tag)!==void 0;Promise.resolve().then(()=>{if(ownsSelection())return loader(tag)}).then(()=>{ownsSelection()&&commitValue()},()=>{ownsSelection()&&(this.loadingTag=void 0,this.loadFailureTag=tag,this.announceLoad("statusError"))})}finally{this.commitDispatching=!1}}}isSearchFocusTransfer(event){const related=event.relatedTarget;return(this.searchable||event.currentTarget===this.searchElement||related===this.searchElement)&&related!==null&&"nodeType"in related&&this.renderRoot.contains(related)}typeAhead(char){this.typeBuffer.add(char,this.effectiveLocale);const rows=this.normalizedEntries;if(!rows.length)return;const currentTag=this.open?rows[this.activeIndex]?.tag:this.previewTag,currentIndex=rows.findIndex(r=>r.tag===currentTag),match=this.typeBuffer.match(rows,currentIndex,row=>row.label,this.effectiveLocale);match!==null&&(this.open?this.setActiveIndex(match):this.commit(rows[match].tag))}setActiveIndex(index){const last=this.visibleEntries.length-1,next=last<0||index<0?-1:Math.min(last,index);this.activeIndex=next,this.queueActiveScroll()}queueActiveScroll(){const generation=++this.activeScrollGeneration,index=this.activeIndex;index<0||!this.open||this.updateComplete.then(()=>{if(generation!==this.activeScrollGeneration||!this.isConnected||!this.open||this.activeIndex!==index)return;const row=this.shadowRoot?.getElementById(`${this.listId}-opt-${index}`),popup=this.renderRoot.querySelector('[part="listbox"]');row&&popup&&revealRow(popup,row,this.searchElement?.offsetHeight)})}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`,selected=entry.tag===this._value;return html`<div
|
|
2
2
|
part="option"
|
|
3
3
|
id=${id}
|
|
4
4
|
role="option"
|
|
@@ -95,4 +95,4 @@ import{__decorate}from"tslib";import{AnnouncementSinkController}from"../../../in
|
|
|
95
95
|
</div>`:nothing}
|
|
96
96
|
${renderFormControlHintError({idPrefix:"locale-picker",hint:this.hint,errorText:this.errorText,hasHint,hasError})}
|
|
97
97
|
</div>
|
|
98
|
-
`}}__decorate([property({attribute:!1})],LyraLocalePicker.prototype,"localeLoader",null),__decorate([property({attribute:!1})],LyraLocalePicker.prototype,"locales",null),__decorate([property({type:Boolean,attribute:"without-flags"})],LyraLocalePicker.prototype,"withoutFlags",void 0),__decorate([property({type:Boolean,attribute:"top-layer",reflect:!0})],LyraLocalePicker.prototype,"topLayer",void 0),__decorate([property({attribute:"trigger-display",converter:declaredDefaultConverter("flag-label")})],LyraLocalePicker.prototype,"triggerDisplay",void 0),__decorate([property({attribute:"option-display",converter:declaredDefaultConverter("label-tag")})],LyraLocalePicker.prototype,"optionDisplay",void 0),__decorate([property({type:Boolean})],LyraLocalePicker.prototype,"searchable",void 0),__decorate([property()],LyraLocalePicker.prototype,"autocomplete",void 0),__decorate([property({attribute:"inputmode"})],LyraLocalePicker.prototype,"inputMode",void 0),__decorate([property({attribute:"enterkeyhint"})],LyraLocalePicker.prototype,"enterKeyHint",void 0),__decorate([property({converter:localeSpellcheckConverter,useDefault:!0})],LyraLocalePicker.prototype,"spellcheck",void 0),__decorate([property()],LyraLocalePicker.prototype,"autocapitalize",void 0),__decorate([property({converter:autocorrectConverter})],LyraLocalePicker.prototype,"autocorrect",null),__decorate([property()],LyraLocalePicker.prototype,"label",void 0),__decorate([property()],LyraLocalePicker.prototype,"hint",void 0),__decorate([property({attribute:"error-text"})],LyraLocalePicker.prototype,"errorText",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraLocalePicker.prototype,"open",null),__decorate([property({reflect:!0,converter:declaredDefaultConverter("m")})],LyraLocalePicker.prototype,"size",void 0),__decorate([state()],LyraLocalePicker.prototype,"activeIndex",void 0),__decorate([state()],LyraLocalePicker.prototype,"searchQuery",void 0),__decorate([state()],LyraLocalePicker.prototype,"touched",void 0),__decorate([state()],LyraLocalePicker.prototype,"registryTick",void 0),__decorate([query('[part="trigger"]')],LyraLocalePicker.prototype,"triggerElement",void 0),__decorate([query('[part="search-input"]')],LyraLocalePicker.prototype,"searchElement",void 0),__decorate([state()],LyraLocalePicker.prototype,"listboxHidden",void 0),__decorate([state()],LyraLocalePicker.prototype,"inputLimited",void 0),__decorate([state()],LyraLocalePicker.prototype,"loadingTag",void 0),__decorate([state()],LyraLocalePicker.prototype,"loadFailureTag",void 0);export{LyraLocalePicker};
|
|
98
|
+
`}}__decorate([property({attribute:!1})],LyraLocalePicker.prototype,"localeLoader",null),__decorate([property({attribute:!1})],LyraLocalePicker.prototype,"locales",null),__decorate([property({type:Boolean,attribute:"without-flags"})],LyraLocalePicker.prototype,"withoutFlags",void 0),__decorate([property({type:Boolean,attribute:"top-layer",reflect:!0})],LyraLocalePicker.prototype,"topLayer",void 0),__decorate([property({attribute:"trigger-display",converter:declaredDefaultConverter("flag-label")})],LyraLocalePicker.prototype,"triggerDisplay",void 0),__decorate([property({attribute:"option-display",converter:declaredDefaultConverter("label-tag")})],LyraLocalePicker.prototype,"optionDisplay",void 0),__decorate([property({type:Boolean})],LyraLocalePicker.prototype,"searchable",void 0),__decorate([property()],LyraLocalePicker.prototype,"autocomplete",void 0),__decorate([property({attribute:"inputmode"})],LyraLocalePicker.prototype,"inputMode",void 0),__decorate([property({attribute:"enterkeyhint"})],LyraLocalePicker.prototype,"enterKeyHint",void 0),__decorate([property({converter:localeSpellcheckConverter,useDefault:!0})],LyraLocalePicker.prototype,"spellcheck",void 0),__decorate([property()],LyraLocalePicker.prototype,"autocapitalize",void 0),__decorate([property({converter:autocorrectConverter})],LyraLocalePicker.prototype,"autocorrect",null),__decorate([property()],LyraLocalePicker.prototype,"label",void 0),__decorate([property({attribute:"label-display",reflect:!0})],LyraLocalePicker.prototype,"labelDisplay",void 0),__decorate([property()],LyraLocalePicker.prototype,"hint",void 0),__decorate([property({attribute:"error-text"})],LyraLocalePicker.prototype,"errorText",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraLocalePicker.prototype,"open",null),__decorate([property({reflect:!0,converter:declaredDefaultConverter("m")})],LyraLocalePicker.prototype,"size",void 0),__decorate([state()],LyraLocalePicker.prototype,"activeIndex",void 0),__decorate([state()],LyraLocalePicker.prototype,"searchQuery",void 0),__decorate([state()],LyraLocalePicker.prototype,"touched",void 0),__decorate([state()],LyraLocalePicker.prototype,"registryTick",void 0),__decorate([query('[part="trigger"]')],LyraLocalePicker.prototype,"triggerElement",void 0),__decorate([query('[part="search-input"]')],LyraLocalePicker.prototype,"searchElement",void 0),__decorate([state()],LyraLocalePicker.prototype,"listboxHidden",void 0),__decorate([state()],LyraLocalePicker.prototype,"inputLimited",void 0),__decorate([state()],LyraLocalePicker.prototype,"loadingTag",void 0),__decorate([state()],LyraLocalePicker.prototype,"loadFailureTag",void 0);export{LyraLocalePicker};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{type PropertyValues,type TemplateResult}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';import type{LyraAppearance,LyraSize}from'../../../internal/variants.js';import type{LyraSelectionDirection}from'../../../internal/shared-unions.js';import{type LyraPhoneCountry,type LyraPhoneNumberAdapter,type LyraPhoneNumberStatus}from'./phone-number-adapter.js';export{loadLibphonenumberAdapter,type LibphonenumberModuleLike,type LyraPhoneCountry,type LyraPhoneNumberAdapter,type LyraPhoneNumberParseResult,type LyraPhoneNumberStatus,}from'./phone-number-adapter.js';export type LyraPhoneInputSelectionDirection=LyraSelectionDirection;export interface LyraPhoneInputEventDetail{
|
|
1
|
+
import{type PropertyValues,type TemplateResult}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';import type{LyraAppearance,LyraSize,LyraLabelDisplay}from'../../../internal/variants.js';import type{LyraSelectionDirection}from'../../../internal/shared-unions.js';import{type LyraPhoneCountry,type LyraPhoneNumberAdapter,type LyraPhoneNumberStatus}from'./phone-number-adapter.js';export{loadLibphonenumberAdapter,type LibphonenumberModuleLike,type LyraPhoneCountry,type LyraPhoneNumberAdapter,type LyraPhoneNumberParseResult,type LyraPhoneNumberStatus,}from'./phone-number-adapter.js';export type LyraPhoneInputSelectionDirection=LyraSelectionDirection;export interface LyraPhoneInputEventDetail{
|
|
2
2
|
/** Canonical E.164 value, or an empty string until the current input is valid.*/
|
|
3
3
|
value:string;
|
|
4
4
|
/** The editable, best-effort formatted text shown to the user.*/
|
|
@@ -136,7 +136,14 @@ export declare class LyraPhoneInput extends LyraPhoneInput_base{static styles:im
|
|
|
136
136
|
*/
|
|
137
137
|
flags:boolean;private _adapter?;private adapterCountries;get adapter():LyraPhoneNumberAdapter|undefined;set adapter(next:LyraPhoneNumberAdapter|undefined);private _countries?;get countries():readonly LyraPhoneCountry[]|undefined;set countries(next:readonly LyraPhoneCountry[]|undefined);
|
|
138
138
|
/** Country selected when no explicit `country` has been set.*/
|
|
139
|
-
defaultCountry:string;label:string;
|
|
139
|
+
defaultCountry:string;label:string;
|
|
140
|
+
/**
|
|
141
|
+
* Whether the `label` renders on screen. `hidden` keeps the label as the accessible name but
|
|
142
|
+
* removes it visually (compact toolbars, table cells); hint, error and required semantics are
|
|
143
|
+
* unaffected. Reflected so styles and `[label-display]` selectors match.
|
|
144
|
+
* @attr label-display
|
|
145
|
+
*/
|
|
146
|
+
labelDisplay:LyraLabelDisplay;hint:string;errorText:string;
|
|
140
147
|
/** SSR slot-presence hint for label content that cannot be inspected before hydration.*/
|
|
141
148
|
withLabel:boolean;
|
|
142
149
|
/** SSR slot-presence hint for hint content that cannot be inspected before hydration.*/
|