flamegraphThemeProvider.tsx 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import {createContext, useCallback, useMemo, useState} from 'react';
  2. import cloneDeep from 'lodash/cloneDeep';
  3. import ConfigStore from 'sentry/stores/configStore';
  4. import {useLegacyStore} from 'sentry/stores/useLegacyStore';
  5. import {
  6. DarkFlamegraphTheme,
  7. FlamegraphTheme,
  8. LightFlamegraphTheme,
  9. } from 'sentry/utils/profiling/flamegraph/flamegraphTheme';
  10. export const FlamegraphThemeContext = createContext<FlamegraphTheme | null>(null);
  11. type FlamegraphThemeMutationCallback = (
  12. theme: FlamegraphTheme,
  13. colorMode?: 'light' | 'dark'
  14. ) => FlamegraphTheme;
  15. export const FlamegraphThemeMutationContext = createContext<
  16. ((cb: FlamegraphThemeMutationCallback) => void) | null
  17. >(null);
  18. interface FlamegraphThemeProviderProps {
  19. children: React.ReactNode;
  20. }
  21. function FlamegraphThemeProvider(
  22. props: FlamegraphThemeProviderProps
  23. ): React.ReactElement {
  24. const {theme: colorMode} = useLegacyStore(ConfigStore);
  25. const [mutation, setMutation] = useState<FlamegraphThemeMutationCallback | null>(null);
  26. const addModifier = useCallback((cb: FlamegraphThemeMutationCallback) => {
  27. setMutation(() => cb);
  28. }, []);
  29. const activeFlamegraphTheme = useMemo(() => {
  30. const flamegraphTheme =
  31. colorMode === 'light' ? LightFlamegraphTheme : DarkFlamegraphTheme;
  32. if (!mutation) {
  33. return flamegraphTheme;
  34. }
  35. const clonedTheme = cloneDeep(flamegraphTheme);
  36. return mutation(clonedTheme, colorMode);
  37. }, [mutation, colorMode]);
  38. return (
  39. <FlamegraphThemeMutationContext.Provider value={addModifier}>
  40. <FlamegraphThemeContext.Provider value={activeFlamegraphTheme}>
  41. {props.children}
  42. </FlamegraphThemeContext.Provider>
  43. </FlamegraphThemeMutationContext.Provider>
  44. );
  45. }
  46. export {FlamegraphThemeProvider};