| 1 |
import apiFetch from '@wordpress/api-fetch'; |
| 2 |
import { create } from 'zustand'; |
| 3 |
import { devtools, persist } from 'zustand/middleware'; |
| 4 |
|
| 5 |
const storage = { |
| 6 |
setItem: (_name, store) => |
| 7 |
apiFetch({ |
| 8 |
path: '/extendify/v1/shared/update-user-meta', |
| 9 |
method: 'POST', |
| 10 |
data: { |
| 11 |
option: 'notifications', |
| 12 |
value: { |
| 13 |
dismissed: store.state.dismissed, |
| 14 |
viewed: store.state.viewed, |
| 15 |
}, |
| 16 |
}, |
| 17 |
}), |
| 18 |
}; |
| 19 |
|
| 20 |
const state = (set, get) => ({ |
| 21 |
dismissed: window.extSharedData?.notifications?.dismissed ?? [], |
| 22 |
viewed: window.extSharedData?.notifications?.viewed ?? [], |
| 23 |
isDismissedBanner: (slug) => |
| 24 |
get().dismissed.some((banner) => banner.slug === slug), |
| 25 |
dismissBanner: (slug) => { |
| 26 |
if (get().isDismissedBanner(slug)) return; |
| 27 |
set((current) => ({ |
| 28 |
dismissed: [ |
| 29 |
...current.dismissed, |
| 30 |
{ slug, dismissedAt: new Date().toISOString() }, |
| 31 |
], |
| 32 |
})); |
| 33 |
}, |
| 34 |
hasViewedNotification: (slug, slot, page) => |
| 35 |
get().viewed.some( |
| 36 |
(view) => view.slug === slug && view.slot === slot && view.page === page, |
| 37 |
), |
| 38 |
recordNotificationView: (slug, slot, page) => { |
| 39 |
if (get().hasViewedNotification(slug, slot, page)) return; |
| 40 |
set((current) => ({ |
| 41 |
viewed: [ |
| 42 |
...current.viewed, |
| 43 |
{ slug, slot, page, viewedAt: new Date().toISOString() }, |
| 44 |
], |
| 45 |
})); |
| 46 |
}, |
| 47 |
}); |
| 48 |
|
| 49 |
export const useNotificationsStore = create( |
| 50 |
persist(devtools(state, { name: 'Extendify Notifications' }), { |
| 51 |
name: 'extendify-notifications', |
| 52 |
storage, |
| 53 |
skipHydration: true, |
| 54 |
}), |
| 55 |
); |
| 56 |
|