ConfigProvider.tsx 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import React, { useEffect, useState } from 'react';
  2. import { createTheme } from '@grafana/data';
  3. import { config, GrafanaBootConfig, ThemeChangedEvent } from '@grafana/runtime';
  4. import { ThemeContext } from '@grafana/ui';
  5. import { appEvents } from '../core';
  6. export const ConfigContext = React.createContext<GrafanaBootConfig>(config);
  7. export const ConfigConsumer = ConfigContext.Consumer;
  8. export const provideConfig = (component: React.ComponentType<any>) => {
  9. const ConfigProvider = (props: any) => (
  10. <ConfigContext.Provider value={config}>{React.createElement(component, { ...props })}</ConfigContext.Provider>
  11. );
  12. return ConfigProvider;
  13. };
  14. export const ThemeProvider = ({ children }: { children: React.ReactNode }) => {
  15. const [theme, setTheme] = useState(getCurrentUserTheme());
  16. useEffect(() => {
  17. const sub = appEvents.subscribe(ThemeChangedEvent, (event) => {
  18. //config.theme = event.payload;
  19. setTheme(event.payload);
  20. });
  21. return () => sub.unsubscribe();
  22. }, []);
  23. return <ThemeContext.Provider value={theme}>{children}</ThemeContext.Provider>;
  24. };
  25. function getCurrentUserTheme() {
  26. return createTheme({
  27. colors: {
  28. mode: config.bootData.user.lightTheme ? 'light' : 'dark',
  29. },
  30. });
  31. }
  32. export const provideTheme = (component: React.ComponentType<any>) => {
  33. return provideConfig((props: any) => <ThemeProvider>{React.createElement(component, { ...props })}</ThemeProvider>);
  34. };