-
Notifications
You must be signed in to change notification settings - Fork 20
/
typing-element.js
96 lines (86 loc) · 2.43 KB
/
typing-element.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import AnimationElement from "./animation-element.js";
/**
* Checks for HTML tags
* @property {function} isIncompleteHTMLTag
* @param {string} text
* @returns {boolean} True for incomplete HTML tag
*
*/
function isIncompleteHTMLTag(text){
return /<\/*$/gmi.test(text) || /(<\w*(?:\s+\w+=\"[^"]+\")*)(?=[^>]+(?:<|$))/gmi.test(text)
}
/**
* Checks character type
* @param {string} text
* @returns {boolean} True for invisible chararacter, false for others
*/
function isInvisibleChar(text){
return /\s+$/gmi.test(text)
}
/**
* Class to create a Typing Element
*/
class TypingElement extends AnimationElement{
/**
* @type {string}
*/
typedLetters;
#slot;
#span;
get text(){
return this.#slot.assignedElements()[0].innerHTML;
}
constructor(){
super();
this.attachShadow({mode: 'open'});
this.reset()
}
connectedCallback(){
this.render();
}
/**
* Renders animated text to screen
* @property {function} render
* @member {Object} TypingElement
* @returns {void} Prints out TypingElement object
*
*/
render(){
this.shadowRoot.innerHTML = "";
this.#slot = document.createElement('slot');
this.#slot.style.display = 'none'
this.shadowRoot.append(this.#slot);
this.#span = document.createElement('span');
this.shadowRoot.append(this.#span);
}
/**
* Animates TypingElement object
* @property {function} animate
* @member {Object} TypingElement
* @returns {void} Print typwriter text
*/
animate(){
if(this.typedLetters > this.text.length) this.typedLetters = 0;
this.disableAnimation()
/**
* @type {string}
*/
let typedText;
do{
typedText = this.text.substr(0, this.typedLetters)
this.typedLetters++;
}while((isInvisibleChar(typedText) || isIncompleteHTMLTag(typedText)) && this.typedLetters <= this.text.length)
this.#span.innerHTML = typedText
this.enableAnimation()
}
/**
* Resets TypingElement object
* @property {function} reset
* @member {Object}
*/
reset(){
this.typedLetters = parseInt(this.getAttribute('typed-letters')) || 0;
if(this.getAttribute('typed-letters') == 'all') this.typedLetters = this.text.length
}
}
customElements.define('typing-element', TypingElement)