aboutsummaryrefslogtreecommitdiff
path: root/packages/ui/memory-graph/hooks/use-graph-data.ts
blob: 6fbcd8b033f46edc54e2688ce67446ce81630d9c (plain) (blame)
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
"use client";

import {
	calculateSemanticSimilarity,
	getConnectionVisualProps,
	getMagicalConnectionColor,
} from "@repo/lib/similarity";
import { useMemo } from "react";
import { colors, LAYOUT_CONSTANTS } from "../constants";
import type {
	DocumentsResponse,
	DocumentWithMemories,
	GraphEdge,
	GraphNode,
	MemoryEntry,
	MemoryRelation,
} from "../types";

export function useGraphData(
	data: DocumentsResponse | null,
	selectedSpace: string,
	nodePositions: Map<string, { x: number; y: number }>,
	draggingNodeId: string | null,
) {
	return useMemo(() => {
		if (!data?.documents) return { nodes: [], edges: [] };

		const allNodes: GraphNode[] = [];
		const allEdges: GraphEdge[] = [];

		// Filter documents that have memories in selected space
		const filteredDocuments = data.documents.map((doc) => ({
			...doc,
			memoryEntries:
				selectedSpace === "all"
					? doc.memoryEntries
					: doc.memoryEntries.filter(
							(memory) =>
								(memory.spaceContainerTag ?? memory.spaceId ?? "default") ===
								selectedSpace,
						),
		}));

		// Group documents by space for better clustering
		const documentsBySpace = new Map<string, typeof filteredDocuments>();
		filteredDocuments.forEach((doc) => {
			const docSpace =
				doc.memoryEntries[0]?.spaceContainerTag ??
				doc.memoryEntries[0]?.spaceId ??
				"default";
			if (!documentsBySpace.has(docSpace)) {
				documentsBySpace.set(docSpace, []);
			}
			const spaceDocsArr = documentsBySpace.get(docSpace);
			if (spaceDocsArr) {
				spaceDocsArr.push(doc);
			}
		});

		// Enhanced Layout with Space Separation
		const { centerX, centerY, clusterRadius, spaceSpacing, documentSpacing } =
			LAYOUT_CONSTANTS;

		/* 1. Build DOCUMENT nodes with space-aware clustering */
		const documentNodes: GraphNode[] = [];
		let spaceIndex = 0;

		documentsBySpace.forEach((spaceDocs) => {
			const spaceAngle = (spaceIndex / documentsBySpace.size) * Math.PI * 2;
			const spaceOffsetX = Math.cos(spaceAngle) * spaceSpacing;
			const spaceOffsetY = Math.sin(spaceAngle) * spaceSpacing;
			const spaceCenterX = centerX + spaceOffsetX;
			const spaceCenterY = centerY + spaceOffsetY;

			spaceDocs.forEach((doc, docIndex) => {
				// Create proper circular layout with concentric rings
				const docsPerRing = 6; // Start with 6 docs in inner ring
				let currentRing = 0;
				let docsInCurrentRing = docsPerRing;
				let totalDocsInPreviousRings = 0;

				// Find which ring this document belongs to
				while (totalDocsInPreviousRings + docsInCurrentRing <= docIndex) {
					totalDocsInPreviousRings += docsInCurrentRing;
					currentRing++;
					docsInCurrentRing = docsPerRing + currentRing * 4; // Each ring has more docs
				}

				// Position within the ring
				const positionInRing = docIndex - totalDocsInPreviousRings;
				const angleInRing = (positionInRing / docsInCurrentRing) * Math.PI * 2;

				// Radius increases significantly with each ring
				const baseRadius = documentSpacing * 0.8;
				const radius =
					currentRing === 0
						? baseRadius
						: baseRadius + currentRing * documentSpacing * 1.2;

				const defaultX = spaceCenterX + Math.cos(angleInRing) * radius;
				const defaultY = spaceCenterY + Math.sin(angleInRing) * radius;

				const customPos = nodePositions.get(doc.id);

				documentNodes.push({
					id: doc.id,
					type: "document",
					x: customPos?.x ?? defaultX,
					y: customPos?.y ?? defaultY,
					data: doc,
					size: 58,
					color: colors.document.primary,
					isHovered: false,
					isDragging: draggingNodeId === doc.id,
				} satisfies GraphNode);
			});

			spaceIndex++;
		});

		/* 2. Gentle document collision avoidance with dampening */
		const minDocDist = LAYOUT_CONSTANTS.minDocDist;

		// Reduced iterations and gentler repulsion for smoother movement
		for (let iter = 0; iter < 2; iter++) {
			documentNodes.forEach((nodeA) => {
				documentNodes.forEach((nodeB) => {
					if (nodeA.id >= nodeB.id) return;

					// Only repel documents in the same space
					const spaceA =
						(nodeA.data as DocumentWithMemories).memoryEntries[0]
							?.spaceContainerTag ??
						(nodeA.data as DocumentWithMemories).memoryEntries[0]?.spaceId ??
						"default";
					const spaceB =
						(nodeB.data as DocumentWithMemories).memoryEntries[0]
							?.spaceContainerTag ??
						(nodeB.data as DocumentWithMemories).memoryEntries[0]?.spaceId ??
						"default";

					if (spaceA !== spaceB) return;

					const dx = nodeB.x - nodeA.x;
					const dy = nodeB.y - nodeA.y;
					const dist = Math.sqrt(dx * dx + dy * dy) || 1;

					if (dist < minDocDist) {
						// Much gentler push with dampening
						const push = (minDocDist - dist) / 8;
						const dampening = Math.max(0.1, Math.min(1, dist / minDocDist));
						const smoothPush = push * dampening * 0.5;

						const nx = dx / dist;
						const ny = dy / dist;
						nodeA.x -= nx * smoothPush;
						nodeA.y -= ny * smoothPush;
						nodeB.x += nx * smoothPush;
						nodeB.y += ny * smoothPush;
					}
				});
			});
		}

		allNodes.push(...documentNodes);

		/* 3. Add memories around documents WITH doc-memory connections */
		documentNodes.forEach((docNode) => {
			const memoryNodeMap = new Map<string, GraphNode>();
			const doc = docNode.data as DocumentWithMemories;

			doc.memoryEntries.forEach((memory, memIndex) => {
				const memoryId = `${memory.id}`;
				const customMemPos = nodePositions.get(memoryId);

				const clusterAngle =
					(memIndex / doc.memoryEntries.length) * Math.PI * 2;
				const variation = Math.sin(memIndex * 2.5) * 0.3 + 0.7;
				const distance = clusterRadius * variation;

				const seed =
					memIndex * 12345 + Number.parseInt(docNode.id.slice(0, 6), 36);
				const offsetX = Math.sin(seed) * 0.5 * 40;
				const offsetY = Math.cos(seed) * 0.5 * 40;

				const defaultMemX =
					docNode.x + Math.cos(clusterAngle) * distance + offsetX;
				const defaultMemY =
					docNode.y + Math.sin(clusterAngle) * distance + offsetY;

				if (!memoryNodeMap.has(memoryId)) {
					const memoryNode: GraphNode = {
						id: memoryId,
						type: "memory",
						x: customMemPos?.x ?? defaultMemX,
						y: customMemPos?.y ?? defaultMemY,
						data: memory,
						size: Math.max(
							32,
							Math.min(48, (memory.memory?.length || 50) * 0.5),
						),
						color: colors.memory.primary,
						isHovered: false,
						isDragging: draggingNodeId === memoryId,
					};
					memoryNodeMap.set(memoryId, memoryNode);
					allNodes.push(memoryNode);
				}

				// Create doc-memory edge with similarity
				allEdges.push({
					id: `edge-${docNode.id}-${memory.id}`,
					source: docNode.id,
					target: memoryId,
					similarity: 1,
					visualProps: getConnectionVisualProps(1),
					color: colors.connection.memory,
					edgeType: "doc-memory",
				});
			});
		});

		// Build mapping of memoryId -> nodeId for version chains
		const memNodeIdMap = new Map<string, string>();
		allNodes.forEach((n) => {
			if (n.type === "memory") {
				memNodeIdMap.set((n.data as MemoryEntry).id, n.id);
			}
		});

		// Add version-chain edges (old -> new)
		data.documents.forEach((doc) => {
			doc.memoryEntries.forEach((mem: MemoryEntry) => {
				// Support both new object structure and legacy array/single parent fields
				let parentRelations: Record<string, MemoryRelation> = {};

				if (
					mem.memoryRelations &&
					typeof mem.memoryRelations === "object" &&
					Object.keys(mem.memoryRelations).length > 0
				) {
					parentRelations = mem.memoryRelations;
				} else if (mem.parentMemoryId) {
					parentRelations = {
						[mem.parentMemoryId]: "updates" as MemoryRelation,
					};
				}
				Object.entries(parentRelations).forEach(([pid, relationType]) => {
					const fromId = memNodeIdMap.get(pid);
					const toId = memNodeIdMap.get(mem.id);
					if (fromId && toId) {
						allEdges.push({
							id: `version-${fromId}-${toId}`,
							source: fromId,
							target: toId,
							similarity: 1,
							visualProps: {
								opacity: 0.8,
								thickness: 1,
								glow: 0,
								pulseDuration: 3000,
							},
							// choose color based on relation type
							color: colors.relations[relationType] ?? colors.relations.updates,
							edgeType: "version",
							relationType: relationType as MemoryRelation,
						});
					}
				});
			});
		});

		// Document-to-document similarity edges
		for (let i = 0; i < filteredDocuments.length; i++) {
			const docI = filteredDocuments[i];
			if (!docI) continue;

			for (let j = i + 1; j < filteredDocuments.length; j++) {
				const docJ = filteredDocuments[j];
				if (!docJ) continue;

				const sim = calculateSemanticSimilarity(
					docI.summaryEmbedding ? Array.from(docI.summaryEmbedding) : null,
					docJ.summaryEmbedding ? Array.from(docJ.summaryEmbedding) : null,
				);
				if (sim > 0.725) {
					allEdges.push({
						id: `doc-doc-${docI.id}-${docJ.id}`,
						source: docI.id,
						target: docJ.id,
						similarity: sim,
						visualProps: getConnectionVisualProps(sim),
						color: getMagicalConnectionColor(sim, 200),
						edgeType: "doc-doc",
					});
				}
			}
		}

		return { nodes: allNodes, edges: allEdges };
	}, [data, selectedSpace, nodePositions, draggingNodeId]);
}