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 | "use client"; /** * The layered 3D scene of a persona overview (issue #271). * * Layers are stacked discs on the z axis, the force layout runs in x and y * only, so a persona reads as a few labelled planes and not a hairball. * Status is a glow halo (pulsing for "bad"), flows are particles on links. * The camera orbits slowly until a node is selected. * * An enhancement: everything it shows is also in the signal list and the * detail panel of the page. It is loaded with next/dynamic and never on * the server; the page leaves it out under prefers-reduced-motion. * * Ported from the prototype engine under ui/public/poc/persona-3d/engine.js * (3d-force-graph 1.80, three r183 as npm dependencies instead of a CDN). */ import { useEffect, useRef } from "react"; import ForceGraph3D, { type ForceGraph3DInstance } from "3d-force-graph"; import * as THREE from "three"; import { applyToOffset, isTypingTarget, keyAction, length, ORBIT_IDLE_MS, ORBIT_SPEED, panShift, rotateAroundZ, type Vec3, } from "@/lib/overview/camera"; import type { OverviewLayer, OverviewLink, OverviewNode, OverviewView, } from "@/lib/overview/types"; import { useT } from "@/lib/i18n/translate"; const STATUS_COLOR: Record<string, string> = { ok: "#22c55e", warn: "#f59e0b", bad: "#ef4444", info: "#38bdf8", none: "#94a3b8", }; const LAYER_GAP = 110; const BASE_R = 100; type SceneNode = OverviewNode & { x?: number; y?: number; z?: number; fx?: number; fy?: number; fz?: number; __threeObj?: THREE.Object3D; }; type SceneLink = Omit<OverviewLink, "source" | "target"> & { source: string | SceneNode; target: string | SceneNode; }; type Graph = ForceGraph3DInstance<SceneNode, SceneLink>; function textSprite( text: string, { size = 22, color = "#e5e7eb", bg = null as string | null } = {}, ): THREE.Sprite { const c = document.createElement("canvas"); const ctx = c.getContext("2d")!; const font = `600 ${size * 2}px Inter, system-ui, sans-serif`; ctx.font = font; const w = Math.ceil(ctx.measureText(text).width) + 24; const h = size * 2 + 20; c.width = w; c.height = h; ctx.font = font; if (bg) { ctx.fillStyle = bg; ctx.beginPath(); ctx.roundRect(0, 0, w, h, 14); ctx.fill(); } ctx.fillStyle = color; ctx.textBaseline = "middle"; ctx.fillText(text, 12, h / 2); const tex = new THREE.CanvasTexture(c); tex.colorSpace = THREE.SRGBColorSpace; const sp = new THREE.Sprite( new THREE.SpriteMaterial({ map: tex, transparent: true, depthWrite: false, }), ); const scale = size / 2.4; sp.scale.set((w / h) * scale, scale, 1); return sp; } function glowSprite(color: string, scale: number): THREE.Sprite { const c = document.createElement("canvas"); c.width = c.height = 128; const ctx = c.getContext("2d")!; const g = ctx.createRadialGradient(64, 64, 8, 64, 64, 64); g.addColorStop(0, color); g.addColorStop(0.45, color + "88"); g.addColorStop(1, color + "00"); ctx.fillStyle = g; ctx.fillRect(0, 0, 128, 128); const sp = new THREE.Sprite( new THREE.SpriteMaterial({ map: new THREE.CanvasTexture(c), transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, }), ); sp.scale.set(scale, scale, 1); return sp; } function nodeObject(n: SceneNode): THREE.Object3D { const g = new THREE.Group(); const r = 3 + (n.size ?? 1) * 1.6; const color = n.color ?? STATUS_COLOR[n.status ?? "none"]; g.add( new THREE.Mesh( new THREE.SphereGeometry(r, 24, 24), new THREE.MeshPhongMaterial({ color, emissive: color, emissiveIntensity: 0.25, shininess: 60, }), ), ); if (n.status && n.status !== "none") { const halo = glowSprite(STATUS_COLOR[n.status], r * 5); halo.userData.pulse = n.pulse ?? n.status === "bad"; halo.userData.base = r * 5; g.add(halo); g.userData.halo = halo; } // An empty label draws no text: a view with a hundred records names them // on hover and in the detail panel instead (lib/overview/import.ts). if (n.label) { const label = textSprite(n.label, { size: (n.size ?? 1) >= 3 ? 26 : 20, color: (n.size ?? 1) >= 3 ? "#fde68a" : "#e5e7eb", }); label.position.set(0, -(r + 7), 0); label.center.set(0.5, 1); g.add(label); } return g; } function layerPlane(layer: OverviewLayer): THREE.Group { const grp = new THREE.Group(); const disc = new THREE.Mesh( new THREE.CircleGeometry(BASE_R, 72), new THREE.MeshBasicMaterial({ color: layer.color, transparent: true, opacity: 0.06, side: THREE.DoubleSide, depthWrite: false, }), ); const ring = new THREE.Mesh( new THREE.RingGeometry(BASE_R - 1.2, BASE_R, 96), new THREE.MeshBasicMaterial({ color: layer.color, transparent: true, opacity: 0.45, side: THREE.DoubleSide, depthWrite: false, }), ); grp.add(disc, ring); const label = textSprite(layer.name, { size: 24, color: layer.color, bg: "rgba(15,23,42,0.85)", }); label.position.set(BASE_R + 10, 0, 0); label.center.set(0, 0.5); grp.add(label); grp.position.z = layer.z * LAYER_GAP; return grp; } export interface OverviewSceneProps { view: OverviewView; selectedId: string | null; /** Ids of nodes whose `expand` set is unfolded */ expandedIds: string[]; onSelect: (id: string | null) => void; className?: string; } interface SceneState { graph: Graph; nodes: Map<string, SceneNode>; layerZ: Record<string, number>; planes: Record<string, THREE.Group>; orbiting: boolean; /** Set once the person moved the camera; stops the easing to the fitted distance */ userAdjusted: boolean; focused: boolean; idleTimer: ReturnType<typeof setTimeout> | null; raf: number; maxR: number; zMid: number; D: number; } export default function OverviewScene({ view, selectedId, expandedIds, onSelect, className, }: OverviewSceneProps) { const t = useT("explore"); const ref = useRef<HTMLDivElement>(null); const state = useRef<SceneState | null>(null); const onSelectRef = useRef(onSelect); onSelectRef.current = onSelect; // ── mount: one graph per view ───────────────────────────────────────────── useEffect(() => { const root = ref.current; if (!root) return; const layerZ = Object.fromEntries( view.layers.map((l) => [l.id, l.z * LAYER_GAP]), ); const nodes = new Map<string, SceneNode>(); for (const n of view.nodes) { const sn: SceneNode = { ...n, fz: layerZ[n.layer] ?? 0 }; if (n.pin) { sn.fx = n.pin[0]; sn.fy = n.pin[1]; } nodes.set(n.id, sn); } const links: SceneLink[] = view.links .filter((l) => nodes.has(l.source) && nodes.has(l.target)) .map((l) => ({ ...l })); // The constructor's types are not generic; the instance's are. const graph = new ForceGraph3D(root, { controlType: "orbit", }) as unknown as Graph; graph .width(root.clientWidth) .height(root.clientHeight) .backgroundColor("#0b1220") .showNavInfo(false) .nodeThreeObject((n) => nodeObject(n)) .nodeLabel( (n) => `<b>${escapeHtml(n.title ?? n.label)}</b><br>${escapeHtml( n.sub ?? "", )}`, ) .linkColor((l) => l.color ?? STATUS_COLOR[l.status ?? "none"]) .linkOpacity(0.55) .linkWidth((l) => l.width ?? (l.status === "bad" ? 1.6 : 0.8)) .linkDirectionalParticles((l) => l.particles ?? 0) .linkDirectionalParticleSpeed(0.006) .linkDirectionalParticleWidth(2.2) .linkDirectionalParticleColor( (l) => l.color ?? STATUS_COLOR[l.status ?? "none"], ) .linkDirectionalArrowLength((l) => (l.arrow ? 4 : 0)) .linkDirectionalArrowRelPos(0.85) .warmupTicks(120) .cooldownTicks(400) .cooldownTime(Infinity) .d3AlphaDecay(0.03) .d3VelocityDecay(0.35) .onNodeClick((n) => onSelectRef.current(n.id)) .onBackgroundClick(() => onSelectRef.current(null)) .graphData({ nodes: [...nodes.values()], links }); graph.d3Force("charge")?.strength(-80); graph.d3Force("link")?.distance((l: SceneLink) => l.distance ?? 60); const planes: Record<string, THREE.Group> = {}; for (const l of view.layers) { planes[l.id] = layerPlane(l); graph.scene().add(planes[l.id]); } graph.scene().add(new THREE.AmbientLight(0xffffff, 0.35)); const zs = view.layers.map((l) => l.z); const zSpan = Math.max(...zs) - Math.min(...zs); const zMid = ((Math.max(...zs) + Math.min(...zs)) / 2) * LAYER_GAP; const st: SceneState = { graph, nodes, layerZ, planes, orbiting: true, userAdjusted: false, focused: false, idleTimer: null, raf: 0, maxR: 100, zMid, D: 400 + zSpan * 40, }; state.current = st; lastUnfold.current = ""; const fitPlanes = () => { st.maxR = 100; for (const l of view.layers) { let r = 60; for (const n of nodes.values()) { if (n.layer === l.id && Number.isFinite(n.x)) { r = Math.max(r, Math.hypot(n.x ?? 0, n.y ?? 0) + 36); } } st.maxR = Math.max(st.maxR, r); const g = planes[l.id]; const k = r / BASE_R; g.children[0].scale.set(k, k, 1); g.children[1].scale.set(k, k, 1); g.children[2].position.x = r + 10; } st.D = Math.max(400 + zSpan * 40, st.maxR * 1.6); }; fitPlanes(); graph.onEngineStop(fitPlanes); const cam = graph.camera(); cam.up.set(0, 0, 1); const controls = graph.controls() as { target: THREE.Vector3 }; controls.target.set(0, 0, zMid); graph.cameraPosition( { x: 0, y: -st.D, z: zMid + st.D * 0.6 }, { x: 0, y: 0, z: zMid }, 0, ); const offsetNow = (): Vec3 => ({ x: cam.position.x - controls.target.x, y: cam.position.y - controls.target.y, z: cam.position.z - controls.target.z, }); const applyOffset = (off: Vec3) => { cam.position.set( controls.target.x + off.x, controls.target.y + off.y, controls.target.z + off.z, ); cam.lookAt(controls.target); }; // After ORBIT_IDLE_MS without input the scene orbits on its own again. const armIdle = () => { if (st.idleTimer) clearTimeout(st.idleTimer); st.idleTimer = setTimeout(() => { st.orbiting = true; }, ORBIT_IDLE_MS); }; const pause = () => { st.orbiting = false; st.userAdjusted = true; armIdle(); }; root.addEventListener("pointerdown", pause); root.addEventListener("wheel", pause, { passive: true }); // Keys: arrows move, Shift + arrows rotate, + and - zoom, Space pauses // or resumes the orbit, Home resets. const onKey = (e: KeyboardEvent) => { if (isTypingTarget(e.target)) return; const action = keyAction(e); if (!action) return; e.preventDefault(); if (action === "toggle-orbit") { st.orbiting = !st.orbiting; st.userAdjusted = true; if (st.orbiting && st.idleTimer) clearTimeout(st.idleTimer); else armIdle(); return; } st.orbiting = false; armIdle(); if (action === "reset") { st.userAdjusted = false; graph.cameraPosition( { x: 0, y: -st.D, z: zMid + st.D * 0.6 }, { x: 0, y: 0, z: zMid }, 600, ); return; } st.userAdjusted = true; if ( action === "pan-left" || action === "pan-right" || action === "pan-up" || action === "pan-down" ) { const right = new THREE.Vector3().setFromMatrixColumn(cam.matrix, 0); const up = new THREE.Vector3().setFromMatrixColumn(cam.matrix, 1); const shift = panShift(right, up, length(offsetNow()), action); controls.target.x += shift.x; controls.target.y += shift.y; controls.target.z += shift.z; cam.position.x += shift.x; cam.position.y += shift.y; cam.position.z += shift.z; cam.lookAt(controls.target); return; } applyOffset(applyToOffset(offsetNow(), action)); }; window.addEventListener("keydown", onKey); let t0 = performance.now(); let frameNo = 0; const frame = (t: number) => { const dt = (t - t0) / 1000; t0 = t; if (st.orbiting && !st.focused) { // Orbit around whatever the camera looks at, from left to right. let off = rotateAroundZ(offsetNow(), ORBIT_SPEED * dt); if (!st.userAdjusted) { // The layout grows after the first frames; until someone moves the // camera, ease the distance and height out to the fitted values. const r = length(off) || st.D; const k = (r + (st.D - r) * Math.min(1, dt * 1.5)) / r; const zTarget = st.D * 0.6; off = { x: off.x * k, y: off.y * k, z: off.z + (zTarget - off.z) * Math.min(1, dt * 1.5), }; } applyOffset(off); } if (frameNo++ % 30 === 0) fitPlanes(); const s = 1 + 0.18 * Math.sin(t / 380); for (const n of nodes.values()) { const h = n.__threeObj?.userData?.halo as THREE.Sprite | undefined; if (h && h.userData.pulse) { h.scale.set(h.userData.base * s, h.userData.base * s, 1); } } st.raf = requestAnimationFrame(frame); }; st.raf = requestAnimationFrame(frame); const onVisible = () => { if (!document.hidden) graph.d3ReheatSimulation(); }; document.addEventListener("visibilitychange", onVisible); const ro = new ResizeObserver(() => graph.width(root.clientWidth).height(root.clientHeight), ); ro.observe(root); return () => { cancelAnimationFrame(st.raf); if (st.idleTimer) clearTimeout(st.idleTimer); root.removeEventListener("pointerdown", pause); root.removeEventListener("wheel", pause); window.removeEventListener("keydown", onKey); document.removeEventListener("visibilitychange", onVisible); ro.disconnect(); graph._destructor(); state.current = null; }; }, [view]); // ── unfold / fold ───────────────────────────────────────────────────────── // Runs only when something was unfolded or folded. On mount the graph // already holds the base data; a second graphData() right away raced the // force layout's initialisation in production and left the scene black // ("Cannot read properties of undefined (reading 'tick')"). const unfoldKey = expandedIds.join("|"); const lastUnfold = useRef(""); useEffect(() => { const st = state.current; if (!st) return; if (unfoldKey === lastUnfold.current) return; lastUnfold.current = unfoldKey; const base = view.nodes.map((n) => st.nodes.get(n.id)!).filter(Boolean); const extra: SceneNode[] = []; const extraLinks: OverviewLink[] = []; for (const id of expandedIds) { const parent = st.nodes.get(id); if (!parent?.expand) continue; parent.expand.nodes.forEach((x, i) => { let sn = st.nodes.get(x.id); if (!sn) { sn = { ...x, fz: st.layerZ[x.layer] ?? parent.fz, x: (parent.x ?? 0) + Math.cos(i) * 30, y: (parent.y ?? 0) + Math.sin(i) * 30, }; st.nodes.set(x.id, sn); } extra.push(sn); }); extraLinks.push(...parent.expand.links); } const all = [...base, ...extra]; const known = new Set(all.map((n) => n.id)); const links: SceneLink[] = [...view.links, ...extraLinks] .filter((l) => known.has(l.source) && known.has(l.target)) .map((l) => ({ ...l })); st.graph.graphData({ nodes: all, links }); try { st.graph.d3ReheatSimulation(); } catch { /* the layout is not up yet; the new data warms up on its own */ } }, [view, expandedIds, unfoldKey]); // ── focus ───────────────────────────────────────────────────────────────── const selectedRef = useRef<string | null>(selectedId); selectedRef.current = selectedId; useEffect(() => { const st = state.current; if (!st) return; if (!selectedId) { st.orbiting = false; if (st.idleTimer) clearTimeout(st.idleTimer); st.idleTimer = setTimeout(() => { st.orbiting = true; }, ORBIT_IDLE_MS); return; } const n = st.nodes.get(selectedId); if (!n) return; st.focused = true; st.orbiting = false; st.userAdjusted = true; if (st.idleTimer) clearTimeout(st.idleTimer); st.idleTimer = setTimeout(() => { st.orbiting = true; }, ORBIT_IDLE_MS); const dist = 230; const cam = st.graph.camera(); const nx = n.x ?? 0; const ny = n.y ?? 0; const nz = n.z ?? n.fz ?? 0; const from = cam.position .clone() .sub(new THREE.Vector3(nx, ny, nz)) .normalize(); st.graph.cameraPosition( { x: nx + from.x * dist, y: ny + from.y * dist, z: nz + from.z * dist + 40, }, { x: nx, y: ny, z: nz }, 900, ); const t = setTimeout(() => (st.focused = false), 12000); return () => clearTimeout(t); }, [selectedId]); return ( <div ref={ref} className={className} data-testid="overview-canvas" role="img" aria-label={t( "Layered 3D scene of the overview; every node is also in the list", )} /> ); } function escapeHtml(s: string): string { return s.replace( /[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]!, ); } |