aboutsummaryrefslogtreecommitdiff
path: root/apps/docs/memory-graph/examples.mdx
blob: 14d615d531d63a41f765f301ac7f2e74c1a6dd00 (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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
---
title: 'Examples'
description: 'Common use cases and implementation patterns'
---

## With Pagination

Load documents in chunks for better performance with large datasets.

```tsx
'use client';

import { MemoryGraph } from '@supermemory/memory-graph';
import type { DocumentWithMemories } from '@supermemory/memory-graph';
import { useCallback, useEffect, useState } from 'react';

export default function PaginatedGraph() {
  const [documents, setDocuments] = useState<DocumentWithMemories[]>([]);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [isLoading, setIsLoading] = useState(true);
  const [isLoadingMore, setIsLoadingMore] = useState(false);

  // Initial load
  useEffect(() => {
    fetchPage(1, false);
  }, []);

  const fetchPage = async (pageNum: number, append: boolean) => {
    if (pageNum === 1) {
      setIsLoading(true);
    } else {
      setIsLoadingMore(true);
    }

    const res = await fetch(`/api/graph?page=${pageNum}&limit=100`);
    const data = await res.json();

    if (append) {
      setDocuments(prev => [...prev, ...data.documents]);
    } else {
      setDocuments(data.documents);
    }

    setHasMore(data.pagination.currentPage < data.pagination.totalPages);
    setIsLoading(false);
    setIsLoadingMore(false);
  };

  const loadMore = useCallback(async () => {
    if (!isLoadingMore && hasMore) {
      const nextPage = page + 1;
      setPage(nextPage);
      await fetchPage(nextPage, true);
    }
  }, [page, hasMore, isLoadingMore]);

  return (
    <div style={{ height: '100vh' }}>
      <MemoryGraph
        documents={documents}
        isLoading={isLoading}
        isLoadingMore={isLoadingMore}
        hasMore={hasMore}
        totalLoaded={documents.length}
        loadMoreDocuments={loadMore}
      />
    </div>
  );
}
```

## Highlighting Search Results

```tsx
'use client';

import { MemoryGraph } from '@supermemory/memory-graph';
import { useState } from 'react';

export default function SearchableGraph() {
  const [documents, setDocuments] = useState([]);
  const [searchResults, setSearchResults] = useState<string[]>([]);
  const [searchQuery, setSearchQuery] = useState('');

  const handleSearch = async (query: string) => {
    setSearchQuery(query);

    if (!query) {
      setSearchResults([]);
      return;
    }

    const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`);
    const data = await res.json();

    // Extract document IDs from search results
    const docIds = data.results.map(r => r.documentId);
    setSearchResults(docIds);
  };

  return (
    <div style={{ height: '100vh' }}>
      <div style={{ position: 'absolute', top: 16, left: 16, zIndex: 10 }}>
        <input
          type="text"
          placeholder="Search memories..."
          value={searchQuery}
          onChange={(e) => handleSearch(e.target.value)}
          style={{
            padding: '8px 12px',
            borderRadius: 8,
            border: '1px solid #333',
            background: '#1a1a1a',
            color: 'white',
          }}
        />
      </div>

      <MemoryGraph
        documents={documents}
        highlightDocumentIds={searchResults}
        highlightsVisible={searchResults.length > 0}
      />
    </div>
  );
}
```

## Controlled Space Selection

Control space filtering from outside the component.

```tsx
'use client';

import { MemoryGraph } from '@supermemory/memory-graph';
import { useState } from 'react';

export default function ControlledSpaceGraph() {
  const [documents, setDocuments] = useState([]);
  const [selectedSpace, setSelectedSpace] = useState('all');

  // Extract available spaces from documents
  const spaces = Array.from(
    new Set(
      documents.flatMap(doc =>
        doc.memoryEntries.map(m => m.spaceId || 'default')
      )
    )
  );

  return (
    <div style={{ height: '100vh' }}>
      <div style={{
        position: 'absolute',
        top: 16,
        right: 16,
        zIndex: 10,
        background: '#1a1a1a',
        padding: 16,
        borderRadius: 8,
        border: '1px solid #333',
      }}>
        <h3 style={{ margin: '0 0 12px 0', color: 'white' }}>Filters</h3>

        <select
          value={selectedSpace}
          onChange={(e) => setSelectedSpace(e.target.value)}
          style={{
            padding: '8px 12px',
            borderRadius: 6,
            background: '#2a2a2a',
            color: 'white',
            border: '1px solid #444',
            width: '100%',
          }}
        >
          <option value="all">All Spaces</option>
          {spaces.map(space => (
            <option key={space} value={space}>{space}</option>
          ))}
        </select>

        <button
          onClick={() => setSelectedSpace('all')}
          style={{
            marginTop: 12,
            padding: '6px 12px',
            borderRadius: 6,
            background: '#333',
            color: 'white',
            border: 'none',
            width: '100%',
            cursor: 'pointer',
          }}
        >
          Reset
        </button>
      </div>

      <MemoryGraph
        documents={documents}
        selectedSpace={selectedSpace}
        onSpaceChange={setSelectedSpace}
        showSpacesSelector={false}
      />
    </div>
  );
}
```

## Embedded Widget

Use the consumer variant for embedded views with custom styling.

```tsx
'use client';

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

export default function EmbeddedGraph({ documents }) {
  return (
    <div
      style={{
        height: 400,
        borderRadius: 12,
        overflow: 'hidden',
        border: '1px solid #2a2a2a',
      }}
    >
      <MemoryGraph
        documents={documents}
        variant="consumer"
        showSpacesSelector={false}
      >
        <div style={{
          textAlign: 'center',
          padding: '2rem',
          color: '#888',
        }}>
          <p>No memories to display</p>
        </div>
      </MemoryGraph>
    </div>
  );
}
```

## With Loading States

```tsx
'use client';

import { MemoryGraph } from '@supermemory/memory-graph';
import { useEffect, useState } from 'react';

export default function LoadingGraph() {
  const [documents, setDocuments] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);

  useEffect(() => {
    fetch('/api/graph')
      .then(res => {
        if (!res.ok) throw new Error('Failed to load graph');
        return res.json();
      })
      .then(data => {
        setDocuments(data.documents);
        setIsLoading(false);
      })
      .catch(err => {
        setError(err);
        setIsLoading(false);
      });
  }, []);

  return (
    <div style={{ height: '100vh' }}>
      <MemoryGraph
        documents={documents}
        isLoading={isLoading}
        error={error}
      >
        <div style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          height: '100%',
          color: '#888',
        }}>
          <div>
            <h2>Welcome to your Memory Graph</h2>
            <p>Add some content to get started</p>
            <button
              style={{
                marginTop: 16,
                padding: '8px 16px',
                borderRadius: 6,
                background: '#2563eb',
                color: 'white',
                border: 'none',
                cursor: 'pointer',
              }}
              onClick={() => window.location.href = '/add-memory'}
            >
              Add First Memory
            </button>
          </div>
        </div>
      </MemoryGraph>
    </div>
  );
}
```

## React Server Component

```tsx
// Next.js App Router with Server Component
import { MemoryGraphClient } from './memory-graph-client';

async function getGraphData() {
  const res = await fetch('https://api.supermemory.ai/v3/documents/documents', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.SUPERMEMORY_API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      page: 1,
      limit: 500,
      sort: 'createdAt',
      order: 'desc',
    }),
    cache: 'no-store', // or use revalidation
  });

  return res.json();
}

export default async function GraphPage() {
  const data = await getGraphData();

  return <MemoryGraphClient initialDocuments={data.documents} />;
}
```

```tsx
// memory-graph-client.tsx
'use client';

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

interface Props {
  initialDocuments: DocumentWithMemories[];
}

export function MemoryGraphClient({ initialDocuments }: Props) {
  return (
    <div style={{ height: '100vh' }}>
      <MemoryGraph
        documents={initialDocuments}
        isLoading={false}
      />
    </div>
  );
}
```

## Mobile-Responsive Layout

```tsx
'use client';

import { MemoryGraph } from '@supermemory/memory-graph';
import { useState, useEffect } from 'react';

export default function ResponsiveGraph({ documents }) {
  const [isMobile, setIsMobile] = useState(false);

  useEffect(() => {
    const checkMobile = () => {
      setIsMobile(window.innerWidth < 768);
    };

    checkMobile();
    window.addEventListener('resize', checkMobile);
    return () => window.removeEventListener('resize', checkMobile);
  }, []);

  return (
    <div style={{
      height: isMobile ? '60vh' : '100vh',
      width: '100%',
    }}>
      <MemoryGraph
        documents={documents}
        variant={isMobile ? 'consumer' : 'console'}
        showSpacesSelector={!isMobile}
      />
    </div>
  );
}
```