1 line
2.8 KiB
JavaScript
1 line
2.8 KiB
JavaScript
(()=>{(function(){"use strict";function u(e){return Array.from(e.querySelectorAll("[data-tui-inputotp-slot]")).sort((t,n)=>parseInt(t.getAttribute("data-tui-inputotp-index"))-parseInt(n.getAttribute("data-tui-inputotp-index")))}function a(e){e&&(e.focus(),setTimeout(()=>e.select(),0))}function i(e){let t=e.querySelector("[data-tui-inputotp-value-target]"),n=u(e);t&&n.length&&(t.value=n.map(o=>o.value).join(""))}function d(e){let t=u(e);for(let n of t)if(!n.value)return n;return null}function f(e,t){let n=u(e),o=n.indexOf(t);return o>=0&&o<n.length-1?n[o+1]:null}function p(e,t){let n=u(e),o=n.indexOf(t);return o>0?n[o-1]:null}document.addEventListener("input",e=>{if(!e.target.matches("[data-tui-inputotp-slot]"))return;let t=e.target,n=t.closest("[data-tui-inputotp]");if(n){if(t.value===" "){t.value="";return}if(t.value.length>1&&(t.value=t.value.slice(-1)),t.value){let o=f(n,t);o&&a(o)}i(n)}}),document.addEventListener("keydown",e=>{if(!e.target.matches("[data-tui-inputotp-slot]"))return;let t=e.target,n=t.closest("[data-tui-inputotp]");if(n){if(e.key==="Backspace")if(e.preventDefault(),t.value)t.value="",i(n);else{let o=p(n,t);o&&(o.value="",i(n),a(o))}else if(e.key==="ArrowLeft"){e.preventDefault();let o=p(n,t);o&&a(o)}else if(e.key==="ArrowRight"){e.preventDefault();let o=f(n,t);o&&a(o)}}}),document.addEventListener("focus",e=>{if(!e.target.matches("[data-tui-inputotp-slot]"))return;let t=e.target,n=t.closest("[data-tui-inputotp]");if(!n)return;let o=d(n);if(o&&o!==t){a(o);return}setTimeout(()=>t.select(),0)},!0),document.addEventListener("paste",e=>{let t=e.target.closest("[data-tui-inputotp-slot]");if(!t)return;e.preventDefault();let n=t.closest("[data-tui-inputotp]");if(!n)return;let r=(e.clipboardData||window.clipboardData).getData("text").replace(/\s/g,"").split(""),s=u(n),c=s.indexOf(t);for(let l=0;l<r.length&&c+l<s.length;l++)s[c+l].value=r[l];i(n);let v=d(n);a(v||s[Math.min(c+r.length,s.length-1)])}),document.addEventListener("click",e=>{if(!e.target.matches("label[for]"))return;let t=e.target.getAttribute("for"),n=document.getElementById(t);if(!n?.matches("[data-tui-inputotp-value-target]"))return;e.preventDefault();let o=n.closest("[data-tui-inputotp]"),r=u(o);r.length>0&&a(r[0])}),document.addEventListener("reset",e=>{e.target.matches("form")&&e.target.querySelectorAll("[data-tui-inputotp]").forEach(t=>{u(t).forEach(n=>{n.value=""}),i(t)})}),new MutationObserver(()=>{document.querySelectorAll("[data-tui-inputotp]").forEach(e=>{let t=u(e);if(t.length===0)return;let n=e.getAttribute("data-tui-inputotp-value");if(n&&!t[0].value){for(let o=0;o<t.length&&o<n.length;o++)t[o].value||(t[o].value=n[o]);i(e)}e.hasAttribute("autofocus")&&!t.some(o=>o===document.activeElement)&&requestAnimationFrame(()=>{t[0]&&!t.some(o=>o===document.activeElement)&&a(t[0])})})}).observe(document.body,{childList:!0,subtree:!0})})();})();
|