Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor: extract shared GraphEdges/GraphScene so MemoryGraph gets BrainGraph's touch-pick and reduced-motion fixes (#6828)

[._.]/ Adam Eivy0e5877615abd
diff --git a/client/src/components/brain/tabs/BrainGraph.jsx b/client/src/components/brain/tabs/BrainGraph.jsx
index 45cfaaf9dc..8b0ce2d0fb 100644
--- a/client/src/components/brain/tabs/BrainGraph.jsx
+++ b/client/src/components/brain/tabs/BrainGraph.jsx
@@ -1,7 +1,5 @@
-import { useState, useEffect, useMemo, useRef, useCallback, memo } from 'react';
-import { Canvas, useThree } from '@react-three/fiber';
-import { OrbitControls } from '@react-three/drei';
-import * as THREE from 'three';
+import { useState, useEffect, useMemo, useRef, useCallback } from 'react';
+import { Canvas } from '@react-three/fiber';
import {AlertTriangle, Zap, RefreshCw, X, ChevronRight, ArrowLeft, Compass, Info} from 'lucide-react';
import toast from '../../ui/Toast';
import * as api from '../../../services/api';
@@ -9,13 +7,12 @@ import { BRAIN_TYPE_HEX, DESTINATIONS } from '../constants';
import { chipColors } from '../../../lib/chipContrast';
import { useThemeContext } from '../../ThemeContext';
import { buildGraph } from '../../../lib/graphSimulation';
-import { pickNearestNodeByScreenDistance, isTapGesture } from '../../../lib/graphPicking';
import { pushFocus, popFocus, currentFocusId } from '../../../lib/brainGraphFocus';
+import GraphScene, { graphMotionSettings } from '../../graph3d/GraphScene';
+import useGraphCanvasInteraction from '../../graph3d/useGraphCanvasInteraction';
import EntityCombobox from '../../EntityCombobox';
import InlineConfirmRow from '../../ui/InlineConfirmRow';
import BrailleSpinner from '../../BrailleSpinner';
-import useHoverTooltip from '../../../hooks/useHoverTooltip';
-import useFirstTouchHint from '../../../hooks/useFirstTouchHint';
import usePrefersReducedMotion from '../../../hooks/usePrefersReducedMotion';
import { formatDateNumeric } from '../../../utils/formatters';
@@ -27,6 +24,14 @@ const EDGE_COLORS = {
const BRAIN_TYPES = ['people', 'projects', 'ideas', 'admin', 'memories', 'songs', 'goals', 'journals'];
+// Scene-appearance callbacks handed to the shared graph3d/GraphScene —
+// exported so the extraction's behavior split from MemoryGraph's own flat
+// blue/gray palette is pinned directly (see BrainGraph.test.jsx).
+export const brainNodeColor = (node) => BRAIN_TYPE_HEX[node.brainType] || '#6b7280';
+export const brainEdgeColor = (edge) => EDGE_COLORS[edge.type] || '#6b7280';
+export const brainEdgeIntensity = (edge, dimmed) =>
+ dimmed ? 0.06 : (edge.type === 'linked' ? 0.6 : 0.3 * (edge.weight || 0.5));
+
/**
* Inline chip style for a brain-type badge. `BRAIN_TYPE_HEX` is a fixed
* category palette picked against the dark graph canvas, so painting it
@@ -42,27 +47,11 @@ const BRAIN_TYPES = ['people', 'projects', 'ideas', 'admin', 'memories', 'songs'
*/
const brainTypeChipStyle = (brainType, mode) => chipColors(BRAIN_TYPE_HEX[brainType], mode) || undefined;
-// Only a gesture on the WebGL canvas itself picks a node. The overlay chrome —
-// "Clear selection", the legend toggle, the loading veil — sits INSIDE the same
-// wrapper the touch handlers are bound to, so its taps bubble there too; without
-// this, tapping the legend toggle would also select whichever node happens to
-// project nearest that corner. (r3f binds its own listeners to the canvas, so
-// the mouse path never had this problem.)
-const isCanvasGesture = (e) => e.target?.tagName === 'CANVAS';
-
// Widest the hover tooltip renders. Single source for both its max-width and
// the clamp that keeps it inside the viewport — as a CSS class plus a mirrored
// constant the two silently drift apart.
const TOOLTIP_WIDTH = 320;
-// The force layout is settled before the scene renders, so reduced-motion
-// users can see it immediately at rest. Keep the canvas on demand and turn
-// off OrbitControls' inertia too, preventing movement after an interaction.
-export const graphMotionSettings = (reducedMotion) => ({
- frameloop: reducedMotion ? 'demand' : 'always',
- enableDamping: !reducedMotion
-});
-
// Per-type API getters for detail panel
const TYPE_GETTERS = {
people: api.getBrainPerson,
@@ -90,145 +79,12 @@ export const recordBody = (record) => {
return '';
};
-function GraphEdges({ simEdges, selectedId }) {
- const geoRef = useRef();
-
- useEffect(() => {
- const geo = geoRef.current;
- if (!geo || !simEdges.length) return;
-
- const count = simEdges.length;
- const positions = new Float32Array(count * 6);
- const colors = new Float32Array(count * 6);
- const tmpColor = new THREE.Color();
-
- simEdges.forEach((e, i) => {
- const a = e.sourceNode, b = e.targetNode;
- const off = i * 6;
- positions[off] = a.x; positions[off + 1] = a.y; positions[off + 2] = a.z;
- positions[off + 3] = b.x; positions[off + 4] = b.y; positions[off + 5] = b.z;
-
- const dimmed = selectedId && e.source !== selectedId && e.target !== selectedId;
- tmpColor.set(EDGE_COLORS[e.type] || '#6b7280');
- const intensity = dimmed ? 0.06 : (e.type === 'linked' ? 0.6 : 0.3 * (e.weight || 0.5));
- const r = tmpColor.r * intensity, g = tmpColor.g * intensity, bl = tmpColor.b * intensity;
- colors[off] = r; colors[off + 1] = g; colors[off + 2] = bl;
- colors[off + 3] = r; colors[off + 4] = g; colors[off + 5] = bl;
- });
-
- geo.setAttribute('position', new THREE.BufferAttribute(positions, 3));
- geo.setAttribute('color', new THREE.BufferAttribute(colors, 3));
- geo.computeBoundingSphere();
- }, [simEdges, selectedId]);
-
- return (
- <lineSegments>
- <bufferGeometry ref={geoRef} />
- <lineBasicMaterial vertexColors />
- </lineSegments>
- );
-}
-
-// Memoized: the container's onPointerMove re-renders BrainGraph on every mouse
-// move over the canvas WHILE A NODE IS HOVERED (it tracks the tooltip position),
-// and every prop here is already identity-stable across that render — so without
-// memo each move reconciles a <mesh> per node for nothing.
-const GraphScene = memo(function GraphScene({ graph, selectedId, adjacentIds, onSelect, onFocus, onHover, pickRef, touchGestureRef, reducedMotion }) {
- const sphereGeo = useMemo(() => new THREE.SphereGeometry(1, 16, 12), []);
- const { camera, size } = useThree();
-
- const selNode = selectedId ? graph.idMap.get(selectedId) : null;
- const selRadius = selNode ? 0.4 + (selNode.importance ?? 0.5) * 0.8 : 0;
-
- // Publish a live screen-space pick to the DOM wrapper, which owns the touch
- // gesture (see the tap handler in BrainGraph). The camera object is stable
- // across orbiting, so the matrices are read at tap time, not captured here.
- useEffect(() => {
- if (!pickRef) return;
- pickRef.current = (point) => {
- camera.updateMatrixWorld();
- const viewProjection = new THREE.Matrix4()
- .multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse)
- .elements;
- return pickNearestNodeByScreenDistance({
- nodes: graph.simNodes,
- viewProjection,
- width: size.width,
- height: size.height,
- point
- });
- };
- return () => { pickRef.current = null; };
- }, [camera, graph, size.width, size.height, pickRef]);
-
- return (
- <>
- <ambientLight intensity={0.4} />
- <pointLight position={[50, 50, 50]} intensity={0.8} />
- <pointLight position={[-30, -30, -30]} intensity={0.3} />
-
- <GraphEdges simEdges={graph.simEdges} selectedId={selectedId} />
-
- {graph.simNodes.map(node => {
- const radius = 0.4 + (node.importance ?? 0.5) * 0.8;
- const color = BRAIN_TYPE_HEX[node.brainType] || '#6b7280';
- const isSelected = node.id === selectedId;
- const isConnected = adjacentIds?.has(node.id);
- const dimmed = selectedId && !isSelected && !isConnected;
-
- return (
- <mesh
- key={node.id}
- geometry={sphereGeo}
- scale={radius}
- position={[node.x, node.y, node.z]}
- // Touch selection is owned by the wrapper's threshold pick, which
- // fires on `pointerup` — ahead of the compatibility `click` r3f
- // raycasts here — so a tap that lands on a mesh must not toggle the
- // same node a second time. `click` is a MouseEvent with no
- // `pointerType` after a touch, hence the recorded gesture ref.
- onClick={(e) => {
- e.stopPropagation();
- if (touchGestureRef?.current) return;
- onSelect(node);
- }}
- onDoubleClick={(e) => { e.stopPropagation(); onFocus(node); }}
- // Pass the enter event's coordinates up: the wrapper's onPointerMove
- // only tracks the cursor WHILE a node is hovered, so the tooltip's
- // first frame has to be placed from this event.
- onPointerOver={(e) => { e.stopPropagation(); onHover(node, { x: e.clientX, y: e.clientY }); }}
- onPointerOut={() => onHover(null)}
- >
- <meshStandardMaterial
- color={dimmed ? '#1a1a1a' : color}
- emissive={color}
- emissiveIntensity={isSelected ? 0.6 : (dimmed ? 0.03 : 0.2)}
- />
- </mesh>
- );
- })}
-
- {selNode && (
- <mesh geometry={sphereGeo} position={[selNode.x, selNode.y, selNode.z]} scale={selRadius + 0.2}>
- <meshBasicMaterial color="#ffffff" transparent opacity={0.15} wireframe />
- </mesh>
- )}
-
- <OrbitControls enableDamping={!reducedMotion} dampingFactor={0.05} minDistance={10} maxDistance={200} />
- </>
- );
-});
-
export default function BrainGraph() {
const [graphData, setGraphData] = useState(null);
const [loading, setLoading] = useState(true);
const [subLoading, setSubLoading] = useState(false);
const [selectedNode, setSelectedNode] = useState(null);
const [fullRecord, setFullRecord] = useState(null);
- // Hover tooltip state + the ref-gated pointer tracking that keeps a plain
- // mouse move from re-rendering this component when nothing can paint.
- const { hoveredNode, tooltipPos, handleHover, handlePointerMove } = useHoverTooltip();
- const { visible: touchHintVisible, showOnFirstTouch } = useFirstTouchHint();
const { theme } = useThemeContext();
const [layoutKey, setLayoutKey] = useState(0);
const [syncing, setSyncing] = useState(false);
@@ -246,12 +102,6 @@ export default function BrainGraph() {
const motionSettings = graphMotionSettings(reducedMotion);
const graphRef = useRef(null);
- const dragStartRef = useRef(null);
- // Set by GraphScene: (point in canvas-local px) => node | null.
- const pickRef = useRef(null);
- // True while the in-flight gesture came from a finger, so the mesh raycast
- // and onPointerMissed can stand down for the threshold pick below.
- const touchGestureRef = useRef(false);
const focusId = currentFocusId(focusTrail);
@@ -371,6 +221,21 @@ export default function BrainGraph() {
setSelectedNode(prev => (node && prev?.id !== node.id ? node : null));
}, []);
+ // Pointer/tap/tooltip wiring shared with MemoryGraph — see
+ // graph3d/useGraphCanvasInteraction.js.
+ const {
+ pickRef,
+ touchGestureRef,
+ hoveredNode,
+ tooltipPos,
+ handleHover,
+ handlePointerMove,
+ touchHintVisible,
+ handlePointerDown,
+ handlePointerUp,
+ handlePointerMissed
+ } = useGraphCanvasInteraction({ onSelect: handleSelect });
+
// Escape always clears selection. Clicking "empty space" is unreliable for
// un-isolating: unselected nodes are only dimmed (not removed), so they still
// capture clicks, and onPointerMissed ignores any orbit drag — leaving the
@@ -382,44 +247,6 @@ export default function BrainGraph() {
return () => window.removeEventListener('keydown', onKey);
}, [selectedNode]);
- // Mouse only: a touch tap is resolved by handlePointerUp below (which also
- // owns clearing on an empty-space tap), and would otherwise be undone here by
- // the compatibility `click` r3f fires afterwards.
- const handlePointerMissed = useCallback((e) => {
- if (touchGestureRef.current) return;
- if (isTapGesture(dragStartRef.current, { x: e.clientX, y: e.clientY })) {
- setSelectedNode(null);
- }
- }, []);
-
- const handlePointerDown = useCallback((e) => {
- if (!isCanvasGesture(e)) return;
- showOnFirstTouch(e);
- // A second finger is a pinch-zoom or two-finger pan, never a tap — drop the
- // recorded start so neither the threshold pick nor the miss-clear can fire
- // for it (both gate on `isTapGesture`, which is false without a start).
- const secondFinger = touchGestureRef.current && !e.isPrimary;
- dragStartRef.current = secondFinger ? null : { x: e.clientX, y: e.clientY };
- touchGestureRef.current = e.pointerType === 'touch';
- }, [showOnFirstTouch]);
-
- // Touch selection. The raw mesh raycast needs the ray to hit a ~10px sphere;
- // instead project every node and take the nearest within a finger-sized
- // radius (see lib/graphPicking.js). Runs on `pointerup` on the wrapper, which
- // bubbles after the canvas' own pointerup and before the `click` r3f picks
- // with — so this result is what sticks. Mouse input is untouched.
- const handlePointerUp = useCallback((e) => {
- if (!touchGestureRef.current || !isCanvasGesture(e)) return;
- const end = { x: e.clientX, y: e.clientY };
- if (!isTapGesture(dragStartRef.current, end)) return; // an orbit drag
- // The CANVAS rect, not the wrapper's: the wrapper carries a 1px border, and
- // `size` from useThree measures the canvas, so mixing the two shifts every
- // projected position against the tap.
- const rect = e.target.getBoundingClientRect();
- const picked = pickRef.current?.({ x: end.x - rect.left, y: end.y - rect.top }) ?? null;
- handleSelect(picked);
- }, [handleSelect]);
-
// refresh:true re-embeds already-mapped records — the recovery path for
// memory entries that diverged before synced-in records were re-vectorized
// automatically (issue #1080). onlyMissing:true embeds just the records that
@@ -654,6 +481,9 @@ export default function BrainGraph() {
graph={graph}
selectedId={selectedNode?.id}
adjacentIds={adjacentIds}
+ nodeColor={brainNodeColor}
+ edgeColor={brainEdgeColor}
+ edgeIntensity={brainEdgeIntensity}
onSelect={handleSelect}
onFocus={focusNode}
onHover={handleHover}
diff --git a/client/src/components/brain/tabs/BrainGraph.test.jsx b/client/src/components/brain/tabs/BrainGraph.test.jsx
index 556bcb8cf9..c38a4573ea 100644
--- a/client/src/components/brain/tabs/BrainGraph.test.jsx
+++ b/client/src/components/brain/tabs/BrainGraph.test.jsx
@@ -41,7 +41,7 @@ vi.mock('../../../services/api', () => ({
import * as api from '../../../services/api';
import { chipColors, parseColor } from '../../../lib/chipContrast';
import { BRAIN_TYPE_HEX } from '../constants';
-import BrainGraph, { graphMotionSettings, recordBody } from './BrainGraph';
+import BrainGraph, { recordBody, brainEdgeColor, brainEdgeIntensity } from './BrainGraph';
const GRAPH = {
hasEmbeddings: true,
@@ -91,13 +91,27 @@ describe('reduced motion', () => {
expect(window.matchMedia).toHaveBeenCalledWith('(prefers-reduced-motion: reduce)');
expect(screen.getByTestId('graph-canvas')).toHaveAttribute('data-frameloop', 'demand');
});
+});
- it('stops the canvas render loop and OrbitControls inertia when motion is reduced', () => {
- expect(graphMotionSettings(true)).toEqual({ frameloop: 'demand', enableDamping: false });
+// The scene appearance moved to the shared graph3d/GraphScene + GraphEdges
+// (#6828) — these callbacks are what preserves BrainGraph's distinct render
+// (a per-edge-type palette, and a flat intensity for "linked" edges) now that
+// MemoryGraph's own flat blue/gray, weight-scaled palette runs through the
+// same shared component. graphMotionSettings' own contract is pinned in
+// graph3d/GraphScene.test.jsx, its new canonical home.
+describe('edge appearance (graph3d extraction)', () => {
+ it('colors each edge type from EDGE_COLORS, falling back to gray for an unknown type', () => {
+ expect(brainEdgeColor({ type: 'similar' })).toBe('#3b82f6');
+ expect(brainEdgeColor({ type: 'shared_tag' })).toBe('#f59e0b');
+ expect(brainEdgeColor({ type: 'linked' })).toBe('#ffffff');
+ expect(brainEdgeColor({ type: 'unknown' })).toBe('#6b7280');
});
- it('keeps animated rendering and controls for users without the preference', () => {
- expect(graphMotionSettings(false)).toEqual({ frameloop: 'always', enableDamping: true });
+ it('holds linked edges at a flat intensity and defaults an unweighted similarity edge to 0.5', () => {
+ expect(brainEdgeIntensity({ type: 'linked', weight: 0.1 }, false)).toBe(0.6);
+ expect(brainEdgeIntensity({ type: 'similar', weight: undefined }, false)).toBeCloseTo(0.3 * 0.5);
+ expect(brainEdgeIntensity({ type: 'similar', weight: 0.8 }, false)).toBeCloseTo(0.3 * 0.8);
+ expect(brainEdgeIntensity({ type: 'linked' }, true)).toBe(0.06);
});
});
diff --git a/client/src/components/cos/tabs/MemoryGraph.jsx b/client/src/components/cos/tabs/MemoryGraph.jsx
index 0b03422f62..0d447be16e 100644
--- a/client/src/components/cos/tabs/MemoryGraph.jsx
+++ b/client/src/components/cos/tabs/MemoryGraph.jsx
@@ -1,14 +1,13 @@
import { useState, useEffect, useMemo, useRef, useCallback } from 'react';
import { Canvas } from '@react-three/fiber';
-import { OrbitControls } from '@react-three/drei';
-import * as THREE from 'three';
import { Info } from 'lucide-react';
import * as api from '../../../services/api';
import { MEMORY_TYPES, MEMORY_TYPE_COLORS } from '../constants';
import { buildGraph } from '../../../lib/graphSimulation';
+import GraphScene, { graphMotionSettings } from '../../graph3d/GraphScene';
+import useGraphCanvasInteraction from '../../graph3d/useGraphCanvasInteraction';
import BrailleSpinner from '../../BrailleSpinner';
-import useHoverTooltip from '../../../hooks/useHoverTooltip';
-import useFirstTouchHint from '../../../hooks/useFirstTouchHint';
+import usePrefersReducedMotion from '../../../hooks/usePrefersReducedMotion';
import { formatDateNumeric } from '../../../utils/formatters';
// Widest the hover tooltip renders. Single source for both its max-width and
@@ -25,100 +24,15 @@ const TYPE_HEX = {
context: '#6b7280'
};
-// --- Three.js scene components ---
-
-function GraphEdges({ simEdges, selectedId }) {
- const geoRef = useRef();
-
- useEffect(() => {
- const geo = geoRef.current;
- if (!geo || !simEdges.length) return;
-
- const count = simEdges.length;
- const positions = new Float32Array(count * 6);
- const colors = new Float32Array(count * 6);
- const tmpColor = new THREE.Color();
-
- simEdges.forEach((e, i) => {
- const a = e.sourceNode, b = e.targetNode;
- const off = i * 6;
- positions[off] = a.x; positions[off + 1] = a.y; positions[off + 2] = a.z;
- positions[off + 3] = b.x; positions[off + 4] = b.y; positions[off + 5] = b.z;
-
- const dimmed = selectedId && e.source !== selectedId && e.target !== selectedId;
- tmpColor.set(e.type === 'linked' ? '#3b82f6' : '#6b7280');
- const intensity = dimmed ? 0.06 : (e.type === 'linked' ? 0.6 * e.weight : 0.3 * e.weight);
- const r = tmpColor.r * intensity, g = tmpColor.g * intensity, bl = tmpColor.b * intensity;
- colors[off] = r; colors[off + 1] = g; colors[off + 2] = bl;
- colors[off + 3] = r; colors[off + 4] = g; colors[off + 5] = bl;
- });
-
- geo.setAttribute('position', new THREE.BufferAttribute(positions, 3));
- geo.setAttribute('color', new THREE.BufferAttribute(colors, 3));
- geo.computeBoundingSphere();
- }, [simEdges, selectedId]);
-
- return (
- <lineSegments>
- <bufferGeometry ref={geoRef} />
- <lineBasicMaterial vertexColors />
- </lineSegments>
- );
-}
-
-function GraphScene({ graph, selectedId, adjacentIds, onSelect, onHover }) {
- const sphereGeo = useMemo(() => new THREE.SphereGeometry(1, 16, 12), []);
-
- const selNode = selectedId ? graph.idMap.get(selectedId) : null;
- const selRadius = selNode ? 0.4 + (selNode.importance ?? 0.5) * 0.8 : 0;
-
- return (
- <>
- <ambientLight intensity={0.4} />
- <pointLight position={[50, 50, 50]} intensity={0.8} />
- <pointLight position={[-30, -30, -30]} intensity={0.3} />
-
- <GraphEdges simEdges={graph.simEdges} selectedId={selectedId} />
-
- {graph.simNodes.map(node => {
- const radius = 0.4 + (node.importance ?? 0.5) * 0.8;
- const color = TYPE_HEX[node.type] || '#6b7280';
- const isSelected = node.id === selectedId;
- const isConnected = adjacentIds?.has(node.id);
- const dimmed = selectedId && !isSelected && !isConnected;
-
- return (
- <mesh
- key={node.id}
- geometry={sphereGeo}
- scale={radius}
- position={[node.x, node.y, node.z]}
- onClick={(e) => { e.stopPropagation(); onSelect(node); }}
- // Pass the enter event's coordinates up: the wrapper's onPointerMove
- // only tracks the cursor WHILE a node is hovered, so the tooltip's
- // first frame has to be placed from this event.
- onPointerOver={(e) => { e.stopPropagation(); onHover(node, { x: e.clientX, y: e.clientY }); }}
- onPointerOut={() => onHover(null)}
- >
- <meshStandardMaterial
- color={dimmed ? '#1a1a1a' : color}
- emissive={color}
- emissiveIntensity={isSelected ? 0.6 : (dimmed ? 0.03 : 0.2)}
- />
- </mesh>
- );
- })}
-
- {selNode && (
- <mesh geometry={sphereGeo} position={[selNode.x, selNode.y, selNode.z]} scale={selRadius + 0.2}>
- <meshBasicMaterial color="#ffffff" transparent opacity={0.15} wireframe />
- </mesh>
- )}
-
- <OrbitControls enableDamping dampingFactor={0.05} minDistance={10} maxDistance={200} />
- </>
- );
-}
+// Scene-appearance callbacks handed to the shared graph3d/GraphScene —
+// exported so the extraction's behavior split from BrainGraph's own
+// per-edge-type palette and weight fallback is pinned directly (see
+// MemoryGraph.test.jsx). Unlike BrainGraph, every edge kind here scales by
+// weight (including "linked", which BrainGraph holds at a flat intensity).
+export const memoryNodeColor = (node) => TYPE_HEX[node.type] || '#6b7280';
+export const memoryEdgeColor = (edge) => (edge.type === 'linked' ? '#3b82f6' : '#6b7280');
+export const memoryEdgeIntensity = (edge, dimmed) =>
+ dimmed ? 0.06 : (edge.type === 'linked' ? 0.6 * edge.weight : 0.3 * edge.weight);
// --- Outer component ---
@@ -127,16 +41,13 @@ export default function MemoryGraph() {
const [loading, setLoading] = useState(true);
const [selectedNode, setSelectedNode] = useState(null);
const [fullMemory, setFullMemory] = useState(null);
- // Hover tooltip state + the ref-gated pointer tracking that keeps a plain
- // mouse move from re-rendering this component when nothing can paint.
- const { hoveredNode, tooltipPos, handleHover, handlePointerMove } = useHoverTooltip();
- const { visible: touchHintVisible, showOnFirstTouch } = useFirstTouchHint();
const [layoutKey, setLayoutKey] = useState(0);
// Mobile-only: the legend auto-shows on a roomy viewport (CSS, not this flag).
const [legendOpen, setLegendOpen] = useState(false);
+ const reducedMotion = usePrefersReducedMotion();
+ const motionSettings = graphMotionSettings(reducedMotion);
const graphRef = useRef(null);
- const dragStartRef = useRef(null);
useEffect(() => {
api.getMemoryGraph().then(setGraphData).catch(() => setGraphData(null)).finally(() => setLoading(false));
@@ -182,17 +93,27 @@ export default function MemoryGraph() {
return () => { cancelled = true; };
}, [selectedNode]);
+ // A null node clears the selection (an empty-space tap, or a touch pick
+ // that landed on nothing — see useGraphCanvasInteraction); re-selecting the
+ // current node toggles it off.
const handleSelect = useCallback((node) => {
- setSelectedNode(prev => prev?.id === node.id ? null : node);
+ setSelectedNode(prev => (node && prev?.id !== node.id ? node : null));
}, []);
- const handlePointerMissed = useCallback((e) => {
- const start = dragStartRef.current;
- if (!start) return;
- if (Math.abs(e.clientX - start.x) < 5 && Math.abs(e.clientY - start.y) < 5) {
- setSelectedNode(null);
- }
- }, []);
+ // Pointer/tap/tooltip wiring shared with BrainGraph — see
+ // graph3d/useGraphCanvasInteraction.js.
+ const {
+ pickRef,
+ touchGestureRef,
+ hoveredNode,
+ tooltipPos,
+ handleHover,
+ handlePointerMove,
+ touchHintVisible,
+ handlePointerDown,
+ handlePointerUp,
+ handlePointerMissed
+ } = useGraphCanvasInteraction({ onSelect: handleSelect });
if (loading) {
return (
@@ -232,15 +153,14 @@ export default function MemoryGraph() {
desktop, floors at 240px so it stays usable on a short viewport. */}
<div
className="relative bg-port-card border border-port-border rounded-lg overflow-hidden h-[clamp(240px,45vh,500px)]"
- onPointerDown={(e) => {
- dragStartRef.current = { x: e.clientX, y: e.clientY };
- if (e.target?.tagName === 'CANVAS') showOnFirstTouch(e);
- }}
+ onPointerDown={handlePointerDown}
+ onPointerUp={handlePointerUp}
onPointerMove={handlePointerMove}
>
{graph && (
<Canvas
camera={{ position: [0, 0, 80], fov: 50 }}
+ frameloop={motionSettings.frameloop}
dpr={[1, 1.5]}
style={{ background: 'rgb(var(--port-bg))' }}
gl={{ antialias: true }}
@@ -250,8 +170,14 @@ export default function MemoryGraph() {
graph={graph}
selectedId={selectedNode?.id}
adjacentIds={adjacentIds}
+ nodeColor={memoryNodeColor}
+ edgeColor={memoryEdgeColor}
+ edgeIntensity={memoryEdgeIntensity}
onSelect={handleSelect}
onHover={handleHover}
+ pickRef={pickRef}
+ touchGestureRef={touchGestureRef}
+ reducedMotion={reducedMotion}
/>
</Canvas>
)}
diff --git a/client/src/components/cos/tabs/MemoryGraph.test.jsx b/client/src/components/cos/tabs/MemoryGraph.test.jsx
index ca9a448c4b..fc0dd4d53f 100644
--- a/client/src/components/cos/tabs/MemoryGraph.test.jsx
+++ b/client/src/components/cos/tabs/MemoryGraph.test.jsx
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
-import { render, screen, act } from '@testing-library/react';
+import { render, screen, act, fireEvent } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
// The three.js stack can't run in jsdom (no WebGL context), and none of it is
@@ -7,12 +7,15 @@ import userEvent from '@testing-library/user-event';
// The stub deliberately drops `children` from the render: mounting the scene
// would create <bufferGeometry>/<mesh> as unknown DOM elements. It still
// *captures* the element so a test can reach GraphScene's callbacks (the only
-// way to open the hover tooltip without a real raycast).
+// way to open the hover tooltip, or stand in for a screen-space pick, without
+// a real raycast). Rendered as an actual <canvas> tag (not a <div>) so the
+// wrapper's `isCanvasGesture` check — `e.target.tagName === 'CANVAS'` — passes
+// for the touch-tap test below, matching what react-three-fiber really mounts.
let sceneElement = null;
vi.mock('@react-three/fiber', () => ({
- Canvas: ({ children }) => {
+ Canvas: ({ children, frameloop }) => {
sceneElement = children;
- return <div data-testid="graph-canvas" />;
+ return <canvas data-testid="graph-canvas" data-frameloop={frameloop} />;
},
}));
vi.mock('@react-three/drei', () => ({ OrbitControls: () => null }));
@@ -23,7 +26,7 @@ vi.mock('../../../services/api', () => ({
}));
import * as api from '../../../services/api';
-import MemoryGraph from './MemoryGraph';
+import MemoryGraph, { memoryEdgeColor, memoryEdgeIntensity } from './MemoryGraph';
const GRAPH = {
nodes: [
@@ -46,6 +49,7 @@ const hoverNode = async (node, point) => {
};
const originalInnerWidth = window.innerWidth;
+const originalMatchMedia = window.matchMedia;
beforeEach(() => {
vi.clearAllMocks();
@@ -56,6 +60,7 @@ beforeEach(() => {
afterEach(() => {
window.innerWidth = originalInnerWidth;
+ window.matchMedia = originalMatchMedia;
});
describe('canvas sizing', () => {
@@ -151,3 +156,60 @@ describe('hover tooltip placement', () => {
expect(tooltipOf(screen.getByText('first'))).toHaveClass('pointer-coarse:hidden');
});
});
+
+// Ported from BrainGraph via the graph3d extraction (#6828) — before this,
+// MemoryGraph never read the system preference at all, so the canvas always
+// ran its render loop and OrbitControls kept inertia regardless.
+describe('reduced motion', () => {
+ it('reads the system preference and renders the canvas on demand', async () => {
+ window.matchMedia = vi.fn(() => ({
+ matches: true,
+ addEventListener() {},
+ removeEventListener() {}
+ }));
+
+ await renderGraph();
+
+ expect(window.matchMedia).toHaveBeenCalledWith('(prefers-reduced-motion: reduce)');
+ expect(screen.getByTestId('graph-canvas')).toHaveAttribute('data-frameloop', 'demand');
+ });
+});
+
+// Ported from BrainGraph via the graph3d extraction (#6828) — before this,
+// MemoryGraph had no touch-pick wiring at all: a finger tap never selected a
+// node because the raw mesh raycast needs a hit on a ~10px sphere.
+describe('touch tap-to-select', () => {
+ it('selects the node the wrapper-owned screen-space pick resolves to', async () => {
+ await renderGraph();
+ const canvas = screen.getByTestId('graph-canvas');
+
+ // GraphScene never mounts in this suite (see the Canvas mock above), so
+ // its own pickRef effect (a real screen-space projection) never runs —
+ // stand in for it exactly as the scene would, via the same ref MemoryGraph
+ // handed it as a prop.
+ sceneElement.props.pickRef.current = () => GRAPH.nodes[1];
+
+ fireEvent.pointerDown(canvas, { pointerType: 'touch', isPrimary: true, clientX: 50, clientY: 50 });
+ fireEvent.pointerUp(canvas, { pointerType: 'touch', clientX: 52, clientY: 51 });
+ await act(async () => {});
+
+ expect(await screen.findByText('second')).toBeInTheDocument();
+ });
+});
+
+// Each page's edge callbacks preserve its own pre-extraction render (see
+// GraphEdges' `edgeColor`/`edgeIntensity` params) — MemoryGraph's flat
+// blue-linked/gray-everything-else, weight-scaled for BOTH edge kinds, unlike
+// BrainGraph's flat intensity for "linked" (BrainGraph.test.jsx).
+describe('edge appearance (graph3d extraction)', () => {
+ it('colors only linked edges blue; everything else gray', () => {
+ expect(memoryEdgeColor({ type: 'linked' })).toBe('#3b82f6');
+ expect(memoryEdgeColor({ type: 'similar' })).toBe('#6b7280');
+ });
+
+ it('scales both edge kinds by weight, unlike BrainGraph\'s flat linked intensity', () => {
+ expect(memoryEdgeIntensity({ type: 'linked', weight: 0.5 }, false)).toBeCloseTo(0.3);
+ expect(memoryEdgeIntensity({ type: 'similar', weight: 0.5 }, false)).toBeCloseTo(0.15);
+ expect(memoryEdgeIntensity({ type: 'linked', weight: 1 }, true)).toBe(0.06);
+ });
+});
diff --git a/client/src/components/graph3d/GraphEdges.jsx b/client/src/components/graph3d/GraphEdges.jsx
new file mode 100644
index 0000000000..948b1d175f
--- /dev/null
+++ b/client/src/components/graph3d/GraphEdges.jsx
@@ -0,0 +1,56 @@
+import { useEffect, useRef } from 'react';
+import * as THREE from 'three';
+
+/**
+ * Shared edge geometry for the 3D graph scenes (BrainGraph, MemoryGraph): one
+ * line-segment buffer built from `simEdges`, colored and dimmed per edge.
+ *
+ * `edgeColor`/`edgeIntensity` are callbacks rather than a fixed palette so
+ * each page's own edge legend reproduces its current render exactly —
+ * BrainGraph's three-way similar/shared_tag/linked color map with a
+ * `weight || 0.5` fallback for an unweighted edge, and MemoryGraph's flat
+ * blue-linked/gray-everything-else, weight-scaled for both edge kinds.
+ *
+ * @param {{sourceNode:{x,y,z}, targetNode:{x,y,z}, source, target}[]} simEdges
+ * @param {string|null} [selectedId]
+ * @param {(edge:object) => string} edgeColor
+ * @param {(edge:object, dimmed:boolean) => number} edgeIntensity
+ */
+export default function GraphEdges({ simEdges, selectedId, edgeColor, edgeIntensity }) {
+ const geoRef = useRef();
+
+ useEffect(() => {
+ const geo = geoRef.current;
+ if (!geo || !simEdges.length) return;
+
+ const count = simEdges.length;
+ const positions = new Float32Array(count * 6);
+ const colors = new Float32Array(count * 6);
+ const tmpColor = new THREE.Color();
+
+ simEdges.forEach((e, i) => {
+ const a = e.sourceNode, b = e.targetNode;
+ const off = i * 6;
+ positions[off] = a.x; positions[off + 1] = a.y; positions[off + 2] = a.z;
+ positions[off + 3] = b.x; positions[off + 4] = b.y; positions[off + 5] = b.z;
+
+ const dimmed = !!(selectedId && e.source !== selectedId && e.target !== selectedId);
+ tmpColor.set(edgeColor(e));
+ const intensity = edgeIntensity(e, dimmed);
+ const r = tmpColor.r * intensity, g = tmpColor.g * intensity, bl = tmpColor.b * intensity;
+ colors[off] = r; colors[off + 1] = g; colors[off + 2] = bl;
+ colors[off + 3] = r; colors[off + 4] = g; colors[off + 5] = bl;
+ });
+
+ geo.setAttribute('position', new THREE.BufferAttribute(positions, 3));
+ geo.setAttribute('color', new THREE.BufferAttribute(colors, 3));
+ geo.computeBoundingSphere();
+ }, [simEdges, selectedId, edgeColor, edgeIntensity]);
+
+ return (
+ <lineSegments>
+ <bufferGeometry ref={geoRef} />
+ <lineBasicMaterial vertexColors />
+ </lineSegments>
+ );
+}
diff --git a/client/src/components/graph3d/GraphScene.jsx b/client/src/components/graph3d/GraphScene.jsx
new file mode 100644
index 0000000000..35e822befc
--- /dev/null
+++ b/client/src/components/graph3d/GraphScene.jsx
@@ -0,0 +1,131 @@
+import { useEffect, useMemo, memo } from 'react';
+import { useThree } from '@react-three/fiber';
+import { OrbitControls } from '@react-three/drei';
+import * as THREE from 'three';
+import GraphEdges from './GraphEdges';
+import { pickNearestNodeByScreenDistance } from '../../lib/graphPicking';
+
+// The force layout is settled before the scene renders, so reduced-motion
+// users can see it immediately at rest. Keep the canvas on demand and turn
+// off OrbitControls' inertia too, preventing movement after an interaction.
+// Canonical home for both graph pages — call from the page that owns the
+// <Canvas> to size its `frameloop` prop; GraphScene reads `reducedMotion`
+// directly for its own OrbitControls damping.
+export const graphMotionSettings = (reducedMotion) => ({
+ frameloop: reducedMotion ? 'demand' : 'always',
+ enableDamping: !reducedMotion
+});
+
+// Memoized: the container's onPointerMove re-renders the owning page on every
+// mouse move over the canvas WHILE A NODE IS HOVERED (it tracks the tooltip
+// position), and every prop here is already identity-stable across that
+// render — so without memo each move reconciles a <mesh> per node for
+// nothing (#4116).
+const GraphScene = memo(function GraphScene({
+ graph,
+ selectedId,
+ adjacentIds,
+ nodeColor,
+ edgeColor,
+ edgeIntensity,
+ onSelect,
+ onFocus,
+ onHover,
+ pickRef,
+ touchGestureRef,
+ reducedMotion = false
+}) {
+ const sphereGeo = useMemo(() => new THREE.SphereGeometry(1, 16, 12), []);
+ const { camera, size } = useThree();
+
+ const selNode = selectedId ? graph.idMap.get(selectedId) : null;
+ const selRadius = selNode ? 0.4 + (selNode.importance ?? 0.5) * 0.8 : 0;
+
+ // Publish a live screen-space pick to the DOM wrapper, which owns the touch
+ // gesture (see useGraphCanvasInteraction). The camera object is stable
+ // across orbiting, so the matrices are read at tap time, not captured here.
+ useEffect(() => {
+ if (!pickRef) return;
+ pickRef.current = (point) => {
+ camera.updateMatrixWorld();
+ const viewProjection = new THREE.Matrix4()
+ .multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse)
+ .elements;
+ return pickNearestNodeByScreenDistance({
+ nodes: graph.simNodes,
+ viewProjection,
+ width: size.width,
+ height: size.height,
+ point
+ });
+ };
+ return () => { pickRef.current = null; };
+ }, [camera, graph, size.width, size.height, pickRef]);
+
+ return (
+ <>
+ <ambientLight intensity={0.4} />
+ <pointLight position={[50, 50, 50]} intensity={0.8} />
+ <pointLight position={[-30, -30, -30]} intensity={0.3} />
+
+ <GraphEdges
+ simEdges={graph.simEdges}
+ selectedId={selectedId}
+ edgeColor={edgeColor}
+ edgeIntensity={edgeIntensity}
+ />
+
+ {graph.simNodes.map(node => {
+ const radius = 0.4 + (node.importance ?? 0.5) * 0.8;
+ const color = nodeColor(node);
+ const isSelected = node.id === selectedId;
+ const isConnected = adjacentIds?.has(node.id);
+ const dimmed = selectedId && !isSelected && !isConnected;
+
+ return (
+ <mesh
+ key={node.id}
+ geometry={sphereGeo}
+ scale={radius}
+ position={[node.x, node.y, node.z]}
+ // Touch selection is owned by the wrapper's threshold pick, which
+ // fires on `pointerup` — ahead of the compatibility `click` r3f
+ // raycasts here — so a tap that lands on a mesh must not toggle the
+ // same node a second time. `click` is a MouseEvent with no
+ // `pointerType` after a touch, hence the recorded gesture ref.
+ onClick={(e) => {
+ e.stopPropagation();
+ if (touchGestureRef?.current) return;
+ onSelect(node);
+ }}
+ // `onFocus` is optional — MemoryGraph has no focus stack to drill
+ // into, so it passes none and a double-click here is a no-op,
+ // matching its pre-extraction behavior of never binding the prop.
+ onDoubleClick={onFocus ? (e) => { e.stopPropagation(); onFocus(node); } : undefined}
+ // Pass the enter event's coordinates up: the wrapper's onPointerMove
+ // only tracks the cursor WHILE a node is hovered, so the tooltip's
+ // first frame has to be placed from this event.
+ onPointerOver={(e) => { e.stopPropagation(); onHover(node, { x: e.clientX, y: e.clientY }); }}
+ onPointerOut={() => onHover(null)}
+ >
+ <meshStandardMaterial
+ color={dimmed ? '#1a1a1a' : color}
+ emissive={color}
+ emissiveIntensity={isSelected ? 0.6 : (dimmed ? 0.03 : 0.2)}
+ />
+ </mesh>
+ );
+ })}
+
+ {selNode && (
+ <mesh geometry={sphereGeo} position={[selNode.x, selNode.y, selNode.z]} scale={selRadius + 0.2}>
+ <meshBasicMaterial color="#ffffff" transparent opacity={0.15} wireframe />
+ </mesh>
+ )}
+
+ <OrbitControls enableDamping={!reducedMotion} dampingFactor={0.05} minDistance={10} maxDistance={200} />
+ </>
+ );
+});
+
+export default GraphScene;
diff --git a/client/src/components/graph3d/GraphScene.test.jsx b/client/src/components/graph3d/GraphScene.test.jsx
new file mode 100644
index 0000000000..ad6f506483
--- /dev/null
+++ b/client/src/components/graph3d/GraphScene.test.jsx
@@ -0,0 +1,76 @@
+import { describe, it, expect, vi } from 'vitest';
+import { render } from '@testing-library/react';
+
+// GraphScene renders raw react-three-fiber primitives (<mesh>, <ambientLight>,
+// ...) that only make sense inside a real WebGL canvas — this test DOM has
+// none. The graph carries no nodes/edges, so nothing tries to raycast or
+// mount a mesh, and the one child GraphScene always renders (GraphEdges) is
+// mocked to a call-counting spy: it doubles as "did GraphScene's function
+// body run again", which is exactly what `memo` gates.
+const graphEdgesSpy = vi.hoisted(() => vi.fn(() => null));
+vi.mock('./GraphEdges', () => ({ default: graphEdgesSpy }));
+vi.mock('@react-three/fiber', () => ({
+ useThree: () => ({ camera: {}, size: { width: 100, height: 100 } }),
+}));
+const orbitControlsSpy = vi.hoisted(() => vi.fn(() => null));
+vi.mock('@react-three/drei', () => ({ OrbitControls: orbitControlsSpy }));
+
+import GraphScene, { graphMotionSettings } from './GraphScene';
+
+const EMPTY_GRAPH = { simNodes: [], simEdges: [], idMap: new Map() };
+
+const baseProps = {
+ graph: EMPTY_GRAPH,
+ selectedId: null,
+ adjacentIds: null,
+ nodeColor: () => '#ffffff',
+ edgeColor: () => '#ffffff',
+ edgeIntensity: () => 1,
+ onSelect: () => {},
+ onHover: () => {},
+ pickRef: { current: null },
+ touchGestureRef: { current: false },
+ reducedMotion: false
+};
+
+describe('GraphScene memoization (#4116)', () => {
+ it('does not re-render when every prop stays referentially identical', () => {
+ const { rerender } = render(<GraphScene {...baseProps} />);
+ expect(graphEdgesSpy).toHaveBeenCalledTimes(1);
+
+ // Same underlying `baseProps` object spread again — exactly what the
+ // owning page's hover-tracking `onPointerMove` does on every mouse move.
+ rerender(<GraphScene {...baseProps} />);
+ expect(graphEdgesSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it('re-renders when a prop actually changes', () => {
+ const { rerender } = render(<GraphScene {...baseProps} />);
+ expect(graphEdgesSpy).toHaveBeenCalledTimes(1);
+
+ rerender(<GraphScene {...baseProps} selectedId="n1" />);
+ expect(graphEdgesSpy).toHaveBeenCalledTimes(2);
+ });
+});
+
+describe('reduced motion', () => {
+ it('keeps OrbitControls inertia by default', () => {
+ render(<GraphScene {...baseProps} />);
+ expect(orbitControlsSpy.mock.calls.at(-1)[0].enableDamping).toBe(true);
+ });
+
+ it('stops OrbitControls inertia when the user prefers reduced motion', () => {
+ render(<GraphScene {...baseProps} reducedMotion />);
+ expect(orbitControlsSpy.mock.calls.at(-1)[0].enableDamping).toBe(false);
+ });
+});
+
+describe('graphMotionSettings', () => {
+ it('stops the canvas render loop and OrbitControls inertia when motion is reduced', () => {
+ expect(graphMotionSettings(true)).toEqual({ frameloop: 'demand', enableDamping: false });
+ });
+
+ it('keeps animated rendering and controls for users without the preference', () => {
+ expect(graphMotionSettings(false)).toEqual({ frameloop: 'always', enableDamping: true });
+ });
+});
diff --git a/client/src/components/graph3d/useGraphCanvasInteraction.js b/client/src/components/graph3d/useGraphCanvasInteraction.js
new file mode 100644
index 0000000000..5c3ad2321f
--- /dev/null
+++ b/client/src/components/graph3d/useGraphCanvasInteraction.js
@@ -0,0 +1,90 @@
+import { useCallback, useRef } from 'react';
+import useHoverTooltip from '../../hooks/useHoverTooltip';
+import useFirstTouchHint from '../../hooks/useFirstTouchHint';
+import { isTapGesture } from '../../lib/graphPicking';
+
+// Only a gesture on the WebGL canvas itself picks or clears a node. The
+// overlay chrome — "Clear selection", the legend toggle, the loading veil —
+// sits INSIDE the same wrapper these handlers are bound to, so its taps
+// bubble there too; without this, tapping the legend toggle could also
+// select or clear whichever node happens to project nearest that corner.
+// (r3f binds its own listeners to the canvas, so the mouse path never had
+// this problem.)
+const isCanvasGesture = (e) => e.target?.tagName === 'CANVAS';
+
+/**
+ * Pointer/tap/tooltip wiring shared by the 3D graph scenes (BrainGraph,
+ * MemoryGraph): tells a canvas tap from an orbit drag, resolves a touch tap
+ * to the nearest node via the wrapper-owned screen-space pick (see
+ * lib/graphPicking.js and GraphScene's `pickRef`), and tracks the hover
+ * tooltip position.
+ *
+ * `onSelect` is called with the picked node to select it, or `null` to clear
+ * the selection — the same null-safe contract each page's own `handleSelect`
+ * already implements for a plain mesh click.
+ *
+ * Returns the refs GraphScene needs (`pickRef`, `touchGestureRef`) plus the
+ * handlers to wire onto the canvas wrapper div (`onPointerDown`,
+ * `onPointerUp`, `onPointerMove`) and the `<Canvas onPointerMissed>` itself.
+ */
+export default function useGraphCanvasInteraction({ onSelect }) {
+ const dragStartRef = useRef(null);
+ // Set by GraphScene: (point in canvas-local px) => node | null.
+ const pickRef = useRef(null);
+ // True while the in-flight gesture came from a finger, so the mesh raycast
+ // and onPointerMissed can stand down for the threshold pick below.
+ const touchGestureRef = useRef(false);
+ const { hoveredNode, tooltipPos, handleHover, handlePointerMove } = useHoverTooltip();
+ const { visible: touchHintVisible, showOnFirstTouch } = useFirstTouchHint();
+
+ const handlePointerDown = useCallback((e) => {
+ if (!isCanvasGesture(e)) return;
+ showOnFirstTouch(e);
+ // A second finger is a pinch-zoom or two-finger pan, never a tap — drop the
+ // recorded start so neither the threshold pick nor the miss-clear can fire
+ // for it (both gate on `isTapGesture`, which is false without a start).
+ const secondFinger = touchGestureRef.current && !e.isPrimary;
+ dragStartRef.current = secondFinger ? null : { x: e.clientX, y: e.clientY };
+ touchGestureRef.current = e.pointerType === 'touch';
+ }, [showOnFirstTouch]);
+
+ // Touch selection. The raw mesh raycast needs the ray to hit a ~10px sphere;
+ // instead project every node and take the nearest within a finger-sized
+ // radius (see lib/graphPicking.js). Runs on `pointerup` on the wrapper, which
+ // bubbles after the canvas' own pointerup and before the `click` r3f picks
+ // with — so this result is what sticks. Mouse input is untouched.
+ const handlePointerUp = useCallback((e) => {
+ if (!touchGestureRef.current || !isCanvasGesture(e)) return;
+ const end = { x: e.clientX, y: e.clientY };
+ if (!isTapGesture(dragStartRef.current, end)) return; // an orbit drag
+ // The CANVAS rect, not the wrapper's: the wrapper carries a 1px border, and
+ // r3f's `size` measures the canvas, so mixing the two shifts every
+ // projected position against the tap.
+ const rect = e.target.getBoundingClientRect();
+ const picked = pickRef.current?.({ x: end.x - rect.left, y: end.y - rect.top }) ?? null;
+ onSelect(picked);
+ }, [onSelect]);
+
+ // Mouse only: a touch tap is resolved by handlePointerUp above (which also
+ // owns clearing on an empty-space tap), and would otherwise be undone here by
+ // the compatibility `click` r3f fires afterwards.
+ const handlePointerMissed = useCallback((e) => {
+ if (touchGestureRef.current) return;
+ if (isTapGesture(dragStartRef.current, { x: e.clientX, y: e.clientY })) {
+ onSelect(null);
+ }
+ }, [onSelect]);
+
+ return {
+ pickRef,
+ touchGestureRef,
+ hoveredNode,
+ tooltipPos,
+ handleHover,
+ handlePointerMove,
+ touchHintVisible,
+ handlePointerDown,
+ handlePointerUp,
+ handlePointerMissed
+ };
+}