All files / apps/web/src/components GraphView.jsx

0% Statements 0/118
0% Branches 0/80
0% Functions 0/28
0% Lines 0/100

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
import { useEffect, useRef, useState } from 'react';
import {
  forceSimulation,
  forceLink,
  forceManyBody,
  forceCenter,
  forceCollide,
  forceX,
  forceY,
} from 'd3-force';
 
const COLORS = {
  uri: '#0d9488', // teal-600
  bnode: '#d97706', // amber-600
  literal: '#94a3b8', // slate-400
};
 
const clamp = (v, min, max) => Math.min(Math.max(v, min), max);
 
// Encombrement d'un nœud : sa pastille + la largeur approximative de son libellé.
const nodeRadius = (d) => (d?.type === 'literal' ? 6 : 9);
const labelWidth = (d) => Math.min(String(d?.label || '').length, 26) * 2.4;
const nodeExtent = (d) => nodeRadius(d) + labelWidth(d) / 2 + 6;
 
/**
 * Vue graphe interactive (force-directed, SVG) : nœuds + liens, drag des nœuds,
 * zoom/pan, clic sur un nœud (callback `onNodeClick`).
 * @param {{ nodes: Array, edges: Array, width?: number, height?: number, onNodeClick?: Function }} props
 */
export default function GraphView({ nodes = [], edges = [], width = 900, height = 560, onNodeClick, selectedId = null, highlightClass = null }) {
  const svgRef = useRef(null);
  const simRef = useRef(null);
  const nodesRef = useRef([]);
  const dragRef = useRef(null);
  const markerIdRef = useRef(`ge-arrow-${Math.random().toString(36).slice(2, 8)}`);
  const markerId = markerIdRef.current;
  const nodeDragMovedRef = useRef(false);
  const [, forceRender] = useState(0);
  const [transform, setTransform] = useState({ k: 1, x: 0, y: 0 });
 
  const linksRef = useRef([]);
 
  // (Re)construit la simulation quand les nœuds/liens changent (positions conservées par id).
  useEffect(() => {
    const prev = new Map(nodesRef.current.map((n) => [n.id, n]));
    const simNodes = nodes.map((n) => {
      const p = prev.get(n.id);
      return { ...n, x: p?.x, y: p?.y, vx: p?.vx, vy: p?.vy };
    });
    const simLinks = edges.map((e) => ({ source: e.source, target: e.target, predicate: e.predicate }));
    linksRef.current = simLinks;
    nodesRef.current = simNodes;
 
    const cx = width / 2;
    const cy = height / 2;
    const sim = forceSimulation(simNodes)
      // Longueur de lien adaptée aux libellés des extrémités (évite les chevauchements).
      .force(
        'link',
        forceLink(simLinks)
          .id((d) => d.id)
          .distance((l) => 70 + labelWidth(l.source) / 2 + labelWidth(l.target) / 2)
          .strength(0.3)
          .iterations(2),
      )
      .force('charge', forceManyBody().strength(-320).distanceMax(700))
      .force('center', forceCenter(cx, cy))
      // Douces attractions vers le centre : graphe plus compact et stable.
      .force('x', forceX(cx).strength(0.04))
      .force('y', forceY(cy).strength(0.06))
      // Empêche le chevauchement des pastilles ET des libellés.
      .force('collide', forceCollide().radius(nodeExtent).strength(0.9))
      .velocityDecay(0.4)
      .alphaDecay(0.022)
      .on('tick', () => forceRender((n) => n + 1));
 
    simRef.current = sim;
    return () => sim.stop();
  }, [nodes, edges, width, height]);
 
  // Calculé à chaque rendu : les positions sont mutées en place par la simulation.
  const posById = {};
  for (const n of nodesRef.current) posById[n.id] = n;
 
  const toLocal = (clientX, clientY) => {
    const rect = svgRef.current.getBoundingClientRect();
    const scaleX = width / rect.width;
    const scaleY = height / rect.height;
    return {
      x: (clientX - rect.left) * scaleX,
      y: (clientY - rect.top) * scaleY,
    };
  };
 
  const onWheel = (e) => {
    e.preventDefault();
    const rect = svgRef.current.getBoundingClientRect();
    // Position du pointeur en coordonnées du viewBox.
    const px = (e.clientX - rect.left) * (width / rect.width);
    const py = (e.clientY - rect.top) * (height / rect.height);
    setTransform((t) => {
      const k = clamp(t.k * (e.deltaY < 0 ? 1.1 : 0.9), 0.2, 4);
      // Garde le point sous le curseur fixe : (px - x) / k invariant.
      const gx = (px - t.x) / t.k;
      const gy = (py - t.y) / t.k;
      return { k, x: px - k * gx, y: py - k * gy };
    });
  };
 
  const onBackgroundDown = (e) => {
    dragRef.current = { type: 'pan', startX: e.clientX, startY: e.clientY, ox: transform.x, oy: transform.y };
    svgRef.current.setPointerCapture?.(e.pointerId);
  };
 
  const onNodeDown = (e, node) => {
    e.stopPropagation();
    const p = toLocal(e.clientX, e.clientY);
    node.fx = (p.x - transform.x) / transform.k;
    node.fy = (p.y - transform.y) / transform.k;
    dragRef.current = { type: 'node', id: node.id, startX: e.clientX, startY: e.clientY };
    nodeDragMovedRef.current = false;
    simRef.current?.alphaTarget(0.3).restart();
  };
 
  const onPointerMove = (e) => {
    const d = dragRef.current;
    if (!d) return;
    if (d.type === 'pan') {
      setTransform((t) => ({ ...t, x: d.ox + (e.clientX - d.startX), y: d.oy + (e.clientY - d.startY) }));
    } else if (d.type === 'node') {
      if (Math.hypot(e.clientX - d.startX, e.clientY - d.startY) > 4) nodeDragMovedRef.current = true;
      const p = toLocal(e.clientX, e.clientY);
      const node = nodesRef.current.find((n) => n.id === d.id);
      if (node) {
        node.fx = (p.x - transform.x) / transform.k;
        node.fy = (p.y - transform.y) / transform.k;
      }
    }
  };
 
  const onPointerUp = () => {
    const d = dragRef.current;
    if (d?.type === 'node') {
      const node = nodesRef.current.find((n) => n.id === d.id);
      if (node) { node.fx = null; node.fy = null; }
      simRef.current?.alphaTarget(0);
    }
    dragRef.current = null;
  };
 
  if (!nodes.length) {
    return <p className="text-sm text-gray-500">Aucun nœud à afficher.</p>;
  }
 
  return (
    <div>
      <svg
        ref={svgRef}
        width="100%"
        viewBox={`0 0 ${width} ${height}`}
        className="border border-gray-200 rounded-lg bg-gray-50 touch-none select-none"
        role="img"
        aria-label="Vue graphe"
        onWheel={onWheel}
        onPointerDown={onBackgroundDown}
        onPointerMove={onPointerMove}
        onPointerUp={onPointerUp}
        onPointerLeave={onPointerUp}
      >
        <defs>
          <marker
            id={markerId}
            viewBox="0 0 10 10"
            refX="9"
            refY="5"
            markerWidth="7"
            markerHeight="7"
            orient="auto"
            markerUnits="userSpaceOnUse"
          >
            <path d="M 0 0 L 10 5 L 0 10 z" fill="#94a3b8" />
          </marker>
        </defs>
        <g transform={`translate(${transform.x},${transform.y}) scale(${transform.k})`}>
          <g>
            {edges.map((e, i) => {
              const s = posById[e.source];
              const t = posById[e.target];
              if (!s || !t) return null;
              const sx = s.x || 0;
              const sy = s.y || 0;
              const tx = t.x || 0;
              const ty = t.y || 0;
              const dx = tx - sx;
              const dy = ty - sy;
              const len = Math.hypot(dx, dy) || 1;
              const ux = dx / len;
              const uy = dy / len;
              const r = 9; // rayon : la flèche s'arrête au bord du nœud cible
              // Grisage : arête hors de la classe surlignée (au moins une extrémité hors classe).
              const dimmed = highlightClass && (s.class !== highlightClass || t.class !== highlightClass);
              return (
                <g key={`e${i}`}>
                  <line
                    x1={sx + ux * r}
                    y1={sy + uy * r}
                    x2={tx - ux * r}
                    y2={ty - uy * r}
                    stroke={dimmed ? '#e2e8f0' : '#cbd5e1'}
                    strokeOpacity={dimmed ? 0.3 : 1}
                    strokeWidth={1.2}
                    markerEnd={`url(#${markerId})`}
                  />
                </g>
              );
            })}
          </g>
          <g>
            {nodesRef.current.map((n) => {
              const dimmed = highlightClass && n.class !== highlightClass;
              return (
                <g
                  key={n.id}
                  transform={`translate(${n.x || 0},${n.y || 0})`}
                  opacity={dimmed ? 0.2 : 1}
                  style={{ cursor: onNodeClick ? 'pointer' : 'grab' }}
                  onPointerDown={(e) => onNodeDown(e, n)}
                  onClick={() => { if (!nodeDragMovedRef.current) onNodeClick?.(n.id); }}
                >
                  <circle
                    r={n.type === 'literal' ? 5 : 8}
                    fill={dimmed ? '#cbd5e1' : (n.color || COLORS[n.type] || COLORS.uri)}
                    stroke={n.id === selectedId ? '#0f172a' : 'none'}
                    strokeWidth={n.id === selectedId ? 2.5 : 0}
                  />
                  <text y={-11} fontSize={9} textAnchor="middle" fill={dimmed ? '#cbd5e1' : '#334155'} fontWeight={n.id === selectedId ? 700 : 400}>
                    {String(n.label).length > 24 ? `${String(n.label).slice(0, 23)}…` : n.label}
                  </text>
                </g>
              );
            })}
          </g>
        </g>
      </svg>
      <p className="text-xs text-gray-400 mt-1">Molette = zoom · glisser le fond = déplacer · glisser un nœud = repositionner{onNodeClick ? ' · clic = étendre' : ''}</p>
    </div>
  );
}