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

73.07% Statements 209/286
58.18% Branches 96/165
77.08% Functions 37/48
76.54% Lines 186/243

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 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524                                1x           1x 1x 1x 1x 1x   1x 1x 1x 1x     1x 1x 1x 1x   1x                 1x 264x                                                 24x 24x 24x 24x   24x 24x     24x 24x     24x   24x 24x         24x   91x   68x       24x         24x 24x 24x   22x 22x   83x 83x         62x 60x   22x 22x       24x 24x 91x 24x       24x 22x 22x 4x 4x 9x 6x   4x             24x 2x 2x 2x 2x     2x                     24x 22x       24x 22x 22x 20x 20x 20x       24x 21x 21x   21x 1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x     21x   21x 21x 21x 21x 21x 21x 21x 21x         24x 21x 21x 20x 20x 20x 20x 20x             24x 21x 21x       24x                                                                                               24x                                                       24x   2x 2x 2x 2x   2x     2x         2x 2x   2x 2x 2x 2x     2x 2x     2x 2x 2x 2x     2x 2x   2x       2x   2x 2x 2x     2x 2x 8x 8x 8x   2x           2x 2x           24x 2x     2x         24x 22x           24x 22x 18x 18x   4x 4x 4x           24x   24x   6x 5x         24x 2x 2x     2x     24x     24x   4x         24x 3x       24x 3x             24x   11x 6x 6x       6x 6x   6x 6x 6x   6x   3x 3x 3x 3x 3x         24x 1x     23x                                                                 2x                  
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Group, Vector3 } from 'three';
import ForceGraph3D from 'react-force-graph-3d';
import { makeLabelSprite, scaleLabelSprite } from './graph3d/labels';
import { makeRingSprite } from './graph3d/ring';
import { applyForces } from './graph3d/forces';
import { createGizmo, disposeGizmo, updateGizmo } from './graph3d/gizmo';
import { fitDistanceForNodes, focusCamera, measureNodes } from './graph3d/geometry';
import { prefixedIri } from '../utils/iri';
import { escapeHtml, truncate } from '../utils/text';
 
/**
 * Normes graphiques alignées sur `GraphView` (2D) :
 * couleur par classe (angle d'or), arêtes `slate-300` fléchées, contour sombre
 * pour la sélection, atténuation du reste lors du surlignage de classe.
 */
const COLORS = {
  uri: '#0d9488', // teal-600
  bnode: '#d97706', // amber-600
  literal: '#94a3b8', // slate-400
};
 
const SELECTION_RING = '#0f172a'; // slate-900 — équivalent du `stroke` 2D
const DIMMED_NODE = '#e2e8f0'; // slate-200 — hors classe surlignée
const LINK = '#cbd5e1'; // slate-300
const DIMMED_LINK = '#e2e8f0'; // slate-200
const BACKGROUND = '#f8fafc'; // slate-50, identique à la 2D
 
const TOOLTIP_MAX_CHARS = 80;
const LABEL_MAX_CHARS = 24;
const RING_SCALE = 22; // diamètre du contour > sphère (rayon 7) + marge
const MIN_CANVAS_WIDTH = 320;
// Simulation bornée : sans cela, l'expansion continue après le cadrage et la
// caméra laisse fuir les nœuds hors du champ.
const FOCUS_DURATION = 600;
const COOLDOWN_TICKS = 220;
const COOLDOWN_TIME = 9000;
const ALPHA_DECAY = 0.035;
 
const prefersReducedMotion = () => {
  try {
    return Boolean(window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches);
  } catch {
    return false;
  }
};
 
/** Id d'une extrémité de lien : nœud (après init de la simulation) ou id brut. */
const endpointId = (endpoint) =>
  endpoint && typeof endpoint === 'object' ? endpoint.id : endpoint;
 
/**
 * Vue graphe 3D interactive (force-directed, WebGL) : nœuds + liens, rotation,
 * zoom, drag des nœuds, clic sur un nœud (callback `onNodeClick`).
 *
 * Navigation reprise du mode 3D de la veille (`static/veille/src/lib/graph3d.js`) :
 * repère du centre d'orbite à taille d'écran constante, cible d'orbite recentrée
 * sur la boîte englobante, simulation bornée puis cadrage, curseur de survol,
 * libération explicite des ressources.
 *
 * Même signature de props que `GraphView` (2D) pour être interchangeable ;
 * chargée paresseusement par `SemanticGraphViewer` (three.js hors du bundle initial).
 *
 * @param {{ nodes: Array, edges: Array, height?: number, onNodeClick?: Function,
 *           selectedId?: string|null, highlightClass?: string|null }} props
 */
export default function GraphView3D({
  nodes = [],
  edges = [],
  height = 560,
  onNodeClick,
  selectedId = null,
  highlightClass = null,
}) {
  const fgRef = useRef(null);
  const containerRef = useRef(null);
  const gizmoRef = useRef(null);
  const controlsRef = useRef(null);
  // Libellés affichés (sélection + voisinage) → re-dimensionnés à taille d'écran constante.
  const labelSpritesRef = useRef(new Map());
  const labelledIdsRef = useRef(new Set());
  // La librairie ne s'adapte pas seule au conteneur (défaut : largeur de la fenêtre) :
  // on mesure le parent pour rester dans le flex du viewer, panneau ouvert ou non.
  const [containerWidth, setContainerWidth] = useState(0);
  const forcesAppliedRef = useRef(false);
  // Le cadrage n'a de sens qu'une fois la simulation stabilisée : avant, les
  // positions bougent encore et la caméra serait cadrée sur un nuage transitoire.
  const engineStoppedRef = useRef(false);
  // Animation de caméra en cours (recentrage sur un nœud).
  const cameraAnimRef = useRef(0);
  const lastSelectionRef = useRef(null);
 
  // Signature du contenu : le parent peut recréer ses tableaux à chaque rendu
  // (sélection, panneau…). Sans cette signature, la librairie verrait de
  // « nouvelles » données et relancerait la simulation à chaque clic.
  const dataSignature = useMemo(
    () =>
      nodes.map((n) => [n.id, n.label, n.class, n.color, n.type].join('\u0001')).join('\u0002') +
      '\u0003' +
      edges.map((e) => `${endpointId(e?.source)}>${e?.predicate}>${endpointId(e?.target)}`).join('\u0002'),
    [nodes, edges],
  );
 
  const graphDataRef = useRef({ signature: '', data: { nodes: [], links: [] } });
 
  // La simulation MUTE les objets reçus : on lui donne des copies. Elles ne sont
  // reconstruites que si le CONTENU change, et les positions déjà calculées sont
  // conservées (une expansion ajoute des nœuds sans refaire la disposition).
  const graphData = useMemo(() => {
    const previous = graphDataRef.current;
    if (previous.signature === dataSignature) return previous.data;
 
    const known = new Map(previous.data.nodes.map((n) => [n.id, n]));
    const data = {
      nodes: nodes.map((n) => {
        const seen = known.get(n.id);
        return seen
          ? { ...n, x: seen.x, y: seen.y, z: seen.z, vx: seen.vx, vy: seen.vy, vz: seen.vz }
          : { ...n };
      }),
      links: edges
        .filter((e) => e && e.source != null && e.target != null)
        .map((e) => ({ source: endpointId(e.source), target: endpointId(e.target), predicate: e.predicate })),
    };
    graphDataRef.current = { signature: dataSignature, data };
    return data;
  }, [dataSignature, nodes, edges]);
 
  // Classe par sujet : les liens portent des ids, il faut la retrouver pour l'atténuation.
  const classById = useMemo(() => {
    const map = new Map();
    for (const n of nodes) map.set(n.id, n.class || null);
    return map;
  }, [nodes]);
 
  // Nœud sélectionné + voisinage direct (entrant et sortant) → seuls nœuds libellés.
  const labelledIds = useMemo(() => {
    const ids = new Set();
    if (!selectedId) return ids;
    ids.add(selectedId);
    for (const link of graphData.links) {
      if (link.source === selectedId) ids.add(link.target);
      else if (link.target === selectedId) ids.add(link.source);
    }
    return ids;
  }, [graphData.links, selectedId]);
 
  /**
   * Aligne le repère et la taille des libellés sur la caméra : norme 2D
   * (libellé de taille fixe à l'écran) transposée en 3D.
   */
  const syncCamera = useCallback(() => {
    const camera = fgRef.current?.camera?.();
    const target = controlsRef.current?.target;
    updateGizmo(gizmoRef.current, target, camera);
    const distance = target && typeof camera?.position?.distanceTo === 'function'
      ? camera.position.distanceTo(target)
      : 0;
    for (const [id, sprite] of labelSpritesRef.current) {
      // Purge des libellés qui ne font plus partie de la sélection/voisinage.
      if (!labelledIdsRef.current.has(id)) {
        labelSpritesRef.current.delete(id);
        continue;
      }
      scaleLabelSprite(sprite, distance);
    }
  }, []);
 
  // Le nettoyage des libellés a besoin de l'ensemble courant hors du rendu.
  useEffect(() => {
    labelledIdsRef.current = labelledIds;
  }, [labelledIds]);
 
  // Forces alignées sur la 2D — appliquées une fois le graphe monté.
  useEffect(() => {
    const fg = fgRef.current;
    if (!fg || forcesAppliedRef.current) return;
    applyForces(fg);
    forcesAppliedRef.current = true;
    fg.d3ReheatSimulation?.();
  }, [graphData]);
 
  // Repère du centre d'orbite — attaché dès que la scène et les contrôles existent.
  useEffect(() => {
    let cancelled = false;
    let frame = 0;
 
    const attach = () => {
      Iif (cancelled || gizmoRef.current) return;
      const fg = fgRef.current;
      const scene = typeof fg?.scene === 'function' ? fg.scene() : null;
      const controls = typeof fg?.controls === 'function' ? fg.controls() : null;
      Iif (!scene || !controls) {
        frame = requestAnimationFrame(attach);
        return;
      }
      const gizmo = createGizmo();
      gizmo.visible = false;
      scene.add(gizmo);
      gizmoRef.current = gizmo;
      controlsRef.current = controls;
      controls.addEventListener('change', syncCamera);
    };
 
    frame = requestAnimationFrame(attach);
 
    return () => {
      cancelled = true;
      cancelAnimationFrame(frame);
      const controls = controlsRef.current;
      controls?.removeEventListener?.('change', syncCamera);
      controlsRef.current = null;
      disposeGizmo(gizmoRef.current);
      gizmoRef.current = null;
    };
  }, [syncCamera]);
 
  // Suit la largeur du conteneur (redimensionnement, ouverture du panneau à 50 %).
  useEffect(() => {
    const element = containerRef.current;
    if (!element) return undefined;
    const measure = () => setContainerWidth(element.clientWidth || 0);
    measure();
    Eif (typeof ResizeObserver === 'undefined') {
      window.addEventListener('resize', measure);
      return () => window.removeEventListener('resize', measure);
    }
    const observer = new ResizeObserver(measure);
    observer.observe(element);
    return () => observer.disconnect();
  }, []);
 
  const stopCameraAnimation = useCallback(() => {
    Iif (cameraAnimRef.current) cancelAnimationFrame(cameraAnimRef.current);
    cameraAnimRef.current = 0;
  }, []);
 
  /** Déplace la caméra vers une cible (animation courte, ou instantané). */
  const moveCamera = useCallback(
    (focus, { animate = true } = {}) => {
      const fg = fgRef.current;
      const controls = controlsRef.current || fg?.controls?.();
      const camera = fg?.camera?.();
      if (!focus || !controls?.target || !camera) return;
 
      stopCameraAnimation();
      const { target: to, position: toPosition } = focus;
      const duration = animate && !prefersReducedMotion() ? FOCUS_DURATION : 0;
 
      if (!duration) {
        controls.target.set(to.x, to.y, to.z);
        camera.position.set(toPosition.x, toPosition.y, toPosition.z);
        controls.update?.();
        syncCamera();
        return;
      }
 
      const fromTarget = { x: controls.target.x, y: controls.target.y, z: controls.target.z };
      const fromPosition = { x: camera.position.x, y: camera.position.y, z: camera.position.z };
      const startedAt = performance.now();
      const ease = (t) => (t < 0.5 ? 4 * t * t * t : 1 - ((-2 * t + 2) ** 3) / 2);
 
      const step = (now) => {
        const t = Math.min(1, (now - startedAt) / duration);
        const k = ease(t);
        controls.target.set(
          fromTarget.x + (to.x - fromTarget.x) * k,
          fromTarget.y + (to.y - fromTarget.y) * k,
          fromTarget.z + (to.z - fromTarget.z) * k,
        );
        camera.position.set(
          fromPosition.x + (toPosition.x - fromPosition.x) * k,
          fromPosition.y + (toPosition.y - fromPosition.y) * k,
          fromPosition.z + (toPosition.z - fromPosition.z) * k,
        );
        controls.update?.();
        syncCamera();
        cameraAnimRef.current = t < 1 ? requestAnimationFrame(step) : 0;
      };
 
      cameraAnimRef.current = requestAnimationFrame(step);
    },
    [stopCameraAnimation, syncCamera],
  );
 
  /** Recentre la caméra sur un nœud en conservant l'orientation et le zoom. */
  const focusOnNode = useCallback(
    (node, options = {}) => {
      const fg = fgRef.current;
      const controls = controlsRef.current || fg?.controls?.();
      const camera = fg?.camera?.();
      if (!node || !controls?.target || !camera) return;
 
      const distance = Math.hypot(
        camera.position.x - controls.target.x,
        camera.position.y - controls.target.y,
        camera.position.z - controls.target.z,
      );
      const focus = focusCamera({
        node,
        cameraPosition: camera.position,
        target: controls.target,
        distance,
      });
      moveCamera(focus, options);
    },
    [moveCamera],
  );
 
  /**
   * Cadre le graphe. Si un nœud est sélectionné, la caméra se recentre sur lui
   * (navigation) ; sinon elle cadre l'ensemble des nœuds avec une vérification
   * finale en espace écran (un nœud proche peut sortir malgré le calcul).
   */
  const frameCamera = useCallback(
    (options = {}) => {
      const fg = fgRef.current;
      const controls = controlsRef.current || fg?.controls?.();
      const camera = fg?.camera?.();
      Iif (!controls?.target || !camera) return;
 
      const selectedNode = selectedId
        ? graphData.nodes.find((n) => n.id === selectedId && Number.isFinite(n.x))
        : null;
      Iif (selectedNode) {
        focusOnNode(selectedNode, options);
        return;
      }
 
      const box = measureNodes(graphData.nodes);
      Iif (!box) return;
 
      const aspect = (containerWidth || MIN_CANVAS_WIDTH) / height;
      Eif (typeof camera.aspect === 'number') {
        camera.aspect = aspect;
        camera.updateProjectionMatrix?.();
      }
 
      const { x, y, z } = box.center;
      controls.target.set(x, y, z);
 
      // On conserve l'orientation courante et on ne règle que la distance.
      let dx = camera.position.x - x;
      let dy = camera.position.y - y;
      let dz = camera.position.z - z;
      Iif (Math.hypot(dx, dy, dz) < 1e-6) {
        dx = 0.5; dy = 0.3; dz = 1;
      }
      const length = Math.hypot(dx, dy, dz);
      dx /= length; dy /= length; dz /= length;
 
      let distance = fitDistanceForNodes(graphData.nodes, { x: dx, y: dy, z: dz }, {
        fovDeg: camera.fov || 50,
        aspect,
      });
      Iif (!distance) return;
 
      const place = (value) => camera.position.set(x + dx * value, y + dy * value, z + dz * value);
      place(distance);
      camera.updateMatrixWorld?.(true);
 
      // Correction en espace écran : NDC hors de [-0.85, 0.85] → on recule.
      let overflow = 0;
      for (const node of graphData.nodes) {
        Iif (!Number.isFinite(node?.x)) continue;
        const projected = new Vector3(node.x, node.y, node.z).project(camera);
        overflow = Math.max(overflow, Math.abs(projected.x), Math.abs(projected.y));
      }
      Iif (Number.isFinite(overflow) && overflow > 0.85) {
        distance *= overflow / 0.85;
        place(distance);
        camera.updateMatrixWorld?.(true);
      }
 
      controls.update?.();
      syncCamera();
    },
    [selectedId, graphData.nodes, containerWidth, height, focusOnNode, syncCamera],
  );
 
  // Cadrage après stabilisation de la simulation (et à chaque nouvelle expansion).
  const handleEngineStop = useCallback(() => {
    engineStoppedRef.current = true;
    // Une frame de marge : les positions du dernier tick doivent être appliquées
    // avant de calculer la boîte englobante.
    requestAnimationFrame(() => frameCamera({ animate: false }));
  }, [frameCamera]);
 
  // Le conteneur change de largeur (panneau ouvert, fenêtre redimensionnée) :
  // on recadre, mais seulement si la simulation est déjà stabilisée.
  useEffect(() => {
    Eif (!containerWidth || !engineStoppedRef.current) return undefined;
    const frame = requestAnimationFrame(() => frameCamera({ animate: true }));
    return () => cancelAnimationFrame(frame);
  }, [containerWidth, frameCamera]);
 
  // Sélection d'un nœud (clic 3D, ou depuis la 2D) → recentrage de la caméra.
  useEffect(() => {
    if (!selectedId) {
      lastSelectionRef.current = null;
      return;
    }
    Iif (lastSelectionRef.current === selectedId) return;
    lastSelectionRef.current = selectedId;
    Eif (!engineStoppedRef.current) return;
    const node = graphData.nodes.find((n) => n.id === selectedId);
    if (node) focusOnNode(node);
  }, [selectedId, graphData.nodes, focusOnNode]);
 
  // Coupe l'animation de caméra au démontage.
  useEffect(() => stopCameraAnimation, [stopCameraAnimation]);
 
  const nodeColor = useCallback(
    (node) => {
      if (highlightClass && node.class !== highlightClass) return DIMMED_NODE;
      return node.color || COLORS[node.type] || COLORS.uri;
    },
    [highlightClass],
  );
 
  const nodeLabel = useCallback((node) => {
    const label = escapeHtml(truncate(node.label ?? node.id, TOOLTIP_MAX_CHARS));
    const cls = node.class
      ? `<div style="color:#64748b;font-size:11px">${escapeHtml(prefixedIri(node.class))}</div>`
      : '';
    return `<div>${label}</div>${cls}`;
  }, []);
 
  const linkLabel = useCallback((link) => escapeHtml(prefixedIri(link.predicate)), []);
 
  // Atténuation : un lien n'est « dans la classe » que si ses DEUX extrémités le sont.
  const isLinkInClass = useCallback(
    (link) =>
      classById.get(endpointId(link.source)) === highlightClass &&
      classById.get(endpointId(link.target)) === highlightClass,
    [classById, highlightClass],
  );
 
  const linkColor = useCallback(
    (link) => (!highlightClass || isLinkInClass(link) ? LINK : DIMMED_LINK),
    [highlightClass, isLinkInClass],
  );
 
  const linkWidth = useCallback(
    (link) => (!highlightClass || isLinkInClass(link) ? 1.2 : 0.4),
    [highlightClass, isLinkInClass],
  );
 
  // Libellé permanent : sélection + voisinage uniquement (sinon la scène devient
  // illisible). Le nœud sélectionné conserve sa couleur de classe et reçoit un
  // contour sombre, comme le `stroke` du graphe 2D.
  const nodeThreeObject = useCallback(
    (node) => {
      if (!labelledIds.has(node.id)) return null;
      const selected = node.id === selectedId;
      const label = makeLabelSprite(truncate(node.label ?? node.id, LABEL_MAX_CHARS), {
        selected,
        color: '#334155',
      });
      Iif (!label) return null;
      labelSpritesRef.current.set(node.id, label);
      // Taille d'écran dès la création (le prochain `change` de la caméra affinera).
      const camera = fgRef.current?.camera?.();
      const target = controlsRef.current?.target;
      Iif (camera && target) scaleLabelSprite(label, camera.position.distanceTo(target));
 
      if (!selected) return label;
 
      const group = new Group();
      group.add(label);
      const ring = makeRingSprite(SELECTION_RING, { scale: RING_SCALE, thickness: 6 });
      Eif (ring) group.add(ring);
      return group;
    },
    [labelledIds, selectedId],
  );
 
  if (!nodes.length) {
    return <p className="text-sm text-gray-500">Aucun nœud à afficher.</p>;
  }
 
  return (
    <div
      ref={containerRef}
      data-testid="graph-3d"
      role="img"
      aria-label="Vue graphe 3D"
      className="border border-gray-200 rounded-lg bg-gray-50 overflow-hidden"
    >
      <ForceGraph3D
        ref={fgRef}
        graphData={graphData}
        width={Math.max(containerWidth, MIN_CANVAS_WIDTH)}
        height={height}
        backgroundColor={BACKGROUND}
        showNavInfo={false}
        nodeId="id"
        nodeRelSize={7}
        nodeResolution={8}
        nodeColor={nodeColor}
        nodeLabel={nodeLabel}
        nodeThreeObject={nodeThreeObject}
        nodeThreeObjectExtend
        linkLabel={linkLabel}
        linkColor={linkColor}
        linkWidth={linkWidth}
        linkOpacity={0.55}
        linkDirectionalArrowLength={6}
        linkDirectionalArrowRelPos={0.92}
        linkDirectionalArrowColor={'#94a3b8'}
        d3AlphaDecay={ALPHA_DECAY}
        d3VelocityDecay={0.4}
        cooldownTicks={COOLDOWN_TICKS}
        cooldownTime={COOLDOWN_TIME}
        onNodeClick={(node) => onNodeClick?.(node.id)}
        onNodeHover={(node) => {
          if (containerRef.current) containerRef.current.style.cursor = node ? 'pointer' : 'grab';
        }}
        onEngineStop={handleEngineStop}
      />
    </div>
  );
}