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