@empathyco/x-components
Version:
Empathy X Components
58 lines (56 loc) • 1.39 kB
JavaScript
/**
* Typing directive.
*
* @public
*/
const typing = {
mounted(el, binding) {
execute(el, binding.value);
},
updated(el, binding) {
if (binding.value.text !== binding.oldValue?.text) {
clearTimeout(el.__timeoutId);
execute(el, binding.value);
}
},
unmounted(el) {
clearTimeout(el.__timeoutId);
},
};
/**
* Execute a typing animation in an HTML element.
*
* @param el - The HTML element where the typing animation will be displayed.
* @param options - Options for the behavior of the animation.
*/
function execute(el, options) {
const { text, speed = 1, targetAttr = '' } = options;
if (!text) {
console.error('v-typing: "text" is required.');
return;
}
let index = 0;
const updateContent = (value) => {
if (targetAttr) {
el.setAttribute(targetAttr, value);
}
else {
el.innerHTML = value;
}
};
const type = () => {
if (index < text.length) {
updateContent(text.slice(0, index + 1));
index++;
el.__timeoutId = setTimeout(type, speed);
}
else {
updateContent(text);
clearTimeout(el.__timeoutId);
el.__timeoutId = undefined;
}
};
type();
}
export { typing };
//# sourceMappingURL=typing.js.map