| 1 |
import { useEffect, useState } from '@wordpress/element' |
| 2 |
import create from 'zustand' |
| 3 |
import { devtools, persist } from 'zustand/middleware' |
| 4 |
import { getGlobalData, saveGlobalData } from '../api/Data' |
| 5 |
|
| 6 |
const state = (set, get) => ({ |
| 7 |
dismissedNotices: [], |
| 8 |
isDismissed(id) { |
| 9 |
return get().dismissedNotices.some((notice) => notice.id === id) |
| 10 |
}, |
| 11 |
dismissNotice(id) { |
| 12 |
if (get().isDismissed(id)) return |
| 13 |
const notice = { id, dismissedAt: new Date().toISOString() } |
| 14 |
set((state) => ({ |
| 15 |
dismissedNotices: [...state.dismissedNotices, notice], |
| 16 |
})) |
| 17 |
}, |
| 18 |
}) |
| 19 |
|
| 20 |
const storage = { |
| 21 |
getItem: async () => JSON.stringify(await getGlobalData()), |
| 22 |
setItem: async (_, value) => await saveGlobalData(value), |
| 23 |
removeItem: () => undefined, |
| 24 |
} |
| 25 |
|
| 26 |
export const useGlobalStore = create( |
| 27 |
persist(devtools(state, { name: 'Extendify Assist Globals' }), { |
| 28 |
name: 'extendify-assist-globals', |
| 29 |
getStorage: () => storage, |
| 30 |
}), |
| 31 |
state, |
| 32 |
) |
| 33 |
|
| 34 |
/* Hook useful for when you need to wait on the async state to hydrate */ |
| 35 |
export const useGlobalStoreReady = () => { |
| 36 |
const [hydrated, setHydrated] = useState(useGlobalStore.persist.hasHydrated) |
| 37 |
useEffect(() => { |
| 38 |
const unsubFinishHydration = useGlobalStore.persist.onFinishHydration( |
| 39 |
() => setHydrated(true), |
| 40 |
) |
| 41 |
return () => { |
| 42 |
unsubFinishHydration() |
| 43 |
} |
| 44 |
}, []) |
| 45 |
return hydrated |
| 46 |
} |
| 47 |
|