| 1 |
import { AI_HOST } from '@constants'; |
| 2 |
import { reqDataBasics } from '@shared/lib/data'; |
| 3 |
import useSWRImmutable from 'swr/immutable'; |
| 4 |
|
| 5 |
// The route never reads siteProfile, and the GET would put it in the query string. |
| 6 |
const { siteProfile, ...basics } = reqDataBasics; |
| 7 |
|
| 8 |
export const ACTIVATION_STATUS = { |
| 9 |
displayed: 'displayed', |
| 10 |
completed: 'completed', |
| 11 |
skipped: 'skipped', |
| 12 |
}; |
| 13 |
|
| 14 |
export const ACCOUNT_STATUS = { |
| 15 |
pending: 'pending', |
| 16 |
success: 'success', |
| 17 |
error: 'error', |
| 18 |
}; |
| 19 |
|
| 20 |
export const getPluginsScriptData = async ([slugs, ineligible]) => { |
| 21 |
const params = new URLSearchParams(slugs.map((slug) => ['plugins', slug])); |
| 22 |
for (const slug of ineligible) { |
| 23 |
params.append('ineligible', slug); |
| 24 |
} |
| 25 |
for (const [key, value] of Object.entries(basics)) { |
| 26 |
params.append(key, value); |
| 27 |
} |
| 28 |
|
| 29 |
const response = await fetch(`${AI_HOST}/api/plugins/activate?${params}`); |
| 30 |
return response.json(); |
| 31 |
}; |
| 32 |
|
| 33 |
export const patchActivation = async ({ |
| 34 |
activationId, |
| 35 |
selectedPlugins, |
| 36 |
status, |
| 37 |
context, |
| 38 |
}) => { |
| 39 |
// Losing this record must not cost the account it was recording. |
| 40 |
await fetch(`${AI_HOST}/api/plugins/activate`, { |
| 41 |
method: 'PATCH', |
| 42 |
headers: { 'Content-Type': 'application/json' }, |
| 43 |
body: JSON.stringify({ |
| 44 |
...basics, |
| 45 |
activationId, |
| 46 |
selectedPlugins, |
| 47 |
status, |
| 48 |
context, |
| 49 |
}), |
| 50 |
// The copy invites closing the window; the settled write has to outlive it. |
| 51 |
keepalive: true, |
| 52 |
}).catch(() => {}); |
| 53 |
}; |
| 54 |
|
| 55 |
export const usePluginsActivation = (plugins, ineligible = []) => { |
| 56 |
const slugs = plugins.map((plugin) => plugin.slug); |
| 57 |
// SWR skips an empty-array key, which would lose the record for an all-ineligible site. |
| 58 |
const { |
| 59 |
data, |
| 60 |
isLoading: loading, |
| 61 |
error, |
| 62 |
} = useSWRImmutable([slugs, ineligible], getPluginsScriptData); |
| 63 |
const { activationId, ...scriptData } = data ?? {}; |
| 64 |
|
| 65 |
const selectedPlugins = plugins |
| 66 |
.filter((plugin) => plugin.selected) |
| 67 |
.map((plugin) => plugin.slug); |
| 68 |
|
| 69 |
const activatePlugins = ({ status, context = undefined }) => |
| 70 |
patchActivation({ activationId, selectedPlugins, status, context }); |
| 71 |
|
| 72 |
return { scriptData, activatePlugins, loading, error }; |
| 73 |
}; |
| 74 |
|