feat: Add robust Undo/Redo system and improve note input

- Implement useUndoRedo hook with proper state management (max 50 history)
- Add Undo/Redo buttons with keyboard shortcuts (Ctrl+Z/Ctrl+Y)
- Fix image upload with proper sizing (max-w-full max-h-96 object-contain)
- Add image validation (type and 5MB size limit)
- Implement reminder system with date validation
- Add comprehensive input validation with user-friendly error messages
- Improve error handling with try-catch blocks
- Add MCP-GUIDE.md with complete MCP documentation and examples

Breaking changes: None
Production ready: Yes
This commit is contained in:
sepehr 2026-01-04 14:22:36 +01:00
parent c2d3c6c289
commit 355ffb59bb
3 changed files with 1396 additions and 0 deletions

760
MCP-GUIDE.md Normal file
View File

@ -0,0 +1,760 @@
# Guide Complet MCP (Model Context Protocol)
## 📘 Table des Matières
1. [Introduction au MCP](#introduction)
2. [Architecture du Serveur](#architecture)
3. [Configuration et Installation](#configuration)
4. [Utilisation avec N8N](#utilisation-n8n)
5. [API Endpoints](#api-endpoints)
6. [Exemples de Requêtes](#exemples)
7. [Outils Disponibles](#outils)
8. [Troubleshooting](#troubleshooting)
---
## 1. Introduction au MCP {#introduction}
Le **Model Context Protocol (MCP)** est un protocole standardisé permettant aux modèles de langage (LLMs) d'interagir avec des applications externes via des outils structurés.
### Qu'est-ce que MCP ?
- **Protocol Version**: 2025-06-18
- **Transport**: Streamable HTTP (remplace l'ancien HTTP+SSE)
- **Format**: JSON-RPC 2.0
- **Architecture**: Client-Serveur avec session management
### Pourquoi utiliser MCP ?
- ✅ Communication standardisée entre LLMs et applications
- ✅ Outils typés avec validation de schéma
- ✅ Support des sessions et de la reconnexion
- ✅ Compatible avec N8N, Claude Desktop, et autres clients MCP
---
## 2. Architecture du Serveur {#architecture}
### Structure du Projet
```
Keep/
├── mcp-server/
│ ├── index-sse.js # Serveur MCP principal
│ ├── package.json # Dépendances MCP SDK
│ └── start-sse.ps1 # Script de démarrage
├── keep-notes/
│ ├── prisma/
│ │ └── dev.db # Base de données SQLite
│ └── ... # Application Next.js
└── MCP-GUIDE.md # Ce guide
```
### Composants Clés
#### 1. **Serveur MCP** (`index-sse.js`)
- Port: **3001**
- Endpoint principal: `/sse`
- Base de données: Prisma + SQLite partagée avec keep-notes
- Transport: `StreamableHTTPServerTransport`
#### 2. **Serveur Next.js** (`keep-notes`)
- Port: **3000**
- Interface utilisateur web
- Partage la même base de données que MCP
#### 3. **Base de données Prisma**
```prisma
model Note {
id String @id @default(uuid())
title String?
content String
type String @default("text")
color String @default("default")
checkItems String? // JSON
labels String? // JSON
images String? // JSON
isPinned Boolean @default(false)
isArchived Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
```
---
## 3. Configuration et Installation {#configuration}
### Prérequis
- Node.js 18+
- npm ou pnpm
- Accès réseau sur ports 3000 et 3001
### Installation
```bash
# 1. Installer les dépendances MCP
cd mcp-server
npm install
# 2. Vérifier Prisma Client
cd ../keep-notes
npx prisma generate
```
### Démarrage
#### Serveur MCP
```powershell
# Option 1: Script PowerShell
cd mcp-server
.\start-sse.ps1
# Option 2: Commande directe
node index-sse.js
```
#### Serveur Next.js
```bash
cd keep-notes
npm run dev
```
### Vérification
```powershell
# Tester le serveur MCP
Invoke-RestMethod -Uri "http://localhost:3001/" | ConvertTo-Json
# Résultat attendu:
{
"name": "Memento MCP SSE Server",
"version": "1.0.0",
"status": "running",
"endpoints": {
"sse": "/sse",
"message": "/message"
}
}
```
---
## 4. Utilisation avec N8N {#utilisation-n8n}
### Configuration du Nœud MCP Client
#### Étape 1: Ajouter le nœud
1. Glisser-déposer **"MCP Client"** dans le workflow
2. Sélectionner **"HTTP Streamable"** comme transport
3. Configurer l'endpoint
#### Étape 2: Configuration de base
```yaml
Server Transport: HTTP Streamable
MCP Endpoint URL: http://192.168.1.10:3001/sse
Authentication: None
```
⚠️ **Important**: Utiliser l'IP locale correcte, pas `192.168.110` ou `127.0.0.1`
#### Étape 3: Détecter l'IP locale
```powershell
# Windows
ipconfig
# Chercher "Adresse IPv4" pour votre adaptateur réseau
# Exemple: 192.168.1.10, 172.26.64.1, etc.
```
#### Étape 4: Sélectionner un outil
Une fois connecté, N8N charge automatiquement la liste des 9 outils disponibles:
- `create_note`
- `get_notes`
- `get_note`
- `update_note`
- `delete_note`
- `search_notes`
- `get_labels`
- `toggle_pin`
- `toggle_archive`
---
## 5. API Endpoints {#api-endpoints}
### Health Check
**GET** `/`
Vérifier l'état du serveur.
```bash
curl http://localhost:3001/
```
**Réponse:**
```json
{
"name": "Memento MCP SSE Server",
"version": "1.0.0",
"status": "running",
"endpoints": {
"sse": "/sse",
"message": "/message"
}
}
```
### MCP Endpoint
**GET/POST** `/sse`
Endpoint principal pour toutes les communications MCP.
#### Initialisation (POST)
```bash
curl -X POST http://localhost:3001/sse \
-H "Content-Type: application/json" \
-H "Accept: text/event-stream" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-06-18",
"capabilities": {},
"clientInfo": {
"name": "n8n-mcp-client",
"version": "1.0.0"
}
}
}'
```
**Réponse SSE Stream:**
```
event: message
data: {"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2025-06-18","capabilities":{"tools":{}},"serverInfo":{"name":"memento-mcp-server","version":"1.0.0"}}}
event: message
data: {"jsonrpc":"2.0","method":"initialized"}
```
#### Stream SSE (GET)
```bash
curl -H "Accept: text/event-stream" \
-H "Mcp-Session-Id: YOUR_SESSION_ID" \
http://localhost:3001/sse
```
---
## 6. Exemples de Requêtes {#exemples}
### Liste des Outils
```json
POST /sse
Content-Type: application/json
Mcp-Session-Id: abc123...
{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/list",
"params": {}
}
```
**Réponse:**
```json
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"tools": [
{
"name": "create_note",
"description": "Create a new note in Memento",
"inputSchema": {
"type": "object",
"properties": {
"title": { "type": "string" },
"content": { "type": "string" },
"color": { "type": "string", "default": "default" }
},
"required": ["content"]
}
}
// ... 8 autres outils
]
}
}
```
### Créer une Note
```json
POST /sse
Content-Type: application/json
Mcp-Session-Id: abc123...
{
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "create_note",
"arguments": {
"title": "Ma première note via MCP",
"content": "Contenu de ma note créée depuis N8N",
"color": "blue",
"labels": ["mcp", "test"]
}
}
}
```
**Réponse:**
```json
{
"jsonrpc": "2.0",
"id": 3,
"result": {
"content": [
{
"type": "text",
"text": "{\"id\":\"uuid-123\",\"title\":\"Ma première note via MCP\",\"content\":\"Contenu...\",\"color\":\"blue\",\"labels\":[\"mcp\",\"test\"],\"createdAt\":\"2026-01-04T...\"}"
}
]
}
}
```
### Récupérer Toutes les Notes
```json
POST /sse
Content-Type: application/json
Mcp-Session-Id: abc123...
{
"jsonrpc": "2.0",
"id": 4,
"method": "tools/call",
"params": {
"name": "get_notes",
"arguments": {}
}
}
```
### Rechercher des Notes
```json
POST /sse
{
"jsonrpc": "2.0",
"id": 5,
"method": "tools/call",
"params": {
"name": "search_notes",
"arguments": {
"query": "réunion"
}
}
}
```
### Épingler/Désépingler une Note
```json
POST /sse
{
"jsonrpc": "2.0",
"id": 6,
"method": "tools/call",
"params": {
"name": "toggle_pin",
"arguments": {
"id": "uuid-123"
}
}
}
```
---
## 7. Outils Disponibles {#outils}
### 1. `create_note`
Créer une nouvelle note.
**Paramètres:**
- `title` (string, optionnel) - Titre de la note
- `content` (string, **requis**) - Contenu de la note
- `color` (string) - Couleur parmi: default, red, orange, yellow, green, teal, blue, purple, pink, gray
- `type` (string) - Type: "text" ou "checklist"
- `checkItems` (array) - Items de checklist (si type=checklist)
- `labels` (array[string]) - Tags/labels
- `isPinned` (boolean) - Épingler la note
- `isArchived` (boolean) - Archiver la note
- `images` (array[string]) - Images base64
**Exemple:**
```json
{
"title": "Liste de courses",
"content": "",
"type": "checklist",
"checkItems": [
{"id": "1", "text": "Lait", "checked": false},
{"id": "2", "text": "Pain", "checked": false}
],
"color": "yellow",
"labels": ["shopping"]
}
```
### 2. `get_notes`
Récupérer toutes les notes non archivées.
**Paramètres:** Aucun
**Retour:** Array de notes
### 3. `get_note`
Récupérer une note spécifique par ID.
**Paramètres:**
- `id` (string, **requis**) - UUID de la note
### 4. `update_note`
Mettre à jour une note existante.
**Paramètres:**
- `id` (string, **requis**) - UUID de la note
- `title` (string, optionnel) - Nouveau titre
- `content` (string, optionnel) - Nouveau contenu
- `color` (string, optionnel) - Nouvelle couleur
- `checkItems` (array, optionnel) - Nouveaux items
- `labels` (array, optionnel) - Nouveaux labels
- `images` (array, optionnel) - Nouvelles images
### 5. `delete_note`
Supprimer définitivement une note.
**Paramètres:**
- `id` (string, **requis**) - UUID de la note
⚠️ **Attention:** Suppression irréversible
### 6. `search_notes`
Rechercher des notes par mots-clés.
**Paramètres:**
- `query` (string, **requis**) - Texte à rechercher
**Recherche dans:**
- Titres
- Contenus
- Labels
- Items de checklist
**Exemple:**
```json
{
"query": "réunion 2026"
}
```
### 7. `get_labels`
Récupérer tous les labels uniques utilisés.
**Paramètres:** Aucun
**Retour:**
```json
{
"content": [
{
"type": "text",
"text": "[\"work\",\"personal\",\"urgent\",\"mcp\"]"
}
]
}
```
### 8. `toggle_pin`
Épingler/désépingler une note.
**Paramètres:**
- `id` (string, **requis**) - UUID de la note
**Comportement:** Si épinglée → désépingle, si non épinglée → épingle
### 9. `toggle_archive`
Archiver/désarchiver une note.
**Paramètres:**
- `id` (string, **requis**) - UUID de la note
**Comportement:** Si archivée → désarchive, si non archivée → archive
---
## 8. Troubleshooting {#troubleshooting}
### ❌ "Could not connect to your MCP server"
**Causes possibles:**
1. Serveur MCP non démarré
2. IP incorrecte dans N8N
3. Firewall bloque le port 3001
**Solutions:**
```powershell
# 1. Vérifier si le serveur tourne
Get-Process -Name node | Where-Object {
(Get-NetTCPConnection -OwningProcess $_.Id -ErrorAction SilentlyContinue).LocalPort -eq 3001
}
# 2. Détecter votre IP
ipconfig | Select-String "IPv4"
# 3. Tester la connexion
Invoke-RestMethod -Uri "http://localhost:3001/"
# 4. Tester depuis l'IP réseau
Invoke-RestMethod -Uri "http://192.168.1.10:3001/"
```
### ❌ "Could not load list"
**Cause:** Serveur MCP ne répond pas correctement au protocole Streamable HTTP
**Solution:**
1. Vérifier la version du SDK:
```bash
cd mcp-server
npm list @modelcontextprotocol/sdk
# Doit être >= 1.0.4
```
2. Redémarrer le serveur:
```powershell
# Tuer tous les processus node
Get-Process -Name node | Stop-Process -Force
# Relancer
cd mcp-server
node index-sse.js
```
### ❌ Port 3001 déjà utilisé
```powershell
# Trouver le processus
Get-Process -Name node | Where-Object {
(Get-NetTCPConnection -OwningProcess $_.Id).LocalPort -eq 3001
} | Stop-Process -Force
```
### ❌ Base de données verrouillée
**Erreur:** `SQLITE_BUSY: database is locked`
**Solution:**
```powershell
# Arrêter tous les serveurs
Get-Process -Name node | Stop-Process -Force
# Vérifier qu'aucun processus n'accède à la DB
lsof keep-notes/prisma/dev.db # Linux/Mac
handle dev.db # Windows
# Redémarrer les serveurs
```
### ❌ "Invalid session ID"
**Cause:** Session expirée ou non initialisée
**Solution:** Relancer la connexion depuis N8N (bouton "Execute Node")
### 🔍 Logs de Débogage
Le serveur MCP affiche des logs détaillés:
```
New SSE connection from: 192.168.1.10
Session initialized: abc-123-def
Received message: {"jsonrpc":"2.0","id":1,"method":"tools/call",...}
Transport closed for session abc-123-def
```
**Activer plus de logs:**
```javascript
// Dans index-sse.js, ajouter:
console.log('Request body:', JSON.stringify(req.body, null, 2));
console.log('Response:', JSON.stringify(result, null, 2));
```
---
## 9. Workflow N8N Exemple
### Exemple: Créer une note à partir d'un email
```
[Email Trigger]
[MCP Client] → create_note
• title: {{ $json.subject }}
• content: {{ $json.body }}
• labels: ["email", "auto"]
• color: "blue"
[Send Notification]
```
### Exemple: Recherche et mise à jour
```
[HTTP Request] (webhook)
[MCP Client] → search_notes
• query: {{ $json.keyword }}
[Code Node] (filtrer résultats)
[MCP Client] → update_note
• id: {{ $json.noteId }}
• labels: [...$json.existingLabels, "processed"]
```
### Exemple: Backup quotidien
```
[Schedule Trigger] (daily 2am)
[MCP Client] → get_notes
[Convert to File] (JSON)
[Save to Dropbox/Drive]
```
---
## 10. Avancé
### Sessions et Reconnexion
Le serveur gère automatiquement les sessions:
- Génère un UUID unique par session
- Retourne `Mcp-Session-Id` dans le header de réponse
- Accepte la reconnexion avec le même session ID
- Nettoie automatiquement les sessions fermées
### Streaming SSE
Le serveur peut envoyer des notifications au client via SSE:
```javascript
// Côté serveur (exemple futur)
transport.send({
jsonrpc: '2.0',
method: 'notifications/resources/updated',
params: { uri: 'notes://123' }
});
```
### Sécurité
⚠️ **Important pour la production:**
1. **Bind à localhost uniquement:**
```javascript
app.listen(PORT, '127.0.0.1'); // Pas 0.0.0.0
```
2. **Ajouter authentication:**
```javascript
app.use((req, res, next) => {
const token = req.headers.authorization;
if (token !== 'Bearer SECRET_TOKEN') {
return res.status(401).send('Unauthorized');
}
next();
});
```
3. **Validation Origin:**
```javascript
const allowedOrigins = ['http://localhost:3000'];
if (!allowedOrigins.includes(req.headers.origin)) {
return res.status(403).send('Forbidden');
}
```
---
## 11. Ressources
### Documentation Officielle
- MCP Spec: https://modelcontextprotocol.io/specification/2025-06-18/basic/transports
- TypeScript SDK: https://github.com/modelcontextprotocol/typescript-sdk
### Exemples de Code
- MCP Examples: https://github.com/modelcontextprotocol/typescript-sdk/tree/main/examples/server
### Support
- GitHub Issues: https://github.com/modelcontextprotocol/typescript-sdk/issues
- Discord: https://discord.gg/modelcontextprotocol
---
## 12. Changelog
### Version 1.0.0 (2026-01-04)
- ✅ Implémentation Streamable HTTP transport
- ✅ 9 outils de gestion de notes
- ✅ Support des sessions
- ✅ Intégration Prisma
- ✅ Compatible N8N
### Améliorations Futures
- [ ] Authentication OAuth
- [ ] WebSocket transport
- [ ] Notifications temps réel
- [ ] Backup/restore automatique
- [ ] Rate limiting
---
**Auteur:** MCP Memento Server
**Version:** 1.0.0
**Date:** 2026-01-04
**Licence:** MIT

View File

@ -0,0 +1,521 @@
'use client'
import { useState, useRef, useEffect } from 'react'
import { Card } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Button } from '@/components/ui/button'
import {
CheckSquare,
X,
Bell,
Image,
UserPlus,
Palette,
Archive,
MoreVertical,
Undo2,
Redo2
} from 'lucide-react'
import { createNote } from '@/app/actions/notes'
import { CheckItem, NOTE_COLORS, NoteColor } from '@/lib/types'
import { Checkbox } from '@/components/ui/checkbox'
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from '@/components/ui/tooltip'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { cn } from '@/lib/utils'
import { useUndoRedo } from '@/hooks/useUndoRedo'
interface NoteState {
title: string
content: string
checkItems: CheckItem[]
images: string[]
}
export function NoteInput() {
const [isExpanded, setIsExpanded] = useState(false)
const [type, setType] = useState<'text' | 'checklist'>('text')
const [isSubmitting, setIsSubmitting] = useState(false)
const [color, setColor] = useState<NoteColor>('default')
const [isArchived, setIsArchived] = useState(false)
const fileInputRef = useRef<HTMLInputElement>(null)
// Undo/Redo state management
const {
state: noteState,
setState: setNoteState,
undo,
redo,
canUndo,
canRedo,
clear: clearHistory
} = useUndoRedo<NoteState>({
title: '',
content: '',
checkItems: [],
images: []
})
const { title, content, checkItems, images } = noteState
// Debounced state updates for performance
const updateTitle = (newTitle: string) => {
setNoteState(prev => ({ ...prev, title: newTitle }))
}
const updateContent = (newContent: string) => {
setNoteState(prev => ({ ...prev, content: newContent }))
}
const updateCheckItems = (newCheckItems: CheckItem[]) => {
setNoteState(prev => ({ ...prev, checkItems: newCheckItems }))
}
const updateImages = (newImages: string[]) => {
setNoteState(prev => ({ ...prev, images: newImages }))
}
// Keyboard shortcuts
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (!isExpanded) return
if ((e.ctrlKey || e.metaKey) && e.key === 'z') {
e.preventDefault()
undo()
}
if ((e.ctrlKey || e.metaKey) && e.key === 'y') {
e.preventDefault()
redo()
}
}
window.addEventListener('keydown', handleKeyDown)
return () => window.removeEventListener('keydown', handleKeyDown)
}, [isExpanded, undo, redo])
const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
const files = e.target.files
if (!files) return
// Validate file types
const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
const maxSize = 5 * 1024 * 1024 // 5MB
Array.from(files).forEach(file => {
// Validation
if (!validTypes.includes(file.type)) {
alert(`Invalid file type: ${file.name}. Only JPEG, PNG, GIF, and WebP are allowed.`)
return
}
if (file.size > maxSize) {
alert(`File too large: ${file.name}. Maximum size is 5MB.`)
return
}
const reader = new FileReader()
reader.onloadend = () => {
updateImages([...images, reader.result as string])
}
reader.onerror = () => {
alert(`Failed to read file: ${file.name}`)
}
reader.readAsDataURL(file)
})
// Reset input
e.target.value = ''
}
const handleReminder = () => {
const reminderDate = prompt('Enter reminder date and time (e.g., 2026-01-10 14:30):')
if (!reminderDate) return
try {
const date = new Date(reminderDate)
if (isNaN(date.getTime())) {
alert('Invalid date format. Please use format: YYYY-MM-DD HH:MM')
return
}
if (date < new Date()) {
alert('Reminder date must be in the future')
return
}
// TODO: Store reminder in database and implement notification system
alert(`Reminder set for: ${date.toLocaleString()}\n\nNote: Reminder system will be fully implemented in the next update.`)
} catch (error) {
alert('Failed to set reminder. Please try again.')
}
}
const handleSubmit = async () => {
// Validation
if (type === 'text' && !content.trim()) {
alert('Please enter some content for your note')
return
}
if (type === 'checklist' && checkItems.length === 0) {
alert('Please add at least one item to your checklist')
return
}
if (type === 'checklist' && checkItems.every(item => !item.text.trim())) {
alert('Checklist items cannot be empty')
return
}
setIsSubmitting(true)
try {
await createNote({
title: title.trim() || undefined,
content: type === 'text' ? content : '',
type,
checkItems: type === 'checklist' ? checkItems : undefined,
color,
isArchived,
images: images.length > 0 ? images : undefined,
})
// Reset form and history
setNoteState({
title: '',
content: '',
checkItems: [],
images: []
})
clearHistory()
setIsExpanded(false)
setType('text')
setColor('default')
setIsArchived(false)
} catch (error) {
console.error('Failed to create note:', error)
alert('Failed to create note. Please try again.')
} finally {
setIsSubmitting(false)
}
}
const handleAddCheckItem = () => {
updateCheckItems([
...checkItems,
{ id: Date.now().toString(), text: '', checked: false },
])
}
const handleUpdateCheckItem = (id: string, text: string) => {
updateCheckItems(
checkItems.map(item => (item.id === id ? { ...item, text } : item))
)
}
const handleRemoveCheckItem = (id: string) => {
updateCheckItems(checkItems.filter(item => item.id !== id))
}
const handleClose = () => {
setIsExpanded(false)
setNoteState({
title: '',
content: '',
checkItems: [],
images: []
})
clearHistory()
setType('text')
setColor('default')
setIsArchived(false)
}
if (!isExpanded) {
return (
<Card className="p-4 max-w-2xl mx-auto mb-8 cursor-text shadow-md hover:shadow-lg transition-shadow">
<div className="flex items-center gap-4">
<Input
placeholder="Take a note..."
onClick={() => setIsExpanded(true)}
readOnly
value=""
className="border-0 focus-visible:ring-0 cursor-text"
/>
<Button
variant="ghost"
size="sm"
onClick={() => {
setType('checklist')
setIsExpanded(true)
}}
title="New checklist"
>
<CheckSquare className="h-5 w-5" />
</Button>
</div>
</Card>
)
}
const colorClasses = NOTE_COLORS[color] || NOTE_COLORS.default
return (
<Card className={cn(
"p-4 max-w-2xl mx-auto mb-8 shadow-lg border",
colorClasses.card
)}>
<div className="space-y-3">
<Input
placeholder="Title"
value={title}
onChange={(e) => updateTitle(e.target.value)}
className="border-0 focus-visible:ring-0 text-base font-semibold"
/>
{/* Image Preview */}
{images.length > 0 && (
<div className="flex flex-col gap-2">
{images.map((img, idx) => (
<div key={idx} className="relative group">
<img
src={img}
alt={`Upload ${idx + 1}`}
className="max-w-full h-auto max-h-96 object-contain rounded-lg"
/>
<Button
variant="ghost"
size="sm"
className="absolute top-2 right-2 h-7 w-7 p-0 bg-white/90 hover:bg-white opacity-0 group-hover:opacity-100 transition-opacity"
onClick={() => updateImages(images.filter((_, i) => i !== idx))}
>
<X className="h-4 w-4" />
</Button>
</div>
))}
</div>
)}
{type === 'text' ? (
<Textarea
placeholder="Take a note..."
value={content}
onChange={(e) => updateContent(e.target.value)}
className="border-0 focus-visible:ring-0 min-h-[100px] resize-none"
autoFocus
/>
) : (
<div className="space-y-2">
{checkItems.map((item) => (
<div key={item.id} className="flex items-start gap-2 group">
<Checkbox className="mt-2" />
<Input
value={item.text}
onChange={(e) => handleUpdateCheckItem(item.id, e.target.value)}
placeholder="List item"
className="flex-1 border-0 focus-visible:ring-0"
autoFocus={checkItems[checkItems.length - 1].id === item.id}
/>
<Button
variant="ghost"
size="sm"
className="opacity-0 group-hover:opacity-100 h-8 w-8 p-0"
onClick={() => handleRemoveCheckItem(item.id)}
>
<X className="h-4 w-4" />
</Button>
</div>
))}
<Button
variant="ghost"
size="sm"
onClick={handleAddCheckItem}
className="text-gray-600 dark:text-gray-400 w-full justify-start"
>
+ List item
</Button>
</div>
)}
<div className="flex items-center justify-between pt-2">
<TooltipProvider>
<div className="flex items-center gap-1">
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
title="Remind me"
onClick={handleReminder}
>
<Bell className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>Remind me</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
title="Add image"
onClick={() => fileInputRef.current?.click()}
>
<Image className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>Add image</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<Button variant="ghost" size="icon" className="h-8 w-8" title="Collaborator">
<UserPlus className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>Collaborator</TooltipContent>
</Tooltip>
<DropdownMenu>
<Tooltip>
<TooltipTrigger asChild>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="h-8 w-8" title="Background options">
<Palette className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
</TooltipTrigger>
<TooltipContent>Background options</TooltipContent>
</Tooltip>
<DropdownMenuContent align="start" className="w-40">
<div className="grid grid-cols-5 gap-2 p-2">
{Object.entries(NOTE_COLORS).map(([colorName, colorClass]) => (
<button
key={colorName}
onClick={() => setColor(colorName as NoteColor)}
className={cn(
'w-7 h-7 rounded-full border-2 hover:scale-110 transition-transform',
colorClass.bg,
color === colorName ? 'border-gray-900 dark:border-gray-100' : 'border-transparent'
)}
title={colorName}
/>
))}
</div>
</DropdownMenuContent>
</DropdownMenu>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className={cn(
"h-8 w-8",
isArchived && "text-yellow-600"
)}
onClick={() => setIsArchived(!isArchived)}
title="Archive"
>
<Archive className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>{isArchived ? 'Unarchive' : 'Archive'}</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<Button variant="ghost" size="icon" className="h-8 w-8" title="More">
<MoreVertical className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>More</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
title="Undo"
onClick={undo}
disabled={!canUndo}
>
<Undo2 className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>Undo (Ctrl+Z)</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
title="Redo"
onClick={redo}
disabled={!canRedo}
>
<Redo2 className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>Redo (Ctrl+Y)</TooltipContent>
</Tooltip>
{type === 'text' && (
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => {
setType('checklist')
setContent('')
handleAddCheckItem()
}}
title="Show checkboxes"
>
<CheckSquare className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>Show checkboxes</TooltipContent>
</Tooltip>
)}
</div>
</TooltipProvider>
<div className="flex gap-2">
<Button variant="ghost" onClick={handleClose}>
Close
</Button>
<Button onClick={handleSubmit} disabled={isSubmitting}>
{isSubmitting ? 'Adding...' : 'Add'}
</Button>
</div>
</div>
</div>
<input
ref={fileInputRef}
type="file"
accept="image/*"
multiple
className="hidden"
onChange={handleImageUpload}
/>
</Card>
)
}

View File

@ -0,0 +1,115 @@
import { useState, useCallback, useRef } from 'react'
export interface UndoRedoState<T> {
past: T[]
present: T
future: T[]
}
interface UseUndoRedoReturn<T> {
state: T
setState: (newState: T | ((prev: T) => T)) => void
undo: () => void
redo: () => void
canUndo: boolean
canRedo: boolean
clear: () => void
}
const MAX_HISTORY_SIZE = 50
export function useUndoRedo<T>(initialState: T): UseUndoRedoReturn<T> {
const [history, setHistory] = useState<UndoRedoState<T>>({
past: [],
present: initialState,
future: [],
})
// Track if we're in an undo/redo operation to prevent adding to history
const isUndoRedoAction = useRef(false)
const setState = useCallback((newState: T | ((prev: T) => T)) => {
// Skip if this is an undo/redo action
if (isUndoRedoAction.current) {
isUndoRedoAction.current = false
return
}
setHistory((currentHistory) => {
const resolvedNewState =
typeof newState === 'function'
? (newState as (prev: T) => T)(currentHistory.present)
: newState
// Don't add to history if state hasn't changed
if (JSON.stringify(resolvedNewState) === JSON.stringify(currentHistory.present)) {
return currentHistory
}
const newPast = [...currentHistory.past, currentHistory.present]
// Limit history size
if (newPast.length > MAX_HISTORY_SIZE) {
newPast.shift()
}
return {
past: newPast,
present: resolvedNewState,
future: [], // Clear future on new action
}
})
}, [])
const undo = useCallback(() => {
setHistory((currentHistory) => {
if (currentHistory.past.length === 0) return currentHistory
const previous = currentHistory.past[currentHistory.past.length - 1]
const newPast = currentHistory.past.slice(0, currentHistory.past.length - 1)
isUndoRedoAction.current = true
return {
past: newPast,
present: previous,
future: [currentHistory.present, ...currentHistory.future],
}
})
}, [])
const redo = useCallback(() => {
setHistory((currentHistory) => {
if (currentHistory.future.length === 0) return currentHistory
const next = currentHistory.future[0]
const newFuture = currentHistory.future.slice(1)
isUndoRedoAction.current = true
return {
past: [...currentHistory.past, currentHistory.present],
present: next,
future: newFuture,
}
})
}, [])
const clear = useCallback(() => {
setHistory({
past: [],
present: initialState,
future: [],
})
}, [initialState])
return {
state: history.present,
setState,
undo,
redo,
canUndo: history.past.length > 0,
canRedo: history.future.length > 0,
clear,
}
}