Added usePlugin hooks
Summary: `usePlugin(pluginFactory)` returns the current plugin instance's api that was exposed by the plugin directory. Passing `pluginFactory` is technically strictly not needed, but having the user pass it, we can make sure it is strongly typed Reviewed By: nikoant Differential Revision: D22286293 fbshipit-source-id: 4268b6849b8cd3d524103de7eadbd6c0a65c7a61
This commit is contained in:
committed by
Facebook GitHub Bot
parent
952e929699
commit
159c0deaf1
@@ -7,9 +7,28 @@
|
||||
* @format
|
||||
*/
|
||||
|
||||
import {createContext} from 'react';
|
||||
import {SandyPluginInstance} from './Plugin';
|
||||
import {createContext, useContext} from 'react';
|
||||
import {SandyPluginInstance, FlipperPluginFactory} from './Plugin';
|
||||
|
||||
export const SandyPluginContext = createContext<
|
||||
SandyPluginInstance | undefined
|
||||
>(undefined);
|
||||
|
||||
export function usePlugin<PluginFactory extends FlipperPluginFactory<any, any>>(
|
||||
plugin: PluginFactory,
|
||||
): ReturnType<PluginFactory> {
|
||||
const pluginInstance = useContext(SandyPluginContext);
|
||||
if (!pluginInstance) {
|
||||
throw new Error('Plugin context not available');
|
||||
}
|
||||
// In principle we don't *need* the plugin, but having it passed it makes sure the
|
||||
// return of this function is strongly typed, without the user needing to create it's own
|
||||
// context.
|
||||
// But since we pass it, let's make sure the user did request the proper context
|
||||
if (pluginInstance.definition.module.plugin !== plugin) {
|
||||
throw new Error(
|
||||
`Plugin context (${pluginInstance.definition.module.plugin}) didn't match the type of the requested plugin (${plugin})`,
|
||||
);
|
||||
}
|
||||
return pluginInstance.instanceApi;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user