-
Notifications
You must be signed in to change notification settings - Fork 0
/
typed.js
433 lines (400 loc) · 12.4 KB
/
typed.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
import { initializer } from './initializer.js';
import { htmlParser } from './html-parser.js';
/**
* Welcome to Typed.js!
* @param {string} elementId HTML element ID _OR_ HTML element
* @param {object} options options object
* @returns {object} a new Typed object
*/
export default class Typed {
constructor(elementId, options) {
// Initialize it up
initializer.load(this, options, elementId);
// All systems go!
this.begin();
}
/**
* Toggle start() and stop() of the Typed instance
* @public
*/
toggle() {
this.pause.status ? this.start() : this.stop();
}
/**
* Stop typing / backspacing and enable cursor blinking
* @public
*/
stop() {
if (this.typingComplete) return;
if (this.pause.status) return;
this.toggleBlinking(true);
this.pause.status = true;
this.options.onStop(this.arrayPos, this);
}
/**
* Start typing / backspacing after being stopped
* @public
*/
start() {
if (this.typingComplete) return;
if (!this.pause.status) return;
this.pause.status = false;
if (this.pause.typewrite) {
this.typewrite(this.pause.curString, this.pause.curStrPos);
} else {
this.backspace(this.pause.curString, this.pause.curStrPos);
}
this.options.onStart(this.arrayPos, this);
}
/**
* Destroy this instance of Typed
* @public
*/
destroy() {
this.reset(false);
this.options.onDestroy(this);
}
/**
* Reset Typed and optionally restarts
* @param {boolean} restart
* @public
*/
reset(restart = true) {
clearInterval(this.timeout);
this.replaceText('');
if (this.cursor && this.cursor.parentNode) {
this.cursor.parentNode.removeChild(this.cursor);
this.cursor = null;
}
this.strPos = 0;
this.arrayPos = 0;
this.curLoop = 0;
if (restart) {
this.insertCursor();
this.options.onReset(this);
this.begin();
}
}
/**
* Begins the typing animation
* @private
*/
begin() {
this.options.onBegin(this);
this.typingComplete = false;
this.shuffleStringsIfNeeded(this);
this.insertCursor();
if (this.bindInputFocusEvents) this.bindFocusEvents();
this.timeout = setTimeout(() => {
// Check if there is some text in the element, if yes start by backspacing the default message
if (!this.currentElContent || this.currentElContent.length === 0) {
this.typewrite(this.strings[this.sequence[this.arrayPos]], this.strPos);
} else {
// Start typing
this.backspace(this.currentElContent, this.currentElContent.length);
}
}, this.startDelay);
}
/**
* Called for each character typed
* @param {string} curString the current string in the strings array
* @param {number} curStrPos the current position in the curString
* @private
*/
typewrite(curString, curStrPos) {
if (this.fadeOut && this.el.classList.contains(this.fadeOutClass)) {
this.el.classList.remove(this.fadeOutClass);
if (this.cursor) this.cursor.classList.remove(this.fadeOutClass);
}
const humanize = this.humanizer(this.typeSpeed);
let numChars = 1;
if (this.pause.status === true) {
this.setPauseStatus(curString, curStrPos, true);
return;
}
// contain typing function in a timeout humanize'd delay
this.timeout = setTimeout(() => {
// skip over any HTML chars
curStrPos = htmlParser.typeHtmlChars(curString, curStrPos, this);
let pauseTime = 0;
let substr = curString.substr(curStrPos);
// check for an escape character before a pause value
// format: \^\d+ .. eg: ^1000 .. should be able to print the ^ too using ^^
// single ^ are removed from string
if (substr.charAt(0) === '^') {
if (/^\^\d+/.test(substr)) {
let skip = 1; // skip at least 1
substr = /\d+/.exec(substr)[0];
skip += substr.length;
pauseTime = parseInt(substr);
this.temporaryPause = true;
this.options.onTypingPaused(this.arrayPos, this);
// strip out the escape character and pause value so they're not printed
curString =
curString.substring(0, curStrPos) +
curString.substring(curStrPos + skip);
this.toggleBlinking(true);
}
}
// check for skip characters formatted as
// "this is a `string to print NOW` ..."
if (substr.charAt(0) === '`') {
while (curString.substr(curStrPos + numChars).charAt(0) !== '`') {
numChars++;
if (curStrPos + numChars > curString.length) break;
}
// strip out the escape characters and append all the string in between
const stringBeforeSkip = curString.substring(0, curStrPos);
const stringSkipped = curString.substring(
stringBeforeSkip.length + 1,
curStrPos + numChars
);
const stringAfterSkip = curString.substring(curStrPos + numChars + 1);
curString = stringBeforeSkip + stringSkipped + stringAfterSkip;
numChars--;
}
// timeout for any pause after a character
this.timeout = setTimeout(() => {
// Accounts for blinking while paused
this.toggleBlinking(false);
// We're done with this sentence!
if (curStrPos >= curString.length) {
this.doneTyping(curString, curStrPos);
} else {
this.keepTyping(curString, curStrPos, numChars);
}
// end of character pause
if (this.temporaryPause) {
this.temporaryPause = false;
this.options.onTypingResumed(this.arrayPos, this);
}
}, pauseTime);
// humanized value for typing
}, humanize);
}
/**
* Continue to the next string & begin typing
* @param {string} curString the current string in the strings array
* @param {number} curStrPos the current position in the curString
* @private
*/
keepTyping(curString, curStrPos, numChars) {
// call before functions if applicable
if (curStrPos === 0) {
this.toggleBlinking(false);
this.options.preStringTyped(this.arrayPos, this);
}
// start typing each new char into existing string
// curString: arg, this.el.html: original text inside element
curStrPos += numChars;
const nextString = curString.substr(0, curStrPos);
this.replaceText(nextString);
// loop the function
this.typewrite(curString, curStrPos);
}
/**
* We're done typing the current string
* @param {string} curString the current string in the strings array
* @param {number} curStrPos the current position in the curString
* @private
*/
doneTyping(curString, curStrPos) {
// fires callback function
this.options.onStringTyped(this.arrayPos, this);
this.toggleBlinking(true);
// is this the final string
if (this.arrayPos === this.strings.length - 1) {
// callback that occurs on the last typed string
this.complete();
// quit if we wont loop back
if (this.loop === false || this.curLoop === this.loopCount) {
return;
}
}
this.timeout = setTimeout(() => {
this.backspace(curString, curStrPos);
}, this.backDelay);
}
/**
* Backspaces 1 character at a time
* @param {string} curString the current string in the strings array
* @param {number} curStrPos the current position in the curString
* @private
*/
backspace(curString, curStrPos) {
if (this.pause.status === true) {
this.setPauseStatus(curString, curStrPos, true);
return;
}
if (this.fadeOut) return this.initFadeOut();
this.toggleBlinking(false);
const humanize = this.humanizer(this.backSpeed);
this.timeout = setTimeout(() => {
curStrPos = htmlParser.backSpaceHtmlChars(curString, curStrPos, this);
// replace text with base text + typed characters
const curStringAtPosition = curString.substr(0, curStrPos);
this.replaceText(curStringAtPosition);
// if smartBack is enabled
if (this.smartBackspace) {
// the remaining part of the current string is equal of the same part of the new string
let nextString = this.strings[this.arrayPos + 1];
if (
nextString &&
curStringAtPosition === nextString.substr(0, curStrPos)
) {
this.stopNum = curStrPos;
} else {
this.stopNum = 0;
}
}
// if the number (id of character in current string) is
// less than the stop number, keep going
if (curStrPos > this.stopNum) {
// subtract characters one by one
curStrPos--;
// loop the function
this.backspace(curString, curStrPos);
} else if (curStrPos <= this.stopNum) {
// if the stop number has been reached, increase
// array position to next string
this.arrayPos++;
// When looping, begin at the beginning after backspace complete
if (this.arrayPos === this.strings.length) {
this.arrayPos = 0;
this.options.onLastStringBackspaced();
this.shuffleStringsIfNeeded();
this.begin();
} else {
this.typewrite(this.strings[this.sequence[this.arrayPos]], curStrPos);
}
}
// humanized value for typing
}, humanize);
}
/**
* Full animation is complete
* @private
*/
complete() {
this.options.onComplete(this);
if (this.loop) {
this.curLoop++;
} else {
this.typingComplete = true;
}
}
/**
* Has the typing been stopped
* @param {string} curString the current string in the strings array
* @param {number} curStrPos the current position in the curString
* @param {boolean} isTyping
* @private
*/
setPauseStatus(curString, curStrPos, isTyping) {
this.pause.typewrite = isTyping;
this.pause.curString = curString;
this.pause.curStrPos = curStrPos;
}
/**
* Toggle the blinking cursor
* @param {boolean} isBlinking
* @private
*/
toggleBlinking(isBlinking) {
if (!this.cursor) return;
// if in paused state, don't toggle blinking a 2nd time
if (this.pause.status) return;
if (this.cursorBlinking === isBlinking) return;
this.cursorBlinking = isBlinking;
if (isBlinking) {
this.cursor.classList.add('typed-cursor--blink');
} else {
this.cursor.classList.remove('typed-cursor--blink');
}
}
/**
* Speed in MS to type
* @param {number} speed
* @private
*/
humanizer(speed) {
return Math.round((Math.random() * speed) / 2) + speed;
}
/**
* Shuffle the sequence of the strings array
* @private
*/
shuffleStringsIfNeeded() {
if (!this.shuffle) return;
this.sequence = this.sequence.sort(() => Math.random() - 0.5);
}
/**
* Adds a CSS class to fade out current string
* @private
*/
initFadeOut() {
this.el.className += ` ${this.fadeOutClass}`;
if (this.cursor) this.cursor.className += ` ${this.fadeOutClass}`;
return setTimeout(() => {
this.arrayPos++;
this.replaceText('');
// Resets current string if end of loop reached
if (this.strings.length > this.arrayPos) {
this.typewrite(this.strings[this.sequence[this.arrayPos]], 0);
} else {
this.typewrite(this.strings[0], 0);
this.arrayPos = 0;
}
}, this.fadeOutDelay);
}
/**
* Replaces current text in the HTML element
* depending on element type
* @param {string} str
* @private
*/
replaceText(str) {
if (this.attr) {
this.el.setAttribute(this.attr, str);
} else {
if (this.isInput) {
this.el.value = str;
} else if (this.contentType === 'html') {
this.el.innerHTML = str;
} else {
this.el.textContent = str;
}
}
}
/**
* If using input elements, bind focus in order to
* start and stop the animation
* @private
*/
bindFocusEvents() {
if (!this.isInput) return;
this.el.addEventListener('focus', (e) => {
this.stop();
});
this.el.addEventListener('blur', (e) => {
if (this.el.value && this.el.value.length !== 0) {
return;
}
this.start();
});
}
/**
* On init, insert the cursor element
* @private
*/
insertCursor() {
if (!this.showCursor) return;
if (this.cursor) return;
this.cursor = document.createElement('span');
this.cursor.className = 'typed-cursor';
this.cursor.setAttribute('aria-hidden', true);
this.cursor.innerHTML = this.cursorChar;
this.el.parentNode &&
this.el.parentNode.insertBefore(this.cursor, this.el.nextSibling);
}
}