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

48.87% Statements 109/223
43.62% Branches 89/204
33.33% Functions 19/57
55.24% Lines 100/181

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 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598                      1x     1x                                         1x 12x 96x 48x   12x 12x   12x         1x   1x       1x               1x                 1x                                                                     1x                                                                                                                                             22x 22x 22x 22x 22x 22x 22x 22x 22x 22x     22x 22x 6x   22x 4x 4x       22x 12x 12x 24x 24x   12x           22x 24x 24x 24x 24x       22x   6x 6x 6x 6x 6x 6x 6x         22x 6x 6x 6x 6x 6x 6x 6x       6x       22x 6x     22x                                       22x 12x 12x 12x 12x 24x 24x 24x   24x 6x     12x 12x 12x     12x 12x 12x   12x   12x 12x 24x 24x 6x 6x 6x         12x               22x 12x                                                 22x 12x                                                   22x               22x   22x                                                                                                                     44x 44x 44x       4x                                                                                                                                                         10x 10x                                                                                                                                                          
import { useState, useEffect, useCallback, useMemo, lazy, Suspense } from 'react';
import { RefreshCw, PanelRight, X, ChevronRight, ChevronDown, Grid, Box } from 'lucide-react';
import api from '../services/api';
import GraphView from './GraphView';
import Graph3DErrorBoundary from './graph3d/ErrorBoundary';
import { buildClassColors, buildClassLegend, DEFAULT_NODE_COLOR } from '../utils/classColor';
import { hasWebGL } from '../utils/webgl';
import { readViewMode, writeViewMode } from '../utils/graphViewMode';
import { prefixedIri, shortIri } from '../utils/iri';
 
// La vue 3D (three.js) est chargée à la demande : elle ne doit pas peser sur le bundle initial.
const GraphView3D = lazy(() => import('./GraphView3D'));
 
// Prédicats de libellé par ordre de priorité (le slug d'IRI en dernier recours).
const LABEL_PREDICATES = [
  'http://www.w3.org/2000/01/rdf-schema#label',
  'http://www.w3.org/2004/02/skos/core#prefLabel',
  'https://schema.org/name',
  'http://schema.org/name',
  'https://schema.org/headline',
  'http://schema.org/headline',
  'https://schema.org/legalName',
  'http://schema.org/legalName',
  'http://xmlns.com/foaf/0.1/name',
  'http://purl.org/dc/terms/title',
  'http://purl.org/dc/elements/1.1/title',
  'http://www.w3.org/2004/02/skos/core#altLabel',
  'https://schema.org/alternateName',
  'http://schema.org/alternateName',
];
 
/**
 * Choisit le meilleur libellé littéral parmi les triplets sortants d'un sujet,
 * selon la langue sélectionnée (puis sans langue, puis fr/en, puis n'importe).
 */
const labelFromTriples = (outTriples, lang) => {
  for (const predicate of LABEL_PREDICATES) {
    const candidates = outTriples.filter((t) => t.p.value === predicate && t.o.type === 'literal');
    if (!candidates.length) continue;
    const pick =
      (lang && candidates.find((c) => c.o['xml:lang'] === lang)) ||
      candidates.find((c) => !c.o['xml:lang']) ||
      candidates[0];
    return pick.o.value;
  }
  return null;
};
 
const RDF_TYPE = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type';
 
const isSchema = (iri) => /^https?:\/\/schema\.org\//.test(String(iri));
 
// Associations « classe + propriété » (noms locaux schema.org) → affichage d'une image.
// `types: null` = toutes les classes.
const IMAGE_ASSOCIATIONS = [
  { types: ['ImageObject', 'Image'], properties: ['url', 'contentUrl'] },
  { types: ['Person'], properties: ['image'] },
  { types: ['Organization'], properties: ['image', 'logo'] },
  { types: ['CreativeWork', 'Article', 'Product', 'Event', 'Place', 'SoftwareApplication'], properties: ['image'] },
  { types: null, properties: ['image'] },
];
 
const shouldShowImage = (types, predicate) => {
  if (!isSchema(predicate)) return false;
  const typeNames = types.map(shortIri);
  const predName = shortIri(predicate);
  return IMAGE_ASSOCIATIONS.some(
    (a) => (!a.types || a.types.some((t) => typeNames.includes(t))) && a.properties.includes(predName),
  );
};
 
const tripleKey = (t) => `${t.s.value}|${t.p.value}|${t.o.value}`;
 
/**
 * Lecture d'une KB sémantique : graphe des SUJETS + panneau de propriétés.
 * - Nœuds = sujets (IRIs) uniquement. Les objets d'ontologie (ex. schema:Person) ou
 *   littéraux ne sont PAS des nœuds ; ils apparaissent dans le panneau du sujet.
 * - Liens = entre deux sujets (propriétés objet).
 * - Clic sur un sujet → panneau de droite : prédicats + valeurs.
 */
function PropValue({ v, onSelectValue }) {
  if (v.isLiteral) return <span className="text-gray-800 break-words">{v.value}</span>;
  return (
    <button
      type="button"
      onClick={() => onSelectValue(v.targetId)}
      className="text-indigo-600 hover:underline break-all text-left"
    >
      {v.value}
    </button>
  );
}
 
function PropImage({ url, alt }) {
  if (!url) return null;
  return (
    <img
      src={url}
      alt={alt || ''}
      className="mt-1 max-w-full rounded-lg border border-gray-200"
      onError={(e) => { e.currentTarget.style.display = 'none'; }}
    />
  );
}
 
/** Date au format YYYY-MM-DD (depuis un littéral xsd:dateTime). */
const dateOnly = (d) => String(d).slice(0, 10);
 
/** Badge des métadonnées d'un triplet : création, validité, provenance (infobulle). */
function TripleMetaBadge({ metadata }) {
  if (!metadata) return null;
  const parts = [];
  if (metadata.created) parts.push(`créé le ${dateOnly(metadata.created)}`);
  if (metadata.validFrom && metadata.validUntil) {
    parts.push(`valide du ${metadata.validFrom} au ${metadata.validUntil}`);
  } else if (metadata.validFrom) {
    parts.push(`valide depuis le ${metadata.validFrom}`);
  }
  if (!parts.length) return null;
  const title = [
    metadata.documentIri ? `source : ${metadata.documentIri}` : null,
    metadata.jobId ? `job : ${metadata.jobId}` : null,
  ]
    .filter(Boolean)
    .join(' · ');
  return (
    <span className="ml-1.5 text-[10px] text-gray-500 align-middle" title={title || undefined}>
      ⟨{parts.join(' · ')}⟩
    </span>
  );
}
 
/** Une propriété : valeur unique inline, ou accordéon (triangle + compteur) si plusieurs. */
function PropertyGroup({ group, onSelectValue }) {
  const [open, setOpen] = useState(false);
  const { predicateLabel, values } = group;
 
  if (values.length === 1) {
    const v = values[0];
    return (
      <li className="text-sm">
        <span className="text-teal-700">{predicateLabel}</span>
        <span className="text-gray-400"> : </span>
        <PropValue v={v} onSelectValue={onSelectValue} />
        <TripleMetaBadge metadata={v.metadata} />
        <PropImage url={v.imageUrl} alt={v.value} />
      </li>
    );
  }
 
  return (
    <li className="text-sm">
      <button
        type="button"
        onClick={() => setOpen((o) => !o)}
        className="inline-flex items-center gap-1 text-teal-700 hover:underline"
      >
        {open ? <ChevronDown className="w-3.5 h-3.5" /> : <ChevronRight className="w-3.5 h-3.5" />}
        {predicateLabel}
        <span className="text-gray-400">({values.length})</span>
      </button>
      {open && (
        <ul className="mt-1 ml-5 space-y-1.5">
          {values.map((v, i) => (
            <li key={i}>
              <PropValue v={v} onSelectValue={onSelectValue} />
              <TripleMetaBadge metadata={v.metadata} />
              <PropImage url={v.imageUrl} alt={v.value} />
            </li>
          ))}
        </ul>
      )}
    </li>
  );
}
 
export default function SemanticGraphViewer({ kbId, limit = 300 }) {
  const [triples, setTriples] = useState([]);
  const [selected, setSelected] = useState(null);
  const [selectedLang, setSelectedLang] = useState('');
  const [panelOpen, setPanelOpen] = useState(false);
  const [panelMode, setPanelMode] = useState('properties');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [fromDate, setFromDate] = useState('');
  const [toDate, setToDate] = useState('');
  const [selectedClass, setSelectedClass] = useState(null);
 
  // Mode d'affichage : 2D par défaut, 3D seulement si WebGL est disponible (sinon écran noir).
  const webglAvailable = useMemo(() => hasWebGL(), []);
  const [viewMode, setViewModeState] = useState(() =>
    webglAvailable && readViewMode() === '3d' ? '3d' : '2d',
  );
  const setViewMode = useCallback((mode) => {
    setViewModeState(mode);
    writeViewMode(mode);
  }, []);
 
  // Langues disponibles (issues des littéraux balisés).
  const languages = useMemo(() => {
    const set = new Set();
    for (const t of triples) {
      const lang = t.o?.type === 'literal' ? t.o['xml:lang'] : null;
      Iif (lang) set.add(lang);
    }
    return [...set].sort();
  }, [triples]);
 
  // Pas de langue par défaut : le sélecteur est vide (= toutes) tant que l'utilisateur ne choisit pas.
 
  // Convertit un triplet de l'API (`{ s, p, o, metadata }`) au format « binding » interne du viewer.
  const toBindingTriple = (t) => {
    const o = { value: t.o.value, type: t.o.type };
    Iif (t.o.lang) o['xml:lang'] = t.o.lang;
    Iif (t.o.datatype) o.datatype = t.o.datatype;
    return { s: { value: t.s, type: 'uri' }, p: { value: t.p }, o, metadata: t.metadata || null };
  };
 
  // Charge les triplets + métadonnées de la KB (endpoint dédié), avec filtre période optionnel.
  const fetchMetadata = useCallback(
    async (params = {}) => {
      const qs = new URLSearchParams();
      Eif (params.limit) qs.set('limit', params.limit);
      Iif (params.subject) qs.set('subject', params.subject);
      Iif (fromDate) qs.set('from', fromDate);
      Iif (toDate) qs.set('to', toDate);
      const res = await api.get(`/semantic-kbs/${kbId}/triples-metadata?${qs.toString()}`);
      return (res.data?.data?.triples || []).map(toBindingTriple);
    },
    [kbId, fromDate, toDate],
  );
 
  const loadWhole = useCallback(async () => {
    Iif (!kbId) return;
    setLoading(true);
    setError(null);
    try {
      const loaded = await fetchMetadata({ limit });
      setTriples(loaded);
      setSelected(null);
    } catch (e) {
      setError(e.response?.data?.message || 'Erreur de lecture de la base');
    } finally {
      setLoading(false);
    }
  }, [kbId, limit, fetchMetadata]);
 
  useEffect(() => {
    loadWhole();
  }, [loadWhole]);
 
  const expand = useCallback(
    async (iri) => {
      if (!iri || iri.startsWith('lit:')) return;
      try {
        const loaded = await fetchMetadata({ subject: iri, limit: 500 });
        setTriples((prev) => {
          const seen = new Set(prev.map(tripleKey));
          const add = loaded.filter((b) => !seen.has(tripleKey(b)));
          return add.length ? [...prev, ...add] : prev;
        });
      } catch (e) {
        setError(e.response?.data?.message || 'Voisinage indisponible');
      }
    },
    [fetchMetadata],
  );
 
  // Modèle du graphe : sujets, liens, légende. Volontairement SANS `selected` :
  // sélectionner un nœud ne doit pas reconstruire les données du graphe (sinon la
  // simulation 3D repart et la disposition saute au lieu de simplement naviguer).
  const { subjectNodes, subjectEdges, classLegend } = useMemo(() => {
    const subjects = new Map();
    const outBySubject = new Map();
    const classBySubject = new Map();
    for (const t of triples) {
      if (!subjects.has(t.s.value)) subjects.set(t.s.value, { id: t.s.value, label: null, type: 'uri' });
      if (!outBySubject.has(t.s.value)) outBySubject.set(t.s.value, []);
      outBySubject.get(t.s.value).push(t);
      // Classe = PREMIÈRE classe IRI du sujet (rdf:type) — PRD §19.
      if (t.p.value === RDF_TYPE && t.o.type === 'uri' && !classBySubject.has(t.s.value)) {
        classBySubject.set(t.s.value, t.o.value);
      }
    }
    for (const [id, node] of subjects) {
      node.label = labelFromTriples(outBySubject.get(id) || [], selectedLang) || shortIri(id);
      node.class = classBySubject.get(id) || null;
    }
    // Couleurs distinctes par classe (angle d'or, ordre trié) — cohérentes avec la légende.
    const classColors = buildClassColors([...subjects.values()]);
    for (const node of subjects.values()) {
      node.color = node.class ? (classColors.get(node.class) || DEFAULT_NODE_COLOR) : DEFAULT_NODE_COLOR;
    }
    const ids = new Set(subjects.keys());
 
    const edgeMap = new Map();
    for (const t of triples) {
      const isUriObject = t.o.type === 'uri' || t.o.type === 'bnode';
      if (isUriObject && ids.has(t.o.value)) {
        const key = `${t.s.value}|${t.p.value}|${t.o.value}`;
        Eif (!edgeMap.has(key)) {
          edgeMap.set(key, { source: t.s.value, target: t.o.value, predicate: t.p.value });
        }
      }
    }
 
    return {
      subjectNodes: [...subjects.values()],
      subjectEdges: [...edgeMap.values()],
      classLegend: buildClassLegend([...subjects.values()]),
    };
  }, [triples, selectedLang]);
 
  // Propriétés du sujet sélectionné (accordéon par prédicat) — dépend de la sélection.
  const propertyGroups = useMemo(() => {
    Eif (!selected) return [];
    const selectedTypes = triples
      .filter((t) => t.s.value === selected && t.p.value === RDF_TYPE)
      .map((t) => t.o.value);
 
    const byPred = new Map();
    for (const t of triples) {
      if (t.s.value !== selected) continue;
      const lang = t.o?.type === 'literal' ? t.o['xml:lang'] : null;
      if (lang && selectedLang && lang !== selectedLang) continue;
      const isLiteral = t.o.type === 'literal';
      // Image affichée uniquement pour une valeur LITTÉRALE (URL directe) :
      // une image référencée par IRI n'est visible qu'en sélectionnant cet ImageObject.
      const imageUrl = isLiteral && shouldShowImage(selectedTypes, t.p.value) ? t.o.value : null;
      if (!byPred.has(t.p.value)) byPred.set(t.p.value, []);
      byPred.get(t.p.value).push({ value: t.o.value, isLiteral, targetId: t.o.value, imageUrl, metadata: t.metadata || null });
    }
    return [...byPred.entries()].map(([predicate, values]) => ({
      predicate,
      predicateLabel: prefixedIri(predicate),
      values,
    }));
  }, [triples, selected, selectedLang]);
 
  // JSON-LD brut du sujet sélectionné (@id / @type / propriétés).
  const selectedJsonLd = useMemo(() => {
    Eif (!selected) return null;
    const node = { '@id': selected };
    const types = [];
    const byPred = {};
    for (const t of triples) {
      if (t.s.value !== selected) continue;
      if (t.p.value === 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type') {
        types.push(t.o.value);
        continue;
      }
      const value =
        t.o.type === 'literal'
          ? {
              '@value': t.o.value,
              ...(t.o['xml:lang'] ? { '@language': t.o['xml:lang'] } : {}),
              ...(t.o.datatype ? { '@type': t.o.datatype } : {}),
            }
          : { '@id': t.o.value };
      if (!byPred[t.p.value]) byPred[t.p.value] = [];
      byPred[t.p.value].push(value);
    }
    if (types.length) node['@type'] = types;
    for (const [p, values] of Object.entries(byPred)) node[p] = values;
    return node;
  }, [selected, triples]);
 
  const onSelect = (id) => {
    setSelected(id);
    setPanelOpen(true);
    expand(id);
  };
 
  // Surlignage : ignoré si la classe sélectionnée n'est plus présente (ex. après filtrage).
  const activeHighlightClass =
    selectedClass && classLegend.some((c) => c.classIri === selectedClass) ? selectedClass : null;
 
  return (
    <div className="space-y-3">
      <div className="flex flex-wrap items-center justify-between gap-2">
        <p className="text-xs text-gray-500">
          {subjectNodes.length} sujet(s) · {subjectEdges.length} lien(s)
        </p>
        <div className="flex w-full flex-wrap items-center justify-start gap-2 sm:w-auto sm:justify-end">
          <label className="inline-flex items-center gap-1 text-sm text-gray-600">
            Du
            <input
              type="date"
              value={fromDate}
              max={toDate || undefined}
              onChange={(e) => setFromDate(e.target.value)}
              className="px-2 py-1.5 text-sm border border-gray-300 rounded-lg bg-white focus:ring-2 focus:ring-teal-500"
            />
          </label>
          <label className="inline-flex items-center gap-1 text-sm text-gray-600">
            Au
            <input
              type="date"
              value={toDate}
              min={fromDate || undefined}
              onChange={(e) => setToDate(e.target.value)}
              className="px-2 py-1.5 text-sm border border-gray-300 rounded-lg bg-white focus:ring-2 focus:ring-teal-500"
            />
          </label>
          {(fromDate || toDate) && (
            <button
              type="button"
              onClick={() => { setFromDate(''); setToDate(''); }}
              className="p-1.5 text-gray-400 hover:text-red-500 rounded-lg"
              title="Effacer le filtre de période"
            >
              <X className="w-4 h-4" />
            </button>
          )}
          <label className="inline-flex items-center gap-1 text-sm text-gray-600">
            Langue
            <select
              value={selectedLang}
              onChange={(e) => setSelectedLang(e.target.value)}
              className="px-2 py-1.5 text-sm border border-gray-300 rounded-lg bg-white focus:ring-2 focus:ring-teal-500"
            >
              <option value="">Toutes</option>
              {languages.map((l) => (
                <option key={l} value={l}>{l}</option>
              ))}
            </select>
          </label>
          <div
            role="group"
            aria-label="Mode d'affichage du graphe"
            className="inline-flex rounded-lg border border-gray-300 overflow-hidden"
          >
            {[
              ['2d', '2D', Grid],
              ['3d', '3D', Box],
            ].map(([mode, label, Icon]) => {
              const active = viewMode === mode;
              const disabled = mode === '3d' && !webglAvailable;
              return (
                <button
                  key={mode}
                  type="button"
                  onClick={() => setViewMode(mode)}
                  disabled={disabled}
                  aria-pressed={active}
                  title={disabled ? '3D indisponible : WebGL non supporté' : `Vue ${label}`}
                  className={`inline-flex items-center px-2.5 py-1.5 text-sm border-0 ${
                    active ? 'bg-teal-50 text-teal-700' : 'bg-white text-gray-600 hover:bg-gray-50'
                  } ${disabled ? 'opacity-40 cursor-not-allowed' : ''}`}
                >
                  <Icon className="w-4 h-4 mr-1" /> {label}
                </button>
              );
            })}
          </div>
          <button
            type="button"
            onClick={() => setPanelOpen((v) => !v)}
            className={`inline-flex items-center px-3 py-1.5 text-sm border rounded-lg ${
              panelOpen ? 'border-teal-500 bg-teal-50 text-teal-700' : 'border-gray-300 hover:bg-gray-50'
            }`}
          >
            <PanelRight className="w-4 h-4 mr-1" /> Panneau
          </button>
          <button
            type="button"
            onClick={loadWhole}
            disabled={loading}
            className="inline-flex items-center px-3 py-1.5 text-sm border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50"
          >
            <RefreshCw className={`w-4 h-4 mr-1 ${loading ? 'animate-spin' : ''}`} /> Recharger
          </button>
        </div>
      </div>
 
      {error && <p className="text-sm text-red-600">{error}</p>}
 
      {!loading && !error && triples.length === 0 && (
        <p className="text-sm text-gray-500">
          {(fromDate || toDate) ? 'Aucun triplet sur la période sélectionnée.' : 'Aucune donnée.'}
        </p>
      )}
 
      {loading && subjectNodes.length === 0 ? (
        <p className="text-sm text-gray-500">Chargement…</p>
      ) : (
        <div className="flex flex-col lg:flex-row gap-4">
          <div className="flex-1 min-w-0">
            {viewMode === '3d' ? (
              <Graph3DErrorBoundary onBackTo2D={() => setViewMode('2d')}>
                <Suspense
                  fallback={<p className="text-sm text-gray-500">Chargement de la vue 3D…</p>}
                >
                  <GraphView3D
                    nodes={subjectNodes}
                    edges={subjectEdges}
                    onNodeClick={onSelect}
                    selectedId={selected}
                    highlightClass={activeHighlightClass}
                  />
                </Suspense>
              </Graph3DErrorBoundary>
            ) : (
              <GraphView
                nodes={subjectNodes}
                edges={subjectEdges}
                onNodeClick={onSelect}
                selectedId={selected}
                highlightClass={activeHighlightClass}
              />
            )}
            {viewMode === '3d' && (
              <p className="text-xs text-gray-400 mt-1">
                Glisser = tourner · molette = zoom · glisser un nœud = repositionner · clic = étendre
              </p>
            )}
            {classLegend.length > 0 && (
              <div className="mt-2 flex flex-wrap gap-x-2 gap-y-1">
                {classLegend.map((c) => {
                  const active = c.classIri === selectedClass;
                  return (
                    <button
                      key={c.classIri}
                      type="button"
                      onClick={() => setSelectedClass((cur) => (cur === c.classIri ? null : c.classIri))}
                      title={`${c.classIri}${active ? ' — cliquer pour désélectionner' : ' — cliquer pour surligner'}`}
                      className={`inline-flex items-center gap-1 text-xs rounded-full px-2 py-0.5 border ${
                        active ? 'border-gray-800 bg-gray-100 text-gray-900 font-medium' : 'border-transparent text-gray-600 hover:bg-gray-100'
                      }`}
                    >
                      <span
                        className="inline-block w-2.5 h-2.5 rounded-full border border-white shadow"
                        style={{ backgroundColor: c.color }}
                      />
                      {c.label}
                    </button>
                  );
                })}
              </div>
            )}
          </div>
 
          {panelOpen && (
            <aside className="lg:w-1/2 shrink-0 border border-gray-200 rounded-lg bg-white flex flex-col lg:max-h-[70vh]">
              <div className="flex items-center justify-between px-4 py-2 border-b border-gray-100">
                <div className="flex items-center gap-1">
                  {[['properties', 'Propriétés'], ['jsonld', 'JSON-LD']].map(([id, label]) => (
                    <button
                      key={id}
                      type="button"
                      onClick={() => setPanelMode(id)}
                      className={`px-2.5 py-1 text-xs rounded-md ${
                        panelMode === id ? 'bg-teal-50 text-teal-700' : 'text-gray-600 hover:bg-gray-50'
                      }`}
                    >
                      {label}
                    </button>
                  ))}
                </div>
                <button
                  type="button"
                  onClick={() => setPanelOpen(false)}
                  className="p-1.5 text-gray-400 hover:text-red-500 rounded-lg"
                  title="Fermer"
                >
                  <X className="w-4 h-4" />
                </button>
              </div>
 
              {!selected ? (
                <div className="p-4 text-sm text-gray-500">Cliquez un sujet pour afficher ses propriétés.</div>
              ) : panelMode === 'properties' ? (
                <div className="p-4 overflow-auto">
                  {propertyGroups.length === 0 ? (
                    <p className="text-xs text-gray-400">Aucune propriété.</p>
                  ) : (
                    <ul className="space-y-1.5">
                      {propertyGroups.map((g) => (
                        <PropertyGroup key={g.predicate} group={g} onSelectValue={setSelected} />
                      ))}
                    </ul>
                  )}
                </div>
              ) : (
                <div className="p-4 overflow-auto">
                  <pre className="text-xs leading-relaxed bg-gray-900 text-gray-100 rounded-lg p-3 overflow-auto whitespace-pre-wrap">
                    {JSON.stringify(selectedJsonLd, null, 2)}
                  </pre>
                </div>
              )}
            </aside>
          )}
        </div>
      )}
    </div>
  );
}