widgetSyncContext.tsx 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import type {ReactNode} from 'react';
  2. import type {EChartsType} from 'echarts';
  3. import * as echarts from 'echarts';
  4. import {uniqueId} from 'sentry/utils/guid';
  5. import {createDefinedContext} from 'sentry/utils/performance/contexts/utils';
  6. type RegistrationFunction = (chart: EChartsType) => void;
  7. interface WidgetSyncContext {
  8. register: RegistrationFunction;
  9. }
  10. const [_WidgetSyncProvider, _useWidgetSyncContext, WidgetSyncContext] =
  11. createDefinedContext<WidgetSyncContext>({
  12. name: 'WidgetSyncContext',
  13. strict: false,
  14. });
  15. interface WidgetSyncContextProviderProps {
  16. children: ReactNode;
  17. groupName?: string;
  18. }
  19. export function WidgetSyncContextProvider({
  20. children,
  21. groupName = uniqueId(),
  22. }: WidgetSyncContextProviderProps) {
  23. const register: RegistrationFunction = chart => {
  24. chart.group = groupName;
  25. echarts?.connect(groupName);
  26. };
  27. return (
  28. <_WidgetSyncProvider
  29. value={{
  30. register,
  31. }}
  32. >
  33. {children}
  34. </_WidgetSyncProvider>
  35. );
  36. }
  37. export {WidgetSyncContext};
  38. export function useWidgetSyncContext(): WidgetSyncContext {
  39. const context = _useWidgetSyncContext();
  40. if (!context) {
  41. // The provider was not registered, return a dummy function
  42. return {
  43. register: (_p: any) => null,
  44. };
  45. }
  46. return context;
  47. }