| 1 |
import { safeParseJson } from '@shared/lib/parsing'; |
| 2 |
import { safeLocalStorage } from '@shared/state/safe-local-storage'; |
| 3 |
import { create } from 'zustand'; |
| 4 |
import { createJSONStorage, devtools, persist } from 'zustand/middleware'; |
| 5 |
|
| 6 |
const initialState = { |
| 7 |
pages: [], |
| 8 |
style: null, |
| 9 |
}; |
| 10 |
|
| 11 |
const key = `extendify-launch-pages-selection-${window.extSharedData.siteId}`; |
| 12 |
const state = (set, get) => ({ |
| 13 |
// initialize the state with default values |
| 14 |
...initialState, |
| 15 |
...(safeParseJson(window.localStorage.getItem(key))?.state || {}), |
| 16 |
has(type, item) { |
| 17 |
if (!item?.id) return false; |
| 18 |
return (get()?.[type] ?? [])?.some((t) => t.id === item.id); |
| 19 |
}, |
| 20 |
add(type, item) { |
| 21 |
if (get().has(type, item)) return; |
| 22 |
set({ [type]: [...(get()?.[type] ?? []), item] }); |
| 23 |
}, |
| 24 |
remove(type, item) { |
| 25 |
set({ [type]: get()?.[type]?.filter((t) => t.id !== item.id) }); |
| 26 |
}, |
| 27 |
removeAll(type) { |
| 28 |
set({ [type]: [] }); |
| 29 |
}, |
| 30 |
setStyle(style) { |
| 31 |
set({ style }); |
| 32 |
}, |
| 33 |
}); |
| 34 |
|
| 35 |
export const usePagesSelectionStore = create( |
| 36 |
persist(devtools(state, { name: 'Extendify Launch Pages Selections' }), { |
| 37 |
name: key, |
| 38 |
storage: createJSONStorage(() => safeLocalStorage), |
| 39 |
skipHydration: true, |
| 40 |
}), |
| 41 |
state, |
| 42 |
); |
| 43 |
|