From 7cc06043601a483c1e578e97687732a276810192 Mon Sep 17 00:00:00 2001 From: Bogdan Matei Date: Mon, 9 Dec 2024 16:37:50 +0200 Subject: [PATCH] Scopes: Add ScopesContext to `@grafana/runtime` (#97566) --- .../src/services/ScopesContext.ts | 61 +++++++++++++++++++ .../grafana-runtime/src/services/index.ts | 2 + 2 files changed, 63 insertions(+) create mode 100644 packages/grafana-runtime/src/services/ScopesContext.ts diff --git a/packages/grafana-runtime/src/services/ScopesContext.ts b/packages/grafana-runtime/src/services/ScopesContext.ts new file mode 100644 index 00000000000..0c7faade62c --- /dev/null +++ b/packages/grafana-runtime/src/services/ScopesContext.ts @@ -0,0 +1,61 @@ +import { createContext, useContext } from 'react'; +import { useObservable } from 'react-use'; +import { Observable } from 'rxjs'; + +import { Scope } from '@grafana/data'; + +export interface ScopesContextValueState { + drawerOpened: boolean; + enabled: boolean; + loading: boolean; + readOnly: boolean; + value: Scope[]; +} + +export interface ScopesContextValue { + /** + * Current state. + */ + state: ScopesContextValueState; + + /** + * Observable that emits the current state. + */ + stateObservable: Observable; + + /** + * Change the selected scopes. The service takes care about loading them and propagating the changes. + * @param scopeNames + */ + changeScopes(scopeNames: string[]): void; + + /** + * Set read-only mode. + * If `readOnly` is `true`, the selector will be set to read-only and the dashboards panel will be closed. + */ + setReadOnly(readOnly: boolean): void; + + /** + * Enable or disable the usage of scopes. + * This will hide the selector and the dashboards panel, and it will stop propagating the scopes to the query object. + */ + setEnabled(enabled: boolean): void; +} + +export const ScopesContext = createContext(undefined); + +export function useScopes(): ScopesContextValue | undefined { + const context = useContext(ScopesContext); + + useObservable(context?.stateObservable ?? new Observable(), context?.state); + + return context + ? { + state: context.state, + stateObservable: context.stateObservable, + changeScopes: context.changeScopes, + setReadOnly: context.setReadOnly, + setEnabled: context.setEnabled, + } + : undefined; +} diff --git a/packages/grafana-runtime/src/services/index.ts b/packages/grafana-runtime/src/services/index.ts index ee4d014e3c9..d36825cb48d 100644 --- a/packages/grafana-runtime/src/services/index.ts +++ b/packages/grafana-runtime/src/services/index.ts @@ -36,3 +36,5 @@ export { setPluginLinksHook, usePluginLinks } from './pluginExtensions/usePlugin export { isPluginExtensionLink, isPluginExtensionComponent } from './pluginExtensions/utils'; export { setCurrentUser } from './user'; + +export { ScopesContext, type ScopesContextValueState, type ScopesContextValue, useScopes } from './ScopesContext';