grafana/public/app/core/context/GrafanaContext.ts
2024-02-02 13:14:58 +01:00

44 lines
1.3 KiB
TypeScript

import React, { useCallback, useContext } from 'react';
import { GrafanaConfig } from '@grafana/data';
import { LocationService, locationService, BackendSrv } from '@grafana/runtime';
import { AppChromeService } from '../components/AppChrome/AppChromeService';
import { NewFrontendAssetsChecker } from '../services/NewFrontendAssetsChecker';
import { KeybindingSrv } from '../services/keybindingSrv';
export interface GrafanaContextType {
backend: BackendSrv;
location: LocationService;
config: GrafanaConfig;
chrome: AppChromeService;
keybindings: KeybindingSrv;
newAssetsChecker: NewFrontendAssetsChecker;
}
export const GrafanaContext = React.createContext<GrafanaContextType | undefined>(undefined);
export function useGrafana(): GrafanaContextType {
const context = useContext(GrafanaContext);
if (!context) {
throw new Error('No GrafanaContext found');
}
return context;
}
// Implementation of useReturnToPrevious that's made available through
// @grafana/runtime
export function useReturnToPreviousInternal() {
const { chrome } = useGrafana();
return useCallback(
(title: string, href?: string) => {
const { pathname, search } = locationService.getLocation();
chrome.setReturnToPrevious({
title: title,
href: href ?? pathname + search,
});
},
[chrome]
);
}