@skillpet/circuit
Version:
Circuit diagram library — render electrical schematics from JSON, with interactive SVG, themes, and Vue/React components
52 lines (51 loc) • 1.79 kB
JavaScript
/// <reference lib="dom" />
/// <reference types="react" />
import { useRef, useEffect, createElement, } from "react";
import { mountFromJson, renderFromJson, } from "../index.js";
export function CircuitDiagram(props) {
const { circuit, options = {}, interactive = false, className, style, onElementClick, onElementHover, onElementLeave, onElementSelect, onCanvasClick, onReady, } = props;
const containerRef = useRef(null);
const ctrlRef = useRef(null);
useEffect(() => {
const el = containerRef.current;
if (!el)
return;
if (ctrlRef.current) {
ctrlRef.current.destroy();
ctrlRef.current = null;
}
if (interactive) {
const ctrl = mountFromJson(el, circuit, {
...options,
interactive: true,
});
ctrlRef.current = ctrl;
if (onElementClick)
ctrl.on("element:click", onElementClick);
if (onElementHover)
ctrl.on("element:hover", onElementHover);
if (onElementLeave)
ctrl.on("element:leave", onElementLeave);
if (onElementSelect)
ctrl.on("element:select", onElementSelect);
if (onCanvasClick)
ctrl.on("canvas:click", onCanvasClick);
if (onReady)
onReady(ctrl);
}
else {
el.innerHTML = renderFromJson(circuit, options);
}
return () => {
if (ctrlRef.current) {
ctrlRef.current.destroy();
ctrlRef.current = null;
}
};
}, [circuit, options, interactive]);
return createElement("div", {
ref: containerRef,
className,
style,
});
}