-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTypedText.js
89 lines (79 loc) · 1.99 KB
/
TypedText.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
import React, { Component } from 'react'
import styled from 'react-emotion'
import { colors } from '../webhart-base/utils/style'
export const animations = {
/* The typing effect */
typing: keyframes`
from {
width: 0;
}
to {
width: 100%;
}
`,
/* The typewriter cursor effect */
blinkCaret: keyframes`
from,
to {
border-color: transparent;
}
50% {
border-color: blue;
}
`,
}
const Wrapper = styled('span')`
border-right: 7px solid blue;
animation: ${animations.blinkCaret} 0.75s step-end infinite;
margin-right: 0;
`
class TypedText extends Component {
constructor(props) {
super(props)
this.state = { currentItemIndex: 0, currentItemText: '', deleting: false }
this.timeOut = null
}
componentDidMount() {
this.type()
}
type() {
const { currentItemText } = this.state
let { deleting, currentItemIndex } = this.state
const { children } = this.props
let currentItem = children[currentItemIndex]
let newCurrentItemText
let delay = 100
if (deleting) {
newCurrentItemText = currentItem.substr(0, currentItemText.length - 1)
delay = 50
} else {
newCurrentItemText = currentItem.substr(0, currentItemText.length + 1)
}
if (currentItemText == newCurrentItemText) {
deleting = true
delay = 1000
}
if (deleting && currentItemText.length == 0) {
currentItemIndex =
currentItemIndex + 1 == children.length ? 0 : currentItemIndex + 1
delay = 500
currentItem = children[currentItemIndex]
deleting = false
}
this.timeOut = setTimeout(() => {
this.setState({
currentItemText: newCurrentItemText,
deleting: deleting,
currentItemIndex: currentItemIndex,
})
this.type()
}, delay)
}
componentWillUnmount() {
clearTimeout(this.timeOut)
}
render() {
return <Wrapper>{this.state.currentItemText}</Wrapper>
}
}
export default TypedText