Neah/app/carnet/page.tsx
2025-04-20 19:15:59 +02:00

458 lines
14 KiB
TypeScript

"use client";
import { useEffect, useState, useRef } from "react";
import { useSession } from "next-auth/react";
import { redirect } from "next/navigation";
import Navigation from "@/components/carnet/navigation";
import { NotesView } from "@/components/carnet/notes-view";
import { Editor } from "@/components/carnet/editor";
import { PanelResizer } from "@/components/carnet/panel-resizer";
import { useMediaQuery } from "@/hooks/use-media-query";
import { ContactsView } from '@/components/carnet/contacts-view';
import { X, Menu } from "lucide-react";
// Layout modes
export enum PaneLayout {
TagSelection = "tag-selection",
ItemSelection = "item-selection",
TableView = "table-view",
Editing = "editing"
}
interface Note {
id: string;
title: string;
content: string;
lastModified: string;
type: string;
mime: string;
etag: string;
}
interface Contact {
id: string;
fullName: string;
email: string;
phone?: string;
organization?: string;
address?: string;
notes?: string;
group?: string;
}
export default function CarnetPage() {
const { data: session, status } = useSession();
const [isLoading, setIsLoading] = useState(true);
const [layoutMode, setLayoutMode] = useState<string>("item-selection");
const [selectedNote, setSelectedNote] = useState<Note | null>(null);
const [isMobile, setIsMobile] = useState(false);
const [showNav, setShowNav] = useState(true);
const [showNotes, setShowNotes] = useState(true);
const [nextcloudFolders, setNextcloudFolders] = useState<string[]>([]);
const [selectedFolder, setSelectedFolder] = useState<string>('Notes');
const [notes, setNotes] = useState<Note[]>([]);
const [isLoadingNotes, setIsLoadingNotes] = useState(true);
const [contacts, setContacts] = useState<Contact[]>([]);
const [selectedContact, setSelectedContact] = useState<Contact | null>(null);
const [isLoadingContacts, setIsLoadingContacts] = useState(true);
// Panel widths state
const [navWidth, setNavWidth] = useState(220);
const [notesWidth, setNotesWidth] = useState(400);
const [isDraggingNav, setIsDraggingNav] = useState(false);
const [isDraggingNotes, setIsDraggingNotes] = useState(false);
// Check screen size
const isSmallScreen = useMediaQuery("(max-width: 768px)");
const isMediumScreen = useMediaQuery("(max-width: 1024px)");
// Cache for Nextcloud folders
const foldersCache = useRef<{ folders: string[]; timestamp: number } | null>(null);
useEffect(() => {
const fetchNextcloudFolders = async () => {
// Check cache first
if (foldersCache.current) {
const cacheAge = Date.now() - foldersCache.current.timestamp;
if (cacheAge < 5 * 60 * 1000) { // 5 minutes cache
setNextcloudFolders(foldersCache.current.folders);
return;
}
}
try {
const response = await fetch('/api/nextcloud/status');
if (!response.ok) {
throw new Error('Failed to fetch Nextcloud folders');
}
const data = await response.json();
const folders = data.folders || [];
// Update cache
foldersCache.current = {
folders,
timestamp: Date.now()
};
setNextcloudFolders(folders);
} catch (err) {
console.error('Error fetching Nextcloud folders:', err);
setNextcloudFolders([]);
}
};
if (status === "authenticated") {
fetchNextcloudFolders();
}
}, [status]);
useEffect(() => {
if (status === "unauthenticated") {
redirect("/signin");
}
if (status !== "loading") {
setIsLoading(false);
}
}, [status]);
useEffect(() => {
if (isSmallScreen) {
setIsMobile(true);
setShowNav(false);
setShowNotes(false);
} else if (isMediumScreen) {
setIsMobile(false);
setShowNav(true);
setShowNotes(false);
} else {
setIsMobile(false);
setShowNav(true);
setShowNotes(true);
}
}, [isSmallScreen, isMediumScreen]);
useEffect(() => {
const fetchNotes = async () => {
try {
setIsLoadingNotes(true);
const response = await fetch(`/api/nextcloud/files?folder=${selectedFolder}`);
if (!response.ok) {
throw new Error('Failed to fetch notes');
}
const data = await response.json();
if (selectedFolder === 'Contacts') {
// For contacts, parse the VCF files
const parsedContacts = await Promise.all(
data.map(async (file: any) => {
const contentResponse = await fetch(`/api/nextcloud/files/content?id=${file.filename}`);
if (contentResponse.ok) {
const content = await contentResponse.text();
return parseVCard(content);
}
return null;
})
);
setContacts(parsedContacts.filter(Boolean));
} else {
setNotes(data);
}
} catch (error) {
console.error('Error fetching data:', error);
if (selectedFolder === 'Contacts') {
setContacts([]);
} else {
setNotes([]);
}
} finally {
setIsLoadingNotes(false);
}
};
fetchNotes();
}, [selectedFolder]);
const fetchContacts = async (folder: string) => {
try {
setIsLoadingContacts(true);
const response = await fetch(`/api/nextcloud/files?folder=${folder}`);
if (response.ok) {
const files = await response.json();
const vcfFiles = files.filter((file: any) => file.basename.endsWith('.vcf'));
// Parse VCF files and extract contact information
const parsedContacts = await Promise.all(
vcfFiles.map(async (file: any) => {
const contentResponse = await fetch(`/api/nextcloud/files/content?id=${file.id}`);
if (contentResponse.ok) {
const content = await contentResponse.text();
return parseVCard(content);
}
return null;
})
);
setContacts(parsedContacts.filter(Boolean));
}
} catch (error) {
console.error('Error fetching contacts:', error);
} finally {
setIsLoadingContacts(false);
}
};
const parseVCard = (content: string): Contact => {
const lines = content.split('\n');
const contact: Partial<Contact> = {};
lines.forEach(line => {
if (line.startsWith('FN:')) {
contact.fullName = line.substring(3).trim();
} else if (line.startsWith('EMAIL;')) {
contact.email = line.split(':')[1].trim();
} else if (line.startsWith('TEL;')) {
contact.phone = line.split(':')[1].trim();
} else if (line.startsWith('ORG:')) {
contact.organization = line.substring(4).trim();
} else if (line.startsWith('ADR;')) {
contact.address = line.split(':')[1].trim();
} else if (line.startsWith('NOTE:')) {
contact.notes = line.substring(5).trim();
}
});
return {
id: Math.random().toString(36).substr(2, 9),
fullName: contact.fullName || 'Unknown',
email: contact.email || '',
phone: contact.phone,
organization: contact.organization,
address: contact.address,
notes: contact.notes
} as Contact;
};
useEffect(() => {
if (selectedFolder === 'Contacts') {
fetchContacts(selectedFolder);
}
}, [selectedFolder]);
// Handle panel resizing
const handleNavResize = (e: MouseEvent) => {
if (!isDraggingNav) return;
const newWidth = e.clientX;
if (newWidth >= 48 && newWidth <= 400) {
setNavWidth(newWidth);
}
};
const handleNotesResize = (e: MouseEvent) => {
if (!isDraggingNotes) return;
const newWidth = e.clientX - navWidth - 2; // 2px for the resizer
if (newWidth >= 200) {
setNotesWidth(newWidth);
}
};
const handleNoteSelect = (note: Note) => {
setSelectedNote(note);
if (isMobile) {
setShowNotes(false);
}
};
const handleNoteSave = async (note: Note) => {
try {
const endpoint = note.id ? '/api/nextcloud/files' : '/api/nextcloud/files';
const method = note.id ? 'PUT' : 'POST';
const response = await fetch(endpoint, {
method,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
id: note.id,
title: note.title,
content: note.content,
folder: selectedFolder
}),
});
if (!response.ok) {
throw new Error('Failed to save note');
}
// After successful save, refresh the notes list
const notesResponse = await fetch(`/api/nextcloud/files?folder=${selectedFolder}`);
if (notesResponse.ok) {
const updatedNotes = await notesResponse.json();
setNotes(updatedNotes);
}
} catch (error) {
console.error('Error saving note:', error);
}
};
const handleFolderSelect = (folder: string) => {
console.log('Selected folder:', folder);
setSelectedFolder(folder);
setLayoutMode("item-selection");
// Reset selected contact when changing folders
setSelectedContact(null);
};
const handleContactSelect = (contact: Contact) => {
setSelectedContact(contact);
if (isMobile) {
setShowNotes(false);
}
};
const handleNewNote = () => {
setSelectedNote({
id: '',
title: '',
content: '',
lastModified: new Date().toISOString(),
type: 'file',
mime: 'text/markdown',
etag: ''
});
if (isMobile) {
setShowNotes(false);
}
};
const handleDeleteNote = async (note: Note) => {
try {
const response = await fetch(`/api/nextcloud/files`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
id: note.id,
folder: selectedFolder
}),
});
if (!response.ok) {
throw new Error('Failed to delete note');
}
// Refresh the notes list
const notesResponse = await fetch(`/api/nextcloud/files?folder=${selectedFolder}`);
if (notesResponse.ok) {
const updatedNotes = await notesResponse.json();
setNotes(updatedNotes);
}
// If the deleted note was selected, clear the selection
if (selectedNote?.id === note.id) {
setSelectedNote(null);
}
} catch (error) {
console.error('Error deleting note:', error);
}
};
if (isLoading) {
return (
<div className="flex h-screen items-center justify-center">
<div className="h-32 w-32 animate-spin rounded-full border-t-2 border-b-2 border-gray-900"></div>
</div>
);
}
return (
<main className="w-full h-screen bg-black">
<div className="w-full h-full px-4 pt-12 pb-4">
<div className="flex h-full bg-carnet-bg">
{/* Navigation Panel */}
{showNav && (
<>
<div className="flex-none" style={{ width: navWidth }}>
<Navigation
nextcloudFolders={nextcloudFolders}
onFolderSelect={handleFolderSelect}
/>
</div>
<PanelResizer
isDragging={isDraggingNav}
onDragStart={() => setIsDraggingNav(true)}
onDragEnd={() => setIsDraggingNav(false)}
onDrag={handleNavResize}
/>
</>
)}
{/* Notes/Contacts Panel */}
{showNotes && (
<>
<div className="flex-1 overflow-hidden">
{selectedFolder === 'Contacts' ? (
<ContactsView
contacts={contacts}
onContactSelect={handleContactSelect}
selectedContact={selectedContact}
loading={isLoadingNotes}
/>
) : (
<NotesView
notes={notes}
loading={isLoadingNotes}
onNoteSelect={handleNoteSelect}
currentFolder={selectedFolder}
onNewNote={handleNewNote}
onDeleteNote={handleDeleteNote}
/>
)}
</div>
{/* Notes Resizer */}
<PanelResizer
isDragging={isDraggingNotes}
onDragStart={() => setIsDraggingNotes(true)}
onDragEnd={() => setIsDraggingNotes(false)}
onDrag={handleNotesResize}
/>
</>
)}
{/* Editor Panel */}
<div className="flex-1 overflow-hidden">
<Editor
note={selectedNote}
onSave={handleNoteSave}
currentFolder={selectedFolder}
onRefresh={() => {
// Refresh the notes list
fetch(`/api/nextcloud/files?folder=${selectedFolder}`)
.then(response => response.json())
.then(updatedNotes => {
if (selectedFolder === 'Contacts') {
setContacts(updatedNotes);
} else {
setNotes(updatedNotes);
}
})
.catch(error => console.error('Error refreshing data:', error));
}}
/>
</div>
{/* Mobile Navigation Toggle */}
{isMobile && (
<button
onClick={() => setShowNav(!showNav)}
className="fixed bottom-4 right-4 bg-primary text-white p-3 rounded-full shadow-lg"
>
{showNav ? <X className="h-6 w-6" /> : <Menu className="h-6 w-6" />}
</button>
)}
</div>
</div>
</main>
);
}