From 5a3127949b7d6f3411ef12dbd19e4b6b662b5534 Mon Sep 17 00:00:00 2001 From: psychedelicious <4822129+psychedelicious@users.noreply.github.com> Date: Wed, 21 Aug 2024 18:00:24 +1000 Subject: [PATCH] feat(ui): add CanvasManagerProviderGate This context waits to render its children its until the canvas manager is available. Then its children have access to the manager directly via hook. --- .../contexts/CanvasManagerProviderGate.tsx | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 invokeai/frontend/web/src/features/controlLayers/contexts/CanvasManagerProviderGate.tsx diff --git a/invokeai/frontend/web/src/features/controlLayers/contexts/CanvasManagerProviderGate.tsx b/invokeai/frontend/web/src/features/controlLayers/contexts/CanvasManagerProviderGate.tsx new file mode 100644 index 0000000000..c94af94b92 --- /dev/null +++ b/invokeai/frontend/web/src/features/controlLayers/contexts/CanvasManagerProviderGate.tsx @@ -0,0 +1,25 @@ +import { useStore } from '@nanostores/react'; +import { $canvasManager, type CanvasManager } from 'features/controlLayers/konva/CanvasManager'; +import type { PropsWithChildren } from 'react'; +import { createContext, memo, useContext } from 'react'; +import { assert } from 'tsafe'; + +const CanvasManagerContext = createContext(null); + +export const useCanvasManager = (): CanvasManager => { + const canvasManager = useContext(CanvasManagerContext); + assert(canvasManager, 'useCanvasManagerContext must be used within a CanvasManagerContext'); + return canvasManager; +}; + +export const CanvasManagerProviderGate = memo(({ children }: PropsWithChildren) => { + const canvasManager = useStore($canvasManager); + + if (!canvasManager) { + return null; + } + + return {children}; +}); + +CanvasManagerProviderGate.displayName = 'CanvasManagerProviderGate';