| 1 |
import { generateCustomContent } from '@page-creator/api/DataApi'; |
| 2 |
import { usePageLayout } from '@page-creator/hooks/usePageLayout'; |
| 3 |
import { usePageProfile } from '@page-creator/hooks/usePageProfile'; |
| 4 |
import { useGlobalsStore } from '@page-creator/state/global'; |
| 5 |
import { replaceThemeVariables } from '@page-creator/util/replaceThemeVariables'; |
| 6 |
import { safeParseJson } from '@shared/lib/parsing'; |
| 7 |
import { useEffect, useMemo } from '@wordpress/element'; |
| 8 |
import { __ } from '@wordpress/i18n'; |
| 9 |
import useSWRImmutable from 'swr/immutable'; |
| 10 |
|
| 11 |
const { state } = safeParseJson(window.extSharedData?.launchDataLegacy); |
| 12 |
|
| 13 |
const siteId = window.extSharedData.siteId; |
| 14 |
const currentTheme = window.extSharedData?.themeSlug || 'extendable'; |
| 15 |
|
| 16 |
export const usePageCustomContent = () => { |
| 17 |
const { pageProfile } = usePageProfile(); |
| 18 |
const { template } = usePageLayout(); |
| 19 |
const { setProgress, regenerationCount } = useGlobalsStore(); |
| 20 |
const loading = !pageProfile || !template; |
| 21 |
const skipCustomContent = pageProfile?.isImprintPage; |
| 22 |
|
| 23 |
const params = { |
| 24 |
key: `page-creator-page-custom-content-${regenerationCount}`, |
| 25 |
pageProfile, |
| 26 |
userState: { |
| 27 |
businessInformation: state?.businessInformation, |
| 28 |
siteInformation: state?.siteInformation, |
| 29 |
siteId, |
| 30 |
}, |
| 31 |
page: template, |
| 32 |
}; |
| 33 |
|
| 34 |
const { data, error } = useSWRImmutable( |
| 35 |
loading || skipCustomContent ? null : params, |
| 36 |
generateCustomContent, |
| 37 |
); |
| 38 |
|
| 39 |
const pageData = useMemo(() => { |
| 40 |
if (skipCustomContent && template) { |
| 41 |
return { patterns: template.patterns || [] }; |
| 42 |
} |
| 43 |
return data; |
| 44 |
}, [skipCustomContent, template, data]); |
| 45 |
|
| 46 |
useEffect(() => { |
| 47 |
if (loading) return; |
| 48 |
setProgress(__('Writing custom content...', 'extendify-local')); |
| 49 |
}, [pageData, setProgress, loading]); |
| 50 |
|
| 51 |
const themeAdjustedPatterns = useMemo(() => { |
| 52 |
if (!pageData?.patterns) return []; |
| 53 |
return pageData.patterns.map((pattern) => ({ |
| 54 |
...pattern, |
| 55 |
code: replaceThemeVariables(pattern.code, currentTheme), |
| 56 |
})); |
| 57 |
}, [pageData?.patterns]); |
| 58 |
|
| 59 |
return { |
| 60 |
page: pageData |
| 61 |
? { |
| 62 |
patterns: themeAdjustedPatterns, |
| 63 |
title: pageProfile.aiTitle, |
| 64 |
} |
| 65 |
: pageData, |
| 66 |
error, |
| 67 |
loading: !pageData && !error, |
| 68 |
}; |
| 69 |
}; |
| 70 |
|