| 1 |
import apiFetch from '@wordpress/api-fetch'; |
| 2 |
import { safeParseJson } from '@shared/lib/parsing'; |
| 3 |
import { create } from 'zustand'; |
| 4 |
import { devtools, persist, createJSONStorage } from 'zustand/middleware'; |
| 5 |
|
| 6 |
const path = '/extendify/v1/shared/activity'; |
| 7 |
|
| 8 |
/** |
| 9 |
* Implementation of a custom storage engine for Zustand's persist middleware. |
| 10 |
* It replicates the Storage interface defined at https://developer.mozilla.org/en-US/docs/Web/API/Storage |
| 11 |
* |
| 12 |
* This storage uses a WordPress custom endpoint to persist the state in `wp_options`. |
| 13 |
*/ |
| 14 |
const storage = { |
| 15 |
getItem: () => apiFetch({ path }), |
| 16 |
setItem: (_name, state) => |
| 17 |
apiFetch({ path, method: 'POST', data: { state } }), |
| 18 |
}; |
| 19 |
|
| 20 |
const incomingState = safeParseJson(window.extSharedData.activity); |
| 21 |
|
| 22 |
const initialState = { |
| 23 |
actions: {}, |
| 24 |
}; |
| 25 |
|
| 26 |
const state = (set, get) => ({ |
| 27 |
...initialState, |
| 28 |
...(incomingState?.state ?? {}), |
| 29 |
incrementActivity: (id) => { |
| 30 |
set((state) => ({ |
| 31 |
...state, |
| 32 |
actions: { |
| 33 |
...state.actions, |
| 34 |
[id]: Number(get().actions[id] || 0) + 1, |
| 35 |
}, |
| 36 |
})); |
| 37 |
}, |
| 38 |
}); |
| 39 |
|
| 40 |
export const useActivityStore = create( |
| 41 |
persist(devtools(state, { name: 'Extendify Activity' }), { |
| 42 |
name: 'extendify_shared_activity', |
| 43 |
storage: createJSONStorage(() => storage), |
| 44 |
skipHydration: true, |
| 45 |
}), |
| 46 |
); |
| 47 |
|