@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,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{acquireAriaDescription}from"../../../internal/aria-controls.js";import{sizes}from"../../../internal/sizes.styles.js";import{closeIcon,chevronIcon}from"../../../internal/icons.js";import{finiteNumber}from"../../../internal/numbers.js";import{place}from"../../../internal/positioner.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{activateOverlay,composedContains}from"../../../internal/overlay-manager.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{setCustomState}from"../../../internal/custom-states.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{dayPeriodLabels,hasTimeStepMismatch,isTimeInRange,localeTimePattern,normalizeTimeValue,parseTimeValue,timeValueFromMilliseconds,timeStepBaseMilliseconds,to24Hour}from"./time-input-shared.js";import{styles}from"./time-input.styles.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_popover,LYRA_DEFAULT_timeInputDayPeriod,LYRA_DEFAULT_timeInputEmptySegment,LYRA_DEFAULT_timeInputHour,LYRA_DEFAULT_timeInputInvalid,LYRA_DEFAULT_timeInputLabel,LYRA_DEFAULT_timeInputMaxMessage,LYRA_DEFAULT_timeInputMinMessage,LYRA_DEFAULT_timeInputMinute,LYRA_DEFAULT_timeInputNow,LYRA_DEFAULT_timeInputOpen,LYRA_DEFAULT_timeInputPopup,LYRA_DEFAULT_timeInputRangeMessage,LYRA_DEFAULT_timeInputSecond,LYRA_DEFAULT_timeInputStepMessage}from"../../../internal/default-strings.generated.js";class LyraTimeInputBase extends LyraElement{}const stepConverter={fromAttribute(value){if(value==="any")return"any";const parsed=Number(value);return Number.isFinite(parsed)&&parsed>0?parsed:60},toAttribute(value){return String(value)}},hourFormatConverter={fromAttribute(value){return value==="12"||value==="24"?value:"auto"},toAttribute(value){return value}},PLACEMENTS=new Set(["top","top-start","top-end","right","right-start","right-end","bottom","bottom-start","bottom-end","left","left-start","left-end"]),placementConverter={fromAttribute(value){return PLACEMENTS.has(value)?value:"bottom-start"},toAttribute(value){return value}},blankDraft=()=>({hour:null,minute:null,second:null,dayPeriod:null}),pad=value=>String(value).padStart(2,"0");function isElementNode(value){if(value===null||typeof value!="object")return!1;const candidate=value;return candidate.nodeType===1&&typeof candidate.getRootNode=="function"&&typeof candidate.contains=="function"}function containsElement(container,value){if(!container||!isElementNode(value))return!1;try{return container.contains(value)}catch{return!1}}class LyraTimeInput extends FormAssociated(LyraTimeInputBase){static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,fieldRequired:LYRA_DEFAULT_fieldRequired,popover:LYRA_DEFAULT_popover,timeInputDayPeriod:LYRA_DEFAULT_timeInputDayPeriod,timeInputEmptySegment:LYRA_DEFAULT_timeInputEmptySegment,timeInputHour:LYRA_DEFAULT_timeInputHour,timeInputInvalid:LYRA_DEFAULT_timeInputInvalid,timeInputLabel:LYRA_DEFAULT_timeInputLabel,timeInputMaxMessage:LYRA_DEFAULT_timeInputMaxMessage,timeInputMinMessage:LYRA_DEFAULT_timeInputMinMessage,timeInputMinute:LYRA_DEFAULT_timeInputMinute,timeInputNow:LYRA_DEFAULT_timeInputNow,timeInputOpen:LYRA_DEFAULT_timeInputOpen,timeInputPopup:LYRA_DEFAULT_timeInputPopup,timeInputRangeMessage:LYRA_DEFAULT_timeInputRangeMessage,timeInputSecond:LYRA_DEFAULT_timeInputSecond,timeInputStepMessage:LYRA_DEFAULT_timeInputStepMessage}}static get validators(){return[currentValidityValidator("required","disabled","readonly","value","min","max","step")]}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}static{this.properties={open:{type:Boolean,reflect:!0,noAccessor:!0},readonly:{type:Boolean,reflect:!0,noAccessor:!0},step:{converter:stepConverter,reflect:!0,noAccessor:!0}}}constructor(){super(),this.appearance="outlined",this.autocomplete="",this.distance=0,this.hint="",this.hourFormat="auto",this.label="",this.min="",this.max="",this.pill=!1,this.placement="bottom-start",this.size="m",this.withClear=!1,this.withHint=!1,this.withLabel=!1,this.withNow=!1,this.errorText="",this.activeSegment="hour",this.touched=!1,this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.hasStartSlot=!1,this.hasEndSlot=!1,this.hasFooterSlot=!1,this._open=!1,this._readonly=!1,this._step=60,this.draft=blankDraft(),this.partial=!1,this.secondsVisible=!1,this.digitBuffer="",this.restoringSegmentFocus=!1,this.restoreFocusOnClose=!0,this.transitionToken=0,this.visibilityPromise=Promise.resolve(),this.segmentOrderKey="",this.pickerGridKey="",this.pickerGridMilliseconds=[],this.inputId=nextId("time-input"),this.labelId=nextId("time-input-label"),this.hintId=nextId("time-input-hint"),this.errorId=nextId("time-input-error"),this.requiredDescriptionId=nextId("time-input-required"),this.popupId=nextId("time-input-popup"),this.now=()=>new Date,this.onSegmentKeyDown=event=>{const name=event.currentTarget.dataset.segment;if(this.liveDisabled)return;if(event.altKey&&event.key==="ArrowDown"){event.preventDefault(),this.show();return}const digit=this.inputDigit(event.key);if(digit!==void 0&&!event.ctrlKey&&!event.metaKey&&!event.altKey&&!this.readonly){event.preventDefault(),this.acceptDigit(name,digit);return}if(name==="dayPeriod"&&!this.readonly&&(event.key.toLowerCase()==="a"||event.key.toLowerCase()==="p")){event.preventDefault(),this.setDraftSegment(name,event.key.toLowerCase()==="a"?"am":"pm");return}if(event.key==="ArrowLeft"||event.key==="ArrowRight"){event.preventDefault();const physical=event.key==="ArrowRight"?1:-1;this.resetDigitBuffer(),this.moveSegment(name,this.effectiveDirection==="rtl"?-physical:physical);return}if((event.key==="ArrowUp"||event.key==="ArrowDown")&&!this.readonly){event.preventDefault(),this.resetDigitBuffer(),this.stepSegment(name,event.key==="ArrowUp"?1:-1);return}if((event.key==="Home"||event.key==="End")&&!this.readonly){event.preventDefault();const bounds=this.segmentBounds(name),next=event.key==="Home"?bounds.min:bounds.max;this.setDraftSegment(name,name==="dayPeriod"?next===0?"am":"pm":next);return}if((event.key==="Backspace"||event.key==="Delete")&&!this.readonly){event.preventDefault(),this.resetDigitBuffer(),this.setDraftSegment(name,null);return}event.key==="Enter"&&(this.open?this.hide():this.readonly||submitOnEnter(this,event))},this.onSegmentPaste=event=>{if(this.liveDisabled||this.readonly)return;const pasted=normalizeTimeValue(event.clipboardData?.getData("text").trim()??"");pasted&&(event.preventDefault(),this.resetDigitBuffer(),this.commitUserValue(pasted,"insertFromPaste",!0))},this.onSegmentFocus=event=>{if(event.stopPropagation(),this.liveDisabled)return;const focusedSegment=event.target.dataset.segment??this.activeSegment;if(this.restoringSegmentFocus){queueMicrotask(()=>{this.isConnected&&this.segmentOrder.includes(focusedSegment)&&(this.activeSegment=focusedSegment)});return}else this.activeSegment=focusedSegment;const related=event.relatedTarget;containsElement(this.renderRoot.querySelector('[part="input"]'),related)||relayNativeEvent(this,event)},this.onSegmentBlur=event=>{if(event.stopPropagation(),this.pendingSegmentFocus){this.resetDigitBuffer();return}const related=event.relatedTarget;containsElement(this.renderRoot.querySelector('[part="input"]'),related)||(this.liveDisabled||(this.touched=!0),this.resetDigitBuffer(),relayNativeEvent(this,event))},this.onDocumentPointerDown=event=>{const target=event.composedPath()[0];isElementNode(target)&&composedContains(this,target)||this.requestVisibility(!1,!0,!1)},this.onExpand=()=>{this.liveDisabled||(this.open?this.hide():this.show())},this.onClear=()=>{this.liveDisabled||this.readonly||!this.draftHasAny&&this.value===""||(this.touched=!0,this.commitUserValue("","deleteContentBackward",!0),this.emit("lr-clear"),this.focus())},this.onNow=()=>{if(this.liveDisabled||this.readonly)return;const now=this.now();let value=`${pad(now.getHours())}:${pad(now.getMinutes())}`;this.includeSeconds&&(value+=`:${pad(now.getSeconds())}`),this.commitUserValue(value)},this.onPopupPointerDown=event=>{event.preventDefault()},this.onAutofillInput=event=>{event.stopPropagation();const input=event.currentTarget,normalized=normalizeTimeValue(input.value),intentionalClear=input.value===""&&(event.isTrusted||event.inputType.startsWith("delete")||event.inputType==="insertReplacementText");if(input.value===""&&this.value!==""&&!intentionalClear){input.value=this.value;return}input.value!==""&&!normalized||this.readonly||this.liveDisabled||(this.value=normalized,dispatchNativeInputEvent(this,{data:event.data,inputType:event.inputType||"insertReplacementText"}),this.emit("lr-input",{value:this.value}))},this.onAutofillChange=event=>{event.stopPropagation();const input=event.currentTarget,normalized=normalizeTimeValue(input.value);input.value!==""&&!normalized||this.readonly||this.liveDisabled||(this.value=normalized,dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value}))},this.onColumnKeyDown=event=>{if(this.liveDisabled||!["ArrowUp","ArrowDown","Home","End"].includes(event.key))return;const current=event.currentTarget,column=current.closest('[role="listbox"]'),options=Array.from(column?.querySelectorAll('[role="option"]')??[]).filter(option=>!option.disabled);if(options.length===0)return;event.preventDefault();const index=Math.max(0,options.indexOf(current)),nextIndex=event.key==="Home"?0:event.key==="End"?options.length-1:(index+(event.key==="ArrowDown"?1:-1)+options.length)%options.length;for(const option of options)option.tabIndex=option===options[nextIndex]?0:-1;options[nextIndex].focus(),options[nextIndex].scrollIntoView({block:"nearest"})},this.addEventListener("invalid",()=>{this.touched=!0})}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncRequiredDescription()}get open(){return this._open}set open(next){this.requestVisibility(!!next,this.isConnected&&this.hasUpdated,!0)}get readonly(){return this._readonly}set readonly(next){const old=this._readonly;this._readonly=!!next,this.toggleAttribute("readonly",this._readonly),this.updateValidity(),this.requestUpdate("readonly",old)}get step(){return this._step}set step(next){const old=this._step;if(next==="any")this._step=next;else{const numeric=finiteNumber(Number(next),60);this._step=numeric>0?numeric:60}const parsedValue=parseTimeValue(this.value);this.secondsVisible=this.numericStep<60||parsedValue!==void 0&&parsedValue.precision!=="minute",this.updateValidity(),this.requestUpdate("step",old)}get disabled(){return super.disabled}set disabled(next){super.disabled=next,next&&this.forceClose(!1),this.syncComponentStates()}get value(){return super.value}set value(next){let normalized=normalizeTimeValue(next);normalized&&this.numericStep<60&&parseTimeValue(normalized)?.precision==="minute"&&(normalized+=":00"),this.partial=!1,this.resetDigitBuffer(),this.syncDraft(normalized),super.value=normalized,this.syncComponentStates()}get valueAsNumber(){return parseTimeValue(this.value)?.milliseconds??Number.NaN}set valueAsNumber(next){this.value=timeValueFromMilliseconds(next)}get valueAsDate(){const parsed=parseTimeValue(this.value);if(!parsed)return null;const result=this.now();return result.setHours(parsed.hour,parsed.minute,parsed.second,parsed.millisecond),result}set valueAsDate(next){this.value=normalizeTimeValue(next)}get numericStep(){return this.step==="any"?60:finiteNumber(this.step,60)}get includeSeconds(){return this.numericStep<60||this.secondsVisible}get pattern(){return localeTimePattern(this.effectiveLocale,this.hourFormat,this.includeSeconds)}get segmentOrder(){return this.pattern.filter(part=>part.type!=="literal").map(part=>part.type)}get liveDisabled(){const matches=this.matches;return this.effectiveDisabled||typeof matches=="function"&&matches.call(this,":disabled")}activeSegmentFor(order=this.segmentOrder){return order.includes(this.activeSegment)?this.activeSegment:order[0]??"hour"}get usesTwelveHour(){return this.segmentOrder.includes("dayPeriod")}get draftComplete(){return this.draft.hour!==null&&this.draft.minute!==null&&(!this.includeSeconds||this.draft.second!==null)&&(!this.usesTwelveHour||this.draft.dayPeriod!==null)}get draftHasAny(){return Object.values(this.draft).some(value=>value!==null)}syncDraft(value){const parsed=parseTimeValue(value);if(!parsed){this.draft=blankDraft(),this.secondsVisible=this.numericStep<60;return}this.draft={hour:parsed.hour,minute:parsed.minute,second:parsed.second,dayPeriod:parsed.hour>=12?"pm":"am"},this.secondsVisible=this.numericStep<60||parsed.precision!=="minute"}canonicalDraftValue(){if(!this.draftComplete)return"";const value=`${pad(this.draft.hour)}:${pad(this.draft.minute)}`;return this.includeSeconds?`${value}:${pad(this.draft.second)}`:value}syncComponentStates(){setCustomState(this.internals,"blank",this.value===""),setCustomState(this.internals,"disabled",this.effectiveDisabled),setCustomState(this.internals,"open",this.open)}formattedNumber(value,minimumIntegerDigits){try{return getNumberFormat(this.effectiveLocale,{minimumIntegerDigits,useGrouping:!1}).format(value)}catch{return String(value).padStart(minimumIntegerDigits,"0")}}inputDigit(key){if(/^[0-9]$/.test(key))return key;try{const formatter=getNumberFormat(this.effectiveLocale,{useGrouping:!1});for(let value=0;value<=9;value++)if(formatter.formatToParts(value).find(part=>part.type==="integer")?.value===key)return String(value)}catch{}}displayTime(value){const parsed=parseTimeValue(value);if(!parsed)return value;const includeSeconds=parsed.precision!=="minute",labels=dayPeriodLabels(this.effectiveLocale);return localeTimePattern(this.effectiveLocale,this.hourFormat,includeSeconds).map(part=>{if(part.type==="literal")return part.value;if(part.type==="hour"){const hour=this.usesTwelveHour?parsed.hour%12||12:parsed.hour;return this.formattedNumber(hour,this.usesTwelveHour?1:2)}return part.type==="minute"?this.formattedNumber(parsed.minute,2):part.type==="second"?this.formattedNumber(parsed.second,2):parsed.hour>=12?labels.pm:labels.am}).join("")}segmentNumericValue(name){return name==="hour"?this.draft.hour===null?null:this.usesTwelveHour?this.draft.hour%12||12:this.draft.hour:name==="minute"?this.draft.minute:name==="second"?this.draft.second:this.draft.dayPeriod==="am"?0:this.draft.dayPeriod==="pm"?1:null}segmentText(name){if(this.digitSegment===name&&this.digitBuffer)return this.formattedNumber(Number(this.digitBuffer),this.digitBuffer.length);if(name==="dayPeriod"){const labels=dayPeriodLabels(this.effectiveLocale);return this.draft.dayPeriod?labels[this.draft.dayPeriod]:"--"}const value=this.segmentNumericValue(name);if(value===null)return"--";const minimumDigits=name==="hour"&&this.usesTwelveHour?1:2;return this.formattedNumber(value,minimumDigits)}segmentLabel(name){const keys={hour:"timeInputHour",minute:"timeInputMinute",second:"timeInputSecond",dayPeriod:"timeInputDayPeriod"};return this.localize(keys[name])}segmentBounds(name){return name==="hour"?this.usesTwelveHour?{min:1,max:12}:{min:0,max:23}:name==="dayPeriod"?{min:0,max:1}:{min:0,max:59}}setDraftSegment(name,value,user=!0){if(!(this.liveDisabled||user&&this.readonly)){if(name==="hour")if(value===null)this.draft.hour=null;else{const numeric=Number(value);this.draft.hour=this.usesTwelveHour?to24Hour(numeric,this.draft.dayPeriod??"am"):numeric}else if(name==="dayPeriod"){const period=value==="pm"?"pm":value==="am"?"am":null;if(period&&this.draft.hour!==null){const displayHour=this.draft.hour%12||12;this.draft.hour=to24Hour(displayHour,period)}this.draft.dayPeriod=period}else this.draft[name]=value===null?null:Number(value);if(!user){this.requestUpdate();return}this.publishDraftEdit()}}publishDraftEdit(){const before=super.value,next=this.canonicalDraftValue();this.partial=this.draftHasAny&&!this.draftComplete,super.value=next,this.syncComponentStates(),dispatchNativeInputEvent(this,{inputType:"insertReplacementText"}),this.emit("lr-input",{value:this.value}),next!==""&&next!==before&&(dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value})),this.requestUpdate()}commitUserValue(value,inputType="insertReplacementText",forceChange=!1){const before=this.value;this.value=value,dispatchNativeInputEvent(this,{inputType}),this.emit("lr-input",{value:this.value}),(forceChange||this.value!==before)&&(dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value}))}resetDigitBuffer(){this.digitBuffer="",this.digitSegment=void 0}moveSegment(from,direction){const order=this.segmentOrder,current=Math.max(0,order.indexOf(from)),next=Math.min(order.length-1,Math.max(0,current+direction));this.activeSegment=order[next]??"hour",this.segmentElement(this.activeSegment)?.focus()}acceptDigit(name,digit){if(name==="dayPeriod")return;this.digitSegment!==name&&(this.digitSegment=name,this.digitBuffer="");const bounds=this.segmentBounds(name);let candidateText=`${this.digitBuffer}${digit}`.slice(-2),candidate=Number(candidateText);(candidate>bounds.max||candidateText.length===2&&candidate<bounds.min)&&(candidateText=digit,candidate=Number(digit)),this.digitBuffer=candidateText,candidate>=bounds.min&&candidate<=bounds.max?this.setDraftSegment(name,candidate):this.requestUpdate();const cannotAcceptAnother=candidate*10>bounds.max;(candidateText.length===2||cannotAcceptAnother)&&(this.resetDigitBuffer(),this.moveSegment(name,1))}stepSegment(name,delta){const bounds=this.segmentBounds(name),current=this.segmentNumericValue(name),next=current===null?bounds.min:(current-bounds.min+delta+(bounds.max-bounds.min+1))%(bounds.max-bounds.min+1)+bounds.min;name==="dayPeriod"?this.setDraftSegment(name,next===0?"am":"pm"):this.setDraftSegment(name,next)}segmentElement(name){return this.renderRoot?.querySelector(`[data-segment="${name}"]`)}focus(options){if(this.liveDisabled)return;const order=this.segmentOrder,activeSegment=this.activeSegmentFor(order);activeSegment!==this.activeSegment&&(this.activeSegment=activeSegment),this.segmentElement(activeSegment)?.focus(options)}blur(){const active=this.shadowRoot?.activeElement;active&&typeof active.blur=="function"&&active.blur()}click(){this.liveDisabled||this.focus()}setOpen(next){if(this._open===next)return;const old=this._open;this._open=next,this.syncComponentStates(),this.requestUpdate("open",old)}syncOpenAttribute(){this.toggleAttribute("open",this._open)}requestVisibility(next,announce,restoreFocus){return this._open===next?this.visibilityPromise:next&&this.liveDisabled?(this.syncOpenAttribute(),Promise.resolve()):announce&&this.emit(next?"lr-show":"lr-hide",null,{cancelable:!0}).defaultPrevented?(this.syncOpenAttribute(),Promise.resolve()):(this.restoreFocusOnClose=restoreFocus,this.setOpen(next),this.visibilityPromise=announce?this.settleTransition(next?"lr-after-show":"lr-after-hide"):Promise.resolve(),this.visibilityPromise)}show(){return this.requestVisibility(!0,!0,!0)}hide(){return this.requestVisibility(!1,!0,!0)}forceClose(restoreFocus){this._open&&(this.restoreFocusOnClose=restoreFocus,this.setOpen(!1))}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="popup"]')?.getAnimations({subtree:!0})??[];if(await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),this.transitionToken!==token)return}this.emit(event)}}positionPopup(){this.cleanupPositioner?.(),this.cleanupPositioner=void 0;const anchor=this.renderRoot.querySelector('[part~="time-input"]'),popup=this.renderRoot.querySelector('[part="popup"]');!anchor||!popup||(this.cleanupPositioner=place(anchor,popup,{placement:rtlAwarePlacement(this.placement,this),offset:finiteNumber(this.distance,0),sync:"width"}))}activatePopup(){this.isConnected&&(this.positionPopup(),this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="popup"]'),onEscape:()=>{this.hide()},restoreFocusTo:this.segmentElement(this.activeSegment),modal:!1,trapFocus:!1}),this.lightDismissDocument=this.ownerDocument,this.lightDismissDocument.addEventListener("pointerdown",this.onDocumentPointerDown,!0),this.updateComplete.then(()=>{this.renderRoot.querySelector('[part~="column-item-selected"]')?.scrollIntoView({block:"center"})}))}teardownPopup(){this.cleanupPositioner?.(),this.cleanupPositioner=void 0,this.overlayHandle?.deactivate({restoreFocus:this.restoreFocusOnClose}),this.overlayHandle=void 0,this.lightDismissDocument?.removeEventListener("pointerdown",this.onDocumentPointerDown,!0),this.lightDismissDocument=void 0,this.restoreFocusOnClose=!0}onColumnSelect(name,value){this.readonly||this.liveDisabled||(this.resetDigitBuffer(),this.setDraftSegment(name,value),this.activeSegment=name,this.updateComplete.then(()=>this.segmentElement(name)?.focus()))}updateSlotState(event){const slot=event.currentTarget,present=slot.assignedNodes({flatten:!0}).some(node=>node.nodeType===Node.ELEMENT_NODE||(node.textContent??"").trim().length>0);slot.name==="label"?this.hasLabelSlot=present:slot.name==="hint"?this.hasHintSlot=present:slot.name==="error"?this.hasErrorSlot=present:slot.name==="start"?this.hasStartSlot=present:slot.name==="end"?this.hasEndSlot=present:slot.name==="footer"&&(this.hasFooterSlot=present)}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let message="";this.required&&this.value===""&&(flags.valueMissing=!0),this.partial&&(flags.badInput=!0);const parsed=parseTimeValue(this.value);if(this.value!==""&&!parsed&&(flags.badInput=!0),parsed&&!isTimeInRange(this.value,this.min,this.max)){const parsedMin=parseTimeValue(this.min),parsedMax=parseTimeValue(this.max);parsedMin&&parsedMax&&parsedMin.milliseconds>parsedMax.milliseconds?(flags.rangeUnderflow=!0,message=this.localize("timeInputRangeMessage",void 0,{min:this.displayTime(this.min),max:this.displayTime(this.max)})):parsedMin&&parsed.milliseconds<parsedMin.milliseconds?(flags.rangeUnderflow=!0,message=this.localize("timeInputMinMessage",void 0,{min:this.displayTime(this.min)})):(flags.rangeOverflow=!0,message=this.localize("timeInputMaxMessage",void 0,{max:this.displayTime(this.max)}))}parsed&&hasTimeStepMismatch(this.value,this.step,this.min,this.defaultValue)&&(flags.stepMismatch=!0,message||=this.localize("timeInputStepMessage")),flags.badInput?message=this.localize("timeInputInvalid"):flags.valueMissing&&(message=this.localize("fieldRequired")),this[SET_ANCHORED_VALIDITY](flags,message)}checkValidity(){return this.updateValidity(),super.checkValidity()}reportValidity(){return this.touched=!0,this.updateValidity(),super.reportValidity()}[VALIDITY_ANCHOR](){return this.segmentElement(this.activeSegmentFor())}formResetCallback(){super.formResetCallback(),this.touched=!1,this.partial=!1,this.resetDigitBuffer()}formStateRestoreCallback(state2,reason="restore"){super.formStateRestoreCallback(state2,reason)}willUpdate(changed){if(super.willUpdate(changed),!this.hasUpdated){const slots=Array.from(this.children??[]).map(element=>element.getAttribute("slot"));this.hasLabelSlot=slots.includes("label"),this.hasHintSlot=slots.includes("hint"),this.hasErrorSlot=slots.includes("error"),this.hasStartSlot=slots.includes("start"),this.hasEndSlot=slots.includes("end"),this.hasFooterSlot=slots.includes("footer")}this.open&&this.effectiveDisabled&&this.forceClose(!1);const order=this.segmentOrder,orderKey=order.join("|"),focusedSegment=orderKey!==this.segmentOrderKey?this.shadowRoot?.activeElement?.getAttribute("data-segment"):null,nextActiveSegment=focusedSegment&&order.includes(focusedSegment)?focusedSegment:this.activeSegmentFor(order);focusedSegment&&(this.pendingSegmentFocus=order.includes(focusedSegment)?focusedSegment:nextActiveSegment),this.segmentOrderKey=orderKey}updated(changed){super.updated(changed),changed.has("open")?this.open?this.activatePopup():this.teardownPopup():this.open&&(changed.has("placement")||changed.has("distance"))&&this.positionPopup(),(changed.has("value")||changed.has("required")||changed.has("readonly")||changed.has("min")||changed.has("max")||changed.has("step"))&&this.updateValidity(),this.syncComponentStates(),this.toggleAttribute("data-invalid",this.touched&&!this.validity.valid),this.syncRequiredDescription();const pendingSegmentFocus=this.pendingSegmentFocus;if(this.pendingSegmentFocus=void 0,pendingSegmentFocus&&!this.effectiveDisabled){this.restoringSegmentFocus=!0;try{this.segmentElement(pendingSegmentFocus)?.focus()}finally{this.restoringSegmentFocus=!1}}}disconnectedCallback(){this.releaseRequiredDescription(),this.transitionToken++,this.forceClose(!1),this.teardownPopup(),this.syncOpenAttribute(),this.pendingSegmentFocus=void 0,super.disconnectedCallback()}syncRequiredDescription(){const target=this.renderRoot.querySelector('[part~="input"]'),description=this.renderRoot.querySelector(`#${this.requiredDescriptionId}`);if(!this.required||!target||!description){this.releaseRequiredDescription();return}if(this.requiredDescriptionTarget!==target){this.releaseRequiredDescription(),this.requiredDescriptionTarget=target,this.requiredDescriptionLease=acquireAriaDescription(target,[description]);return}this.requiredDescriptionLease?.update([description])}releaseRequiredDescription(){this.requiredDescriptionLease?.release(),this.requiredDescriptionLease=void 0,this.requiredDescriptionTarget=void 0}renderSegment(name,invalid){const value=this.segmentNumericValue(name),bounds=this.segmentBounds(name),empty=value===null;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{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{acquireAriaDescription}from"../../../internal/aria-controls.js";import{sizes}from"../../../internal/sizes.styles.js";import{closeIcon,chevronIcon}from"../../../internal/icons.js";import{finiteNumber}from"../../../internal/numbers.js";import{place}from"../../../internal/positioner.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{activateNonmodalOverlay,composedContains}from"../../../internal/nonmodal-overlay-manager.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{setCustomState}from"../../../internal/custom-states.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{dayPeriodLabels,hasTimeStepMismatch,isTimeInRange,localeTimePattern,normalizeTimeValue,parseTimeValue,timeValueFromMilliseconds,timeStepBaseMilliseconds,to24Hour}from"./time-input-shared.js";import{styles}from"./time-input.styles.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_popover,LYRA_DEFAULT_timeInputDayPeriod,LYRA_DEFAULT_timeInputEmptySegment,LYRA_DEFAULT_timeInputHour,LYRA_DEFAULT_timeInputInvalid,LYRA_DEFAULT_timeInputLabel,LYRA_DEFAULT_timeInputMaxMessage,LYRA_DEFAULT_timeInputMinMessage,LYRA_DEFAULT_timeInputMinute,LYRA_DEFAULT_timeInputNow,LYRA_DEFAULT_timeInputOpen,LYRA_DEFAULT_timeInputPopup,LYRA_DEFAULT_timeInputRangeMessage,LYRA_DEFAULT_timeInputSecond,LYRA_DEFAULT_timeInputStepMessage}from"../../../internal/default-strings.generated.js";class LyraTimeInputBase extends LyraElement{}const stepConverter={fromAttribute(value){if(value==="any")return"any";const parsed=Number(value);return Number.isFinite(parsed)&&parsed>0?parsed:60},toAttribute(value){return String(value)}},hourFormatConverter={fromAttribute(value){return value==="12"||value==="24"?value:"auto"},toAttribute(value){return value}},PLACEMENTS=new Set(["top","top-start","top-end","right","right-start","right-end","bottom","bottom-start","bottom-end","left","left-start","left-end"]),placementConverter={fromAttribute(value){return PLACEMENTS.has(value)?value:"bottom-start"},toAttribute(value){return value}},blankDraft=()=>({hour:null,minute:null,second:null,dayPeriod:null}),pad=value=>String(value).padStart(2,"0");function isElementNode(value){if(value===null||typeof value!="object")return!1;const candidate=value;return candidate.nodeType===1&&typeof candidate.getRootNode=="function"&&typeof candidate.contains=="function"}function containsElement(container,value){if(!container||!isElementNode(value))return!1;try{return container.contains(value)}catch{return!1}}class LyraTimeInput extends FormAssociated(LyraTimeInputBase){static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,fieldRequired:LYRA_DEFAULT_fieldRequired,popover:LYRA_DEFAULT_popover,timeInputDayPeriod:LYRA_DEFAULT_timeInputDayPeriod,timeInputEmptySegment:LYRA_DEFAULT_timeInputEmptySegment,timeInputHour:LYRA_DEFAULT_timeInputHour,timeInputInvalid:LYRA_DEFAULT_timeInputInvalid,timeInputLabel:LYRA_DEFAULT_timeInputLabel,timeInputMaxMessage:LYRA_DEFAULT_timeInputMaxMessage,timeInputMinMessage:LYRA_DEFAULT_timeInputMinMessage,timeInputMinute:LYRA_DEFAULT_timeInputMinute,timeInputNow:LYRA_DEFAULT_timeInputNow,timeInputOpen:LYRA_DEFAULT_timeInputOpen,timeInputPopup:LYRA_DEFAULT_timeInputPopup,timeInputRangeMessage:LYRA_DEFAULT_timeInputRangeMessage,timeInputSecond:LYRA_DEFAULT_timeInputSecond,timeInputStepMessage:LYRA_DEFAULT_timeInputStepMessage}}static get validators(){return[currentValidityValidator("required","disabled","readonly","value","min","max","step")]}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}static{this.properties={open:{type:Boolean,reflect:!0,noAccessor:!0},readonly:{type:Boolean,reflect:!0,noAccessor:!0},step:{converter:stepConverter,reflect:!0,noAccessor:!0}}}constructor(){super(),this.appearance="outlined",this.autocomplete="",this.distance=0,this.hint="",this.hourFormat="auto",this.label="",this.min="",this.max="",this.pill=!1,this.placement="bottom-start",this.size="m",this.withClear=!1,this.withHint=!1,this.withLabel=!1,this.withNow=!1,this.errorText="",this.activeSegment="hour",this.touched=!1,this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.hasStartSlot=!1,this.hasEndSlot=!1,this.hasFooterSlot=!1,this._open=!1,this._readonly=!1,this._step=60,this.draft=blankDraft(),this.partial=!1,this.secondsVisible=!1,this.digitBuffer="",this.restoringSegmentFocus=!1,this.restoreFocusOnClose=!0,this.transitionToken=0,this.visibilityPromise=Promise.resolve(),this.segmentOrderKey="",this.pickerGridKey="",this.pickerGridMilliseconds=[],this.inputId=nextId("time-input"),this.labelId=nextId("time-input-label"),this.hintId=nextId("time-input-hint"),this.errorId=nextId("time-input-error"),this.requiredDescriptionId=nextId("time-input-required"),this.popupId=nextId("time-input-popup"),this.now=()=>new Date,this.onSegmentKeyDown=event=>{const name=event.currentTarget.dataset.segment;if(this.liveDisabled)return;if(event.altKey&&event.key==="ArrowDown"){event.preventDefault(),this.show();return}const digit=this.inputDigit(event.key);if(digit!==void 0&&!event.ctrlKey&&!event.metaKey&&!event.altKey&&!this.readonly){event.preventDefault(),this.acceptDigit(name,digit);return}if(name==="dayPeriod"&&!this.readonly&&(event.key.toLowerCase()==="a"||event.key.toLowerCase()==="p")){event.preventDefault(),this.setDraftSegment(name,event.key.toLowerCase()==="a"?"am":"pm");return}if(event.key==="ArrowLeft"||event.key==="ArrowRight"){event.preventDefault();const physical=event.key==="ArrowRight"?1:-1;this.resetDigitBuffer(),this.moveSegment(name,this.effectiveDirection==="rtl"?-physical:physical);return}if((event.key==="ArrowUp"||event.key==="ArrowDown")&&!this.readonly){event.preventDefault(),this.resetDigitBuffer(),this.stepSegment(name,event.key==="ArrowUp"?1:-1);return}if((event.key==="Home"||event.key==="End")&&!this.readonly){event.preventDefault();const bounds=this.segmentBounds(name),next=event.key==="Home"?bounds.min:bounds.max;this.setDraftSegment(name,name==="dayPeriod"?next===0?"am":"pm":next);return}if((event.key==="Backspace"||event.key==="Delete")&&!this.readonly){event.preventDefault(),this.resetDigitBuffer(),this.setDraftSegment(name,null);return}event.key==="Enter"&&(this.open?this.hide():this.readonly||submitOnEnter(this,event))},this.onSegmentPaste=event=>{if(this.liveDisabled||this.readonly)return;const pasted=normalizeTimeValue(event.clipboardData?.getData("text").trim()??"");pasted&&(event.preventDefault(),this.resetDigitBuffer(),this.commitUserValue(pasted,"insertFromPaste",!0))},this.onSegmentFocus=event=>{if(event.stopPropagation(),this.liveDisabled)return;const focusedSegment=event.target.dataset.segment??this.activeSegment;if(this.restoringSegmentFocus){queueMicrotask(()=>{this.isConnected&&this.segmentOrder.includes(focusedSegment)&&(this.activeSegment=focusedSegment)});return}else this.activeSegment=focusedSegment;const related=event.relatedTarget;containsElement(this.renderRoot.querySelector('[part="input"]'),related)||relayNativeEvent(this,event)},this.onSegmentBlur=event=>{if(event.stopPropagation(),this.pendingSegmentFocus){this.resetDigitBuffer();return}const related=event.relatedTarget;containsElement(this.renderRoot.querySelector('[part="input"]'),related)||(this.liveDisabled||(this.touched=!0),this.resetDigitBuffer(),relayNativeEvent(this,event))},this.onDocumentPointerDown=event=>{const target=event.composedPath()[0];isElementNode(target)&&composedContains(this,target)||this.requestVisibility(!1,!0,!1)},this.onExpand=()=>{this.liveDisabled||(this.open?this.hide():this.show())},this.onClear=()=>{this.liveDisabled||this.readonly||!this.draftHasAny&&this.value===""||(this.touched=!0,this.commitUserValue("","deleteContentBackward",!0),this.emit("lr-clear"),this.focus())},this.onNow=()=>{if(this.liveDisabled||this.readonly)return;const now=this.now();let value=`${pad(now.getHours())}:${pad(now.getMinutes())}`;this.includeSeconds&&(value+=`:${pad(now.getSeconds())}`),this.commitUserValue(value)},this.onPopupPointerDown=event=>{event.preventDefault()},this.onAutofillInput=event=>{event.stopPropagation();const input=event.currentTarget,normalized=normalizeTimeValue(input.value),intentionalClear=input.value===""&&(event.isTrusted||event.inputType.startsWith("delete")||event.inputType==="insertReplacementText");if(input.value===""&&this.value!==""&&!intentionalClear){input.value=this.value;return}input.value!==""&&!normalized||this.readonly||this.liveDisabled||(this.value=normalized,dispatchNativeInputEvent(this,{data:event.data,inputType:event.inputType||"insertReplacementText"}),this.emit("lr-input",{value:this.value}))},this.onAutofillChange=event=>{event.stopPropagation();const input=event.currentTarget,normalized=normalizeTimeValue(input.value);input.value!==""&&!normalized||this.readonly||this.liveDisabled||(this.value=normalized,dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value}))},this.onColumnKeyDown=event=>{if(this.liveDisabled||!["ArrowUp","ArrowDown","Home","End"].includes(event.key))return;const current=event.currentTarget,column=current.closest('[role="listbox"]'),options=Array.from(column?.querySelectorAll('[role="option"]')??[]).filter(option=>!option.disabled);if(options.length===0)return;event.preventDefault();const index=Math.max(0,options.indexOf(current)),nextIndex=event.key==="Home"?0:event.key==="End"?options.length-1:(index+(event.key==="ArrowDown"?1:-1)+options.length)%options.length;for(const option of options)option.tabIndex=option===options[nextIndex]?0:-1;options[nextIndex].focus(),options[nextIndex].scrollIntoView({block:"nearest"})},this.addEventListener("invalid",()=>{this.touched=!0})}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncRequiredDescription()}get open(){return this._open}set open(next){this.requestVisibility(!!next,this.isConnected&&this.hasUpdated,!0)}get readonly(){return this._readonly}set readonly(next){const old=this._readonly;this._readonly=!!next,this.toggleAttribute("readonly",this._readonly),this.updateValidity(),this.requestUpdate("readonly",old)}get step(){return this._step}set step(next){const old=this._step;if(next==="any")this._step=next;else{const numeric=finiteNumber(Number(next),60);this._step=numeric>0?numeric:60}const parsedValue=parseTimeValue(this.value);this.secondsVisible=this.numericStep<60||parsedValue!==void 0&&parsedValue.precision!=="minute",this.updateValidity(),this.requestUpdate("step",old)}get disabled(){return super.disabled}set disabled(next){super.disabled=next,next&&this.forceClose(!1),this.syncComponentStates()}get value(){return super.value}set value(next){let normalized=normalizeTimeValue(next);normalized&&this.numericStep<60&&parseTimeValue(normalized)?.precision==="minute"&&(normalized+=":00"),this.partial=!1,this.resetDigitBuffer(),this.syncDraft(normalized),super.value=normalized,this.syncComponentStates()}get valueAsNumber(){return parseTimeValue(this.value)?.milliseconds??Number.NaN}set valueAsNumber(next){this.value=timeValueFromMilliseconds(next)}get valueAsDate(){const parsed=parseTimeValue(this.value);if(!parsed)return null;const result=this.now();return result.setHours(parsed.hour,parsed.minute,parsed.second,parsed.millisecond),result}set valueAsDate(next){this.value=normalizeTimeValue(next)}get numericStep(){return this.step==="any"?60:finiteNumber(this.step,60)}get includeSeconds(){return this.numericStep<60||this.secondsVisible}get pattern(){return localeTimePattern(this.effectiveLocale,this.hourFormat,this.includeSeconds)}get segmentOrder(){return this.pattern.filter(part=>part.type!=="literal").map(part=>part.type)}get liveDisabled(){const matches=this.matches;return this.effectiveDisabled||typeof matches=="function"&&matches.call(this,":disabled")}activeSegmentFor(order=this.segmentOrder){return order.includes(this.activeSegment)?this.activeSegment:order[0]??"hour"}get usesTwelveHour(){return this.segmentOrder.includes("dayPeriod")}get draftComplete(){return this.draft.hour!==null&&this.draft.minute!==null&&(!this.includeSeconds||this.draft.second!==null)&&(!this.usesTwelveHour||this.draft.dayPeriod!==null)}get draftHasAny(){return Object.values(this.draft).some(value=>value!==null)}syncDraft(value){const parsed=parseTimeValue(value);if(!parsed){this.draft=blankDraft(),this.secondsVisible=this.numericStep<60;return}this.draft={hour:parsed.hour,minute:parsed.minute,second:parsed.second,dayPeriod:parsed.hour>=12?"pm":"am"},this.secondsVisible=this.numericStep<60||parsed.precision!=="minute"}canonicalDraftValue(){if(!this.draftComplete)return"";const value=`${pad(this.draft.hour)}:${pad(this.draft.minute)}`;return this.includeSeconds?`${value}:${pad(this.draft.second)}`:value}syncComponentStates(){setCustomState(this.internals,"blank",this.value===""),setCustomState(this.internals,"disabled",this.effectiveDisabled),setCustomState(this.internals,"open",this.open)}formattedNumber(value,minimumIntegerDigits){try{return getNumberFormat(this.effectiveLocale,{minimumIntegerDigits,useGrouping:!1}).format(value)}catch{return String(value).padStart(minimumIntegerDigits,"0")}}inputDigit(key){if(/^[0-9]$/.test(key))return key;try{const formatter=getNumberFormat(this.effectiveLocale,{useGrouping:!1});for(let value=0;value<=9;value++)if(formatter.formatToParts(value).find(part=>part.type==="integer")?.value===key)return String(value)}catch{}}displayTime(value){const parsed=parseTimeValue(value);if(!parsed)return value;const includeSeconds=parsed.precision!=="minute",labels=dayPeriodLabels(this.effectiveLocale);return localeTimePattern(this.effectiveLocale,this.hourFormat,includeSeconds).map(part=>{if(part.type==="literal")return part.value;if(part.type==="hour"){const hour=this.usesTwelveHour?parsed.hour%12||12:parsed.hour;return this.formattedNumber(hour,this.usesTwelveHour?1:2)}return part.type==="minute"?this.formattedNumber(parsed.minute,2):part.type==="second"?this.formattedNumber(parsed.second,2):parsed.hour>=12?labels.pm:labels.am}).join("")}segmentNumericValue(name){return name==="hour"?this.draft.hour===null?null:this.usesTwelveHour?this.draft.hour%12||12:this.draft.hour:name==="minute"?this.draft.minute:name==="second"?this.draft.second:this.draft.dayPeriod==="am"?0:this.draft.dayPeriod==="pm"?1:null}segmentText(name){if(this.digitSegment===name&&this.digitBuffer)return this.formattedNumber(Number(this.digitBuffer),this.digitBuffer.length);if(name==="dayPeriod"){const labels=dayPeriodLabels(this.effectiveLocale);return this.draft.dayPeriod?labels[this.draft.dayPeriod]:"--"}const value=this.segmentNumericValue(name);if(value===null)return"--";const minimumDigits=name==="hour"&&this.usesTwelveHour?1:2;return this.formattedNumber(value,minimumDigits)}segmentLabel(name){const keys={hour:"timeInputHour",minute:"timeInputMinute",second:"timeInputSecond",dayPeriod:"timeInputDayPeriod"};return this.localize(keys[name])}segmentBounds(name){return name==="hour"?this.usesTwelveHour?{min:1,max:12}:{min:0,max:23}:name==="dayPeriod"?{min:0,max:1}:{min:0,max:59}}setDraftSegment(name,value,user=!0){if(!(this.liveDisabled||user&&this.readonly)){if(name==="hour")if(value===null)this.draft.hour=null;else{const numeric=Number(value);this.draft.hour=this.usesTwelveHour?to24Hour(numeric,this.draft.dayPeriod??"am"):numeric}else if(name==="dayPeriod"){const period=value==="pm"?"pm":value==="am"?"am":null;if(period&&this.draft.hour!==null){const displayHour=this.draft.hour%12||12;this.draft.hour=to24Hour(displayHour,period)}this.draft.dayPeriod=period}else this.draft[name]=value===null?null:Number(value);if(!user){this.requestUpdate();return}this.publishDraftEdit()}}publishDraftEdit(){const before=super.value,next=this.canonicalDraftValue();this.partial=this.draftHasAny&&!this.draftComplete,super.value=next,this.syncComponentStates(),dispatchNativeInputEvent(this,{inputType:"insertReplacementText"}),this.emit("lr-input",{value:this.value}),next!==""&&next!==before&&(dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value})),this.requestUpdate()}commitUserValue(value,inputType="insertReplacementText",forceChange=!1){const before=this.value;this.value=value,dispatchNativeInputEvent(this,{inputType}),this.emit("lr-input",{value:this.value}),(forceChange||this.value!==before)&&(dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value}))}resetDigitBuffer(){this.digitBuffer="",this.digitSegment=void 0}moveSegment(from,direction){const order=this.segmentOrder,current=Math.max(0,order.indexOf(from)),next=Math.min(order.length-1,Math.max(0,current+direction));this.activeSegment=order[next]??"hour",this.segmentElement(this.activeSegment)?.focus()}acceptDigit(name,digit){if(name==="dayPeriod")return;this.digitSegment!==name&&(this.digitSegment=name,this.digitBuffer="");const bounds=this.segmentBounds(name);let candidateText=`${this.digitBuffer}${digit}`.slice(-2),candidate=Number(candidateText);(candidate>bounds.max||candidateText.length===2&&candidate<bounds.min)&&(candidateText=digit,candidate=Number(digit)),this.digitBuffer=candidateText,candidate>=bounds.min&&candidate<=bounds.max?this.setDraftSegment(name,candidate):this.requestUpdate();const cannotAcceptAnother=candidate*10>bounds.max;(candidateText.length===2||cannotAcceptAnother)&&(this.resetDigitBuffer(),this.moveSegment(name,1))}stepSegment(name,delta){const bounds=this.segmentBounds(name),current=this.segmentNumericValue(name),next=current===null?bounds.min:(current-bounds.min+delta+(bounds.max-bounds.min+1))%(bounds.max-bounds.min+1)+bounds.min;name==="dayPeriod"?this.setDraftSegment(name,next===0?"am":"pm"):this.setDraftSegment(name,next)}segmentElement(name){return this.renderRoot?.querySelector(`[data-segment="${name}"]`)}focus(options){if(this.liveDisabled)return;const order=this.segmentOrder,activeSegment=this.activeSegmentFor(order);activeSegment!==this.activeSegment&&(this.activeSegment=activeSegment),this.segmentElement(activeSegment)?.focus(options)}blur(){const active=this.shadowRoot?.activeElement;active&&typeof active.blur=="function"&&active.blur()}click(){this.liveDisabled||this.focus()}setOpen(next){if(this._open===next)return;const old=this._open;this._open=next,this.syncComponentStates(),this.requestUpdate("open",old)}syncOpenAttribute(){this.toggleAttribute("open",this._open)}requestVisibility(next,announce,restoreFocus){return this._open===next?this.visibilityPromise:next&&this.liveDisabled?(this.syncOpenAttribute(),Promise.resolve()):announce&&this.emit(next?"lr-show":"lr-hide",null,{cancelable:!0}).defaultPrevented?(this.syncOpenAttribute(),Promise.resolve()):(this.restoreFocusOnClose=restoreFocus,this.setOpen(next),this.visibilityPromise=announce?this.settleTransition(next?"lr-after-show":"lr-after-hide"):Promise.resolve(),this.visibilityPromise)}show(){return this.requestVisibility(!0,!0,!0)}hide(){return this.requestVisibility(!1,!0,!0)}forceClose(restoreFocus){this._open&&(this.restoreFocusOnClose=restoreFocus,this.setOpen(!1))}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="popup"]')?.getAnimations({subtree:!0})??[];if(await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),this.transitionToken!==token)return}this.emit(event)}}positionPopup(){this.cleanupPositioner?.(),this.cleanupPositioner=void 0;const anchor=this.renderRoot.querySelector('[part~="time-input"]'),popup=this.renderRoot.querySelector('[part="popup"]');!anchor||!popup||(this.cleanupPositioner=place(anchor,popup,{placement:rtlAwarePlacement(this.placement,this),offset:finiteNumber(this.distance,0),sync:"width"}))}activatePopup(){this.isConnected&&(this.positionPopup(),this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="popup"]'),onEscape:()=>{this.hide()},restoreFocusTo:this.segmentElement(this.activeSegment)}),this.lightDismissDocument=this.ownerDocument,this.lightDismissDocument.addEventListener("pointerdown",this.onDocumentPointerDown,!0),this.updateComplete.then(()=>{this.renderRoot.querySelector('[part~="column-item-selected"]')?.scrollIntoView({block:"center"})}))}teardownPopup(){this.cleanupPositioner?.(),this.cleanupPositioner=void 0,this.overlayHandle?.deactivate({restoreFocus:this.restoreFocusOnClose}),this.overlayHandle=void 0,this.lightDismissDocument?.removeEventListener("pointerdown",this.onDocumentPointerDown,!0),this.lightDismissDocument=void 0,this.restoreFocusOnClose=!0}onColumnSelect(name,value){this.readonly||this.liveDisabled||(this.resetDigitBuffer(),this.setDraftSegment(name,value),this.activeSegment=name,this.updateComplete.then(()=>this.segmentElement(name)?.focus()))}updateSlotState(event){const slot=event.currentTarget,present=slot.assignedNodes({flatten:!0}).some(node=>node.nodeType===Node.ELEMENT_NODE||(node.textContent??"").trim().length>0);slot.name==="label"?this.hasLabelSlot=present:slot.name==="hint"?this.hasHintSlot=present:slot.name==="error"?this.hasErrorSlot=present:slot.name==="start"?this.hasStartSlot=present:slot.name==="end"?this.hasEndSlot=present:slot.name==="footer"&&(this.hasFooterSlot=present)}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let message="";this.required&&this.value===""&&(flags.valueMissing=!0),this.partial&&(flags.badInput=!0);const parsed=parseTimeValue(this.value);if(this.value!==""&&!parsed&&(flags.badInput=!0),parsed&&!isTimeInRange(this.value,this.min,this.max)){const parsedMin=parseTimeValue(this.min),parsedMax=parseTimeValue(this.max);parsedMin&&parsedMax&&parsedMin.milliseconds>parsedMax.milliseconds?(flags.rangeUnderflow=!0,message=this.localize("timeInputRangeMessage",void 0,{min:this.displayTime(this.min),max:this.displayTime(this.max)})):parsedMin&&parsed.milliseconds<parsedMin.milliseconds?(flags.rangeUnderflow=!0,message=this.localize("timeInputMinMessage",void 0,{min:this.displayTime(this.min)})):(flags.rangeOverflow=!0,message=this.localize("timeInputMaxMessage",void 0,{max:this.displayTime(this.max)}))}parsed&&hasTimeStepMismatch(this.value,this.step,this.min,this.defaultValue)&&(flags.stepMismatch=!0,message||=this.localize("timeInputStepMessage")),flags.badInput?message=this.localize("timeInputInvalid"):flags.valueMissing&&(message=this.localize("fieldRequired")),this[SET_ANCHORED_VALIDITY](flags,message)}checkValidity(){return this.updateValidity(),super.checkValidity()}reportValidity(){return this.touched=!0,this.updateValidity(),super.reportValidity()}[VALIDITY_ANCHOR](){return this.segmentElement(this.activeSegmentFor())}formResetCallback(){super.formResetCallback(),this.touched=!1,this.partial=!1,this.resetDigitBuffer()}formStateRestoreCallback(state2,reason="restore"){super.formStateRestoreCallback(state2,reason)}willUpdate(changed){if(super.willUpdate(changed),!this.hasUpdated){const slots=Array.from(this.children??[]).map(element=>element.getAttribute("slot"));this.hasLabelSlot=slots.includes("label"),this.hasHintSlot=slots.includes("hint"),this.hasErrorSlot=slots.includes("error"),this.hasStartSlot=slots.includes("start"),this.hasEndSlot=slots.includes("end"),this.hasFooterSlot=slots.includes("footer")}this.open&&this.effectiveDisabled&&this.forceClose(!1);const order=this.segmentOrder,orderKey=order.join("|"),focusedSegment=orderKey!==this.segmentOrderKey?this.shadowRoot?.activeElement?.getAttribute("data-segment"):null,nextActiveSegment=focusedSegment&&order.includes(focusedSegment)?focusedSegment:this.activeSegmentFor(order);focusedSegment&&(this.pendingSegmentFocus=order.includes(focusedSegment)?focusedSegment:nextActiveSegment),this.segmentOrderKey=orderKey}updated(changed){super.updated(changed),changed.has("open")?this.open?this.activatePopup():this.teardownPopup():this.open&&(changed.has("placement")||changed.has("distance"))&&this.positionPopup(),(changed.has("value")||changed.has("required")||changed.has("readonly")||changed.has("min")||changed.has("max")||changed.has("step"))&&this.updateValidity(),this.syncComponentStates(),this.toggleAttribute("data-invalid",this.touched&&!this.validity.valid),this.syncRequiredDescription();const pendingSegmentFocus=this.pendingSegmentFocus;if(this.pendingSegmentFocus=void 0,pendingSegmentFocus&&!this.effectiveDisabled){this.restoringSegmentFocus=!0;try{this.segmentElement(pendingSegmentFocus)?.focus()}finally{this.restoringSegmentFocus=!1}}}disconnectedCallback(){this.releaseRequiredDescription(),this.transitionToken++,this.forceClose(!1),this.teardownPopup(),this.syncOpenAttribute(),this.pendingSegmentFocus=void 0,super.disconnectedCallback()}syncRequiredDescription(){const target=this.renderRoot.querySelector('[part~="input"]'),description=this.renderRoot.querySelector(`#${this.requiredDescriptionId}`);if(!this.required||!target||!description){this.releaseRequiredDescription();return}if(this.requiredDescriptionTarget!==target){this.releaseRequiredDescription(),this.requiredDescriptionTarget=target,this.requiredDescriptionLease=acquireAriaDescription(target,[description]);return}this.requiredDescriptionLease?.update([description])}releaseRequiredDescription(){this.requiredDescriptionLease?.release(),this.requiredDescriptionLease=void 0,this.requiredDescriptionTarget=void 0}renderSegment(name,invalid){const value=this.segmentNumericValue(name),bounds=this.segmentBounds(name),empty=value===null;return html`
|
|
2
2
|
<span
|
|
3
3
|
part="segment"
|
|
4
4
|
role="spinbutton"
|
|
@@ -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 { LyraLocaleDirection } from '../../../internal/localization.js';
|
|
5
4
|
import type { LyraSize } from '../../../internal/variants.js';
|
|
6
5
|
import { type FormOwnerValue } from '../../../internal/form-associated.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,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import"../../../internal/form-control-labels.js";import{place}from"../../../internal/positioner.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{getLyraLocaleDirection,getRegisteredLyraLocales,subscribeLyraLocaleRegistry,setLyraLocale}from"../../../internal/localization-runtime.js";import{localeNativeName}from"../../media/flag/language-map.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./locale-picker.styles.js";import{declaredDefaultConverter,trueDefaultBooleanFromAttributeConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_localePickerLabel,LYRA_DEFAULT_localePickerRequired}from"../../../internal/default-strings.generated.js";const MAX_LOCALE_ENTRIES=512;function snapshotLocaleCatalog(source){if(!Array.isArray(source))return Object.freeze([]);const rows=[];for(let index=0;index<Math.min(source.length,MAX_LOCALE_ENTRIES);index+=1)try{const raw=source[index];if(typeof raw=="string"){raw.length>0&&rows.push(raw);continue}if(raw===null||typeof raw!="object")continue;const candidate=raw,tag=candidate.tag,label=candidate.label,country=candidate.country;if(typeof tag!="string"||tag.length===0||label!==void 0&&typeof label!="string"||country!==void 0&&typeof country!="string")continue;rows.push(Object.freeze({tag,...label===void 0?{}:{label},...country===void 0?{}:{country}}))}catch{}return Object.freeze(rows)}class LyraLocalePicker extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,localePickerLabel:LYRA_DEFAULT_localePickerLabel,localePickerRequired:LYRA_DEFAULT_localePickerRequired}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:"value",reflect:!0,useDefault:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0}}}get locales(){return this._locales}set locales(next){const previous=this._locales;this._locales=next===void 0?void 0:snapshotLocaleCatalog(next),this.requestUpdate("locales",previous)}get open(){return this._open}set open(next){const old=this._open,liveDisabled=this.effectiveDisabled||typeof this.matches=="function"&&this.matches(":disabled");if(this._open=!!next&&!liveDisabled,this._open===old){next&&!this._open&&this.hasAttribute("open")&&this.removeAttribute("open");return}this._open||(this.activeIndex=-1),this.requestUpdate("open",old)}constructor(){super(),this.showFlags=!0,this.label="",this.hint="",this.errorText="",this.size="m",this.activeIndex=-1,this.touched=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.hasLabelSlot=!1,this.registryTick=0,this.listId=nextId("locale-picker-list"),this.controlId=nextId("locale-picker-control"),this._value="",this._open=!1,this._fieldsetDisabled=!1,this._name="",this._disabled=!1,this._required=!1,this._defaultValue="",this._valueDirty=!1,this.settingDefaultValue=!1,this.reflectingDefaultValue=!1,this.typeAheadBuffer="",this.typeAheadTimerGeneration=0,this.activeScrollGeneration=0,this.onDocPointer=e=>{e.composedPath().includes(this)||this.hide()},this.onTriggerClick=()=>{this.liveDisabled||(this.open?this.hide():this.show())},this.onTriggerBlur=event=>{this.liveDisabled||(this.touched=!0),this.syncCustomStates(),this.hide(),relayNativeEvent(this,event)},this.onTriggerFocus=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.onKeyDown=e=>{if(this.liveDisabled)return;const rows=this.normalizedEntries;switch(e.key){case"ArrowDown":if(e.preventDefault(),!this.open)return this.show();this.setActiveIndex(Math.min(rows.length-1,this.activeIndex+1));break;case"ArrowUp":if(e.preventDefault(),!this.open)return this.show();this.setActiveIndex(Math.max(0,this.activeIndex-1));break;case"Enter":case" ":if(this.open){e.preventDefault();const activeRow=rows[this.activeIndex];this.activeIndex>=0&&activeRow?this.commit(activeRow.tag):this.hide()}break;case"Escape":this.open&&(e.preventDefault(),this.hide());break;case"Home":this.open&&(e.preventDefault(),this.setActiveIndex(0));break;case"End":this.open&&(e.preventDefault(),this.setActiveIndex(rows.length-1));break;default:e.key.length===1&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&this.typeAhead(e.key);break}},this.onListboxMouseDown=e=>{e.target.closest('[part="option"]')&&e.preventDefault()},this.onListboxClick=e=>{if(this.liveDisabled)return;const tag=e.target.closest('[part="option"]')?.dataset.value;tag!==void 0&&this.commit(tag)},this.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("")}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}focus(options){this.liveDisabled||this.triggerElement?.focus(options)}blur(){this.triggerElement?.blur()}click(){this.liveDisabled||this.triggerElement?.click()}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.stopRegistrySubscription=subscribeLyraLocaleRegistry(()=>{this.registryTick+=1}),this.hasUpdated&&this.open&&queueMicrotask(()=>this.syncPopup())}disconnectedCallback(){super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.unbindDocumentPointer(),this.stopRegistrySubscription?.(),this.stopRegistrySubscription=void 0,this.clearTypeAheadTimer(),this.activeScrollGeneration+=1,this.typeAheadBuffer="",this.open=!1}adoptedCallback(){super.adoptedCallback(),this.cleanup?.(),this.cleanup=void 0,this.unbindDocumentPointer(),this.clearTypeAheadTimer()}willUpdate(changed){super.willUpdate(changed),this.open&&(changed.has("locales")||changed.has("registryTick"))&&this.activeIndex>=0&&(this.activeIndex=Math.min(this.activeIndex,this.normalizedEntries.length-1),this.queueActiveScroll()),this.hasUpdated||(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.hasLabelSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="label"))}get value(){return this._value}set value(next){const old=this._value;this.settingDefaultValue||(this._valueDirty=!0),this._value=next??"",this.internals.setFormValue(this._value),this.updateValidity(),this.requestUpdate("value",old)}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next??"",this.reflectingDefaultValue=!0;try{this._defaultValue?this.setAttribute("value",this._defaultValue):this.removeAttribute("value")}finally{this.reflectingDefaultValue=!1}this._valueDirty||this.restoreLiveValueFromDefault(),this.requestUpdate("defaultValue",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._disabled&&this.hide(),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}updateValidity(){this.isBarred()?this.validityController.setValidity({}):this.required&&!this._value?this.validityController.setValidity({valueMissing:!0},this.localize("localePickerRequired")):this.validityController.setValidity({}),this.syncCustomStates()}isBarred(){return isBarredFromValidation(this,this.internals)}syncCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.isBarred()})}formResetCallback(){this.touched=!1,this.restoreLiveValueFromDefault()}restoreLiveValueFromDefault(){this.settingDefaultValue=!0;try{this.value=this._defaultValue}finally{this.settingDefaultValue=!1}this._valueDirty=!1}formStateRestoreCallback(state2,_mode){this.value=typeof state2=="string"?state2:""}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,disabled&&this.hide(),this.updateValidity(),this.requestUpdate()}checkValidity(){return this.internals.checkValidity()}reportValidity(){return this.touched=!0,this.syncCustomStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncCustomStates(),this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),this.requestUpdate()}get normalizedEntries(){const raw=this.locales;return raw!==void 0?raw.map(entry=>typeof entry=="string"?{tag:entry,label:localeNativeName(entry)}:{tag:entry.tag,label:entry.label??localeNativeName(entry.tag),country:entry.country}):getRegisteredLyraLocales().map(tag=>({tag,label:localeNativeName(tag)}))}get previewTag(){return this._value||this.effectiveLocale}entryFor(tag){return this.normalizedEntries.find(e=>e.tag===tag)}labelFor(tag){return this.entryFor(tag)?.label??localeNativeName(tag)}show(){this.open||this.liveDisabled||(this.open=!0)}hide(){this.open&&(this.open=!1,this.setActiveIndex(-1))}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)}unbindDocumentPointer(){this.pointerListenerDocument&&this.pointerListener&&this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener),this.pointerListenerDocument=void 0,this.pointerListener=void 0}syncPopup(){if(this.cleanup?.(),this.cleanup=void 0,!this.open||!this.isConnected){this.unbindDocumentPointer();return}this.bindDocumentPointer();const anchor=this.renderRoot.querySelector('[part="trigger"]'),listbox=this.renderRoot.querySelector('[part="listbox"]');anchor&&listbox&&(this.cleanup=place(anchor,listbox))}updated(changed){super.updated(changed),(changed.has("open")||this.open&&(changed.has("locales")||changed.has("registryTick")))&&this.syncPopup(),(changed.has("touched")||changed.has("required")||changed.has("value"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}commit(tag){const previousValue=this._value;this.value=tag,this.hide(),this.emit("lr-change",{value:tag,previousValue,direction:getLyraLocaleDirection(tag)},{cancelable:!0}).defaultPrevented||setLyraLocale(tag)}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 rows=this.normalizedEntries;if(!rows.length)return;const currentTag=this.open?rows[this.activeIndex]?.tag:this.previewTag,currentIndex=rows.findIndex(r=>r.tag===currentTag),n=rows.length;for(let step=1;step<=n;step++){const idx=(currentIndex+step+n)%n,row=rows[idx];if(row&&row.label.toLocaleLowerCase(this.effectiveLocale).startsWith(this.typeAheadBuffer)){this.open?this.setActiveIndex(idx):this.commit(row.tag);return}}}clearTypeAheadTimer(){this.typeAheadTimerGeneration+=1,this.typeAheadTimer!==void 0&&this.typeAheadTimerWindow?.clearTimeout(this.typeAheadTimer),this.typeAheadTimer=void 0,this.typeAheadTimerWindow=void 0}setActiveIndex(index){const last=this.normalizedEntries.length-1,next=last<0||index<0?-1:Math.min(last,index);this.activeIndex=next,this.queueActiveScroll()}queueActiveScroll(){const generation=++this.activeScrollGeneration,index=this.activeIndex;index<0||!this.open||this.updateComplete.then(()=>{generation!==this.activeScrollGeneration||!this.isConnected||!this.open||this.activeIndex!==index||this.shadowRoot?.getElementById(`${this.listId}-opt-${index}`)?.scrollIntoView({block:"nearest"})})}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`,selected=entry.tag===this._value;return html`<div
|
|
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{place}from"../../../internal/positioner.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{getLyraLocaleDirection,getRegisteredLyraLocales,subscribeLyraLocaleRegistry,setLyraLocale}from"../../../internal/localization-runtime.js";import{localeNativeName}from"../../media/flag/language-map.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./locale-picker.styles.js";import{declaredDefaultConverter,trueDefaultBooleanFromAttributeConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_localePickerLabel,LYRA_DEFAULT_localePickerRequired}from"../../../internal/default-strings.generated.js";const MAX_LOCALE_ENTRIES=512;function snapshotLocaleCatalog(source){if(!Array.isArray(source))return Object.freeze([]);const rows=[];for(let index=0;index<Math.min(source.length,MAX_LOCALE_ENTRIES);index+=1)try{const raw=source[index];if(typeof raw=="string"){raw.length>0&&rows.push(raw);continue}if(raw===null||typeof raw!="object")continue;const candidate=raw,tag=candidate.tag,label=candidate.label,country=candidate.country;if(typeof tag!="string"||tag.length===0||label!==void 0&&typeof label!="string"||country!==void 0&&typeof country!="string")continue;rows.push(Object.freeze({tag,...label===void 0?{}:{label},...country===void 0?{}:{country}}))}catch{}return Object.freeze(rows)}class LyraLocalePicker extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,localePickerLabel:LYRA_DEFAULT_localePickerLabel,localePickerRequired:LYRA_DEFAULT_localePickerRequired}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:"value",reflect:!0,useDefault:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0}}}get locales(){return this._locales}set locales(next){const previous=this._locales;this._locales=next===void 0?void 0:snapshotLocaleCatalog(next),this.requestUpdate("locales",previous)}get open(){return this._open}set open(next){const old=this._open,liveDisabled=this.effectiveDisabled||typeof this.matches=="function"&&this.matches(":disabled");if(this._open=!!next&&!liveDisabled,this._open===old){next&&!this._open&&this.hasAttribute("open")&&this.removeAttribute("open");return}this._open||(this.activeIndex=-1),this.requestUpdate("open",old)}constructor(){super(),this.showFlags=!0,this.label="",this.hint="",this.errorText="",this.size="m",this.activeIndex=-1,this.touched=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.hasLabelSlot=!1,this.registryTick=0,this.listId=nextId("locale-picker-list"),this.controlId=nextId("locale-picker-control"),this._value="",this._open=!1,this._fieldsetDisabled=!1,this._name="",this._disabled=!1,this._required=!1,this._defaultValue="",this._valueDirty=!1,this.settingDefaultValue=!1,this.reflectingDefaultValue=!1,this.typeAheadBuffer="",this.typeAheadTimerGeneration=0,this.activeScrollGeneration=0,this.onDocPointer=e=>{e.composedPath().includes(this)||this.hide()},this.onTriggerClick=()=>{this.liveDisabled||(this.open?this.hide():this.show())},this.onTriggerBlur=event=>{this.liveDisabled||(this.touched=!0),this.syncCustomStates(),this.hide(),relayNativeEvent(this,event)},this.onTriggerFocus=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.onKeyDown=e=>{if(this.liveDisabled)return;const rows=this.normalizedEntries;switch(e.key){case"ArrowDown":if(e.preventDefault(),!this.open)return this.show();this.setActiveIndex(Math.min(rows.length-1,this.activeIndex+1));break;case"ArrowUp":if(e.preventDefault(),!this.open)return this.show();this.setActiveIndex(Math.max(0,this.activeIndex-1));break;case"Enter":case" ":if(this.open){e.preventDefault();const activeRow=rows[this.activeIndex];this.activeIndex>=0&&activeRow?this.commit(activeRow.tag):this.hide()}break;case"Escape":this.open&&(e.preventDefault(),this.hide());break;case"Home":this.open&&(e.preventDefault(),this.setActiveIndex(0));break;case"End":this.open&&(e.preventDefault(),this.setActiveIndex(rows.length-1));break;default:e.key.length===1&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&this.typeAhead(e.key);break}},this.onListboxMouseDown=e=>{e.target.closest('[part="option"]')&&e.preventDefault()},this.onListboxClick=e=>{if(this.liveDisabled)return;const tag=e.target.closest('[part="option"]')?.dataset.value;tag!==void 0&&this.commit(tag)},this.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("")}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}focus(options){this.liveDisabled||this.triggerElement?.focus(options)}blur(){this.triggerElement?.blur()}click(){this.liveDisabled||this.triggerElement?.click()}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.stopRegistrySubscription=subscribeLyraLocaleRegistry(()=>{this.registryTick+=1}),this.hasUpdated&&this.open&&queueMicrotask(()=>this.syncPopup())}disconnectedCallback(){super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.unbindDocumentPointer(),this.stopRegistrySubscription?.(),this.stopRegistrySubscription=void 0,this.clearTypeAheadTimer(),this.activeScrollGeneration+=1,this.typeAheadBuffer="",this.open=!1}adoptedCallback(){super.adoptedCallback(),this.cleanup?.(),this.cleanup=void 0,this.unbindDocumentPointer(),this.clearTypeAheadTimer()}willUpdate(changed){super.willUpdate(changed),this.open&&(changed.has("locales")||changed.has("registryTick"))&&this.activeIndex>=0&&(this.activeIndex=Math.min(this.activeIndex,this.normalizedEntries.length-1),this.queueActiveScroll()),this.hasUpdated||(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.hasLabelSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="label"))}get value(){return this._value}set value(next){const old=this._value;this.settingDefaultValue||(this._valueDirty=!0),this._value=next??"",this.internals.setFormValue(this._value),this.updateValidity(),this.requestUpdate("value",old)}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next??"",this.reflectingDefaultValue=!0;try{this._defaultValue?this.setAttribute("value",this._defaultValue):this.removeAttribute("value")}finally{this.reflectingDefaultValue=!1}this._valueDirty||this.restoreLiveValueFromDefault(),this.requestUpdate("defaultValue",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._disabled&&this.hide(),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}updateValidity(){this.isBarred()?this.validityController.setValidity({}):this.required&&!this._value?this.validityController.setValidity({valueMissing:!0},this.localize("localePickerRequired")):this.validityController.setValidity({}),this.syncCustomStates()}isBarred(){return isBarredFromValidation(this,this.internals)}syncCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.isBarred()})}formResetCallback(){this.touched=!1,this.restoreLiveValueFromDefault()}restoreLiveValueFromDefault(){this.settingDefaultValue=!0;try{this.value=this._defaultValue}finally{this.settingDefaultValue=!1}this._valueDirty=!1}formStateRestoreCallback(state2,_mode){this.value=typeof state2=="string"?state2:""}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,disabled&&this.hide(),this.updateValidity(),this.requestUpdate()}checkValidity(){return this.internals.checkValidity()}reportValidity(){return this.touched=!0,this.syncCustomStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncCustomStates(),this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),this.requestUpdate()}get normalizedEntries(){const raw=this.locales;return raw!==void 0?raw.map(entry=>typeof entry=="string"?{tag:entry,label:localeNativeName(entry)}:{tag:entry.tag,label:entry.label??localeNativeName(entry.tag),country:entry.country}):getRegisteredLyraLocales().map(tag=>({tag,label:localeNativeName(tag)}))}get previewTag(){return this._value||this.effectiveLocale}entryFor(tag){return this.normalizedEntries.find(e=>e.tag===tag)}labelFor(tag){return this.entryFor(tag)?.label??localeNativeName(tag)}show(){this.open||this.liveDisabled||(this.open=!0)}hide(){this.open&&(this.open=!1,this.setActiveIndex(-1))}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)}unbindDocumentPointer(){this.pointerListenerDocument&&this.pointerListener&&this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener),this.pointerListenerDocument=void 0,this.pointerListener=void 0}syncPopup(){if(this.cleanup?.(),this.cleanup=void 0,!this.open||!this.isConnected){this.unbindDocumentPointer();return}this.bindDocumentPointer();const anchor=this.renderRoot.querySelector('[part="trigger"]'),listbox=this.renderRoot.querySelector('[part="listbox"]');anchor&&listbox&&(this.cleanup=place(anchor,listbox))}updated(changed){super.updated(changed),(changed.has("open")||this.open&&(changed.has("locales")||changed.has("registryTick")))&&this.syncPopup(),(changed.has("touched")||changed.has("required")||changed.has("value"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}commit(tag){const previousValue=this._value;this.value=tag,this.hide(),this.emit("lr-change",{value:tag,previousValue,direction:getLyraLocaleDirection(tag)},{cancelable:!0}).defaultPrevented||setLyraLocale(tag)}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 rows=this.normalizedEntries;if(!rows.length)return;const currentTag=this.open?rows[this.activeIndex]?.tag:this.previewTag,currentIndex=rows.findIndex(r=>r.tag===currentTag),n=rows.length;for(let step=1;step<=n;step++){const idx=(currentIndex+step+n)%n,row=rows[idx];if(row&&row.label.toLocaleLowerCase(this.effectiveLocale).startsWith(this.typeAheadBuffer)){this.open?this.setActiveIndex(idx):this.commit(row.tag);return}}}clearTypeAheadTimer(){this.typeAheadTimerGeneration+=1,this.typeAheadTimer!==void 0&&this.typeAheadTimerWindow?.clearTimeout(this.typeAheadTimer),this.typeAheadTimer=void 0,this.typeAheadTimerWindow=void 0}setActiveIndex(index){const last=this.normalizedEntries.length-1,next=last<0||index<0?-1:Math.min(last,index);this.activeIndex=next,this.queueActiveScroll()}queueActiveScroll(){const generation=++this.activeScrollGeneration,index=this.activeIndex;index<0||!this.open||this.updateComplete.then(()=>{generation!==this.activeScrollGeneration||!this.isConnected||!this.open||this.activeIndex!==index||this.shadowRoot?.getElementById(`${this.listId}-opt-${index}`)?.scrollIntoView({block:"nearest"})})}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`,selected=entry.tag===this._value;return html`<div
|
|
2
2
|
part="option"
|
|
3
3
|
id=${id}
|
|
4
4
|
role="option"
|
|
@@ -1,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 { LyraRadio } from './radio.class.js';
|
|
6
5
|
import { type FormOwnerValue } from '../../../internal/form-associated.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{nextId}from"../../../internal/a11y.js";import{tag}from"../../../internal/prefix.js";import{sizes}from"../../../internal/sizes.styles.js";import{groupStyles}from"./radio-group.styles.js";import{dispatchNativeEvent,dispatchNativeInputEvent}from"../../../internal/native-event-relay.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{attachInternalsSafely,getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{declaredDefaultConverter,omittedEmptyStringConverter}from"../../../internal/converters.js";import{isAccessibilitySubtreeExcluded,isAriaTrue}from"../../../internal/accessibility-visibility.js";import{composedParentElement}from"../../../internal/active-element.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_radioRequired}from"../../../internal/default-strings.generated.js";const RADIO_TAGS=()=>[tag("radio"),tag("radio-button")];class LyraRadioGroup extends LyraElement{static{this.defaultStrings={...super.defaultStrings,radioRequired:LYRA_DEFAULT_radioRequired}}static{this.immutableEventDetails=Object.freeze(["lr-input","lr-change"])}static{this.identityEventDetailProperties=Object.freeze({"lr-input":Object.freeze(["radio"]),"lr-change":Object.freeze(["radio"])})}static get validators(){return[currentValidityValidator("required","disabled","value")]}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,groupStyles]}static{this.properties={name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:"value",reflect:!0,useDefault:!0,noAccessor:!0},customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},orientation:{reflect:!0,converter:declaredDefaultConverter("vertical")},form:{noAccessor:!0}}}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.syncFormState(),this.requestUpdate("name",old)}get value(){return this._value}set value(next){this._valueDirty=!0,this.selectValue(next??"")}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next??"",this.reflectingDefaultValue=!0;try{this._defaultValue?this.setAttribute("value",this._defaultValue):this.removeAttribute("value")}finally{this.reflectingDefaultValue=!1}this._valueDirty||(this.selectValue(this._defaultValue),this._valueDirty=!1),this.requestUpdate("defaultValue",old)}get customError(){return this.validityController?.customValidityMessage||null}set customError(next){this.reflectingCustomError||this.commitCustomValidity(next)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.syncRadios(),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.syncRadios(),this.updateValidity(),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}constructor(){super(),this.size="m",this.orientation="vertical",this.label="",this.hint="",this.helpText="",this.shoelaceDefaultValue="",this.withLabel=!1,this.withHint=!1,this.errorText="",this.accessibleLabel="",this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasHelpTextSlot=!1,this.hasErrorSlot=!1,this.labelId=nextId("radio-group-label"),this.hintId=nextId("radio-group-hint"),this.errorId=nextId("radio-group-error"),this.managedRadios=new Set,this.syncingRadios=!1,this.membershipObserverGeneration=0,this._name="",this._value="",this._defaultValue="",this._valueDirty=!1,this.reflectingDefaultValue=!1,this.reflectingCustomError=!1,this._required=!1,this._disabled=!1,this._fieldsetDisabled=!1,this.hasInteracted=!1,this.hadShoelaceDefaultValue=!1,this.onInvalid=event=>{const target=event.target;if(target!==this&&!(target?.nodeType===1&&this.ownsRadio(target)))return;this.emit("lr-invalid",null,{cancelable:!0}).defaultPrevented&&event.preventDefault()},this.onKeyDown=event=>{if(![...this.orientation==="horizontal"?["ArrowRight","ArrowLeft"]:["ArrowDown","ArrowUp"],"Home","End"].includes(event.key)||this.effectiveDisabled)return;const radios=this.radios().filter(radio=>this.isRadioAvailable(radio)),current=event.target;if(!this.isRadioAvailable(current))return;const index=radios.indexOf(current);if(index<0||radios.length===0)return;event.preventDefault();const rtl=this.effectiveDirection==="rtl",forward=this.orientation==="vertical"?event.key==="ArrowDown":rtl?event.key==="ArrowLeft":event.key==="ArrowRight",backward=this.orientation==="vertical"?event.key==="ArrowUp":rtl?event.key==="ArrowRight":event.key==="ArrowLeft",nextIndex=event.key==="Home"?0:event.key==="End"?radios.length-1:forward?(index+1)%radios.length:backward?(index-1+radios.length)%radios.length:index,next=radios[nextIndex];next.focus(),next.activateFromGroup()},this.onSlotChange=event=>{const slot=event.target,elements=slot.assignedElements({flatten:!0});slot.name==="label"&&(this.hasLabelSlot=elements.length>0),slot.name==="hint"&&(this.hasHintSlot=elements.length>0),slot.name==="help-text"&&(this.hasHelpTextSlot=elements.length>0),slot.name==="error"&&(this.hasErrorSlot=elements.length>0)},this.onRadioSlotChange=()=>{this.syncRadios();const ownerDocument=this.ownerDocument,generation=this.membershipObserverGeneration,ownerWindow=ownerDocument?.defaultView;ownerWindow&&ownerWindow.queueMicrotask(()=>{this.membershipObserverGeneration===generation&&this.isConnected&&this.ownerDocument===ownerDocument&&this.syncRadios()})},this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),this.addEventListener("invalid",this.onInvalid,!0),this.syncFormState(),this.updateValidity()}connectedCallback(){super.connectedCallback(),this.syncSupportSlots(),this.syncRadios(),this.armMembershipObserver(),this.armRunResizeObserver(),this.scheduleRunProjection()}armRunResizeObserver(){this.runResizeObserver?.disconnect();const ResizeObserverCtor=this.ownerDocument?.defaultView?.ResizeObserver;if(!(!ResizeObserverCtor||!this.isConnected)){this.runResizeObserver=new ResizeObserverCtor(()=>this.scheduleRunProjection()),this.runResizeObserver.observe(this);for(const radio of this.radios())this.runResizeObserver.observe(radio)}}scheduleRunProjection(){const ownerWindow=this.ownerDocument?.defaultView;!ownerWindow||!this.isConnected||this.runProjectionFrame!==void 0||(this.runProjectionFrame=ownerWindow.requestAnimationFrame(()=>{this.runProjectionFrame=void 0,this.isConnected&&this.projectButtonRuns()}))}isButtonRadio(radio){return radio.localName===tag("radio-button")||radio.appearance==="button"}areActuallyAdjacent(first,second){const firstRect=first.getBoundingClientRect(),secondRect=second.getBoundingClientRect();if(firstRect.width<=0||firstRect.height<=0||secondRect.width<=0||secondRect.height<=0||!(Math.abs(firstRect.top-secondRect.top)<=1&&Math.abs(firstRect.bottom-secondRect.bottom)<=1))return!1;const gap=getComputedStyle(this).direction==="rtl"?firstRect.left-secondRect.right:secondRect.left-firstRect.right;return gap>=-2&&gap<=1}projectButtonRuns(){const radios=this.radios(),joinsPrevious=radios.map(()=>!1);if(this.orientation==="horizontal")for(let index=1;index<radios.length;index+=1){const previous=radios[index-1],current=radios[index];joinsPrevious[index]=this.isButtonRadio(previous)&&this.isButtonRadio(current)&&this.areActuallyAdjacent(previous,current)}for(let index=0;index<radios.length;index+=1){const joinsBefore=joinsPrevious[index]??!1,joinsAfter=joinsPrevious[index+1]??!1,position=joinsBefore?joinsAfter?"middle":"end":joinsAfter?"start":"standalone";radios[index].setButtonRunPosition(position)}}armMembershipObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected||this.membershipObserver&&this.membershipObserverDocument===ownerDocument)return;this.resetMembershipObserver();const ownerWindow=ownerDocument?.defaultView,MutationObserverCtor=ownerWindow?.MutationObserver;if(!ownerWindow||!MutationObserverCtor)return;const generation=this.membershipObserverGeneration,observer=new MutationObserverCtor(()=>{this.membershipObserver!==observer||this.membershipObserverDocument!==ownerDocument||this.membershipObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||ownerWindow.queueMicrotask(()=>{this.membershipObserver!==observer||this.membershipObserverDocument!==ownerDocument||this.membershipObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.syncRadios()})});this.membershipObserver=observer,this.membershipObserverDocument=ownerDocument,observer.observe(this,{attributes:!0,childList:!0,subtree:!0,attributeFilter:["slot","checked","disabled","value","size","appearance","hidden","inert","aria-hidden","aria-disabled","class","style"]})}disconnectedCallback(){this.resetMembershipObserver(),this.runResizeObserver?.disconnect(),this.runResizeObserver=void 0;const ownerWindow=this.ownerDocument?.defaultView;ownerWindow&&this.runProjectionFrame!==void 0&&ownerWindow.cancelAnimationFrame(this.runProjectionFrame),this.runProjectionFrame=void 0,this.releaseRadios(this.managedRadios),this.managedRadios.clear(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resetMembershipObserver()}resetMembershipObserver(){this.membershipObserverGeneration+=1,this.membershipObserver?.disconnect(),this.membershipObserver=void 0,this.membershipObserverDocument=void 0}willUpdate(changed){super.willUpdate(changed),changed.has("shoelaceDefaultValue")&&(this.hasAttribute("default-value")||this.hadShoelaceDefaultValue)&&(this.defaultValue=this.shoelaceDefaultValue,this.hadShoelaceDefaultValue=this.hasAttribute("default-value"))}updated(changed){super.updated(changed),this.syncRadios()}syncSupportSlots(){this.hasLabelSlot=Array.from(this.children??[]).some(element=>element.getAttribute("slot")==="label"),this.hasHintSlot=Array.from(this.children??[]).some(element=>element.getAttribute("slot")==="hint"),this.hasHelpTextSlot=Array.from(this.children??[]).some(element=>element.getAttribute("slot")==="help-text"),this.hasErrorSlot=Array.from(this.children??[]).some(element=>element.getAttribute("slot")==="error")}radioGroupOwner(element){const group=element.closest(tag("radio-group"));if(!group)return null;let topLevelChild=element;for(;topLevelChild.parentElement&&topLevelChild.parentElement!==group;)topLevelChild=topLevelChild.parentElement;if(topLevelChild.parentElement!==group)return null;const slot=topLevelChild.getAttribute("slot");return slot==="label"||slot==="hint"||slot==="help-text"||slot==="error"?null:group}ownsRadio(element){return RADIO_TAGS().includes(element.localName)&&this.radioGroupOwner(element)===this}radios(){const querySelectorAll=this.querySelectorAll;return typeof querySelectorAll!="function"?[]:[...querySelectorAll.call(this,RADIO_TAGS().join(","))].filter(radio=>this.ownsRadio(radio)&&typeof radio.setGroupOwner=="function")}isRadioAvailable(radio){if(radio.effectiveDisabled||radio.matches(":disabled"))return!1;for(let current=radio;current;current=composedParentElement(current)){if(isAccessibilitySubtreeExcluded(current)||isAriaTrue(current.getAttribute("aria-disabled")))return!1;if(current===this)break}return!0}selectValue(next){const desired=next??"",radios=this.radios();if(radios.length===0){const old=this._value;this._value=desired,this.pendingSelection=desired,this.syncFormState(),this.updateValidity(),this.requestUpdate("value",old);return}const match=radios.find(radio=>radio.value===desired);this.syncingRadios=!0;try{for(const radio of radios)radio.checked=radio===match}finally{this.syncingRadios=!1}this.pendingSelection=void 0,this.syncRadios(match)}syncRadios(preferred){if(!this.syncingRadios){this.syncingRadios=!0;try{const radios=this.radios(),current=new Set(radios);this.releaseRadios([...this.managedRadios].filter(radio=>!current.has(radio)));for(const radio of radios)radio.setGroupOwner(this);this.managedRadios=current,this.armRunResizeObserver();for(const radio of radios)radio.setGroupDisabled(this.effectiveDisabled);const enabled=radios.filter(radio=>this.isRadioAvailable(radio));let checked=radios.filter(radio=>radio.checked),checkedRadio;if(this.pendingSelection!==void 0&&radios.length>0){checkedRadio=radios.find(radio=>radio.value===this.pendingSelection);for(const radio of radios)radio.checked=radio===checkedRadio;checked=checkedRadio?[checkedRadio]:[],this.pendingSelection=void 0}else checkedRadio=preferred?.checked&¤t.has(preferred)?preferred:checked[checked.length-1];for(const radio of checked)radio!==checkedRadio&&(radio.checked=!1);const tabbableRadio=checkedRadio&&this.isRadioAvailable(checkedRadio)?checkedRadio:enabled[0];for(const radio of radios)radio.setGroupSize(this.size),radio.setGroupRequired(this.required&&!this.effectiveDisabled),radio.setGroupTabbable(radio===tabbableRadio);const oldValue=this._value;this._value=checkedRadio?.value??"",this.syncFormState(),this.updateValidity(),oldValue!==this._value&&this.requestUpdate("value",oldValue),this.scheduleRunProjection()}finally{this.syncingRadios=!1}}}releaseRadios(radios){for(const radio of radios)radio.releaseGroupOwner(this),radio.setButtonRunPosition("standalone")}reconcileRadio(radio){return this.ownsRadio(radio)?(this.syncRadios(radio.checked?radio:void 0),!0):!1}releaseRadio(radio){this.managedRadios.has(radio)&&(this.releaseRadios([radio]),this.managedRadios.delete(radio),this.syncRadios())}radioCheckedChanged(radio){this.syncingRadios||!this.ownsRadio(radio)||(this._valueDirty=!0,this.syncRadios(radio.checked?radio:void 0))}selectRadio(radio){if(this.effectiveDisabled||!this.ownsRadio(radio)||!this.isRadioAvailable(radio))return!1;this._valueDirty=!0,this.hasInteracted=!0,this.syncingRadios=!0;try{for(const candidate of this.radios())candidate.checked=candidate===radio}finally{this.syncingRadios=!1}return this.syncRadios(),dispatchNativeInputEvent(this),this.emit("lr-input",{value:radio.value,radio}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:radio.value,radio}),!0}focus(options){if(this.effectiveDisabled||this.matches(":disabled"))return;const enabled=this.radios().filter(radio=>this.isRadioAvailable(radio));(enabled.find(radio=>radio.checked)??enabled[0])?.focus(options)}blur(){this.radios().find(radio=>radio.matches(":focus-within"))?.blur()}click(){if(this.effectiveDisabled||this.matches(":disabled"))return;const enabled=this.radios().filter(radio=>this.isRadioAvailable(radio));(enabled.find(radio=>radio.checked)??enabled[0])?.click()}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part~="base"]')??null}syncFormState(){this.internals&&this.internals.setFormValue(this.name&&this.value?this.value:null,this.value)}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){if(!this.validityController)return;const missing=!this.barredFromValidation&&this.required&&!this.value;this.validityController.setValidity(missing?{valueMissing:!0}:{},missing?this.localize("radioRequired"):""),this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred:this.barredFromValidation})}checkValidity(){return this.internals.checkValidity()}reportValidity(){return this.hasInteracted=!0,this.updateValidity(),this.internals.reportValidity()}commitCustomValidity(message){const old=this.customError,normalized=message??"";this.validityController.setCustomValidity(normalized),this.reflectValidityStates(),this.reflectingCustomError=!0;try{normalized?this.setAttribute("custom-error",normalized):this.removeAttribute("custom-error")}finally{this.reflectingCustomError=!1}this.requestUpdate("customError",old)}setCustomValidity(message=""){this.commitCustomValidity(message)}resetValidity(){this.commitCustomValidity(""),this.updateValidity()}formResetCallback(){this._valueDirty=!1,this.pendingSelection=void 0,this.syncingRadios=!0;try{for(const radio of this.radios())radio.resetFromGroup()}finally{this.syncingRadios=!1}this.defaultValue&&(this.pendingSelection=this.defaultValue),this.hasInteracted=!1,this.syncRadios()}formStateRestoreCallback(state2,reason){this._valueDirty=!0,this.hasInteracted=!1,this.pendingSelection=typeof state2=="string"?state2:"",this.selectValue(this.pendingSelection)}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,this.syncRadios(),this.updateValidity(),this.requestUpdate()}render(){const hasLabel=this.hasLabelSlot||!!this.label||this.withLabel,hasAccessibleLabel=this.hasAttribute("aria-label")||!!this.accessibleLabel,hasHint=this.hasHintSlot||this.hasHelpTextSlot||!!(this.hint||this.helpText)||this.withHint,hasError=this.hasErrorSlot||!!this.errorText,described=[hasHint?this.hintId:"",hasError?this.errorId:""].filter(Boolean).join(" ")||nothing;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{nextId}from"../../../internal/a11y.js";import{tag}from"../../../internal/prefix.js";import{sizes}from"../../../internal/sizes.styles.js";import{groupStyles}from"./radio-group.styles.js";import{dispatchNativeEvent,dispatchNativeInputEvent}from"../../../internal/native-event-relay.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{attachInternalsSafely,getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{declaredDefaultConverter,omittedEmptyStringConverter}from"../../../internal/converters.js";import{isAccessibilitySubtreeExcluded,isAriaTrue}from"../../../internal/accessibility-visibility.js";import{composedParentElement}from"../../../internal/active-element.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_radioRequired}from"../../../internal/default-strings.generated.js";const RADIO_TAGS=()=>[tag("radio"),tag("radio-button")];class LyraRadioGroup extends LyraElement{static{this.defaultStrings={...super.defaultStrings,radioRequired:LYRA_DEFAULT_radioRequired}}static{this.immutableEventDetails=Object.freeze(["lr-input","lr-change"])}static{this.identityEventDetailProperties=Object.freeze({"lr-input":Object.freeze(["radio"]),"lr-change":Object.freeze(["radio"])})}static get validators(){return[currentValidityValidator("required","disabled","value")]}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,groupStyles]}static{this.properties={name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:"value",reflect:!0,useDefault:!0,noAccessor:!0},customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},orientation:{reflect:!0,converter:declaredDefaultConverter("vertical")},form:{noAccessor:!0}}}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.syncFormState(),this.requestUpdate("name",old)}get value(){return this._value}set value(next){this._valueDirty=!0,this.selectValue(next??"")}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next??"",this.reflectingDefaultValue=!0;try{this._defaultValue?this.setAttribute("value",this._defaultValue):this.removeAttribute("value")}finally{this.reflectingDefaultValue=!1}this._valueDirty||(this.selectValue(this._defaultValue),this._valueDirty=!1),this.requestUpdate("defaultValue",old)}get customError(){return this.validityController?.customValidityMessage||null}set customError(next){this.reflectingCustomError||this.commitCustomValidity(next)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.syncRadios(),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.syncRadios(),this.updateValidity(),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}constructor(){super(),this.size="m",this.orientation="vertical",this.label="",this.hint="",this.helpText="",this.shoelaceDefaultValue="",this.withLabel=!1,this.withHint=!1,this.errorText="",this.accessibleLabel="",this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasHelpTextSlot=!1,this.hasErrorSlot=!1,this.labelId=nextId("radio-group-label"),this.hintId=nextId("radio-group-hint"),this.errorId=nextId("radio-group-error"),this.managedRadios=new Set,this.syncingRadios=!1,this.membershipObserverGeneration=0,this._name="",this._value="",this._defaultValue="",this._valueDirty=!1,this.reflectingDefaultValue=!1,this.reflectingCustomError=!1,this._required=!1,this._disabled=!1,this._fieldsetDisabled=!1,this.hasInteracted=!1,this.hadShoelaceDefaultValue=!1,this.onInvalid=event=>{const target=event.target;if(target!==this&&!(target?.nodeType===1&&this.ownsRadio(target)))return;this.emit("lr-invalid",null,{cancelable:!0}).defaultPrevented&&event.preventDefault()},this.onKeyDown=event=>{if(![...this.orientation==="horizontal"?["ArrowRight","ArrowLeft"]:["ArrowDown","ArrowUp"],"Home","End"].includes(event.key)||this.effectiveDisabled)return;const radios=this.radios().filter(radio=>this.isRadioAvailable(radio)),current=event.target;if(!this.isRadioAvailable(current))return;const index=radios.indexOf(current);if(index<0||radios.length===0)return;event.preventDefault();const rtl=this.effectiveDirection==="rtl",forward=this.orientation==="vertical"?event.key==="ArrowDown":rtl?event.key==="ArrowLeft":event.key==="ArrowRight",backward=this.orientation==="vertical"?event.key==="ArrowUp":rtl?event.key==="ArrowRight":event.key==="ArrowLeft",nextIndex=event.key==="Home"?0:event.key==="End"?radios.length-1:forward?(index+1)%radios.length:backward?(index-1+radios.length)%radios.length:index,next=radios[nextIndex];next.focus(),next.activateFromGroup()},this.onSlotChange=event=>{const slot=event.target,elements=slot.assignedElements({flatten:!0});slot.name==="label"&&(this.hasLabelSlot=elements.length>0),slot.name==="hint"&&(this.hasHintSlot=elements.length>0),slot.name==="help-text"&&(this.hasHelpTextSlot=elements.length>0),slot.name==="error"&&(this.hasErrorSlot=elements.length>0)},this.onRadioSlotChange=()=>{this.syncRadios();const ownerDocument=this.ownerDocument,generation=this.membershipObserverGeneration,ownerWindow=ownerDocument?.defaultView;ownerWindow&&ownerWindow.queueMicrotask(()=>{this.membershipObserverGeneration===generation&&this.isConnected&&this.ownerDocument===ownerDocument&&this.syncRadios()})},this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),this.addEventListener("invalid",this.onInvalid,!0),this.syncFormState(),this.updateValidity()}connectedCallback(){super.connectedCallback(),this.syncSupportSlots(),this.syncRadios(),this.armMembershipObserver(),this.armRunResizeObserver(),this.scheduleRunProjection()}armRunResizeObserver(){this.runResizeObserver?.disconnect();const ResizeObserverCtor=this.ownerDocument?.defaultView?.ResizeObserver;if(!(!ResizeObserverCtor||!this.isConnected)){this.runResizeObserver=new ResizeObserverCtor(()=>this.scheduleRunProjection()),this.runResizeObserver.observe(this);for(const radio of this.radios())this.runResizeObserver.observe(radio)}}scheduleRunProjection(){const ownerWindow=this.ownerDocument?.defaultView;!ownerWindow||!this.isConnected||this.runProjectionFrame!==void 0||(this.runProjectionFrame=ownerWindow.requestAnimationFrame(()=>{this.runProjectionFrame=void 0,this.isConnected&&this.projectButtonRuns()}))}isButtonRadio(radio){return radio.localName===tag("radio-button")||radio.appearance==="button"}areActuallyAdjacent(first,second){const firstRect=first.getBoundingClientRect(),secondRect=second.getBoundingClientRect();if(firstRect.width<=0||firstRect.height<=0||secondRect.width<=0||secondRect.height<=0||!(Math.abs(firstRect.top-secondRect.top)<=1&&Math.abs(firstRect.bottom-secondRect.bottom)<=1))return!1;const gap=getComputedStyle(this).direction==="rtl"?firstRect.left-secondRect.right:secondRect.left-firstRect.right;return gap>=-2&&gap<=1}projectButtonRuns(){const radios=this.radios(),joinsPrevious=radios.map(()=>!1);if(this.orientation==="horizontal")for(let index=1;index<radios.length;index+=1){const previous=radios[index-1],current=radios[index];joinsPrevious[index]=this.isButtonRadio(previous)&&this.isButtonRadio(current)&&this.areActuallyAdjacent(previous,current)}for(let index=0;index<radios.length;index+=1){const joinsBefore=joinsPrevious[index]??!1,joinsAfter=joinsPrevious[index+1]??!1,position=joinsBefore?joinsAfter?"middle":"end":joinsAfter?"start":"standalone";radios[index].setButtonRunPosition(position)}}armMembershipObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected||this.membershipObserver&&this.membershipObserverDocument===ownerDocument)return;this.resetMembershipObserver();const ownerWindow=ownerDocument?.defaultView,MutationObserverCtor=ownerWindow?.MutationObserver;if(!ownerWindow||!MutationObserverCtor)return;const generation=this.membershipObserverGeneration,observer=new MutationObserverCtor(()=>{this.membershipObserver!==observer||this.membershipObserverDocument!==ownerDocument||this.membershipObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||ownerWindow.queueMicrotask(()=>{this.membershipObserver!==observer||this.membershipObserverDocument!==ownerDocument||this.membershipObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.syncRadios()})});this.membershipObserver=observer,this.membershipObserverDocument=ownerDocument,observer.observe(this,{attributes:!0,childList:!0,subtree:!0,attributeFilter:["slot","checked","disabled","value","size","appearance","hidden","inert","aria-hidden","aria-disabled","class","style"]})}disconnectedCallback(){this.resetMembershipObserver(),this.runResizeObserver?.disconnect(),this.runResizeObserver=void 0;const ownerWindow=this.ownerDocument?.defaultView;ownerWindow&&this.runProjectionFrame!==void 0&&ownerWindow.cancelAnimationFrame(this.runProjectionFrame),this.runProjectionFrame=void 0,this.releaseRadios(this.managedRadios),this.managedRadios.clear(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resetMembershipObserver()}resetMembershipObserver(){this.membershipObserverGeneration+=1,this.membershipObserver?.disconnect(),this.membershipObserver=void 0,this.membershipObserverDocument=void 0}willUpdate(changed){super.willUpdate(changed),changed.has("shoelaceDefaultValue")&&(this.hasAttribute("default-value")||this.hadShoelaceDefaultValue)&&(this.defaultValue=this.shoelaceDefaultValue,this.hadShoelaceDefaultValue=this.hasAttribute("default-value"))}updated(changed){super.updated(changed),this.syncRadios()}syncSupportSlots(){this.hasLabelSlot=Array.from(this.children??[]).some(element=>element.getAttribute("slot")==="label"),this.hasHintSlot=Array.from(this.children??[]).some(element=>element.getAttribute("slot")==="hint"),this.hasHelpTextSlot=Array.from(this.children??[]).some(element=>element.getAttribute("slot")==="help-text"),this.hasErrorSlot=Array.from(this.children??[]).some(element=>element.getAttribute("slot")==="error")}radioGroupOwner(element){const group=element.closest(tag("radio-group"));if(!group)return null;let topLevelChild=element;for(;topLevelChild.parentElement&&topLevelChild.parentElement!==group;)topLevelChild=topLevelChild.parentElement;if(topLevelChild.parentElement!==group)return null;const slot=topLevelChild.getAttribute("slot");return slot==="label"||slot==="hint"||slot==="help-text"||slot==="error"?null:group}ownsRadio(element){return RADIO_TAGS().includes(element.localName)&&this.radioGroupOwner(element)===this}radios(){const querySelectorAll=this.querySelectorAll;return typeof querySelectorAll!="function"?[]:[...querySelectorAll.call(this,RADIO_TAGS().join(","))].filter(radio=>this.ownsRadio(radio)&&typeof radio.setGroupOwner=="function")}isRadioAvailable(radio){if(radio.effectiveDisabled||radio.matches(":disabled"))return!1;for(let current=radio;current;current=composedParentElement(current)){if(isAccessibilitySubtreeExcluded(current)||isAriaTrue(current.getAttribute("aria-disabled")))return!1;if(current===this)break}return!0}selectValue(next){const desired=next??"",radios=this.radios();if(radios.length===0){const old=this._value;this._value=desired,this.pendingSelection=desired,this.syncFormState(),this.updateValidity(),this.requestUpdate("value",old);return}const match=radios.find(radio=>radio.value===desired);this.syncingRadios=!0;try{for(const radio of radios)radio.checked=radio===match}finally{this.syncingRadios=!1}this.pendingSelection=void 0,this.syncRadios(match)}syncRadios(preferred){if(!this.syncingRadios){this.syncingRadios=!0;try{const radios=this.radios(),current=new Set(radios);this.releaseRadios([...this.managedRadios].filter(radio=>!current.has(radio)));for(const radio of radios)radio.setGroupOwner(this);this.managedRadios=current,this.armRunResizeObserver();for(const radio of radios)radio.setGroupDisabled(this.effectiveDisabled);const enabled=radios.filter(radio=>this.isRadioAvailable(radio));let checked=radios.filter(radio=>radio.checked),checkedRadio;if(this.pendingSelection!==void 0&&radios.length>0){checkedRadio=radios.find(radio=>radio.value===this.pendingSelection);for(const radio of radios)radio.checked=radio===checkedRadio;checked=checkedRadio?[checkedRadio]:[],this.pendingSelection=void 0}else checkedRadio=preferred?.checked&¤t.has(preferred)?preferred:checked[checked.length-1];for(const radio of checked)radio!==checkedRadio&&(radio.checked=!1);const tabbableRadio=checkedRadio&&this.isRadioAvailable(checkedRadio)?checkedRadio:enabled[0];for(const radio of radios)radio.setGroupSize(this.size),radio.setGroupRequired(this.required&&!this.effectiveDisabled),radio.setGroupTabbable(radio===tabbableRadio);const oldValue=this._value;this._value=checkedRadio?.value??"",this.syncFormState(),this.updateValidity(),oldValue!==this._value&&this.requestUpdate("value",oldValue),this.scheduleRunProjection()}finally{this.syncingRadios=!1}}}releaseRadios(radios){for(const radio of radios)radio.releaseGroupOwner(this),radio.setButtonRunPosition("standalone")}reconcileRadio(radio){return this.ownsRadio(radio)?(this.syncRadios(radio.checked?radio:void 0),!0):!1}releaseRadio(radio){this.managedRadios.has(radio)&&(this.releaseRadios([radio]),this.managedRadios.delete(radio),this.syncRadios())}radioCheckedChanged(radio){this.syncingRadios||!this.ownsRadio(radio)||(this._valueDirty=!0,this.syncRadios(radio.checked?radio:void 0))}selectRadio(radio){if(this.effectiveDisabled||!this.ownsRadio(radio)||!this.isRadioAvailable(radio))return!1;this._valueDirty=!0,this.hasInteracted=!0,this.syncingRadios=!0;try{for(const candidate of this.radios())candidate.checked=candidate===radio}finally{this.syncingRadios=!1}return this.syncRadios(),dispatchNativeInputEvent(this),this.emit("lr-input",{value:radio.value,radio}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:radio.value,radio}),!0}focus(options){if(this.effectiveDisabled||this.matches(":disabled"))return;const enabled=this.radios().filter(radio=>this.isRadioAvailable(radio));(enabled.find(radio=>radio.checked)??enabled[0])?.focus(options)}blur(){this.radios().find(radio=>radio.matches(":focus-within"))?.blur()}click(){if(this.effectiveDisabled||this.matches(":disabled"))return;const enabled=this.radios().filter(radio=>this.isRadioAvailable(radio));(enabled.find(radio=>radio.checked)??enabled[0])?.click()}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part~="base"]')??null}syncFormState(){this.internals&&this.internals.setFormValue(this.name&&this.value?this.value:null,this.value)}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){if(!this.validityController)return;const missing=!this.barredFromValidation&&this.required&&!this.value;this.validityController.setValidity(missing?{valueMissing:!0}:{},missing?this.localize("radioRequired"):""),this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred:this.barredFromValidation})}checkValidity(){return this.internals.checkValidity()}reportValidity(){return this.hasInteracted=!0,this.updateValidity(),this.internals.reportValidity()}commitCustomValidity(message){const old=this.customError,normalized=message??"";this.validityController.setCustomValidity(normalized),this.reflectValidityStates(),this.reflectingCustomError=!0;try{normalized?this.setAttribute("custom-error",normalized):this.removeAttribute("custom-error")}finally{this.reflectingCustomError=!1}this.requestUpdate("customError",old)}setCustomValidity(message=""){this.commitCustomValidity(message)}resetValidity(){this.commitCustomValidity(""),this.updateValidity()}formResetCallback(){this._valueDirty=!1,this.pendingSelection=void 0,this.syncingRadios=!0;try{for(const radio of this.radios())radio.resetFromGroup()}finally{this.syncingRadios=!1}this.defaultValue&&(this.pendingSelection=this.defaultValue),this.hasInteracted=!1,this.syncRadios()}formStateRestoreCallback(state2,reason){this._valueDirty=!0,this.hasInteracted=!1,this.pendingSelection=typeof state2=="string"?state2:"",this.selectValue(this.pendingSelection)}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,this.syncRadios(),this.updateValidity(),this.requestUpdate()}render(){const hasLabel=this.hasLabelSlot||!!this.label||this.withLabel,hasAccessibleLabel=this.hasAttribute("aria-label")||!!this.accessibleLabel,hasHint=this.hasHintSlot||this.hasHelpTextSlot||!!(this.hint||this.helpText)||this.withHint,hasError=this.hasErrorSlot||!!this.errorText,described=[hasHint?this.hintId:"",hasError?this.errorId:""].filter(Boolean).join(" ")||nothing;return html`
|
|
2
2
|
<div part="base" role="radiogroup"
|
|
3
3
|
aria-label=${hasAccessibleLabel?this.accessibleLabel:nothing}
|
|
4
4
|
aria-labelledby=${!hasAccessibleLabel&&hasLabel?this.labelId:nothing}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { 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
|
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{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{tag}from"../../../internal/prefix.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./radio.styles.js";import{appearanceStyles}from"./radio-button.styles.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{declaredDefaultConverter,omittedEmptyStringConverter}from"../../../internal/converters.js";import{hasRealContent}from"../../../internal/a11y.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_radioRequired}from"../../../internal/default-strings.generated.js";class LyraRadio extends LyraElement{static{this.defaultStrings={...super.defaultStrings,radioRequired:LYRA_DEFAULT_radioRequired}}static get validators(){return[currentValidityValidator("required","disabled","checked","value")]}static{this.styles=[LyraElement.styles,sizes,styles,appearanceStyles]}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},appearance:{reflect:!0,converter:declaredDefaultConverter("default")},disabled:{type:Boolean,reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},pill:{type:Boolean,reflect:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},size:{reflect:!0,converter:declaredDefaultConverter("m")},value:{reflect:!0,noAccessor:!0}}}get checked(){return this._checked}set checked(value){const old=this._checked,next=!!value;old!==next&&(this.settingDefaultChecked||(this._checkedDirty=!0),this._checked=next,this.syncFormState(),this.requestUpdate("checked",old),this.isConnected&&this.group()?.radioCheckedChanged?.(this))}get defaultChecked(){return this._defaultChecked}set defaultChecked(value){if(this.reflectingDefaultChecked)return;const old=this._defaultChecked;this._defaultChecked=!!value,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(value){const old=this._disabled;this._disabled=!!value,this.toggleAttribute("disabled",this._disabled),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(value){const old=this._required;this._required=!!value,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get name(){return this._name}set name(value){const old=this._name,next=value??"";if(old===next){!next&&this.hasAttribute("name")&&this.removeAttribute("name");return}this._name=next,next?this.getAttribute("name")!==next&&this.setAttribute("name",next):this.hasAttribute("name")&&this.removeAttribute("name"),this.requestUpdate("name",old)}get value(){return this._value}set value(value){const old=this._value,next=value??"on";old!==next&&(this._value=next,value==null?this.hasAttribute("value")&&this.removeAttribute("value"):this.getAttribute("value")!==next&&this.setAttribute("value",next),this.syncFormState(),this.requestUpdate("value",old))}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled||!!this.currentGroup()&&this._groupDisabled}get effectiveRequired(){return this.required||(this.currentGroup()?this._groupRequired:!1)}get effectiveName(){return this.currentGroup()?.name||this.name}get effectiveSize(){return this.currentGroup()?.size??this._groupSize??this.size}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}constructor(){super(),this.size="m",this.appearance="default",this.pill=!1,this.hasLabel=!1,this.hasStart=!1,this.hasEnd=!1,this.hasInteracted=!1,this._checked=!1,this._disabled=!1,this._required=!1,this._name="",this._value="on",this._fieldsetDisabled=!1,this._groupDisabled=!1,this._groupRequired=!1,this._groupSize=null,this._tabbable=!0,this._buttonRunPosition="standalone",this.groupOwner=null,this._defaultChecked=!1,this._checkedDirty=!1,this.settingDefaultChecked=!1,this.reflectingDefaultChecked=!1,this.onClick=()=>this.select(),this.onKeyDown=event=>{this.effectiveDisabled||(event.key===" "||event.key==="Spacebar")&&(event.preventDefault(),this.select())},this.onFocus=event=>{relayNativeEvent(this,event)},this.onBlur=event=>{this.effectiveDisabled||(this.hasInteracted=!0,this.reflectValidityStates()),relayNativeEvent(this,event)},this.onLabelSlotChange=event=>this.handleLabelSlotChange(event),this.onSlotChange=event=>this.handleLabelSlotChange(event),this.onAdornmentSlotChange=()=>{this.bindLabelObserverTargets(),this.recomputeButtonAdornments()},this.internals=this.safeAttachInternals(),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.currentGroup()?.customError??this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.syncFormState()}safeAttachInternals(){if(typeof globalThis.ElementInternals>"u")return this.inertInternals();try{return this.attachInternals()}catch{return this.inertInternals()}}inertInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:!1,setFormValue:()=>{},setValidity:()=>{},checkValidity:()=>!0,reportValidity:()=>!0,states:new Set}}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part~="base"]')??null}connectedCallback(){super.connectedCallback();const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;this.labelObserver=MutationObserverCtor?new MutationObserverCtor(()=>{this.bindLabelObserverTargets(),this.recomputeHasLabel(),this.recomputeButtonAdornments()}):void 0,this.addEventListener("slotchange",this.onLabelSlotChange),this.addEventListener("slotchange",this.onAdornmentSlotChange),this.bindLabelObserverTargets(),this.recomputeHasLabel(),this.recomputeButtonAdornments(),this.updateValidity(),this.group()}disconnectedCallback(){this.removeEventListener("slotchange",this.onLabelSlotChange),this.removeEventListener("slotchange",this.onAdornmentSlotChange),this.labelObserver?.disconnect(),this.labelObserver=void 0,super.disconnectedCallback()}formResetCallback(){this.currentGroup()||(this.hasInteracted=!1,this.restoreCheckedFromDefault(),this.reflectValidityStates())}resetFromGroup(){this.hasInteracted=!1,this.restoreCheckedFromDefault()}restoreCheckedFromDefault(){this.settingDefaultChecked=!0;try{this.checked=this._defaultChecked}finally{this.settingDefaultChecked=!1}this._checkedDirty=!1}formStateRestoreCallback(state2,reason){if(this.currentGroup())return;const old=this._checked;this._checked=state2==="checked",this._checkedDirty=!0,this.syncFormState(),this.requestUpdate("checked",old),this.isConnected&&this.group()?.radioCheckedChanged?.(this)}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,this.updateValidity(),this.requestUpdate()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){const owned=!!this.currentGroup(),violates=!this.barredFromValidation&&!owned&&this.effectiveRequired&&!this.checked;this.validityController.setValidity(violates?{valueMissing:!0}:{},this.localize("radioRequired")),this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.effectiveRequired,hasInteracted:this.hasInteracted,barred:this.barredFromValidation}),setCustomState(this.internals,"checked",this.checked),setCustomState(this.internals,"disabled",this.effectiveDisabled)}setGroupDisabled(value){this._groupDisabled!==value&&(this._groupDisabled=value,this.updateValidity(),this.requestUpdate())}setGroupRequired(value){this._groupRequired!==value&&(this._groupRequired=value,this.updateValidity(),this.requestUpdate())}setGroupSize(value){this._groupSize!==value&&(this._groupSize=value,this.toggleAttribute("data-lr-group-size",value!==null),this.requestUpdate())}setGroupTabbable(value){this._tabbable!==value&&(this._tabbable=value,this.requestUpdate())}setButtonRunPosition(value){this._buttonRunPosition!==value&&(this._buttonRunPosition=value,this.requestUpdate())}setGroupOwner(owner){if(this.groupOwner===owner)return;this.groupOwner?.releaseRadio?.(this);const standaloneCustomError=this.validityController.customValidityMessage;this.groupOwner=owner,standaloneCustomError&&owner.setCustomValidity&&(owner.setCustomValidity(standaloneCustomError),this.validityController.setCustomValidity("")),this.syncFormState()}releaseGroupOwner(owner){if(this.groupOwner!==owner)return;this.groupOwner=null,this.setGroupRequired(!1),this.setGroupDisabled(!1),this.setGroupSize(null),this.setGroupTabbable(!0),this.setButtonRunPosition("standalone");const reflectedCustomError=this.getAttribute("custom-error")??"";reflectedCustomError&&this.validityController.setCustomValidity(reflectedCustomError),this.syncFormState()}checkValidity(){return this.internals.checkValidity()}reportValidity(){return this.hasInteracted=!0,this.reflectValidityStates(),this.internals.reportValidity()}setCustomValidity(message){const group=this.currentGroup();if(group?.setCustomValidity){group.setCustomValidity(message??"");return}this.validityController.setCustomValidity(message??""),this.reflectValidityStates(),this.requestUpdate()}resetValidity(){this.setCustomValidity("")}click(){this.effectiveDisabled||this[VALIDITY_ANCHOR]()?.click()}focus(options){this.effectiveDisabled||this[VALIDITY_ANCHOR]()?.focus(options)}blur(){this[VALIDITY_ANCHOR]()?.blur()}syncFormState(){!!this.currentGroup()?this.internals.setFormValue(null):this.internals.setFormValue(this.checked?this.value:null,this.checked?"checked":"unchecked"),this.updateValidity()}currentGroup(){if(!this.isConnected)return null;const closest=this.closest;if(typeof closest!="function")return null;const group=closest.call(this,tag("radio-group"));return group?.isConnected&&group.ownsRadio?.(this)?group:null}group(){const group=this.currentGroup();return group?(this.setGroupOwner(group),group.reconcileRadio?.(this),group):(this.groupOwner?.releaseRadio?.(this),null)}activateFromGroup(){this.select()}select(){const group=this.group();if(!(this.effectiveDisabled||this.checked)){if(this.hasInteracted=!0,group)return group.selectRadio?.(this),void 0;this.checked=!0,dispatchNativeEvent(this,"input"),this.emit("lr-input",{checked:!0,value:this.value}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{checked:!0,value:this.value})}}get groupTabbable(){return this._tabbable}get buttonRunPosition(){return this._buttonRunPosition}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)})}adornmentForwardingSlots(){const names=["start","prefix","end","suffix"];return Array.from(this.querySelectorAll("slot")).filter(slot=>{let top=slot;for(;top.parentNode&&top.parentNode!==this;)top=top.parentNode;return top===slot&&top.parentNode===this&&names.includes(slot.getAttribute("slot")??"")})}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);for(const slot of this.adornmentForwardingSlots())if(slot.assignedNodes().length!==0)for(const assigned of slot.assignedNodes({flatten:!0}))this.observeLabelNode(assigned)}}recomputeHasLabel(){const slot=this.renderRoot.querySelector("slot:not([name])"),nodes=slot?slot.assignedNodes({flatten:!0}):Array.from(this.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.hasLabel=hasRealContent(nodes)}assignedAdornmentNodes(names){const slots=names.map(name=>this.renderRoot.querySelector(`slot[name="${name}"]`)).filter(slot=>!!slot);if(slots.length>0)return slots.flatMap(slot=>slot.assignedNodes({flatten:!0}));const children=this.children;return(children?Array.from(children):[]).filter(element=>names.includes(element.getAttribute("slot")??"")).flatMap(element=>{if(element.localName!=="slot")return[element];const forwardingSlot=element;return forwardingSlot.assignedNodes().length>0?forwardingSlot.assignedNodes({flatten:!0}):Array.from(forwardingSlot.childNodes)})}recomputeButtonAdornments(){this.hasStart=hasRealContent(this.assignedAdornmentNodes(["start","prefix"])),this.hasEnd=hasRealContent(this.assignedAdornmentNodes(["end","suffix"]))}handleLabelSlotChange(event){const target=event.target;target?.nodeType!==1||target.localName!=="slot"||target.getRootNode()!==this.renderRoot&&!this.labelForwardingSlots().includes(target)||(this.bindLabelObserverTargets(),this.recomputeHasLabel())}renderButtonContent(){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{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{tag}from"../../../internal/prefix.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./radio.styles.js";import{appearanceStyles}from"./radio-button.styles.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{declaredDefaultConverter,omittedEmptyStringConverter}from"../../../internal/converters.js";import{hasRealContent}from"../../../internal/a11y.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_radioRequired}from"../../../internal/default-strings.generated.js";class LyraRadio extends LyraElement{static{this.defaultStrings={...super.defaultStrings,radioRequired:LYRA_DEFAULT_radioRequired}}static get validators(){return[currentValidityValidator("required","disabled","checked","value")]}static{this.styles=[LyraElement.styles,sizes,styles,appearanceStyles]}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},appearance:{reflect:!0,converter:declaredDefaultConverter("default")},disabled:{type:Boolean,reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},pill:{type:Boolean,reflect:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},size:{reflect:!0,converter:declaredDefaultConverter("m")},value:{reflect:!0,noAccessor:!0}}}get checked(){return this._checked}set checked(value){const old=this._checked,next=!!value;old!==next&&(this.settingDefaultChecked||(this._checkedDirty=!0),this._checked=next,this.syncFormState(),this.requestUpdate("checked",old),this.isConnected&&this.group()?.radioCheckedChanged?.(this))}get defaultChecked(){return this._defaultChecked}set defaultChecked(value){if(this.reflectingDefaultChecked)return;const old=this._defaultChecked;this._defaultChecked=!!value,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(value){const old=this._disabled;this._disabled=!!value,this.toggleAttribute("disabled",this._disabled),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(value){const old=this._required;this._required=!!value,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get name(){return this._name}set name(value){const old=this._name,next=value??"";if(old===next){!next&&this.hasAttribute("name")&&this.removeAttribute("name");return}this._name=next,next?this.getAttribute("name")!==next&&this.setAttribute("name",next):this.hasAttribute("name")&&this.removeAttribute("name"),this.requestUpdate("name",old)}get value(){return this._value}set value(value){const old=this._value,next=value??"on";old!==next&&(this._value=next,value==null?this.hasAttribute("value")&&this.removeAttribute("value"):this.getAttribute("value")!==next&&this.setAttribute("value",next),this.syncFormState(),this.requestUpdate("value",old))}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled||!!this.currentGroup()&&this._groupDisabled}get effectiveRequired(){return this.required||(this.currentGroup()?this._groupRequired:!1)}get effectiveName(){return this.currentGroup()?.name||this.name}get effectiveSize(){return this.currentGroup()?.size??this._groupSize??this.size}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}constructor(){super(),this.size="m",this.appearance="default",this.pill=!1,this.hasLabel=!1,this.hasStart=!1,this.hasEnd=!1,this.hasInteracted=!1,this._checked=!1,this._disabled=!1,this._required=!1,this._name="",this._value="on",this._fieldsetDisabled=!1,this._groupDisabled=!1,this._groupRequired=!1,this._groupSize=null,this._tabbable=!0,this._buttonRunPosition="standalone",this.groupOwner=null,this._defaultChecked=!1,this._checkedDirty=!1,this.settingDefaultChecked=!1,this.reflectingDefaultChecked=!1,this.onClick=()=>this.select(),this.onKeyDown=event=>{this.effectiveDisabled||(event.key===" "||event.key==="Spacebar")&&(event.preventDefault(),this.select())},this.onFocus=event=>{relayNativeEvent(this,event)},this.onBlur=event=>{this.effectiveDisabled||(this.hasInteracted=!0,this.reflectValidityStates()),relayNativeEvent(this,event)},this.onLabelSlotChange=event=>this.handleLabelSlotChange(event),this.onSlotChange=event=>this.handleLabelSlotChange(event),this.onAdornmentSlotChange=()=>{this.bindLabelObserverTargets(),this.recomputeButtonAdornments()},this.internals=this.safeAttachInternals(),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.currentGroup()?.customError??this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.syncFormState()}safeAttachInternals(){if(typeof globalThis.ElementInternals>"u")return this.inertInternals();try{return this.attachInternals()}catch{return this.inertInternals()}}inertInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:!1,setFormValue:()=>{},setValidity:()=>{},checkValidity:()=>!0,reportValidity:()=>!0,states:new Set}}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part~="base"]')??null}connectedCallback(){super.connectedCallback();const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;this.labelObserver=MutationObserverCtor?new MutationObserverCtor(()=>{this.bindLabelObserverTargets(),this.recomputeHasLabel(),this.recomputeButtonAdornments()}):void 0,this.addEventListener("slotchange",this.onLabelSlotChange),this.addEventListener("slotchange",this.onAdornmentSlotChange),this.bindLabelObserverTargets(),this.recomputeHasLabel(),this.recomputeButtonAdornments(),this.updateValidity(),this.group()}disconnectedCallback(){this.removeEventListener("slotchange",this.onLabelSlotChange),this.removeEventListener("slotchange",this.onAdornmentSlotChange),this.labelObserver?.disconnect(),this.labelObserver=void 0,super.disconnectedCallback()}formResetCallback(){this.currentGroup()||(this.hasInteracted=!1,this.restoreCheckedFromDefault(),this.reflectValidityStates())}resetFromGroup(){this.hasInteracted=!1,this.restoreCheckedFromDefault()}restoreCheckedFromDefault(){this.settingDefaultChecked=!0;try{this.checked=this._defaultChecked}finally{this.settingDefaultChecked=!1}this._checkedDirty=!1}formStateRestoreCallback(state2,reason){if(this.currentGroup())return;const old=this._checked;this._checked=state2==="checked",this._checkedDirty=!0,this.syncFormState(),this.requestUpdate("checked",old),this.isConnected&&this.group()?.radioCheckedChanged?.(this)}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,this.updateValidity(),this.requestUpdate()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){const owned=!!this.currentGroup(),violates=!this.barredFromValidation&&!owned&&this.effectiveRequired&&!this.checked;this.validityController.setValidity(violates?{valueMissing:!0}:{},this.localize("radioRequired")),this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.effectiveRequired,hasInteracted:this.hasInteracted,barred:this.barredFromValidation}),setCustomState(this.internals,"checked",this.checked),setCustomState(this.internals,"disabled",this.effectiveDisabled)}setGroupDisabled(value){this._groupDisabled!==value&&(this._groupDisabled=value,this.updateValidity(),this.requestUpdate())}setGroupRequired(value){this._groupRequired!==value&&(this._groupRequired=value,this.updateValidity(),this.requestUpdate())}setGroupSize(value){this._groupSize!==value&&(this._groupSize=value,this.toggleAttribute("data-lr-group-size",value!==null),this.requestUpdate())}setGroupTabbable(value){this._tabbable!==value&&(this._tabbable=value,this.requestUpdate())}setButtonRunPosition(value){this._buttonRunPosition!==value&&(this._buttonRunPosition=value,this.requestUpdate())}setGroupOwner(owner){if(this.groupOwner===owner)return;this.groupOwner?.releaseRadio?.(this);const standaloneCustomError=this.validityController.customValidityMessage;this.groupOwner=owner,standaloneCustomError&&owner.setCustomValidity&&(owner.setCustomValidity(standaloneCustomError),this.validityController.setCustomValidity("")),this.syncFormState()}releaseGroupOwner(owner){if(this.groupOwner!==owner)return;this.groupOwner=null,this.setGroupRequired(!1),this.setGroupDisabled(!1),this.setGroupSize(null),this.setGroupTabbable(!0),this.setButtonRunPosition("standalone");const reflectedCustomError=this.getAttribute("custom-error")??"";reflectedCustomError&&this.validityController.setCustomValidity(reflectedCustomError),this.syncFormState()}checkValidity(){return this.internals.checkValidity()}reportValidity(){return this.hasInteracted=!0,this.reflectValidityStates(),this.internals.reportValidity()}setCustomValidity(message){const group=this.currentGroup();if(group?.setCustomValidity){group.setCustomValidity(message??"");return}this.validityController.setCustomValidity(message??""),this.reflectValidityStates(),this.requestUpdate()}resetValidity(){this.setCustomValidity("")}click(){this.effectiveDisabled||this[VALIDITY_ANCHOR]()?.click()}focus(options){this.effectiveDisabled||this[VALIDITY_ANCHOR]()?.focus(options)}blur(){this[VALIDITY_ANCHOR]()?.blur()}syncFormState(){!!this.currentGroup()?this.internals.setFormValue(null):this.internals.setFormValue(this.checked?this.value:null,this.checked?"checked":"unchecked"),this.updateValidity()}currentGroup(){if(!this.isConnected)return null;const closest=this.closest;if(typeof closest!="function")return null;const group=closest.call(this,tag("radio-group"));return group?.isConnected&&group.ownsRadio?.(this)?group:null}group(){const group=this.currentGroup();return group?(this.setGroupOwner(group),group.reconcileRadio?.(this),group):(this.groupOwner?.releaseRadio?.(this),null)}activateFromGroup(){this.select()}select(){const group=this.group();if(!(this.effectiveDisabled||this.checked)){if(this.hasInteracted=!0,group)return group.selectRadio?.(this),void 0;this.checked=!0,dispatchNativeEvent(this,"input"),this.emit("lr-input",{checked:!0,value:this.value}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{checked:!0,value:this.value})}}get groupTabbable(){return this._tabbable}get buttonRunPosition(){return this._buttonRunPosition}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)})}adornmentForwardingSlots(){const names=["start","prefix","end","suffix"];return Array.from(this.querySelectorAll("slot")).filter(slot=>{let top=slot;for(;top.parentNode&&top.parentNode!==this;)top=top.parentNode;return top===slot&&top.parentNode===this&&names.includes(slot.getAttribute("slot")??"")})}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);for(const slot of this.adornmentForwardingSlots())if(slot.assignedNodes().length!==0)for(const assigned of slot.assignedNodes({flatten:!0}))this.observeLabelNode(assigned)}}recomputeHasLabel(){const slot=this.renderRoot.querySelector("slot:not([name])"),nodes=slot?slot.assignedNodes({flatten:!0}):Array.from(this.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.hasLabel=hasRealContent(nodes)}assignedAdornmentNodes(names){const slots=names.map(name=>this.renderRoot.querySelector(`slot[name="${name}"]`)).filter(slot=>!!slot);if(slots.length>0)return slots.flatMap(slot=>slot.assignedNodes({flatten:!0}));const children=this.children;return(children?Array.from(children):[]).filter(element=>names.includes(element.getAttribute("slot")??"")).flatMap(element=>{if(element.localName!=="slot")return[element];const forwardingSlot=element;return forwardingSlot.assignedNodes().length>0?forwardingSlot.assignedNodes({flatten:!0}):Array.from(forwardingSlot.childNodes)})}recomputeButtonAdornments(){this.hasStart=hasRealContent(this.assignedAdornmentNodes(["start","prefix"])),this.hasEnd=hasRealContent(this.assignedAdornmentNodes(["end","suffix"]))}handleLabelSlotChange(event){const target=event.target;target?.nodeType!==1||target.localName!=="slot"||target.getRootNode()!==this.renderRoot&&!this.labelForwardingSlots().includes(target)||(this.bindLabelObserverTargets(),this.recomputeHasLabel())}renderButtonContent(){return html`
|
|
2
2
|
<span part="start prefix" ?hidden=${!this.hasStart}>
|
|
3
3
|
<slot name="start" @slotchange=${this.onAdornmentSlotChange}></slot>
|
|
4
4
|
<slot name="prefix" @slotchange=${this.onAdornmentSlotChange}></slot>
|
|
@@ -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 '../../layout/segmented/segmented.class.js';
|
|
5
4
|
import '../slider/slider.class.js';
|
|
6
5
|
import '../select/select.class.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{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import"../../../internal/form-control-labels.js";import{nextId}from"../../../internal/a11y.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{styles}from"./rubric-form.styles.js";import"../../layout/segmented/segmented.class.js";import"../slider/slider.class.js";import"../select/select.class.js";import"../combobox/option.class.js";import"../checkbox/checkbox.class.js";import"../checkbox-group/checkbox-group.class.js";import"../textarea/textarea.class.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_noData,LYRA_DEFAULT_rubricSkip,LYRA_DEFAULT_rubricSubmit,LYRA_DEFAULT_rubricSubmitAndNext,LYRA_DEFAULT_unsupportedFieldType}from"../../../internal/default-strings.generated.js";const EMPTY_KEYS=[],EMPTY_VALUE={};function cloneRubricValue(value){return Object.freeze(Object.fromEntries(Object.entries(value).map(([key,entry])=>[key,Array.isArray(entry)?Object.freeze([...entry]):entry])))}function normalizeRubricKeys(next){if(!Array.isArray(next))return[];const seen=new Set,normalized=[];for(const candidate of next){if(candidate===null||typeof candidate!="object"||Array.isArray(candidate))continue;const raw=candidate,key=typeof raw.key=="string"?raw.key:"";if(key.trim().length===0||seen.has(key))continue;seen.add(key);const common={key,...typeof raw.label=="string"?{label:raw.label}:{},...typeof raw.description=="string"?{description:raw.description}:{},...typeof raw.required=="boolean"?{required:raw.required}:{}};if(raw.type==="score")normalized.push({...common,type:"score",...typeof raw.min=="number"?{min:raw.min}:{},...typeof raw.max=="number"?{max:raw.max}:{},...typeof raw.step=="number"?{step:raw.step}:{}});else if(raw.type==="category"){const options=Array.isArray(raw.options)?raw.options.flatMap(option=>{if(option===null||typeof option!="object"||Array.isArray(option))return[];const entry=option;return typeof entry.value!="string"?[]:[{value:entry.value,...typeof entry.label=="string"?{label:entry.label}:{},...typeof entry.description=="string"?{description:entry.description}:{}}]}):[];normalized.push({...common,type:"category",options,...typeof raw.multiple=="boolean"?{multiple:raw.multiple}:{}})}else raw.type==="comment"?normalized.push({...common,type:"comment",...typeof raw.placeholder=="string"?{placeholder:raw.placeholder}:{}}):normalized.push({...common,type:String(raw.type??"")})}return normalized}function scoreDomain(key){const min=Number.isFinite(key.min)?key.min:0,rawMax=Number.isFinite(key.max)?key.max:5,max=Math.max(min,rawMax),step=Number.isFinite(key.step)&&key.step>0?key.step:1;return{min,max,step}}function canonicalScore(value,key){if(typeof value!="number"||!Number.isFinite(value))return;const{min,max,step}=scoreDomain(key),clamped=Math.min(max,Math.max(min,value)),snapped=Math.min(max,Math.max(min,min+Math.round((clamped-min)/step)*step));return Number(snapped.toPrecision(15))}function normalizeRubricValue(value,keys){if(value===null||typeof value!="object"||Array.isArray(value))return{};const source=value,normalized={};for(const key of keys){let entry;try{if(!Object.prototype.hasOwnProperty.call(source,key.key))continue;entry=source[key.key]}catch{continue}if(key.type==="score"){const score=canonicalScore(entry,key);score!==void 0&&(normalized[key.key]=score)}else if(key.type==="category"){const allowed=(key.options??[]).map(option=>option.value);if(key.multiple){if(!Array.isArray(entry))continue;const remaining=new Map;for(const option of allowed)remaining.set(option,(remaining.get(option)??0)+1);const selected=[];for(const candidate of entry){if(typeof candidate!="string")continue;const count=remaining.get(candidate)??0;count<=0||(selected.push(candidate),remaining.set(candidate,count-1))}normalized[key.key]=selected}else typeof entry=="string"&&entry!==""&&allowed.includes(entry)&&(normalized[key.key]=entry)}else key.type==="comment"&&typeof entry=="string"&&(normalized[key.key]=entry)}return normalized}class LyraRubricForm extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,noData:LYRA_DEFAULT_noData,rubricSkip:LYRA_DEFAULT_rubricSkip,rubricSubmit:LYRA_DEFAULT_rubricSubmit,rubricSubmitAndNext:LYRA_DEFAULT_rubricSubmitAndNext,unsupportedFieldType:LYRA_DEFAULT_unsupportedFieldType}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},keys:{attribute:!1,noAccessor:!0},value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:!1,noAccessor:!0},itemId:{attribute:"item-id",reflect:!0,noAccessor:!0},hasNext:{type:Boolean,attribute:"has-next",noAccessor:!0},skippable:{type:Boolean,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0}}}constructor(){super(),this.label="",this.hint="",this.errorText="",this.withLabel=!1,this.withHint=!1,this._errors={},this.touchedFields=new Set,this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.baseId=nextId("rubric-form"),this.aggregateLabelId=`${this.baseId}-label`,this.aggregateHintId=`${this.baseId}-hint`,this.aggregateErrorId=`${this.baseId}-error`,this._fieldsetDisabled=!1,this._name="",this._keys=EMPTY_KEYS,this._value=EMPTY_VALUE,this._defaultValue=EMPTY_VALUE,this._valueDirty=!1,this._itemId="",this._hasNext=!1,this._skippable=!1,this._disabled=!1,this.pendingFocusFirst=!1,this.onFormKeyDown=e=>{e.key==="Enter"&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),this.submit())},this.stopChildEvent=event=>{event.stopPropagation()},this.onAggregateSlotChange=event=>{const slot=event.target,populated=slot.assignedNodes({flatten:!0}).some(node=>node.nodeType===Node.ELEMENT_NODE||!!node.textContent?.trim());slot.name==="label"?this.hasLabelSlot=populated:slot.name==="hint"?this.hasHintSlot=populated:slot.name==="error"&&(this.hasErrorSlot=populated)},this.internals=this.safeAttachInternals(),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.addEventListener("keydown",this.onFormKeyDown),this.syncFormState()}safeAttachInternals(){if(typeof globalThis.ElementInternals>"u")return this.inertInternals();try{return this.attachInternals()}catch{return this.inertInternals()}}inertInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:!1,setFormValue:()=>{},setValidity:()=>{},checkValidity:()=>!0,reportValidity:()=>!0,states:new Set}}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}get keys(){return this._keys}set keys(next){const old=this._keys;this._keys=normalizeRubricKeys(next??EMPTY_KEYS);const oldDefault=this._defaultValue,oldValue=this._value;this._defaultValue=normalizeRubricValue(this._defaultValue,this._keys),this._value=this._valueDirty?normalizeRubricValue(this._value,this._keys):cloneRubricValue(this._defaultValue),this.syncFormState(),this.requestUpdate("keys",old),this.requestUpdate("defaultValue",oldDefault),this.requestUpdate("value",oldValue)}get value(){return cloneRubricValue(this._value)}set value(next){this.setLiveValue(next,!0)}get defaultValue(){return cloneRubricValue(this._defaultValue)}set defaultValue(next){const old=this._defaultValue;this._defaultValue=normalizeRubricValue(next??EMPTY_VALUE,this._keys),this._valueDirty||this.setLiveValue(this._defaultValue,!1),this.requestUpdate("defaultValue",old)}setLiveValue(next,dirty){const old=this._value;this._value=normalizeRubricValue(next??EMPTY_VALUE,this._keys),this._valueDirty=dirty,this.syncFormState(),this.requestUpdate("value",old)}get itemId(){return this._itemId}set itemId(next){const old=this._itemId;this._itemId=next??"",old!==this._itemId&&(this.touchedFields=new Set,this.syncCustomStates(),this.hasUpdated&&(this.pendingFocusFirst=!0)),this._itemId?this.setAttribute("item-id",this._itemId):this.removeAttribute("item-id"),this.requestUpdate("itemId",old)}get hasNext(){return this._hasNext}set hasNext(next){const old=this._hasNext;this._hasNext=!!next,this.toggleAttribute("has-next",this._hasNext),this.requestUpdate("hasNext",old)}get skippable(){return this._skippable}set skippable(next){const old=this._skippable;this._skippable=!!next,this.requestUpdate("skippable",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this.validityController&&this.syncFormState(),this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get errors(){return this.publicValidityErrors()}publicValidityErrors(){const errors={...this._errors};return this.willValidate&&this.validityController.customValidityMessage&&(errors.base=this.validationMessage),Object.freeze(errors)}publishValiditySnapshot(){if(!this.isConnected)return;const valid=!this.willValidate||this.validity.valid,errors=valid?Object.freeze({}):this.publicValidityErrors(),key=JSON.stringify({valid,errors});key!==this.lastValidityKey&&(this.lastValidityKey=key,this.emit("lr-validity-change",Object.freeze({valid,errors})))}fieldElement(key){const root=this.renderRoot,ownerCss=this.ownerDocument.defaultView?.CSS;if(typeof ownerCss?.escape=="function")try{const candidate=root.querySelector(`[part="field"][data-key="${ownerCss.escape(key)}"]`);if(candidate?.getAttribute("data-key")===key)return candidate}catch{}return Array.from(root.querySelectorAll('[part="field"][data-key]')).find(candidate=>candidate.getAttribute("data-key")===key)??null}[VALIDITY_ANCHOR](){const firstInvalidKey=Object.keys(this._errors)[0];return!firstInvalidKey||!this.renderRoot?void 0:this.fieldElement(firstInvalidKey)?.querySelector(".control")??void 0}isSegmentedScore(k){if(k.step!==void 0&&(!Number.isFinite(k.step)||k.step<=0)||Number.isFinite(k.min)&&Number.isFinite(k.max)&&k.max<k.min)return!1;const{min,max,step}=scoreDomain(k);if(!Number.isInteger(min)||!Number.isInteger(max)||!Number.isInteger(step))return!1;const count=(max-min)/step;return Number.isInteger(count)&&count>=0&&count<=10}scoreValues(k){if(!this.isSegmentedScore(k))return[];const{min,max,step}=scoreDomain(k),count=Math.round((max-min)/step);return Array.from({length:count+1},(_,index)=>index===count?max:min+index*step)}computeValidation(){const errors={},flags={};for(const k of this._keys){if(k.type!=="score"&&k.type!=="category"&&k.type!=="comment"){const unsupported=k;errors[unsupported.key]=this.localize("unsupportedFieldType",void 0,{type:unsupported.type}),flags.customError=!0;continue}if(!k.required)continue;const v=this._value[k.key];(k.type==="category"&&k.multiple?Array.isArray(v)&&v.length>0:v!==void 0&&v!=="")||(errors[k.key]=this.localize("fieldRequired"),flags.valueMissing=!0)}return{errors,flags}}syncFormState(){const{errors,flags}=this.computeValidation();this._errors=errors;let formValue=null;try{formValue=JSON.stringify(this._value)}catch{formValue=null}if(this.internals.setFormValue(formValue,formValue),this.barredFromValidation||Object.keys(flags).length===0)this.validityController.setValidity({});else{const message=Object.values(errors)[0]??"";this.validityController.setValidity(flags,message)}this.syncCustomStates(),this.publishValiditySnapshot()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}syncCustomStates(){syncValidityStates(this.internals,{required:this._keys.some(key=>!!key.required),hasInteracted:this.touchedFields.size>0,barred:this.barredFromValidation})}checkValidity(){return this.syncFormState(),this.internals.checkValidity()}reportValidity(){return this.syncFormState(),Object.keys(this._errors).length>0&&(this.touchedFields=new Set([...this.touchedFields,...Object.keys(this._errors)]),this.syncCustomStates()),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncCustomStates(),this.publishValiditySnapshot(),this.requestUpdate()}formResetCallback(){this.setLiveValue(this._defaultValue,!1),this.touchedFields=new Set,this.syncCustomStates()}formStateRestoreCallback(state2,_mode){let restored={};if(typeof state2=="string")try{const parsed=JSON.parse(state2);parsed!==null&&typeof parsed=="object"&&!Array.isArray(parsed)&&(restored=parsed)}catch{}this.setLiveValue(restored,!0)}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,this.syncFormState(),this.requestUpdate()}setFieldValue(key,val){this.effectiveDisabled||(this.value={...this._value,[key]:val},this.emit("lr-input",Object.freeze({value:cloneRubricValue(this._value)})))}markTouched(key){this.effectiveDisabled||this.touchedFields.has(key)||(this.touchedFields=new Set(this.touchedFields).add(key),this.syncCustomStates())}submit(){this.effectiveDisabled||this.reportValidity()&&this.emit("lr-submit",Object.freeze({value:cloneRubricValue(this._value),itemId:this.itemId}))}skip(){this.effectiveDisabled||this.emit("lr-skip",{itemId:this.itemId})}focusFirstControl(){const firstKey=this._keys[0];if(!firstKey)return;const control=this.fieldElement(firstKey.key)?.querySelector(".control");control&&(firstKey.type==="score"&&this.isSegmentedScore(firstKey)?control.shadowRoot?.querySelector('[part="segment"][tabindex="0"]')?.focus():firstKey.type==="score"?control.shadowRoot?.querySelector('[part="thumb"]')?.focus():firstKey.type==="category"&&firstKey.multiple?control.querySelector("lr-checkbox")?.focus():control.focus())}click(){this.effectiveDisabled||this.focusFirstControl()}updated(changed){super.updated(changed),this.publishValiditySnapshot(),this.pendingFocusFirst&&(this.pendingFocusFirst=!1,this.focusFirstControl())}renderScoreControl(k,fieldId,current,hasError){const{min,max,step}=scoreDomain(k),disabled=this.effectiveDisabled,accessibleLabel=[k.label??k.key,k.description,hasError?this._errors[k.key]:void 0].filter(value=>!!value).join(". ");if(this.isSegmentedScore(k)){const numberFormat=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:20}),items=this.scoreValues(k).map(score=>({value:String(score),label:numberFormat.format(score),disabled})),value=typeof current=="number"?String(current):"";return html`<lr-segmented
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";installFormControlLabelSupport();import{nextId}from"../../../internal/a11y.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{styles}from"./rubric-form.styles.js";import"../../layout/segmented/segmented.class.js";import"../slider/slider.class.js";import"../select/select.class.js";import"../combobox/option.class.js";import"../checkbox/checkbox.class.js";import"../checkbox-group/checkbox-group.class.js";import"../textarea/textarea.class.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_noData,LYRA_DEFAULT_rubricSkip,LYRA_DEFAULT_rubricSubmit,LYRA_DEFAULT_rubricSubmitAndNext,LYRA_DEFAULT_unsupportedFieldType}from"../../../internal/default-strings.generated.js";const EMPTY_KEYS=[],EMPTY_VALUE={};function cloneRubricValue(value){return Object.freeze(Object.fromEntries(Object.entries(value).map(([key,entry])=>[key,Array.isArray(entry)?Object.freeze([...entry]):entry])))}function normalizeRubricKeys(next){if(!Array.isArray(next))return[];const seen=new Set,normalized=[];for(const candidate of next){if(candidate===null||typeof candidate!="object"||Array.isArray(candidate))continue;const raw=candidate,key=typeof raw.key=="string"?raw.key:"";if(key.trim().length===0||seen.has(key))continue;seen.add(key);const common={key,...typeof raw.label=="string"?{label:raw.label}:{},...typeof raw.description=="string"?{description:raw.description}:{},...typeof raw.required=="boolean"?{required:raw.required}:{}};if(raw.type==="score")normalized.push({...common,type:"score",...typeof raw.min=="number"?{min:raw.min}:{},...typeof raw.max=="number"?{max:raw.max}:{},...typeof raw.step=="number"?{step:raw.step}:{}});else if(raw.type==="category"){const options=Array.isArray(raw.options)?raw.options.flatMap(option=>{if(option===null||typeof option!="object"||Array.isArray(option))return[];const entry=option;return typeof entry.value!="string"?[]:[{value:entry.value,...typeof entry.label=="string"?{label:entry.label}:{},...typeof entry.description=="string"?{description:entry.description}:{}}]}):[];normalized.push({...common,type:"category",options,...typeof raw.multiple=="boolean"?{multiple:raw.multiple}:{}})}else raw.type==="comment"?normalized.push({...common,type:"comment",...typeof raw.placeholder=="string"?{placeholder:raw.placeholder}:{}}):normalized.push({...common,type:String(raw.type??"")})}return normalized}function scoreDomain(key){const min=Number.isFinite(key.min)?key.min:0,rawMax=Number.isFinite(key.max)?key.max:5,max=Math.max(min,rawMax),step=Number.isFinite(key.step)&&key.step>0?key.step:1;return{min,max,step}}function canonicalScore(value,key){if(typeof value!="number"||!Number.isFinite(value))return;const{min,max,step}=scoreDomain(key),clamped=Math.min(max,Math.max(min,value)),snapped=Math.min(max,Math.max(min,min+Math.round((clamped-min)/step)*step));return Number(snapped.toPrecision(15))}function normalizeRubricValue(value,keys){if(value===null||typeof value!="object"||Array.isArray(value))return{};const source=value,normalized={};for(const key of keys){let entry;try{if(!Object.prototype.hasOwnProperty.call(source,key.key))continue;entry=source[key.key]}catch{continue}if(key.type==="score"){const score=canonicalScore(entry,key);score!==void 0&&(normalized[key.key]=score)}else if(key.type==="category"){const allowed=(key.options??[]).map(option=>option.value);if(key.multiple){if(!Array.isArray(entry))continue;const remaining=new Map;for(const option of allowed)remaining.set(option,(remaining.get(option)??0)+1);const selected=[];for(const candidate of entry){if(typeof candidate!="string")continue;const count=remaining.get(candidate)??0;count<=0||(selected.push(candidate),remaining.set(candidate,count-1))}normalized[key.key]=selected}else typeof entry=="string"&&entry!==""&&allowed.includes(entry)&&(normalized[key.key]=entry)}else key.type==="comment"&&typeof entry=="string"&&(normalized[key.key]=entry)}return normalized}class LyraRubricForm extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,noData:LYRA_DEFAULT_noData,rubricSkip:LYRA_DEFAULT_rubricSkip,rubricSubmit:LYRA_DEFAULT_rubricSubmit,rubricSubmitAndNext:LYRA_DEFAULT_rubricSubmitAndNext,unsupportedFieldType:LYRA_DEFAULT_unsupportedFieldType}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},keys:{attribute:!1,noAccessor:!0},value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:!1,noAccessor:!0},itemId:{attribute:"item-id",reflect:!0,noAccessor:!0},hasNext:{type:Boolean,attribute:"has-next",noAccessor:!0},skippable:{type:Boolean,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0}}}constructor(){super(),this.label="",this.hint="",this.errorText="",this.withLabel=!1,this.withHint=!1,this._errors={},this.touchedFields=new Set,this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.baseId=nextId("rubric-form"),this.aggregateLabelId=`${this.baseId}-label`,this.aggregateHintId=`${this.baseId}-hint`,this.aggregateErrorId=`${this.baseId}-error`,this._fieldsetDisabled=!1,this._name="",this._keys=EMPTY_KEYS,this._value=EMPTY_VALUE,this._defaultValue=EMPTY_VALUE,this._valueDirty=!1,this._itemId="",this._hasNext=!1,this._skippable=!1,this._disabled=!1,this.pendingFocusFirst=!1,this.onFormKeyDown=e=>{e.key==="Enter"&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),this.submit())},this.stopChildEvent=event=>{event.stopPropagation()},this.onAggregateSlotChange=event=>{const slot=event.target,populated=slot.assignedNodes({flatten:!0}).some(node=>node.nodeType===Node.ELEMENT_NODE||!!node.textContent?.trim());slot.name==="label"?this.hasLabelSlot=populated:slot.name==="hint"?this.hasHintSlot=populated:slot.name==="error"&&(this.hasErrorSlot=populated)},this.internals=this.safeAttachInternals(),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.addEventListener("keydown",this.onFormKeyDown),this.syncFormState()}safeAttachInternals(){if(typeof globalThis.ElementInternals>"u")return this.inertInternals();try{return this.attachInternals()}catch{return this.inertInternals()}}inertInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:!1,setFormValue:()=>{},setValidity:()=>{},checkValidity:()=>!0,reportValidity:()=>!0,states:new Set}}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}get keys(){return this._keys}set keys(next){const old=this._keys;this._keys=normalizeRubricKeys(next??EMPTY_KEYS);const oldDefault=this._defaultValue,oldValue=this._value;this._defaultValue=normalizeRubricValue(this._defaultValue,this._keys),this._value=this._valueDirty?normalizeRubricValue(this._value,this._keys):cloneRubricValue(this._defaultValue),this.syncFormState(),this.requestUpdate("keys",old),this.requestUpdate("defaultValue",oldDefault),this.requestUpdate("value",oldValue)}get value(){return cloneRubricValue(this._value)}set value(next){this.setLiveValue(next,!0)}get defaultValue(){return cloneRubricValue(this._defaultValue)}set defaultValue(next){const old=this._defaultValue;this._defaultValue=normalizeRubricValue(next??EMPTY_VALUE,this._keys),this._valueDirty||this.setLiveValue(this._defaultValue,!1),this.requestUpdate("defaultValue",old)}setLiveValue(next,dirty){const old=this._value;this._value=normalizeRubricValue(next??EMPTY_VALUE,this._keys),this._valueDirty=dirty,this.syncFormState(),this.requestUpdate("value",old)}get itemId(){return this._itemId}set itemId(next){const old=this._itemId;this._itemId=next??"",old!==this._itemId&&(this.touchedFields=new Set,this.syncCustomStates(),this.hasUpdated&&(this.pendingFocusFirst=!0)),this._itemId?this.setAttribute("item-id",this._itemId):this.removeAttribute("item-id"),this.requestUpdate("itemId",old)}get hasNext(){return this._hasNext}set hasNext(next){const old=this._hasNext;this._hasNext=!!next,this.toggleAttribute("has-next",this._hasNext),this.requestUpdate("hasNext",old)}get skippable(){return this._skippable}set skippable(next){const old=this._skippable;this._skippable=!!next,this.requestUpdate("skippable",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this.validityController&&this.syncFormState(),this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get errors(){return this.publicValidityErrors()}publicValidityErrors(){const errors={...this._errors};return this.willValidate&&this.validityController.customValidityMessage&&(errors.base=this.validationMessage),Object.freeze(errors)}publishValiditySnapshot(){if(!this.isConnected)return;const valid=!this.willValidate||this.validity.valid,errors=valid?Object.freeze({}):this.publicValidityErrors(),key=JSON.stringify({valid,errors});key!==this.lastValidityKey&&(this.lastValidityKey=key,this.emit("lr-validity-change",Object.freeze({valid,errors})))}fieldElement(key){const root=this.renderRoot,ownerCss=this.ownerDocument.defaultView?.CSS;if(typeof ownerCss?.escape=="function")try{const candidate=root.querySelector(`[part="field"][data-key="${ownerCss.escape(key)}"]`);if(candidate?.getAttribute("data-key")===key)return candidate}catch{}return Array.from(root.querySelectorAll('[part="field"][data-key]')).find(candidate=>candidate.getAttribute("data-key")===key)??null}[VALIDITY_ANCHOR](){const firstInvalidKey=Object.keys(this._errors)[0];return!firstInvalidKey||!this.renderRoot?void 0:this.fieldElement(firstInvalidKey)?.querySelector(".control")??void 0}isSegmentedScore(k){if(k.step!==void 0&&(!Number.isFinite(k.step)||k.step<=0)||Number.isFinite(k.min)&&Number.isFinite(k.max)&&k.max<k.min)return!1;const{min,max,step}=scoreDomain(k);if(!Number.isInteger(min)||!Number.isInteger(max)||!Number.isInteger(step))return!1;const count=(max-min)/step;return Number.isInteger(count)&&count>=0&&count<=10}scoreValues(k){if(!this.isSegmentedScore(k))return[];const{min,max,step}=scoreDomain(k),count=Math.round((max-min)/step);return Array.from({length:count+1},(_,index)=>index===count?max:min+index*step)}computeValidation(){const errors={},flags={};for(const k of this._keys){if(k.type!=="score"&&k.type!=="category"&&k.type!=="comment"){const unsupported=k;errors[unsupported.key]=this.localize("unsupportedFieldType",void 0,{type:unsupported.type}),flags.customError=!0;continue}if(!k.required)continue;const v=this._value[k.key];(k.type==="category"&&k.multiple?Array.isArray(v)&&v.length>0:v!==void 0&&v!=="")||(errors[k.key]=this.localize("fieldRequired"),flags.valueMissing=!0)}return{errors,flags}}syncFormState(){const{errors,flags}=this.computeValidation();this._errors=errors;let formValue=null;try{formValue=JSON.stringify(this._value)}catch{formValue=null}if(this.internals.setFormValue(formValue,formValue),this.barredFromValidation||Object.keys(flags).length===0)this.validityController.setValidity({});else{const message=Object.values(errors)[0]??"";this.validityController.setValidity(flags,message)}this.syncCustomStates(),this.publishValiditySnapshot()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}syncCustomStates(){syncValidityStates(this.internals,{required:this._keys.some(key=>!!key.required),hasInteracted:this.touchedFields.size>0,barred:this.barredFromValidation})}checkValidity(){return this.syncFormState(),this.internals.checkValidity()}reportValidity(){return this.syncFormState(),Object.keys(this._errors).length>0&&(this.touchedFields=new Set([...this.touchedFields,...Object.keys(this._errors)]),this.syncCustomStates()),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncCustomStates(),this.publishValiditySnapshot(),this.requestUpdate()}formResetCallback(){this.setLiveValue(this._defaultValue,!1),this.touchedFields=new Set,this.syncCustomStates()}formStateRestoreCallback(state2,_mode){let restored={};if(typeof state2=="string")try{const parsed=JSON.parse(state2);parsed!==null&&typeof parsed=="object"&&!Array.isArray(parsed)&&(restored=parsed)}catch{}this.setLiveValue(restored,!0)}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,this.syncFormState(),this.requestUpdate()}setFieldValue(key,val){this.effectiveDisabled||(this.value={...this._value,[key]:val},this.emit("lr-input",Object.freeze({value:cloneRubricValue(this._value)})))}markTouched(key){this.effectiveDisabled||this.touchedFields.has(key)||(this.touchedFields=new Set(this.touchedFields).add(key),this.syncCustomStates())}submit(){this.effectiveDisabled||this.reportValidity()&&this.emit("lr-submit",Object.freeze({value:cloneRubricValue(this._value),itemId:this.itemId}))}skip(){this.effectiveDisabled||this.emit("lr-skip",{itemId:this.itemId})}focusFirstControl(){const firstKey=this._keys[0];if(!firstKey)return;const control=this.fieldElement(firstKey.key)?.querySelector(".control");control&&(firstKey.type==="score"&&this.isSegmentedScore(firstKey)?control.shadowRoot?.querySelector('[part="segment"][tabindex="0"]')?.focus():firstKey.type==="score"?control.shadowRoot?.querySelector('[part="thumb"]')?.focus():firstKey.type==="category"&&firstKey.multiple?control.querySelector("lr-checkbox")?.focus():control.focus())}click(){this.effectiveDisabled||this.focusFirstControl()}updated(changed){super.updated(changed),this.publishValiditySnapshot(),this.pendingFocusFirst&&(this.pendingFocusFirst=!1,this.focusFirstControl())}renderScoreControl(k,fieldId,current,hasError){const{min,max,step}=scoreDomain(k),disabled=this.effectiveDisabled,accessibleLabel=[k.label??k.key,k.description,hasError?this._errors[k.key]:void 0].filter(value=>!!value).join(". ");if(this.isSegmentedScore(k)){const numberFormat=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:20}),items=this.scoreValues(k).map(score=>({value:String(score),label:numberFormat.format(score),disabled})),value=typeof current=="number"?String(current):"";return html`<lr-segmented
|
|
2
2
|
id=${fieldId}
|
|
3
3
|
class="control"
|
|
4
4
|
part="scale"
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { type TemplateResult, type PropertyValues } from 'lit';
|
|
2
2
|
import type { Placement } from '@floating-ui/dom';
|
|
3
3
|
import { LyraElement, type LyraEventDetailSnapshot } from '../../../internal/lyra-element.js';
|
|
4
|
-
import '../../../internal/form-control-labels.js';
|
|
5
4
|
import type { LyraAppearance, LyraSize } from '../../../internal/variants.js';
|
|
6
5
|
import type { LyraOption } from '../combobox/option.class.js';
|
|
7
6
|
import '../combobox/option.class.js';
|