@aceshooting/lyra-ui 11.2.0 → 12.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +407 -0
- package/README.md +11 -8
- package/custom-elements.json +1 -1
- package/dist/all.d.ts +1 -0
- package/dist/all.js +1 -1
- package/dist/autoloader.js +1 -1
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.d.ts +0 -1
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +1 -1
- package/dist/components/charts/chart/chart.class.d.ts +13 -1
- package/dist/components/charts/chart/histogram-bin.d.ts +0 -1
- package/dist/components/charts/chart/histogram-bin.js +1 -1
- package/dist/components/charts/chart/lite-chart.class.d.ts +22 -9
- package/dist/components/charts/chart/lite-chart.class.js +6 -6
- package/dist/components/conversation/code-block/code-block-shared.d.ts +4 -54
- package/dist/components/conversation/code-block/code-block-shared.js +1 -1
- package/dist/components/conversation/code-block/shiki-types.d.ts +2 -1
- package/dist/components/conversation/generation-metrics/generation-metrics.class.js +1 -1
- package/dist/components/conversation/model-select/model-select.class.d.ts +0 -3
- package/dist/components/conversation/model-select/model-select.class.js +1 -1
- package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
- package/dist/components/conversation/voice-picker/voice-picker.class.d.ts +0 -1
- package/dist/components/conversation/voice-picker/voice-picker.class.js +1 -1
- package/dist/components/data/data-grid/data-grid.class.js +1 -1
- package/dist/components/data/funnel/funnel.class.d.ts +92 -0
- package/dist/components/data/funnel/funnel.class.js +25 -0
- package/dist/components/data/funnel/funnel.d.ts +1 -0
- package/dist/components/data/funnel/funnel.js +1 -0
- package/dist/components/data/funnel/funnel.styles.d.ts +1 -0
- package/dist/components/data/funnel/funnel.styles.js +127 -0
- package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +0 -1
- package/dist/components/data/graph-query-builder/graph-query-builder.class.js +1 -1
- package/dist/components/data/heatmap/heatmap.class.d.ts +199 -14
- package/dist/components/data/heatmap/heatmap.class.js +30 -22
- package/dist/components/data/heatmap/heatmap.styles.js +36 -0
- package/dist/components/data/index.d.ts +1 -0
- package/dist/components/data/index.js +1 -1
- package/dist/components/data/table/table.class.d.ts +18 -4
- package/dist/components/data/table/table.class.js +2 -2
- package/dist/components/data/table/table.styles.js +2 -1
- package/dist/components/data/timeline/timeline-cluster.d.ts +1 -0
- package/dist/components/data/timeline/timeline-cluster.js +1 -0
- package/dist/components/data/timeline/timeline-item.class.d.ts +17 -2
- package/dist/components/data/timeline/timeline-item.class.js +13 -2
- package/dist/components/data/timeline/timeline-item.styles.js +65 -0
- package/dist/components/data/timeline/timeline.class.d.ts +83 -27
- package/dist/components/data/timeline/timeline.class.js +3 -3
- package/dist/components/data/timeline/timeline.d.ts +1 -0
- package/dist/components/data/timeline/timeline.js +1 -1
- package/dist/components/data/timeline/timeline.styles.js +14 -0
- package/dist/components/forms/button/button.class.js +1 -1
- package/dist/components/forms/checkbox/checkbox.class.d.ts +0 -1
- package/dist/components/forms/checkbox/checkbox.class.js +1 -1
- package/dist/components/forms/checkbox-group/checkbox-group.class.d.ts +0 -1
- package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
- package/dist/components/forms/code-editor/code-editor.class.js +1 -1
- package/dist/components/forms/color-picker/color-picker.class.js +1 -1
- package/dist/components/forms/combobox/combobox.class.d.ts +7 -1
- package/dist/components/forms/combobox/combobox.class.js +3 -2
- package/dist/components/forms/combobox/combobox.styles.js +1 -1
- package/dist/components/forms/date-picker/date-input.class.d.ts +23 -0
- package/dist/components/forms/date-picker/date-input.class.js +1 -1
- package/dist/components/forms/emoji-picker/emoji-data-loader.d.ts +0 -1
- package/dist/components/forms/input/native-time-input.class.js +1 -1
- package/dist/components/forms/input/time-input-shared.d.ts +2 -1
- package/dist/components/forms/input/time-input.class.js +1 -1
- package/dist/components/forms/locale-picker/locale-picker.class.d.ts +0 -1
- package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
- package/dist/components/forms/radio/radio-button.styles.d.ts +0 -1
- package/dist/components/forms/radio/radio-button.styles.js +1 -1
- package/dist/components/forms/radio/radio-group.class.d.ts +0 -1
- package/dist/components/forms/radio/radio-group.class.js +1 -1
- package/dist/components/forms/radio/radio.class.d.ts +0 -1
- package/dist/components/forms/radio/radio.class.js +1 -1
- package/dist/components/forms/rubric-form/rubric-form.class.d.ts +0 -1
- package/dist/components/forms/rubric-form/rubric-form.class.js +1 -1
- package/dist/components/forms/select/select.class.d.ts +0 -1
- package/dist/components/forms/select/select.class.js +1 -1
- package/dist/components/forms/slider/slider.class.d.ts +0 -1
- package/dist/components/forms/slider/slider.class.js +1 -1
- package/dist/components/forms/switch/switch.class.d.ts +0 -1
- package/dist/components/forms/switch/switch.class.js +1 -1
- package/dist/components/forms/time-range/time-range.class.d.ts +0 -1
- package/dist/components/forms/time-range/time-range.class.js +1 -1
- package/dist/components/forms/token-input/token-input.class.d.ts +0 -1
- package/dist/components/forms/token-input/token-input.class.js +1 -1
- package/dist/components/layout/app-rail/app-rail-item.class.d.ts +16 -0
- package/dist/components/layout/app-rail/app-rail-item.class.js +4 -4
- package/dist/components/layout/dashboard-grid/layout-internal.d.ts +0 -1
- package/dist/components/layout/dashboard-grid/layout-internal.js +1 -1
- package/dist/components/layout/details/accordion-owner.d.ts +1 -1
- package/dist/components/layout/filter-bar/filter-bar.class.d.ts +32 -3
- package/dist/components/layout/filter-bar/filter-bar.class.js +2 -1
- package/dist/components/layout/menu/menu-item.class.js +1 -1
- package/dist/components/layout/virtual-list/virtual-list.class.js +1 -1
- package/dist/components/layout/widget/widget.class.d.ts +16 -0
- package/dist/components/layout/widget/widget.class.js +2 -2
- package/dist/components/lr-funnel.d.ts +1 -0
- package/dist/components/lr-funnel.js +1 -0
- package/dist/components/media/av-player/av-metadata.d.ts +0 -2
- package/dist/components/media/av-player/av-metadata.js +1 -1
- package/dist/components/media/file-input/file-input.class.d.ts +0 -1
- package/dist/components/media/file-input/file-input.class.js +1 -1
- package/dist/components/media/flag/flag-peer-bulk-standard.d.ts +25 -0
- package/dist/components/media/flag/flag-peer-bulk-standard.js +1 -0
- package/dist/components/media/flag/flag.class.d.ts +8 -0
- package/dist/components/media/flag/flag.class.js +1 -1
- package/dist/components/media/map/map-loader.d.ts +4 -1
- package/dist/components/media/map/map.class.d.ts +242 -23
- package/dist/components/media/map/map.class.js +2 -2
- package/dist/components/overlays/chip/chip-group.class.d.ts +16 -0
- package/dist/components/overlays/chip/chip-group.class.js +10 -3
- package/dist/components/overlays/overlay/popover.class.d.ts +7 -1
- package/dist/components/overlays/overlay/popover.class.js +1 -1
- package/dist/components/overlays/overlay/tooltip.class.d.ts +1 -0
- package/dist/components/overlays/overlay/tooltip.class.js +1 -1
- package/dist/components/overlays/progress/progress-shared.d.ts +0 -2
- package/dist/components/overlays/progress/progress-shared.js +1 -1
- package/dist/components/overlays/rating/rating.class.js +1 -1
- package/dist/components/retrieval/graph/graph-canvas.d.ts +10 -9
- package/dist/components/retrieval/mind-map/mind-map-layout.d.ts +0 -4
- package/dist/components/retrieval/mind-map/mind-map-layout.js +1 -1
- package/dist/components/utility/format/format-options.d.ts +0 -2
- package/dist/components/utility/format/format-options.js +1 -1
- package/dist/components/utility/icon/icon-resource.d.ts +0 -2
- package/dist/components/utility/icon/icon-resource.js +1 -1
- package/dist/components/viewers/archive-viewer/zip-resource-guard.d.ts +2 -1
- package/dist/components/viewers/docx-viewer/docx-resource-guard.d.ts +0 -3
- package/dist/components/viewers/docx-viewer/docx-resource-guard.js +1 -1
- package/dist/components/viewers/ebook-viewer/ebook-loader.d.ts +2 -1
- package/dist/components/viewers/ebook-viewer/epub-resource-guard.d.ts +0 -3
- package/dist/components/viewers/ebook-viewer/epub-resource-guard.js +1 -1
- package/dist/components/viewers/pdf-viewer/pdf-loader.d.ts +2 -2
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +2 -2
- package/dist/components/viewers/pptx-viewer/pptx-resource-guard.d.ts +0 -2
- package/dist/components/viewers/pptx-viewer/pptx-resource-guard.js +1 -1
- package/dist/components/viewers/spreadsheet-viewer/xlsx-resource-guard.d.ts +0 -5
- package/dist/components/viewers/spreadsheet-viewer/xlsx-resource-guard.js +1 -1
- package/dist/custom-elements-jsx.d.ts +16 -8
- package/dist/events.d.ts +15 -0
- package/dist/internal/accessibility-visibility.d.ts +1 -1
- package/dist/internal/anchor-target.d.ts +1 -3
- package/dist/internal/anchor-target.js +2 -2
- package/dist/internal/anchored-overlay-runtime.d.ts +7 -0
- package/dist/internal/anchored-overlay-runtime.js +1 -0
- package/dist/internal/announcement-text.d.ts +1 -1
- package/dist/internal/ansi.d.ts +0 -4
- package/dist/internal/ansi.js +1 -1
- package/dist/internal/aria-ownership.d.ts +2 -1
- package/dist/internal/autoloader-manifest.js +1 -1
- package/dist/internal/autoloader-tags.d.ts +1 -1
- package/dist/internal/autoloader-tags.js +1 -1
- package/dist/internal/default-strings.generated.d.ts +1 -0
- package/dist/internal/default-strings.generated.js +1 -1
- package/dist/internal/focus-navigation.d.ts +3 -2
- package/dist/internal/form-associated.d.ts +0 -1
- package/dist/internal/form-associated.js +1 -1
- package/dist/internal/form-control-labels.d.ts +0 -3
- package/dist/internal/form-control-labels.js +1 -1
- package/dist/internal/localization-runtime.js +1 -1
- package/dist/internal/localization-types.d.ts +1 -1
- package/dist/internal/localization.js +1 -1
- package/dist/internal/lyra-element.d.ts +7 -14
- package/dist/internal/lyra-element.js +1 -1
- package/dist/internal/nonmodal-overlay-manager.d.ts +9 -0
- package/dist/internal/nonmodal-overlay-manager.js +1 -0
- package/dist/internal/overlay-manager.d.ts +4 -20
- package/dist/internal/overlay-manager.js +1 -1
- package/dist/internal/overlay-stack.d.ts +66 -0
- package/dist/internal/overlay-stack.js +1 -0
- package/dist/internal/package-metadata.d.ts +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/positioner.js +1 -1
- package/dist/internal/root-registration-allowlist.d.ts +1 -1
- package/dist/internal/root-registration-allowlist.js +1 -1
- package/dist/internal/text-quote.d.ts +1 -1
- package/dist/lyra.d.ts +5 -4
- package/dist/lyra.js +1 -1
- package/dist/ssr/all.d.ts +1 -0
- package/dist/ssr/all.js +1 -1
- package/dist/ssr.d.ts +4 -4
- package/dist/styles/tokens-root.css +488 -0
- package/dist/svelte.d.ts +17 -8
- package/dist/translations/ar.js +1 -1
- package/dist/translations/de.js +1 -1
- package/dist/translations/es.js +1 -1
- package/dist/translations/fa.js +1 -1
- package/dist/translations/fr.js +1 -1
- package/dist/translations/he.js +1 -1
- package/dist/translations/ja.js +1 -1
- package/dist/translations/pt-BR.js +1 -1
- package/dist/translations/ru.js +1 -1
- package/dist/translations/zh-CN.js +1 -1
- package/dist/utilities/localization.js +1 -1
- package/dist/vue.d.ts +16 -8
- package/llms/components/lr-app-rail-item.md +8 -1
- package/llms/components/lr-app-rail.md +6 -0
- package/llms/components/lr-chip-group.md +7 -0
- package/llms/components/lr-chip.md +7 -0
- package/llms/components/lr-combobox.md +42 -0
- package/llms/components/lr-date-input.md +19 -1
- package/llms/components/lr-date-picker.md +19 -1
- package/llms/components/lr-filter-bar.md +50 -1
- package/llms/components/lr-flag.md +14 -0
- package/llms/components/lr-funnel.md +122 -0
- package/llms/components/lr-heatmap.md +55 -8
- package/llms/components/lr-lite-chart.md +20 -8
- package/llms/components/lr-map.md +109 -22
- package/llms/components/lr-option.md +42 -0
- package/llms/components/lr-popover.md +39 -0
- package/llms/components/lr-table.md +7 -3
- package/llms/components/lr-timeline-item.md +49 -24
- package/llms/components/lr-timeline.md +49 -24
- package/llms/components/lr-widget.md +7 -1
- package/llms/index.md +3 -2
- package/llms/peers.md +1 -1
- package/llms/shared.md +110 -1
- package/llms-full.txt +681 -67
- package/llms.txt +1 -1
- package/package.json +26 -8
- package/vscode-css-data.json +63 -0
- package/vscode-html-data.json +108 -23
- package/web-types.json +32738 -310
|
@@ -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{LyraElement}from"../../../internal/lyra-element.js";import"../../../internal/form-control-labels.js";import{place}from"../../../internal/positioner.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{activateOverlay}from"../../../internal/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,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.restoreFocusOnClose=!0,this._isFirstUpdate=!0,this.openVetoed=!1,this.openStateGeneration=0,this.transitionToken=0,this.transitionWaiters=new Map,this._selected=[],this._selectedOptions=[],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.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 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}connectedCallback(){super.connectedCallback(),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[index],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.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.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);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"}))}activateListboxOverlay(){this.cleanup?.(),this.cleanup=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.restoreFocusOnClose=!0,this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="listbox"]'),onEscape:()=>{this.hide()},onBackdrop:()=>{this.restoreFocusOnClose=!1,this.hide()},restoreFocusTo:this.triggerElement??null,modal:!1,trapFocus:!1}),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);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(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{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{place}from"../../../internal/positioner.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,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.restoreFocusOnClose=!0,this._isFirstUpdate=!0,this.openVetoed=!1,this.openStateGeneration=0,this.transitionToken=0,this.transitionWaiters=new Map,this._selected=[],this._selectedOptions=[],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.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 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}connectedCallback(){super.connectedCallback(),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[index],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.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.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);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"}))}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);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(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
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { type PropertyValues, type TemplateResult } from 'lit';
|
|
2
2
|
import { LyraElement } from '../../../internal/lyra-element.js';
|
|
3
|
-
import '../../../internal/form-control-labels.js';
|
|
4
3
|
import { type FormOwnerValue } from '../../../internal/form-associated.js';
|
|
5
4
|
import type { LyraSize } from '../../../internal/variants.js';
|
|
6
5
|
import { type LyraFormValidator } from '../form-validator.js';
|
|
@@ -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"../../../internal/form-control-labels.js";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{decimalPlaces,finiteInterpolate,finiteNumber,finiteRange,finiteRatio,isSliderKey}from"../../../internal/numbers.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{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}}}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.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.setValueFor(handle,next,!1)&&(this.pendingKeyHandle=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&&this.beginDrag(e.pointerId,handle,e.target,this.trackRect(),isRtl(this))},this.onBasePointerDown=e=>{if(!this.interactive)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.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),this._value=this.clampValue(finiteNumber(Number(next),this.defaultNumericValue())),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.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){const old=this._min;this._min=finiteNumber(next,0),this.requestUpdate("min",old),this.sanitizeCurrentValue()}get max(){return this._max}set max(next){const old=this._max;this._max=finiteNumber(next,100),this.requestUpdate("max",old),this.sanitizeCurrentValue()}get step(){return this._step}set step(next){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 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 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)}connectedCallback(){super.connectedCallback(),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),!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),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(){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.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.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()}resetValidity(){this.setCustomValidity("")}formResetCallback(){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.readonly}sanitizeCurrentValue(){this.sanitizeHandles();const old=this._value;this._value=this.clampValue(this._value),this._value!==old&&this.requestUpdate("value",old),this.syncFormValue()}sanitizeHandles(){this._minValue=this.clampValue(this._minValue),this._maxValue=this.clampValue(this._maxValue),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();raw=finiteNumber(raw,lo);const step=finiteRange(this.step,0,0),hasStep=step>0;let stepped=raw;if(hasStep){const stepsFromLo=Math.round((raw-lo)/step);if(Number.isFinite(stepsFromLo)){const candidate=lo+stepsFromLo*step,factor=10**Math.min(decimalPlaces(step),15);Number.isFinite(candidate)&&(stepped=Number.isFinite(candidate*factor)?Math.round(candidate*factor)/factor:candidate)}}return Math.min(hi,Math.max(lo,stepped))}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.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(){return this.range?`${this.formatValue(this.minValue)}\u2013${this.formatValue(this.maxValue)}`:this.formatValue(this.valueAsNumber)}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{decimalPlaces,finiteInterpolate,finiteNumber,finiteRange,finiteRatio,isSliderKey}from"../../../internal/numbers.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{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}}}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.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.setValueFor(handle,next,!1)&&(this.pendingKeyHandle=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&&this.beginDrag(e.pointerId,handle,e.target,this.trackRect(),isRtl(this))},this.onBasePointerDown=e=>{if(!this.interactive)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.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),this._value=this.clampValue(finiteNumber(Number(next),this.defaultNumericValue())),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.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){const old=this._min;this._min=finiteNumber(next,0),this.requestUpdate("min",old),this.sanitizeCurrentValue()}get max(){return this._max}set max(next){const old=this._max;this._max=finiteNumber(next,100),this.requestUpdate("max",old),this.sanitizeCurrentValue()}get step(){return this._step}set step(next){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 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 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)}connectedCallback(){super.connectedCallback(),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),!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),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(){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.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.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()}resetValidity(){this.setCustomValidity("")}formResetCallback(){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.readonly}sanitizeCurrentValue(){this.sanitizeHandles();const old=this._value;this._value=this.clampValue(this._value),this._value!==old&&this.requestUpdate("value",old),this.syncFormValue()}sanitizeHandles(){this._minValue=this.clampValue(this._minValue),this._maxValue=this.clampValue(this._maxValue),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();raw=finiteNumber(raw,lo);const step=finiteRange(this.step,0,0),hasStep=step>0;let stepped=raw;if(hasStep){const stepsFromLo=Math.round((raw-lo)/step);if(Number.isFinite(stepsFromLo)){const candidate=lo+stepsFromLo*step,factor=10**Math.min(decimalPlaces(step),15);Number.isFinite(candidate)&&(stepped=Number.isFinite(candidate*factor)?Math.round(candidate*factor)/factor:candidate)}}return Math.min(hi,Math.max(lo,stepped))}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.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(){return this.range?`${this.formatValue(this.minValue)}\u2013${this.formatValue(this.maxValue)}`:this.formatValue(this.valueAsNumber)}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"
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { type TemplateResult, type PropertyValues } from 'lit';
|
|
2
2
|
import { LyraElement } from '../../../internal/lyra-element.js';
|
|
3
|
-
import '../../../internal/form-control-labels.js';
|
|
4
3
|
import type { LyraSize } from '../../../internal/variants.js';
|
|
5
4
|
import { type FormOwnerValue } from '../../../internal/form-associated.js';
|
|
6
5
|
import { type LyraFormValidator } from '../form-validator.js';
|
|
@@ -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"../../../internal/form-control-labels.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./switch.styles.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{hasRealContent}from"../../../internal/a11y.js";import{isActionableElement}from"../../../internal/focus-navigation.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_switchRequired}from"../../../internal/default-strings.generated.js";class LyraSwitch extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,switchRequired:LYRA_DEFAULT_switchRequired}}static get validators(){return[currentValidityValidator("required","disabled","checked","value")]}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.formAssociated=!0}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},checked:{attribute:!1,noAccessor:!0},defaultChecked:{attribute:"checked",type:Boolean,reflect:!0,useDefault:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},required:{type:Boolean,reflect:!0,noAccessor:!0},size:{reflect:!0},value:{reflect:!0,noAccessor:!0}}}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get checked(){return this._checked}set checked(next){const old=this._checked;this.settingDefaultChecked||(this._checkedDirty=!0),this._checked=!!next,this.syncFormState(),this.requestUpdate("checked",old)}get defaultChecked(){return this._defaultChecked}set defaultChecked(next){if(this.reflectingDefaultChecked)return;const old=this._defaultChecked;this._defaultChecked=!!next,this.reflectingDefaultChecked=!0;try{this.toggleAttribute("checked",this._defaultChecked)}finally{this.reflectingDefaultChecked=!1}this._checkedDirty||this.restoreCheckedFromDefault(),this.requestUpdate("defaultChecked",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this.updateValidity(),this.requestUpdate("disabled",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),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 value(){return this._value}set value(next){const old=this._value;this._value=next??"on",next==null?this.hasAttribute("value")&&this.removeAttribute("value"):this.getAttribute("value")!==this._value&&this.setAttribute("value",this._value),this.syncFormState(),this.requestUpdate("value",old,{reflect:!1})}constructor(){super(),this.size="m",this.hint="",this.helpText="",this.withHint=!1,this.errorText="",this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasHelpTextSlot=!1,this.hasErrorSlot=!1,this.touched=!1,this.hasInteracted=!1,this._defaultChecked=!1,this._checkedDirty=!1,this.settingDefaultChecked=!1,this.reflectingDefaultChecked=!1,this._fieldsetDisabled=!1,this._name="",this._checked=!1,this._disabled=!1,this._required=!1,this._value="on",this.onClick=event=>{const owner=this[VALIDITY_ANCHOR]();for(const target of event.composedPath()){if(target===event.currentTarget)break;if(target&&typeof target=="object"&&target.nodeType===1&&target!==owner&&isActionableElement(target))return}this.setFromUser(!this.checked)},this.onBlur=event=>{this.liveDisabled||(this.touched=!0,this.hasInteracted=!0,this.reflectValidityStates()),relayNativeEvent(this,event)},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onKeyDown=e=>{if(!this.liveDisabled&&!e.repeat){if(e.key===" "||e.key==="Spacebar"){e.preventDefault(),this.setFromUser(!this.checked);return}if(e.key==="ArrowLeft"||e.key==="ArrowRight"){e.preventDefault();const turnsOn=this.effectiveDirection==="rtl"?e.key==="ArrowLeft":e.key==="ArrowRight";this.setFromUser(turnsOn)}}},this.onLabelSlotChange=event=>this.handleLabelSlotChange(event),this.onSlotChange=event=>this.handleLabelSlotChange(event),this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:!0}).length>0},this.onHelpTextSlotChange=e=>{this.hasHelpTextSlot=e.target.assignedElements({flatten:!0}).length>0},this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:!0}).length>0},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.syncFormState()}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector(".switch-owner")??null}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}click(){this.liveDisabled||this[VALIDITY_ANCHOR]()?.click()}focus(options){this.liveDisabled||this[VALIDITY_ANCHOR]()?.focus(options)}blur(){this[VALIDITY_ANCHOR]()?.blur()}connectedCallback(){super.connectedCallback(),this.updateValidity();const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;this.labelObserver=MutationObserverCtor?new MutationObserverCtor(()=>{this.bindLabelObserverTargets(),this.recomputeHasLabelSlot()}):void 0,this.addEventListener("slotchange",this.onLabelSlotChange),this.bindLabelObserverTargets(),this.hasUpdated?this.recomputeLightDomSlotState():this.seedFirstRenderState(()=>this.recomputeLightDomSlotState())}disconnectedCallback(){this.removeEventListener("slotchange",this.onLabelSlotChange),this.labelObserver?.disconnect(),this.labelObserver=void 0,super.disconnectedCallback()}willUpdate(changed){super.willUpdate(changed)}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){this.barredFromValidation?this.validityController.setValidity({}):this.required&&!this.checked?this.validityController.setValidity({valueMissing:!0},this.localize("switchRequired")):this.validityController.setValidity({}),this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred:this.barredFromValidation}),setCustomState(this.internals,"checked",this.checked),setCustomState(this.internals,"disabled",this.effectiveDisabled)}syncFormState(){this.internals.setFormValue(this.checked?this.value:null,this.checked?"checked":"unchecked"),this.updateValidity()}formResetCallback(){this.touched=!1,this.hasInteracted=!1,this.restoreCheckedFromDefault(),this.reflectValidityStates()}formStateRestoreCallback(state2,reason){this.checked=state2==="checked"}restoreCheckedFromDefault(){this.settingDefaultChecked=!0;try{this.checked=this._defaultChecked}finally{this.settingDefaultChecked=!1}this._checkedDirty=!1}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,this.updateValidity(),this.requestUpdate()}checkValidity(){return this.internals.checkValidity()}reportValidity(){return this.hasInteracted=!0,this.reflectValidityStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.reflectValidityStates(),this.requestUpdate()}resetValidity(){this.setCustomValidity("")}setFromUser(next){this.liveDisabled||this.checked!==next&&(this.hasInteracted=!0,this.checked=next,dispatchNativeInputEvent(this),this.emit("lr-input",{checked:this.checked}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{checked:this.checked}))}isDefaultLabelNode(node){if(node.nodeType!==1)return!0;const slotName=node.getAttribute("slot");return slotName===null||slotName===""}labelForwardingSlots(){return Array.from(this.querySelectorAll("slot")).filter(slot=>{let top=slot;for(;top.parentNode&&top.parentNode!==this;)top=top.parentNode;return top.parentNode===this&&this.isDefaultLabelNode(top)})}observeLabelNode(node){if(this.labelObserver){if(node.nodeType===3){this.labelObserver.observe(node,{characterData:!0});return}node.nodeType===1&&this.labelObserver.observe(node,{attributes:!0,attributeFilter:["aria-hidden","aria-label","class","hidden","inert","slot","style"],childList:!0,characterData:!0,subtree:!0})}}bindLabelObserverTargets(){if(this.labelObserver){this.labelObserver.disconnect(),this.observeLabelNode(this);for(const slot of this.labelForwardingSlots())if(slot.assignedNodes().length!==0)for(const assigned of slot.assignedNodes({flatten:!0}))this.observeLabelNode(assigned)}}recomputeHasLabelSlot(){const renderRoot=this.renderRoot,childNodes=this.childNodes;if(!renderRoot||!childNodes)return;const slot=renderRoot.querySelector("slot:not([name])"),nodes=slot?slot.assignedNodes({flatten:!0}):Array.from(childNodes).filter(node=>this.isDefaultLabelNode(node)).flatMap(node=>{if(node.nodeType!==1||node.localName!=="slot")return[node];const forwardingSlot=node;return forwardingSlot.assignedNodes().length>0?forwardingSlot.assignedNodes({flatten:!0}):Array.from(forwardingSlot.childNodes)});this.hasLabelSlot=hasRealContent(nodes)}recomputeLightDomSlotState(){this.recomputeHasLabelSlot();const children=this.children;children&&(this.hasHintSlot=Array.from(children).some(element=>element.getAttribute("slot")==="hint"),this.hasHelpTextSlot=Array.from(children).some(element=>element.getAttribute("slot")==="help-text"),this.hasErrorSlot=Array.from(children).some(element=>element.getAttribute("slot")==="error"))}handleLabelSlotChange(event){const target=event.target;target?.nodeType!==1||target.localName!=="slot"||target.getRootNode()!==this.renderRoot&&!this.labelForwardingSlots().includes(target)||(this.bindLabelObserverTargets(),this.recomputeHasLabelSlot())}render(){const hasHint=this.withHint||this.hasHintSlot||this.hasHelpTextSlot||this.hint.length>0||this.helpText.length>0,hasError=this.hasErrorSlot||this.errorText.length>0,describedBy=[hasError?"switch-error":"",hasHint?"switch-hint":""].filter(Boolean).join(" ");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{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./switch.styles.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{hasRealContent}from"../../../internal/a11y.js";import{isActionableElement}from"../../../internal/focus-navigation.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_switchRequired}from"../../../internal/default-strings.generated.js";class LyraSwitch extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,switchRequired:LYRA_DEFAULT_switchRequired}}static get validators(){return[currentValidityValidator("required","disabled","checked","value")]}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.formAssociated=!0}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},checked:{attribute:!1,noAccessor:!0},defaultChecked:{attribute:"checked",type:Boolean,reflect:!0,useDefault:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},required:{type:Boolean,reflect:!0,noAccessor:!0},size:{reflect:!0},value:{reflect:!0,noAccessor:!0}}}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get checked(){return this._checked}set checked(next){const old=this._checked;this.settingDefaultChecked||(this._checkedDirty=!0),this._checked=!!next,this.syncFormState(),this.requestUpdate("checked",old)}get defaultChecked(){return this._defaultChecked}set defaultChecked(next){if(this.reflectingDefaultChecked)return;const old=this._defaultChecked;this._defaultChecked=!!next,this.reflectingDefaultChecked=!0;try{this.toggleAttribute("checked",this._defaultChecked)}finally{this.reflectingDefaultChecked=!1}this._checkedDirty||this.restoreCheckedFromDefault(),this.requestUpdate("defaultChecked",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this.updateValidity(),this.requestUpdate("disabled",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),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 value(){return this._value}set value(next){const old=this._value;this._value=next??"on",next==null?this.hasAttribute("value")&&this.removeAttribute("value"):this.getAttribute("value")!==this._value&&this.setAttribute("value",this._value),this.syncFormState(),this.requestUpdate("value",old,{reflect:!1})}constructor(){super(),this.size="m",this.hint="",this.helpText="",this.withHint=!1,this.errorText="",this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasHelpTextSlot=!1,this.hasErrorSlot=!1,this.touched=!1,this.hasInteracted=!1,this._defaultChecked=!1,this._checkedDirty=!1,this.settingDefaultChecked=!1,this.reflectingDefaultChecked=!1,this._fieldsetDisabled=!1,this._name="",this._checked=!1,this._disabled=!1,this._required=!1,this._value="on",this.onClick=event=>{const owner=this[VALIDITY_ANCHOR]();for(const target of event.composedPath()){if(target===event.currentTarget)break;if(target&&typeof target=="object"&&target.nodeType===1&&target!==owner&&isActionableElement(target))return}this.setFromUser(!this.checked)},this.onBlur=event=>{this.liveDisabled||(this.touched=!0,this.hasInteracted=!0,this.reflectValidityStates()),relayNativeEvent(this,event)},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onKeyDown=e=>{if(!this.liveDisabled&&!e.repeat){if(e.key===" "||e.key==="Spacebar"){e.preventDefault(),this.setFromUser(!this.checked);return}if(e.key==="ArrowLeft"||e.key==="ArrowRight"){e.preventDefault();const turnsOn=this.effectiveDirection==="rtl"?e.key==="ArrowLeft":e.key==="ArrowRight";this.setFromUser(turnsOn)}}},this.onLabelSlotChange=event=>this.handleLabelSlotChange(event),this.onSlotChange=event=>this.handleLabelSlotChange(event),this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:!0}).length>0},this.onHelpTextSlotChange=e=>{this.hasHelpTextSlot=e.target.assignedElements({flatten:!0}).length>0},this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:!0}).length>0},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.syncFormState()}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector(".switch-owner")??null}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}click(){this.liveDisabled||this[VALIDITY_ANCHOR]()?.click()}focus(options){this.liveDisabled||this[VALIDITY_ANCHOR]()?.focus(options)}blur(){this[VALIDITY_ANCHOR]()?.blur()}connectedCallback(){super.connectedCallback(),this.updateValidity();const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;this.labelObserver=MutationObserverCtor?new MutationObserverCtor(()=>{this.bindLabelObserverTargets(),this.recomputeHasLabelSlot()}):void 0,this.addEventListener("slotchange",this.onLabelSlotChange),this.bindLabelObserverTargets(),this.hasUpdated?this.recomputeLightDomSlotState():this.seedFirstRenderState(()=>this.recomputeLightDomSlotState())}disconnectedCallback(){this.removeEventListener("slotchange",this.onLabelSlotChange),this.labelObserver?.disconnect(),this.labelObserver=void 0,super.disconnectedCallback()}willUpdate(changed){super.willUpdate(changed)}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){this.barredFromValidation?this.validityController.setValidity({}):this.required&&!this.checked?this.validityController.setValidity({valueMissing:!0},this.localize("switchRequired")):this.validityController.setValidity({}),this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred:this.barredFromValidation}),setCustomState(this.internals,"checked",this.checked),setCustomState(this.internals,"disabled",this.effectiveDisabled)}syncFormState(){this.internals.setFormValue(this.checked?this.value:null,this.checked?"checked":"unchecked"),this.updateValidity()}formResetCallback(){this.touched=!1,this.hasInteracted=!1,this.restoreCheckedFromDefault(),this.reflectValidityStates()}formStateRestoreCallback(state2,reason){this.checked=state2==="checked"}restoreCheckedFromDefault(){this.settingDefaultChecked=!0;try{this.checked=this._defaultChecked}finally{this.settingDefaultChecked=!1}this._checkedDirty=!1}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,this.updateValidity(),this.requestUpdate()}checkValidity(){return this.internals.checkValidity()}reportValidity(){return this.hasInteracted=!0,this.reflectValidityStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.reflectValidityStates(),this.requestUpdate()}resetValidity(){this.setCustomValidity("")}setFromUser(next){this.liveDisabled||this.checked!==next&&(this.hasInteracted=!0,this.checked=next,dispatchNativeInputEvent(this),this.emit("lr-input",{checked:this.checked}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{checked:this.checked}))}isDefaultLabelNode(node){if(node.nodeType!==1)return!0;const slotName=node.getAttribute("slot");return slotName===null||slotName===""}labelForwardingSlots(){return Array.from(this.querySelectorAll("slot")).filter(slot=>{let top=slot;for(;top.parentNode&&top.parentNode!==this;)top=top.parentNode;return top.parentNode===this&&this.isDefaultLabelNode(top)})}observeLabelNode(node){if(this.labelObserver){if(node.nodeType===3){this.labelObserver.observe(node,{characterData:!0});return}node.nodeType===1&&this.labelObserver.observe(node,{attributes:!0,attributeFilter:["aria-hidden","aria-label","class","hidden","inert","slot","style"],childList:!0,characterData:!0,subtree:!0})}}bindLabelObserverTargets(){if(this.labelObserver){this.labelObserver.disconnect(),this.observeLabelNode(this);for(const slot of this.labelForwardingSlots())if(slot.assignedNodes().length!==0)for(const assigned of slot.assignedNodes({flatten:!0}))this.observeLabelNode(assigned)}}recomputeHasLabelSlot(){const renderRoot=this.renderRoot,childNodes=this.childNodes;if(!renderRoot||!childNodes)return;const slot=renderRoot.querySelector("slot:not([name])"),nodes=slot?slot.assignedNodes({flatten:!0}):Array.from(childNodes).filter(node=>this.isDefaultLabelNode(node)).flatMap(node=>{if(node.nodeType!==1||node.localName!=="slot")return[node];const forwardingSlot=node;return forwardingSlot.assignedNodes().length>0?forwardingSlot.assignedNodes({flatten:!0}):Array.from(forwardingSlot.childNodes)});this.hasLabelSlot=hasRealContent(nodes)}recomputeLightDomSlotState(){this.recomputeHasLabelSlot();const children=this.children;children&&(this.hasHintSlot=Array.from(children).some(element=>element.getAttribute("slot")==="hint"),this.hasHelpTextSlot=Array.from(children).some(element=>element.getAttribute("slot")==="help-text"),this.hasErrorSlot=Array.from(children).some(element=>element.getAttribute("slot")==="error"))}handleLabelSlotChange(event){const target=event.target;target?.nodeType!==1||target.localName!=="slot"||target.getRootNode()!==this.renderRoot&&!this.labelForwardingSlots().includes(target)||(this.bindLabelObserverTargets(),this.recomputeHasLabelSlot())}render(){const hasHint=this.withHint||this.hasHintSlot||this.hasHelpTextSlot||this.hint.length>0||this.helpText.length>0,hasError=this.hasErrorSlot||this.errorText.length>0,describedBy=[hasError?"switch-error":"",hasHint?"switch-hint":""].filter(Boolean).join(" ");return html`
|
|
2
2
|
<div part="form-control">
|
|
3
3
|
<span class="switch-layout" part="row" @click=${this.onClick}>
|
|
4
4
|
<span
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { type TemplateResult, type PropertyValues } from 'lit';
|
|
2
2
|
import { LyraElement } from '../../../internal/lyra-element.js';
|
|
3
|
-
import '../../../internal/form-control-labels.js';
|
|
4
3
|
import type { LyraSize } from '../../../internal/variants.js';
|
|
5
4
|
import { type FormOwnerValue } from '../../../internal/form-associated.js';
|
|
6
5
|
export type TimeRangeHandle = 'start' | 'end';
|
|
@@ -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}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import"../../../internal/form-control-labels.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{isRtl}from"../../../internal/rtl.js";import{decimalPlaces,finiteAdd,finiteInterpolate,finiteNumber,finiteRange,finiteRatio,isSliderKey}from"../../../internal/numbers.js";import{styles}from"./time-range.styles.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{activeElementIn}from"../../../internal/active-element.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_rangeEnd,LYRA_DEFAULT_rangeStart}from"../../../internal/default-strings.generated.js";const PAGE_STEP_MULTIPLIER=10;function createInternalsSafely(host){if(typeof host.attachInternals!="function")return createNoopInternals();try{return host.attachInternals()}catch{return createNoopInternals()}}function createNoopInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:!1,setFormValue(){},setValidity(){},checkValidity(){return!0},reportValidity(){return!0},states:new Set}}class LyraTimeRange extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,rangeEnd:LYRA_DEFAULT_rangeEnd,rangeStart:LYRA_DEFAULT_rangeStart}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,styles]}static{this.properties={disabled:{type:Boolean,reflect:!0,noAccessor:!0},customError:{attribute:"custom-error",reflect:!0,noAccessor:!0}}}get presets(){return this._presets}set presets(next){const previous=this._presets,snapshots=[];if(Array.isArray(next))for(let index=0;index<Math.min(next.length,256);index+=1)try{const raw=next[index];if(raw===null||typeof raw!="object"||typeof raw.label!="string"||typeof raw.start!="number"||typeof raw.end!="number")continue;snapshots.push(Object.freeze({label:raw.label,start:raw.start,end:raw.end}))}catch{}this._presets=Object.freeze(snapshots),this.requestUpdate("presets",previous)}constructor(){super(),this.min=0,this.max=100,this.start=0,this.end=100,this.step=1,this.size="m",this._presets=Object.freeze([]),this._disabled=!1,this._fieldsetDisabled=!1,this.drags=new Map,this.keyboardChanged=!1,this.hasInteracted=!1,this.markInteracted=()=>{this.liveDisabled||this.hasInteracted||(this.hasInteracted=!0,this.reflectValidityStates())},this.onHandleFocus=event=>{relayNativeEvent(this,event)},this.onHandleBlur=event=>{this.finishKeyboardGesture(),relayNativeEvent(this,event)},this.onKeyDown=(handle,e)=>{if(this.liveDisabled)return;const current=handle==="start"?finiteRange(this.start,this.domain().lo):finiteRange(this.end,this.domain().hi),step=finiteRange(this.step,0,0),move=(direction,multiplier=1)=>{const delta=finiteRange(step*multiplier,Number.MAX_VALUE,0,Number.MAX_VALUE);delta!==0&&(this.keyboardChanged=this.setValue(handle,finiteAdd(current,direction*delta,current),!1)||this.keyboardChanged)},rtl=isRtl(this),forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";e.key===forwardKey||e.key==="ArrowUp"?(e.preventDefault(),move(1)):e.key===backwardKey||e.key==="ArrowDown"?(e.preventDefault(),move(-1)):e.key==="PageUp"?(e.preventDefault(),move(1,PAGE_STEP_MULTIPLIER)):e.key==="PageDown"?(e.preventDefault(),move(-1,PAGE_STEP_MULTIPLIER)):e.key==="Home"?(e.preventDefault(),this.keyboardChanged=this.setValue(handle,this.reachableBounds(handle).min,!1)||this.keyboardChanged):e.key==="End"&&(e.preventDefault(),this.keyboardChanged=this.setValue(handle,this.reachableBounds(handle).max,!1)||this.keyboardChanged)},this.onKeyUp=e=>{isSliderKey(e.key)&&this.finishKeyboardGesture()},this.onPointerDown=(handle,e)=>{this.beginDrag(handle,e,e.target)},this.onBasePointerDown=e=>{if(this.liveDisabled)return;const handles=Array.from(this.renderRoot.querySelectorAll('[part="handle-start"],[part="handle-end"]'));if(handles.length===0||handles.includes(e.target))return;const base=this.renderRoot.querySelector('[part="base"]');if(!base)return;const rect=base.getBoundingClientRect();if(rect.width===0)return;const target=this.valueAtPointer(e.clientX,rect,isRtl(this)),handle=this.nearestHandle(target),handleEl=this.renderRoot.querySelector(`[part="handle-${handle}"]`);if(!handleEl)return;const drag=this.beginDrag(handle,e,handleEl);drag&&(this.setValue(handle,target,!1)&&(drag.changed=!0),handleEl.focus())},this.onPointerMove=e=>{const drag=this.drags.get(e.pointerId);if(drag===void 0)return;if(this.liveDisabled){this.endDrag(e.pointerId,!1);return}const value=this.valueAtPointer(e.clientX,drag.rect,drag.rtl);drag.changed=this.setValue(drag.handle,value,!1)||drag.changed},this.onPointerUp=e=>{this.endDrag(e.pointerId,e.type==="pointerup"&&!this.liveDisabled)},this.internals=createInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.addEventListener("focusout",this.markInteracted),this.reflectValidityStates()}get liveDisabled(){return this.effectiveDisabled||typeof this.matches=="function"&&this.matches(":disabled")}emitInput(){dispatchNativeEvent(this,"input"),this.emit("lr-input",{start:this.start,end:this.end})}emitChange(){dispatchNativeEvent(this,"change"),this.emit("lr-change",{start:this.start,end:this.end})}reflectValidityStates(){syncValidityStates(this.internals,{required:!1,hasInteracted:this.hasInteracted,barred:isBarredFromValidation(this,this.internals)})}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="handle-start"]')??null}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}checkValidity(){return this.internals.checkValidity()}reportValidity(){return this.markInteracted(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.reflectValidityStates()}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this._disabled&&this.abortActiveGestures(),this.toggleAttribute("disabled",this._disabled),this.reflectValidityStates(),this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,disabled&&this.abortActiveGestures(),this.reflectValidityStates(),this.requestUpdate()}declaredHandleValue(handle,fallback){const declared=this.getAttribute(handle);return declared===null?fallback:finiteNumber(Number(declared),fallback)}formResetCallback(){const{lo,hi}=this.domain(),declaredStart=this.declaredHandleValue("start",lo),declaredEnd=this.declaredHandleValue("end",hi),start=finiteRange(declaredStart,lo,lo,hi),end=finiteRange(declaredEnd,hi,lo,hi);this.start=Math.min(start,end),this.end=Math.max(start,end),this.abortActiveGestures(),this.hasInteracted=!1,this.reflectValidityStates()}disconnectedCallback(){super.disconnectedCallback(),this.drags.clear(),this.keyboardChanged=!1,this.teardownDragWindow()}adoptedCallback(){super.adoptedCallback(),this.drags.clear(),this.keyboardChanged=!1,this.teardownDragWindow()}click(){this.liveDisabled||this.renderRoot?.querySelector('[part="handle-start"]')?.click()}focus(options){this.liveDisabled||this.renderRoot?.querySelector('[part="handle-start"]')?.focus(options)}blur(){const active=activeElementIn(this.shadowRoot);active?.nodeType===1&&typeof active.matches=="function"&&typeof active.blur=="function"&&active.matches('[part^="handle-"]')?active.blur():this.renderRoot?.querySelector('[part="handle-start"]')?.blur()}domain(){const min=finiteNumber(this.min,0),max=finiteNumber(this.max,100);return{lo:Math.min(min,max),hi:Math.max(min,max)}}percentOf(value){const{lo,hi}=this.domain(),safeValue=finiteRange(value,lo,lo,hi);return finiteRatio(safeValue,lo,hi)*100}reachableBounds(handle){const{lo,hi}=this.domain(),start=finiteRange(this.start,lo,lo,hi),end=finiteRange(this.end,hi,lo,hi);return handle==="start"?{min:lo,max:end}:{min:start,max:hi}}clamp(handle,value){const{lo,hi}=this.domain();let stepped=finiteNumber(value,lo);const step=finiteRange(this.step,0,0);if(Number.isFinite(step)&&step>0){const stepsFromLo=Math.round((stepped-lo)/step);if(Number.isFinite(stepsFromLo)){const candidate=lo+stepsFromLo*step,factor=10**Math.min(decimalPlaces(step),15);Number.isFinite(candidate)&&(stepped=Number.isFinite(candidate*factor)?Math.round(candidate*factor)/factor:candidate)}}const bounded=Math.min(hi,Math.max(lo,stepped));return handle==="start"?Math.min(bounded,finiteRange(this.end,hi,lo,hi)):Math.max(bounded,finiteRange(this.start,lo,lo,hi))}setValue(handle,value,commit){const clamped=this.clamp(handle,value),previous=handle==="start"?this.start:this.end;return clamped===previous?!1:(handle==="start"?this.start=clamped:this.end=clamped,this.markInteracted(),this.emitInput(),commit&&this.emitChange(),!0)}applyPreset(preset){if(this.liveDisabled)return;const{start:nextStart,end:nextEnd}=this.normalizePreset(preset);nextStart===this.start&&nextEnd===this.end||(this.start=nextStart,this.end=nextEnd,this.markInteracted(),this.emitInput(),this.emitChange())}normalizePreset(preset){const{lo,hi}=this.domain(),start=finiteRange(preset.start,lo,lo,hi),end=finiteRange(preset.end,hi,lo,hi);return{start:Math.min(start,end),end:Math.max(start,end)}}finishKeyboardGesture(){this.keyboardChanged&&(this.keyboardChanged=!1,this.liveDisabled||this.emitChange())}beginDrag(handle,e,captureTarget){if(this.liveDisabled)return;const base=this.renderRoot.querySelector('[part="base"]'),dragWindow=base?.ownerDocument.defaultView;if(!base||!this.isConnected||!dragWindow)return;const firstDrag=this.drags.size===0;if(!firstDrag&&this.dragWindow!==dragWindow)return;captureTarget.setPointerCapture?.(e.pointerId);const drag={handle,changed:!1,rect:base.getBoundingClientRect(),rtl:isRtl(this)};return this.drags.set(e.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)),drag}valueAtPointer(clientX,rect,rtl){const raw=rect.width===0?0:(clientX-rect.left)/rect.width,ratio=Math.min(1,Math.max(0,rtl?1-raw:raw)),{lo,hi}=this.domain();return finiteInterpolate(lo,hi,ratio)}nearestHandle(target){const{lo,hi}=this.domain(),start=finiteRange(this.start,lo),end=finiteRange(this.end,hi),toStart=Math.abs(target-start),toEnd=Math.abs(target-end);return toStart<toEnd?"start":toEnd<toStart?"end":target<start?"start":"end"}abortActiveGestures(){this.keyboardChanged=!1;for(const pointerId of[...this.drags.keys()])this.endDrag(pointerId,!1)}endDrag(pointerId,commit){const drag=this.drags.get(pointerId);drag&&(this.drags.delete(pointerId),commit&&drag.changed&&this.emitChange(),this.drags.size===0&&this.teardownDragWindow())}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)}willUpdate(changed){if(super.willUpdate(changed),changed.has("start")||changed.has("end")||changed.has("min")||changed.has("max")){const{lo,hi}=this.domain(),start=Number.isFinite(this.start)?finiteRange(this.start,lo,lo,hi):this.start,end=Number.isFinite(this.end)?finiteRange(this.end,hi,lo,hi):this.end;if(changed.has("start")&&changed.has("end")&&Number.isFinite(start)&&Number.isFinite(end)){this.start=Math.min(start,end),this.end=Math.max(start,end);return}Number.isFinite(start)&&(this.start=start),Number.isFinite(end)&&(this.end=end)}(changed.has("start")||changed.has("min")||changed.has("max"))&&Number.isFinite(this.start)&&Number.isFinite(this.end)&&(this.start=Math.min(this.start,this.end)),(changed.has("end")||changed.has("min")||changed.has("max"))&&Number.isFinite(this.start)&&Number.isFinite(this.end)&&(this.end=Math.max(this.end,this.start))}render(){const startPct=this.percentOf(this.start),endPct=this.percentOf(this.end),startBounds=this.reachableBounds("start"),endBounds=this.reachableBounds("end"),startValue=Number.isFinite(this.start)?finiteRange(this.start,startBounds.min,startBounds.min,startBounds.max):void 0,endValue=Number.isFinite(this.end)?finiteRange(this.end,endBounds.min,endBounds.min,endBounds.max):void 0,startValueText=startValue===void 0?void 0:this.valueFormatter?.(startValue,"start"),endValueText=endValue===void 0?void 0:this.valueFormatter?.(endValue,"end");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}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";installFormControlLabelSupport();import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{isRtl}from"../../../internal/rtl.js";import{decimalPlaces,finiteAdd,finiteInterpolate,finiteNumber,finiteRange,finiteRatio,isSliderKey}from"../../../internal/numbers.js";import{styles}from"./time-range.styles.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{activeElementIn}from"../../../internal/active-element.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_rangeEnd,LYRA_DEFAULT_rangeStart}from"../../../internal/default-strings.generated.js";const PAGE_STEP_MULTIPLIER=10;function createInternalsSafely(host){if(typeof host.attachInternals!="function")return createNoopInternals();try{return host.attachInternals()}catch{return createNoopInternals()}}function createNoopInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:!1,setValidity(){},checkValidity(){return!0},reportValidity(){return!0},states:new Set}}class LyraTimeRange extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,rangeEnd:LYRA_DEFAULT_rangeEnd,rangeStart:LYRA_DEFAULT_rangeStart}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,styles]}static{this.properties={disabled:{type:Boolean,reflect:!0,noAccessor:!0},customError:{attribute:"custom-error",reflect:!0,noAccessor:!0}}}get presets(){return this._presets}set presets(next){const previous=this._presets,snapshots=[];if(Array.isArray(next))for(let index=0;index<Math.min(next.length,256);index+=1)try{const raw=next[index];if(raw===null||typeof raw!="object"||typeof raw.label!="string"||typeof raw.start!="number"||typeof raw.end!="number")continue;snapshots.push(Object.freeze({label:raw.label,start:raw.start,end:raw.end}))}catch{}this._presets=Object.freeze(snapshots),this.requestUpdate("presets",previous)}constructor(){super(),this.min=0,this.max=100,this.start=0,this.end=100,this.step=1,this.size="m",this._presets=Object.freeze([]),this._disabled=!1,this._fieldsetDisabled=!1,this.drags=new Map,this.keyboardChanged=!1,this.hasInteracted=!1,this.markInteracted=()=>{this.liveDisabled||this.hasInteracted||(this.hasInteracted=!0,this.reflectValidityStates())},this.onHandleFocus=event=>{relayNativeEvent(this,event)},this.onHandleBlur=event=>{this.finishKeyboardGesture(),relayNativeEvent(this,event)},this.onKeyDown=(handle,e)=>{if(this.liveDisabled)return;const current=handle==="start"?finiteRange(this.start,this.domain().lo):finiteRange(this.end,this.domain().hi),step=finiteRange(this.step,0,0),move=(direction,multiplier=1)=>{const delta=finiteRange(step*multiplier,Number.MAX_VALUE,0,Number.MAX_VALUE);delta!==0&&(this.keyboardChanged=this.setValue(handle,finiteAdd(current,direction*delta,current),!1)||this.keyboardChanged)},rtl=isRtl(this),forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";e.key===forwardKey||e.key==="ArrowUp"?(e.preventDefault(),move(1)):e.key===backwardKey||e.key==="ArrowDown"?(e.preventDefault(),move(-1)):e.key==="PageUp"?(e.preventDefault(),move(1,PAGE_STEP_MULTIPLIER)):e.key==="PageDown"?(e.preventDefault(),move(-1,PAGE_STEP_MULTIPLIER)):e.key==="Home"?(e.preventDefault(),this.keyboardChanged=this.setValue(handle,this.reachableBounds(handle).min,!1)||this.keyboardChanged):e.key==="End"&&(e.preventDefault(),this.keyboardChanged=this.setValue(handle,this.reachableBounds(handle).max,!1)||this.keyboardChanged)},this.onKeyUp=e=>{isSliderKey(e.key)&&this.finishKeyboardGesture()},this.onPointerDown=(handle,e)=>{this.beginDrag(handle,e,e.target)},this.onBasePointerDown=e=>{if(this.liveDisabled)return;const handles=Array.from(this.renderRoot.querySelectorAll('[part="handle-start"],[part="handle-end"]'));if(handles.length===0||handles.includes(e.target))return;const base=this.renderRoot.querySelector('[part="base"]');if(!base)return;const rect=base.getBoundingClientRect();if(rect.width===0)return;const target=this.valueAtPointer(e.clientX,rect,isRtl(this)),handle=this.nearestHandle(target),handleEl=this.renderRoot.querySelector(`[part="handle-${handle}"]`);if(!handleEl)return;const drag=this.beginDrag(handle,e,handleEl);drag&&(this.setValue(handle,target,!1)&&(drag.changed=!0),handleEl.focus())},this.onPointerMove=e=>{const drag=this.drags.get(e.pointerId);if(drag===void 0)return;if(this.liveDisabled){this.endDrag(e.pointerId,!1);return}const value=this.valueAtPointer(e.clientX,drag.rect,drag.rtl);drag.changed=this.setValue(drag.handle,value,!1)||drag.changed},this.onPointerUp=e=>{this.endDrag(e.pointerId,e.type==="pointerup"&&!this.liveDisabled)},this.internals=createInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.addEventListener("focusout",this.markInteracted),this.reflectValidityStates()}get liveDisabled(){return this.effectiveDisabled||typeof this.matches=="function"&&this.matches(":disabled")}emitInput(){dispatchNativeEvent(this,"input"),this.emit("lr-input",{start:this.start,end:this.end})}emitChange(){dispatchNativeEvent(this,"change"),this.emit("lr-change",{start:this.start,end:this.end})}reflectValidityStates(){syncValidityStates(this.internals,{required:!1,hasInteracted:this.hasInteracted,barred:isBarredFromValidation(this,this.internals)})}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="handle-start"]')??null}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}checkValidity(){return this.internals.checkValidity()}reportValidity(){return this.markInteracted(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.reflectValidityStates()}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this._disabled&&this.abortActiveGestures(),this.toggleAttribute("disabled",this._disabled),this.reflectValidityStates(),this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,disabled&&this.abortActiveGestures(),this.reflectValidityStates(),this.requestUpdate()}declaredHandleValue(handle,fallback){const declared=this.getAttribute(handle);return declared===null?fallback:finiteNumber(Number(declared),fallback)}formResetCallback(){const{lo,hi}=this.domain(),declaredStart=this.declaredHandleValue("start",lo),declaredEnd=this.declaredHandleValue("end",hi),start=finiteRange(declaredStart,lo,lo,hi),end=finiteRange(declaredEnd,hi,lo,hi);this.start=Math.min(start,end),this.end=Math.max(start,end),this.abortActiveGestures(),this.hasInteracted=!1,this.reflectValidityStates()}disconnectedCallback(){super.disconnectedCallback(),this.drags.clear(),this.keyboardChanged=!1,this.teardownDragWindow()}adoptedCallback(){super.adoptedCallback(),this.drags.clear(),this.keyboardChanged=!1,this.teardownDragWindow()}click(){this.liveDisabled||this.renderRoot?.querySelector('[part="handle-start"]')?.click()}focus(options){this.liveDisabled||this.renderRoot?.querySelector('[part="handle-start"]')?.focus(options)}blur(){const active=activeElementIn(this.shadowRoot);active?.nodeType===1&&typeof active.matches=="function"&&typeof active.blur=="function"&&active.matches('[part^="handle-"]')?active.blur():this.renderRoot?.querySelector('[part="handle-start"]')?.blur()}domain(){const min=finiteNumber(this.min,0),max=finiteNumber(this.max,100);return{lo:Math.min(min,max),hi:Math.max(min,max)}}percentOf(value){const{lo,hi}=this.domain(),safeValue=finiteRange(value,lo,lo,hi);return finiteRatio(safeValue,lo,hi)*100}reachableBounds(handle){const{lo,hi}=this.domain(),start=finiteRange(this.start,lo,lo,hi),end=finiteRange(this.end,hi,lo,hi);return handle==="start"?{min:lo,max:end}:{min:start,max:hi}}clamp(handle,value){const{lo,hi}=this.domain();let stepped=finiteNumber(value,lo);const step=finiteRange(this.step,0,0);if(Number.isFinite(step)&&step>0){const stepsFromLo=Math.round((stepped-lo)/step);if(Number.isFinite(stepsFromLo)){const candidate=lo+stepsFromLo*step,factor=10**Math.min(decimalPlaces(step),15);Number.isFinite(candidate)&&(stepped=Number.isFinite(candidate*factor)?Math.round(candidate*factor)/factor:candidate)}}const bounded=Math.min(hi,Math.max(lo,stepped));return handle==="start"?Math.min(bounded,finiteRange(this.end,hi,lo,hi)):Math.max(bounded,finiteRange(this.start,lo,lo,hi))}setValue(handle,value,commit){const clamped=this.clamp(handle,value),previous=handle==="start"?this.start:this.end;return clamped===previous?!1:(handle==="start"?this.start=clamped:this.end=clamped,this.markInteracted(),this.emitInput(),commit&&this.emitChange(),!0)}applyPreset(preset){if(this.liveDisabled)return;const{start:nextStart,end:nextEnd}=this.normalizePreset(preset);nextStart===this.start&&nextEnd===this.end||(this.start=nextStart,this.end=nextEnd,this.markInteracted(),this.emitInput(),this.emitChange())}normalizePreset(preset){const{lo,hi}=this.domain(),start=finiteRange(preset.start,lo,lo,hi),end=finiteRange(preset.end,hi,lo,hi);return{start:Math.min(start,end),end:Math.max(start,end)}}finishKeyboardGesture(){this.keyboardChanged&&(this.keyboardChanged=!1,this.liveDisabled||this.emitChange())}beginDrag(handle,e,captureTarget){if(this.liveDisabled)return;const base=this.renderRoot.querySelector('[part="base"]'),dragWindow=base?.ownerDocument.defaultView;if(!base||!this.isConnected||!dragWindow)return;const firstDrag=this.drags.size===0;if(!firstDrag&&this.dragWindow!==dragWindow)return;captureTarget.setPointerCapture?.(e.pointerId);const drag={handle,changed:!1,rect:base.getBoundingClientRect(),rtl:isRtl(this)};return this.drags.set(e.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)),drag}valueAtPointer(clientX,rect,rtl){const raw=rect.width===0?0:(clientX-rect.left)/rect.width,ratio=Math.min(1,Math.max(0,rtl?1-raw:raw)),{lo,hi}=this.domain();return finiteInterpolate(lo,hi,ratio)}nearestHandle(target){const{lo,hi}=this.domain(),start=finiteRange(this.start,lo),end=finiteRange(this.end,hi),toStart=Math.abs(target-start),toEnd=Math.abs(target-end);return toStart<toEnd?"start":toEnd<toStart?"end":target<start?"start":"end"}abortActiveGestures(){this.keyboardChanged=!1;for(const pointerId of[...this.drags.keys()])this.endDrag(pointerId,!1)}endDrag(pointerId,commit){const drag=this.drags.get(pointerId);drag&&(this.drags.delete(pointerId),commit&&drag.changed&&this.emitChange(),this.drags.size===0&&this.teardownDragWindow())}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)}willUpdate(changed){if(super.willUpdate(changed),changed.has("start")||changed.has("end")||changed.has("min")||changed.has("max")){const{lo,hi}=this.domain(),start=Number.isFinite(this.start)?finiteRange(this.start,lo,lo,hi):this.start,end=Number.isFinite(this.end)?finiteRange(this.end,hi,lo,hi):this.end;if(changed.has("start")&&changed.has("end")&&Number.isFinite(start)&&Number.isFinite(end)){this.start=Math.min(start,end),this.end=Math.max(start,end);return}Number.isFinite(start)&&(this.start=start),Number.isFinite(end)&&(this.end=end)}(changed.has("start")||changed.has("min")||changed.has("max"))&&Number.isFinite(this.start)&&Number.isFinite(this.end)&&(this.start=Math.min(this.start,this.end)),(changed.has("end")||changed.has("min")||changed.has("max"))&&Number.isFinite(this.start)&&Number.isFinite(this.end)&&(this.end=Math.max(this.end,this.start))}render(){const startPct=this.percentOf(this.start),endPct=this.percentOf(this.end),startBounds=this.reachableBounds("start"),endBounds=this.reachableBounds("end"),startValue=Number.isFinite(this.start)?finiteRange(this.start,startBounds.min,startBounds.min,startBounds.max):void 0,endValue=Number.isFinite(this.end)?finiteRange(this.end,endBounds.min,endBounds.min,endBounds.max):void 0,startValueText=startValue===void 0?void 0:this.valueFormatter?.(startValue,"start"),endValueText=endValue===void 0?void 0:this.valueFormatter?.(endValue,"end");return html`
|
|
2
2
|
${this.presets.length>0?html`<div part="presets">
|
|
3
3
|
${this.presets.map(preset=>{const normalized=this.normalizePreset(preset),active=normalized.start===this.start&&normalized.end===this.end;return html`<button
|
|
4
4
|
part="preset-button"
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { type PropertyValues, type TemplateResult } from 'lit';
|
|
2
2
|
import { LyraElement } from '../../../internal/lyra-element.js';
|
|
3
|
-
import '../../../internal/form-control-labels.js';
|
|
4
3
|
import type { LyraSize } from '../../../internal/variants.js';
|
|
5
4
|
import { type FormOwnerValue } from '../../../internal/form-associated.js';
|
|
6
5
|
export interface LyraTokenInputEventMap {
|
|
@@ -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{LyraElement}from"../../../internal/lyra-element.js";import"../../../internal/form-control-labels.js";import{activeElementIn}from"../../../internal/active-element.js";import{captureComposedFocusRepair,applyComposedFocusRepair}from"../../../internal/focus-navigation.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{nextId}from"../../../internal/a11y.js";import{closeIcon}from"../../../internal/icons.js";import{autocorrectConverter,normalizeAutocorrect,spellcheckConverter}from"../../../internal/converters.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./token-input.styles.js";import{attachInternalsSafely,createStringArrayFormDataState,getFormOwner,installCustomErrorProperty,isBarredFromValidation,readStringArrayFormDataState,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_tokenInputEditWithContext,LYRA_DEFAULT_tokenInputRequired}from"../../../internal/default-strings.generated.js";const delimiterConverter={fromAttribute:value=>value===null?",":value===""||value==="none"?null:value,toAttribute:value=>value===null?"none":value};function normalizeStringArray(value){if(!Array.isArray(value))return Object.freeze([]);try{const normalized=[];for(const entry of value)typeof entry=="string"&&normalized.push(entry);return Object.freeze(normalized)}catch{return Object.freeze([])}}const stringArrayConverter={fromAttribute:value=>{if(value===null)return null;try{const parsed=JSON.parse(value);return normalizeStringArray(parsed)}catch{return[]}},toAttribute:value=>value==null?null:JSON.stringify(value)};class LyraTokenInput extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,removeWithContext:LYRA_DEFAULT_removeWithContext,tokenInputEditWithContext:LYRA_DEFAULT_tokenInputEditWithContext,tokenInputRequired:LYRA_DEFAULT_tokenInputRequired}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},defaultValue:{attribute:"value",reflect:!0,useDefault:!0,converter:stringArrayConverter,noAccessor:!0}}}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=normalizeAutocorrect(next),this.requestUpdate()}get editable(){return this._editable}set editable(next){const old=this._editable;this._editable=!!next,this._editable||this.discardTransientState(!1),this.requestUpdate("editable",old)}get value(){return this._value}set value(next){const old=this._value;this.settingDefaultValue||(this._valueDirty=!0);const normalized=normalizeStringArray(next);this.captureTokenFocusRepair(normalized),this.editingIndex>=0&&normalized!==old&&(this.editingIndex=-1,this.editDraft="",this.focusEditorPending=!1),this._value=normalized,this.requestUpdate("value",old),this.internals&&this.syncValidity()}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=normalizeStringArray(next),this.reflectingDefaultValue=!0;try{next==null?this.removeAttribute("value"):this.setAttribute("value",JSON.stringify(this._defaultValue))}finally{this.reflectingDefaultValue=!1}this._valueDirty||this.restoreLiveValueFromDefault(),this.requestUpdate("defaultValue",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),this.syncValidity(),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.syncValidity(),this.requestUpdate("required",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled,wasEffectivelyDisabled=this.effectiveDisabled;this._disabled=!!next,!wasEffectivelyDisabled&&this.effectiveDisabled&&this.retireDisabledInteraction(),this.toggleAttribute("disabled",this._disabled),this.syncValidity(),this.requestUpdate("disabled",old)}constructor(){super(),this.label="",this.hint="",this.errorText="",this.placeholder="",this.spellcheck=!0,this.autocapitalize="",this.autocorrectValue=!0,this.accessibleLabel="",this.size="m",this.pill=!1,this.allowDuplicates=!1,this._editable=!1,this.delimiter=",",this.draft="",this.touched=!1,this.editingIndex=-1,this.editDraft="",this.rovingIndex=0,this.focusEditorPending=!1,this.focusTokenPending=-1,this.editorBlurRelayed=!1,this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.hasStartSlot=!1,this.hasEndSlot=!1,this.labelId=nextId("token-input-label"),this.hintId=nextId("token-input-hint"),this.errorId=nextId("token-input-error"),this._value=Object.freeze([]),this._defaultValue=Object.freeze([]),this._valueDirty=!1,this.settingDefaultValue=!1,this.reflectingDefaultValue=!1,this._fieldsetDisabled=!1,this._name="",this._required=!1,this._disabled=!1,this.onEditInput=event=>{event.stopPropagation(),!this.liveDisabled&&(this.editDraft=event.target.value)},this.onEditFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}this.editorBlurRelayed=!1,relayNativeEvent(this,event)},this.onEditKeyDown=event=>{event.key==="Enter"?(event.preventDefault(),this.commitEdit(!0)):event.key==="Escape"&&(event.preventDefault(),event.stopPropagation(),this.cancelEdit())},this.onEditBlur=event=>{if(this.editorBlurRelayed){event.stopPropagation();return}this.editorBlurRelayed=!0,event.stopPropagation(),queueMicrotask(()=>{!this.isConnected||!this.editable||this.liveDisabled?this.discardTransientState(!1):this.commitEdit(!1),relayNativeEvent(this,event)})},this.onInput=event=>{event.stopPropagation(),!this.liveDisabled&&(this.draft=event.target.value)},this.onKeyDown=event=>{this.liveDisabled||(event.key==="Enter"||this.delimiter!==null&&event.key===this.delimiter?this.draft.trim()?(event.preventDefault(),this.addDraft()):event.key==="Enter"&&submitOnEnter(this,event):event.key==="Tab"?this.draft.trim()&&this.addDraft():event.key==="Backspace"&&!this.draft&&this.value.length&&this.editingIndex<0&&this.removeToken(this.value.length-1))},this.onBlur=event=>{this.liveDisabled||(this.draft.trim()&&this.addDraft(),this.touched=!0),this.syncValidity(),relayNativeEvent(this,event)},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onLabelSlotChange=e=>{this.hasLabelSlot=e.target.assignedElements({flatten:!0}).length>0},this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:!0}).length>0},this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:!0}).length>0},this.onStartSlotChange=e=>{this.hasStartSlot=e.target.assignedElements({flatten:!0}).length>0},this.onEndSlotChange=e=>{this.hasEndSlot=e.target.assignedElements({flatten:!0}).length>0},this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init))}connectedCallback(){super.connectedCallback(),this.syncValidity()}disconnectedCallback(){this.tokenFocusRepairPending=void 0,this.discardTransientState(!0),super.disconnectedCallback()}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 effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formDisabledCallback(disabled){const wasEffectivelyDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,!wasEffectivelyDisabled&&this.effectiveDisabled&&this.retireDisabledInteraction(),this.syncValidity(),this.requestUpdate()}[VALIDITY_ANCHOR](){return this.inputEl??this.renderRoot?.querySelector('[part="input-wrapper"]')??null}checkValidity(){return this.internals.checkValidity()}reportValidity(){return this.touched=!0,this.syncValidity(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncValidity()}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}focus(options){this.liveDisabled||this.inputEl?.focus(options)}blur(){const active=this.shadowRoot?.activeElement;active&&typeof active.blur=="function"&&active.blur()}click(){this.liveDisabled||this.inputEl?.focus()}select(){this.inputEl?.select()}get selectionStart(){return this.inputEl?.selectionStart??null}set selectionStart(value){this.inputEl&&(this.inputEl.selectionStart=value??0)}get selectionEnd(){return this.inputEl?.selectionEnd??null}set selectionEnd(value){this.inputEl&&(this.inputEl.selectionEnd=value??0)}get selectionDirection(){return this.inputEl?.selectionDirection??null}set selectionDirection(value){this.inputEl&&(this.inputEl.selectionDirection=value??"none")}setSelectionRange(selectionStart,selectionEnd,selectionDirection="none"){this.inputEl?.setSelectionRange(selectionStart,selectionEnd,selectionDirection??"none")}setRangeText(replacement,start,end,selectMode="preserve"){const input=this.inputEl;input&&(start===void 0||end===void 0?input.setRangeText(replacement):input.setRangeText(replacement,start,end,selectMode),this.draft=input.value)}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasLabelSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="label"),this.hasHintSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="hint"),this.hasErrorSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="error"),this.hasStartSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="start"),this.hasEndSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="end"))}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}syncValidity(){const barred=this.barredFromValidation,missing=!barred&&this.required&&this.value.length===0;this.validityController.setValidity(missing?{valueMissing:!0}:{},missing?this.localize("tokenInputRequired"):""),this.toggleAttribute("data-invalid",!barred&&this.touched&&!this.internals.validity.valid),syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred});const data=new FormData;this.name&&this.value.forEach(token=>data.append(this.name,token)),this.internals.setFormValue(this.name?data:null,createStringArrayFormDataState(this.name,this.value))}updateValue(next){this.value=next,this.syncValidity(),dispatchNativeInputEvent(this),this.emit("lr-input",Object.freeze({value:Object.freeze([...this.value])})),dispatchNativeEvent(this,"change"),this.emit("lr-change",Object.freeze({value:Object.freeze([...this.value])}))}addDraft(){if(this.liveDisabled)return;const candidates=(this.delimiter?this.draft.split(this.delimiter):[this.draft]).map(token=>token.trim()).filter(Boolean),next=[...this.value],seen=this.allowDuplicates?null:new Set(next),added=[];for(const token of candidates)seen?.has(token)||(seen?.add(token),next.push(token),added.push(token));if(added.length===0){this.draft="";return}this.emit("lr-add",Object.freeze({value:added[added.length-1],values:Object.freeze([...added])}),{cancelable:!0}).defaultPrevented||(this.updateValue(next),this.draft="")}discardTransientState(clearDraft){this.editingIndex=-1,this.editDraft="",this.focusEditorPending=!1,this.focusTokenPending=-1,clearDraft&&(this.draft="",this.inputEl&&(this.inputEl.value=""))}retireDisabledInteraction(){this.tokenFocusRepairPending=void 0,this.discardTransientState(!0);const active=this.shadowRoot?.activeElement;active&&typeof active.blur=="function"&&active.blur()}captureTokenFocusRepair(next){this.tokenFocusRepairPending=void 0;const tokens=[...this.renderRoot?.querySelectorAll('[part~="token"]')??[]];if(next.length>=tokens.length)return;const active=activeElementIn(this.shadowRoot),token=active?.closest('[part~="token"]');if(!active||!token)return;const index=tokens.indexOf(token);if(index<0)return;const repair=captureComposedFocusRepair(this,active);if(!repair)return;const targetIndex=Math.min(index,Math.max(0,next.length-1));this.rovingIndex=targetIndex,this.tokenFocusRepairPending={index:targetIndex,surface:active.matches('[part~="remove"]')?"remove":"label",repair}}removeToken(index){if(this.liveDisabled)return;const removed=this.value[index];removed===void 0||this.emit("lr-remove",{value:removed,index},{cancelable:!0}).defaultPrevented||(this.editingIndex>=0&&(this.editingIndex=-1,this.editDraft=""),this.updateValue(this.value.filter((_token,i)=>i!==index)))}get activeTokenIndex(){return this.value.length?Math.min(Math.max(this.rovingIndex,0),this.value.length-1):-1}startEdit(index){this.liveDisabled||!this.editable||index<0||index>=this.value.length||(this.editingIndex=index,this.editDraft=this.value[index],this.rovingIndex=index,this.editorBlurRelayed=!1,this.focusEditorPending=!0)}cancelEdit(){this.editingIndex<0||(this.focusTokenPending=this.editingIndex,this.editingIndex=-1,this.editDraft="")}commitEdit(restoreFocus){if(this.liveDisabled){this.discardTransientState(!1);return}const index=this.editingIndex;if(index<0)return;const previousValue=this.value[index],next=this.editDraft.trim();if(previousValue===void 0||!next||next===previousValue||!this.allowDuplicates&&this.value.some((token,i)=>i!==index&&token===next)){restoreFocus&&(this.focusTokenPending=index),this.editingIndex=-1,this.editDraft="";return}this.emit("lr-token-edit",{value:next,previousValue,index},{cancelable:!0}).defaultPrevented||(restoreFocus&&(this.focusTokenPending=index),this.editingIndex=-1,this.editDraft="",this.updateValue(this.value.map((token,i)=>i===index?next:token)))}moveRovingFocus(index){if(!this.value.length)return;const clamped=Math.min(Math.max(index,0),this.value.length-1);this.rovingIndex=clamped,this.focusTokenPending=clamped}onTokenKeyDown(event,index){if(this.liveDisabled)return;const rtl=this.effectiveDirection==="rtl",forward=rtl?"ArrowLeft":"ArrowRight",backward=rtl?"ArrowRight":"ArrowLeft";event.key==="Enter"||event.key===" "||event.key==="F2"?(event.preventDefault(),this.startEdit(index)):event.key===forward?(event.preventDefault(),this.moveRovingFocus(index+1)):event.key===backward?(event.preventDefault(),this.moveRovingFocus(index-1)):event.key==="Home"?(event.preventDefault(),this.moveRovingFocus(0)):event.key==="End"&&(event.preventDefault(),this.moveRovingFocus(this.value.length-1))}stopInternalChange(event){event.stopPropagation()}formResetCallback(){this.restoreLiveValueFromDefault(),this.discardTransientState(!0),this.rovingIndex=0,this.touched=!1,this.syncValidity()}restoreLiveValueFromDefault(){this.settingDefaultValue=!0;try{this.value=[...this._defaultValue]}finally{this.settingDefaultValue=!1}this._valueDirty=!1}formStateRestoreCallback(state2,_mode){this.value=readStringArrayFormDataState(state2),this.discardTransientState(!0),this.rovingIndex=0,this.touched=!1,this.syncValidity()}updated(changed){if(super.updated(changed),this.focusEditorPending){this.focusEditorPending=!1;const editor=this.renderRoot?.querySelector('[part="token-editor"]');editor?.focus(),editor?.select()}if(this.focusTokenPending>=0){const index=this.focusTokenPending;this.focusTokenPending=-1;const label=this.renderRoot?.querySelectorAll('[part="token-label"]')?.[index];label?.focus(),label?.scrollIntoView({block:"nearest",inline:"nearest"})}const pending=this.tokenFocusRepairPending;if(this.tokenFocusRepairPending=void 0,pending){const token=[...this.renderRoot.querySelectorAll('[part~="token"]')][pending.index],target=(pending.surface==="remove"?token?.querySelector('[part~="remove"]'):token?.querySelector('[part~="token-label"]'))??token?.querySelector('[part~="remove"]')??this.inputEl??null;applyComposedFocusRepair(pending.repair,target)&&target?.scrollIntoView({block:"nearest",inline:"nearest"})}}renderRemoveButton(token,index){return html`<button
|
|
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{LyraElement}from"../../../internal/lyra-element.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";installFormControlLabelSupport();import{activeElementIn}from"../../../internal/active-element.js";import{captureComposedFocusRepair,applyComposedFocusRepair}from"../../../internal/focus-navigation.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{nextId}from"../../../internal/a11y.js";import{closeIcon}from"../../../internal/icons.js";import{autocorrectConverter,normalizeAutocorrect,spellcheckConverter}from"../../../internal/converters.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./token-input.styles.js";import{attachInternalsSafely,createStringArrayFormDataState,getFormOwner,installCustomErrorProperty,isBarredFromValidation,readStringArrayFormDataState,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_tokenInputEditWithContext,LYRA_DEFAULT_tokenInputRequired}from"../../../internal/default-strings.generated.js";const delimiterConverter={fromAttribute:value=>value===null?",":value===""||value==="none"?null:value};function normalizeStringArray(value){if(!Array.isArray(value))return Object.freeze([]);try{const normalized=[];for(const entry of value)typeof entry=="string"&&normalized.push(entry);return Object.freeze(normalized)}catch{return Object.freeze([])}}const stringArrayConverter={fromAttribute:value=>{if(value===null)return null;try{const parsed=JSON.parse(value);return normalizeStringArray(parsed)}catch{return[]}},toAttribute:value=>value==null?null:JSON.stringify(value)};class LyraTokenInput extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,removeWithContext:LYRA_DEFAULT_removeWithContext,tokenInputEditWithContext:LYRA_DEFAULT_tokenInputEditWithContext,tokenInputRequired:LYRA_DEFAULT_tokenInputRequired}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},defaultValue:{attribute:"value",reflect:!0,useDefault:!0,converter:stringArrayConverter,noAccessor:!0}}}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=normalizeAutocorrect(next),this.requestUpdate()}get editable(){return this._editable}set editable(next){const old=this._editable;this._editable=!!next,this._editable||this.discardTransientState(!1),this.requestUpdate("editable",old)}get value(){return this._value}set value(next){const old=this._value;this.settingDefaultValue||(this._valueDirty=!0);const normalized=normalizeStringArray(next);this.captureTokenFocusRepair(normalized),this.editingIndex>=0&&normalized!==old&&(this.editingIndex=-1,this.editDraft="",this.focusEditorPending=!1),this._value=normalized,this.requestUpdate("value",old),this.internals&&this.syncValidity()}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=normalizeStringArray(next),this.reflectingDefaultValue=!0;try{next==null?this.removeAttribute("value"):this.setAttribute("value",JSON.stringify(this._defaultValue))}finally{this.reflectingDefaultValue=!1}this._valueDirty||this.restoreLiveValueFromDefault(),this.requestUpdate("defaultValue",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),this.syncValidity(),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.syncValidity(),this.requestUpdate("required",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled,wasEffectivelyDisabled=this.effectiveDisabled;this._disabled=!!next,!wasEffectivelyDisabled&&this.effectiveDisabled&&this.retireDisabledInteraction(),this.toggleAttribute("disabled",this._disabled),this.syncValidity(),this.requestUpdate("disabled",old)}constructor(){super(),this.label="",this.hint="",this.errorText="",this.placeholder="",this.spellcheck=!0,this.autocapitalize="",this.autocorrectValue=!0,this.accessibleLabel="",this.size="m",this.pill=!1,this.allowDuplicates=!1,this._editable=!1,this.delimiter=",",this.draft="",this.touched=!1,this.editingIndex=-1,this.editDraft="",this.rovingIndex=0,this.focusEditorPending=!1,this.focusTokenPending=-1,this.editorBlurRelayed=!1,this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.hasStartSlot=!1,this.hasEndSlot=!1,this.labelId=nextId("token-input-label"),this.hintId=nextId("token-input-hint"),this.errorId=nextId("token-input-error"),this._value=Object.freeze([]),this._defaultValue=Object.freeze([]),this._valueDirty=!1,this.settingDefaultValue=!1,this.reflectingDefaultValue=!1,this._fieldsetDisabled=!1,this._name="",this._required=!1,this._disabled=!1,this.onEditInput=event=>{event.stopPropagation(),!this.liveDisabled&&(this.editDraft=event.target.value)},this.onEditFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}this.editorBlurRelayed=!1,relayNativeEvent(this,event)},this.onEditKeyDown=event=>{event.key==="Enter"?(event.preventDefault(),this.commitEdit(!0)):event.key==="Escape"&&(event.preventDefault(),event.stopPropagation(),this.cancelEdit())},this.onEditBlur=event=>{if(this.editorBlurRelayed){event.stopPropagation();return}this.editorBlurRelayed=!0,event.stopPropagation(),queueMicrotask(()=>{!this.isConnected||!this.editable||this.liveDisabled?this.discardTransientState(!1):this.commitEdit(!1),relayNativeEvent(this,event)})},this.onInput=event=>{event.stopPropagation(),!this.liveDisabled&&(this.draft=event.target.value)},this.onKeyDown=event=>{this.liveDisabled||(event.key==="Enter"||this.delimiter!==null&&event.key===this.delimiter?this.draft.trim()?(event.preventDefault(),this.addDraft()):event.key==="Enter"&&submitOnEnter(this,event):event.key==="Tab"?this.draft.trim()&&this.addDraft():event.key==="Backspace"&&!this.draft&&this.value.length&&this.editingIndex<0&&this.removeToken(this.value.length-1))},this.onBlur=event=>{this.liveDisabled||(this.draft.trim()&&this.addDraft(),this.touched=!0),this.syncValidity(),relayNativeEvent(this,event)},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onLabelSlotChange=e=>{this.hasLabelSlot=e.target.assignedElements({flatten:!0}).length>0},this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:!0}).length>0},this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:!0}).length>0},this.onStartSlotChange=e=>{this.hasStartSlot=e.target.assignedElements({flatten:!0}).length>0},this.onEndSlotChange=e=>{this.hasEndSlot=e.target.assignedElements({flatten:!0}).length>0},this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init))}connectedCallback(){super.connectedCallback(),this.syncValidity()}disconnectedCallback(){this.tokenFocusRepairPending=void 0,this.discardTransientState(!0),super.disconnectedCallback()}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 effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formDisabledCallback(disabled){const wasEffectivelyDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,!wasEffectivelyDisabled&&this.effectiveDisabled&&this.retireDisabledInteraction(),this.syncValidity(),this.requestUpdate()}[VALIDITY_ANCHOR](){return this.inputEl??this.renderRoot?.querySelector('[part="input-wrapper"]')??null}checkValidity(){return this.internals.checkValidity()}reportValidity(){return this.touched=!0,this.syncValidity(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncValidity()}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}focus(options){this.liveDisabled||this.inputEl?.focus(options)}blur(){const active=this.shadowRoot?.activeElement;active&&typeof active.blur=="function"&&active.blur()}click(){this.liveDisabled||this.inputEl?.focus()}select(){this.inputEl?.select()}get selectionStart(){return this.inputEl?.selectionStart??null}set selectionStart(value){this.inputEl&&(this.inputEl.selectionStart=value??0)}get selectionEnd(){return this.inputEl?.selectionEnd??null}set selectionEnd(value){this.inputEl&&(this.inputEl.selectionEnd=value??0)}get selectionDirection(){return this.inputEl?.selectionDirection??null}set selectionDirection(value){this.inputEl&&(this.inputEl.selectionDirection=value??"none")}setSelectionRange(selectionStart,selectionEnd,selectionDirection="none"){this.inputEl?.setSelectionRange(selectionStart,selectionEnd,selectionDirection??"none")}setRangeText(replacement,start,end,selectMode="preserve"){const input=this.inputEl;input&&(start===void 0||end===void 0?input.setRangeText(replacement):input.setRangeText(replacement,start,end,selectMode),this.draft=input.value)}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasLabelSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="label"),this.hasHintSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="hint"),this.hasErrorSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="error"),this.hasStartSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="start"),this.hasEndSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="end"))}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}syncValidity(){const barred=this.barredFromValidation,missing=!barred&&this.required&&this.value.length===0;this.validityController.setValidity(missing?{valueMissing:!0}:{},missing?this.localize("tokenInputRequired"):""),this.toggleAttribute("data-invalid",!barred&&this.touched&&!this.internals.validity.valid),syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred});const data=new FormData;this.name&&this.value.forEach(token=>data.append(this.name,token)),this.internals.setFormValue(this.name?data:null,createStringArrayFormDataState(this.name,this.value))}updateValue(next){this.value=next,this.syncValidity(),dispatchNativeInputEvent(this),this.emit("lr-input",Object.freeze({value:Object.freeze([...this.value])})),dispatchNativeEvent(this,"change"),this.emit("lr-change",Object.freeze({value:Object.freeze([...this.value])}))}addDraft(){if(this.liveDisabled)return;const candidates=(this.delimiter?this.draft.split(this.delimiter):[this.draft]).map(token=>token.trim()).filter(Boolean),next=[...this.value],seen=this.allowDuplicates?null:new Set(next),added=[];for(const token of candidates)seen?.has(token)||(seen?.add(token),next.push(token),added.push(token));if(added.length===0){this.draft="";return}this.emit("lr-add",Object.freeze({value:added[added.length-1],values:Object.freeze([...added])}),{cancelable:!0}).defaultPrevented||(this.updateValue(next),this.draft="")}discardTransientState(clearDraft){this.editingIndex=-1,this.editDraft="",this.focusEditorPending=!1,this.focusTokenPending=-1,clearDraft&&(this.draft="",this.inputEl&&(this.inputEl.value=""))}retireDisabledInteraction(){this.tokenFocusRepairPending=void 0,this.discardTransientState(!0);const active=this.shadowRoot?.activeElement;active&&typeof active.blur=="function"&&active.blur()}captureTokenFocusRepair(next){this.tokenFocusRepairPending=void 0;const tokens=[...this.renderRoot?.querySelectorAll('[part~="token"]')??[]];if(next.length>=tokens.length)return;const active=activeElementIn(this.shadowRoot),token=active?.closest('[part~="token"]');if(!active||!token)return;const index=tokens.indexOf(token);if(index<0)return;const repair=captureComposedFocusRepair(this,active);if(!repair)return;const targetIndex=Math.min(index,Math.max(0,next.length-1));this.rovingIndex=targetIndex,this.tokenFocusRepairPending={index:targetIndex,surface:active.matches('[part~="remove"]')?"remove":"label",repair}}removeToken(index){if(this.liveDisabled)return;const removed=this.value[index];removed===void 0||this.emit("lr-remove",{value:removed,index},{cancelable:!0}).defaultPrevented||(this.editingIndex>=0&&(this.editingIndex=-1,this.editDraft=""),this.updateValue(this.value.filter((_token,i)=>i!==index)))}get activeTokenIndex(){return this.value.length?Math.min(Math.max(this.rovingIndex,0),this.value.length-1):-1}startEdit(index){this.liveDisabled||!this.editable||index<0||index>=this.value.length||(this.editingIndex=index,this.editDraft=this.value[index],this.rovingIndex=index,this.editorBlurRelayed=!1,this.focusEditorPending=!0)}cancelEdit(){this.editingIndex<0||(this.focusTokenPending=this.editingIndex,this.editingIndex=-1,this.editDraft="")}commitEdit(restoreFocus){if(this.liveDisabled){this.discardTransientState(!1);return}const index=this.editingIndex;if(index<0)return;const previousValue=this.value[index],next=this.editDraft.trim();if(previousValue===void 0||!next||next===previousValue||!this.allowDuplicates&&this.value.some((token,i)=>i!==index&&token===next)){restoreFocus&&(this.focusTokenPending=index),this.editingIndex=-1,this.editDraft="";return}this.emit("lr-token-edit",{value:next,previousValue,index},{cancelable:!0}).defaultPrevented||(restoreFocus&&(this.focusTokenPending=index),this.editingIndex=-1,this.editDraft="",this.updateValue(this.value.map((token,i)=>i===index?next:token)))}moveRovingFocus(index){if(!this.value.length)return;const clamped=Math.min(Math.max(index,0),this.value.length-1);this.rovingIndex=clamped,this.focusTokenPending=clamped}onTokenKeyDown(event,index){if(this.liveDisabled)return;const rtl=this.effectiveDirection==="rtl",forward=rtl?"ArrowLeft":"ArrowRight",backward=rtl?"ArrowRight":"ArrowLeft";event.key==="Enter"||event.key===" "||event.key==="F2"?(event.preventDefault(),this.startEdit(index)):event.key===forward?(event.preventDefault(),this.moveRovingFocus(index+1)):event.key===backward?(event.preventDefault(),this.moveRovingFocus(index-1)):event.key==="Home"?(event.preventDefault(),this.moveRovingFocus(0)):event.key==="End"&&(event.preventDefault(),this.moveRovingFocus(this.value.length-1))}stopInternalChange(event){event.stopPropagation()}formResetCallback(){this.restoreLiveValueFromDefault(),this.discardTransientState(!0),this.rovingIndex=0,this.touched=!1,this.syncValidity()}restoreLiveValueFromDefault(){this.settingDefaultValue=!0;try{this.value=[...this._defaultValue]}finally{this.settingDefaultValue=!1}this._valueDirty=!1}formStateRestoreCallback(state2,_mode){this.value=readStringArrayFormDataState(state2),this.discardTransientState(!0),this.rovingIndex=0,this.touched=!1,this.syncValidity()}updated(changed){if(super.updated(changed),this.focusEditorPending){this.focusEditorPending=!1;const editor=this.renderRoot?.querySelector('[part="token-editor"]');editor?.focus(),editor?.select()}if(this.focusTokenPending>=0){const index=this.focusTokenPending;this.focusTokenPending=-1;const label=this.renderRoot?.querySelectorAll('[part="token-label"]')?.[index];label?.focus(),label?.scrollIntoView({block:"nearest",inline:"nearest"})}const pending=this.tokenFocusRepairPending;if(this.tokenFocusRepairPending=void 0,pending){const token=[...this.renderRoot.querySelectorAll('[part~="token"]')][pending.index],target=(pending.surface==="remove"?token?.querySelector('[part~="remove"]'):token?.querySelector('[part~="token-label"]'))??token?.querySelector('[part~="remove"]')??this.inputEl??null;applyComposedFocusRepair(pending.repair,target)&&target?.scrollIntoView({block:"nearest",inline:"nearest"})}}renderRemoveButton(token,index){return html`<button
|
|
2
2
|
part="remove"
|
|
3
3
|
type="button"
|
|
4
4
|
aria-label=${this.localize("removeWithContext",void 0,{label:token})}
|
|
@@ -49,6 +49,22 @@ export declare class LyraAppRailItem extends LyraElement {
|
|
|
49
49
|
* treatment -- the rail has no built-in routing, so the consumer sets
|
|
50
50
|
* this per item (e.g. by comparing `href` against the current location). */
|
|
51
51
|
current: boolean;
|
|
52
|
+
/**
|
|
53
|
+
* Deprecated alias for `current`, read alongside it.
|
|
54
|
+
*
|
|
55
|
+
* `active` was this property's original public name. It was renamed to `current` with no
|
|
56
|
+
* changelog entry, no alias and no deprecation record, which broke every shipped consumer
|
|
57
|
+
* silently: a Lit `.active=${...}` binding on a custom element is untyped, so it did not error --
|
|
58
|
+
* it became a dead expando, leaving the rail with no current-item indicator and a permanent
|
|
59
|
+
* `aria-current="false"`. Nothing in a consumer's type check, test suite or build could see that.
|
|
60
|
+
*
|
|
61
|
+
* Set either name; the item is current when either is true. Prefer `current`.
|
|
62
|
+
*
|
|
63
|
+
* @deprecated Use `current`.
|
|
64
|
+
*/
|
|
65
|
+
active: boolean;
|
|
66
|
+
/** True when either the canonical `current` or its deprecated `active` alias is set. */
|
|
67
|
+
private get isCurrent();
|
|
52
68
|
/** Opt-in hover/focus flyout showing this item's label text while `icon-only` (set externally by
|
|
53
69
|
* the parent `<lr-app-rail>` as the viewport narrows) hides it from view -- an explicit,
|
|
54
70
|
* documented property instead of an unverified cross-browser `::part()` + `::after` + `attr()`
|