@aceshooting/lyra-ui 30.8.0 → 31.0.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 +239 -329
- package/dist/ai/adapters/ag-ui.js +1 -1
- package/dist/components/agent-tools/activity-feed/activity-feed.class.js +1 -1
- package/dist/components/agent-tools/compare-panel/compare-panel.class.js +1 -1
- package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +1 -1
- package/dist/components/agent-tools/thinking-panel/thinking-panel.class.js +1 -1
- package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.class.js +1 -1
- package/dist/components/charts/chart/box-plot-loader.js +1 -1
- package/dist/components/charts/chart/box-plot.class.js +2 -2
- package/dist/components/charts/chart/chart-core-loader.js +1 -1
- package/dist/components/charts/chart/chart-feature-loader.js +1 -1
- package/dist/components/charts/chart/chart-sync.js +1 -1
- package/dist/components/charts/chart/chart.class.d.ts +1 -1
- package/dist/components/charts/chart/chart.class.js +4 -4
- package/dist/components/charts/chart/lite-chart-axis-layout.js +1 -1
- package/dist/components/charts/chart/lite-chart.class.js +1 -1
- package/dist/components/charts/chart-3d/chart-3d-engine.js +1 -1
- package/dist/components/conversation/chat-composer/chat-composer.class.d.ts +9 -4
- package/dist/components/conversation/chat-composer/chat-composer.class.js +1 -1
- package/dist/components/conversation/chat-composer/chat-composer.styles.js +1 -1
- package/dist/components/conversation/chat-message/chat-message.class.d.ts +27 -3
- package/dist/components/conversation/chat-message/chat-message.class.js +14 -12
- package/dist/components/conversation/chat-message/chat-message.styles.js +1 -1
- package/dist/components/conversation/chat-viewport/chat-viewport.class.d.ts +29 -2
- package/dist/components/conversation/chat-viewport/chat-viewport.class.js +2 -2
- package/dist/components/conversation/chat-viewport/chat-viewport.styles.js +1 -1
- package/dist/components/conversation/code-block/code-block-shared.js +1 -1
- package/dist/components/conversation/code-block/code-loader.js +1 -1
- package/dist/components/conversation/code-block/shiki-oniguruma.js +1 -1
- package/dist/components/conversation/code-block/shiki-types.js +1 -1
- package/dist/components/conversation/markdown/katex-loader.js +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-code-header.js +1 -1
- package/dist/components/conversation/markdown/markdown-core.class.d.ts +10 -0
- package/dist/components/conversation/markdown/markdown-core.class.js +1 -1
- package/dist/components/conversation/markdown/markdown-loader.js +1 -1
- 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 +10 -0
- package/dist/components/conversation/markdown/markdown.class.js +1 -1
- package/dist/components/conversation/message-feedback/message-feedback.class.js +2 -2
- package/dist/components/conversation/message-parts/message-parts.class.js +1 -1
- package/dist/components/conversation/prompt-input/prompt-input.class.d.ts +2 -1
- package/dist/components/conversation/streaming-text/streaming-text-base.class.d.ts +4 -0
- package/dist/components/conversation/streaming-text/streaming-text-base.class.js +1 -1
- 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 +17 -3
- package/dist/components/conversation/suggestion-chips/suggestion-chips.class.js +3 -3
- package/dist/components/conversation/suggestion-chips/suggestion-chips.d.ts +1 -1
- package/dist/components/conversation/suggestion-chips/suggestion-chips.js +1 -1
- package/dist/components/conversation/suggestion-chips/suggestion-chips.styles.js +1 -1
- package/dist/components/conversation/thread-list/thread-list.class.js +2 -2
- package/dist/components/conversation/transcript-feed/transcript-feed.class.js +1 -1
- package/dist/components/data/data-grid/data-grid.class.d.ts +10 -10
- package/dist/components/data/data-grid/data-grid.class.js +1 -1
- package/dist/components/data/file-tree/file-tree.class.js +1 -1
- package/dist/components/data/flow-canvas/flow-canvas.class.js +1 -1
- package/dist/components/data/heatmap/heatmap.class.d.ts +1 -1
- package/dist/components/data/heatmap/heatmap.class.js +1 -1
- package/dist/components/data/pagination/pagination.class.js +1 -1
- package/dist/components/data/table/table.class.d.ts +31 -2
- package/dist/components/data/table/table.class.js +3 -3
- package/dist/components/data/table/table.styles.js +1 -1
- package/dist/components/data/timeline/timeline-cluster.js +1 -1
- package/dist/components/data/timeline/timeline-item.class.d.ts +10 -3
- package/dist/components/data/timeline/timeline-item.class.js +16 -12
- package/dist/components/data/timeline/timeline-item.styles.js +1 -1
- package/dist/components/data/timeline/timeline.class.d.ts +14 -2
- package/dist/components/data/timeline/timeline.class.js +9 -5
- package/dist/components/data/tree/tree-item.class.js +1 -1
- package/dist/components/data/tree/tree.class.d.ts +2 -0
- package/dist/components/data/tree/tree.class.js +1 -1
- package/dist/components/forms/button/button.class.d.ts +8 -6
- package/dist/components/forms/button/button.class.js +2 -2
- package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
- package/dist/components/forms/color-picker/color-core.js +1 -1
- package/dist/components/forms/date-picker/date-input.class.d.ts +1 -1
- package/dist/components/forms/date-picker/date-input.class.js +1 -1
- package/dist/components/forms/emoji-picker/emoji-data-loader.js +1 -1
- package/dist/components/forms/icon-button/icon-button.class.d.ts +4 -2
- package/dist/components/forms/icon-button/icon-button.class.js +2 -2
- package/dist/components/forms/input/input-shared.js +2 -2
- package/dist/components/forms/input/number-input-locale.js +1 -0
- package/dist/components/forms/input/number-input.class.d.ts +19 -2
- package/dist/components/forms/input/number-input.class.js +2 -2
- package/dist/components/forms/locale-picker/locale-picker.class.d.ts +3 -3
- package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
- package/dist/components/layout/app-rail-group/app-rail-group.class.js +1 -1
- package/dist/components/layout/details/accordion-item.class.js +1 -1
- package/dist/components/layout/menu/menu.class.js +1 -1
- package/dist/components/layout/multi-split/multi-split.class.js +1 -1
- package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.js +1 -1
- package/dist/components/layout/tab-group/tab-group.class.d.ts +8 -1
- package/dist/components/layout/tab-group/tab-group.class.js +1 -1
- package/dist/components/layout/tab-group/tab.class.d.ts +7 -1
- package/dist/components/layout/tab-group/tab.class.js +1 -1
- package/dist/components/layout/virtual-list/virtual-list.class.d.ts +2 -2
- package/dist/components/layout/virtual-list/virtual-list.class.js +1 -1
- package/dist/components/media/animated-image/animated-image.class.js +1 -1
- package/dist/components/media/attachment-chip/attachment-chip.class.d.ts +21 -14
- package/dist/components/media/attachment-chip/attachment-chip.class.js +1 -1
- package/dist/components/media/attachment-trigger/attachment-trigger.class.d.ts +36 -12
- package/dist/components/media/attachment-trigger/attachment-trigger.class.js +3 -3
- package/dist/components/media/drop-zone/drop-zone.class.d.ts +23 -5
- package/dist/components/media/drop-zone/drop-zone.class.js +2 -2
- package/dist/components/media/drop-zone/drop-zone.styles.js +1 -1
- package/dist/components/media/file-icon/file-icon.class.js +1 -1
- package/dist/components/media/flag/flag-peer-bulk-standard.js +1 -1
- package/dist/components/media/flag/flag-peer-bulk.js +1 -1
- package/dist/components/media/flag/flag-peer.js +1 -1
- package/dist/components/media/flag/flag-url-resolver.js +1 -1
- package/dist/components/media/image-viewer/image-viewer.class.d.ts +2 -2
- package/dist/components/media/image-viewer/image-viewer.class.js +1 -1
- package/dist/components/media/map/map-feature-loader.js +1 -1
- package/dist/components/media/map/map-loader.js +1 -1
- package/dist/components/media/map/map-owned-features.js +1 -1
- package/dist/components/media/map/map-scene-elevated-lines.js +2 -2
- package/dist/components/media/map/map-scene-render-controller.js +1 -1
- package/dist/components/media/map/map.class.d.ts +5 -5
- package/dist/components/media/map/map.class.js +3 -3
- package/dist/components/media/pan-zoom/pan-zoom.class.js +1 -1
- package/dist/components/media/qr-code/qr-code-loader.js +1 -1
- package/dist/components/media/video/video.class.d.ts +3 -3
- package/dist/components/media/video/video.class.js +3 -1
- package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
- package/dist/components/overlays/chip/chip.class.js +1 -1
- package/dist/components/overlays/overlay/dropdown.class.js +1 -1
- package/dist/components/overlays/overlay/tooltip.class.d.ts +5 -1
- package/dist/components/overlays/overlay/tooltip.class.js +3 -3
- package/dist/components/retrieval/embedding-explorer/embedding-explorer-engine.js +1 -1
- package/dist/components/retrieval/graph/graph-engine-adapter.js +1 -1
- package/dist/components/retrieval/graph/graph-loader.js +1 -1
- package/dist/components/retrieval/graph/graph-node-renderer.js +1 -1
- package/dist/components/retrieval/graph/graph-spatial-controller.js +1 -1
- package/dist/components/retrieval/graph/graph.class.d.ts +1 -1
- package/dist/components/retrieval/graph/graph.class.js +1 -1
- package/dist/components/retrieval/mind-map/mind-map.class.js +1 -1
- package/dist/components/retrieval/neighbor-list/neighbor-list.class.d.ts +1 -1
- package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +3 -3
- package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +1 -1
- package/dist/components/utility/icon/dompurify-loader.js +1 -1
- package/dist/components/utility/json-viewer/json-viewer.class.d.ts +16 -1
- package/dist/components/utility/json-viewer/json-viewer.class.js +4 -4
- package/dist/components/utility/json-viewer/json-viewer.styles.js +1 -1
- package/dist/components/utility/known-date/known-date.class.js +1 -1
- package/dist/components/utility/mention-popover/mention-popover.class.js +1 -1
- package/dist/components/viewers/calendar-viewer/calendar-loader.js +1 -1
- package/dist/components/viewers/calendar-viewer/calendar-viewer.class.js +1 -1
- package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
- package/dist/components/viewers/csv-viewer/csv-viewer.class.js +1 -1
- package/dist/components/viewers/dataset-viewer/dataset-viewer.class.js +1 -1
- package/dist/components/viewers/docx-viewer/docx-loader.js +1 -1
- package/dist/components/viewers/docx-viewer/docx-viewer.class.js +1 -1
- package/dist/components/viewers/ebook-viewer/ebook-loader.js +1 -1
- package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
- package/dist/components/viewers/ebook-viewer/epub-unload-guard.js +1 -0
- package/dist/components/viewers/email-viewer/email-loader.js +1 -1
- package/dist/components/viewers/html-viewer/dompurify-loader.js +1 -1
- package/dist/components/viewers/include/include.class.js +1 -1
- package/dist/components/viewers/model-viewer/model-viewer-loader.js +1 -1
- package/dist/components/viewers/model-viewer/model-viewer.class.js +1 -1
- package/dist/components/viewers/notebook-viewer/dompurify-loader.js +1 -1
- package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +1 -1
- package/dist/components/viewers/pdf-viewer/pdf-loader.js +1 -1
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.d.ts +2 -2
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +2 -2
- package/dist/components/viewers/pptx-viewer/pptx-loader.js +1 -1
- package/dist/components/viewers/spreadsheet-viewer/spreadsheet-loader.js +1 -1
- package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.js +1 -1
- package/dist/components/viewers/svg-viewer/dompurify-loader.js +1 -1
- package/dist/components/viewers/table-viewer-shared.js +4 -4
- package/dist/framework-types.d.ts +1 -1
- package/dist/internal/anchored-overlay-runtime.js +1 -1
- package/dist/internal/catalog-picker.js +1 -1
- package/dist/internal/document-tokens.js +2 -2
- package/dist/internal/dompurify-loader.js +1 -1
- package/dist/internal/drop-session-controller.js +1 -1
- package/dist/internal/engine-3d.js +1 -1
- package/dist/internal/icon-only-content.js +1 -1
- package/dist/internal/layered-layout.js +1 -1
- package/dist/internal/locale-loaders.generated.js +1 -1
- package/dist/internal/map-custom-layer-controller.js +1 -1
- package/dist/internal/map-scene-layer-runtime.js +1 -1
- package/dist/internal/media-panorama.js +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/papaparse-loader.js +1 -1
- package/dist/internal/safe-url.js +1 -1
- package/dist/internal/scoped-definitions.generated.js +1 -1
- package/dist/internal/scroll-overflow.js +1 -1
- package/dist/internal/source-window-controller.js +1 -1
- package/dist/internal/text-quote.js +1 -1
- package/dist/internal/viewer-search.js +1 -1
- package/dist/lyra.d.ts +1 -1
- package/dist/sequence-time-binding.js +1 -1
- package/dist/simulation-clock.js +1 -1
- package/dist/styles/reservations.css +1 -1
- package/dist/styles/reservations.styles.js +1 -1
- package/dist/testing/happy-dom-shims.js +1 -1
- package/dist/theme/theme.js +1 -1
- package/dist/theme-core.css +1 -0
- package/dist/utilities/scoped-registry.js +1 -1
- package/llms/components/lr-attachment-chip.md +27 -12
- package/llms/components/lr-attachment-trigger.md +27 -7
- package/llms/components/lr-button.md +6 -4
- package/llms/components/lr-chat-composer.md +13 -7
- package/llms/components/lr-chat-message.md +44 -3
- package/llms/components/lr-chat-viewport.md +39 -2
- package/llms/components/lr-data-grid.md +2 -0
- package/llms/components/lr-dialog.md +10 -0
- package/llms/components/lr-drop-zone.md +26 -2
- package/llms/components/lr-icon-button.md +2 -1
- package/llms/components/lr-json-viewer.md +17 -0
- package/llms/components/lr-locale-picker.md +5 -0
- package/llms/components/lr-markdown-core.md +2 -1
- package/llms/components/lr-markdown.md +20 -4
- package/llms/components/lr-menu.md +3 -1
- package/llms/components/lr-number-input.md +28 -1
- package/llms/components/lr-prompt-input.md +1 -1
- 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 +28 -5
- package/llms/components/lr-tab-group.md +13 -1
- package/llms/components/lr-tab.md +5 -0
- package/llms/components/lr-table.md +25 -4
- package/llms/components/lr-timeline-item.md +1 -1
- package/llms/components/lr-timeline.md +38 -4
- package/llms/components/lr-tooltip.md +3 -1
- package/llms/components/lr-tree.md +4 -0
- package/llms/components/lr-virtual-list.md +1 -0
- package/llms/peers.md +2 -2
- package/llms/shared/ai-and-peers.md +34 -0
- package/llms/shared/forms-and-accessibility.md +21 -4
- package/llms/shared/imports-and-registration.md +2 -0
- package/llms/shared/styles-and-tokens.md +47 -1
- package/llms/shared.md +104 -5
- package/package.json +25 -21
- package/registrations.json +1 -1
|
@@ -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.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`
|
|
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.valueFromNativeText(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.valueFromNativeText(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 nativeInputType(){return this.type==="password"&&this.passwordVisible?"text":this.type}get nativeInputText(){return this.value}valueFromNativeText(text){return text}get constraintControl(){return this.inputEl??null}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.constraintControl;return native?(native.value!==this.value&&(native.value=this.value),native.valueAsNumber):Number.NaN}set valueAsNumber(next){const native=this.constraintControl;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.constraintControl;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=this.valueFromNativeText(input.value))}updateValidity(){const native=this.constraintControl;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("required")||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(" "),showPasswordToggle=this.type==="password"&&this.passwordToggle,nativeType=this.nativeInputType,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"
|
|
@@ -38,7 +38,7 @@ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,quer
|
|
|
38
38
|
minlength=${this.minlength??nothing}
|
|
39
39
|
maxlength=${this.maxlength??nothing}
|
|
40
40
|
pattern=${this.pattern??nothing}
|
|
41
|
-
.value=${this.
|
|
41
|
+
.value=${this.nativeInputText}
|
|
42
42
|
?required=${this.required}
|
|
43
43
|
?disabled=${this.effectiveDisabled}
|
|
44
44
|
?readonly=${this.readonly}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{getNumberFormat}from"../../../internal/intl-cache.js";const SPACE_GROUPS=[" "," "," "],APOSTROPHE_GROUPS=["'","’"],BIDI_MARKS=/[]/g,MINUS_SIGNS=new Set(["-","−"]),CANONICAL_DECIMAL=/^(-?)(\d*)(?:\.(\d*))?$/,ASCII_DIGIT=/^[0-9]$/,symbolCache=new Map;function groupSizes(formatter){const integerRuns=formatter.formatToParts(1234567890).filter(part=>part.type==="integer").map(part=>part.value.length);if(integerRuns.length<2)return{primary:3,secondary:3};const primary=integerRuns[integerRuns.length-1],secondary=integerRuns.length>2?integerRuns[integerRuns.length-2]:primary;return{primary,secondary}}function localeNumberSymbols(locale){const cached=symbolCache.get(locale);if(cached)return cached;const formatter=getNumberFormat(locale,{useGrouping:!0}),decimal=formatter.formatToParts(1.5).find(part=>part.type==="decimal")?.value??".",group=formatter.formatToParts(1234567).find(part=>part.type==="group")?.value??",",groups=new Set([group]);if(SPACE_GROUPS.includes(group))for(const space of SPACE_GROUPS)groups.add(space);if(APOSTROPHE_GROUPS.includes(group))for(const mark of APOSTROPHE_GROUPS)groups.add(mark);const{primary,secondary}=groupSizes(formatter),plain=getNumberFormat(locale,{useGrouping:!1}),digits=new Map;for(let digit=0;digit<=9;digit+=1){const localDigit=plain.format(digit);localDigit!==String(digit)&&digits.set(localDigit,String(digit))}const negativeParts=formatter.formatToParts(-1),integerIndex=negativeParts.findIndex(part=>part.type==="integer"),negativePrefix=negativeParts.slice(0,Math.max(integerIndex,0)).map(part=>part.value).join("")||"-",symbols={decimal,groups,primaryGroup:primary,secondaryGroup:secondary,digits,negativePrefix};return symbolCache.set(locale,symbols),symbols}function validGrouping(chunks,symbols){if(chunks.length<2)return!0;const last=chunks.length-1;return chunks.every((chunk,index)=>index===last?chunk.length===symbols.primaryGroup:index===0?chunk.length>=1&&chunk.length<=symbols.secondaryGroup:chunk.length===symbols.secondaryGroup)}function parseLocaleNumber(text,locale){const symbols=localeNumberSymbols(locale);let rest=text.replace(BIDI_MARKS,"").trim();if(rest==="")return"";let negative=!1;const first=rest[0];(MINUS_SIGNS.has(first)||first==="+")&&(negative=first!=="+",rest=rest.slice(1).trimStart());let integer="",fraction=null;const chunks=[""];let groupPending=!1;for(const char of rest){const digit=ASCII_DIGIT.test(char)?char:symbols.digits.get(char);if(digit!==void 0){fraction===null?(integer+=digit,chunks[chunks.length-1]+=digit):fraction+=digit,groupPending=!1;continue}if(char===symbols.decimal&&fraction===null&&!groupPending){fraction="";continue}if(symbols.groups.has(char)&&fraction===null&&integer!==""&&!groupPending){chunks.push(""),groupPending=!0;continue}return null}if(groupPending||!validGrouping(chunks,symbols)||integer===""&&(fraction===null||fraction===""))return null;const whole=integer===""?"0":integer,canonical=fraction?`${whole}.${fraction}`:whole;return negative?`-${canonical}`:canonical}function formatLocaleNumber(value,locale){const match=CANONICAL_DECIMAL.exec(value);if(!match||match[2]===""&&!match[3])return value;const[,sign,integer,fraction]=match,symbols=localeNumberSymbols(locale),wholeText=getNumberFormat(locale,{useGrouping:!0,maximumFractionDigits:0}).format(BigInt(integer||"0"));let fractionText="";if(fraction){const localDigits=new Map(Array.from(symbols.digits,([local,ascii])=>[ascii,local]));fractionText=symbols.decimal+Array.from(fraction,digit=>localDigits.get(digit)??digit).join("")}return`${sign?symbols.negativePrefix:""}${wholeText}${fractionText}`}export{formatLocaleNumber,localeNumberSymbols,parseLocaleNumber};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{nothing,type TemplateResult}from'lit';import{LyraInput}from'./input.class.js';import type{LyraInputEventMap}from'./input-shared.js';import type{LyraAppearance}from'../../../internal/variants.js';import type{LyraFormValidator}from'../form-validator.js';
|
|
1
|
+
import{nothing,type PropertyValues,type TemplateResult}from'lit';import{LyraInput}from'./input.class.js';import type{LyraInputEventMap}from'./input-shared.js';import type{LyraAppearance}from'../../../internal/variants.js';import type{LyraFormValidator}from'../form-validator.js';
|
|
2
2
|
/** Number-input events, including the native cancelable edit veto exposed by its mapped API.*/
|
|
3
3
|
export interface LyraNumberInputEventMap extends LyraInputEventMap{beforeinput:InputEvent;}
|
|
4
4
|
/**
|
|
@@ -25,6 +25,14 @@ export interface LyraNumberInputEventMap extends LyraInputEventMap{beforeinput:I
|
|
|
25
25
|
* larger control heights. The mirrored `small`, `medium`, and `large` spellings render exactly as
|
|
26
26
|
* canonical `s`, `m`, and `l`, including row height, padding, and native-input font size.
|
|
27
27
|
*
|
|
28
|
+
* `localized` opts into locale-aware entry: the field then reads and shows numbers with the
|
|
29
|
+
* grouping and decimal separators of the effective locale (`25.000` and `10,24` in `de`), while
|
|
30
|
+
* `value`, the submitted form value, `valueAsNumber` and range/step validity keep the native
|
|
31
|
+
* `type="number"` form (`25000`, `10.24`). The internal input becomes a text field with spinbutton
|
|
32
|
+
* semantics; ArrowUp/ArrowDown step the value as the native field does. Grouping is checked, so
|
|
33
|
+
* text the locale would not write (`10.24` in `de`, `10,24` in `en`) reports `badInput` instead
|
|
34
|
+
* of being misread. Typed text stays as entered until `change` or blur, which re-format it.
|
|
35
|
+
*
|
|
28
36
|
* Inherited stepUp/stepDown use pending value, step, min, and max properties synchronously
|
|
29
37
|
* and remain event-silent. Removed label/hint/help-text/error-text content is safely omitted.
|
|
30
38
|
*
|
|
@@ -49,6 +57,12 @@ export interface LyraNumberInputEventMap extends LyraInputEventMap{beforeinput:I
|
|
|
49
57
|
export declare class LyraNumberInput extends LyraInput{
|
|
50
58
|
/** Public WA-compatible catalog, inherited without narrowing its accepted base-input type.*/
|
|
51
59
|
static get validators():LyraFormValidator<LyraInput>[];static styles:import("lit").CSSResultGroup[];protected get inputWrapperParts():string;
|
|
60
|
+
/** Reads and shows numbers with the grouping and decimal separators of the effective locale
|
|
61
|
+
* (`lang`/`locale`), e.g. `25.000` and `10,24` in `de`. `value` and the submitted form value stay
|
|
62
|
+
* in the native `type="number"` form (`25000`, `10.24`). Unset (the default) keeps the native
|
|
63
|
+
* number field unchanged. Pair it with `inputmode="decimal"` when fractions are expected, so
|
|
64
|
+
* touch keyboards offer the decimal separator. */
|
|
65
|
+
localized:boolean;
|
|
52
66
|
/** Hides the increment/decrement pair for a bare numeric field.*/
|
|
53
67
|
withoutSteppers:boolean;
|
|
54
68
|
/** Numeric inputs use the outlined field treatment by default.*/
|
|
@@ -60,4 +74,7 @@ step:number|'any'|undefined;
|
|
|
60
74
|
/** Defaults to `true` here (unlike `<lr-input>`) so the component's own steppers are not shown
|
|
61
75
|
* alongside the browser's built-in spin buttons. `without-spin-buttons="false"` brings the
|
|
62
76
|
* native pair back. */
|
|
63
|
-
withoutSpinButtons:boolean;
|
|
77
|
+
withoutSpinButtons:boolean;private draftText;private pendingTextEdit?;private localizedProbe?;constructor();get value():string;set value(next:string|null);protected get nativeInputType():string;protected get nativeInputText():string;protected valueFromNativeText(text:string):string;
|
|
78
|
+
/** A detached `type="number"` input carrying the live constraints, so a localized field keeps
|
|
79
|
+
* the platform's own stepping, `valueAsNumber` and range/step/required validity. */
|
|
80
|
+
protected get constraintControl():HTMLInputElement|null;private get hasUnparsedDraft();protected updateValidity():void;private commitDraft;private onLocalizedKeyDown;protected updated(changed:PropertyValues):void;private syncSpinbuttonSemantics;connectedCallback():void;private syncMappedStates;private onFocusWithin;private onBlurWithin;private stepFromButton;private onStepUp;private onStepDown;protected renderControls():TemplateResult|typeof nothing;}declare global{interface HTMLElementTagNameMap{'lr-number-input':LyraNumberInput;}}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{chevronIcon}from"../../../internal/icons.js";import{presenceTrueDefaultBooleanConverter}from"../../../internal/converters.js";import{LyraInput}from"./input.class.js";import{dispatchNativeEvent,dispatchNativeInputEvent}from"../../../internal/native-event-relay.js";import{setCustomState}from"../../../internal/custom-states.js";import{styles as numberInputStyles}from"./number-input.styles.js";import{LYRA_DEFAULT_numberInputDecrease,LYRA_DEFAULT_numberInputIncrease}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings/shared.generated.js";class LyraNumberInput extends LyraInput{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,numberInputDecrease:LYRA_DEFAULT_numberInputDecrease,numberInputIncrease:LYRA_DEFAULT_numberInputIncrease}}static get validators(){return super.validators}static{this.styles=[...LyraInput.styles,numberInputStyles]}get inputWrapperParts(){return`${super.inputWrapperParts} number-input`}constructor(){super(),this.withoutSteppers=!1,this.appearance="outlined",this.inputMode="numeric",this.step=1,this.withoutSpinButtons=!0,this.onFocusWithin=()=>{setCustomState(this.internals,"focused",!0)},this.onBlurWithin=()=>{setCustomState(this.internals,"focused",!1)},this.onStepUp=()=>{this.stepFromButton("up")},this.onStepDown=()=>{this.stepFromButton("down")},this.type="number",this.addEventListener("focusin",this.onFocusWithin),this.addEventListener("focusout",this.onBlurWithin)}connectedCallback(){super.connectedCallback(),this.type="number",this.syncMappedStates()}syncMappedStates(){setCustomState(this.internals,"blank",this.value==="")}stepFromButton(direction){if(this.effectiveDisabled||this.readonly)return;const before=this.value;direction==="up"?this.stepUp():this.stepDown(),this.value!==before&&(dispatchNativeInputEvent(this,{inputType:"insertReplacementText"}),this.emit("lr-input",{value:this.value}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value})),this.input?.focus()}renderControls(){if(this.withoutSteppers)return nothing;const inert=this.effectiveDisabled||this.readonly;return html`
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{chevronIcon}from"../../../internal/icons.js";import{presenceTrueDefaultBooleanConverter}from"../../../internal/converters.js";import{LyraInput}from"./input.class.js";import{dispatchNativeEvent,dispatchNativeInputEvent}from"../../../internal/native-event-relay.js";import{setCustomState}from"../../../internal/custom-states.js";import{styles as numberInputStyles}from"./number-input.styles.js";import{isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY}from"../../../internal/anchored-validity.js";import{formatLocaleNumber,parseLocaleNumber}from"./number-input-locale.js";import{LYRA_DEFAULT_numberInputDecrease,LYRA_DEFAULT_numberInputIncrease}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings/shared.generated.js";class LyraNumberInput extends LyraInput{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,numberInputDecrease:LYRA_DEFAULT_numberInputDecrease,numberInputIncrease:LYRA_DEFAULT_numberInputIncrease,valueInvalid:LYRA_DEFAULT_valueInvalid}}static get validators(){return super.validators}static{this.styles=[...LyraInput.styles,numberInputStyles]}get inputWrapperParts(){return`${super.inputWrapperParts} number-input`}constructor(){super(),this.localized=!1,this.withoutSteppers=!1,this.appearance="outlined",this.inputMode="numeric",this.step=1,this.withoutSpinButtons=!0,this.draftText=null,this.commitDraft=()=>{this.draftText===null||this.hasUnparsedDraft||(this.draftText=null,this.requestUpdate())},this.onLocalizedKeyDown=event=>{!this.localized||event.defaultPrevented||event.altKey||event.ctrlKey||event.metaKey||event.key!=="ArrowUp"&&event.key!=="ArrowDown"||event.composedPath()[0]===this.input&&(event.preventDefault(),this.stepFromButton(event.key==="ArrowUp"?"up":"down"))},this.onFocusWithin=()=>{setCustomState(this.internals,"focused",!0)},this.onBlurWithin=()=>{setCustomState(this.internals,"focused",!1),this.commitDraft()},this.onStepUp=()=>{this.stepFromButton("up")},this.onStepDown=()=>{this.stepFromButton("down")},this.type="number",this.addEventListener("focusin",this.onFocusWithin),this.addEventListener("focusout",this.onBlurWithin),this.addEventListener("change",this.commitDraft),this.addEventListener("keydown",this.onLocalizedKeyDown)}get value(){return super.value}set value(next){const edit=this.pendingTextEdit;this.pendingTextEdit=void 0,this.draftText=edit!==void 0&&edit.value===(next??"")?edit.text:null,super.value=next}get nativeInputType(){return this.localized?"text":super.nativeInputType}get nativeInputText(){return this.localized?this.draftText??formatLocaleNumber(this.value,this.effectiveLocale):super.nativeInputText}valueFromNativeText(text){if(!this.localized)return super.valueFromNativeText(text);const value=parseLocaleNumber(text,this.effectiveLocale)??"";return this.pendingTextEdit={text,value},value}get constraintControl(){const rendered=super.constraintControl;if(!this.localized||!rendered)return rendered;const probe=this.localizedProbe??=this.ownerDocument.createElement("input");return probe.type="number",probe.min=this.min==null?"":String(this.min),probe.max=this.max==null?"":String(this.max),probe.step=this.step==null?"":String(this.step),probe.required=this.required,probe}get hasUnparsedDraft(){return this.localized&&this.draftText!==null&&parseLocaleNumber(this.draftText,this.effectiveLocale)===null}updateValidity(){if(this.hasUnparsedDraft&&!isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({badInput:!0},this.localize("valueInvalid"));return}super.updateValidity()}updated(changed){super.updated(changed),changed.has("localized")&&this.updateValidity(),this.syncSpinbuttonSemantics()}syncSpinbuttonSemantics(){const native=this.input;if(!native)return;const attributes={role:null,"aria-valuenow":null,"aria-valuetext":null,"aria-valuemin":null,"aria-valuemax":null};if(this.localized){const number=this.valueAsNumber,min=Number(this.min),max=Number(this.max);attributes.role="spinbutton",attributes["aria-valuenow"]=Number.isFinite(number)?String(number):null,attributes["aria-valuetext"]=native.value===""?null:native.value,attributes["aria-valuemin"]=this.min!=null&&String(this.min)!==""&&Number.isFinite(min)?String(min):null,attributes["aria-valuemax"]=this.max!=null&&String(this.max)!==""&&Number.isFinite(max)?String(max):null}for(const[name,value]of Object.entries(attributes))value===null?native.removeAttribute(name):native.getAttribute(name)!==value&&native.setAttribute(name,value)}connectedCallback(){super.connectedCallback(),this.type="number",this.syncMappedStates()}syncMappedStates(){setCustomState(this.internals,"blank",this.value==="")}stepFromButton(direction){if(this.effectiveDisabled||this.readonly)return;const before=this.value;direction==="up"?this.stepUp():this.stepDown(),this.value!==before&&(dispatchNativeInputEvent(this,{inputType:"insertReplacementText"}),this.emit("lr-input",{value:this.value}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value})),this.input?.focus()}renderControls(){if(this.withoutSteppers)return nothing;const inert=this.effectiveDisabled||this.readonly;return html`
|
|
2
2
|
<button
|
|
3
3
|
part="stepper stepper-decrement stepper-down"
|
|
4
4
|
type="button"
|
|
@@ -19,4 +19,4 @@ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property}from
|
|
|
19
19
|
>
|
|
20
20
|
<span aria-hidden="true" inert><slot name="increment-icon">${chevronIcon()}</slot></span>
|
|
21
21
|
</button>
|
|
22
|
-
`}}__decorate([property({type:Boolean,attribute:"without-steppers"})],LyraNumberInput.prototype,"withoutSteppers",void 0),__decorate([property({reflect:!0})],LyraNumberInput.prototype,"appearance",void 0),__decorate([property({attribute:"inputmode"})],LyraNumberInput.prototype,"inputMode",void 0),__decorate([property()],LyraNumberInput.prototype,"step",void 0),__decorate([property({attribute:"without-spin-buttons",converter:presenceTrueDefaultBooleanConverter,reflect:!0})],LyraNumberInput.prototype,"withoutSpinButtons",void 0);export{LyraNumberInput};
|
|
22
|
+
`}}__decorate([property({type:Boolean,reflect:!0})],LyraNumberInput.prototype,"localized",void 0),__decorate([property({type:Boolean,attribute:"without-steppers"})],LyraNumberInput.prototype,"withoutSteppers",void 0),__decorate([property({reflect:!0})],LyraNumberInput.prototype,"appearance",void 0),__decorate([property({attribute:"inputmode"})],LyraNumberInput.prototype,"inputMode",void 0),__decorate([property()],LyraNumberInput.prototype,"step",void 0),__decorate([property({attribute:"without-spin-buttons",converter:presenceTrueDefaultBooleanConverter,reflect:!0})],LyraNumberInput.prototype,"withoutSpinButtons",void 0);export{LyraNumberInput};
|
|
@@ -84,8 +84,8 @@ export interface LyraLocaleChangeDetail{value:string;previousValue:string;direct
|
|
|
84
84
|
*
|
|
85
85
|
* @customElement lr-locale-picker
|
|
86
86
|
* @event lr-show - Cancelable before an ordinary popup opening. Preventing it retains the closed state.
|
|
87
|
-
* @event lr-hide - Conditionally cancelable before closing.
|
|
88
|
-
*
|
|
87
|
+
* @event lr-hide - Conditionally cancelable before closing. Disablement, disconnect, and failed
|
|
88
|
+
* positioning force-close with a non-cancelable notification; ordinary closes can be vetoed.
|
|
89
89
|
* @event lr-after-show - The current opening finished positioning and its transition settled.
|
|
90
90
|
* @event lr-after-hide - The current closing settled and left layout. Not emitted after disconnect.
|
|
91
91
|
* @event lr-change-request - Cancelable before selection, popup, and global locale changes. Same detail as `lr-change`.
|
|
@@ -264,7 +264,7 @@ get open():boolean;set open(next:boolean);
|
|
|
264
264
|
* tag rename with no attribute rewrite. */
|
|
265
265
|
size:LyraSize;private activeIndex;private searchQuery;private touched;private readonly slotPresence;private registryTick;private triggerElement?;private searchElement?;private searchAnnouncements?;private searchFocusGeneration;private internals;private validityController;
|
|
266
266
|
/** Consumer-supplied validation message reflected through `custom-error`.*/
|
|
267
|
-
customError:string|null;private listId;private controlId;private cleanup?;private placedTopLayer?;private listboxHidden;private openGeneration;private suppressedOpenGeneration?;private openVetoed;private openTransition?;private lifecycleMounted;private lastRenderedOpen;private announcingHide;private restoreFocusOnClose;private overlayHandle?;private readonly popupController;private stopRegistrySubscription?;private _value;private _open;private _fieldsetDisabled;private _name;private _disabled;private _required;private _defaultValue;private _valueDirty;private settingDefaultValue;private reflectingDefaultValue;private readonly typeBuffer;private activeScrollGeneration;private localizedValidityLocale;private localizedIntrinsicMessage;constructor();private get liveDisabled();
|
|
267
|
+
customError:string|null;private listId;private controlId;private cleanup?;private placedTopLayer?;private listboxHidden;private openGeneration;private suppressedOpenGeneration?;private forcedCloseGeneration?;private openVetoed;private openTransition?;private lifecycleMounted;private lastRenderedOpen;private announcingHide;private restoreFocusOnClose;private overlayHandle?;private readonly popupController;private stopRegistrySubscription?;private _value;private _open;private _fieldsetDisabled;private _name;private _disabled;private _required;private _defaultValue;private _valueDirty;private settingDefaultValue;private reflectingDefaultValue;private readonly typeBuffer;private activeScrollGeneration;private localizedValidityLocale;private localizedIntrinsicMessage;constructor();private get liveDisabled();
|
|
268
268
|
/** Focus the internal trigger unless the form control is effectively disabled.*/
|
|
269
269
|
focus(options?:FocusOptions):void;
|
|
270
270
|
/** Blur the internal trigger or the optional focused search input.*/
|
|
@@ -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)}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
|
|
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"]');if(anchor&&listbox){this.placedTopLayer=syncTopLayerRelease(listbox,this.placedTopLayer,this.topLayer);const operation=place(anchor,listbox,topLayerPlacement(this.topLayer,resolveEffectivePositioningStrategy(this,void 0,"fixed")));this.cleanup=operation,operation.ready.then(positioned=>{!positioned&&this.cleanup===operation&&this.open&&(this.open=!1,this.forcedCloseGeneration=this.openGeneration)})}}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||this.forcedCloseGeneration===generation)?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"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{nextId}from"../../../internal/a11y.js";import{repairComposedFocus}from"../../../internal/focus-navigation.js";import{chevronIcon}from"../../../internal/icons.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{LyraElement}from"../../../internal/lyra-element.js";import{resolveHeadingLevel}from"../../../internal/heading-level.js";import{tag}from"../../../internal/prefix.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{styles}from"./app-rail-group.styles.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_expand}from"../../../internal/default-strings/shared.generated.js";class LyraAppRailGroup extends LyraElement{constructor(){super(...arguments),this.heading="",this.headingLevel="3",this.collapsible=!1,this._collapsed=!1,this.toggleGuard=new VetoWriteGuard,this.hasHeadingSlot=!1,this.hasHeaderActionsSlot=!1,this.headingId=nextId("app-rail-group-heading"),this.contentId=nextId("app-rail-group-content"),this.onHeadingSlotChange=event=>{this.applyHeadingSlotPresence(event.target)},this.onHeaderActionsSlotChange=event=>{this.applyHeaderActionsSlotPresence(event.target)},this.onContentSlotChange=()=>{this.syncOwnedItems()},this.onToggleClick=()=>{const expanded=this._collapsed;requestThenCommit({requestDetail:{expanded},emitRequest:(detail,init)=>this.emit("lr-toggle-request",detail,init),guard:this.toggleGuard,commit:()=>{this.collapsed=!expanded,this.emit("lr-toggle",{expanded})}})}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,expand:LYRA_DEFAULT_expand}}static{this.styles=[LyraElement.styles,styles]}static get observedAttributes(){return[...super.observedAttributes,"icon-only"]}get collapsed(){return this._collapsed}set collapsed(next){const old=this._collapsed;this._collapsed=next,markVetoGuardWrite(this.toggleGuard),this.requestUpdate("collapsed",old)}get safeHeadingLevel(){return resolveHeadingLevel(this.headingLevel)}connectedCallback(){super.connectedCallback(),this.syncOwnedItems()}attributeChangedCallback(name,oldValue,newValue){super.attributeChangedCallback(name,oldValue,newValue),!(name!=="icon-only"||oldValue===newValue)&&(this.syncOwnedItems(),this.requestUpdate())}willUpdate(changed){super.willUpdate(changed);const content=this.renderRoot?.querySelector('[part="content"]');changed.has("collapsed")&&this._collapsed&&content&&repairComposedFocus(content,()=>this.renderRoot.querySelector('[part="toggle"]'))}updated(changed){super.updated(changed),this.syncOwnedItems()}firstUpdated(changed){super.firstUpdated(changed);const headingSlot=this.headingSlot,headerActionsSlot=this.headerActionsSlot;queueMicrotask(()=>{collectInitialSlotAssignment(headingSlot,s=>this.applyHeadingSlotPresence(s)),collectInitialSlotAssignment(headerActionsSlot,s=>this.applyHeaderActionsSlotPresence(s))})}syncOwnedItems(){if(!this.isConnected)return;const iconOnly=this.hasAttribute("icon-only"),groupTag=tag("app-rail-group");for(const node of this.querySelectorAll(`${tag("app-rail-item")}, ${groupTag}`))(node.parentElement?.closest(groupTag)??null)===this&&node.toggleAttribute("icon-only",iconOnly)}applyHeadingSlotPresence(slot){this.hasHeadingSlot=slot.assignedNodes().length>0&&slot.assignedNodes({flatten:!0}).length>0}applyHeaderActionsSlotPresence(slot){this.hasHeaderActionsSlot=slot.assignedNodes({flatten:!0}).some(node=>node.nodeType!==3||(node.textContent??"").trim()!=="")}render(){const named=this.hasHeadingSlot||this.heading
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{nextId}from"../../../internal/a11y.js";import{repairComposedFocus}from"../../../internal/focus-navigation.js";import{chevronIcon}from"../../../internal/icons.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{LyraElement}from"../../../internal/lyra-element.js";import{resolveHeadingLevel}from"../../../internal/heading-level.js";import{tag}from"../../../internal/prefix.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{styles}from"./app-rail-group.styles.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_expand}from"../../../internal/default-strings/shared.generated.js";class LyraAppRailGroup extends LyraElement{constructor(){super(...arguments),this.heading="",this.headingLevel="3",this.collapsible=!1,this._collapsed=!1,this.toggleGuard=new VetoWriteGuard,this.hasHeadingSlot=!1,this.hasHeaderActionsSlot=!1,this.headingId=nextId("app-rail-group-heading"),this.contentId=nextId("app-rail-group-content"),this.onHeadingSlotChange=event=>{this.applyHeadingSlotPresence(event.target)},this.onHeaderActionsSlotChange=event=>{this.applyHeaderActionsSlotPresence(event.target)},this.onContentSlotChange=()=>{this.syncOwnedItems()},this.onToggleClick=()=>{const expanded=this._collapsed;requestThenCommit({requestDetail:{expanded},emitRequest:(detail,init)=>this.emit("lr-toggle-request",detail,init),guard:this.toggleGuard,commit:()=>{this.collapsed=!expanded,this.emit("lr-toggle",{expanded})}})}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,expand:LYRA_DEFAULT_expand}}static{this.styles=[LyraElement.styles,styles]}static get observedAttributes(){return[...super.observedAttributes,"icon-only"]}get collapsed(){return this._collapsed}set collapsed(next){const old=this._collapsed;this._collapsed=next,markVetoGuardWrite(this.toggleGuard),this.requestUpdate("collapsed",old)}get safeHeadingLevel(){return resolveHeadingLevel(this.headingLevel)}connectedCallback(){super.connectedCallback(),this.syncOwnedItems()}attributeChangedCallback(name,oldValue,newValue){super.attributeChangedCallback(name,oldValue,newValue),!(name!=="icon-only"||oldValue===newValue)&&(this.syncOwnedItems(),this.requestUpdate())}willUpdate(changed){super.willUpdate(changed);const content=this.renderRoot?.querySelector('[part="content"]');changed.has("collapsed")&&this._collapsed&&content&&repairComposedFocus(content,()=>this.renderRoot.querySelector('[part="toggle"]'))}updated(changed){super.updated(changed),this.syncOwnedItems()}firstUpdated(changed){super.firstUpdated(changed);const headingSlot=this.headingSlot,headerActionsSlot=this.headerActionsSlot;queueMicrotask(()=>{collectInitialSlotAssignment(headingSlot,s=>this.applyHeadingSlotPresence(s)),collectInitialSlotAssignment(headerActionsSlot,s=>this.applyHeaderActionsSlotPresence(s))})}syncOwnedItems(){if(!this.isConnected)return;const iconOnly=this.hasAttribute("icon-only"),groupTag=tag("app-rail-group");for(const node of this.querySelectorAll(`${tag("app-rail-item")}, ${groupTag}`))(node.parentElement?.closest(groupTag)??null)===this&&node.toggleAttribute("icon-only",iconOnly)}applyHeadingSlotPresence(slot){this.hasHeadingSlot=slot.assignedNodes().length>0&&slot.assignedNodes({flatten:!0}).length>0}applyHeaderActionsSlotPresence(slot){this.hasHeaderActionsSlot=slot.assignedNodes({flatten:!0}).some(node=>node.nodeType!==3||(node.textContent??"").trim()!=="")}render(){const named=this.hasHeadingSlot||(this.heading?.trim()??"")!=="",headingContent=html`<span part="heading-text"
|
|
2
2
|
><slot name="heading" @slotchange=${this.onHeadingSlotChange}
|
|
3
3
|
>${this.hasHeadingSlot?nothing:this.heading}</slot
|
|
4
4
|
></span
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{attachInternalsSafely}from"../../../internal/element-internals.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{resolveHeadingLevel}from"../../../internal/heading-level.js";import{LyraElement}from"../../../internal/lyra-element.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./accordion-item.styles.js";import{DisclosureMotionController}from"./disclosure-motion.js";import{accordionItemOwnerContext,notifyAccordionItemStateChanged,notifyAccordionItemTransitionSettled,registerAccordionItemStateController,requestAccordionItemTransition}from"./accordion-owner.js";import{LYRA_DEFAULT_details}from"../../../internal/default-strings/shared.generated.js";class LyraAccordionItem extends LyraElement{static{this.defaultStrings={...super.defaultStrings,details:LYRA_DEFAULT_details}}static{this.styles=[LyraElement.styles,sizes,styles]}constructor(){super(),this.itemInternals=attachInternalsSafely(this),this.disclosureMotion=new DisclosureMotionController(this,this.itemInternals,()=>this.renderRoot,'[part~="accordion-item"]'),this._expanded=!1,this.hasLabel=!1,this.settledClosed=!0,this.label="",this.disabled=!1,this.headingLevel="3",this.iconPlacement="end",this.appearance="outlined",this.isTabbable=!0,this.onTrigger=()=>{this.disabled||this.transitionTo(!this.expanded,"user")},this.onLabel=event=>{this.hasLabel=event.target.assignedElements({flatten:!0}).length>0},this.onBeforeMatch=event=>{const clip=event.currentTarget;this.transitionTo(!0,"user"),queueMicrotask(()=>{!this._expanded&&this.settledClosed&&clip.setAttribute("hidden","until-found")})},registerAccordionItemStateController(this,(expanded,announce)=>this.transitionTo(expanded,"programmatic",!0,announce))}get expanded(){return this._expanded}set expanded(next){const normalized=!!next;if(normalized!==this._expanded){if(!this.hasUpdated){this.applyExpandedState(normalized);return}this.transitionTo(normalized,"programmatic")}}disconnectedCallback(){this.disclosureMotion.cancel(),this.settledClosed=!this._expanded,super.disconnectedCallback()}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasLabel=Array.from(this.children).some(child=>child.getAttribute("slot")==="label"))}updated(changed){super.updated(changed),changed.has("disabled")&¬ifyAccordionItemStateChanged(this)}applyExpandedState(next){const old=this._expanded,panel=this.renderRoot?.querySelector("#panel");next?this.settledClosed=!1:panel&&this.disclosureMotion.repairFocus(panel,this.button),this._expanded=next,this.requestUpdate("expanded",old)}syncExpandedAttribute(){this.toggleAttribute("expanded",this._expanded)}async transitionTo(expanded,source,ownerPreflighted=!1,announceOwner=!0){if(expanded!==this._expanded){if(!ownerPreflighted&&this.disabled){this.syncExpandedAttribute();return}if(!ownerPreflighted&&requestAccordionItemTransition(this,expanded,source)===!1){this.syncExpandedAttribute();return}this.applyExpandedState(expanded),await this.disclosureMotion.settle()&&(this.settledClosed=!this._expanded,announceOwner&¬ifyAccordionItemTransitionSettled(this,expanded))}}expand(){return this.transitionTo(!0,"programmatic")}collapse(){return this.transitionTo(!1,"programmatic")}toggle(){return this.transitionTo(!this.expanded,"programmatic")}focus(options){this.button?.focus(options)}click(){const trigger=this.button;trigger?trigger.click():super.click()}get button(){return this.renderRoot
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{attachInternalsSafely}from"../../../internal/element-internals.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{resolveHeadingLevel}from"../../../internal/heading-level.js";import{LyraElement}from"../../../internal/lyra-element.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./accordion-item.styles.js";import{DisclosureMotionController}from"./disclosure-motion.js";import{accordionItemOwnerContext,notifyAccordionItemStateChanged,notifyAccordionItemTransitionSettled,registerAccordionItemStateController,requestAccordionItemTransition}from"./accordion-owner.js";import{LYRA_DEFAULT_details}from"../../../internal/default-strings/shared.generated.js";class LyraAccordionItem extends LyraElement{static{this.defaultStrings={...super.defaultStrings,details:LYRA_DEFAULT_details}}static{this.styles=[LyraElement.styles,sizes,styles]}constructor(){super(),this.itemInternals=attachInternalsSafely(this),this.disclosureMotion=new DisclosureMotionController(this,this.itemInternals,()=>this.renderRoot,'[part~="accordion-item"]'),this._expanded=!1,this.hasLabel=!1,this.settledClosed=!0,this.label="",this.disabled=!1,this.headingLevel="3",this.iconPlacement="end",this.appearance="outlined",this.isTabbable=!0,this.onTrigger=()=>{this.disabled||this.transitionTo(!this.expanded,"user")},this.onLabel=event=>{this.hasLabel=event.target.assignedElements({flatten:!0}).length>0},this.onBeforeMatch=event=>{const clip=event.currentTarget;this.transitionTo(!0,"user"),queueMicrotask(()=>{!this._expanded&&this.settledClosed&&clip.setAttribute("hidden","until-found")})},registerAccordionItemStateController(this,(expanded,announce)=>this.transitionTo(expanded,"programmatic",!0,announce))}get expanded(){return this._expanded}set expanded(next){const normalized=!!next;if(normalized!==this._expanded){if(!this.hasUpdated){this.applyExpandedState(normalized);return}this.transitionTo(normalized,"programmatic")}}disconnectedCallback(){this.disclosureMotion.cancel(),this.settledClosed=!this._expanded,super.disconnectedCallback()}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasLabel=Array.from(this.children).some(child=>child.getAttribute("slot")==="label"))}updated(changed){super.updated(changed),changed.has("disabled")&¬ifyAccordionItemStateChanged(this)}applyExpandedState(next){const old=this._expanded,panel=this.renderRoot?.querySelector("#panel");next?this.settledClosed=!1:panel&&this.disclosureMotion.repairFocus(panel,this.button),this._expanded=next,this.requestUpdate("expanded",old)}syncExpandedAttribute(){this.toggleAttribute("expanded",this._expanded)}async transitionTo(expanded,source,ownerPreflighted=!1,announceOwner=!0){if(expanded!==this._expanded){if(!ownerPreflighted&&this.disabled){this.syncExpandedAttribute();return}if(!ownerPreflighted&&requestAccordionItemTransition(this,expanded,source)===!1){this.syncExpandedAttribute();return}this.applyExpandedState(expanded),await this.disclosureMotion.settle()&&(this.settledClosed=!this._expanded,announceOwner&¬ifyAccordionItemTransitionSettled(this,expanded))}}expand(){return this.transitionTo(!0,"programmatic")}collapse(){return this.transitionTo(!1,"programmatic")}toggle(){return this.transitionTo(!this.expanded,"programmatic")}focus(options){this.button?.focus(options)}click(){const trigger=this.button;trigger?trigger.click():super.click()}get button(){return this.renderRoot?.querySelector('[part~="button"]')??null}heading(level,button){switch(level){case"1":return html`<h1 part="heading">${button}</h1>`;case"2":return html`<h2 part="heading">${button}</h2>`;case"4":return html`<h4 part="heading">${button}</h4>`;case"5":return html`<h5 part="heading">${button}</h5>`;case"6":return html`<h6 part="heading">${button}</h6>`;default:return html`<h3 part="heading">${button}</h3>`}}get effectiveAppearance(){return accordionItemOwnerContext(this)?.appearance??this.appearance}get effectiveHeadingLevel(){return accordionItemOwnerContext(this)?.headingLevel??this.headingLevel}get effectiveIconPlacement(){return accordionItemOwnerContext(this)?.iconPlacement??this.iconPlacement}render(){const fallbackLabel=this.label||this.localize("details"),hostLabel=hostAriaLabel(this),level=resolveHeadingLevel(this.effectiveHeadingLevel),button=html`<button
|
|
2
2
|
id="trigger"
|
|
3
3
|
part="button"
|
|
4
4
|
type="button"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var _a;import{__decorate}from"tslib";import{resolveIntlLocale}from"../../../internal/intl-cache.js";import{maxCssTime}from"../../../internal/css-motion-time.js";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{deferredPlaceReady as place,syncTopLayerRelease,topLayerPlacement,waitForDeferredPlacement}from"../../../internal/anchored-overlay-runtime.js";import{TypeAheadBuffer}from"../../../internal/type-ahead-buffer.js";import{isRovingTargetAvailable,resolveListMove}from"../../../internal/list-navigation.js";import{PopupController}from"../../../internal/popup-controller.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{nextId,resolveAccessibleTrigger}from"../../../internal/a11y.js";import{collectFocusableElements,composedContains}from"../../../internal/overlay-manager.js";import{styles}from"./menu.styles.js";import{menuItemOwner,submenuPanelController}from"./menu-shared.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{tag}from"../../../internal/prefix.js";import{activeElementIn,isUsableActiveElement,safeDeepActiveElement}from"../../../internal/active-element.js";import{syncAriaDescribedByElements}from"../../../internal/aria-reflection.js";import"./menu-item.class.js";import{LYRA_DEFAULT_menuLabel}from"../../../internal/default-strings/shared.generated.js";const SUBMENU_PLACEMENT="right-start",SUBMENU_FALLBACK_PLACEMENTS=["right-end","left-start","left-end","bottom-start","top-start"],MENUBAR_PLACEMENT="bottom-start",SUBMENU_OPEN_DELAY=150,SUBMENU_CLOSE_DELAY=300;function isLyraMenuItemElement(value){return isHtmlElement(value)?value.localName===tag("menu-item")||value.localName===tag("dropdown-item"):!1}function isLyraMenuElement(value){return isHtmlElement(value)&&value.localName===tag("menu")}let menuWidthScaleRegistered=!1;function registerMenuWidthScale(){if(!menuWidthScaleRegistered&&(menuWidthScaleRegistered=!0,!(typeof CSS>"u"||typeof CSS.registerProperty!="function")))try{CSS.registerProperty({name:"--_lr-menu-max-inline-size",syntax:"<length-percentage>",inherits:!1,initialValue:"100%"})}catch{}}class LyraMenu extends LyraElement{constructor(){super(...arguments),this.presentationOpen=!1,this.presentationHidden=!0,this.submenuAnchor=null,this.submenuStateChange=null,this.dropdownContained=!1,this.dropdownOwner=null,this._dropdownOpen=!1,this.dropdownRendersMenuRole=!1,this.dropdownStayOpenOnSelect=!1,this.items=[],this.activeIndex=-1,this.presentationPositioned=!1,this.popupController=new PopupController({host:this,onPointer:event=>this.onDocPointer(event)}),this.menubarAnchored=!1,this.pendingFocus="first",this.listId=nextId("menu-list"),this.owningMenu={activate:item=>this.onOwnedItemSelect(item),uncheckRadioGroup:(item,group)=>this.uncheckRadioGroupSiblings(item,group)},this.typeBuffer=new TypeAheadBuffer(this),this.typeAheadLabels=new WeakMap,this[_a]=this.createSubmenuController(),this.onRegionSlotChange=()=>{this.syncRegionState()},this.onDocPointer=e=>{const path=e.composedPath();path.includes(this)||this.submenuAnchor&&path.includes(this.submenuAnchor)||this.closePresentation()},this.onItemsSlotChange=e=>{this.syncItemsFromSlot(e.target)},this.itemStateChangeReconciliationPending=!1,this.onItemStateChangeEvent=event=>{event.stopPropagation(),!this.itemStateChangeReconciliationPending&&(this.itemStateChangeReconciliationPending=!0,queueMicrotask(()=>{this.itemStateChangeReconciliationPending=!1,this.onItemStateChange()}))},this.onItemStateChange=()=>{const navigable=[];if(this.items.forEach((item,index)=>{this.isNavigable(item)&&navigable.push({item,index})}),this.activeIndex>=0&&!this.isNavigable(this.items[this.activeIndex])){const current=this.activeIndex,displaced=this.items[current],focused=safeDeepActiveElement(this.ownerDocument),displacedHadFocus=focused===null||focused===this.ownerDocument.body||focused===displaced||composedContains(displaced,focused),next=navigable.find(({index})=>index>current)?.item??navigable.find(({index})=>index<current)?.item;next?this.setActiveItem(next,displacedHadFocus):(this.activeIndex=-1,this.applyRovingTabIndex(),displacedHadFocus&&this.rehomeZeroSurvivorFocus());return}this.applyRovingTabIndex()},this.onListFocusIn=e=>{const target=e.target;if(!isLyraMenuItemElement(target))return;const index=this.items.indexOf(target);index===-1||index===this.activeIndex||!this.isNavigable(target)||(this.activeIndex=index,this.applyRovingTabIndex(),this.closeSubmenus(target))},this.onListKeyDown=e=>{if(this.isForeignEvent(e)||e.altKey||e.ctrlKey||e.metaKey||e.isComposing||e.keyCode===229)return;const isItemTarget=isLyraMenuItemElement(e.target);if(e.key==="Escape"&&isItemTarget&&!this.hasStandalonePresentation){e.preventDefault(),this.closePresentation({focusTrigger:!0});return}if(!isItemTarget)return;const navigable=this.items.filter(i=>this.isNavigable(i)),current=this.activeIndex>=0?this.items[this.activeIndex]:void 0,currentNavIndex=current?navigable.indexOf(current):-1,intoSubmenuKey=this.effectiveDirection==="rtl"?"ArrowLeft":"ArrowRight";switch(e.key){case"ArrowRight":case"ArrowLeft":e.key===intoSubmenuKey?current?.hasSubmenu&&this.isNavigable(current)&&(e.preventDefault(),this.closeSubmenus(current),current.openSubmenu("first")):this.submenuAnchor&&!this.menubarAnchored&&(e.preventDefault(),this.closePresentation({focusTrigger:!0}));break;case"ArrowDown":case"ArrowUp":case"Home":case"End":{e.preventDefault();const nextIndex=resolveListMove(e,{count:navigable.length,current:currentNavIndex,orientation:"vertical"});nextIndex!==null&&this.setActiveItem(navigable[nextIndex]);break}case"Enter":case" ":e.preventDefault(),current?.hasSubmenu?(this.closeSubmenus(current),current.openSubmenu("first")):current?.isLinkItem?current.click():current?.select();break;default:this.typeBuffer.accepts(e)&&this.typeAhead(e.key);return}},this.onPopupPointerOver=e=>{if(!this.interactionOpen)return;const hovered=this.ownItemFromEvent(e);this.clearOwnedTimeout(this.submenuOpenTimer),this.submenuOpenTimer=void 0;const opened=this.openSubmenuItem();opened&&opened===hovered?(this.clearOwnedTimeout(this.submenuCloseTimer),this.submenuCloseTimer=void 0):opened&&this.scheduleSubmenuClose(opened),!(!hovered||hovered===opened||!hovered.hasSubmenu||!this.isNavigable(hovered))&&(this.submenuOpenTimer=this.scheduleOwnedTimeout(()=>{this.submenuOpenTimer=void 0,!(!this.interactionOpen||!this.items.includes(hovered))&&(this.closeSubmenus(hovered),hovered.openSubmenu("none"))},SUBMENU_OPEN_DELAY))},this.onPopupPointerLeave=()=>{this.clearOwnedTimeout(this.submenuOpenTimer),this.submenuOpenTimer=void 0;const opened=this.openSubmenuItem();opened&&this.scheduleSubmenuClose(opened)},this.onNestedSelect=e=>{if(e.target===this)return;const event=e;this.dropdownStayOpenOnSelect&&event.preventDefault(),queueMicrotask(()=>{event.defaultPrevented||this.dismissAfterSelection(!0)})},this.onPopupKeyDown=e=>{const listEl=this.popupPart("list");if(e.key==="Escape"){if(listEl&&e.composedPath().includes(listEl)||this.hasStandalonePresentation)return;e.preventDefault(),this.closePresentation({focusTrigger:!0});return}e.key==="Tab"&&this.tabWouldLeavePopup(e)&&this.closePresentation()}}static{_a=submenuPanelController}static{this.defaultStrings={...super.defaultStrings,menuLabel:LYRA_DEFAULT_menuLabel}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-select"])}static{this.identityEventDetailProperties=Object.freeze({"lr-select":Object.freeze(["item"])})}static{this.styles=[LyraElement.styles,styles]}get dropdownOpen(){return this._dropdownOpen}set dropdownOpen(next){const normalized=!!next;if(normalized===this._dropdownOpen)return;const old=this._dropdownOpen;this._dropdownOpen=normalized,this.presentationOpen=normalized,this.requestUpdate("dropdownOpen",old)}foldedTypeAheadLabel(item,locale){const label=item.getTextLabel(),previous=this.typeAheadLabels.get(item);if(previous?.label===label&&previous.locale===locale)return previous.folded;const folded=label.toLocaleLowerCase(resolveIntlLocale(locale));return this.typeAheadLabels.set(item,{label,locale,folded}),folded}createSubmenuController(){const menu=this;return{get open(){return menu.submenuAnchor!==null&&menu.presentationOpen},attach(anchor,onStateChange,options){menu.submenuAnchor&&menu.submenuAnchor!==anchor&&menu.closePresentation(),menu.menubarAnchored=options?.menubar===!0,menu.submenuAnchor=anchor,menu.submenuStateChange=onStateChange,menu.syncPresentationState(),menu.requestUpdate()},detach(anchor){menu.submenuAnchor===anchor&&(menu.closePresentation(),menu.submenuAnchor=null,menu.menubarAnchored=!1,menu.submenuStateChange=null,menu.cleanup?.(),menu.cleanup=void 0,menu.syncPresentationState(),menu.requestUpdate())},async show(focus="first"){menu.submenuAnchor&&(menu.openPresentation(focus),await menu.updateComplete,await menu.focusAfterPlacement(focus))},async hide(options){menu.closePresentation(options),await menu.updateComplete}}}connectedCallback(){if(super.connectedCallback(),registerMenuWidthScale(),this.hasUpdated){const slot=this.renderRoot.querySelector("slot:not([name])");slot&&this.syncItemsFromSlot(slot,!0)}}firstUpdated(changed){super.firstUpdated(changed),this.syncRegionState(),this.syncPresentationState();const slot=this.itemsSlot;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>this.syncItemsFromSlot(s))})}get hasStandalonePresentation(){return!this.dropdownContained&&!this.submenuAnchor}get interactionOpen(){return this.hasStandalonePresentation||this.presentationOpen}syncPresentationState(){const standalone=this.hasStandalonePresentation;if(this.toggleAttribute("data-inline",standalone),this.toggleAttribute("data-submenu",this.submenuAnchor!==null),this.toggleAttribute("data-contained",this.dropdownContained),standalone){const active=this.activeIndex>=0?this.items[this.activeIndex]:void 0;if(!active||!this.isNavigable(active)){const first=this.items.find(item=>this.isNavigable(item));this.activeIndex=first?this.items.indexOf(first):-1}}else this.presentationOpen||(this.activeIndex=-1);this.applyRovingTabIndex()}syncRegionState(){const assigned=selector=>this.renderRoot.querySelector(selector)?.assignedElements({flatten:!0}).length??0;this.toggleAttribute("data-has-header",assigned('slot[name="header"]')>0),this.toggleAttribute("data-has-footer",assigned('slot[name="footer"]')>0),this.toggleAttribute("data-list-empty",assigned("slot:not([name])")===0)}willUpdate(changed){super.willUpdate(changed),this.presentationOpen&&this.submenuAnchor&&(this.cancelPresentationHideWatch(),this.presentationHidden=!1)}updated(changed){super.updated(changed);const list=this.renderRoot.querySelector('[part~="list"]')??void 0;syncAriaDescribedByElements(this,list,this.getAttribute("aria-describedby")),(changed.has("presentationOpen")||changed.has("dropdownOpen")||changed.has("dropdownContained"))&&(this.cleanup?.(),this.cleanup=void 0,this.presentationPositioned=!1,this.presentationOpen?this.submenuAnchor?(this.popupController.bindPointer(),this.reposition()):(this.popupController.unbindPointer(),this.presentationPositioned=!0,this.focusRoving(this.pendingFocus)):(this.popupController.unbindPointer(),this.resetTypeAhead(),this.activeIndex=-1,this.applyRovingTabIndex(),this.clearSubmenuTimers(),this.closeSubmenus(),this.submenuAnchor&&this.schedulePresentationHide())),changed.has("dropdownContained")&&this.syncPresentationState(),changed.has("dropdownSize")&&this.applyDropdownSize()}reposition(){this.cleanup?.(),this.cleanup=void 0,this.presentationPositioned=!1;const popup=this.renderRoot.querySelector(".submenu-surface");if(this.submenuAnchor&&popup){const placement=this.menubarAnchored?MENUBAR_PLACEMENT:rtlAwarePlacement(SUBMENU_PLACEMENT,this),topLayer=this.submenuAnchor.closest(tag("menubar"))?.topLayer===!0;this.placedTopLayer=syncTopLayerRelease(popup,this.placedTopLayer,topLayer),this.cleanup=place(this.submenuAnchor,popup,{placement,flipFallbackPlacements:this.menubarAnchored?void 0:SUBMENU_FALLBACK_PLACEMENTS.map(candidate=>rtlAwarePlacement(candidate,this)),...topLayerPlacement(topLayer,resolveEffectivePositioningStrategy(this,void 0,"fixed"))})}}cancelPresentationHideWatch(){this.presentationHideWatcher?.(),this.presentationHideWatcher=void 0}schedulePresentationHide(){this.cancelPresentationHideWatch();const surface=this.renderRoot.querySelector(".submenu-surface"),view=this.ownerDocument.defaultView,transitionMs=surface&&view?maxCssTime(view.getComputedStyle(surface).transitionDuration)+maxCssTime(view.getComputedStyle(surface).transitionDelay):0,waitForEvent=!!(surface&&view&&transitionMs>0&&!prefersReducedMotion(this));let settled=!1,timeout;const finish=()=>{settled||(settled=!0,timeout!==void 0&&view?.clearTimeout(timeout),surface?.removeEventListener("transitionend",onEnd),this.presentationHideWatcher===cancel&&(this.presentationHideWatcher=void 0),this.presentationHidden=!0)},onEnd=event=>{event.target===surface&&finish()},cancel=()=>{settled=!0,timeout!==void 0&&view?.clearTimeout(timeout),surface?.removeEventListener("transitionend",onEnd)};this.presentationHideWatcher=cancel,waitForEvent&&surface&&view?(surface.addEventListener("transitionend",onEnd),timeout=view.setTimeout(finish,transitionMs+50)):queueMicrotask(finish)}async focusAfterPlacement(focus){if(!this.presentationOpen||!this.submenuAnchor)return;const positioned=this.cleanup!==void 0&&(this.presentationPositioned||await waitForDeferredPlacement(()=>this.cleanup));if(!(!this.presentationOpen||!this.submenuAnchor)){if(!positioned){this.closePresentation(),await this.updateComplete;return}this.presentationPositioned=!0,this.focusRoving(focus)}}disconnectedCallback(){super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.presentationPositioned=!1,this.resetTypeAhead(),this.clearSubmenuTimers(),this.itemStateObserver?.disconnect(),this.itemStateObserver=void 0,this.popupController.unbindPointer();for(const item of this.items)this.releaseItemOwner(item);this._dropdownOpen=!1,this.presentationOpen=!1,this.cancelPresentationHideWatch(),this.presentationHidden=!0,this.submenuStateChange?.(!1)}scheduleOwnedTimeout(callback,delay){const owner=this.ownerDocument.defaultView;if(owner)return{owner,handle:owner.setTimeout(callback,delay)}}clearOwnedTimeout(timer){timer&&timer.owner.clearTimeout(timer.handle)}focusContained(focus="first"){if(this.dropdownContained&&this.dropdownOwner)if(this.dropdownOwner.open)this.pendingFocus=focus,this.focusRoving(focus);else{const transition=this.dropdownOwner.show();this.dropdownOwner.open&&(this.pendingFocus=focus)}}openPresentation(focus="first"){this.pendingFocus=focus,this.presentationOpen?(!this.submenuAnchor||this.presentationPositioned)&&this.focusRoving(focus):(this.presentationOpen=!0,this.submenuStateChange?.(!0))}closePresentation(options){if(this.dropdownContained&&this.dropdownOwner){this.dropdownOwner.hide(options);return}this.presentationOpen&&(this.presentationOpen=!1,this.submenuStateChange?.(!1),options?.focusTrigger&&this.submenuAnchor&&resolveAccessibleTrigger(this.submenuAnchor).focus())}syncItemsFromSlot(slot,reconnect=!1){if(!this.isConnected)return;const assigned=slot.assignedElements({flatten:!0}).filter(isLyraMenuItemElement);if(assigned.length===this.items.length&&assigned.every((item,index)=>item===this.items[index])){reconnect&&(this.observeItems(),this.syncPresentationState());return}this.itemStateObserver?.disconnect();const previousItems=this.items,previouslyActive=this.activeIndex>=0?this.items[this.activeIndex]:void 0,focusedBefore=safeDeepActiveElement(this.ownerDocument),activeItemLostFocus=!!previouslyActive&&(focusedBefore===null||focusedBefore===this.ownerDocument.body||focusedBefore===previouslyActive||composedContains(previouslyActive,focusedBefore));this.items=assigned;const assignedItems=new Set(assigned);for(const item of previousItems)assignedItems.has(item)||this.releaseItemOwner(item);if(this.observeItems(),this.activeIndex=previouslyActive?this.items.indexOf(previouslyActive):-1,this.syncPresentationState(),this.syncRegionState(),this.interactionOpen)if(this.activeIndex===-1){const successor=this.items.find(item=>this.isNavigable(item));previouslyActive&&successor?this.setActiveItem(successor,activeItemLostFocus):this.focusRoving(this.pendingFocus),activeItemLostFocus&&!this.items.some(item=>this.isNavigable(item))&&this.rehomeZeroSurvivorFocus()}else{const active=activeElementIn(this.ownerDocument);!(isUsableActiveElement(active)&&this.contains(active))&&activeItemLostFocus&&this.items[this.activeIndex].focus()}}observeItems(){for(const item of this.items)this.acquireItemOwner(item);this.applyDropdownSize();const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;if(MutationObserverCtor){const owner=this.ownerDocument;let observer;observer=new MutationObserverCtor(()=>{this.itemStateObserver!==observer||this.ownerDocument!==owner||this.onItemStateChange()}),this.itemStateObserver=observer;for(const item of this.items)this.itemStateObserver.observe(item,{attributes:!0,attributeFilter:["disabled","hidden","aria-hidden","inert"]})}}acquireItemOwner(item){item[menuItemOwner]?.(this.owningMenu)}releaseItemOwner(item){item[menuItemOwner]?.(null,this.owningMenu)}uncheckRadioGroupSiblings(item,group){for(const sibling of this.items)sibling!==item&&sibling.type==="radio"&&sibling.group===group&&sibling.checked&&(sibling.checked=!1)}isNavigable(item){return!item.interactionDisabled&&isRovingTargetAvailable(item)}applyDropdownSize(){if(this.dropdownSize)for(const item of this.items)item.size=this.dropdownSize}rehomeZeroSurvivorFocus(){if(this.dropdownContained&&this.dropdownOwner){this.dropdownOwner.hide({focusTrigger:!0});return}if(this.submenuAnchor){this.closePresentation({focusTrigger:!0});return}const list=this.renderRoot.querySelector('[part~="list"]');list&&(list.tabIndex=-1,list.focus({preventScroll:!0}))}onOwnedItemSelect(item){if(!isLyraMenuItemElement(item)||!this.items.includes(item))return;!this.emit("lr-select",{item},{cancelable:!0}).defaultPrevented&&!this.dropdownStayOpenOnSelect&&this.dismissAfterSelection(!0)}dismissAfterSelection(focusTrigger){this.closeSubmenus(),this.dropdownContained?this.dropdownOwner&&this.dropdownOwner.hide({focusTrigger}):this.submenuAnchor&&this.closePresentation({focusTrigger})}applyRovingTabIndex(){this.items.forEach((item,i)=>{item.tabIndex=i===this.activeIndex?0:-1})}focusRoving(which){if(which==="none")return;const navigable=this.items.filter(i=>this.isNavigable(i));if(!navigable.length)return;const item=which==="first"?navigable[0]:navigable[navigable.length-1];item&&this.setActiveItem(item)}setActiveItem(item,moveFocus=!0){this.activeIndex=this.items.indexOf(item),this.applyRovingTabIndex(),this.closeSubmenus(item),moveFocus&&item.focus()}closeSubmenus(keep){for(const item of this.items)item!==keep&&item.submenuOpen&&item.closeSubmenu()}openSubmenuItem(){return this.items.find(item=>item.submenuOpen)}clearSubmenuTimers(){this.clearOwnedTimeout(this.submenuOpenTimer),this.clearOwnedTimeout(this.submenuCloseTimer),this.submenuOpenTimer=void 0,this.submenuCloseTimer=void 0}ownItemFromEvent(e){let owner;for(const node of e.composedPath()){if(node===this)break;isLyraMenuItemElement(node)&&(owner=node)}return owner}isForeignEvent(e){for(const node of e.composedPath()){if(node===this)break;if(isLyraMenuElement(node))return!0}return!1}scheduleSubmenuClose(item){this.submenuCloseTimer||(this.submenuCloseTimer=this.scheduleOwnedTimeout(()=>{this.submenuCloseTimer=void 0,item.submenuOpen&&(composedContains(item,safeDeepActiveElement(this.ownerDocument))||item.closeSubmenu())},SUBMENU_CLOSE_DELAY))}popupPart(name){return this.renderRoot.querySelector(`[part="${name}"]`)}tabWouldLeavePopup(e){const header=this.popupPart("header"),footer=this.popupPart("footer"),listEl=this.popupPart("list"),backwards=e.shiftKey,active=safeDeepActiveElement(this.ownerDocument),headerStops=header?collectFocusableElements(header):[],footerStops=footer?collectFocusableElements(footer):[],listStops=listEl?collectFocusableElements(listEl):[],hasNeighbor=stops=>{const index=active?stops.indexOf(active):-1;return index===-1?!1:backwards?index>0:index<stops.length-1},path=e.composedPath();return footer&&path.includes(footer)?hasNeighbor(footerStops)?!1:backwards?listStops.length===0&&headerStops.length===0:!0:header&&path.includes(header)?hasNeighbor(headerStops)?!1:backwards?!0:listStops.length===0&&footerStops.length===0:!isLyraMenuItemElement(e.target)&&hasNeighbor(listStops)?!1:backwards?headerStops.length===0:footerStops.length===0}typeAhead(char){this.typeBuffer.add(char,this.effectiveLocale);const navigable=this.items.filter(i=>this.isNavigable(i));if(!navigable.length)return;const current=this.activeIndex>=0?this.items[this.activeIndex]:void 0,currentIndex=current?navigable.indexOf(current):-1,locale=resolveIntlLocale(this.effectiveLocale);let match=null;for(let step=1;step<=navigable.length;step++){const candidate=((currentIndex+step)%navigable.length+navigable.length)%navigable.length;if(this.foldedTypeAheadLabel(navigable[candidate],locale).startsWith(this.typeBuffer.text)){match=candidate;break}}match!==null&&this.setActiveItem(navigable[match])}resetTypeAhead(){this.typeBuffer.clear()}get effectiveLabel(){const hostLabel=this.getAttribute("aria-label");return hostLabel!==null?hostLabel:this.label!==void 0?this.label:this.dropdownLabel!==void 0?this.dropdownLabel:this.localize("menuLabel")}renderContents(bindPointerOver=!0){return html`
|
|
1
|
+
var _a;import{__decorate}from"tslib";import{resolveIntlLocale}from"../../../internal/intl-cache.js";import{maxCssTime}from"../../../internal/css-motion-time.js";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{deferredPlaceReady as place,syncTopLayerRelease,topLayerPlacement,waitForDeferredPlacement}from"../../../internal/anchored-overlay-runtime.js";import{TypeAheadBuffer}from"../../../internal/type-ahead-buffer.js";import{isRovingTargetAvailable,resolveListMove}from"../../../internal/list-navigation.js";import{PopupController}from"../../../internal/popup-controller.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{nextId,resolveAccessibleTrigger}from"../../../internal/a11y.js";import{collectFocusableElements,composedContains}from"../../../internal/overlay-manager.js";import{styles}from"./menu.styles.js";import{menuItemOwner,submenuPanelController}from"./menu-shared.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{tag}from"../../../internal/prefix.js";import{activeElementIn,isUsableActiveElement,safeDeepActiveElement}from"../../../internal/active-element.js";import{syncAriaDescribedByElements}from"../../../internal/aria-reflection.js";import"./menu-item.class.js";import{LYRA_DEFAULT_menuLabel}from"../../../internal/default-strings/shared.generated.js";const SUBMENU_PLACEMENT="right-start",SUBMENU_FALLBACK_PLACEMENTS=["right-end","left-start","left-end","bottom-start","top-start"],MENUBAR_PLACEMENT="bottom-start",SUBMENU_OPEN_DELAY=150,SUBMENU_CLOSE_DELAY=300;function isLyraMenuItemElement(value){return isHtmlElement(value)?value.localName===tag("menu-item")||value.localName===tag("dropdown-item"):!1}function isLyraMenuElement(value){return isHtmlElement(value)&&value.localName===tag("menu")}let menuWidthScaleRegistered=!1;function registerMenuWidthScale(){if(!menuWidthScaleRegistered&&(menuWidthScaleRegistered=!0,!(typeof CSS>"u"||typeof CSS.registerProperty!="function")))try{CSS.registerProperty({name:"--_lr-menu-max-inline-size",syntax:"<length-percentage>",inherits:!1,initialValue:"100%"})}catch{}}class LyraMenu extends LyraElement{constructor(){super(...arguments),this.presentationOpen=!1,this.presentationHidden=!0,this.submenuAnchor=null,this.submenuStateChange=null,this.dropdownContained=!1,this.dropdownOwner=null,this._dropdownOpen=!1,this.dropdownRendersMenuRole=!1,this.dropdownStayOpenOnSelect=!1,this.items=[],this.activeIndex=-1,this.presentationPositioned=!1,this.popupController=new PopupController({host:this,onPointer:event=>this.onDocPointer(event)}),this.menubarAnchored=!1,this.pendingFocus="first",this.listId=nextId("menu-list"),this.owningMenu={activate:item=>this.onOwnedItemSelect(item),uncheckRadioGroup:(item,group)=>this.uncheckRadioGroupSiblings(item,group)},this.typeBuffer=new TypeAheadBuffer(this),this.typeAheadLabels=new WeakMap,this[_a]=this.createSubmenuController(),this.onRegionSlotChange=()=>{this.syncRegionState()},this.onDocPointer=e=>{const path=e.composedPath();path.includes(this)||this.submenuAnchor&&path.includes(this.submenuAnchor)||this.closePresentation()},this.onItemsSlotChange=e=>{this.syncItemsFromSlot(e.target)},this.itemStateChangeReconciliationPending=!1,this.onItemStateChangeEvent=event=>{event.stopPropagation(),!this.itemStateChangeReconciliationPending&&(this.itemStateChangeReconciliationPending=!0,queueMicrotask(()=>{this.itemStateChangeReconciliationPending=!1,this.onItemStateChange()}))},this.onItemStateChange=()=>{const navigable=[];if(this.items.forEach((item,index)=>{this.isNavigable(item)&&navigable.push({item,index})}),this.activeIndex>=0&&!this.isNavigable(this.items[this.activeIndex])){const current=this.activeIndex,displaced=this.items[current],focused=safeDeepActiveElement(this.ownerDocument),displacedHadFocus=focused===null||focused===this.ownerDocument.body||focused===displaced||composedContains(displaced,focused),next=navigable.find(({index})=>index>current)?.item??navigable.find(({index})=>index<current)?.item;next?this.setActiveItem(next,displacedHadFocus):(this.activeIndex=-1,this.applyRovingTabIndex(),displacedHadFocus&&this.rehomeZeroSurvivorFocus());return}this.applyRovingTabIndex()},this.onListFocusIn=e=>{const target=e.target;if(!isLyraMenuItemElement(target))return;const index=this.items.indexOf(target);index===-1||index===this.activeIndex||!this.isNavigable(target)||(this.activeIndex=index,this.applyRovingTabIndex(),this.closeSubmenus(target))},this.onListKeyDown=e=>{if(this.isForeignEvent(e)||e.altKey||e.ctrlKey||e.metaKey||e.isComposing||e.keyCode===229)return;const isItemTarget=isLyraMenuItemElement(e.target);if(e.key==="Escape"&&isItemTarget&&!this.hasStandalonePresentation){e.preventDefault(),this.closePresentation({focusTrigger:!0});return}if(!isItemTarget)return;const navigable=this.items.filter(i=>this.isNavigable(i)),current=this.activeIndex>=0?this.items[this.activeIndex]:void 0,currentNavIndex=current?navigable.indexOf(current):-1,intoSubmenuKey=this.effectiveDirection==="rtl"?"ArrowLeft":"ArrowRight";switch(e.key){case"ArrowRight":case"ArrowLeft":e.key===intoSubmenuKey?current?.hasSubmenu&&this.isNavigable(current)&&(e.preventDefault(),this.closeSubmenus(current),current.openSubmenu("first")):this.submenuAnchor&&!this.menubarAnchored&&(e.preventDefault(),this.closePresentation({focusTrigger:!0}));break;case"ArrowDown":case"ArrowUp":case"Home":case"End":{e.preventDefault();const nextIndex=resolveListMove(e,{count:navigable.length,current:currentNavIndex,orientation:"vertical"});nextIndex!==null&&this.setActiveItem(navigable[nextIndex]);break}case"Enter":case" ":e.preventDefault(),current?.hasSubmenu?(this.closeSubmenus(current),current.openSubmenu("first")):current?.isLinkItem?current.click():current?.select();break;default:this.typeBuffer.accepts(e)&&this.typeAhead(e.key);return}},this.onPopupPointerOver=e=>{if(!this.interactionOpen)return;const hovered=this.ownItemFromEvent(e);this.clearOwnedTimeout(this.submenuOpenTimer),this.submenuOpenTimer=void 0;const opened=this.openSubmenuItem();opened&&opened===hovered?(this.clearOwnedTimeout(this.submenuCloseTimer),this.submenuCloseTimer=void 0):opened&&this.scheduleSubmenuClose(opened),!(!hovered||hovered===opened||!hovered.hasSubmenu||!this.isNavigable(hovered))&&(this.submenuOpenTimer=this.scheduleOwnedTimeout(()=>{this.submenuOpenTimer=void 0,!(!this.interactionOpen||!this.items.includes(hovered))&&(this.closeSubmenus(hovered),hovered.openSubmenu("none"))},SUBMENU_OPEN_DELAY))},this.onPopupPointerLeave=()=>{this.clearOwnedTimeout(this.submenuOpenTimer),this.submenuOpenTimer=void 0;const opened=this.openSubmenuItem();opened&&this.scheduleSubmenuClose(opened)},this.onNestedSelect=e=>{if(e.target===this)return;const event=e;this.dropdownStayOpenOnSelect&&event.preventDefault(),queueMicrotask(()=>{event.defaultPrevented||this.dismissAfterSelection(!0)})},this.onPopupKeyDown=e=>{const listEl=this.popupPart("list");if(e.key==="Escape"){if(listEl&&e.composedPath().includes(listEl)||this.hasStandalonePresentation)return;e.preventDefault(),this.closePresentation({focusTrigger:!0});return}e.key==="Tab"&&this.tabWouldLeavePopup(e)&&this.closePresentation()}}static{_a=submenuPanelController}static{this.defaultStrings={...super.defaultStrings,menuLabel:LYRA_DEFAULT_menuLabel}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-select"])}static{this.identityEventDetailProperties=Object.freeze({"lr-select":Object.freeze(["item"])})}static{this.styles=[LyraElement.styles,styles]}get dropdownOpen(){return this._dropdownOpen}set dropdownOpen(next){const normalized=!!next;if(normalized===this._dropdownOpen)return;const old=this._dropdownOpen;this._dropdownOpen=normalized,this.presentationOpen=normalized,this.requestUpdate("dropdownOpen",old)}foldedTypeAheadLabel(item,locale){const label=item.getTextLabel(),previous=this.typeAheadLabels.get(item);if(previous?.label===label&&previous.locale===locale)return previous.folded;const folded=label.toLocaleLowerCase(resolveIntlLocale(locale));return this.typeAheadLabels.set(item,{label,locale,folded}),folded}createSubmenuController(){const menu=this;return{get open(){return menu.submenuAnchor!==null&&menu.presentationOpen},attach(anchor,onStateChange,options){menu.submenuAnchor&&menu.submenuAnchor!==anchor&&menu.closePresentation(),menu.menubarAnchored=options?.menubar===!0,menu.submenuAnchor=anchor,menu.submenuStateChange=onStateChange,menu.syncPresentationState(),menu.requestUpdate()},detach(anchor){menu.submenuAnchor===anchor&&(menu.closePresentation(),menu.submenuAnchor=null,menu.menubarAnchored=!1,menu.submenuStateChange=null,menu.cleanup?.(),menu.cleanup=void 0,menu.syncPresentationState(),menu.requestUpdate())},async show(focus="first"){menu.submenuAnchor&&(menu.openPresentation(focus),await menu.updateComplete,await menu.focusAfterPlacement(focus))},async hide(options){menu.closePresentation(options),await menu.updateComplete}}}connectedCallback(){if(super.connectedCallback(),registerMenuWidthScale(),this.hasUpdated){const slot=this.renderRoot.querySelector("slot:not([name])");slot&&this.syncItemsFromSlot(slot,!0)}}firstUpdated(changed){super.firstUpdated(changed),this.syncRegionState(),this.syncPresentationState();const slot=this.itemsSlot;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>this.syncItemsFromSlot(s))})}get hasStandalonePresentation(){return!this.dropdownContained&&!this.submenuAnchor}get interactionOpen(){return this.hasStandalonePresentation||this.presentationOpen}syncPresentationState(){const standalone=this.hasStandalonePresentation;if(this.toggleAttribute("data-inline",standalone),this.toggleAttribute("data-submenu",this.submenuAnchor!==null),this.toggleAttribute("data-contained",this.dropdownContained),standalone){const active=this.activeIndex>=0?this.items[this.activeIndex]:void 0;if(!active||!this.isNavigable(active)){const first=this.items.find(item=>this.isNavigable(item));this.activeIndex=first?this.items.indexOf(first):-1}}else this.presentationOpen||(this.activeIndex=-1);this.applyRovingTabIndex()}syncRegionState(){const assigned=selector=>this.renderRoot.querySelector(selector)?.assignedElements({flatten:!0}).length??0;this.toggleAttribute("data-has-header",assigned('slot[name="header"]')>0),this.toggleAttribute("data-has-footer",assigned('slot[name="footer"]')>0),this.toggleAttribute("data-list-empty",assigned("slot:not([name])")===0)}willUpdate(changed){super.willUpdate(changed),this.presentationOpen&&this.submenuAnchor&&(this.cancelPresentationHideWatch(),this.presentationHidden=!1)}updated(changed){super.updated(changed);const list=this.renderRoot.querySelector('[part~="list"]')??void 0;syncAriaDescribedByElements(this,list,this.getAttribute("aria-describedby")),(changed.has("presentationOpen")||changed.has("dropdownOpen")||changed.has("dropdownContained"))&&(this.cleanup?.(),this.cleanup=void 0,this.presentationPositioned=!1,this.presentationOpen?this.submenuAnchor?(this.popupController.bindPointer(),this.reposition()):(this.popupController.unbindPointer(),this.presentationPositioned=!0,this.focusRoving(this.pendingFocus)):(this.popupController.unbindPointer(),this.resetTypeAhead(),this.activeIndex=-1,this.applyRovingTabIndex(),this.clearSubmenuTimers(),this.closeSubmenus(),this.submenuAnchor&&this.schedulePresentationHide())),changed.has("dropdownContained")&&this.syncPresentationState(),changed.has("dropdownSize")&&this.applyDropdownSize()}reposition(){this.cleanup?.(),this.cleanup=void 0,this.presentationPositioned=!1;const popup=this.renderRoot.querySelector(".submenu-surface");if(this.submenuAnchor&&popup){const placement=this.menubarAnchored?MENUBAR_PLACEMENT:rtlAwarePlacement(SUBMENU_PLACEMENT,this),topLayer=this.submenuAnchor.closest(tag("menubar"))?.topLayer===!0;this.placedTopLayer=syncTopLayerRelease(popup,this.placedTopLayer,topLayer),this.cleanup=place(this.submenuAnchor,popup,{placement,flipFallbackPlacements:this.menubarAnchored?void 0:SUBMENU_FALLBACK_PLACEMENTS.map(candidate=>rtlAwarePlacement(candidate,this)),...topLayerPlacement(topLayer,resolveEffectivePositioningStrategy(this,void 0,"fixed"))})}}cancelPresentationHideWatch(){this.presentationHideWatcher?.(),this.presentationHideWatcher=void 0}schedulePresentationHide(){this.cancelPresentationHideWatch();const surface=this.renderRoot.querySelector(".submenu-surface"),view=this.ownerDocument.defaultView,transitionMs=surface&&view?maxCssTime(view.getComputedStyle(surface).transitionDuration)+maxCssTime(view.getComputedStyle(surface).transitionDelay):0,waitForEvent=!!(surface&&view&&transitionMs>0&&!prefersReducedMotion(this));let settled=!1,timeout;const finish=()=>{settled||(settled=!0,timeout!==void 0&&view?.clearTimeout(timeout),surface?.removeEventListener("transitionend",onEnd),this.presentationHideWatcher===cancel&&(this.presentationHideWatcher=void 0),this.presentationHidden=!0)},onEnd=event=>{event.target===surface&&finish()},cancel=()=>{settled=!0,timeout!==void 0&&view?.clearTimeout(timeout),surface?.removeEventListener("transitionend",onEnd)};this.presentationHideWatcher=cancel,waitForEvent&&surface&&view?(surface.addEventListener("transitionend",onEnd),timeout=view.setTimeout(finish,transitionMs+50)):queueMicrotask(finish)}async focusAfterPlacement(focus){if(!this.presentationOpen||!this.submenuAnchor)return;const positioned=this.cleanup!==void 0&&(this.presentationPositioned||await waitForDeferredPlacement(()=>this.cleanup));if(!(!this.presentationOpen||!this.submenuAnchor)){if(!positioned){this.closePresentation(),await this.updateComplete;return}this.presentationPositioned=!0,this.focusRoving(focus)}}disconnectedCallback(){super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.presentationPositioned=!1,this.resetTypeAhead(),this.clearSubmenuTimers(),this.itemStateObserver?.disconnect(),this.itemStateObserver=void 0,this.popupController.unbindPointer();for(const item of this.items)this.releaseItemOwner(item);this._dropdownOpen=!1,this.presentationOpen=!1,this.cancelPresentationHideWatch(),this.presentationHidden=!0,this.submenuStateChange?.(!1)}scheduleOwnedTimeout(callback,delay){const owner=this.ownerDocument.defaultView;if(owner)return{owner,handle:owner.setTimeout(callback,delay)}}clearOwnedTimeout(timer){timer&&timer.owner.clearTimeout(timer.handle)}focusContained(focus="first"){if(this.dropdownContained&&this.dropdownOwner)if(this.dropdownOwner.open)this.pendingFocus=focus,this.focusRoving(focus);else{const transition=this.dropdownOwner.show();this.dropdownOwner.open&&(this.pendingFocus=focus)}}openPresentation(focus="first"){this.pendingFocus=focus,this.presentationOpen?(!this.submenuAnchor||this.presentationPositioned)&&this.focusRoving(focus):(this.presentationOpen=!0,this.submenuStateChange?.(!0))}closePresentation(options){if(this.dropdownContained&&this.dropdownOwner){this.dropdownOwner.hide(options);return}this.presentationOpen&&(this.presentationOpen=!1,this.submenuStateChange?.(!1),options?.focusTrigger&&this.submenuAnchor&&resolveAccessibleTrigger(this.submenuAnchor).focus())}syncItemsFromSlot(slot,reconnect=!1){if(!this.isConnected)return;const assigned=slot.assignedElements({flatten:!0}).filter(isLyraMenuItemElement);if(assigned.length===this.items.length&&assigned.every((item,index)=>item===this.items[index])){reconnect&&(this.observeItems(),this.syncPresentationState());return}this.itemStateObserver?.disconnect();const previousItems=this.items,previouslyActive=this.activeIndex>=0?this.items[this.activeIndex]:void 0,focusedBefore=safeDeepActiveElement(this.ownerDocument),activeItemLostFocus=!!previouslyActive&&(focusedBefore===null||focusedBefore===this.ownerDocument.body||focusedBefore===previouslyActive||composedContains(previouslyActive,focusedBefore));this.items=assigned;const assignedItems=new Set(assigned);for(const item of previousItems)assignedItems.has(item)||this.releaseItemOwner(item);if(this.observeItems(),this.activeIndex=previouslyActive?this.items.indexOf(previouslyActive):-1,this.syncPresentationState(),this.syncRegionState(),this.interactionOpen)if(this.activeIndex===-1){const successor=this.items.find(item=>this.isNavigable(item));previouslyActive&&successor?this.setActiveItem(successor,activeItemLostFocus):this.focusRoving(this.pendingFocus),activeItemLostFocus&&!this.items.some(item=>this.isNavigable(item))&&this.rehomeZeroSurvivorFocus()}else{const active=activeElementIn(this.ownerDocument);!(isUsableActiveElement(active)&&this.contains(active))&&activeItemLostFocus&&this.items[this.activeIndex].focus()}}observeItems(){for(const item of this.items)this.acquireItemOwner(item);this.applyDropdownSize();const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;if(MutationObserverCtor){const owner=this.ownerDocument;let observer;observer=new MutationObserverCtor(()=>{this.itemStateObserver!==observer||this.ownerDocument!==owner||this.onItemStateChange()}),this.itemStateObserver=observer;for(const item of this.items)this.itemStateObserver.observe(item,{attributes:!0,attributeFilter:["disabled","hidden","aria-hidden","inert"]})}}acquireItemOwner(item){item[menuItemOwner]?.(this.owningMenu)}releaseItemOwner(item){item[menuItemOwner]?.(null,this.owningMenu)}uncheckRadioGroupSiblings(item,group){for(const sibling of this.items)sibling!==item&&sibling.type==="radio"&&sibling.group===group&&sibling.checked&&(sibling.checked=!1)}isNavigable(item){return!item.interactionDisabled&&isRovingTargetAvailable(item)}applyDropdownSize(){if(this.dropdownSize)for(const item of this.items)item.size=this.dropdownSize}rehomeZeroSurvivorFocus(){if(this.dropdownContained&&this.dropdownOwner){this.dropdownOwner.hide({focusTrigger:!0});return}if(this.submenuAnchor){this.closePresentation({focusTrigger:!0});return}const list=this.renderRoot.querySelector('[part~="list"]');list&&(list.tabIndex=-1,list.focus({preventScroll:!0}))}onOwnedItemSelect(item){if(!isLyraMenuItemElement(item)||!this.items.includes(item))return;!this.emit("lr-select",{item},{cancelable:!0}).defaultPrevented&&!this.dropdownStayOpenOnSelect&&this.dismissAfterSelection(!0)}dismissAfterSelection(focusTrigger){this.closeSubmenus(),this.dropdownContained?this.dropdownOwner&&this.dropdownOwner.hide({focusTrigger}):this.submenuAnchor&&this.closePresentation({focusTrigger})}applyRovingTabIndex(){this.items.forEach((item,i)=>{item.tabIndex=i===this.activeIndex?0:-1})}focusRoving(which){if(which==="none")return;const navigable=this.items.filter(i=>this.isNavigable(i));if(!navigable.length)return;const item=which==="first"?navigable[0]:navigable[navigable.length-1];item&&this.setActiveItem(item)}setActiveItem(item,moveFocus=!0){this.activeIndex=this.items.indexOf(item),this.applyRovingTabIndex(),this.closeSubmenus(item),moveFocus&&item.focus()}closeSubmenus(keep){for(const item of this.items)item!==keep&&item.submenuOpen&&item.closeSubmenu()}openSubmenuItem(){return this.items.find(item=>item.submenuOpen)}clearSubmenuTimers(){this.clearOwnedTimeout(this.submenuOpenTimer),this.clearOwnedTimeout(this.submenuCloseTimer),this.submenuOpenTimer=void 0,this.submenuCloseTimer=void 0}ownItemFromEvent(e){let owner;for(const node of e.composedPath()){if(node===this)break;isLyraMenuItemElement(node)&&(owner=node)}return owner}isForeignEvent(e){for(const node of e.composedPath()){if(node===this)break;if(isLyraMenuElement(node))return!0}return!1}scheduleSubmenuClose(item){this.submenuCloseTimer||(this.submenuCloseTimer=this.scheduleOwnedTimeout(()=>{this.submenuCloseTimer=void 0,item.submenuOpen&&(composedContains(item,safeDeepActiveElement(this.ownerDocument))||item.closeSubmenu())},SUBMENU_CLOSE_DELAY))}popupPart(name){return this.renderRoot.querySelector(`[part="${name}"]`)}tabWouldLeavePopup(e){const header=this.popupPart("header"),footer=this.popupPart("footer"),listEl=this.popupPart("list"),backwards=e.shiftKey,active=safeDeepActiveElement(this.ownerDocument),headerStops=header?collectFocusableElements(header):[],footerStops=footer?collectFocusableElements(footer):[],listStops=listEl?collectFocusableElements(listEl):[],hasNeighbor=stops=>{const index=active?stops.indexOf(active):-1;return index===-1?!1:backwards?index>0:index<stops.length-1},path=e.composedPath();return footer&&path.includes(footer)?hasNeighbor(footerStops)?!1:backwards?listStops.length===0&&headerStops.length===0:!0:header&&path.includes(header)?hasNeighbor(headerStops)?!1:backwards?!0:listStops.length===0&&footerStops.length===0:!isLyraMenuItemElement(e.target)&&hasNeighbor(listStops)?!1:backwards?headerStops.length===0:footerStops.length===0}typeAhead(char){this.typeBuffer.add(char,this.effectiveLocale);const navigable=this.items.filter(i=>this.isNavigable(i));if(!navigable.length)return;const current=this.activeIndex>=0?this.items[this.activeIndex]:void 0,currentIndex=current?navigable.indexOf(current):-1,locale=resolveIntlLocale(this.effectiveLocale);let match=null;for(let step=1;step<=navigable.length;step++){const candidate=((currentIndex+step)%navigable.length+navigable.length)%navigable.length;if(this.foldedTypeAheadLabel(navigable[candidate],locale).startsWith(this.typeBuffer.text)){match=candidate;break}}match!==null&&this.setActiveItem(navigable[match])}resetTypeAhead(){this.typeBuffer.clear()}get effectiveLabel(){const hostLabel=this.getAttribute("aria-label");return hostLabel!==null?hostLabel:this.label!=null?this.label:this.dropdownLabel!==void 0?this.dropdownLabel:this.localize("menuLabel")}renderContents(bindPointerOver=!0){return html`
|
|
2
2
|
<div part="header">
|
|
3
3
|
<slot name="header" @slotchange=${this.onRegionSlotChange}></slot>
|
|
4
4
|
</div>
|