forked from authgear/authgear-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresendButton.ts
More file actions
52 lines (43 loc) · 1.33 KB
/
resendButton.ts
File metadata and controls
52 lines (43 loc) · 1.33 KB
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
import { Controller } from "@hotwired/stimulus";
export class ResendButtonController extends Controller {
static values = {
cooldown: Number,
label: String,
labelUnit: String,
};
declare cooldownValue: number;
declare labelValue: string;
declare labelUnitValue: string;
declare animHandle: number | null;
connect() {
const button = this.element as HTMLButtonElement;
const scheduledAt = new Date();
const cooldown = this.cooldownValue * 1000;
const label = this.labelValue;
const labelUnit = this.labelUnitValue;
const tick = () => {
const now = new Date();
const timeElapsed = now.getTime() - scheduledAt.getTime();
let displaySeconds = 0;
if (timeElapsed <= cooldown) {
displaySeconds = Math.round((cooldown - timeElapsed) / 1000);
}
if (displaySeconds === 0) {
button.disabled = false;
button.textContent = label;
this.animHandle = null;
} else {
button.disabled = true;
button.textContent = labelUnit.replace("%d", String(displaySeconds));
this.animHandle = requestAnimationFrame(tick);
}
};
this.animHandle = requestAnimationFrame(tick);
}
disconnect() {
if (this.animHandle != null) {
cancelAnimationFrame(this.animHandle);
this.animHandle = null;
}
}
}