| 1 |
import apiFetch from '@wordpress/api-fetch'; |
| 2 |
import { useEffect, useState } from '@wordpress/element'; |
| 3 |
import create from 'zustand'; |
| 4 |
import { devtools, persist } from 'zustand/middleware'; |
| 5 |
|
| 6 |
type Settings = { |
| 7 |
seenNotices: string[]; |
| 8 |
hiddenThemes: string[]; |
| 9 |
setSeenNotice: (notice: string) => void; |
| 10 |
toggleHiddenTheme: (theme: string) => void; |
| 11 |
}; |
| 12 |
const path = '/wp/v2/settings'; |
| 13 |
const getSettings = async (name: string) => { |
| 14 |
const allSettings = await apiFetch({ path }); |
| 15 |
// eslint-disable-next-line @typescript-eslint/ban-ts-comment |
| 16 |
// @ts-ignore-next-line |
| 17 |
return allSettings?.[name]; |
| 18 |
}; |
| 19 |
export const useSettingsStore = create<Settings>()( |
| 20 |
persist( |
| 21 |
devtools( |
| 22 |
(set) => ({ |
| 23 |
seenNotices: [], |
| 24 |
hiddenThemes: [], |
| 25 |
setSeenNotice(notice: string) { |
| 26 |
set((state) => { |
| 27 |
if (state.seenNotices.includes(notice)) return state; |
| 28 |
return { seenNotices: [...state.seenNotices, notice] }; |
| 29 |
}); |
| 30 |
}, |
| 31 |
toggleHiddenTheme(theme: string) { |
| 32 |
set((state) => ({ |
| 33 |
hiddenThemes: state.hiddenThemes.includes(theme) |
| 34 |
? state.hiddenThemes.filter((t) => t !== theme) |
| 35 |
: [...state.hiddenThemes, theme], |
| 36 |
})); |
| 37 |
}, |
| 38 |
}), |
| 39 |
{ name: 'Code Block Pro Settings' }, |
| 40 |
), |
| 41 |
{ |
| 42 |
name: 'code_block_pro_settings_2', |
| 43 |
getStorage: () => ({ |
| 44 |
getItem: async (name: string) => { |
| 45 |
const settings = await getSettings(name); |
| 46 |
return JSON.stringify({ |
| 47 |
version: settings?.version ?? 0, |
| 48 |
state: settings, |
| 49 |
}); |
| 50 |
}, |
| 51 |
setItem: async (name: string, value: string) => { |
| 52 |
const { state, version } = JSON.parse(value); |
| 53 |
const data = { |
| 54 |
[name]: Object.assign( |
| 55 |
(await getSettings(name)) ?? {}, |
| 56 |
state, |
| 57 |
version, |
| 58 |
), |
| 59 |
}; |
| 60 |
await apiFetch({ path, method: 'POST', data }); |
| 61 |
}, |
| 62 |
removeItem: async (name: string) => { |
| 63 |
const data = { [name]: null }; |
| 64 |
return await apiFetch({ path, method: 'POST', data }); |
| 65 |
}, |
| 66 |
}), |
| 67 |
}, |
| 68 |
), |
| 69 |
); |
| 70 |
|
| 71 |
/* Hook useful for when you need to wait on the async state to hydrate */ |
| 72 |
export const useSettingsStoreReady = () => { |
| 73 |
const [hydrated, setHydrated] = useState( |
| 74 |
useSettingsStore.persist.hasHydrated, |
| 75 |
); |
| 76 |
useEffect(() => { |
| 77 |
const unsubFinishHydration = useSettingsStore.persist.onFinishHydration( |
| 78 |
() => setHydrated(true), |
| 79 |
); |
| 80 |
return () => { |
| 81 |
unsubFinishHydration(); |
| 82 |
}; |
| 83 |
}, []); |
| 84 |
return hydrated; |
| 85 |
}; |
| 86 |
|