UNPKG

@gravity-ui/graph

Version:

Modern graph editor component

47 lines (46 loc) 1.95 kB
import React, { useEffect, useLayoutEffect, useRef } from "react"; import { setCssProps } from "../utils/functions/cssProp"; import { GraphContextProvider } from "./GraphContext"; import { useLayer } from "./hooks"; import { useGraphEvent, useGraphEvents } from "./hooks/useGraphEvents"; import { ReactLayer } from "./layer"; import { cn } from "./utils/cn"; import { useFn } from "./utils/hooks/useFn"; import "./graph-canvas.css"; export function GraphCanvas({ graph, className, blockListClassName, renderBlock, reactLayerRef, children, ...cbs }) { const containerRef = useRef(); const reactLayer = useLayer(graph, ReactLayer, { blockListClassName, }); if (reactLayerRef) { reactLayerRef.current = reactLayer; } useEffect(() => { if (containerRef.current) { graph.attach(containerRef.current); } return () => { graph.detach(); }; }, [graph, containerRef]); useGraphEvents(graph, cbs); const setColors = useFn((colors) => { setCssProps(containerRef.current, { "--graph-block-bg": colors.block.background, "--graph-block-border": colors.block.border, "--graph-block-border-selected": colors.block.selectedBorder, "--graph-block-anchor-bg": colors.anchor.background, "--graph-block-anchor-border-selected": colors.anchor.selectedBorder, }); }); useLayoutEffect(() => { setColors(graph.graphColors); }, [graph, setColors]); useGraphEvent(graph, "colors-changed", ({ colors }) => { setColors(colors); }); return (React.createElement(GraphContextProvider, { graph: graph }, React.createElement("div", { className: cn("graph-wrapper", className) }, React.createElement("div", { className: "graph-canvas", ref: containerRef }, graph && reactLayer && reactLayer.renderPortal(renderBlock)), children))); }