✨ Show a notification when adding a product to Cart
This commit is contained in:
@@ -93,7 +93,6 @@ export const clamp = (num: number, a: number, b: number) => {
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Return a random element from an array
|
||||
*/
|
||||
|
||||
39
src/utils/notifications.ts
Normal file
39
src/utils/notifications.ts
Normal 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))
|
||||
}
|
||||
@@ -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([])
|
||||
Reference in New Issue
Block a user