Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
172 changes: 159 additions & 13 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import { Panel, PanelGroup, PanelResizeHandle, type ImperativePanelHandle } from 'react-resizable-panels'
import { useQueryClient } from '@tanstack/react-query'
import { useGraphSnapshot, useRecall } from './hooks/useGraphData'
import { useGraphSnapshot, useGraphNeighbors, useRecall } from './hooks/useGraphData'
import { useExpandableGraph } from './hooks/useExpandableGraph'
import { normalizeNode } from './lib/normalizeNode'
import {
Expand Down Expand Up @@ -142,7 +142,10 @@
const [performanceMode, setPerformanceMode] = useState(false)
const [settingsPanelOpen, setSettingsPanelOpen] = useState(false)
const [shortcutsHelpOpen, setShortcutsHelpOpen] = useState(false)
const [statusMessage, setStatusMessage] = useState<string | null>(null)
const [statusMessage, setStatusMessage] = useState<{
text: string
action?: { label: string; onClick: () => void }
} | null>(null)
const statusTimeoutRef = useRef<number | null>(null)

const canvasContainerRef = useRef<HTMLDivElement>(null)
Expand Down Expand Up @@ -323,7 +326,7 @@
if (recording.isRecording) {
recording.recordFrame(state, trackingInfo.hasLiDAR)
}
}, [recording.isRecording, recording.recordFrame, trackingInfo.hasLiDAR])

Check warning on line 329 in src/App.tsx

View workflow job for this annotation

GitHub Actions / lint-build

React Hook useCallback has a missing dependency: 'recording'. Either include it or remove the dependency array

const { lock: handLock } = useHandLockAndGrab(gestureState, gestureControlEnabled)

Expand Down Expand Up @@ -510,7 +513,7 @@
}
prevTimeTravelActive.current = timeTravel.isActive
}
}, [timeTravel.isActive, sound.playTimeTravel])

Check warning on line 516 in src/App.tsx

View workflow job for this annotation

GitHub Actions / lint-build

React Hook useEffect has a missing dependency: 'sound'. Either include it or remove the dependency array

// Get source and target nodes for pathfinding overlay
const pathSourceNode = useMemo(() => {
Expand All @@ -523,22 +526,90 @@
return nodes.find(n => n.id === pathfinding.targetId) ?? null
}, [pathfinding.targetId, nodes])

const showStatus = useCallback((message: string) => {
setStatusMessage(message)
if (statusTimeoutRef.current !== null) {
window.clearTimeout(statusTimeoutRef.current)
const showStatus = useCallback(
(
message: string,
opts?: { actionLabel: string; onAction: () => void; durationMs?: number }
) => {
setStatusMessage(
opts
? { text: message, action: { label: opts.actionLabel, onClick: opts.onAction } }
: { text: message }
)
if (statusTimeoutRef.current !== null) {
window.clearTimeout(statusTimeoutRef.current)
}
statusTimeoutRef.current = window.setTimeout(() => {
setStatusMessage(null)
statusTimeoutRef.current = null
}, opts?.durationMs ?? 1800)
},
[]
)

// Acknowledge the silent URL-token handshake. A shared /viewer/#token= link
// auto-authenticates with zero feedback — confirm which server answered, once,
// on the first successful load. Standalone (typed-in) auth already had its
// explicit Connect step, so it stays quiet.
const connectionToastShownRef = useRef(false)

Check failure on line 554 in src/App.tsx

View workflow job for this annotation

GitHub Actions / lint-build

Cannot redeclare block-scoped variable 'connectionToastShownRef'.
useEffect(() => {
if (!data || connectionToastShownRef.current) return
connectionToastShownRef.current = true
const info = getConnectionInfo()
if (info.embedded || info.tokenFromUrl) {
let host = info.serverUrl
try {
host = new URL(info.serverUrl).host
} catch {
// Relative base — keep as-is.
}
showStatus(`Connected to ${host}`)
}
statusTimeoutRef.current = window.setTimeout(() => {
setStatusMessage(null)
statusTimeoutRef.current = null
}, 1800)
}, [])
}, [data, showStatus])

// Sign out / re-enter credentials: URL-borne tokens (?token=, #token=) outrank
// localStorage in the auth chain, so clearing storage alone wouldn't sign a
// shared-link session out — strip them from the URL too, then TokenPrompt
// renders naturally via isAuthenticated.
const handleReenterCredentials = useCallback(() => {

Check failure on line 574 in src/App.tsx

View workflow job for this annotation

GitHub Actions / lint-build

Cannot redeclare block-scoped variable 'handleReenterCredentials'.
const url = new URL(window.location.href)
url.searchParams.delete('token')
if (url.hash) {
const hashParams = new URLSearchParams(url.hash.slice(1))
hashParams.delete('token')
const rest = hashParams.toString()
url.hash = rest ? `#${rest}` : ''
}
window.history.replaceState(null, '', url.toString())
clearAuth()
}, [clearAuth])

// Settings → Connection section. Recomputed when the panel opens (token /
// server state lives in localStorage + URL, both cheap reads).
const connectionInfo = useMemo(() => {

Check failure on line 589 in src/App.tsx

View workflow job for this annotation

GitHub Actions / lint-build

Cannot redeclare block-scoped variable 'connectionInfo'.
if (!settingsPanelOpen) return undefined
const info = getConnectionInfo()
return {
serverUrl: info.serverUrl,
token: info.token,
tokenFromUrl: info.tokenFromUrl,
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [settingsPanelOpen, isAuthenticated])

// Auth rejections deserve their own story: a bad shared-link token used to
// surface as a generic "Connection Error" + Retry, a dead end that retries
// into the same 401 forever.
const isAuthError = useMemo(

Check failure on line 603 in src/App.tsx

View workflow job for this annotation

GitHub Actions / lint-build

Cannot redeclare block-scoped variable 'isAuthError'.
() => !!error && isAuthErrorMessage((error as Error).message ?? ''),
[error]
)

// Acknowledge the silent URL-token handshake. A shared /viewer/#token= link
// auto-authenticates with zero feedback — confirm which server answered, once,
// on the first successful load. Standalone (typed-in) auth already had its
// explicit Connect step, so it stays quiet.
const connectionToastShownRef = useRef(false)

Check failure on line 612 in src/App.tsx

View workflow job for this annotation

GitHub Actions / lint-build

Cannot redeclare block-scoped variable 'connectionToastShownRef'.
useEffect(() => {
if (!data || connectionToastShownRef.current) return
connectionToastShownRef.current = true
Expand All @@ -558,7 +629,7 @@
// localStorage in the auth chain, so clearing storage alone wouldn't sign a
// shared-link session out — strip them from the URL too, then TokenPrompt
// renders naturally via isAuthenticated.
const handleReenterCredentials = useCallback(() => {

Check failure on line 632 in src/App.tsx

View workflow job for this annotation

GitHub Actions / lint-build

Cannot redeclare block-scoped variable 'handleReenterCredentials'.
const url = new URL(window.location.href)
url.searchParams.delete('token')
if (url.hash) {
Expand All @@ -573,7 +644,7 @@

// Settings → Connection section. Recomputed when the panel opens (token /
// server state lives in localStorage + URL, both cheap reads).
const connectionInfo = useMemo(() => {

Check failure on line 647 in src/App.tsx

View workflow job for this annotation

GitHub Actions / lint-build

Cannot redeclare block-scoped variable 'connectionInfo'.
if (!settingsPanelOpen) return undefined
const info = getConnectionInfo()
return {
Expand All @@ -587,7 +658,7 @@
// Auth rejections deserve their own story: a bad shared-link token used to
// surface as a generic "Connection Error" + Retry, a dead end that retries
// into the same 401 forever.
const isAuthError = useMemo(

Check failure on line 661 in src/App.tsx

View workflow job for this annotation

GitHub Actions / lint-build

Cannot redeclare block-scoped variable 'isAuthError'.
() => !!error && isAuthErrorMessage((error as Error).message ?? ''),
[error]
)
Expand All @@ -609,7 +680,7 @@
breadcrumbPush(node)
}
setSelectedNode(node)
}, [pathfinding.isSelectingTarget, pathfinding.completePathSelection, sound.playPathFound, sound.playSelect, breadcrumbPush])

Check warning on line 683 in src/App.tsx

View workflow job for this annotation

GitHub Actions / lint-build

React Hook useCallback has missing dependencies: 'pathfinding' and 'sound'. Either include them or remove the dependency array

const handleInspectorNavigate = useCallback((node: GraphNode | null) => {
if (!node) return
Expand Down Expand Up @@ -677,12 +748,66 @@
[visibleNodeIds, nodes, handleResultSelect, handleNodeSelect, graph, queryClient, data?.meta?.type_colors, NEIGHBOR_PARAMS],
)

// Expansion frontier: how many of the selected node's neighbors are NOT yet
// in view. Shares the Inspector's exact query key, so the two dedupe to a
// single request when both mount; the hook can still fetch on its own when
// the cache is cold or stale. Drives the dashed "+N more" ring on the canvas.
const selectedNeighbors = useGraphNeighbors(selectedNode?.id ?? null, NEIGHBOR_PARAMS)
const frontierCount = useMemo(() => {
const d = selectedNeighbors.data
if (!d || !selectedNode) return 0
const seen = new Set<string>()
let count = 0
for (const n of [...d.graph_neighbors, ...d.semantic_neighbors]) {
if (!n.id || seen.has(n.id) || n.id === selectedNode.id) continue
seen.add(n.id)
if (!visibleNodeIds.has(n.id)) count++
}
return count
}, [selectedNeighbors.data, visibleNodeIds, selectedNode])

// Announce arrivals: every expansion (inspector "Expand into graph" or an
// off-graph search-result injection) gets a toast naming the anchor, with a
// single-level Undo (tail-only removal — see useExpandableGraph invariants).
// Keyed on lastExpansion identity (not newNodeIds) so an edges-only
// expansion — all neighbor nodes already in view, new connections discovered
// — announces itself too instead of merging silently.
const prevLastExpansionRef = useRef(graph.lastExpansion)
const { undoLastExpansion } = graph
useEffect(() => {
const last = graph.lastExpansion
if (last === prevLastExpansionRef.current) return
prevLastExpansionRef.current = last
if (!last) return // reset/undo cleared it — nothing to announce
const nodeCount = last.nodeIds.length
const edgeCount = last.edgeIds.length
if (nodeCount === 0 && edgeCount === 0) return
const center = rawNodes.find((n) => n.id === last.centerId)
const title = center
? `"${center.content.slice(0, 28)}${center.content.length > 28 ? '…' : ''}"`
: 'the selection'
const message =
nodeCount > 0
? `+${nodeCount} ${nodeCount === 1 ? 'memory' : 'memories'} connected to ${title}`
: `+${edgeCount} new ${edgeCount === 1 ? 'connection' : 'connections'} to ${title}`
const removedIds = new Set(last.nodeIds)
showStatus(message, {
actionLabel: 'Undo',
onAction: () => {
undoLastExpansion()
// Don't leave a removed node selected — it no longer exists in view.
setSelectedNode((prev) => (prev && removedIds.has(prev.id) ? null : prev))
},
durationMs: 6000,
})
}, [graph.lastExpansion, undoLastExpansion, rawNodes, showStatus])

const handleNodeHover = useCallback((node: GraphNode | null) => {
if (node) {
sound.playHover()
}
setHoveredNode(node)
}, [sound.playHover])

Check warning on line 810 in src/App.tsx

View workflow job for this annotation

GitHub Actions / lint-build

React Hook useCallback has a missing dependency: 'sound'. Either include it or remove the dependency array

const handleSearch = useCallback((term: string) => {
// Play search sound on typing (only if term changed and is not empty)
Expand All @@ -693,7 +818,7 @@
setSelectedNode(null)
}
setSearchTerm(term)
}, [sound.playSearch])

Check warning on line 821 in src/App.tsx

View workflow job for this annotation

GitHub Actions / lint-build

React Hook useCallback has a missing dependency: 'sound'. Either include it or remove the dependency array

// Inspector tag click: add tag filter + close inspector + reheat
const { selectTag } = tagCloud
Expand Down Expand Up @@ -752,7 +877,7 @@
if (selectedNode) {
pathfinding.startPathSelection(selectedNode.id)
}
}, [selectedNode, pathfinding.startPathSelection])

Check warning on line 880 in src/App.tsx

View workflow job for this annotation

GitHub Actions / lint-build

React Hook useCallback has a missing dependency: 'pathfinding'. Either include it or remove the dependency array

const { shortcuts } = useKeyboardNavigation({
nodes: nodes as any,
Expand Down Expand Up @@ -792,15 +917,15 @@

const handleBreadcrumbBack = useCallback(() => {
breadcrumbs.goBack(nodesRef.current, breadcrumbNavigate)
}, [breadcrumbs.goBack, breadcrumbNavigate])

Check warning on line 920 in src/App.tsx

View workflow job for this annotation

GitHub Actions / lint-build

React Hook useCallback has a missing dependency: 'breadcrumbs'. Either include it or remove the dependency array

const handleBreadcrumbForward = useCallback(() => {
breadcrumbs.goForward(nodesRef.current, breadcrumbNavigate)
}, [breadcrumbs.goForward, breadcrumbNavigate])

Check warning on line 924 in src/App.tsx

View workflow job for this annotation

GitHub Actions / lint-build

React Hook useCallback has a missing dependency: 'breadcrumbs'. Either include it or remove the dependency array

const handleBreadcrumbJumpTo = useCallback((index: number) => {
breadcrumbs.jumpTo(index, nodesRef.current, breadcrumbNavigate)
}, [breadcrumbs.jumpTo, breadcrumbNavigate])

Check warning on line 928 in src/App.tsx

View workflow job for this annotation

GitHub Actions / lint-build

React Hook useCallback has a missing dependency: 'breadcrumbs'. Either include it or remove the dependency array

// Breadcrumb keyboard shortcuts: Cmd+[ back, Cmd+] forward
useEffect(() => {
Expand Down Expand Up @@ -873,6 +998,8 @@
<StatsBar
stats={data?.stats}
isLoading={isLoading}
inViewNodeCount={nodes.length}
inViewEdgeCount={filteredEdges.length}
clientVisibleCount={tagVisibleNodeCount}
hasClientFilter={tagCloud.hasActiveFilter}
/>
Expand Down Expand Up @@ -1139,6 +1266,8 @@
relationshipVisibility={relationshipVisibility}
typeColors={data?.meta?.type_colors}
expansionAnchors={graph.expansionAnchors}
newNodeIds={graph.newNodeIds}
frontierCount={frontierCount}
onReheatReady={setReheatFn}
onResetViewReady={setResetViewFn}
onNavigateForBookmarks={(fn) => { navigateForBookmarksRef.current = fn }}
Expand Down Expand Up @@ -1335,9 +1464,26 @@
role="status"
aria-live="polite"
aria-atomic="true"
className="fixed bottom-5 right-5 z-[95] rounded-lg border border-hairline bg-surface-1 px-3 py-2 text-sm text-ink shadow-xl"
className="fixed bottom-5 right-5 z-[95] flex items-center gap-3 rounded-lg border border-hairline bg-surface-1 px-3 py-2 text-sm text-ink shadow-xl"
>
{statusMessage}
<span>{statusMessage.text}</span>
{statusMessage.action && (
<button
type="button"
onClick={() => {
// Cancel the auto-dismiss so it can't clear a LATER toast.
if (statusTimeoutRef.current !== null) {
window.clearTimeout(statusTimeoutRef.current)
statusTimeoutRef.current = null
}
statusMessage.action!.onClick()
setStatusMessage(null)
}}
className="px-2 py-0.5 rounded bg-white/10 hover:bg-white/20 text-accent text-xs font-medium transition-colors"
>
Comment on lines +1471 to +1483

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 0681810 — explicit type="button" and the auto-dismiss timer is cancelled on click so a stale timer can't clear a later toast.

{statusMessage.action.label}
</button>
)}
</div>
)}
</div>
Expand Down
67 changes: 67 additions & 0 deletions src/components/GraphCanvas.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ const EDGE_BOW = 0.12;
import {
SelectionHighlight,
PinchPreSelectHighlight,
ExpansionFrontierRing,
} from "./SelectionHighlight";
import { getEdgeStyle } from "../lib/edgeStyles";
import { TRACE_START, TRACE_END, TRACE_PATH } from "../lib/palette";
Expand Down Expand Up @@ -135,6 +136,12 @@ interface GraphCanvasProps {
typeColors?: Record<string, string>;
// Expansion: seed newly-merged nodes next to the node the user expanded from.
expansionAnchors?: Map<string, string>;
// Ids merged by the most recent expansion — drives the arrival animation
// (scale-up + emissive pulse for ~1.5s so the user SEES the graph grow).
newNodeIds?: Set<string>;
// Unloaded-neighbor count for the selected node (the expansion frontier).
// > 0 renders a dashed "+N more" ring: this node has more world to pull in.
frontierCount?: number;
onReheatReady?: (reheat: () => void) => void;
onResetViewReady?: (resetView: () => void) => void;
// Expose an imperative camera-navigation handle to the parent (used by the
Expand Down Expand Up @@ -180,6 +187,8 @@ export function GraphCanvas({
relationshipVisibility = DEFAULT_RELATIONSHIP_VISIBILITY,
typeColors = {},
expansionAnchors,
newNodeIds,
frontierCount = 0,
onReheatReady,
onResetViewReady,
onNavigateForBookmarks,
Expand Down Expand Up @@ -315,6 +324,8 @@ export function GraphCanvas({
relationshipVisibility={relationshipVisibility}
typeColors={typeColors}
expansionAnchors={expansionAnchors}
newNodeIds={newNodeIds}
frontierCount={frontierCount}
onReheatReady={onReheatReady}
onResetViewReady={onResetViewReady}
onCameraStateChange={setCameraState}
Expand Down Expand Up @@ -401,6 +412,8 @@ function Scene({
relationshipVisibility = DEFAULT_RELATIONSHIP_VISIBILITY,
typeColors = {},
expansionAnchors,
newNodeIds,
frontierCount = 0,
onReheatReady,
onResetViewReady,
onCameraStateChange,
Expand Down Expand Up @@ -1415,6 +1428,7 @@ function Scene({
onNodeHover={onNodeHover}
nodeSizeScale={displayConfig.nodeSizeScale}
focusStates={focusStates}
newNodeIds={newNodeIds}
pathNodeIds={pathNodeIds}
pathSourceId={pathSourceId}
pathTargetId={pathTargetId}
Expand All @@ -1439,6 +1453,20 @@ function Scene({
/>
)}

{/* Expansion frontier — dashed "+N more" ring when the selected node
still has unloaded neighbors (sits outside the selection ring). */}
{selectedLayoutNode && frontierCount > 0 && (
<ExpansionFrontierRing
node={selectedLayoutNode}
count={frontierCount}
radius={
selectedLayoutNode.radius * displayConfig.nodeSizeScale * 2.4
}
animatedPositions={animPositions}
nodeIdToIdx={nodeIdToIdx}
/>
)}

{/* Pinch pre-select highlight - tightening ring for "pick the berry" selection */}
{gestureControlEnabled && (
<PinchPreSelectHighlight
Expand Down Expand Up @@ -1830,6 +1858,7 @@ interface InstancedNodesProps {
onNodeHover: (node: GraphNode | null) => void;
nodeSizeScale?: number;
focusStates: Map<string, NodeFocusState>;
newNodeIds?: Set<string>;
pathNodeIds?: Set<string>;
pathSourceId?: string | null;
pathTargetId?: string | null;
Expand All @@ -1852,6 +1881,7 @@ function InstancedNodes({
onNodeHover,
nodeSizeScale = 1.0,
focusStates,
newNodeIds,
pathNodeIds,
pathSourceId,
pathTargetId,
Expand Down Expand Up @@ -1958,6 +1988,24 @@ function InstancedNodes({
hasTagFilterRef.current = hasTagFilter;
tagFilteredNodeIdsRef.current = tagFilteredNodeIds;

// Arrival animation: when an expansion merges nodes, stamp each new id with
// its arrival time. For ARRIVAL_MS the node scales up from ~0.2x with an
// emissive boost that catches the bloom pass — embers cooling into place —
// so the user unmistakably sees WHERE the graph just grew.
const ARRIVAL_MS = 1500;
const arrivalsRef = useRef<Map<string, number>>(new Map());
useEffect(() => {
const now = performance.now();
// Sweep expired entries first: useFrame only deletes an entry when its
// node is still rendered, so an Undo that removes nodes mid-animation
// would otherwise leave their ids in the map forever.
arrivalsRef.current.forEach((startedAt, id) => {
if (now - startedAt > ARRIVAL_MS) arrivalsRef.current.delete(id);
});
if (!newNodeIds || newNodeIds.size === 0) return;
newNodeIds.forEach((id) => arrivalsRef.current.set(id, now));
}, [newNodeIds]);
Comment thread
jack-arturo marked this conversation as resolved.
Resolved

// Shared geometry and material - created once
const geometry = useMemo(
() => new THREE.SphereGeometry(1, SPHERE_SEGMENTS, SPHERE_SEGMENTS),
Expand Down Expand Up @@ -2150,6 +2198,20 @@ function InstancedNodes({
1 + Math.sin(breathingTime + nodePhase) * breathingAmplitude;
finalScale *= breathing;

// Arrival: scale up from 0.2x and glow while the ember cools (≤1.5s).
let arrivalGlow = 1;
const arrivedAt = arrivalsRef.current.get(node.id);
if (arrivedAt !== undefined) {
const at = (performance.now() - arrivedAt) / ARRIVAL_MS;
if (at >= 1) {
arrivalsRef.current.delete(node.id);
} else {
const ease = 1 - Math.pow(1 - at, 3);
finalScale *= 0.2 + 0.8 * ease;
arrivalGlow = 1 + 2.5 * (1 - at);
}
}

// Keep off-focus search matches readable as markers (not specks) in detail view.
if (isOffFocusMatch) {
finalScale = Math.max(finalScale, newScale * 1.1);
Expand Down Expand Up @@ -2233,6 +2295,11 @@ function InstancedNodes({
if (isOffFocusMatch) {
tempColor.lerp(accentColor, 0.4);
}
// Arrival glow rides on top of everything — a just-merged node must read
// as new even under selection-focus dimming.
if (arrivalGlow > 1) {
tempColor.multiplyScalar(arrivalGlow);
}
mesh.setColorAt(i, tempColor);
});

Expand Down
Loading
Loading