|
1 | 1 | import { useEffect, useRef } from 'react'; |
2 | | -import { useNavigate } from 'react-router-dom'; |
| 2 | +import { useNavigate, useLocation } from 'react-router-dom'; |
3 | 3 | import { LearningMapEditor, useEditorStore } from '@learningmap/learningmap'; |
4 | 4 | import "@learningmap/learningmap/index.css"; |
5 | 5 | import * as db from './db'; |
6 | 6 | import './TeacherEditor.css'; |
7 | 7 | import { Header } from './Header'; |
8 | 8 |
|
9 | 9 | // This component wraps the LearningMapEditor and saves maps to the teacher's collection |
10 | | -// when they are shared |
| 10 | +// when they are shared or modified |
11 | 11 | function TeacherEditorInner() { |
| 12 | + const location = useLocation(); |
12 | 13 | const shareLink = useEditorStore(state => state.shareLink); |
13 | 14 | const shareDialogOpen = useEditorStore(state => state.shareDialogOpen); |
14 | 15 | const getRoadmapData = useEditorStore(state => state.getRoadmapData); |
| 16 | + const nodes = useEditorStore(state => state.nodes); |
| 17 | + const edges = useEditorStore(state => state.edges); |
| 18 | + const settings = useEditorStore(state => state.settings); |
15 | 19 | const lastSavedRef = useRef<string | null>(null); |
| 20 | + const saveTimeoutRef = useRef<number | null>(null); |
| 21 | + |
| 22 | + // Extract jsonId from URL |
| 23 | + const jsonId = location.hash.startsWith('#json=') ? location.hash.replace('#json=', '') : null; |
| 24 | + |
| 25 | + // Auto-save changes with debouncing |
| 26 | + useEffect(() => { |
| 27 | + if (!jsonId) return; |
| 28 | + |
| 29 | + // Clear any pending save |
| 30 | + if (saveTimeoutRef.current) { |
| 31 | + clearTimeout(saveTimeoutRef.current); |
| 32 | + } |
| 33 | + |
| 34 | + // Debounce saves to avoid too many writes |
| 35 | + saveTimeoutRef.current = window.setTimeout(async () => { |
| 36 | + const roadmapData = getRoadmapData(); |
| 37 | + const storageId = roadmapData.settings?.id || jsonId; |
| 38 | + |
| 39 | + try { |
| 40 | + // Check if this map exists in teacher's collection |
| 41 | + const existingMap = await db.getTeacherMap(storageId); |
| 42 | + if (existingMap) { |
| 43 | + // Update existing map |
| 44 | + await db.addTeacherMap(storageId, roadmapData, existingMap.jsonId); |
| 45 | + } |
| 46 | + } catch (err) { |
| 47 | + console.error('Failed to auto-save map:', err); |
| 48 | + } |
| 49 | + }, 1000); // Save after 1 second of inactivity |
| 50 | + |
| 51 | + return () => { |
| 52 | + if (saveTimeoutRef.current) { |
| 53 | + clearTimeout(saveTimeoutRef.current); |
| 54 | + } |
| 55 | + }; |
| 56 | + }, [nodes, edges, settings, jsonId, getRoadmapData]); |
16 | 57 |
|
17 | 58 | // When a map is shared, save it to the teacher's collection |
18 | 59 | useEffect(() => { |
|
0 commit comments