From 3e0e65812f7269c6bab6a4cc41e9e2c9b40281dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emil=20W=C3=A5reus?= Date: Sat, 5 Sep 2026 17:09:26 +0200 Subject: [PATCH] Improve insight graph layout, hover labels, and drag reliability --- .gitignore | 2 + .prettierignore | 1 + README.md | 18 + components/brain/insight-browser.tsx | 1074 ++------------------- components/brain/insight-graph.module.css | 436 +++++++++ components/brain/insight-graph.tsx | 624 ++++++++++++ eslint.config.mjs | 2 + package.json | 3 +- playwright.config.ts | 27 + test-results/.last-run.json | 4 - tests/e2e/insight-graph.spec.ts | 327 +++++++ 11 files changed, 1501 insertions(+), 1017 deletions(-) create mode 100644 components/brain/insight-graph.module.css create mode 100644 components/brain/insight-graph.tsx create mode 100644 playwright.config.ts delete mode 100644 test-results/.last-run.json create mode 100644 tests/e2e/insight-graph.spec.ts diff --git a/.gitignore b/.gitignore index 9bcecf0..e2e67fa 100644 --- a/.gitignore +++ b/.gitignore @@ -12,6 +12,8 @@ # testing /coverage +/test-results/ +/playwright-report/ # next.js /.next/ diff --git a/.prettierignore b/.prettierignore index 932bd0c..6c09308 100644 --- a/.prettierignore +++ b/.prettierignore @@ -30,6 +30,7 @@ build # Testing coverage test-results +playwright-report # Vercel .vercel diff --git a/README.md b/README.md index 24ea236..95ae4be 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,24 @@ You can start editing the page by modifying `app/page.tsx`. The page auto-update This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel. +## Graph end-to-end tests + +Install the test browsers once, then run the suite: + +```bash +pnpm exec playwright install chromium firefox webkit +pnpm test:e2e +``` + +The suite builds the site and starts a production server on port 49300. It does +not start or use the development server. It checks Chromium, Firefox, and WebKit +with desktop and iPhone viewports. Tests cover rapid drag release, pointer cancellation, +capture loss, multiple pointers, graph links, zoom, note navigation, filters, +and motion controls. Any uncaught browser error fails the test. + +Run one browser with `pnpm test:e2e --project=firefox`. After a failure, run +`pnpm exec playwright show-report` to inspect the screenshot and trace. + ## Learn More To learn more about Next.js, take a look at the following resources: diff --git a/components/brain/insight-browser.tsx b/components/brain/insight-browser.tsx index 64a983d..c6eb3b3 100644 --- a/components/brain/insight-browser.tsx +++ b/components/brain/insight-browser.tsx @@ -1,10 +1,11 @@ 'use client'; import Link from 'next/link'; -import { ExternalLink, FileText, Folder, FolderOpen, List, Network, Search, X } from 'lucide-react'; +import { FileText, Folder, FolderOpen, List, Network, Search, X } from 'lucide-react'; import { useMemo, useState } from 'react'; import type { BrainGraphEdge, BrainNoteType, PublishedBrainNote } from '@/lib/brain/types'; import { cn } from '@/lib/utils'; +import { InsightGraph } from './insight-graph'; interface InsightBrowserProps { notes: PublishedBrainNote[]; @@ -14,39 +15,6 @@ interface InsightBrowserProps { } type ViewMode = 'folders' | 'list' | 'graph'; -type GraphNodeKind = BrainNoteType | 'folder'; - -interface GraphNode { - id: string; - type: GraphNodeKind; - slug: string; - title: string; - excerpt: string; - tags: readonly string[]; - status: string; - filePath: string; - clusterKey: string; - clusterLabel: string; - subtopic: string; - href?: string; - virtual: boolean; - x: number; - y: number; - radius: number; -} - -interface GraphCluster { - key: string; - label: string; - centerX: number; - centerY: number; - haloX: number; - haloY: number; - haloRadius: number; - notes: number; - subtopicAnchors: ReadonlyMap; -} - interface FolderTreeNode { name: string; path: string; @@ -55,16 +23,6 @@ interface FolderTreeNode { totalNotes: number; } -const graphWidth = 1040; -const graphHeight = 660; -const graphCenterX = graphWidth / 2; -const graphCenterY = graphHeight / 2; -const graphMargin = 110; - -function getNodeId(slug: string) { - return `graph:${slug}`; -} - function noteMatchesQuery(note: PublishedBrainNote, normalizedQuery: string) { if (!normalizedQuery) { return true; @@ -83,79 +41,6 @@ function getDisplayPath(note: Pick) { return note.filePath.replace(/^brain\//, ''); } -function titleizeSlug(slug: string) { - const acronymByPart = new Map([ - ['ai', 'AI'], - ['api', 'API'], - ['apis', 'APIs'], - ['llm', 'LLM'], - ['llms', 'LLMs'], - ['pr', 'PR'], - ['prs', 'PRs'], - ['sdk', 'SDK'], - ['sdks', 'SDKs'], - ['stt', 'STT'], - ['tts', 'TTS'], - ['vad', 'VAD'], - ]); - - return slug - .split('-') - .map((part) => acronymByPart.get(part) ?? part.charAt(0).toUpperCase() + part.slice(1)) - .join(' '); -} - -function truncateLabel(label: string, maxLength: number) { - if (label.length <= maxLength) { - return label; - } - - return `${label.slice(0, maxLength - 1)}…`; -} - -function getGraphClusterKey(note: Pick) { - const segments = note.filePath.replace(/^brain\//, '').split('/'); - - if (segments[0] === 'insights' && segments[1]) { - return segments[1]; - } - - if (segments[0] === 'post-seeds' && segments[1]) { - return segments[1]; - } - - return segments[0] ?? note.type; -} - -function getGraphSubtopic(note: Pick) { - const segments = note.filePath.replace(/^brain\//, '').split('/'); - - if (segments[0] === 'insights' && segments[2]) { - return segments[2]; - } - - if (segments[0] === 'post-seeds') { - return 'post-seeds'; - } - - return note.type; -} - -function getTopicNodeSlug(clusterKey: string, subtopic: string) { - return `folder:${clusterKey}:${subtopic}`; -} - -function hashToUnit(value: string) { - let hash = 2166136261; - - for (let index = 0; index < value.length; index += 1) { - hash ^= value.charCodeAt(index); - hash = Math.imul(hash, 16777619); - } - - return (hash >>> 0) / 4294967295; -} - function createFolderNode(name: string, folderPath: string): FolderTreeNode { return { name, @@ -237,574 +122,6 @@ function getFolderSubtreeNotes(folder: FolderTreeNode): PublishedBrainNote[] { }, folder.notes); } -function getClusterCenter(index: number, count: number) { - if (count === 1) { - return { x: graphCenterX, y: graphCenterY }; - } - - if (count === 2) { - return { - x: graphCenterX + (index === 0 ? -290 : 290), - y: graphCenterY, - }; - } - - const angle = -Math.PI / 2 + (index / count) * Math.PI * 2; - - return { - x: graphCenterX + Math.cos(angle) * 305, - y: graphCenterY + Math.sin(angle) * 210, - }; -} - -function buildClusterLayouts(notes: PublishedBrainNote[]) { - const clusterKeys = Array.from(new Set(notes.map(getGraphClusterKey))).sort(); - const subtopicsByCluster = new Map>(); - - notes.forEach((note) => { - const clusterKey = getGraphClusterKey(note); - const subtopics = subtopicsByCluster.get(clusterKey) ?? new Set(); - subtopics.add(getGraphSubtopic(note)); - subtopicsByCluster.set(clusterKey, subtopics); - }); - - return new Map( - clusterKeys.map((clusterKey, index) => { - const center = getClusterCenter(index, clusterKeys.length); - const subtopics = Array.from(subtopicsByCluster.get(clusterKey) ?? []).sort(); - const petalSubtopics = subtopics.filter((subtopic) => subtopic !== 'post-seeds'); - const petalRadius = clusterKeys.length <= 2 ? 150 : 118; - const subtopicAnchors = new Map(); - - subtopicAnchors.set('post-seeds', center); - petalSubtopics.forEach((subtopic, subtopicIndex) => { - const angle = - -Math.PI / 2 + (subtopicIndex / Math.max(petalSubtopics.length, 1)) * Math.PI * 2; - subtopicAnchors.set(subtopic, { - x: center.x + Math.cos(angle) * petalRadius, - y: center.y + Math.sin(angle) * petalRadius, - }); - }); - - return [ - clusterKey, - { - key: clusterKey, - label: titleizeSlug(clusterKey), - centerX: center.x, - centerY: center.y, - haloX: center.x, - haloY: center.y, - haloRadius: 120, - notes: 0, - subtopicAnchors, - } satisfies GraphCluster, - ]; - }) - ); -} - -function getNodeRadius(node: Pick, degree: number) { - if (node.type === 'post-seed') { - return 31; - } - - if (node.type === 'folder') { - return 23; - } - - return 14 + Math.min(degree, 6) * 1.6; -} - -function dedupeGraphEdges(notes: PublishedBrainNote[], graphEdges: BrainGraphEdge[]) { - const visibleSlugs = new Set(notes.map((note) => note.slug)); - const edgesByPair = new Map(); - - graphEdges.forEach((edge) => { - if (!visibleSlugs.has(edge.sourceSlug) || !visibleSlugs.has(edge.targetSlug)) { - return; - } - - if (edge.sourceSlug === edge.targetSlug) { - return; - } - - const [firstSlug, secondSlug] = [edge.sourceSlug, edge.targetSlug].sort(); - const pairKey = `${firstSlug}<->${secondSlug}`; - const existingEdge = edgesByPair.get(pairKey); - - if (existingEdge) { - const relations = new Set(existingEdge.relation.split(', ').concat(edge.relation)); - edgesByPair.set(pairKey, { - ...existingEdge, - relation: Array.from(relations).sort().join(', '), - }); - return; - } - - edgesByPair.set(pairKey, { - ...edge, - id: pairKey, - sourceSlug: firstSlug, - targetSlug: secondSlug, - }); - }); - - return Array.from(edgesByPair.values()); -} - -function shouldRerouteSeedEdge(edge: BrainGraphEdge, nodeBySlug: ReadonlyMap) { - const source = nodeBySlug.get(edge.sourceSlug); - const target = nodeBySlug.get(edge.targetSlug); - - if (!source || !target) { - return false; - } - - if (source.clusterKey !== target.clusterKey) { - return false; - } - - return source.type === 'post-seed' || target.type === 'post-seed'; -} - -function getNodeAnchor(node: GraphNode, clusterByKey: ReadonlyMap) { - const cluster = clusterByKey.get(node.clusterKey); - - if (!cluster) { - throw new Error(`Missing graph cluster for ${node.clusterKey}`); - } - - return ( - cluster.subtopicAnchors.get(node.subtopic) ?? { - x: cluster.centerX, - y: cluster.centerY, - } - ); -} - -function simulateGraphLayout( - nodes: GraphNode[], - edges: BrainGraphEdge[], - clusterByKey: ReadonlyMap -) { - const nodeBySlug = new Map(nodes.map((node) => [node.slug, node])); - const velocities = new Map(nodes.map((node) => [node.slug, { x: 0, y: 0 }])); - const linkedNodePairs = edges.map((edge) => { - const source = nodeBySlug.get(edge.sourceSlug); - const target = nodeBySlug.get(edge.targetSlug); - - if (!source || !target) { - throw new Error(`Missing graph node for edge ${edge.id}`); - } - - return { source, target }; - }); - - for (let iteration = 0; iteration < 340; iteration += 1) { - const alpha = 1 - iteration / 340; - const attractionStrength = 0.025 * alpha; - const linkStrength = 0.018 * alpha; - const chargeStrength = 1700 * alpha; - - nodes.forEach((node) => { - const velocity = velocities.get(node.slug); - - if (!velocity) { - throw new Error(`Missing graph velocity for ${node.slug}`); - } - - const anchor = getNodeAnchor(node, clusterByKey); - const cluster = clusterByKey.get(node.clusterKey); - const targetX = node.type === 'post-seed' ? (cluster?.centerX ?? anchor.x) : anchor.x; - const targetY = node.type === 'post-seed' ? (cluster?.centerY ?? anchor.y) : anchor.y; - const strength = node.type === 'post-seed' ? attractionStrength * 2.8 : attractionStrength; - - velocity.x += (targetX - node.x) * strength; - velocity.y += (targetY - node.y) * strength; - }); - - linkedNodePairs.forEach(({ source, target }) => { - const sourceVelocity = velocities.get(source.slug); - const targetVelocity = velocities.get(target.slug); - - if (!sourceVelocity || !targetVelocity) { - throw new Error(`Missing graph velocity for linked nodes ${source.slug} -> ${target.slug}`); - } - - const dx = target.x - source.x; - const dy = target.y - source.y; - const distance = Math.max(Math.sqrt(dx * dx + dy * dy), 0.001); - const desiredDistance = - source.clusterKey === target.clusterKey - ? source.type === 'post-seed' || target.type === 'post-seed' - ? 112 - : 86 - : 180; - const force = (distance - desiredDistance) * linkStrength; - const forceX = (dx / distance) * force; - const forceY = (dy / distance) * force; - - sourceVelocity.x += forceX; - sourceVelocity.y += forceY; - targetVelocity.x -= forceX; - targetVelocity.y -= forceY; - }); - - for (let firstIndex = 0; firstIndex < nodes.length; firstIndex += 1) { - for (let secondIndex = firstIndex + 1; secondIndex < nodes.length; secondIndex += 1) { - const firstNode = nodes[firstIndex]; - const secondNode = nodes[secondIndex]; - - if (!firstNode || !secondNode) { - throw new Error('Missing graph node during collision simulation'); - } - - const firstVelocity = velocities.get(firstNode.slug); - const secondVelocity = velocities.get(secondNode.slug); - - if (!firstVelocity || !secondVelocity) { - throw new Error(`Missing graph velocity for ${firstNode.slug} or ${secondNode.slug}`); - } - - const dx = secondNode.x - firstNode.x; - const dy = secondNode.y - firstNode.y; - const distance = Math.max(Math.sqrt(dx * dx + dy * dy), 0.001); - const collisionDistance = firstNode.radius + secondNode.radius + 24; - const clusterMultiplier = firstNode.clusterKey === secondNode.clusterKey ? 1 : 1.45; - const repulsion = (chargeStrength * clusterMultiplier) / (distance * distance); - const forceX = (dx / distance) * repulsion; - const forceY = (dy / distance) * repulsion; - - firstVelocity.x -= forceX; - firstVelocity.y -= forceY; - secondVelocity.x += forceX; - secondVelocity.y += forceY; - - if (distance < collisionDistance) { - const overlap = (collisionDistance - distance) * 0.11 * alpha; - const overlapX = (dx / distance) * overlap; - const overlapY = (dy / distance) * overlap; - - firstVelocity.x -= overlapX; - firstVelocity.y -= overlapY; - secondVelocity.x += overlapX; - secondVelocity.y += overlapY; - } - } - } - - nodes.forEach((node) => { - const velocity = velocities.get(node.slug); - - if (!velocity) { - throw new Error(`Missing graph velocity for ${node.slug}`); - } - - velocity.x *= 0.72; - velocity.y *= 0.72; - node.x += velocity.x; - node.y += velocity.y; - }); - } -} - -function fitGraphToViewport(nodes: GraphNode[]) { - const minX = Math.min(...nodes.map((node) => node.x - node.radius)); - const maxX = Math.max(...nodes.map((node) => node.x + node.radius)); - const minY = Math.min(...nodes.map((node) => node.y - node.radius)); - const maxY = Math.max(...nodes.map((node) => node.y + node.radius)); - const width = Math.max(maxX - minX, 1); - const height = Math.max(maxY - minY, 1); - const scale = Math.min( - 1, - (graphWidth - graphMargin * 2) / width, - (graphHeight - graphMargin * 2) / height - ); - const offsetX = graphMargin + (graphWidth - graphMargin * 2 - width * scale) / 2 - minX * scale; - const offsetY = graphMargin + (graphHeight - graphMargin * 2 - height * scale) / 2 - minY * scale; - - nodes.forEach((node) => { - node.x = node.x * scale + offsetX; - node.y = node.y * scale + offsetY; - }); -} - -function finalizeClusterHalos(nodes: GraphNode[], clusterByKey: Map) { - clusterByKey.forEach((cluster) => { - const clusterNodes = nodes.filter((node) => node.clusterKey === cluster.key); - - if (clusterNodes.length === 0) { - return; - } - - const haloX = - clusterNodes.reduce((total, node) => total + node.x, 0) / Math.max(clusterNodes.length, 1); - const haloY = - clusterNodes.reduce((total, node) => total + node.y, 0) / Math.max(clusterNodes.length, 1); - const haloRadius = Math.max( - 82, - ...clusterNodes.map((node) => { - const dx = node.x - haloX; - const dy = node.y - haloY; - - return Math.sqrt(dx * dx + dy * dy) + node.radius + 38; - }) - ); - - cluster.haloX = haloX; - cluster.haloY = haloY; - cluster.haloRadius = haloRadius; - cluster.notes = clusterNodes.filter((node) => !node.virtual).length; - }); -} - -function buildGraph(notes: PublishedBrainNote[], graphEdges: BrainGraphEdge[]) { - const orderedNotes = [...notes].sort((a, b) => a.title.localeCompare(b.title)); - const clusterByKey = buildClusterLayouts(orderedNotes); - const noteNodes: GraphNode[] = orderedNotes.map((note) => { - const clusterKey = getGraphClusterKey(note); - const cluster = clusterByKey.get(clusterKey); - - if (!cluster) { - throw new Error(`Missing graph cluster for ${clusterKey}`); - } - - const subtopic = getGraphSubtopic(note); - const anchor = cluster.subtopicAnchors.get(subtopic) ?? { - x: cluster.centerX, - y: cluster.centerY, - }; - const seedAngle = hashToUnit(note.slug) * Math.PI * 2; - const seedRadius = note.type === 'post-seed' ? 0 : 28 + hashToUnit(`${note.slug}:r`) * 38; - - return { - id: getNodeId(note.slug), - type: note.type, - slug: note.slug, - title: note.title, - excerpt: note.excerpt, - tags: note.tags, - status: note.status, - filePath: note.filePath, - clusterKey, - clusterLabel: cluster.label, - subtopic, - href: `/brain/${note.slug}`, - virtual: false, - x: anchor.x + Math.cos(seedAngle) * seedRadius, - y: anchor.y + Math.sin(seedAngle) * seedRadius, - radius: 18, - }; - }); - const topicNodes: GraphNode[] = Array.from(clusterByKey.values()).flatMap((cluster) => { - return Array.from(cluster.subtopicAnchors.entries()).flatMap(([subtopic, anchor]) => { - if (subtopic === 'post-seeds') { - return []; - } - - const notesInSubtopic = noteNodes.filter((node) => { - return node.clusterKey === cluster.key && node.subtopic === subtopic; - }); - - if (notesInSubtopic.length === 0) { - return []; - } - - const slug = getTopicNodeSlug(cluster.key, subtopic); - - return [ - { - id: getNodeId(slug), - type: 'folder' as const, - slug, - title: titleizeSlug(subtopic), - excerpt: `${notesInSubtopic.length} notes in ${cluster.label}.`, - tags: [], - status: 'folder', - filePath: `brain/insights/${cluster.key}/${subtopic}/`, - clusterKey: cluster.key, - clusterLabel: cluster.label, - subtopic, - href: undefined, - virtual: true, - x: anchor.x, - y: anchor.y, - radius: 23, - }, - ]; - }); - }); - const nodes = [...noteNodes, ...topicNodes]; - const nodeBySlug = new Map(nodes.map((node) => [node.slug, node])); - const actualEdges = dedupeGraphEdges(orderedNotes, graphEdges).filter((edge) => { - return !shouldRerouteSeedEdge(edge, nodeBySlug); - }); - const postSeedByCluster = new Map( - noteNodes.filter((node) => node.type === 'post-seed').map((node) => [node.clusterKey, node]) - ); - const folderEdges: BrainGraphEdge[] = topicNodes.flatMap((topicNode) => { - const postSeed = postSeedByCluster.get(topicNode.clusterKey); - const notesInSubtopic = noteNodes.filter((node) => { - return node.clusterKey === topicNode.clusterKey && node.subtopic === topicNode.subtopic; - }); - const topicEdges = notesInSubtopic.map((note) => ({ - id: `${topicNode.slug}<->${note.slug}`, - sourceSlug: topicNode.slug, - targetSlug: note.slug, - relation: 'contains', - })); - - if (!postSeed) { - return topicEdges; - } - - return [ - { - id: `${postSeed.slug}<->${topicNode.slug}`, - sourceSlug: postSeed.slug, - targetSlug: topicNode.slug, - relation: 'groups', - }, - ...topicEdges, - ]; - }); - const edges = [...actualEdges, ...folderEdges]; - const degreeBySlug = new Map(); - - edges.forEach((edge) => { - degreeBySlug.set(edge.sourceSlug, (degreeBySlug.get(edge.sourceSlug) ?? 0) + 1); - degreeBySlug.set(edge.targetSlug, (degreeBySlug.get(edge.targetSlug) ?? 0) + 1); - }); - - nodes.forEach((node) => { - node.radius = getNodeRadius(node, degreeBySlug.get(node.slug) ?? 0); - }); - - simulateGraphLayout(nodes, edges, clusterByKey); - fitGraphToViewport(nodes); - finalizeClusterHalos(nodes, clusterByKey); - - return { - nodes, - edges, - clusters: Array.from(clusterByKey.values()).sort((a, b) => a.label.localeCompare(b.label)), - nodeById: new Map(nodes.map((node) => [node.id, node])), - nodeBySlug, - }; -} - -function getEdgePath(source: GraphNode, target: GraphNode) { - const controlX = (source.x + target.x) / 2 + (source.y - target.y) * 0.08; - const controlY = (source.y + target.y) / 2 + (target.x - source.x) * 0.08; - - return `M ${source.x} ${source.y} Q ${controlX} ${controlY} ${target.x} ${target.y}`; -} - -function isNodeConnected(nodeId: string, activeNodeId: string | null, edges: BrainGraphEdge[]) { - if (!activeNodeId || nodeId === activeNodeId) { - return true; - } - - const activeSlug = activeNodeId.replace(/^graph:/, ''); - const nodeSlug = nodeId.replace(/^graph:/, ''); - - return edges.some((edge) => { - return ( - (edge.sourceSlug === activeSlug && edge.targetSlug === nodeSlug) || - (edge.targetSlug === activeSlug && edge.sourceSlug === nodeSlug) - ); - }); -} - -function getRequiredNode(nodeBySlug: ReadonlyMap, slug: string) { - const node = nodeBySlug.get(slug); - - if (!node) { - throw new Error(`Missing graph node for visible edge: ${slug}`); - } - - return node; -} - -function getRequiredCluster(clusters: ReadonlyMap, key: string) { - const cluster = clusters.get(key); - - if (!cluster) { - throw new Error(`Missing graph cluster for visible node: ${key}`); - } - - return cluster; -} - -function getNodeLabelLayout(node: GraphNode, cluster: GraphCluster) { - if (node.type === 'post-seed') { - return { - x: node.x, - y: node.y + node.radius + 17, - textAnchor: 'middle' as const, - dominantBaseline: 'hanging' as const, - }; - } - - if (node.type !== 'folder') { - return { - x: node.x, - y: node.y + node.radius + 12, - textAnchor: 'middle' as const, - dominantBaseline: 'hanging' as const, - }; - } - - const dx = node.x - cluster.haloX; - const dy = node.y - cluster.haloY; - const horizontal = Math.abs(dx) > Math.abs(dy) * 0.72; - const offset = node.radius + 10; - - if (horizontal) { - let direction = dx >= 0 ? 1 : -1; - let x = node.x + direction * offset; - - if (x < 150) { - direction = 1; - x = node.x + offset; - } - - if (x > graphWidth - 150) { - direction = -1; - x = node.x - offset; - } - - return { - x, - y: node.y, - textAnchor: direction > 0 ? ('start' as const) : ('end' as const), - dominantBaseline: 'middle' as const, - }; - } - - const direction = dy >= 0 ? 1 : -1; - - return { - x: node.x, - y: node.y + direction * offset, - textAnchor: 'middle' as const, - dominantBaseline: direction > 0 ? ('hanging' as const) : ('alphabetic' as const), - }; -} - -function getNodeLabelMaxLength(node: Pick) { - if (node.type === 'post-seed') { - return 25; - } - - if (node.type === 'folder') { - return 17; - } - - return 22; -} - function ToggleButton({ active, children, @@ -818,6 +135,7 @@ function ToggleButton({ - )} - - ); - })} - {activeEdges.length > 7 && ( -

- showing 7 / {activeEdges.length} visible links -

- )} - - ) : ( -

- No visible links in this filtered view. -

- )} - - - ) : ( - <> -

- Graph overview -

-

Clustered brain graph

-

- Notes are pulled toward their research area and subfolder, then spaced with a - deterministic force layout. Hover or select a node to inspect its local links. -

-
- {clusters.map((cluster) => ( -
-

{cluster.label}

-

- {cluster.notes} notes -

-
- ))} -
- - )} - - - ); -} - function FolderTreeItem({ node, selectedPath, @@ -1444,50 +478,62 @@ export function InsightBrowser({ notes, tags, statuses, graphEdges }: InsightBro
-
- setActiveType(null)}> - all types - - {noteTypes.map((type) => ( - setActiveType((current) => (current === type ? null : type))} - > - {type} - - ))} -
+
+ + Filter notes + {[activeType, activeStatus, activeTag].some(Boolean) && ( + + · {[activeType, activeStatus, activeTag].filter(Boolean).join(' / ')} + + )} + +
+
+ setActiveType(null)}> + all types + + {noteTypes.map((type) => ( + setActiveType((current) => (current === type ? null : type))} + > + {type} + + ))} +
-
- setActiveStatus(null)}> - all statuses - - {statuses.map((status) => ( - setActiveStatus((current) => (current === status ? null : status))} - > - {status} - - ))} -
+
+ setActiveStatus(null)}> + all statuses + + {statuses.map((status) => ( + setActiveStatus((current) => (current === status ? null : status))} + > + {status} + + ))} +
-
- setActiveTag(null)}> - all tags - - {tags.map((tag) => ( - setActiveTag((current) => (current === tag ? null : tag))} - > - {tag} - - ))} -
+
+ setActiveTag(null)}> + all tags + + {tags.map((tag) => ( + setActiveTag((current) => (current === tag ? null : tag))} + > + {tag} + + ))} +
+
+
+ )} + +
+ + +
+
+
+ + Note + + + Post idea + + + Note link + + + {notes.length} notes · {topics.length} topics + +
+
+
+ + + +
+ { + if ( + event.button !== 0 || + drag.current || + (event.target as Element).closest('[role="button"]') + ) + return; + const point = pointerPosition(event); + drag.current = { + pointerId: event.pointerId, + x: point.x, + y: point.y, + originX: camera.x, + originY: camera.y, + }; + event.currentTarget.setPointerCapture(event.pointerId); + }} + onPointerMove={(event) => { + const gesture = drag.current; + if (!gesture || gesture.pointerId !== event.pointerId) return; + const point = pointerPosition(event); + // React can process this update after release or capture loss clears the ref. + const x = gesture.originX + point.x - gesture.x; + const y = gesture.originY + point.y - gesture.y; + setCamera((current) => ({ ...current, x, y })); + }} + onPointerUp={endDrag} + onPointerCancel={endDrag} + onLostPointerCapture={endDrag} + > + + + {visibleEdges.map((edge) => { + const source = pointBySlug.get(edge.sourceSlug)!; + const target = pointBySlug.get(edge.targetSlug)!; + const active = activeSlug + ? edge.sourceSlug === activeSlug || edge.targetSlug === activeSlug + : Boolean(topic) && + (topicKey(source.note) === topic || topicKey(target.note) === topic); + return ( + + ); + })} + {clusters.map((cluster) => ( + { + setTopic(topic === cluster.key ? null : cluster.key); + setSelectedSlug(null); + }} + onKeyDown={(event) => { + if (event.key !== 'Enter' && event.key !== ' ') return; + event.preventDefault(); + setTopic(topic === cluster.key ? null : cluster.key); + setSelectedSlug(null); + }} + > + + {wrapTopicLabel(cluster.label).map((line, index) => ( + + {line} + + ))} + + + ))} + {points.map(({ note, x, y }) => { + const active = activeSlug === note.slug; + const selected = selectedSlug === note.slug; + const connected = connectedSlugs.has(note.slug); + const radius = + note.type === 'post-seed' + ? 10 + : 5 + Math.min(degree.get(note.slug) ?? 0, 8) * 0.35; + return ( + selectNote(note.slug)} + onKeyDown={(event) => { + if (event.key === 'Enter' || event.key === ' ') { + event.preventDefault(); + selectNote(note.slug); + } + }} + onMouseEnter={(event) => showNodeName(note.slug, event.currentTarget)} + onMouseLeave={() => setHoveredSlug(null)} + onFocus={(event) => showNodeName(note.slug, event.currentTarget)} + onBlur={() => setHoveredSlug(null)} + > + + + + + ); + })} + + + + {hoveredSlug && activeNote && ( + + )} +
+
+ + {activeNote + ? activeNote.title + : currentTopic + ? `Highlighted: ${currentTopic.label}. All notes remain on the map.` + : 'Drag to move. Zoom to explore. Lines connect notes across topics.'} + + {activeNote && ( + + {connectedSlugs.size} connected {connectedSlugs.size === 1 ? 'note' : 'notes'} + + )} +
+
+ + +
+
+ ); +} diff --git a/eslint.config.mjs b/eslint.config.mjs index 6f8d9a0..a07a9a5 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -13,6 +13,8 @@ const eslintConfig = defineConfig([ 'build/**', 'next-env.d.ts', '.context/**', + 'test-results/**', + 'playwright-report/**', ]), ]); diff --git a/package.json b/package.json index 604bdce..985ad64 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,8 @@ "check-links": "tsx scripts/check-about-links.ts", "optimize-images": "tsx scripts/optimize-images.ts", "extract-text": "tsx scripts/extract-post-text.ts", - "generate-audio": "tsx scripts/generate-audio.ts" + "generate-audio": "tsx scripts/generate-audio.ts", + "test:e2e": "playwright test" }, "dependencies": { "@ai-sdk/openai": "^3.0.64", diff --git a/playwright.config.ts b/playwright.config.ts new file mode 100644 index 0000000..c26ac62 --- /dev/null +++ b/playwright.config.ts @@ -0,0 +1,27 @@ +import { defineConfig, devices } from '@playwright/test'; + +export default defineConfig({ + testDir: './tests/e2e', + fullyParallel: true, + forbidOnly: Boolean(process.env.CI), + retries: 0, + workers: 2, + reporter: [['list'], ['html', { open: 'never' }]], + use: { + baseURL: 'http://127.0.0.1:49300', + trace: 'retain-on-failure', + screenshot: 'only-on-failure', + }, + projects: [ + { name: 'chromium', use: { ...devices['Desktop Chrome'] } }, + { name: 'firefox', use: { ...devices['Desktop Firefox'] } }, + { name: 'webkit', use: { ...devices['Desktop Safari'] } }, + { name: 'mobile-safari', use: { ...devices['iPhone 13'] } }, + ], + webServer: { + command: 'pnpm build && pnpm start --hostname 127.0.0.1 --port 49300', + url: 'http://127.0.0.1:49300/brain', + reuseExistingServer: false, + timeout: 180_000, + }, +}); diff --git a/test-results/.last-run.json b/test-results/.last-run.json deleted file mode 100644 index f740f7c..0000000 --- a/test-results/.last-run.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "status": "passed", - "failedTests": [] -} diff --git a/tests/e2e/insight-graph.spec.ts b/tests/e2e/insight-graph.spec.ts new file mode 100644 index 0000000..1335504 --- /dev/null +++ b/tests/e2e/insight-graph.spec.ts @@ -0,0 +1,327 @@ +import { test as base, expect, type Locator, type Page } from '@playwright/test'; +import { getAllPublishedBrainNotes, getBrainGraphEdges } from '../../lib/brain/read-vault'; + +const notes = getAllPublishedBrainNotes(); +const expectedPairs = [ + ...new Set( + getBrainGraphEdges() + .filter((edge) => edge.sourceSlug !== edge.targetSlug) + .map((edge) => [edge.sourceSlug, edge.targetSlug].sort().join('|')) + ), +].sort(); + +// Every scenario must finish without an uncaught browser error. +const test = base.extend({ + page: async ({ page }, runTest) => { + const errors: string[] = []; + page.on('pageerror', (error) => errors.push(error.message)); + await runTest(page); + expect(errors, 'Uncaught browser errors').toEqual([]); + }, +}); + +function graph(page: Page) { + return page.getByRole('group', { name: 'Connected insight graph', exact: true }); +} + +function camera(page: Page) { + return graph(page).locator(':scope > g'); +} + +async function startDrag(page: Page) { + const canvas = graph(page); + await canvas.scrollIntoViewIfNeeded(); + await canvas.evaluate((element) => { + element.addEventListener( + 'pointerdown', + (event) => { + const pointer = event as PointerEvent; + element.setAttribute('data-test-pointer-id', String(pointer.pointerId)); + }, + { once: true } + ); + }); + const bounds = (await canvas.boundingBox())!; + await page.mouse.move(bounds.x + 16, bounds.y + bounds.height / 2); + await page.mouse.down(); + await expect(canvas).toHaveAttribute('data-test-pointer-id', /^\d+$/); + return { x: bounds.x + 16, y: bounds.y + bounds.height / 2 }; +} + +async function moveAndEndInSameTask(canvas: Locator, ending: string, x: number, y: number) { + await canvas.evaluate( + (element, args) => { + const pointerId = Number(element.getAttribute('data-test-pointer-id')); + // Queue several React updates before release/cancel clears the drag ref. + for (let step = 1; step <= 8; step++) { + element.dispatchEvent( + new PointerEvent('pointermove', { + bubbles: true, + pointerId, + pointerType: 'mouse', + buttons: 1, + clientX: args.x + step * 7, + clientY: args.y + step * 3, + }) + ); + } + element.dispatchEvent( + new PointerEvent(args.ending, { + bubbles: true, + pointerId, + pointerType: 'mouse', + buttons: 0, + }) + ); + }, + { ending, x, y } + ); +} + +test.beforeEach(async ({ page }) => { + await page.goto('/brain'); + await page.getByRole('button', { name: 'Graph', exact: true }).click(); + await expect(graph(page)).toBeVisible(); +}); + +for (const ending of ['pointerup', 'pointercancel', 'lostpointercapture']) { + test(`rapid drag updates survive ${ending}`, async ({ page }) => { + const start = await startDrag(page); + const initial = await camera(page).getAttribute('transform'); + await moveAndEndInSameTask(graph(page), ending, start.x, start.y); + await expect(camera(page)).not.toHaveAttribute('transform', initial!); + const ended = await camera(page).getAttribute('transform'); + await graph(page).evaluate((element) => { + element.dispatchEvent( + new PointerEvent('pointermove', { + bubbles: true, + pointerId: Number(element.getAttribute('data-test-pointer-id')), + clientX: 800, + clientY: 500, + buttons: 0, + }) + ); + }); + await page.mouse.up(); + await expect(camera(page)).toHaveAttribute('transform', ended!); + await page.getByRole('button', { name: 'Fit graph', exact: true }).click(); + await expect(camera(page)).toHaveAttribute('transform', 'translate(0 0) scale(1)'); + // A new gesture still works after the previous gesture ends. + const next = await startDrag(page); + await page.mouse.move(next.x + 40, next.y + 20, { steps: 5 }); + await page.mouse.up(); + await expect(camera(page)).not.toHaveAttribute('transform', 'translate(0 0) scale(1)'); + }); +} + +test('another pointer cannot move or end an active drag', async ({ page }) => { + const start = await startDrag(page); + const before = await camera(page).getAttribute('transform'); + await graph(page).evaluate((element) => { + const pointerId = Number(element.getAttribute('data-test-pointer-id')) + 100; + for (const type of ['pointermove', 'pointerup', 'pointercancel', 'lostpointercapture']) { + element.dispatchEvent( + new PointerEvent(type, { + bubbles: true, + pointerId, + pointerType: 'touch', + clientX: 700, + clientY: 500, + }) + ); + } + }); + await expect(camera(page)).toHaveAttribute('transform', before!); + await page.mouse.move(start.x + 50, start.y + 30, { steps: 3 }); + await page.mouse.up(); + await expect(camera(page)).not.toHaveAttribute('transform', before!); +}); + +test('keeps every note and cross-topic link in one graph', async ({ page }) => { + await expect(graph(page)).toHaveCount(1); + await expect(graph(page).locator('[data-note]')).toHaveCount(notes.length); + const pairs = await graph(page) + .locator('path[data-source]') + .evaluateAll((paths) => + paths + .map((path) => + [path.getAttribute('data-source'), path.getAttribute('data-target')].sort().join('|') + ) + .sort() + ); + expect(pairs).toEqual(expectedPairs); + // Stop idle motion before Playwright checks whether the SVG label is stable. + await page.getByRole('button', { name: 'Pause graph motion' }).click(); + const highlight = page.getByRole('button', { name: 'Highlight Static analysis', exact: true }); + await highlight.click(); + await expect(highlight).toHaveAttribute('aria-pressed', 'true'); + await expect(graph(page).locator('[data-note]')).toHaveCount(notes.length); + await expect(graph(page).locator('path[data-active=true]').first()).toBeVisible(); + await page.getByRole('button', { name: 'All topics', exact: true }).click(); + await expect(highlight).toHaveAttribute('aria-pressed', 'false'); +}); + +test('zooms within limits, pans, and fits the whole graph', async ({ page }) => { + const zoomIn = page.getByRole('button', { name: 'Zoom in', exact: true }); + const zoomOut = page.getByRole('button', { name: 'Zoom out', exact: true }); + await expect(zoomOut).toBeDisabled(); + for (let index = 0; index < 4; index++) await zoomIn.click(); + await expect(zoomIn).toBeDisabled(); + await expect(camera(page)).toHaveAttribute('transform', /scale\(3\)/); + const start = await startDrag(page); + const before = await camera(page).getAttribute('transform'); + await page.mouse.move(start.x + 60, start.y + 50, { steps: 8 }); + await page.mouse.up(); + await expect(camera(page)).not.toHaveAttribute('transform', before!); + await page.getByRole('button', { name: 'Fit graph', exact: true }).click(); + await expect(camera(page)).toHaveAttribute('transform', 'translate(0 0) scale(1)'); + await expect(zoomOut).toBeDisabled(); +}); + +test('selects notes by keyboard, follows connections, and opens a note', async ({ + page, + isMobile, +}) => { + const note = graph(page).locator('[data-note="polint"]'); + await note.focus(); + await note.press('Enter'); + const details = page.getByRole('complementary', { name: 'Note details' }); + await expect(details).toHaveAttribute('data-selected', 'true'); + const title = await details.getByRole('heading').textContent(); + if (!isMobile) { + await graph(page).locator('[data-note="voice-agents"]').hover(); + await expect(page.getByRole('tooltip')).toBeVisible(); + await expect(details.getByRole('heading')).toHaveText(title!); + } + if (isMobile) { + const bounds = (await details.boundingBox())!; + expect(bounds.y).toBeGreaterThanOrEqual(0); + expect(bounds.y + bounds.height).toBeLessThanOrEqual(page.viewportSize()!.height); + } + await details.getByRole('button').nth(1).click(); + await expect(details.getByRole('heading')).not.toHaveText(title!); + const nextTitle = await details.getByRole('heading').textContent(); + const href = await details.getByRole('link', { name: 'Read note' }).getAttribute('href'); + await details.getByRole('link', { name: 'Read note' }).click(); + await expect(page).toHaveURL(href!); + await expect(page.getByRole('heading', { level: 1 })).toHaveText(nextTitle!); +}); + +test('clears selection with Escape and resets the graph when filters change', async ({ page }) => { + await graph(page).locator('[data-note="polint"]').focus(); + await page.keyboard.press('Space'); + const details = page.getByRole('complementary', { name: 'Note details' }); + await expect(details).toHaveAttribute('data-selected', 'true'); + await page.keyboard.press('Escape'); + await expect(details).toHaveAttribute('data-selected', 'false'); + await page.getByRole('button', { name: 'Zoom in', exact: true }).click(); + await page.locator('summary').click(); + await page.getByRole('button', { name: 'post-seed', exact: true }).click(); + await expect(graph(page).locator('[data-note]')).toHaveCount( + notes.filter((note) => note.type === 'post-seed').length + ); + await expect(camera(page)).toHaveAttribute('transform', 'translate(0 0) scale(1)'); + await page.getByRole('button', { name: 'all types', exact: true }).click(); + await page.getByRole('textbox', { name: 'Search brain notes' }).fill('no-matching-note-984739'); + await expect(graph(page)).toHaveCount(0); + await expect( + page.getByText('No notes match these filters. Clear a filter to see the map.') + ).toBeVisible(); + await page.getByRole('button', { name: 'Clear search', exact: true }).click(); + await expect(graph(page).locator('[data-note]')).toHaveCount(notes.length); +}); + +test('pauses motion and respects reduced motion', async ({ page }) => { + await page.emulateMedia({ reducedMotion: 'no-preference' }); + const motion = camera(page).locator(':scope > g'); + await page.getByRole('button', { name: 'Pause graph motion' }).click(); + await expect(motion).toHaveCSS('animation-play-state', 'paused'); + await page.getByRole('button', { name: 'Resume graph motion' }).click(); + await page.mouse.move(0, 0); + await expect(motion).toHaveCSS('animation-play-state', 'running'); + await page.emulateMedia({ reducedMotion: 'reduce' }); + await expect(motion).toHaveCSS('animation-name', 'none'); + await expect(page.getByRole('button', { name: 'Pause graph motion' })).toBeHidden(); + expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true); +}); + +test('a click or tap selects a note without starting a drag', async ({ page, isMobile }) => { + await page.getByRole('button', { name: 'Pause graph motion' }).click(); + const note = graph(page).locator('[data-note="polint"]'); + const before = await camera(page).getAttribute('transform'); + if (isMobile) await note.tap(); + else await note.click(); + await expect(note).toHaveAttribute('aria-pressed', 'true'); + await expect(camera(page)).toHaveAttribute('transform', before!); + await expect(page.getByRole('link', { name: 'Read note' })).toBeVisible(); + await page.getByRole('button', { name: 'Clear selected note' }).click(); + await expect(note).toHaveAttribute('aria-pressed', 'false'); +}); + +test('releasing the pointer outside the graph ends the drag', async ({ page }) => { + const start = await startDrag(page); + const bounds = (await graph(page).boundingBox())!; + const outsideX = Math.min(page.viewportSize()!.width - 2, bounds.x + bounds.width + 20); + await page.mouse.move(outsideX, start.y, { steps: 10 }); + await page.mouse.up(); + const ended = await camera(page).getAttribute('transform'); + await page.mouse.move(start.x + 40, start.y + 30); + await expect(camera(page)).toHaveAttribute('transform', ended!); + await page.getByRole('button', { name: 'Fit graph' }).click(); + await expect(camera(page)).toHaveAttribute('transform', 'translate(0 0) scale(1)'); +}); + +test('each node shows its full name beside the node on hover or focus', async ({ + page, + isMobile, +}) => { + await page.getByRole('button', { name: 'Pause graph motion' }).click(); + const tooltip = page.getByRole('tooltip'); + for (const note of notes) { + const node = graph(page).locator(`[data-note="${note.slug}"]`); + if (isMobile) await node.focus(); + else await node.hover(); + await expect(tooltip).toHaveText(note.title); + await expect(tooltip).toBeVisible(); + await expect(node).toHaveAttribute('aria-describedby', (await tooltip.getAttribute('id'))!); + const nodeBounds = (await node.boundingBox())!; + const labelBounds = (await tooltip.boundingBox())!; + const canvas = (await graph(page).boundingBox())!; + expect(labelBounds.x).toBeGreaterThanOrEqual(canvas.x); + expect(labelBounds.x + labelBounds.width).toBeLessThanOrEqual(canvas.x + canvas.width); + expect(labelBounds.y).toBeGreaterThanOrEqual(canvas.y); + expect(labelBounds.y + labelBounds.height).toBeLessThanOrEqual(canvas.y + canvas.height); + const centerX = nodeBounds.x + nodeBounds.width / 2; + const centerY = nodeBounds.y + nodeBounds.height / 2; + const distanceX = Math.max( + labelBounds.x - centerX, + centerX - labelBounds.x - labelBounds.width, + 0 + ); + const distanceY = Math.max( + labelBounds.y - centerY, + centerY - labelBounds.y - labelBounds.height, + 0 + ); + expect(distanceX).toBeLessThan(25); + expect(distanceY).toBeLessThan(25); + } + await page.keyboard.press('Escape'); + await expect(tooltip).toHaveCount(0); +}); + +test('node names follow the zoomed position and clear on pointer exit', async ({ page }) => { + await page.getByRole('button', { name: 'Pause graph motion' }).click(); + await page.getByRole('button', { name: 'Zoom in' }).click(); + const node = graph(page).locator('[data-note="write-code-ai-agents-love"]'); + await node.hover(); + const tooltip = page.getByRole('tooltip'); + await expect(tooltip).toHaveText( + notes.find((note) => note.slug === 'write-code-ai-agents-love')!.title + ); + const nodeBounds = (await node.boundingBox())!; + const labelBounds = (await tooltip.boundingBox())!; + expect(Math.abs(labelBounds.y - nodeBounds.y)).toBeLessThan(150); + await page.getByRole('button', { name: 'Fit graph' }).hover(); + await expect(tooltip).toHaveCount(0); +});