forked from JoelSutherland/GitHub-jQuery-Repo-Widget
/
CommandLine.tsx
94 lines (73 loc) · 2.11 KB
/
CommandLine.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
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
import { observable } from 'mobx';
import { WebCell, attribute, component, observer } from 'web-cell';
export interface CommandLineProps {
text: string;
}
export interface CommandLine extends WebCell<CommandLineProps> {}
@component({ tagName: 'command-line' })
@observer
export class CommandLine
extends HTMLElement
implements WebCell<CommandLineProps>
{
@attribute
@observable
accessor active = false;
@attribute
@observable
accessor shownIndex = 0;
@attribute
@observable
accessor text = '';
mountedCallback() {
this.classList.add(
'd-block',
'rounded',
'p-3',
'bg-dark',
'text-white'
);
this.tabIndex = -1;
this.addEventListener('click', this.autoCopy);
this.addEventListener('focus', () => (this.active = true));
this.addEventListener('blur', () => (this.active = false));
this.boot();
}
private timer: number;
protected boot() {
this.timer = self.setInterval(() => {
const { text } = this;
if (!text) return;
const { shownIndex } = this;
this.shownIndex++;
if (shownIndex >= text.length) self.clearInterval(this.timer);
}, 100);
}
disconnectedCallback() {
self.clearInterval(this.timer);
}
autoCopy = () => {
const target = this.querySelector('kbd')!;
self.getSelection().getRangeAt(0).selectNode(target);
document.execCommand('copy');
};
render() {
const { text } = this,
{ shownIndex, active } = this;
return (
<>
<span className="user-select-none">$</span>
<kbd className="bg-dark">{text.slice(0, shownIndex)}</kbd>
<small
className="badge bg-success"
style={{
opacity: active ? '1' : '0',
transition: '0.25s'
}}
>
Copied !
</small>
</>
);
}
}