| 1 |
import { safeParseJson } from '@shared/lib/parsing'; |
| 2 |
import apiFetch from '@wordpress/api-fetch'; |
| 3 |
import { create } from 'zustand'; |
| 4 |
import { createJSONStorage, devtools, persist } from 'zustand/middleware'; |
| 5 |
|
| 6 |
const path = '/extendify/v1/shared/image-generation'; |
| 7 |
const storage = { |
| 8 |
getItem: async () => await apiFetch({ path }), |
| 9 |
setItem: async (_name, state) => |
| 10 |
await apiFetch({ path, method: 'POST', data: { state } }), |
| 11 |
}; |
| 12 |
const startingState = { |
| 13 |
aiImageOptions: { |
| 14 |
prompt: '', |
| 15 |
size: '1024x1024', |
| 16 |
}, |
| 17 |
imageCredits: { |
| 18 |
remaining: 10, |
| 19 |
total: 10, |
| 20 |
refresh: undefined, |
| 21 |
}, |
| 22 |
}; |
| 23 |
const store = (set) => ({ |
| 24 |
...startingState, |
| 25 |
...safeParseJson(window.extSharedData?.globalState)?.state, |
| 26 |
updateImageCredits({ remaining, total, refresh }) { |
| 27 |
set((state) => ({ |
| 28 |
imageCredits: { |
| 29 |
...state.imageCredits, |
| 30 |
// Only update truthy values |
| 31 |
...(remaining && { remaining }), |
| 32 |
...(total && { total }), |
| 33 |
...(refresh && { refresh }), |
| 34 |
}, |
| 35 |
})); |
| 36 |
}, |
| 37 |
subtractOneCredit() { |
| 38 |
set((state) => ({ |
| 39 |
imageCredits: { |
| 40 |
...state.imageCredits, |
| 41 |
remaining: state.imageCredits.remaining - 1, |
| 42 |
// set to 24 hours from now (in ms) |
| 43 |
refresh: new Date(Date.now() + 24 * 60 * 60 * 1000).getTime(), |
| 44 |
}, |
| 45 |
})); |
| 46 |
}, |
| 47 |
resetImageCredits() { |
| 48 |
set({ imageCredits: startingState.imageCredits }); |
| 49 |
}, |
| 50 |
setAiImageOption(option, value) { |
| 51 |
set((state) => ({ |
| 52 |
aiImageOptions: { ...state.aiImageOptions, [option]: value }, |
| 53 |
})); |
| 54 |
}, |
| 55 |
}); |
| 56 |
const withDevtools = devtools(store, { name: 'Extendify Image Generation' }); |
| 57 |
const withPersist = persist(withDevtools, { |
| 58 |
name: 'extendify_image_generation', |
| 59 |
storage: createJSONStorage(() => storage), |
| 60 |
skipHydration: true, |
| 61 |
partialize: (state) => { |
| 62 |
// Remove the prompt |
| 63 |
return { |
| 64 |
...state, |
| 65 |
aiImageOptions: { ...state.aiImageOptions, prompt: '' }, |
| 66 |
}; |
| 67 |
}, |
| 68 |
}); |
| 69 |
export const useImageGenerationStore = create(withPersist); |
| 70 |
|