// Notes App Logic let notes = []; let currentFilter = 'all'; let currentColor = 'yellow'; let isPinned = false; let editingId = null; let currentMode = 'manual'; // Color mapping const colorClasses = { yellow: 'note-yellow', blue: 'note-blue', green: 'note-green', pink: 'note-pink', purple: 'note-purple' }; const colorBgClasses = { yellow: 'bg-yellow-400', blue: 'bg-blue-400', green: 'bg-green-400', pink: 'bg-pink-400', purple: 'bg-purple-400' }; // Initialize document.addEventListener('DOMContentLoaded', () => { loadNotes(); setupEventListeners(); renderNotes(); }); // Load notes from localStorage function loadNotes() { const stored = localStorage.getItem('virtualNotes'); if (stored) { notes = JSON.parse(stored); } } // Save notes to localStorage function saveNotes() { localStorage.setItem('virtualNotes', JSON.stringify(notes)); updateStats(); } // Setup Event Listeners function setupEventListeners() { // Form submission document.getElementById('noteForm').addEventListener('submit', handleSubmit); // Search inputs document.getElementById('searchInput').addEventListener('input', handleSearch); document.getElementById('searchInputMobile').addEventListener('input', handleSearch); // Close modal on outside click document.getElementById('noteModal').addEventListener('click', (e) => { if (e.target === document.getElementById('noteModal')) { closeModal(); } }); // Keyboard shortcuts document.addEventListener('keydown', (e) => { if (e.key === 'Escape') closeModal(); if (e.ctrlKey && e.key === 'n') { e.preventDefault(); openModal(); } }); // Topic input enter key document.getElementById('topicInput')?.addEventListener('keypress', (e) => { if (e.key === 'Enter') { e.preventDefault(); generateNote(); } }); } // Render Notes function renderNotes() { const grid = document.getElementById('notesGrid'); const emptyState = document.getElementById('emptyState'); const searchTerm = (document.getElementById('searchInput').value || document.getElementById('searchInputMobile').value || '').toLowerCase(); // Filter notes let filteredNotes = notes.filter(note => { const matchesSearch = note.title.toLowerCase().includes(searchTerm) || note.content.toLowerCase().includes(searchTerm); const matchesFilter = currentFilter === 'all' || (currentFilter === 'pinned' && note.pinned); return matchesSearch && matchesFilter; }); // Sort: pinned first, then by date filteredNotes.sort((a, b) => { if (a.pinned && !b.pinned) return -1; if (!a.pinned && b.pinned) return 1; return new Date(b.updatedAt) - new Date(a.updatedAt); }); // Clear grid grid.innerHTML = ''; // Show empty state if no notes if (filteredNotes.length === 0) { grid.classList.add('hidden'); emptyState.classList.remove('hidden'); if (notes.length > 0 && searchTerm) { emptyState.querySelector('h3').textContent = 'No matching notes'; emptyState.querySelector('p').textContent = 'Try adjusting your search terms.'; } else { emptyState.querySelector('h3').textContent = 'No notes yet'; emptyState.querySelector('p').textContent = 'Start capturing your ideas, thoughts, and reminders by creating your first note.'; } } else { grid.classList.remove('hidden'); emptyState.classList.add('hidden'); filteredNotes.forEach(note => { const card = createNoteCard(note); grid.appendChild(card); }); } updateStats(); lucide.createIcons(); } // Create Note Card HTML function createNoteCard(note) { const div = document.createElement('div'); div.className = `note-card ${colorClasses[note.color]} rounded-2xl p-5 cursor-pointer relative group`; div.onclick = (e) => { if (!e.target.closest('.action-btn')) { openModal(note.id); } }; const date = new Date(note.updatedAt).toLocaleDateString('en-US', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }); const aiBadge = note.autoGenerated ? `
AI
` : (note.pinned ? '' : ''); div.innerHTML = `

${escapeHtml(note.title)}

${aiBadge}

${escapeHtml(note.content)}

${date}
`; return div; } // Escape HTML to prevent XSS function escapeHtml(text) { const map = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }; return text.replace(/[&<>"']/g, (m) => map[m]); } // Mode Switching function setMode(mode) { currentMode = mode; const manualBtn = document.getElementById('manualModeBtn'); const autoBtn = document.getElementById('autoModeBtn'); const manualFields = document.getElementById('manualFields'); const autoFields = document.getElementById('autoFields'); if (mode === 'manual') { manualBtn.classList.add('bg-white', 'text-gray-900', 'shadow-sm'); manualBtn.classList.remove('text-gray-500'); autoBtn.classList.remove('bg-white', 'text-gray-900', 'shadow-sm'); autoBtn.classList.add('text-gray-500'); manualFields.classList.remove('hidden'); autoFields.classList.add('hidden'); } else { autoBtn.classList.add('bg-white', 'text-gray-900', 'shadow-sm'); autoBtn.classList.remove('text-gray-500'); manualBtn.classList.remove('bg-white', 'text-gray-900', 'shadow-sm'); manualBtn.classList.add('text-gray-500'); manualFields.classList.add('hidden'); autoFields.classList.remove('hidden'); // Auto-focus topic input setTimeout(() => document.getElementById('topicInput')?.focus(), 100); } lucide.createIcons(); } // Generate Note from Topic (Web Search) async function generateNote() { const topic = document.getElementById('topicInput').value.trim(); if (!topic) { showToast('Please enter a topic first'); return; } const loadingState = document.getElementById('loadingState'); const generateBtn = document.getElementById('generateBtn'); const generatedPreview = document.getElementById('generatedPreview'); // Show loading loadingState.classList.remove('hidden'); generatedPreview.classList.add('hidden'); generateBtn.disabled = true; generateBtn.innerHTML = '
'; try { // Search Wikipedia API const searchUrl = `https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=${encodeURIComponent(topic)}&format=json&origin=*&srlimit=1`; const searchResponse = await fetch(searchUrl); const searchData = await searchResponse.json(); if (!searchData.query?.search?.length) { throw new Error('No results found'); } const pageTitle = searchData.query.search[0].title; const snippet = searchData.query.search[0].snippet; // Get full extract const extractUrl = `https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exintro=true&explaintext=true&exsentences=5&titles=${encodeURIComponent(pageTitle)}&format=json&origin=*`; const extractResponse = await fetch(extractUrl); const extractData = await extractResponse.json(); const pages = extractData.query.pages; const pageId = Object.keys(pages)[0]; const extract = pages[pageId].extract || snippet.replace(/<\/?span[^>]*>/g, ''); // Display generated content document.getElementById('generatedTitle').textContent = pageTitle; document.getElementById('generatedContent').textContent = extract + '\n\n(Source: Wikipedia)'; document.getElementById('generatedTitleHidden').value = pageTitle; document.getElementById('generatedContentHidden').value = extract + '\n\n(Source: Wikipedia)'; // Set color to purple for AI-generated notes selectColor('purple'); generatedPreview.classList.remove('hidden'); showToast('Note generated successfully!'); } catch (error) { console.error('Error:', error); showToast('Failed to generate note. Try a different topic.'); } finally { loadingState.classList.add('hidden'); generateBtn.disabled = false; generateBtn.innerHTML = 'Search'; lucide.createIcons(); } } // Handle Form Submit function handleSubmit(e) { e.preventDefault(); let title, content; if (currentMode === 'auto') { title = document.getElementById('generatedTitleHidden').value.trim(); content = document.getElementById('generatedContentHidden').value.trim(); if (!title || !content) { showToast('Please generate a note first'); return; } } else { title = document.getElementById('noteTitle').value.trim(); content = document.getElementById('noteContent').value.trim(); } if (!title || !content) return; if (editingId) { // Update existing note const index = notes.findIndex(n => n.id === editingId); if (index !== -1) { notes[index] = { ...notes[index], title, content, color: currentColor, pinned: isPinned, updatedAt: new Date().toISOString() }; showToast('Note updated successfully'); } } else { // Create new note const newNote = { id: Date.now().toString(), title, content, color: currentColor, pinned: isPinned, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), autoGenerated: currentMode === 'auto' }; notes.unshift(newNote); showToast(currentMode === 'auto' ? 'AI note saved successfully!' : 'Note created successfully'); } saveNotes(); renderNotes(); closeModal(); } // Delete Note function deleteNote(id) { if (confirm('Are you sure you want to delete this note?')) { notes = notes.filter(n => n.id !== id); saveNotes(); renderNotes(); showToast('Note deleted'); } } // Modal Functions function openModal(noteId = null) { const modal = document.getElementById('noteModal'); const modalContent = document.getElementById('modalContent'); const form = document.getElementById('noteForm'); editingId = noteId; if (noteId) { const note = notes.find(n => n.id === noteId); if (note) { document.getElementById('modalTitle').textContent = 'Edit Note'; document.getElementById('noteId').value = note.id; document.getElementById('noteTitle').value = note.title; document.getElementById('noteContent').value = note.content; selectColor(note.color); isPinned = note.pinned; updatePinButton(); } } else { document.getElementById('modalTitle').textContent = 'Create Note'; form.reset(); selectColor('yellow'); isPinned = false; updatePinButton(); } modal.classList.remove('hidden'); modal.classList.add('flex'); setTimeout(() => { modal.classList.add('modal-enter'); }, 10); // Focus title after animation setTimeout(() => { document.getElementById('noteTitle').focus(); }, 100); } function closeModal() { const modal = document.getElementById('noteModal'); const modalContent = document.getElementById('modalContent'); modal.classList.remove('modal-enter'); setTimeout(() => { modal.classList.add('hidden'); modal.classList.remove('flex'); editingId = null; }, 300); } // Color Selection function selectColor(color) { currentColor = color; // Update UI document.querySelectorAll('.color-btn').forEach(btn => { btn.classList.remove('selected'); if (btn.dataset.color === color) { btn.classList.add('selected'); } }); } // Pin Toggle function togglePin() { isPinned = !isPinned; updatePinButton(); } function updatePinButton() { const btn = document.getElementById('pinBtn'); if (isPinned) { btn.classList.add('pin-active'); btn.innerHTML = ''; } else { btn.classList.remove('pin-active'); btn.innerHTML = ''; } lucide.createIcons(); } // Search Handler function handleSearch(e) { renderNotes(); } // Filter Handler function filterNotes(filter) { currentFilter = filter; // Update buttons document.querySelectorAll('.filter-btn').forEach(btn => { if (btn.dataset.filter === filter) { btn.classList.add('active'); } else { btn.classList.remove('active'); } }); renderNotes(); } // Update Stats function updateStats() { const count = notes.length; document.getElementById('notesCount').textContent = `${count} note${count !== 1 ? 's' : ''}`; } // Toast Notification function showToast(message) { const toast = document.getElementById('toast'); document.getElementById('toastMessage').textContent = message; toast.classList.remove('translate-y-20', 'opacity-0'); setTimeout(() => { toast.classList.add('translate-y-20', 'opacity-0'); }, 3000); }