2024-03-11 17:02:15 +02:00
|
|
|
import PluginService from '@joplin/lib/services/plugins/PluginService';
|
2024-06-04 10:57:52 +02:00
|
|
|
import Logger from '@joplin/utils/Logger';
|
|
|
|
import { useEffect, useMemo, useRef, useState } from 'react';
|
|
|
|
|
|
|
|
const logger = Logger.create('usePlugin');
|
2024-03-11 17:02:15 +02:00
|
|
|
|
|
|
|
const usePlugin = (pluginId: string) => {
|
2024-06-04 10:57:52 +02:00
|
|
|
const [pluginReloadCounter, setPluginReloadCounter] = useState(0);
|
|
|
|
|
|
|
|
const plugin = useMemo(() => {
|
|
|
|
if (!PluginService.instance().pluginIds.includes(pluginId)) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (pluginReloadCounter > 0) {
|
|
|
|
logger.debug('Reloading plugin', pluginId, 'because the set of loaded plugins changed.');
|
|
|
|
}
|
|
|
|
|
2024-03-11 17:02:15 +02:00
|
|
|
return PluginService.instance().pluginById(pluginId);
|
2024-06-04 10:57:52 +02:00
|
|
|
// The dependency on pluginReloadCounter is important -- it ensures that the plugin
|
|
|
|
// matches the one loaded in the PluginService.
|
|
|
|
}, [pluginId, pluginReloadCounter]);
|
|
|
|
|
|
|
|
const reloadCounterRef = useRef(0);
|
|
|
|
reloadCounterRef.current = pluginReloadCounter;
|
|
|
|
|
|
|
|
// The plugin may need to be re-fetched from the PluginService. When a plugin is reloaded,
|
|
|
|
// its Plugin object is replaced with a new one.
|
|
|
|
useEffect(() => {
|
|
|
|
const { remove } = PluginService.instance().addLoadedPluginsChangeListener(() => {
|
|
|
|
setPluginReloadCounter(reloadCounterRef.current + 1);
|
|
|
|
});
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
remove();
|
|
|
|
};
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
return plugin;
|
2024-03-11 17:02:15 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
export default usePlugin;
|