aboutsummaryrefslogtreecommitdiff
path: root/packages/memory-graph/README.md
blob: eae06940d2d7315ac386fa64a3a17a7faa943b88 (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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# @supermemory/memory-graph

> Interactive graph visualization component for Supermemory - visualize and explore your memory connections

[![npm version](https://img.shields.io/npm/v/@supermemory/memory-graph.svg)](https://www.npmjs.com/package/@supermemory/memory-graph)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## Features

- **WebGL-powered rendering** - Smooth performance with hundreds of nodes
- **Interactive exploration** - Pan, zoom, drag nodes, and explore connections
- **Semantic connections** - Visualizes relationships based on content similarity
- **Space filtering with search** - Dynamically search and filter by spaces/tags
- **Memory limit control** - Limit memories per document (50-3000) for performance
- **Controlled/uncontrolled modes** - Flexible state management for integration
- **Responsive design** - Works seamlessly on mobile and desktop
- **Zero configuration** - Works out of the box with automatic CSS injection
- **Lightweight** - Tree-shakeable and optimized bundle
- **TypeScript** - Full TypeScript support with exported types

## Installation

```bash
npm install @supermemory/memory-graph
# or
yarn add @supermemory/memory-graph
# or
pnpm add @supermemory/memory-graph
# or
bun add @supermemory/memory-graph
```

## Quick Start

The component accepts document data directly - you fetch the data from your backend, which proxies requests to the Supermemory API with proper authentication.

```tsx
import { MemoryGraph } from '@supermemory/memory-graph'
import type { DocumentWithMemories } from '@supermemory/memory-graph'

function App() {
  const [documents, setDocuments] = useState<DocumentWithMemories[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<Error | null>(null)

  useEffect(() => {
    // Fetch from YOUR backend (which proxies to Supermemory API)
    fetch('/api/supermemory-graph')
      .then(res => res.json())
      .then(data => {
        setDocuments(data.documents)
        setIsLoading(false)
      })
      .catch(err => {
        setError(err)
        setIsLoading(false)
      })
  }, [])

  return (
    <MemoryGraph
      documents={documents}
      isLoading={isLoading}
      error={error}
    />
  )
}
```

## Backend Proxy Example

Create an API route in your backend that authenticates and proxies requests to Supermemory:

### Next.js API Route

```typescript
// app/api/supermemory-graph/route.ts
import { NextResponse } from 'next/server'

export async function GET(request: Request) {
  // Add your own auth check here
  const user = await getAuthenticatedUser(request)
  if (!user) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }

  const response = await fetch('https://api.supermemory.ai/v3/documents/documents', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${process.env.SUPERMEMORY_API_KEY}`,
    },
    body: JSON.stringify({
      page: 1,
      limit: 500,
      sort: 'createdAt',
      order: 'desc',
    }),
  })

  const data = await response.json()
  return NextResponse.json(data)
}
```

## API Reference

### Props

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `documents` | `DocumentWithMemories[]` | **required** | Array of documents to display |
| `isLoading` | `boolean` | `false` | Whether data is currently loading |
| `error` | `Error \| null` | `null` | Error that occurred during fetching |
| `variant` | `"console" \| "consumer"` | `"console"` | Visual variant |
| `showSpacesSelector` | `boolean` | Based on variant | Show/hide the spaces filter |
| `children` | `ReactNode` | - | Content to show when no documents |
| `highlightDocumentIds` | `string[]` | `[]` | Document IDs to highlight |
| `highlightsVisible` | `boolean` | `true` | Whether highlights are visible |

### Space & Memory Control Props (Optional)

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `selectedSpace` | `string` | `"all"` | Currently selected space (controlled) |
| `onSpaceChange` | `(spaceId: string) => void` | - | Callback when space changes |
| `onSearchSpaces` | `(query: string) => Promise<string[]>` | - | Async space search function |
| `memoryLimit` | `number` | `500` | Max memories per document when space selected |
| `onMemoryLimitChange` | `(limit: number) => void` | - | Callback when limit changes |
| `isExperimental` | `boolean` | `false` | Enable experimental features |

### Pagination Props (Optional)

For large datasets, you can implement pagination:

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `isLoadingMore` | `boolean` | `false` | Whether loading more data |
| `hasMore` | `boolean` | `false` | Whether more data is available |
| `totalLoaded` | `number` | `documents.length` | Total documents loaded |
| `loadMoreDocuments` | `() => Promise<void>` | - | Callback to load more |

### Types

```typescript
import type {
  DocumentWithMemories,
  MemoryEntry,
  DocumentsResponse,
  MemoryGraphProps,
  MemoryLimit,
  MemoryCountSelectorProps,
  GraphNode,
  GraphEdge,
  MemoryRelation
} from '@supermemory/memory-graph'

// Memory limit can be one of these values
type MemoryLimit = 50 | 100 | 250 | 500 | 1000 | 2000 | 3000
```

## Advanced Usage

### With Pagination

```tsx
import { MemoryGraph } from '@supermemory/memory-graph'

function GraphWithPagination() {
  const [documents, setDocuments] = useState([])
  const [page, setPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)
  const [isLoadingMore, setIsLoadingMore] = useState(false)

  const loadMore = async () => {
    setIsLoadingMore(true)
    const res = await fetch(`/api/supermemory-graph?page=${page + 1}`)
    const data = await res.json()
    setDocuments(prev => [...prev, ...data.documents])
    setHasMore(data.pagination.currentPage < data.pagination.totalPages)
    setPage(p => p + 1)
    setIsLoadingMore(false)
  }

  return (
    <MemoryGraph
      documents={documents}
      isLoading={isLoading}
      isLoadingMore={isLoadingMore}
      hasMore={hasMore}
      loadMoreDocuments={loadMore}
      totalLoaded={documents.length}
    />
  )
}
```

### Custom Empty State

```tsx
<MemoryGraph documents={[]} isLoading={false}>
  <div className="empty-state">
    <h2>No memories yet</h2>
    <p>Start adding content to see your knowledge graph</p>
  </div>
</MemoryGraph>
```

### Controlled Space Selection & Memory Limiting

Control the selected space and memory limit externally for integration with your app's state management:

```tsx
import { MemoryGraph } from '@supermemory/memory-graph'

function ControlledGraph() {
  const [selectedSpace, setSelectedSpace] = useState("all")
  const [memoryLimit, setMemoryLimit] = useState(500)
  const [searchResults, setSearchResults] = useState([])

  // Handle space search via your API
  const handleSpaceSearch = async (query: string) => {
    const response = await fetch(`/api/spaces/search?q=${query}`)
    const spaces = await response.json()
    setSearchResults(spaces)
    return spaces
  }

  return (
    <div>
      {/* Display current state */}
      <div className="controls">
        <p>Selected Space: {selectedSpace}</p>
        <p>Memory Limit: {memoryLimit}</p>
        <button onClick={() => {
          setSelectedSpace("all")
          setMemoryLimit(500)
        }}>
          Reset Filters
        </button>
      </div>

      {/* Controlled graph */}
      <MemoryGraph
        documents={documents}
        selectedSpace={selectedSpace}
        onSpaceChange={setSelectedSpace}
        onSearchSpaces={handleSpaceSearch}
        memoryLimit={memoryLimit}
        onMemoryLimitChange={setMemoryLimit}
        variant="console"
        showSpacesSelector={true}
      />
    </div>
  )
}
```

### Uncontrolled Mode (Automatic)

If you don't provide `selectedSpace` or `memoryLimit` props, the component manages its own state:

```tsx
<MemoryGraph
  documents={documents}
  // Component manages space selection and memory limit internally
  onSearchSpaces={handleSpaceSearch} // Still can provide search function
  showSpacesSelector={true}
/>
```

### Space Search Integration

Implement server-side space search for dynamic filtering:

```tsx
// Frontend
const handleSpaceSearch = async (query: string): Promise<string[]> => {
  const response = await fetch('/api/spaces/search', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ query })
  })
  return response.json()
}

<MemoryGraph
  documents={documents}
  onSearchSpaces={handleSpaceSearch}
  showSpacesSelector={true}
/>

// Backend (Next.js example)
// app/api/spaces/search/route.ts
export async function POST(request: Request) {
  const { query } = await request.json()

  const response = await fetch('https://api.supermemory.ai/v3/search/spaces', {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${process.env.SUPERMEMORY_API_KEY}`,
    },
    params: { q: query }
  })

  return response.json()
}
```

### Variants

The `variant` prop controls the visual layout and initial viewport settings:

| Variant | Initial Zoom | Spaces Selector | Legend Position | Use Case |
|---------|-------------|-----------------|-----------------|----------|
| `console` | 0.8 | Shown | Bottom-right | Full-page dashboard views |
| `consumer` | 0.5 | Hidden | Top-right | Embedded/widget views |

```tsx
// Full dashboard view
<MemoryGraph
  documents={documents}
  variant="console"
/>

// Embedded widget
<MemoryGraph
  documents={documents}
  variant="consumer"
/>
```

## Interactive Controls

- **Pan**: Click and drag the background
- **Zoom**: Mouse wheel or pinch on mobile
- **Select Node**: Click on any document or memory
- **Drag Nodes**: Click and drag individual nodes
- **Fit to View**: Auto-fit button to center all content
- **Space Filter**: Click the space selector to filter by space
- **Space Search**: Type in the search box and press Enter to find spaces
- **Memory Limit**: Select a limit (50-3K) when filtering by space

## Browser Support

- Chrome/Edge (latest)
- Firefox (latest)
- Safari (latest)
- Mobile browsers with WebGL support

## Requirements

- React 18+
- Modern browser with WebGL support

## Development

```bash
# Install dependencies
bun install

# Build the package
bun run build

# Watch mode for development
bun run dev

# Type checking
bun run check-types
```

## License

MIT

## Support

- Issues: [GitHub Issues](https://github.com/supermemoryai/supermemory/issues)