This commit is contained in:
Zimeng Xiong
2025-11-21 19:18:07 -08:00
parent 35734936b3
commit 4e8beae0ee
66 changed files with 21548 additions and 315 deletions
File diff suppressed because it is too large Load Diff
+183
View File
@@ -0,0 +1,183 @@
import React, { useCallback, useEffect, useState, useRef } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { ArrowLeft } from 'lucide-react';
import { Excalidraw, convertToExcalidrawElements } from '@excalidraw/excalidraw';
import '@excalidraw/excalidraw/index.css';
import debounce from 'lodash/debounce';
import { Toaster, toast } from 'sonner';
import * as api from '../api';
import { useTheme } from '../context/ThemeContext';
export const Editor: React.FC = () => {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const { theme } = useTheme();
const [drawingName, setDrawingName] = useState('Drawing Editor');
const [isRenaming, setIsRenaming] = useState(false);
const [newName, setNewName] = useState('');
const [initialData, setInitialData] = useState<any>(null);
// Refs for API interaction
const excalidrawAPI = useRef<any>(null);
// ------------------------------------------------------------------
// 1. STABLE SAVE LOGIC (The Fix)
// We use a Ref to hold the save function so the debounce wrapper
// doesn't need to be recreated on every render.
// ------------------------------------------------------------------
const saveDataRef = useRef<(elements: any, appState: any) => Promise<void>>(null);
// Update the ref on every render to ensure it has access to the latest props/state
saveDataRef.current = async (elements, appState) => {
if (!id) return;
try {
const persistableAppState = {
viewBackgroundColor: appState.viewBackgroundColor,
gridSize: appState.gridSize,
};
await api.updateDrawing(id, {
elements,
appState: persistableAppState,
});
} catch (err) {
console.error('Failed to save drawing', err);
toast.error("Failed to save changes");
}
};
// Create the debounced function ONLY ONCE.
// It simply calls whatever is currently in saveDataRef.current
const debouncedSave = useCallback(
debounce((elements, appState) => {
if (saveDataRef.current) {
saveDataRef.current(elements, appState);
}
}, 1000),
[] // Empty dependency array = Stable across renders
);
// ------------------------------------------------------------------
// 2. DATA LOADING
// ------------------------------------------------------------------
useEffect(() => {
const loadData = async () => {
if (!id) return;
try {
const data = await api.getDrawing(id);
setDrawingName(data.name);
setInitialData({
elements: convertToExcalidrawElements(data.elements || []),
appState: {
...data.appState,
collaborators: new Map(),
},
scrollToContent: true,
});
} catch (err) {
console.error('Failed to load drawing', err);
}
};
loadData();
}, [id]);
// ------------------------------------------------------------------
// 3. HANDLERS
// ------------------------------------------------------------------
// Hijack Ctrl+S to save immediately
useEffect(() => {
const handleKeyDown = async (e: KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && e.key === 's') {
e.preventDefault();
if (excalidrawAPI.current && saveDataRef.current) {
const elements = excalidrawAPI.current.getSceneElements();
const appState = excalidrawAPI.current.getAppState();
// Call save immediately, bypassing debounce
await saveDataRef.current(elements, appState);
toast.success("Saved changes to server");
}
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, []);
const handleCanvasChange = (elements: readonly any[], appState: any) => {
// Trigger the stable debounced save
debouncedSave(elements, appState);
};
const handleRenameSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (newName.trim() && id) {
setDrawingName(newName);
setIsRenaming(false);
try {
await api.updateDrawing(id, { name: newName });
} catch (err) {
console.error("Failed to rename", err);
}
}
};
// Disable native Excalidraw save dialogs
const UIOptions = {
canvasActions: {
saveToActiveFile: false,
loadScene: false,
export: { saveFileToDisk: false },
toggleTheme: true,
},
};
return (
<div className="h-screen flex flex-col bg-white dark:bg-neutral-950 overflow-hidden">
<header className="h-14 bg-white dark:bg-neutral-900 border-b border-gray-200 dark:border-neutral-800 flex items-center px-4 justify-between z-10">
<div className="flex items-center gap-4">
<button onClick={() => navigate('/')} className="p-2 hover:bg-gray-100 dark:hover:bg-neutral-800 rounded-full text-gray-600 dark:text-gray-300">
<ArrowLeft size={20} />
</button>
{isRenaming ? (
<form onSubmit={handleRenameSubmit}>
<input
autoFocus
type="text"
value={newName}
onChange={(e) => setNewName(e.target.value)}
onBlur={() => setIsRenaming(false)}
className="font-medium text-gray-900 dark:text-white bg-transparent px-2 py-1 border-2 border-indigo-500 rounded-md outline-none"
/>
</form>
) : (
<h1
className="font-medium text-gray-900 dark:text-white px-2 py-1 hover:bg-gray-100 dark:hover:bg-neutral-800 rounded cursor-text"
onDoubleClick={() => { setNewName(drawingName); setIsRenaming(true); }}
>
{drawingName}
</h1>
)}
</div>
<div className="flex items-center gap-2">
{/* Status indicator removed */}
</div>
</header>
<div className="flex-1 w-full relative" style={{ height: 'calc(100vh - 3.5rem)' }}>
<Excalidraw
theme={theme === 'dark' ? 'dark' : 'light'}
initialData={initialData}
onChange={handleCanvasChange}
excalidrawAPI={(api) => (excalidrawAPI.current = api)}
UIOptions={UIOptions}
/>
<Toaster position="bottom-center" />
</div>
</div>
);
};
+267
View File
@@ -0,0 +1,267 @@
import React, { useEffect, useState } from 'react';
import { Layout } from '../components/Layout';
import { useNavigate } from 'react-router-dom';
import * as api from '../api';
import type { Collection } from '../types';
import { Database, FileJson, Upload, Moon, Sun } from 'lucide-react';
import { ConfirmModal } from '../components/ConfirmModal';
import { importDrawings } from '../utils/importUtils';
import { useTheme } from '../context/ThemeContext';
export const Settings: React.FC = () => {
const [collections, setCollections] = useState<Collection[]>([]);
const navigate = useNavigate();
const { theme, toggleTheme } = useTheme();
// Import state
const [importConfirmation, setImportConfirmation] = useState<{ isOpen: boolean; file: File | null }>({ isOpen: false, file: null });
const [importError, setImportError] = useState<{ isOpen: boolean; message: string }>({ isOpen: false, message: '' });
const [importSuccess, setImportSuccess] = useState(false);
useEffect(() => {
const fetchCollections = async () => {
try {
const data = await api.getCollections();
setCollections(data);
} catch (err) {
console.error('Failed to fetch collections:', err);
}
};
fetchCollections();
}, []);
const handleCreateCollection = async (name: string) => {
await api.createCollection(name);
const newCollections = await api.getCollections();
setCollections(newCollections);
};
const handleEditCollection = async (id: string, name: string) => {
setCollections(prev => prev.map(c => c.id === id ? { ...c, name } : c));
await api.updateCollection(id, name);
};
const handleDeleteCollection = async (id: string) => {
setCollections(prev => prev.filter(c => c.id !== id));
await api.deleteCollection(id);
};
const handleSelectCollection = (id: string | null | undefined) => {
// Navigate to dashboard with selected collection
if (id === undefined) navigate('/');
else if (id === null) navigate('/collections?id=unorganized');
else navigate(`/collections?id=${id}`);
};
return (
<Layout
collections={collections}
selectedCollectionId="SETTINGS" // Special ID to highlight Settings in Sidebar if we add logic for it
onSelectCollection={handleSelectCollection}
onCreateCollection={handleCreateCollection}
onEditCollection={handleEditCollection}
onDeleteCollection={handleDeleteCollection}
>
<h1 className="text-5xl mb-8 text-slate-900 dark:text-white pl-1" style={{ fontFamily: 'Excalifont' }}>
Settings
</h1>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{/* Theme Toggle */}
<button
onClick={toggleTheme}
className="flex flex-col items-center justify-center gap-4 p-8 bg-white dark:bg-neutral-900 border-2 border-black dark:border-neutral-700 rounded-2xl shadow-[4px_4px_0px_0px_rgba(0,0,0,1)] dark:shadow-[4px_4px_0px_0px_rgba(255,255,255,0.2)] hover:shadow-[6px_6px_0px_0px_rgba(0,0,0,1)] dark:hover:shadow-[6px_6px_0px_0px_rgba(255,255,255,0.2)] hover:-translate-y-1 transition-all duration-200 group"
>
<div className="w-16 h-16 bg-amber-50 dark:bg-neutral-800 rounded-2xl flex items-center justify-center border-2 border-amber-100 dark:border-neutral-700 group-hover:border-amber-200 dark:group-hover:border-neutral-600 transition-colors">
{theme === 'light' ? (
<Moon size={32} className="text-amber-600 dark:text-amber-400" />
) : (
<Sun size={32} className="text-amber-600 dark:text-amber-400" />
)}
</div>
<div className="text-center">
<h3 className="text-xl font-bold text-slate-900 dark:text-white mb-1">
{theme === 'light' ? 'Dark Mode' : 'Light Mode'}
</h3>
<p className="text-sm text-slate-500 dark:text-neutral-400 font-medium">
Switch to {theme === 'light' ? 'dark' : 'light'} theme
</p>
</div>
</button>
{/* Export SQLite */}
<button
onClick={() => window.location.href = `${api.API_URL}/export`}
className="flex flex-col items-center justify-center gap-4 p-8 bg-white dark:bg-neutral-900 border-2 border-black dark:border-neutral-700 rounded-2xl shadow-[4px_4px_0px_0px_rgba(0,0,0,1)] dark:shadow-[4px_4px_0px_0px_rgba(255,255,255,0.2)] hover:shadow-[6px_6px_0px_0px_rgba(0,0,0,1)] dark:hover:shadow-[6px_6px_0px_0px_rgba(255,255,255,0.2)] hover:-translate-y-1 transition-all duration-200 group"
>
<div className="w-16 h-16 bg-indigo-50 dark:bg-neutral-800 rounded-2xl flex items-center justify-center border-2 border-indigo-100 dark:border-neutral-700 group-hover:border-indigo-200 dark:group-hover:border-neutral-600 transition-colors">
<Database size={32} className="text-indigo-600 dark:text-indigo-400" />
</div>
<div className="text-center">
<h3 className="text-xl font-bold text-slate-900 dark:text-white mb-1">Export Data (SQLite)</h3>
<p className="text-sm text-slate-500 dark:text-neutral-400 font-medium">Download full database backup</p>
</div>
</button>
{/* Export JSON */}
<button
onClick={() => window.location.href = `${api.API_URL}/export/json`}
className="flex flex-col items-center justify-center gap-4 p-8 bg-white dark:bg-neutral-900 border-2 border-black dark:border-neutral-700 rounded-2xl shadow-[4px_4px_0px_0px_rgba(0,0,0,1)] dark:shadow-[4px_4px_0px_0px_rgba(255,255,255,0.2)] hover:shadow-[6px_6px_0px_0px_rgba(0,0,0,1)] dark:hover:shadow-[6px_6px_0px_0px_rgba(255,255,255,0.2)] hover:-translate-y-1 transition-all duration-200 group"
>
<div className="w-16 h-16 bg-emerald-50 dark:bg-neutral-800 rounded-2xl flex items-center justify-center border-2 border-emerald-100 dark:border-neutral-700 group-hover:border-emerald-200 dark:group-hover:border-neutral-600 transition-colors">
<FileJson size={32} className="text-emerald-600 dark:text-emerald-400" />
</div>
<div className="text-center">
<h3 className="text-xl font-bold text-slate-900 dark:text-white mb-1">Export Data (JSON)</h3>
<p className="text-sm text-slate-500 dark:text-neutral-400 font-medium">Download drawings as JSON</p>
</div>
</button>
{/* Import Data */}
<div className="relative">
<input
type="file"
multiple
accept=".sqlite,.json,.excalidraw"
className="hidden"
id="settings-import-db"
onChange={async (e) => {
const files = Array.from(e.target.files || []);
if (files.length === 0) return;
// Handle SQLite Import
const sqliteFile = files.find(f => f.name.endsWith('.sqlite'));
if (sqliteFile) {
if (files.length > 1) {
setImportError({ isOpen: true, message: 'Please import database files separately from other files.' });
e.target.value = '';
return;
}
const formData = new FormData();
formData.append('db', sqliteFile);
try {
const res = await fetch(`${api.API_URL}/import/sqlite/verify`, {
method: 'POST',
body: formData,
});
if (!res.ok) {
const errorData = await res.json();
setImportError({ isOpen: true, message: errorData.error || 'Invalid database file.' });
e.target.value = '';
return;
}
setImportConfirmation({ isOpen: true, file: sqliteFile });
} catch (err) {
console.error('Verification failed:', err);
setImportError({ isOpen: true, message: 'Failed to verify database file.' });
}
e.target.value = '';
return;
}
// Handle Bulk Drawing Import
const drawingFiles = files.filter(f => f.name.endsWith('.json') || f.name.endsWith('.excalidraw'));
if (drawingFiles.length === 0) {
setImportError({ isOpen: true, message: 'No supported files found.' });
e.target.value = '';
return;
}
const result = await importDrawings(drawingFiles, null, () => { });
if (result.failed > 0) {
setImportError({
isOpen: true,
message: `Import complete with errors.\nSuccess: ${result.success}\nFailed: ${result.failed}\nErrors:\n${result.errors.join('\n')}`
});
} else {
setImportSuccess(true);
}
e.target.value = '';
}}
/>
<button
onClick={() => document.getElementById('settings-import-db')?.click()}
className="w-full h-full flex flex-col items-center justify-center gap-4 p-8 bg-white dark:bg-neutral-900 border-2 border-black dark:border-neutral-700 rounded-2xl shadow-[4px_4px_0px_0px_rgba(0,0,0,1)] dark:shadow-[4px_4px_0px_0px_rgba(255,255,255,0.2)] hover:shadow-[6px_6px_0px_0px_rgba(0,0,0,1)] dark:hover:shadow-[6px_6px_0px_0px_rgba(255,255,255,0.2)] hover:-translate-y-1 transition-all duration-200 group"
>
<div className="w-16 h-16 bg-blue-50 dark:bg-neutral-800 rounded-2xl flex items-center justify-center border-2 border-blue-100 dark:border-neutral-700 group-hover:border-blue-200 dark:group-hover:border-neutral-600 transition-colors">
<Upload size={32} className="text-blue-600 dark:text-blue-400" />
</div>
<div className="text-center">
<h3 className="text-xl font-bold text-slate-900 dark:text-white mb-1">Import Data</h3>
<p className="text-sm text-slate-500 dark:text-neutral-400 font-medium">Import SQLite or Drawings</p>
</div>
</button>
</div>
</div>
{/* Modals */}
<ConfirmModal
isOpen={importConfirmation.isOpen}
title="Import Database"
message="WARNING: This will overwrite your current database with the imported file. This action cannot be undone. Are you sure?"
confirmText="Import Database"
onConfirm={async () => {
if (!importConfirmation.file) return;
const formData = new FormData();
formData.append('db', importConfirmation.file);
try {
const res = await fetch(`${api.API_URL}/import/sqlite`, {
method: 'POST',
body: formData,
});
if (!res.ok) {
const errorData = await res.json();
throw new Error(errorData.error || 'Import failed');
}
setImportConfirmation({ isOpen: false, file: null });
setImportSuccess(true);
} catch (err: any) {
console.error(err);
setImportError({ isOpen: true, message: `Failed to import database: ${err.message}` });
setImportConfirmation({ isOpen: false, file: null });
}
}}
onCancel={() => setImportConfirmation({ isOpen: false, file: null })}
/>
<ConfirmModal
isOpen={importError.isOpen}
title="Import Failed"
message={importError.message}
confirmText="OK"
cancelText=""
showCancel={false}
isDangerous={false}
onConfirm={() => setImportError({ isOpen: false, message: '' })}
onCancel={() => setImportError({ isOpen: false, message: '' })}
/>
<ConfirmModal
isOpen={importSuccess}
title="Import Successful"
message="Data imported successfully."
confirmText="OK"
showCancel={false}
isDangerous={false}
onConfirm={() => setImportSuccess(false)}
onCancel={() => setImportSuccess(false)}
/>
</Layout >
);
};