@aceshooting/lyra-ui 30.9.0 → 31.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +361 -335
- package/dist/ai/adapters/ag-ui.js +1 -1
- package/dist/autoloader-cdn.js +1 -1
- package/dist/components/agent-tools/activity-feed/activity-feed.class.js +1 -1
- package/dist/components/agent-tools/budget-meter/budget-meter.class.d.ts +12 -1
- package/dist/components/agent-tools/budget-meter/budget-meter.class.js +4 -4
- 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.class.js +2 -2
- 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 +2 -2
- package/dist/components/conversation/chat-composer/chat-composer.class.d.ts +26 -11
- package/dist/components/conversation/chat-composer/chat-composer.class.js +11 -9
- 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/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-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.d.ts +11 -3
- package/dist/components/conversation/message-feedback/message-feedback.class.js +12 -6
- package/dist/components/conversation/message-feedback/message-feedback.styles.js +1 -1
- package/dist/components/conversation/message-parts/message-parts.class.js +1 -1
- package/dist/components/conversation/prompt-input/prompt-input.class.d.ts +8 -4
- package/dist/components/conversation/prompt-input/prompt-input.class.js +3 -2
- package/dist/components/conversation/push-to-talk/push-to-talk.class.js +1 -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.d.ts +1 -1
- package/dist/components/conversation/thread-list/thread-list.class.js +3 -3
- 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/document-library/document-library-cursor.js +1 -0
- package/dist/components/data/document-library/document-library-types.d.ts +20 -0
- package/dist/components/data/document-library/document-library.class.d.ts +37 -26
- package/dist/components/data/document-library/document-library.class.js +20 -11
- package/dist/components/data/document-library/document-library.styles.js +1 -1
- package/dist/components/data/file-tree/file-tree.class.js +1 -1
- package/dist/components/data/flow-canvas/flow-canvas.class.d.ts +1 -1
- package/dist/components/data/flow-canvas/flow-canvas.class.js +2 -2
- 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/combobox/combobox.class.d.ts +20 -12
- package/dist/components/forms/combobox/combobox.class.js +2 -2
- 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/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/dock-panel/dock-panel.class.d.ts +1 -1
- package/dist/components/layout/dock-panel/dock-panel.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/page/page.class.d.ts +3 -3
- package/dist/components/layout/page/page.class.js +1 -1
- package/dist/components/layout/segmented/segmented.class.d.ts +20 -7
- package/dist/components/layout/segmented/segmented.class.js +34 -24
- package/dist/components/layout/segmented/segmented.styles.js +1 -1
- package/dist/components/layout/stepper/stepper.styles.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-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-anchor-controller.js +1 -1
- package/dist/components/media/map/map-canvas-target.js +1 -0
- 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 +15 -6
- package/dist/components/media/map/map.class.js +4 -4
- package/dist/components/media/map/map.styles.js +1 -1
- package/dist/components/media/pan-zoom/pan-zoom.class.js +1 -1
- package/dist/components/media/sequence-playback/sequence-playback.class.d.ts +21 -9
- package/dist/components/media/sequence-playback/sequence-playback.class.js +7 -6
- package/dist/components/media/sequence-playback/sequence-playback.styles.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/overlay.styles.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-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/ingestion-queue/ingestion-queue-presentation.d.ts +11 -0
- package/dist/components/retrieval/ingestion-queue/ingestion-queue-presentation.js +1 -0
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.d.ts +18 -7
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.js +13 -26
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.styles.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/diff-view/diff-view.class.d.ts +5 -5
- package/dist/components/utility/diff-view/diff-view.class.js +1 -1
- package/dist/components/utility/icon/icon.class.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/archive-viewer/archive-viewer.class.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/document-preview/document-preview.class.js +2 -2
- package/dist/components/viewers/docx-viewer/docx-viewer.class.d.ts +1 -1
- package/dist/components/viewers/docx-viewer/docx-viewer.class.js +2 -2
- package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
- package/dist/components/viewers/email-viewer/email-viewer.class.d.ts +1 -1
- package/dist/components/viewers/email-viewer/email-viewer.class.js +2 -2
- package/dist/components/viewers/html-viewer/html-viewer.class.js +1 -1
- package/dist/components/viewers/include/include.class.js +1 -1
- package/dist/components/viewers/model-viewer/model-viewer.class.js +1 -1
- package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +2 -2
- 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-viewer.class.js +1 -1
- package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.js +1 -1
- package/dist/components/viewers/svg-viewer/svg-viewer.class.js +1 -1
- package/dist/components/viewers/table-viewer-shared.js +4 -4
- package/dist/components/viewers/xml-viewer/xml-viewer.class.js +2 -2
- package/dist/data-sources.d.ts +10 -0
- package/dist/events.d.ts +9 -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/default-strings/conversation.generated.js +1 -1
- package/dist/internal/default-strings/data.generated.js +1 -1
- package/dist/internal/default-strings/retrieval.generated.js +1 -1
- package/dist/internal/document-tokens.js +2 -2
- 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/localization-types.d.ts +1 -1
- package/dist/internal/localization.js +1 -1
- package/dist/internal/lyra-element.js +2 -2
- package/dist/internal/map-custom-layer-controller.js +1 -1
- package/dist/internal/media-panorama.js +1 -1
- package/dist/internal/native-modal-context.js +1 -1
- package/dist/internal/overlay-manager.js +1 -1
- package/dist/internal/overlay-order.js +1 -1
- package/dist/internal/overlay-stack.js +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/runtime-diagnostics.js +1 -0
- 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-cursor-controller.js +1 -0
- package/dist/internal/source-cursor-projection.js +1 -0
- package/dist/internal/source-page-scope.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-bootstrap.js +1 -1
- package/dist/theme/theme.js +1 -1
- package/dist/utilities/overlay-manager.d.ts +2 -0
- package/llms/components/lr-attachment-chip.md +27 -12
- package/llms/components/lr-attachment-trigger.md +27 -7
- package/llms/components/lr-budget-meter.md +31 -0
- package/llms/components/lr-button.md +6 -4
- package/llms/components/lr-chat-composer.md +26 -9
- package/llms/components/lr-chat-message.md +44 -3
- package/llms/components/lr-chat-viewport.md +39 -2
- package/llms/components/lr-combobox.md +27 -1
- package/llms/components/lr-data-grid.md +2 -0
- package/llms/components/lr-dialog.md +10 -0
- package/llms/components/lr-diff-view.md +6 -0
- package/llms/components/lr-document-library.md +90 -6
- package/llms/components/lr-drop-zone.md +26 -2
- package/llms/components/lr-graph.md +5 -0
- package/llms/components/lr-icon-button.md +2 -1
- package/llms/components/lr-ingestion-queue.md +76 -8
- package/llms/components/lr-json-viewer.md +51 -0
- package/llms/components/lr-lite-chart.md +2 -1
- package/llms/components/lr-locale-picker.md +5 -0
- package/llms/components/lr-map.md +33 -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-message-feedback.md +38 -3
- package/llms/components/lr-number-input.md +28 -1
- package/llms/components/lr-page.md +4 -2
- package/llms/components/lr-prompt-input.md +6 -3
- package/llms/components/lr-segmented.md +30 -10
- package/llms/components/lr-sequence-playback.md +47 -12
- 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 +4 -1
- package/llms/peers.md +2 -2
- package/llms/shared/events-and-types.md +61 -2
- package/llms/shared/forms-and-accessibility.md +46 -4
- package/llms/shared/imports-and-registration.md +154 -110
- package/llms/shared/testing-and-utilities.md +5 -1
- package/llms/shared.md +266 -117
- package/locales.json +1 -1
- package/package.json +22 -21
- package/registrations.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{emitValueEvents}from"../../../internal/value-events.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{FormControlController,reflectFormName}from"../../../internal/form-control-controller.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{tag}from"../../../internal/prefix.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{resolveValidityAnchor,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{hostAriaLabel,nextId,srOnly}from"../../../internal/a11y.js";import{acquireAriaDescription,acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./checkbox-group.styles.js";import{createStringArrayFormDataState,getFormOwner,isBarredFromValidation,readStringArrayFormDataState,setFormOwner}from"../../../internal/form-associated.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{LYRA_DEFAULT_checkboxGroupRequired}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();const DUPLICATE_VALUE_WARNING_KEY="lyra-checkbox-group-duplicate-child-values",DUPLICATE_VALUE_WARNING="<lr-checkbox-group>: duplicate child values make submitted FormData ambiguous; give each child a distinct value.";class LyraCheckboxGroup extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,checkboxGroupRequired:LYRA_DEFAULT_checkboxGroupRequired,fieldRequired:LYRA_DEFAULT_fieldRequired}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-checkbox-group-toggle-request"])}static{this.identityEventDetailProperties=Object.freeze({"lr-checkbox-group-toggle-request":Object.freeze(["option"])})}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},size:{reflect:!0},orientation:{reflect:!0},value:{attribute:!1,noAccessor:!0}}}get hasLabelSlot(){return this.slotPresence.has("label")}get hasHintSlot(){return this.slotPresence.has("hint")}get hasErrorSlot(){return this.slotPresence.has("error")}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",reflectFormName(this,this._name),this.sync(),this.requestUpdate("name",old)}get value(){return Object.freeze([...this._value])}set value(next){markVetoGuardWrite(this.toggleGuard);const requested=Array.isArray(next)?next.filter(entry=>typeof entry=="string"):[];if(this.boxes.length===0){this.pendingValues=requested;return}this.pendingValues=void 0,this.applyValues(requested)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.sync(),this.requestUpdate("required",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this.propagateDisabled(),this.sync(),this.requestUpdate("disabled",old)}constructor(){super(),this.orientation="vertical",this.label="",this.hint="",this.withLabel=!1,this.withHint=!1,this.errorText="",this.accessibleLabel="",this.hasInteracted=!1,this.slotPresence=new SlotPresenceController(this),this.labelId=nextId("checkbox-group-label"),this.hintId=nextId("checkbox-group-hint"),this.errorId=nextId("checkbox-group-error"),this.requiredDescriptionId=nextId("checkbox-group-required"),this._fieldsetDisabled=!1,this._name="",this._required=!1,this._disabled=!1,this._value=[],this.childObserverGeneration=0,this.childControllers=new Map,this.toggleGuard=new VetoWriteGuard,this.authoredChildSizes=new Map,this.markInteracted=()=>{this.hasInteracted||(this.hasInteracted=!0,this.reflectValidityStates())},this.syncQueued=!1,this.suppressCheckboxSync=!1,this.onChildEvent=event=>{if(!this.isOwnedCheckbox(event.target)||(event.stopImmediatePropagation(),event.type!=="change"||this.effectiveDisabled))return;this.hasInteracted=!0,this.sync();const value=this.value,detail=()=>Object.freeze({value:Object.freeze([...value])});emitValueEvents(this,"input",detail(),detail2=>this.emit("lr-input",detail2)),emitValueEvents(this,"change",detail(),detail2=>this.emit("lr-change",detail2))},this.onChildToggleRequest=event=>{if(!this.isOwnedCheckbox(event.target)||(event.stopImmediatePropagation(),this.effectiveDisabled))return;const option=event.target,proposed=event.detail.checked;let allowed=!1;requestThenCommit({requestDetail:{value:this.projectedValue(option,proposed),previousValue:this.value,option},emitRequest:(detail,init)=>this.emit("lr-checkbox-group-toggle-request",detail,init),guard:this.toggleGuard,commit:()=>{allowed=!0}}),allowed||event.preventDefault()},this.onChildMutations=records=>{if(records.some(record=>record.type==="childList"||record.attributeName==="slot")){this.onSlotChange();return}for(const record of records){if(record.attributeName!=="size"||!this.isOwnedCheckbox(record.target))continue;const box=record.target;this.size!==void 0&&box.size!==this.size&&this.authoredChildSizes.set(box,box.size)}records.some(record=>record.attributeName==="size"&&this.isOwnedCheckbox(record.target))&&this.propagateSize(),records.some(record=>this.isOwnedCheckbox(record.target))&&this.sync()},this.onSlotChange=()=>{this.cachedBoxes=void 0,this.reconcileChildControllers(),!this.applyPendingRestore()&&!this.applyPendingValues()&&this.sync(),this.propagateDisabled(),this.propagateSize()},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}checkboxGroupOwner(element){const group=element.closest(tag("checkbox-group"));if(!group)return null;let topLevelChild=element;for(;topLevelChild.parentElement&&topLevelChild.parentElement!==group;)topLevelChild=topLevelChild.parentElement;if(topLevelChild.parentElement!==group)return null;const slot=topLevelChild.getAttribute("slot");return slot==="label"||slot==="hint"||slot==="error"?null:group}ownsCheckbox(element){return element.localName===tag("checkbox")&&this.checkboxGroupOwner(element)===this}get boxes(){const querySelectorAll=this.querySelectorAll;return typeof querySelectorAll!="function"?[]:Array.from(querySelectorAll.call(this,"lr-checkbox")).filter(box=>this.ownsCheckbox(box))}syncBoxes(){return this.cachedBoxes||(this.cachedBoxes=this.boxes,queueMicrotask(()=>{this.cachedBoxes=void 0})),this.cachedBoxes}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}propagateDisabled(){const effective=this.effectiveDisabled;this.boxes.forEach(box=>box.setGroupDisabled?.(effective))}propagateSize(){for(const box of this.boxes)if(this.authoredChildSizes.has(box)||this.authoredChildSizes.set(box,box.size),this.size===void 0||this.size===null){const authored=this.authoredChildSizes.get(box);authored!==void 0&&box.size!==authored&&(box.size=authored),this.authoredChildSizes.delete(box)}else box.size!==this.size&&(box.size=this.size)}sync(){const next=[],seen=new Set;for(const box of this.syncBoxes()){const value=box.value??box.getAttribute("value")??"on";seen.has(value)&&devWarnOnce(DUPLICATE_VALUE_WARNING_KEY,DUPLICATE_VALUE_WARNING),seen.add(value),box.checked&&next.push(value)}const old=this._value;this._value=next,this.requestUpdate("value",old);const data=new FormData;this.name&&next.forEach(value=>data.append(this.name,value)),this.internals.setFormValue(this.name?data:null,createStringArrayFormDataState(this.name,next)),!this.barredFromValidation&&this.required&&next.length===0?this.validityController.setValidity({valueMissing:!0},this.localize("checkboxGroupRequired")):this.validityController.setValidity({}),this.reflectValidityStates()}scheduleSync(){this.syncQueued||(this.syncQueued=!0,queueMicrotask(()=>{this.syncQueued=!1,this.isConnected&&this.sync()}))}notifyCheckboxStateChange(checkbox){this.suppressCheckboxSync||this.isConnected&&this.ownsCheckbox(checkbox)&&this.sync()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}reflectValidityStates(){const barred=this.barredFromValidation;this.toggleAttribute("data-invalid",!barred&&this.hasInteracted&&!this.internals.validity.valid),syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred})}isOwnedCheckbox(target){return target?.nodeType===1&&this.ownsCheckbox(target)}projectedValue(option,proposed){return Object.freeze(this.boxes.filter(box=>box===option?proposed:box.checked).map(box=>box.value??"on"))}reconcileChildControllers(){const current=new Set(this.boxes);for(const[box,controller]of this.childControllers){if(current.has(box))continue;box.removeController(controller),this.childControllers.delete(box);const authoredSize=this.authoredChildSizes.get(box);authoredSize!==void 0&&box.size!==authoredSize&&(box.size=authoredSize),this.authoredChildSizes.delete(box);const nextOwner=this.checkboxGroupOwner(box);(!nextOwner||nextOwner===this)&&box.setGroupDisabled?.(!1)}for(const box of current){if(this.childControllers.has(box)||typeof box.addController!="function")continue;const controller={hostUpdated:()=>{this.isConnected&&this.ownsCheckbox(box)&&this.scheduleSync()}};box.addController(controller),this.childControllers.set(box,controller)}}applyValues(values){const remaining=new Map;for(const value of values)remaining.set(value,(remaining.get(value)??0)+1);this.suppressCheckboxSync=!0;try{for(const box of this.boxes){const value=box.value??"on",count=remaining.get(value)??0;box.checked=count>0,count>0&&remaining.set(value,count-1)}}finally{this.suppressCheckboxSync=!1}this.sync()}applyPendingRestore(){if(this.pendingRestoreValues===void 0||this.boxes.length===0)return!1;const values=this.pendingRestoreValues;return this.pendingRestoreValues=void 0,this.hasInteracted=!1,this.applyValues(values),!0}applyPendingValues(){if(this.pendingValues===void 0||this.boxes.length===0)return!1;const values=this.pendingValues;return this.pendingValues=void 0,this.applyValues(values),!0}connectedCallback(){super.connectedCallback(),this.cachedBoxes=void 0,this.addEventListener("input",this.onChildEvent,{capture:!0}),this.addEventListener("lr-input",this.onChildEvent,{capture:!0}),this.addEventListener("change",this.onChildEvent,{capture:!0}),this.addEventListener("lr-change",this.onChildEvent,{capture:!0}),this.addEventListener("lr-checkbox-toggle-request",this.onChildToggleRequest,{capture:!0}),this.hasUpdated?this.onSlotChange():(this.reconcileChildControllers(),!this.applyPendingRestore()&&!this.applyPendingValues()&&this.sync(),this.propagateDisabled(),this.propagateSize()),this.armChildObserver(),this.hasUpdated&&(this.syncRequiredDescription(),this.syncExternalDescription())}armChildObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected||this.childObserver&&this.childObserverDocument===ownerDocument)return;this.resetChildObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.childObserverGeneration,observer=new MutationObserverCtor(records=>{this.childObserver!==observer||this.childObserverDocument!==ownerDocument||this.childObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.onChildMutations(records)});this.childObserver=observer,this.childObserverDocument=ownerDocument,observer.observe(this,{attributes:!0,childList:!0,subtree:!0,attributeFilter:["checked","value","disabled","size","slot"]})}disconnectedCallback(){this.releaseExternalDescription(),this.releaseRequiredDescription(),this.cachedBoxes=void 0,this.removeEventListener("input",this.onChildEvent,{capture:!0}),this.removeEventListener("lr-input",this.onChildEvent,{capture:!0}),this.removeEventListener("change",this.onChildEvent,{capture:!0}),this.removeEventListener("lr-change",this.onChildEvent,{capture:!0}),this.removeEventListener("lr-checkbox-toggle-request",this.onChildToggleRequest,{capture:!0}),this.resetChildObserver();for(const[box,controller]of this.childControllers){box.removeController(controller),box.setGroupDisabled?.(!1);const authoredSize=this.authoredChildSizes.get(box);authoredSize!==void 0&&box.size!==authoredSize&&(box.size=authoredSize)}this.childControllers.clear(),this.authoredChildSizes.clear(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.releaseRequiredDescription(),this.resetChildObserver(),this.isConnected&&this.hasUpdated&&(this.syncRequiredDescription(),this.syncExternalDescription())}resetChildObserver(){this.childObserverGeneration+=1,this.childObserver?.disconnect(),this.childObserver=void 0,this.childObserverDocument=void 0}firstUpdated(changed){super.firstUpdated(changed),this.addEventListener("blur",event=>{const blurredControl=event.target;(typeof blurredControl?.matches=="function"?blurredControl.matches(":disabled"):this.effectiveDisabled)||(this.hasInteracted=!0),this.sync()},!0)}updated(changed){super.updated(changed),changed.has("size")&&this.propagateSize(),this.syncRequiredDescription(),this.syncExternalDescription()}syncExternalDescription(){const target=this.renderRoot.querySelector("fieldset");if(!target){this.releaseExternalDescription();return}if(!this.externalDescriptionLease){this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby");return}this.externalDescriptionLease.update(target)}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}syncRequiredDescription(){const target=this.renderRoot.querySelector("fieldset"),description=this.renderRoot.querySelector(`#${this.requiredDescriptionId}`);if(!this.required||!target||!description){this.releaseRequiredDescription();return}if(this.requiredDescriptionTarget!==target){this.releaseRequiredDescription(),this.requiredDescriptionTarget=target,this.requiredDescriptionLease=acquireAriaDescription(target,[description]);return}this.requiredDescriptionLease?.update([description])}releaseRequiredDescription(){this.requiredDescriptionLease?.release(),this.requiredDescriptionLease=void 0,this.requiredDescriptionTarget=void 0}[VALIDITY_ANCHOR](){const first=this.firstEnabledBox();return resolveValidityAnchor(first)??first??null}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}checkValidity(){return this.validityController.checkValidity()}reportValidity(){return this.validityController.syncConstraints(),this.hasInteracted=!0,this.reflectValidityStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.reflectValidityStates(),this.requestUpdate()}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}firstEnabledBox(){return this.boxes.find(box=>!box.effectiveDisabled&&!box.matches(":disabled"))}focus(options){this.liveDisabled||this.firstEnabledBox()?.focus(options)}blur(){this.boxes.find(box=>box.matches(":focus-within"))?.blur()}click(){this.liveDisabled||this.firstEnabledBox()?.click()}formResetCallback(){this.suppressCheckboxSync=!0;try{this.boxes.forEach(box=>box.resetFromGroup())}finally{this.suppressCheckboxSync=!1}this.hasInteracted=!1,this.sync()}formStateRestoreCallback(state2,_mode){this.pendingRestoreValues=readStringArrayFormDataState(state2),this.applyPendingRestore()}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(this.propagateDisabled(),this.sync(),this.requestUpdate())}render(){const hasLabel=this.hasLabelSlot||!!this.label||this.withLabel,hasHint=this.hasHintSlot||!!this.hint||this.withHint,hasError=this.hasErrorSlot||!!this.errorText,described=[hasHint?this.hintId:"",hasError?this.errorId:""].filter(Boolean).join(" ")||nothing,invalid=hasError||this.hasInteracted&&!this.internals.validity.valid;return html`<fieldset
|
|
1
|
+
import{__decorate}from"tslib";import{emitValueEvents}from"../../../internal/value-events.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{FormControlController,reflectFormName}from"../../../internal/form-control-controller.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{tag}from"../../../internal/prefix.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{resolveValidityAnchor,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{hostAriaLabel,nextId,srOnly}from"../../../internal/a11y.js";import{acquireAriaDescription,acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./checkbox-group.styles.js";import{createStringArrayFormDataState,getFormOwner,isBarredFromValidation,readStringArrayFormDataState,setFormOwner}from"../../../internal/form-associated.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{LYRA_DEFAULT_checkboxGroupRequired}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();const DUPLICATE_VALUE_WARNING_KEY="lyra-checkbox-group-duplicate-child-values",DUPLICATE_VALUE_WARNING="<lr-checkbox-group>: duplicate child values make submitted FormData ambiguous; give each child a distinct value.";class LyraCheckboxGroup extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,checkboxGroupRequired:LYRA_DEFAULT_checkboxGroupRequired,fieldRequired:LYRA_DEFAULT_fieldRequired}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-checkbox-group-toggle-request"])}static{this.identityEventDetailProperties=Object.freeze({"lr-checkbox-group-toggle-request":Object.freeze(["option"])})}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},size:{reflect:!0},orientation:{reflect:!0},value:{attribute:!1,noAccessor:!0}}}get hasLabelSlot(){return this.slotPresence.has("label")}get hasHintSlot(){return this.slotPresence.has("hint")}get hasErrorSlot(){return this.slotPresence.has("error")}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",reflectFormName(this,this._name),this.sync(),this.requestUpdate("name",old)}get value(){return Object.freeze([...this._value])}set value(next){markVetoGuardWrite(this.toggleGuard);const requested=Array.isArray(next)?next.filter(entry=>typeof entry=="string"):[];if(this.boxes.length===0){this.pendingValues=requested;return}this.pendingValues=void 0,this.applyValues(requested)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.sync(),this.requestUpdate("required",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this.propagateDisabled(),this.sync(),this.requestUpdate("disabled",old)}constructor(){super(),this.orientation="vertical",this.label="",this.hint="",this.withLabel=!1,this.withHint=!1,this.errorText="",this.accessibleLabel="",this.hasInteracted=!1,this.slotPresence=new SlotPresenceController(this),this.labelId=nextId("checkbox-group-label"),this.hintId=nextId("checkbox-group-hint"),this.errorId=nextId("checkbox-group-error"),this.requiredDescriptionId=nextId("checkbox-group-required"),this._fieldsetDisabled=!1,this._name="",this._required=!1,this._disabled=!1,this._value=[],this.childObserverGeneration=0,this.childControllers=new Map,this.toggleGuard=new VetoWriteGuard,this.authoredChildSizes=new Map,this.markInteracted=()=>{this.hasInteracted||(this.hasInteracted=!0,this.reflectValidityStates())},this.syncQueued=!1,this.suppressCheckboxSync=!1,this.onChildEvent=event=>{if(!this.isOwnedCheckbox(event.target)||(event.stopImmediatePropagation(),event.type!=="change"||this.effectiveDisabled))return;this.hasInteracted=!0,this.sync();const value=this.value,detail=()=>Object.freeze({value:Object.freeze([...value])});emitValueEvents(this,"input",detail(),detail2=>this.emit("lr-input",detail2)),emitValueEvents(this,"change",detail(),detail2=>this.emit("lr-change",detail2))},this.onChildToggleRequest=event=>{if(!this.isOwnedCheckbox(event.target)||(event.stopImmediatePropagation(),this.effectiveDisabled))return;const option=event.target,proposed=event.detail.checked;let allowed=!1;requestThenCommit({requestDetail:{value:this.projectedValue(option,proposed),previousValue:this.value,option},emitRequest:(detail,init)=>this.emit("lr-checkbox-group-toggle-request",detail,init),guard:this.toggleGuard,commit:()=>{allowed=!0}}),allowed||event.preventDefault()},this.onChildMutations=records=>{if(records.some(record=>record.type==="childList"||record.attributeName==="slot")){this.onSlotChange();return}for(const record of records){if(record.attributeName!=="size"||!this.isOwnedCheckbox(record.target))continue;const box=record.target;this.size!==void 0&&box.size!==this.size&&this.authoredChildSizes.set(box,box.size)}records.some(record=>record.attributeName==="size"&&this.isOwnedCheckbox(record.target))&&this.propagateSize(),records.some(record=>this.isOwnedCheckbox(record.target))&&this.sync()},this.onSlotChange=()=>{this.cachedBoxes=void 0,this.reconcileChildControllers(),!this.applyPendingRestore()&&!this.applyPendingValues()&&this.sync(),this.propagateDisabled(),this.propagateSize()},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}checkboxGroupOwner(element){const group=element.closest(tag("checkbox-group"));if(!group)return null;let topLevelChild=element;for(;topLevelChild.parentElement&&topLevelChild.parentElement!==group;)topLevelChild=topLevelChild.parentElement;if(topLevelChild.parentElement!==group)return null;const slot=topLevelChild.getAttribute("slot");return slot==="label"||slot==="hint"||slot==="error"?null:group}ownsCheckbox(element){return element.localName===tag("checkbox")&&this.checkboxGroupOwner(element)===this}get boxes(){const querySelectorAll=this.querySelectorAll;return typeof querySelectorAll!="function"?[]:Array.from(querySelectorAll.call(this,"lr-checkbox")).filter(box=>this.ownsCheckbox(box))}syncBoxes(){return this.cachedBoxes||(this.cachedBoxes=this.boxes,queueMicrotask(()=>{this.cachedBoxes=void 0})),this.cachedBoxes}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}propagateDisabled(){const effective=this.effectiveDisabled;this.boxes.forEach(box=>box.setGroupDisabled?.(effective))}propagateSize(){for(const box of this.boxes)if(this.authoredChildSizes.has(box)||this.authoredChildSizes.set(box,box.size),this.size===void 0||this.size===null){const authored=this.authoredChildSizes.get(box);authored!==void 0&&box.size!==authored&&(box.size=authored),this.authoredChildSizes.delete(box)}else box.size!==this.size&&(box.size=this.size)}sync(){const next=[],seen=new Set;for(const box of this.syncBoxes()){const value=box.value??box.getAttribute("value")??"on";seen.has(value)&&devWarnOnce(DUPLICATE_VALUE_WARNING_KEY,DUPLICATE_VALUE_WARNING),seen.add(value),box.checked&&next.push(value)}const old=this._value;this._value=next,this.requestUpdate("value",old);const data=new FormData;this.name&&next.forEach(value=>data.append(this.name,value)),this.internals.setFormValue(this.name?data:null,createStringArrayFormDataState(this.name,next)),!this.barredFromValidation&&this.required&&next.length===0?this.validityController.setValidity({valueMissing:!0},this.localize("checkboxGroupRequired")):this.validityController.setValidity({}),this.reflectValidityStates()}scheduleSync(){this.syncQueued||(this.syncQueued=!0,queueMicrotask(()=>{this.syncQueued=!1,this.isConnected&&this.sync()}))}notifyCheckboxStateChange(checkbox){this.suppressCheckboxSync||this.isConnected&&this.ownsCheckbox(checkbox)&&this.sync()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}reflectValidityStates(){const barred=this.barredFromValidation;this.toggleAttribute("data-invalid",!barred&&this.hasInteracted&&!this.internals.validity.valid),syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred})}isOwnedCheckbox(target){return target?.nodeType===1&&this.ownsCheckbox(target)}projectedValue(option,proposed){return Object.freeze(this.boxes.filter(box=>box===option?proposed:box.checked).map(box=>box.value??"on"))}reconcileChildControllers(){const current=new Set(this.boxes);for(const[box,controller]of this.childControllers){if(current.has(box))continue;box.removeController(controller),this.childControllers.delete(box);const authoredSize=this.authoredChildSizes.get(box);authoredSize!==void 0&&box.size!==authoredSize&&(box.size=authoredSize),this.authoredChildSizes.delete(box);const nextOwner=this.checkboxGroupOwner(box);(!nextOwner||nextOwner===this)&&box.setGroupDisabled?.(!1)}for(const box of current){if(this.childControllers.has(box)||typeof box.addController!="function")continue;const controller={hostUpdated:()=>{this.isConnected&&this.ownsCheckbox(box)&&this.scheduleSync()}};box.addController(controller),this.childControllers.set(box,controller)}}applyValues(values){const remaining=new Map;for(const value of values)remaining.set(value,(remaining.get(value)??0)+1);this.suppressCheckboxSync=!0;try{for(const box of this.boxes){const value=box.value??"on",count=remaining.get(value)??0;box.checked=count>0,count>0&&remaining.set(value,count-1)}}finally{this.suppressCheckboxSync=!1}this.sync()}applyPendingRestore(){if(this.pendingRestoreValues===void 0||this.boxes.length===0)return!1;const values=this.pendingRestoreValues;return this.pendingRestoreValues=void 0,this.hasInteracted=!1,this.applyValues(values),!0}applyPendingValues(){if(this.pendingValues===void 0||this.boxes.length===0)return!1;const values=this.pendingValues;return this.pendingValues=void 0,this.applyValues(values),!0}connectedCallback(){super.connectedCallback(),this.cachedBoxes=void 0,this.addEventListener("input",this.onChildEvent,{capture:!0}),this.addEventListener("lr-input",this.onChildEvent,{capture:!0}),this.addEventListener("change",this.onChildEvent,{capture:!0}),this.addEventListener("lr-change",this.onChildEvent,{capture:!0}),this.addEventListener("lr-checkbox-toggle-request",this.onChildToggleRequest,{capture:!0}),this.hasUpdated?this.onSlotChange():(this.reconcileChildControllers(),!this.applyPendingRestore()&&!this.applyPendingValues()&&this.sync(),this.propagateDisabled(),this.propagateSize()),this.armChildObserver(),this.hasUpdated&&(this.syncRequiredDescription(),this.syncExternalDescription())}armChildObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected||this.childObserver&&this.childObserverDocument===ownerDocument)return;this.resetChildObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.childObserverGeneration,observer=new MutationObserverCtor(records=>{this.childObserver!==observer||this.childObserverDocument!==ownerDocument||this.childObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.onChildMutations(records)});this.childObserver=observer,this.childObserverDocument=ownerDocument,observer.observe(this,{attributes:!0,childList:!0,subtree:!0,attributeFilter:["checked","value","disabled","size","slot"]})}disconnectedCallback(){this.releaseExternalDescription(),this.releaseRequiredDescription(),this.cachedBoxes=void 0,this.removeEventListener("input",this.onChildEvent,{capture:!0}),this.removeEventListener("lr-input",this.onChildEvent,{capture:!0}),this.removeEventListener("change",this.onChildEvent,{capture:!0}),this.removeEventListener("lr-change",this.onChildEvent,{capture:!0}),this.removeEventListener("lr-checkbox-toggle-request",this.onChildToggleRequest,{capture:!0}),this.resetChildObserver();for(const[box,controller]of this.childControllers){box.removeController(controller),box.setGroupDisabled?.(!1);const authoredSize=this.authoredChildSizes.get(box);authoredSize!==void 0&&box.size!==authoredSize&&(box.size=authoredSize)}this.childControllers.clear(),this.authoredChildSizes.clear(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.releaseRequiredDescription(),this.resetChildObserver(),this.isConnected&&this.hasUpdated&&(this.syncRequiredDescription(),this.syncExternalDescription())}resetChildObserver(){this.childObserverGeneration+=1,this.childObserver?.disconnect(),this.childObserver=void 0,this.childObserverDocument=void 0}firstUpdated(changed){super.firstUpdated(changed),this.addEventListener("blur",event=>{const blurredControl=event.target;(typeof blurredControl?.matches=="function"?blurredControl.matches(":disabled"):this.effectiveDisabled)||(this.hasInteracted=!0),this.sync()},!0)}updated(changed){super.updated(changed),changed.has("size")&&this.propagateSize(),this.syncRequiredDescription(),this.syncExternalDescription()}syncExternalDescription(){const target=this.isConnected?this.renderRoot.querySelector("fieldset"):null;if(!target){this.releaseExternalDescription();return}if(!this.externalDescriptionLease){this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby");return}this.externalDescriptionLease.update(target)}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}syncRequiredDescription(){const target=this.isConnected?this.renderRoot.querySelector("fieldset"):null,description=this.renderRoot.querySelector(`#${this.requiredDescriptionId}`);if(!this.required||!target||!description){this.releaseRequiredDescription();return}if(this.requiredDescriptionTarget!==target){this.releaseRequiredDescription(),this.requiredDescriptionTarget=target,this.requiredDescriptionLease=acquireAriaDescription(target,[description]);return}this.requiredDescriptionLease?.update([description])}releaseRequiredDescription(){this.requiredDescriptionLease?.release(),this.requiredDescriptionLease=void 0,this.requiredDescriptionTarget=void 0}[VALIDITY_ANCHOR](){const first=this.firstEnabledBox();return resolveValidityAnchor(first)??first??null}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}checkValidity(){return this.validityController.checkValidity()}reportValidity(){return this.validityController.syncConstraints(),this.hasInteracted=!0,this.reflectValidityStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.reflectValidityStates(),this.requestUpdate()}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}firstEnabledBox(){return this.boxes.find(box=>!box.effectiveDisabled&&!box.matches(":disabled"))}focus(options){this.liveDisabled||this.firstEnabledBox()?.focus(options)}blur(){this.boxes.find(box=>box.matches(":focus-within"))?.blur()}click(){this.liveDisabled||this.firstEnabledBox()?.click()}formResetCallback(){this.suppressCheckboxSync=!0;try{this.boxes.forEach(box=>box.resetFromGroup())}finally{this.suppressCheckboxSync=!1}this.hasInteracted=!1,this.sync()}formStateRestoreCallback(state2,_mode){this.pendingRestoreValues=readStringArrayFormDataState(state2),this.applyPendingRestore()}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(this.propagateDisabled(),this.sync(),this.requestUpdate())}render(){const hasLabel=this.hasLabelSlot||!!this.label||this.withLabel,hasHint=this.hasHintSlot||!!this.hint||this.withHint,hasError=this.hasErrorSlot||!!this.errorText,described=[hasHint?this.hintId:"",hasError?this.errorId:""].filter(Boolean).join(" ")||nothing,invalid=hasError||this.hasInteracted&&!this.internals.validity.valid;return html`<fieldset
|
|
2
2
|
part="form-control"
|
|
3
3
|
?disabled=${this.effectiveDisabled}
|
|
4
4
|
aria-label=${hostAriaLabel(this)??nothing}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{finiteRange}from"../../../internal/numbers.js";const CSS_WIDE_KEYWORDS=/^(?:inherit|initial|unset|revert|revert-layer|currentcolor)$/i,HEX_PATTERN=/^#([0-9a-f]+)$/i,FUNCTION_PATTERN=/^([a-z]+)\(([^()]*)\)$/i,NUMBER_PATTERN=/^([-+]?(?:\d+(?:\.\d*)?|\.\d+))(%?)$/,ANGLE_PATTERN=/^([-+]?(?:\d+(?:\.\d*)?|\.\d+))(deg|grad|rad|turn)?$/i,clamp=(value,min,max)=>finiteRange(value,min,min,max);function normalizeHue(hue){if(!Number.isFinite(hue))return 0;if(hue===360)return 360;const wrapped=hue%360;return wrapped<0?wrapped+360:wrapped}function hsva(h,s,v,a=1){return{h:normalizeHue(h),s:clamp(s,0,100),v:clamp(v,0,100),a:clamp(a,0,1)}}function hsvToRgb(h,s,v){const sector=normalizeHue(h)/60,saturation=clamp(s,0,100)/100,value=clamp(v,0,100)/100,chroma=value*saturation,secondary=chroma*(1-Math.abs(sector%2-1)),base=value-chroma;let r=0,g=0,b=0;return sector<1?[r,g,b]=[chroma,secondary,0]:sector<2?[r,g,b]=[secondary,chroma,0]:sector<3?[r,g,b]=[0,chroma,secondary]:sector<4?[r,g,b]=[0,secondary,chroma]:sector<5?[r,g,b]=[secondary,0,chroma]:[r,g,b]=[chroma,0,secondary],{r:(r+base)*255,g:(g+base)*255,b:(b+base)*255}}function rgbToHsv(r,g,b){const red=clamp(r,0,255)/255,green=clamp(g,0,255)/255,blue=clamp(b,0,255)/255,max=Math.max(red,green,blue),min=Math.min(red,green,blue),chroma=max-min;let hue=0;return chroma!==0&&(max===red?hue=60*((green-blue)/chroma%6):max===green?hue=60*((blue-red)/chroma+2):hue=60*((red-green)/chroma+4)),{h:normalizeHue(hue),s:max===0?0:chroma/max*100,v:max*100}}function hsvToHsl(h,s,v){const value=clamp(v,0,100)/100,saturation=clamp(s,0,100)/100,lightness=value*(1-saturation/2),denominator=Math.min(lightness,1-lightness);return{h:normalizeHue(h),s:denominator===0?0:(value-lightness)/denominator*100,l:lightness*100}}function hslToHsv(h,s,l){const lightness=clamp(l,0,100)/100,saturation=clamp(s,0,100)/100,value=lightness+saturation*Math.min(lightness,1-lightness);return{h:normalizeHue(h),s:value===0?0:2*(1-lightness/value)*100,v:value*100}}function parseNumber(text,percentBase){if(text===void 0)return null;const match=NUMBER_PATTERN.exec(text.trim());if(!match)return null;const raw=Number(match[1]);return Number.isFinite(raw)?match[2]==="%"?raw/100*percentBase:raw:null}function parseAngle(text){if(text===void 0)return null;const match=ANGLE_PATTERN.exec(text.trim());if(!match)return null;const raw=Number(match[1]);if(!Number.isFinite(raw))return null;switch((match[2]??"deg").toLowerCase()){case"grad":return raw*360/400;case"rad":return raw*180/Math.PI;case"turn":return raw*360;default:return raw}}function splitArguments(body){const[head="",tail]=body.split("/"),channels=head.split(/[,\s]+/).map(entry=>entry.trim()).filter(Boolean);return tail!==void 0?{channels,alpha:tail.trim()}:channels.length===4?{channels:channels.slice(0,3),alpha:channels[3]}:{channels}}function parseHex(text){const match=HEX_PATTERN.exec(text);if(!match)return null;const digits=match[1],short=digits.length===3||digits.length===4,long=digits.length===6||digits.length===8;if(!short&&!long)return null;const size=short?1:2,channel=index=>{const slice=digits.slice(index*size,index*size+size);return Number.parseInt(short?slice+slice:slice,16)},hasAlpha=digits.length===4||digits.length===8,{h,s,v}=rgbToHsv(channel(0),channel(1),channel(2));return hsva(h,s,v,hasAlpha?channel(3)/255:1)}const float32=Math.fround,BROWSER_ROUNDING_EPSILON=float32(1e-7),BYTE_MARGIN=1e-9;function browserHslBytes(hue,saturation,lightness){const h=float32(normalizeHue(hue)),s=float32(clamp(saturation,0,100)/100),l=float32(clamp(lightness,0,100)/100),channel=offset=>{let value=l;if(s!==0){const k=float32(offset+float32(h/30))%12,a=float32(s*Math.min(l,float32(1-l))),t=Math.max(-1,Math.min(float32(k-3),float32(9-k),1));value=float32(l-float32(a*t))}return Math.round(clamp(float32(float32(value+BROWSER_ROUNDING_EPSILON)*255),0,255))};return[channel(0),channel(8),channel(4)]}function settleOnBytes(color,bytes){const{r,g,b}=hsvToRgb(color.h,color.s,color.v),channels=[r,g,b];if(channels.every((channel,index)=>Math.round(channel)===bytes[index]))return color;const[red=0,green=0,blue=0]=channels.map((channel,index)=>{const byte=bytes[index]??0;return clamp(channel,byte-.5+BYTE_MARGIN,byte+.5-BYTE_MARGIN)}),settled=rgbToHsv(red,green,blue),keepHue=settled.s===0||settled.h===0&&color.h===360;return hsva(keepHue?color.h:settled.h,settled.s,settled.v,color.a)}function parseFunctional(text){const match=FUNCTION_PATTERN.exec(text);if(!match)return null;const name=match[1].toLowerCase(),{channels,alpha}=splitArguments(match[2]??"");if(channels.length!==3)return null;const alphaValue=alpha===void 0?1:parseNumber(alpha,1);if(alphaValue===null)return null;if(name==="rgb"||name==="rgba"){const r=parseNumber(channels[0],255),g=parseNumber(channels[1],255),b=parseNumber(channels[2],255);if(r===null||g===null||b===null)return null;const converted=rgbToHsv(r,g,b);return hsva(converted.h,converted.s,converted.v,alphaValue)}if(name==="hsl"||name==="hsla"||name==="hsv"||name==="hsva"){const h=parseAngle(channels[0]),second=parseNumber(channels[1],100),third=parseNumber(channels[2],100);if(h===null||second===null||third===null)return null;if(name.startsWith("hsv"))return hsva(h,second,third,alphaValue);const converted=hslToHsv(h,second,third);return settleOnBytes(hsva(converted.h,converted.s,converted.v,alphaValue),browserHslBytes(h,second,third))}return null}function parseViaCssom(text){if(typeof document>"u"||CSS_WIDE_KEYWORDS.test(text))return null;const cached=cssomCache.get(text);if(cached!==void 0)return cached;const resolved=resolveViaCssom(text);return cssomCache.size>=CSSOM_CACHE_LIMIT&&cssomCache.clear(),cssomCache.set(text,resolved),resolved}const CSSOM_CACHE_LIMIT=64,cssomCache=new Map;function resolveViaCssom(text){const probe=document.createElement("span");if(probe.style.color=text,probe.style.color==="")return null;probe.style.position="absolute",probe.style.visibility="hidden",probe.style.pointerEvents="none",document.body.append(probe);const computed=getComputedStyle(probe).color;probe.remove();const serialized=computed.trim(),functional=parseFunctional(serialized);if(functional)return functional;const canvas=document.createElement("canvas");canvas.width=1,canvas.height=1;const context=canvas.getContext("2d",{willReadFrequently:!0});if(!context)return null;context.clearRect(0,0,1,1),context.fillStyle=serialized,context.fillRect(0,0,1,1);const[red=0,green=0,blue=0,alpha=0]=context.getImageData(0,0,1,1).data,converted=rgbToHsv(red,green,blue);return hsva(converted.h,converted.s,converted.v,alpha/255)}function parseColor(input){const text=(input??"").trim();return text===""?null:parseHex(text)??parseFunctional(text)??parseViaCssom(text)}const hexByte=channel=>Math.round(clamp(channel,0,255)).toString(16).padStart(2,"0"),round=value=>String(Math.round(value)),alphaText=alpha=>clamp(alpha,0,1).toFixed(2);function formatColor(color,format,uppercase=!1){const{r,g,b}=hsvToRgb(color.h,color.s,color.v);let text;switch(format){case"hex":text=`#${hexByte(r)}${hexByte(g)}${hexByte(b)}`;break;case"hexa":text=`#${hexByte(r)}${hexByte(g)}${hexByte(b)}${hexByte(color.a*255)}`;break;case"rgb":text=`rgb(${round(r)}, ${round(g)}, ${round(b)})`;break;case"rgba":text=`rgba(${round(r)}, ${round(g)}, ${round(b)}, ${alphaText(color.a)})`;break;case"hsv":text=`hsv(${round(color.h)}, ${round(color.s)}%, ${round(color.v)}%)`;break;case"hsva":text=`hsva(${round(color.h)}, ${round(color.s)}%, ${round(color.v)}%, ${alphaText(color.a)})`;break;default:{const hsl=hsvToHsl(color.h,color.s,color.v);text=format==="hsla"?`hsla(${round(hsl.h)}, ${round(hsl.s)}%, ${round(hsl.l)}%, ${alphaText(color.a)})`:`hsl(${round(hsl.h)}, ${round(hsl.s)}%, ${round(hsl.l)}%)`;break}}return uppercase?text.toUpperCase():text}function withAlphaFormat(format,includeAlpha){return includeAlpha?`${format}a`:format}function cssColor(color){const{r,g,b}=hsvToRgb(color.h,color.s,color.v);return`rgba(${round(r)}, ${round(g)}, ${round(b)}, ${alphaText(color.a)})`}function sameColor(left,right){return formatColor(left,"hexa")===formatColor(right,"hexa")}export{cssColor,formatColor,hslToHsv,hsvToHsl,hsvToRgb,hsva,parseColor,rgbToHsv,sameColor,withAlphaFormat};
|
|
1
|
+
import{finiteRange}from"../../../internal/numbers.js";const CSS_WIDE_KEYWORDS=/^(?:inherit|initial|unset|revert|revert-layer|currentcolor)$/i,HEX_PATTERN=/^#([0-9a-f]+)$/i,FUNCTION_PATTERN=/^([a-z]+)\(([^()]*)\)$/i,NUMBER_PATTERN=/^([-+]?(?:\d+(?:\.\d*)?|\.\d+))(%?)$/,ANGLE_PATTERN=/^([-+]?(?:\d+(?:\.\d*)?|\.\d+))(deg|grad|rad|turn)?$/i,clamp=(value,min,max)=>finiteRange(value,min,min,max);function normalizeHue(hue){if(!Number.isFinite(hue))return 0;if(hue===360)return 360;const wrapped=hue%360;return wrapped<0?wrapped+360:wrapped}function hsva(h,s,v,a=1){return{h:normalizeHue(h),s:clamp(s,0,100),v:clamp(v,0,100),a:clamp(a,0,1)}}function hsvToRgb(h,s,v){const sector=normalizeHue(h)/60,saturation=clamp(s,0,100)/100,value=clamp(v,0,100)/100,chroma=value*saturation,secondary=chroma*(1-Math.abs(sector%2-1)),base=value-chroma;let r=0,g=0,b=0;return sector<1?[r,g,b]=[chroma,secondary,0]:sector<2?[r,g,b]=[secondary,chroma,0]:sector<3?[r,g,b]=[0,chroma,secondary]:sector<4?[r,g,b]=[0,secondary,chroma]:sector<5?[r,g,b]=[secondary,0,chroma]:[r,g,b]=[chroma,0,secondary],{r:(r+base)*255,g:(g+base)*255,b:(b+base)*255}}function rgbToHsv(r,g,b){const red=clamp(r,0,255)/255,green=clamp(g,0,255)/255,blue=clamp(b,0,255)/255,max=Math.max(red,green,blue),min=Math.min(red,green,blue),chroma=max-min;let hue=0;return chroma!==0&&(max===red?hue=60*((green-blue)/chroma%6):max===green?hue=60*((blue-red)/chroma+2):hue=60*((red-green)/chroma+4)),{h:normalizeHue(hue),s:max===0?0:chroma/max*100,v:max*100}}function hsvToHsl(h,s,v){const value=clamp(v,0,100)/100,saturation=clamp(s,0,100)/100,lightness=value*(1-saturation/2),denominator=Math.min(lightness,1-lightness);return{h:normalizeHue(h),s:denominator===0?0:(value-lightness)/denominator*100,l:lightness*100}}function hslToHsv(h,s,l){const lightness=clamp(l,0,100)/100,saturation=clamp(s,0,100)/100,value=lightness+saturation*Math.min(lightness,1-lightness);return{h:normalizeHue(h),s:value===0?0:2*(1-lightness/value)*100,v:value*100}}function parseNumber(text,percentBase){if(text===void 0)return null;const match=NUMBER_PATTERN.exec(text.trim());if(!match)return null;const raw=Number(match[1]);return Number.isFinite(raw)?match[2]==="%"?clamp(raw,0,100)/100*percentBase:raw:null}function parseAngle(text){if(text===void 0)return null;const match=ANGLE_PATTERN.exec(text.trim());if(!match)return null;const raw=Number(match[1]);if(!Number.isFinite(raw))return null;switch((match[2]??"deg").toLowerCase()){case"grad":return raw*360/400;case"rad":return raw*180/Math.PI;case"turn":return raw*360;default:return raw}}function splitArguments(body){const[head="",tail]=body.split("/"),channels=head.split(/[,\s]+/).map(entry=>entry.trim()).filter(Boolean);return tail!==void 0?{channels,alpha:tail.trim()}:channels.length===4?{channels:channels.slice(0,3),alpha:channels[3]}:{channels}}function parseHex(text){const match=HEX_PATTERN.exec(text);if(!match)return null;const digits=match[1],short=digits.length===3||digits.length===4,long=digits.length===6||digits.length===8;if(!short&&!long)return null;const size=short?1:2,channel=index=>{const slice=digits.slice(index*size,index*size+size);return Number.parseInt(short?slice+slice:slice,16)},hasAlpha=digits.length===4||digits.length===8,{h,s,v}=rgbToHsv(channel(0),channel(1),channel(2));return hsva(h,s,v,hasAlpha?channel(3)/255:1)}const float32=Math.fround,BROWSER_ROUNDING_EPSILON=float32(1e-7),BYTE_MARGIN=1e-9;function browserHslBytes(hue,saturation,lightness){const h=float32(normalizeHue(hue)),s=float32(clamp(saturation,0,100)/100),l=float32(clamp(lightness,0,100)/100),channel=offset=>{let value=l;if(s!==0){const k=float32(offset+float32(h/30))%12,a=float32(s*Math.min(l,float32(1-l))),t=Math.max(-1,Math.min(float32(k-3),float32(9-k),1));value=float32(l-float32(a*t))}return Math.round(clamp(float32(float32(value+BROWSER_ROUNDING_EPSILON)*255),0,255))};return[channel(0),channel(8),channel(4)]}function settleOnBytes(color,bytes){const{r,g,b}=hsvToRgb(color.h,color.s,color.v),channels=[r,g,b];if(channels.every((channel,index)=>Math.round(channel)===bytes[index]))return color;const[red=0,green=0,blue=0]=channels.map((channel,index)=>{const byte=bytes[index]??0;return clamp(channel,byte-.5+BYTE_MARGIN,byte+.5-BYTE_MARGIN)}),settled=rgbToHsv(red,green,blue),keepHue=settled.s===0||settled.h===0&&color.h===360;return hsva(keepHue?color.h:settled.h,settled.s,settled.v,color.a)}function parseFunctional(text){const match=FUNCTION_PATTERN.exec(text);if(!match)return null;const name=match[1].toLowerCase(),{channels,alpha}=splitArguments(match[2]??"");if(channels.length!==3)return null;const alphaValue=alpha===void 0?1:parseNumber(alpha,1);if(alphaValue===null)return null;if(name==="rgb"||name==="rgba"){const r=parseNumber(channels[0],255),g=parseNumber(channels[1],255),b=parseNumber(channels[2],255);if(r===null||g===null||b===null)return null;const converted=rgbToHsv(r,g,b);return hsva(converted.h,converted.s,converted.v,alphaValue)}if(name==="hsl"||name==="hsla"||name==="hsv"||name==="hsva"){const h=parseAngle(channels[0]),second=parseNumber(channels[1],100),third=parseNumber(channels[2],100);if(h===null||second===null||third===null)return null;if(name.startsWith("hsv"))return hsva(h,second,third,alphaValue);const converted=hslToHsv(h,second,third);return settleOnBytes(hsva(converted.h,converted.s,converted.v,alphaValue),browserHslBytes(h,second,third))}return null}function parseViaCssom(text){if(typeof document>"u"||CSS_WIDE_KEYWORDS.test(text))return null;const cached=cssomCache.get(text);if(cached!==void 0)return cached;const resolved=resolveViaCssom(text);return cssomCache.size>=CSSOM_CACHE_LIMIT&&cssomCache.clear(),cssomCache.set(text,resolved),resolved}const CSSOM_CACHE_LIMIT=64,cssomCache=new Map;function resolveViaCssom(text){const probe=document.createElement("span");if(probe.style.color=text,probe.style.color==="")return null;probe.style.position="absolute",probe.style.visibility="hidden",probe.style.pointerEvents="none",document.body.append(probe);const computed=getComputedStyle(probe).color;probe.remove();const serialized=computed.trim(),functional=parseFunctional(serialized);if(functional)return functional;const canvas=document.createElement("canvas");canvas.width=1,canvas.height=1;const context=canvas.getContext("2d",{willReadFrequently:!0});if(!context)return null;context.clearRect(0,0,1,1),context.fillStyle=serialized,context.fillRect(0,0,1,1);const[red=0,green=0,blue=0,alpha=0]=context.getImageData(0,0,1,1).data,converted=rgbToHsv(red,green,blue);return hsva(converted.h,converted.s,converted.v,alpha/255)}function parseColor(input){const text=(input??"").trim();return text===""?null:parseHex(text)??parseFunctional(text)??parseViaCssom(text)}const hexByte=channel=>Math.round(clamp(channel,0,255)).toString(16).padStart(2,"0"),round=value=>String(Math.round(value)),alphaText=alpha=>clamp(alpha,0,1).toFixed(2);function formatColor(color,format,uppercase=!1){const{r,g,b}=hsvToRgb(color.h,color.s,color.v);let text;switch(format){case"hex":text=`#${hexByte(r)}${hexByte(g)}${hexByte(b)}`;break;case"hexa":text=`#${hexByte(r)}${hexByte(g)}${hexByte(b)}${hexByte(color.a*255)}`;break;case"rgb":text=`rgb(${round(r)}, ${round(g)}, ${round(b)})`;break;case"rgba":text=`rgba(${round(r)}, ${round(g)}, ${round(b)}, ${alphaText(color.a)})`;break;case"hsv":text=`hsv(${round(color.h)}, ${round(color.s)}%, ${round(color.v)}%)`;break;case"hsva":text=`hsva(${round(color.h)}, ${round(color.s)}%, ${round(color.v)}%, ${alphaText(color.a)})`;break;default:{const hsl=hsvToHsl(color.h,color.s,color.v);text=format==="hsla"?`hsla(${round(hsl.h)}, ${round(hsl.s)}%, ${round(hsl.l)}%, ${alphaText(color.a)})`:`hsl(${round(hsl.h)}, ${round(hsl.s)}%, ${round(hsl.l)}%)`;break}}return uppercase?text.toUpperCase():text}function withAlphaFormat(format,includeAlpha){return includeAlpha?`${format}a`:format}function cssColor(color){const{r,g,b}=hsvToRgb(color.h,color.s,color.v);return`rgba(${round(r)}, ${round(g)}, ${round(b)}, ${alphaText(color.a)})`}function sameColor(left,right){return formatColor(left,"hexa")===formatColor(right,"hexa")}export{cssColor,formatColor,hslToHsv,hsvToHsl,hsvToRgb,hsva,parseColor,rgbToHsv,sameColor,withAlphaFormat};
|
|
@@ -149,7 +149,8 @@ export type LyraComboboxChangeEvent<Multiple extends boolean=boolean> =LyraCombo
|
|
|
149
149
|
* a host that owns its own retry timing.
|
|
150
150
|
* @method refresh - `refresh(): void` — re-runs the current `source` query without changing the
|
|
151
151
|
* source's identity, its debounce controller, or its delay. Queues for the next open when the
|
|
152
|
-
* listbox is closed; does
|
|
152
|
+
* listbox is closed; does not call a source while the query is below `minQueryLength`, and
|
|
153
|
+
* does nothing without a `source`.
|
|
153
154
|
* @slot source-error - Replaces the built-in failed-`source` state, retry control included. Named
|
|
154
155
|
* apart from the form-control `error` slot deliberately: they are different failures and a
|
|
155
156
|
* control has to be able to show both.
|
|
@@ -158,8 +159,8 @@ export type LyraComboboxChangeEvent<Multiple extends boolean=boolean> =LyraCombo
|
|
|
158
159
|
* @event lr-after-show - The listbox finished opening and its transition settled.
|
|
159
160
|
* @event lr-hide - The listbox is about to close, however `open` became false. Conditionally
|
|
160
161
|
* cancelable: connected transitions can be vetoed on the same terms as `lr-show`; an
|
|
161
|
-
* already-removed element closing on disconnect
|
|
162
|
-
* a veto. Vetoing an ordinary connected dismissal preserves the live filter query, active
|
|
162
|
+
* already-removed element closing on disconnect, a failed positioning runtime, or an enforced
|
|
163
|
+
* minimum-query close cannot honour a veto. Vetoing an ordinary connected dismissal preserves the live filter query, active
|
|
163
164
|
* option, and async rows exactly.
|
|
164
165
|
* @event lr-after-hide - The listbox finished closing and its transition settled.
|
|
165
166
|
* @event lr-clear - The value was cleared.
|
|
@@ -170,7 +171,8 @@ export type LyraComboboxChangeEvent<Multiple extends boolean=boolean> =LyraCombo
|
|
|
170
171
|
* host's `value` (the committed selection). User-input only: typing and the clear button announce
|
|
171
172
|
* it. Programmatic edits, including `setRangeText()`, are silent. `setRangeText()` preserves
|
|
172
173
|
* the replaced filter text and synchronizes its query/options without changing selected value.
|
|
173
|
-
* Picking a row, resetting the form, and
|
|
174
|
+
* Picking a row, resetting the form, and ordinary dismissal also update the filter silently.
|
|
175
|
+
* A minimum-query close instead preserves the typed filter.
|
|
174
176
|
* @event {FocusEvent} blur - Re-dispatched from the internal native input as a bubbling, composed,
|
|
175
177
|
* non-cancelable event.
|
|
176
178
|
* @event {FocusEvent} focus - Re-dispatched from the internal native input as a bubbling, composed,
|
|
@@ -328,7 +330,7 @@ export declare class LyraCombobox<Multiple extends boolean=boolean>extends LyraF
|
|
|
328
330
|
/** `data` carries opaque per-row caller payload -- preserve each item's identity through the
|
|
329
331
|
* frozen event envelope instead of recursively cloning unknown data, the same policy
|
|
330
332
|
* `<lr-prompt-queue>`'s `lr-queue-change` detail uses for its own `items`. */
|
|
331
|
-
protected static readonly identityEventDetailCollectionItems:Readonly<{'lr-input':readonly string[];'lr-change':readonly string[];}>;static formAssociated:boolean;static styles:import("lit").CSSResultGroup[];static properties:{customError:{attribute:string;reflect:boolean;noAccessor:boolean;};multiple:{type:BooleanConstructor;reflect:boolean;noAccessor:boolean;};disabled:{type:BooleanConstructor;reflect:boolean;noAccessor:boolean;};required:{type:BooleanConstructor;reflect:boolean;noAccessor:boolean;};readonly:{type:BooleanConstructor;reflect:boolean;noAccessor:boolean;};value:{noAccessor:boolean;};name:{reflect:boolean;noAccessor:boolean;converter:import("lit").ComplexAttributeConverter<string,unknown>;};maxOptionsVisible:{type:NumberConstructor;attribute:string;noAccessor:boolean;};maxRender:{type:NumberConstructor;attribute:string;noAccessor:boolean;};sourceDelay:{type:NumberConstructor;attribute:string;noAccessor:boolean;};};placeholder:string;label:string;
|
|
333
|
+
protected static readonly identityEventDetailCollectionItems:Readonly<{'lr-input':readonly string[];'lr-change':readonly string[];}>;static formAssociated:boolean;static styles:import("lit").CSSResultGroup[];static properties:{customError:{attribute:string;reflect:boolean;noAccessor:boolean;};multiple:{type:BooleanConstructor;reflect:boolean;noAccessor:boolean;};disabled:{type:BooleanConstructor;reflect:boolean;noAccessor:boolean;};required:{type:BooleanConstructor;reflect:boolean;noAccessor:boolean;};readonly:{type:BooleanConstructor;reflect:boolean;noAccessor:boolean;};value:{noAccessor:boolean;};name:{reflect:boolean;noAccessor:boolean;converter:import("lit").ComplexAttributeConverter<string,unknown>;};maxOptionsVisible:{type:NumberConstructor;attribute:string;noAccessor:boolean;};maxRender:{type:NumberConstructor;attribute:string;noAccessor:boolean;};sourceDelay:{type:NumberConstructor;attribute:string;noAccessor:boolean;};minQueryLength:{type:NumberConstructor;attribute:string;noAccessor:boolean;};};placeholder:string;label:string;
|
|
332
334
|
/**
|
|
333
335
|
* Whether the `label` renders on screen. `hidden` keeps the label as the accessible name but
|
|
334
336
|
* removes it visually (compact toolbars, table cells); hint, error and required semantics are
|
|
@@ -336,8 +338,8 @@ protected static readonly identityEventDetailCollectionItems:Readonly<{'lr-input
|
|
|
336
338
|
* @attr label-display
|
|
337
339
|
*/
|
|
338
340
|
labelDisplay:LyraLabelDisplay;hint:string;errorText:string;
|
|
339
|
-
/** Whether the listbox is open. Disabled or
|
|
340
|
-
* including a synchronous fieldset cascade. */
|
|
341
|
+
/** Whether the listbox is open. Disabled, readonly, or below-minimum queries reject direct
|
|
342
|
+
* reopen attempts, including a synchronous fieldset cascade. */
|
|
341
343
|
get open():boolean;set open(next:boolean);
|
|
342
344
|
/** Allows a nonmatching query to be created as a new option through the cancelable `lr-create`
|
|
343
345
|
* veto point. The default action appends and selects an `<lr-option>`. */
|
|
@@ -497,9 +499,9 @@ get autocorrect():boolean;set autocorrect(next:boolean);
|
|
|
497
499
|
get inputmode():string;set inputmode(next:string);get enterkeyhint():string;set enterkeyhint(next:string);
|
|
498
500
|
/** Live text in the native filter input. Programmatic writes are event-silent.
|
|
499
501
|
* @default '' */
|
|
500
|
-
get inputValue():string;set inputValue(next:string);private query;private explicitInputValue;private activeIndex;private options;private optionsObserved;private touched;private validityRevision;private validatorAttributeObserver?;private readonly slotPresence;private sourceLoading;private sourceFailed;private sourceEverSettled;private asyncRows;private _sourceTotal;private _sourceTruncated;private readonly sourceErrorAnnouncements;private inputEl?;private optionsSlot?;private readonly sourceDebounce;private sourceToken;private refreshQueued;private sourceAbort?;private _sourceWarmed;private _selectedLabelCache;private _selectedRowCache;private pendingSelectedRowValues?;private _renderedRows;private internals;private _open;private validityController;
|
|
502
|
+
get inputValue():string;set inputValue(next:string);private _query;private get query();private set query(value);private explicitInputValue;private activeIndex;private options;private optionsObserved;private touched;private validityRevision;private validatorAttributeObserver?;private readonly slotPresence;private sourceLoading;private sourceFailed;private sourceEverSettled;private asyncRows;private _sourceTotal;private _sourceTruncated;private readonly sourceErrorAnnouncements;private inputEl?;private optionsSlot?;private readonly sourceDebounce;private sourceToken;private refreshQueued;private sourceAbort?;private _sourceWarmed;private _selectedLabelCache;private _selectedRowCache;private pendingSelectedRowValues?;private _renderedRows;private internals;private _open;private validityController;
|
|
501
503
|
/** Consumer-supplied validation message reflected through `custom-error`.*/
|
|
502
|
-
customError:string|null;private _fieldsetDisabled;private listId;private inputId;private cleanup?;private listboxPositioned;private positioningGeneration;private positioningReady;private resolvePositioningReady?;private overlayHandle?;private restoreFocusOnClose;private restoringOverlayFocus;private readonly popupController;private listboxHidden;private listboxRendered;private _isFirstUpdate;private openVetoed;private closeAfterPositioningFailure;private closeCleanupPending;private _selected;private singleSelectedOption?;private readonly sourceOptionsByRow;private _valueDirty;private _multiple;private _disabled;private _required;private _readonly;private _defaultSelected;private _defaultCaptured;private _restoredStateActive;private _name;private validationTargetOverride?;
|
|
504
|
+
customError:string|null;private _fieldsetDisabled;private listId;private inputId;private cleanup?;private listboxPositioned;private positioningGeneration;private positioningReady;private resolvePositioningReady?;private overlayHandle?;private restoreFocusOnClose;private restoringOverlayFocus;private readonly popupController;private listboxHidden;private listboxRendered;private _isFirstUpdate;private openVetoed;private closeAfterPositioningFailure;private minimumQueryClosePending;private minimumQueryCloseUnpainted;private closeCleanupPending;private _selected;private singleSelectedOption?;private readonly sourceOptionsByRow;private _valueDirty;private _multiple;private _disabled;private _required;private _readonly;private _defaultSelected;private _defaultCaptured;private _restoredStateActive;private _name;private validationTargetOverride?;
|
|
503
505
|
/**
|
|
504
506
|
* Bounds the popup to roughly this many option rows, leaving the rest reachable by scrolling.
|
|
505
507
|
*
|
|
@@ -516,7 +518,7 @@ customError:string|null;private _fieldsetDisabled;private listId;private inputId
|
|
|
516
518
|
* as it was. Zero, negative, and non-finite values normalize to unset rather than collapsing the
|
|
517
519
|
* popup.
|
|
518
520
|
*/
|
|
519
|
-
visibleOptions?:number;private _maxOptionsVisible;private _maxRender;private _sourceDelay;constructor();get form():HTMLFormElement|null;set form(owner:FormOwnerValue);
|
|
521
|
+
visibleOptions?:number;private _maxOptionsVisible;private _maxRender;private _sourceDelay;private _minQueryLength;constructor();get form():HTMLFormElement|null;set form(owner:FormOwnerValue);
|
|
520
522
|
/** Native element used as the constraint-validation focus anchor.*/
|
|
521
523
|
get validationTarget():HTMLElement|undefined;set validationTarget(next:HTMLElement|undefined);
|
|
522
524
|
/** Clears consumer-supplied validity and restores the current intrinsic constraints.*/
|
|
@@ -588,7 +590,12 @@ get maxRender():number;
|
|
|
588
590
|
/** Debounce (ms) between the last keystroke and the `source` call. Sanitized to a finite
|
|
589
591
|
* duration clamped to `[0, browser-timer-ceiling]`; `0` fires on every keystroke, a
|
|
590
592
|
* non-finite value falls back to the `200` default. */
|
|
591
|
-
get sourceDelay():number;set sourceDelay(next:number);
|
|
593
|
+
get sourceDelay():number;set sourceDelay(next:number);
|
|
594
|
+
/** Minimum Unicode code points in the trimmed query before suggestions or source calls are
|
|
595
|
+
* allowed. Counting never changes the displayed or provider query. Zero preserves unrestricted
|
|
596
|
+
* opening and selected-value source warmup; positive values also gate that empty-query warmup.
|
|
597
|
+
* @default 0 */
|
|
598
|
+
get minQueryLength():number;set minQueryLength(next:number);private meetsMinimumQuery;private enforceMinimumQuery;set maxRender(next:number);
|
|
592
599
|
/** Provider-side match count for the latest accepted source response, before component caps.*/
|
|
593
600
|
get sourceTotal():number;
|
|
594
601
|
/** Whether the latest response contained or reported more rows than the bounded retained set.*/
|
|
@@ -626,7 +633,8 @@ formDisabledCallback(disabled:boolean):void;private markInteracted;checkValidity
|
|
|
626
633
|
* The message is caller-supplied content, so it is used verbatim and never localized here.
|
|
627
634
|
*/
|
|
628
635
|
setCustomValidity(message:string):void;disconnectedCallback():void;private collectOptions;private collectOptionsFromSlot;private refreshOptionDefaults;private callbackRefreshEpoch;requestUpdate(...args:Parameters<LyraElement['requestUpdate']>):void;private optionMemo;private memoOption;private get optionIndex();private get asyncIndex();private get searchCorpus();private pendingSelectedWrites;private selectedWritesQueued;private flushSelectedWrites;private optionRefreshPending;private onOptionChange;private reflectSelected;private labelFor;private isUnknownValue;private adornmentClones;private adornmentMarkup;private adornmentsFor;private rowForOption;private get hasSelectionSourceRows();private applySelectedRowValues;private applyPendingSelectedRows;private get unknownRows();private get createRow();private capRows;private lastRenderedRows;private get renderedRows();private computeRenderedRows;private normalizeActiveIndex;private get filtered();private get displayValue();private announceOpenTransition;
|
|
629
|
-
/** Opens the listbox and resolves after `lr-after-show
|
|
636
|
+
/** Opens the listbox and resolves after `lr-after-show`; a below-minimum query resolves
|
|
637
|
+
* immediately without starting an opening. */
|
|
630
638
|
show():Promise<void>;
|
|
631
639
|
/** Closes the listbox and resolves after `lr-after-hide`.*/
|
|
632
640
|
hide():Promise<void>;private finalizeCloseState;private onDocPointer;private activateListboxOverlay;private beginListboxPositioning;private invalidateListboxPositioning;private resolveCurrentPositioning;private startListboxPositioning;private teardownListboxOverlay;private reconnectOpenPopup;private syncVisibleOptionsCap;protected updated(changed:PropertyValues):void;private settleTransition;private emitValueEvents;private assignValue;private createOption;private commitCustomValue;private pickRow;private removeValueAt;private clear;private onInput;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{capOptionRows}from"../../../internal/option-selection.js";import{emitValueEvents}from"../../../internal/value-events.js";import{setNativeRangeText,nativeAutocorrectAttribute}from"../../../internal/native-text-control.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{collectionSupport}from"../../../internal/collection-snapshot.js";import{acquireNativeControlDescription}from"../../../internal/native-control-description.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{loadAnchoredOverlayRuntime,syncTopLayerRelease,topLayerPlacement}from"../../../internal/anchored-overlay-runtime.js";import{hostAriaLabel,nextId,srOnly}from"../../../internal/a11y.js";import{chevronIcon,closeIcon}from"../../../internal/icons.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{finiteCount,finiteDuration}from"../../../internal/numbers.js";import{PopupController,emitPopupEvent}from"../../../internal/popup-controller.js";import{revealRow}from"../../../internal/reveal-row.js";import{DebounceController}from"../../../internal/debounce-controller.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./combobox.styles.js";import{autocorrectConverter,literalSetConverter,omittedEmptyStringConverter,optionalLiteralSetConverter,spellcheckConverter}from"../../../internal/converters.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{tag}from"../../../internal/prefix.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{renderDataState}from"../../../internal/data-state-renderer.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{isOptionSelectedDirty,isOptionSelectedWrite,wasOptionInitiallySelected,RESET_OPTION_SELECTED_FROM_OWNER,SET_OPTION_SELECTED_FROM_OWNER}from"../../../internal/option-selection.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{LYRA_DEFAULT_comboboxCreate,LYRA_DEFAULT_comboboxLabel,LYRA_DEFAULT_comboboxLoadError,LYRA_DEFAULT_comboboxOverflow,LYRA_DEFAULT_comboboxRequired,LYRA_DEFAULT_comboboxSelectedOverflow}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noData,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_notInCatalog,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_retry,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_tableLoadFailed,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();function isLyraOptionElement(value){return isHtmlElement(value)&&value.localName===tag("option")}function normalizeSelectionValues(next){return Array.isArray(next)?next.filter(value=>typeof value=="string"):typeof next=="string"?[next]:[]}const POSITIONING_STRATEGY=optionalLiteralSetConverter(["absolute","fixed"]),APPEARANCE=literalSetConverter(["accent","filled","outlined","filled-outlined","plain"],"outlined"),VALIDITY_FLAG_KEYS=new Set(["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"]),comboboxSpellcheckConverter={...spellcheckConverter,fromAttribute:(value,type)=>value===null?void 0:spellcheckConverter.fromAttribute?.(value,type)};function adornmentContent(value){return typeof value=="string"||typeof value=="number"?html`<span>${value}</span>`:value}function isValidityFlagKey(value){return typeof value=="string"&&VALIDITY_FLAG_KEYS.has(value)}const MAX_SOURCE_ROWS=2e3,MAX_SOURCE_TEXT_UNITS=25e4,MAX_SOURCE_FIELD_UNITS=4096,MAX_RENDER_ROWS=1e3;function isRenderable(value,nested=!1){if(typeof value=="string"||typeof value=="number")return!0;if(typeof value!="object"||value===null)return!1;if(Array.isArray(value))return!nested&&value.every(item=>isRenderable(item,!0));const{nodeType,cloneNode,strings}=value;return typeof nodeType=="number"&&typeof cloneNode=="function"||Array.isArray(strings)&&Object.hasOwn(strings,"raw")}function normalizeSourceResult(input){let candidateRows,candidateTotal;try{Array.isArray(input)?candidateRows=input:typeof input=="object"&&input!==null&&(candidateRows=input.rows,candidateTotal=input.total)}catch{throw new TypeError("Invalid combobox source result")}if(!Array.isArray(candidateRows))throw new TypeError("Invalid combobox source result");const providerTotal=typeof candidateTotal=="number"&&Number.isFinite(candidateTotal)&&candidateTotal>=0?Math.trunc(candidateTotal):candidateRows.length,rows=[];let textUnits=0;const limit=Math.min(candidateRows.length,MAX_SOURCE_ROWS);for(let index=0;index<limit;index++)try{const value=candidateRows[index]?.value,label=candidateRows[index]?.label;if(typeof value!="string"||typeof label!="string"||value.length>MAX_SOURCE_FIELD_UNITS||label.length>MAX_SOURCE_FIELD_UNITS)continue;const source=candidateRows[index],optionalText=key=>{const candidate=source[key];return typeof candidate=="string"&&candidate.length<=MAX_SOURCE_FIELD_UNITS?candidate:void 0},content=key=>{const candidate=source[key];return isRenderable(candidate)?candidate:void 0},icon=content("icon"),start=content("start"),end=content("end"),sub=optionalText("sub"),accessibleLabel=optionalText("accessibleLabel"),dotColor=optionalText("dotColor"),title=optionalText("title"),group=optionalText("group"),badgeCandidate=source.badge,badge=typeof badgeCandidate=="string"&&badgeCandidate.length<=MAX_SOURCE_FIELD_UNITS||typeof badgeCandidate=="number"&&Number.isFinite(badgeCandidate)?badgeCandidate:void 0,units=value.length+label.length+(sub?.length??0)+(accessibleLabel?.length??0)+(dotColor?.length??0)+(title?.length??0)+(group?.length??0)+(typeof badge=="string"?badge.length:0);if(textUnits+units>MAX_SOURCE_TEXT_UNITS)break;textUnits+=units,rows.push({value,label,...sub===void 0?{}:{sub},...icon===void 0?{}:{icon},...start===void 0?{}:{start},...end===void 0?{}:{end},...badge===void 0?{}:{badge},...accessibleLabel===void 0?{}:{accessibleLabel},...source.data===void 0?{}:{data:source.data},...dotColor===void 0?{}:{dotColor},...title===void 0?{}:{title},...group===void 0?{}:{group},...typeof source.disabled=="boolean"?{disabled:source.disabled}:{}})}catch{}const total=Math.max(providerTotal,candidateRows.length);return{rows,total,truncated:total>rows.length}}class LyraCombobox extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,collapse:LYRA_DEFAULT_collapse,comboboxCreate:LYRA_DEFAULT_comboboxCreate,comboboxLabel:LYRA_DEFAULT_comboboxLabel,comboboxLoadError:LYRA_DEFAULT_comboboxLoadError,comboboxOverflow:LYRA_DEFAULT_comboboxOverflow,comboboxRequired:LYRA_DEFAULT_comboboxRequired,comboboxSelectedOverflow:LYRA_DEFAULT_comboboxSelectedOverflow,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,noData:LYRA_DEFAULT_noData,noMatches:LYRA_DEFAULT_noMatches,notInCatalog:LYRA_DEFAULT_notInCatalog,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,retry:LYRA_DEFAULT_retry,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,tableLoadFailed:LYRA_DEFAULT_tableLoadFailed,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-input","lr-change"])}static{this.identityEventDetailCollectionItems=Object.freeze({"lr-input":Object.freeze(["data"]),"lr-change":Object.freeze(["data"])})}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles,srOnly]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},multiple:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},readonly:{type:Boolean,reflect:!0,noAccessor:!0},value:{noAccessor:!0},name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},maxOptionsVisible:{type:Number,attribute:"max-options-visible",noAccessor:!0},maxRender:{type:Number,attribute:"max-render",noAccessor:!0},sourceDelay:{type:Number,attribute:"source-delay",noAccessor:!0}}}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&&!this.readonly&&!liveDisabled,this._open===old){next&&!this._open&&this.hasAttribute("open")&&this.removeAttribute("open");return}this.requestUpdate("open",old)}get appearance(){return this._appearance}set appearance(next){const normalized=APPEARANCE.normalizeReflected(this,"appearance",next),old=this._appearance;this._appearance=normalized,normalized!==old&&this.requestUpdate("appearance",old)}get positioningStrategy(){return this._positioningStrategy??"fixed"}set positioningStrategy(next){const normalized=POSITIONING_STRATEGY.normalize(next)??"fixed",old=this.positioningStrategy;this._positioningStrategy=normalized,normalized!==old&&this.requestUpdate("positioningStrategy",old)}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=!!next,this.requestUpdate()}get inputmode(){return this.inputMode}set inputmode(next){this.inputMode=next??""}get enterkeyhint(){return this.enterKeyHint}set enterkeyhint(next){this.enterKeyHint=next??""}get inputValue(){return this.query}set inputValue(next){this.explicitInputValue=!0,this.query=next??"",this.activeIndex=-1,this.source&&this.runSource(this.query),this.requestUpdate()}constructor(){super(),this.placeholder="",this.label="",this.labelDisplay="visible",this.hint="",this.errorText="",this.allowCreate=!1,this.allowCustomValue=!1,this.withUnknownOption=!1,this.loading=!1,this._appearance="outlined",this.placement="bottom",this.topLayer=!1,this.size="m",this.pill=!1,this.clearable=!1,this.withClear=!1,this.withLabel=!1,this.withHint=!1,this.validators=[],this.autocomplete="off",this.inputMode="",this.enterKeyHint="",this.spellcheck=!1,this.autocapitalize="",this.autocorrectValue=!0,this.filter=null,this.source=null,this.query="",this.explicitInputValue=!1,this.activeIndex=-1,this.options=[],this.optionsObserved=!1,this.touched=!1,this.validityRevision=0,this.slotPresence=new SlotPresenceController(this),this.sourceLoading=!1,this.sourceFailed=!1,this.sourceEverSettled=!1,this.asyncRows=[],this._sourceTotal=0,this._sourceTruncated=!1,this.sourceErrorAnnouncements=new AnnouncementSinkController(this,{eager:["assertive"]}),this.sourceDebounce=new DebounceController(0,request=>this.runSourceRequest(request),()=>this.ownerDocument.defaultView),this.sourceToken=0,this.refreshQueued=!1,this._sourceWarmed=!1,this._selectedLabelCache=new Map,this._selectedRowCache=new Map,this._renderedRows=[],this._open=!1,this._fieldsetDisabled=!1,this.listId=nextId("combobox-list"),this.inputId=nextId("combobox-input"),this.listboxPositioned=!1,this.positioningGeneration=0,this.positioningReady=Promise.resolve(!1),this.restoreFocusOnClose=!0,this.restoringOverlayFocus=!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.listboxHidden=!0,this.listboxRendered=!1,this._isFirstUpdate=!0,this.openVetoed=!1,this.closeAfterPositioningFailure=!1,this.closeCleanupPending=!1,this._selected=[],this.sourceOptionsByRow=new WeakMap,this._valueDirty=!1,this._multiple=!1,this._disabled=!1,this._required=!1,this._readonly=!1,this._defaultSelected=[],this._defaultCaptured=!1,this._restoredStateActive=!1,this._name="",this._maxOptionsVisible=3,this._maxRender=200,this._sourceDelay=200,this.localDescriptionIds="",this.previousSelection=[],this.markInteracted=()=>{this.touched||(this.touched=!0,this.updateValidity(),this.syncCustomStates())},this.collectOptions=e=>{this.collectOptionsFromSlot(e.target)},this.callbackRefreshEpoch=0,this.optionMemo=new Map,this.pendingSelectedWrites=new Map,this.selectedWritesQueued=!1,this.optionRefreshPending=!1,this.onOptionChange=e=>{e.stopPropagation();const option=e.composedPath().find(isLyraOptionElement);if(isOptionSelectedWrite(e)&&isLyraOptionElement(option)&&this.optionIndex.members.has(option)){this._valueDirty=!0,this._restoredStateActive=!1,this.pendingSelectedWrites.delete(option),this.pendingSelectedWrites.set(option,{selected:option.selected,value:option.value}),this.selectedWritesQueued||(this.selectedWritesQueued=!0,queueMicrotask(()=>this.flushSelectedWrites()));return}if(isLyraOptionElement(option)){const cached=this.adornmentClones.get(option);cached&&cached.markup!==this.adornmentMarkup(option)&&this.adornmentClones.delete(option)}this.optionRefreshPending||(this.optionRefreshPending=!0,queueMicrotask(()=>{this.optionRefreshPending=!1,this.refreshOptionDefaults(),this.reflectSelected(),this.options=[...this.options],this.normalizeActiveIndex()}))},this.adornmentClones=new WeakMap,this.lastRenderedRows=[],this.onDocPointer=e=>{if(!e.composedPath().includes(this)){if(this.overlayHandle?.isActive()){this.overlayHandle.dismissBackdrop();return}this.restoreFocusOnClose=!1,this.hide()}},this.onInput=e=>{this.liveDisabled||this.readonly||(this.explicitInputValue=!1,this.query=e.target.value,this.activeIndex=-1,this.show(),this.source&&this.runSource(this.query),this.emit("lr-filter",{value:this.query}))},this.onInputBlur=event=>{this.liveDisabled||(this.touched=!0),this.syncCustomStates(),this.onComboFocusOut(event),relayNativeEvent(this,event)},this.onComboFocusOut=event=>{const trigger=this.renderRoot.querySelector('[part="combobox"]'),target=event.relatedTarget;target&&typeof target.nodeType=="number"&&trigger?.contains(target)||(this.restoreFocusOnClose=!1,this.hide())},this.onInputFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}this.restoringOverlayFocus||this.show(),relayNativeEvent(this,event)},this.onKeyDown=e=>{if(e.isComposing||e.keyCode===229||this.liveDisabled||this.readonly)return;const navigable=["ArrowDown","ArrowUp","Enter","End"].includes(e.key)?this.renderedRows.rows.filter(r=>!r.disabled):[];switch(e.key){case"ArrowDown":case"ArrowUp":if(e.preventDefault(),!this.open){this.activeIndex=navigable.findIndex(row=>this.committed.includes(row.value)),this.show();return}if(e.key==="ArrowDown"){this.activeIndex=Math.min(navigable.length-1,this.activeIndex+1);break}this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":{const activeRow=navigable[this.activeIndex];if(this.open&&this.activeIndex>=0&&activeRow){e.preventDefault(),this.pickRow(activeRow);break}const create=this.createRow;if(this.open&&create){e.preventDefault(),this.createOption(create.createInput);break}if(this.open&&this.allowCustomValue&&!this.multiple&&this.query.trim()){e.preventDefault(),this.commitCustomValue(this.query.trim());break}submitOnEnter(this,e);break}case"Escape":this.open&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(e.preventDefault(),this.hide());break;case"Home":this.open&&(e.preventDefault(),this.activeIndex=0);break;case"End":this.open&&(e.preventDefault(),this.activeIndex=navigable.length-1);break;case"Backspace":this.multiple&&!this.query&&this._selected.length&&this.removeValueAt(this._selected.length-1);break}},this.onComboMouseDown=e=>{this.liveDisabled||e.composedPath()[0]!==this.inputEl&&(e.target.closest("button")||(e.preventDefault(),this.inputEl?.focus(),this.show()))},this.onListboxMouseDown=e=>{e.preventDefault()},this.onListboxClick=e=>{const optionEl=e.target.closest('[part="option"]'),row=this._renderedRows[Number(optionEl?.dataset.index)];row&&this.pickRow(row)},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)}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}get validationTarget(){return this.validationTargetOverride??this.inputEl??void 0}set validationTarget(next){this.validationTargetOverride=next??void 0,this.validityController.refreshAnchor()}resetValidity(){this.validityController.setCustomValidity(""),this.updateValidity()}get input(){return this.inputEl??null}get selectionStart(){return this.inputEl?.selectionStart??null}set selectionStart(value){this.inputEl&&(this.inputEl.selectionStart=value)}get selectionEnd(){return this.inputEl?.selectionEnd??null}set selectionEnd(value){this.inputEl&&(this.inputEl.selectionEnd=value)}get selectionDirection(){return this.inputEl?.selectionDirection}set selectionDirection(value){this.inputEl&&(this.inputEl.selectionDirection=value)}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}get interactionBarred(){return this.liveDisabled||this.readonly}focus(options){this.liveDisabled||this.inputEl?.focus(options)}blur(){this.inputEl?.blur()}click(){this.liveDisabled||(this.inputEl?.focus(),this.show())}select(){this.inputEl?.select()}setSelectionRange(start,end,direction){this.inputEl?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){const input=this.inputEl;input&&(setNativeRangeText(input,replacement,start,end,selectMode),this.explicitInputValue=!0,this.query=input.value,this.activeIndex=-1,this.source&&this.runSource(this.query))}[VALIDITY_ANCHOR](){return this.validationTarget}syncExternalDescription(){if(!this.isConnected)return;const target=this.renderRoot.querySelector('[part="combobox-input"]');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.updateValidity(),this.hasUpdated&&this.syncValidatorAttributeObserver(),this.hasUpdated&&queueMicrotask(()=>{this.open?this.reconnectOpenPopup():this.source&&this._selected.length&&this.asyncRows.length===0&&this.runSource("")})}adoptedCallback(){super.adoptedCallback(),this.popupController.cancel(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription(),this.listboxPositioned=!1,this.invalidateListboxPositioning(),this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.popupController.unbindPointer(),this.clearSourceTimer(),this.sourceToken+=1,this.sourceAbort?.abort(),this.sourceAbort=void 0,this.sourceErrorAnnouncements.adopted()}willUpdate(changed){super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,this.announceOpenTransition(changed),this.open?(this.listboxHidden=!1,this.listboxRendered=!0):changed.has("open")&&this.interactionBarred&&(this.listboxHidden=!0),changed.has("open")&&!this.openVetoed&&(this.listboxPositioned=!1),changed.has("open")&&this.openVetoed?this.closeCleanupPending=!1:changed.has("open")&&!this.open&&this.finalizeCloseState(),changed.has("source")&&(this.clearSourceTimer(),this.sourceAbort?.abort(),this.sourceAbort=void 0,this.sourceToken++,this.sourceLoading=!1,this.sourceFailed=!1,this.sourceEverSettled=!1,this.asyncRows=[],this._sourceTotal=0,this._sourceTruncated=!1,this.activeIndex=-1,this._sourceWarmed=!1,this.source&&this.open&&this.runSource(this.query)),!this._sourceWarmed&&this.source&&(this._selected.length>0||(this.pendingSelectedRowValues?.length??0)>0)&&this.asyncRows.length===0&&(this._sourceWarmed=!0,this.runSource(""))}firstUpdated(changed){super.firstUpdated(changed);const slot=this.optionsSlot;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>{this.optionsObserved=!0,s.assignedElements({flatten:!0}).some(isLyraOptionElement)&&this.collectOptionsFromSlot(s)})})}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",reflectFormName(this,this._name),this.syncFormValue(),this.requestUpdate("name",old)}get multiple(){return this._multiple}set multiple(next){const old=this._multiple;this._multiple=!!next,this.toggleAttribute("multiple",this._multiple),this.reflectSelected(),this.syncFormValue(),this.requestUpdate("multiple",old)}get disabled(){return this._disabled}set disabled(next){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 readonly(){return this._readonly}set readonly(next){const old=this._readonly;this._readonly=!!next,this.toggleAttribute("readonly",this._readonly),this._readonly&&this.hide(),this.updateValidity(),this.requestUpdate("readonly",old)}get value(){return this.multiple?[...this._selected]:this._selected[0]??""}set value(next){this.setValue(next,!0)}setValue(next,dirty,preferred){this.pendingSelectedWrites.clear();const old=this._selected;this.previousSelection=old,this.singleSelectedOption=preferred,dirty&&(this._restoredStateActive=!1,this._valueDirty=!0),this._selected=normalizeSelectionValues(next);const selected=new Set(this._selected);if(selected.size>0){const rows=this.rowsByValue(selected);for(const value of selected){const row=rows.get(value);row&&this._selectedRowCache.set(value,row)}}for(const value of this._selectedRowCache.keys())selected.has(value)||this._selectedRowCache.delete(value);for(const value of this._selectedLabelCache.keys())selected.has(value)||this._selectedLabelCache.delete(value);this.syncFormValue(),this.reflectSelected(),this.updateValidity(),this.requestUpdate("value",old)}get maxOptionsVisible(){return this._maxOptionsVisible}set maxOptionsVisible(next){const old=this._maxOptionsVisible;this._maxOptionsVisible=finiteCount(next,3),this.requestUpdate("maxOptionsVisible",old)}get maxRender(){return this._maxRender}get sourceDelay(){return this._sourceDelay}set sourceDelay(next){const old=this._sourceDelay;this._sourceDelay=finiteDuration(next,200),this.requestUpdate("sourceDelay",old)}set maxRender(next){const old=this._maxRender;this._maxRender=Math.min(finiteCount(next,200),MAX_RENDER_ROWS),this.requestUpdate("maxRender",old)}get sourceTotal(){return this._sourceTotal}get sourceTruncated(){return this._sourceTruncated}get selectedRows(){return this.resolveSelectedRowSlots().filter(row=>row!=null).map(row=>{const option=this.sourceOptionsByRow.get(row);return{...row,...option?this.adornmentsFor(option):{}}})}resolveSelectedRowSlots(){let rows;return this.committed.map(value=>this._selectedRowCache.get(value)??(rows??=this.rowsByValue(new Set(this.committed))).get(value))}get committed(){return this.multiple?this._selected:this._selected.slice(0,1)}rowsByValue(values){const rows=this.source?new Map:this.localRowsByValue(values,this.options);for(const row of this.asyncRows)values.has(row.value)&&!rows.has(row.value)&&rows.set(row.value,row);return rows}localRowsByValue(values,options){const rows=new Map;if(values.size===0)return rows;for(const option of options){const value=option.value;values.has(value)&&!rows.has(value)&&rows.set(value,this.rowForOption(option,!1))}return rows}set selectedRows(next){const values=[],seen=new Set;if(Array.isArray(next))for(const candidate of next){let value;try{value=candidate?.value}catch{continue}typeof value!="string"||seen.has(value)||(seen.add(value),values.push(value))}if(values.length>0&&!this.hasSelectionSourceRows){this.pendingSelectedRowValues=values,this.source&&this.isConnected&&(this._sourceWarmed=!0,this.runSource(""));return}this.pendingSelectedRowValues=void 0,this.applySelectedRowValues(values)}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}validatorResult(){const self=this,current=self.value;for(const validator of Array.isArray(this.validators)?this.validators:[]){let result;try{if(typeof validator=="object"&&validator!==null&&"checkValidity"in validator){const checked=validator.checkValidity(this);if(checked?.isValid===!0)continue;const flags={};for(const key of Array.isArray(checked?.invalidKeys)?checked.invalidKeys:[])isValidityFlagKey(key)&&(flags[key]=!0);Object.values(flags).some(Boolean)||(flags.customError=!0);let message=typeof checked?.message=="string"?checked.message:"";return!message&&typeof validator.message=="string"&&(message=validator.message),!message&&typeof validator.message=="function"&&(message=validator.message(this)),{flags,message:message||this.localize("valueInvalid")}}result=typeof validator=="function"?validator(current,self):validator?.validate(current,self)}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}if(!(result===void 0||result===!0)){if(typeof result=="string")return{flags:{customError:!0},message:result};if(result===!1)return{flags:{customError:!0},message:this.localize("valueInvalid")};if(result&&typeof result=="object"&&Object.values(result).some(Boolean))return{flags:result,message:this.localize("valueInvalid")}}}return{}}syncValidatorAttributeObserver(){this.disconnectValidatorAttributeObserver();const owner=this.ownerDocument.defaultView,MutationObserverCtor=owner?.MutationObserver;if(!this.isConnected||!owner||typeof MutationObserverCtor!="function")return;const attributes=new Set;for(const validator of Array.isArray(this.validators)?this.validators:[]){if(typeof validator!="object"||validator===null||!("checkValidity"in validator))continue;let observed;try{observed=validator.observedAttributes}catch{continue}if(Array.isArray(observed))for(const name of observed)typeof name=="string"&&name.length>0&&attributes.add(name)}if(attributes.size===0)return;const binding={},observer=new MutationObserverCtor(()=>{this.validatorAttributeObserver!==binding||!this.isConnected||this.ownerDocument.defaultView!==owner||(this.updateValidity(),this.validityRevision++)});binding.observer=observer,binding.owner=owner;try{observer.observe(this,{attributes:!0,attributeFilter:[...attributes]}),this.validatorAttributeObserver=binding}catch{observer.disconnect()}}disconnectValidatorAttributeObserver(){const binding=this.validatorAttributeObserver;this.validatorAttributeObserver=void 0,binding?.observer.disconnect()}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({}),this.syncCustomStates();return}const flags={};let message="";this.required&&this._selected.length===0&&(flags.valueMissing=!0,message=this.localize("comboboxRequired"));const configured=this.validatorResult();configured.flags&&Object.assign(flags,configured.flags),configured.message&&(message=configured.message),this.validityController.setValidity(flags,message),this.syncCustomStates()}syncCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",this._selected.length===0),setCustomState(this.internals,"disabled",this.effectiveDisabled)}syncFormValue(){const state2=JSON.stringify(this._selected);if(this.multiple){if(!this.name){this.internals.setFormValue(null,state2);return}const fd=new FormData;for(const v of this._selected)fd.append(this.name,v);this.internals.setFormValue(fd,state2)}else this.internals.setFormValue(this._selected[0]??"",state2)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formResetCallback(){this.touched=!1,this._restoredStateActive=!1,this._valueDirty=!1;const resetValues=this._defaultSelected.length>0?this._defaultSelected:this.options.filter(option=>wasOptionInitiallySelected(option)).map(option=>option.value);this._defaultSelected.length===0&&resetValues.length>0&&(this._defaultSelected=[...resetValues]);const defaults=new Set(resetValues);for(const option of this.options)option[RESET_OPTION_SELECTED_FROM_OWNER](defaults.has(option.value));this.setValue(this.multiple?[...resetValues]:resetValues.slice(0,1),!1),this.query="",this.explicitInputValue=!1}formStateRestoreCallback(state2,reason){let selected=[];if(typeof state2=="string")try{const parsed=JSON.parse(state2);Array.isArray(parsed)&&parsed.every(value=>typeof value=="string")&&(selected=parsed)}catch{}this.assignValue(this.multiple?selected:selected.slice(0,1)),this._restoredStateActive=!0}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(disabled&&this.hide(),this.updateValidity(),this.requestUpdate())}checkValidity(){return this.validityController.checkValidity(()=>this.updateValidity())}reportValidity(){return this.validityController.syncConstraints(),this.touched=!0,this.updateValidity(),this.syncCustomStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncCustomStates()}disconnectedCallback(){this.pendingSelectedWrites.clear(),this.listboxHidden=!0,this.releaseExternalDescription(),this.popupController.cancel(),this.listboxPositioned=!1,this.disconnectValidatorAttributeObserver(),super.disconnectedCallback(),this.invalidateListboxPositioning(),this.clearSourceTimer(),this.sourceToken+=1,this.sourceAbort?.abort(),this.sourceAbort=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.popupController.unbindPointer(),this.open=!1}collectOptionsFromSlot(slot){const previous=new Set(this.options);if(this.optionsObserved=!0,this.options=slot.assignedElements({flatten:!0}).filter(isLyraOptionElement),this.adornmentClones=new WeakMap,this.normalizeActiveIndex(),this.applyPendingSelectedRows(),this._defaultCaptured){const newDefaults=this.options.filter(option=>!previous.has(option)&&option.defaultSelected),newLive=this.options.filter(option=>!previous.has(option)&&option.selected&&!option.defaultSelected);this.refreshOptionDefaults();const eligible=[...!this._restoredStateActive&&!this._valueDirty?newDefaults:[],...this._restoredStateActive?[]:newLive];if(eligible.length){const values=eligible.map(option=>option.value),next=this.multiple?[...new Set([...this._selected,...values])]:values[values.length-1];newLive.length>0?this.assignValue(next):this.setValue(next,!1);return}}else{this._defaultCaptured=!0;const allDefaults=this.options.filter(option=>option.defaultSelected).map(option=>option.value),allLive=this.options.filter(option=>option.selected).map(option=>option.value),defaults=this.multiple?allDefaults:allDefaults.slice(0,1),live=this.multiple?allLive:allLive.slice(0,1),initialLive=this.options.filter(option=>wasOptionInitiallySelected(option)).map(option=>option.value),optionDirty=this.options.some(option=>isOptionSelectedDirty(option)),dirtyValues=this.options.filter(option=>isOptionSelectedDirty(option)&&option.selected).map(option=>option.value);this._defaultSelected=[...defaults.length>0?defaults:initialLive.length>0?initialLive:live];const fromDefaults=defaults.length>0,initial=optionDirty?this.multiple?allLive:dirtyValues.slice(-1)[0]?dirtyValues.slice(-1):live:fromDefaults?defaults:live;if(initial.length&&!this._restoredStateActive&&!this._valueDirty){const next=this.multiple?initial:initial[0];fromDefaults&&!optionDirty?this.setValue(next,!1):this.assignValue(next);return}optionDirty&&(this._valueDirty=!0)}this.reflectSelected()}refreshOptionDefaults(){const declared=this.options.filter(option=>option.defaultSelected).map(option=>option.value);this._defaultSelected=this.multiple?declared:declared.slice(0,1),!this._valueDirty&&!this._restoredStateActive&&this.setValue([...this._defaultSelected],!1)}requestUpdate(...args){args[0]===void 0&&(this.callbackRefreshEpoch=(this.callbackRefreshEpoch??0)+1),super.requestUpdate(...args)}memoOption(key,inputs,compute){const previous=this.optionMemo.get(key);if(previous&&previous.inputs.length===inputs.length&&previous.inputs.every((input,index)=>Object.is(input,inputs[index])))return previous.value;const value=compute();return this.optionMemo.set(key,{inputs,value}),value}get optionIndex(){return this.memoOption("index",[this.options],()=>{const values=new Map;for(const option of this.options)values.has(option.value)||values.set(option.value,option);return{values,members:new Set(this.options)}})}get asyncIndex(){return this.memoOption("asyncIndex",[this.asyncRows],()=>{const values=new Map;for(const row of this.asyncRows)values.has(row.value)||values.set(row.value,row);return values})}get searchCorpus(){return this.memoOption("corpus",[this.options,this.effectiveLocale],()=>this.options.map(option=>({label:option.label.toLocaleLowerCase(this.effectiveLocale),search:option.searchText.toLocaleLowerCase(this.effectiveLocale),value:option.value.toLocaleLowerCase(this.effectiveLocale)})))}flushSelectedWrites(){this.selectedWritesQueued=!1;const writes=[...this.pendingSelectedWrites];if(this.pendingSelectedWrites.clear(),!(!this.isConnected||writes.length===0))if(this.multiple){const values=new Set(this._selected);for(const[option,write]of writes)this.optionIndex.members.has(option)&&(write.selected?values.add(write.value):values.delete(write.value));this.setValue([...values],!0)}else{let value=this._selected[0],option=this.singleSelectedOption;for(const[candidate,write]of writes)this.optionIndex.members.has(candidate)&&(write.selected?(value=write.value,option=candidate):candidate===option&&(value=void 0,option=void 0));this.setValue(value===void 0?[]:value,!0,option)}}reflectSelected(){const value=this._selected[0];(!this.singleSelectedOption||!this.optionIndex.members.has(this.singleSelectedOption)||this.singleSelectedOption.value!==value)&&(this.singleSelectedOption=value===void 0?void 0:this.optionIndex.values.get(value));const selected=new Set(this._selected);for(const option of this.options)option[SET_OPTION_SELECTED_FROM_OWNER](this.multiple?selected.has(option.value):option===this.singleSelectedOption)}labelFor(value){const nonBlank=label=>label!==void 0&&label.trim().length>0?label:void 0;if(this.getUnknownLabel&&this.isUnknownValue(value)){const override=nonBlank(this.getUnknownLabel(value));if(override!==void 0)return override}return(!this.source&&!this.multiple&&this.singleSelectedOption?.value===value?nonBlank(this.singleSelectedOption.label):void 0)??nonBlank(this._selectedLabelCache.get(value))??nonBlank(this.optionIndex.values.get(value)?.label)??nonBlank(this.asyncIndex.get(value)?.label)??(this.loading||this.source&&!this.sourceEverSettled?this.statusText("loading",this.loadingText):void 0)??value}isUnknownValue(value){return!this.source&&!this.optionsObserved||this.loading||this.source&&!this.sourceEverSettled?!1:!(!this.source&&!this.multiple&&this.singleSelectedOption?.value===value||this._selectedLabelCache.has(value)||this.optionIndex.values.has(value)||this.asyncIndex.has(value))}adornmentMarkup(option){return Array.from(option.children).filter(child=>["start","end","prefix","suffix"].includes(child.getAttribute("slot")??"")).map(child=>child.outerHTML).join("")}adornmentsFor(option){const cached=this.adornmentClones.get(option);if(cached)return cached;const cloneSlot=selector=>{const nodes=Array.from(option.querySelectorAll(selector));if(nodes.length!==0)return nodes.map(node=>node.cloneNode(!0))},resolved={markup:this.adornmentMarkup(option),start:cloneSlot(':scope > [slot="start"], :scope > [slot="prefix"]'),end:cloneSlot(':scope > [slot="end"], :scope > [slot="suffix"]')};return this.adornmentClones.set(option,resolved),resolved}rowForOption(option,withAdornments=!0){const adornments=withAdornments?this.adornmentsFor(option):{},row={value:option.value,label:option.label||option.value,sub:option.sub||void 0,dotColor:option.dotColor||void 0,title:option.title||void 0,group:option.group||void 0,disabled:option.disabled||option.inert||option.closest("[inert]")!==null,data:option.data,...adornments.start===void 0?{}:{start:adornments.start},...adornments.end===void 0?{}:{end:adornments.end}};return this.sourceOptionsByRow.set(row,option),row}get hasSelectionSourceRows(){return(this.source?this.asyncRows.length:this.options.length)>0}applySelectedRowValues(values){const requested=new Set(values),rowsByValue=this.source?this.rowsByValue(requested):this.localRowsByValue(requested,this.options),rows=values.map(value=>rowsByValue.get(value)).filter(row=>row!==void 0),limited=this.multiple?rows:rows.slice(0,1);this.assignValue(limited.map(row=>row.value));for(const row of limited)this._selectedRowCache.set(row.value,row)}applyPendingSelectedRows(acceptEmptySource=!1){if(this.pendingSelectedRowValues===void 0||!acceptEmptySource&&!this.hasSelectionSourceRows)return!1;const values=this.pendingSelectedRowValues;return this.pendingSelectedRowValues=void 0,this.applySelectedRowValues(values),!0}get unknownRows(){if(!this.withUnknownOption)return[];const locale=this.effectiveLocale,query2=this.query.trim().toLocaleLowerCase(locale);return this.committed.filter(value=>this.isUnknownValue(value)).map(value=>({value,label:this.labelFor(value),badge:this.localize("notInCatalog"),unknownValue:value})).filter(row=>!query2||row.label.toLocaleLowerCase(locale).includes(query2)||row.value.toLocaleLowerCase(locale).includes(query2))}get createRow(){if(!this.allowCreate)return;const inputValue=this.query.trim();if(!inputValue)return;const locale=this.effectiveLocale,folded=inputValue.toLocaleLowerCase(locale);if(!(this.source?this.memoOption("asyncExact",[this.asyncRows,locale],()=>new Set(this.asyncRows.flatMap(row=>[row.value.toLocaleLowerCase(locale),row.label.toLocaleLowerCase(locale)]))).has(folded):this.searchCorpus.some(row=>row.value===folded||row.label===folded)))return{value:inputValue,label:this.localize("comboboxCreate",void 0,{value:inputValue}),createInput:inputValue}}capRows(all,activeValue){return this.memoOption("capRows",[all,this.maxRender,this._selected,this.multiple,activeValue],()=>{const selected=new Set(this.committed),retained=all.filter(row=>selected.has(row.value)),active=activeValue===void 0?void 0:all.find(row=>row.value===activeValue);return capOptionRows(all,this.maxRender,active?[active,...retained]:retained)})}get renderedRows(){const active=this.lastRenderedRows.filter(row=>!row.disabled)[this.activeIndex]?.value,result=this.memoOption("renderedRows",[this.callbackRefreshEpoch,this.options,this.asyncRows,this.source,this.query,this._selected,this.multiple,this.maxRender,this._sourceTotal,this.withUnknownOption,this.allowCreate,this.filter,this.getUnknownLabel,this.loading,this.sourceEverSettled,this.effectiveLocale,this.strings,active],()=>this.computeRenderedRows(active));return this.lastRenderedRows=result.rows,result}computeRenderedRows(active){let rows,overflow;if(this.source){const capped=this.capRows(this.asyncRows,active);rows=[...capped.rows],overflow=capped.overflow,overflow+=Math.max(0,this._sourceTotal-this.asyncRows.length)}else{const capped=this.capRows(this.filtered,active);rows=capped.rows.map(option=>this.rowForOption(option)),overflow=capped.overflow}rows=[...rows];const create=this.createRow;rows.push(...this.unknownRows),create&&rows.push(create);const selected=new Set(this.committed),retained=rows.filter(row=>selected.has(row.value)),activeRow=rows.find(row=>row.value===active),bounded=capOptionRows(rows,MAX_RENDER_ROWS,activeRow?[activeRow,...retained]:retained);return{rows:bounded.rows,overflow:overflow+bounded.overflow}}normalizeActiveIndex(){if(this.activeIndex<0)return;const navigableCount=this.renderedRows.rows.filter(row=>!row.disabled).length,next=navigableCount>0?Math.min(this.activeIndex,navigableCount-1):-1;next!==this.activeIndex&&(this.activeIndex=next)}get filtered(){const locale=this.effectiveLocale,q=this.query.trim().toLocaleLowerCase(locale),selectedLabel=this.multiple?"":this.labelFor(this._selected[0]??"")??"",effective=q&&q===selectedLabel.toLocaleLowerCase(locale)?"":q;return effective?this.memoOption("filtered",[this.options,this.filter,effective,locale,this.callbackRefreshEpoch],()=>{const filter=this.filter;if(filter)return this.options.filter(option=>filter(option,effective));const corpus=this.searchCorpus;return this.options.filter((_option,index)=>corpus[index].label.includes(effective)||corpus[index].search.includes(effective))}):this.options}get displayValue(){return this.multiple||this.open||this.explicitInputValue?this.query:this._selected[0]?this.labelFor(this._selected[0]):""}announceOpenTransition(changed){this.openVetoed=!1;const closeAfterPositioningFailure=!this.open&&this.closeAfterPositioningFailure;if(this.closeAfterPositioningFailure=!1,!(!changed.has("open")||this._isFirstUpdate||!this.open&&this.interactionBarred)){if(!this.isConnected||closeAfterPositioningFailure){emitPopupEvent(this,"lr-hide",!1);return}this.openVetoed=this.popupController.announce(this.open,()=>{this.open=!this.open})}}show(){if(this.open||this.interactionBarred)return Promise.resolve();const settled=this.popupController.wait(!0);return this.open=!0,settled}hide(){if(!this.open)return Promise.resolve();const settled=this.popupController.wait(!1);return this.closeCleanupPending=!0,this.open=!1,settled}finalizeCloseState(){if(this.closeCleanupPending&&(this.closeCleanupPending=!1,this.activeIndex=-1,!this.multiple)){const queryChanged=this.query!=="";this.query="",this.explicitInputValue=!1,queryChanged&&this.source&&(this.asyncRows=[],this.sourceFailed=!1,this._sourceTotal=0,this._sourceTruncated=!1)}}activateListboxOverlay(){this.invalidateListboxPositioning(),this.overlayHandle?.deactivate({restoreFocus:!1}),this.restoreFocusOnClose=!0,this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="listbox"]'),onEscape:()=>{this.hide()},onBackdrop:()=>{this.restoreFocusOnClose=!1,this.hide()},restoreFocusTo:this.inputEl??null}),this.popupController.bindPointer(),this.beginListboxPositioning()}beginListboxPositioning(){const anchor=this.renderRoot.querySelector('[part="combobox"]'),listbox=this.renderRoot.querySelector('[part="listbox"]');if(anchor&&listbox){const generation=this.positioningGeneration;this.positioningReady=new Promise(resolve=>{this.resolvePositioningReady=resolve}),this.startListboxPositioning(generation,anchor,listbox)}}invalidateListboxPositioning(){this.positioningGeneration++,this.cleanup?.(),this.cleanup=void 0,this.resolvePositioningReady?.(!1),this.resolvePositioningReady=void 0}resolveCurrentPositioning(positioned){const resolve=this.resolvePositioningReady;this.resolvePositioningReady=void 0,resolve?.(positioned)}async startListboxPositioning(generation,anchor,listbox){try{const runtime=await loadAnchoredOverlayRuntime(),{place}=runtime;if(generation!==this.positioningGeneration||!this.open||!this.isConnected||this.renderRoot.querySelector('[part="combobox"]')!==anchor||this.renderRoot.querySelector('[part="listbox"]')!==listbox)return;this.placedTopLayer=syncTopLayerRelease(listbox,this.placedTopLayer,this.topLayer,runtime);const cleanup=place(anchor,listbox,{placement:`${this.placement}-start`,...topLayerPlacement(this.topLayer,resolveEffectivePositioningStrategy(this,this._positioningStrategy,"fixed")),sync:this.sync,onPlaced:()=>{generation===this.positioningGeneration&&(this.listboxPositioned=!0,this.updateComplete.then(()=>{generation!==this.positioningGeneration||!this.open||this.resolveCurrentPositioning(!0)}))}});generation!==this.positioningGeneration?cleanup():this.cleanup=cleanup}catch{if(generation!==this.positioningGeneration||!this.open)return;this.resolveCurrentPositioning(!1),this.closeAfterPositioningFailure=!0,this.hide()}}teardownListboxOverlay(restoreFocus=this.restoreFocusOnClose){this.invalidateListboxPositioning(),this.restoringOverlayFocus=restoreFocus;try{this.overlayHandle?.deactivate({restoreFocus})}finally{this.restoringOverlayFocus=!1}this.overlayHandle=void 0,this.popupController.unbindPointer(),this.restoreFocusOnClose=!0}reconnectOpenPopup(){!this.isConnected||!this.open||(this.activateListboxOverlay(),this.source&&this.asyncRows.length===0&&this.runSource(this.query))}syncVisibleOptionsCap(){const listbox=this.renderRoot?.querySelector('[part="listbox"]');if(!listbox)return;const clear=()=>{listbox.style.removeProperty("max-block-size")},requested=typeof this.visibleOptions=="number"?finiteCount(this.visibleOptions,0):0;if(requested<=0)return clear();const rows=listbox.querySelectorAll('[part="option"]');if(rows.length<=requested)return clear();const boundary=rows[requested];if(!boundary)return clear();const cap=boundary.getBoundingClientRect().top-listbox.getBoundingClientRect().top;if(!Number.isFinite(cap)||cap<=0)return clear();listbox.style.setProperty("max-block-size",`min(${Math.ceil(cap)}px, var(--lr-positioner-available-block-size, var(--lr-size-18rem)))`)}updated(changed){if(super.updated(changed),this.syncExternalDescription(),(changed.has("visibleOptions")||changed.has("open")||changed.has("query")||changed.has("options")||changed.has("asyncRows")||changed.has("maxRender")||changed.has("value")||changed.has("listboxPositioned")||changed.has("strings")||changed.has("lang")||changed.has("size")||changed.has("filter")||changed.has("allowCreate")||changed.has("withUnknownOption"))&&this.syncVisibleOptionsCap(),changed.has("open")&&!this.openVetoed?this.open&&this.isConnected?(this.activateListboxOverlay(),this._isFirstUpdate||this.settleTransition("lr-after-show"),this.refreshQueued?(this.refreshQueued=!1,this.runSource(this.query)):this.source&&this.asyncRows.length===0&&this.runSource(this.query)):this.open?this.teardownListboxOverlay(!1):(this.teardownListboxOverlay(),this.interactionBarred?this.popupController.cancel():this._isFirstUpdate||this.settleTransition("lr-after-hide")):changed.has("open")&&this.openVetoed&&(this.restoreFocusOnClose=!0),changed.has("topLayer")&&!changed.has("open")&&this.open&&this.isConnected&&(this.invalidateListboxPositioning(),this.beginListboxPositioning()),changed.has("name")&&this.syncFormValue(),changed.has("validators")&&(this.updateValidity(),this.syncValidatorAttributeObserver()),(changed.has("touched")||changed.has("required")||changed.has("value")||changed.has("validators")||changed.has("validityRevision"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),changed.has("activeIndex")||changed.has("listboxPositioned")){const listbox=this.renderRoot.querySelector('[part="listbox"]'),row=listbox?.querySelector('[part="option"][data-active]');listbox&&row&&revealRow(listbox,row)}}settleTransition(event){return this.popupController.settle(event,{waitForPosition:async stale=>{for(;this.open&&!this.listboxPositioned;){const readiness=this.positioningReady,positioned=await readiness;if(stale())return!1;if(positioned)break;if(readiness===this.positioningReady)return!1}return!0},conceal:()=>{this.listboxHidden=!0,this.listboxRendered=!1}})}emitValueEvents(){const self=this,data=this.resolveSelectedRowSlots().map(row=>row?.data),previousValue=this.multiple?[...this.previousSelection]:this.previousSelection[0]??"",detail={value:self.value,previousValue,data};emitValueEvents(self,"input",detail,detail2=>self.emit("lr-input",detail2)),emitValueEvents(self,"change",detail,detail2=>self.emit("lr-change",detail2))}assignValue(next){this.value=next}createOption(inputValue){if(this.liveDisabled||this.readonly||this.emit("lr-create",{inputValue},{cancelable:!0}).defaultPrevented)return;const option=this.ownerDocument.createElement(tag("option"));option.setAttribute("value",inputValue),option.textContent=inputValue,this.append(option),this.pickRow({value:inputValue,label:inputValue})}commitCustomValue(inputValue){if(this.liveDisabled||this.readonly||this.multiple||!inputValue)return;const selectionChanged=this._selected[0]!==inputValue;this.touched=!0,this._selectedLabelCache.set(inputValue,inputValue),this.assignValue(inputValue),this.query="",this.explicitInputValue=!1,this.hide(),selectionChanged&&this.emitValueEvents()}pickRow(row){const sourceOption=this.sourceOptionsByRow.get(row);if(this.liveDisabled||this.readonly||row.disabled||sourceOption&&(sourceOption.disabled||sourceOption.closest("[inert]")))return;if(row.createInput!==void 0){this.createOption(row.createInput);return}this.touched=!0;const synthetic=row.unknownValue!==void 0,selectionChanged=this.multiple||this._selected[0]!==row.value;if(this.multiple){const set=new Set(this._selected);set.has(row.value)?(set.delete(row.value),this._selectedRowCache.delete(row.value)):(set.add(row.value),synthetic||(this._selectedLabelCache.set(row.value,row.label),this._selectedRowCache.set(row.value,row))),this.assignValue([...set]),this.query="",this.explicitInputValue=!1}else synthetic||(this._selectedLabelCache.set(row.value,row.label),this._selectedRowCache.clear(),this._selectedRowCache.set(row.value,row)),this.setValue(row.value,!0,sourceOption),this.query="",this.explicitInputValue=!1,this.hide();this.source&&this.runSource(this.query),selectionChanged&&this.emitValueEvents(),this.emit("lr-activate",{value:row.value})}removeValueAt(index){if(this.liveDisabled||this.readonly||index<0||index>=this._selected.length)return;const next=this._selected.filter((_,i)=>i!==index);this.touched=!0,this.assignValue(next),this.emitValueEvents()}clear(){if(this.liveDisabled||this.readonly)return;const hadSelection=this._selected.length>0,queryChanged=this.query!=="";!hadSelection&&!queryChanged||(hadSelection&&(this.touched=!0,this.assignValue([])),this.query="",this.explicitInputValue=!1,this.source&&this.runSource(this.query),hadSelection&&(this.emitValueEvents(),this.emit("lr-clear")),queryChanged&&this.emit("lr-filter",{value:this.query}))}refresh(){if(this.source){if(!this.open){this.refreshQueued=!0;return}this.refreshQueued=!1,this.runSource(this.query,{immediate:!0})}}runSource(query2,options){const source=this.source;if(!source)return;this.clearSourceTimer(),this.sourceAbort?.abort(),this.sourceAbort=void 0;const token=++this.sourceToken,ownerWindow=this.ownerDocument.defaultView;if(!this.isConnected||!ownerWindow)return;const request={query:query2,token,owner:ownerWindow,source};if(options?.immediate){this.runSourceRequest(request);return}this.sourceDebounce.delayMs=this._sourceDelay,this.sourceDebounce.push(request)}runSourceRequest({query:query2,token,owner:ownerWindow,source}){if(token!==this.sourceToken||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow)return;const controller=new ownerWindow.AbortController;this.sourceAbort=controller,this.sourceLoading=!0,this.sourceFailed=!1,Promise.resolve().then(()=>source(query2,{signal:controller.signal,limit:MAX_SOURCE_ROWS})).then(result=>{if(token!==this.sourceToken||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow)return;const normalized=normalizeSourceResult(result);this._sourceTotal=normalized.total,this._sourceTruncated=normalized.truncated,this.asyncRows=normalized.rows,this.sourceFailed=!1,this.sourceEverSettled=!0,this.normalizeActiveIndex(),this.applyPendingSelectedRows(!0);const selected=new Set(this._selected);for(const row of normalized.rows)selected.has(row.value)&&this._selectedRowCache.set(row.value,row)}).catch(err=>{token!==this.sourceToken||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow||typeof err=="object"&&err!==null&&"name"in err&&err.name==="AbortError"||(this.asyncRows=[],this._sourceTotal=0,this._sourceTruncated=!1,this.activeIndex=-1,this.sourceFailed=!0,this.sourceEverSettled=!0,this.sourceErrorAnnouncements.announceAssertive(this.localize("comboboxLoadError")),this.emit("lr-source-error",{error:err,query:query2}),console.warn("<lr-combobox> source() rejected:",err))}).finally(()=>{token===this.sourceToken&&(this.sourceLoading=!1)})}clearSourceTimer(){this.sourceDebounce.cancel()}renderRows(rows,activeId){const out=[];let currentGroup,currentGroupRows=[],groupIndex=0;const selectedSet=new Set(this.committed),flushGroup=()=>{if(currentGroupRows.length){if(currentGroup){const labelId=`${this.listId}-group-${groupIndex++}`;out.push(html`<div role="group" aria-labelledby=${labelId}>
|
|
1
|
+
import{__decorate}from"tslib";import{capOptionRows}from"../../../internal/option-selection.js";import{emitValueEvents}from"../../../internal/value-events.js";import{setNativeRangeText,nativeAutocorrectAttribute}from"../../../internal/native-text-control.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{collectionSupport}from"../../../internal/collection-snapshot.js";import{acquireNativeControlDescription}from"../../../internal/native-control-description.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{loadAnchoredOverlayRuntime,syncTopLayerRelease,topLayerPlacement}from"../../../internal/anchored-overlay-runtime.js";import{hostAriaLabel,nextId,srOnly}from"../../../internal/a11y.js";import{chevronIcon,closeIcon}from"../../../internal/icons.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{finiteCount,finiteDuration}from"../../../internal/numbers.js";import{PopupController,emitPopupEvent}from"../../../internal/popup-controller.js";import{revealRow}from"../../../internal/reveal-row.js";import{DebounceController}from"../../../internal/debounce-controller.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./combobox.styles.js";import{autocorrectConverter,literalSetConverter,omittedEmptyStringConverter,optionalLiteralSetConverter,spellcheckConverter}from"../../../internal/converters.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{tag}from"../../../internal/prefix.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{renderDataState}from"../../../internal/data-state-renderer.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{isOptionSelectedDirty,isOptionSelectedWrite,wasOptionInitiallySelected,RESET_OPTION_SELECTED_FROM_OWNER,SET_OPTION_SELECTED_FROM_OWNER}from"../../../internal/option-selection.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{LYRA_DEFAULT_comboboxCreate,LYRA_DEFAULT_comboboxLabel,LYRA_DEFAULT_comboboxLoadError,LYRA_DEFAULT_comboboxOverflow,LYRA_DEFAULT_comboboxRequired,LYRA_DEFAULT_comboboxSelectedOverflow}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noData,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_notInCatalog,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_retry,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_tableLoadFailed,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();function isLyraOptionElement(value){return isHtmlElement(value)&&value.localName===tag("option")}function normalizeSelectionValues(next){return Array.isArray(next)?next.filter(value=>typeof value=="string"):typeof next=="string"?[next]:[]}const POSITIONING_STRATEGY=optionalLiteralSetConverter(["absolute","fixed"]),APPEARANCE=literalSetConverter(["accent","filled","outlined","filled-outlined","plain"],"outlined"),VALIDITY_FLAG_KEYS=new Set(["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"]),comboboxSpellcheckConverter={...spellcheckConverter,fromAttribute:(value,type)=>value===null?void 0:spellcheckConverter.fromAttribute?.(value,type)};function adornmentContent(value){return typeof value=="string"||typeof value=="number"?html`<span>${value}</span>`:value}function isValidityFlagKey(value){return typeof value=="string"&&VALIDITY_FLAG_KEYS.has(value)}const MAX_SOURCE_ROWS=2e3,MAX_SOURCE_TEXT_UNITS=25e4,MAX_SOURCE_FIELD_UNITS=4096,MAX_RENDER_ROWS=1e3;function isRenderable(value,nested=!1){if(typeof value=="string"||typeof value=="number")return!0;if(typeof value!="object"||value===null)return!1;if(Array.isArray(value))return!nested&&value.every(item=>isRenderable(item,!0));const{nodeType,cloneNode,strings}=value;return typeof nodeType=="number"&&typeof cloneNode=="function"||Array.isArray(strings)&&Object.hasOwn(strings,"raw")}function normalizeSourceResult(input){let candidateRows,candidateTotal;try{Array.isArray(input)?candidateRows=input:typeof input=="object"&&input!==null&&(candidateRows=input.rows,candidateTotal=input.total)}catch{throw new TypeError("Invalid combobox source result")}if(!Array.isArray(candidateRows))throw new TypeError("Invalid combobox source result");const providerTotal=typeof candidateTotal=="number"&&Number.isFinite(candidateTotal)&&candidateTotal>=0?Math.trunc(candidateTotal):candidateRows.length,rows=[];let textUnits=0;const limit=Math.min(candidateRows.length,MAX_SOURCE_ROWS);for(let index=0;index<limit;index++)try{const value=candidateRows[index]?.value,label=candidateRows[index]?.label;if(typeof value!="string"||typeof label!="string"||value.length>MAX_SOURCE_FIELD_UNITS||label.length>MAX_SOURCE_FIELD_UNITS)continue;const source=candidateRows[index],optionalText=key=>{const candidate=source[key];return typeof candidate=="string"&&candidate.length<=MAX_SOURCE_FIELD_UNITS?candidate:void 0},content=key=>{const candidate=source[key];return isRenderable(candidate)?candidate:void 0},icon=content("icon"),start=content("start"),end=content("end"),sub=optionalText("sub"),accessibleLabel=optionalText("accessibleLabel"),dotColor=optionalText("dotColor"),title=optionalText("title"),group=optionalText("group"),badgeCandidate=source.badge,badge=typeof badgeCandidate=="string"&&badgeCandidate.length<=MAX_SOURCE_FIELD_UNITS||typeof badgeCandidate=="number"&&Number.isFinite(badgeCandidate)?badgeCandidate:void 0,units=value.length+label.length+(sub?.length??0)+(accessibleLabel?.length??0)+(dotColor?.length??0)+(title?.length??0)+(group?.length??0)+(typeof badge=="string"?badge.length:0);if(textUnits+units>MAX_SOURCE_TEXT_UNITS)break;textUnits+=units,rows.push({value,label,...sub===void 0?{}:{sub},...icon===void 0?{}:{icon},...start===void 0?{}:{start},...end===void 0?{}:{end},...badge===void 0?{}:{badge},...accessibleLabel===void 0?{}:{accessibleLabel},...source.data===void 0?{}:{data:source.data},...dotColor===void 0?{}:{dotColor},...title===void 0?{}:{title},...group===void 0?{}:{group},...typeof source.disabled=="boolean"?{disabled:source.disabled}:{}})}catch{}const total=Math.max(providerTotal,candidateRows.length);return{rows,total,truncated:total>rows.length}}class LyraCombobox extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,collapse:LYRA_DEFAULT_collapse,comboboxCreate:LYRA_DEFAULT_comboboxCreate,comboboxLabel:LYRA_DEFAULT_comboboxLabel,comboboxLoadError:LYRA_DEFAULT_comboboxLoadError,comboboxOverflow:LYRA_DEFAULT_comboboxOverflow,comboboxRequired:LYRA_DEFAULT_comboboxRequired,comboboxSelectedOverflow:LYRA_DEFAULT_comboboxSelectedOverflow,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,noData:LYRA_DEFAULT_noData,noMatches:LYRA_DEFAULT_noMatches,notInCatalog:LYRA_DEFAULT_notInCatalog,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,retry:LYRA_DEFAULT_retry,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,tableLoadFailed:LYRA_DEFAULT_tableLoadFailed,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-input","lr-change"])}static{this.identityEventDetailCollectionItems=Object.freeze({"lr-input":Object.freeze(["data"]),"lr-change":Object.freeze(["data"])})}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles,srOnly]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},multiple:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},readonly:{type:Boolean,reflect:!0,noAccessor:!0},value:{noAccessor:!0},name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},maxOptionsVisible:{type:Number,attribute:"max-options-visible",noAccessor:!0},maxRender:{type:Number,attribute:"max-render",noAccessor:!0},sourceDelay:{type:Number,attribute:"source-delay",noAccessor:!0},minQueryLength:{type:Number,attribute:"min-query-length",noAccessor:!0}}}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&&!this.readonly&&!liveDisabled&&this.meetsMinimumQuery(this.query),this._open===old){next&&!this._open&&this.hasAttribute("open")&&this.removeAttribute("open");return}this.requestUpdate("open",old)}get appearance(){return this._appearance}set appearance(next){const normalized=APPEARANCE.normalizeReflected(this,"appearance",next),old=this._appearance;this._appearance=normalized,normalized!==old&&this.requestUpdate("appearance",old)}get positioningStrategy(){return this._positioningStrategy??"fixed"}set positioningStrategy(next){const normalized=POSITIONING_STRATEGY.normalize(next)??"fixed",old=this.positioningStrategy;this._positioningStrategy=normalized,normalized!==old&&this.requestUpdate("positioningStrategy",old)}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=!!next,this.requestUpdate()}get inputmode(){return this.inputMode}set inputmode(next){this.inputMode=next??""}get enterkeyhint(){return this.enterKeyHint}set enterkeyhint(next){this.enterKeyHint=next??""}get inputValue(){return this.query}set inputValue(next){this.explicitInputValue=!0,this.query=next??"",this.activeIndex=-1,this.source&&this.runSource(this.query),this.requestUpdate()}get query(){return this._query}set query(next){const old=this._query;next!==old&&(this._query=next,this.requestUpdate("query",old),this.enforceMinimumQuery(!0))}constructor(){super(),this.placeholder="",this.label="",this.labelDisplay="visible",this.hint="",this.errorText="",this.allowCreate=!1,this.allowCustomValue=!1,this.withUnknownOption=!1,this.loading=!1,this._appearance="outlined",this.placement="bottom",this.topLayer=!1,this.size="m",this.pill=!1,this.clearable=!1,this.withClear=!1,this.withLabel=!1,this.withHint=!1,this.validators=[],this.autocomplete="off",this.inputMode="",this.enterKeyHint="",this.spellcheck=!1,this.autocapitalize="",this.autocorrectValue=!0,this.filter=null,this.source=null,this._query="",this.explicitInputValue=!1,this.activeIndex=-1,this.options=[],this.optionsObserved=!1,this.touched=!1,this.validityRevision=0,this.slotPresence=new SlotPresenceController(this),this.sourceLoading=!1,this.sourceFailed=!1,this.sourceEverSettled=!1,this.asyncRows=[],this._sourceTotal=0,this._sourceTruncated=!1,this.sourceErrorAnnouncements=new AnnouncementSinkController(this,{eager:["assertive"]}),this.sourceDebounce=new DebounceController(0,request=>this.runSourceRequest(request),()=>this.ownerDocument.defaultView),this.sourceToken=0,this.refreshQueued=!1,this._sourceWarmed=!1,this._selectedLabelCache=new Map,this._selectedRowCache=new Map,this._renderedRows=[],this._open=!1,this._fieldsetDisabled=!1,this.listId=nextId("combobox-list"),this.inputId=nextId("combobox-input"),this.listboxPositioned=!1,this.positioningGeneration=0,this.positioningReady=Promise.resolve(!1),this.restoreFocusOnClose=!0,this.restoringOverlayFocus=!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.listboxHidden=!0,this.listboxRendered=!1,this._isFirstUpdate=!0,this.openVetoed=!1,this.closeAfterPositioningFailure=!1,this.minimumQueryClosePending=!1,this.minimumQueryCloseUnpainted=!1,this.closeCleanupPending=!1,this._selected=[],this.sourceOptionsByRow=new WeakMap,this._valueDirty=!1,this._multiple=!1,this._disabled=!1,this._required=!1,this._readonly=!1,this._defaultSelected=[],this._defaultCaptured=!1,this._restoredStateActive=!1,this._name="",this._maxOptionsVisible=3,this._maxRender=200,this._sourceDelay=200,this._minQueryLength=0,this.localDescriptionIds="",this.previousSelection=[],this.markInteracted=()=>{this.touched||(this.touched=!0,this.updateValidity(),this.syncCustomStates())},this.collectOptions=e=>{this.collectOptionsFromSlot(e.target)},this.callbackRefreshEpoch=0,this.optionMemo=new Map,this.pendingSelectedWrites=new Map,this.selectedWritesQueued=!1,this.optionRefreshPending=!1,this.onOptionChange=e=>{e.stopPropagation();const option=e.composedPath().find(isLyraOptionElement);if(isOptionSelectedWrite(e)&&isLyraOptionElement(option)&&this.optionIndex.members.has(option)){this._valueDirty=!0,this._restoredStateActive=!1,this.pendingSelectedWrites.delete(option),this.pendingSelectedWrites.set(option,{selected:option.selected,value:option.value}),this.selectedWritesQueued||(this.selectedWritesQueued=!0,queueMicrotask(()=>this.flushSelectedWrites()));return}if(isLyraOptionElement(option)){const cached=this.adornmentClones.get(option);cached&&cached.markup!==this.adornmentMarkup(option)&&this.adornmentClones.delete(option)}this.optionRefreshPending||(this.optionRefreshPending=!0,queueMicrotask(()=>{this.optionRefreshPending=!1,this.refreshOptionDefaults(),this.reflectSelected(),this.options=[...this.options],this.normalizeActiveIndex()}))},this.adornmentClones=new WeakMap,this.lastRenderedRows=[],this.onDocPointer=e=>{if(!e.composedPath().includes(this)){if(this.overlayHandle?.isActive()){this.overlayHandle.dismissBackdrop();return}this.restoreFocusOnClose=!1,this.hide()}},this.onInput=e=>{this.liveDisabled||this.readonly||(this.explicitInputValue=!1,this.query=e.target.value,this.activeIndex=-1,this.show(),this.source&&this.runSource(this.query),this.emit("lr-filter",{value:this.query}))},this.onInputBlur=event=>{this.liveDisabled||(this.touched=!0),this.syncCustomStates(),this.onComboFocusOut(event),relayNativeEvent(this,event)},this.onComboFocusOut=event=>{const trigger=this.renderRoot.querySelector('[part="combobox"]'),target=event.relatedTarget;target&&typeof target.nodeType=="number"&&trigger?.contains(target)||(this.restoreFocusOnClose=!1,this.hide())},this.onInputFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}this.restoringOverlayFocus||this.show(),relayNativeEvent(this,event)},this.onKeyDown=e=>{if(e.isComposing||e.keyCode===229||this.liveDisabled||this.readonly)return;const navigable=["ArrowDown","ArrowUp","Enter","End"].includes(e.key)?this.renderedRows.rows.filter(r=>!r.disabled):[];switch(e.key){case"ArrowDown":case"ArrowUp":if(!this.meetsMinimumQuery(this.query))return;if(e.preventDefault(),!this.open){this.activeIndex=navigable.findIndex(row=>this.committed.includes(row.value)),this.show();return}if(e.key==="ArrowDown"){this.activeIndex=Math.min(navigable.length-1,this.activeIndex+1);break}this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":{const activeRow=navigable[this.activeIndex];if(this.open&&this.activeIndex>=0&&activeRow){e.preventDefault(),this.pickRow(activeRow);break}const create=this.createRow;if(this.open&&create){e.preventDefault(),this.createOption(create.createInput);break}if(this.open&&this.allowCustomValue&&!this.multiple&&this.query.trim()){e.preventDefault(),this.commitCustomValue(this.query.trim());break}submitOnEnter(this,e);break}case"Escape":this.open&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(e.preventDefault(),this.hide());break;case"Home":this.open&&(e.preventDefault(),this.activeIndex=0);break;case"End":this.open&&(e.preventDefault(),this.activeIndex=navigable.length-1);break;case"Backspace":this.multiple&&!this.query&&this._selected.length&&this.removeValueAt(this._selected.length-1);break}},this.onComboMouseDown=e=>{this.liveDisabled||e.composedPath()[0]!==this.inputEl&&(e.target.closest("button")||(e.preventDefault(),this.inputEl?.focus(),this.show()))},this.onListboxMouseDown=e=>{e.preventDefault()},this.onListboxClick=e=>{const optionEl=e.target.closest('[part="option"]'),row=this._renderedRows[Number(optionEl?.dataset.index)];row&&this.pickRow(row)},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)}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}get validationTarget(){return this.validationTargetOverride??this.inputEl??void 0}set validationTarget(next){this.validationTargetOverride=next??void 0,this.validityController.refreshAnchor()}resetValidity(){this.validityController.setCustomValidity(""),this.updateValidity()}get input(){return this.inputEl??null}get selectionStart(){return this.inputEl?.selectionStart??null}set selectionStart(value){this.inputEl&&(this.inputEl.selectionStart=value)}get selectionEnd(){return this.inputEl?.selectionEnd??null}set selectionEnd(value){this.inputEl&&(this.inputEl.selectionEnd=value)}get selectionDirection(){return this.inputEl?.selectionDirection}set selectionDirection(value){this.inputEl&&(this.inputEl.selectionDirection=value)}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}get interactionBarred(){return this.liveDisabled||this.readonly}focus(options){this.liveDisabled||this.inputEl?.focus(options)}blur(){this.inputEl?.blur()}click(){this.liveDisabled||(this.inputEl?.focus(),this.show())}select(){this.inputEl?.select()}setSelectionRange(start,end,direction){this.inputEl?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){const input=this.inputEl;input&&(setNativeRangeText(input,replacement,start,end,selectMode),this.explicitInputValue=!0,this.query=input.value,this.activeIndex=-1,this.source&&this.runSource(this.query))}[VALIDITY_ANCHOR](){return this.validationTarget}syncExternalDescription(){if(!this.isConnected)return;const target=this.renderRoot.querySelector('[part="combobox-input"]');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.updateValidity(),this.hasUpdated&&this.syncValidatorAttributeObserver(),this.hasUpdated&&queueMicrotask(()=>{this.open?this.reconnectOpenPopup():this.source&&this._selected.length&&this.asyncRows.length===0&&this.runSource("")})}adoptedCallback(){super.adoptedCallback(),this.popupController.cancel(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription(),this.listboxPositioned=!1,this.invalidateListboxPositioning(),this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.popupController.unbindPointer(),this.clearSourceTimer(),this.sourceToken+=1,this.sourceAbort?.abort(),this.sourceAbort=void 0,this.sourceErrorAnnouncements.adopted()}willUpdate(changed){super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,this.enforceMinimumQuery(!1),this.announceOpenTransition(changed),this.open?(this.listboxHidden=!1,this.listboxRendered=!0):changed.has("open")&&this.interactionBarred&&(this.listboxHidden=!0),changed.has("open")&&!this.openVetoed&&(this.listboxPositioned=!1),changed.has("open")&&this.openVetoed?this.closeCleanupPending=!1:changed.has("open")&&!this.open&&this.finalizeCloseState(),changed.has("source")&&(this.clearSourceTimer(),this.sourceAbort?.abort(),this.sourceAbort=void 0,this.sourceToken++,this.sourceLoading=!1,this.sourceFailed=!1,this.sourceEverSettled=!1,this.asyncRows=[],this._sourceTotal=0,this._sourceTruncated=!1,this.activeIndex=-1,this._sourceWarmed=!1,this.source&&this.open&&this.runSource(this.query)),!this._sourceWarmed&&this.source&&(this._selected.length>0||(this.pendingSelectedRowValues?.length??0)>0)&&this.asyncRows.length===0&&(this._sourceWarmed=!0,this.runSource(""))}firstUpdated(changed){super.firstUpdated(changed);const slot=this.optionsSlot;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>{this.optionsObserved=!0,s.assignedElements({flatten:!0}).some(isLyraOptionElement)&&this.collectOptionsFromSlot(s)})})}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",reflectFormName(this,this._name),this.syncFormValue(),this.requestUpdate("name",old)}get multiple(){return this._multiple}set multiple(next){const old=this._multiple;this._multiple=!!next,this.toggleAttribute("multiple",this._multiple),this.reflectSelected(),this.syncFormValue(),this.requestUpdate("multiple",old)}get disabled(){return this._disabled}set disabled(next){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 readonly(){return this._readonly}set readonly(next){const old=this._readonly;this._readonly=!!next,this.toggleAttribute("readonly",this._readonly),this._readonly&&this.hide(),this.updateValidity(),this.requestUpdate("readonly",old)}get value(){return this.multiple?[...this._selected]:this._selected[0]??""}set value(next){this.setValue(next,!0)}setValue(next,dirty,preferred){this.pendingSelectedWrites.clear();const old=this._selected;this.previousSelection=old,this.singleSelectedOption=preferred,dirty&&(this._restoredStateActive=!1,this._valueDirty=!0),this._selected=normalizeSelectionValues(next);const selected=new Set(this._selected);if(selected.size>0){const rows=this.rowsByValue(selected);for(const value of selected){const row=rows.get(value);row&&this._selectedRowCache.set(value,row)}}for(const value of this._selectedRowCache.keys())selected.has(value)||this._selectedRowCache.delete(value);for(const value of this._selectedLabelCache.keys())selected.has(value)||this._selectedLabelCache.delete(value);this.syncFormValue(),this.reflectSelected(),this.updateValidity(),this.requestUpdate("value",old)}get maxOptionsVisible(){return this._maxOptionsVisible}set maxOptionsVisible(next){const old=this._maxOptionsVisible;this._maxOptionsVisible=finiteCount(next,3),this.requestUpdate("maxOptionsVisible",old)}get maxRender(){return this._maxRender}get sourceDelay(){return this._sourceDelay}set sourceDelay(next){const old=this._sourceDelay;this._sourceDelay=finiteDuration(next,200),this.requestUpdate("sourceDelay",old)}get minQueryLength(){return this._minQueryLength}set minQueryLength(next){const old=this._minQueryLength;this._minQueryLength=finiteCount(next),this.enforceMinimumQuery(this.open||this.explicitInputValue),this.requestUpdate("minQueryLength",old)}meetsMinimumQuery(query2){const minimum=this._minQueryLength??0;if(minimum===0)return!0;const trimmed=query2.trim();let count=0;for(let index=0;index<trimmed.length;index+=trimmed.codePointAt(index)>65535?2:1)if(++count>=minimum)return!0;return!1}enforceMinimumQuery(preserveDraft){if(this.meetsMinimumQuery(this.query))return;this.clearSourceTimer();const abort=this.sourceAbort;this.sourceAbort=void 0;const token=++this.sourceToken;this.refreshQueued=!1,this.sourceLoading=!1,this.sourceFailed=!1,this.asyncRows.length&&(this.asyncRows=[]),this._sourceTotal=0,this._sourceTruncated=!1,this.activeIndex=-1,abort?.abort(),!(token!==this.sourceToken||this.meetsMinimumQuery(this.query))&&(this.closeCleanupPending=!1,preserveDraft&&(this.explicitInputValue=!0),this.minimumQueryClosePending||=this.open,this.open=!1,this.listboxHidden=!0,this.listboxRendered=!1,this.listboxPositioned=!1,this.popupController.cancel())}set maxRender(next){const old=this._maxRender;this._maxRender=Math.min(finiteCount(next,200),MAX_RENDER_ROWS),this.requestUpdate("maxRender",old)}get sourceTotal(){return this._sourceTotal}get sourceTruncated(){return this._sourceTruncated}get selectedRows(){return this.resolveSelectedRowSlots().filter(row=>row!=null).map(row=>{const option=this.sourceOptionsByRow.get(row);return{...row,...option?this.adornmentsFor(option):{}}})}resolveSelectedRowSlots(){let rows;return this.committed.map(value=>this._selectedRowCache.get(value)??(rows??=this.rowsByValue(new Set(this.committed))).get(value))}get committed(){return this.multiple?this._selected:this._selected.slice(0,1)}rowsByValue(values){const rows=this.source?new Map:this.localRowsByValue(values,this.options);for(const row of this.asyncRows)values.has(row.value)&&!rows.has(row.value)&&rows.set(row.value,row);return rows}localRowsByValue(values,options){const rows=new Map;if(values.size===0)return rows;for(const option of options){const value=option.value;values.has(value)&&!rows.has(value)&&rows.set(value,this.rowForOption(option,!1))}return rows}set selectedRows(next){const values=[],seen=new Set;if(Array.isArray(next))for(const candidate of next){let value;try{value=candidate?.value}catch{continue}typeof value!="string"||seen.has(value)||(seen.add(value),values.push(value))}if(values.length>0&&!this.hasSelectionSourceRows){this.pendingSelectedRowValues=values,this.source&&this.isConnected&&(this._sourceWarmed=!0,this.runSource(""));return}this.pendingSelectedRowValues=void 0,this.applySelectedRowValues(values)}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}validatorResult(){const self=this,current=self.value;for(const validator of Array.isArray(this.validators)?this.validators:[]){let result;try{if(typeof validator=="object"&&validator!==null&&"checkValidity"in validator){const checked=validator.checkValidity(this);if(checked?.isValid===!0)continue;const flags={};for(const key of Array.isArray(checked?.invalidKeys)?checked.invalidKeys:[])isValidityFlagKey(key)&&(flags[key]=!0);Object.values(flags).some(Boolean)||(flags.customError=!0);let message=typeof checked?.message=="string"?checked.message:"";return!message&&typeof validator.message=="string"&&(message=validator.message),!message&&typeof validator.message=="function"&&(message=validator.message(this)),{flags,message:message||this.localize("valueInvalid")}}result=typeof validator=="function"?validator(current,self):validator?.validate(current,self)}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}if(!(result===void 0||result===!0)){if(typeof result=="string")return{flags:{customError:!0},message:result};if(result===!1)return{flags:{customError:!0},message:this.localize("valueInvalid")};if(result&&typeof result=="object"&&Object.values(result).some(Boolean))return{flags:result,message:this.localize("valueInvalid")}}}return{}}syncValidatorAttributeObserver(){this.disconnectValidatorAttributeObserver();const owner=this.ownerDocument.defaultView,MutationObserverCtor=owner?.MutationObserver;if(!this.isConnected||!owner||typeof MutationObserverCtor!="function")return;const attributes=new Set;for(const validator of Array.isArray(this.validators)?this.validators:[]){if(typeof validator!="object"||validator===null||!("checkValidity"in validator))continue;let observed;try{observed=validator.observedAttributes}catch{continue}if(Array.isArray(observed))for(const name of observed)typeof name=="string"&&name.length>0&&attributes.add(name)}if(attributes.size===0)return;const binding={},observer=new MutationObserverCtor(()=>{this.validatorAttributeObserver!==binding||!this.isConnected||this.ownerDocument.defaultView!==owner||(this.updateValidity(),this.validityRevision++)});binding.observer=observer,binding.owner=owner;try{observer.observe(this,{attributes:!0,attributeFilter:[...attributes]}),this.validatorAttributeObserver=binding}catch{observer.disconnect()}}disconnectValidatorAttributeObserver(){const binding=this.validatorAttributeObserver;this.validatorAttributeObserver=void 0,binding?.observer.disconnect()}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({}),this.syncCustomStates();return}const flags={};let message="";this.required&&this._selected.length===0&&(flags.valueMissing=!0,message=this.localize("comboboxRequired"));const configured=this.validatorResult();configured.flags&&Object.assign(flags,configured.flags),configured.message&&(message=configured.message),this.validityController.setValidity(flags,message),this.syncCustomStates()}syncCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",this._selected.length===0),setCustomState(this.internals,"disabled",this.effectiveDisabled)}syncFormValue(){const state2=JSON.stringify(this._selected);if(this.multiple){if(!this.name){this.internals.setFormValue(null,state2);return}const fd=new FormData;for(const v of this._selected)fd.append(this.name,v);this.internals.setFormValue(fd,state2)}else this.internals.setFormValue(this._selected[0]??"",state2)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formResetCallback(){this.touched=!1,this._restoredStateActive=!1,this._valueDirty=!1;const resetValues=this._defaultSelected.length>0?this._defaultSelected:this.options.filter(option=>wasOptionInitiallySelected(option)).map(option=>option.value);this._defaultSelected.length===0&&resetValues.length>0&&(this._defaultSelected=[...resetValues]);const defaults=new Set(resetValues);for(const option of this.options)option[RESET_OPTION_SELECTED_FROM_OWNER](defaults.has(option.value));this.setValue(this.multiple?[...resetValues]:resetValues.slice(0,1),!1),this.query="",this.explicitInputValue=!1}formStateRestoreCallback(state2,reason){let selected=[];if(typeof state2=="string")try{const parsed=JSON.parse(state2);Array.isArray(parsed)&&parsed.every(value=>typeof value=="string")&&(selected=parsed)}catch{}this.assignValue(this.multiple?selected:selected.slice(0,1)),this._restoredStateActive=!0}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(disabled&&this.hide(),this.updateValidity(),this.requestUpdate())}checkValidity(){return this.validityController.checkValidity(()=>this.updateValidity())}reportValidity(){return this.validityController.syncConstraints(),this.touched=!0,this.updateValidity(),this.syncCustomStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncCustomStates()}disconnectedCallback(){this.pendingSelectedWrites.clear(),this.listboxHidden=!0,this.releaseExternalDescription(),this.popupController.cancel(),this.listboxPositioned=!1,this.disconnectValidatorAttributeObserver(),super.disconnectedCallback(),this.invalidateListboxPositioning(),this.clearSourceTimer(),this.sourceToken+=1,this.sourceAbort?.abort(),this.sourceAbort=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.popupController.unbindPointer(),this.open=!1}collectOptionsFromSlot(slot){const previous=new Set(this.options);if(this.optionsObserved=!0,this.options=slot.assignedElements({flatten:!0}).filter(isLyraOptionElement),this.adornmentClones=new WeakMap,this.normalizeActiveIndex(),this.applyPendingSelectedRows(),this._defaultCaptured){const newDefaults=this.options.filter(option=>!previous.has(option)&&option.defaultSelected),newLive=this.options.filter(option=>!previous.has(option)&&option.selected&&!option.defaultSelected);this.refreshOptionDefaults();const eligible=[...!this._restoredStateActive&&!this._valueDirty?newDefaults:[],...this._restoredStateActive?[]:newLive];if(eligible.length){const values=eligible.map(option=>option.value),next=this.multiple?[...new Set([...this._selected,...values])]:values[values.length-1];newLive.length>0?this.assignValue(next):this.setValue(next,!1);return}}else{this._defaultCaptured=!0;const allDefaults=this.options.filter(option=>option.defaultSelected).map(option=>option.value),allLive=this.options.filter(option=>option.selected).map(option=>option.value),defaults=this.multiple?allDefaults:allDefaults.slice(0,1),live=this.multiple?allLive:allLive.slice(0,1),initialLive=this.options.filter(option=>wasOptionInitiallySelected(option)).map(option=>option.value),optionDirty=this.options.some(option=>isOptionSelectedDirty(option)),dirtyValues=this.options.filter(option=>isOptionSelectedDirty(option)&&option.selected).map(option=>option.value);this._defaultSelected=[...defaults.length>0?defaults:initialLive.length>0?initialLive:live];const fromDefaults=defaults.length>0,initial=optionDirty?this.multiple?allLive:dirtyValues.slice(-1)[0]?dirtyValues.slice(-1):live:fromDefaults?defaults:live;if(initial.length&&!this._restoredStateActive&&!this._valueDirty){const next=this.multiple?initial:initial[0];fromDefaults&&!optionDirty?this.setValue(next,!1):this.assignValue(next);return}optionDirty&&(this._valueDirty=!0)}this.reflectSelected()}refreshOptionDefaults(){const declared=this.options.filter(option=>option.defaultSelected).map(option=>option.value);this._defaultSelected=this.multiple?declared:declared.slice(0,1),!this._valueDirty&&!this._restoredStateActive&&this.setValue([...this._defaultSelected],!1)}requestUpdate(...args){args[0]===void 0&&(this.callbackRefreshEpoch=(this.callbackRefreshEpoch??0)+1),super.requestUpdate(...args)}memoOption(key,inputs,compute){const previous=this.optionMemo.get(key);if(previous&&previous.inputs.length===inputs.length&&previous.inputs.every((input,index)=>Object.is(input,inputs[index])))return previous.value;const value=compute();return this.optionMemo.set(key,{inputs,value}),value}get optionIndex(){return this.memoOption("index",[this.options],()=>{const values=new Map;for(const option of this.options)values.has(option.value)||values.set(option.value,option);return{values,members:new Set(this.options)}})}get asyncIndex(){return this.memoOption("asyncIndex",[this.asyncRows],()=>{const values=new Map;for(const row of this.asyncRows)values.has(row.value)||values.set(row.value,row);return values})}get searchCorpus(){return this.memoOption("corpus",[this.options,this.effectiveLocale],()=>this.options.map(option=>({label:option.label.toLocaleLowerCase(this.effectiveLocale),search:option.searchText.toLocaleLowerCase(this.effectiveLocale),value:option.value.toLocaleLowerCase(this.effectiveLocale)})))}flushSelectedWrites(){this.selectedWritesQueued=!1;const writes=[...this.pendingSelectedWrites];if(this.pendingSelectedWrites.clear(),!(!this.isConnected||writes.length===0))if(this.multiple){const values=new Set(this._selected);for(const[option,write]of writes)this.optionIndex.members.has(option)&&(write.selected?values.add(write.value):values.delete(write.value));this.setValue([...values],!0)}else{let value=this._selected[0],option=this.singleSelectedOption;for(const[candidate,write]of writes)this.optionIndex.members.has(candidate)&&(write.selected?(value=write.value,option=candidate):candidate===option&&(value=void 0,option=void 0));this.setValue(value===void 0?[]:value,!0,option)}}reflectSelected(){const value=this._selected[0];(!this.singleSelectedOption||!this.optionIndex.members.has(this.singleSelectedOption)||this.singleSelectedOption.value!==value)&&(this.singleSelectedOption=value===void 0?void 0:this.optionIndex.values.get(value));const selected=new Set(this._selected);for(const option of this.options)option[SET_OPTION_SELECTED_FROM_OWNER](this.multiple?selected.has(option.value):option===this.singleSelectedOption)}labelFor(value){const nonBlank=label=>label!==void 0&&label.trim().length>0?label:void 0;if(this.getUnknownLabel&&this.isUnknownValue(value)){const override=nonBlank(this.getUnknownLabel(value));if(override!==void 0)return override}return(!this.source&&!this.multiple&&this.singleSelectedOption?.value===value?nonBlank(this.singleSelectedOption.label):void 0)??nonBlank(this._selectedLabelCache.get(value))??nonBlank(this.optionIndex.values.get(value)?.label)??nonBlank(this.asyncIndex.get(value)?.label)??(this.loading||this.source&&!this.sourceEverSettled?this.statusText("loading",this.loadingText):void 0)??value}isUnknownValue(value){return!this.source&&!this.optionsObserved||this.loading||this.source&&!this.sourceEverSettled?!1:!(!this.source&&!this.multiple&&this.singleSelectedOption?.value===value||this._selectedLabelCache.has(value)||this.optionIndex.values.has(value)||this.asyncIndex.has(value))}adornmentMarkup(option){return Array.from(option.children).filter(child=>["start","end","prefix","suffix"].includes(child.getAttribute("slot")??"")).map(child=>child.outerHTML).join("")}adornmentsFor(option){const cached=this.adornmentClones.get(option);if(cached)return cached;const cloneSlot=selector=>{const nodes=Array.from(option.querySelectorAll(selector));if(nodes.length!==0)return nodes.map(node=>node.cloneNode(!0))},resolved={markup:this.adornmentMarkup(option),start:cloneSlot(':scope > [slot="start"], :scope > [slot="prefix"]'),end:cloneSlot(':scope > [slot="end"], :scope > [slot="suffix"]')};return this.adornmentClones.set(option,resolved),resolved}rowForOption(option,withAdornments=!0){const adornments=withAdornments?this.adornmentsFor(option):{},row={value:option.value,label:option.label||option.value,sub:option.sub||void 0,dotColor:option.dotColor||void 0,title:option.title||void 0,group:option.group||void 0,disabled:option.disabled||option.inert||option.closest("[inert]")!==null,data:option.data,...adornments.start===void 0?{}:{start:adornments.start},...adornments.end===void 0?{}:{end:adornments.end}};return this.sourceOptionsByRow.set(row,option),row}get hasSelectionSourceRows(){return(this.source?this.asyncRows.length:this.options.length)>0}applySelectedRowValues(values){const requested=new Set(values),rowsByValue=this.source?this.rowsByValue(requested):this.localRowsByValue(requested,this.options),rows=values.map(value=>rowsByValue.get(value)).filter(row=>row!==void 0),limited=this.multiple?rows:rows.slice(0,1);this.assignValue(limited.map(row=>row.value));for(const row of limited)this._selectedRowCache.set(row.value,row)}applyPendingSelectedRows(acceptEmptySource=!1){if(this.pendingSelectedRowValues===void 0||!acceptEmptySource&&!this.hasSelectionSourceRows)return!1;const values=this.pendingSelectedRowValues;return this.pendingSelectedRowValues=void 0,this.applySelectedRowValues(values),!0}get unknownRows(){if(!this.withUnknownOption)return[];const locale=this.effectiveLocale,query2=this.query.trim().toLocaleLowerCase(locale);return this.committed.filter(value=>this.isUnknownValue(value)).map(value=>({value,label:this.labelFor(value),badge:this.localize("notInCatalog"),unknownValue:value})).filter(row=>!query2||row.label.toLocaleLowerCase(locale).includes(query2)||row.value.toLocaleLowerCase(locale).includes(query2))}get createRow(){if(!this.allowCreate)return;const inputValue=this.query.trim();if(!inputValue)return;const locale=this.effectiveLocale,folded=inputValue.toLocaleLowerCase(locale);if(!(this.source?this.memoOption("asyncExact",[this.asyncRows,locale],()=>new Set(this.asyncRows.flatMap(row=>[row.value.toLocaleLowerCase(locale),row.label.toLocaleLowerCase(locale)]))).has(folded):this.searchCorpus.some(row=>row.value===folded||row.label===folded)))return{value:inputValue,label:this.localize("comboboxCreate",void 0,{value:inputValue}),createInput:inputValue}}capRows(all,activeValue){return this.memoOption("capRows",[all,this.maxRender,this._selected,this.multiple,activeValue],()=>{const selected=new Set(this.committed),retained=all.filter(row=>selected.has(row.value)),active=activeValue===void 0?void 0:all.find(row=>row.value===activeValue);return capOptionRows(all,this.maxRender,active?[active,...retained]:retained)})}get renderedRows(){const active=this.lastRenderedRows.filter(row=>!row.disabled)[this.activeIndex]?.value,result=this.memoOption("renderedRows",[this.callbackRefreshEpoch,this.options,this.asyncRows,this.source,this.query,this._selected,this.multiple,this.maxRender,this._sourceTotal,this.withUnknownOption,this.allowCreate,this.filter,this.getUnknownLabel,this.loading,this.sourceEverSettled,this.effectiveLocale,this.strings,active],()=>this.computeRenderedRows(active));return this.lastRenderedRows=result.rows,result}computeRenderedRows(active){let rows,overflow;if(this.source){const capped=this.capRows(this.asyncRows,active);rows=[...capped.rows],overflow=capped.overflow,overflow+=Math.max(0,this._sourceTotal-this.asyncRows.length)}else{const capped=this.capRows(this.filtered,active);rows=capped.rows.map(option=>this.rowForOption(option)),overflow=capped.overflow}rows=[...rows];const create=this.createRow;rows.push(...this.unknownRows),create&&rows.push(create);const selected=new Set(this.committed),retained=rows.filter(row=>selected.has(row.value)),activeRow=rows.find(row=>row.value===active),bounded=capOptionRows(rows,MAX_RENDER_ROWS,activeRow?[activeRow,...retained]:retained);return{rows:bounded.rows,overflow:overflow+bounded.overflow}}normalizeActiveIndex(){if(this.activeIndex<0)return;const navigableCount=this.renderedRows.rows.filter(row=>!row.disabled).length,next=navigableCount>0?Math.min(this.activeIndex,navigableCount-1):-1;next!==this.activeIndex&&(this.activeIndex=next)}get filtered(){const locale=this.effectiveLocale,q=this.query.trim().toLocaleLowerCase(locale),selectedLabel=this.multiple?"":this.labelFor(this._selected[0]??"")??"",effective=q&&q===selectedLabel.toLocaleLowerCase(locale)?"":q;return effective?this.memoOption("filtered",[this.options,this.filter,effective,locale,this.callbackRefreshEpoch],()=>{const filter=this.filter;if(filter)return this.options.filter(option=>filter(option,effective));const corpus=this.searchCorpus;return this.options.filter((_option,index)=>corpus[index].label.includes(effective)||corpus[index].search.includes(effective))}):this.options}get displayValue(){return this.multiple||this.open||this.explicitInputValue?this.query:this._selected[0]?this.labelFor(this._selected[0]):""}announceOpenTransition(changed){this.openVetoed=!1,this.minimumQueryCloseUnpainted=!1;const minimumClose=this.minimumQueryClosePending;if(this.minimumQueryClosePending=!1,minimumClose&&!this.open)if(!this._isFirstUpdate&&changed.has("open")&&changed.get("open")===!0&&this.isConnected){if(emitPopupEvent(this,"lr-hide",!1),!this.open)return}else{this.minimumQueryCloseUnpainted=!0;return}const closeAfterPositioningFailure=!this.open&&this.closeAfterPositioningFailure;if(this.closeAfterPositioningFailure=!1,!(!changed.has("open")||this._isFirstUpdate||!this.open&&this.interactionBarred)){if(!this.isConnected||closeAfterPositioningFailure){emitPopupEvent(this,"lr-hide",!1);return}this.openVetoed=this.popupController.announce(this.open,()=>{this.open=!this.open})}}show(){if(this.open||this.interactionBarred||!this.meetsMinimumQuery(this.query))return Promise.resolve();const settled=this.popupController.wait(!0);return this.open=!0,this.open||this.popupController.release("lr-after-show"),settled}hide(){if(!this.open)return Promise.resolve();const settled=this.popupController.wait(!1);return this.closeCleanupPending=!0,this.open=!1,settled}finalizeCloseState(){if(this.closeCleanupPending&&(this.closeCleanupPending=!1,this.activeIndex=-1,!this.multiple)){const queryChanged=this.query!=="";this.query="",this.explicitInputValue=!1,queryChanged&&this.source&&(this.asyncRows=[],this.sourceFailed=!1,this._sourceTotal=0,this._sourceTruncated=!1)}}activateListboxOverlay(){this.invalidateListboxPositioning(),this.overlayHandle?.deactivate({restoreFocus:!1}),this.restoreFocusOnClose=!0,this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="listbox"]'),onEscape:()=>{this.hide()},onBackdrop:()=>{this.restoreFocusOnClose=!1,this.hide()},restoreFocusTo:this.inputEl??null}),this.popupController.bindPointer(),this.beginListboxPositioning()}beginListboxPositioning(){const anchor=this.renderRoot.querySelector('[part="combobox"]'),listbox=this.renderRoot.querySelector('[part="listbox"]');if(anchor&&listbox){const generation=this.positioningGeneration;this.positioningReady=new Promise(resolve=>{this.resolvePositioningReady=resolve}),this.startListboxPositioning(generation,anchor,listbox)}}invalidateListboxPositioning(){this.positioningGeneration++,this.cleanup?.(),this.cleanup=void 0,this.resolvePositioningReady?.(!1),this.resolvePositioningReady=void 0}resolveCurrentPositioning(positioned){const resolve=this.resolvePositioningReady;this.resolvePositioningReady=void 0,resolve?.(positioned)}async startListboxPositioning(generation,anchor,listbox){try{const runtime=await loadAnchoredOverlayRuntime(),{place}=runtime;if(generation!==this.positioningGeneration||!this.open||!this.isConnected||this.renderRoot.querySelector('[part="combobox"]')!==anchor||this.renderRoot.querySelector('[part="listbox"]')!==listbox)return;this.placedTopLayer=syncTopLayerRelease(listbox,this.placedTopLayer,this.topLayer,runtime);const cleanup=place(anchor,listbox,{placement:`${this.placement}-start`,...topLayerPlacement(this.topLayer,resolveEffectivePositioningStrategy(this,this._positioningStrategy,"fixed")),sync:this.sync,onPlaced:()=>{generation===this.positioningGeneration&&(this.listboxPositioned=!0,this.updateComplete.then(()=>{generation!==this.positioningGeneration||!this.open||this.resolveCurrentPositioning(!0)}))}});generation!==this.positioningGeneration?cleanup():this.cleanup=cleanup}catch{if(generation!==this.positioningGeneration||!this.open)return;this.resolveCurrentPositioning(!1),this.closeAfterPositioningFailure=!0,this.hide()}}teardownListboxOverlay(restoreFocus=this.restoreFocusOnClose){this.invalidateListboxPositioning(),this.restoringOverlayFocus=restoreFocus;try{this.overlayHandle?.deactivate({restoreFocus})}finally{this.restoringOverlayFocus=!1}this.overlayHandle=void 0,this.popupController.unbindPointer(),this.restoreFocusOnClose=!0}reconnectOpenPopup(){!this.isConnected||!this.open||(this.activateListboxOverlay(),this.source&&this.asyncRows.length===0&&this.runSource(this.query))}syncVisibleOptionsCap(){const listbox=this.renderRoot?.querySelector('[part="listbox"]');if(!listbox)return;const clear=()=>{listbox.style.removeProperty("max-block-size")},requested=typeof this.visibleOptions=="number"?finiteCount(this.visibleOptions,0):0;if(requested<=0)return clear();const rows=listbox.querySelectorAll('[part="option"]');if(rows.length<=requested)return clear();const boundary=rows[requested];if(!boundary)return clear();const cap=boundary.getBoundingClientRect().top-listbox.getBoundingClientRect().top;if(!Number.isFinite(cap)||cap<=0)return clear();listbox.style.setProperty("max-block-size",`min(${Math.ceil(cap)}px, var(--lr-positioner-available-block-size, var(--lr-size-18rem)))`)}updated(changed){if(super.updated(changed),this.syncExternalDescription(),(changed.has("visibleOptions")||changed.has("open")||changed.has("query")||changed.has("options")||changed.has("asyncRows")||changed.has("maxRender")||changed.has("value")||changed.has("listboxPositioned")||changed.has("strings")||changed.has("lang")||changed.has("size")||changed.has("filter")||changed.has("allowCreate")||changed.has("withUnknownOption"))&&this.syncVisibleOptionsCap(),changed.has("open")&&!this.openVetoed?this.open&&this.isConnected?(this.activateListboxOverlay(),this._isFirstUpdate||this.settleTransition("lr-after-show"),this.refreshQueued?(this.refreshQueued=!1,this.runSource(this.query)):this.source&&this.asyncRows.length===0&&this.runSource(this.query)):this.open?this.teardownListboxOverlay(!1):(this.teardownListboxOverlay(),this.interactionBarred||this.minimumQueryCloseUnpainted?this.popupController.cancel():this._isFirstUpdate||this.settleTransition("lr-after-hide")):changed.has("open")&&this.openVetoed&&(this.restoreFocusOnClose=!0),changed.has("topLayer")&&!changed.has("open")&&this.open&&this.isConnected&&(this.invalidateListboxPositioning(),this.beginListboxPositioning()),changed.has("name")&&this.syncFormValue(),changed.has("validators")&&(this.updateValidity(),this.syncValidatorAttributeObserver()),(changed.has("touched")||changed.has("required")||changed.has("value")||changed.has("validators")||changed.has("validityRevision"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),changed.has("activeIndex")||changed.has("listboxPositioned")){const listbox=this.renderRoot.querySelector('[part="listbox"]'),row=listbox?.querySelector('[part="option"][data-active]');listbox&&row&&revealRow(listbox,row)}}settleTransition(event){return this.popupController.settle(event,{waitForPosition:async stale=>{for(;this.open&&!this.listboxPositioned;){const readiness=this.positioningReady,positioned=await readiness;if(stale())return!1;if(positioned)break;if(readiness===this.positioningReady)return!1}return!0},conceal:()=>{this.listboxHidden=!0,this.listboxRendered=!1}})}emitValueEvents(){const self=this,data=this.resolveSelectedRowSlots().map(row=>row?.data),previousValue=this.multiple?[...this.previousSelection]:this.previousSelection[0]??"",detail={value:self.value,previousValue,data};emitValueEvents(self,"input",detail,detail2=>self.emit("lr-input",detail2)),emitValueEvents(self,"change",detail,detail2=>self.emit("lr-change",detail2))}assignValue(next){this.value=next}createOption(inputValue){if(this.liveDisabled||this.readonly||this.emit("lr-create",{inputValue},{cancelable:!0}).defaultPrevented)return;const option=this.ownerDocument.createElement(tag("option"));option.setAttribute("value",inputValue),option.textContent=inputValue,this.append(option),this.pickRow({value:inputValue,label:inputValue})}commitCustomValue(inputValue){if(this.liveDisabled||this.readonly||this.multiple||!inputValue)return;const selectionChanged=this._selected[0]!==inputValue;this.touched=!0,this._selectedLabelCache.set(inputValue,inputValue),this.assignValue(inputValue),this.query="",this.explicitInputValue=!1,this.hide(),selectionChanged&&this.emitValueEvents()}pickRow(row){const sourceOption=this.sourceOptionsByRow.get(row);if(this.liveDisabled||this.readonly||row.disabled||sourceOption&&(sourceOption.disabled||sourceOption.closest("[inert]")))return;if(row.createInput!==void 0){this.createOption(row.createInput);return}this.touched=!0;const synthetic=row.unknownValue!==void 0,selectionChanged=this.multiple||this._selected[0]!==row.value;if(this.multiple){const set=new Set(this._selected);set.has(row.value)?(set.delete(row.value),this._selectedRowCache.delete(row.value)):(set.add(row.value),synthetic||(this._selectedLabelCache.set(row.value,row.label),this._selectedRowCache.set(row.value,row))),this.assignValue([...set]),this.query="",this.explicitInputValue=!1}else synthetic||(this._selectedLabelCache.set(row.value,row.label),this._selectedRowCache.clear(),this._selectedRowCache.set(row.value,row)),this.setValue(row.value,!0,sourceOption),this.query="",this.explicitInputValue=!1,this.hide();this.source&&this.runSource(this.query),selectionChanged&&this.emitValueEvents(),this.emit("lr-activate",{value:row.value})}removeValueAt(index){if(this.liveDisabled||this.readonly||index<0||index>=this._selected.length)return;const next=this._selected.filter((_,i)=>i!==index);this.touched=!0,this.assignValue(next),this.emitValueEvents()}clear(){if(this.liveDisabled||this.readonly)return;const hadSelection=this._selected.length>0,queryChanged=this.query!=="";!hadSelection&&!queryChanged||(hadSelection&&(this.touched=!0,this.assignValue([])),this.query="",this.explicitInputValue=!1,this.source&&this.runSource(this.query),hadSelection&&(this.emitValueEvents(),this.emit("lr-clear")),queryChanged&&this.emit("lr-filter",{value:this.query}))}refresh(){if(this.source){if(!this.open){this.refreshQueued=!0;return}this.refreshQueued=!1,this.runSource(this.query,{immediate:!0})}}runSource(query2,options){const source=this.source;if(!source)return;if(!this.meetsMinimumQuery(query2)||!this.meetsMinimumQuery(this.query)){this.enforceMinimumQuery(!1);return}this.clearSourceTimer();const abort=this.sourceAbort;this.sourceAbort=void 0;const token=++this.sourceToken;if(abort?.abort(),token!==this.sourceToken||source!==this.source||!this.meetsMinimumQuery(this.query))return;const ownerWindow=this.ownerDocument.defaultView;if(!this.isConnected||!ownerWindow)return;const request={query:query2,token,owner:ownerWindow,source};if(options?.immediate){this.runSourceRequest(request);return}this.sourceDebounce.delayMs=this._sourceDelay,this.sourceDebounce.push(request)}runSourceRequest({query:query2,token,owner:ownerWindow,source}){if(token!==this.sourceToken||source!==this.source||!this.meetsMinimumQuery(query2)||!this.meetsMinimumQuery(this.query)||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow)return;const controller=new ownerWindow.AbortController;this.sourceAbort=controller,this.sourceLoading=!0,this.sourceFailed=!1,Promise.resolve().then(()=>{if(!(token!==this.sourceToken||source!==this.source||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow||!this.meetsMinimumQuery(query2)||!this.meetsMinimumQuery(this.query)))return source(query2,{signal:controller.signal,limit:MAX_SOURCE_ROWS})}).then(result=>{if(token!==this.sourceToken||source!==this.source||!this.meetsMinimumQuery(query2)||!this.meetsMinimumQuery(this.query)||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow)return;const normalized=normalizeSourceResult(result);this._sourceTotal=normalized.total,this._sourceTruncated=normalized.truncated,this.asyncRows=normalized.rows,this.sourceFailed=!1,this.sourceEverSettled=!0,this.normalizeActiveIndex(),this.applyPendingSelectedRows(!0);const selected=new Set(this._selected);for(const row of normalized.rows)selected.has(row.value)&&this._selectedRowCache.set(row.value,row)}).catch(err=>{token!==this.sourceToken||source!==this.source||!this.meetsMinimumQuery(query2)||!this.meetsMinimumQuery(this.query)||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow||typeof err=="object"&&err!==null&&"name"in err&&err.name==="AbortError"||(this.asyncRows=[],this._sourceTotal=0,this._sourceTruncated=!1,this.activeIndex=-1,this.sourceFailed=!0,this.sourceEverSettled=!0,this.sourceErrorAnnouncements.announceAssertive(this.localize("comboboxLoadError")),this.emit("lr-source-error",{error:err,query:query2}),console.warn("<lr-combobox> source() rejected:",err))}).finally(()=>{token===this.sourceToken&&(this.sourceLoading=!1)})}clearSourceTimer(){this.sourceDebounce.cancel()}renderRows(rows,activeId){const out=[];let currentGroup,currentGroupRows=[],groupIndex=0;const selectedSet=new Set(this.committed),flushGroup=()=>{if(currentGroupRows.length){if(currentGroup){const labelId=`${this.listId}-group-${groupIndex++}`;out.push(html`<div role="group" aria-labelledby=${labelId}>
|
|
2
2
|
<div id=${labelId} part="group-label" class="group-label">${currentGroup}</div>
|
|
3
3
|
${currentGroupRows}
|
|
4
4
|
</div>`)}else out.push(...currentGroupRows);currentGroupRows=[]}};return rows.forEach((o,i)=>{o.group!==currentGroup&&(flushGroup(),currentGroup=o.group);const id=`${this.listId}-opt-${i}`,selected=this.multiple||this.source?selectedSet.has(o.value):this.singleSelectedOption!==void 0&&this.sourceOptionsByRow.get(o)===this.singleSelectedOption;selected&&!this.multiple&&selectedSet.delete(o.value),currentGroupRows.push(html`<div
|
|
@@ -146,4 +146,4 @@ import{__decorate}from"tslib";import{capOptionRows}from"../../../internal/option
|
|
|
146
146
|
@lr-option-change=${this.onOptionChange}
|
|
147
147
|
hidden
|
|
148
148
|
></slot>
|
|
149
|
-
`}}__decorate([property()],LyraCombobox.prototype,"placeholder",void 0),__decorate([property()],LyraCombobox.prototype,"label",void 0),__decorate([property({attribute:"label-display",reflect:!0})],LyraCombobox.prototype,"labelDisplay",void 0),__decorate([property()],LyraCombobox.prototype,"hint",void 0),__decorate([property({attribute:"error-text"})],LyraCombobox.prototype,"errorText",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraCombobox.prototype,"open",null),__decorate([property({type:Boolean,attribute:"allow-create"})],LyraCombobox.prototype,"allowCreate",void 0),__decorate([property({type:Boolean,attribute:"allow-custom-value"})],LyraCombobox.prototype,"allowCustomValue",void 0),__decorate([property({type:Boolean,attribute:"with-unknown-option",reflect:!0})],LyraCombobox.prototype,"withUnknownOption",void 0),__decorate([property({attribute:!1})],LyraCombobox.prototype,"getUnknownLabel",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraCombobox.prototype,"loading",void 0),__decorate([property({converter:APPEARANCE,reflect:!0})],LyraCombobox.prototype,"appearance",null),__decorate([property({reflect:!0})],LyraCombobox.prototype,"placement",void 0),__decorate([property({reflect:!0})],LyraCombobox.prototype,"sync",void 0),__decorate([property({attribute:"positioning-strategy",reflect:!0,converter:POSITIONING_STRATEGY})],LyraCombobox.prototype,"positioningStrategy",null),__decorate([property({type:Boolean,attribute:"top-layer",reflect:!0})],LyraCombobox.prototype,"topLayer",void 0),__decorate([property({reflect:!0})],LyraCombobox.prototype,"size",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraCombobox.prototype,"pill",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraCombobox.prototype,"clearable",void 0),__decorate([property({type:Boolean,attribute:"with-clear"})],LyraCombobox.prototype,"withClear",void 0),__decorate([property({type:Boolean,attribute:"with-label"})],LyraCombobox.prototype,"withLabel",void 0),__decorate([property({type:Boolean,attribute:"with-hint"})],LyraCombobox.prototype,"withHint",void 0),__decorate([property({attribute:!1})],LyraCombobox.prototype,"getTag",void 0),__decorate([property({attribute:!1})],LyraCombobox.prototype,"validators",void 0),__decorate([property()],LyraCombobox.prototype,"autocomplete",void 0),__decorate([property({attribute:"inputmode"})],LyraCombobox.prototype,"inputMode",void 0),__decorate([property({attribute:"enterkeyhint"})],LyraCombobox.prototype,"enterKeyHint",void 0),__decorate([property({converter:comboboxSpellcheckConverter,useDefault:!0})],LyraCombobox.prototype,"spellcheck",void 0),__decorate([property()],LyraCombobox.prototype,"autocapitalize",void 0),__decorate([property({attribute:"empty-text"})],LyraCombobox.prototype,"emptyText",void 0),__decorate([property({attribute:"loading-text"})],LyraCombobox.prototype,"loadingText",void 0),__decorate([property({attribute:"overflow-text"})],LyraCombobox.prototype,"overflowText",void 0),__decorate([property({attribute:!1})],LyraCombobox.prototype,"filter",void 0),__decorate([property({attribute:!1})],LyraCombobox.prototype,"source",void 0),__decorate([property({converter:autocorrectConverter})],LyraCombobox.prototype,"autocorrect",null),__decorate([state()],LyraCombobox.prototype,"query",
|
|
149
|
+
`}}__decorate([property()],LyraCombobox.prototype,"placeholder",void 0),__decorate([property()],LyraCombobox.prototype,"label",void 0),__decorate([property({attribute:"label-display",reflect:!0})],LyraCombobox.prototype,"labelDisplay",void 0),__decorate([property()],LyraCombobox.prototype,"hint",void 0),__decorate([property({attribute:"error-text"})],LyraCombobox.prototype,"errorText",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraCombobox.prototype,"open",null),__decorate([property({type:Boolean,attribute:"allow-create"})],LyraCombobox.prototype,"allowCreate",void 0),__decorate([property({type:Boolean,attribute:"allow-custom-value"})],LyraCombobox.prototype,"allowCustomValue",void 0),__decorate([property({type:Boolean,attribute:"with-unknown-option",reflect:!0})],LyraCombobox.prototype,"withUnknownOption",void 0),__decorate([property({attribute:!1})],LyraCombobox.prototype,"getUnknownLabel",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraCombobox.prototype,"loading",void 0),__decorate([property({converter:APPEARANCE,reflect:!0})],LyraCombobox.prototype,"appearance",null),__decorate([property({reflect:!0})],LyraCombobox.prototype,"placement",void 0),__decorate([property({reflect:!0})],LyraCombobox.prototype,"sync",void 0),__decorate([property({attribute:"positioning-strategy",reflect:!0,converter:POSITIONING_STRATEGY})],LyraCombobox.prototype,"positioningStrategy",null),__decorate([property({type:Boolean,attribute:"top-layer",reflect:!0})],LyraCombobox.prototype,"topLayer",void 0),__decorate([property({reflect:!0})],LyraCombobox.prototype,"size",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraCombobox.prototype,"pill",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraCombobox.prototype,"clearable",void 0),__decorate([property({type:Boolean,attribute:"with-clear"})],LyraCombobox.prototype,"withClear",void 0),__decorate([property({type:Boolean,attribute:"with-label"})],LyraCombobox.prototype,"withLabel",void 0),__decorate([property({type:Boolean,attribute:"with-hint"})],LyraCombobox.prototype,"withHint",void 0),__decorate([property({attribute:!1})],LyraCombobox.prototype,"getTag",void 0),__decorate([property({attribute:!1})],LyraCombobox.prototype,"validators",void 0),__decorate([property()],LyraCombobox.prototype,"autocomplete",void 0),__decorate([property({attribute:"inputmode"})],LyraCombobox.prototype,"inputMode",void 0),__decorate([property({attribute:"enterkeyhint"})],LyraCombobox.prototype,"enterKeyHint",void 0),__decorate([property({converter:comboboxSpellcheckConverter,useDefault:!0})],LyraCombobox.prototype,"spellcheck",void 0),__decorate([property()],LyraCombobox.prototype,"autocapitalize",void 0),__decorate([property({attribute:"empty-text"})],LyraCombobox.prototype,"emptyText",void 0),__decorate([property({attribute:"loading-text"})],LyraCombobox.prototype,"loadingText",void 0),__decorate([property({attribute:"overflow-text"})],LyraCombobox.prototype,"overflowText",void 0),__decorate([property({attribute:!1})],LyraCombobox.prototype,"filter",void 0),__decorate([property({attribute:!1})],LyraCombobox.prototype,"source",void 0),__decorate([property({converter:autocorrectConverter})],LyraCombobox.prototype,"autocorrect",null),__decorate([state()],LyraCombobox.prototype,"query",null),__decorate([state()],LyraCombobox.prototype,"activeIndex",void 0),__decorate([state()],LyraCombobox.prototype,"options",void 0),__decorate([state()],LyraCombobox.prototype,"optionsObserved",void 0),__decorate([state()],LyraCombobox.prototype,"touched",void 0),__decorate([state()],LyraCombobox.prototype,"validityRevision",void 0),__decorate([state()],LyraCombobox.prototype,"sourceLoading",void 0),__decorate([state()],LyraCombobox.prototype,"sourceFailed",void 0),__decorate([state()],LyraCombobox.prototype,"sourceEverSettled",void 0),__decorate([state()],LyraCombobox.prototype,"asyncRows",void 0),__decorate([query('[part="combobox-input"]')],LyraCombobox.prototype,"inputEl",void 0),__decorate([query("slot:not([name])")],LyraCombobox.prototype,"optionsSlot",void 0),__decorate([state()],LyraCombobox.prototype,"listboxPositioned",void 0),__decorate([state()],LyraCombobox.prototype,"listboxHidden",void 0),__decorate([state()],LyraCombobox.prototype,"listboxRendered",void 0),__decorate([property({type:Number,attribute:"visible-options"})],LyraCombobox.prototype,"visibleOptions",void 0);export{LyraCombobox};
|
|
@@ -274,7 +274,7 @@ resetValidity():void;private setTypedBadInput;private parseStrictISO;private nor
|
|
|
274
274
|
/** Open the calendar popover, unless the cancelable `lr-show` request is vetoed.*/
|
|
275
275
|
show():Promise<void>;
|
|
276
276
|
/** Close the calendar popover, unless the cancelable `lr-hide` request is vetoed.*/
|
|
277
|
-
hide(restoreFocus?:boolean):Promise<void>;private forceClose;private onDocPointer;private reconnectOpenPopup;private settleTransition;connectedCallback():void;private daySlotNames;private observeDaySlots;private onClearClick;
|
|
277
|
+
hide(restoreFocus?:boolean):Promise<void>;private forceClose;private onDocPointer;private reconnectOpenPopup;private watchPopupPlacement;private settleTransition;connectedCallback():void;private daySlotNames;private observeDaySlots;private onClearClick;
|
|
278
278
|
/** Clear the value (`input`, `change`, `lr-clear`); inert while blank, disabled or readonly.*/
|
|
279
279
|
clear():void;private syncInteractionListeners;private syncValidatorAttributeObserver;private disconnectValidatorAttributeObserver;private syncCustomStates;disconnectedCallback():void;adoptedCallback():void;private syncExternalDescription;protected updated(changed:PropertyValues):void;private commitTypedValue;private applyTypedText;private onInputChange;private commitInputChange;private onInput;private numericDate;private parseOneDate;private parseSingleText;private localizedRangeSeparator;private parseRangeText;private onInputKey;private onInputBlur;private onInputFocus;
|
|
280
280
|
/** Activate the internal date text input unless the form control is effectively disabled.*/
|