The open and composable observability and data visualization platform. Visualize metrics, logs, and traces from multiple sources like Prometheus, Loki, Elasticsearch, InfluxDB, Postgres and many more.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 
grafana/public/app/features/plugins/extensions/usePluginComponent.tsx

60 lines
2.1 KiB

import { useMemo } from 'react';
import { useObservable } from 'react-use';
import { usePluginContext } from '@grafana/data';
import { UsePluginComponentResult } from '@grafana/runtime';
import { useExposedComponentsRegistry } from './ExtensionRegistriesContext';
import * as errors from './errors';
import { log } from './logs/log';
import { useLoadAppPlugins } from './useLoadAppPlugins';
import { getExposedComponentPluginDependencies, isGrafanaDevMode, wrapWithPluginContext } from './utils';
import { isExposedComponentDependencyMissing } from './validators';
// Returns a component exposed by a plugin.
// (Exposed components can be defined in plugins by calling .exposeComponent() on the AppPlugin instance.)
export function usePluginComponent<Props extends object = {}>(id: string): UsePluginComponentResult<Props> {
const registry = useExposedComponentsRegistry();
const registryState = useObservable(registry.asObservable());
const pluginContext = usePluginContext();
const { isLoading: isLoadingAppPlugins } = useLoadAppPlugins(getExposedComponentPluginDependencies(id));
return useMemo(() => {
// For backwards compatibility we don't enable restrictions in production or when the hook is used in core Grafana.
const enableRestrictions = isGrafanaDevMode() && pluginContext;
if (isLoadingAppPlugins) {
return {
isLoading: true,
component: null,
};
}
if (!registryState?.[id]) {
return {
isLoading: false,
component: null,
};
}
const registryItem = registryState[id];
const componentLog = log.child({
title: registryItem.title,
description: registryItem.description ?? '',
pluginId: registryItem.pluginId,
});
if (enableRestrictions && isExposedComponentDependencyMissing(id, pluginContext)) {
componentLog.error(errors.EXPOSED_COMPONENT_DEPENDENCY_MISSING);
return {
isLoading: false,
component: null,
};
}
return {
isLoading: false,
component: wrapWithPluginContext(registryItem.pluginId, registryItem.component, componentLog),
};
}, [id, pluginContext, registryState, isLoadingAppPlugins]);
}