react-phylogeny-tree-gl
Version:
React integration of phylocanvas.gl. Component and hook for phylogenetic tree visualistion.
61 lines • 2.54 kB
JavaScript
import PhylocanvasGL from '@phylocanvas/phylocanvas.gl';
import React from 'react';
const emptyArray = [];
export function usePhylogenyTree(canvasRef, initProps, controlledProps, plugins = emptyArray, hooks = emptyArray) {
const treeInstance = React.useRef(null);
const getTree = React.useCallback(() => treeInstance.current, []);
const [, setIsInit] = React.useState(false);
React.useEffect(() => {
var _a;
if (canvasRef.current) {
const tree = new PhylocanvasGL(canvasRef.current, Object.assign(Object.assign({ size: (_a = canvasRef.current.parentElement) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect() }, initProps), controlledProps), plugins);
treeInstance.current = tree;
setIsInit(true);
return function cleanUp() {
tree.destroy();
setIsInit(false);
};
}
}, [initProps, plugins, canvasRef]);
React.useEffect(() => {
const tree = getTree();
if (tree && controlledProps) {
tree.setProps(controlledProps);
}
}, [controlledProps, getTree]);
const zoomFactor = 0.2;
const handleZoomIn = React.useCallback(() => {
const tree = getTree();
if (tree) {
const { maxZoom, zoom } = tree.getView();
const newZoom = zoom + zoomFactor;
if (newZoom < maxZoom)
tree.setZoom(newZoom);
else if (zoom < maxZoom)
tree.setZoom(maxZoom);
}
}, [getTree]);
const handleZoomOut = React.useCallback(() => {
const tree = getTree();
if (tree) {
const { minZoom, zoom } = tree.getView();
const newZoom = zoom - zoomFactor;
if (newZoom > minZoom)
tree.setZoom(newZoom);
else if (zoom > minZoom)
tree.setZoom(minZoom);
}
}, [getTree]);
loopHooks(hooks, getTree, Object.assign(Object.assign({}, initProps), controlledProps));
return { handleZoomIn, handleZoomOut, getTree };
}
export const loopHooks = (hooks, getInstance, props) => {
hooks.forEach((hook) => {
const nextValue = hook(getInstance, props);
if (process && process.env.NODE_ENV === 'development')
if (typeof nextValue !== 'undefined') {
throw new Error('react-phylogeny-tree.gl: A loop-type hook ☝️ just returned a value! This is not allowed.');
}
});
};
//# sourceMappingURL=usePhylogenyTree.js.map