@gravity-ui/graph
Version:
Modern graph editor component
25 lines (24 loc) • 1.1 kB
JavaScript
import { forwardRef, useImperativeHandle, useState } from "react";
import { GraphState } from "../graph";
import { useGraphContext } from "./GraphContext";
import { useGraphEvent } from "./hooks/useGraphEvents";
import { useLayer } from "./hooks/useLayer";
/**
* GraphLayer component provides declarative way to add existing Layer classes to the graph
*/
export const GraphLayer = forwardRef(function GraphLayer({ layer: LayerClass, props }, ref) {
// Get graph from context
const { graph } = useGraphContext();
// Track graph state to determine readiness for layer creation
const [_graphState, setGraphState] = useState(graph?.state ?? GraphState.INIT);
// Subscribe to graph state changes
useGraphEvent(graph, "state-change", ({ state }) => {
setGraphState(state);
});
// Always create layer using useLayer (hooks must be called unconditionally)
const layer = useLayer(graph, LayerClass, props);
// Expose layer through ref
useImperativeHandle(ref, () => layer, [layer]);
// GraphLayer doesn't render any visible content
return null;
});