Show a notification when adding a product to Cart

This commit is contained in:
2021-11-07 20:18:19 +01:00
parent 03cc79da69
commit e1c259164f
7 changed files with 92 additions and 24 deletions

View File

@@ -93,7 +93,6 @@ export const clamp = (num: number, a: number, b: number) => {
}
/**
* Return a random element from an array
*/

View File

@@ -0,0 +1,39 @@
import { cartNotifications } from './store'
interface Notification {
title: string
name: string
image: string
timeout?: number
id?: number
}
/**
* Add a notification
*/
export const addNotification = (notification: Notification) => {
const id = Math.floor(Math.random() * 10000)
// Add ID and default timeout
notification = {
id,
timeout: notification.timeout || 3000,
...notification,
}
// Push the notifications to the top of the list of notificationss
cartNotifications.update((all) => [notification, ...all])
// If notification is dismissible, dismiss it after an amount of time (timeout)
if (notification.timeout) {
setTimeout(() => dismissNotification(id), notification.timeout)
}
}
/**
* Dismiss a notification
*/
export const dismissNotification = (id: number) => {
cartNotifications.update((all) => all.filter((t) => t.id !== id))
}

View File

@@ -24,4 +24,9 @@ export const cartData = writable(null)
/** Amount of products present in cart */
export const cartAmount = derived(cartData, ($cart) => {
return $cart && $cart.item_quantity > 0 ? $cart.item_quantity : 0
})
})
/**
* Notifications
*/
export const cartNotifications = writable([])