@stimulus-plumbers/controllers 0.2.0 → 0.2.2
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/README.md +42 -100
- package/dist/stimulus-plumbers-controllers.es.js +1120 -1437
- package/dist/stimulus-plumbers-controllers.umd.js +1 -1
- package/package.json +2 -2
- package/src/index.js +0 -2
- package/src/controllers/auto_resize_controller.js +0 -17
- package/src/controllers/form-field_controller.js +0 -77
- package/src/controllers/password_reveal_controller.js +0 -9
|
@@ -1 +1 @@
|
|
|
1
|
-
(function(o,d){typeof exports=="object"&&typeof module<"u"?d(exports,require("@hotwired/stimulus")):typeof define=="function"&&define.amd?define(["exports","@hotwired/stimulus"],d):(o=typeof globalThis<"u"?globalThis:o||self,d(o.StimulusPlumbersControllers={},o.Stimulus))})(this,(function(o,d){"use strict";const M=["a[href]","area[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])',"audio[controls]","video[controls]",'[contenteditable]:not([contenteditable="false"])'].join(",");function T(s){return Array.from(s.querySelectorAll(M)).filter(t=>w(t))}function w(s){return!!(s.offsetWidth||s.offsetHeight||s.getClientRects().length)}function k(s){const t=T(s);return t.length>0?(t[0].focus(),!0):!1}class x{constructor(t,e={}){this.container=t,this.previouslyFocused=null,this.options=e,this.isActive=!1}activate(){this.isActive||(this.previouslyFocused=document.activeElement,this.isActive=!0,this.options.initialFocus?this.options.initialFocus.focus():k(this.container),this.container.addEventListener("keydown",this.handleKeyDown))}deactivate(){if(!this.isActive)return;this.isActive=!1,this.container.removeEventListener("keydown",this.handleKeyDown);const t=this.options.returnFocus||this.previouslyFocused;t&&w(t)&&t.focus()}handleKeyDown=t=>{if(t.key==="Escape"&&this.options.escapeDeactivates){t.preventDefault(),this.deactivate();return}if(t.key!=="Tab")return;const e=T(this.container);if(e.length===0)return;const i=e[0],n=e[e.length-1];t.shiftKey&&document.activeElement===i?(t.preventDefault(),n.focus()):!t.shiftKey&&document.activeElement===n&&(t.preventDefault(),i.focus())}}class q{constructor(){this.savedElement=null}save(){this.savedElement=document.activeElement}restore(){this.savedElement&&w(this.savedElement)&&(this.savedElement.focus(),this.savedElement=null)}}function B(s,t){return s.key===t}function K(s){return s.key==="Enter"||s.key===" "}function U(s){return["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(s.key)}function z(s){s.preventDefault(),s.stopPropagation()}class X{constructor(t,e=0){this.items=t,this.currentIndex=e,this.updateTabIndex()}handleKeyDown(t){let e;switch(t.key){case"ArrowDown":case"ArrowRight":t.preventDefault(),e=(this.currentIndex+1)%this.items.length;break;case"ArrowUp":case"ArrowLeft":t.preventDefault(),e=this.currentIndex===0?this.items.length-1:this.currentIndex-1;break;case"Home":t.preventDefault(),e=0;break;case"End":t.preventDefault(),e=this.items.length-1;break;default:return}this.setCurrentIndex(e)}setCurrentIndex(t){t>=0&&t<this.items.length&&(this.currentIndex=t,this.updateTabIndex(),this.items[t].focus())}updateTabIndex(){this.items.forEach((t,e)=>{t.tabIndex=e===this.currentIndex?0:-1})}updateItems(t){this.items=t,this.currentIndex=Math.min(this.currentIndex,t.length-1),this.updateTabIndex()}}const G=(s,t,e)=>{let i=document.querySelector(`[data-live-region="${s}"]`);return i||(i=document.createElement("div"),i.className="sr-only",i.dataset.liveRegion=s,i.setAttribute("aria-live",s),i.setAttribute("aria-atomic",t.toString()),i.setAttribute("aria-relevant",e),document.body.appendChild(i)),i};function D(s,t={}){const{politeness:e="polite",atomic:i=!0,relevant:n="additions text"}=t,a=G(e,i,n);a.textContent="",setTimeout(()=>{a.textContent=s},100)}const E=(s="a11y")=>`${s}-${Math.random().toString(36).substr(2,9)}`,J=(s,t="element")=>s.id||(s.id=E(t)),b=(s,t,e)=>{s.setAttribute(t,e.toString())},Q=(s,t)=>b(s,"aria-expanded",t),Z=(s,t)=>b(s,"aria-pressed",t),tt=(s,t)=>b(s,"aria-checked",t);function et(s,t){b(s,"aria-disabled",t),t?s.setAttribute("tabindex","-1"):s.removeAttribute("tabindex")}const A={menu:"menu",listbox:"listbox",tree:"tree",grid:"grid",dialog:"dialog"},L=(s,t,e)=>{Object.entries(t).forEach(([i,n])=>{s.setAttribute(i,n),e[i]=n})},v=(s,t,e)=>e||!s.hasAttribute(t);function F({trigger:s,target:t,role:e=null,override:i=!1}){const n={trigger:{},target:{}};if(!s||!t)return n;const a={},r={};if(e&&v(t,"role",i)&&(r.role=e),t.id&&(v(s,"aria-controls",i)&&(a["aria-controls"]=t.id),e==="tooltip"&&v(s,"aria-describedby",i)&&(a["aria-describedby"]=t.id)),e&&v(s,"aria-haspopup",i)){const l=A[e]||"true";a["aria-haspopup"]=l}return L(t,r,n.target),L(s,a,n.trigger),n}const S=(s,t)=>{t.forEach(e=>{s.hasAttribute(e)&&s.removeAttribute(e)})};function it({trigger:s,target:t,attributes:e=null}){if(!s||!t)return;S(s,e||["aria-controls","aria-haspopup","aria-describedby"]),(!e||e.includes("role"))&&S(t,["role"])}const I={get visibleOnly(){return!0},hiddenClass:null},V={get top(){return"bottom"},get bottom(){return"top"},get left(){return"right"},get right(){return"left"}};function u({x:s,y:t,width:e,height:i}){return{x:s,y:t,width:e,height:i,left:s,right:s+e,top:t,bottom:t+i}}function O(){return u({x:0,y:0,width:window.innerWidth||document.documentElement.clientWidth,height:window.innerHeight||document.documentElement.clientHeight})}function st(s){if(!(s instanceof HTMLElement))return!1;const t=O(),e=s.getBoundingClientRect(),i=e.top<=t.height&&e.top+e.height>0,n=e.left<=t.width&&e.left+e.width>0;return i&&n}function y(s){return s instanceof Date&&!isNaN(s)}function g(...s){if(s.length===0)throw"Missing values to parse as date";if(s.length===1){const t=new Date(s[0]);if(s[0]&&y(t))return t}else{const t=new Date(...s);if(y(t))return t}}const nt={element:null,visible:null,dispatch:!0,prefix:""};class p{constructor(t,e={}){this.controller=t;const i=Object.assign({},nt,e),{element:n,visible:a,dispatch:r,prefix:l}=i;this.element=n||t.element,this.visibleOnly=typeof a=="boolean"?a:I.visibleOnly,this.visibleCallback=typeof a=="string"?a:null,this.notify=!!r,this.prefix=typeof l=="string"&&l?l:t.identifier}get visible(){return this.element instanceof HTMLElement?this.visibleOnly?st(this.element)&&this.isVisible(this.element):!0:!1}isVisible(t){if(this.visibleCallback){const e=this.findCallback(this.visibleCallback);if(typeof e=="function")return e(t)}return t instanceof HTMLElement?!t.hasAttribute("hidden"):!1}dispatch(t,{target:e=null,prefix:i=null,detail:n=null}={}){if(this.notify)return this.controller.dispatch(t,{target:e||this.element,prefix:i||this.prefix,detail:n})}findCallback(t){if(typeof t!="string")return;const e=this,i=t.split(".").reduce((a,r)=>a&&a[r],e.controller);if(typeof i=="function")return i.bind(e.controller);const n=t.split(".").reduce((a,r)=>a&&a[r],e);if(typeof n=="function")return n.bind(e)}async awaitCallback(t,...e){if(typeof t=="string"&&(t=this.findCallback(t)),typeof t=="function"){const i=t(...e);return i instanceof Promise?await i:i}}}const R=7,W={locales:["default"],today:"",day:null,month:null,year:null,since:null,till:null,disabledDates:[],disabledWeekdays:[],disabledDays:[],disabledMonths:[],disabledYears:[],firstDayOfWeek:0,onNavigated:"navigated"};class at extends p{constructor(t,e={}){super(t,e);const i=Object.assign({},W,e),{onNavigated:n,since:a,till:r,firstDayOfWeek:l}=i;this.onNavigated=n,this.since=g(a),this.till=g(r),this.firstDayOfWeek=0<=l&&l<7?l:W.firstDayOfWeek;const{disabledDates:h,disabledWeekdays:f,disabledDays:c,disabledMonths:m,disabledYears:P}=i;this.disabledDates=Array.isArray(h)?h:[],this.disabledWeekdays=Array.isArray(f)?f:[],this.disabledDays=Array.isArray(c)?c:[],this.disabledMonths=Array.isArray(m)?m:[],this.disabledYears=Array.isArray(P)?P:[];const{today:Et,day:_,month:$,year:N}=i;this.now=g(Et)||new Date,typeof N=="number"&&typeof $=="number"&&typeof _=="number"?this.current=g(N,$,_):this.current=this.now,this.build(),this.enhance()}build(){this.daysOfWeek=this.buildDaysOfWeek(),this.daysOfMonth=this.buildDaysOfMonth(),this.monthsOfYear=this.buildMonthsOfYear()}buildDaysOfWeek(){const t=new Intl.DateTimeFormat(this.localesValue,{weekday:"long"}),e=new Intl.DateTimeFormat(this.localesValue,{weekday:"short"}),i=new Date("2024-10-06"),n=[];for(let a=this.firstDayOfWeek,r=a+7;a<r;a++){const l=new Date(i);l.setDate(i.getDate()+a),n.push({date:l,value:l.getDay(),long:t.format(l),short:e.format(l)})}return n}buildDaysOfMonth(){const t=this.month,e=this.year,i=[],n=c=>({current:this.month===c.getMonth()&&this.year===c.getFullYear(),date:c,value:c.getDate(),month:c.getMonth(),year:c.getFullYear(),iso:c.toISOString()}),a=new Date(e,t).getDay(),r=this.firstDayOfWeek-a;for(let c=r>0?r-7:r;c<0;c++){const m=new Date(e,t,c+1);i.push(n(m))}const l=new Date(e,t+1,0).getDate();for(let c=1;c<=l;c++){const m=new Date(e,t,c);i.push(n(m))}const h=i.length%R,f=h===0?0:R-h;for(let c=1;c<=f;c++){const m=new Date(e,t+1,c);i.push(n(m))}return i}buildMonthsOfYear(){const t=new Intl.DateTimeFormat(this.localesValue,{month:"long"}),e=new Intl.DateTimeFormat(this.localesValue,{month:"short"}),i=new Intl.DateTimeFormat(this.localesValue,{month:"numeric"}),n=[];for(let a=0;a<12;a++){const r=new Date(this.year,a);n.push({date:r,value:r.getMonth(),long:t.format(r),short:e.format(r),numeric:i.format(r)})}return n}get today(){return this.now}set today(t){if(!y(t))return;const e=this.month?this.month:t.getMonth(),i=this.year?this.year:t.getFullYear(),n=e==t.getMonth()&&i==t.getFullYear(),a=this.hasDayValue?this.day:n?t.getDate():1;this.now=new Date(i,e,a).toISOString()}get current(){return typeof this.year=="number"&&typeof this.month=="number"&&typeof this.day=="number"?g(this.year,this.month,this.day):null}set current(t){y(t)&&(this.day=t.getDate(),this.month=t.getMonth(),this.year=t.getFullYear())}navigate=async t=>{if(!y(t))return;const e=this.current,i=t.toISOString(),n=e.toISOString();this.dispatch("navigate",{detail:{from:n,to:i}}),this.current=t,this.build(),await this.awaitCallback(this.onNavigated,{from:n,to:i}),this.dispatch("navigated",{detail:{from:n,to:i}})};step=async(t,e)=>{if(e===0)return;const i=this.current;switch(t){case"year":{i.setFullYear(i.getFullYear()+e);break}case"month":{i.setMonth(i.getMonth()+e);break}case"day":{i.setDate(i.getDate()+e);break}default:return}await this.navigate(i)};isDisabled=t=>{if(!y(t))return!1;if(this.disabledDates.length){const e=t.getTime();for(const i of this.disabledDates)if(e===new Date(i).getTime())return!0}if(this.disabledWeekdays.length){const e=t.getDay(),i=this.daysOfWeek,n=i.findIndex(a=>a.value===e);if(n>=0){const a=i[n];for(const r of this.disabledWeekdays)if(a.value==r||a.short===r||a.long===r)return!0}}if(this.disabledDays.length){const e=t.getDate();for(const i of this.disabledDays)if(e==i)return!0}if(this.disabledMonths.length){const e=t.getMonth(),i=this.monthsOfYear,n=i.findIndex(a=>a.value===e);if(n>=0){const a=i[n];for(const r of this.disabledMonths)if(a.value==r||a.short===r||a.long===r)return!0}}if(this.disabledYears.length){const e=t.getFullYear();for(const i of this.disabledYears)if(e==i)return!0}return!1};isWithinRange=t=>{if(!y(t))return!1;let e=!0;return this.since&&(e=e&&t>=this.since),this.till&&(e=e&&t<=this.till),e};enhance(){const t=this;Object.assign(this.controller,{get calendar(){return{get today(){return t.today},get current(){return t.current},get day(){return t.day},get month(){return t.month},get year(){return t.year},get since(){return t.since},get till(){return t.till},get firstDayOfWeek(){return t.firstDayOfWeek},get disabledDates(){return t.disabledDates},get disabledWeekdays(){return t.disabledWeekdays},get disabledDays(){return t.disabledDays},get disabledMonths(){return t.disabledMonths},get disabledYears(){return t.disabledYears},get daysOfWeek(){return t.daysOfWeek},get daysOfMonth(){return t.daysOfMonth},get monthsOfYear(){return t.monthsOfYear},navigate:async e=>await t.navigate(e),step:async(e,i)=>await t.step(e,i),isDisabled:e=>t.isDisabled(e),isWithinRange:e=>t.isWithinRange(e)}}})}}const rt=(s,t)=>new at(s,t),C={content:null,url:"",reload:"never",stale:3600,onLoad:"contentLoad",onLoading:"contentLoading",onLoaded:"contentLoaded"};class ot extends p{constructor(t,e={}){super(t,e);const i=Object.assign({},C,e),{content:n,url:a,reload:r,stale:l}=i;this.content=n,this.url=a,this.reload=typeof r=="string"?r:C.reload,this.stale=typeof l=="number"?l:C.stale;const{onLoad:h,onLoading:f,onLoaded:c}=i;this.onLoad=h,this.onLoading=f,this.onLoaded=c,this.enhance()}get reloadable(){switch(this.reload){case"never":return!1;case"always":return!0;default:{const t=g(this.loadedAt);return t&&new Date-t>this.stale*1e3}}}contentLoadable=({url:t})=>!!t;contentLoading=async({url:t})=>t?await this.remoteContentLoader(t):await this.contentLoader();contentLoader=async()=>"";remoteContentLoader=async t=>(await fetch(t)).text();load=async()=>{if(this.loadedAt&&!this.reloadable)return;const t=this.findCallback(this.onLoad),e=await this.awaitCallback(t||this.contentLoadable,{url:this.url});if(this.dispatch("load",{detail:{url:this.url}}),!e)return;const i=this.url?await this.remoteContentLoader(this.url):await this.contentLoader();this.dispatch("loading",{detail:{url:this.url}}),i&&(await this.awaitCallback(this.onLoaded,{url:this.url,content:i}),this.loadedAt=new Date().getTime(),this.dispatch("loaded",{detail:{url:this.url,content:i}}))};enhance(){const t=this;Object.assign(this.controller,{load:t.load.bind(t)})}}const lt=(s,t)=>new ot(s,t),ht={trigger:null,events:["click"],onDismissed:"dismissed"};class ct extends p{constructor(t,e={}){super(t,e);const{trigger:i,events:n,onDismissed:a}=Object.assign({},ht,e);this.onDismissed=a,this.trigger=i||this.element,this.events=n,this.enhance(),this.observe()}dismiss=async t=>{const{target:e}=t;e instanceof HTMLElement&&(this.element.contains(e)||this.visible&&(this.dispatch("dismiss"),await this.awaitCallback(this.onDismissed,{target:this.trigger}),this.dispatch("dismissed")))};observe(){this.events.forEach(t=>{window.addEventListener(t,this.dismiss,!0)})}unobserve(){this.events.forEach(t=>{window.removeEventListener(t,this.dismiss,!0)})}enhance(){const t=this,e=t.controller.disconnect.bind(t.controller);Object.assign(this.controller,{disconnect:()=>{t.unobserve(),e()}})}}const Y=(s,t)=>new ct(s,t),dt={anchor:null,events:["click"],placement:"bottom",alignment:"start",onFlipped:"flipped",ariaRole:null,respectMotion:!0};class ut extends p{constructor(t,e={}){super(t,e);const{anchor:i,events:n,placement:a,alignment:r,onFlipped:l,ariaRole:h,respectMotion:f}=Object.assign({},dt,e);this.anchor=i,this.events=n,this.placement=a,this.alignment=r,this.onFlipped=l,this.ariaRole=h,this.respectMotion=f,this.prefersReducedMotion=window.matchMedia("(prefers-reduced-motion: reduce)").matches,this.anchor&&this.element&&F({trigger:this.anchor,target:this.element,role:this.ariaRole}),this.enhance(),this.observe()}flip=async()=>{if(!this.visible)return;this.dispatch("flip"),window.getComputedStyle(this.element).position!="absolute"&&(this.element.style.position="absolute");const e=this.flippedRect(this.anchor.getBoundingClientRect(),this.element.getBoundingClientRect());this.element.style.transition=this.respectMotion&&this.prefersReducedMotion?"none":"";for(const[i,n]of Object.entries(e))this.element.style[i]=n;await this.awaitCallback(this.onFlipped,{target:this.element,placement:e}),this.dispatch("flipped",{detail:{placement:e}})};flippedRect(t,e){const i=this.quadrumRect(t,O()),n=[this.placement,V[this.placement]];let a={};for(;!Object.keys(a).length&&n.length>0;){const r=n.shift();if(!this.biggerRectThan(i[r],e))continue;const l=this.quadrumPlacement(t,r,e),h=this.quadrumAlignment(t,r,l);a.top=`${h.top+window.scrollY}px`,a.left=`${h.left+window.scrollX}px`}return Object.keys(a).length||(a.top="",a.left=""),a}quadrumRect(t,e){return{left:u({x:e.x,y:e.y,width:t.x-e.x,height:e.height}),right:u({x:t.x+t.width,y:e.y,width:e.width-(t.x+t.width),height:e.height}),top:u({x:e.x,y:e.y,width:e.width,height:t.y-e.y}),bottom:u({x:e.x,y:t.y+t.height,width:e.width,height:e.height-(t.y+t.height)})}}quadrumPlacement(t,e,i){switch(e){case"top":return u({x:i.x,y:t.y-i.height,width:i.width,height:i.height});case"bottom":return u({x:i.x,y:t.y+t.height,width:i.width,height:i.height});case"left":return u({x:t.x-i.width,y:i.y,width:i.width,height:i.height});case"right":return u({x:t.x+t.width,y:i.y,width:i.width,height:i.height});default:throw`Unable place at the quadrum, ${e}`}}quadrumAlignment(t,e,i){switch(e){case"top":case"bottom":{let n=t.x;return this.alignment==="center"?n=t.x+t.width/2-i.width/2:this.alignment==="end"&&(n=t.x+t.width-i.width),u({x:n,y:i.y,width:i.width,height:i.height})}case"left":case"right":{let n=t.y;return this.alignment==="center"?n=t.y+t.height/2-i.height/2:this.alignment==="end"&&(n=t.y+t.height-i.height),u({x:i.x,y:n,width:i.width,height:i.height})}default:throw`Unable align at the quadrum, ${e}`}}biggerRectThan(t,e){return t.height>=e.height&&t.width>=e.width}observe(){this.events.forEach(t=>{window.addEventListener(t,this.flip,!0)})}unobserve(){this.events.forEach(t=>{window.removeEventListener(t,this.flip,!0)})}enhance(){const t=this,e=t.controller.disconnect.bind(t.controller);Object.assign(this.controller,{disconnect:()=>{t.unobserve(),e()},flip:t.flip.bind(t)})}}const ft=(s,t)=>new ut(s,t),gt={events:["resize"],boundaries:["top","left","right"],onShifted:"shifted",respectMotion:!0};class mt extends p{constructor(t,e={}){super(t,e);const{onShifted:i,events:n,boundaries:a,respectMotion:r}=Object.assign({},gt,e);this.onShifted=i,this.events=n,this.boundaries=a,this.respectMotion=r,this.prefersReducedMotion=window.matchMedia("(prefers-reduced-motion: reduce)").matches,this.enhance(),this.observe()}shift=async()=>{if(!this.visible)return;this.dispatch("shift");const t=this.overflowRect(this.element.getBoundingClientRect(),this.elementTranslations(this.element)),e=t.left||t.right||0,i=t.top||t.bottom||0;this.element.style.transition=this.respectMotion&&this.prefersReducedMotion?"none":"",this.element.style.transform=`translate(${e}px, ${i}px)`,await this.awaitCallback(this.onShifted,t),this.dispatch("shifted",{detail:t})};overflowRect(t,e){const i={},n=O(),a=u({x:t.x-e.x,y:t.y-e.y,width:t.width,height:t.height});for(const r of this.boundaries){const l=this.directionDistance(a,r,n),h=V[r];l<0?a[h]+l>=n[h]&&!i[h]&&(i[r]=l):i[r]=""}return i}directionDistance(t,e,i){switch(e){case"top":case"left":return t[e]-i[e];case"bottom":case"right":return i[e]-t[e];default:throw`Invalid direction to calcuate distance, ${e}`}}elementTranslations(t){const e=window.getComputedStyle(t),i=e.transform||e.webkitTransform||e.mozTransform;if(i==="none"||typeof i>"u")return{x:0,y:0};const n=i.includes("3d")?"3d":"2d",a=i.match(/matrix.*\((.+)\)/)[1].split(", ");return n==="2d"?{x:Number(a[4]),y:Number(a[5])}:{x:0,y:0}}observe(){this.events.forEach(t=>{window.addEventListener(t,this.shift,!0)})}unobserve(){this.events.forEach(t=>{window.removeEventListener(t,this.shift,!0)})}enhance(){const t=this,e=t.controller.disconnect.bind(t.controller);Object.assign(this.controller,{disconnect:()=>{t.unobserve(),e()},shift:t.shift.bind(t)})}}const yt=(s,t)=>new mt(s,t),H={visibility:"visibility",onShown:"shown",onHidden:"hidden"};class pt extends p{constructor(t,e={}){const{visibility:i,onShown:n,onHidden:a,activator:r}=Object.assign({},H,e),l=typeof i=="string"?i:H.namespace,h=typeof e.visible=="string"?e.visible:"isVisible";(typeof e.visible!="boolean"||e.visible)&&(e.visible=`${l}.${h}`),super(t,e),this.visibility=l,this.visibilityResolver=h,this.onShown=n,this.onHidden=a,this.activator=r instanceof HTMLElement?r:null,this.enhance(),this.element instanceof HTMLElement&&this.activate(this.isVisible(this.element))}isVisible(t){if(!(t instanceof HTMLElement))return!1;const e=I.hiddenClass;return e?!t.classList.contains(e):!t.hasAttribute("hidden")}toggle(t,e){t instanceof HTMLElement&&(e?t.removeAttribute("hidden"):t.setAttribute("hidden",!0))}activate(t){this.activator&&this.activator.setAttribute("aria-expanded",t?"true":"false")}async show(){!(this.element instanceof HTMLElement)||this.isVisible(this.element)||(this.dispatch("show"),this.toggle(this.element,!0),this.activate(!0),await this.awaitCallback(this.onShown,{target:this.element}),this.dispatch("shown"))}async hide(){!(this.element instanceof HTMLElement)||!this.isVisible(this.element)||(this.dispatch("hide"),this.toggle(this.element,!1),this.activate(!1),await this.awaitCallback(this.onHidden,{target:this.element}),this.dispatch("hidden"))}enhance(){const t=this,e={show:t.show.bind(t),hide:t.hide.bind(t)};Object.defineProperty(e,"visible",{get(){return t.isVisible(t.element)}}),Object.defineProperty(e,this.visibilityResolver,{value:t.isVisible.bind(t)}),Object.defineProperty(this.controller,this.visibility,{get(){return e}})}}const j=(s,t)=>new pt(s,t);class bt extends d.Controller{static targets=["modal","overlay"];connect(){if(!this.hasModalTarget){console.error('ModalController requires a modal target. Add data-modal-target="modal" to your element.');return}this.isNativeDialog=this.modalTarget instanceof HTMLDialogElement,this.isNativeDialog?(this.modalTarget.addEventListener("cancel",this.close),this.modalTarget.addEventListener("click",this.handleBackdropClick)):(this.focusTrap=new x(this.modalTarget,{escapeDeactivates:!0}),Y(this,{element:this.modalTarget}))}dismissed=()=>{this.close()};disconnect(){this.isNativeDialog&&(this.modalTarget.removeEventListener("cancel",this.close),this.modalTarget.removeEventListener("click",this.handleBackdropClick))}open(t){if(t&&t.preventDefault(),!!this.hasModalTarget){if(this.isNativeDialog)this.previouslyFocused=document.activeElement,this.modalTarget.showModal();else{const e=this.hasOverlayTarget?this.overlayTarget:this.modalTarget;e.hidden=!1,document.body.style.overflow="hidden",this.focusTrap&&this.focusTrap.activate()}D("Modal opened")}}close(t){if(t&&t.preventDefault(),!!this.hasModalTarget){if(this.isNativeDialog)this.modalTarget.close(),this.previouslyFocused&&this.previouslyFocused.isConnected&&setTimeout(()=>{this.previouslyFocused.focus()},0);else{const e=this.hasOverlayTarget?this.overlayTarget:this.modalTarget;e.hidden=!0,document.body.style.overflow="",this.focusTrap&&this.focusTrap.deactivate()}D("Modal closed")}}handleBackdropClick=t=>{const e=this.modalTarget.getBoundingClientRect();(t.clientY<e.top||t.clientY>e.bottom||t.clientX<e.left||t.clientX>e.right)&&this.close()}}class wt extends d.Controller{static targets=["trigger"];connect(){Y(this,{trigger:this.hasTriggerTarget?this.triggerTarget:null})}}class vt extends d.Controller{static targets=["anchor","reference"];static values={placement:{type:String,default:"bottom"},alignment:{type:String,default:"start"},role:{type:String,default:"tooltip"}};connect(){if(!this.hasReferenceTarget){console.error('FlipperController requires a reference target. Add data-flipper-target="reference" to your element.');return}if(!this.hasAnchorTarget){console.error('FlipperController requires an anchor target. Add data-flipper-target="anchor" to your element.');return}ft(this,{element:this.referenceTarget,anchor:this.anchorTarget,placement:this.placementValue,alignment:this.alignmentValue,ariaRole:this.roleValue})}}class Tt extends d.Controller{static targets=["content","template","loader","activator"];static classes=["hidden"];static values={url:String,loadedAt:String,reload:{type:String,default:"never"},staleAfter:{type:Number,default:3600}};connect(){lt(this,{element:this.hasContentTarget?this.contentTarget:null,url:this.hasUrlValue?this.urlValue:null}),this.hasContentTarget&&j(this,{element:this.contentTarget,activator:this.hasActivatorTarget?this.activatorTarget:null}),this.hasLoaderTarget&&j(this,{element:this.loaderTarget,visibility:"contentLoaderVisibility"})}async show(){await this.visibility.show()}async hide(){await this.visibility.hide()}async shown(){await this.load()}contentLoad(){return this.hasContentTarget&&this.contentTarget.tagName.toLowerCase()==="turbo-frame"?(this.hasUrlValue&&this.contentTarget.setAttribute("src",this.urlValue),!1):!0}async contentLoading(){this.hasLoaderTarget&&await this.contentLoaderVisibility.show()}async contentLoaded({content:t}){this.hasContentTarget&&this.contentTarget.replaceChildren(this.getContentNode(t)),this.hasLoaderTarget&&await this.contentLoaderVisibility.hide()}getContentNode(t){if(typeof t=="string"){const e=document.createElement("template");return e.innerHTML=t,document.importNode(e.content,!0)}return document.importNode(t,!0)}contentLoader(){if(this.hasTemplateTarget)return this.templateTarget instanceof HTMLTemplateElement?this.templateTarget.content:this.templateTarget.innerHTML}}class Dt extends d.Controller{static targets=["daysOfWeek","daysOfMonth"];static classes=["dayOfWeek","dayOfMonth"];static values={locales:{type:Array,default:["default"]},weekdayFormat:{type:String,default:"short"},dayFormat:{type:String,default:"numeric"},daysOfOtherMonth:{type:Boolean,default:!1}};initialize(){rt(this)}connect(){this.draw()}navigated(){this.draw()}draw(){this.drawDaysOfWeek(),this.drawDaysOfMonth()}createDayElement(t,{selectable:e=!1,disabled:i=!1}={}){const n=document.createElement(e?"button":"div");return n.tabIndex=-1,t?n.textContent=t:n.setAttribute("aria-hidden","true"),i&&(n instanceof HTMLButtonElement?n.disabled=!0:n.setAttribute("aria-disabled","true")),n}drawDaysOfWeek(){if(!this.hasDaysOfWeekTarget)return;const t=new Intl.DateTimeFormat(this.localesValue,{weekday:this.weekdayFormatValue}),e=[];for(const n of this.calendar.daysOfWeek){const a=this.createDayElement(t.format(n.date));a.setAttribute("role","columnheader"),a.title=n.long,this.hasDayOfWeekClass&&a.classList.add(...this.dayOfWeekClasses),e.push(a)}const i=document.createElement("div");i.setAttribute("role","row"),i.replaceChildren(...e),this.daysOfWeekTarget.replaceChildren(i)}drawDaysOfMonth(){if(!this.hasDaysOfMonthTarget)return;const t=this.calendar.today,e=new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime(),i=[];for(const a of this.calendar.daysOfMonth){const r=!a.current||this.calendar.isDisabled(a.date)||!this.calendar.isWithinRange(a.date),l=a.current||this.daysOfOtherMonthValue?a.value:"",h=this.createDayElement(l,{selectable:a.current,disabled:r});e===a.date.getTime()&&h.setAttribute("aria-current","date"),this.hasDayOfMonthClass&&h.classList.add(...this.dayOfMonthClasses);const f=document.createElement("time");f.dateTime=a.iso,h.appendChild(f),i.push(h)}const n=[];for(let a=0;a<i.length;a+=7){const r=document.createElement("div");r.setAttribute("role","row");for(const l of i.slice(a,a+7))l.setAttribute("role","gridcell"),r.appendChild(l);n.push(r)}this.daysOfMonthTarget.replaceChildren(...n)}}class Ot extends d.Controller{select(t){if(!(t.target instanceof HTMLElement))return;t.preventDefault();const e=t.target instanceof HTMLTimeElement?t.target.parentElement:t.target;if(e.disabled||e.getAttribute("aria-disabled")==="true")return;this.dispatch("select",{target:e});const i=t.target instanceof HTMLTimeElement?t.target:t.target.querySelector("time");if(!i)return console.error(`unable to locate time element within ${e}`);const n=g(i.dateTime);if(!n)return console.error(`unable to parse ${i.dateTime} found within the time element`);this.dispatch("selected",{target:e,detail:{epoch:n.getTime(),iso:n.toISOString()}})}}class Ct extends d.Controller{static targets=["previous","next","day","month","year","input","display"];static outlets=["calendar-month"];static values={locales:{type:Array,default:["default"]},dayFormat:{type:String,default:"numeric"},monthFormat:{type:String,default:"long"},yearFormat:{type:String,default:"numeric"}};initialize(){this.previous=this.previous.bind(this),this.next=this.next.bind(this)}async calendarMonthOutletConnected(){if(this.hasInputTarget&&this.inputTarget.value){const t=g(this.inputTarget.value);t&&await this.calendarMonthOutlet.calendar.navigate(t)}this.draw()}selected(t){this.hasInputTarget&&(this.inputTarget.value=t.detail.iso),this.hasDisplayTarget&&(this.displayTarget.value=this.formatDate(new Date(t.detail.iso)))}formatDate(t){return new Intl.DateTimeFormat(this.localesValue,{day:this.dayFormatValue,month:this.monthFormatValue,year:this.yearFormatValue}).format(t)}previousTargetConnected(t){t.addEventListener("click",this.previous)}previousTargetDisconnected(t){t.removeEventListener("click",this.previous)}async previous(){await this.calendarMonthOutlet.calendar.step("month",-1),this.draw()}nextTargetConnected(t){t.addEventListener("click",this.next)}nextTargetDisconnected(t){t.removeEventListener("click",this.next)}async next(){await this.calendarMonthOutlet.calendar.step("month",1),this.draw()}draw(){this.drawDay(),this.drawMonth(),this.drawYear()}drawDay(){if(!this.hasDayTarget||!this.hasCalendarMonthOutlet)return;const{year:t,month:e,day:i}=this.calendarMonthOutlet.calendar,n=new Intl.DateTimeFormat(this.localesValue,{day:this.dayFormatValue});this.dayTarget.textContent=n.format(new Date(t,e,i))}drawMonth(){if(!this.hasMonthTarget||!this.hasCalendarMonthOutlet)return;const{year:t,month:e}=this.calendarMonthOutlet.calendar,i=new Intl.DateTimeFormat(this.localesValue,{month:this.monthFormatValue});this.monthTarget.textContent=i.format(new Date(t,e))}drawYear(){if(!this.hasYearTarget||!this.hasCalendarMonthOutlet)return;const{year:t}=this.calendarMonthOutlet.calendar,e=new Intl.DateTimeFormat(this.localesValue,{year:this.yearFormatValue});this.yearTarget.textContent=e.format(new Date(t,0))}}class Mt extends d.Controller{static targets=["content"];connect(){yt(this,{element:this.hasContentTarget?this.contentTarget:null})}}class kt extends d.Controller{static targets=["input"];toggle(){this.inputTarget.type=this.inputTarget.type==="password"?"text":"password"}}class xt extends d.Controller{connect(){this.resize(),this.element.addEventListener("input",this.resize.bind(this))}disconnect(){this.element.removeEventListener("input",this.resize.bind(this))}resize(){this.element.style.height="auto",this.element.style.height=`${this.element.scrollHeight}px`}}o.ARIA_HASPOPUP_VALUES=A,o.AutoResizeController=xt,o.CalendarMonthController=Dt,o.CalendarMonthObserverController=Ot,o.DatepickerController=Ct,o.DismisserController=wt,o.FOCUSABLE_SELECTOR=M,o.FlipperController=vt,o.FocusRestoration=q,o.FocusTrap=x,o.ModalController=bt,o.PannerController=Mt,o.PasswordRevealController=kt,o.PopoverController=Tt,o.RovingTabIndex=X,o.announce=D,o.connectTriggerToTarget=F,o.disconnectTriggerFromTarget=it,o.ensureId=J,o.focusFirst=k,o.generateId=E,o.getFocusableElements=T,o.isActivationKey=K,o.isArrowKey=U,o.isKey=B,o.isVisible=w,o.preventDefault=z,o.setAriaState=b,o.setChecked=tt,o.setDisabled=et,o.setExpanded=Q,o.setPressed=Z,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"})}));
|
|
1
|
+
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require(`@hotwired/stimulus`)):typeof define==`function`&&define.amd?define([`exports`,`@hotwired/stimulus`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.StimulusPlumbersControllers={},e.Stimulus))})(this,function(e,t){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var n=[`a[href]`,`area[href]`,`button:not([disabled])`,`input:not([disabled])`,`select:not([disabled])`,`textarea:not([disabled])`,`[tabindex]:not([tabindex="-1"])`,`audio[controls]`,`video[controls]`,`[contenteditable]:not([contenteditable="false"])`].join(`,`);function r(e){return Array.from(e.querySelectorAll(n)).filter(e=>i(e))}function i(e){return!!(e.offsetWidth||e.offsetHeight||e.getClientRects().length)}function a(e){let t=r(e);return t.length>0?(t[0].focus(),!0):!1}var o=class{constructor(e,t={}){this.container=e,this.previouslyFocused=null,this.options=t,this.isActive=!1}activate(){this.isActive||(this.previouslyFocused=document.activeElement,this.isActive=!0,this.options.initialFocus?this.options.initialFocus.focus():a(this.container),this.container.addEventListener(`keydown`,this.handleKeyDown))}deactivate(){if(!this.isActive)return;this.isActive=!1,this.container.removeEventListener(`keydown`,this.handleKeyDown);let e=this.options.returnFocus||this.previouslyFocused;e&&i(e)&&e.focus()}handleKeyDown=e=>{if(e.key===`Escape`&&this.options.escapeDeactivates){e.preventDefault(),this.deactivate();return}if(e.key!==`Tab`)return;let t=r(this.container);if(t.length===0)return;let n=t[0],i=t[t.length-1];e.shiftKey&&document.activeElement===n?(e.preventDefault(),i.focus()):!e.shiftKey&&document.activeElement===i&&(e.preventDefault(),n.focus())}},s=class{constructor(){this.savedElement=null}save(){this.savedElement=document.activeElement}restore(){this.savedElement&&i(this.savedElement)&&(this.savedElement.focus(),this.savedElement=null)}};function c(e,t){return e.key===t}function l(e){return e.key===`Enter`||e.key===` `}function u(e){return[`ArrowUp`,`ArrowDown`,`ArrowLeft`,`ArrowRight`].includes(e.key)}function d(e){e.preventDefault(),e.stopPropagation()}var f=class{constructor(e,t=0){this.items=e,this.currentIndex=t,this.updateTabIndex()}handleKeyDown(e){let t;switch(e.key){case`ArrowDown`:case`ArrowRight`:e.preventDefault(),t=(this.currentIndex+1)%this.items.length;break;case`ArrowUp`:case`ArrowLeft`:e.preventDefault(),t=this.currentIndex===0?this.items.length-1:this.currentIndex-1;break;case`Home`:e.preventDefault(),t=0;break;case`End`:e.preventDefault(),t=this.items.length-1;break;default:return}this.setCurrentIndex(t)}setCurrentIndex(e){e>=0&&e<this.items.length&&(this.currentIndex=e,this.updateTabIndex(),this.items[e].focus())}updateTabIndex(){this.items.forEach((e,t)=>{e.tabIndex=t===this.currentIndex?0:-1})}updateItems(e){this.items=e,this.currentIndex=Math.min(this.currentIndex,e.length-1),this.updateTabIndex()}},p=(e,t,n)=>{let r=document.querySelector(`[data-live-region="${e}"]`);return r||(r=document.createElement(`div`),r.className=`sr-only`,r.dataset.liveRegion=e,r.setAttribute(`aria-live`,e),r.setAttribute(`aria-atomic`,t.toString()),r.setAttribute(`aria-relevant`,n),document.body.appendChild(r)),r};function m(e,t={}){let{politeness:n=`polite`,atomic:r=!0,relevant:i=`additions text`}=t,a=p(n,r,i);a.textContent=``,setTimeout(()=>{a.textContent=e},100)}var h=(e=`a11y`)=>`${e}-${Math.random().toString(36).substr(2,9)}`,g=(e,t=`element`)=>e.id||=h(t),_=(e,t,n)=>{e.setAttribute(t,n.toString())},v=(e,t)=>_(e,`aria-expanded`,t),y=(e,t)=>_(e,`aria-pressed`,t),b=(e,t)=>_(e,`aria-checked`,t);function x(e,t){_(e,`aria-disabled`,t),t?e.setAttribute(`tabindex`,`-1`):e.removeAttribute(`tabindex`)}var S={menu:`menu`,listbox:`listbox`,tree:`tree`,grid:`grid`,dialog:`dialog`},C=(e,t,n)=>{Object.entries(t).forEach(([t,r])=>{e.setAttribute(t,r),n[t]=r})},w=(e,t,n)=>n||!e.hasAttribute(t);function T({trigger:e,target:t,role:n=null,override:r=!1}){let i={trigger:{},target:{}};if(!e||!t)return i;let a={},o={};if(n&&w(t,`role`,r)&&(o.role=n),t.id&&(w(e,`aria-controls`,r)&&(a[`aria-controls`]=t.id),n===`tooltip`&&w(e,`aria-describedby`,r)&&(a[`aria-describedby`]=t.id)),n&&w(e,`aria-haspopup`,r)){let e=S[n]||`true`;e&&(a[`aria-haspopup`]=e)}return C(t,o,i.target),C(e,a,i.trigger),i}var E=(e,t)=>{t.forEach(t=>{e.hasAttribute(t)&&e.removeAttribute(t)})};function ee({trigger:e,target:t,attributes:n=null}){!e||!t||(E(e,n||[`aria-controls`,`aria-haspopup`,`aria-describedby`]),(!n||n.includes(`role`))&&E(t,[`role`]))}var D={get visibleOnly(){return!0},hiddenClass:null},O={get top(){return`bottom`},get bottom(){return`top`},get left(){return`right`},get right(){return`left`}};function k({x:e,y:t,width:n,height:r}){return{x:e,y:t,width:n,height:r,left:e,right:e+n,top:t,bottom:t+r}}function A(){return k({x:0,y:0,width:window.innerWidth||document.documentElement.clientWidth,height:window.innerHeight||document.documentElement.clientHeight})}function j(e){if(!(e instanceof HTMLElement))return!1;let t=A(),n=e.getBoundingClientRect(),r=n.top<=t.height&&n.top+n.height>0,i=n.left<=t.width&&n.left+n.width>0;return r&&i}function M(e){return e instanceof Date&&!isNaN(e)}function N(...e){if(e.length===0)throw`Missing values to parse as date`;if(e.length===1){let t=new Date(e[0]);if(e[0]&&M(t))return t}else{let t=new Date(...e);if(M(t))return t}}var te={element:null,visible:null,dispatch:!0,prefix:``},P=class{constructor(e,t={}){this.controller=e;let{element:n,visible:r,dispatch:i,prefix:a}=Object.assign({},te,t);this.element=n||e.element,this.visibleOnly=typeof r==`boolean`?r:D.visibleOnly,this.visibleCallback=typeof r==`string`?r:null,this.notify=!!i,this.prefix=typeof a==`string`&&a?a:e.identifier}get visible(){return this.element instanceof HTMLElement?this.visibleOnly?j(this.element)&&this.isVisible(this.element):!0:!1}isVisible(e){if(this.visibleCallback){let t=this.findCallback(this.visibleCallback);if(typeof t==`function`)return t(e)}return e instanceof HTMLElement?!e.hasAttribute(`hidden`):!1}dispatch(e,{target:t=null,prefix:n=null,detail:r=null}={}){if(this.notify)return this.controller.dispatch(e,{target:t||this.element,prefix:n||this.prefix,detail:r})}findCallback(e){if(typeof e!=`string`)return;let t=this,n=e.split(`.`).reduce((e,t)=>e&&e[t],t.controller);if(typeof n==`function`)return n.bind(t.controller);let r=e.split(`.`).reduce((e,t)=>e&&e[t],t);if(typeof r==`function`)return r.bind(t)}async awaitCallback(e,...t){if(typeof e==`string`&&(e=this.findCallback(e)),typeof e==`function`){let n=e(...t);return n instanceof Promise?await n:n}}},F=7,I={locales:[`default`],today:``,day:null,month:null,year:null,since:null,till:null,disabledDates:[],disabledWeekdays:[],disabledDays:[],disabledMonths:[],disabledYears:[],firstDayOfWeek:0,onNavigated:`navigated`},L=class extends P{constructor(e,t={}){super(e,t);let n=Object.assign({},I,t),{onNavigated:r,since:i,till:a,firstDayOfWeek:o}=n;this.onNavigated=r,this.since=N(i),this.till=N(a),this.firstDayOfWeek=0<=o&&o<7?o:I.firstDayOfWeek;let{disabledDates:s,disabledWeekdays:c,disabledDays:l,disabledMonths:u,disabledYears:d}=n;this.disabledDates=Array.isArray(s)?s:[],this.disabledWeekdays=Array.isArray(c)?c:[],this.disabledDays=Array.isArray(l)?l:[],this.disabledMonths=Array.isArray(u)?u:[],this.disabledYears=Array.isArray(d)?d:[];let{today:f,day:p,month:m,year:h}=n;this.now=N(f)||new Date,typeof h==`number`&&typeof m==`number`&&typeof p==`number`?this.current=N(h,m,p):this.current=this.now,this.build(),this.enhance()}build(){this.daysOfWeek=this.buildDaysOfWeek(),this.daysOfMonth=this.buildDaysOfMonth(),this.monthsOfYear=this.buildMonthsOfYear()}buildDaysOfWeek(){let e=new Intl.DateTimeFormat(this.localesValue,{weekday:`long`}),t=new Intl.DateTimeFormat(this.localesValue,{weekday:`short`}),n=new Date(`2024-10-06`),r=[];for(let i=this.firstDayOfWeek,a=i+7;i<a;i++){let a=new Date(n);a.setDate(n.getDate()+i),r.push({date:a,value:a.getDay(),long:e.format(a),short:t.format(a)})}return r}buildDaysOfMonth(){let e=this.month,t=this.year,n=[],r=e=>({current:this.month===e.getMonth()&&this.year===e.getFullYear(),date:e,value:e.getDate(),month:e.getMonth(),year:e.getFullYear(),iso:e.toISOString()}),i=new Date(t,e).getDay(),a=this.firstDayOfWeek-i;for(let i=a>0?a-7:a;i<0;i++){let a=new Date(t,e,i+1);n.push(r(a))}let o=new Date(t,e+1,0).getDate();for(let i=1;i<=o;i++){let a=new Date(t,e,i);n.push(r(a))}let s=n.length%F,c=s===0?0:F-s;for(let i=1;i<=c;i++){let a=new Date(t,e+1,i);n.push(r(a))}return n}buildMonthsOfYear(){let e=new Intl.DateTimeFormat(this.localesValue,{month:`long`}),t=new Intl.DateTimeFormat(this.localesValue,{month:`short`}),n=new Intl.DateTimeFormat(this.localesValue,{month:`numeric`}),r=[];for(let i=0;i<12;i++){let a=new Date(this.year,i);r.push({date:a,value:a.getMonth(),long:e.format(a),short:t.format(a),numeric:n.format(a)})}return r}get today(){return this.now}set today(e){if(!M(e))return;let t=this.month?this.month:e.getMonth(),n=this.year?this.year:e.getFullYear(),r=t==e.getMonth()&&n==e.getFullYear(),i=this.hasDayValue?this.day:r?e.getDate():1;this.now=new Date(n,t,i).toISOString()}get current(){return typeof this.year==`number`&&typeof this.month==`number`&&typeof this.day==`number`?N(this.year,this.month,this.day):null}set current(e){M(e)&&(this.day=e.getDate(),this.month=e.getMonth(),this.year=e.getFullYear())}navigate=async e=>{if(!M(e))return;let t=this.current,n=e.toISOString(),r=t.toISOString();this.dispatch(`navigate`,{detail:{from:r,to:n}}),this.current=e,this.build(),await this.awaitCallback(this.onNavigated,{from:r,to:n}),this.dispatch(`navigated`,{detail:{from:r,to:n}})};step=async(e,t)=>{if(t===0)return;let n=this.current;switch(e){case`year`:n.setFullYear(n.getFullYear()+t);break;case`month`:n.setMonth(n.getMonth()+t);break;case`day`:n.setDate(n.getDate()+t);break;default:return}await this.navigate(n)};isDisabled=e=>{if(!M(e))return!1;if(this.disabledDates.length){let t=e.getTime();for(let e of this.disabledDates)if(t===new Date(e).getTime())return!0}if(this.disabledWeekdays.length){let t=e.getDay(),n=this.daysOfWeek,r=n.findIndex(e=>e.value===t);if(r>=0){let e=n[r];for(let t of this.disabledWeekdays)if(e.value==t||e.short===t||e.long===t)return!0}}if(this.disabledDays.length){let t=e.getDate();for(let e of this.disabledDays)if(t==e)return!0}if(this.disabledMonths.length){let t=e.getMonth(),n=this.monthsOfYear,r=n.findIndex(e=>e.value===t);if(r>=0){let e=n[r];for(let t of this.disabledMonths)if(e.value==t||e.short===t||e.long===t)return!0}}if(this.disabledYears.length){let t=e.getFullYear();for(let e of this.disabledYears)if(t==e)return!0}return!1};isWithinRange=e=>{if(!M(e))return!1;let t=!0;return this.since&&(t&&=e>=this.since),this.till&&(t&&=e<=this.till),t};enhance(){let e=this;Object.assign(this.controller,{get calendar(){return{get today(){return e.today},get current(){return e.current},get day(){return e.day},get month(){return e.month},get year(){return e.year},get since(){return e.since},get till(){return e.till},get firstDayOfWeek(){return e.firstDayOfWeek},get disabledDates(){return e.disabledDates},get disabledWeekdays(){return e.disabledWeekdays},get disabledDays(){return e.disabledDays},get disabledMonths(){return e.disabledMonths},get disabledYears(){return e.disabledYears},get daysOfWeek(){return e.daysOfWeek},get daysOfMonth(){return e.daysOfMonth},get monthsOfYear(){return e.monthsOfYear},navigate:async t=>await e.navigate(t),step:async(t,n)=>await e.step(t,n),isDisabled:t=>e.isDisabled(t),isWithinRange:t=>e.isWithinRange(t)}}})}},R=(e,t)=>new L(e,t),z={content:null,url:``,reload:`never`,stale:3600,onLoad:`contentLoad`,onLoading:`contentLoading`,onLoaded:`contentLoaded`},B=class extends P{constructor(e,t={}){super(e,t);let n=Object.assign({},z,t),{content:r,url:i,reload:a,stale:o}=n;this.content=r,this.url=i,this.reload=typeof a==`string`?a:z.reload,this.stale=typeof o==`number`?o:z.stale;let{onLoad:s,onLoading:c,onLoaded:l}=n;this.onLoad=s,this.onLoading=c,this.onLoaded=l,this.enhance()}get reloadable(){switch(this.reload){case`never`:return!1;case`always`:return!0;default:{let e=N(this.loadedAt);return e&&new Date-e>this.stale*1e3}}}contentLoadable=({url:e})=>!!e;contentLoading=async({url:e})=>e?await this.remoteContentLoader(e):await this.contentLoader();contentLoader=async()=>``;remoteContentLoader=async e=>(await fetch(e)).text();load=async()=>{if(this.loadedAt&&!this.reloadable)return;let e=this.findCallback(this.onLoad),t=await this.awaitCallback(e||this.contentLoadable,{url:this.url});if(this.dispatch(`load`,{detail:{url:this.url}}),!t)return;let n=this.url?await this.remoteContentLoader(this.url):await this.contentLoader();this.dispatch(`loading`,{detail:{url:this.url}}),n&&(await this.awaitCallback(this.onLoaded,{url:this.url,content:n}),this.loadedAt=new Date().getTime(),this.dispatch(`loaded`,{detail:{url:this.url,content:n}}))};enhance(){let e=this;Object.assign(this.controller,{load:e.load.bind(e)})}},V=(e,t)=>new B(e,t),H={trigger:null,events:[`click`],onDismissed:`dismissed`},U=class extends P{constructor(e,t={}){super(e,t);let{trigger:n,events:r,onDismissed:i}=Object.assign({},H,t);this.onDismissed=i,this.trigger=n||this.element,this.events=r,this.enhance(),this.observe()}dismiss=async e=>{let{target:t}=e;t instanceof HTMLElement&&(this.element.contains(t)||this.visible&&(this.dispatch(`dismiss`),await this.awaitCallback(this.onDismissed,{target:this.trigger}),this.dispatch(`dismissed`)))};observe(){this.events.forEach(e=>{window.addEventListener(e,this.dismiss,!0)})}unobserve(){this.events.forEach(e=>{window.removeEventListener(e,this.dismiss,!0)})}enhance(){let e=this,t=e.controller.disconnect.bind(e.controller);Object.assign(this.controller,{disconnect:()=>{e.unobserve(),t()}})}},W=(e,t)=>new U(e,t),G={anchor:null,events:[`click`],placement:`bottom`,alignment:`start`,onFlipped:`flipped`,ariaRole:null,respectMotion:!0},K=class extends P{constructor(e,t={}){super(e,t);let{anchor:n,events:r,placement:i,alignment:a,onFlipped:o,ariaRole:s,respectMotion:c}=Object.assign({},G,t);this.anchor=n,this.events=r,this.placement=i,this.alignment=a,this.onFlipped=o,this.ariaRole=s,this.respectMotion=c,this.prefersReducedMotion=window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,this.anchor&&this.element&&T({trigger:this.anchor,target:this.element,role:this.ariaRole}),this.enhance(),this.observe()}flip=async()=>{if(!this.visible)return;this.dispatch(`flip`),window.getComputedStyle(this.element).position!=`absolute`&&(this.element.style.position=`absolute`);let e=this.flippedRect(this.anchor.getBoundingClientRect(),this.element.getBoundingClientRect());this.element.style.transition=this.respectMotion&&this.prefersReducedMotion?`none`:``;for(let[t,n]of Object.entries(e))this.element.style[t]=n;await this.awaitCallback(this.onFlipped,{target:this.element,placement:e}),this.dispatch(`flipped`,{detail:{placement:e}})};flippedRect(e,t){let n=this.quadrumRect(e,A()),r=[this.placement,O[this.placement]],i={};for(;!Object.keys(i).length&&r.length>0;){let a=r.shift();if(!this.biggerRectThan(n[a],t))continue;let o=this.quadrumPlacement(e,a,t),s=this.quadrumAlignment(e,a,o);i.top=`${s.top+window.scrollY}px`,i.left=`${s.left+window.scrollX}px`}return Object.keys(i).length||(i.top=``,i.left=``),i}quadrumRect(e,t){return{left:k({x:t.x,y:t.y,width:e.x-t.x,height:t.height}),right:k({x:e.x+e.width,y:t.y,width:t.width-(e.x+e.width),height:t.height}),top:k({x:t.x,y:t.y,width:t.width,height:e.y-t.y}),bottom:k({x:t.x,y:e.y+e.height,width:t.width,height:t.height-(e.y+e.height)})}}quadrumPlacement(e,t,n){switch(t){case`top`:return k({x:n.x,y:e.y-n.height,width:n.width,height:n.height});case`bottom`:return k({x:n.x,y:e.y+e.height,width:n.width,height:n.height});case`left`:return k({x:e.x-n.width,y:n.y,width:n.width,height:n.height});case`right`:return k({x:e.x+e.width,y:n.y,width:n.width,height:n.height});default:throw`Unable place at the quadrum, ${t}`}}quadrumAlignment(e,t,n){switch(t){case`top`:case`bottom`:{let t=e.x;return this.alignment===`center`?t=e.x+e.width/2-n.width/2:this.alignment===`end`&&(t=e.x+e.width-n.width),k({x:t,y:n.y,width:n.width,height:n.height})}case`left`:case`right`:{let t=e.y;return this.alignment===`center`?t=e.y+e.height/2-n.height/2:this.alignment===`end`&&(t=e.y+e.height-n.height),k({x:n.x,y:t,width:n.width,height:n.height})}default:throw`Unable align at the quadrum, ${t}`}}biggerRectThan(e,t){return e.height>=t.height&&e.width>=t.width}observe(){this.events.forEach(e=>{window.addEventListener(e,this.flip,!0)})}unobserve(){this.events.forEach(e=>{window.removeEventListener(e,this.flip,!0)})}enhance(){let e=this,t=e.controller.disconnect.bind(e.controller);Object.assign(this.controller,{disconnect:()=>{e.unobserve(),t()},flip:e.flip.bind(e)})}},q=(e,t)=>new K(e,t),J={events:[`resize`],boundaries:[`top`,`left`,`right`],onShifted:`shifted`,respectMotion:!0},Y=class extends P{constructor(e,t={}){super(e,t);let{onShifted:n,events:r,boundaries:i,respectMotion:a}=Object.assign({},J,t);this.onShifted=n,this.events=r,this.boundaries=i,this.respectMotion=a,this.prefersReducedMotion=window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,this.enhance(),this.observe()}shift=async()=>{if(!this.visible)return;this.dispatch(`shift`);let e=this.overflowRect(this.element.getBoundingClientRect(),this.elementTranslations(this.element)),t=e.left||e.right||0,n=e.top||e.bottom||0;this.element.style.transition=this.respectMotion&&this.prefersReducedMotion?`none`:``,this.element.style.transform=`translate(${t}px, ${n}px)`,await this.awaitCallback(this.onShifted,e),this.dispatch(`shifted`,{detail:e})};overflowRect(e,t){let n={},r=A(),i=k({x:e.x-t.x,y:e.y-t.y,width:e.width,height:e.height});for(let e of this.boundaries){let t=this.directionDistance(i,e,r),a=O[e];t<0?i[a]+t>=r[a]&&!n[a]&&(n[e]=t):n[e]=``}return n}directionDistance(e,t,n){switch(t){case`top`:case`left`:return e[t]-n[t];case`bottom`:case`right`:return n[t]-e[t];default:throw`Invalid direction to calcuate distance, ${t}`}}elementTranslations(e){let t=window.getComputedStyle(e),n=t.transform||t.webkitTransform||t.mozTransform;if(n===`none`||n===void 0)return{x:0,y:0};let r=n.includes(`3d`)?`3d`:`2d`,i=n.match(/matrix.*\((.+)\)/)[1].split(`, `);return r===`2d`?{x:Number(i[4]),y:Number(i[5])}:{x:0,y:0}}observe(){this.events.forEach(e=>{window.addEventListener(e,this.shift,!0)})}unobserve(){this.events.forEach(e=>{window.removeEventListener(e,this.shift,!0)})}enhance(){let e=this,t=e.controller.disconnect.bind(e.controller);Object.assign(this.controller,{disconnect:()=>{e.unobserve(),t()},shift:e.shift.bind(e)})}},X=(e,t)=>new Y(e,t),Z={visibility:`visibility`,onShown:`shown`,onHidden:`hidden`},ne=class extends P{constructor(e,t={}){let{visibility:n,onShown:r,onHidden:i,activator:a}=Object.assign({},Z,t),o=typeof n==`string`?n:Z.namespace,s=typeof t.visible==`string`?t.visible:`isVisible`;(typeof t.visible!=`boolean`||t.visible)&&(t.visible=`${o}.${s}`),super(e,t),this.visibility=o,this.visibilityResolver=s,this.onShown=r,this.onHidden=i,this.activator=a instanceof HTMLElement?a:null,this.enhance(),this.element instanceof HTMLElement&&this.activate(this.isVisible(this.element))}isVisible(e){if(!(e instanceof HTMLElement))return!1;let t=D.hiddenClass;return t?!e.classList.contains(t):!e.hasAttribute(`hidden`)}toggle(e,t){if(!(e instanceof HTMLElement))return;let n=D.hiddenClass;n?t?e.classList.remove(n):e.classList.add(n):t?e.removeAttribute(`hidden`):e.setAttribute(`hidden`,!0)}activate(e){this.activator&&this.activator.setAttribute(`aria-expanded`,e?`true`:`false`)}async show(){!(this.element instanceof HTMLElement)||this.isVisible(this.element)||(this.dispatch(`show`),this.toggle(this.element,!0),this.activate(!0),await this.awaitCallback(this.onShown,{target:this.element}),this.dispatch(`shown`))}async hide(){!(this.element instanceof HTMLElement)||!this.isVisible(this.element)||(this.dispatch(`hide`),this.toggle(this.element,!1),this.activate(!1),await this.awaitCallback(this.onHidden,{target:this.element}),this.dispatch(`hidden`))}enhance(){let e=this,t={show:e.show.bind(e),hide:e.hide.bind(e)};Object.defineProperty(t,`visible`,{get(){return e.isVisible(e.element)}}),Object.defineProperty(t,this.visibilityResolver,{value:e.isVisible.bind(e)}),Object.defineProperty(this.controller,this.visibility,{get(){return t}})}},Q=(e,t)=>new ne(e,t),re=class extends t.Controller{static targets=[`modal`,`overlay`];connect(){if(!this.hasModalTarget){console.error(`ModalController requires a modal target. Add data-modal-target="modal" to your element.`);return}this.isNativeDialog=this.modalTarget instanceof HTMLDialogElement,this.isNativeDialog?(this.modalTarget.addEventListener(`cancel`,this.close),this.modalTarget.addEventListener(`click`,this.handleBackdropClick)):(this.focusTrap=new o(this.modalTarget,{escapeDeactivates:!0}),W(this,{element:this.modalTarget}))}dismissed=()=>{this.close()};disconnect(){this.isNativeDialog&&(this.modalTarget.removeEventListener(`cancel`,this.close),this.modalTarget.removeEventListener(`click`,this.handleBackdropClick))}open(e){if(e&&e.preventDefault(),this.hasModalTarget){if(this.isNativeDialog)this.previouslyFocused=document.activeElement,this.modalTarget.showModal();else{let e=this.hasOverlayTarget?this.overlayTarget:this.modalTarget;e.hidden=!1,document.body.style.overflow=`hidden`,this.focusTrap&&this.focusTrap.activate()}m(`Modal opened`)}}close(e){if(e&&e.preventDefault(),this.hasModalTarget){if(this.isNativeDialog)this.modalTarget.close(),this.previouslyFocused&&this.previouslyFocused.isConnected&&setTimeout(()=>{this.previouslyFocused.focus()},0);else{let e=this.hasOverlayTarget?this.overlayTarget:this.modalTarget;e.hidden=!0,document.body.style.overflow=``,this.focusTrap&&this.focusTrap.deactivate()}m(`Modal closed`)}}handleBackdropClick=e=>{let t=this.modalTarget.getBoundingClientRect();(e.clientY<t.top||e.clientY>t.bottom||e.clientX<t.left||e.clientX>t.right)&&this.close()}},ie=class extends t.Controller{static targets=[`trigger`];connect(){W(this,{trigger:this.hasTriggerTarget?this.triggerTarget:null})}},ae=class extends t.Controller{static targets=[`anchor`,`reference`];static values={placement:{type:String,default:`bottom`},alignment:{type:String,default:`start`},role:{type:String,default:`tooltip`}};connect(){if(!this.hasReferenceTarget){console.error(`FlipperController requires a reference target. Add data-flipper-target="reference" to your element.`);return}if(!this.hasAnchorTarget){console.error(`FlipperController requires an anchor target. Add data-flipper-target="anchor" to your element.`);return}q(this,{element:this.referenceTarget,anchor:this.anchorTarget,placement:this.placementValue,alignment:this.alignmentValue,ariaRole:this.roleValue})}},oe=class extends t.Controller{static targets=[`content`,`template`,`loader`,`activator`];static classes=[`hidden`];static values={url:String,loadedAt:String,reload:{type:String,default:`never`},staleAfter:{type:Number,default:3600}};connect(){V(this,{element:this.hasContentTarget?this.contentTarget:null,url:this.hasUrlValue?this.urlValue:null}),this.hasContentTarget&&Q(this,{element:this.contentTarget,activator:this.hasActivatorTarget?this.activatorTarget:null}),this.hasLoaderTarget&&Q(this,{element:this.loaderTarget,visibility:`contentLoaderVisibility`})}async show(){await this.visibility.show()}async hide(){await this.visibility.hide()}async shown(){await this.load()}contentLoad(){return this.hasContentTarget&&this.contentTarget.tagName.toLowerCase()===`turbo-frame`?(this.hasUrlValue&&this.contentTarget.setAttribute(`src`,this.urlValue),!1):!0}async contentLoading(){this.hasLoaderTarget&&await this.contentLoaderVisibility.show()}async contentLoaded({content:e}){this.hasContentTarget&&this.contentTarget.replaceChildren(this.getContentNode(e)),this.hasLoaderTarget&&await this.contentLoaderVisibility.hide()}getContentNode(e){if(typeof e==`string`){let t=document.createElement(`template`);return t.innerHTML=e,document.importNode(t.content,!0)}return document.importNode(e,!0)}contentLoader(){if(this.hasTemplateTarget)return this.templateTarget instanceof HTMLTemplateElement?this.templateTarget.content:this.templateTarget.innerHTML}},$=class extends t.Controller{static targets=[`daysOfWeek`,`daysOfMonth`];static classes=[`dayOfWeek`,`dayOfMonth`];static values={locales:{type:Array,default:[`default`]},weekdayFormat:{type:String,default:`short`},dayFormat:{type:String,default:`numeric`},daysOfOtherMonth:{type:Boolean,default:!1}};initialize(){R(this)}connect(){this.draw()}navigated(){this.draw()}draw(){this.drawDaysOfWeek(),this.drawDaysOfMonth()}createDayElement(e,{selectable:t=!1,disabled:n=!1}={}){let r=document.createElement(t?`button`:`div`);return r.tabIndex=-1,e?r.textContent=e:r.setAttribute(`aria-hidden`,`true`),n&&(r instanceof HTMLButtonElement?r.disabled=!0:r.setAttribute(`aria-disabled`,`true`)),r}drawDaysOfWeek(){if(!this.hasDaysOfWeekTarget)return;let e=new Intl.DateTimeFormat(this.localesValue,{weekday:this.weekdayFormatValue}),t=[];for(let n of this.calendar.daysOfWeek){let r=this.createDayElement(e.format(n.date));r.setAttribute(`role`,`columnheader`),r.title=n.long,this.hasDayOfWeekClass&&r.classList.add(...this.dayOfWeekClasses),t.push(r)}let n=document.createElement(`div`);n.setAttribute(`role`,`row`),n.replaceChildren(...t),this.daysOfWeekTarget.replaceChildren(n)}drawDaysOfMonth(){if(!this.hasDaysOfMonthTarget)return;let e=this.calendar.today,t=new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime(),n=[];for(let e of this.calendar.daysOfMonth){let r=!e.current||this.calendar.isDisabled(e.date)||!this.calendar.isWithinRange(e.date),i=e.current||this.daysOfOtherMonthValue?e.value:``,a=this.createDayElement(i,{selectable:e.current,disabled:r});t===e.date.getTime()&&a.setAttribute(`aria-current`,`date`),this.hasDayOfMonthClass&&a.classList.add(...this.dayOfMonthClasses);let o=document.createElement(`time`);o.dateTime=e.iso,a.appendChild(o),n.push(a)}let r=[];for(let e=0;e<n.length;e+=7){let t=document.createElement(`div`);t.setAttribute(`role`,`row`);for(let r of n.slice(e,e+7))r.setAttribute(`role`,`gridcell`),t.appendChild(r);r.push(t)}this.daysOfMonthTarget.replaceChildren(...r)}},se=class extends t.Controller{select(e){if(!(e.target instanceof HTMLElement))return;e.preventDefault();let t=e.target instanceof HTMLTimeElement?e.target.parentElement:e.target;if(t.disabled||t.getAttribute(`aria-disabled`)===`true`)return;this.dispatch(`select`,{target:t});let n=e.target instanceof HTMLTimeElement?e.target:e.target.querySelector(`time`);if(!n)return console.error(`unable to locate time element within ${t}`);let r=N(n.dateTime);if(!r)return console.error(`unable to parse ${n.dateTime} found within the time element`);this.dispatch(`selected`,{target:t,detail:{epoch:r.getTime(),iso:r.toISOString()}})}},ce=class extends t.Controller{static targets=[`previous`,`next`,`day`,`month`,`year`,`input`,`display`];static outlets=[`calendar-month`];static values={locales:{type:Array,default:[`default`]},dayFormat:{type:String,default:`numeric`},monthFormat:{type:String,default:`long`},yearFormat:{type:String,default:`numeric`}};initialize(){this.previous=this.previous.bind(this),this.next=this.next.bind(this)}async calendarMonthOutletConnected(){if(this.hasInputTarget&&this.inputTarget.value){let e=N(this.inputTarget.value);e&&await this.calendarMonthOutlet.calendar.navigate(e)}this.draw()}selected(e){this.hasInputTarget&&(this.inputTarget.value=e.detail.iso),this.hasDisplayTarget&&(this.displayTarget.value=this.formatDate(new Date(e.detail.iso)))}formatDate(e){return new Intl.DateTimeFormat(this.localesValue,{day:this.dayFormatValue,month:this.monthFormatValue,year:this.yearFormatValue}).format(e)}previousTargetConnected(e){e.addEventListener(`click`,this.previous)}previousTargetDisconnected(e){e.removeEventListener(`click`,this.previous)}async previous(){await this.calendarMonthOutlet.calendar.step(`month`,-1),this.draw()}nextTargetConnected(e){e.addEventListener(`click`,this.next)}nextTargetDisconnected(e){e.removeEventListener(`click`,this.next)}async next(){await this.calendarMonthOutlet.calendar.step(`month`,1),this.draw()}draw(){this.drawDay(),this.drawMonth(),this.drawYear()}drawDay(){if(!this.hasDayTarget||!this.hasCalendarMonthOutlet)return;let{year:e,month:t,day:n}=this.calendarMonthOutlet.calendar,r=new Intl.DateTimeFormat(this.localesValue,{day:this.dayFormatValue});this.dayTarget.textContent=r.format(new Date(e,t,n))}drawMonth(){if(!this.hasMonthTarget||!this.hasCalendarMonthOutlet)return;let{year:e,month:t}=this.calendarMonthOutlet.calendar,n=new Intl.DateTimeFormat(this.localesValue,{month:this.monthFormatValue});this.monthTarget.textContent=n.format(new Date(e,t))}drawYear(){if(!this.hasYearTarget||!this.hasCalendarMonthOutlet)return;let{year:e}=this.calendarMonthOutlet.calendar,t=new Intl.DateTimeFormat(this.localesValue,{year:this.yearFormatValue});this.yearTarget.textContent=t.format(new Date(e,0))}},le=class extends t.Controller{static targets=[`content`];connect(){X(this,{element:this.hasContentTarget?this.contentTarget:null})}};e.ARIA_HASPOPUP_VALUES=S,e.CalendarMonthController=$,e.CalendarMonthObserverController=se,e.DatepickerController=ce,e.DismisserController=ie,e.FOCUSABLE_SELECTOR=n,e.FlipperController=ae,e.FocusRestoration=s,e.FocusTrap=o,e.ModalController=re,e.PannerController=le,e.PopoverController=oe,e.RovingTabIndex=f,e.announce=m,e.connectTriggerToTarget=T,e.disconnectTriggerFromTarget=ee,e.ensureId=g,e.focusFirst=a,e.generateId=h,e.getFocusableElements=r,e.isActivationKey=l,e.isArrowKey=u,e.isKey=c,e.isVisible=i,e.preventDefault=d,e.setAriaState=_,e.setChecked=b,e.setDisabled=x,e.setExpanded=v,e.setPressed=y});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stimulus-plumbers/controllers",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.2",
|
|
4
4
|
"description": "Stimulus controllers following WCAG standards",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
"license": "MIT",
|
|
32
32
|
"repository": {
|
|
33
33
|
"type": "git",
|
|
34
|
-
"url": "https://github.com/
|
|
34
|
+
"url": "https://github.com/ryancyq/stimulus-plumbers",
|
|
35
35
|
"directory": "stimulus"
|
|
36
36
|
},
|
|
37
37
|
"peerDependencies": {
|
package/src/index.js
CHANGED
|
@@ -19,5 +19,3 @@ export { default as CalendarMonthController } from './controllers/calendar_month
|
|
|
19
19
|
export { default as CalendarMonthObserverController } from './controllers/calendar_month_observer_controller.js';
|
|
20
20
|
export { default as DatepickerController } from './controllers/datepicker_controller.js';
|
|
21
21
|
export { default as PannerController } from './controllers/panner_controller.js';
|
|
22
|
-
export { default as PasswordRevealController } from './controllers/password_reveal_controller.js';
|
|
23
|
-
export { default as AutoResizeController } from './controllers/auto_resize_controller.js';
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import { Controller } from '@hotwired/stimulus';
|
|
2
|
-
|
|
3
|
-
export default class extends Controller {
|
|
4
|
-
connect() {
|
|
5
|
-
this.resize();
|
|
6
|
-
this.element.addEventListener('input', this.resize.bind(this));
|
|
7
|
-
}
|
|
8
|
-
|
|
9
|
-
disconnect() {
|
|
10
|
-
this.element.removeEventListener('input', this.resize.bind(this));
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
resize() {
|
|
14
|
-
this.element.style.height = 'auto';
|
|
15
|
-
this.element.style.height = `${this.element.scrollHeight}px`;
|
|
16
|
-
}
|
|
17
|
-
}
|
|
@@ -1,77 +0,0 @@
|
|
|
1
|
-
import { Controller } from '@hotwired/stimulus';
|
|
2
|
-
import { attachDismisser, attachVisibility } from '../plumbers';
|
|
3
|
-
|
|
4
|
-
export default class extends Controller {
|
|
5
|
-
static targets = ['dropdown', 'trigger', 'input'];
|
|
6
|
-
static values = {
|
|
7
|
-
inputPath: { type: String, default: 'detail.value' },
|
|
8
|
-
};
|
|
9
|
-
|
|
10
|
-
initialize() {
|
|
11
|
-
this.update = this.update.bind(this);
|
|
12
|
-
this.expand = this.expand.bind(this);
|
|
13
|
-
this.collapse = this.collapse.bind(this);
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
connect() {
|
|
17
|
-
attachDismisser(this, { events: ['click', 'focus'] });
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
triggerTargetConnected(target) {
|
|
21
|
-
target.addEventListener('click', this.expand);
|
|
22
|
-
target.addEventListener('focus', this.expand);
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
triggerTargetDisconnected(target) {
|
|
26
|
-
target.removeEventListener('click', this.expand);
|
|
27
|
-
target.removeEventListener('focus', this.expand);
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
dropdownTargetConnected(target) {
|
|
31
|
-
attachVisibility(this, { element: target, visibility: 'dropdownVisibility' });
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
async update(event) {
|
|
35
|
-
const value = this.inputPathValue.split('.').reduce((acc, key) => acc && acc[key], event);
|
|
36
|
-
if (this.hasInputTarget) this.updateField(this.inputTarget, value);
|
|
37
|
-
await this.collapse();
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
updateField(element, value) {
|
|
41
|
-
const attr = this.fieldAttribute(element);
|
|
42
|
-
const from = element[attr];
|
|
43
|
-
|
|
44
|
-
this.dispatch('update', { target: element, from, to: value });
|
|
45
|
-
element[attr] = value;
|
|
46
|
-
this.dispatch('updated', { target: element, from, to: value });
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
fieldAttribute(element) {
|
|
50
|
-
switch (element.constructor) {
|
|
51
|
-
case HTMLInputElement:
|
|
52
|
-
case HTMLTextAreaElement:
|
|
53
|
-
case HTMLButtonElement: {
|
|
54
|
-
return 'value';
|
|
55
|
-
}
|
|
56
|
-
default: {
|
|
57
|
-
return 'textContent';
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
async expand(_event) {
|
|
63
|
-
if (!this.hasDropdownTarget || this.dropdownVisibility.visible) return;
|
|
64
|
-
|
|
65
|
-
await this.dropdownVisibility.show();
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
async collapse(_event) {
|
|
69
|
-
if (!this.hasDropdownTarget || !this.dropdownVisibility.visible) return;
|
|
70
|
-
|
|
71
|
-
await this.dropdownVisibility.hide();
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
async dismissed() {
|
|
75
|
-
await this.collapse();
|
|
76
|
-
}
|
|
77
|
-
}
|