Add notifications inline drawer (#292)

* Render missed notifications inline in drawer

* Fix tests
This commit is contained in:
Rijk van Zanten
2020-04-02 15:35:46 -04:00
committed by GitHub
parent 170487e3b2
commit 9f79f744f3
14 changed files with 273 additions and 70 deletions

View File

@@ -14,10 +14,8 @@ describe('Stores / Notifications', () => {
mountComposition(() => {
const store = useNotificationsStore({});
const id = store.add({ title: 'test' });
expect(store.state.queue[0]).toEqual({
id,
title: 'test',
});
jest.spyOn(Date, 'now').mockImplementation(() => 15);
expect(store.state.queue[0].id).toBe(id);
});
});
@@ -28,27 +26,22 @@ describe('Stores / Notifications', () => {
{
id: 'abc',
title: 'test',
timestamp: 1,
},
{
id: 'def',
title: 'test',
timestamp: 2,
},
{
id: 'ghi',
title: 'test',
timestamp: 3,
},
];
store.remove('def');
expect(store.state.queue).toEqual([
{
id: 'abc',
title: 'test',
},
{
id: 'ghi',
title: 'test',
},
]);
expect(store.state.queue[0].id).toBe('abc');
expect(store.state.queue[1].id).toBe('ghi');
});
});
});

View File

@@ -1,26 +1,51 @@
import { createStore } from 'pinia';
import { Notification, NotificationRaw } from './types';
import { nanoid } from 'nanoid';
import { reverse, sortBy } from 'lodash';
export const useNotificationsStore = createStore({
id: 'useNotifications',
state: () => ({
queue: [] as Notification[],
previous: [] as Notification[],
}),
actions: {
add(notification: NotificationRaw) {
const id = nanoid();
const timestamp = Date.now();
this.state.queue = [
...this.state.queue,
{
...notification,
id,
timestamp,
},
];
if (notification.persist !== true) {
setTimeout(() => {
this.remove(id);
}, 3000);
}
return id;
},
remove(id: string) {
const toBeRemoved = this.state.queue.find((n) => n.id === id);
if (!toBeRemoved) return;
this.state.queue = this.state.queue.filter((n) => n.id !== id);
this.state.previous = [...this.state.previous, toBeRemoved];
},
},
getters: {
lastFour(state) {
const all = [...state.queue, ...state.previous];
const chronologicalAll = reverse(sortBy(all, ['timestamp']));
const newestFour = chronologicalAll.slice(0, 4);
return reverse(newestFour);
},
},
});

View File

@@ -11,4 +11,5 @@ export interface NotificationRaw {
export interface Notification extends NotificationRaw {
readonly id: string;
readonly timestamp: number;
}