@taprootio/espalier 2.2.0 → 2.3.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/custom-elements.json +1373 -878
- package/dist/checkbox/esp-checkbox-group.js +4 -4
- package/dist/checkbox/esp-checkbox.js +3 -3
- package/dist/date-picker/esp-date-picker.js +17 -17
- package/dist/font-picker/esp-font-picker.js +3 -3
- package/dist/form-item/esp-form-item.d.ts +52 -0
- package/dist/form-item/esp-form-item.js +27 -7
- package/dist/input/esp-input.js +4 -4
- package/dist/pickers/esp-picker-base.js +1 -1
- package/dist/radio-button/esp-radio-button-group.js +3 -3
- package/dist/radio-button/esp-radio-button.js +4 -4
- package/dist/shared/form-field-description-controller.js +1 -0
- package/dist/slider/esp-slider.js +2 -2
- package/dist/switch/esp-switch.js +3 -3
- package/dist/textarea/esp-textarea.js +1 -1
- package/espalier.token-manifest.json +12 -0
- package/package.json +2 -1
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
var
|
|
1
|
+
var o=function(l,e,t,r){var a=arguments.length,i=a<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(l,e,t,r);else for(var c=l.length-1;c>=0;c--)(h=l[c])&&(i=(a<3?h(i):a>3?h(e,t,i):h(e,t))||i);return a>3&&i&&Object.defineProperty(e,t,i),i};import{css as p,html as m}from"lit";import{customElement as f,property as n}from"lit/decorators.js";import{EspalierElementBase as d}from"../shared/esp-element-base.js";import{createRef as u,ref as b}from"lit/directives/ref.js";import{EspalierCheckbox as g}from"./esp-checkbox.js";import{FormFieldController as C}from"../shared/form-field-controller.js";let s=class extends d{constructor(){super(...arguments),this.internals=this.attachInternals(),this.formCtrl=new C({host:this,internals:this.internals,getFormValue:()=>{const e=this.values;return e.length>0?e.join(","):null},getValidity:()=>this.required&&this.values.length===0?{flags:{valueMissing:!0},message:this.requiredMessage||"Please select at least one option."}:null,onReset:()=>{for(const e of this.getCheckboxes())e.checked=!1},onRestore:e=>{const t=e.split(",");for(const r of this.getCheckboxes())r.checked=t.includes(r.value)},onDisabled:e=>{this.disabled=e}}),this.itemsSlot=u(),this.formItemDescription=null,this.describedCheckboxes=new Set,this.name="",this.required=!1,this.requiredMessage="",this.disabled=!1,this.handleItemsSlotChange=()=>{this.applyDisabledState(),this.applyFormItemDescription()}}get values(){return this.getCheckboxes().filter(e=>e.checked).map(e=>e.value)}focus(e){this.focusResolvedElementAfterUpdate(()=>this.getCheckboxes().find(t=>!t.disabled),e)}setFormItemDescription(e){this.formItemDescription=e,this.applyFormItemDescription()}validate(){this.formCtrl.validate()}checkValidity(){return this.formCtrl.checkValidity()}getCheckboxes(){return this.itemsSlot.value?Array.from(this.itemsSlot.value.assignedElements()).filter(e=>e instanceof g):[]}applyDisabledState(){for(const e of this.getCheckboxes())e.disabled=this.disabled}applyFormItemDescription(){const e=new Set(this.getCheckboxes());for(const t of this.describedCheckboxes)e.has(t)||t.setFormItemDescription(null);for(const t of e)t.setFormItemDescription(this.formItemDescription);this.describedCheckboxes=e}handleChildChanged(e){e.stopPropagation(),this.formCtrl.syncValue(),this.emitValueChanged(this.values)}formResetCallback(){this.formCtrl.handleFormReset()}formStateRestoreCallback(e){this.formCtrl.handleFormStateRestore(e)}formDisabledCallback(e){this.formCtrl.handleFormDisabled(e)}firstUpdated(e){super.firstUpdated(e),this.applyDisabledState(),this.applyFormItemDescription()}updated(e){super.updated(e),e.has("disabled")&&this.applyDisabledState()}render(){return m`
|
|
2
2
|
<div class="checkbox-group" role="group" @value-changed=${this.handleChildChanged}>
|
|
3
|
-
<slot ${b(this.itemsSlot)}></slot>
|
|
3
|
+
<slot ${b(this.itemsSlot)} @slotchange=${this.handleItemsSlotChange}></slot>
|
|
4
4
|
</div>
|
|
5
|
-
`}};s.formAssociated=!0,s.styles=[...
|
|
5
|
+
`}};s.formAssociated=!0,s.styles=[...d.styles,p`
|
|
6
6
|
.checkbox-group {
|
|
7
7
|
display: grid;
|
|
8
8
|
gap: var(--esp-size-tiny);
|
|
9
9
|
}
|
|
10
|
-
`],
|
|
10
|
+
`],o([n({type:String,reflect:!0})],s.prototype,"name",void 0),o([n({type:Boolean,reflect:!0})],s.prototype,"required",void 0),o([n({attribute:"required-message"})],s.prototype,"requiredMessage",void 0),o([n({type:Boolean,reflect:!0})],s.prototype,"disabled",void 0),s=o([f("esp-checkbox-group")],s);export{s as EspalierCheckboxGroup};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var o=function(l,e,s,c){var n=arguments.length,i=n<3?e:c===null?c=Object.getOwnPropertyDescriptor(e,s):c,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(l,e,s,c);else for(var h=l.length-1;h>=0;h--)(a=l[h])&&(i=(n<3?a(i):n>3?a(e,s,i):a(e,s))||i);return n>3&&i&&Object.defineProperty(e,s,i),i};import{css as p,html as m}from"lit";import{customElement as f,property as r}from"lit/decorators.js";import{EspalierElementBase as d}from"../shared/esp-element-base.js";import{checkboxChecked as u}from"../shared/svgs/checkbox-checked.js";import{checkboxUnchecked as b}from"../shared/svgs/checkbox-unchecked.js";import{checkboxIndeterminate as k}from"../shared/svgs/checkbox-indeterminate.js";import{FormFieldController as v}from"../shared/form-field-controller.js";import{FormFieldDescriptionController as g}from"../shared/form-field-description-controller.js";import{disabledControl as y,focusRing as x}from"../shared/style-fragments.js";let t=class extends d{constructor(){super(...arguments),this.internals=this.attachInternals(),this.formCtrl=new v({host:this,internals:this.internals,getFormValue:()=>this.checked?this.value||"on":null,getValidity:()=>this.required&&!this.checked?{flags:{valueMissing:!0},message:this.requiredMessage||"Please check this box to continue."}:null,onReset:()=>{this.checked=!1,this.indeterminate=!1},onRestore:e=>{this.checked=e==="on"||e===this.value},onDisabled:e=>{this.disabled=e}}),this.formItemDescription=new g({host:this,getTarget:()=>this.shadowRoot?.querySelector(".checkbox-control")}),this.checked=!1,this.value="",this.name="",this.required=!1,this.requiredMessage="",this.disabled=!1,this.indeterminate=!1}focus(e){this.focusShadowElementAfterUpdate(".checkbox-control",e)}setFormItemDescription(e){this.formItemDescription.setDescription(e)}validate(){this.formCtrl.validate()}checkValidity(){return this.formCtrl.checkValidity()}toggle(){this.disabled||(this.indeterminate=!1,this.checked=!this.checked,this.formCtrl.syncValue(),this.emitValueChanged({checked:this.checked,value:this.value}))}handleKeyDown(e){e.key===" "&&(e.preventDefault(),this.toggle())}getSvg(){return this.indeterminate?k:this.checked?u:b}formResetCallback(){this.formCtrl.handleFormReset()}formStateRestoreCallback(e){this.formCtrl.handleFormStateRestore(e)}formDisabledCallback(e){this.formCtrl.handleFormDisabled(e)}render(){return m`
|
|
2
2
|
<div
|
|
3
3
|
class="checkbox-control"
|
|
4
4
|
role="checkbox"
|
|
@@ -11,7 +11,7 @@ var r=function(l,e,s,a){var c=arguments.length,i=c<3?e:a===null?a=Object.getOwnP
|
|
|
11
11
|
<span class="icon">${this.getSvg()}</span>
|
|
12
12
|
<span class="label"><slot></slot></span>
|
|
13
13
|
</div>
|
|
14
|
-
`}};t.formAssociated=!0,t.styles=[...d.styles,
|
|
14
|
+
`}};t.formAssociated=!0,t.styles=[...d.styles,x(".checkbox-control:focus-visible","--esp-checkbox-focus-shadow"),y(".checkbox-control"),p`
|
|
15
15
|
:host {
|
|
16
16
|
display: block;
|
|
17
17
|
}
|
|
@@ -44,4 +44,4 @@ var r=function(l,e,s,a){var c=arguments.length,i=c<3?e:a===null?a=Object.getOwnP
|
|
|
44
44
|
line-height: 1.3;
|
|
45
45
|
}
|
|
46
46
|
}
|
|
47
|
-
`],
|
|
47
|
+
`],o([r({type:Boolean,reflect:!0})],t.prototype,"checked",void 0),o([r({type:String})],t.prototype,"value",void 0),o([r({type:String,reflect:!0})],t.prototype,"name",void 0),o([r({type:Boolean,reflect:!0})],t.prototype,"required",void 0),o([r({attribute:"required-message"})],t.prototype,"requiredMessage",void 0),o([r({type:Boolean,reflect:!0})],t.prototype,"disabled",void 0),o([r({type:Boolean,reflect:!0})],t.prototype,"indeterminate",void 0),t=o([f("esp-checkbox")],t);export{t as EspalierCheckbox};
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
var n=function(m,e,t,i){var o=arguments.length,s=o<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(m,e,t,i);else for(var l=m.length-1;l>=0;l--)(a=m[l])&&(s=(o<3?a(s):o>3?a(e,t,s):a(e,t))||s);return o>3&&s&&Object.defineProperty(e,t,s),s},_;import{html as c,nothing as P}from"lit";import{customElement as $,property as p,state as d}from"lit/decorators.js";import{classMap as R}from"lit/directives/class-map.js";import{createRef as g,ref as v}from"lit/directives/ref.js";import{repeat as C}from"lit/directives/repeat.js";import{EspalierElementBase as w}from"../shared/esp-element-base.js";import{PopoverController as M}from"../shared/popover-controller.js";import{FormFieldController as A}from"../shared/form-field-controller.js";import{leftArrow as E}from"../shared/svgs/left-arrow.js";import{rightArrow as x}from"../shared/svgs/right-arrow.js";import{checkSVG as b}from"../shared/svgs/check.js";import{cancelSVG as D}from"../shared/svgs/cancel.js";import"../button/esp-button.js";import"../pickers/esp-pick-one.js";import"../pickers/esp-picker-item.js";import{GRID_COLS as S,GRID_ROWS as G,GRID_SIZE as O,HOURS_12 as F,MINUTES_60 as V,MONTH_NAMES as k,WEEKDAY_LABELS as q}from"./helpers/constants.js";import{displayValue as B,formatDate as T,parseValue as L}from"./helpers/parsing.js";import{generateCalendarGrid as H,getEffectiveRange as X,getSelectedDate as Y,isDateDisabled as I,parseDateBound as y}from"./helpers/calendar-grid.js";import{calendarIcon as W}from"../shared/svgs/calendar-icon.js";import{datePickerStyles as U}from"./helpers/styles.js";let r=_=class extends w{constructor(){super(...arguments),this.internals=this.attachInternals(),this.formCtrl=new A({host:this,internals:this.internals,getFormValue:()=>this._value||null,getValidity:()=>this._getValidityResult(),getValidationAnchor:()=>this.inputRef.value??this,onReset:()=>{this._rangeAnchor=null,this._rangePreview=null,this._value="",this.requestUpdate("value",""),this._syncFromValue()},onRestore:e=>{this.value=e},onDisabled:e=>{this.disabled=e}}),this.popoverCtrl=new M({host:this,closeStrategy:"source-identity",isOpen:()=>this.open,onShouldClose:()=>this._closePopover(),onPositionUpdate:()=>this._positionPopover(),shouldContinueTracking:()=>{const e=this.getBoundingClientRect(),t=window.innerHeight||document.documentElement.clientHeight;return!(e.bottom<0||e.top>t)},getInsideElements:()=>[this.popoverRef.value??null],onOutsideClick:()=>this._closePopover()}),this.inputRef=g(),this.popoverRef=g(),this.calBodyRef=g(),this.timePickerRef=g(),this.temporalSupported=!0,this.mode="date",this._value="",this.placeholder="Select...",this.min="",this.max="",this.disabled=!1,this.name="",this.required=!1,this.requiredMessage="",this.open=!1,this.parsed={kind:"none"},this._parsedMinDate=null,this._parsedMaxDate=null,this._hour=12,this._minute=0,this._period="AM",this._rangeAnchor=null,this._rangePreview=null,this._cachedGridKey="",this._cachedGrid=[],this._valueOnOpen="",this._touchStartX=0,this._touchStartY=0,this._touchGesture="none",this._swipeAnimating=!1,this._longPressTimer=0,this._edgeScrollTimer=0}get value(){return this._value}set value(e){const t=this._value;this._value=e,this.requestUpdate("value",t),this._syncFromValue(),this.formCtrl.syncValue()}get _rangePhase(){return this._rangeAnchor?this.parsed.kind==="range"?"complete":"start":"empty"}_getGrid(){const e=[this.viewDate?.toString(),this._value,this._rangeAnchor?.toString()??"",this._rangePreview?.toString()??""].join("|");if(e!==this._cachedGridKey){this._cachedGridKey=e;const t=Y(this.parsed),{start:i,end:o}=X(this.mode,this.parsed,this._rangeAnchor,this._rangePreview);this._cachedGrid=H(this.viewDate,t,i,o,this._minDate,this._maxDate)}return this._cachedGrid}_dateAtPoint(e,t){const i=this.shadowRoot?.elementsFromPoint(e,t);if(!i)return null;for(const o of i){const s=o.dataset?.date;if(s)try{return Temporal.PlainDate.from(s)}catch{return null}}return null}_edgeSide(e){const t=this.shadowRoot?.querySelector(".calendar");if(!t)return null;const i=t.getBoundingClientRect(),o=this.shadowRoot?.querySelector(".day-cell"),s=o?o.getBoundingClientRect().width:32;return e<=i.left+s?"left":e>=i.right-s?"right":null}_onCalendarTouchStart(e){if(e.touches.length!==1||this._swipeAnimating)return;const t=e.touches[0];if(this._touchStartX=t.clientX,this._touchStartY=t.clientY,this._touchGesture="pending",this._clearLongPressTimer(),this.mode==="range"&&this._rangePhase!=="empty"){const i=this.shadowRoot?.querySelector(".calendar");i&&(i.style.touchAction="none"),this._longPressTimer=window.setTimeout(()=>{if(this._longPressTimer=0,this._touchGesture!=="pending")return;this._touchGesture="drag";const o=this._dateAtPoint(this._touchStartX,this._touchStartY);o&&!this._isDateDisabled(o)&&(this._rangePhase==="complete"&&(this._rangeAnchor=o,this._value="",this.parsed={kind:"none"},this.formCtrl.syncValue()),this._rangePreview=o,this.requestUpdate())},_.LONG_PRESS_MS)}}_onCalendarTouchMove(e){if(e.touches.length!==1||this._swipeAnimating||this._touchGesture==="none")return;const t=e.touches[0],i=t.clientX-this._touchStartX,o=t.clientY-this._touchStartY;if(this._touchGesture==="drag"){e.cancelable&&e.preventDefault();const s=this._dateAtPoint(t.clientX,t.clientY);s&&!this._isDateDisabled(s)&&(this._rangePreview=s),this._handleEdgeScroll(t.clientX);return}if(this._touchGesture==="pending"){if(Math.abs(i)<10&&Math.abs(o)<10)return;if(this._clearLongPressTimer(),Math.abs(o)>Math.abs(i)){this._touchGesture="none",this._resetTouchAction();return}this._touchGesture="swipe"}if(this._touchGesture==="swipe"){e.cancelable&&e.preventDefault();const s=this.calBodyRef.value;s&&(s.style.transition="none",s.style.transform=`translateX(${i}px)`)}}_onCalendarTouchEnd(e){this._clearLongPressTimer(),this._clearEdgeScrollTimer(),this._resetTouchAction();const t=this._touchGesture;if(this._touchGesture="none",t==="drag"){if(e.changedTouches.length===1){const o=e.changedTouches[0];let s=this._dateAtPoint(o.clientX,o.clientY);if(s||(s=this._rangePreview),s&&!this._isDateDisabled(s)&&this._rangeAnchor){const a=this._rangeAnchor;let l,h;Temporal.PlainDate.compare(s,a)<0?(l=s,h=a):(l=a,h=s),this._rangePreview=null,this.value=`${l.toString()}/${h.toString()}`,this._dispatchValueChanged()}}return}if(t==="swipe"){this._finishSwipe(e);return}const i=this.calBodyRef.value;i&&(i.style.transition="",i.style.transform="")}_finishSwipe(e){const t=this.calBodyRef.value;if(!t||e.changedTouches.length!==1){t&&(t.style.transition="",t.style.transform="");return}const o=e.changedTouches[0].clientX-this._touchStartX,s=t.offsetWidth;if(Math.abs(o)>=30){const a=o<0?1:-1,l=a===1?-s:s;this._swipeAnimating=!0,t.style.transition="transform 150ms ease-in",t.style.transform=`translateX(${l}px)`,t.addEventListener("transitionend",()=>{this._navigateMonth(a),this.updateComplete.then(()=>{const h=this.calBodyRef.value;if(!h){this._swipeAnimating=!1;return}h.style.transition="none",h.style.transform=`translateX(${-l}px)`,h.getBoundingClientRect(),h.style.transition="transform 150ms ease-out",h.style.transform="",h.addEventListener("transitionend",()=>{h.style.transition="",this._swipeAnimating=!1},{once:!0})})},{once:!0})}else t.style.transition="transform 150ms ease-out",t.style.transform="",t.addEventListener("transitionend",()=>{t.style.transition=""},{once:!0})}_clearLongPressTimer(){this._longPressTimer&&(clearTimeout(this._longPressTimer),this._longPressTimer=0)}_handleEdgeScroll(e){const t=this._edgeSide(e);if(!t){this._clearEdgeScrollTimer();return}if(this._edgeScrollTimer)return;const i=t==="right"?1:-1;this._edgeScrollTimer=window.setTimeout(async()=>{this._edgeScrollTimer=0,this._touchGesture==="drag"&&(this._navigateMonth(i),await this.updateComplete)},_.EDGE_SCROLL_MS)}_clearEdgeScrollTimer(){this._edgeScrollTimer&&(clearTimeout(this._edgeScrollTimer),this._edgeScrollTimer=0)}_resetTouchAction(){const e=this.shadowRoot?.querySelector(".calendar");e&&e.style.removeProperty("touch-action")}connectedCallback(){if(super.connectedCallback(),typeof window.Temporal>"u"){this.temporalSupported=!1;return}this.viewDate||(this.viewDate=Temporal.Now.plainDateISO().toPlainYearMonth()),this.focusedDate||(this.focusedDate=Temporal.Now.plainDateISO()),this._parsedMinDate=y(this.min),this._parsedMaxDate=y(this.max),this._syncFromValue(),this.formCtrl.validate()}disconnectedCallback(){super.disconnectedCallback()}willUpdate(e){super.willUpdate(e),e.has("min")&&(this._parsedMinDate=y(this.min)),e.has("max")&&(this._parsedMaxDate=y(this.max))}updated(e){super.updated(e),e.has("disabled")&&(this.internals.ariaDisabled=this.disabled?"true":"false"),e.has("required")&&(this.internals.ariaRequired=this.required?"true":"false",this.formCtrl.validate()),(e.has("min")||e.has("max"))&&this.formCtrl.validate()}focus(e){this.focusResolvedElementAfterUpdate(()=>this.inputRef.value,e)}validate(){this.formCtrl.validate()}checkValidity(){return this.formCtrl.checkValidity()}formResetCallback(){this.formCtrl.handleFormReset()}formStateRestoreCallback(e){this.formCtrl.handleFormStateRestore(e)}formDisabledCallback(e){this.formCtrl.handleFormDisabled(e)}_syncFromValue(){if(this.temporalSupported)switch(this.parsed=L(this._value,this.mode),this.parsed.kind){case"date":this.viewDate=this.parsed.date.toPlainYearMonth(),this.focusedDate=this.parsed.date;break;case"datetime":{this.viewDate=this.parsed.datetime.toPlainDate().toPlainYearMonth(),this.focusedDate=this.parsed.datetime.toPlainDate();const e=this.parsed.datetime.toPlainTime(),t=e.hour;this._period=t>=12?"PM":"AM",this._hour=t===0?12:t>12?t-12:t,this._minute=e.minute;break}case"time":{const e=this.parsed.time,t=e.hour;this._period=t>=12?"PM":"AM",this._hour=t===0?12:t>12?t-12:t,this._minute=e.minute;break}case"range":this.viewDate=this.parsed.start.toPlainYearMonth(),this.focusedDate=this.parsed.start,this._rangeAnchor=this.parsed.start,this._rangePreview=null;break;case"none":break}}_getValidityResult(){if(!this.temporalSupported)return null;if(this.required&&!this._value)return{flags:{valueMissing:!0},message:this.requiredMessage||"Please select a date."};if(this._value&&this.parsed.kind==="none")return{flags:{typeMismatch:!0},message:"The value is not a valid date."};const e=this._getValidationDates();if(e.length>0){const t=this._minDate,i=this._maxDate;if(t){for(const o of e)if(Temporal.PlainDate.compare(o,t)<0)return{flags:{rangeUnderflow:!0},message:`Date must not be before ${T(t)}.`}}if(i){for(const o of e)if(Temporal.PlainDate.compare(o,i)>0)return{flags:{rangeOverflow:!0},message:`Date must not be after ${T(i)}.`}}}return null}_getValidationDates(){switch(this.parsed.kind){case"date":return[this.parsed.date];case"datetime":return[this.parsed.datetime.toPlainDate()];case"range":return[this.parsed.start,this.parsed.end];default:return[]}}get _minDate(){return this._parsedMinDate}get _maxDate(){return this._parsedMaxDate}_isDateDisabled(e){return I(e,this._minDate,this._maxDate)}_navigateMonth(e){this.viewDate=this.viewDate.add({months:e}),this.focusedDate=this.viewDate.toPlainDate({day:Math.min(this.focusedDate.day,this.viewDate.daysInMonth)})}_moveFocus(e){const t=this.focusedDate.add({days:e});if(this._isDateDisabled(t)){const o=e>0?1:-1;let s=t;for(let a=0;a<O&&this._isDateDisabled(s);a++)s=s.add({days:o});this.focusedDate=s}else this.focusedDate=t;const i=this.focusedDate.toPlainYearMonth();Temporal.PlainYearMonth.compare(i,this.viewDate)!==0&&(this.viewDate=i),this.mode==="range"&&this._rangePhase==="start"&&(this._rangePreview=this.focusedDate)}_selectDate(e){if(!this._isDateDisabled(e)){switch(this.mode){case"date":this.value=e.toString(),this._closePopover(),this.inputRef.value?.focus();break;case"datetime":{const t=this.parsed.kind==="datetime"?this.parsed.datetime.toPlainTime():new Temporal.PlainTime;this.value=e.toPlainDateTime(t).toString();break}case"range":this._selectRangeEndpoint(e);break}this._dispatchValueChanged()}}_selectRangeEndpoint(e){switch(this._rangePhase){case"empty":case"complete":this._rangeAnchor=e,this._rangePreview=null,this._value="",this.parsed={kind:"none"},this.formCtrl.syncValue(),this.requestUpdate();break;case"start":{const i=this._rangeAnchor;let o,s;Temporal.PlainDate.compare(e,i)<0?(o=e,s=i):(o=i,s=e),this._rangePreview=null,this.value=`${o.toString()}/${s.toString()}`;break}}}_dispatchValueChanged(){this.emitValueChanged(this._value)}get _showTimePicker(){return this.mode==="time"||this.mode==="datetime"}get _showCalendar(){return this.mode!=="time"}_commitTime(){let e=this._hour%12;this._period==="PM"&&(e+=12);const t=new Temporal.PlainTime(e,this._minute);if(this.mode==="time")this.value=t.toString();else if(this.mode==="datetime"){const i=this.parsed.kind==="datetime"?this.parsed.datetime.toPlainDate():this.parsed.kind==="date"?this.parsed.date:Temporal.Now.plainDateISO();this.value=i.toPlainDateTime(t).toString()}this._dispatchValueChanged()}async _openPopover(){if(this.disabled)return;this.popoverCtrl.publishCloseOthers(),this._valueOnOpen=this._value,this.open=!0,this._positionPopover(),this.popoverCtrl.startTracking(),this.popoverCtrl.startOutsideClick(),await this.updateComplete,this._shrinkTimePickerToFit(),this._scrollToContainPopover();const t=this.shadowRoot?.querySelector('[role="grid"]')?.querySelector('[tabindex="0"]');requestAnimationFrame(()=>t?.focus())}_closePopover(){this.open=!1;const e=this.popoverRef.value;if(e){e.classList.remove("visible");try{e.hidePopover()}catch{}}this.popoverCtrl.stopTracking(),this.popoverCtrl.stopOutsideClick(),this.mode==="range"&&this._rangePhase==="start"&&(this._rangeAnchor=null,this._rangePreview=null)}_togglePopover(){this.open?this._closePopover():this._openPopover()}_positionPopover(){const e=this.popoverRef.value;if(!e)return;const t=this.getBoundingClientRect(),i=window.innerHeight||document.documentElement.clientHeight,o=window.innerWidth||document.documentElement.clientWidth,s=t.top,a=i-t.bottom;e.matches(":popover-open")||e.showPopover(),e.style.removeProperty("top"),e.style.removeProperty("bottom"),e.style.removeProperty("font-size"),e.style.setProperty("width","min-content"),this._shrinkToFitViewport(e,o);let l=t.left;const h=e.offsetWidth;l+h>o&&(l=Math.max(0,o-h)),e.style.setProperty("left",`${l}px`);const f=e.offsetHeight;if(s>a){let u=i-t.top;f>s&&(u=i-f),e.style.setProperty("bottom",`${u}px`)}else{let u=t.bottom;f>a&&(u=i-f),e.style.setProperty("top",`${Math.max(0,u)}px`)}requestAnimationFrame(()=>e.classList.add("visible"))}_shrinkToFitViewport(e,t){if(e.offsetWidth<=t)return;const i=getComputedStyle(e);let o=parseFloat(i.fontSize);const s=8;for(;e.offsetWidth>t&&o>s;)o-=.5,e.style.setProperty("font-size",`${o}px`)}_shrinkTimePickerToFit(){const e=this.timePickerRef.value,t=this.popoverRef.value;if(!e||!t)return;e.style.removeProperty("font-size");const i=t.clientWidth;if(e.scrollWidth<=i)return;const o=getComputedStyle(e);let s=parseFloat(o.fontSize);const a=8;for(;e.scrollWidth>i&&s>a;)s-=.5,e.style.setProperty("font-size",`${s}px`)}_scrollToContainPopover(){const e=this.popoverRef.value;if(!e)return;const t=e.getBoundingClientRect(),i=this.getBoundingClientRect(),o=window.innerHeight||document.documentElement.clientHeight,s=Math.min(i.top,t.top),a=Math.max(i.bottom,t.bottom);if(a>o){const l=a-o;window.scrollBy({top:l+8,behavior:"smooth"}),requestAnimationFrame(()=>this._positionPopover())}else s<0&&(window.scrollBy({top:s-8,behavior:"smooth"}),requestAnimationFrame(()=>this._positionPopover()))}async _handleGridKeyDown(e){let t=!0;switch(e.key){case"ArrowLeft":this._moveFocus(-1);break;case"ArrowRight":this._moveFocus(1);break;case"ArrowUp":this._moveFocus(-7);break;case"ArrowDown":this._moveFocus(7);break;case"Home":{const i=this.focusedDate.dayOfWeek;i>1&&this._moveFocus(-(i-1));break}case"End":{const i=this.focusedDate.dayOfWeek;i<7&&this._moveFocus(7-i);break}case"PageUp":this._navigateMonth(e.shiftKey?-12:-1);break;case"PageDown":this._navigateMonth(e.shiftKey?12:1);break;case"Enter":case" ":this._selectDate(this.focusedDate);break;case"Escape":this._closePopover(),this.inputRef.value?.focus();break;default:t=!1}t&&(e.preventDefault(),e.stopPropagation(),await this.updateComplete,this.shadowRoot?.querySelector('[role="grid"]')?.querySelector('[tabindex="0"]')?.focus())}_onDayCellHover(e){this.mode==="range"&&this._rangePhase==="start"&&(this._rangePreview=e)}render(){return this.temporalSupported?c`
|
|
1
|
+
var n=function(m,e,t,i){var o=arguments.length,s=o<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(m,e,t,i);else for(var l=m.length-1;l>=0;l--)(a=m[l])&&(s=(o<3?a(s):o>3?a(e,t,s):a(e,t))||s);return o>3&&s&&Object.defineProperty(e,t,s),s},_;import{html as c,nothing as w}from"lit";import{customElement as $,property as p,state as d}from"lit/decorators.js";import{classMap as R}from"lit/directives/class-map.js";import{createRef as g,ref as v}from"lit/directives/ref.js";import{repeat as C}from"lit/directives/repeat.js";import{EspalierElementBase as P}from"../shared/esp-element-base.js";import{PopoverController as M}from"../shared/popover-controller.js";import{FormFieldController as A}from"../shared/form-field-controller.js";import{FormFieldDescriptionController as E}from"../shared/form-field-description-controller.js";import{leftArrow as x}from"../shared/svgs/left-arrow.js";import{rightArrow as G}from"../shared/svgs/right-arrow.js";import{checkSVG as D}from"../shared/svgs/check.js";import{cancelSVG as b}from"../shared/svgs/cancel.js";import"../button/esp-button.js";import"../pickers/esp-pick-one.js";import"../pickers/esp-picker-item.js";import{GRID_COLS as S,GRID_ROWS as F,GRID_SIZE as O,HOURS_12 as V,MINUTES_60 as q,MONTH_NAMES as k,WEEKDAY_LABELS as B}from"./helpers/constants.js";import{displayValue as L,formatDate as T,parseValue as H}from"./helpers/parsing.js";import{generateCalendarGrid as I,getEffectiveRange as X,getSelectedDate as Y,isDateDisabled as W,parseDateBound as y}from"./helpers/calendar-grid.js";import{calendarIcon as U}from"../shared/svgs/calendar-icon.js";import{datePickerStyles as N}from"./helpers/styles.js";let r=_=class extends P{constructor(){super(...arguments),this.internals=this.attachInternals(),this.formCtrl=new A({host:this,internals:this.internals,getFormValue:()=>this._value||null,getValidity:()=>this._getValidityResult(),getValidationAnchor:()=>this.inputRef.value??this,onReset:()=>{this._rangeAnchor=null,this._rangePreview=null,this._value="",this.requestUpdate("value",""),this._syncFromValue()},onRestore:e=>{this.value=e},onDisabled:e=>{this.disabled=e}}),this.formItemDescription=new E({host:this,getTarget:()=>this.inputRef.value}),this.popoverCtrl=new M({host:this,closeStrategy:"source-identity",isOpen:()=>this.open,onShouldClose:()=>this._closePopover(),onPositionUpdate:()=>this._positionPopover(),shouldContinueTracking:()=>{const e=this.getBoundingClientRect(),t=window.innerHeight||document.documentElement.clientHeight;return!(e.bottom<0||e.top>t)},getInsideElements:()=>[this.popoverRef.value??null],onOutsideClick:()=>this._closePopover()}),this.inputRef=g(),this.popoverRef=g(),this.calBodyRef=g(),this.timePickerRef=g(),this.temporalSupported=!0,this.mode="date",this._value="",this.placeholder="Select...",this.min="",this.max="",this.disabled=!1,this.name="",this.required=!1,this.requiredMessage="",this.open=!1,this.parsed={kind:"none"},this._parsedMinDate=null,this._parsedMaxDate=null,this._hour=12,this._minute=0,this._period="AM",this._rangeAnchor=null,this._rangePreview=null,this._cachedGridKey="",this._cachedGrid=[],this._valueOnOpen="",this._touchStartX=0,this._touchStartY=0,this._touchGesture="none",this._swipeAnimating=!1,this._longPressTimer=0,this._edgeScrollTimer=0}get value(){return this._value}set value(e){const t=this._value;this._value=e,this.requestUpdate("value",t),this._syncFromValue(),this.formCtrl.syncValue()}get _rangePhase(){return this._rangeAnchor?this.parsed.kind==="range"?"complete":"start":"empty"}_getGrid(){const e=[this.viewDate?.toString(),this._value,this._rangeAnchor?.toString()??"",this._rangePreview?.toString()??""].join("|");if(e!==this._cachedGridKey){this._cachedGridKey=e;const t=Y(this.parsed),{start:i,end:o}=X(this.mode,this.parsed,this._rangeAnchor,this._rangePreview);this._cachedGrid=I(this.viewDate,t,i,o,this._minDate,this._maxDate)}return this._cachedGrid}_dateAtPoint(e,t){const i=this.shadowRoot?.elementsFromPoint(e,t);if(!i)return null;for(const o of i){const s=o.dataset?.date;if(s)try{return Temporal.PlainDate.from(s)}catch{return null}}return null}_edgeSide(e){const t=this.shadowRoot?.querySelector(".calendar");if(!t)return null;const i=t.getBoundingClientRect(),o=this.shadowRoot?.querySelector(".day-cell"),s=o?o.getBoundingClientRect().width:32;return e<=i.left+s?"left":e>=i.right-s?"right":null}_onCalendarTouchStart(e){if(e.touches.length!==1||this._swipeAnimating)return;const t=e.touches[0];if(this._touchStartX=t.clientX,this._touchStartY=t.clientY,this._touchGesture="pending",this._clearLongPressTimer(),this.mode==="range"&&this._rangePhase!=="empty"){const i=this.shadowRoot?.querySelector(".calendar");i&&(i.style.touchAction="none"),this._longPressTimer=window.setTimeout(()=>{if(this._longPressTimer=0,this._touchGesture!=="pending")return;this._touchGesture="drag";const o=this._dateAtPoint(this._touchStartX,this._touchStartY);o&&!this._isDateDisabled(o)&&(this._rangePhase==="complete"&&(this._rangeAnchor=o,this._value="",this.parsed={kind:"none"},this.formCtrl.syncValue()),this._rangePreview=o,this.requestUpdate())},_.LONG_PRESS_MS)}}_onCalendarTouchMove(e){if(e.touches.length!==1||this._swipeAnimating||this._touchGesture==="none")return;const t=e.touches[0],i=t.clientX-this._touchStartX,o=t.clientY-this._touchStartY;if(this._touchGesture==="drag"){e.cancelable&&e.preventDefault();const s=this._dateAtPoint(t.clientX,t.clientY);s&&!this._isDateDisabled(s)&&(this._rangePreview=s),this._handleEdgeScroll(t.clientX);return}if(this._touchGesture==="pending"){if(Math.abs(i)<10&&Math.abs(o)<10)return;if(this._clearLongPressTimer(),Math.abs(o)>Math.abs(i)){this._touchGesture="none",this._resetTouchAction();return}this._touchGesture="swipe"}if(this._touchGesture==="swipe"){e.cancelable&&e.preventDefault();const s=this.calBodyRef.value;s&&(s.style.transition="none",s.style.transform=`translateX(${i}px)`)}}_onCalendarTouchEnd(e){this._clearLongPressTimer(),this._clearEdgeScrollTimer(),this._resetTouchAction();const t=this._touchGesture;if(this._touchGesture="none",t==="drag"){if(e.changedTouches.length===1){const o=e.changedTouches[0];let s=this._dateAtPoint(o.clientX,o.clientY);if(s||(s=this._rangePreview),s&&!this._isDateDisabled(s)&&this._rangeAnchor){const a=this._rangeAnchor;let l,h;Temporal.PlainDate.compare(s,a)<0?(l=s,h=a):(l=a,h=s),this._rangePreview=null,this.value=`${l.toString()}/${h.toString()}`,this._dispatchValueChanged()}}return}if(t==="swipe"){this._finishSwipe(e);return}const i=this.calBodyRef.value;i&&(i.style.transition="",i.style.transform="")}_finishSwipe(e){const t=this.calBodyRef.value;if(!t||e.changedTouches.length!==1){t&&(t.style.transition="",t.style.transform="");return}const o=e.changedTouches[0].clientX-this._touchStartX,s=t.offsetWidth;if(Math.abs(o)>=30){const a=o<0?1:-1,l=a===1?-s:s;this._swipeAnimating=!0,t.style.transition="transform 150ms ease-in",t.style.transform=`translateX(${l}px)`,t.addEventListener("transitionend",()=>{this._navigateMonth(a),this.updateComplete.then(()=>{const h=this.calBodyRef.value;if(!h){this._swipeAnimating=!1;return}h.style.transition="none",h.style.transform=`translateX(${-l}px)`,h.getBoundingClientRect(),h.style.transition="transform 150ms ease-out",h.style.transform="",h.addEventListener("transitionend",()=>{h.style.transition="",this._swipeAnimating=!1},{once:!0})})},{once:!0})}else t.style.transition="transform 150ms ease-out",t.style.transform="",t.addEventListener("transitionend",()=>{t.style.transition=""},{once:!0})}_clearLongPressTimer(){this._longPressTimer&&(clearTimeout(this._longPressTimer),this._longPressTimer=0)}_handleEdgeScroll(e){const t=this._edgeSide(e);if(!t){this._clearEdgeScrollTimer();return}if(this._edgeScrollTimer)return;const i=t==="right"?1:-1;this._edgeScrollTimer=window.setTimeout(async()=>{this._edgeScrollTimer=0,this._touchGesture==="drag"&&(this._navigateMonth(i),await this.updateComplete)},_.EDGE_SCROLL_MS)}_clearEdgeScrollTimer(){this._edgeScrollTimer&&(clearTimeout(this._edgeScrollTimer),this._edgeScrollTimer=0)}_resetTouchAction(){const e=this.shadowRoot?.querySelector(".calendar");e&&e.style.removeProperty("touch-action")}connectedCallback(){if(super.connectedCallback(),typeof window.Temporal>"u"){this.temporalSupported=!1;return}this.viewDate||(this.viewDate=Temporal.Now.plainDateISO().toPlainYearMonth()),this.focusedDate||(this.focusedDate=Temporal.Now.plainDateISO()),this._parsedMinDate=y(this.min),this._parsedMaxDate=y(this.max),this._syncFromValue(),this.formCtrl.validate()}disconnectedCallback(){super.disconnectedCallback()}willUpdate(e){super.willUpdate(e),e.has("min")&&(this._parsedMinDate=y(this.min)),e.has("max")&&(this._parsedMaxDate=y(this.max))}updated(e){super.updated(e),e.has("disabled")&&(this.internals.ariaDisabled=this.disabled?"true":"false"),e.has("required")&&(this.internals.ariaRequired=this.required?"true":"false",this.formCtrl.validate()),(e.has("min")||e.has("max"))&&this.formCtrl.validate()}focus(e){this.focusResolvedElementAfterUpdate(()=>this.inputRef.value,e)}setFormItemDescription(e){this.formItemDescription.setDescription(e)}validate(){this.formCtrl.validate()}checkValidity(){return this.formCtrl.checkValidity()}formResetCallback(){this.formCtrl.handleFormReset()}formStateRestoreCallback(e){this.formCtrl.handleFormStateRestore(e)}formDisabledCallback(e){this.formCtrl.handleFormDisabled(e)}_syncFromValue(){if(this.temporalSupported)switch(this.parsed=H(this._value,this.mode),this.parsed.kind){case"date":this.viewDate=this.parsed.date.toPlainYearMonth(),this.focusedDate=this.parsed.date;break;case"datetime":{this.viewDate=this.parsed.datetime.toPlainDate().toPlainYearMonth(),this.focusedDate=this.parsed.datetime.toPlainDate();const e=this.parsed.datetime.toPlainTime(),t=e.hour;this._period=t>=12?"PM":"AM",this._hour=t===0?12:t>12?t-12:t,this._minute=e.minute;break}case"time":{const e=this.parsed.time,t=e.hour;this._period=t>=12?"PM":"AM",this._hour=t===0?12:t>12?t-12:t,this._minute=e.minute;break}case"range":this.viewDate=this.parsed.start.toPlainYearMonth(),this.focusedDate=this.parsed.start,this._rangeAnchor=this.parsed.start,this._rangePreview=null;break;case"none":break}}_getValidityResult(){if(!this.temporalSupported)return null;if(this.required&&!this._value)return{flags:{valueMissing:!0},message:this.requiredMessage||"Please select a date."};if(this._value&&this.parsed.kind==="none")return{flags:{typeMismatch:!0},message:"The value is not a valid date."};const e=this._getValidationDates();if(e.length>0){const t=this._minDate,i=this._maxDate;if(t){for(const o of e)if(Temporal.PlainDate.compare(o,t)<0)return{flags:{rangeUnderflow:!0},message:`Date must not be before ${T(t)}.`}}if(i){for(const o of e)if(Temporal.PlainDate.compare(o,i)>0)return{flags:{rangeOverflow:!0},message:`Date must not be after ${T(i)}.`}}}return null}_getValidationDates(){switch(this.parsed.kind){case"date":return[this.parsed.date];case"datetime":return[this.parsed.datetime.toPlainDate()];case"range":return[this.parsed.start,this.parsed.end];default:return[]}}get _minDate(){return this._parsedMinDate}get _maxDate(){return this._parsedMaxDate}_isDateDisabled(e){return W(e,this._minDate,this._maxDate)}_navigateMonth(e){this.viewDate=this.viewDate.add({months:e}),this.focusedDate=this.viewDate.toPlainDate({day:Math.min(this.focusedDate.day,this.viewDate.daysInMonth)})}_moveFocus(e){const t=this.focusedDate.add({days:e});if(this._isDateDisabled(t)){const o=e>0?1:-1;let s=t;for(let a=0;a<O&&this._isDateDisabled(s);a++)s=s.add({days:o});this.focusedDate=s}else this.focusedDate=t;const i=this.focusedDate.toPlainYearMonth();Temporal.PlainYearMonth.compare(i,this.viewDate)!==0&&(this.viewDate=i),this.mode==="range"&&this._rangePhase==="start"&&(this._rangePreview=this.focusedDate)}_selectDate(e){if(!this._isDateDisabled(e)){switch(this.mode){case"date":this.value=e.toString(),this._closePopover(),this.inputRef.value?.focus();break;case"datetime":{const t=this.parsed.kind==="datetime"?this.parsed.datetime.toPlainTime():new Temporal.PlainTime;this.value=e.toPlainDateTime(t).toString();break}case"range":this._selectRangeEndpoint(e);break}this._dispatchValueChanged()}}_selectRangeEndpoint(e){switch(this._rangePhase){case"empty":case"complete":this._rangeAnchor=e,this._rangePreview=null,this._value="",this.parsed={kind:"none"},this.formCtrl.syncValue(),this.requestUpdate();break;case"start":{const i=this._rangeAnchor;let o,s;Temporal.PlainDate.compare(e,i)<0?(o=e,s=i):(o=i,s=e),this._rangePreview=null,this.value=`${o.toString()}/${s.toString()}`;break}}}_dispatchValueChanged(){this.emitValueChanged(this._value)}get _showTimePicker(){return this.mode==="time"||this.mode==="datetime"}get _showCalendar(){return this.mode!=="time"}_commitTime(){let e=this._hour%12;this._period==="PM"&&(e+=12);const t=new Temporal.PlainTime(e,this._minute);if(this.mode==="time")this.value=t.toString();else if(this.mode==="datetime"){const i=this.parsed.kind==="datetime"?this.parsed.datetime.toPlainDate():this.parsed.kind==="date"?this.parsed.date:Temporal.Now.plainDateISO();this.value=i.toPlainDateTime(t).toString()}this._dispatchValueChanged()}async _openPopover(){if(this.disabled)return;this.popoverCtrl.publishCloseOthers(),this._valueOnOpen=this._value,this.open=!0,this._positionPopover(),this.popoverCtrl.startTracking(),this.popoverCtrl.startOutsideClick(),await this.updateComplete,this._shrinkTimePickerToFit(),this._scrollToContainPopover();const t=this.shadowRoot?.querySelector('[role="grid"]')?.querySelector('[tabindex="0"]');requestAnimationFrame(()=>t?.focus())}_closePopover(){this.open=!1;const e=this.popoverRef.value;if(e){e.classList.remove("visible");try{e.hidePopover()}catch{}}this.popoverCtrl.stopTracking(),this.popoverCtrl.stopOutsideClick(),this.mode==="range"&&this._rangePhase==="start"&&(this._rangeAnchor=null,this._rangePreview=null)}_togglePopover(){this.open?this._closePopover():this._openPopover()}_positionPopover(){const e=this.popoverRef.value;if(!e)return;const t=this.getBoundingClientRect(),i=window.innerHeight||document.documentElement.clientHeight,o=window.innerWidth||document.documentElement.clientWidth,s=t.top,a=i-t.bottom;e.matches(":popover-open")||e.showPopover(),e.style.removeProperty("top"),e.style.removeProperty("bottom"),e.style.removeProperty("font-size"),e.style.setProperty("width","min-content"),this._shrinkToFitViewport(e,o);let l=t.left;const h=e.offsetWidth;l+h>o&&(l=Math.max(0,o-h)),e.style.setProperty("left",`${l}px`);const f=e.offsetHeight;if(s>a){let u=i-t.top;f>s&&(u=i-f),e.style.setProperty("bottom",`${u}px`)}else{let u=t.bottom;f>a&&(u=i-f),e.style.setProperty("top",`${Math.max(0,u)}px`)}requestAnimationFrame(()=>e.classList.add("visible"))}_shrinkToFitViewport(e,t){if(e.offsetWidth<=t)return;const i=getComputedStyle(e);let o=parseFloat(i.fontSize);const s=8;for(;e.offsetWidth>t&&o>s;)o-=.5,e.style.setProperty("font-size",`${o}px`)}_shrinkTimePickerToFit(){const e=this.timePickerRef.value,t=this.popoverRef.value;if(!e||!t)return;e.style.removeProperty("font-size");const i=t.clientWidth;if(e.scrollWidth<=i)return;const o=getComputedStyle(e);let s=parseFloat(o.fontSize);const a=8;for(;e.scrollWidth>i&&s>a;)s-=.5,e.style.setProperty("font-size",`${s}px`)}_scrollToContainPopover(){const e=this.popoverRef.value;if(!e)return;const t=e.getBoundingClientRect(),i=this.getBoundingClientRect(),o=window.innerHeight||document.documentElement.clientHeight,s=Math.min(i.top,t.top),a=Math.max(i.bottom,t.bottom);if(a>o){const l=a-o;window.scrollBy({top:l+8,behavior:"smooth"}),requestAnimationFrame(()=>this._positionPopover())}else s<0&&(window.scrollBy({top:s-8,behavior:"smooth"}),requestAnimationFrame(()=>this._positionPopover()))}async _handleGridKeyDown(e){let t=!0;switch(e.key){case"ArrowLeft":this._moveFocus(-1);break;case"ArrowRight":this._moveFocus(1);break;case"ArrowUp":this._moveFocus(-7);break;case"ArrowDown":this._moveFocus(7);break;case"Home":{const i=this.focusedDate.dayOfWeek;i>1&&this._moveFocus(-(i-1));break}case"End":{const i=this.focusedDate.dayOfWeek;i<7&&this._moveFocus(7-i);break}case"PageUp":this._navigateMonth(e.shiftKey?-12:-1);break;case"PageDown":this._navigateMonth(e.shiftKey?12:1);break;case"Enter":case" ":this._selectDate(this.focusedDate);break;case"Escape":this._closePopover(),this.inputRef.value?.focus();break;default:t=!1}t&&(e.preventDefault(),e.stopPropagation(),await this.updateComplete,this.shadowRoot?.querySelector('[role="grid"]')?.querySelector('[tabindex="0"]')?.focus())}_onDayCellHover(e){this.mode==="range"&&this._rangePhase==="start"&&(this._rangePreview=e)}render(){return this.temporalSupported?c`
|
|
2
2
|
|
|
3
3
|
<div class="esp-field" @click=${()=>this._togglePopover()}>
|
|
4
4
|
<input
|
|
5
5
|
${v(this.inputRef)}
|
|
6
6
|
class="esp-input"
|
|
7
|
-
.value=${
|
|
7
|
+
.value=${L(this.parsed)}
|
|
8
8
|
placeholder=${this.placeholder}
|
|
9
9
|
readonly
|
|
10
10
|
?disabled=${this.disabled}
|
|
@@ -12,7 +12,7 @@ var n=function(m,e,t,i){var o=arguments.length,s=o<3?e:i===null?i=Object.getOwnP
|
|
|
12
12
|
aria-expanded=${this.open?"true":"false"}
|
|
13
13
|
@keydown=${e=>{(e.key==="Enter"||e.key===" "||e.key==="ArrowDown"||e.key==="ArrowUp")&&(e.preventDefault(),this._openPopover()),e.key==="Escape"&&this.open&&(e.preventDefault(),this._closePopover())}}
|
|
14
14
|
/>
|
|
15
|
-
<label class="field-icon">${
|
|
15
|
+
<label class="field-icon">${U}</label>
|
|
16
16
|
</div>
|
|
17
17
|
|
|
18
18
|
|
|
@@ -22,9 +22,9 @@ var n=function(m,e,t,i){var o=arguments.length,s=o<3?e:i===null?i=Object.getOwnP
|
|
|
22
22
|
popover="manual"
|
|
23
23
|
@keydown=${e=>{e.key==="Tab"&&(e.preventDefault(),this._closePopover(),this.inputRef.value?.focus())}}
|
|
24
24
|
>
|
|
25
|
-
${this._showCalendar?this._renderCalendar():
|
|
26
|
-
${this._showTimePicker?this._renderTimePicker():
|
|
27
|
-
${!this._showTimePicker&&this.mode!=="date"?this._renderActions():
|
|
25
|
+
${this._showCalendar?this._renderCalendar():w}
|
|
26
|
+
${this._showTimePicker?this._renderTimePicker():w}
|
|
27
|
+
${!this._showTimePicker&&this.mode!=="date"?this._renderActions():w}
|
|
28
28
|
</div>
|
|
29
29
|
`:c`<p class="temporal-error">
|
|
30
30
|
<code>Temporal</code> API not found. Load the polyfill in <code><head></code> before
|
|
@@ -45,7 +45,7 @@ var n=function(m,e,t,i){var o=arguments.length,s=o<3?e:i===null?i=Object.getOwnP
|
|
|
45
45
|
aria-label="Previous month"
|
|
46
46
|
@click=${i=>{i.stopPropagation(),this._navigateMonth(-1)}}
|
|
47
47
|
>
|
|
48
|
-
${
|
|
48
|
+
${x}
|
|
49
49
|
</button>
|
|
50
50
|
<span class="cal-title">${t}</span>
|
|
51
51
|
<button
|
|
@@ -53,14 +53,14 @@ var n=function(m,e,t,i){var o=arguments.length,s=o<3?e:i===null?i=Object.getOwnP
|
|
|
53
53
|
aria-label="Next month"
|
|
54
54
|
@click=${i=>{i.stopPropagation(),this._navigateMonth(1)}}
|
|
55
55
|
>
|
|
56
|
-
${
|
|
56
|
+
${G}
|
|
57
57
|
</button>
|
|
58
58
|
</header>
|
|
59
59
|
|
|
60
60
|
|
|
61
61
|
<div ${v(this.calBodyRef)} class="cal-body">
|
|
62
62
|
<div class="weekday-row" role="row">
|
|
63
|
-
${
|
|
63
|
+
${B.map(i=>c`<abbr class="weekday-label" title=${i}>${i}</abbr>`)}
|
|
64
64
|
</div>
|
|
65
65
|
|
|
66
66
|
<div class="day-grid" role="grid" aria-label=${t}>
|
|
@@ -68,7 +68,7 @@ var n=function(m,e,t,i){var o=arguments.length,s=o<3?e:i===null?i=Object.getOwnP
|
|
|
68
68
|
</div>
|
|
69
69
|
</div>
|
|
70
70
|
</div>
|
|
71
|
-
`}_renderGridRows(e){const t=[];for(let i=0;i<
|
|
71
|
+
`}_renderGridRows(e){const t=[];for(let i=0;i<F;i++){const o=e.slice(i*S,(i+1)*S);t.push(c`
|
|
72
72
|
<div class="day-row" role="row">
|
|
73
73
|
${C(o,s=>s.date.toString(),s=>this._renderDayCell(s))}
|
|
74
74
|
</div>
|
|
@@ -97,7 +97,7 @@ var n=function(m,e,t,i){var o=arguments.length,s=o<3?e:i===null?i=Object.getOwnP
|
|
|
97
97
|
.value=${String(this._hour)}
|
|
98
98
|
@value-changed=${e=>{e.stopPropagation(),e.detail?.value&&(this._hour=Number(e.detail.value),this._commitTime())}}
|
|
99
99
|
>
|
|
100
|
-
${
|
|
100
|
+
${V.map(e=>c`
|
|
101
101
|
<esp-picker-item
|
|
102
102
|
text=${String(e)}
|
|
103
103
|
value=${String(e)}
|
|
@@ -115,7 +115,7 @@ var n=function(m,e,t,i){var o=arguments.length,s=o<3?e:i===null?i=Object.getOwnP
|
|
|
115
115
|
.value=${String(this._minute)}
|
|
116
116
|
@value-changed=${e=>{e.stopPropagation(),e.detail?.value&&(this._minute=Number(e.detail.value),this._commitTime())}}
|
|
117
117
|
>
|
|
118
|
-
${
|
|
118
|
+
${q.map(e=>c`
|
|
119
119
|
<esp-picker-item
|
|
120
120
|
text=${String(e).padStart(2,"0")}
|
|
121
121
|
value=${String(e)}
|
|
@@ -147,14 +147,14 @@ var n=function(m,e,t,i){var o=arguments.length,s=o<3?e:i===null?i=Object.getOwnP
|
|
|
147
147
|
icon-only
|
|
148
148
|
@clicked=${()=>{this._closePopover(),this.inputRef.value?.focus()}}
|
|
149
149
|
>
|
|
150
|
-
${
|
|
150
|
+
${D}
|
|
151
151
|
</esp-button>
|
|
152
152
|
<esp-button
|
|
153
153
|
icon-only
|
|
154
154
|
variant="danger"
|
|
155
155
|
@clicked=${()=>{this.value=this._valueOnOpen,this._closePopover(),this.inputRef.value?.focus()}}
|
|
156
156
|
>
|
|
157
|
-
${
|
|
157
|
+
${b}
|
|
158
158
|
</esp-button>
|
|
159
159
|
</div>
|
|
160
160
|
`}_renderActions(){return c`
|
|
@@ -163,14 +163,14 @@ var n=function(m,e,t,i){var o=arguments.length,s=o<3?e:i===null?i=Object.getOwnP
|
|
|
163
163
|
icon-only
|
|
164
164
|
@clicked=${()=>{this._closePopover(),this.inputRef.value?.focus()}}
|
|
165
165
|
>
|
|
166
|
-
${
|
|
166
|
+
${D}
|
|
167
167
|
</esp-button>
|
|
168
168
|
<esp-button
|
|
169
169
|
icon-only
|
|
170
170
|
variant="danger"
|
|
171
171
|
@clicked=${()=>{this.value=this._valueOnOpen,this._closePopover(),this.inputRef.value?.focus()}}
|
|
172
172
|
>
|
|
173
|
-
${
|
|
173
|
+
${b}
|
|
174
174
|
</esp-button>
|
|
175
175
|
</div>
|
|
176
|
-
`}};r.formAssociated=!0,r.LONG_PRESS_MS=400,r.EDGE_SCROLL_MS=1e3,r.styles=[...
|
|
176
|
+
`}};r.formAssociated=!0,r.LONG_PRESS_MS=400,r.EDGE_SCROLL_MS=1e3,r.styles=[...P.styles,N],n([d()],r.prototype,"temporalSupported",void 0),n([p({type:String,reflect:!0})],r.prototype,"mode",void 0),n([p({type:String})],r.prototype,"value",null),n([p({type:String})],r.prototype,"placeholder",void 0),n([p({type:String})],r.prototype,"min",void 0),n([p({type:String})],r.prototype,"max",void 0),n([p({type:Boolean,reflect:!0})],r.prototype,"disabled",void 0),n([p({type:String,reflect:!0})],r.prototype,"name",void 0),n([p({type:Boolean,reflect:!0})],r.prototype,"required",void 0),n([p({attribute:"required-message"})],r.prototype,"requiredMessage",void 0),n([d()],r.prototype,"viewDate",void 0),n([d()],r.prototype,"focusedDate",void 0),n([d()],r.prototype,"open",void 0),n([d()],r.prototype,"parsed",void 0),n([d()],r.prototype,"_hour",void 0),n([d()],r.prototype,"_minute",void 0),n([d()],r.prototype,"_period",void 0),n([d()],r.prototype,"_rangeAnchor",void 0),n([d()],r.prototype,"_rangePreview",void 0),r=_=n([$("esp-date-picker")],r);export{r as EspalierDatePicker};
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var u=function(t,e,o,n){var
|
|
1
|
+
var u=function(t,e,o,n){var i=arguments.length,s=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,o):n,c;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,o,n);else for(var l=t.length-1;l>=0;l--)(c=t[l])&&(s=(i<3?c(s):i>3?c(e,o,s):c(e,o))||s);return i>3&&s&&Object.defineProperty(e,o,s),s};import"../pickers/esp-pick-one.js";import{customElement as $,property as p,state as G}from"lit/decorators.js";import{EspalierElementBase as A}from"../shared/esp-element-base.js";import{html as N}from"lit";const w=[{family:"Arial / Helvetica",stack:"Arial, Helvetica, sans-serif",category:"sans-serif",kind:"web-safe"},{family:"Georgia / Times New Roman",stack:'Georgia, "Times New Roman", Times, serif',category:"serif",kind:"web-safe"},{family:"Verdana / Geneva",stack:"Verdana, Geneva, sans-serif",category:"sans-serif",kind:"web-safe"},{family:"Tahoma / Geneva",stack:"Tahoma, Geneva, sans-serif",category:"sans-serif",kind:"web-safe"},{family:"Trebuchet MS",stack:'"Trebuchet MS", Arial, sans-serif',category:"sans-serif",kind:"web-safe"},{family:"Courier New",stack:'"Courier New", Courier, monospace',category:"monospace",kind:"web-safe"},{family:"System Sans",stack:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif',category:"sans-serif",kind:"web-safe"},{family:"System Serif",stack:'ui-serif, Georgia, Cambria, "Times New Roman", Times, serif',category:"serif",kind:"web-safe"},{family:"System Monospace",stack:'ui-monospace, SFMono-Regular, Consolas, "Liberation Mono", "Courier New", monospace',category:"monospace",kind:"web-safe"}];let f,m=!1;const U=async()=>{if(f)return f;if(m){for(;!f;)await new Promise(n=>setTimeout(n,100));return f}m=!0;const t=document.getElementsByTagName("esp-root")[0];if(!t)throw new Error("<esp-font-picker> requires an <esp-root> ancestor. Wrap your application in <esp-root> to use the font picker.");const e=t.fontDefinitionsUrl||`${t.fontCSSRoot}font-definitions.json`,o=await fetch(e);if(!o.ok)throw m=!1,new Error(`Failed to load font definitions from ${e} (${o.status}). Run 'npm run build-fonts' to generate the font catalog.`);return f=await o.json(),f},k="esp-preview-",V=t=>`${k}${t}`,d=new Map,g=async t=>{if(d.has(t))return!0;try{const e=document.getElementsByTagName("esp-root")[0];if(!e)return!1;const o=t.replaceAll(" ","-"),n=await fetch(`${e.fontCSSRoot}${o}.css`);if(!n.ok)return!1;let i=await n.text();i=i.replace(/font-family:\s*'([^']+)'/g,(c,l)=>`font-family: '${k}${l}'`);const s=document.createElement("style");return s.textContent=i,s.dataset.font=t,document.head.appendChild(s),d.set(t,s),!0}catch(e){return console.warn(`Failed to load CSS for font ${t}:`,e),!1}},v=t=>{const e=d.get(t);e&&(e.remove(),d.delete(t))},F="data-esp-font-picker",b="data-esp-font-picker-root",I=t=>t.closest("esp-root"),C=t=>I(t)?.correlationId??"",E=(t,e)=>`link[${F}="${CSS.escape(t)}"][${b}="${CSS.escape(e)}"]`,S=(t,e)=>{if(!e)return;const o=I(t),n=o?.correlationId??"";if(o?.googleFontLoading==="none"){h(t,e);return}if(document.head.querySelector(E(e,n)))return;const i=encodeURIComponent(e),s=document.createElement("link");s.rel="stylesheet",s.href=`https://fonts.googleapis.com/css2?family=${i}&display=swap`,s.setAttribute(F,e),s.setAttribute(b,n),document.head.appendChild(s)},h=(t,e)=>{if(!e)return;const o=C(t);if(Array.from(document.getElementsByTagName("esp-font-picker")).some(s=>C(s)===o&&s.fontSource==="google"&&s.value===e))return;document.head.querySelector(E(e,o))?.remove()},R=t=>t.kind!=="web-safe",y=t=>R(t)?t.family:t.stack,x=t=>R(t)?`${V(t.family)}, "${t.family}"`:t.stack,_=(t,e)=>t.filter(o=>{switch(e){case"not-display":return o.category!=="display";default:return o.category===e}});let r=class extends A{constructor(){super(...arguments),this.loadedFonts=new Set,this.formItemDescription=null,this._rangeGeneration=0,this._initGeneration=0,this._fontsReady=Promise.resolve(),this.fonts=[],this.category=null,this.fontSource="google",this.value="",this.placeholder="Choose a font...",this.handleItemsInViewEvent=e=>{e.stopPropagation(),this.handleItemsInView(e.detail)}}focus(){this.shadowRoot?.querySelector("esp-pick-one")?.focus()}setFormItemDescription(e){this.formItemDescription=e,this.syncFormItemDescription()}syncFormItemDescription(){this.shadowRoot?.querySelector("esp-pick-one")?.setFormItemDescription?.(this.formItemDescription)}async getUpdateComplete(){const e=await super.getUpdateComplete();return await this._fontsReady,e}firstUpdated(e){super.firstUpdated(e),this._fontsReady=this.initFonts()}updated(e){super.updated(e),this.syncFormItemDescription();const o=e.has("fontSource")&&e.get("fontSource")!==void 0,n=e.has("category")&&e.get("category")!==void 0;if(o||n){if(e.get("fontSource")==="google"&&this.fontSource==="web-safe"){const i=this.value;for(const s of this.loadedFonts)v(s);this.loadedFonts.clear(),this.value="",i&&h(this,i)}this._fontsReady=this.initFonts()}if(e.has("value")&&this.value&&this.fontSource==="google"){const i=e.get("value");i!==this.value&&this.ensureFontLoaded(this.value,i)}}async ensureFontLoaded(e,o){await g(e)&&this.loadedFonts.add(e),this.value===e&&(S(this,e),o&&o!==e&&h(this,o))}async initFonts(){const e=++this._initGeneration;if(this.fontSource==="web-safe"){this.fonts=this.category?_(w,this.category):w;return}const o=await U();if(!(e!==this._initGeneration||this.fontSource!=="google")&&(this.fonts=this.category?_(o,this.category):o,this.value&&this.fonts.some(n=>y(n)===this.value))){const n=this.value;if(await g(n)){if(e!==this._initGeneration||this.fontSource!=="google"||this.value!==n){v(n);return}this.loadedFonts.add(n)}if(e!==this._initGeneration||this.fontSource!=="google"||this.value!==n)return;S(this,n)}}async handleItemsInView(e){if(this.fontSource==="web-safe")return;const o=++this._rangeGeneration,n=3,i=e.items??[],s=new Set,c=Math.max(0,e.first),l=Math.min(e.last+n,i.length);for(let a=c;a<l;a++)s.add(i[a].value);for(const a of s)this.loadedFonts.has(a)||await g(a)&&this.loadedFonts.add(a);if(o!==this._rangeGeneration)return;const T=new Set(Array.from(document.getElementsByTagName("esp-font-picker")).map(a=>a.value).filter(Boolean));for(const a of this.loadedFonts)T.has(a)||s.has(a)||(this.loadedFonts.delete(a),v(a))}render(){return N`<esp-pick-one
|
|
2
2
|
typeahead
|
|
3
3
|
.pickerItems=${this.fonts.map(e=>({text:e.family,value:y(e),selected:this.value===y(e),styles:{fontFamily:x(e)}}))}
|
|
4
4
|
.value=${this.value}
|
|
5
5
|
.placeholder=${this.placeholder}
|
|
6
6
|
@range-changed=${this.handleItemsInViewEvent}
|
|
7
|
-
@value-changed=${async e=>{e.stopPropagation();const o=this.value;if(!e.detail){this.value="",o&&h(this,o),this.dispatchEvent(new CustomEvent("value-changed",{detail:void 0,bubbles:!0,composed:!0}));return}const n=this.fonts.find(
|
|
7
|
+
@value-changed=${async e=>{e.stopPropagation();const o=this.value;if(!e.detail){this.value="",o&&h(this,o),this.dispatchEvent(new CustomEvent("value-changed",{detail:void 0,bubbles:!0,composed:!0}));return}const n=this.fonts.find(i=>y(i)===e.detail.value);this.value=e.detail.value,this.fontSource==="google"&&(await g(this.value)&&this.loadedFonts.add(this.value),S(this,this.value),o&&o!==this.value&&h(this,o)),this.dispatchEvent(new CustomEvent("value-changed",{detail:n,bubbles:!0,composed:!0}))}}
|
|
8
8
|
>
|
|
9
|
-
</esp-pick-one>`}};u([G()],r.prototype,"fonts",void 0),u([p({attribute:"category",type:String})],r.prototype,"category",void 0),u([p({attribute:"font-source",type:String})],r.prototype,"fontSource",void 0),u([p({type:String})],r.prototype,"value",void 0),u([p({type:String})],r.prototype,"placeholder",void 0),r=u([
|
|
9
|
+
</esp-pick-one>`}};u([G()],r.prototype,"fonts",void 0),u([p({attribute:"category",type:String})],r.prototype,"category",void 0),u([p({attribute:"font-source",type:String})],r.prototype,"fontSource",void 0),u([p({type:String})],r.prototype,"value",void 0),u([p({type:String})],r.prototype,"placeholder",void 0),r=u([$("esp-font-picker")],r);const q=()=>{f=void 0,m=!1;for(const t of document.head.querySelectorAll("style[data-font]"))t.remove();d.clear();for(const t of document.head.querySelectorAll(`link[${F}]`))t.remove()};export{r as EspalierFontPicker,w as WEB_SAFE_FONTS,U as getGoogleFonts,V as previewFontFamily,q as resetFontCache};
|
|
@@ -25,7 +25,12 @@ export type EspalierFormField = {
|
|
|
25
25
|
* </esp-box>
|
|
26
26
|
* ```
|
|
27
27
|
*
|
|
28
|
+
* @slot - The single form control the item wraps.
|
|
29
|
+
* @slot hint - Rich hint content; replaces the `hint` attribute text when present.
|
|
30
|
+
*
|
|
28
31
|
* @cssprop --esp-form-item-label-color - The color of the label text.
|
|
32
|
+
* @cssprop --esp-form-item-hint-color - The color of the hint text. Defaults to a muted variant of the body text color.
|
|
33
|
+
* @cssprop --esp-form-item-hint-font-size - The font size of the hint text. Defaults to `var(--esp-type-tiny)`.
|
|
29
34
|
* @cssprop --esp-form-item-error-color - The color of the visible error badge text.
|
|
30
35
|
* @cssprop --esp-form-item-error-background - The background color of the visible error badge.
|
|
31
36
|
* @cssprop --esp-form-item-error-field-background - The background color applied to slotted fields while an error is shown.
|
|
@@ -55,6 +60,51 @@ export declare class EspalierFormItem extends LitElement {
|
|
|
55
60
|
* focus captured.
|
|
56
61
|
*/
|
|
57
62
|
autofocus: boolean;
|
|
63
|
+
/**
|
|
64
|
+
* Persistent helper text shown with the field — the bottom rung of
|
|
65
|
+
* the help ladder. Hints are static authored guidance such as an
|
|
66
|
+
* expected format; validation messaging belongs to `error` and
|
|
67
|
+
* `warning` and must not be routed through the hint. The hint stays
|
|
68
|
+
* visible while an error or warning badge is showing, and is
|
|
69
|
+
* announced to assistive technology as the field's description via
|
|
70
|
+
* `aria-describedby`.
|
|
71
|
+
*
|
|
72
|
+
* ```html
|
|
73
|
+
* <esp-box class="demo-form">
|
|
74
|
+
* <esp-form-item
|
|
75
|
+
* label="Employer ID"
|
|
76
|
+
* hint="Use the format XX-XXXXXXX.">
|
|
77
|
+
* <esp-input></esp-input>
|
|
78
|
+
* </esp-form-item>
|
|
79
|
+
* <esp-button label="Form Things"></esp-button>
|
|
80
|
+
* </esp-box>
|
|
81
|
+
* ```
|
|
82
|
+
*
|
|
83
|
+
* For rich hint content, slot markup into the `hint` slot instead;
|
|
84
|
+
* it replaces the attribute text when present.
|
|
85
|
+
*
|
|
86
|
+
* @type {string}
|
|
87
|
+
*/
|
|
88
|
+
hint: string;
|
|
89
|
+
/**
|
|
90
|
+
* Where the hint renders. `below` (the default) places it directly
|
|
91
|
+
* under the field, above the error/warning badge rows. `above`
|
|
92
|
+
* places it between the label text and the field. Any other value
|
|
93
|
+
* falls back to `below`.
|
|
94
|
+
*
|
|
95
|
+
* ```html
|
|
96
|
+
* <esp-box class="demo-form">
|
|
97
|
+
* <esp-form-item
|
|
98
|
+
* label="Employer ID"
|
|
99
|
+
* hint="Use the format XX-XXXXXXX."
|
|
100
|
+
* hint-placement="above">
|
|
101
|
+
* <esp-input></esp-input>
|
|
102
|
+
* </esp-form-item>
|
|
103
|
+
* <esp-button label="Form Things"></esp-button>
|
|
104
|
+
* </esp-box>
|
|
105
|
+
* ```
|
|
106
|
+
*/
|
|
107
|
+
hintPlacement: "below" | "above";
|
|
58
108
|
/**
|
|
59
109
|
* An error message to show for the given form control.
|
|
60
110
|
*
|
|
@@ -119,6 +169,8 @@ export declare class EspalierFormItem extends LitElement {
|
|
|
119
169
|
set errorPool(errors: Array<ValidationError>);
|
|
120
170
|
protected firstUpdated(): void;
|
|
121
171
|
protected updated(changed: PropertyValues): void;
|
|
172
|
+
connectedCallback(): void;
|
|
173
|
+
disconnectedCallback(): void;
|
|
122
174
|
/**
|
|
123
175
|
* Focus the assigned slotted field.
|
|
124
176
|
*/
|
|
@@ -1,11 +1,16 @@
|
|
|
1
|
-
var
|
|
2
|
-
<div class=${
|
|
1
|
+
var n=function(l,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(l,e,t,r);else for(var d=l.length-1;d>=0;d--)(h=l[d])&&(i=(o<3?h(i):o>3?h(e,t,i):h(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i};import{LitElement as f,css as u,html as m,nothing as c}from"lit";import{customElement as g,property as a}from"lit/decorators.js";import{classMap as v}from"lit/directives/class-map.js";import{createRef as b,ref as y}from"lit/directives/ref.js";import{VALIDITY_CHANGED_EVENT as w}from"../shared/validation.js";let p=0,s=class extends f{constructor(){super(...arguments),this.fieldSlot=b(),this.theField={focus:()=>{}},this._errorSource="manual",this.label="",this.autofocus=!1,this.hint="",this.hintPlacement="below",this.hintId=`esp-form-item-hint-${++p}`,this.managedHintEl=null,this.appliedHintTokens=[],this.hintContentObserver=new MutationObserver(()=>{this.syncFieldDescribedBy()}),this._error="",this._warning="",this.fieldName="",this._errorPool=[],this.handleHintSlotChange=()=>{this.syncManagedHint(),this.observeConsumerHintContent(),this.requestUpdate(),this.syncFieldDescribedBy()}}get hasHint(){return!!this.hint||this.consumerHintElements().length>0}consumerHintElements(){return[...this.children].filter(e=>e.slot==="hint"&&!e.hasAttribute("data-esp-managed-hint"))}get error(){return this._error}set error(e){this._setError(e,"manual")}_setError(e,t){const r=this._error;this._error=e,this._errorSource=t,this.requestUpdate("error",r)}get warning(){return this._warning}set warning(e){const t=this._warning;this._warning=e,this.requestUpdate("warning",t)}get errorPool(){return this._errorPool}set errorPool(e){const t=this._errorPool;this._errorPool=e,this.requestUpdate("errorPool",t);const r=e.filter(o=>o.fieldName===this.fieldName);if(r.length===0){this._errorSource==="pool"&&this._setError("","pool");return}this._setError(r[0].errorMessage,"pool")}firstUpdated(){if(this.fieldSlot.value?.assignedElements().length!=1)throw new Error("esp-form-item requires exactly one slotted element.");this.theField=this.fieldSlot.value?.assignedElements()[0],this.fieldName&&this.theField.setAttribute("name",this.fieldName),this.syncFieldDescribedBy(),this.autofocus&&this.focus(),this.addEventListener(w,t=>{const r=t.detail;this._errorSource==="pool"&&this._error.length>0||(r.valid?this._errorSource==="native"&&this._setError("","manual"):this._setError(r.message,"native"))});const e=this.theField;e.addEventListener("invalid",t=>{t.preventDefault(),!(this._errorSource==="pool"&&this._error.length>0)&&"validationMessage"in e&&this._setError(e.validationMessage,"native")})}updated(e){if(super.updated(e),(e.has("hint")||e.has("hintPlacement"))&&(this.syncManagedHint(),this.syncFieldDescribedBy()),!e.has("fieldName"))return;const t=this.theField;t instanceof Element&&(this.fieldName?t.setAttribute("name",this.fieldName):t.removeAttribute("name"))}connectedCallback(){super.connectedCallback(),this.observeConsumerHintContent()}disconnectedCallback(){this.hintContentObserver.disconnect(),super.disconnectedCallback()}observeConsumerHintContent(){this.hintContentObserver.disconnect();for(const e of this.consumerHintElements())this.hintContentObserver.observe(e,{attributes:!0,attributeFilter:["id"],characterData:!0,childList:!0,subtree:!0})}syncManagedHint(){if(!(!!this.hint&&this.consumerHintElements().length===0)){this.managedHintEl?.remove(),this.managedHintEl=null;return}if(!this.managedHintEl){const t=document.createElement("span");t.slot="hint",t.id=this.hintId,t.toggleAttribute("data-esp-managed-hint",!0),this.managedHintEl=t,this.appendChild(t)}this.managedHintEl.textContent=this.hint}hintDescriptionIds(){return this.managedHintEl?[this.managedHintEl.id]:this.consumerHintElements().map(e=>(e.id||(e.id=`esp-form-item-hint-${++p}`),e.id))}hintDescriptionText(){if(!this.hasHint)return null;if(this.managedHintEl)return this.managedHintEl.textContent??"";const e=this.consumerHintElements();return e.length===0?this.hint:e.map(t=>t.textContent?.trim()??"").filter(Boolean).join(" ")}syncFieldDescribedBy(){const e=this.fieldSlot.value?.assignedElements()[0];if(!e)return;const t=this.hasHint?this.hintDescriptionIds():[],r=(e.getAttribute("aria-describedby")??"").split(/\s+/).filter(i=>i&&!this.appliedHintTokens.includes(i)&&!t.includes(i));this.appliedHintTokens=t;const o=[...r,...t];o.length>0?e.setAttribute("aria-describedby",o.join(" ")):e.removeAttribute("aria-describedby"),e.setFormItemDescription?.(this.hintDescriptionText())}focus(e){(this.fieldSlot.value?.assignedElements()[0]??this.theField).focus(e)}renderHint(){return m`
|
|
2
|
+
<div class="hint" aria-hidden=${this.hintPlacement==="above"?"true":c}>
|
|
3
|
+
<slot name="hint" @slotchange=${this.handleHintSlotChange}></slot>
|
|
4
|
+
</div>
|
|
5
|
+
`}render(){const e={"form-item":!0,"has-hint":this.hasHint,"has-error":this.error.length>0,"has-warning":this.warning.length>0&&this.error.length===0};return m`
|
|
6
|
+
<div class=${v(e)}>
|
|
3
7
|
<label
|
|
4
|
-
@click=${
|
|
8
|
+
@click=${t=>{this.focus(),t.stopPropagation()}}
|
|
5
9
|
>
|
|
6
|
-
${this.label}
|
|
7
|
-
<slot ${
|
|
10
|
+
${this.label} ${this.hintPlacement==="above"?this.renderHint():c}
|
|
11
|
+
<slot ${y(this.fieldSlot)}></slot>
|
|
8
12
|
</label>
|
|
13
|
+
${this.hintPlacement!=="above"?this.renderHint():c}
|
|
9
14
|
<div class="error-message">
|
|
10
15
|
<span>${this.error}</span>
|
|
11
16
|
</div>
|
|
@@ -13,7 +18,7 @@ var i=function(n,r,e,o){var l=arguments.length,s=l<3?r:o===null?o=Object.getOwnP
|
|
|
13
18
|
<span>${this.warning}</span>
|
|
14
19
|
</div>
|
|
15
20
|
</div>
|
|
16
|
-
`}};
|
|
21
|
+
`}};s.styles=u`
|
|
17
22
|
.form-item {
|
|
18
23
|
font-family: var(--esp-form-item-font, var(--esp-font-body));
|
|
19
24
|
font-size: var(--esp-form-item-font-size, var(--esp-size-font));
|
|
@@ -25,6 +30,21 @@ var i=function(n,r,e,o){var l=arguments.length,s=l<3?r:o===null?o=Object.getOwnP
|
|
|
25
30
|
color: var(--esp-form-item-label-color, var(--esp-color-text));
|
|
26
31
|
}
|
|
27
32
|
|
|
33
|
+
.hint {
|
|
34
|
+
display: none;
|
|
35
|
+
font-size: var(--esp-form-item-hint-font-size, var(--esp-type-tiny));
|
|
36
|
+
font-weight: normal;
|
|
37
|
+
color: var(--esp-form-item-hint-color, oklch(from var(--esp-color-text) l c h / 0.7));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
> .hint {
|
|
41
|
+
margin: var(--esp-size-tiny) 0;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
&.has-hint .hint {
|
|
45
|
+
display: block;
|
|
46
|
+
}
|
|
47
|
+
|
|
28
48
|
> .error-message {
|
|
29
49
|
font-size: var(--esp-type-tiny);
|
|
30
50
|
color: var(
|
|
@@ -126,4 +146,4 @@ var i=function(n,r,e,o){var l=arguments.length,s=l<3?r:o===null?o=Object.getOwnP
|
|
|
126
146
|
}
|
|
127
147
|
}
|
|
128
148
|
}
|
|
129
|
-
`,
|
|
149
|
+
`,n([a({type:String})],s.prototype,"label",void 0),n([a({type:Boolean,reflect:!0})],s.prototype,"autofocus",void 0),n([a({type:String})],s.prototype,"hint",void 0),n([a({attribute:"hint-placement",type:String})],s.prototype,"hintPlacement",void 0),n([a({type:String})],s.prototype,"error",null),n([a({type:String})],s.prototype,"warning",null),n([a({attribute:"field-name",type:String})],s.prototype,"fieldName",void 0),n([a({attribute:"error-pool",type:Array})],s.prototype,"errorPool",null),s=n([g("esp-form-item")],s);export{s as EspalierFormItem};
|
package/dist/input/esp-input.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var r=function(p,e,t,i){var a=arguments.length,l=a<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")l=Reflect.decorate(p,e,t,i);else for(var u=p.length-1;u>=0;u--)(o=p[u])&&(l=(a<3?o(l):a>3?o(e,t,l):o(e,t))||l);return a>3&&l&&Object.defineProperty(e,t,l),l};import{css as _,html as c,nothing as b}from"lit";import{customElement as
|
|
1
|
+
var r=function(p,e,t,i){var a=arguments.length,l=a<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")l=Reflect.decorate(p,e,t,i);else for(var u=p.length-1;u>=0;u--)(o=p[u])&&(l=(a<3?o(l):a>3?o(e,t,l):o(e,t))||l);return a>3&&l&&Object.defineProperty(e,t,l),l};import{css as _,html as c,nothing as b}from"lit";import{customElement as D,property as n,state as g}from"lit/decorators.js";import{ifDefined as h}from"lit/directives/if-defined.js";import{createRef as T,ref as f}from"lit/directives/ref.js";import{EspalierElementBase as y}from"../shared/esp-element-base.js";import{FormFieldController as x}from"../shared/form-field-controller.js";import{FormFieldDescriptionController as M}from"../shared/form-field-description-controller.js";import{getIconHrefForHost as v}from"../shared/intent-values.js";import{SlottedIconController as I}from"../shared/slotted-icon-controller.js";import{renderSpriteIcon as C}from"../shared/svgs/render-sprite-icon.js";import{detectDatePattern as P,parseDateInput as S,formatDateForLocale as d}from"./date-locale.js";import{getPhoneLocalities as $,parsePhoneInput as w,formatPhoneForLocale as L}from"./tel-locale.js";let s=class extends y{constructor(){super(...arguments),this.internals=this.attachInternals(),this.theInput=T(),this.iconSlot=new I(this),this.formCtrl=new x({host:this,internals:this.internals,getFormValue:()=>this.value||null,getValidity:()=>this._getValidity(),getValidationAnchor:()=>this.theInput.value??this,onReset:()=>{this.value="",this._dateDisplayText="",this._dateManaged=!1,this._telDisplayText="",this._telManaged=!1,this._hasVisibleError=!1},onRestore:e=>{this.value=e,this.inputType==="date"&&e&&this._restoreDateDisplay(e),this.inputType==="tel"&&e&&this._restoreTelDisplay(e)},onDisabled:e=>{this.disabled=e}}),this.formItemDescription=new M({host:this,getTarget:()=>this.theInput.value}),this._hasVisibleError=!1,this._datePattern=null,this._dateDisplayText="",this._dateManaged=!1,this._phoneLocalitiesCache=null,this._telDisplayText="",this._telManaged=!1,this.fieldName="",this.icon="",this.iconLabel="",this.inputType="text",this.forceLowercase=!1,this.value="",this.name="",this.required=!1,this.requiredMessage="",this.validationMessage="",this.disabled=!1,this.readonly=!1,this._trackVisibleError=e=>{const t=e.detail;this._hasVisibleError=!t.valid}}_getDatePattern(){return this._datePattern||(this._datePattern=P()),this._datePattern}_getPhoneLocalities(){if(!this._phoneLocalitiesCache){const e=this.telLocalities?this.telLocalities.trim().split(/\s+/):void 0;this._phoneLocalitiesCache=$(e)}return this._phoneLocalitiesCache}get _nativeInputType(){return this.inputType==="date"?"text":this.inputType}get _effectiveInputmode(){if(this.inputmode)return this.inputmode;switch(this.inputType){case"email":return"email";case"url":return"url";case"tel":return"tel";case"number":return"decimal";case"date":return"numeric";default:return}}get _displayValue(){return this.inputType==="date"?this._dateDisplayText:this.inputType==="tel"?this._telDisplayText:this.value}get _effectivePlaceholder(){if(this.placeholder!==void 0)return this.placeholder;if(this.inputType==="date")return this._getDatePattern().placeholder;if(this.inputType==="tel"){const e=this._getPhoneLocalities();return e.length>0?e[0].placeholder:void 0}}handleInput(e){const t=e.target;if(this.readonly){t.value=this._displayValue;return}let i=t.value;if(this.inputType==="date"){const a=i.replace(/[^\d/\-.\s]/g,"");if(a!==i){const l=i.length-a.length,o=Math.max(0,(t.selectionStart??a.length)-l);t.value=a,t.setSelectionRange(o,o),i=a}this._dateDisplayText=i,this._dateManaged=!0,i||(this.value="",this._syncInput());return}if(this.inputType==="tel"){const a=i.replace(/[^\d+\-.()\s]/g,"");if(a!==i){const l=i.length-a.length,o=Math.max(0,(t.selectionStart??a.length)-l);t.value=a,t.setSelectionRange(o,o),i=a}this._telDisplayText=i,this._telManaged=!0,i||(this.value="",this._syncInput());return}this.forceLowercase&&(i=i.toLowerCase()),this.value=t.value=i,this._syncInput()}_syncInput(){this._hasVisibleError?this.formCtrl.syncValue():this.formCtrl.syncValueSilently(),this.emitValueChanged(this.value)}_handleBlur(){this.inputType==="date"&&this._finalizeDateValue(),this.inputType==="tel"&&this._finalizeTelValue(),this.formCtrl.syncValue()}_finalizeDateValue(){const e=this._dateDisplayText;if(!e.trim()){this.value="",this._dateDisplayText="",this._dateManaged=!1,this.emitValueChanged(this.value);return}const t=this._getDatePattern(),i=S(e,t);i?(this._dateDisplayText=d(i,t),this.value=i.toString()):this.value=e,this._dateManaged=!0,this.requestUpdate(),this.emitValueChanged(this.value)}_finalizeTelValue(){const e=this._telDisplayText;if(!e.trim()){this.value="",this._telDisplayText="",this._telManaged=!1,this.emitValueChanged(this.value);return}const t=this._getPhoneLocalities(),i=w(e,t);i?(this._telDisplayText=i.displayText,this.value=i.e164):this.value=e,this._telManaged=!0,this.requestUpdate(),this.emitValueChanged(this.value)}_getValidity(){if(this.inputType==="date")return this._getDateValidity();if(this.inputType==="tel")return this._getTelValidity();const e=this.theInput.value;if(e&&!e.validity.valid){const t=e.validity,i={valueMissing:t.valueMissing,typeMismatch:t.typeMismatch,patternMismatch:t.patternMismatch,tooLong:t.tooLong,tooShort:t.tooShort,rangeUnderflow:t.rangeUnderflow,rangeOverflow:t.rangeOverflow,stepMismatch:t.stepMismatch,badInput:t.badInput};return{flags:i,message:this._getFriendlyMessage(i)}}return this.required&&!this.value?{flags:{valueMissing:!0},message:this.requiredMessage||"Please fill out this field."}:null}_getFriendlyMessage(e){if(e.valueMissing)return this.requiredMessage||"Please fill out this field.";if(e.typeMismatch){if(this.validationMessage)return this.validationMessage;switch(this.inputType){case"email":return"Please enter a valid email address.";case"url":return"Please enter a valid URL.";case"number":return"Please enter a valid number.";case"tel":return"Please enter a valid phone number.";default:return"Please enter a valid value."}}return e.patternMismatch?this.validationMessage||"Please match the requested format.":e.tooShort?`Must be at least ${this.minlength} characters.`:e.tooLong?`Must be no more than ${this.maxlength} characters.`:e.rangeUnderflow?`Value must be ${this.min} or greater.`:e.rangeOverflow?`Value must be ${this.max} or less.`:(e.stepMismatch||e.badInput,"Please enter a valid value.")}_getDateValidity(){if(this.required&&!this.value)return{flags:{valueMissing:!0},message:this.requiredMessage||"Please fill out this field."};if(!this.value)return null;let e;try{e=Temporal.PlainDate.from(this.value)}catch{return{flags:{typeMismatch:!0},message:this.validationMessage||"Please enter a valid date."}}if(this.min)try{const t=Temporal.PlainDate.from(this.min);if(Temporal.PlainDate.compare(e,t)<0){const i=this._getDatePattern(),a=d(t,i);return{flags:{rangeUnderflow:!0},message:`Date must be ${a} or later.`}}}catch{}if(this.max)try{const t=Temporal.PlainDate.from(this.max);if(Temporal.PlainDate.compare(e,t)>0){const i=this._getDatePattern(),a=d(t,i);return{flags:{rangeOverflow:!0},message:`Date must be ${a} or earlier.`}}}catch{}return null}_getTelValidity(){return this.required&&!this.value?{flags:{valueMissing:!0},message:this.requiredMessage||"Please fill out this field."}:this.value?/^\+\d+$/.test(this.value)?null:{flags:{typeMismatch:!0},message:this.validationMessage||"Please enter a valid phone number."}:null}focus(e){this.focusResolvedElementAfterUpdate(()=>this.theInput.value,e)}setFormItemDescription(e){this.formItemDescription.setDescription(e)}validate(){this.formCtrl.validate()}checkValidity(){return this.formCtrl.checkValidity()}formResetCallback(){this.formCtrl.handleFormReset()}formStateRestoreCallback(e){this.formCtrl.handleFormStateRestore(e)}formDisabledCallback(e){this.formCtrl.handleFormDisabled(e)}connectedCallback(){super.connectedCallback(),this.addEventListener("validity-changed",this._trackVisibleError),this.inputType==="date"&&this.value&&this._restoreDateDisplay(this.value),this.inputType==="tel"&&this.value&&this._restoreTelDisplay(this.value)}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("validity-changed",this._trackVisibleError)}updated(e){super.updated(e),e.has("value")&&this.inputType==="date"&&!this._dateManaged&&this._restoreDateDisplay(this.value),e.has("value")&&this.inputType==="tel"&&!this._telManaged&&this._restoreTelDisplay(this.value),e.has("telLocalities")&&(this._phoneLocalitiesCache=null),this._dateManaged=!1,this._telManaged=!1}_restoreDateDisplay(e){if(!e){this._dateDisplayText="";return}try{const t=Temporal.PlainDate.from(e),i=this._getDatePattern();this._dateDisplayText=d(t,i)}catch{this._dateDisplayText=e}}_restoreTelDisplay(e){if(!e){this._telDisplayText="";return}const t=this._getPhoneLocalities();this._telDisplayText=L(e,t)}_handleIconClick(){this.disabled||!(this.hasIconSlotContent||v(this.icon,this).length>0)||this.dispatchEvent(new CustomEvent("icon-clicked",{bubbles:!0,composed:!0}))}get hasIconSlotContent(){return this.iconSlot.hasSlottedIcon(":scope > :not([slot]), :scope > [slot='']")}_getIconButtonLabel(){const e=this.iconLabel.trim();if(e)return e;const t=this.icon.trim();return t?`${this._humanizeIconName(t)} action`:"Input icon action"}_humanizeIconName(e){const t=e.replace(/[-_]+/gu," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):"Icon"}render(){const e=this.inputType==="date",t=this.inputType==="number",i=this.inputType==="tel",a=e||t||i,l=v(this.icon,this),o=this.hasIconSlotContent,u=o||l.length>0,m=this._getIconButtonLabel();return c`
|
|
2
2
|
<div class="esp-field">
|
|
3
3
|
<input
|
|
4
4
|
id=${this.fieldName}
|
|
@@ -32,7 +32,7 @@ var r=function(p,e,t,i){var a=arguments.length,l=a<3?e:i===null?i=Object.getOwnP
|
|
|
32
32
|
${f(this.iconSlot.slotRef)}
|
|
33
33
|
@slotchange=${this.iconSlot.handleSlotChange}
|
|
34
34
|
></slot>
|
|
35
|
-
${!o&&l?
|
|
35
|
+
${!o&&l?C(l):b}
|
|
36
36
|
</button>
|
|
37
37
|
`:c`
|
|
38
38
|
<span class="icon-slot-probe" hidden>
|
|
@@ -43,7 +43,7 @@ var r=function(p,e,t,i){var a=arguments.length,l=a<3?e:i===null?i=Object.getOwnP
|
|
|
43
43
|
</span>
|
|
44
44
|
`}
|
|
45
45
|
</div>
|
|
46
|
-
`}};s.formAssociated=!0,s.styles=[...
|
|
46
|
+
`}};s.formAssociated=!0,s.styles=[...y.styles,_`
|
|
47
47
|
.esp-field {
|
|
48
48
|
margin: 1px;
|
|
49
49
|
display: grid;
|
|
@@ -88,4 +88,4 @@ var r=function(p,e,t,i){var a=arguments.length,l=a<3?e:i===null?i=Object.getOwnP
|
|
|
88
88
|
}
|
|
89
89
|
}
|
|
90
90
|
}
|
|
91
|
-
`],r([
|
|
91
|
+
`],r([g()],s.prototype,"_dateDisplayText",void 0),r([g()],s.prototype,"_telDisplayText",void 0),r([n({attribute:"field-name",type:String})],s.prototype,"fieldName",void 0),r([n({type:String})],s.prototype,"icon",void 0),r([n({attribute:"icon-label",type:String})],s.prototype,"iconLabel",void 0),r([n({attribute:"input-type",type:String})],s.prototype,"inputType",void 0),r([n({type:String})],s.prototype,"placeholder",void 0),r([n({attribute:"force-lowercase",type:Boolean})],s.prototype,"forceLowercase",void 0),r([n({type:String})],s.prototype,"value",void 0),r([n({type:String,reflect:!0})],s.prototype,"name",void 0),r([n({type:Boolean,reflect:!0})],s.prototype,"required",void 0),r([n({attribute:"required-message"})],s.prototype,"requiredMessage",void 0),r([n({attribute:"validation-message"})],s.prototype,"validationMessage",void 0),r([n({type:Boolean,reflect:!0})],s.prototype,"disabled",void 0),r([n({type:Boolean,reflect:!0})],s.prototype,"readonly",void 0),r([n({type:String})],s.prototype,"pattern",void 0),r([n({type:Number})],s.prototype,"minlength",void 0),r([n({type:Number})],s.prototype,"maxlength",void 0),r([n({type:String})],s.prototype,"min",void 0),r([n({type:String})],s.prototype,"max",void 0),r([n({type:Number})],s.prototype,"step",void 0),r([n({type:String})],s.prototype,"inputmode",void 0),r([n({attribute:"tel-localities",type:String})],s.prototype,"telLocalities",void 0),s=r([D("esp-input")],s);export{s as EspalierInput};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var a=function(c,t,e,s){var o=arguments.length,i=o<3?t:s===null?s=Object.getOwnPropertyDescriptor(t,e):s,n;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(c,t,e,s);else for(var l=c.length-1;l>=0;l--)(n=c[l])&&(i=(o<3?n(i):o>3?n(t,e,i):n(t,e))||i);return o>3&&i&&Object.defineProperty(t,e,i),i};import{createRef as u}from"lit/directives/ref.js";import{EspalierElementBase as d}from"../shared/esp-element-base.js";import{property as h,state as m}from"lit/decorators.js";import{EspalierPickerItem as f}from"./esp-picker-item.js";import{PopoverController as g}from"../shared/popover-controller.js";import{FormFieldController as v}from"../shared/form-field-controller.js";class r extends d{constructor(){super(...arguments),this.internals=this.attachInternals(),this.formCtrl=new v({host:this,internals:this.internals,getFormValue:()=>this.getPickerFormValue(),getValidity:()=>this.getPickerValidity(),onReset:()=>this.handlePickerReset(),onRestore:t=>this.handlePickerRestore(t),onDisabled:t=>{this.disabled=t}}),this._showOptions=!1,this.itemsSlot=u(),this.pickerMenu=u(),this.theInput=u(),this._lastViewportHeight=0,this.popoverCtrl=new g({host:this,closeStrategy:"source-identity",isOpen:()=>this._showOptions,onShouldClose:()=>{this.showOptions=!1},onPositionUpdate:()=>{this.pickerMenu.value?.updatePosition(this);const t=window.innerHeight||document.documentElement.clientHeight;if(this._lastViewportHeight!==0&&t!==this._lastViewportHeight){const e=this._lastViewportHeight-t;e>=r.KEYBOARD_THRESHOLD?(this._scrollToContainPopover(),this._lastViewportHeight=t):e<0&&(this._lastViewportHeight=t)}},getInsideElements:()=>[this.pickerMenu.value??null],onOutsideClick:()=>{this.showOptions=!1}}),this.name="",this.required=!1,this.requiredMessage="",this.disabled=!1,this.pickerItems=[],this.placeholder="Choose...",this.width="",this._slotExtractPending=!1}getPickerFormValue(){return null}getPickerValidity(){return null}handlePickerReset(){}handlePickerRestore(t){}formResetCallback(){this.formCtrl.handleFormReset()}formStateRestoreCallback(t){this.formCtrl.handleFormStateRestore(t)}formDisabledCallback(t){this.formCtrl.handleFormDisabled(t)}get showOptions(){return this._showOptions}set showOptions(t){if(t&&this.disabled)return;this._showOptions=t;const e=this.theInput.value;e&&(e.ariaExpanded=String(t)),t&&this.pickerMenu.value?(this.popoverCtrl.publishCloseOthers(),this.pickerMenu.value.positionSelf(this),this._lastViewportHeight=window.innerHeight||document.documentElement.clientHeight,this.clearActiveDescendant(),this.popoverCtrl.startTracking(),this.popoverCtrl.startOutsideClick()):!t&&this.pickerMenu.value&&(this.popoverCtrl.stopTracking(),this.popoverCtrl.stopOutsideClick(),this.pickerMenu.value.hideMenu(),this.clearActiveDescendant(),this._lastViewportHeight=0)}focus(){this.theInput.value?.focus()}validate(){this.formCtrl.validate()}checkValidity(){return this.formCtrl.checkValidity()}updateActiveDescendant(){const t=this.theInput.value;if(!t||!this.pickerMenu.value)return;const e=this.pickerMenu.value.getHighlightedElement();t.ariaActiveDescendantElement=e}clearActiveDescendant(){const t=this.theInput.value;t&&(t.ariaActiveDescendantElement=null)}_scrollToContainPopover(){const t=this.pickerMenu.value;if(!t)return;const e=t.getBoundingClientRect(),s=this.getBoundingClientRect(),o=window.innerHeight||document.documentElement.clientHeight,i=Math.min(s.top,e.top),n=Math.max(s.bottom,e.bottom),l=window.matchMedia("(prefers-reduced-motion: reduce)").matches?"auto":"smooth";if(n>o){const p=n-o;window.scrollBy({top:p+8,behavior:l}),requestAnimationFrame(()=>{this.pickerMenu.value?.updatePosition(this)})}else i<0&&(window.scrollBy({top:i-8,behavior:l}),requestAnimationFrame(()=>{this.pickerMenu.value?.updatePosition(this)}))}updated(t){super.updated(t),t.has("width")&&(this.width?this.style.width=this.width:this.style.removeProperty("width"))}firstUpdated(t){super.firstUpdated(t);const e=this.theInput.value;if(e&&(e.role="combobox",e.ariaHasPopup="listbox",e.ariaExpanded="false",e.ariaAutoComplete="none",this.pickerMenu.value)){const o=e;o.ariaControlsElements=[this.pickerMenu.value]}const s=this.itemsSlot.value;s&&(this.extractSlotItems(s),s.addEventListener("slotchange",()=>this.extractSlotItems(s)))}extractSlotItems(t){this._slotExtractPending||(this._slotExtractPending=!0,queueMicrotask(()=>{this._slotExtractPending=!1;const e=t.assignedElements();if(e.length===0)return;const s=[];for(const o of e){if(!(o instanceof f))throw new Error(`Picker items must be of type esp-picker-item, but got <${o.tagName.toLowerCase()}>`);const i=o,n=Array.from(i.childNodes),l=n.length>0?n.map(p=>p.cloneNode(!0)):void 0;s.push({text:i.text||i.getAttribute("text")||i.textContent?.trim()||"",value:i.value||i.getAttribute("value")||"",selected:i.selected||i.hasAttribute("selected"),icon:i.icon||i.getAttribute("icon")||"",styles:i.styles,slotNodes:l})}this.pickerItems=s;for(const o of e)o.remove()}))}}r.formAssociated=!0,r.KEYBOARD_THRESHOLD=150,a([m()],r.prototype,"showOptions",null),a([h({type:String,reflect:!0})],r.prototype,"name",void 0),a([h({type:Boolean,reflect:!0})],r.prototype,"required",void 0),a([h({attribute:"required-message"})],r.prototype,"requiredMessage",void 0),a([h({type:Boolean,reflect:!0})],r.prototype,"disabled",void 0),a([h({type:Array})],r.prototype,"pickerItems",void 0),a([h({type:String})],r.prototype,"placeholder",void 0),a([h({type:String})],r.prototype,"width",void 0);export{r as EspalierPickerBase};
|
|
1
|
+
var a=function(c,t,e,s){var o=arguments.length,i=o<3?t:s===null?s=Object.getOwnPropertyDescriptor(t,e):s,n;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(c,t,e,s);else for(var l=c.length-1;l>=0;l--)(n=c[l])&&(i=(o<3?n(i):o>3?n(t,e,i):n(t,e))||i);return o>3&&i&&Object.defineProperty(t,e,i),i};import{createRef as u}from"lit/directives/ref.js";import{EspalierElementBase as d}from"../shared/esp-element-base.js";import{property as h,state as m}from"lit/decorators.js";import{EspalierPickerItem as f}from"./esp-picker-item.js";import{PopoverController as g}from"../shared/popover-controller.js";import{FormFieldController as v}from"../shared/form-field-controller.js";import{FormFieldDescriptionController as w}from"../shared/form-field-description-controller.js";class r extends d{constructor(){super(...arguments),this.internals=this.attachInternals(),this.formCtrl=new v({host:this,internals:this.internals,getFormValue:()=>this.getPickerFormValue(),getValidity:()=>this.getPickerValidity(),onReset:()=>this.handlePickerReset(),onRestore:t=>this.handlePickerRestore(t),onDisabled:t=>{this.disabled=t}}),this.formItemDescription=new w({host:this,getTarget:()=>this.theInput.value}),this._showOptions=!1,this.itemsSlot=u(),this.pickerMenu=u(),this.theInput=u(),this._lastViewportHeight=0,this.popoverCtrl=new g({host:this,closeStrategy:"source-identity",isOpen:()=>this._showOptions,onShouldClose:()=>{this.showOptions=!1},onPositionUpdate:()=>{this.pickerMenu.value?.updatePosition(this);const t=window.innerHeight||document.documentElement.clientHeight;if(this._lastViewportHeight!==0&&t!==this._lastViewportHeight){const e=this._lastViewportHeight-t;e>=r.KEYBOARD_THRESHOLD?(this._scrollToContainPopover(),this._lastViewportHeight=t):e<0&&(this._lastViewportHeight=t)}},getInsideElements:()=>[this.pickerMenu.value??null],onOutsideClick:()=>{this.showOptions=!1}}),this.name="",this.required=!1,this.requiredMessage="",this.disabled=!1,this.pickerItems=[],this.placeholder="Choose...",this.width="",this._slotExtractPending=!1}getPickerFormValue(){return null}getPickerValidity(){return null}handlePickerReset(){}handlePickerRestore(t){}formResetCallback(){this.formCtrl.handleFormReset()}formStateRestoreCallback(t){this.formCtrl.handleFormStateRestore(t)}formDisabledCallback(t){this.formCtrl.handleFormDisabled(t)}get showOptions(){return this._showOptions}set showOptions(t){if(t&&this.disabled)return;this._showOptions=t;const e=this.theInput.value;e&&(e.ariaExpanded=String(t)),t&&this.pickerMenu.value?(this.popoverCtrl.publishCloseOthers(),this.pickerMenu.value.positionSelf(this),this._lastViewportHeight=window.innerHeight||document.documentElement.clientHeight,this.clearActiveDescendant(),this.popoverCtrl.startTracking(),this.popoverCtrl.startOutsideClick()):!t&&this.pickerMenu.value&&(this.popoverCtrl.stopTracking(),this.popoverCtrl.stopOutsideClick(),this.pickerMenu.value.hideMenu(),this.clearActiveDescendant(),this._lastViewportHeight=0)}focus(){this.theInput.value?.focus()}setFormItemDescription(t){this.formItemDescription.setDescription(t)}validate(){this.formCtrl.validate()}checkValidity(){return this.formCtrl.checkValidity()}updateActiveDescendant(){const t=this.theInput.value;if(!t||!this.pickerMenu.value)return;const e=this.pickerMenu.value.getHighlightedElement();t.ariaActiveDescendantElement=e}clearActiveDescendant(){const t=this.theInput.value;t&&(t.ariaActiveDescendantElement=null)}_scrollToContainPopover(){const t=this.pickerMenu.value;if(!t)return;const e=t.getBoundingClientRect(),s=this.getBoundingClientRect(),o=window.innerHeight||document.documentElement.clientHeight,i=Math.min(s.top,e.top),n=Math.max(s.bottom,e.bottom),l=window.matchMedia("(prefers-reduced-motion: reduce)").matches?"auto":"smooth";if(n>o){const p=n-o;window.scrollBy({top:p+8,behavior:l}),requestAnimationFrame(()=>{this.pickerMenu.value?.updatePosition(this)})}else i<0&&(window.scrollBy({top:i-8,behavior:l}),requestAnimationFrame(()=>{this.pickerMenu.value?.updatePosition(this)}))}updated(t){super.updated(t),t.has("width")&&(this.width?this.style.width=this.width:this.style.removeProperty("width"))}firstUpdated(t){super.firstUpdated(t);const e=this.theInput.value;if(e&&(e.role="combobox",e.ariaHasPopup="listbox",e.ariaExpanded="false",e.ariaAutoComplete="none",this.pickerMenu.value)){const o=e;o.ariaControlsElements=[this.pickerMenu.value]}const s=this.itemsSlot.value;s&&(this.extractSlotItems(s),s.addEventListener("slotchange",()=>this.extractSlotItems(s)))}extractSlotItems(t){this._slotExtractPending||(this._slotExtractPending=!0,queueMicrotask(()=>{this._slotExtractPending=!1;const e=t.assignedElements();if(e.length===0)return;const s=[];for(const o of e){if(!(o instanceof f))throw new Error(`Picker items must be of type esp-picker-item, but got <${o.tagName.toLowerCase()}>`);const i=o,n=Array.from(i.childNodes),l=n.length>0?n.map(p=>p.cloneNode(!0)):void 0;s.push({text:i.text||i.getAttribute("text")||i.textContent?.trim()||"",value:i.value||i.getAttribute("value")||"",selected:i.selected||i.hasAttribute("selected"),icon:i.icon||i.getAttribute("icon")||"",styles:i.styles,slotNodes:l})}this.pickerItems=s;for(const o of e)o.remove()}))}}r.formAssociated=!0,r.KEYBOARD_THRESHOLD=150,a([m()],r.prototype,"showOptions",null),a([h({type:String,reflect:!0})],r.prototype,"name",void 0),a([h({type:Boolean,reflect:!0})],r.prototype,"required",void 0),a([h({attribute:"required-message"})],r.prototype,"requiredMessage",void 0),a([h({type:Boolean,reflect:!0})],r.prototype,"disabled",void 0),a([h({type:Array})],r.prototype,"pickerItems",void 0),a([h({type:String})],r.prototype,"placeholder",void 0),a([h({type:String})],r.prototype,"width",void 0);export{r as EspalierPickerBase};
|