-
Notifications
You must be signed in to change notification settings - Fork 1
/
TypeEcho.tsx
49 lines (39 loc) · 1.26 KB
/
TypeEcho.tsx
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
import classNames from 'classnames';
import { observable } from 'mobx';
import { observer } from 'mobx-react';
import { Component, HTMLAttributes, RefCallback } from 'react';
import { sleep } from 'web-utility';
export interface TypeEchoProps extends HTMLAttributes<HTMLPreElement> {
text: string;
intervals?: number;
}
@observer
export class TypeEcho extends Component<TypeEchoProps> {
static displayName = 'TypeEcho';
@observable
accessor echoed = '';
init: RefCallback<HTMLPreElement> = node =>
node &&
new IntersectionObserver(async ([{ isIntersecting }], observer) => {
if (!isIntersecting) return;
observer.disconnect();
const { text, intervals = 150 } = this.props;
for (const char of text) {
await sleep(intervals / 1000);
this.echoed += char;
}
}).observe(node);
render() {
const { className, text, ...props } = this.props,
{ echoed } = this;
return (
<pre
{...props}
ref={this.init}
className={classNames('text-wrap', className)}
>
{echoed + (echoed === text ? '' : '_')}
</pre>
);
}
}