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.
This commit is contained in:
psychedelicious 2024-08-21 18:00:24 +10:00
parent ced934c0a3
commit 5a3127949b

View File

@ -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<CanvasManager | null>(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 <CanvasManagerContext.Provider value={canvasManager}>{children}</CanvasManagerContext.Provider>;
});
CanvasManagerProviderGate.displayName = 'CanvasManagerProviderGate';