| 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 |
// Seed from the server so we read-modify-write the full activity list and |
| 7 |
// don't clobber what Assist already stored in the same option. |
| 8 |
const initialState = { |
| 9 |
activities: [], |
| 10 |
...(safeParseJson( |
| 11 |
window.extAgentData?.userData?.domainsRecommendationsActivities, |
| 12 |
)?.state ?? {}), |
| 13 |
}; |
| 14 |
|
| 15 |
const state = (set, get) => ({ |
| 16 |
...initialState, |
| 17 |
setDomainActivity: ({ |
| 18 |
domain, |
| 19 |
position, |
| 20 |
type = 'primary', |
| 21 |
action = 'clicked', |
| 22 |
}) => { |
| 23 |
set({ |
| 24 |
activities: [ |
| 25 |
...get().activities, |
| 26 |
{ |
| 27 |
domain: domain?.toLowerCase(), |
| 28 |
position, |
| 29 |
type, |
| 30 |
action, |
| 31 |
date: new Date().toISOString(), |
| 32 |
}, |
| 33 |
], |
| 34 |
}); |
| 35 |
}, |
| 36 |
}); |
| 37 |
|
| 38 |
const debounce = (func, delay) => { |
| 39 |
let timeoutId; |
| 40 |
return (...params) => { |
| 41 |
clearTimeout(timeoutId); |
| 42 |
timeoutId = setTimeout(() => func(...params), delay); |
| 43 |
}; |
| 44 |
}; |
| 45 |
|
| 46 |
// Same endpoint/option as Assist so both surfaces feed one list. |
| 47 |
const path = '/extendify/v1/assists/domains-recommendations-activities'; |
| 48 |
const storage = { |
| 49 |
getItem: async () => await apiFetch({ path }), |
| 50 |
setItem: debounce( |
| 51 |
async (_name, state) => |
| 52 |
await apiFetch({ path, method: 'POST', data: { state } }), |
| 53 |
500, |
| 54 |
), |
| 55 |
}; |
| 56 |
|
| 57 |
export const useDomainActivities = create( |
| 58 |
persist(devtools(state, { name: 'Extendify Agent Domain Activities' }), { |
| 59 |
storage: createJSONStorage(() => storage), |
| 60 |
skipHydration: true, |
| 61 |
}), |
| 62 |
); |
| 63 |
|