widgetBuilderContext.tsx 1022 B

12345678910111213141516171819202122232425262728293031323334353637
  1. import type React from 'react';
  2. import {createContext, useContext} from 'react';
  3. import useWidgetBuilderState from '../hooks/useWidgetBuilderState';
  4. const WidgetBuilderContext = createContext<
  5. ReturnType<typeof useWidgetBuilderState> | undefined
  6. >(undefined);
  7. interface WidgetBuilderProviderProps {
  8. children: React.ReactNode;
  9. }
  10. /**
  11. * Provider for maintaining a single source of truth for the widget builder state.
  12. */
  13. export function WidgetBuilderProvider({children}: WidgetBuilderProviderProps) {
  14. const widgetBuilderState = useWidgetBuilderState();
  15. return (
  16. <WidgetBuilderContext.Provider value={widgetBuilderState}>
  17. {children}
  18. </WidgetBuilderContext.Provider>
  19. );
  20. }
  21. /**
  22. * Custom hook to get state and dispatch from the WidgetBuilderContext
  23. */
  24. export const useWidgetBuilderContext = () => {
  25. const context = useContext(WidgetBuilderContext);
  26. if (!context) {
  27. throw new Error(
  28. 'useWidgetBuilderContext must be used within a WidgetBuilderProvider'
  29. );
  30. }
  31. return context;
  32. };