import { ResourceBrowserSource, ResourceBrowserPlugin, ResourceBrowserSourceWithPlugin } from '../types'; import { useAsync } from '@squiz/generic-browser-lib'; export type UseSourcesProps = { onRequestSources: () => Promise; plugins: Array; }; /** * Loads and caches the source list when a component using the hook is mounted. */ export const useSources = ({ onRequestSources, plugins }: UseSourcesProps) => { const pluginsKey = plugins.reduce((acc, plugin) => acc + plugin.type, ''); return useAsync( { callback: () => { return new Promise((resolve, reject) => { // Get all the sources from the outer context onRequestSources() .then((sources: ResourceBrowserSource[]) => { // Remove any sources which we don't have a plugin to handle const filteredSources = sources.filter((source) => { return !!plugins.find((plugin) => { if (plugin.type === source.type) { return true; } return false; }); }); // Attach the plugin to the source so it can be quickly used later const combinedSources = filteredSources.map((source) => { const plugin = plugins.find((plugin) => { if (plugin.type === source.type) { return true; } return false; }); return { ...source, plugin, } as ResourceBrowserSourceWithPlugin; }); resolve(combinedSources); }) .catch((e: unknown) => { reject(e); }); }); }, defaultValue: [] as ResourceBrowserSourceWithPlugin[], }, [onRequestSources, pluginsKey], ); };