UNPKG

@ui-machines/pin-input

Version:

Core logic for the pin-input widget implemented as a state machine

3 lines (2 loc) 7.19 kB
var u=e=>e?"":void 0,g=e=>e?!0:void 0;var O=(()=>{let e=0;return()=>(e++,e.toString(36))})();function f(e){let t=new Set;function o(n){let r=globalThis.requestAnimationFrame(n);t.add(()=>globalThis.cancelAnimationFrame(r))}return o(()=>o(e)),function(){t.forEach(function(n){n()})}}function m(e){var t;return(t=e.nativeEvent)!=null?t:e}var R=["input:not([disabled]):not([type=hidden])","select:not([disabled])","textarea:not([disabled])","button:not([disabled])","embed","iframe","object","a[href]","area[href]","[tabindex]","audio[controls]","video[controls]","*[tabindex]:not([aria-disabled])","[contenteditable]:not([contenteditable=false])","details > summary:first-of-type"].join(",");var v={ArrowLeft:"ArrowRight",ArrowRight:"ArrowLeft",Home:"End",End:"Home"},P={Up:"ArrowUp",Down:"ArrowDown",Esc:"Escape"," ":"Space",",":"Comma",Left:"ArrowLeft",Right:"ArrowRight"};function y(e,t={}){var o;let{dir:n="ltr",orientation:r="horizontal"}=t,{key:l}=e;return l=(o=P[l])!=null?o:l,n==="rtl"&&r==="horizontal"&&l in v&&(l=v[l]),l}function w(e,t){var o;return Array.from((o=e==null?void 0:e.querySelectorAll(t))!=null?o:[])}var s=(e,t)=>({variable:e,reference:t?`var(${e}, ${t})`:`var(${e})`}),D={arrowShadowColor:s("--arrow-shadow-color"),arrowSize:s("--arrow-size"),arrowSizeHalf:s("--arrow-size-half"),arrowBg:s("--arrow-background"),transformOrigin:s("--transform-origin"),arrowOffset:s("--arrow-offset"),boxShadow:s("--arrow-box-shadow")};function k(e){return{button:e,label:e,input:e,output:e,element:e}}var b=k(e=>e);var x=e=>Array.from(Array(e).keys());var z=(()=>{let e=0;return()=>(e++,e.toString(36))})();var E=e=>e.ctrlKey||e.altKey||e.metaKey||e.shiftKey;var i={getDoc:e=>{var t;return(t=e.doc)!=null?t:document},getRootId:e=>`pin-input-${e.uid}`,getInputId:(e,t)=>`pin-input-${e.uid}-${t}`,getRootEl:e=>i.getDoc(e).getElementById(i.getRootId(e)),getElements:e=>w(i.getRootEl(e),`input[data-ownedby=${i.getRootId(e)}]`),getFocusedEl:e=>i.getElements(e)[e.focusedIndex],getFirstInputEl:e=>i.getElements(e)[0]};function I(e,t,o=b){let{context:n}=e;return{value:n.value,focusedIndex:n.focusedIndex,setValue(r){t({type:"SET_VALUE",value:r})},clearValue(){t({type:"CLEAR_VALUE"})},setValueAtIndex(r,l){t({type:"SET_VALUE",value:r,index:l})},focus(){var r;(r=i.getFirstInputEl(n))==null||r.focus()},blur(){var r;n.focusedIndex!==-1&&((r=i.getFirstInputEl(n))==null||r.blur())},containerProps:o.element({"data-part":"container",id:i.getRootId(n),"data-invalid":u(n.invalid),"data-disabled":u(n.disabled),"data-complete":u(n.isValueComplete)}),getInputProps({index:r}){let l=n.type==="numeric"?"tel":"text";return o.input({"data-part":"input",disabled:n.disabled,"data-disabled":u(n.disabled),"data-complete":u(n.isValueComplete),id:i.getInputId(n,r),"data-ownedby":i.getRootId(n),"aria-label":"Please enter your pin code",inputMode:n.otp||n.type==="numeric"?"numeric":"text","aria-invalid":g(n.invalid),"data-invalid":u(n.invalid),type:n.mask?"password":l,value:n.value[r]||"",autoCapitalize:"off",autoComplete:n.otp?"one-time-code":"off",placeholder:n.focusedIndex===r?"":n.placeholder,onChange(a){let c=m(a);if(c.isComposing)return;let d=a.target.value;if(c.inputType==="insertFromPaste"||d.length>2){t({type:"PASTE",value:d}),a.preventDefault();return}c.inputType==="insertText"&&t({type:"INPUT",value:d})},onKeyDown(a){let c=m(a);if(c.isComposing||E(c))return;let d={Backspace(){t("BACKSPACE")},Delete(){t("DELETE")},ArrowLeft(){t("ARROW_LEFT")},ArrowRight(){t("ARROW_RIGHT")}},A=y(a,{dir:n.dir}),p=d[A];p&&(p==null||p(a),a.preventDefault())},onFocus(){t({type:"FOCUS",index:r})},onBlur(){t({type:"BLUR",index:r})}})}}}import{createMachine as S,guards as C,ref as T}from"@ui-machines/core";var{and:L}=C,V=S({id:"pin-input",initial:"unknown",context:{uid:"pin-input",value:[],focusedIndex:-1,placeholder:"\u25CB",otp:!1,type:"numeric"},on:{SET_VALUE:[{guard:"hasIndex",actions:"setValueAtIndex"},{actions:"setValue"}],CLEAR_VALUE:{actions:["clearValue","setFocusIndexToFirst"]}},computed:{valueLength:e=>e.value.length,filledValueLength:e=>e.value.filter(t=>(t==null?void 0:t.trim())!=="").length,isValueComplete:e=>e.valueLength===e.filledValueLength,valueAsString:e=>e.value.join("")},watch:{focusedIndex:"focusInput",value:"invokeOnChange",isValueComplete:"invokeComplete"},states:{unknown:{on:{SETUP:[{guard:"autoFocus",target:"focused",actions:["setupDocument","setupValue","setFocusIndexToFirst"]},{target:"idle",actions:["setupDocument","setupValue"]}]}},idle:{on:{FOCUS:{target:"focused",actions:"setFocusedIndex"}}},focused:{on:{INPUT:[{guard:L("isFinalValue","isValidValue"),actions:"setFocusedValue"},{guard:L("hasValue","isValidValue"),actions:["replaceFocusedValue","setNextFocusedIndex"]},{guard:"isValidValue",actions:["setFocusedValue","setNextFocusedIndex"]}],PASTE:{guard:"isValidValue",actions:["setPastedValue","setLastValueFocusIndex"]},BLUR:{target:"idle",actions:"clearFocusedIndex"},DELETE:{guard:"hasValue",actions:"clearFocusedValue"},ARROW_LEFT:{actions:"setPrevFocusedIndex"},ARROW_RIGHT:{actions:"setNextFocusedIndex"},BACKSPACE:[{guard:"hasValue",actions:"clearFocusedValue"},{actions:["setPrevFocusedIndex","clearFocusedValue"]}]}}}},{guards:{autoFocus:e=>!!e.autoFocus,isValueEmpty:(e,t)=>t.value==="",hasValue:e=>e.value[e.focusedIndex]!=="",isValueComplete:e=>e.isValueComplete,isValidValue:(e,t)=>M(t.value,e.type),isFinalValue:e=>e.filledValueLength+1===e.valueLength&&e.value.findIndex(t=>t.trim()==="")===e.focusedIndex,isLastInputFocused:e=>e.focusedIndex===e.valueLength-1,hasIndex:(e,t)=>t.index!==void 0},actions:{setupDocument:(e,t)=>{e.doc=T(t.doc),e.uid=t.id},setupValue:e=>{f(()=>{let t=i.getElements(e),o=x(t.length).map(()=>"");e.value=Object.assign(o,e.value)})},focusInput:e=>{f(()=>{var t;e.focusedIndex!==-1&&((t=i.getFocusedEl(e))==null||t.focus())})},invokeComplete:e=>{var t;e.isValueComplete&&((t=e.onComplete)==null||t.call(e,Array.from(e.value),e.valueAsString))},invokeOnChange:(e,t)=>{var o;t.type!=="SETUP"&&((o=e.onChange)==null||o.call(e,Array.from(e.value)))},clearFocusedIndex:e=>{e.focusedIndex=-1},setValue:(e,t)=>{h(e,t.value)},setFocusedIndex:(e,t)=>{e.focusedIndex=t.index},setFocusedValue:(e,t)=>{e.value[e.focusedIndex]=t.value},replaceFocusedValue:(e,t)=>{let o=e.value[e.focusedIndex];e.value[e.focusedIndex]=t.value.replace(o,"").charAt(0)},setPastedValue(e,t){f(()=>{let o=t.value.substr(0,e.valueLength);h(e,o.split("").filter(Boolean))})},setValueAtIndex:(e,t)=>{e.value[t.index]=t.value},clearValue:e=>{h(e,"")},clearFocusedValue:e=>{e.value[e.focusedIndex]=""},setFocusIndexToFirst:e=>{e.focusedIndex=0},setNextFocusedIndex:e=>{e.focusedIndex=Math.min(e.focusedIndex+1,e.valueLength-1)},setPrevFocusedIndex:e=>{e.focusedIndex=Math.max(e.focusedIndex-1,0)},setLastValueFocusIndex:e=>{f(()=>{e.focusedIndex=Math.min(e.filledValueLength,e.valueLength-1)})}}}),F={numeric:/^[0-9]+$/,alphabetic:/^[A-Za-z]+$/,alphanumeric:/^[a-zA-Z0-9]+$/i};function M(e,t){var o;return t?!!((o=F[t])==null?void 0:o.test(e)):!0}function h(e,t){for(let o=0;o<e.value.length;o++)if(Array.isArray(t)){if(!t[o])continue;e.value[o]=t[o]}else e.value[o]=t}export{I as connect,V as machine}; //# sourceMappingURL=index.mjs.map