| 1 |
import { buildPaletteCssMap } from '@shared/lib/palette-preview'; |
| 2 |
import { |
| 3 |
getServedPalettes, |
| 4 |
palettesBySlug, |
| 5 |
rankPalettes, |
| 6 |
} from '@shared/lib/palettes'; |
| 7 |
import { getVibes, vibesBySlug } from '@shared/lib/vibes'; |
| 8 |
import apiFetch from '@wordpress/api-fetch'; |
| 9 |
import useSWRImmutable from 'swr/immutable'; |
| 10 |
|
| 11 |
export const usePalettes = () => { |
| 12 |
const { data, error, isLoading } = useSWRImmutable( |
| 13 |
{ key: 'agent-palettes' }, |
| 14 |
fetcher, |
| 15 |
); |
| 16 |
return { |
| 17 |
palettes: data?.palettes, |
| 18 |
css: data?.css, |
| 19 |
preferred: data?.preferred, |
| 20 |
error, |
| 21 |
isLoading, |
| 22 |
}; |
| 23 |
}; |
| 24 |
|
| 25 |
const fetcher = async () => { |
| 26 |
const siteStyle = await getSiteStyle(); |
| 27 |
const [palettes, preferred, theme] = await Promise.all([ |
| 28 |
getServedPalettes('agent', siteStyle?.colorPalette), |
| 29 |
getPreferredPalettes(siteStyle?.vibe), |
| 30 |
getThemeGlobalStyles(), |
| 31 |
]); |
| 32 |
|
| 33 |
if (!palettes.length) return null; |
| 34 |
|
| 35 |
return { |
| 36 |
palettes: rankPalettes(palettes, preferred), |
| 37 |
preferred, |
| 38 |
css: buildPaletteCssMap({ |
| 39 |
payloads: palettesBySlug(palettes), |
| 40 |
themeStyles: theme?.styles, |
| 41 |
themeSettings: theme?.settings, |
| 42 |
}), |
| 43 |
}; |
| 44 |
}; |
| 45 |
|
| 46 |
const getSiteStyle = async () => { |
| 47 |
try { |
| 48 |
const { data } = await apiFetch({ |
| 49 |
path: '/extendify/v1/launch/options?option=extendify_siteStyle', |
| 50 |
}); |
| 51 |
return data; |
| 52 |
} catch { |
| 53 |
return null; |
| 54 |
} |
| 55 |
}; |
| 56 |
|
| 57 |
const getPreferredPalettes = async (vibe) => { |
| 58 |
if (!vibe) return []; |
| 59 |
|
| 60 |
try { |
| 61 |
const vibes = await getVibes(`agent,${vibe}`); |
| 62 |
return vibesBySlug(vibes)[vibe]?.preferredPalettes ?? []; |
| 63 |
} catch { |
| 64 |
return []; |
| 65 |
} |
| 66 |
}; |
| 67 |
|
| 68 |
// Without the theme's own values a reset falls back to revert, not the theme. |
| 69 |
const getThemeGlobalStyles = async () => { |
| 70 |
const themeSlug = window.extAgentData?.context?.themeSlug; |
| 71 |
if (!themeSlug) return null; |
| 72 |
|
| 73 |
try { |
| 74 |
return await apiFetch({ |
| 75 |
path: `/wp/v2/global-styles/themes/${themeSlug}?context=edit`, |
| 76 |
}); |
| 77 |
} catch { |
| 78 |
return null; |
| 79 |
} |
| 80 |
}; |
| 81 |
|