@aceshooting/lyra-ui 14.3.2 → 15.0.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 +116 -0
- package/custom-elements.json +1 -1
- package/design-tokens.json +1 -1
- package/dist/cli/migration-contract.json +1 -1
- package/dist/components/agent-tools/activity-feed/activity-feed.class.d.ts +4 -0
- package/dist/components/agent-tools/activity-feed/activity-feed.class.js +3 -3
- package/dist/components/agent-tools/approval-queue/approval-queue.class.js +3 -2
- package/dist/components/agent-tools/artifact-panel/artifact-panel.styles.js +1 -1
- package/dist/components/agent-tools/commit-card/commit-card.styles.js +1 -1
- package/dist/components/agent-tools/compare-panel/compare-panel.styles.js +1 -1
- package/dist/components/agent-tools/confirm-bar/confirm-bar.class.js +8 -3
- package/dist/components/agent-tools/eval-dataset/eval-dataset.class.d.ts +3 -1
- package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +10 -1
- package/dist/components/agent-tools/eval-dataset/eval-dataset.styles.js +1 -1
- package/dist/components/agent-tools/span-waterfall/span-waterfall.class.js +1 -1
- package/dist/components/agent-tools/subagent-panel/subagent-panel.class.d.ts +19 -1
- package/dist/components/agent-tools/subagent-panel/subagent-panel.class.js +4 -4
- package/dist/components/agent-tools/subagent-panel/subagent-panel.styles.js +1 -1
- package/dist/components/agent-tools/task-list/task-list.class.d.ts +5 -0
- package/dist/components/agent-tools/task-list/task-list.class.js +3 -3
- package/dist/components/agent-tools/terminal/terminal.class.d.ts +1 -1
- package/dist/components/agent-tools/terminal/terminal.styles.js +1 -1
- package/dist/components/agent-tools/test-results/test-results.class.js +1 -1
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.d.ts +10 -7
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +15 -14
- package/dist/components/agent-tools/tool-param-form/tool-param-form.d.ts +1 -1
- package/dist/components/agent-tools/tool-param-form/tool-param-form.js +1 -1
- package/dist/components/agent-tools/tool-param-form/tool-param-form.styles.js +1 -1
- package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.class.d.ts +5 -2
- package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.class.js +1 -1
- package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.class.d.ts +3 -1
- package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.class.js +9 -1
- package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.styles.js +1 -1
- package/dist/components/charts/chart/box-plot.class.d.ts +64 -4
- package/dist/components/charts/chart/box-plot.class.js +5 -5
- package/dist/components/charts/chart/chart-colors.d.ts +10 -0
- package/dist/components/charts/chart/chart-colors.js +1 -1
- package/dist/components/charts/chart/chart.class.d.ts +35 -10
- package/dist/components/charts/chart/chart.class.js +4 -4
- package/dist/components/charts/chart/lite-chart.class.d.ts +10 -2
- package/dist/components/charts/chart/lite-chart.styles.js +1 -1
- package/dist/components/conversation/markdown/markdown.class.d.ts +9 -1
- package/dist/components/conversation/markdown/markdown.class.js +1 -1
- package/dist/components/conversation/message-parts/message-parts.class.d.ts +18 -1
- package/dist/components/conversation/message-parts/message-parts.class.js +4 -4
- package/dist/components/conversation/model-select/model-select.class.d.ts +6 -2
- package/dist/components/conversation/model-select/model-select.class.js +3 -3
- package/dist/components/conversation/prompt-input/prompt-input.styles.js +1 -1
- package/dist/components/conversation/selection-toolbar/selection-toolbar.class.d.ts +5 -1
- package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
- package/dist/components/data/calendar/calendar.class.js +2 -2
- package/dist/components/data/context-meter/context-meter.styles.js +1 -1
- package/dist/components/data/data-grid/data-grid-types.d.ts +8 -2
- package/dist/components/data/data-grid/data-grid.class.d.ts +16 -3
- package/dist/components/data/data-grid/data-grid.class.js +3 -2
- package/dist/components/data/env-list/env-list.styles.js +1 -1
- package/dist/components/data/flow-canvas/flow-canvas.class.d.ts +22 -2
- package/dist/components/data/flow-canvas/flow-canvas.class.js +1 -1
- package/dist/components/data/flow-minimap/flow-minimap.class.d.ts +12 -4
- package/dist/components/data/flow-minimap/flow-minimap.class.js +2 -2
- package/dist/components/data/flow-minimap/flow-minimap.styles.js +1 -1
- package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +5 -1
- package/dist/components/data/graph-query-builder/graph-query-builder.class.js +1 -1
- package/dist/components/data/heatmap/heatmap.class.d.ts +12 -1
- package/dist/components/data/heatmap/heatmap.class.js +3 -3
- package/dist/components/data/heatmap/heatmap.styles.js +1 -1
- package/dist/components/forms/button/button.styles.js +1 -1
- package/dist/components/forms/code-editor/code-editor.class.js +1 -1
- package/dist/components/forms/combobox/combobox.class.js +1 -1
- package/dist/components/forms/combobox/combobox.styles.js +1 -1
- package/dist/components/forms/date-picker/date-input.class.js +1 -1
- package/dist/components/forms/date-picker/date-picker.class.d.ts +12 -1
- package/dist/components/forms/date-picker/date-picker.class.js +1 -1
- package/dist/components/forms/icon-button/icon-button.class.d.ts +27 -5
- package/dist/components/forms/icon-button/icon-button.class.js +7 -3
- package/dist/components/forms/input/input.styles.js +1 -1
- package/dist/components/forms/input/time-input.class.d.ts +13 -2
- package/dist/components/forms/input/time-input.class.js +1 -1
- package/dist/components/forms/otp-input/otp-input.class.d.ts +8 -1
- package/dist/components/forms/otp-input/otp-input.class.js +1 -1
- package/dist/components/forms/rubric-form/rubric-form.class.d.ts +1 -1
- package/dist/components/forms/rubric-form/rubric-form.class.js +1 -1
- package/dist/components/forms/select/select.class.d.ts +1 -1
- package/dist/components/forms/select/select.class.js +1 -1
- package/dist/components/forms/slider/slider.class.d.ts +4 -1
- package/dist/components/forms/slider/slider.class.js +1 -1
- package/dist/components/forms/textarea/textarea.class.d.ts +9 -4
- package/dist/components/forms/textarea/textarea.class.js +1 -1
- package/dist/components/forms/time-range/time-range.class.js +1 -1
- package/dist/components/layout/app-rail/app-rail.class.d.ts +7 -2
- package/dist/components/layout/app-rail/app-rail.class.js +1 -1
- package/dist/components/layout/card/card.class.js +2 -2
- package/dist/components/layout/card/card.styles.js +1 -1
- package/dist/components/layout/control-group/control-group.class.js +1 -1
- package/dist/components/layout/dashboard-grid/dashboard-grid.styles.js +1 -1
- package/dist/components/layout/details/details.styles.js +1 -1
- package/dist/components/layout/filter-bar/filter-bar.class.d.ts +13 -3
- package/dist/components/layout/filter-bar/filter-bar.class.js +1 -1
- package/dist/components/layout/menu/dropdown-item.class.d.ts +2 -0
- package/dist/components/layout/menu/menu-item.class.d.ts +28 -1
- package/dist/components/layout/menu/menu-item.class.js +45 -35
- package/dist/components/layout/menu/menu-item.styles.js +1 -1
- package/dist/components/layout/menu/menu.class.js +1 -1
- package/dist/components/layout/multi-split/multi-split.class.d.ts +12 -2
- package/dist/components/layout/multi-split/multi-split.class.js +1 -1
- package/dist/components/layout/page/page.class.js +2 -1
- package/dist/components/layout/page/page.styles.js +1 -1
- package/dist/components/layout/responsive-panel/responsive-panel.class.d.ts +6 -4
- package/dist/components/layout/responsive-panel/responsive-panel.class.js +2 -2
- package/dist/components/layout/responsive-panel/responsive-panel.styles.js +1 -1
- package/dist/components/layout/stepper/stepper.class.js +2 -2
- package/dist/components/layout/virtual-list/virtual-list.class.js +2 -2
- package/dist/components/layout/widget/widget.class.d.ts +12 -2
- package/dist/components/layout/widget/widget.class.js +2 -2
- package/dist/components/media/attachment-trigger/attachment-trigger.class.d.ts +1 -1
- package/dist/components/media/attachment-trigger/attachment-trigger.class.js +3 -3
- package/dist/components/media/file-icon/file-icon.class.d.ts +3 -1
- package/dist/components/media/file-icon/file-icon.class.js +1 -1
- package/dist/components/media/file-input/file-input.class.d.ts +1 -1
- package/dist/components/media/file-input/file-input.class.js +1 -1
- package/dist/components/media/flag/flag.styles.js +1 -1
- package/dist/components/media/image-comparer/image-comparer.class.d.ts +5 -5
- package/dist/components/media/image-comparer/image-comparer.class.js +1 -1
- package/dist/components/media/image-comparer/image-comparer.styles.js +1 -1
- package/dist/components/media/lightbox/lightbox.styles.js +1 -1
- package/dist/components/media/map/map.styles.js +1 -1
- package/dist/components/media/sequence-playback/sequence-playback.class.js +1 -1
- package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
- package/dist/components/media/video-playlist/video-playlist.styles.js +1 -1
- package/dist/components/overlays/alert/alert.class.d.ts +6 -0
- package/dist/components/overlays/alert/alert.styles.js +1 -1
- package/dist/components/overlays/empty/empty.class.js +2 -2
- package/dist/components/overlays/kbd/kbd.styles.js +1 -1
- package/dist/components/overlays/progress/progress-ring.class.d.ts +4 -1
- package/dist/components/overlays/progress/progress.styles.js +1 -1
- package/dist/components/overlays/toast/toast.styles.js +1 -1
- package/dist/components/retrieval/graph/graph-canvas.js +1 -1
- package/dist/components/retrieval/graph/graph.class.d.ts +10 -3
- package/dist/components/retrieval/graph/graph.class.js +1 -1
- package/dist/components/retrieval/graph/graph.styles.js +1 -1
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.d.ts +1 -1
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.js +6 -6
- package/dist/components/retrieval/knowledge-base-admin/knowledge-base-admin.class.js +2 -2
- package/dist/components/retrieval/mind-map/mind-map.styles.js +1 -1
- package/dist/components/retrieval/neighbor-list/neighbor-list.class.d.ts +3 -3
- package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +3 -3
- package/dist/components/retrieval/node-palette/node-palette.class.d.ts +7 -1
- package/dist/components/retrieval/node-palette/node-palette.class.js +23 -13
- package/dist/components/retrieval/node-palette/node-palette.styles.js +1 -1
- package/dist/components/retrieval/rag-eval-dashboard/rag-eval-dashboard.class.d.ts +4 -1
- package/dist/components/retrieval/rag-eval-dashboard/rag-eval-dashboard.class.js +1 -1
- package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +1 -1
- package/dist/components/retrieval/retrieval-search/retrieval-search.class.js +4 -3
- package/dist/components/retrieval/retrieval-trace/retrieval-trace.class.js +1 -1
- package/dist/components/retrieval/source-list/source-list.class.d.ts +7 -1
- package/dist/components/retrieval/source-list/source-list.class.js +1 -1
- package/dist/components/utility/export-button/export-button.class.d.ts +14 -2
- package/dist/components/utility/export-button/export-button.class.js +3 -3
- package/dist/components/utility/export-button/export-button.styles.js +1 -1
- 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.d.ts +4 -2
- package/dist/components/utility/mention-popover/mention-popover.class.js +1 -1
- package/dist/components/viewers/csv-viewer/csv-viewer.class.d.ts +9 -1
- package/dist/components/viewers/csv-viewer/csv-viewer.class.js +4 -4
- package/dist/components/viewers/dataset-viewer/dataset-viewer.class.d.ts +1 -1
- package/dist/components/viewers/dataset-viewer/dataset-viewer.class.js +4 -4
- package/dist/components/viewers/document-compare/document-compare.class.d.ts +5 -0
- package/dist/components/viewers/document-compare/document-compare.class.js +9 -4
- package/dist/components/viewers/document-compare/document-compare.styles.js +1 -1
- package/dist/components/viewers/document-preview/document-preview.class.d.ts +9 -1
- package/dist/components/viewers/document-preview/document-preview.class.js +2 -1
- package/dist/components/viewers/notebook-viewer/notebook-viewer.class.d.ts +5 -0
- package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +1 -1
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.d.ts +5 -0
- package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.d.ts +1 -1
- package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.js +3 -3
- package/dist/components/viewers/xml-viewer/xml-viewer.styles.js +1 -1
- package/dist/custom-elements-jsx.d.ts +1 -1
- package/dist/events.d.ts +5 -4
- package/dist/internal/package-metadata.d.ts +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/lyra.d.ts +1 -1
- package/dist/svelte.d.ts +1 -1
- package/dist/vue.d.ts +1 -1
- package/llms/components/lr-alert.md +11 -3
- package/llms/components/lr-box-plot.md +21 -4
- package/llms/components/lr-chart.md +13 -4
- package/llms/components/lr-code-block.md +5 -4
- package/llms/components/lr-data-grid.md +24 -10
- package/llms/components/lr-document-compare.md +5 -0
- package/llms/components/lr-dropdown-item.md +24 -0
- package/llms/components/lr-eval-dataset.md +5 -4
- package/llms/components/lr-export-button.md +10 -5
- package/llms/components/lr-filter-bar.md +4 -1
- package/llms/components/lr-flow-minimap.md +7 -1
- package/llms/components/lr-icon-button.md +6 -1
- package/llms/components/lr-lite-chart.md +2 -1
- package/llms/components/lr-markdown.md +2 -2
- package/llms/components/lr-menu-item.md +24 -0
- package/llms/components/lr-menu.md +24 -0
- package/llms/components/lr-message-parts.md +7 -0
- package/llms/components/lr-model-settings-panel.md +4 -1
- package/llms/components/lr-node-palette.md +5 -4
- package/llms/components/lr-pdf-viewer.md +7 -0
- package/llms/components/lr-responsive-panel.md +2 -2
- package/llms/components/lr-subagent-panel.md +17 -2
- package/llms/components/lr-thinking-panel.md +4 -0
- package/llms/components/lr-timeline-item.md +1 -1
- package/llms/components/lr-timeline.md +1 -1
- package/llms/components/lr-tool-select-dialog.md +4 -3
- package/llms/components/lr-virtual-list.md +11 -11
- package/llms/peers.md +1 -1
- package/llms-full.txt +205 -59
- package/package.json +7 -7
- package/vscode-css-data.json +1 -1
- package/vscode-html-data.json +1 -1
- package/web-types.json +1 -1
|
@@ -123,7 +123,7 @@ withLabel:boolean;
|
|
|
123
123
|
/** SSR hint-presence hint; hydrated instances also discover populated hint/help-text slots. */
|
|
124
124
|
withHint:boolean;private _errors;private touchedFields;private hasLabelSlot;private hasHintSlot;private hasErrorSlot;private internals;private validityController;
|
|
125
125
|
/** Consumer-supplied validation message reflected through `custom-error`. */
|
|
126
|
-
customError:string|null;private baseId;private aggregateLabelId;private aggregateHintId;private aggregateErrorId;private _fieldsetDisabled;private _name;private _keys;private _value;private _defaultValue;private _valueDirty;private _itemId;private _hasNext;private _skippable;private _disabled;private lastValidityKey;private pendingFocusFirst;constructor();
|
|
126
|
+
customError:string|null;private baseId;private aggregateLabelId;private aggregateHintId;private aggregateErrorId;private _fieldsetDisabled;private _name;private _keys;private _value;private _defaultValue;private _rawValue;private _rawDefaultValue;private _valueDirty;private _itemId;private _hasNext;private _skippable;private _disabled;private lastValidityKey;private pendingFocusFirst;constructor();
|
|
127
127
|
/** `attachInternals()` throws in any environment without a real `ElementInternals`
|
|
128
128
|
* implementation (e.g. a downstream consumer's happy-dom test suite) -- merely constructing
|
|
129
129
|
* (or importing) this component must not hard-crash there. Falls back to an inert stand-in:
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{live}from"lit/directives/live.js";import{LyraElement}from"../../../internal/lyra-element.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";installFormControlLabelSupport();import{nextId}from"../../../internal/a11y.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{styles}from"./rubric-form.styles.js";import"../../layout/segmented/segmented.class.js";import"../slider/slider.class.js";import"../select/select.class.js";import"../combobox/option.class.js";import"../checkbox/checkbox.class.js";import"../checkbox-group/checkbox-group.class.js";import"../textarea/textarea.class.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_noData,LYRA_DEFAULT_rubricSkip,LYRA_DEFAULT_rubricSubmit,LYRA_DEFAULT_rubricSubmitAndNext,LYRA_DEFAULT_unsupportedFieldType}from"../../../internal/default-strings.generated.js";const EMPTY_KEYS=[],EMPTY_VALUE={},MAX_RUBRIC_COLLECTION_ENTRIES=1e4;function cloneRubricValue(value){return Object.freeze(Object.fromEntries(Object.entries(value).map(([key,entry])=>[key,Array.isArray(entry)?Object.freeze([...entry]):entry])))}function projectRubricStringArray(value){try{if(!Array.isArray(value))return;const length=getOwnDataDescriptor(value,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return;const values=[];for(let index=0;index<Math.min(length.value,MAX_RUBRIC_COLLECTION_ENTRIES);index+=1){const entry=getOwnDataDescriptor(value,String(index));entry===MISSING_OWN_DATA_DESCRIPTOR||entry===UNSAFE_OWN_DATA_DESCRIPTOR||typeof entry.value=="string"&&values.push(entry.value)}return Object.freeze(values)}catch{return}}function projectRubricOptions(value){try{if(!Array.isArray(value))return Object.freeze([]);const length=getOwnDataDescriptor(value,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return Object.freeze([]);const options=[];for(let index=0;index<Math.min(length.value,MAX_RUBRIC_COLLECTION_ENTRIES);index+=1){const candidate=getOwnDataDescriptor(value,String(index));if(candidate===MISSING_OWN_DATA_DESCRIPTOR||candidate===UNSAFE_OWN_DATA_DESCRIPTOR||candidate.value===null||typeof candidate.value!="object"||Array.isArray(candidate.value))continue;const optionValue=getOwnDataDescriptor(candidate.value,"value"),label=getOwnDataDescriptor(candidate.value,"label"),description=getOwnDataDescriptor(candidate.value,"description");if(optionValue===MISSING_OWN_DATA_DESCRIPTOR||optionValue===UNSAFE_OWN_DATA_DESCRIPTOR||typeof optionValue.value!="string")continue;const labelValue=label===MISSING_OWN_DATA_DESCRIPTOR||label===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:typeof label.value=="string"?label.value:void 0,descriptionValue=description===MISSING_OWN_DATA_DESCRIPTOR||description===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:typeof description.value=="string"?description.value:void 0;options.push(Object.freeze({value:optionValue.value,...labelValue===void 0?{}:{label:labelValue},...descriptionValue===void 0?{}:{description:descriptionValue}}))}return Object.freeze(options)}catch{return Object.freeze([])}}function projectRubricKey(candidate){try{if(candidate===null||typeof candidate!="object"||Array.isArray(candidate))return;const key=getOwnDataDescriptor(candidate,"key"),type=getOwnDataDescriptor(candidate,"type"),label=getOwnDataDescriptor(candidate,"label"),description=getOwnDataDescriptor(candidate,"description"),required=getOwnDataDescriptor(candidate,"required");if(key===MISSING_OWN_DATA_DESCRIPTOR||key===UNSAFE_OWN_DATA_DESCRIPTOR||type===UNSAFE_OWN_DATA_DESCRIPTOR||label===UNSAFE_OWN_DATA_DESCRIPTOR||description===UNSAFE_OWN_DATA_DESCRIPTOR||required===UNSAFE_OWN_DATA_DESCRIPTOR||typeof key.value!="string"||key.value.trim().length===0)return;const typeValue=type===MISSING_OWN_DATA_DESCRIPTOR?"":type.value;if(typeof typeValue!="string")return;const labelValue=label===MISSING_OWN_DATA_DESCRIPTOR?void 0:label.value,descriptionValue=description===MISSING_OWN_DATA_DESCRIPTOR?void 0:description.value,requiredValue=required===MISSING_OWN_DATA_DESCRIPTOR?void 0:required.value,common={key:key.value,...typeof labelValue=="string"?{label:labelValue}:{},...typeof descriptionValue=="string"?{description:descriptionValue}:{},...typeof requiredValue=="boolean"?{required:requiredValue}:{}};if(typeValue==="score"){const min=getOwnDataDescriptor(candidate,"min"),max=getOwnDataDescriptor(candidate,"max"),step=getOwnDataDescriptor(candidate,"step");return min===UNSAFE_OWN_DATA_DESCRIPTOR||max===UNSAFE_OWN_DATA_DESCRIPTOR||step===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:Object.freeze({...common,type:"score",...min!==MISSING_OWN_DATA_DESCRIPTOR&&typeof min.value=="number"?{min:min.value}:{},...max!==MISSING_OWN_DATA_DESCRIPTOR&&typeof max.value=="number"?{max:max.value}:{},...step!==MISSING_OWN_DATA_DESCRIPTOR&&typeof step.value=="number"?{step:step.value}:{}})}if(typeValue==="category"){const options=getOwnDataDescriptor(candidate,"options"),multiple=getOwnDataDescriptor(candidate,"multiple");return options===UNSAFE_OWN_DATA_DESCRIPTOR||multiple===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:Object.freeze({...common,type:"category",options:options===MISSING_OWN_DATA_DESCRIPTOR?Object.freeze([]):projectRubricOptions(options.value),...multiple!==MISSING_OWN_DATA_DESCRIPTOR&&typeof multiple.value=="boolean"?{multiple:multiple.value}:{}})}if(typeValue==="comment"){const placeholder=getOwnDataDescriptor(candidate,"placeholder");return placeholder===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:Object.freeze({...common,type:"comment",...placeholder!==MISSING_OWN_DATA_DESCRIPTOR&&typeof placeholder.value=="string"?{placeholder:placeholder.value}:{}})}return Object.freeze({...common,type:typeValue})}catch{return}}function normalizeRubricKeys(next){try{if(!Array.isArray(next))return EMPTY_KEYS;const length=getOwnDataDescriptor(next,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return EMPTY_KEYS;const seen=new Set,normalized=[];for(let index=0;index<Math.min(length.value,MAX_RUBRIC_COLLECTION_ENTRIES);index+=1){const candidate=getOwnDataDescriptor(next,String(index));if(candidate===MISSING_OWN_DATA_DESCRIPTOR||candidate===UNSAFE_OWN_DATA_DESCRIPTOR)continue;const key=projectRubricKey(candidate.value);!key||seen.has(key.key)||(seen.add(key.key),normalized.push(key))}return Object.freeze(normalized)}catch{return EMPTY_KEYS}}function scoreDomain(key){const min=Number.isFinite(key.min)?key.min:0,rawMax=Number.isFinite(key.max)?key.max:5,max=Math.max(min,rawMax),step=Number.isFinite(key.step)&&key.step>0?key.step:1;return{min,max,step}}function isSegmentedScoreKey(key){if(key.step!==void 0&&(!Number.isFinite(key.step)||key.step<=0)||Number.isFinite(key.min)&&Number.isFinite(key.max)&&key.max<key.min)return!1;const{min,max,step}=scoreDomain(key);if(!Number.isInteger(min)||!Number.isInteger(max)||!Number.isInteger(step))return!1;const count=(max-min)/step;return Number.isInteger(count)&&count>=0&&count<=10}function canonicalScore(value,key){if(typeof value!="number"||!Number.isFinite(value))return;const{min,max,step}=scoreDomain(key),clamped=Math.min(max,Math.max(min,value)),snapped=Math.min(max,Math.max(min,min+Math.round((clamped-min)/step)*step));return Number(snapped.toPrecision(15))}function normalizeRubricValue(value,keys){const source=value!==null&&typeof value=="object"&&!Array.isArray(value)?value:EMPTY_VALUE,normalized={};for(const key of keys){const descriptor=getOwnDataDescriptor(source,key.key);if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)continue;const hasEntry=descriptor!==MISSING_OWN_DATA_DESCRIPTOR,entry=descriptor===MISSING_OWN_DATA_DESCRIPTOR?void 0:descriptor.value;if(key.type==="score"){const{min,max}=scoreDomain(key),score=canonicalScore(hasEntry?entry:isSegmentedScoreKey(key)?void 0:min+(max-min)/2,key);score!==void 0&&(normalized[key.key]=score)}else if(key.type==="category"){if(!hasEntry)continue;const allowed=(key.options??[]).map(option=>option.value);if(key.multiple){const entries=projectRubricStringArray(entry);if(!entries)continue;const remaining=new Map;for(const option of allowed)remaining.set(option,(remaining.get(option)??0)+1);const selected=[];for(const candidate of entries){const count=remaining.get(candidate)??0;count<=0||(selected.push(candidate),remaining.set(candidate,count-1))}normalized[key.key]=selected}else typeof entry=="string"&&entry!==""&&allowed.includes(entry)&&(normalized[key.key]=entry)}else key.type==="comment"&&hasEntry&&typeof entry=="string"&&(normalized[key.key]=entry)}return normalized}class LyraRubricForm extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,noData:LYRA_DEFAULT_noData,rubricSkip:LYRA_DEFAULT_rubricSkip,rubricSubmit:LYRA_DEFAULT_rubricSubmit,rubricSubmitAndNext:LYRA_DEFAULT_rubricSubmitAndNext,unsupportedFieldType:LYRA_DEFAULT_unsupportedFieldType}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},keys:{attribute:!1,noAccessor:!0},value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:!1,noAccessor:!0},itemId:{attribute:"item-id",reflect:!0,noAccessor:!0},hasNext:{type:Boolean,attribute:"has-next",noAccessor:!0},skippable:{type:Boolean,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0}}}constructor(){super(),this.label="",this.hint="",this.errorText="",this.withLabel=!1,this.withHint=!1,this._errors={},this.touchedFields=new Set,this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.baseId=nextId("rubric-form"),this.aggregateLabelId=`${this.baseId}-label`,this.aggregateHintId=`${this.baseId}-hint`,this.aggregateErrorId=`${this.baseId}-error`,this._fieldsetDisabled=!1,this._name="",this._keys=EMPTY_KEYS,this._value=EMPTY_VALUE,this._defaultValue=EMPTY_VALUE,this._valueDirty=!1,this._itemId="",this._hasNext=!1,this._skippable=!1,this._disabled=!1,this.pendingFocusFirst=!1,this.onFormKeyDown=e=>{e.key==="Enter"&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),this.submit())},this.stopChildEvent=event=>{event.stopPropagation()},this.onAggregateSlotChange=event=>{const slot=event.target,populated=slot.assignedNodes({flatten:!0}).some(node=>node.nodeType===Node.ELEMENT_NODE||!!node.textContent?.trim());slot.name==="label"?this.hasLabelSlot=populated:slot.name==="hint"?this.hasHintSlot=populated:slot.name==="error"&&(this.hasErrorSlot=populated)},this.internals=this.safeAttachInternals(),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.addEventListener("keydown",this.onFormKeyDown),this.syncFormState()}safeAttachInternals(){if(typeof globalThis.ElementInternals>"u")return this.inertInternals();try{return this.attachInternals()}catch{return this.inertInternals()}}inertInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:!1,setFormValue:()=>{},setValidity:()=>{},checkValidity:()=>!0,reportValidity:()=>!0,states:new Set}}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}get keys(){return this._keys}set keys(next){const old=this._keys;this._keys=normalizeRubricKeys(next??EMPTY_KEYS);const oldDefault=this._defaultValue,oldValue=this._value;this._defaultValue=normalizeRubricValue(this._defaultValue,this._keys),this._value=this._valueDirty?normalizeRubricValue(this._value,this._keys):cloneRubricValue(this._defaultValue),this.syncFormState(),this.requestUpdate("keys",old),this.requestUpdate("defaultValue",oldDefault),this.requestUpdate("value",oldValue)}get value(){return cloneRubricValue(this._value)}set value(next){this.setLiveValue(next,!0)}get defaultValue(){return cloneRubricValue(this._defaultValue)}set defaultValue(next){const old=this._defaultValue;this._defaultValue=normalizeRubricValue(next??EMPTY_VALUE,this._keys),this._valueDirty||this.setLiveValue(this._defaultValue,!1),this.requestUpdate("defaultValue",old)}setLiveValue(next,dirty){const old=this._value;this._value=normalizeRubricValue(next??EMPTY_VALUE,this._keys),this._valueDirty=dirty,this.syncFormState(),this.requestUpdate("value",old)}get itemId(){return this._itemId}set itemId(next){const old=this._itemId;this._itemId=next??"",old!==this._itemId&&(this.touchedFields=new Set,this.syncCustomStates(),this.hasUpdated&&(this.pendingFocusFirst=!0)),this._itemId?this.setAttribute("item-id",this._itemId):this.removeAttribute("item-id"),this.requestUpdate("itemId",old)}get hasNext(){return this._hasNext}set hasNext(next){const old=this._hasNext;this._hasNext=!!next,this.toggleAttribute("has-next",this._hasNext),this.requestUpdate("hasNext",old)}get skippable(){return this._skippable}set skippable(next){const old=this._skippable;this._skippable=!!next,this.requestUpdate("skippable",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this.validityController&&this.syncFormState(),this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get errors(){return this.publicValidityErrors()}publicValidityErrors(){const errors={...this._errors};return this.willValidate&&this.validityController.customValidityMessage&&(errors.base=this.validationMessage),Object.freeze(errors)}publishValiditySnapshot(){if(!this.isConnected)return;const valid=!this.willValidate||this.validity.valid,errors=valid?Object.freeze({}):this.publicValidityErrors(),key=JSON.stringify({valid,errors});key!==this.lastValidityKey&&(this.lastValidityKey=key,this.emit("lr-validity-change",Object.freeze({valid,errors})))}fieldElement(key){const root=this.renderRoot,ownerCss=this.ownerDocument.defaultView?.CSS;if(typeof ownerCss?.escape=="function")try{const candidate=root.querySelector(`[part="field"][data-key="${ownerCss.escape(key)}"]`);if(candidate?.getAttribute("data-key")===key)return candidate}catch{}return Array.from(root.querySelectorAll('[part="field"][data-key]')).find(candidate=>candidate.getAttribute("data-key")===key)??null}[VALIDITY_ANCHOR](){const firstInvalidKey=Object.keys(this._errors)[0];return!firstInvalidKey||!this.renderRoot?void 0:this.fieldElement(firstInvalidKey)?.querySelector(".control")??void 0}isSegmentedScore(k){return isSegmentedScoreKey(k)}scoreValues(k){if(!this.isSegmentedScore(k))return[];const{min,max,step}=scoreDomain(k),count=Math.round((max-min)/step);return Array.from({length:count+1},(_,index)=>index===count?max:min+index*step)}computeValidation(){const errors={},flags={};for(const k of this._keys){if(k.type!=="score"&&k.type!=="category"&&k.type!=="comment"){const unsupported=k;errors[unsupported.key]=this.localize("unsupportedFieldType",void 0,{type:unsupported.type}),flags.customError=!0;continue}if(!k.required)continue;const v=this._value[k.key];(k.type==="category"&&k.multiple?Array.isArray(v)&&v.length>0:v!==void 0&&v!=="")||(errors[k.key]=this.localize("fieldRequired"),flags.valueMissing=!0)}return{errors,flags}}syncFormState(){const{errors,flags}=this.computeValidation();this._errors=errors;let formValue=null;try{formValue=JSON.stringify(this._value)}catch{formValue=null}if(this.internals.setFormValue(formValue,formValue),this.barredFromValidation||Object.keys(flags).length===0)this.validityController.setValidity({});else{const message=Object.values(errors)[0]??"";this.validityController.setValidity(flags,message)}this.syncCustomStates(),this.publishValiditySnapshot()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}syncCustomStates(){syncValidityStates(this.internals,{required:this._keys.some(key=>!!key.required),hasInteracted:this.touchedFields.size>0,barred:this.barredFromValidation})}checkValidity(){return this.syncFormState(),this.internals.checkValidity()}reportValidity(){return this.syncFormState(),Object.keys(this._errors).length>0&&(this.touchedFields=new Set([...this.touchedFields,...Object.keys(this._errors)]),this.syncCustomStates()),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncCustomStates(),this.publishValiditySnapshot(),this.requestUpdate()}formResetCallback(){this.setLiveValue(this._defaultValue,!1),this.touchedFields=new Set,this.syncCustomStates()}formStateRestoreCallback(state2,_mode){let restored={};if(typeof state2=="string")try{const parsed=JSON.parse(state2);parsed!==null&&typeof parsed=="object"&&!Array.isArray(parsed)&&(restored=parsed)}catch{}this.setLiveValue(restored,!0)}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,this.syncFormState(),this.requestUpdate()}setFieldValue(key,val){this.effectiveDisabled||(this.value={...this._value,[key]:val},this.emit("lr-input",Object.freeze({value:cloneRubricValue(this._value)})))}markTouched(key){this.effectiveDisabled||this.touchedFields.has(key)||(this.touchedFields=new Set(this.touchedFields).add(key),this.syncCustomStates())}submit(){this.effectiveDisabled||this.reportValidity()&&this.emit("lr-submit",Object.freeze({value:cloneRubricValue(this._value),itemId:this.itemId}))}skip(){this.effectiveDisabled||this.emit("lr-skip",{itemId:this.itemId})}focusFirstControl(){const firstKey=this._keys[0];if(!firstKey)return;const control=this.fieldElement(firstKey.key)?.querySelector(".control");control&&(firstKey.type==="score"&&this.isSegmentedScore(firstKey)?control.shadowRoot?.querySelector('[part="segment"][tabindex="0"]')?.focus():firstKey.type==="score"?control.shadowRoot?.querySelector('[part="thumb"]')?.focus():firstKey.type==="category"&&firstKey.multiple?control.querySelector("lr-checkbox")?.focus():control.focus())}click(){this.effectiveDisabled||this.focusFirstControl()}syncExternalDescription(){const target=this.isConnected?this.renderRoot.querySelector('[part="base"][role="group"]'):null;if(!target){this.releaseExternalDescription();return}this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby")}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription()}disconnectedCallback(){this.releaseExternalDescription(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.isConnected&&this.hasUpdated&&this.syncExternalDescription()}updated(changed){super.updated(changed),this.syncExternalDescription(),this.publishValiditySnapshot(),this.pendingFocusFirst&&(this.pendingFocusFirst=!1,this.focusFirstControl())}renderScoreControl(k,fieldId,current,hasError){const{min,max,step}=scoreDomain(k),disabled=this.effectiveDisabled,accessibleLabel=[k.label??k.key,k.description,hasError?this._errors[k.key]:void 0].filter(value=>!!value).join(". ");if(this.isSegmentedScore(k)){const numberFormat=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:20}),items=this.scoreValues(k).map(score=>({value:String(score),label:numberFormat.format(score),disabled})),value=typeof current=="number"?String(current):"";return html`<lr-segmented
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{live}from"lit/directives/live.js";import{LyraElement}from"../../../internal/lyra-element.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";installFormControlLabelSupport();import{nextId}from"../../../internal/a11y.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{styles}from"./rubric-form.styles.js";import"../../layout/segmented/segmented.class.js";import"../slider/slider.class.js";import"../select/select.class.js";import"../combobox/option.class.js";import"../checkbox/checkbox.class.js";import"../checkbox-group/checkbox-group.class.js";import"../textarea/textarea.class.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_noData,LYRA_DEFAULT_rubricSkip,LYRA_DEFAULT_rubricSubmit,LYRA_DEFAULT_rubricSubmitAndNext,LYRA_DEFAULT_unsupportedFieldType}from"../../../internal/default-strings.generated.js";const EMPTY_KEYS=[],EMPTY_VALUE={},MAX_RUBRIC_COLLECTION_ENTRIES=1e4;function cloneRubricValue(value){return Object.freeze(Object.fromEntries(Object.entries(value).map(([key,entry])=>[key,Array.isArray(entry)?Object.freeze([...entry]):entry])))}function projectRubricStringArray(value){try{if(!Array.isArray(value))return;const length=getOwnDataDescriptor(value,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return;const values=[];for(let index=0;index<Math.min(length.value,MAX_RUBRIC_COLLECTION_ENTRIES);index+=1){const entry=getOwnDataDescriptor(value,String(index));entry===MISSING_OWN_DATA_DESCRIPTOR||entry===UNSAFE_OWN_DATA_DESCRIPTOR||typeof entry.value=="string"&&values.push(entry.value)}return Object.freeze(values)}catch{return}}function projectRubricOptions(value){try{if(!Array.isArray(value))return Object.freeze([]);const length=getOwnDataDescriptor(value,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return Object.freeze([]);const options=[];for(let index=0;index<Math.min(length.value,MAX_RUBRIC_COLLECTION_ENTRIES);index+=1){const candidate=getOwnDataDescriptor(value,String(index));if(candidate===MISSING_OWN_DATA_DESCRIPTOR||candidate===UNSAFE_OWN_DATA_DESCRIPTOR||candidate.value===null||typeof candidate.value!="object"||Array.isArray(candidate.value))continue;const optionValue=getOwnDataDescriptor(candidate.value,"value"),label=getOwnDataDescriptor(candidate.value,"label"),description=getOwnDataDescriptor(candidate.value,"description");if(optionValue===MISSING_OWN_DATA_DESCRIPTOR||optionValue===UNSAFE_OWN_DATA_DESCRIPTOR||typeof optionValue.value!="string")continue;const labelValue=label===MISSING_OWN_DATA_DESCRIPTOR||label===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:typeof label.value=="string"?label.value:void 0,descriptionValue=description===MISSING_OWN_DATA_DESCRIPTOR||description===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:typeof description.value=="string"?description.value:void 0;options.push(Object.freeze({value:optionValue.value,...labelValue===void 0?{}:{label:labelValue},...descriptionValue===void 0?{}:{description:descriptionValue}}))}return Object.freeze(options)}catch{return Object.freeze([])}}function projectRubricKey(candidate){try{if(candidate===null||typeof candidate!="object"||Array.isArray(candidate))return;const key=getOwnDataDescriptor(candidate,"key"),type=getOwnDataDescriptor(candidate,"type"),label=getOwnDataDescriptor(candidate,"label"),description=getOwnDataDescriptor(candidate,"description"),required=getOwnDataDescriptor(candidate,"required");if(key===MISSING_OWN_DATA_DESCRIPTOR||key===UNSAFE_OWN_DATA_DESCRIPTOR||type===UNSAFE_OWN_DATA_DESCRIPTOR||label===UNSAFE_OWN_DATA_DESCRIPTOR||description===UNSAFE_OWN_DATA_DESCRIPTOR||required===UNSAFE_OWN_DATA_DESCRIPTOR||typeof key.value!="string"||key.value.trim().length===0)return;const typeValue=type===MISSING_OWN_DATA_DESCRIPTOR?"":type.value;if(typeof typeValue!="string")return;const labelValue=label===MISSING_OWN_DATA_DESCRIPTOR?void 0:label.value,descriptionValue=description===MISSING_OWN_DATA_DESCRIPTOR?void 0:description.value,requiredValue=required===MISSING_OWN_DATA_DESCRIPTOR?void 0:required.value,common={key:key.value,...typeof labelValue=="string"?{label:labelValue}:{},...typeof descriptionValue=="string"?{description:descriptionValue}:{},...typeof requiredValue=="boolean"?{required:requiredValue}:{}};if(typeValue==="score"){const min=getOwnDataDescriptor(candidate,"min"),max=getOwnDataDescriptor(candidate,"max"),step=getOwnDataDescriptor(candidate,"step");return min===UNSAFE_OWN_DATA_DESCRIPTOR||max===UNSAFE_OWN_DATA_DESCRIPTOR||step===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:Object.freeze({...common,type:"score",...min!==MISSING_OWN_DATA_DESCRIPTOR&&typeof min.value=="number"?{min:min.value}:{},...max!==MISSING_OWN_DATA_DESCRIPTOR&&typeof max.value=="number"?{max:max.value}:{},...step!==MISSING_OWN_DATA_DESCRIPTOR&&typeof step.value=="number"?{step:step.value}:{}})}if(typeValue==="category"){const options=getOwnDataDescriptor(candidate,"options"),multiple=getOwnDataDescriptor(candidate,"multiple");return options===UNSAFE_OWN_DATA_DESCRIPTOR||multiple===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:Object.freeze({...common,type:"category",options:options===MISSING_OWN_DATA_DESCRIPTOR?Object.freeze([]):projectRubricOptions(options.value),...multiple!==MISSING_OWN_DATA_DESCRIPTOR&&typeof multiple.value=="boolean"?{multiple:multiple.value}:{}})}if(typeValue==="comment"){const placeholder=getOwnDataDescriptor(candidate,"placeholder");return placeholder===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:Object.freeze({...common,type:"comment",...placeholder!==MISSING_OWN_DATA_DESCRIPTOR&&typeof placeholder.value=="string"?{placeholder:placeholder.value}:{}})}return Object.freeze({...common,type:typeValue})}catch{return}}function normalizeRubricKeys(next){try{if(!Array.isArray(next))return EMPTY_KEYS;const length=getOwnDataDescriptor(next,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return EMPTY_KEYS;const seen=new Set,normalized=[];for(let index=0;index<Math.min(length.value,MAX_RUBRIC_COLLECTION_ENTRIES);index+=1){const candidate=getOwnDataDescriptor(next,String(index));if(candidate===MISSING_OWN_DATA_DESCRIPTOR||candidate===UNSAFE_OWN_DATA_DESCRIPTOR)continue;const key=projectRubricKey(candidate.value);!key||seen.has(key.key)||(seen.add(key.key),normalized.push(key))}return Object.freeze(normalized)}catch{return EMPTY_KEYS}}function scoreDomain(key){const min=Number.isFinite(key.min)?key.min:0,rawMax=Number.isFinite(key.max)?key.max:5,max=Math.max(min,rawMax),step=Number.isFinite(key.step)&&key.step>0?key.step:1;return{min,max,step}}function isSegmentedScoreKey(key){if(key.step!==void 0&&(!Number.isFinite(key.step)||key.step<=0)||Number.isFinite(key.min)&&Number.isFinite(key.max)&&key.max<key.min)return!1;const{min,max,step}=scoreDomain(key);if(!Number.isInteger(min)||!Number.isInteger(max)||!Number.isInteger(step))return!1;const count=(max-min)/step;return Number.isInteger(count)&&count>=0&&count<=10}function canonicalScore(value,key){if(typeof value!="number"||!Number.isFinite(value))return;const{min,max,step}=scoreDomain(key),clamped=Math.min(max,Math.max(min,value)),snapped=Math.min(max,Math.max(min,min+Math.round((clamped-min)/step)*step));return Number(snapped.toPrecision(15))}function normalizeRubricValue(value,keys){const source=value!==null&&typeof value=="object"&&!Array.isArray(value)?value:EMPTY_VALUE,normalized={};for(const key of keys){const descriptor=getOwnDataDescriptor(source,key.key);if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)continue;const hasEntry=descriptor!==MISSING_OWN_DATA_DESCRIPTOR,entry=descriptor===MISSING_OWN_DATA_DESCRIPTOR?void 0:descriptor.value;if(key.type==="score"){const{min,max}=scoreDomain(key),score=canonicalScore(hasEntry?entry:isSegmentedScoreKey(key)?void 0:min+(max-min)/2,key);score!==void 0&&(normalized[key.key]=score)}else if(key.type==="category"){if(!hasEntry)continue;const allowed=(key.options??[]).map(option=>option.value);if(key.multiple){const entries=projectRubricStringArray(entry);if(!entries)continue;const remaining=new Map;for(const option of allowed)remaining.set(option,(remaining.get(option)??0)+1);const selected=[];for(const candidate of entries){const count=remaining.get(candidate)??0;count<=0||(selected.push(candidate),remaining.set(candidate,count-1))}normalized[key.key]=selected}else typeof entry=="string"&&entry!==""&&allowed.includes(entry)&&(normalized[key.key]=entry)}else key.type==="comment"&&hasEntry&&typeof entry=="string"&&(normalized[key.key]=entry)}return normalized}class LyraRubricForm extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,noData:LYRA_DEFAULT_noData,rubricSkip:LYRA_DEFAULT_rubricSkip,rubricSubmit:LYRA_DEFAULT_rubricSubmit,rubricSubmitAndNext:LYRA_DEFAULT_rubricSubmitAndNext,unsupportedFieldType:LYRA_DEFAULT_unsupportedFieldType}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},keys:{attribute:!1,noAccessor:!0},value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:!1,noAccessor:!0},itemId:{attribute:"item-id",reflect:!0,noAccessor:!0},hasNext:{type:Boolean,attribute:"has-next",noAccessor:!0},skippable:{type:Boolean,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0}}}constructor(){super(),this.label="",this.hint="",this.errorText="",this.withLabel=!1,this.withHint=!1,this._errors={},this.touchedFields=new Set,this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.baseId=nextId("rubric-form"),this.aggregateLabelId=`${this.baseId}-label`,this.aggregateHintId=`${this.baseId}-hint`,this.aggregateErrorId=`${this.baseId}-error`,this._fieldsetDisabled=!1,this._name="",this._keys=EMPTY_KEYS,this._value=EMPTY_VALUE,this._defaultValue=EMPTY_VALUE,this._rawValue=EMPTY_VALUE,this._rawDefaultValue=EMPTY_VALUE,this._valueDirty=!1,this._itemId="",this._hasNext=!1,this._skippable=!1,this._disabled=!1,this.pendingFocusFirst=!1,this.onFormKeyDown=e=>{e.key==="Enter"&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),this.submit())},this.stopChildEvent=event=>{event.stopPropagation()},this.onAggregateSlotChange=event=>{const slot=event.target,populated=slot.assignedNodes({flatten:!0}).some(node=>node.nodeType===Node.ELEMENT_NODE||!!node.textContent?.trim());slot.name==="label"?this.hasLabelSlot=populated:slot.name==="hint"?this.hasHintSlot=populated:slot.name==="error"&&(this.hasErrorSlot=populated)},this.internals=this.safeAttachInternals(),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.addEventListener("keydown",this.onFormKeyDown),this.syncFormState()}safeAttachInternals(){if(typeof globalThis.ElementInternals>"u")return this.inertInternals();try{return this.attachInternals()}catch{return this.inertInternals()}}inertInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:!1,setFormValue:()=>{},setValidity:()=>{},checkValidity:()=>!0,reportValidity:()=>!0,states:new Set}}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}get keys(){return this._keys}set keys(next){const old=this._keys,recoverFromRaw=old.length===0;this._keys=normalizeRubricKeys(next??EMPTY_KEYS);const oldDefault=this._defaultValue,oldValue=this._value;this._defaultValue=normalizeRubricValue(recoverFromRaw?this._rawDefaultValue:this._defaultValue,this._keys),this._value=this._valueDirty?normalizeRubricValue(recoverFromRaw?this._rawValue:this._value,this._keys):cloneRubricValue(this._defaultValue),this.syncFormState(),this.requestUpdate("keys",old),this.requestUpdate("defaultValue",oldDefault),this.requestUpdate("value",oldValue)}get value(){return cloneRubricValue(this._value)}set value(next){this.setLiveValue(next,!0)}get defaultValue(){return cloneRubricValue(this._defaultValue)}set defaultValue(next){const old=this._defaultValue;this._rawDefaultValue=next??EMPTY_VALUE,this._defaultValue=normalizeRubricValue(this._rawDefaultValue,this._keys),this._valueDirty||this.setLiveValue(this._defaultValue,!1),this.requestUpdate("defaultValue",old)}setLiveValue(next,dirty){const old=this._value;this._rawValue=next??EMPTY_VALUE,this._value=normalizeRubricValue(this._rawValue,this._keys),this._valueDirty=dirty,this.syncFormState(),this.requestUpdate("value",old)}get itemId(){return this._itemId}set itemId(next){const old=this._itemId;this._itemId=next??"",old!==this._itemId&&(this.touchedFields=new Set,this.syncCustomStates(),this.hasUpdated&&(this.pendingFocusFirst=!0)),this._itemId?this.setAttribute("item-id",this._itemId):this.removeAttribute("item-id"),this.requestUpdate("itemId",old)}get hasNext(){return this._hasNext}set hasNext(next){const old=this._hasNext;this._hasNext=!!next,this.toggleAttribute("has-next",this._hasNext),this.requestUpdate("hasNext",old)}get skippable(){return this._skippable}set skippable(next){const old=this._skippable;this._skippable=!!next,this.requestUpdate("skippable",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this.validityController&&this.syncFormState(),this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get errors(){return this.publicValidityErrors()}publicValidityErrors(){const errors={...this._errors};return this.willValidate&&this.validityController.customValidityMessage&&(errors.base=this.validationMessage),Object.freeze(errors)}publishValiditySnapshot(){if(!this.isConnected)return;const valid=!this.willValidate||this.validity.valid,errors=valid?Object.freeze({}):this.publicValidityErrors(),key=JSON.stringify({valid,errors});key!==this.lastValidityKey&&(this.lastValidityKey=key,this.emit("lr-validity-change",Object.freeze({valid,errors})))}fieldElement(key){const root=this.renderRoot,ownerCss=this.ownerDocument.defaultView?.CSS;if(typeof ownerCss?.escape=="function")try{const candidate=root.querySelector(`[part="field"][data-key="${ownerCss.escape(key)}"]`);if(candidate?.getAttribute("data-key")===key)return candidate}catch{}return Array.from(root.querySelectorAll('[part="field"][data-key]')).find(candidate=>candidate.getAttribute("data-key")===key)??null}[VALIDITY_ANCHOR](){const firstInvalidKey=Object.keys(this._errors)[0];return!firstInvalidKey||!this.renderRoot?void 0:this.fieldElement(firstInvalidKey)?.querySelector(".control")??void 0}isSegmentedScore(k){return isSegmentedScoreKey(k)}scoreValues(k){if(!this.isSegmentedScore(k))return[];const{min,max,step}=scoreDomain(k),count=Math.round((max-min)/step);return Array.from({length:count+1},(_,index)=>index===count?max:min+index*step)}computeValidation(){const errors={},flags={};for(const k of this._keys){if(k.type!=="score"&&k.type!=="category"&&k.type!=="comment"){const unsupported=k;errors[unsupported.key]=this.localize("unsupportedFieldType",void 0,{type:unsupported.type}),flags.customError=!0;continue}if(!k.required)continue;const v=this._value[k.key];(k.type==="category"&&k.multiple?Array.isArray(v)&&v.length>0:v!==void 0&&v!=="")||(errors[k.key]=this.localize("fieldRequired"),flags.valueMissing=!0)}return{errors,flags}}syncFormState(){const{errors,flags}=this.computeValidation();this._errors=errors;let formValue=null;try{formValue=JSON.stringify(this._value)}catch{formValue=null}if(this.internals.setFormValue(formValue,formValue),this.barredFromValidation||Object.keys(flags).length===0)this.validityController.setValidity({});else{const message=Object.values(errors)[0]??"";this.validityController.setValidity(flags,message)}this.syncCustomStates(),this.publishValiditySnapshot()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}syncCustomStates(){syncValidityStates(this.internals,{required:this._keys.some(key=>!!key.required),hasInteracted:this.touchedFields.size>0,barred:this.barredFromValidation})}checkValidity(){return this.syncFormState(),this.internals.checkValidity()}reportValidity(){return this.syncFormState(),Object.keys(this._errors).length>0&&(this.touchedFields=new Set([...this.touchedFields,...Object.keys(this._errors)]),this.syncCustomStates()),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncCustomStates(),this.publishValiditySnapshot(),this.requestUpdate()}formResetCallback(){this.setLiveValue(this._defaultValue,!1),this.touchedFields=new Set,this.syncCustomStates()}formStateRestoreCallback(state2,_mode){let restored={};if(typeof state2=="string")try{const parsed=JSON.parse(state2);parsed!==null&&typeof parsed=="object"&&!Array.isArray(parsed)&&(restored=parsed)}catch{}this.setLiveValue(restored,!0)}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,this.syncFormState(),this.requestUpdate()}setFieldValue(key,val){this.effectiveDisabled||(this.value={...this._value,[key]:val},this.emit("lr-input",Object.freeze({value:cloneRubricValue(this._value)})))}markTouched(key){this.effectiveDisabled||this.touchedFields.has(key)||(this.touchedFields=new Set(this.touchedFields).add(key),this.syncCustomStates())}submit(){this.effectiveDisabled||this.reportValidity()&&this.emit("lr-submit",Object.freeze({value:cloneRubricValue(this._value),itemId:this.itemId}))}skip(){this.effectiveDisabled||this.emit("lr-skip",{itemId:this.itemId})}focusFirstControl(){const firstKey=this._keys[0];if(!firstKey)return;const control=this.fieldElement(firstKey.key)?.querySelector(".control");control&&(firstKey.type==="score"&&this.isSegmentedScore(firstKey)?control.shadowRoot?.querySelector('[part="segment"][tabindex="0"]')?.focus():firstKey.type==="score"?control.shadowRoot?.querySelector('[part="thumb"]')?.focus():firstKey.type==="category"&&firstKey.multiple?control.querySelector("lr-checkbox")?.focus():control.focus())}click(){this.effectiveDisabled||this.focusFirstControl()}syncExternalDescription(){const target=this.isConnected?this.renderRoot.querySelector('[part="base"][role="group"]'):null;if(!target){this.releaseExternalDescription();return}this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby")}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription()}disconnectedCallback(){this.releaseExternalDescription(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.isConnected&&this.hasUpdated&&this.syncExternalDescription()}updated(changed){super.updated(changed),this.syncExternalDescription(),this.publishValiditySnapshot(),this.pendingFocusFirst&&(this.pendingFocusFirst=!1,this.focusFirstControl())}renderScoreControl(k,fieldId,current,hasError){const{min,max,step}=scoreDomain(k),disabled=this.effectiveDisabled,accessibleLabel=[k.label??k.key,k.description,hasError?this._errors[k.key]:void 0].filter(value=>!!value).join(". ");if(this.isSegmentedScore(k)){const numberFormat=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:20}),items=this.scoreValues(k).map(score=>({value:String(score),label:numberFormat.format(score),disabled})),value=typeof current=="number"?String(current):"";return html`<lr-segmented
|
|
2
2
|
id=${fieldId}
|
|
3
3
|
class="control"
|
|
4
4
|
part="scale"
|
|
@@ -277,7 +277,7 @@ private activeOption?;private options;private touched;
|
|
|
277
277
|
private hasInteracted;private readonly slotPresence;private triggerElement?;private internals;private validityController;
|
|
278
278
|
/** Consumer-supplied validation message reflected through `custom-error`.
|
|
279
279
|
* @default null */
|
|
280
|
-
customError:string|null;private _fieldsetDisabled;private listId;private triggerId;private valueTextId;private cleanup?;private positioningReady;private overlayHandle?;private restoreFocusOnClose;private positionedDirection?;private pointerListenerDocument?;private pointerListener?;private _isFirstUpdate;private openVetoed;private openStateGeneration;private pendingOpenTransitionStart?;private suppressedOpenLifecycleGeneration?;private transitionToken;private transitionWaiters;private _selected;private _selectedOptions;private _selectedValuesByOption;private _multiple;private _disabled;private _required;private _defaultSelected;private _defaultSelectedOptions;private _defaultCaptured;private _valueDirty;private _restoredStateActive;private typeAheadBuffer;private typeAheadTimer?;private typeAheadTimerWindow?;private typeAheadTimerGeneration;
|
|
280
|
+
customError:string|null;private _fieldsetDisabled;private listId;private triggerId;private valueTextId;private cleanup?;private positioningReady;private overlayHandle?;private restoreFocusOnClose;private positionedDirection?;private pointerListenerDocument?;private pointerListener?;private _isFirstUpdate;private openVetoed;private openStateGeneration;private pendingOpenTransitionStart?;private suppressedOpenLifecycleGeneration?;private transitionToken;private transitionWaiters;private _selected;private _selectedOptions;private _selectedValuesByOption;private _multiple;private _disabled;private _required;private _defaultSelected;private _defaultSelectedOptions;private _defaultCaptured;private _valueDirty;private _restoredStateActive;private _pendingInitialValue?;private _pendingInitialSelectedOptions?;private _pendingInitialDefaultValue?;private _resolvingPendingInitialSelection;private _defaultValueDirty;private typeAheadBuffer;private typeAheadTimer?;private typeAheadTimerWindow?;private typeAheadTimerGeneration;
|
|
281
281
|
/** Focus the internal select trigger. */
|
|
282
282
|
focus(options?:FocusOptions):void;
|
|
283
283
|
/** Blur the internal select trigger. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{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{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";installFormControlLabelSupport();import{deferredPlaceReady as place}from"../../../internal/anchored-overlay-runtime.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{chevronIcon,closeIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{finiteCount}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./select.styles.js";import{sizes}from"../../../internal/sizes.styles.js";import"../combobox/option.class.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{omittedEmptyStringConverter}from"../../../internal/converters.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.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{tag}from"../../../internal/prefix.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_select,LYRA_DEFAULT_selectSelectedOverflow,LYRA_DEFAULT_selectValueMissing}from"../../../internal/default-strings.generated.js";function isLyraOptionElement(value){return isHtmlElement(value)&&value.localName===tag("option")}class LyraSelect extends LyraElement{static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,removeWithContext:LYRA_DEFAULT_removeWithContext,select:LYRA_DEFAULT_select,selectSelectedOverflow:LYRA_DEFAULT_selectSelectedOverflow,selectValueMissing:LYRA_DEFAULT_selectValueMissing}}static{this.immutableEventDetails=Object.freeze(["lr-input","lr-change"])}static get validators(){return[currentValidityValidator("required","disabled","value","multiple")]}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},value:{noAccessor:!0},name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},maxOptionsVisible:{type:Number,attribute:"max-options-visible",noAccessor:!0},defaultValue:{attribute:"default-value",noAccessor:!0}}}get open(){return this._open}set open(next){const requested=!!next,normalized=requested&&!this.effectiveDisabled;if(normalized===this._open){requested!==normalized&&this.hasAttribute("open")&&this.removeAttribute("open");return}this.applyOpenState(normalized)}focus(options){this.effectiveDisabled||this.triggerElement?.focus(options)}blur(){this.triggerElement?.blur()}click(){this.effectiveDisabled||this.triggerElement?.click()}constructor(){super(),this.placeholder="",this.label="",this.hint="",this.helpText="",this.withLabel=!1,this.withHint=!1,this.errorText="",this.autofocus=!1,this.title="",this._open=!1,this.size="m",this.appearance="outlined",this.pill=!1,this.placement="bottom",this.hoist=!1,this.filled=!1,this.withClear=!1,this.clearable=!1,this.autoCommitSingleOption=!1,this.activeIndex=-1,this.options=[],this.touched=!1,this.hasInteracted=!1,this.slotPresence=new SlotPresenceController(this),this._fieldsetDisabled=!1,this.listId=nextId("select-list"),this.triggerId=nextId("select-trigger"),this.valueTextId=nextId("select-value"),this.positioningReady=Promise.resolve(!1),this.restoreFocusOnClose=!0,this._isFirstUpdate=!0,this.openVetoed=!1,this.openStateGeneration=0,this.transitionToken=0,this.transitionWaiters=new Map,this._selected=[],this._selectedOptions=[],this._selectedValuesByOption=new Map,this._multiple=!1,this._disabled=!1,this._required=!1,this._defaultSelected=[],this._defaultSelectedOptions=[],this._defaultCaptured=!1,this._valueDirty=!1,this._restoredStateActive=!1,this.typeAheadBuffer="",this.typeAheadTimerGeneration=0,this._name="",this._maxOptionsVisible=3,this.localDescriptionIds="",this.collectOptions=e=>{const slot=e.target,previous=new Set(this.options),previousActive=this.activeOption,previousActiveRawIndex=previousActive?this.options.indexOf(previousActive):this.activeIndex;if(this.options=slot.assignedElements({flatten:!0}).filter(isLyraOptionElement),this.reconcileActiveOption(previousActive,previousActiveRawIndex),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>0){const added=this.multiple?eligible:eligible.slice(-1),occurrences=this.multiple?[...new Set([...this._selectedOptions,...added])]:added;newLive.length>0&&(this._valueDirty=!0),this.setSelection(occurrences.map(option=>option.value),occurrences);return}}else{this._defaultCaptured=!0;const hasDefaultValue=this.hasAttribute("default-value"),allDefaults=this.options.filter(option=>option.defaultSelected),defaults=this.multiple?allDefaults:allDefaults.slice(0,1),allLive=this.options.filter(option=>option.selected),live=this.multiple?allLive:allLive.slice(0,1),initialLive=this.options.filter(option=>wasOptionInitiallySelected(option)),optionDirty=this.options.some(option=>isOptionSelectedDirty(option)),dirtySelected=this.options.filter(option=>isOptionSelectedDirty(option)&&option.selected);if(hasDefaultValue)this._defaultSelectedOptions=this.resolveOccurrences(this._defaultSelected);else{const resetOptions=defaults.length>0?defaults:initialLive.length>0?initialLive:live;this._defaultSelected=resetOptions.map(option=>option.value),this._defaultSelectedOptions=[...resetOptions]}const fromDefaults=hasDefaultValue||defaults.length>0,initial=optionDirty?this.multiple?allLive:dirtySelected.slice(-1)[0]?dirtySelected.slice(-1):live:hasDefaultValue?this._defaultSelectedOptions:fromDefaults?defaults:live;if(initial.length>0&&!this._restoredStateActive&&!this._valueDirty){(!fromDefaults||optionDirty)&&(this._valueDirty=!0),this.setSelection(initial.map(option=>option.value),[...initial]);return}if(optionDirty&&(this._valueDirty=!0),hasDefaultValue&&!this._valueDirty&&!this._restoredStateActive){this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions]);return}}this.reflectSelected()},this.onOptionChange=e=>{e.stopPropagation();const option=e.composedPath().find(isLyraOptionElement);if(isLyraOptionElement(option)&&this.options.includes(option)&&isOptionSelectedWrite(e)){this._valueDirty=!0,this._restoredStateActive=!1;const selected=this._selectedOptions.includes(option);if(option.selected===selected&&(!selected||this._selectedValuesByOption.get(option)===option.value))return;if(option.selected&&!this.multiple){this.setSelection([option.value],[option]);return}const remaining=[...this._selectedOptions],preferred=this._selected.map(value=>{const index2=remaining.findIndex(candidate=>this._selectedValuesByOption.get(candidate)===value);return index2<0?void 0:remaining.splice(index2,1)[0]}),values=[...this._selected],index=preferred.indexOf(option);if(option.selected)index<0?(values.push(option.value),preferred.push(option)):values[index]=option.value;else{if(index<0)return;values.splice(index,1),preferred.splice(index,1)}this.setSelection(values,preferred);return}const previousActive=this.activeOption,previousActiveRawIndex=previousActive?this.options.indexOf(previousActive):this.activeIndex;queueMicrotask(()=>{this.refreshOptionDefaults(),this.reflectSelected(),this.options=[...this.options],this.reconcileActiveOption(previousActive,previousActiveRawIndex)})},this.onDocPointer=e=>{if(!e.composedPath().includes(this)){if(this.overlayHandle?.isActive()){this.overlayHandle.dismissBackdrop();return}this.restoreFocusOnClose=!1,this.hide()}},this.onTriggerClick=()=>{if(!this.effectiveDisabled){if(this.onlyOption)return this.selectOption(this.onlyOption);this.open?this.hide():this.show()}},this.onTriggerBlur=event=>{this.effectiveDisabled||(this.touched=!0,this.hasInteracted=!0,this.reflectValidityStates()),this.open&&(this.restoreFocusOnClose=!1),this.hide(),relayNativeEvent(this,event)},this.onTriggerFocus=event=>{relayNativeEvent(this,event)},this.onKeyDown=e=>{const navigable=this.navigableOptions();switch(e.key){case"ArrowDown":if(e.preventDefault(),this.onlyOption)return this.selectOption(this.onlyOption);if(!this.open){this.show();return}this.setActiveIndex(Math.min(navigable.length-1,this.activeIndex+1),navigable);break;case"ArrowUp":if(e.preventDefault(),this.onlyOption)return this.selectOption(this.onlyOption);if(!this.open){this.show();return}this.setActiveIndex(Math.max(0,this.activeIndex-1),navigable);break;case"Enter":case" ":if(this.open){e.preventDefault();const active=navigable[this.activeIndex];this.activeIndex>=0&&active?this.selectOption(active):this.hide()}break;case"Escape":this.open&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(e.preventDefault(),this.hide());break;case"Home":this.open&&(e.preventDefault(),this.setActiveIndex(0,navigable));break;case"End":this.open&&(e.preventDefault(),this.setActiveIndex(navigable.length-1,navigable));break;case"Backspace":case"Delete":this.multiple&&this._selected.length>0&&(e.preventDefault(),this.removeValueAt(this._selected.length-1));break;default:e.key.length===1&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&this.typeAhead(e.key);break}},this.onListboxMouseDown=e=>{e.preventDefault()},this.onListboxClick=e=>{const optionEl=e.target.closest('[part="option"]'),index=Number(optionEl?.dataset.index);if(!Number.isInteger(index))return;const option=this.options[index];option&&this.selectOption(option)},installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),this.syncFormValue()}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"]')??null}syncExternalDescription(){if(!this.isConnected)return;const target=this.renderRoot.querySelector('[part="trigger"]');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.open&&queueMicrotask(()=>this.reconnectOpenPopup())}willUpdate(changed){super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,this.announceOpenTransition(changed),changed.has("open")&&!this.open&&!this.openVetoed&&this.setActiveIndex(-1)}applyOpenState(next){const old=this._open;this.pendingOpenTransitionStart===void 0&&(this.pendingOpenTransitionStart=old),this.openStateGeneration++,this._open=next,this.requestUpdate("open",old)}forceCloseOpenState(){const isClosing=this._open||this.pendingOpenTransitionStart===!0;if(this.transitionToken++,this.resolveTransitionWaiters("lr-after-show"),this.resolveTransitionWaiters("lr-after-hide"),!this._open){isClosing&&(this.suppressedOpenLifecycleGeneration=this.openStateGeneration),this.hasAttribute("open")&&this.removeAttribute("open");return}this.applyOpenState(!1),this.suppressedOpenLifecycleGeneration=this.openStateGeneration}announceOpenTransition(changed){if(this.openVetoed=!1,!changed.has("open")||this._isFirstUpdate||this.suppressedOpenLifecycleGeneration===this.openStateGeneration)return;const name=this.open?"lr-show":"lr-hide";if(!this.isConnected){this.emit("lr-hide");return}this.emit(name,null,{cancelable:!0}).defaultPrevented&&(this.openVetoed=!0,this.open=!this.open,this.resolveTransitionWaiters(this.open?"lr-after-hide":"lr-after-show"))}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("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._multiple&&this._selected.length>1?this.setSelection(this._selected.slice(0,1),this._selectedOptions.slice(0,1)):this.syncFormValue(),this.requestUpdate("multiple",old)}get maxOptionsVisible(){return this._maxOptionsVisible}set maxOptionsVisible(next){const old=this._maxOptionsVisible;this._maxOptionsVisible=finiteCount(next,3),this.requestUpdate("maxOptionsVisible",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._disabled&&this.forceCloseOpenState(),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 value(){return this.multiple?[...this._selected]:this._selected[0]??""}set value(next){this._restoredStateActive=!1,this._valueDirty=!0;const values=(Array.isArray(next)?next:next?[next]:[]).filter(value=>typeof value=="string");this.setSelection(values,values.map(value=>this.options.find(option=>option.value===value)))}get defaultValue(){return this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??""}set defaultValue(next){const old=this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??"",values=(Array.isArray(next)?next:next?[next]:[]).filter(value=>typeof value=="string");this._defaultSelected=this.multiple?[...values]:values.slice(0,1),this._defaultSelectedOptions=this.resolveOccurrences(this._defaultSelected),!this._valueDirty&&!this._restoredStateActive&&this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions]),this.requestUpdate("defaultValue",old)}get selectedOptions(){return[...this._selectedOptions]}set selectedOptions(next){this._restoredStateActive=!1,this._valueDirty=!0;const candidates=Array.isArray(next)?next:[],live=candidates.filter((option,index)=>isLyraOptionElement(option)&&this.contains(option)&&this.options.includes(option)&&candidates.indexOf(option)===index),selected=this.multiple?live:live.slice(0,1);this.setSelection(selected.map(option=>option.value),selected)}setSelection(next,preferred=[]){const values=this.multiple?[...next]:next.slice(0,1),previousValues=this._selected,previousOptions=this._selectedOptions,old=this.multiple?[...previousValues]:previousValues[0]??"";this._selected=values,this._selectedOptions=this.resolveOccurrences(values,preferred),this.syncFormValue(),this.reflectSelected(),this.updateValidity(),this.requestUpdate("value",old);const sameValues=previousValues.length===values.length&&previousValues.every((value,i)=>value===values[i]),sameOptions=previousOptions.length===this._selectedOptions.length&&previousOptions.every((option,i)=>option===this._selectedOptions[i]);sameValues&&!sameOptions&&this.requestUpdate()}resolveOccurrences(values,preferred=[]){const claimed=new Set,resolved=[];return values.forEach((value,index)=>{const hint=preferred.length===values.length?preferred[index]:preferred.find(option=>option?.value===value&&!claimed.has(option)),match=hint&&hint.value===value&&this.options.includes(hint)&&!claimed.has(hint)?hint:this.options.find(option=>option.value===value&&!claimed.has(option));match&&(claimed.add(match),resolved.push(match))}),resolved}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){this.barredFromValidation?this.validityController.setValidity({}):this.required&&this._selected.length===0?this.validityController.setValidity({valueMissing:!0},this.localize("selectValueMissing")):this.validityController.setValidity({}),this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred:this.barredFromValidation}),this._selected.length===0?this.internals.states?.add("blank"):this.internals.states?.delete("blank")}syncFormValue(){if(!this.multiple){this.internals.setFormValue(this._selected[0]??"");return}const state2=JSON.stringify(this._selected);if(!this.name){this.internals.setFormValue(null,state2);return}const data=new FormData;for(const value of this._selected)data.append(this.name,value);this.internals.setFormValue(data,state2)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formResetCallback(){this.touched=!1,this.hasInteracted=!1,this._restoredStateActive=!1,this._valueDirty=!1;const resetOptions=this._defaultSelectedOptions.length>0?this._defaultSelectedOptions:this.options.filter(option=>wasOptionInitiallySelected(option));this._defaultSelectedOptions.length===0&&resetOptions.length>0&&(this._defaultSelectedOptions=[...resetOptions],this._defaultSelected=resetOptions.map(option=>option.value));const defaults=new Set(resetOptions);for(const option of this.options)option[RESET_OPTION_SELECTED_FROM_OWNER](defaults.has(option));this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}formStateRestoreCallback(state2,reason){if(!this.multiple)this.value=typeof state2=="string"?state2:"";else{let restored=[];if(typeof state2=="string")try{const parsed=JSON.parse(state2);Array.isArray(parsed)&&parsed.every(entry=>typeof entry=="string")&&(restored=parsed)}catch{}this.value=restored}this._restoredStateActive=!0,this._valueDirty=!0}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,disabled&&this.forceCloseOpenState(),this.updateValidity(),this.requestUpdate()}checkValidity(){return this.updateValidity(),this.internals.checkValidity()}reportValidity(){return this.updateValidity(),this.hasInteracted=!0,this.reflectValidityStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.reflectValidityStates()}resetValidity(){this.setCustomValidity("")}disconnectedCallback(){this.releaseExternalDescription(),this.transitionToken++,super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.clearTypeAheadTimer(),this.typeAheadBuffer="",this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.unbindDocumentPointer(),this.resolveTransitionWaiters("lr-after-show"),this.resolveTransitionWaiters("lr-after-hide"),this.open=!1}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription(),this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.unbindDocumentPointer(),this.clearTypeAheadTimer(),queueMicrotask(()=>this.reconnectOpenPopup())}refreshOptionDefaults(){if(this.hasAttribute("default-value"))return;const declared=this.options.filter(option=>option.defaultSelected),defaults=this.multiple?declared:declared.slice(0,1);this._defaultSelected=defaults.map(option=>option.value),this._defaultSelectedOptions=[...defaults],!this._valueDirty&&!this._restoredStateActive&&this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}reflectSelected(){this._selectedOptions=this.resolveOccurrences(this._selected,this._selectedOptions),this._selectedValuesByOption=new Map(this._selectedOptions.map(option=>[option,option.value]));const chosen=new Set(this._selectedOptions);for(const option of this.options)option[SET_OPTION_SELECTED_FROM_OWNER](chosen.has(option))}labelFor(value,occurrenceIndex=0){return(this._selectedOptions[occurrenceIndex]?.value===value?this._selectedOptions[occurrenceIndex]?.label:void 0)??this._selectedOptions.find(option=>option.value===value)?.label??this.options.find(option=>option.value===value)?.label??value}get onlyOption(){if(!this.autoCommitSingleOption)return;const navigable=this.navigableOptions();return navigable.length===1?navigable[0]:void 0}isOptionAvailable(option){return!option.disabled&&!option.inert&&!option.closest("[inert]")}navigableOptions(options=this.options){return options.filter(option=>this.isOptionAvailable(option))}setActiveIndex(next,navigable=this.navigableOptions()){if(next<0||navigable.length===0){this.activeIndex=-1,this.activeOption=void 0;return}const index=Math.min(next,navigable.length-1);this.activeIndex=index,this.activeOption=navigable[index]}reconcileActiveOption(previousActive,previousRawIndex){if(!previousActive&&this.activeIndex<0)return;const navigable=this.navigableOptions();if(previousActive){const preservedIndex=navigable.indexOf(previousActive);if(preservedIndex>=0){this.setActiveIndex(preservedIndex,navigable);return}}if(navigable.length===0){this.setActiveIndex(-1,navigable);return}const pivot=Math.max(0,previousRawIndex);let nearestIndex=0,nearestDistance=Number.POSITIVE_INFINITY,nearestRawIndex=-1;navigable.forEach((option,index)=>{const rawIndex=this.options.indexOf(option),distance=Math.abs(rawIndex-pivot);(distance<nearestDistance||distance===nearestDistance&&rawIndex>=pivot&&nearestRawIndex<pivot)&&(nearestIndex=index,nearestDistance=distance,nearestRawIndex=rawIndex)}),this.setActiveIndex(nearestIndex,navigable)}show(){if(this.open||this.effectiveDisabled)return Promise.resolve();this.resolveTransitionWaiters("lr-after-hide");const settled=this.waitForTransition("lr-after-show");return this.open=!0,settled}hide(){if(!this.open)return Promise.resolve();this.resolveTransitionWaiters("lr-after-show");const settled=this.waitForTransition("lr-after-hide");return this.open=!1,settled}positionListbox(){this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=this.effectiveDirection;const anchor=this.renderRoot.querySelector('[part="trigger"]'),listbox=this.renderRoot.querySelector('[part="listbox"]');!anchor||!listbox||(this.cleanup=place(anchor,listbox,{placement:rtlAwarePlacement(this.placement,this),strategy:this.hoist?"fixed":"absolute"}),this.positioningReady=this.cleanup.ready)}activateListboxOverlay(){this.cleanup?.(),this.cleanup=void 0,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.triggerElement??null}),this.bindDocumentPointer(),this.positionListbox()}teardownListboxOverlay(restoreFocus=this.restoreFocusOnClose){this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.overlayHandle?.deactivate({restoreFocus}),this.overlayHandle=void 0,this.unbindDocumentPointer(),this.restoreFocusOnClose=!0}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument||this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument,this.pointerListener=listener,ownerDocument.addEventListener("pointerdown",listener,!0)}unbindDocumentPointer(){this.pointerListenerDocument&&this.pointerListener&&this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener,!0),this.pointerListenerDocument=void 0,this.pointerListener=void 0}reconnectOpenPopup(){!this.isConnected||!this.open||this.activateListboxOverlay()}updated(changed){super.updated(changed),this.syncExternalDescription();const suppressOpenLifecycle=changed.has("open")&&this.suppressedOpenLifecycleGeneration===this.openStateGeneration,shouldRefreshPosition=this.open&&this.isConnected&&(changed.has("placement")||changed.has("hoist")||this.positionedDirection!==this.effectiveDirection);changed.has("open")&&!this.openVetoed?this.open&&this.isConnected?(this.activateListboxOverlay(),!this._isFirstUpdate&&!suppressOpenLifecycle&&this.settleTransition("lr-after-show")):this.open?this.teardownListboxOverlay(!1):(this.teardownListboxOverlay(),!this._isFirstUpdate&&!suppressOpenLifecycle&&this.settleTransition("lr-after-hide")):changed.has("open")&&this.openVetoed?(this.restoreFocusOnClose=!0,shouldRefreshPosition&&this.positionListbox()):shouldRefreshPosition&&this.positionListbox(),(changed.has("touched")||changed.has("required")||changed.has("value"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),changed.has("open")&&(this.pendingOpenTransitionStart=void 0,this.suppressedOpenLifecycleGeneration=void 0)}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(event==="lr-after-show"){for(;this.open;){const readiness=this.positioningReady,positioned=await readiness;if(this.transitionToken!==token)return;if(positioned)break;if(readiness===this.positioningReady){this.forceCloseOpenState();return}}if(await this.updateComplete,this.transitionToken!==token)return}if(this.isConnected){const view=this.ownerDocument.defaultView;if(view&&await new Promise(resolve=>view.requestAnimationFrame(()=>resolve())),this.transitionToken!==token)return;const animations=this.renderRoot.querySelector('[part="listbox"]')?.getAnimations({subtree:!0})??[];if(await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),this.transitionToken!==token)return}this.emit(event),this.resolveTransitionWaiters(event)}}waitForTransition(event){return new Promise(resolve=>{const waiters=this.transitionWaiters.get(event)??new Set;waiters.add(resolve),this.transitionWaiters.set(event,waiters)})}resolveTransitionWaiters(event){const waiters=this.transitionWaiters.get(event);if(waiters){this.transitionWaiters.delete(event);for(const resolve of waiters)resolve()}}emitValueEvents(){dispatchNativeInputEvent(this),this.emit("lr-input",{value:this.value}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value})}selectOption(option){if(this.effectiveDisabled||!this.isOptionAvailable(option))return;if(this.hasInteracted=!0,this._restoredStateActive=!1,this._valueDirty=!0,this.multiple){const selectedIndex=this._selectedOptions.indexOf(option),selected=selectedIndex>=0,occurrences=selected?this._selectedOptions.filter((_,index)=>index!==selectedIndex):[...this._selectedOptions,option],values=selected?this._selected.filter((_,index)=>index!==selectedIndex):[...this._selected,option.value];this.setSelection(values,occurrences),this.emitValueEvents();return}const changed=option!==this._selectedOptions[0]||option.value!==this._selected[0];this.setSelection([option.value],[option]),this.hide(),changed&&this.emitValueEvents()}removeValueAt(index){this.effectiveDisabled||index<0||index>=this._selected.length||(this._restoredStateActive=!1,this._valueDirty=!0,this.setSelection(this._selected.filter((_,candidateIndex)=>candidateIndex!==index),this._selectedOptions.filter((_,candidateIndex)=>candidateIndex!==index)),this.emitValueEvents())}clear(){this.effectiveDisabled||this._selected.length===0||(this._restoredStateActive=!1,this._valueDirty=!0,this.setSelection([],[]),this.emitValueEvents(),this.emit("lr-clear"))}removeTag(value,index,event){event.stopPropagation(),this._selected[index]===value&&(this.removeValueAt(index),this.updateComplete.then(()=>{const buttons=[...this.renderRoot.querySelectorAll('[part~="tag__remove-button"]')];(buttons[Math.min(index,buttons.length-1)]??this.triggerElement)?.focus()}))}typeAhead(char){this.clearTypeAheadTimer(),this.typeAheadBuffer+=char.toLocaleLowerCase(this.effectiveLocale);const ownerWindow=this.ownerDocument.defaultView;if(this.isConnected&&ownerWindow){const generation=this.typeAheadTimerGeneration;this.typeAheadTimerWindow=ownerWindow,this.typeAheadTimer=ownerWindow.setTimeout(()=>{this.typeAheadTimerGeneration!==generation||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow||(this.typeAheadTimer=void 0,this.typeAheadTimerWindow=void 0,this.typeAheadBuffer="")},500)}const navigable=this.navigableOptions();if(!navigable.length)return;const currentOption=this.open?navigable[this.activeIndex]:this._selectedOptions[this._selectedOptions.length-1],currentIndex=navigable.indexOf(currentOption),n=navigable.length;for(let step=1;step<=n;step++){const idx=(currentIndex+step+n)%n,candidate=navigable[idx];if(candidate!==void 0&&candidate.label.toLocaleLowerCase(this.effectiveLocale).startsWith(this.typeAheadBuffer)){if(this.open){this.setActiveIndex(idx,navigable);return}if(this.multiple&&this._selectedOptions.includes(candidate))continue;this.selectOption(candidate);return}}}clearTypeAheadTimer(){this.typeAheadTimerGeneration+=1,this.typeAheadTimer!==void 0&&this.typeAheadTimerWindow?.clearTimeout(this.typeAheadTimer),this.typeAheadTimer=void 0,this.typeAheadTimerWindow=void 0}renderRows(options,activeId){const out=[],chosen=new Set(this._selectedOptions);let currentGroup,groupRows=[],groupIndex=0;const flushGroup=()=>{if(groupRows.length!==0){if(currentGroup){const labelId=`${this.listId}-group-${groupIndex++}`;out.push(html`<div role="group" aria-labelledby=${labelId}>
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{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{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";installFormControlLabelSupport();import{deferredPlaceReady as place}from"../../../internal/anchored-overlay-runtime.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{chevronIcon,closeIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{finiteCount}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./select.styles.js";import{sizes}from"../../../internal/sizes.styles.js";import"../combobox/option.class.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{omittedEmptyStringConverter}from"../../../internal/converters.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.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{tag}from"../../../internal/prefix.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_select,LYRA_DEFAULT_selectSelectedOverflow,LYRA_DEFAULT_selectValueMissing}from"../../../internal/default-strings.generated.js";function isLyraOptionElement(value){return isHtmlElement(value)&&value.localName===tag("option")}class LyraSelect extends LyraElement{static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,removeWithContext:LYRA_DEFAULT_removeWithContext,select:LYRA_DEFAULT_select,selectSelectedOverflow:LYRA_DEFAULT_selectSelectedOverflow,selectValueMissing:LYRA_DEFAULT_selectValueMissing}}static{this.immutableEventDetails=Object.freeze(["lr-input","lr-change"])}static get validators(){return[currentValidityValidator("required","disabled","value","multiple")]}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},value:{noAccessor:!0},name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},maxOptionsVisible:{type:Number,attribute:"max-options-visible",noAccessor:!0},defaultValue:{attribute:"default-value",noAccessor:!0}}}get open(){return this._open}set open(next){const requested=!!next,normalized=requested&&!this.effectiveDisabled;if(normalized===this._open){requested!==normalized&&this.hasAttribute("open")&&this.removeAttribute("open");return}this.applyOpenState(normalized)}focus(options){this.effectiveDisabled||this.triggerElement?.focus(options)}blur(){this.triggerElement?.blur()}click(){this.effectiveDisabled||this.triggerElement?.click()}constructor(){super(),this.placeholder="",this.label="",this.hint="",this.helpText="",this.withLabel=!1,this.withHint=!1,this.errorText="",this.autofocus=!1,this.title="",this._open=!1,this.size="m",this.appearance="outlined",this.pill=!1,this.placement="bottom",this.hoist=!1,this.filled=!1,this.withClear=!1,this.clearable=!1,this.autoCommitSingleOption=!1,this.activeIndex=-1,this.options=[],this.touched=!1,this.hasInteracted=!1,this.slotPresence=new SlotPresenceController(this),this._fieldsetDisabled=!1,this.listId=nextId("select-list"),this.triggerId=nextId("select-trigger"),this.valueTextId=nextId("select-value"),this.positioningReady=Promise.resolve(!1),this.restoreFocusOnClose=!0,this._isFirstUpdate=!0,this.openVetoed=!1,this.openStateGeneration=0,this.transitionToken=0,this.transitionWaiters=new Map,this._selected=[],this._selectedOptions=[],this._selectedValuesByOption=new Map,this._multiple=!1,this._disabled=!1,this._required=!1,this._defaultSelected=[],this._defaultSelectedOptions=[],this._defaultCaptured=!1,this._valueDirty=!1,this._restoredStateActive=!1,this._resolvingPendingInitialSelection=!1,this._defaultValueDirty=!1,this.typeAheadBuffer="",this.typeAheadTimerGeneration=0,this._name="",this._maxOptionsVisible=3,this.localDescriptionIds="",this.collectOptions=e=>{const slot=e.target,previous=new Set(this.options),previousActive=this.activeOption,previousActiveRawIndex=previousActive?this.options.indexOf(previousActive):this.activeIndex;if(this.options=slot.assignedElements({flatten:!0}).filter(isLyraOptionElement),this.reconcileActiveOption(previousActive,previousActiveRawIndex),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>0){const added=this.multiple?eligible:eligible.slice(-1),occurrences=this.multiple?[...new Set([...this._selectedOptions,...added])]:added;newLive.length>0&&(this._valueDirty=!0),this.setSelection(occurrences.map(option=>option.value),occurrences);return}}else{this._defaultCaptured=!0;const explicitDefault=this.hasAttribute("default-value")||this._defaultValueDirty,allDefaults=this.options.filter(option=>option.defaultSelected),defaults=this.multiple?allDefaults:allDefaults.slice(0,1),allLive=this.options.filter(option=>option.selected),live=this.multiple?allLive:allLive.slice(0,1),initialLive=this.options.filter(option=>wasOptionInitiallySelected(option)),optionDirty=this.options.some(option=>isOptionSelectedDirty(option)),dirtySelected=this.options.filter(option=>isOptionSelectedDirty(option)&&option.selected);if(explicitDefault)this._defaultSelectedOptions=this.resolveOccurrences(this._defaultSelected);else{const resetOptions=defaults.length>0?defaults:initialLive.length>0?initialLive:live;this._defaultSelected=resetOptions.map(option=>option.value),this._defaultSelectedOptions=[...resetOptions]}const fromDefaults=explicitDefault||defaults.length>0,initial=optionDirty?this.multiple?allLive:dirtySelected.slice(-1)[0]?dirtySelected.slice(-1):live:explicitDefault?this._defaultSelectedOptions:fromDefaults?defaults:live;if(initial.length>0&&!this._restoredStateActive&&!this._valueDirty){(!fromDefaults||optionDirty)&&(this._valueDirty=!0),this.setSelection(initial.map(option=>option.value),[...initial]);return}if(optionDirty&&(this._valueDirty=!0),explicitDefault&&!this._valueDirty&&!this._restoredStateActive){this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions]);return}}this.reflectSelected()},this.onOptionChange=e=>{e.stopPropagation();const option=e.composedPath().find(isLyraOptionElement);if(isLyraOptionElement(option)&&this.options.includes(option)&&isOptionSelectedWrite(e)){this._valueDirty=!0,this._restoredStateActive=!1;const selected=this._selectedOptions.includes(option);if(option.selected===selected&&(!selected||this._selectedValuesByOption.get(option)===option.value))return;if(option.selected&&!this.multiple){this.setSelection([option.value],[option]);return}const remaining=[...this._selectedOptions],preferred=this._selected.map(value=>{const index2=remaining.findIndex(candidate=>this._selectedValuesByOption.get(candidate)===value);return index2<0?void 0:remaining.splice(index2,1)[0]}),values=[...this._selected],index=preferred.indexOf(option);if(option.selected)index<0?(values.push(option.value),preferred.push(option)):values[index]=option.value;else{if(index<0)return;values.splice(index,1),preferred.splice(index,1)}this.setSelection(values,preferred);return}const previousActive=this.activeOption,previousActiveRawIndex=previousActive?this.options.indexOf(previousActive):this.activeIndex;queueMicrotask(()=>{this.refreshOptionDefaults(),this.reflectSelected(),this.options=[...this.options],this.reconcileActiveOption(previousActive,previousActiveRawIndex)})},this.onDocPointer=e=>{if(!e.composedPath().includes(this)){if(this.overlayHandle?.isActive()){this.overlayHandle.dismissBackdrop();return}this.restoreFocusOnClose=!1,this.hide()}},this.onTriggerClick=()=>{if(!this.effectiveDisabled){if(this.onlyOption)return this.selectOption(this.onlyOption);this.open?this.hide():this.show()}},this.onTriggerBlur=event=>{this.effectiveDisabled||(this.touched=!0,this.hasInteracted=!0,this.reflectValidityStates()),this.open&&(this.restoreFocusOnClose=!1),this.hide(),relayNativeEvent(this,event)},this.onTriggerFocus=event=>{relayNativeEvent(this,event)},this.onKeyDown=e=>{const navigable=this.navigableOptions();switch(e.key){case"ArrowDown":if(e.preventDefault(),this.onlyOption)return this.selectOption(this.onlyOption);if(!this.open){this.show();return}this.setActiveIndex(Math.min(navigable.length-1,this.activeIndex+1),navigable);break;case"ArrowUp":if(e.preventDefault(),this.onlyOption)return this.selectOption(this.onlyOption);if(!this.open){this.show();return}this.setActiveIndex(Math.max(0,this.activeIndex-1),navigable);break;case"Enter":case" ":if(this.open){e.preventDefault();const active=navigable[this.activeIndex];this.activeIndex>=0&&active?this.selectOption(active):this.hide()}break;case"Escape":this.open&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(e.preventDefault(),this.hide());break;case"Home":this.open&&(e.preventDefault(),this.setActiveIndex(0,navigable));break;case"End":this.open&&(e.preventDefault(),this.setActiveIndex(navigable.length-1,navigable));break;case"Backspace":case"Delete":this.multiple&&this._selected.length>0&&(e.preventDefault(),this.removeValueAt(this._selected.length-1));break;default:e.key.length===1&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&this.typeAhead(e.key);break}},this.onListboxMouseDown=e=>{e.preventDefault()},this.onListboxClick=e=>{const optionEl=e.target.closest('[part="option"]'),index=Number(optionEl?.dataset.index);if(!Number.isInteger(index))return;const option=this.options[index];option&&this.selectOption(option)},installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),this.syncFormValue()}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"]')??null}syncExternalDescription(){if(!this.isConnected)return;const target=this.renderRoot.querySelector('[part="trigger"]');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.open&&queueMicrotask(()=>this.reconnectOpenPopup())}willUpdate(changed){if(super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,this._isFirstUpdate&&(this._pendingInitialDefaultValue!==void 0||this._pendingInitialValue!==void 0||this._pendingInitialSelectedOptions!==void 0)){this._resolvingPendingInitialSelection=!0;try{if(this._pendingInitialDefaultValue!==void 0){const pending=this._pendingInitialDefaultValue;this._pendingInitialDefaultValue=void 0,this.defaultValue=pending}if(this._pendingInitialValue!==void 0){const pending=this._pendingInitialValue;this._pendingInitialValue=void 0,this.value=pending}if(this._pendingInitialSelectedOptions!==void 0){const pending=this._pendingInitialSelectedOptions;this._pendingInitialSelectedOptions=void 0,this.selectedOptions=pending}}finally{this._resolvingPendingInitialSelection=!1}}this.announceOpenTransition(changed),changed.has("open")&&!this.open&&!this.openVetoed&&this.setActiveIndex(-1)}applyOpenState(next){const old=this._open;this.pendingOpenTransitionStart===void 0&&(this.pendingOpenTransitionStart=old),this.openStateGeneration++,this._open=next,this.requestUpdate("open",old)}forceCloseOpenState(){const isClosing=this._open||this.pendingOpenTransitionStart===!0;if(this.transitionToken++,this.resolveTransitionWaiters("lr-after-show"),this.resolveTransitionWaiters("lr-after-hide"),!this._open){isClosing&&(this.suppressedOpenLifecycleGeneration=this.openStateGeneration),this.hasAttribute("open")&&this.removeAttribute("open");return}this.applyOpenState(!1),this.suppressedOpenLifecycleGeneration=this.openStateGeneration}announceOpenTransition(changed){if(this.openVetoed=!1,!changed.has("open")||this._isFirstUpdate||this.suppressedOpenLifecycleGeneration===this.openStateGeneration)return;const name=this.open?"lr-show":"lr-hide";if(!this.isConnected){this.emit("lr-hide");return}this.emit(name,null,{cancelable:!0}).defaultPrevented&&(this.openVetoed=!0,this.open=!this.open,this.resolveTransitionWaiters(this.open?"lr-after-hide":"lr-after-show"))}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("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._multiple&&this._selected.length>1?this.setSelection(this._selected.slice(0,1),this._selectedOptions.slice(0,1)):this.syncFormValue(),this.requestUpdate("multiple",old)}get maxOptionsVisible(){return this._maxOptionsVisible}set maxOptionsVisible(next){const old=this._maxOptionsVisible;this._maxOptionsVisible=finiteCount(next,3),this.requestUpdate("maxOptionsVisible",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._disabled&&this.forceCloseOpenState(),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 value(){return this.multiple?[...this._selected]:this._selected[0]??""}set value(next){!this.hasUpdated&&!this._resolvingPendingInitialSelection&&(this._pendingInitialValue=next),this._restoredStateActive=!1,this._valueDirty=!0;const values=(Array.isArray(next)?next:next?[next]:[]).filter(value=>typeof value=="string");this.setSelection(values,values.map(value=>this.options.find(option=>option.value===value)))}get defaultValue(){return this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??""}set defaultValue(next){!this.hasUpdated&&!this._resolvingPendingInitialSelection&&(this._pendingInitialDefaultValue=next),this._defaultValueDirty=!0;const old=this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??"",values=(Array.isArray(next)?next:next?[next]:[]).filter(value=>typeof value=="string");this._defaultSelected=this.multiple?[...values]:values.slice(0,1),this._defaultSelectedOptions=this.resolveOccurrences(this._defaultSelected),!this._valueDirty&&!this._restoredStateActive&&this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions]),this.requestUpdate("defaultValue",old)}get selectedOptions(){return[...this._selectedOptions]}set selectedOptions(next){!this.hasUpdated&&!this._resolvingPendingInitialSelection&&(this._pendingInitialSelectedOptions=next),this._restoredStateActive=!1,this._valueDirty=!0;const candidates=Array.isArray(next)?next:[],live=candidates.filter((option,index)=>isLyraOptionElement(option)&&this.contains(option)&&this.options.includes(option)&&candidates.indexOf(option)===index),selected=this.multiple?live:live.slice(0,1);this.setSelection(selected.map(option=>option.value),selected)}setSelection(next,preferred=[]){const values=this.multiple?[...next]:next.slice(0,1),previousValues=this._selected,previousOptions=this._selectedOptions,old=this.multiple?[...previousValues]:previousValues[0]??"";this._selected=values,this._selectedOptions=this.resolveOccurrences(values,preferred),this.syncFormValue(),this.reflectSelected(),this.updateValidity(),this.requestUpdate("value",old);const sameValues=previousValues.length===values.length&&previousValues.every((value,i)=>value===values[i]),sameOptions=previousOptions.length===this._selectedOptions.length&&previousOptions.every((option,i)=>option===this._selectedOptions[i]);sameValues&&!sameOptions&&this.requestUpdate()}resolveOccurrences(values,preferred=[]){const claimed=new Set,resolved=[];return values.forEach((value,index)=>{const hint=preferred.length===values.length?preferred[index]:preferred.find(option=>option?.value===value&&!claimed.has(option)),match=hint&&hint.value===value&&this.options.includes(hint)&&!claimed.has(hint)?hint:this.options.find(option=>option.value===value&&!claimed.has(option));match&&(claimed.add(match),resolved.push(match))}),resolved}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){this.barredFromValidation?this.validityController.setValidity({}):this.required&&this._selected.length===0?this.validityController.setValidity({valueMissing:!0},this.localize("selectValueMissing")):this.validityController.setValidity({}),this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred:this.barredFromValidation}),this._selected.length===0?this.internals.states?.add("blank"):this.internals.states?.delete("blank")}syncFormValue(){if(!this.multiple){this.internals.setFormValue(this._selected[0]??"");return}const state2=JSON.stringify(this._selected);if(!this.name){this.internals.setFormValue(null,state2);return}const data=new FormData;for(const value of this._selected)data.append(this.name,value);this.internals.setFormValue(data,state2)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formResetCallback(){this.touched=!1,this.hasInteracted=!1,this._restoredStateActive=!1,this._valueDirty=!1;const resetOptions=this._defaultSelectedOptions.length>0?this._defaultSelectedOptions:this.options.filter(option=>wasOptionInitiallySelected(option));this._defaultSelectedOptions.length===0&&resetOptions.length>0&&(this._defaultSelectedOptions=[...resetOptions],this._defaultSelected=resetOptions.map(option=>option.value));const defaults=new Set(resetOptions);for(const option of this.options)option[RESET_OPTION_SELECTED_FROM_OWNER](defaults.has(option));this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}formStateRestoreCallback(state2,reason){if(!this.multiple)this.value=typeof state2=="string"?state2:"";else{let restored=[];if(typeof state2=="string")try{const parsed=JSON.parse(state2);Array.isArray(parsed)&&parsed.every(entry=>typeof entry=="string")&&(restored=parsed)}catch{}this.value=restored}this._restoredStateActive=!0,this._valueDirty=!0}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,disabled&&this.forceCloseOpenState(),this.updateValidity(),this.requestUpdate()}checkValidity(){return this.updateValidity(),this.internals.checkValidity()}reportValidity(){return this.updateValidity(),this.hasInteracted=!0,this.reflectValidityStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.reflectValidityStates()}resetValidity(){this.setCustomValidity("")}disconnectedCallback(){this.releaseExternalDescription(),this.transitionToken++,super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.clearTypeAheadTimer(),this.typeAheadBuffer="",this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.unbindDocumentPointer(),this.resolveTransitionWaiters("lr-after-show"),this.resolveTransitionWaiters("lr-after-hide"),this.open=!1}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription(),this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.unbindDocumentPointer(),this.clearTypeAheadTimer(),queueMicrotask(()=>this.reconnectOpenPopup())}refreshOptionDefaults(){if(this.hasAttribute("default-value")||this._defaultValueDirty)return;const declared=this.options.filter(option=>option.defaultSelected),defaults=this.multiple?declared:declared.slice(0,1);this._defaultSelected=defaults.map(option=>option.value),this._defaultSelectedOptions=[...defaults],!this._valueDirty&&!this._restoredStateActive&&this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}reflectSelected(){this._selectedOptions=this.resolveOccurrences(this._selected,this._selectedOptions),this._selectedValuesByOption=new Map(this._selectedOptions.map(option=>[option,option.value]));const chosen=new Set(this._selectedOptions);for(const option of this.options)option[SET_OPTION_SELECTED_FROM_OWNER](chosen.has(option))}labelFor(value,occurrenceIndex=0){return(this._selectedOptions[occurrenceIndex]?.value===value?this._selectedOptions[occurrenceIndex]?.label:void 0)??this._selectedOptions.find(option=>option.value===value)?.label??this.options.find(option=>option.value===value)?.label??value}get onlyOption(){if(!this.autoCommitSingleOption)return;const navigable=this.navigableOptions();return navigable.length===1?navigable[0]:void 0}isOptionAvailable(option){return!option.disabled&&!option.inert&&!option.closest("[inert]")}navigableOptions(options=this.options){return options.filter(option=>this.isOptionAvailable(option))}setActiveIndex(next,navigable=this.navigableOptions()){if(next<0||navigable.length===0){this.activeIndex=-1,this.activeOption=void 0;return}const index=Math.min(next,navigable.length-1);this.activeIndex=index,this.activeOption=navigable[index]}reconcileActiveOption(previousActive,previousRawIndex){if(!previousActive&&this.activeIndex<0)return;const navigable=this.navigableOptions();if(previousActive){const preservedIndex=navigable.indexOf(previousActive);if(preservedIndex>=0){this.setActiveIndex(preservedIndex,navigable);return}}if(navigable.length===0){this.setActiveIndex(-1,navigable);return}const pivot=Math.max(0,previousRawIndex);let nearestIndex=0,nearestDistance=Number.POSITIVE_INFINITY,nearestRawIndex=-1;navigable.forEach((option,index)=>{const rawIndex=this.options.indexOf(option),distance=Math.abs(rawIndex-pivot);(distance<nearestDistance||distance===nearestDistance&&rawIndex>=pivot&&nearestRawIndex<pivot)&&(nearestIndex=index,nearestDistance=distance,nearestRawIndex=rawIndex)}),this.setActiveIndex(nearestIndex,navigable)}show(){if(this.open||this.effectiveDisabled)return Promise.resolve();this.resolveTransitionWaiters("lr-after-hide");const settled=this.waitForTransition("lr-after-show");return this.open=!0,settled}hide(){if(!this.open)return Promise.resolve();this.resolveTransitionWaiters("lr-after-show");const settled=this.waitForTransition("lr-after-hide");return this.open=!1,settled}positionListbox(){this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=this.effectiveDirection;const anchor=this.renderRoot.querySelector('[part="trigger"]'),listbox=this.renderRoot.querySelector('[part="listbox"]');!anchor||!listbox||(this.cleanup=place(anchor,listbox,{placement:rtlAwarePlacement(this.placement,this),strategy:this.hoist?"fixed":"absolute"}),this.positioningReady=this.cleanup.ready)}activateListboxOverlay(){this.cleanup?.(),this.cleanup=void 0,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.triggerElement??null}),this.bindDocumentPointer(),this.positionListbox()}teardownListboxOverlay(restoreFocus=this.restoreFocusOnClose){this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.overlayHandle?.deactivate({restoreFocus}),this.overlayHandle=void 0,this.unbindDocumentPointer(),this.restoreFocusOnClose=!0}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument||this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument,this.pointerListener=listener,ownerDocument.addEventListener("pointerdown",listener,!0)}unbindDocumentPointer(){this.pointerListenerDocument&&this.pointerListener&&this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener,!0),this.pointerListenerDocument=void 0,this.pointerListener=void 0}reconnectOpenPopup(){!this.isConnected||!this.open||this.activateListboxOverlay()}updated(changed){super.updated(changed),this.syncExternalDescription();const suppressOpenLifecycle=changed.has("open")&&this.suppressedOpenLifecycleGeneration===this.openStateGeneration,shouldRefreshPosition=this.open&&this.isConnected&&(changed.has("placement")||changed.has("hoist")||this.positionedDirection!==this.effectiveDirection);changed.has("open")&&!this.openVetoed?this.open&&this.isConnected?(this.activateListboxOverlay(),!this._isFirstUpdate&&!suppressOpenLifecycle&&this.settleTransition("lr-after-show")):this.open?this.teardownListboxOverlay(!1):(this.teardownListboxOverlay(),!this._isFirstUpdate&&!suppressOpenLifecycle&&this.settleTransition("lr-after-hide")):changed.has("open")&&this.openVetoed?(this.restoreFocusOnClose=!0,shouldRefreshPosition&&this.positionListbox()):shouldRefreshPosition&&this.positionListbox(),(changed.has("touched")||changed.has("required")||changed.has("value"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),changed.has("open")&&(this.pendingOpenTransitionStart=void 0,this.suppressedOpenLifecycleGeneration=void 0)}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(event==="lr-after-show"){for(;this.open;){const readiness=this.positioningReady,positioned=await readiness;if(this.transitionToken!==token)return;if(positioned)break;if(readiness===this.positioningReady){this.forceCloseOpenState();return}}if(await this.updateComplete,this.transitionToken!==token)return}if(this.isConnected){const view=this.ownerDocument.defaultView;if(view&&await new Promise(resolve=>view.requestAnimationFrame(()=>resolve())),this.transitionToken!==token)return;const animations=this.renderRoot.querySelector('[part="listbox"]')?.getAnimations({subtree:!0})??[];if(await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),this.transitionToken!==token)return}this.emit(event),this.resolveTransitionWaiters(event)}}waitForTransition(event){return new Promise(resolve=>{const waiters=this.transitionWaiters.get(event)??new Set;waiters.add(resolve),this.transitionWaiters.set(event,waiters)})}resolveTransitionWaiters(event){const waiters=this.transitionWaiters.get(event);if(waiters){this.transitionWaiters.delete(event);for(const resolve of waiters)resolve()}}emitValueEvents(){dispatchNativeInputEvent(this),this.emit("lr-input",{value:this.value}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value})}selectOption(option){if(this.effectiveDisabled||!this.isOptionAvailable(option))return;if(this.hasInteracted=!0,this._restoredStateActive=!1,this._valueDirty=!0,this.multiple){const selectedIndex=this._selectedOptions.indexOf(option),selected=selectedIndex>=0,occurrences=selected?this._selectedOptions.filter((_,index)=>index!==selectedIndex):[...this._selectedOptions,option],values=selected?this._selected.filter((_,index)=>index!==selectedIndex):[...this._selected,option.value];this.setSelection(values,occurrences),this.emitValueEvents();return}const changed=option!==this._selectedOptions[0]||option.value!==this._selected[0];this.setSelection([option.value],[option]),this.hide(),changed&&this.emitValueEvents()}removeValueAt(index){this.effectiveDisabled||index<0||index>=this._selected.length||(this._restoredStateActive=!1,this._valueDirty=!0,this.setSelection(this._selected.filter((_,candidateIndex)=>candidateIndex!==index),this._selectedOptions.filter((_,candidateIndex)=>candidateIndex!==index)),this.emitValueEvents())}clear(){this.effectiveDisabled||this._selected.length===0||(this._restoredStateActive=!1,this._valueDirty=!0,this.setSelection([],[]),this.emitValueEvents(),this.emit("lr-clear"))}removeTag(value,index,event){event.stopPropagation(),this._selected[index]===value&&(this.removeValueAt(index),this.updateComplete.then(()=>{const buttons=[...this.renderRoot.querySelectorAll('[part~="tag__remove-button"]')];(buttons[Math.min(index,buttons.length-1)]??this.triggerElement)?.focus()}))}typeAhead(char){this.clearTypeAheadTimer(),this.typeAheadBuffer+=char.toLocaleLowerCase(this.effectiveLocale);const ownerWindow=this.ownerDocument.defaultView;if(this.isConnected&&ownerWindow){const generation=this.typeAheadTimerGeneration;this.typeAheadTimerWindow=ownerWindow,this.typeAheadTimer=ownerWindow.setTimeout(()=>{this.typeAheadTimerGeneration!==generation||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow||(this.typeAheadTimer=void 0,this.typeAheadTimerWindow=void 0,this.typeAheadBuffer="")},500)}const navigable=this.navigableOptions();if(!navigable.length)return;const currentOption=this.open?navigable[this.activeIndex]:this._selectedOptions[this._selectedOptions.length-1],currentIndex=navigable.indexOf(currentOption),n=navigable.length;for(let step=1;step<=n;step++){const idx=(currentIndex+step+n)%n,candidate=navigable[idx];if(candidate!==void 0&&candidate.label.toLocaleLowerCase(this.effectiveLocale).startsWith(this.typeAheadBuffer)){if(this.open){this.setActiveIndex(idx,navigable);return}if(this.multiple&&this._selectedOptions.includes(candidate))continue;this.selectOption(candidate);return}}}clearTypeAheadTimer(){this.typeAheadTimerGeneration+=1,this.typeAheadTimer!==void 0&&this.typeAheadTimerWindow?.clearTimeout(this.typeAheadTimer),this.typeAheadTimer=void 0,this.typeAheadTimerWindow=void 0}renderRows(options,activeId){const out=[],chosen=new Set(this._selectedOptions);let currentGroup,groupRows=[],groupIndex=0;const flushGroup=()=>{if(groupRows.length!==0){if(currentGroup){const labelId=`${this.listId}-group-${groupIndex++}`;out.push(html`<div role="group" aria-labelledby=${labelId}>
|
|
2
2
|
<div id=${labelId} class="group-label" part="group-label">${currentGroup}</div>
|
|
3
3
|
${groupRows}
|
|
4
4
|
</div>`)}else out.push(...groupRows);groupRows=[]}};return options.forEach((o,i)=>{o.group!==currentGroup&&(flushGroup(),currentGroup=o.group);const id=`${this.listId}-opt-${i}`,selected=chosen.has(o);groupRows.push(html`<div
|
|
@@ -295,7 +295,10 @@ private autofocusFrame?;
|
|
|
295
295
|
* or `null`. Also names the handle the eventual `lr-change` reports. */
|
|
296
296
|
private pendingKeyHandle;
|
|
297
297
|
/** The focused handle, tracked only to decide tooltip visibility. */
|
|
298
|
-
private focusedHandle;private rangeFocusTransfer?;private rangeFocusGeneration;private externalDescriptionLease?;
|
|
298
|
+
private focusedHandle;private rangeFocusTransfer?;private rangeFocusGeneration;private externalDescriptionLease?;
|
|
299
|
+
/** Second handle's lease while `range` -- a two-handle slider has no single "the thumb" a host
|
|
300
|
+
* `aria-describedby` could bind to, so both handles pick up the same external description. */
|
|
301
|
+
private externalDescriptionLeaseMax?;private syncExternalDescription;private releaseExternalDescription;connectedCallback():void;
|
|
299
302
|
/**
|
|
300
303
|
* `readonly` is a plain reactive property, and the platform reads its reflected *attribute* when
|
|
301
304
|
* it answers `internals.willValidate` — so the barred recomputation behind the validity custom
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";installFormControlLabelSupport();import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{sizes}from"../../../internal/sizes.styles.js";import{isRtl}from"../../../internal/rtl.js";import{finiteInterpolate,finiteNumber,finiteRange,finiteRatio,isSliderKey}from"../../../internal/numbers.js";import{clampSteppedValue}from"../../../internal/step-value.js";import{styles}from"./slider.styles.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{activeElementIn}from"../../../internal/active-element.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_rangeEnd,LYRA_DEFAULT_rangeStart,LYRA_DEFAULT_sliderLabel}from"../../../internal/default-strings.generated.js";const PAGE_STEP_MULTIPLIER=10,MAX_MARKER_INTERVALS=100,falseDefaultBooleanConverter={fromAttribute:value=>value!==null&&value!=="false"},HINT_ID="slider-hint",ERROR_ID="slider-error",LABEL_ID="slider-label";class LyraSliderBase extends LyraElement{}class LyraSlider extends LyraSliderBase{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,rangeEnd:LYRA_DEFAULT_rangeEnd,rangeStart:LYRA_DEFAULT_rangeStart,sliderLabel:LYRA_DEFAULT_sliderLabel}}static get validators(){return[currentValidityValidator("required","disabled","value","min","max","step")]}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:"value",type:Number,reflect:!0,useDefault:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},min:{type:Number,noAccessor:!0},max:{type:Number,noAccessor:!0},step:{type:Number,noAccessor:!0},range:{type:Boolean,reflect:!0,noAccessor:!0},minValue:{type:Number,attribute:"min-value",noAccessor:!0},maxValue:{type:Number,attribute:"max-value",noAccessor:!0},size:{reflect:!0}}}captureValueBatch(){return this.pendingValueBatch||(this.pendingValueBatch={value:this._value,min:this._minValue,max:this._maxValue},this.requestUpdate()),this.pendingValueBatch}constructor(){super(),this.size="m",this._value=0,this._defaultValue=0,this._valueDirty=!1,this.settingDefaultValue=!1,this.reflectingDefaultValue=!1,this._name=null,this._required=!1,this._disabled=!1,this._fieldsetDisabled=!1,this._hasInteracted=!1,this._min=0,this._max=100,this._step=1,this._range=!1,this._minValue=0,this._maxValue=50,this._minValueDirty=!1,this._maxValueDirty=!1,this.applyingRangeValueAttribute=!1,this._defaultMinValue=0,this._defaultMaxValue=50,this.label="",this.hint="",this.helpText="",this.errorText="",this.withLabel=!1,this.withHint=!1,this.autofocus=!1,this.orientation="horizontal",this.readonly=!1,this.withMarkers=!1,this.withTooltip=!1,this.tooltipPlacement="top",this.tooltipDistance=8,this.tooltip="none",this.showValue=!1,this.valueDisplay="numeric",this.valuePlacement="inline",this.hasHintSlot=!1,this.hasErrorSlot=!1,this.hasLabelSlot=!1,this.hasReferenceSlot=!1,this.drags=new Map,this.pendingKeyHandle=null,this.focusedHandle=null,this.rangeFocusGeneration=0,this.markInteracted=()=>{this._hasInteracted||(this._hasInteracted=!0,this.syncValidityStates())},this.markFocusoutInteracted=()=>{this.effectiveDisabled||this.markInteracted()},this.onKeyDown=(handle,e)=>{if(!this.interactive)return;const current=this.valueForHandle(handle),rtl=isRtl(this),forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft",bounds=this.reachableBounds(handle),move=next=>{e.preventDefault(),this.assignValueFor(handle,next)&&(this.pendingKeyHandle=handle,this.emitInput(handle))};e.key===forwardKey||e.key==="ArrowUp"?move(this.directionalStep(current,1)):e.key===backwardKey||e.key==="ArrowDown"?move(this.directionalStep(current,-1)):e.key==="PageUp"?move(this.directionalStep(current,PAGE_STEP_MULTIPLIER)):e.key==="PageDown"?move(this.directionalStep(current,-PAGE_STEP_MULTIPLIER)):e.key==="Home"?move(bounds.min):e.key==="End"&&move(bounds.max)},this.onKeyUp=e=>{if(!this.interactive||!isSliderKey(e.key))return;const handle=this.pendingKeyHandle;handle!==null&&(this.pendingKeyHandle=null,this.emitChange(handle))},this.onPointerDown=(handle,e)=>{!this.interactive||e.button!==0||this.beginDrag(e.pointerId,handle,e.target,this.trackRect(),isRtl(this))},this.onBasePointerDown=e=>{if(!this.interactive||e.button!==0)return;const thumbs=Array.from(this.renderRoot.querySelectorAll('[part~="thumb"]'));if(thumbs.length===0||thumbs.includes(e.target))return;const rect=this.trackRect();if(!rect)return;const rtl=isRtl(this),{lo,hi}=this.domain(),target=finiteInterpolate(lo,hi,this.ratioFromPointer(e,rect,rtl)),handle=this.range?this.nearestHandle(target):"value",thumb=this.handleElement(handle)??thumbs[0];if(!thumb)return;const drag=this.beginDrag(e.pointerId,handle,thumb,rect,rtl);drag&&(this.setValueFor(handle,target,!1)&&(drag.changed=!0),thumb.focus())},this.onPointerMove=e=>{const drag=this.drags.get(e.pointerId);if(drag===void 0)return;if(!this.interactive){this.endDrag(e.pointerId,!1);return}if(!drag.rect)return;const{lo,hi}=this.domain(),value=finiteInterpolate(lo,hi,this.ratioFromPointer(e,drag.rect,drag.rtl));this.setValueFor(drag.handle,value,!1)&&(drag.changed=!0)},this.onPointerUp=e=>{this.endDrag(e.pointerId,e.type==="pointerup"&&this.interactive)},this.onSlotChange=event=>{const slot=event.target;(slot.name==="hint"||slot.name==="help-text")&&(this.hasHintSlot=this.slotsHaveContent(["hint","help-text"])),slot.name==="error"&&(this.hasErrorSlot=this.slotsHaveContent(["error"])),slot.name==="label"&&(this.hasLabelSlot=this.slotsHaveContent(["label"])),slot.name==="reference"&&(this.hasReferenceSlot=this.slotsHaveContent(["reference"]))},this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.internals.setFormValue("0","0"),this.addEventListener("input",this.markInteracted),this.addEventListener("change",this.markInteracted),this.addEventListener("focusout",this.markFocusoutInteracted),this.syncValidityStates()}get value(){return this._value}set value(next){const old=this._value;this.settingDefaultValue||(this._valueDirty=!0);const raw=finiteNumber(Number(next),this.defaultNumericValue());this.captureValueBatch().value=raw,this._value=this.clampValue(raw),this.syncFormValue(),this.requestUpdate("value",old)}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next==null?0:finiteNumber(Number(next),0),this.reflectingDefaultValue=!0;try{next==null?this.removeAttribute("value"):this.setAttribute("value",String(this._defaultValue))}finally{this.reflectingDefaultValue=!1}this._valueDirty||this.restoreLiveValueFromDefault(),this.requestUpdate("defaultValue",old)}get valueAsNumber(){return this.value}set valueAsNumber(next){this.value=next}get valueAsString(){return String(this.value)}set valueAsString(next){this.value=next}get name(){return this._name}set name(next){const old=this._name;this._name=next||null,this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),this.syncFormValue(),this.requestUpdate("name",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 disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._disabled&&(this.pendingKeyHandle=null,this.abortActiveDrags()),this.syncInteractionStates(),this.syncValidityStates(),this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}get min(){return this._min}set min(next){this.captureValueBatch();const old=this._min;this._min=finiteNumber(next,0),this.requestUpdate("min",old),this.sanitizeCurrentValue()}get max(){return this._max}set max(next){this.captureValueBatch();const old=this._max;this._max=finiteNumber(next,100),this.requestUpdate("max",old),this.sanitizeCurrentValue()}get step(){return this._step}set step(next){this.captureValueBatch();const old=this._step;this._step=next==null?1:finiteRange(next,0,0),this.requestUpdate("step",old),this.sanitizeCurrentValue()}get range(){return this._range}set range(next){const old=this._range;this._range=!!next,this.requestUpdate("range",old),this.syncFormValue()}get isRange(){return this.range}get minValue(){return this._minValue}set minValue(next){const batch=this.captureValueBatch();batch.min=finiteNumber(next,0),batch.lastRange="min";const old=this._minValue;if(this.applyingRangeValueAttribute||(this._minValueDirty=!0),this._minValue=this.clampValue(finiteNumber(next,0)),this._minValue>this._maxValue){const oldMax=this._maxValue;this._maxValue=this._minValue,this.applyingRangeValueAttribute||(this._maxValueDirty=!0),this.requestUpdate("maxValue",oldMax)}this.syncFormValue(),this.requestUpdate("minValue",old)}get maxValue(){return this._maxValue}set maxValue(next){const batch=this.captureValueBatch();batch.max=finiteNumber(next,50),batch.lastRange="max";const old=this._maxValue;if(this.applyingRangeValueAttribute||(this._maxValueDirty=!0),this._maxValue=this.clampValue(finiteNumber(next,50)),this._maxValue<this._minValue){const oldMin=this._minValue;this._minValue=this._maxValue,this.applyingRangeValueAttribute||(this._minValueDirty=!0),this.requestUpdate("minValue",oldMin)}this.syncFormValue(),this.requestUpdate("maxValue",old)}requestUpdate(name,oldValue,options){name==="readonly"&&this.readonly&&(this.pendingKeyHandle=null,this.abortActiveDrags()),super.requestUpdate(name,oldValue,options)}syncExternalDescription(){const target=this.isConnected&&!this.range?this.firstThumb():null;if(!target){this.releaseExternalDescription();return}this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby")}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this._valueDirty?this.sanitizeCurrentValue():this.restoreLiveValueFromDefault(),this._minValueDirty||(this._minValue=this.clampValue(this._defaultMinValue)),this._maxValueDirty||(this._maxValue=this.clampValue(this._defaultMaxValue)),this.sanitizeHandles();const slots=Array.from(this.children??[],child=>child.getAttribute("slot"));this.hasHintSlot=slots.some(slot=>slot==="hint"||slot==="help-text"),this.hasErrorSlot=slots.includes("error"),this.hasLabelSlot=slots.includes("label"),this.hasReferenceSlot=slots.includes("reference"),this.syncFormValue(),this.updateValidity(),this.syncInteractionStates()}willUpdate(changed){if(super.willUpdate(changed),this.pendingValueBatch&&(this.sanitizeCurrentValue(),this.pendingValueBatch=void 0),!changed.has("range")||!this.hasUpdated)return;const active=activeElementIn(this.shadowRoot);if(active?.matches('[part~="thumb"]')){const target=this.range?"min":"value";this.rangeFocusTransfer={origin:active,target},this.focusedHandle=target,this.syncInteractionStates(),this.rangeFocusGeneration++}this.pendingKeyHandle=null,this.abortActiveDrags()}updated(changed){if(super.updated(changed),this.syncExternalDescription(),changed.has("readonly")&&this.syncValidityStates(),!changed.has("range"))return;const transfer=this.rangeFocusTransfer;if(this.rangeFocusTransfer=void 0,!transfer)return;const generation=this.rangeFocusGeneration;this.scheduleAfterUpdate(()=>{if(generation!==this.rangeFocusGeneration||!this.isConnected||this.effectiveDisabled)return;const internalActive=activeElementIn(this.shadowRoot),documentActive=activeElementIn(this.ownerDocument),focusStayedAtOrigin=internalActive===transfer.origin,originWasRemovedWithoutReplacement=internalActive===null&&(documentActive===null||documentActive===this||documentActive===this.ownerDocument.body);if(!focusStayedAtOrigin&&!originWasRemovedWithoutReplacement)return;this.handleElement(transfer.target)?.focus()},"slider-range-focus")}firstUpdated(changed){if(super.firstUpdated(changed),!this.autofocus)return;const owner=this.ownerDocument.defaultView;if(!owner)return;const handle=owner.requestAnimationFrame(()=>{this.autofocusFrame?.owner!==owner||this.autofocusFrame.handle!==handle||(this.autofocusFrame=void 0,this.isConnected&&this.ownerDocument.defaultView===owner&&this.autofocus&&this.focus())});this.autofocusFrame={owner,handle}}disconnectedCallback(){this.releaseExternalDescription(),super.disconnectedCallback(),this.rangeFocusGeneration++,this.rangeFocusTransfer=void 0,this.abortActiveDrags(),this.pendingKeyHandle=null,this.focusedHandle=null,this.syncInteractionStates(),this.teardownDragWindow(),this.cancelAutofocusFrame()}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.isConnected&&this.hasUpdated&&this.syncExternalDescription(),this.rangeFocusGeneration++,this.rangeFocusTransfer=void 0,this.abortActiveDrags(),this.pendingKeyHandle=null,this.focusedHandle=null,this.syncInteractionStates(),this.teardownDragWindow(),this.cancelAutofocusFrame()}cancelAutofocusFrame(){const autofocusFrame=this.autofocusFrame;this.autofocusFrame=void 0,autofocusFrame&&autofocusFrame.owner.cancelAnimationFrame(autofocusFrame.handle)}attributeChangedCallback(name,old,value){const isRangeValue=name==="min-value"||name==="max-value";isRangeValue&&(this.applyingRangeValueAttribute=!0);try{super.attributeChangedCallback(name,old,value)}finally{isRangeValue&&(this.applyingRangeValueAttribute=!1)}name==="min-value"&&(this._defaultMinValue=value===null?0:finiteNumber(Number(value),0)),name==="max-value"&&(this._defaultMaxValue=value===null?50:finiteNumber(Number(value),50))}formDisabledCallback(fieldsetDisabled){this._fieldsetDisabled=fieldsetDisabled,fieldsetDisabled&&(this.pendingKeyHandle=null,this.abortActiveDrags()),this.syncInteractionStates(),this.syncValidityStates(),this.requestUpdate()}[VALIDITY_ANCHOR](){return this.firstThumb()}checkValidity(){return this.internals.checkValidity()}reportValidity(){return this.markInteracted(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncValidityStates(),this.requestUpdate()}resetValidity(){this.setCustomValidity("")}formResetCallback(){this.pendingValueBatch={value:this._defaultValue,min:this._defaultMinValue,max:this._defaultMaxValue},this.restoreLiveValueFromDefault(),this._minValue=this._defaultMinValue,this._maxValue=this._defaultMaxValue,this._minValueDirty=!1,this._maxValueDirty=!1,this.sanitizeHandles(),this._hasInteracted=!1,this.syncFormValue(),this.syncValidityStates(),this.requestUpdate()}formStateRestoreCallback(state2,reason){const values=this.readFormDataStrings(state2);if(values){values.length>=2&&(this.minValue=finiteNumber(Number(values[0]),this._defaultMinValue),this.maxValue=finiteNumber(Number(values[1]),this._defaultMaxValue));return}this.value=typeof state2=="string"?state2:this._defaultValue}readFormDataStrings(value){if(value===null||typeof value!="object")return null;const FormDataCtor=this.ownerDocument.defaultView?.FormData;if(!FormDataCtor)return null;try{const iterator=FormDataCtor.prototype.values.call(value),strings=[];for(const entry of iterator)typeof entry=="string"&&strings.push(entry);return strings}catch{return null}}restoreLiveValueFromDefault(){this.settingDefaultValue=!0;try{this.value=this._defaultValue}finally{this.settingDefaultValue=!1}this._valueDirty=!1}updateValidity(){this.validityController.setValidity({}),this.syncValidityStates()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}syncValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this._hasInteracted,barred:this.barredFromValidation})}syncInteractionStates(){const states=this.internals.states,set=(name,active)=>{active?states.add(name):states.delete(name)};set("disabled",this.effectiveDisabled),set("dragging",this.drags.size>0),set("focused",this.focusedHandle!==null)}click(){this.effectiveDisabled||this.firstThumb()?.click()}focus(options){this.effectiveDisabled||this.firstThumb()?.focus(options)}blur(){const active=activeElementIn(this.shadowRoot);active?.nodeType===1&&typeof active.matches=="function"&&typeof active.blur=="function"&&active.matches('[part~="thumb"]')?active.blur():this.firstThumb()?.blur()}stepUp(steps=1){this.stepBy(steps)}stepDown(steps=1){this.stepBy(-steps)}stepBy(steps){if(!this.interactive||finiteRange(this.step,0,0)<=0)return;const count=Math.trunc(finiteNumber(steps,1));if(count===0)return;const handle=this.range&&this.focusedHandle!=="max"?"min":this.focusedHandle??"value";this.assignValueFor(handle,this.directionalStep(this.valueForHandle(handle),count))}directionalStep(current,count){const{lo,hi}=this.domain();if(count===0)return current;const direction=Math.sign(count),magnitude=this.step*Math.abs(count);if(!Number.isFinite(magnitude))return direction>0?hi:lo;const candidate=current+direction*magnitude;return Number.isFinite(candidate)?candidate:direction>0?hi:lo}firstThumb(){return this.renderRoot?.querySelector('[part~="thumb"]')??null}handleElement(handle){const selector={value:'[part~="thumb"]',min:'[part~="thumb-min"]',max:'[part~="thumb-max"]'}[handle];return this.renderRoot?.querySelector(selector)??null}get interactive(){return!this.effectiveDisabled&&!this.matches(":disabled")&&!this.readonly}sanitizeCurrentValue(){this.sanitizeHandles();const old=this._value;this._value=this.clampValue(this.pendingValueBatch?.value??this._value),this._value!==old&&this.requestUpdate("value",old),this.syncFormValue()}sanitizeHandles(){this._minValue=this.clampValue(this.pendingValueBatch?.min??this._minValue),this._maxValue=this.clampValue(this.pendingValueBatch?.max??this._maxValue),this._minValue>this._maxValue&&(this.pendingValueBatch?.lastRange==="max"?this._minValue=this._maxValue:this._maxValue=this._minValue)}syncFormValue(){if(!this.internals)return;if(!this.range){const serialized=String(this.value);this.internals.setFormValue(serialized,serialized),this.updateValidity();return}const FormDataCtor=this.ownerDocument?.defaultView?.FormData;if(!FormDataCtor){this.internals.setFormValue(null),this.updateValidity();return}const state2=new FormDataCtor,stateKey=this.name||"value";if(state2.append(stateKey,String(this.minValue)),state2.append(stateKey,String(this.maxValue)),!this.name)this.internals.setFormValue(null,state2);else{const submission=new FormDataCtor;submission.append(this.name,String(this.minValue)),submission.append(this.name,String(this.maxValue)),this.internals.setFormValue(submission,state2)}this.updateValidity()}domain(){const min=finiteNumber(this.min,0),max=finiteNumber(this.max,100);return{lo:Math.min(min,max),hi:Math.max(min,max)}}defaultNumericValue(){return this.clampValue(0)}percentOf(value){const{lo,hi}=this.domain(),safeValue=finiteRange(value,lo,lo,hi);return finiteRatio(safeValue,lo,hi)*100}clampValue(raw){const{lo,hi}=this.domain();return clampSteppedValue(raw,lo,hi,this.step)}valueForHandle(handle){return handle==="min"?this.minValue:handle==="max"?this.maxValue:this.valueAsNumber}reachableBounds(handle){const{lo,hi}=this.domain();return{min:lo,max:hi}}detailFor(handle){return{value:this.valueForHandle(handle),minValue:this.minValue,maxValue:this.maxValue,handle}}emitInput(handle){dispatchNativeInputEvent(this),this.emit("lr-input",this.detailFor(handle))}emitChange(handle){dispatchNativeEvent(this,"change"),this.emit("lr-change",this.detailFor(handle))}assignValueFor(handle,raw){const previous=this.valueForHandle(handle),stepped=this.clampValue(raw);if(stepped===previous)return!1;if(handle==="min"){if(this._minValueDirty=!0,this._minValue=stepped,this.requestUpdate("minValue",previous),this._minValue>this._maxValue){const previousMax=this._maxValue;this._maxValueDirty=!0,this._maxValue=this._minValue,this.requestUpdate("maxValue",previousMax)}}else if(handle==="max"){if(this._maxValueDirty=!0,this._maxValue=stepped,this.requestUpdate("maxValue",previous),this._maxValue<this._minValue){const previousMin=this._minValue;this._minValueDirty=!0,this._minValue=this._maxValue,this.requestUpdate("minValue",previousMin)}}else this.value=stepped;return handle!=="value"&&this.syncFormValue(),!0}setValueFor(handle,raw,commit){return this.assignValueFor(handle,raw)?(this.emitInput(handle),commit&&this.emitChange(handle),!0):!1}ratioFromPointer(e,rect,rtl){if(this.orientation==="vertical"){const raw2=rect.height===0?0:(e.clientY-rect.top)/rect.height;return Math.min(1,Math.max(0,1-raw2))}const raw=rect.width===0?0:(e.clientX-rect.left)/rect.width;return Math.min(1,Math.max(0,rtl?1-raw:raw))}nearestHandle(target){const toMin=Math.abs(target-this.minValue),toMax=Math.abs(target-this.maxValue);return toMin<toMax?"min":toMax<toMin?"max":target<this.minValue?"min":"max"}beginDrag(pointerId,handle,captureTarget,rect,rtl){const dragWindow=captureTarget.ownerDocument.defaultView;if(!this.isConnected||!dragWindow)return;const firstDrag=this.drags.size===0;if(!firstDrag&&this.dragWindow!==dragWindow)return;captureTarget.setPointerCapture(pointerId);const drag={handle,changed:!1,captureTarget,rect,rtl};return this.drags.set(pointerId,drag),firstDrag&&(this.dragWindow=dragWindow,dragWindow.addEventListener("pointermove",this.onPointerMove),dragWindow.addEventListener("pointerup",this.onPointerUp),dragWindow.addEventListener("pointercancel",this.onPointerUp),dragWindow.addEventListener("lostpointercapture",this.onPointerUp)),this.syncInteractionStates(),this.requestUpdate(),drag}trackRect(){return this.renderRoot.querySelector('[part="track"]')?.getBoundingClientRect()??null}endDrag(pointerId,commit){const drag=this.drags.get(pointerId);drag!==void 0&&(this.drags.delete(pointerId),commit&&drag.changed&&this.emitChange(drag.handle),this.drags.size===0&&this.teardownDragWindow(),this.syncInteractionStates(),this.requestUpdate())}teardownDragWindow(){const dragWindow=this.dragWindow;this.dragWindow=void 0,dragWindow?.removeEventListener("pointermove",this.onPointerMove),dragWindow?.removeEventListener("pointerup",this.onPointerUp),dragWindow?.removeEventListener("pointercancel",this.onPointerUp),dragWindow?.removeEventListener("lostpointercapture",this.onPointerUp)}abortActiveDrags(){const activeDrags=[...this.drags.entries()];if(activeDrags.length!==0){this.drags.clear(),this.teardownDragWindow();for(const[pointerId,drag]of activeDrags)try{drag.captureTarget.hasPointerCapture(pointerId)&&drag.captureTarget.releasePointerCapture(pointerId)}catch{}this.syncInteractionStates()}}onHandleFocus(handle,event){this.focusedHandle!==handle&&(this.focusedHandle=handle,this.syncInteractionStates(),this.requestUpdate()),relayNativeEvent(this,event)}onHandleBlur(handle,event){this.pendingKeyHandle===handle&&(this.pendingKeyHandle=null,this.interactive&&this.isConnected&&this.emitChange(handle)),this.focusedHandle===handle&&(this.focusedHandle=null,this.syncInteractionStates(),this.requestUpdate()),relayNativeEvent(this,event)}slotsHaveContent(names){return names.some(name=>this.renderRoot.querySelector(`slot[name="${name}"]`)?.assignedNodes({flatten:!0}).some(node=>node.nodeType===1||!!node.textContent?.trim())??!1)}formatValue(value){return getNumberFormat(this.effectiveLocale,{maximumFractionDigits:20}).format(value)}readoutText(){const format=(value,handle)=>{if(this.valueDisplay==="formatted"){const text=this.valueFormatter?this.valueFormatter(value,handle):this.tooltipFormatter?.(value);if(text!=null)return text}return this.formatValue(value)};return this.range?`${format(this.minValue,"min")}–${format(this.maxValue,"max")}`:format(this.valueAsNumber,"value")}resolvedLabel(){const hostLabel=this.getAttribute("aria-label");return hostLabel!==null?hostLabel:this.label||this.localize("sliderLabel")}offsetStyle(percent){return this.orientation==="vertical"?`inset-block-end:${percent}%`:`inset-inline-start:${percent}%`}markerPercents(){if(!this.withMarkers)return[];const step=finiteRange(this.step,0,0);if(step<=0)return[];const{lo,hi}=this.domain(),span=hi-lo;if(!Number.isFinite(span)||span<=0)return[];const ratio=span/step,intervals=Math.floor(ratio+Number.EPSILON*Math.max(1,Math.abs(ratio))*4);return!Number.isFinite(intervals)||intervals<1||intervals>MAX_MARKER_INTERVALS?[]:Array.from({length:intervals+1},(_unused,index)=>{const value=lo+index*step;return finiteRatio(value,lo,hi)*100})}renderHandle(handle,describedBy,labelledBy){const value=this.valueForHandle(handle),bounds=this.reachableBounds(handle),percent=this.percentOf(value),numeric=this.formatValue(value),valueText=this.valueFormatter?this.valueFormatter(value,handle):this.tooltipFormatter?this.tooltipFormatter(value):numeric,partName={value:"thumb",min:"thumb thumb-min",max:"thumb thumb-max"}[handle],handleLabel={value:this.resolvedLabel(),min:this.localize("rangeStart"),max:this.localize("rangeEnd")}[handle],tooltipPart=this.focusedHandle===handle||Array.from(this.drags.values()).some(drag=>drag.handle===handle)?"tooltip tooltip__tooltip tooltip-visible":"tooltip tooltip__tooltip",showTooltip=this.withTooltip||this.tooltip!=="none",placement=this.tooltip==="none"?this.tooltipPlacement:this.tooltip,tooltipStyle=`${this.offsetStyle(percent)};--lr-slider-tooltip-distance:${finiteRange(this.tooltipDistance,8,0)}`;return html`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";installFormControlLabelSupport();import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{sizes}from"../../../internal/sizes.styles.js";import{isRtl}from"../../../internal/rtl.js";import{finiteInterpolate,finiteNumber,finiteRange,finiteRatio,isSliderKey}from"../../../internal/numbers.js";import{clampSteppedValue}from"../../../internal/step-value.js";import{styles}from"./slider.styles.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{activeElementIn}from"../../../internal/active-element.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_rangeEnd,LYRA_DEFAULT_rangeStart,LYRA_DEFAULT_sliderLabel}from"../../../internal/default-strings.generated.js";const PAGE_STEP_MULTIPLIER=10,MAX_MARKER_INTERVALS=100,falseDefaultBooleanConverter={fromAttribute:value=>value!==null&&value!=="false"},HINT_ID="slider-hint",ERROR_ID="slider-error",LABEL_ID="slider-label";class LyraSliderBase extends LyraElement{}class LyraSlider extends LyraSliderBase{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,rangeEnd:LYRA_DEFAULT_rangeEnd,rangeStart:LYRA_DEFAULT_rangeStart,sliderLabel:LYRA_DEFAULT_sliderLabel}}static get validators(){return[currentValidityValidator("required","disabled","value","min","max","step")]}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:"value",type:Number,reflect:!0,useDefault:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},min:{type:Number,noAccessor:!0},max:{type:Number,noAccessor:!0},step:{type:Number,noAccessor:!0},range:{type:Boolean,reflect:!0,noAccessor:!0},minValue:{type:Number,attribute:"min-value",noAccessor:!0},maxValue:{type:Number,attribute:"max-value",noAccessor:!0},size:{reflect:!0}}}captureValueBatch(){return this.pendingValueBatch||(this.pendingValueBatch={value:this._value,min:this._minValue,max:this._maxValue},this.requestUpdate()),this.pendingValueBatch}constructor(){super(),this.size="m",this._value=0,this._defaultValue=0,this._valueDirty=!1,this.settingDefaultValue=!1,this.reflectingDefaultValue=!1,this._name=null,this._required=!1,this._disabled=!1,this._fieldsetDisabled=!1,this._hasInteracted=!1,this._min=0,this._max=100,this._step=1,this._range=!1,this._minValue=0,this._maxValue=50,this._minValueDirty=!1,this._maxValueDirty=!1,this.applyingRangeValueAttribute=!1,this._defaultMinValue=0,this._defaultMaxValue=50,this.label="",this.hint="",this.helpText="",this.errorText="",this.withLabel=!1,this.withHint=!1,this.autofocus=!1,this.orientation="horizontal",this.readonly=!1,this.withMarkers=!1,this.withTooltip=!1,this.tooltipPlacement="top",this.tooltipDistance=8,this.tooltip="none",this.showValue=!1,this.valueDisplay="numeric",this.valuePlacement="inline",this.hasHintSlot=!1,this.hasErrorSlot=!1,this.hasLabelSlot=!1,this.hasReferenceSlot=!1,this.drags=new Map,this.pendingKeyHandle=null,this.focusedHandle=null,this.rangeFocusGeneration=0,this.markInteracted=()=>{this._hasInteracted||(this._hasInteracted=!0,this.syncValidityStates())},this.markFocusoutInteracted=()=>{this.effectiveDisabled||this.markInteracted()},this.onKeyDown=(handle,e)=>{if(!this.interactive)return;const current=this.valueForHandle(handle),rtl=isRtl(this),forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft",bounds=this.reachableBounds(handle),move=next=>{e.preventDefault(),this.assignValueFor(handle,next)&&(this.pendingKeyHandle=handle,this.emitInput(handle))};e.key===forwardKey||e.key==="ArrowUp"?move(this.directionalStep(current,1)):e.key===backwardKey||e.key==="ArrowDown"?move(this.directionalStep(current,-1)):e.key==="PageUp"?move(this.directionalStep(current,PAGE_STEP_MULTIPLIER)):e.key==="PageDown"?move(this.directionalStep(current,-PAGE_STEP_MULTIPLIER)):e.key==="Home"?move(bounds.min):e.key==="End"&&move(bounds.max)},this.onKeyUp=e=>{if(!this.interactive||!isSliderKey(e.key))return;const handle=this.pendingKeyHandle;handle!==null&&(this.pendingKeyHandle=null,this.emitChange(handle))},this.onPointerDown=(handle,e)=>{!this.interactive||e.button!==0||this.beginDrag(e.pointerId,handle,e.target,this.trackRect(),isRtl(this))},this.onBasePointerDown=e=>{if(!this.interactive||e.button!==0)return;const thumbs=Array.from(this.renderRoot.querySelectorAll('[part~="thumb"]'));if(thumbs.length===0||thumbs.includes(e.target))return;const rect=this.trackRect();if(!rect)return;const rtl=isRtl(this),{lo,hi}=this.domain(),target=finiteInterpolate(lo,hi,this.ratioFromPointer(e,rect,rtl)),handle=this.range?this.nearestHandle(target):"value",thumb=this.handleElement(handle)??thumbs[0];if(!thumb)return;const drag=this.beginDrag(e.pointerId,handle,thumb,rect,rtl);drag&&(this.setValueFor(handle,target,!1)&&(drag.changed=!0),thumb.focus())},this.onPointerMove=e=>{const drag=this.drags.get(e.pointerId);if(drag===void 0)return;if(!this.interactive){this.endDrag(e.pointerId,!1);return}if(!drag.rect)return;const{lo,hi}=this.domain(),value=finiteInterpolate(lo,hi,this.ratioFromPointer(e,drag.rect,drag.rtl));this.setValueFor(drag.handle,value,!1)&&(drag.changed=!0)},this.onPointerUp=e=>{this.endDrag(e.pointerId,e.type==="pointerup"&&this.interactive)},this.onSlotChange=event=>{const slot=event.target;(slot.name==="hint"||slot.name==="help-text")&&(this.hasHintSlot=this.slotsHaveContent(["hint","help-text"])),slot.name==="error"&&(this.hasErrorSlot=this.slotsHaveContent(["error"])),slot.name==="label"&&(this.hasLabelSlot=this.slotsHaveContent(["label"])),slot.name==="reference"&&(this.hasReferenceSlot=this.slotsHaveContent(["reference"]))},this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.internals.setFormValue("0","0"),this.addEventListener("input",this.markInteracted),this.addEventListener("change",this.markInteracted),this.addEventListener("focusout",this.markFocusoutInteracted),this.syncValidityStates()}get value(){return this._value}set value(next){const old=this._value;this.settingDefaultValue||(this._valueDirty=!0);const raw=finiteNumber(Number(next),this.defaultNumericValue());this.captureValueBatch().value=raw,this._value=this.clampValue(raw),this.syncFormValue(),this.requestUpdate("value",old)}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next==null?0:finiteNumber(Number(next),0),this.reflectingDefaultValue=!0;try{next==null?this.removeAttribute("value"):this.setAttribute("value",String(this._defaultValue))}finally{this.reflectingDefaultValue=!1}this._valueDirty||this.restoreLiveValueFromDefault(),this.requestUpdate("defaultValue",old)}get valueAsNumber(){return this.value}set valueAsNumber(next){this.value=next}get valueAsString(){return String(this.value)}set valueAsString(next){this.value=next}get name(){return this._name}set name(next){const old=this._name;this._name=next||null,this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),this.syncFormValue(),this.requestUpdate("name",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 disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._disabled&&(this.pendingKeyHandle=null,this.abortActiveDrags()),this.syncInteractionStates(),this.syncValidityStates(),this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}get min(){return this._min}set min(next){this.captureValueBatch();const old=this._min;this._min=finiteNumber(next,0),this.requestUpdate("min",old),this.sanitizeCurrentValue()}get max(){return this._max}set max(next){this.captureValueBatch();const old=this._max;this._max=finiteNumber(next,100),this.requestUpdate("max",old),this.sanitizeCurrentValue()}get step(){return this._step}set step(next){this.captureValueBatch();const old=this._step;this._step=next==null?1:finiteRange(next,0,0),this.requestUpdate("step",old),this.sanitizeCurrentValue()}get range(){return this._range}set range(next){const old=this._range;this._range=!!next,this.requestUpdate("range",old),this.syncFormValue()}get isRange(){return this.range}get minValue(){return this._minValue}set minValue(next){const batch=this.captureValueBatch();batch.min=finiteNumber(next,0),batch.lastRange="min";const old=this._minValue;if(this.applyingRangeValueAttribute||(this._minValueDirty=!0),this._minValue=this.clampValue(finiteNumber(next,0)),this._minValue>this._maxValue){const oldMax=this._maxValue;this._maxValue=this._minValue,this.applyingRangeValueAttribute||(this._maxValueDirty=!0),this.requestUpdate("maxValue",oldMax)}this.syncFormValue(),this.requestUpdate("minValue",old)}get maxValue(){return this._maxValue}set maxValue(next){const batch=this.captureValueBatch();batch.max=finiteNumber(next,50),batch.lastRange="max";const old=this._maxValue;if(this.applyingRangeValueAttribute||(this._maxValueDirty=!0),this._maxValue=this.clampValue(finiteNumber(next,50)),this._maxValue<this._minValue){const oldMin=this._minValue;this._minValue=this._maxValue,this.applyingRangeValueAttribute||(this._minValueDirty=!0),this.requestUpdate("minValue",oldMin)}this.syncFormValue(),this.requestUpdate("maxValue",old)}requestUpdate(name,oldValue,options){name==="readonly"&&this.readonly&&(this.pendingKeyHandle=null,this.abortActiveDrags()),super.requestUpdate(name,oldValue,options)}syncExternalDescription(){const primary=this.isConnected?this.range?this.handleElement("min"):this.firstThumb():null;primary?this.externalDescriptionLease?this.externalDescriptionLease.update(primary):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,primary,"aria-describedby"):(this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0);const secondary=this.isConnected&&this.range?this.handleElement("max"):null;secondary?this.externalDescriptionLeaseMax?this.externalDescriptionLeaseMax.update(secondary):this.externalDescriptionLeaseMax=acquireResolvedAriaRelationship(this,secondary,"aria-describedby"):(this.externalDescriptionLeaseMax?.release(),this.externalDescriptionLeaseMax=void 0)}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0,this.externalDescriptionLeaseMax?.release(),this.externalDescriptionLeaseMax=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this._valueDirty?this.sanitizeCurrentValue():this.restoreLiveValueFromDefault(),this._minValueDirty||(this._minValue=this.clampValue(this._defaultMinValue)),this._maxValueDirty||(this._maxValue=this.clampValue(this._defaultMaxValue)),this.sanitizeHandles();const slots=Array.from(this.children??[],child=>child.getAttribute("slot"));this.hasHintSlot=slots.some(slot=>slot==="hint"||slot==="help-text"),this.hasErrorSlot=slots.includes("error"),this.hasLabelSlot=slots.includes("label"),this.hasReferenceSlot=slots.includes("reference"),this.syncFormValue(),this.updateValidity(),this.syncInteractionStates()}willUpdate(changed){if(super.willUpdate(changed),this.pendingValueBatch&&(this.sanitizeCurrentValue(),this.pendingValueBatch=void 0),!changed.has("range")||!this.hasUpdated)return;const active=activeElementIn(this.shadowRoot);if(active?.matches('[part~="thumb"]')){const target=this.range?"min":"value";this.rangeFocusTransfer={origin:active,target},this.focusedHandle=target,this.syncInteractionStates(),this.rangeFocusGeneration++}this.pendingKeyHandle=null,this.abortActiveDrags()}updated(changed){if(super.updated(changed),this.syncExternalDescription(),changed.has("readonly")&&this.syncValidityStates(),!changed.has("range"))return;const transfer=this.rangeFocusTransfer;if(this.rangeFocusTransfer=void 0,!transfer)return;const generation=this.rangeFocusGeneration;this.scheduleAfterUpdate(()=>{if(generation!==this.rangeFocusGeneration||!this.isConnected||this.effectiveDisabled)return;const internalActive=activeElementIn(this.shadowRoot),documentActive=activeElementIn(this.ownerDocument),focusStayedAtOrigin=internalActive===transfer.origin,originWasRemovedWithoutReplacement=internalActive===null&&(documentActive===null||documentActive===this||documentActive===this.ownerDocument.body);if(!focusStayedAtOrigin&&!originWasRemovedWithoutReplacement)return;this.handleElement(transfer.target)?.focus()},"slider-range-focus")}firstUpdated(changed){if(super.firstUpdated(changed),!this.autofocus)return;const owner=this.ownerDocument.defaultView;if(!owner)return;const handle=owner.requestAnimationFrame(()=>{this.autofocusFrame?.owner!==owner||this.autofocusFrame.handle!==handle||(this.autofocusFrame=void 0,this.isConnected&&this.ownerDocument.defaultView===owner&&this.autofocus&&this.focus())});this.autofocusFrame={owner,handle}}disconnectedCallback(){this.releaseExternalDescription(),super.disconnectedCallback(),this.rangeFocusGeneration++,this.rangeFocusTransfer=void 0,this.abortActiveDrags(),this.pendingKeyHandle=null,this.focusedHandle=null,this.syncInteractionStates(),this.teardownDragWindow(),this.cancelAutofocusFrame()}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.isConnected&&this.hasUpdated&&this.syncExternalDescription(),this.rangeFocusGeneration++,this.rangeFocusTransfer=void 0,this.abortActiveDrags(),this.pendingKeyHandle=null,this.focusedHandle=null,this.syncInteractionStates(),this.teardownDragWindow(),this.cancelAutofocusFrame()}cancelAutofocusFrame(){const autofocusFrame=this.autofocusFrame;this.autofocusFrame=void 0,autofocusFrame&&autofocusFrame.owner.cancelAnimationFrame(autofocusFrame.handle)}attributeChangedCallback(name,old,value){const isRangeValue=name==="min-value"||name==="max-value";isRangeValue&&(this.applyingRangeValueAttribute=!0);try{super.attributeChangedCallback(name,old,value)}finally{isRangeValue&&(this.applyingRangeValueAttribute=!1)}name==="min-value"&&(this._defaultMinValue=value===null?0:finiteNumber(Number(value),0)),name==="max-value"&&(this._defaultMaxValue=value===null?50:finiteNumber(Number(value),50))}formDisabledCallback(fieldsetDisabled){this._fieldsetDisabled=fieldsetDisabled,fieldsetDisabled&&(this.pendingKeyHandle=null,this.abortActiveDrags()),this.syncInteractionStates(),this.syncValidityStates(),this.requestUpdate()}[VALIDITY_ANCHOR](){return this.firstThumb()}checkValidity(){return this.internals.checkValidity()}reportValidity(){return this.markInteracted(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncValidityStates(),this.requestUpdate()}resetValidity(){this.setCustomValidity("")}formResetCallback(){this.pendingValueBatch={value:this._defaultValue,min:this._defaultMinValue,max:this._defaultMaxValue},this.restoreLiveValueFromDefault(),this._minValue=this._defaultMinValue,this._maxValue=this._defaultMaxValue,this._minValueDirty=!1,this._maxValueDirty=!1,this.sanitizeHandles(),this._hasInteracted=!1,this.syncFormValue(),this.syncValidityStates(),this.requestUpdate()}formStateRestoreCallback(state2,reason){const values=this.readFormDataStrings(state2);if(values){values.length>=2&&(this.minValue=finiteNumber(Number(values[0]),this._defaultMinValue),this.maxValue=finiteNumber(Number(values[1]),this._defaultMaxValue));return}this.value=typeof state2=="string"?state2:this._defaultValue}readFormDataStrings(value){if(value===null||typeof value!="object")return null;const FormDataCtor=this.ownerDocument.defaultView?.FormData;if(!FormDataCtor)return null;try{const iterator=FormDataCtor.prototype.values.call(value),strings=[];for(const entry of iterator)typeof entry=="string"&&strings.push(entry);return strings}catch{return null}}restoreLiveValueFromDefault(){this.settingDefaultValue=!0;try{this.value=this._defaultValue}finally{this.settingDefaultValue=!1}this._valueDirty=!1}updateValidity(){this.validityController.setValidity({}),this.syncValidityStates()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}syncValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this._hasInteracted,barred:this.barredFromValidation})}syncInteractionStates(){const states=this.internals.states,set=(name,active)=>{active?states.add(name):states.delete(name)};set("disabled",this.effectiveDisabled),set("dragging",this.drags.size>0),set("focused",this.focusedHandle!==null)}click(){this.effectiveDisabled||this.firstThumb()?.click()}focus(options){this.effectiveDisabled||this.firstThumb()?.focus(options)}blur(){const active=activeElementIn(this.shadowRoot);active?.nodeType===1&&typeof active.matches=="function"&&typeof active.blur=="function"&&active.matches('[part~="thumb"]')?active.blur():this.firstThumb()?.blur()}stepUp(steps=1){this.stepBy(steps)}stepDown(steps=1){this.stepBy(-steps)}stepBy(steps){if(!this.interactive||finiteRange(this.step,0,0)<=0)return;const count=Math.trunc(finiteNumber(steps,1));if(count===0)return;const handle=this.range&&this.focusedHandle!=="max"?"min":this.focusedHandle??"value";this.assignValueFor(handle,this.directionalStep(this.valueForHandle(handle),count))}directionalStep(current,count){const{lo,hi}=this.domain();if(count===0)return current;const direction=Math.sign(count),magnitude=this.step*Math.abs(count);if(!Number.isFinite(magnitude))return direction>0?hi:lo;const candidate=current+direction*magnitude;return Number.isFinite(candidate)?candidate:direction>0?hi:lo}firstThumb(){return this.renderRoot?.querySelector('[part~="thumb"]')??null}handleElement(handle){const selector={value:'[part~="thumb"]',min:'[part~="thumb-min"]',max:'[part~="thumb-max"]'}[handle];return this.renderRoot?.querySelector(selector)??null}get interactive(){return!this.effectiveDisabled&&!this.matches(":disabled")&&!this.readonly}sanitizeCurrentValue(){this.sanitizeHandles();const old=this._value;this._value=this.clampValue(this.pendingValueBatch?.value??this._value),this._value!==old&&this.requestUpdate("value",old),this.syncFormValue()}sanitizeHandles(){this._minValue=this.clampValue(this.pendingValueBatch?.min??this._minValue),this._maxValue=this.clampValue(this.pendingValueBatch?.max??this._maxValue),this._minValue>this._maxValue&&(this.pendingValueBatch?.lastRange==="max"?this._minValue=this._maxValue:this._maxValue=this._minValue)}syncFormValue(){if(!this.internals)return;if(!this.range){const serialized=String(this.value);this.internals.setFormValue(serialized,serialized),this.updateValidity();return}const FormDataCtor=this.ownerDocument?.defaultView?.FormData;if(!FormDataCtor){this.internals.setFormValue(null),this.updateValidity();return}const state2=new FormDataCtor,stateKey=this.name||"value";if(state2.append(stateKey,String(this.minValue)),state2.append(stateKey,String(this.maxValue)),!this.name)this.internals.setFormValue(null,state2);else{const submission=new FormDataCtor;submission.append(this.name,String(this.minValue)),submission.append(this.name,String(this.maxValue)),this.internals.setFormValue(submission,state2)}this.updateValidity()}domain(){const min=finiteNumber(this.min,0),max=finiteNumber(this.max,100);return{lo:Math.min(min,max),hi:Math.max(min,max)}}defaultNumericValue(){return this.clampValue(0)}percentOf(value){const{lo,hi}=this.domain(),safeValue=finiteRange(value,lo,lo,hi);return finiteRatio(safeValue,lo,hi)*100}clampValue(raw){const{lo,hi}=this.domain();return clampSteppedValue(raw,lo,hi,this.step)}valueForHandle(handle){return handle==="min"?this.minValue:handle==="max"?this.maxValue:this.valueAsNumber}reachableBounds(handle){const{lo,hi}=this.domain();return{min:lo,max:hi}}detailFor(handle){return{value:this.valueForHandle(handle),minValue:this.minValue,maxValue:this.maxValue,handle}}emitInput(handle){dispatchNativeInputEvent(this),this.emit("lr-input",this.detailFor(handle))}emitChange(handle){dispatchNativeEvent(this,"change"),this.emit("lr-change",this.detailFor(handle))}assignValueFor(handle,raw){const previous=this.valueForHandle(handle),stepped=this.clampValue(raw);if(stepped===previous)return!1;if(handle==="min"){if(this._minValueDirty=!0,this._minValue=stepped,this.requestUpdate("minValue",previous),this._minValue>this._maxValue){const previousMax=this._maxValue;this._maxValueDirty=!0,this._maxValue=this._minValue,this.requestUpdate("maxValue",previousMax)}}else if(handle==="max"){if(this._maxValueDirty=!0,this._maxValue=stepped,this.requestUpdate("maxValue",previous),this._maxValue<this._minValue){const previousMin=this._minValue;this._minValueDirty=!0,this._minValue=this._maxValue,this.requestUpdate("minValue",previousMin)}}else this.value=stepped;return handle!=="value"&&this.syncFormValue(),!0}setValueFor(handle,raw,commit){return this.assignValueFor(handle,raw)?(this.emitInput(handle),commit&&this.emitChange(handle),!0):!1}ratioFromPointer(e,rect,rtl){if(this.orientation==="vertical"){const raw2=rect.height===0?0:(e.clientY-rect.top)/rect.height;return Math.min(1,Math.max(0,1-raw2))}const raw=rect.width===0?0:(e.clientX-rect.left)/rect.width;return Math.min(1,Math.max(0,rtl?1-raw:raw))}nearestHandle(target){const toMin=Math.abs(target-this.minValue),toMax=Math.abs(target-this.maxValue);return toMin<toMax?"min":toMax<toMin?"max":target<this.minValue?"min":"max"}beginDrag(pointerId,handle,captureTarget,rect,rtl){const dragWindow=captureTarget.ownerDocument.defaultView;if(!this.isConnected||!dragWindow)return;const firstDrag=this.drags.size===0;if(!firstDrag&&this.dragWindow!==dragWindow)return;captureTarget.setPointerCapture(pointerId);const drag={handle,changed:!1,captureTarget,rect,rtl};return this.drags.set(pointerId,drag),firstDrag&&(this.dragWindow=dragWindow,dragWindow.addEventListener("pointermove",this.onPointerMove),dragWindow.addEventListener("pointerup",this.onPointerUp),dragWindow.addEventListener("pointercancel",this.onPointerUp),dragWindow.addEventListener("lostpointercapture",this.onPointerUp)),this.syncInteractionStates(),this.requestUpdate(),drag}trackRect(){return this.renderRoot.querySelector('[part="track"]')?.getBoundingClientRect()??null}endDrag(pointerId,commit){const drag=this.drags.get(pointerId);drag!==void 0&&(this.drags.delete(pointerId),commit&&drag.changed&&this.emitChange(drag.handle),this.drags.size===0&&this.teardownDragWindow(),this.syncInteractionStates(),this.requestUpdate())}teardownDragWindow(){const dragWindow=this.dragWindow;this.dragWindow=void 0,dragWindow?.removeEventListener("pointermove",this.onPointerMove),dragWindow?.removeEventListener("pointerup",this.onPointerUp),dragWindow?.removeEventListener("pointercancel",this.onPointerUp),dragWindow?.removeEventListener("lostpointercapture",this.onPointerUp)}abortActiveDrags(){const activeDrags=[...this.drags.entries()];if(activeDrags.length!==0){this.drags.clear(),this.teardownDragWindow();for(const[pointerId,drag]of activeDrags)try{drag.captureTarget.hasPointerCapture(pointerId)&&drag.captureTarget.releasePointerCapture(pointerId)}catch{}this.syncInteractionStates()}}onHandleFocus(handle,event){this.focusedHandle!==handle&&(this.focusedHandle=handle,this.syncInteractionStates(),this.requestUpdate()),relayNativeEvent(this,event)}onHandleBlur(handle,event){this.pendingKeyHandle===handle&&(this.pendingKeyHandle=null,this.interactive&&this.isConnected&&this.emitChange(handle)),this.focusedHandle===handle&&(this.focusedHandle=null,this.syncInteractionStates(),this.requestUpdate()),relayNativeEvent(this,event)}slotsHaveContent(names){return names.some(name=>this.renderRoot.querySelector(`slot[name="${name}"]`)?.assignedNodes({flatten:!0}).some(node=>node.nodeType===1||!!node.textContent?.trim())??!1)}formatValue(value){return getNumberFormat(this.effectiveLocale,{maximumFractionDigits:20}).format(value)}readoutText(){const format=(value,handle)=>{if(this.valueDisplay==="formatted"){const text=this.valueFormatter?this.valueFormatter(value,handle):this.tooltipFormatter?.(value);if(text!=null)return text}return this.formatValue(value)};return this.range?`${format(this.minValue,"min")}–${format(this.maxValue,"max")}`:format(this.valueAsNumber,"value")}resolvedLabel(){const hostLabel=this.getAttribute("aria-label");return hostLabel!==null?hostLabel:this.label||this.localize("sliderLabel")}offsetStyle(percent){return this.orientation==="vertical"?`inset-block-end:${percent}%`:`inset-inline-start:${percent}%`}markerPercents(){if(!this.withMarkers)return[];const step=finiteRange(this.step,0,0);if(step<=0)return[];const{lo,hi}=this.domain(),span=hi-lo;if(!Number.isFinite(span)||span<=0)return[];const ratio=span/step,intervals=Math.floor(ratio+Number.EPSILON*Math.max(1,Math.abs(ratio))*4);return!Number.isFinite(intervals)||intervals<1||intervals>MAX_MARKER_INTERVALS?[]:Array.from({length:intervals+1},(_unused,index)=>{const value=lo+index*step;return finiteRatio(value,lo,hi)*100})}renderHandle(handle,describedBy,labelledBy){const value=this.valueForHandle(handle),bounds=this.reachableBounds(handle),percent=this.percentOf(value),numeric=this.formatValue(value),valueText=this.valueFormatter?this.valueFormatter(value,handle):this.tooltipFormatter?this.tooltipFormatter(value):numeric,partName={value:"thumb",min:"thumb thumb-min",max:"thumb thumb-max"}[handle],handleLabel={value:this.resolvedLabel(),min:this.localize("rangeStart"),max:this.localize("rangeEnd")}[handle],tooltipPart=this.focusedHandle===handle||Array.from(this.drags.values()).some(drag=>drag.handle===handle)?"tooltip tooltip__tooltip tooltip-visible":"tooltip tooltip__tooltip",showTooltip=this.withTooltip||this.tooltip!=="none",placement=this.tooltip==="none"?this.tooltipPlacement:this.tooltip,tooltipStyle=`${this.offsetStyle(percent)};--lr-slider-tooltip-distance:${finiteRange(this.tooltipDistance,8,0)}`;return html`
|
|
2
2
|
<div
|
|
3
3
|
part=${partName}
|
|
4
4
|
role="slider"
|
|
@@ -15,8 +15,11 @@ export interface LyraTextareaEventMap{input:InputEvent;change:Event;'lr-input':C
|
|
|
15
15
|
* Ships an opt-in `label`/`hint`/`errorText` form-control chrome (props + matching named slots +
|
|
16
16
|
* `form-control-label`/`hint`/`error` parts), mirroring `<lr-select>`'s exact pattern -- left
|
|
17
17
|
* unset, the chrome remains hidden. A consumer preferring their own form-field layout can still
|
|
18
|
-
* ignore these and wrap the element. A host `aria-label` is forwarded to the internal textbox
|
|
19
|
-
*
|
|
18
|
+
* ignore these and wrap the element. A host `aria-label` is forwarded to the internal textbox via
|
|
19
|
+
* the typed `accessibleLabel` property. A host `aria-describedby` is resolved onto that native
|
|
20
|
+
* textarea, ahead of its own hint/error descriptions, so externally-owned guidance remains valid
|
|
21
|
+
* across the shadow boundary. Host `aria-labelledby` is deliberately not projected: the native
|
|
22
|
+
* `<label>` already owns this control's visible label relationship.
|
|
20
23
|
*
|
|
21
24
|
* `minlength`/`maxlength` are forwarded to the internal native `<textarea>` and bridged into this
|
|
22
25
|
* element's own `ElementInternals` as `tooShort`/`tooLong` by `updateValidity()`.
|
|
@@ -164,7 +167,7 @@ minlength?:number;
|
|
|
164
167
|
* value, a programmatic assignment). */
|
|
165
168
|
maxlength?:number;private touched;
|
|
166
169
|
/** Empty until the user pauses typing, so the live region says nothing on first render. */
|
|
167
|
-
private announcedCountText;private readonly slotPresence;private textareaEl?;private resizeObserver?;private lastObservedWidth?;private resizeRaf?;private resizeRafOwner?;private countAnnounceTimer?;private countAnnounceTimerOwner?;private countAnnouncementSink?;constructor();
|
|
170
|
+
private announcedCountText;private readonly slotPresence;private textareaEl?;private resizeObserver?;private lastObservedWidth?;private resizeRaf?;private resizeRafOwner?;private countAnnounceTimer?;private countAnnounceTimerOwner?;private countAnnouncementSink?;private externalDescriptionLease?;constructor();
|
|
168
171
|
/** The internal native `<textarea>` element, for direct DOM access (caret position, selection,
|
|
169
172
|
* `setRangeText()`) that has no first-class `lr-*` equivalent -- mirrors `wa-textarea`'s own
|
|
170
173
|
* `input` getter. */
|
|
@@ -183,7 +186,9 @@ private get liveDisabled();click():void;focus(options?:FocusOptions):void;blur()
|
|
|
183
186
|
scrollPosition(position?:{top?:number;left?:number;}):{top:number;left:number;}|undefined;
|
|
184
187
|
/** Passthrough to the native `<textarea>`'s `setRangeText()`. Mirrors `wa-textarea`'s own method
|
|
185
188
|
* of the same name/signature. No-op if the element hasn't rendered yet. */
|
|
186
|
-
setRangeText(replacement:string,start?:number,end?:number,selectMode?:'select'|'start'|'end'|'preserve'):void;connectedCallback():void;disconnectedCallback():void;
|
|
189
|
+
setRangeText(replacement:string,start?:number,end?:number,selectMode?:'select'|'start'|'end'|'preserve'):void;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;
|
|
190
|
+
/** Resolves host-owned descriptions onto the native textarea without copying labelledby. */
|
|
191
|
+
private syncExternalDescription;private releaseExternalDescription;
|
|
187
192
|
/**
|
|
188
193
|
* `maxlength` as a usable non-negative integer, or `undefined` when it was never set or arrived
|
|
189
194
|
* unparseable — an attribute goes through `Number()`, so `maxlength="oops"` reaches this
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{isAccessibilityVisible}from"../../../internal/accessibility-visibility.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY}from"../../../internal/anchored-validity.js";import{lengthViolations}from"../../../internal/length-constraints.js";import{styles}from"./textarea.styles.js";import{sizes}from"../../../internal/sizes.styles.js";import{autocorrectConverter,normalizeAutocorrect,spellcheckConverter}from"../../../internal/converters.js";import{sanitizeCssResize}from"../../../internal/safe-css.js";import{finiteCount,finiteNumber}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_textareaCharacterCount,LYRA_DEFAULT_textareaCharactersRemaining,LYRA_DEFAULT_textareaLabel,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";const COUNT_ANNOUNCE_DELAY_MS=1e3;class LyraTextareaBase extends LyraElement{}class LyraTextarea extends FormAssociated(LyraTextareaBase){static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,textareaCharacterCount:LYRA_DEFAULT_textareaCharacterCount,textareaCharactersRemaining:LYRA_DEFAULT_textareaCharactersRemaining,textareaLabel:LYRA_DEFAULT_textareaLabel,valueInvalid:LYRA_DEFAULT_valueInvalid}}static get validators(){return[currentValidityValidator("required","disabled","readonly","value","minlength","maxlength")]}static{this.styles=[LyraElement.styles,sizes,styles]}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=normalizeAutocorrect(next),this.requestUpdate()}get inputmode(){return this.inputMode}set inputmode(next){this.inputMode=next??""}get enterkeyhint(){return this.enterKeyHint}set enterkeyhint(next){this.enterKeyHint=next??""}get defaultValueAlias(){return this.defaultValue}set defaultValueAlias(next){this.defaultValue=next??""}constructor(){super(),this.rows=4,this.resize="vertical",this.size="m",this.appearance="outlined",this.filled=!1,this.pill=!1,this.withCount=!1,this.placeholder="",this.readonly=!1,this.label="",this.hint="",this.helpText="",this.withLabel=!1,this.withHint=!1,this.errorText="",this.accessibleLabel=null,this.spellcheck=!0,this.autofocus=!1,this.title="",this.autocapitalize="",this.autocorrectValue=!0,this.wrap="soft",this.autocomplete="",this.inputMode="",this.enterKeyHint="",this.touched=!1,this.announcedCountText="",this.slotPresence=new SlotPresenceController(this),this.onInput=event=>{if(this.liveDisabled){event.stopPropagation();return}this.textareaEl&&(this.value=this.textareaEl.value,this.resize==="auto"&&this.fitToContent(),this.scheduleCountAnnouncement(),relayNativeEvent(this,event),this.emit("lr-input",{value:this.value}))},this.onChange=event=>{if(this.liveDisabled){event.stopPropagation();return}this.textareaEl&&(this.value=this.textareaEl.value,relayNativeEvent(this,event),this.emit("lr-change",{value:this.value}))},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onBlur=event=>{this.liveDisabled||(this.touched=!0),relayNativeEvent(this,event)},this.addEventListener("invalid",()=>{this.touched=!0})}get input(){return this.textareaEl??null}get selectionStart(){return this.textareaEl?.selectionStart??null}set selectionStart(value){this.textareaEl&&(this.textareaEl.selectionStart=value??0)}get selectionEnd(){return this.textareaEl?.selectionEnd??null}set selectionEnd(value){this.textareaEl&&(this.textareaEl.selectionEnd=value??0)}get selectionDirection(){return this.textareaEl?.selectionDirection}set selectionDirection(value){this.textareaEl&&(this.textareaEl.selectionDirection=value??"none")}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}click(){this.liveDisabled||this.textareaEl?.click()}focus(options){this.liveDisabled||this.textareaEl?.focus(options)}blur(){this.textareaEl?.blur()}select(){this.textareaEl?.select()}setSelectionRange(selectionStart,selectionEnd,selectionDirection="none"){this.textareaEl?.setSelectionRange(selectionStart,selectionEnd,selectionDirection)}scrollPosition(position){const ta=this.textareaEl;if(ta){if(position){position.top!==void 0&&(ta.scrollTop=finiteNumber(position.top,ta.scrollTop)),position.left!==void 0&&(ta.scrollLeft=finiteNumber(position.left,ta.scrollLeft));return}return{top:ta.scrollTop,left:ta.scrollLeft}}}setRangeText(replacement,start,end,selectMode="preserve"){const ta=this.textareaEl;ta&&(start===void 0||end===void 0?ta.setRangeText(replacement):ta.setRangeText(replacement,start,end,selectMode),this.value=ta.value,this.fitToContent())}connectedCallback(){super.connectedCallback(),this.countAnnouncementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.resize==="auto"&&this.hasUpdated&&(this.armResizeObserver(),this.fitToContent())}disconnectedCallback(){this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeRaf!==void 0&&this.resizeRafOwner?.cancelAnimationFrame(this.resizeRaf),this.resizeRaf=void 0,this.resizeRafOwner=void 0,this.countAnnounceTimer!==void 0&&this.countAnnounceTimerOwner?.clearTimeout(this.countAnnounceTimer),this.countAnnounceTimer=void 0,this.countAnnounceTimerOwner=void 0,this.countAnnouncementSink?.release(),this.countAnnouncementSink=void 0,super.disconnectedCallback()}effectiveLengthLimit(declared){if(!(declared===void 0||!Number.isFinite(declared)||declared<0))return finiteCount(Math.trunc(declared),0)}countMaxlength(){return this.effectiveLengthLimit(this.maxlength)}countText(){const format=getNumberFormat(this.effectiveLocale),max=this.countMaxlength();if(max!==void 0){const remaining=Math.max(0,max-this.value.length);return this.localize("textareaCharactersRemaining",void 0,{count:format.format(remaining),pluralCount:remaining})}const length=this.value.length;return this.localize("textareaCharacterCount",void 0,{count:format.format(length),pluralCount:length})}scheduleCountAnnouncement(){if(this.countAnnounceTimer!==void 0&&this.countAnnounceTimerOwner?.clearTimeout(this.countAnnounceTimer),this.countAnnounceTimer=void 0,this.countAnnounceTimerOwner=void 0,!this.withCount)return;const view=this.ownerDocument.defaultView;view&&(this.countAnnounceTimerOwner=view,this.countAnnounceTimer=view.setTimeout(()=>{if(this.countAnnounceTimer=void 0,this.countAnnounceTimerOwner=void 0,!this.isConnected||this.ownerDocument.defaultView!==view||!this.withCount||!isAccessibilityVisible(this))return;const text=this.countText();this.announcedCountText=text,this.countAnnouncementSink?.announce(text)},COUNT_ANNOUNCE_DELAY_MS))}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}if(this.required&&this.value===""){this[SET_ANCHORED_VALIDITY]({valueMissing:!0},this.localize("fieldRequired"));return}const native=this.textareaEl;native&&native.value!==this.value&&(native.value=this.value);const effectiveMinlength=this.effectiveLengthLimit(this.minlength),effectiveMaxlength=this.effectiveLengthLimit(this.maxlength),own=lengthViolations(this.value,effectiveMinlength,effectiveMaxlength),tooShort=!!native?.validity.tooShort||own.tooShort,tooLong=!!native?.validity.tooLong||own.tooLong;if(!tooShort&&!tooLong){this[SET_ANCHORED_VALIDITY]({});return}this[SET_ANCHORED_VALIDITY]({tooShort,tooLong},native?.validationMessage||this.localize("valueInvalid"))}updated(changed){super.updated(changed),changed.has("value")&&(this.value===""?this.internals.states.add("blank"):this.internals.states.delete("blank")),(changed.has("minlength")||changed.has("maxlength")||changed.has("readonly"))&&this.updateValidity(),changed.has("resize")&&(this.resize==="auto"?this.armResizeObserver():changed.get("resize")==="auto"&&(this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeRaf!==void 0&&this.resizeRafOwner?.cancelAnimationFrame(this.resizeRaf),this.resizeRaf=void 0,this.resizeRafOwner=void 0,this.textareaEl&&(this.textareaEl.style.blockSize="",this.textareaEl.style.overflowY=""))),this.resize==="auto"&&(this.armResizeObserver(),(changed.has("value")||changed.has("rows")||changed.has("resize"))&&this.fitToContent())}formResetCallback(){super.formResetCallback(),this.touched=!1}armResizeObserver(){const textarea=this.textareaEl;if(this.resizeObserver||!textarea)return;const view=this.ownerDocument.defaultView,ResizeObserverCtor=view?.ResizeObserver;!view||!ResizeObserverCtor||(this.lastObservedWidth=textarea.getBoundingClientRect().width,this.resizeObserver=new ResizeObserverCtor(entries=>{if(!this.isConnected||this.ownerDocument.defaultView!==view)return;const width=entries[0]?.contentRect.width;width===void 0||this.lastObservedWidth!==void 0&&Math.abs(width-this.lastObservedWidth)<.5||(this.lastObservedWidth=width,this.resizeRaf!==void 0&&this.resizeRafOwner?.cancelAnimationFrame(this.resizeRaf),this.resizeRafOwner=view,this.resizeRaf=view.requestAnimationFrame(()=>{this.resizeRaf=void 0,this.resizeRafOwner=void 0,!(!this.isConnected||this.ownerDocument.defaultView!==view)&&this.fitToContent()}))}),this.resizeObserver.observe(textarea))}fitToContent(){const ta=this.textareaEl;if(!ta||this.resize!=="auto")return;ta.style.blockSize="auto";const computed=ta.ownerDocument.defaultView?.getComputedStyle(ta);if(!computed)return;const borderBlock=parseFloat(computed.borderBlockStartWidth)+parseFloat(computed.borderBlockEndWidth),parsedMax=parseFloat(computed.maxBlockSize),maxBlockSize=Number.isFinite(parsedMax)?parsedMax:Number.POSITIVE_INFINITY,contentBlockSize=ta.scrollHeight+borderBlock;ta.style.blockSize=`${Math.min(contentBlockSize,maxBlockSize)}px`,ta.style.overflowY=contentBlockSize>maxBlockSize?"auto":"hidden"}render(){const hasHint=this.slotPresence.has("hint")||this.slotPresence.has("help-text")||(this.hint??"").length>0||(this.helpText??"").length>0||this.withHint,hasError=this.slotPresence.has("error")||(this.errorText??"").length>0,hasLabel=this.slotPresence.has("label")||(this.label??"").length>0||this.withLabel,describedBy=[hasError?"textarea-error":"",hasHint?"textarea-hint":""].filter(Boolean).join(" "),cssResize=this.resize==="auto"?"none":sanitizeCssResize(this.resize,"vertical");return html`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{isAccessibilityVisible}from"../../../internal/accessibility-visibility.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY}from"../../../internal/anchored-validity.js";import{lengthViolations}from"../../../internal/length-constraints.js";import{styles}from"./textarea.styles.js";import{sizes}from"../../../internal/sizes.styles.js";import{autocorrectConverter,normalizeAutocorrect,spellcheckConverter}from"../../../internal/converters.js";import{sanitizeCssResize}from"../../../internal/safe-css.js";import{finiteCount,finiteNumber}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_textareaCharacterCount,LYRA_DEFAULT_textareaCharactersRemaining,LYRA_DEFAULT_textareaLabel,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";const COUNT_ANNOUNCE_DELAY_MS=1e3;class LyraTextareaBase extends LyraElement{}class LyraTextarea extends FormAssociated(LyraTextareaBase){static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,textareaCharacterCount:LYRA_DEFAULT_textareaCharacterCount,textareaCharactersRemaining:LYRA_DEFAULT_textareaCharactersRemaining,textareaLabel:LYRA_DEFAULT_textareaLabel,valueInvalid:LYRA_DEFAULT_valueInvalid}}static get validators(){return[currentValidityValidator("required","disabled","readonly","value","minlength","maxlength")]}static{this.styles=[LyraElement.styles,sizes,styles]}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=normalizeAutocorrect(next),this.requestUpdate()}get inputmode(){return this.inputMode}set inputmode(next){this.inputMode=next??""}get enterkeyhint(){return this.enterKeyHint}set enterkeyhint(next){this.enterKeyHint=next??""}get defaultValueAlias(){return this.defaultValue}set defaultValueAlias(next){this.defaultValue=next??""}constructor(){super(),this.rows=4,this.resize="vertical",this.size="m",this.appearance="outlined",this.filled=!1,this.pill=!1,this.withCount=!1,this.placeholder="",this.readonly=!1,this.label="",this.hint="",this.helpText="",this.withLabel=!1,this.withHint=!1,this.errorText="",this.accessibleLabel=null,this.spellcheck=!0,this.autofocus=!1,this.title="",this.autocapitalize="",this.autocorrectValue=!0,this.wrap="soft",this.autocomplete="",this.inputMode="",this.enterKeyHint="",this.touched=!1,this.announcedCountText="",this.slotPresence=new SlotPresenceController(this),this.onInput=event=>{if(this.liveDisabled){event.stopPropagation();return}this.textareaEl&&(this.value=this.textareaEl.value,this.resize==="auto"&&this.fitToContent(),this.scheduleCountAnnouncement(),relayNativeEvent(this,event),this.emit("lr-input",{value:this.value}))},this.onChange=event=>{if(this.liveDisabled){event.stopPropagation();return}this.textareaEl&&(this.value=this.textareaEl.value,relayNativeEvent(this,event),this.emit("lr-change",{value:this.value}))},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onBlur=event=>{this.liveDisabled||(this.touched=!0),relayNativeEvent(this,event)},this.addEventListener("invalid",()=>{this.touched=!0})}get input(){return this.textareaEl??null}get selectionStart(){return this.textareaEl?.selectionStart??null}set selectionStart(value){this.textareaEl&&(this.textareaEl.selectionStart=value??0)}get selectionEnd(){return this.textareaEl?.selectionEnd??null}set selectionEnd(value){this.textareaEl&&(this.textareaEl.selectionEnd=value??0)}get selectionDirection(){return this.textareaEl?.selectionDirection}set selectionDirection(value){this.textareaEl&&(this.textareaEl.selectionDirection=value??"none")}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}click(){this.liveDisabled||this.textareaEl?.click()}focus(options){this.liveDisabled||this.textareaEl?.focus(options)}blur(){this.textareaEl?.blur()}select(){this.textareaEl?.select()}setSelectionRange(selectionStart,selectionEnd,selectionDirection="none"){this.textareaEl?.setSelectionRange(selectionStart,selectionEnd,selectionDirection)}scrollPosition(position){const ta=this.textareaEl;if(ta){if(position){position.top!==void 0&&(ta.scrollTop=finiteNumber(position.top,ta.scrollTop)),position.left!==void 0&&(ta.scrollLeft=finiteNumber(position.left,ta.scrollLeft));return}return{top:ta.scrollTop,left:ta.scrollLeft}}}setRangeText(replacement,start,end,selectMode="preserve"){const ta=this.textareaEl;ta&&(start===void 0||end===void 0?ta.setRangeText(replacement):ta.setRangeText(replacement,start,end,selectMode),this.value=ta.value,this.fitToContent())}connectedCallback(){super.connectedCallback(),this.countAnnouncementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.resize==="auto"&&this.hasUpdated&&(this.armResizeObserver(),this.fitToContent()),this.hasUpdated&&this.syncExternalDescription()}disconnectedCallback(){this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeRaf!==void 0&&this.resizeRafOwner?.cancelAnimationFrame(this.resizeRaf),this.resizeRaf=void 0,this.resizeRafOwner=void 0,this.countAnnounceTimer!==void 0&&this.countAnnounceTimerOwner?.clearTimeout(this.countAnnounceTimer),this.countAnnounceTimer=void 0,this.countAnnounceTimerOwner=void 0,this.countAnnouncementSink?.release(),this.countAnnouncementSink=void 0,this.releaseExternalDescription(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.isConnected&&this.hasUpdated&&this.syncExternalDescription()}syncExternalDescription(){const target=this.textareaEl??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}effectiveLengthLimit(declared){if(!(declared===void 0||!Number.isFinite(declared)||declared<0))return finiteCount(Math.trunc(declared),0)}countMaxlength(){return this.effectiveLengthLimit(this.maxlength)}countText(){const format=getNumberFormat(this.effectiveLocale),max=this.countMaxlength();if(max!==void 0){const remaining=Math.max(0,max-this.value.length);return this.localize("textareaCharactersRemaining",void 0,{count:format.format(remaining),pluralCount:remaining})}const length=this.value.length;return this.localize("textareaCharacterCount",void 0,{count:format.format(length),pluralCount:length})}scheduleCountAnnouncement(){if(this.countAnnounceTimer!==void 0&&this.countAnnounceTimerOwner?.clearTimeout(this.countAnnounceTimer),this.countAnnounceTimer=void 0,this.countAnnounceTimerOwner=void 0,!this.withCount)return;const view=this.ownerDocument.defaultView;view&&(this.countAnnounceTimerOwner=view,this.countAnnounceTimer=view.setTimeout(()=>{if(this.countAnnounceTimer=void 0,this.countAnnounceTimerOwner=void 0,!this.isConnected||this.ownerDocument.defaultView!==view||!this.withCount||!isAccessibilityVisible(this))return;const text=this.countText();this.announcedCountText=text,this.countAnnouncementSink?.announce(text)},COUNT_ANNOUNCE_DELAY_MS))}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}if(this.required&&this.value===""){this[SET_ANCHORED_VALIDITY]({valueMissing:!0},this.localize("fieldRequired"));return}const native=this.textareaEl;native&&native.value!==this.value&&(native.value=this.value);const effectiveMinlength=this.effectiveLengthLimit(this.minlength),effectiveMaxlength=this.effectiveLengthLimit(this.maxlength),own=lengthViolations(this.value,effectiveMinlength,effectiveMaxlength),tooShort=!!native?.validity.tooShort||own.tooShort,tooLong=!!native?.validity.tooLong||own.tooLong;if(!tooShort&&!tooLong){this[SET_ANCHORED_VALIDITY]({});return}this[SET_ANCHORED_VALIDITY]({tooShort,tooLong},native?.validationMessage||this.localize("valueInvalid"))}updated(changed){super.updated(changed),changed.has("value")&&(this.value===""?this.internals.states.add("blank"):this.internals.states.delete("blank")),this.syncExternalDescription(),(changed.has("minlength")||changed.has("maxlength")||changed.has("readonly"))&&this.updateValidity(),changed.has("resize")&&(this.resize==="auto"?this.armResizeObserver():changed.get("resize")==="auto"&&(this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeRaf!==void 0&&this.resizeRafOwner?.cancelAnimationFrame(this.resizeRaf),this.resizeRaf=void 0,this.resizeRafOwner=void 0,this.textareaEl&&(this.textareaEl.style.blockSize="",this.textareaEl.style.overflowY=""))),this.resize==="auto"&&(this.armResizeObserver(),(changed.has("value")||changed.has("rows")||changed.has("resize"))&&this.fitToContent())}formResetCallback(){super.formResetCallback(),this.touched=!1}armResizeObserver(){const textarea=this.textareaEl;if(this.resizeObserver||!textarea)return;const view=this.ownerDocument.defaultView,ResizeObserverCtor=view?.ResizeObserver;!view||!ResizeObserverCtor||(this.lastObservedWidth=textarea.getBoundingClientRect().width,this.resizeObserver=new ResizeObserverCtor(entries=>{if(!this.isConnected||this.ownerDocument.defaultView!==view)return;const width=entries[0]?.contentRect.width;width===void 0||this.lastObservedWidth!==void 0&&Math.abs(width-this.lastObservedWidth)<.5||(this.lastObservedWidth=width,this.resizeRaf!==void 0&&this.resizeRafOwner?.cancelAnimationFrame(this.resizeRaf),this.resizeRafOwner=view,this.resizeRaf=view.requestAnimationFrame(()=>{this.resizeRaf=void 0,this.resizeRafOwner=void 0,!(!this.isConnected||this.ownerDocument.defaultView!==view)&&this.fitToContent()}))}),this.resizeObserver.observe(textarea))}fitToContent(){const ta=this.textareaEl;if(!ta||this.resize!=="auto")return;ta.style.blockSize="auto";const computed=ta.ownerDocument.defaultView?.getComputedStyle(ta);if(!computed)return;const borderBlock=parseFloat(computed.borderBlockStartWidth)+parseFloat(computed.borderBlockEndWidth),parsedMax=parseFloat(computed.maxBlockSize),maxBlockSize=Number.isFinite(parsedMax)?parsedMax:Number.POSITIVE_INFINITY,contentBlockSize=ta.scrollHeight+borderBlock;ta.style.blockSize=`${Math.min(contentBlockSize,maxBlockSize)}px`,ta.style.overflowY=contentBlockSize>maxBlockSize?"auto":"hidden"}render(){const hasHint=this.slotPresence.has("hint")||this.slotPresence.has("help-text")||(this.hint??"").length>0||(this.helpText??"").length>0||this.withHint,hasError=this.slotPresence.has("error")||(this.errorText??"").length>0,hasLabel=this.slotPresence.has("label")||(this.label??"").length>0||this.withLabel,describedBy=[hasError?"textarea-error":"",hasHint?"textarea-hint":""].filter(Boolean).join(" "),cssResize=this.resize==="auto"?"none":sanitizeCssResize(this.resize,"vertical");return html`
|
|
2
2
|
<div part="form-control">
|
|
3
3
|
<label part="form-control-label" for="textarea" ?hidden=${!hasLabel}>
|
|
4
4
|
<span part="label">${this.label}<slot name="label"></slot></span>
|
|
@@ -14,7 +14,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
14
14
|
<div
|
|
15
15
|
part="base"
|
|
16
16
|
role="group"
|
|
17
|
-
aria-label=${this.getAttribute("aria-label")
|
|
17
|
+
aria-label=${this.getAttribute("aria-label")??nothing}
|
|
18
18
|
@pointerdown=${this.onBasePointerDown}
|
|
19
19
|
>
|
|
20
20
|
<div part="track"></div>
|