fixed toast timer

This commit is contained in:
Fran Jurmanović
2021-06-12 22:07:21 +02:00
parent 64b54b3568
commit 4df3801f42
3 changed files with 57 additions and 24 deletions

View File

@@ -1,11 +1,12 @@
import { controller, targets } from '@github/catalyst';
import { delay, html, until } from 'core/utils';
import { delay, html, Timer } from 'core/utils';
import { BaseComponentElement } from 'common/';
@controller
class ToastPortalElement extends BaseComponentElement {
@targets toastElement: HTMLElement;
toasts: Array<Toast> = [];
timer: Timer;
constructor() {
super();
}
@@ -15,11 +16,20 @@ class ToastPortalElement extends BaseComponentElement {
};
pushToast = (type: string, message: string): void => {
const toastLen = this.toasts.length;
this.toasts = [{ type, message }, ...this.toasts];
const interval = setInterval(() => {
if (toastLen < 1) {
this.timer = new Timer(() => {
this.popToast();
clearInterval(interval);
if (this.toasts.length > 0) {
this.timer.reset();
}
}, 5000);
}
// const interval = setInterval(() => {
// this.popToast();
// clearInterval(interval);
// }, 5000);
this.update();
};
@@ -33,7 +43,12 @@ class ToastPortalElement extends BaseComponentElement {
render = () => {
const renderToast = (note: string, type: string) => {
const message = () => html` <div class="toast ${type ? `--${type}` : '--default'}">${note}</div> `;
const message = () =>
html`
<div class="toast ${type ? `--${type}` : '--default'}">
<span class="toast-text">${note}</span>
</div>
`;
return html`${message()}`;
};

View File

@@ -1,20 +1,33 @@
const Timer = function (callback, delay, ...args) {
var timerId,
start,
remaining = delay;
this.pause = function () {
window.clearTimeout(timerId);
remaining -= Date.now() - start;
};
this.resume = function () {
start = Date.now();
window.clearTimeout(timerId);
timerId = window.setTimeout(callback, remaining, ...args);
};
class Timer {
private timerId: number;
private start: number;
private remaining: number;
private args: any;
constructor(private callback: () => any, private delay: number, ...args) {
this.remaining = delay;
this.args = args;
this.resume();
}
pause = () => {
window.clearTimeout(this.timerId);
this.remaining -= Date.now() - this.start;
};
resume = () => {
this.start = Date.now();
window.clearTimeout(this.timerId);
console.log(this.remaining);
this.timerId = window.setTimeout(this.callback, this.remaining, ...this.args);
};
reset = (pause: boolean = false) => {
window.clearTimeout(this.timerId);
this.remaining = this.delay;
if (!pause) {
this.resume();
}
};
}
export default Timer;

View File

@@ -14,14 +14,19 @@ toast-portal {
top: 5px;
right: 7px;
.toast {
&.--default {
position: relative;
width: 200px;
height: 40px;
border-radius: 4px;
margin: 4px 3px;
padding: 2px 3px;
display: flex;
align-items: center;
&.--default {
background-color: $gray-07;
border: 1px solid $gray-08;
border-radius: 4px;
}
.toast-text {
}
}
}