carnet panel3

This commit is contained in:
alma 2025-04-20 17:12:26 +02:00
parent cfd217a054
commit 49895eb166
4 changed files with 320 additions and 304 deletions

View File

@ -12,30 +12,6 @@ declare global {
const prisma = global.prisma || new PrismaClient();
if (process.env.NODE_ENV !== 'production') global.prisma = prisma;
// Helper function to create WebDAV client
const createWebDAVClient = async (userId: string) => {
const credentials = await prisma.webDAVCredentials.findUnique({
where: { userId },
});
if (!credentials) {
throw new Error('No WebDAV credentials found');
}
const baseURL = process.env.NEXTCLOUD_URL;
if (!baseURL) {
throw new Error('NEXTCLOUD_URL environment variable is not set');
}
const normalizedBaseURL = baseURL.endsWith('/') ? baseURL.slice(0, -1) : baseURL;
return createClient(`${normalizedBaseURL}/remote.php/dav`, {
username: credentials.username,
password: credentials.password,
authType: 'password',
});
};
export async function GET(
request: Request,
{ params }: { params: { id: string } }
@ -46,9 +22,33 @@ export async function GET(
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const client = await createWebDAVClient(session.user.id);
// Get WebDAV credentials
const credentials = await prisma.webDAVCredentials.findUnique({
where: { userId: session.user.id },
});
if (!credentials) {
console.error('No WebDAV credentials found for user:', session.user.id);
return NextResponse.json({ error: 'No WebDAV credentials found' }, { status: 404 });
}
// Initialize WebDAV client
const baseURL = process.env.NEXTCLOUD_URL;
if (!baseURL) {
throw new Error('NEXTCLOUD_URL environment variable is not set');
}
// Remove trailing slash if present
const normalizedBaseURL = baseURL.endsWith('/') ? baseURL.slice(0, -1) : baseURL;
const client = createClient(`${normalizedBaseURL}/remote.php/dav`, {
username: credentials.username,
password: credentials.password,
authType: 'password',
});
try {
// Get the file content
const content = await client.getFileContents(params.id);
const textContent = content.toString('utf-8');
@ -69,66 +69,4 @@ export async function GET(
}
return NextResponse.json({ error: 'Failed to fetch file' }, { status: 500 });
}
}
export async function POST(
request: Request,
{ params }: { params: { id: string } }
) {
try {
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const { content } = await request.json();
const client = await createWebDAVClient(session.user.id);
try {
await client.putFileContents(params.id, content);
return NextResponse.json({ success: true });
} catch (error) {
console.error('Error saving file content:', error);
return NextResponse.json({ error: 'Failed to save file content' }, { status: 500 });
}
} catch (error) {
console.error('Error saving file:', error);
return NextResponse.json({ error: 'Failed to save file' }, { status: 500 });
}
}
export async function PUT(
request: Request,
{ params }: { params: { id: string } }
) {
try {
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const { title, content, folder } = await request.json();
const client = await createWebDAVClient(session.user.id);
try {
const path = `/files/${client.credentials.username}/Private/${folder}/${title}.md`;
await client.putFileContents(path, content);
return NextResponse.json({
success: true,
id: path,
title,
lastModified: new Date().toISOString(),
size: content.length,
type: 'file',
mime: 'text/markdown',
etag: ''
});
} catch (error) {
console.error('Error creating file:', error);
return NextResponse.json({ error: 'Failed to create file' }, { status: 500 });
}
} catch (error) {
console.error('Error creating file:', error);
return NextResponse.json({ error: 'Failed to create file' }, { status: 500 });
}
}

View File

@ -1,98 +1,234 @@
"use client";
import React, { useState, useEffect } from 'react';
import { FileList } from '@/components/carnet/file-list';
import { Editor } from '@/components/carnet/editor';
import { Plus } from 'lucide-react';
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";
// Layout modes
export enum PaneLayout {
TagSelection = "tag-selection",
ItemSelection = "item-selection",
TableView = "table-view",
Editing = "editing"
}
interface Note {
id: string;
title: string;
lastModified: string;
size: number;
type: string;
mime: string;
etag: string;
content?: string;
content: string;
lastEdited: Date;
}
export default function CarnetPage() {
const [notes, setNotes] = useState<Note[]>([]);
const { data: session, status } = useSession();
const [isLoading, setIsLoading] = useState(true);
const [layoutMode, setLayoutMode] = useState<PaneLayout>(PaneLayout.ItemSelection);
const [selectedNote, setSelectedNote] = useState<Note | null>(null);
const [currentFolder, setCurrentFolder] = useState('Notes');
const [loading, setLoading] = useState(true);
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');
// 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(() => {
fetchNotes();
}, [currentFolder]);
const fetchNotes = async () => {
try {
setLoading(true);
const response = await fetch(`/api/nextcloud/files?folder=${encodeURIComponent(currentFolder)}`);
if (!response.ok) {
throw new Error('Failed to fetch notes');
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;
}
}
const data = await response.json();
setNotes(data);
} catch (err) {
console.error('Error fetching notes:', err);
} finally {
setLoading(false);
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]);
// 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 = (updatedNote: Note) => {
setNotes(prevNotes => {
const index = prevNotes.findIndex(n => n.id === updatedNote.id);
if (index === -1) {
return [...prevNotes, updatedNote];
}
const newNotes = [...prevNotes];
newNotes[index] = updatedNote;
return newNotes;
});
setSelectedNote(updatedNote);
const handleNoteSave = (note: Note) => {
// TODO: Implement note saving logic
console.log('Saving note:', note);
};
const handleNewNote = () => {
setSelectedNote(null);
const handleFolderSelect = (folder: string) => {
console.log('Selected folder:', folder);
setSelectedFolder(folder);
setLayoutMode(PaneLayout.ItemSelection);
};
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 (
<div className="flex h-screen bg-carnet-bg">
{/* Sidebar */}
<div className="w-64 border-r border-carnet-border">
<div className="p-4">
<button
onClick={handleNewNote}
className="w-full flex items-center justify-center space-x-2 px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90"
>
<Plus className="h-4 w-4" />
<span>Nouvelle note</span>
</button>
</div>
<FileList
notes={notes}
onNoteSelect={handleNoteSelect}
currentFolder={currentFolder}
onFolderChange={setCurrentFolder}
loading={loading}
/>
</div>
<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 flex-col h-full bg-carnet-sidebar"
style={{ width: `${navWidth}px` }}
>
<Navigation
layout={layoutMode}
onLayoutChange={setLayoutMode}
nextcloudFolders={nextcloudFolders}
onFolderSelect={handleFolderSelect}
/>
</div>
{/* Editor */}
<div className="flex-1">
<Editor
note={selectedNote}
onSave={handleNoteSave}
currentFolder={currentFolder}
/>
{/* Navigation Resizer */}
<PanelResizer
isDragging={isDraggingNav}
onDragStart={() => setIsDraggingNav(true)}
onDragEnd={() => setIsDraggingNav(false)}
onDrag={handleNavResize}
/>
</>
)}
{/* Notes Panel */}
{showNotes && (
<>
<div
className="flex flex-col h-full bg-carnet-bg"
style={{ width: `${notesWidth}px` }}
>
<NotesView
onNoteSelect={handleNoteSelect}
currentFolder={selectedFolder}
/>
</div>
{/* Notes Resizer */}
<PanelResizer
isDragging={isDraggingNotes}
onDragStart={() => setIsDraggingNotes(true)}
onDragEnd={() => setIsDraggingNotes(false)}
onDrag={handleNotesResize}
/>
</>
)}
{/* Editor Panel */}
<div className="flex-1 flex flex-col h-full bg-carnet-bg">
<Editor note={selectedNote} onSave={handleNoteSave} />
</div>
{/* Mobile Navigation Toggle */}
{isMobile && (
<div className="fixed bottom-4 right-4 flex space-x-2">
<button
className="p-2 rounded-full bg-primary text-white"
onClick={() => setShowNav(!showNav)}
>
{showNav ? 'Hide Nav' : 'Show Nav'}
</button>
<button
className="p-2 rounded-full bg-primary text-white"
onClick={() => setShowNotes(!showNotes)}
>
{showNotes ? 'Hide Notes' : 'Show Notes'}
</button>
</div>
)}
</div>
</div>
</div>
</main>
);
}

View File

@ -1,12 +1,7 @@
"use client";
import React, { useState, useEffect } from 'react';
import { Save } from 'lucide-react';
import dynamic from 'next/dynamic';
// Dynamically import the editor to avoid SSR issues
const ReactQuill = dynamic(() => import('react-quill'), { ssr: false });
import 'react-quill/dist/quill.snow.css';
import { Image, FileText, Link, List } from 'lucide-react';
interface Note {
id: string;
@ -20,92 +15,110 @@ interface Note {
}
interface EditorProps {
note: Note | null;
onSave: (note: Note) => void;
currentFolder: string;
note?: Note | null;
onSave?: (note: Note) => void;
}
export function Editor({ note, onSave, currentFolder }: EditorProps) {
const [content, setContent] = useState('');
const [isSaving, setIsSaving] = useState(false);
const [isLoading, setIsLoading] = useState(false);
export const Editor: React.FC<EditorProps> = ({ note, onSave }) => {
const [title, setTitle] = useState(note?.title || '');
const [content, setContent] = useState(note?.content || '');
const [loading, setLoading] = useState(false);
useEffect(() => {
if (note?.content) {
setIsLoading(true);
setContent(note.content);
setIsLoading(false);
const fetchNoteContent = async () => {
if (note?.id) {
try {
setLoading(true);
const response = await fetch(`/api/nextcloud/files/${encodeURIComponent(note.id)}`);
if (!response.ok) {
throw new Error('Failed to fetch note content');
}
const data = await response.json();
setContent(data.content || '');
} catch (err) {
console.error('Error fetching note content:', err);
} finally {
setLoading(false);
}
}
};
if (note) {
setTitle(note.title);
fetchNoteContent();
} else {
setTitle('');
setContent('');
}
}, [note]);
const handleSave = async () => {
if (!note) return;
setIsSaving(true);
try {
const updatedNote = {
const handleTitleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setTitle(e.target.value);
};
const handleContentChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
setContent(e.target.value);
};
const handleSave = () => {
if (note?.id) {
onSave?.({
...note,
content,
lastModified: new Date().toISOString(),
size: content.length
};
onSave(updatedNote);
} catch (error) {
console.error('Failed to save note:', error);
} finally {
setIsSaving(false);
title,
content
});
}
};
if (isLoading) {
return (
<div className="p-4">
<div className="h-4 w-full bg-gray-200 rounded animate-pulse"></div>
</div>
);
}
if (!note) {
return (
<div className="flex items-center justify-center h-full">
<p className="text-gray-500">Select a note to edit</p>
</div>
);
}
return (
<div className="flex flex-col h-full">
<div className="flex items-center justify-between p-4 border-b">
<h2 className="text-xl font-semibold">{note.title}</h2>
<button
onClick={handleSave}
disabled={isSaving}
className="flex items-center space-x-2 px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 disabled:opacity-50"
>
<Save className="h-4 w-4" />
<span>{isSaving ? 'Saving...' : 'Save'}</span>
</button>
</div>
<div className="flex-1 overflow-y-auto p-4">
<ReactQuill
theme="snow"
value={content}
onChange={setContent}
className="h-full"
modules={{
toolbar: [
[{ header: [1, 2, 3, false] }],
['bold', 'italic', 'underline', 'strike'],
[{ list: 'ordered' }, { list: 'bullet' }],
['link', 'image'],
['clean']
]
}}
<div className="flex flex-col h-full bg-carnet-bg">
{/* Title Bar */}
<div className="p-4 border-b border-carnet-border">
<input
type="text"
value={title}
onChange={handleTitleChange}
placeholder="Titre"
className="w-full text-xl font-semibold text-carnet-text-primary placeholder-carnet-text-muted focus:outline-none bg-transparent"
/>
</div>
{/* Toolbar */}
<div className="px-4 py-2 border-b border-carnet-border">
<div className="flex space-x-1">
<button className="p-1.5 rounded hover:bg-carnet-hover">
<List className="h-4 w-4 text-carnet-text-muted" />
</button>
<button className="p-1.5 rounded hover:bg-carnet-hover">
<Link className="h-4 w-4 text-carnet-text-muted" />
</button>
<button className="p-1.5 rounded hover:bg-carnet-hover">
<Image className="h-4 w-4 text-carnet-text-muted" />
</button>
<button
className="p-1.5 rounded hover:bg-carnet-hover"
onClick={handleSave}
>
<FileText className="h-4 w-4 text-carnet-text-muted" />
</button>
</div>
</div>
{/* Editor Area */}
<div className="flex-1 p-4">
{loading ? (
<div className="flex items-center justify-center h-full">
<div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-primary"></div>
</div>
) : (
<textarea
value={content}
onChange={handleContentChange}
placeholder="Ecrire..."
className="w-full h-full resize-none focus:outline-none bg-transparent text-carnet-text-primary placeholder-carnet-text-muted"
/>
)}
</div>
</div>
);
}
};

View File

@ -1,71 +0,0 @@
"use client";
import React from 'react';
import { Folder, File } from 'lucide-react';
interface Note {
id: string;
title: string;
lastModified: string;
size: number;
type: string;
mime: string;
etag: string;
content?: string;
}
interface FileListProps {
notes: Note[];
onNoteSelect: (note: Note) => void;
currentFolder: string;
onFolderChange: (folder: string) => void;
loading: boolean;
}
export function FileList({ notes, onNoteSelect, currentFolder, onFolderChange, loading }: FileListProps) {
const folders = ['Notes', 'Diary', 'Health', 'Contacts'];
if (loading) {
return (
<div className="p-4">
<div className="h-4 w-full bg-gray-200 rounded animate-pulse"></div>
</div>
);
}
return (
<div className="flex flex-col h-full">
{/* Folders */}
<div className="p-4 space-y-2">
{folders.map((folder) => (
<button
key={folder}
onClick={() => onFolderChange(folder)}
className={`w-full flex items-center space-x-2 px-4 py-2 rounded-lg ${
currentFolder === folder
? 'bg-primary/10 text-primary'
: 'hover:bg-gray-100'
}`}
>
<Folder className="h-4 w-4" />
<span>{folder}</span>
</button>
))}
</div>
{/* Notes */}
<div className="flex-1 overflow-y-auto p-4 space-y-2">
{notes.map((note) => (
<button
key={note.id}
onClick={() => onNoteSelect(note)}
className="w-full flex items-center space-x-2 px-4 py-2 rounded-lg hover:bg-gray-100"
>
<File className="h-4 w-4" />
<span className="truncate">{note.title}</span>
</button>
))}
</div>
</div>
);
}