mirror of
https://github.com/laurent22/joplin.git
synced 2024-12-18 09:35:20 +02:00
43 lines
1.3 KiB
TypeScript
43 lines
1.3 KiB
TypeScript
import PluginService from '@joplin/lib/services/plugins/PluginService';
|
|
import Logger from '@joplin/utils/Logger';
|
|
import { useEffect, useMemo, useRef, useState } from 'react';
|
|
|
|
const logger = Logger.create('usePlugin');
|
|
|
|
const usePlugin = (pluginId: string) => {
|
|
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.');
|
|
}
|
|
|
|
return PluginService.instance().pluginById(pluginId);
|
|
// 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;
|
|
};
|
|
|
|
export default usePlugin;
|