2021-02-20 09:02:06 +01:00
|
|
|
import React, { useEffect, useState } from 'react';
|
2019-06-19 11:31:47 -07:00
|
|
|
import { config, GrafanaBootConfig } from '@grafana/runtime';
|
2021-02-20 09:02:06 +01:00
|
|
|
import { ThemeContext } from '@grafana/ui';
|
|
|
|
|
import { appEvents } from '../core';
|
|
|
|
|
import { ThemeChangedEvent } from 'app/types/events';
|
|
|
|
|
import { GrafanaTheme } from '@grafana/data';
|
2019-01-18 09:50:29 +01:00
|
|
|
|
2019-06-19 11:31:47 -07:00
|
|
|
export const ConfigContext = React.createContext<GrafanaBootConfig>(config);
|
2019-01-18 09:50:29 +01:00
|
|
|
export const ConfigConsumer = ConfigContext.Consumer;
|
|
|
|
|
|
|
|
|
|
export const provideConfig = (component: React.ComponentType<any>) => {
|
|
|
|
|
const ConfigProvider = (props: any) => (
|
|
|
|
|
<ConfigContext.Provider value={config}>{React.createElement(component, { ...props })}</ConfigContext.Provider>
|
|
|
|
|
);
|
|
|
|
|
return ConfigProvider;
|
|
|
|
|
};
|
|
|
|
|
|
2021-02-20 09:02:06 +01:00
|
|
|
export const ThemeProvider = ({ children }: { children: React.ReactNode }) => {
|
|
|
|
|
const [theme, setTheme] = useState<GrafanaTheme>(config.theme);
|
2019-01-18 09:50:29 +01:00
|
|
|
|
2021-02-20 09:02:06 +01:00
|
|
|
useEffect(() => {
|
|
|
|
|
const sub = appEvents.subscribe(ThemeChangedEvent, (event) => {
|
|
|
|
|
config.theme = event.payload;
|
|
|
|
|
setTheme(event.payload);
|
|
|
|
|
});
|
2019-01-18 09:50:29 +01:00
|
|
|
|
2021-02-20 09:02:06 +01:00
|
|
|
return () => sub.unsubscribe();
|
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
|
|
return <ThemeContext.Provider value={theme}>{children}</ThemeContext.Provider>;
|
2019-01-18 09:50:29 +01:00
|
|
|
};
|
2019-02-05 17:04:48 +01:00
|
|
|
|
|
|
|
|
export const provideTheme = (component: React.ComponentType<any>) => {
|
|
|
|
|
return provideConfig((props: any) => <ThemeProvider>{React.createElement(component, { ...props })}</ThemeProvider>);
|
|
|
|
|
};
|