Skip to content

Commit

Permalink
Merge pull request #35 from runeharlyk/notification-timeout
Browse files Browse the repository at this point in the history
Make each toasts disappear after timeout
  • Loading branch information
theelims authored Apr 5, 2024
2 parents b072393 + 265d6e1 commit 7394b06
Showing 1 changed file with 11 additions and 21 deletions.
32 changes: 11 additions & 21 deletions interface/src/lib/components/toasts/notifications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,35 +6,25 @@ type State = {
id: string;
type: StateType;
message: string;
timeout: number;
};

function createNotificationStore() {
const state: State[] = [];
const _notifications = writable(state);
const notifications = writable(state);
const { subscribe } = notifications;

function send(message: string, type: StateType = 'info', timeout: number) {
_notifications.update((state) => {
return [...state, { id: id(), type, message, timeout }];
const id = generateId();
setTimeout(() => {
notifications.update((state) => {
return state.filter((n) => n.id !== id);
});
}, timeout);
notifications.update((state) => {
return [...state, { id, type, message }];
});
}

const notifications = derived(_notifications, ($_notifications, set) => {
set($_notifications);
if ($_notifications.length > 0) {
const timer = setTimeout(() => {
_notifications.update((state) => {
state.shift();
return state;
});
}, $_notifications[0].timeout);
return () => {
clearTimeout(timer);
};
}
}) as Writable<State[]>;
const { subscribe } = notifications;

return {
subscribe,
send,
Expand All @@ -45,7 +35,7 @@ function createNotificationStore() {
};
}

function id() {
function generateId() {
return '_' + Math.random().toString(36).substr(2, 9);
}

Expand Down

0 comments on commit 7394b06

Please sign in to comment.