wikimedica-disease-search/app/src/Graph.js

281 lines
7.6 KiB
JavaScript
Raw Normal View History

import React, {useState, useRef, useEffect} from 'react';
import Springy from 'springy';
2019-12-02 05:18:52 +00:00
/**
* Échappe une valeur utilisée dans un sélecteur dattributs CSS.
*
* @param value Valeur à échapper.
* @return Valeur échappée.
*/
const escapeAttrValue = value => value.replace(/"/g, '\\"');
/**
* Crée un identifiant unique pour larête identifiée par ses deux extrémités.
*
* @param from Premier nœud de larête.
* @param to Second nœud de larête.
* @return Identifiant unique pour les deux directions de larête.
*/
const getEdgeId = (from, to) =>
{
if (to < from)
{
2019-12-02 05:18:52 +00:00
[to, from] = [from, to];
}
2019-12-02 05:18:52 +00:00
return JSON.stringify([from, to]);
};
/**
* Vérifie si une liste darêtes contient une arête donnée, dans un sens ou
* dans lautre.
*
* @param list Liste darêtes.
* @param from Premier nœud de larête.
* @param to Second nœud de larête.
* @return Vrai si et seulement si larête existe.
*/
const includesEdge = (list, from, to) =>
list.some(([source, target]) => (
(source === from && target === to)
|| (source === to && target === from)
));
2019-12-02 05:18:52 +00:00
/**
* Recherche parmi les descendants dun élément celui qui représente un
* nœud donnée, sil existe.
*
* @param parent Élément parent.
* @param id Identifiant du nœud recherché.
* @return Élément trouvé ou null sinon.
*/
const findNode = (parent, id) =>
parent.querySelector(`[data-node-id="${escapeAttrValue(id)}"]`);
/**
* Recherche parmi les descendants dun élément celui qui représente une
* arête donnée, sil existe.
*
* @param parent Élément parent.
* @param id Identifiant de larête recherchée.
* @return Élément trouvé ou null sinon.
*/
const findEdge = (parent, id) =>
parent.querySelector(`[data-edge-id="${escapeAttrValue(id)}"]`);
/**
* Recherche le premier élément parent représentant un nœud et renvoie
* lidentifiant de ce nœud.
*
* @param start Élément de départ.
* @return Identifiant de lélément trouvé ou null sinon.
*/
const findParentNode = start =>
{
if (start instanceof window.HTMLDocument)
{
return null;
}
if (start.hasAttribute('data-node-id'))
{
return start.getAttribute('data-node-id');
}
return findParentNode(start.parentNode);
};
/**
* Affiche un graphe.
*
2019-12-02 05:18:52 +00:00
* @prop nodes Liste des identifiants de nœuds du graphe.
* @prop edges Couples didentifiants de nœuds formant les arêtes du graphe.
* @prop render Fonction de rendu prenant en paramètre lidentifiant dun nœud
* du graphe et renvoyant un élément à afficher pour le représenter.
*/
const Graph = ({nodes, edges, render}) =>
{
const [graph,] = useState(new Springy.Graph());
const [layout,] = useState(new Springy.Layout.ForceDirected(
graph,
2019-12-02 05:18:52 +00:00
/* rigidité des arêtes = */ 400,
/* répulsion des nœuds = */ 450,
/* amortissement de vitesse = */ 0.4
));
// Narrête jamais lanimation
layout.minEnergyThreshold = 0;
2019-12-02 05:18:52 +00:00
// Pointeur sur lélément englobant le graphe
const graphParent = useRef(null);
2019-12-02 05:18:52 +00:00
// Ajout des nouveaux nœuds et retrait des anciens
const oldNodes = new Set(Object.keys(graph.nodeSet));
for (let node of nodes)
{
2019-12-02 05:18:52 +00:00
if (!oldNodes.has(node))
{
graph.addNode(new Springy.Node(node));
}
}
2019-12-02 05:18:52 +00:00
for (let node of oldNodes)
{
2019-12-02 05:18:52 +00:00
if (!nodes.includes(node))
{
2019-12-02 05:18:52 +00:00
graph.removeNode({id: node});
}
2019-12-02 05:18:52 +00:00
}
2019-12-02 05:18:52 +00:00
const oldNodePoints = new Set(Object.keys(layout.nodePoints));
for (let node of oldNodePoints)
{
if (!nodes.includes(node))
{
delete layout.nodePoints[node];
}
}
// Ajout des nouvelles arêtes et retrait des anciennes
const newEdges = new Set(edges.map(edge => getEdgeId(...edge)));
const oldEdges = new Set(graph.edges.map(edge => edge.id));
for (let [from, to] of edges)
{
const edgeId = getEdgeId(from, to);
2019-12-02 05:18:52 +00:00
if (!oldEdges.has(edgeId))
{
graph.addEdge(new Springy.Edge(edgeId, {id: from}, {id: to}));
}
}
2019-12-02 05:18:52 +00:00
for (let edge of oldEdges)
{
2019-12-02 05:18:52 +00:00
if (!newEdges.has(edge))
{
2019-12-02 05:18:52 +00:00
graph.removeEdge({id: edge});
}
2019-12-02 05:18:52 +00:00
}
2019-12-02 05:18:52 +00:00
const oldEdgeSprings = new Set(Object.keys(layout.edgeSprings));
2019-12-02 05:18:52 +00:00
for (let edge of oldEdgeSprings)
{
if (!newEdges.has(edge))
{
delete layout.edgeSprings[edge];
}
}
// Rendu de lanimation du graphe
useEffect(() =>
{
2019-12-02 05:18:52 +00:00
const center = () => new Springy.Vector(
window.innerWidth / 2,
window.innerHeight / 2
);
const scale = 50;
const coordsToScreen = vec => vec.multiply(scale).add(center());
const screenToCoords = vec => vec.subtract(center()).divide(scale);
layout.start(() =>
{
layout.eachNode(({id}, {p}) =>
{
2019-12-02 05:18:52 +00:00
const element = findNode(graphParent.current, id);
const {x, y} = coordsToScreen(p);
element.style.transform = `translate(
calc(${x}px - 50%),
calc(${y}px - 50%)
)`;
});
layout.eachEdge(({id}, {point1: {p: p1}, point2: {p: p2}}) =>
{
2019-12-02 05:18:52 +00:00
const element = findEdge(graphParent.current, id);
const {x: x1, y: y1} = coordsToScreen(p1);
const {x: x2, y: y2} = coordsToScreen(p2);
element.setAttribute('x1', x1);
element.setAttribute('y1', y1);
element.setAttribute('x2', x2);
element.setAttribute('y2', y2);
});
});
let dragging = null;
const mouseDown = ev =>
{
const {clientX: x, clientY: y} = ev;
const screen = new Springy.Vector(x, y);
2019-12-02 05:18:52 +00:00
const clickedNode = findParentNode(ev.target);
2019-12-02 05:18:52 +00:00
if (clickedNode !== null)
{
2019-12-02 05:18:52 +00:00
dragging = layout.nodePoints[clickedNode];
dragging.m = Infinity;
}
};
const mouseMove = ev =>
{
if (dragging !== null)
{
const {clientX: x, clientY: y} = ev;
const screen = new Springy.Vector(x, y);
2019-12-02 05:18:52 +00:00
dragging.p = screenToCoords(screen);
}
};
const mouseUp = ev =>
{
if (dragging !== null)
{
2019-12-02 05:18:52 +00:00
dragging.m = 1;
dragging = null;
}
};
graphParent.current.addEventListener('mousedown', mouseDown);
document.body.addEventListener('mousemove', mouseMove);
document.body.addEventListener('mouseup', mouseUp);
return () =>
{
graphParent.current.removeEventListener('mousedown', mouseDown);
document.body.removeEventListener('mousemove', mouseMove);
document.body.removeEventListener('mouseup', mouseUp);
};
2019-12-02 05:18:52 +00:00
}, []);
return (
<div ref={graphParent} className="Graph">
<svg className="Graph_edgesContainer">
{edges.map(edge => (
2019-12-02 05:18:52 +00:00
<line
key={getEdgeId(...edge)}
data-edge-id={getEdgeId(...edge)}
/>
))}
</svg>
{nodes.map(id => (
<span
2019-12-02 05:18:52 +00:00
key={id}
data-node-id={id}
2019-12-02 05:18:52 +00:00
className="Graph_node"
>{render(id)}</span>
))}
</div>
);
};
export default Graph;