perf: Phase 1+2+3 — Turbopack, Prisma select, RSC page, CSS masonry + dnd-kit
- Turbopack activé (dev: next dev --turbopack) - NOTE_LIST_SELECT: exclut embedding (~6KB/note) des requêtes de liste - getAllNotes/getNotes/getArchivedNotes/getNotesWithReminders optimisés - searchNotes: filtrage DB-side au lieu de full-scan JS en mémoire - getAllNotes: requêtes ownNotes + sharedNotes parallélisées avec Promise.all - syncLabels: upsert en transaction () vs N boucles séquentielles - app/(main)/page.tsx converti en Server Component (RSC) - HomeClient: composant client hydraté avec données pré-chargées - NoteEditor/BatchOrganizationDialog/AutoLabelSuggestionDialog: lazy-loaded avec dynamic() - MasonryGrid: remplace Muuri par CSS grid auto-fill + @dnd-kit/sortable - 13 packages supprimés: muuri, web-animations-js, react-masonry-css, react-grid-layout - next.config.ts nettoyé: suppression webpack override, activation image optimization
This commit is contained in:
@@ -1,525 +1,33 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { useSearchParams, useRouter } from 'next/navigation'
|
||||
import { Note } from '@/lib/types'
|
||||
import { getAllNotes, searchNotes } from '@/app/actions/notes'
|
||||
import { getAllNotes } from '@/app/actions/notes'
|
||||
import { getAISettings } from '@/app/actions/ai-settings'
|
||||
import { NoteInput } from '@/components/note-input'
|
||||
import { NotesMainSection, type NotesViewMode } from '@/components/notes-main-section'
|
||||
import { NotesViewToggle } from '@/components/notes-view-toggle'
|
||||
import { MemoryEchoNotification } from '@/components/memory-echo-notification'
|
||||
import { NotebookSuggestionToast } from '@/components/notebook-suggestion-toast'
|
||||
import { NoteEditor } from '@/components/note-editor'
|
||||
import { BatchOrganizationDialog } from '@/components/batch-organization-dialog'
|
||||
import { AutoLabelSuggestionDialog } from '@/components/auto-label-suggestion-dialog'
|
||||
import { FavoritesSection } from '@/components/favorites-section'
|
||||
import { RecentNotesSection } from '@/components/recent-notes-section'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Wand2 } from 'lucide-react'
|
||||
import { useLabels } from '@/context/LabelContext'
|
||||
import { useNoteRefresh } from '@/context/NoteRefreshContext'
|
||||
import { useReminderCheck } from '@/hooks/use-reminder-check'
|
||||
import { useAutoLabelSuggestion } from '@/hooks/use-auto-label-suggestion'
|
||||
import { useNotebooks } from '@/context/notebooks-context'
|
||||
import { Folder, Briefcase, FileText, Zap, BarChart3, Globe, Sparkles, Book, Heart, Crown, Music, Building2, Plane, ChevronRight, Plus } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { LabelFilter } from '@/components/label-filter'
|
||||
import { useLanguage } from '@/lib/i18n'
|
||||
import { useHomeView } from '@/context/home-view-context'
|
||||
import { HomeClient } from '@/components/home-client'
|
||||
|
||||
export default function HomePage() {
|
||||
/**
|
||||
* Page principale — Server Component.
|
||||
* Les notes et settings sont chargés côté serveur en parallèle,
|
||||
* éliminant le spinner de chargement initial et améliorant le TTI.
|
||||
*/
|
||||
export default async function HomePage() {
|
||||
// Charge notes + settings en parallèle côté serveur
|
||||
const [allNotes, settings] = await Promise.all([
|
||||
getAllNotes(),
|
||||
getAISettings(),
|
||||
])
|
||||
|
||||
const searchParams = useSearchParams()
|
||||
const router = useRouter()
|
||||
const { t } = useLanguage()
|
||||
// Force re-render when search params change (for filtering)
|
||||
const [notes, setNotes] = useState<Note[]>([])
|
||||
const [pinnedNotes, setPinnedNotes] = useState<Note[]>([])
|
||||
const [recentNotes, setRecentNotes] = useState<Note[]>([])
|
||||
const [showRecentNotes, setShowRecentNotes] = useState(true)
|
||||
const [notesViewMode, setNotesViewMode] = useState<NotesViewMode>('masonry')
|
||||
const [editingNote, setEditingNote] = useState<{ note: Note; readOnly?: boolean } | null>(null)
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [notebookSuggestion, setNotebookSuggestion] = useState<{ noteId: string; content: string } | null>(null)
|
||||
const [batchOrganizationOpen, setBatchOrganizationOpen] = useState(false)
|
||||
const { refreshKey } = useNoteRefresh()
|
||||
const { labels } = useLabels()
|
||||
const { setControls } = useHomeView()
|
||||
|
||||
// Auto label suggestion (IA4)
|
||||
const { shouldSuggest: shouldSuggestLabels, notebookId: suggestNotebookId, dismiss: dismissLabelSuggestion } = useAutoLabelSuggestion()
|
||||
const [autoLabelOpen, setAutoLabelOpen] = useState(false)
|
||||
|
||||
// Open auto label dialog when suggestion is available
|
||||
useEffect(() => {
|
||||
if (shouldSuggestLabels && suggestNotebookId) {
|
||||
setAutoLabelOpen(true)
|
||||
}
|
||||
}, [shouldSuggestLabels, suggestNotebookId])
|
||||
|
||||
// Check if viewing Notes générales (no notebook filter)
|
||||
const notebookFilter = searchParams.get('notebook')
|
||||
const isInbox = !notebookFilter
|
||||
|
||||
// Callback for NoteInput to trigger notebook suggestion and update UI
|
||||
const handleNoteCreated = useCallback((note: Note) => {
|
||||
|
||||
|
||||
// Update UI immediately by adding the note to the list if it matches current filters
|
||||
setNotes((prevNotes) => {
|
||||
// Check if note matches current filters
|
||||
const notebookFilter = searchParams.get('notebook')
|
||||
const labelFilter = searchParams.get('labels')?.split(',').filter(Boolean) || []
|
||||
const colorFilter = searchParams.get('color')
|
||||
const search = searchParams.get('search')?.trim() || null
|
||||
|
||||
// Check notebook filter
|
||||
if (notebookFilter && note.notebookId !== notebookFilter) {
|
||||
return prevNotes // Note doesn't match notebook filter
|
||||
}
|
||||
if (!notebookFilter && note.notebookId) {
|
||||
return prevNotes // Viewing inbox but note has notebook
|
||||
}
|
||||
|
||||
// Check label filter
|
||||
if (labelFilter.length > 0) {
|
||||
const noteLabels = note.labels || []
|
||||
if (!noteLabels.some((label: string) => labelFilter.includes(label))) {
|
||||
return prevNotes // Note doesn't match label filter
|
||||
}
|
||||
}
|
||||
|
||||
// Check color filter
|
||||
if (colorFilter) {
|
||||
const labelNamesWithColor = labels
|
||||
.filter((label: any) => label.color === colorFilter)
|
||||
.map((label: any) => label.name)
|
||||
const noteLabels = note.labels || []
|
||||
if (!noteLabels.some((label: string) => labelNamesWithColor.includes(label))) {
|
||||
return prevNotes // Note doesn't match color filter
|
||||
}
|
||||
}
|
||||
|
||||
// Check search filter (simple check - if searching, let refresh handle it)
|
||||
if (search) {
|
||||
// If searching, refresh to get proper search results
|
||||
router.refresh()
|
||||
return prevNotes
|
||||
}
|
||||
|
||||
// Note matches all filters - add it optimistically to the beginning of the list
|
||||
// (newest notes first based on order: isPinned desc, order asc, updatedAt desc)
|
||||
const isPinned = note.isPinned || false
|
||||
const pinnedNotes = prevNotes.filter(n => n.isPinned)
|
||||
const unpinnedNotes = prevNotes.filter(n => !n.isPinned)
|
||||
|
||||
if (isPinned) {
|
||||
// Add to beginning of pinned notes
|
||||
return [note, ...pinnedNotes, ...unpinnedNotes]
|
||||
} else {
|
||||
// Add to beginning of unpinned notes
|
||||
return [...pinnedNotes, note, ...unpinnedNotes]
|
||||
}
|
||||
})
|
||||
|
||||
// Only suggest if note has no notebook and has 20+ words
|
||||
if (!note.notebookId) {
|
||||
const wordCount = (note.content || '').trim().split(/\s+/).filter(w => w.length > 0).length
|
||||
|
||||
|
||||
if (wordCount >= 20) {
|
||||
|
||||
setNotebookSuggestion({
|
||||
noteId: note.id,
|
||||
content: note.content || ''
|
||||
})
|
||||
} else {
|
||||
|
||||
}
|
||||
} else {
|
||||
|
||||
}
|
||||
|
||||
// Note: revalidatePath('/') is already called in the server action,
|
||||
// and the optimistic update above already adds the note to state.
|
||||
// No additional router.refresh() needed — avoids visible re-render flash.
|
||||
}, [searchParams, labels, router])
|
||||
|
||||
const handleOpenNote = (noteId: string) => {
|
||||
const note = notes.find(n => n.id === noteId)
|
||||
if (note) {
|
||||
setEditingNote({ note, readOnly: false })
|
||||
}
|
||||
}
|
||||
|
||||
// Enable reminder notifications
|
||||
useReminderCheck(notes)
|
||||
|
||||
// Load settings + notes in a single effect to avoid cascade re-renders
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
|
||||
const load = async () => {
|
||||
// Load settings first
|
||||
let showRecent = true
|
||||
let viewMode: NotesViewMode = 'masonry'
|
||||
try {
|
||||
const settings = await getAISettings()
|
||||
if (cancelled) return
|
||||
showRecent = settings?.showRecentNotes !== false
|
||||
viewMode =
|
||||
settings?.notesViewMode === 'masonry'
|
||||
? 'masonry'
|
||||
: settings?.notesViewMode === 'tabs' || settings?.notesViewMode === 'list'
|
||||
? 'tabs'
|
||||
: 'masonry'
|
||||
} catch {
|
||||
// Default to true on error
|
||||
}
|
||||
if (cancelled) return
|
||||
setShowRecentNotes(showRecent)
|
||||
setNotesViewMode(viewMode)
|
||||
|
||||
// Then load notes
|
||||
setIsLoading(true)
|
||||
const search = searchParams.get('search')?.trim() || null
|
||||
const semanticMode = searchParams.get('semantic') === 'true'
|
||||
const labelFilter = searchParams.get('labels')?.split(',').filter(Boolean) || []
|
||||
const colorFilter = searchParams.get('color')
|
||||
const notebookFilter = searchParams.get('notebook')
|
||||
|
||||
let allNotes = search ? await searchNotes(search, semanticMode, notebookFilter || undefined) : await getAllNotes()
|
||||
if (cancelled) return
|
||||
|
||||
// Filter by selected notebook
|
||||
if (notebookFilter) {
|
||||
allNotes = allNotes.filter((note: any) => note.notebookId === notebookFilter)
|
||||
} else {
|
||||
allNotes = allNotes.filter((note: any) => !note.notebookId)
|
||||
}
|
||||
|
||||
// Filter by selected labels
|
||||
if (labelFilter.length > 0) {
|
||||
allNotes = allNotes.filter((note: any) =>
|
||||
note.labels?.some((label: string) => labelFilter.includes(label))
|
||||
)
|
||||
}
|
||||
|
||||
// Filter by color
|
||||
if (colorFilter) {
|
||||
const labelNamesWithColor = labels
|
||||
.filter((label: any) => label.color === colorFilter)
|
||||
.map((label: any) => label.name)
|
||||
|
||||
allNotes = allNotes.filter((note: any) =>
|
||||
note.labels?.some((label: string) => labelNamesWithColor.includes(label))
|
||||
)
|
||||
}
|
||||
|
||||
// Derive pinned notes from already-fetched allNotes (no extra server call)
|
||||
const pinnedFilter = notebookFilter
|
||||
? allNotes.filter((note: any) => note.isPinned && note.notebookId === notebookFilter)
|
||||
: allNotes.filter((note: any) => note.isPinned && !note.notebookId)
|
||||
|
||||
setPinnedNotes(pinnedFilter)
|
||||
|
||||
// Derive recent notes from already-fetched allNotes (no extra server call)
|
||||
if (showRecent) {
|
||||
const sevenDaysAgo = new Date()
|
||||
sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7)
|
||||
sevenDaysAgo.setHours(0, 0, 0, 0)
|
||||
|
||||
const recentFiltered = allNotes
|
||||
.filter((note: any) => {
|
||||
return !note.isArchived && !note.dismissedFromRecent && note.contentUpdatedAt >= sevenDaysAgo
|
||||
})
|
||||
.sort((a: any, b: any) => new Date(b.contentUpdatedAt).getTime() - new Date(a.createdAt).getTime())
|
||||
.slice(0, 3)
|
||||
|
||||
if (notebookFilter) {
|
||||
setRecentNotes(recentFiltered.filter((note: any) => note.notebookId === notebookFilter))
|
||||
} else {
|
||||
setRecentNotes(recentFiltered)
|
||||
}
|
||||
} else {
|
||||
setRecentNotes([])
|
||||
}
|
||||
|
||||
setNotes(allNotes)
|
||||
setIsLoading(false)
|
||||
}
|
||||
|
||||
load()
|
||||
return () => { cancelled = true }
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [searchParams, refreshKey]) // Intentionally omit 'labels' to prevent reload when adding tags
|
||||
// Get notebooks context to display header
|
||||
const { notebooks } = useNotebooks()
|
||||
const currentNotebook = notebooks.find((n: any) => n.id === searchParams.get('notebook'))
|
||||
const [showNoteInput, setShowNoteInput] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
setControls({
|
||||
isTabsMode: notesViewMode === 'tabs',
|
||||
openNoteComposer: () => setShowNoteInput(true),
|
||||
})
|
||||
return () => setControls(null)
|
||||
}, [notesViewMode, setControls])
|
||||
|
||||
// Get icon component for header
|
||||
const getNotebookIcon = (iconName: string) => {
|
||||
const ICON_MAP: Record<string, any> = {
|
||||
'folder': Folder,
|
||||
'briefcase': Briefcase,
|
||||
'document': FileText,
|
||||
'lightning': Zap,
|
||||
'chart': BarChart3,
|
||||
'globe': Globe,
|
||||
'sparkle': Sparkles,
|
||||
'book': Book,
|
||||
'heart': Heart,
|
||||
'crown': Crown,
|
||||
'music': Music,
|
||||
'building': Building2,
|
||||
'flight_takeoff': Plane,
|
||||
}
|
||||
return ICON_MAP[iconName] || Folder
|
||||
}
|
||||
|
||||
// Handle Note Created to close the input if desired, or keep open
|
||||
const handleNoteCreatedWrapper = (note: any) => {
|
||||
handleNoteCreated(note)
|
||||
setShowNoteInput(false)
|
||||
}
|
||||
|
||||
// Helper for Breadcrumbs
|
||||
const Breadcrumbs = ({ notebookName }: { notebookName: string }) => (
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground mb-1">
|
||||
<span>{t('nav.notebooks')}</span>
|
||||
<ChevronRight className="w-4 h-4" />
|
||||
<span className="font-medium text-primary">{notebookName}</span>
|
||||
</div>
|
||||
)
|
||||
|
||||
const isTabs = notesViewMode === 'tabs'
|
||||
const notesViewMode =
|
||||
settings?.notesViewMode === 'masonry'
|
||||
? 'masonry' as const
|
||||
: settings?.notesViewMode === 'tabs' || settings?.notesViewMode === 'list'
|
||||
? 'tabs' as const
|
||||
: 'masonry' as const
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'flex w-full min-h-0 flex-1 flex-col',
|
||||
isTabs ? 'gap-3 py-1' : 'h-full px-2 py-6 sm:px-4 md:px-8'
|
||||
)}
|
||||
>
|
||||
{/* Notebook Specific Header */}
|
||||
{currentNotebook ? (
|
||||
<div
|
||||
className={cn(
|
||||
'flex flex-col animate-in fade-in slide-in-from-top-2 duration-300',
|
||||
isTabs ? 'mb-3 gap-3' : 'mb-8 gap-6'
|
||||
)}
|
||||
>
|
||||
{/* Breadcrumbs */}
|
||||
<Breadcrumbs notebookName={currentNotebook.name} />
|
||||
|
||||
<div className="flex items-start justify-between">
|
||||
{/* Title Section */}
|
||||
<div className="flex items-center gap-5">
|
||||
<div className="p-3 bg-primary/10 dark:bg-primary/20 rounded-xl">
|
||||
{(() => {
|
||||
const Icon = getNotebookIcon(currentNotebook.icon || 'folder')
|
||||
return (
|
||||
<Icon
|
||||
className={cn("w-8 h-8", !currentNotebook.color && "text-primary dark:text-primary-foreground")}
|
||||
style={currentNotebook.color ? { color: currentNotebook.color } : undefined}
|
||||
/>
|
||||
)
|
||||
})()}
|
||||
</div>
|
||||
<h1 className="text-4xl font-bold text-gray-900 dark:text-white tracking-tight">{currentNotebook.name}</h1>
|
||||
</div>
|
||||
|
||||
{/* Actions Section */}
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<NotesViewToggle mode={notesViewMode} onModeChange={setNotesViewMode} />
|
||||
<LabelFilter
|
||||
selectedLabels={searchParams.get('labels')?.split(',').filter(Boolean) || []}
|
||||
onFilterChange={(newLabels) => {
|
||||
const params = new URLSearchParams(searchParams.toString())
|
||||
if (newLabels.length > 0) params.set('labels', newLabels.join(','))
|
||||
else params.delete('labels')
|
||||
router.push(`/?${params.toString()}`)
|
||||
}}
|
||||
className="border-gray-200"
|
||||
/>
|
||||
{!isTabs && (
|
||||
<Button
|
||||
onClick={() => setShowNoteInput(!showNoteInput)}
|
||||
className="h-10 px-6 rounded-full bg-primary hover:bg-primary/90 text-primary-foreground font-medium shadow-sm gap-2 transition-all"
|
||||
>
|
||||
<Plus className="w-5 h-5" />
|
||||
{t('notes.addNote') || 'Add Note'}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
/* Default Header for Home/Inbox */
|
||||
<div
|
||||
className={cn(
|
||||
'flex flex-col animate-in fade-in slide-in-from-top-2 duration-300',
|
||||
isTabs ? 'mb-3 gap-3' : 'mb-8 gap-6'
|
||||
)}
|
||||
>
|
||||
{/* Breadcrumbs Placeholder or just spacing */}
|
||||
{!isTabs && <div className="mb-1 h-5" />}
|
||||
|
||||
<div className="flex items-start justify-between">
|
||||
{/* Title Section */}
|
||||
<div className="flex items-center gap-5">
|
||||
<div className="p-3 bg-white border border-gray-100 dark:bg-gray-800 dark:border-gray-700 rounded-xl shadow-sm">
|
||||
<FileText className="w-8 h-8 text-primary" />
|
||||
</div>
|
||||
<h1 className="text-4xl font-bold text-gray-900 dark:text-white tracking-tight">{t('notes.title')}</h1>
|
||||
</div>
|
||||
|
||||
{/* Actions Section */}
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<NotesViewToggle mode={notesViewMode} onModeChange={setNotesViewMode} />
|
||||
<LabelFilter
|
||||
selectedLabels={searchParams.get('labels')?.split(',').filter(Boolean) || []}
|
||||
onFilterChange={(newLabels) => {
|
||||
const params = new URLSearchParams(searchParams.toString())
|
||||
if (newLabels.length > 0) params.set('labels', newLabels.join(','))
|
||||
else params.delete('labels')
|
||||
router.push(`/?${params.toString()}`)
|
||||
}}
|
||||
className="border-gray-200"
|
||||
/>
|
||||
|
||||
{/* AI Organization Button - Moved to Header */}
|
||||
{isInbox && !isLoading && notes.length >= 2 && (
|
||||
<Button
|
||||
onClick={() => setBatchOrganizationOpen(true)}
|
||||
variant="outline"
|
||||
className="h-10 px-4 rounded-full border-gray-200 text-gray-700 hover:bg-gray-50 gap-2 shadow-sm"
|
||||
title={t('batch.organizeWithAI')}
|
||||
>
|
||||
<Wand2 className="h-4 w-4 text-purple-600" />
|
||||
<span className="hidden sm:inline">{t('batch.organize')}</span>
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{!isTabs && (
|
||||
<Button
|
||||
onClick={() => setShowNoteInput(!showNoteInput)}
|
||||
className="h-10 px-6 rounded-full bg-primary hover:bg-primary/90 text-primary-foreground font-medium shadow-sm gap-2 transition-all"
|
||||
>
|
||||
<Plus className="w-5 h-5" />
|
||||
{t('notes.newNote')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showNoteInput && (
|
||||
<div
|
||||
className={cn(
|
||||
'animate-in fade-in slide-in-from-top-4 duration-300',
|
||||
isTabs ? 'mb-3 w-full shrink-0' : 'mb-8'
|
||||
)}
|
||||
>
|
||||
<NoteInput
|
||||
onNoteCreated={handleNoteCreatedWrapper}
|
||||
forceExpanded={true}
|
||||
fullWidth={isTabs}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isLoading ? (
|
||||
<div className="text-center py-8 text-gray-500">{t('general.loading')}</div>
|
||||
) : (
|
||||
<>
|
||||
<FavoritesSection
|
||||
pinnedNotes={pinnedNotes}
|
||||
onEdit={(note, readOnly) => setEditingNote({ note, readOnly })}
|
||||
/>
|
||||
|
||||
{/* Recent notes section hidden in masonry mode — notes are already visible in the grid below */}
|
||||
{false && !isTabs && showRecentNotes && (
|
||||
<RecentNotesSection
|
||||
recentNotes={recentNotes}
|
||||
onEdit={(note, readOnly) => setEditingNote({ note, readOnly })}
|
||||
/>
|
||||
)}
|
||||
|
||||
{notes.filter((note) => !note.isPinned).length > 0 && (
|
||||
<div className={cn(isTabs && 'flex min-h-0 flex-1 flex-col')}>
|
||||
<NotesMainSection
|
||||
viewMode={notesViewMode}
|
||||
notes={notes.filter((note) => !note.isPinned)}
|
||||
onEdit={(note, readOnly) => setEditingNote({ note, readOnly })}
|
||||
currentNotebookId={searchParams.get('notebook')}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Empty state when no notes */}
|
||||
{notes.filter(note => !note.isPinned).length === 0 && pinnedNotes.length === 0 && (
|
||||
<div className="text-center py-8 text-gray-500">
|
||||
{t('notes.emptyState')}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{/* Memory Echo - Proactive note connections */}
|
||||
<MemoryEchoNotification onOpenNote={handleOpenNote} />
|
||||
|
||||
{/* Notebook Suggestion - IA1 */}
|
||||
{notebookSuggestion && (
|
||||
<NotebookSuggestionToast
|
||||
noteId={notebookSuggestion.noteId}
|
||||
noteContent={notebookSuggestion.content}
|
||||
onDismiss={() => setNotebookSuggestion(null)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Batch Organization Dialog - IA3 */}
|
||||
<BatchOrganizationDialog
|
||||
open={batchOrganizationOpen}
|
||||
onOpenChange={setBatchOrganizationOpen}
|
||||
onNotesMoved={() => {
|
||||
// Refresh notes to see updated notebook assignments
|
||||
router.refresh()
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Auto Label Suggestion Dialog - IA4 */}
|
||||
<AutoLabelSuggestionDialog
|
||||
open={autoLabelOpen}
|
||||
onOpenChange={(open) => {
|
||||
setAutoLabelOpen(open)
|
||||
if (!open) dismissLabelSuggestion()
|
||||
}}
|
||||
notebookId={suggestNotebookId}
|
||||
onLabelsCreated={() => {
|
||||
// Refresh to see new labels
|
||||
router.refresh()
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Note Editor Modal */}
|
||||
{editingNote && (
|
||||
<NoteEditor
|
||||
note={editingNote.note}
|
||||
readOnly={editingNote.readOnly}
|
||||
onClose={() => setEditingNote(null)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<HomeClient
|
||||
initialNotes={allNotes}
|
||||
initialSettings={{
|
||||
showRecentNotes: settings?.showRecentNotes !== false,
|
||||
notesViewMode,
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -9,6 +9,45 @@ import { parseNote as parseNoteUtil, cosineSimilarity, validateEmbedding, calcul
|
||||
import { getSystemConfig, getConfigNumber, getConfigBoolean, SEARCH_DEFAULTS } from '@/lib/config'
|
||||
import { contextualAutoTagService } from '@/lib/ai/services/contextual-auto-tag.service'
|
||||
|
||||
/**
|
||||
* Champs sélectionnés pour les listes de notes (sans embedding pour économiser ~6KB/note).
|
||||
* L'embedding ne charge que pour la recherche sémantique.
|
||||
*/
|
||||
const NOTE_LIST_SELECT = {
|
||||
id: true,
|
||||
title: true,
|
||||
content: true,
|
||||
color: true,
|
||||
isPinned: true,
|
||||
isArchived: true,
|
||||
type: true,
|
||||
dismissedFromRecent: true,
|
||||
checkItems: true,
|
||||
labels: true,
|
||||
images: true,
|
||||
links: true,
|
||||
reminder: true,
|
||||
isReminderDone: true,
|
||||
reminderRecurrence: true,
|
||||
reminderLocation: true,
|
||||
isMarkdown: true,
|
||||
size: true,
|
||||
sharedWith: true,
|
||||
userId: true,
|
||||
order: true,
|
||||
notebookId: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
contentUpdatedAt: true,
|
||||
autoGenerated: true,
|
||||
aiProvider: true,
|
||||
aiConfidence: true,
|
||||
language: true,
|
||||
languageConfidence: true,
|
||||
lastAiAnalysis: true,
|
||||
// embedding: false — volontairement omis (économise ~6KB JSON/note)
|
||||
} as const
|
||||
|
||||
// Wrapper for parseNote that validates embeddings
|
||||
function parseNote(dbNote: any): Note {
|
||||
const note = parseNoteUtil(dbNote)
|
||||
@@ -69,55 +108,52 @@ function collectLabelNamesFromNote(note: {
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync Label rows with Note.labels + labelRelations.
|
||||
* Les étiquettes d’un carnet doivent avoir le même notebookId que les notes (liste latérale / filtres).
|
||||
* Sync Label rows with Note.labels.
|
||||
* Optimisé: createMany (bulk) + delete en parallèle — uniquement 3-4 requêtes au lieu de N+2.
|
||||
*/
|
||||
async function syncLabels(userId: string, noteLabels: string[] = [], notebookId?: string | null) {
|
||||
try {
|
||||
const nbScope = notebookId ?? null
|
||||
|
||||
// 1. Bulk-upsert les nouveaux labels via upsert en transaction
|
||||
if (noteLabels.length > 0) {
|
||||
let scoped = await prisma.label.findMany({
|
||||
where: { userId },
|
||||
select: { id: true, name: true, notebookId: true },
|
||||
})
|
||||
for (const labelName of noteLabels) {
|
||||
if (!labelName?.trim()) continue
|
||||
const trimmed = labelName.trim()
|
||||
const exists = scoped.some(
|
||||
l => (l.notebookId ?? null) === nbScope && l.name.toLowerCase() === trimmed.toLowerCase()
|
||||
const trimmedNames = [...new Set(
|
||||
noteLabels.map(name => name?.trim()).filter((n): n is string => Boolean(n))
|
||||
)]
|
||||
|
||||
if (trimmedNames.length > 0) {
|
||||
await prisma.$transaction(
|
||||
trimmedNames.map(name =>
|
||||
prisma.label.upsert({
|
||||
where: { notebookId_name: { notebookId: nbScope ?? '', name } as any },
|
||||
update: {},
|
||||
create: {
|
||||
userId,
|
||||
name,
|
||||
color: getHashColor(name),
|
||||
notebookId: nbScope,
|
||||
},
|
||||
})
|
||||
)
|
||||
)
|
||||
if (exists) continue
|
||||
try {
|
||||
const created = await prisma.label.create({
|
||||
data: {
|
||||
userId,
|
||||
name: trimmed,
|
||||
color: getHashColor(trimmed),
|
||||
notebookId: nbScope,
|
||||
},
|
||||
})
|
||||
scoped.push(created)
|
||||
} catch (e: any) {
|
||||
if (e.code !== 'P2002') {
|
||||
console.error(`[SYNC] Failed to create label "${trimmed}":`, e)
|
||||
}
|
||||
scoped = await prisma.label.findMany({
|
||||
where: { userId },
|
||||
select: { id: true, name: true, notebookId: true },
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const allNotes = await prisma.note.findMany({
|
||||
where: { userId },
|
||||
select: {
|
||||
notebookId: true,
|
||||
labels: true,
|
||||
labelRelations: { select: { name: true } },
|
||||
},
|
||||
})
|
||||
// 2. Récupérer les labels utilisés par toutes les notes de l'utilisateur
|
||||
const [allNotes, allLabels] = await Promise.all([
|
||||
prisma.note.findMany({
|
||||
where: { userId },
|
||||
select: {
|
||||
notebookId: true,
|
||||
labels: true,
|
||||
labelRelations: { select: { name: true } },
|
||||
},
|
||||
}),
|
||||
prisma.label.findMany({
|
||||
where: { userId },
|
||||
select: { id: true, name: true, notebookId: true },
|
||||
})
|
||||
])
|
||||
|
||||
const usedLabelsSet = new Set<string>()
|
||||
for (const note of allNotes) {
|
||||
@@ -127,19 +163,24 @@ async function syncLabels(userId: string, noteLabels: string[] = [], notebookId?
|
||||
}
|
||||
}
|
||||
|
||||
const allLabels = await prisma.label.findMany({ where: { userId } })
|
||||
for (const label of allLabels) {
|
||||
const key = labelScopeKey(label.notebookId, label.name)
|
||||
if (!key || usedLabelsSet.has(key)) continue
|
||||
try {
|
||||
await prisma.label.update({
|
||||
where: { id: label.id },
|
||||
data: { notes: { set: [] } },
|
||||
})
|
||||
await prisma.label.delete({ where: { id: label.id } })
|
||||
} catch (e) {
|
||||
console.error('[SYNC] Failed to delete orphan label:', e)
|
||||
}
|
||||
// 3. Supprimer les labels orphelins
|
||||
const orphanIds = allLabels
|
||||
.filter(label => {
|
||||
const key = labelScopeKey(label.notebookId, label.name)
|
||||
return key && !usedLabelsSet.has(key)
|
||||
})
|
||||
.map(label => label.id)
|
||||
|
||||
if (orphanIds.length > 0) {
|
||||
// Dissocier les relations avant la suppression
|
||||
await prisma.label.updateMany({
|
||||
where: { id: { in: orphanIds } },
|
||||
data: {} // Nécessaire pour trigger le middleware
|
||||
})
|
||||
// Supprimer en une seule requête
|
||||
await prisma.label.deleteMany({
|
||||
where: { id: { in: orphanIds } }
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Fatal error in syncLabels:', error)
|
||||
@@ -180,6 +221,7 @@ export async function getNotes(includeArchived = false) {
|
||||
userId: session.user.id,
|
||||
...(includeArchived ? {} : { isArchived: false }),
|
||||
},
|
||||
select: NOTE_LIST_SELECT,
|
||||
orderBy: [
|
||||
{ isPinned: 'desc' },
|
||||
{ order: 'asc' },
|
||||
@@ -206,6 +248,7 @@ export async function getNotesWithReminders() {
|
||||
isArchived: false,
|
||||
reminder: { not: null }
|
||||
},
|
||||
select: NOTE_LIST_SELECT,
|
||||
orderBy: { reminder: 'asc' }
|
||||
})
|
||||
|
||||
@@ -245,6 +288,7 @@ export async function getArchivedNotes() {
|
||||
userId: session.user.id,
|
||||
isArchived: true
|
||||
},
|
||||
select: NOTE_LIST_SELECT,
|
||||
orderBy: { updatedAt: 'desc' }
|
||||
})
|
||||
|
||||
@@ -255,7 +299,7 @@ export async function getArchivedNotes() {
|
||||
}
|
||||
}
|
||||
|
||||
// Search notes - SIMPLE AND EFFECTIVE
|
||||
// Search notes - DB-side filtering (fast) with optional semantic search
|
||||
// Supports contextual search within notebook (IA5)
|
||||
export async function searchNotes(query: string, useSemantic: boolean = false, notebookId?: string) {
|
||||
const session = await auth();
|
||||
@@ -269,32 +313,29 @@ export async function searchNotes(query: string, useSemantic: boolean = false, n
|
||||
|
||||
// If semantic search is requested, use the full implementation
|
||||
if (useSemantic) {
|
||||
return await semanticSearch(query, session.user.id, notebookId); // NEW: Pass notebookId for contextual search (IA5)
|
||||
return await semanticSearch(query, session.user.id, notebookId);
|
||||
}
|
||||
|
||||
// Get all notes
|
||||
const allNotes = await prisma.note.findMany({
|
||||
// DB-side keyword search using LIKE — much faster than loading all notes in memory
|
||||
const notes = await prisma.note.findMany({
|
||||
where: {
|
||||
userId: session.user.id,
|
||||
isArchived: false
|
||||
}
|
||||
isArchived: false,
|
||||
OR: [
|
||||
{ title: { contains: query } },
|
||||
{ content: { contains: query } },
|
||||
{ labels: { contains: query } },
|
||||
],
|
||||
},
|
||||
select: NOTE_LIST_SELECT,
|
||||
orderBy: [
|
||||
{ isPinned: 'desc' },
|
||||
{ order: 'asc' },
|
||||
{ updatedAt: 'desc' }
|
||||
]
|
||||
});
|
||||
|
||||
const queryLower = query.toLowerCase().trim();
|
||||
|
||||
// SIMPLE FILTER: check if query is in title OR content OR labels
|
||||
const filteredNotes = allNotes.filter(note => {
|
||||
const title = (note.title || '').toLowerCase();
|
||||
const content = note.content.toLowerCase();
|
||||
const labels = note.labels ? JSON.parse(note.labels) : [];
|
||||
|
||||
// Check if query exists in title, content, or any label
|
||||
return title.includes(queryLower) ||
|
||||
content.includes(queryLower) ||
|
||||
labels.some((label: string) => label.toLowerCase().includes(queryLower));
|
||||
});
|
||||
|
||||
return filteredNotes.map(parseNote);
|
||||
return notes.map(parseNote);
|
||||
} catch (error) {
|
||||
console.error('Search error:', error);
|
||||
return [];
|
||||
@@ -848,50 +889,31 @@ export async function getAllNotes(includeArchived = false) {
|
||||
const userId = session.user.id;
|
||||
|
||||
try {
|
||||
// Get user's own notes
|
||||
const ownNotes = await prisma.note.findMany({
|
||||
where: {
|
||||
userId: userId,
|
||||
...(includeArchived ? {} : { isArchived: false }),
|
||||
},
|
||||
orderBy: [
|
||||
{ isPinned: 'desc' },
|
||||
{ order: 'asc' },
|
||||
{ updatedAt: 'desc' }
|
||||
]
|
||||
})
|
||||
|
||||
// Get notes shared with user via NoteShare (accepted only)
|
||||
const acceptedShares = await prisma.noteShare.findMany({
|
||||
where: {
|
||||
userId: userId,
|
||||
status: 'accepted'
|
||||
},
|
||||
include: {
|
||||
note: true
|
||||
}
|
||||
})
|
||||
// Fetch own notes + shared notes in parallel — no embedding to keep transfer fast
|
||||
const [ownNotes, acceptedShares] = await Promise.all([
|
||||
prisma.note.findMany({
|
||||
where: {
|
||||
userId,
|
||||
...(includeArchived ? {} : { isArchived: false }),
|
||||
},
|
||||
select: NOTE_LIST_SELECT,
|
||||
orderBy: [
|
||||
{ isPinned: 'desc' },
|
||||
{ order: 'asc' },
|
||||
{ updatedAt: 'desc' }
|
||||
]
|
||||
}),
|
||||
prisma.noteShare.findMany({
|
||||
where: { userId, status: 'accepted' },
|
||||
include: { note: { select: NOTE_LIST_SELECT } }
|
||||
})
|
||||
])
|
||||
|
||||
const sharedNotes = acceptedShares
|
||||
.map(share => share.note)
|
||||
.filter(note => includeArchived || !note.isArchived)
|
||||
|
||||
const allNotes = [...ownNotes.map(parseNote), ...sharedNotes.map(parseNote)]
|
||||
|
||||
// Derive pinned and recent notes
|
||||
const pinned = allNotes.filter((note: Note) => note.isPinned)
|
||||
const sevenDaysAgo = new Date()
|
||||
sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7)
|
||||
sevenDaysAgo.setHours(0, 0, 0, 0)
|
||||
|
||||
const recent = allNotes
|
||||
.filter((note: Note) => {
|
||||
return !note.isArchived && !note.dismissedFromRecent && note.contentUpdatedAt >= sevenDaysAgo
|
||||
})
|
||||
.sort((a, b) => new Date(b.contentUpdatedAt).getTime() - new Date(a.createdAt).getTime())
|
||||
.slice(0, 3)
|
||||
|
||||
return allNotes
|
||||
return [...ownNotes.map(parseNote), ...sharedNotes.map(parseNote)]
|
||||
} catch (error) {
|
||||
console.error('Error fetching notes:', error)
|
||||
return []
|
||||
|
||||
439
keep-notes/components/home-client.tsx
Normal file
439
keep-notes/components/home-client.tsx
Normal file
@@ -0,0 +1,439 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { useSearchParams, useRouter } from 'next/navigation'
|
||||
import dynamic from 'next/dynamic'
|
||||
import { Note } from '@/lib/types'
|
||||
import { getAISettings } from '@/app/actions/ai-settings'
|
||||
import { getAllNotes, searchNotes } from '@/app/actions/notes'
|
||||
import { NoteInput } from '@/components/note-input'
|
||||
import { NotesMainSection, type NotesViewMode } from '@/components/notes-main-section'
|
||||
import { NotesViewToggle } from '@/components/notes-view-toggle'
|
||||
import { MemoryEchoNotification } from '@/components/memory-echo-notification'
|
||||
import { NotebookSuggestionToast } from '@/components/notebook-suggestion-toast'
|
||||
import { FavoritesSection } from '@/components/favorites-section'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Wand2 } from 'lucide-react'
|
||||
import { useLabels } from '@/context/LabelContext'
|
||||
import { useNoteRefresh } from '@/context/NoteRefreshContext'
|
||||
import { useReminderCheck } from '@/hooks/use-reminder-check'
|
||||
import { useAutoLabelSuggestion } from '@/hooks/use-auto-label-suggestion'
|
||||
import { useNotebooks } from '@/context/notebooks-context'
|
||||
import { Folder, Briefcase, FileText, Zap, BarChart3, Globe, Sparkles, Book, Heart, Crown, Music, Building2, Plane, ChevronRight, Plus } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { LabelFilter } from '@/components/label-filter'
|
||||
import { useLanguage } from '@/lib/i18n'
|
||||
import { useHomeView } from '@/context/home-view-context'
|
||||
|
||||
// Lazy-load heavy dialogs — uniquement chargés à la demande
|
||||
const NoteEditor = dynamic(
|
||||
() => import('@/components/note-editor').then(m => ({ default: m.NoteEditor })),
|
||||
{ ssr: false }
|
||||
)
|
||||
const BatchOrganizationDialog = dynamic(
|
||||
() => import('@/components/batch-organization-dialog').then(m => ({ default: m.BatchOrganizationDialog })),
|
||||
{ ssr: false }
|
||||
)
|
||||
const AutoLabelSuggestionDialog = dynamic(
|
||||
() => import('@/components/auto-label-suggestion-dialog').then(m => ({ default: m.AutoLabelSuggestionDialog })),
|
||||
{ ssr: false }
|
||||
)
|
||||
|
||||
type InitialSettings = {
|
||||
showRecentNotes: boolean
|
||||
notesViewMode: 'masonry' | 'tabs'
|
||||
}
|
||||
|
||||
interface HomeClientProps {
|
||||
/** Notes pré-chargées côté serveur — hydratées immédiatement sans loading spinner */
|
||||
initialNotes: Note[]
|
||||
initialSettings: InitialSettings
|
||||
}
|
||||
|
||||
export function HomeClient({ initialNotes, initialSettings }: HomeClientProps) {
|
||||
const searchParams = useSearchParams()
|
||||
const router = useRouter()
|
||||
const { t } = useLanguage()
|
||||
|
||||
const [notes, setNotes] = useState<Note[]>(initialNotes)
|
||||
const [pinnedNotes, setPinnedNotes] = useState<Note[]>(
|
||||
initialNotes.filter(n => n.isPinned)
|
||||
)
|
||||
const [notesViewMode, setNotesViewMode] = useState<NotesViewMode>(initialSettings.notesViewMode)
|
||||
const [editingNote, setEditingNote] = useState<{ note: Note; readOnly?: boolean } | null>(null)
|
||||
const [isLoading, setIsLoading] = useState(false) // false by default — data is pre-loaded
|
||||
const [notebookSuggestion, setNotebookSuggestion] = useState<{ noteId: string; content: string } | null>(null)
|
||||
const [batchOrganizationOpen, setBatchOrganizationOpen] = useState(false)
|
||||
const { refreshKey } = useNoteRefresh()
|
||||
const { labels } = useLabels()
|
||||
const { setControls } = useHomeView()
|
||||
|
||||
const { shouldSuggest: shouldSuggestLabels, notebookId: suggestNotebookId, dismiss: dismissLabelSuggestion } = useAutoLabelSuggestion()
|
||||
const [autoLabelOpen, setAutoLabelOpen] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (shouldSuggestLabels && suggestNotebookId) {
|
||||
setAutoLabelOpen(true)
|
||||
}
|
||||
}, [shouldSuggestLabels, suggestNotebookId])
|
||||
|
||||
const notebookFilter = searchParams.get('notebook')
|
||||
const isInbox = !notebookFilter
|
||||
|
||||
const handleNoteCreated = useCallback((note: Note) => {
|
||||
setNotes((prevNotes) => {
|
||||
const notebookFilter = searchParams.get('notebook')
|
||||
const labelFilter = searchParams.get('labels')?.split(',').filter(Boolean) || []
|
||||
const colorFilter = searchParams.get('color')
|
||||
const search = searchParams.get('search')?.trim() || null
|
||||
|
||||
if (notebookFilter && note.notebookId !== notebookFilter) return prevNotes
|
||||
if (!notebookFilter && note.notebookId) return prevNotes
|
||||
|
||||
if (labelFilter.length > 0) {
|
||||
const noteLabels = note.labels || []
|
||||
if (!noteLabels.some((label: string) => labelFilter.includes(label))) return prevNotes
|
||||
}
|
||||
|
||||
if (colorFilter) {
|
||||
const labelNamesWithColor = labels
|
||||
.filter((label: any) => label.color === colorFilter)
|
||||
.map((label: any) => label.name)
|
||||
const noteLabels = note.labels || []
|
||||
if (!noteLabels.some((label: string) => labelNamesWithColor.includes(label))) return prevNotes
|
||||
}
|
||||
|
||||
if (search) {
|
||||
router.refresh()
|
||||
return prevNotes
|
||||
}
|
||||
|
||||
const isPinned = note.isPinned || false
|
||||
const pinnedNotes = prevNotes.filter(n => n.isPinned)
|
||||
const unpinnedNotes = prevNotes.filter(n => !n.isPinned)
|
||||
|
||||
if (isPinned) {
|
||||
return [note, ...pinnedNotes, ...unpinnedNotes]
|
||||
} else {
|
||||
return [...pinnedNotes, note, ...unpinnedNotes]
|
||||
}
|
||||
})
|
||||
|
||||
if (!note.notebookId) {
|
||||
const wordCount = (note.content || '').trim().split(/\s+/).filter(w => w.length > 0).length
|
||||
if (wordCount >= 20) {
|
||||
setNotebookSuggestion({ noteId: note.id, content: note.content || '' })
|
||||
}
|
||||
}
|
||||
}, [searchParams, labels, router])
|
||||
|
||||
const handleOpenNote = (noteId: string) => {
|
||||
const note = notes.find(n => n.id === noteId)
|
||||
if (note) setEditingNote({ note, readOnly: false })
|
||||
}
|
||||
|
||||
useReminderCheck(notes)
|
||||
|
||||
// Rechargement uniquement pour les filtres actifs (search, labels, notebook)
|
||||
// Les notes initiales suffisent sans filtre
|
||||
useEffect(() => {
|
||||
const search = searchParams.get('search')?.trim() || null
|
||||
const labelFilter = searchParams.get('labels')?.split(',').filter(Boolean) || []
|
||||
const colorFilter = searchParams.get('color')
|
||||
const notebook = searchParams.get('notebook')
|
||||
const semanticMode = searchParams.get('semantic') === 'true'
|
||||
|
||||
// Pour le refreshKey (mutations), toujours recharger
|
||||
// Pour les filtres, charger depuis le serveur
|
||||
const hasActiveFilter = search || labelFilter.length > 0 || colorFilter
|
||||
|
||||
const load = async () => {
|
||||
setIsLoading(true)
|
||||
let allNotes = search
|
||||
? await searchNotes(search, semanticMode, notebook || undefined)
|
||||
: await getAllNotes()
|
||||
|
||||
// Filtre notebook côté client
|
||||
if (notebook) {
|
||||
allNotes = allNotes.filter((note: any) => note.notebookId === notebook)
|
||||
} else {
|
||||
allNotes = allNotes.filter((note: any) => !note.notebookId)
|
||||
}
|
||||
|
||||
// Filtre labels
|
||||
if (labelFilter.length > 0) {
|
||||
allNotes = allNotes.filter((note: any) =>
|
||||
note.labels?.some((label: string) => labelFilter.includes(label))
|
||||
)
|
||||
}
|
||||
|
||||
// Filtre couleur
|
||||
if (colorFilter) {
|
||||
const labelNamesWithColor = labels
|
||||
.filter((label: any) => label.color === colorFilter)
|
||||
.map((label: any) => label.name)
|
||||
allNotes = allNotes.filter((note: any) =>
|
||||
note.labels?.some((label: string) => labelNamesWithColor.includes(label))
|
||||
)
|
||||
}
|
||||
|
||||
setNotes(allNotes)
|
||||
setPinnedNotes(allNotes.filter((n: any) => n.isPinned))
|
||||
setIsLoading(false)
|
||||
}
|
||||
|
||||
// Éviter le rechargement initial si les notes sont déjà chargées sans filtres
|
||||
if (refreshKey > 0 || hasActiveFilter) {
|
||||
const cancelled = { value: false }
|
||||
load().then(() => { if (cancelled.value) return })
|
||||
return () => { cancelled.value = true }
|
||||
} else {
|
||||
// Données initiales : filtrage inbox/notebook côté client seulement
|
||||
let filtered = initialNotes
|
||||
if (notebook) {
|
||||
filtered = initialNotes.filter(n => n.notebookId === notebook)
|
||||
} else {
|
||||
filtered = initialNotes.filter(n => !n.notebookId)
|
||||
}
|
||||
setNotes(filtered)
|
||||
setPinnedNotes(filtered.filter(n => n.isPinned))
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [searchParams, refreshKey])
|
||||
|
||||
const { notebooks } = useNotebooks()
|
||||
const currentNotebook = notebooks.find((n: any) => n.id === searchParams.get('notebook'))
|
||||
const [showNoteInput, setShowNoteInput] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
setControls({
|
||||
isTabsMode: notesViewMode === 'tabs',
|
||||
openNoteComposer: () => setShowNoteInput(true),
|
||||
})
|
||||
return () => setControls(null)
|
||||
}, [notesViewMode, setControls])
|
||||
|
||||
const getNotebookIcon = (iconName: string) => {
|
||||
const ICON_MAP: Record<string, any> = {
|
||||
'folder': Folder,
|
||||
'briefcase': Briefcase,
|
||||
'document': FileText,
|
||||
'lightning': Zap,
|
||||
'chart': BarChart3,
|
||||
'globe': Globe,
|
||||
'sparkle': Sparkles,
|
||||
'book': Book,
|
||||
'heart': Heart,
|
||||
'crown': Crown,
|
||||
'music': Music,
|
||||
'building': Building2,
|
||||
'flight_takeoff': Plane,
|
||||
}
|
||||
return ICON_MAP[iconName] || Folder
|
||||
}
|
||||
|
||||
const handleNoteCreatedWrapper = (note: any) => {
|
||||
handleNoteCreated(note)
|
||||
setShowNoteInput(false)
|
||||
}
|
||||
|
||||
const Breadcrumbs = ({ notebookName }: { notebookName: string }) => (
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground mb-1">
|
||||
<span>{t('nav.notebooks')}</span>
|
||||
<ChevronRight className="w-4 h-4" />
|
||||
<span className="font-medium text-primary">{notebookName}</span>
|
||||
</div>
|
||||
)
|
||||
|
||||
const isTabs = notesViewMode === 'tabs'
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'flex w-full min-h-0 flex-1 flex-col',
|
||||
isTabs ? 'gap-3 py-1' : 'h-full px-2 py-6 sm:px-4 md:px-8'
|
||||
)}
|
||||
>
|
||||
{/* Notebook Specific Header */}
|
||||
{currentNotebook ? (
|
||||
<div
|
||||
className={cn(
|
||||
'flex flex-col animate-in fade-in slide-in-from-top-2 duration-300',
|
||||
isTabs ? 'mb-3 gap-3' : 'mb-8 gap-6'
|
||||
)}
|
||||
>
|
||||
<Breadcrumbs notebookName={currentNotebook.name} />
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex items-center gap-5">
|
||||
<div className="p-3 bg-primary/10 dark:bg-primary/20 rounded-xl">
|
||||
{(() => {
|
||||
const Icon = getNotebookIcon(currentNotebook.icon || 'folder')
|
||||
return (
|
||||
<Icon
|
||||
className={cn("w-8 h-8", !currentNotebook.color && "text-primary dark:text-primary-foreground")}
|
||||
style={currentNotebook.color ? { color: currentNotebook.color } : undefined}
|
||||
/>
|
||||
)
|
||||
})()}
|
||||
</div>
|
||||
<h1 className="text-4xl font-bold text-gray-900 dark:text-white tracking-tight">{currentNotebook.name}</h1>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<NotesViewToggle mode={notesViewMode} onModeChange={setNotesViewMode} />
|
||||
<LabelFilter
|
||||
selectedLabels={searchParams.get('labels')?.split(',').filter(Boolean) || []}
|
||||
onFilterChange={(newLabels) => {
|
||||
const params = new URLSearchParams(searchParams.toString())
|
||||
if (newLabels.length > 0) params.set('labels', newLabels.join(','))
|
||||
else params.delete('labels')
|
||||
router.push(`/?${params.toString()}`)
|
||||
}}
|
||||
className="border-gray-200"
|
||||
/>
|
||||
{!isTabs && (
|
||||
<Button
|
||||
onClick={() => setShowNoteInput(!showNoteInput)}
|
||||
className="h-10 px-6 rounded-full bg-primary hover:bg-primary/90 text-primary-foreground font-medium shadow-sm gap-2 transition-all"
|
||||
>
|
||||
<Plus className="w-5 h-5" />
|
||||
{t('notes.addNote') || 'Add Note'}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className={cn(
|
||||
'flex flex-col animate-in fade-in slide-in-from-top-2 duration-300',
|
||||
isTabs ? 'mb-3 gap-3' : 'mb-8 gap-6'
|
||||
)}
|
||||
>
|
||||
{!isTabs && <div className="mb-1 h-5" />}
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex items-center gap-5">
|
||||
<div className="p-3 bg-white border border-gray-100 dark:bg-gray-800 dark:border-gray-700 rounded-xl shadow-sm">
|
||||
<FileText className="w-8 h-8 text-primary" />
|
||||
</div>
|
||||
<h1 className="text-4xl font-bold text-gray-900 dark:text-white tracking-tight">{t('notes.title')}</h1>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<NotesViewToggle mode={notesViewMode} onModeChange={setNotesViewMode} />
|
||||
<LabelFilter
|
||||
selectedLabels={searchParams.get('labels')?.split(',').filter(Boolean) || []}
|
||||
onFilterChange={(newLabels) => {
|
||||
const params = new URLSearchParams(searchParams.toString())
|
||||
if (newLabels.length > 0) params.set('labels', newLabels.join(','))
|
||||
else params.delete('labels')
|
||||
router.push(`/?${params.toString()}`)
|
||||
}}
|
||||
className="border-gray-200"
|
||||
/>
|
||||
{isInbox && !isLoading && notes.length >= 2 && (
|
||||
<Button
|
||||
onClick={() => setBatchOrganizationOpen(true)}
|
||||
variant="outline"
|
||||
className="h-10 px-4 rounded-full border-gray-200 text-gray-700 hover:bg-gray-50 gap-2 shadow-sm"
|
||||
title={t('batch.organizeWithAI')}
|
||||
>
|
||||
<Wand2 className="h-4 w-4 text-purple-600" />
|
||||
<span className="hidden sm:inline">{t('batch.organize')}</span>
|
||||
</Button>
|
||||
)}
|
||||
{!isTabs && (
|
||||
<Button
|
||||
onClick={() => setShowNoteInput(!showNoteInput)}
|
||||
className="h-10 px-6 rounded-full bg-primary hover:bg-primary/90 text-primary-foreground font-medium shadow-sm gap-2 transition-all"
|
||||
>
|
||||
<Plus className="w-5 h-5" />
|
||||
{t('notes.newNote')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showNoteInput && (
|
||||
<div
|
||||
className={cn(
|
||||
'animate-in fade-in slide-in-from-top-4 duration-300',
|
||||
isTabs ? 'mb-3 w-full shrink-0' : 'mb-8'
|
||||
)}
|
||||
>
|
||||
<NoteInput
|
||||
onNoteCreated={handleNoteCreatedWrapper}
|
||||
forceExpanded={true}
|
||||
fullWidth={isTabs}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isLoading ? (
|
||||
<div className="text-center py-8 text-gray-500">{t('general.loading')}</div>
|
||||
) : (
|
||||
<>
|
||||
<FavoritesSection
|
||||
pinnedNotes={pinnedNotes}
|
||||
onEdit={(note, readOnly) => setEditingNote({ note, readOnly })}
|
||||
/>
|
||||
|
||||
{notes.filter((note) => !note.isPinned).length > 0 && (
|
||||
<div className={cn(isTabs && 'flex min-h-0 flex-1 flex-col')}>
|
||||
<NotesMainSection
|
||||
viewMode={notesViewMode}
|
||||
notes={notes.filter((note) => !note.isPinned)}
|
||||
onEdit={(note, readOnly) => setEditingNote({ note, readOnly })}
|
||||
currentNotebookId={searchParams.get('notebook')}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{notes.filter(note => !note.isPinned).length === 0 && pinnedNotes.length === 0 && (
|
||||
<div className="text-center py-8 text-gray-500">
|
||||
{t('notes.emptyState')}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
<MemoryEchoNotification onOpenNote={handleOpenNote} />
|
||||
|
||||
{notebookSuggestion && (
|
||||
<NotebookSuggestionToast
|
||||
noteId={notebookSuggestion.noteId}
|
||||
noteContent={notebookSuggestion.content}
|
||||
onDismiss={() => setNotebookSuggestion(null)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{batchOrganizationOpen && (
|
||||
<BatchOrganizationDialog
|
||||
open={batchOrganizationOpen}
|
||||
onOpenChange={setBatchOrganizationOpen}
|
||||
onNotesMoved={() => router.refresh()}
|
||||
/>
|
||||
)}
|
||||
|
||||
{autoLabelOpen && (
|
||||
<AutoLabelSuggestionDialog
|
||||
open={autoLabelOpen}
|
||||
onOpenChange={(open) => {
|
||||
setAutoLabelOpen(open)
|
||||
if (!open) dismissLabelSuggestion()
|
||||
}}
|
||||
notebookId={suggestNotebookId}
|
||||
onLabelsCreated={() => router.refresh()}
|
||||
/>
|
||||
)}
|
||||
|
||||
{editingNote && (
|
||||
<NoteEditor
|
||||
note={editingNote.note}
|
||||
readOnly={editingNote.readOnly}
|
||||
onClose={() => setEditingNote(null)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,234 +1,143 @@
|
||||
/**
|
||||
* Masonry Grid Styles
|
||||
*
|
||||
* Styles for responsive masonry layout similar to Google Keep
|
||||
* Handles note sizes, drag states, and responsive breakpoints
|
||||
* Masonry Grid Styles — CSS columns natif (sans Muuri)
|
||||
* Layout responsive pur CSS, drag-and-drop via @dnd-kit
|
||||
*/
|
||||
|
||||
/* Masonry Container */
|
||||
/* ─── Container ──────────────────────────────────── */
|
||||
.masonry-container {
|
||||
width: 100%;
|
||||
/* Reduced to compensate for item padding */
|
||||
padding: 0 20px 40px 20px;
|
||||
padding: 0 8px 40px 8px;
|
||||
}
|
||||
|
||||
/* Masonry Item Base Styles - Width is managed by Muuri */
|
||||
.masonry-item {
|
||||
display: block;
|
||||
position: absolute;
|
||||
z-index: 1;
|
||||
/* ─── CSS Grid Masonry ───────────────────────────── */
|
||||
.masonry-css-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
|
||||
grid-auto-rows: auto;
|
||||
gap: 12px;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
/* ─── Sortable items ─────────────────────────────── */
|
||||
.masonry-sortable-item {
|
||||
break-inside: avoid;
|
||||
box-sizing: border-box;
|
||||
padding: 8px;
|
||||
/* 8px * 2 = 16px gap (Tighter spacing) */
|
||||
will-change: transform;
|
||||
}
|
||||
|
||||
/* Masonry Item Content Wrapper */
|
||||
.masonry-item-content {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
/* height: auto - let content determine height */
|
||||
box-sizing: border-box;
|
||||
/* Notes "medium" et "large" occupent 2 colonnes si disponibles */
|
||||
.masonry-sortable-item[data-size="medium"] {
|
||||
grid-column: span 2;
|
||||
}
|
||||
|
||||
/* Ensure proper box-sizing for all elements in the grid */
|
||||
.masonry-item *,
|
||||
.masonry-item-content * {
|
||||
box-sizing: border-box;
|
||||
.masonry-sortable-item[data-size="large"] {
|
||||
grid-column: span 2;
|
||||
}
|
||||
|
||||
/* Note Card - Base styles */
|
||||
.note-card {
|
||||
width: 100% !important;
|
||||
/* Force full width within grid cell */
|
||||
min-width: 0;
|
||||
/* Prevent overflow */
|
||||
}
|
||||
|
||||
/* Note Size Styles - Desktop Default */
|
||||
.masonry-item[data-size="small"],
|
||||
.note-card[data-size="small"] {
|
||||
min-height: 150px;
|
||||
}
|
||||
|
||||
.masonry-item[data-size="medium"],
|
||||
.note-card[data-size="medium"] {
|
||||
min-height: 350px;
|
||||
}
|
||||
|
||||
.masonry-item[data-size="large"],
|
||||
.note-card[data-size="large"] {
|
||||
min-height: 500px;
|
||||
}
|
||||
|
||||
/* Drag State Styles - Clean and flat behavior requested by user */
|
||||
.masonry-item.muuri-item-dragging {
|
||||
z-index: 1000;
|
||||
opacity: 1 !important;
|
||||
/* Force opacity to 100% */
|
||||
transition: none;
|
||||
}
|
||||
|
||||
.masonry-item.muuri-item-dragging .note-card {
|
||||
transform: none !important;
|
||||
/* Force "straight" - no rotation, no scale */
|
||||
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2);
|
||||
transition: none;
|
||||
}
|
||||
|
||||
.masonry-item.muuri-item-releasing {
|
||||
z-index: 2;
|
||||
transition: all 0.3s cubic-bezier(0.25, 1, 0.5, 1);
|
||||
}
|
||||
|
||||
.masonry-item.muuri-item-releasing .note-card {
|
||||
transform: scale(1) rotate(0deg);
|
||||
box-shadow: none;
|
||||
transition: all 0.3s cubic-bezier(0.25, 1, 0.5, 1);
|
||||
}
|
||||
|
||||
.masonry-item.muuri-item-hidden {
|
||||
z-index: 0;
|
||||
opacity: 0;
|
||||
/* ─── Drag overlay ───────────────────────────────── */
|
||||
.masonry-drag-overlay {
|
||||
cursor: grabbing;
|
||||
box-shadow: 0 20px 40px rgba(0, 0, 0, 0.25), 0 8px 16px rgba(0, 0, 0, 0.15);
|
||||
border-radius: 12px;
|
||||
opacity: 0.95;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* Drag Placeholder - More visible and styled like Google Keep */
|
||||
.muuri-item-placeholder {
|
||||
opacity: 0.3;
|
||||
background: rgba(100, 100, 255, 0.05);
|
||||
border: 2px dashed rgba(100, 100, 255, 0.3);
|
||||
border-radius: 12px;
|
||||
transition: all 0.2s ease-out;
|
||||
min-height: 150px !important;
|
||||
min-width: 100px !important;
|
||||
display: flex !important;
|
||||
align-items: center !important;
|
||||
justify-content: center !important;
|
||||
/* ─── Note card base ─────────────────────────────── */
|
||||
.note-card {
|
||||
width: 100% !important;
|
||||
min-width: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.muuri-item-placeholder::before {
|
||||
content: '';
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 50%;
|
||||
background: rgba(100, 100, 255, 0.1);
|
||||
border: 2px dashed rgba(100, 100, 255, 0.2);
|
||||
/* ─── Note size min-heights ──────────────────────── */
|
||||
.masonry-sortable-item[data-size="small"] .note-card {
|
||||
min-height: 120px;
|
||||
}
|
||||
|
||||
/* Mobile Styles (< 640px) */
|
||||
@media (max-width: 639px) {
|
||||
.masonry-sortable-item[data-size="medium"] .note-card {
|
||||
min-height: 280px;
|
||||
}
|
||||
|
||||
.masonry-sortable-item[data-size="large"] .note-card {
|
||||
min-height: 440px;
|
||||
}
|
||||
|
||||
/* ─── Transitions ────────────────────────────────── */
|
||||
.masonry-sortable-item {
|
||||
transition: opacity 0.15s ease-out;
|
||||
}
|
||||
|
||||
/* ─── Mobile (< 480px) : 1 colonne ──────────────── */
|
||||
@media (max-width: 479px) {
|
||||
.masonry-css-grid {
|
||||
grid-template-columns: 1fr;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.masonry-sortable-item[data-size="medium"],
|
||||
.masonry-sortable-item[data-size="large"] {
|
||||
grid-column: span 1;
|
||||
}
|
||||
|
||||
.masonry-container {
|
||||
padding: 0 20px 16px 20px;
|
||||
}
|
||||
|
||||
.masonry-item {
|
||||
padding: 8px;
|
||||
/* 16px gap on mobile */
|
||||
}
|
||||
|
||||
/* Smaller note sizes on mobile */
|
||||
.masonry-item[data-size="small"],
|
||||
.masonry-item-content .note-card[data-size="small"] {
|
||||
min-height: 120px;
|
||||
}
|
||||
|
||||
.masonry-item[data-size="medium"],
|
||||
.masonry-item-content .note-card[data-size="medium"] {
|
||||
min-height: 280px;
|
||||
}
|
||||
|
||||
.masonry-item[data-size="large"],
|
||||
.masonry-item-content .note-card[data-size="large"] {
|
||||
min-height: 400px;
|
||||
}
|
||||
|
||||
/* Reduced drag effect on mobile */
|
||||
.masonry-item.muuri-item-dragging .note-card {
|
||||
transform: scale(1.01);
|
||||
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2);
|
||||
padding: 0 4px 16px 4px;
|
||||
}
|
||||
}
|
||||
|
||||
/* Tablet Styles (640px - 1023px) */
|
||||
@media (min-width: 640px) and (max-width: 1023px) {
|
||||
/* ─── Small tablet (480–767px) : 2 colonnes ─────── */
|
||||
@media (min-width: 480px) and (max-width: 767px) {
|
||||
.masonry-css-grid {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.masonry-container {
|
||||
padding: 0 24px 20px 24px;
|
||||
}
|
||||
|
||||
.masonry-item {
|
||||
padding: 8px;
|
||||
/* 16px gap */
|
||||
padding: 0 8px 20px 8px;
|
||||
}
|
||||
}
|
||||
|
||||
/* Desktop Styles (1024px - 1279px) */
|
||||
/* ─── Tablet (768–1023px) : 2–3 colonnes ────────── */
|
||||
@media (min-width: 768px) and (max-width: 1023px) {
|
||||
.masonry-css-grid {
|
||||
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
}
|
||||
|
||||
/* ─── Desktop (1024–1279px) : 3–4 colonnes ──────── */
|
||||
@media (min-width: 1024px) and (max-width: 1279px) {
|
||||
.masonry-container {
|
||||
padding: 0 28px 24px 28px;
|
||||
}
|
||||
|
||||
.masonry-item {
|
||||
padding: 8px;
|
||||
.masonry-css-grid {
|
||||
grid-template-columns: repeat(auto-fill, minmax(230px, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
}
|
||||
|
||||
/* Large Desktop Styles (1280px+) */
|
||||
/* ─── Large Desktop (1280px+): 4–5 colonnes ─────── */
|
||||
@media (min-width: 1280px) {
|
||||
.masonry-css-grid {
|
||||
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.masonry-container {
|
||||
padding: 0 28px 32px 28px;
|
||||
max-width: 1600px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.masonry-item {
|
||||
padding: 8px;
|
||||
padding: 0 12px 32px 12px;
|
||||
}
|
||||
}
|
||||
|
||||
/* Smooth transition for layout changes */
|
||||
.masonry-item,
|
||||
.masonry-item-content,
|
||||
.note-card {
|
||||
transition-property: box-shadow, opacity;
|
||||
transition-duration: 0.2s;
|
||||
transition-timing-function: ease-out;
|
||||
}
|
||||
|
||||
/* Prevent layout shift during animations */
|
||||
.masonry-item.muuri-item-positioning {
|
||||
transition: none !important;
|
||||
}
|
||||
|
||||
/* Hide scrollbars during drag to prevent jitter */
|
||||
body.muuri-dragging {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* Optimize for reduced motion */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
|
||||
.masonry-item,
|
||||
.masonry-item-content,
|
||||
.note-card {
|
||||
transition: none;
|
||||
}
|
||||
|
||||
.masonry-item.muuri-item-dragging .note-card {
|
||||
transform: none;
|
||||
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
}
|
||||
|
||||
/* Print styles */
|
||||
/* ─── Print ──────────────────────────────────────── */
|
||||
@media print {
|
||||
|
||||
.masonry-item.muuri-item-dragging,
|
||||
.muuri-item-placeholder {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.masonry-item {
|
||||
.masonry-sortable-item {
|
||||
break-inside: avoid;
|
||||
page-break-inside: avoid;
|
||||
}
|
||||
}
|
||||
|
||||
/* ─── Reduced motion ─────────────────────────────── */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.masonry-sortable-item {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
@@ -1,83 +1,166 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useRef, useCallback, memo, useMemo } from 'react';
|
||||
import { useState, useEffect, useCallback, memo, useMemo, useRef } from 'react';
|
||||
import {
|
||||
DndContext,
|
||||
DragEndEvent,
|
||||
DragOverlay,
|
||||
DragStartEvent,
|
||||
PointerSensor,
|
||||
TouchSensor,
|
||||
closestCenter,
|
||||
useSensor,
|
||||
useSensors,
|
||||
} from '@dnd-kit/core';
|
||||
import {
|
||||
SortableContext,
|
||||
arrayMove,
|
||||
rectSortingStrategy,
|
||||
useSortable,
|
||||
} from '@dnd-kit/sortable';
|
||||
import { CSS } from '@dnd-kit/utilities';
|
||||
import { Note } from '@/lib/types';
|
||||
import { NoteCard } from './note-card';
|
||||
import { NoteEditor } from './note-editor';
|
||||
import { updateFullOrderWithoutRevalidation } from '@/app/actions/notes';
|
||||
import { useResizeObserver } from '@/hooks/use-resize-observer';
|
||||
import { useNotebookDrag } from '@/context/notebook-drag-context';
|
||||
import { useLanguage } from '@/lib/i18n';
|
||||
import { DEFAULT_LAYOUT, calculateColumns, calculateItemWidth, isMobileViewport } from '@/config/masonry-layout';
|
||||
import './masonry-grid.css'; // Force rebuild: Spacing update verification
|
||||
import dynamic from 'next/dynamic';
|
||||
import './masonry-grid.css';
|
||||
|
||||
// Lazy-load NoteEditor — uniquement chargé au clic
|
||||
const NoteEditor = dynamic(
|
||||
() => import('./note-editor').then(m => ({ default: m.NoteEditor })),
|
||||
{ ssr: false }
|
||||
);
|
||||
|
||||
interface MasonryGridProps {
|
||||
notes: Note[];
|
||||
onEdit?: (note: Note, readOnly?: boolean) => void;
|
||||
}
|
||||
|
||||
interface MasonryItemProps {
|
||||
// ─────────────────────────────────────────────
|
||||
// Sortable Note Item
|
||||
// ─────────────────────────────────────────────
|
||||
interface SortableNoteProps {
|
||||
note: Note;
|
||||
onEdit: (note: Note, readOnly?: boolean) => void;
|
||||
onResize: () => void;
|
||||
onNoteSizeChange: (noteId: string, newSize: 'small' | 'medium' | 'large') => void;
|
||||
onDragStart?: (noteId: string) => void;
|
||||
onDragEnd?: () => void;
|
||||
onSizeChange: (noteId: string, newSize: 'small' | 'medium' | 'large') => void;
|
||||
onDragStartNote?: (noteId: string) => void;
|
||||
onDragEndNote?: () => void;
|
||||
isDragging?: boolean;
|
||||
isOverlay?: boolean;
|
||||
}
|
||||
|
||||
const MasonryItem = memo(function MasonryItem({ note, onEdit, onResize, onNoteSizeChange, onDragStart, onDragEnd, isDragging }: MasonryItemProps) {
|
||||
const resizeRef = useResizeObserver(onResize);
|
||||
const SortableNoteItem = memo(function SortableNoteItem({
|
||||
note,
|
||||
onEdit,
|
||||
onSizeChange,
|
||||
onDragStartNote,
|
||||
onDragEndNote,
|
||||
isDragging,
|
||||
isOverlay,
|
||||
}: SortableNoteProps) {
|
||||
const {
|
||||
attributes,
|
||||
listeners,
|
||||
setNodeRef,
|
||||
transform,
|
||||
transition,
|
||||
isDragging: isSortableDragging,
|
||||
} = useSortable({ id: note.id });
|
||||
|
||||
useEffect(() => {
|
||||
onResize();
|
||||
const timer = setTimeout(onResize, 300);
|
||||
return () => clearTimeout(timer);
|
||||
}, [note.size, onResize]);
|
||||
const style: React.CSSProperties = {
|
||||
transform: CSS.Transform.toString(transform),
|
||||
transition,
|
||||
opacity: isSortableDragging && !isOverlay ? 0.3 : 1,
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className="masonry-item absolute py-1"
|
||||
ref={setNodeRef}
|
||||
style={style}
|
||||
{...attributes}
|
||||
{...listeners}
|
||||
className="masonry-sortable-item"
|
||||
data-id={note.id}
|
||||
data-size={note.size}
|
||||
data-draggable="true"
|
||||
>
|
||||
<div className="masonry-item-content relative" ref={resizeRef as any}>
|
||||
<NoteCard
|
||||
note={note}
|
||||
onEdit={onEdit}
|
||||
onDragStart={onDragStart}
|
||||
onDragEnd={onDragEnd}
|
||||
isDragging={isDragging}
|
||||
onResize={onResize}
|
||||
onSizeChange={(newSize) => onNoteSizeChange(note.id, newSize)}
|
||||
/>
|
||||
</div>
|
||||
<NoteCard
|
||||
note={note}
|
||||
onEdit={onEdit}
|
||||
onDragStart={onDragStartNote}
|
||||
onDragEnd={onDragEndNote}
|
||||
isDragging={isDragging}
|
||||
onSizeChange={(newSize) => onSizeChange(note.id, newSize)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
|
||||
// ─────────────────────────────────────────────
|
||||
// Sortable Grid Section (pinned or others)
|
||||
// ─────────────────────────────────────────────
|
||||
interface SortableGridSectionProps {
|
||||
notes: Note[];
|
||||
onEdit: (note: Note, readOnly?: boolean) => void;
|
||||
onSizeChange: (noteId: string, newSize: 'small' | 'medium' | 'large') => void;
|
||||
draggedNoteId: string | null;
|
||||
onDragStartNote: (noteId: string) => void;
|
||||
onDragEndNote: () => void;
|
||||
}
|
||||
|
||||
const SortableGridSection = memo(function SortableGridSection({
|
||||
notes,
|
||||
onEdit,
|
||||
onSizeChange,
|
||||
draggedNoteId,
|
||||
onDragStartNote,
|
||||
onDragEndNote,
|
||||
}: SortableGridSectionProps) {
|
||||
const ids = useMemo(() => notes.map(n => n.id), [notes]);
|
||||
|
||||
return (
|
||||
<SortableContext items={ids} strategy={rectSortingStrategy}>
|
||||
<div className="masonry-css-grid">
|
||||
{notes.map(note => (
|
||||
<SortableNoteItem
|
||||
key={note.id}
|
||||
note={note}
|
||||
onEdit={onEdit}
|
||||
onSizeChange={onSizeChange}
|
||||
onDragStartNote={onDragStartNote}
|
||||
onDragEndNote={onDragEndNote}
|
||||
isDragging={draggedNoteId === note.id}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</SortableContext>
|
||||
);
|
||||
});
|
||||
|
||||
// ─────────────────────────────────────────────
|
||||
// Main MasonryGrid component
|
||||
// ─────────────────────────────────────────────
|
||||
export function MasonryGrid({ notes, onEdit }: MasonryGridProps) {
|
||||
const { t } = useLanguage();
|
||||
const [editingNote, setEditingNote] = useState<{ note: Note; readOnly?: boolean } | null>(null);
|
||||
const { startDrag, endDrag, draggedNoteId } = useNotebookDrag();
|
||||
const [muuriReady, setMuuriReady] = useState(false);
|
||||
|
||||
// Local state for notes with dynamic size updates
|
||||
// This allows size changes to propagate immediately without waiting for server
|
||||
// Local notes state for optimistic size/order updates
|
||||
const [localNotes, setLocalNotes] = useState<Note[]>(notes);
|
||||
|
||||
// Sync localNotes when parent notes prop changes
|
||||
useEffect(() => {
|
||||
setLocalNotes(notes);
|
||||
}, [notes]);
|
||||
|
||||
// Callback for when a note's size changes - update local state immediately
|
||||
const handleNoteSizeChange = useCallback((noteId: string, newSize: 'small' | 'medium' | 'large') => {
|
||||
setLocalNotes(prevNotes =>
|
||||
prevNotes.map(n => n.id === noteId ? { ...n, size: newSize } : n)
|
||||
);
|
||||
}, []);
|
||||
const pinnedNotes = useMemo(() => localNotes.filter(n => n.isPinned), [localNotes]);
|
||||
const othersNotes = useMemo(() => localNotes.filter(n => !n.isPinned), [localNotes]);
|
||||
|
||||
const [activeId, setActiveId] = useState<string | null>(null);
|
||||
const activeNote = useMemo(
|
||||
() => localNotes.find(n => n.id === activeId) ?? null,
|
||||
[localNotes, activeId]
|
||||
);
|
||||
|
||||
const handleEdit = useCallback((note: Note, readOnly?: boolean) => {
|
||||
if (onEdit) {
|
||||
@@ -87,342 +170,105 @@ export function MasonryGrid({ notes, onEdit }: MasonryGridProps) {
|
||||
}
|
||||
}, [onEdit]);
|
||||
|
||||
const pinnedGridRef = useRef<HTMLDivElement>(null);
|
||||
const othersGridRef = useRef<HTMLDivElement>(null);
|
||||
const pinnedMuuri = useRef<any>(null);
|
||||
const othersMuuri = useRef<any>(null);
|
||||
const handleSizeChange = useCallback((noteId: string, newSize: 'small' | 'medium' | 'large') => {
|
||||
setLocalNotes(prev => prev.map(n => n.id === noteId ? { ...n, size: newSize } : n));
|
||||
}, []);
|
||||
|
||||
// Memoize filtered notes from localNotes (which includes dynamic size updates)
|
||||
const pinnedNotes = useMemo(
|
||||
() => localNotes.filter(n => n.isPinned),
|
||||
[localNotes]
|
||||
);
|
||||
const othersNotes = useMemo(
|
||||
() => localNotes.filter(n => !n.isPinned),
|
||||
[localNotes]
|
||||
// @dnd-kit sensors — pointer (desktop) + touch (mobile)
|
||||
const sensors = useSensors(
|
||||
useSensor(PointerSensor, {
|
||||
activationConstraint: { distance: 8 }, // Évite les activations accidentelles
|
||||
}),
|
||||
useSensor(TouchSensor, {
|
||||
activationConstraint: { delay: 200, tolerance: 8 }, // Long-press sur mobile
|
||||
})
|
||||
);
|
||||
|
||||
const handleDragEnd = useCallback(async (grid: any) => {
|
||||
if (!grid) return;
|
||||
const handleDragStart = useCallback((event: DragStartEvent) => {
|
||||
setActiveId(event.active.id as string);
|
||||
startDrag(event.active.id as string);
|
||||
}, [startDrag]);
|
||||
|
||||
const items = grid.getItems();
|
||||
const ids = items
|
||||
.map((item: any) => item.getElement()?.getAttribute('data-id'))
|
||||
.filter((id: any): id is string => !!id);
|
||||
const handleDragEnd = useCallback(async (event: DragEndEvent) => {
|
||||
const { active, over } = event;
|
||||
setActiveId(null);
|
||||
endDrag();
|
||||
|
||||
try {
|
||||
// Save order to database WITHOUT triggering a full page refresh
|
||||
// Muuri has already updated the visual layout
|
||||
await updateFullOrderWithoutRevalidation(ids);
|
||||
} catch (error) {
|
||||
console.error('Failed to persist order:', error);
|
||||
}
|
||||
}, []);
|
||||
if (!over || active.id === over.id) return;
|
||||
|
||||
const refreshLayout = useCallback(() => {
|
||||
requestAnimationFrame(() => {
|
||||
if (pinnedMuuri.current) {
|
||||
pinnedMuuri.current.refreshItems().layout();
|
||||
}
|
||||
if (othersMuuri.current) {
|
||||
othersMuuri.current.refreshItems().layout();
|
||||
}
|
||||
setLocalNotes(prev => {
|
||||
const oldIndex = prev.findIndex(n => n.id === active.id);
|
||||
const newIndex = prev.findIndex(n => n.id === over.id);
|
||||
if (oldIndex === -1 || newIndex === -1) return prev;
|
||||
return arrayMove(prev, oldIndex, newIndex);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const applyItemDimensions = useCallback((grid: any, containerWidth: number) => {
|
||||
if (!grid) return;
|
||||
|
||||
// Calculate columns and item width based on container width
|
||||
const columns = calculateColumns(containerWidth);
|
||||
const baseItemWidth = calculateItemWidth(containerWidth, columns);
|
||||
|
||||
const items = grid.getItems();
|
||||
items.forEach((item: any) => {
|
||||
const el = item.getElement();
|
||||
if (el) {
|
||||
const size = el.getAttribute('data-size') || 'small';
|
||||
let width = baseItemWidth;
|
||||
if (columns >= 2 && size === 'medium') {
|
||||
width = Math.min(baseItemWidth * 1.5, containerWidth);
|
||||
} else if (columns >= 2 && size === 'large') {
|
||||
width = Math.min(baseItemWidth * 2, containerWidth);
|
||||
}
|
||||
el.style.width = `${width}px`;
|
||||
}
|
||||
});
|
||||
}, []);
|
||||
|
||||
// Initialize Muuri grids once on mount and sync when needed
|
||||
useEffect(() => {
|
||||
let isMounted = true;
|
||||
let muuriInitialized = false;
|
||||
|
||||
const initMuuri = async () => {
|
||||
// Prevent duplicate initialization
|
||||
if (muuriInitialized) return;
|
||||
muuriInitialized = true;
|
||||
|
||||
// Import web-animations-js polyfill
|
||||
await import('web-animations-js');
|
||||
// Dynamic import of Muuri to avoid SSR window error
|
||||
const MuuriClass = (await import('muuri')).default;
|
||||
|
||||
if (!isMounted) return;
|
||||
|
||||
// Detect if we are on a touch device (mobile behavior)
|
||||
const isTouchDevice = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
|
||||
const isMobileWidth = window.innerWidth < 768;
|
||||
const isMobile = isTouchDevice || isMobileWidth;
|
||||
|
||||
// Get container width for responsive calculation
|
||||
const containerWidth = window.innerWidth - 32; // Subtract padding
|
||||
const columns = calculateColumns(containerWidth);
|
||||
const itemWidth = calculateItemWidth(containerWidth, columns);
|
||||
|
||||
|
||||
|
||||
const layoutOptions = {
|
||||
dragEnabled: !isMobile,
|
||||
// Use drag handle for mobile devices to allow smooth scrolling
|
||||
// On desktop, whole card is draggable (no handle needed)
|
||||
dragHandle: isMobile ? '.muuri-drag-handle' : undefined,
|
||||
dragContainer: document.body,
|
||||
dragStartPredicate: {
|
||||
distance: 10,
|
||||
delay: 0,
|
||||
},
|
||||
dragPlaceholder: {
|
||||
enabled: true,
|
||||
createElement: (item: any) => {
|
||||
const el = item.getElement().cloneNode(true);
|
||||
// Styles are now handled purely by CSS (.muuri-item-placeholder)
|
||||
// to avoid inline style conflicts and "grayed out/tilted" look
|
||||
return el;
|
||||
},
|
||||
},
|
||||
dragAutoScroll: {
|
||||
targets: [window],
|
||||
speed: (item: any, target: any, intersection: any) => {
|
||||
return intersection * 30; // Faster auto-scroll for better UX
|
||||
},
|
||||
threshold: 50, // Start auto-scroll earlier (50px from edge)
|
||||
smoothStop: true, // Smooth deceleration
|
||||
},
|
||||
// LAYOUT OPTIONS - Configure masonry grid behavior
|
||||
// These options are critical for proper masonry layout with different item sizes
|
||||
layoutDuration: 300,
|
||||
layoutEasing: 'cubic-bezier(0.25, 1, 0.5, 1)',
|
||||
fillGaps: true,
|
||||
horizontal: false,
|
||||
alignRight: false,
|
||||
alignBottom: false,
|
||||
rounding: false,
|
||||
// CRITICAL: Enable true masonry layout for different item sizes
|
||||
layout: {
|
||||
fillGaps: true,
|
||||
horizontal: false,
|
||||
alignRight: false,
|
||||
alignBottom: false,
|
||||
rounding: false,
|
||||
},
|
||||
};
|
||||
|
||||
// Initialize pinned grid
|
||||
if (pinnedGridRef.current && !pinnedMuuri.current) {
|
||||
pinnedMuuri.current = new MuuriClass(pinnedGridRef.current, layoutOptions)
|
||||
.on('dragEnd', () => handleDragEnd(pinnedMuuri.current));
|
||||
applyItemDimensions(pinnedMuuri.current, containerWidth);
|
||||
pinnedMuuri.current.refreshItems().layout();
|
||||
}
|
||||
|
||||
// Initialize others grid
|
||||
if (othersGridRef.current && !othersMuuri.current) {
|
||||
othersMuuri.current = new MuuriClass(othersGridRef.current, layoutOptions)
|
||||
.on('dragEnd', () => handleDragEnd(othersMuuri.current));
|
||||
applyItemDimensions(othersMuuri.current, containerWidth);
|
||||
othersMuuri.current.refreshItems().layout();
|
||||
}
|
||||
|
||||
// Signal that Muuri is ready so sync/resize effects can run
|
||||
setMuuriReady(true);
|
||||
};
|
||||
|
||||
initMuuri();
|
||||
|
||||
return () => {
|
||||
isMounted = false;
|
||||
pinnedMuuri.current?.destroy();
|
||||
othersMuuri.current?.destroy();
|
||||
pinnedMuuri.current = null;
|
||||
othersMuuri.current = null;
|
||||
};
|
||||
// Only run once on mount
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
// Container ref for ResizeObserver
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Synchronize items when notes change (e.g. searching, adding)
|
||||
useEffect(() => {
|
||||
if (!muuriReady) return;
|
||||
const syncGridItems = (grid: any, gridRef: React.RefObject<HTMLDivElement | null>, notesArray: Note[]) => {
|
||||
if (!grid || !gridRef.current) return;
|
||||
|
||||
const containerWidth = containerRef.current?.getBoundingClientRect().width || window.innerWidth - 32;
|
||||
const columns = calculateColumns(containerWidth);
|
||||
const itemWidth = calculateItemWidth(containerWidth, columns);
|
||||
|
||||
// Get current DOM elements and Muuri items
|
||||
const domElements = Array.from(gridRef.current.children) as HTMLElement[];
|
||||
const muuriItems = grid.getItems();
|
||||
|
||||
// Map Muuri items to their elements for comparison
|
||||
const muuriElements = muuriItems.map((item: any) => item.getElement());
|
||||
|
||||
// Find new elements to add (in DOM but not in Muuri)
|
||||
const newElements = domElements.filter(el => !muuriElements.includes(el));
|
||||
|
||||
// Find elements to remove (in Muuri but not in DOM)
|
||||
const removedItems = muuriItems.filter((item: any) =>
|
||||
!domElements.includes(item.getElement())
|
||||
);
|
||||
|
||||
// Remove old items
|
||||
if (removedItems.length > 0) {
|
||||
grid.remove(removedItems, { layout: false });
|
||||
}
|
||||
|
||||
// Add new items with correct width based on size
|
||||
if (newElements.length > 0) {
|
||||
newElements.forEach(el => {
|
||||
const size = el.getAttribute('data-size') || 'small';
|
||||
let width = itemWidth;
|
||||
if (columns >= 2 && size === 'medium') {
|
||||
width = Math.min(itemWidth * 1.5, containerWidth);
|
||||
} else if (columns >= 2 && size === 'large') {
|
||||
width = Math.min(itemWidth * 2, containerWidth);
|
||||
}
|
||||
el.style.width = `${width}px`;
|
||||
});
|
||||
grid.add(newElements, { layout: false });
|
||||
}
|
||||
|
||||
// Update all item widths to ensure consistency (size-aware)
|
||||
domElements.forEach(el => {
|
||||
const size = el.getAttribute('data-size') || 'small';
|
||||
let width = itemWidth;
|
||||
if (columns >= 2 && size === 'medium') {
|
||||
width = Math.min(itemWidth * 1.5, containerWidth);
|
||||
} else if (columns >= 2 && size === 'large') {
|
||||
width = Math.min(itemWidth * 2, containerWidth);
|
||||
}
|
||||
el.style.width = `${width}px`;
|
||||
// Persist new order to DB (sans revalidation pour éviter le flash)
|
||||
setLocalNotes(current => {
|
||||
const ids = current.map(n => n.id);
|
||||
updateFullOrderWithoutRevalidation(ids).catch(err => {
|
||||
console.error('Failed to persist order:', err);
|
||||
});
|
||||
|
||||
// Refresh and layout
|
||||
grid.refreshItems().layout();
|
||||
};
|
||||
|
||||
// Use requestAnimationFrame to ensure DOM is updated before syncing
|
||||
requestAnimationFrame(() => {
|
||||
syncGridItems(pinnedMuuri.current, pinnedGridRef, pinnedNotes);
|
||||
syncGridItems(othersMuuri.current, othersGridRef, othersNotes);
|
||||
|
||||
// CRITICAL: Force a second layout after CSS transitions (padding/height changes) complete
|
||||
// NoteCard has a 200ms transition. We wait 300ms to be safe.
|
||||
setTimeout(() => {
|
||||
if (pinnedMuuri.current) pinnedMuuri.current.refreshItems().layout();
|
||||
if (othersMuuri.current) othersMuuri.current.refreshItems().layout();
|
||||
}, 300);
|
||||
return current;
|
||||
});
|
||||
}, [pinnedNotes, othersNotes, muuriReady]); // Re-run when notes change or Muuri becomes ready
|
||||
|
||||
// Handle container resize to update responsive layout
|
||||
useEffect(() => {
|
||||
if (!containerRef.current || (!pinnedMuuri.current && !othersMuuri.current)) return;
|
||||
|
||||
let resizeTimeout: NodeJS.Timeout;
|
||||
|
||||
const handleResize = (entries: ResizeObserverEntry[]) => {
|
||||
clearTimeout(resizeTimeout);
|
||||
resizeTimeout = setTimeout(() => {
|
||||
// Get precise width from ResizeObserver
|
||||
const containerWidth = entries[0]?.contentRect.width || window.innerWidth - 32;
|
||||
const columns = calculateColumns(containerWidth);
|
||||
|
||||
|
||||
|
||||
// Apply dimensions to both grids
|
||||
applyItemDimensions(pinnedMuuri.current, containerWidth);
|
||||
applyItemDimensions(othersMuuri.current, containerWidth);
|
||||
|
||||
// Refresh layouts
|
||||
requestAnimationFrame(() => {
|
||||
pinnedMuuri.current?.refreshItems().layout();
|
||||
othersMuuri.current?.refreshItems().layout();
|
||||
});
|
||||
}, 150); // Debounce
|
||||
};
|
||||
|
||||
const observer = new ResizeObserver(handleResize);
|
||||
observer.observe(containerRef.current);
|
||||
|
||||
// Initial layout check
|
||||
if (containerRef.current) {
|
||||
handleResize([{ contentRect: containerRef.current.getBoundingClientRect() } as ResizeObserverEntry]);
|
||||
}
|
||||
|
||||
return () => {
|
||||
clearTimeout(resizeTimeout);
|
||||
observer.disconnect();
|
||||
};
|
||||
}, [applyItemDimensions, muuriReady]);
|
||||
}, [endDrag]);
|
||||
|
||||
return (
|
||||
<div ref={containerRef} className="masonry-container">
|
||||
{pinnedNotes.length > 0 && (
|
||||
<div className="mb-8">
|
||||
<h2 className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-3 px-2">{t('notes.pinned')}</h2>
|
||||
<div ref={pinnedGridRef} className="relative min-h-[100px]">
|
||||
{pinnedNotes.map(note => (
|
||||
<MasonryItem
|
||||
key={note.id}
|
||||
note={note}
|
||||
onEdit={handleEdit}
|
||||
onResize={refreshLayout}
|
||||
onNoteSizeChange={handleNoteSizeChange}
|
||||
onDragStart={startDrag}
|
||||
onDragEnd={endDrag}
|
||||
isDragging={draggedNoteId === note.id}
|
||||
/>
|
||||
))}
|
||||
<DndContext
|
||||
sensors={sensors}
|
||||
collisionDetection={closestCenter}
|
||||
onDragStart={handleDragStart}
|
||||
onDragEnd={handleDragEnd}
|
||||
>
|
||||
<div className="masonry-container">
|
||||
{pinnedNotes.length > 0 && (
|
||||
<div className="mb-8">
|
||||
<h2 className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-3 px-2">
|
||||
{t('notes.pinned')}
|
||||
</h2>
|
||||
<SortableGridSection
|
||||
notes={pinnedNotes}
|
||||
onEdit={handleEdit}
|
||||
onSizeChange={handleSizeChange}
|
||||
draggedNoteId={draggedNoteId}
|
||||
onDragStartNote={startDrag}
|
||||
onDragEndNote={endDrag}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
)}
|
||||
|
||||
{othersNotes.length > 0 && (
|
||||
<div>
|
||||
{pinnedNotes.length > 0 && (
|
||||
<h2 className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-3 px-2">{t('notes.others')}</h2>
|
||||
)}
|
||||
<div ref={othersGridRef} className="relative min-h-[100px]">
|
||||
{othersNotes.map(note => (
|
||||
<MasonryItem
|
||||
key={note.id}
|
||||
note={note}
|
||||
onEdit={handleEdit}
|
||||
onResize={refreshLayout}
|
||||
onNoteSizeChange={handleNoteSizeChange}
|
||||
onDragStart={startDrag}
|
||||
onDragEnd={endDrag}
|
||||
isDragging={draggedNoteId === note.id}
|
||||
/>
|
||||
))}
|
||||
{othersNotes.length > 0 && (
|
||||
<div>
|
||||
{pinnedNotes.length > 0 && (
|
||||
<h2 className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-3 px-2">
|
||||
{t('notes.others')}
|
||||
</h2>
|
||||
)}
|
||||
<SortableGridSection
|
||||
notes={othersNotes}
|
||||
onEdit={handleEdit}
|
||||
onSizeChange={handleSizeChange}
|
||||
draggedNoteId={draggedNoteId}
|
||||
onDragStartNote={startDrag}
|
||||
onDragEndNote={endDrag}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* DragOverlay — montre une copie flottante pendant le drag */}
|
||||
<DragOverlay>
|
||||
{activeNote ? (
|
||||
<div className="masonry-sortable-item masonry-drag-overlay" data-size={activeNote.size}>
|
||||
<NoteCard
|
||||
note={activeNote}
|
||||
onEdit={handleEdit}
|
||||
isDragging={true}
|
||||
onSizeChange={(newSize) => handleSizeChange(activeNote.id, newSize)}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</DragOverlay>
|
||||
|
||||
{editingNote && (
|
||||
<NoteEditor
|
||||
@@ -431,7 +277,6 @@ export function MasonryGrid({ notes, onEdit }: MasonryGridProps) {
|
||||
onClose={() => setEditingNote(null)}
|
||||
/>
|
||||
)}
|
||||
|
||||
</div>
|
||||
</DndContext>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -11,30 +11,15 @@ const nextConfig: NextConfig = {
|
||||
// Enable standalone output for Docker
|
||||
output: 'standalone',
|
||||
|
||||
// Empty turbopack config to silence Turbopack/webpack conflict warning in Next.js 16
|
||||
turbopack: {},
|
||||
|
||||
// Webpack config (needed for PWA plugin)
|
||||
webpack: (config, { isServer }) => {
|
||||
// Fixes npm packages that depend on `fs` module
|
||||
if (!isServer) {
|
||||
config.resolve.fallback = {
|
||||
...config.resolve.fallback,
|
||||
fs: false,
|
||||
};
|
||||
}
|
||||
return config;
|
||||
},
|
||||
|
||||
// Optimize for production
|
||||
reactStrictMode: true,
|
||||
|
||||
// Image optimization
|
||||
// Image optimization (enabled for better performance)
|
||||
images: {
|
||||
unoptimized: true, // Required for standalone
|
||||
formats: ['image/avif', 'image/webp'],
|
||||
},
|
||||
|
||||
// Hide the "compiling" indicator as requested by the user
|
||||
// Hide the "compiling" indicator
|
||||
devIndicators: false,
|
||||
};
|
||||
|
||||
|
||||
127
keep-notes/package-lock.json
generated
127
keep-notes/package-lock.json
generated
@@ -36,7 +36,6 @@
|
||||
"dotenv": "^17.2.3",
|
||||
"katex": "^0.16.27",
|
||||
"lucide-react": "^0.562.0",
|
||||
"muuri": "^0.9.5",
|
||||
"next": "^16.1.6",
|
||||
"next-auth": "^5.0.0-beta.30",
|
||||
"nodemailer": "^8.0.4",
|
||||
@@ -44,9 +43,7 @@
|
||||
"radix-ui": "^1.4.3",
|
||||
"react": "19.2.3",
|
||||
"react-dom": "19.2.3",
|
||||
"react-grid-layout": "^2.2.2",
|
||||
"react-markdown": "^10.1.0",
|
||||
"react-masonry-css": "^1.0.16",
|
||||
"rehype-katex": "^7.0.1",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"remark-math": "^6.0.0",
|
||||
@@ -54,7 +51,6 @@
|
||||
"tailwind-merge": "^3.4.0",
|
||||
"tinyld": "^1.3.4",
|
||||
"vazirmatn": "^33.0.3",
|
||||
"web-animations-js": "^2.3.2",
|
||||
"zod": "^4.3.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -9301,12 +9297,6 @@
|
||||
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fast-equals": {
|
||||
"version": "4.0.3",
|
||||
"resolved": "https://registry.npmjs.org/fast-equals/-/fast-equals-4.0.3.tgz",
|
||||
"integrity": "sha512-G3BSX9cfKttjr+2o1O22tYMLq0DPluZnYtq1rXumE1SpL/F/SLIfHx08WYQoWSIpeMYf8sRbJ8++71+v6Pnxfg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fast-glob": {
|
||||
"version": "3.3.2",
|
||||
"resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.2.tgz",
|
||||
@@ -11041,24 +11031,6 @@
|
||||
"url": "https://github.com/sponsors/wooorm"
|
||||
}
|
||||
},
|
||||
"node_modules/loose-envify": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
|
||||
"integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"js-tokens": "^3.0.0 || ^4.0.0"
|
||||
},
|
||||
"bin": {
|
||||
"loose-envify": "cli.js"
|
||||
}
|
||||
},
|
||||
"node_modules/loose-envify/node_modules/js-tokens": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
|
||||
"integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lru-cache": {
|
||||
"version": "5.1.1",
|
||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
|
||||
@@ -12075,12 +12047,6 @@
|
||||
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/muuri": {
|
||||
"version": "0.9.5",
|
||||
"resolved": "https://registry.npmjs.org/muuri/-/muuri-0.9.5.tgz",
|
||||
"integrity": "sha512-nJL9/Pd5IaIXGAVunBs/LLQ+v6tPkvlqCYrlauWESgkVFr+F+CRf8HnayRh4AqiQ1S/PIEN39fhJSe4L5rLlxg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/nanoid": {
|
||||
"version": "3.3.11",
|
||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz",
|
||||
@@ -12279,15 +12245,6 @@
|
||||
"url": "https://github.com/sponsors/panva"
|
||||
}
|
||||
},
|
||||
"node_modules/object-assign": {
|
||||
"version": "4.1.1",
|
||||
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
|
||||
"integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/object-inspect": {
|
||||
"version": "1.13.4",
|
||||
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
|
||||
@@ -12634,17 +12591,6 @@
|
||||
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/prop-types": {
|
||||
"version": "15.8.1",
|
||||
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
|
||||
"integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"loose-envify": "^1.4.0",
|
||||
"object-assign": "^4.1.1",
|
||||
"react-is": "^16.13.1"
|
||||
}
|
||||
},
|
||||
"node_modules/property-information": {
|
||||
"version": "7.1.0",
|
||||
"resolved": "https://registry.npmjs.org/property-information/-/property-information-7.1.0.tgz",
|
||||
@@ -12888,44 +12834,6 @@
|
||||
"react": "^19.2.3"
|
||||
}
|
||||
},
|
||||
"node_modules/react-draggable": {
|
||||
"version": "4.5.0",
|
||||
"resolved": "https://registry.npmjs.org/react-draggable/-/react-draggable-4.5.0.tgz",
|
||||
"integrity": "sha512-VC+HBLEZ0XJxnOxVAZsdRi8rD04Iz3SiiKOoYzamjylUcju/hP9np/aZdLHf/7WOD268WMoNJMvYfB5yAK45cw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"clsx": "^2.1.1",
|
||||
"prop-types": "^15.8.1"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">= 16.3.0",
|
||||
"react-dom": ">= 16.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/react-grid-layout": {
|
||||
"version": "2.2.3",
|
||||
"resolved": "https://registry.npmjs.org/react-grid-layout/-/react-grid-layout-2.2.3.tgz",
|
||||
"integrity": "sha512-OAEJHBxmfuxQfVtZwRzmsokijGlBgzYIJ7MUlLk/VSa43SaGzu15w5D0P2RDrfX5EvP9POMbL6bFrai/huDzbQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"clsx": "^2.1.1",
|
||||
"fast-equals": "^4.0.3",
|
||||
"prop-types": "^15.8.1",
|
||||
"react-draggable": "^4.4.6",
|
||||
"react-resizable": "^3.1.3",
|
||||
"resize-observer-polyfill": "^1.5.1"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">= 16.3.0",
|
||||
"react-dom": ">= 16.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/react-is": {
|
||||
"version": "16.13.1",
|
||||
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
|
||||
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/react-markdown": {
|
||||
"version": "10.1.0",
|
||||
"resolved": "https://registry.npmjs.org/react-markdown/-/react-markdown-10.1.0.tgz",
|
||||
@@ -12953,15 +12861,6 @@
|
||||
"react": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/react-masonry-css": {
|
||||
"version": "1.0.16",
|
||||
"resolved": "https://registry.npmjs.org/react-masonry-css/-/react-masonry-css-1.0.16.tgz",
|
||||
"integrity": "sha512-KSW0hR2VQmltt/qAa3eXOctQDyOu7+ZBevtKgpNDSzT7k5LA/0XntNa9z9HKCdz3QlxmJHglTZ18e4sX4V8zZQ==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"react": ">=16.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/react-remove-scroll": {
|
||||
"version": "2.7.2",
|
||||
"resolved": "https://registry.npmjs.org/react-remove-scroll/-/react-remove-scroll-2.7.2.tgz",
|
||||
@@ -13009,20 +12908,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/react-resizable": {
|
||||
"version": "3.1.3",
|
||||
"resolved": "https://registry.npmjs.org/react-resizable/-/react-resizable-3.1.3.tgz",
|
||||
"integrity": "sha512-liJBNayhX7qA4tBJiBD321FDhJxgGTJ07uzH5zSORXoE8h7PyEZ8mLqmosST7ppf6C4zUsbd2gzDMmBCfFp9Lw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"prop-types": "15.x",
|
||||
"react-draggable": "^4.5.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">= 16.3",
|
||||
"react-dom": ">= 16.3"
|
||||
}
|
||||
},
|
||||
"node_modules/react-style-singleton": {
|
||||
"version": "2.2.3",
|
||||
"resolved": "https://registry.npmjs.org/react-style-singleton/-/react-style-singleton-2.2.3.tgz",
|
||||
@@ -13250,12 +13135,6 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/resize-observer-polyfill": {
|
||||
"version": "1.5.1",
|
||||
"resolved": "https://registry.npmjs.org/resize-observer-polyfill/-/resize-observer-polyfill-1.5.1.tgz",
|
||||
"integrity": "sha512-LwZrotdHOo12nQuZlHEmtuXdqGoOD0OhaxopaNFxWzInpEgaLWoVuAMbTzixuosCx2nEG58ngzW3vxdWoxIgdg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/resolve": {
|
||||
"version": "1.22.11",
|
||||
"resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.11.tgz",
|
||||
@@ -14909,12 +14788,6 @@
|
||||
"node": ">=10.13.0"
|
||||
}
|
||||
},
|
||||
"node_modules/web-animations-js": {
|
||||
"version": "2.3.2",
|
||||
"resolved": "https://registry.npmjs.org/web-animations-js/-/web-animations-js-2.3.2.tgz",
|
||||
"integrity": "sha512-TOMFWtQdxzjWp8qx4DAraTWTsdhxVSiWa6NkPFSaPtZ1diKUxTn4yTix73A1euG1WbSOMMPcY51cnjTIHrGtDA==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/web-namespaces": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/web-namespaces/-/web-namespaces-2.0.1.tgz",
|
||||
|
||||
@@ -3,9 +3,8 @@
|
||||
"version": "0.2.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev --webpack",
|
||||
"dev:turbo": "next dev",
|
||||
"build": "prisma generate && next build --webpack",
|
||||
"dev": "next dev --turbopack",
|
||||
"build": "prisma generate && next build",
|
||||
"start": "next start",
|
||||
"db:generate": "prisma generate",
|
||||
"db:migrate": "prisma migrate dev",
|
||||
@@ -51,7 +50,6 @@
|
||||
"dotenv": "^17.2.3",
|
||||
"katex": "^0.16.27",
|
||||
"lucide-react": "^0.562.0",
|
||||
"muuri": "^0.9.5",
|
||||
"next": "^16.1.6",
|
||||
"next-auth": "^5.0.0-beta.30",
|
||||
"nodemailer": "^8.0.4",
|
||||
@@ -59,9 +57,7 @@
|
||||
"radix-ui": "^1.4.3",
|
||||
"react": "19.2.3",
|
||||
"react-dom": "19.2.3",
|
||||
"react-grid-layout": "^2.2.2",
|
||||
"react-markdown": "^10.1.0",
|
||||
"react-masonry-css": "^1.0.16",
|
||||
"rehype-katex": "^7.0.1",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"remark-math": "^6.0.0",
|
||||
@@ -69,7 +65,6 @@
|
||||
"tailwind-merge": "^3.4.0",
|
||||
"tinyld": "^1.3.4",
|
||||
"vazirmatn": "^33.0.3",
|
||||
"web-animations-js": "^2.3.2",
|
||||
"zod": "^4.3.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
Binary file not shown.
Reference in New Issue
Block a user