| 1 |
import { useEffect, useCallback } from '@wordpress/element' |
| 2 |
import { General as GeneralApi } from '@library/api/General' |
| 3 |
import MainWindow from '@library/pages/MainWindow' |
| 4 |
import { useGlobalStore } from '@library/state/GlobalState' |
| 5 |
import { useTemplatesStore } from '@library/state/Templates' |
| 6 |
import { useUserStore } from '@library/state/User' |
| 7 |
import '@library/utility-control' |
| 8 |
import { useTaxonomyStore } from './state/Taxonomies' |
| 9 |
|
| 10 |
export default function ExtendifyLibrary({ show = false }) { |
| 11 |
const open = useGlobalStore((state) => state.open) |
| 12 |
const setReady = useGlobalStore((state) => state.setReady) |
| 13 |
const setOpen = useGlobalStore((state) => state.setOpen) |
| 14 |
const showLibrary = useCallback(() => setOpen(true), [setOpen]) |
| 15 |
const hideLibrary = useCallback(() => setOpen(false), [setOpen]) |
| 16 |
const initTemplateData = useTemplatesStore( |
| 17 |
(state) => state.initTemplateData, |
| 18 |
) |
| 19 |
const fetchTaxonomies = useTaxonomyStore((state) => state.fetchTaxonomies) |
| 20 |
|
| 21 |
// When the uuid of the user comes back from the database, we can |
| 22 |
// assume that the state object is ready. This is important to check |
| 23 |
// as the library may be "open" when loaded, but not ready. |
| 24 |
const userHasHydrated = useUserStore((state) => state._hasHydrated) |
| 25 |
const taxonomiesReady = useTemplatesStore( |
| 26 |
(state) => Object.keys(state.taxonomyDefaultState).length > 0, |
| 27 |
) |
| 28 |
|
| 29 |
useEffect(() => { |
| 30 |
if (!open) return |
| 31 |
fetchTaxonomies().then(() => { |
| 32 |
useTemplatesStore.getState().setupDefaultTaxonomies() |
| 33 |
}) |
| 34 |
}, [open, fetchTaxonomies]) |
| 35 |
|
| 36 |
useEffect(() => { |
| 37 |
if (userHasHydrated && taxonomiesReady) { |
| 38 |
initTemplateData() |
| 39 |
setReady(true) |
| 40 |
} |
| 41 |
}, [userHasHydrated, taxonomiesReady, initTemplateData, setReady]) |
| 42 |
|
| 43 |
useEffect(() => { |
| 44 |
const search = new URLSearchParams(window.location.search) |
| 45 |
if (show || search.has('ext-open')) { |
| 46 |
setOpen(true) |
| 47 |
} |
| 48 |
}, [show, setOpen]) |
| 49 |
|
| 50 |
useEffect(() => { |
| 51 |
GeneralApi.metaData().then((data) => { |
| 52 |
useGlobalStore.setState({ |
| 53 |
metaData: data, |
| 54 |
}) |
| 55 |
}) |
| 56 |
}, []) |
| 57 |
|
| 58 |
// Let the visibility to be controlled from outside the application |
| 59 |
// e.g. from the main button in the toolbar. |
| 60 |
useEffect(() => { |
| 61 |
window.addEventListener('extendify::open-library', showLibrary) |
| 62 |
window.addEventListener('extendify::close-library', hideLibrary) |
| 63 |
return () => { |
| 64 |
window.removeEventListener('extendify::open-library', showLibrary) |
| 65 |
window.removeEventListener('extendify::close-library', hideLibrary) |
| 66 |
} |
| 67 |
}, [hideLibrary, showLibrary]) |
| 68 |
|
| 69 |
return <MainWindow /> |
| 70 |
} |
| 71 |
|