| 1 |
import apiFetch from '@wordpress/api-fetch'; |
| 2 |
import { __ } from '@wordpress/i18n'; |
| 3 |
import useSWRImmutable from 'swr/immutable'; |
| 4 |
|
| 5 |
const fetcher = async () => { |
| 6 |
const path = window.location.pathname; |
| 7 |
const s = new URLSearchParams(window.location.search); |
| 8 |
const onEditor = |
| 9 |
path.includes('/wp-admin/post.php') && s.get('action') === 'edit'; |
| 10 |
|
| 11 |
const variations = await apiFetch({ |
| 12 |
method: 'GET', |
| 13 |
// On the frontend we need to include layout styles |
| 14 |
path: `/extendify/v1/agent/theme-variations${onEditor ? '' : '?includeLayoutStyles'}`, |
| 15 |
}); |
| 16 |
if (!variations || !Array.isArray(variations)) { |
| 17 |
throw new Error(__('Failed to fetch theme variations.', 'extendify-local')); |
| 18 |
} |
| 19 |
return { |
| 20 |
// remove duplicate variations by title |
| 21 |
variations: variations.reduce((acc, variation) => { |
| 22 |
if (!acc.some((v) => v.title === variation.title)) { |
| 23 |
acc.push(variation); |
| 24 |
} |
| 25 |
return acc; |
| 26 |
}, []), |
| 27 |
}; |
| 28 |
}; |
| 29 |
|
| 30 |
export const useThemeVariations = () => { |
| 31 |
const { data, error, isLoading } = useSWRImmutable( |
| 32 |
{ |
| 33 |
key: 'theme-variations', |
| 34 |
themeSlug: window.extAgentData.context.themeSlug, |
| 35 |
}, |
| 36 |
fetcher, |
| 37 |
); |
| 38 |
return { variations: data?.variations, error, isLoading }; |
| 39 |
}; |
| 40 |
|