cm-typing-effect
Version:
Typing animation effect for web elements with customizable caret and timing.
24 lines (23 loc) • 3.13 kB
JavaScript
;var l=Object.defineProperty;var $=Object.getOwnPropertyDescriptor;var k=Object.getOwnPropertyNames;var P=Object.prototype.hasOwnProperty;var A=(e,t)=>{for(var i in t)l(e,i,{get:t[i],enumerable:!0})},S=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of k(t))!P.call(e,n)&&n!==i&&l(e,n,{get:()=>t[n],enumerable:!(r=$(t,n))||r.enumerable});return e};var N=e=>S(l({},"__esModule",{value:!0}),e);var O={};A(O,{startTyping:()=>F});module.exports=N(O);var x=e=>typeof e=="string"?document.getElementById(e):e,u=e=>{if(!e)throw new Error("Invalid Target Element! (cm-typing-effect)");if(!e.textContent)throw new Error("Target Element Without Text! (cm-typing-effect)");if(e.children.length!=0)throw new Error("Target Element Has Internal Tags! (cm-typing-effect)")},T=(e,t,i)=>{let r=document.createElement("span");r.className="wrapper-cm-typing-effect";let n=document.createElement("span");n.className="text-cm-typing-effect",n.textContent=t;let s=document.createElement("span");return s.className="caret-cm-typing-effect",s.textContent=i,r.appendChild(n),r.appendChild(s),e.innerHTML="",e.appendChild(r),{wrapperElement:r,textElement:n,caretElement:s}},h=(e,t,i)=>{let r="cm-typing-effect-styles";if(!document.getElementById(r)){let n=document.createElement("style");n.id=r,n.textContent=`
@keyframes blinking-cm-typing-effect {
50% { color: transparent; }
}
@keyframes typing-cm-typing-effect {
from { width: 0; }
}
.wrapper-cm-typing-effect {
display: flex;
width: fit-content;
position: relative;
}
.text-cm-typing-effect {
display: flex;
height: 100%;
overflow: hidden;
white-space: nowrap;
width: 0;
}
.caret-cm-typing-effect {
user-select: none;
}
`,document.head.appendChild(n)}e&&w(t,i)},w=(e,t)=>{e.style.width=t+"ch"},b=(e,t,i,r)=>{if(w(e,t),r){e.style.animation=`typing-cm-typing-effect ${i}ms steps(${t}) reverse forwards`;return}e.style.animation=`typing-cm-typing-effect ${i}ms steps(${t})`},c=(e,t)=>{let i=(1/t).toFixed(2);e.style.animation=`blinking-cm-typing-effect ${i}s step-end infinite`},v=e=>e.style.removeProperty("animation"),C=(e,t)=>{e.style.position="absolute",e.style.left=`calc(100% + ${t}px)`},H=e=>{e.style.visibility==="hidden"&&e.style.removeProperty("visibility")},a=e=>new Promise(t=>{setTimeout(()=>t(!0),e)});var F=(e,{startDelay:t=0,endDelay:i=0,realisticTyping:r=!1,keepCaretBlinkingAfterEnd:n=!1,animationTime:s=1e3,caret:p="|",caretBlinkingSpeed:f=1.6,caretTakeSpace:L=!1,caretOffset:M=0,eraseMode:y=!1}={})=>new Promise(async I=>{let o=x(e);u(o);let g=!!o.querySelector(".caret-cm-typing-effect")?o.textContent.trim().slice(0,-p.length):o.textContent.trim(),d=g.length,{caretElement:m,textElement:E}=T(o,g,p);L||C(m,M),h(y,E,d),H(o),c(m,f),await a(t),r&&v(m),b(E,d,s,y),await a(s),c(m,f),await a(i),n||m.remove(),I()});0&&(module.exports={startTyping});