File size: 15,278 Bytes
69fd44b 5c34d3b 69fd44b 5c34d3b 69fd44b 5c34d3b 69fd44b 5c34d3b 69fd44b 5c34d3b 69fd44b 5c34d3b 69fd44b 5c34d3b 69fd44b 5c34d3b 69fd44b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 | // 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 ? `
<div class="absolute top-5 right-5 flex items-center gap-1 bg-purple-600 text-white text-[10px] px-2 py-1 rounded-full font-bold uppercase tracking-wider shadow-sm">
<i data-lucide="sparkles" class="w-3 h-3"></i>
<span>AI</span>
</div>
` : (note.pinned ? '<i data-lucide="pin" class="w-4 h-4 text-gray-700 absolute top-5 right-5 fill-current"></i>' : '');
div.innerHTML = `
<div class="flex items-start justify-between mb-3">
<h3 class="font-bold text-gray-900 text-lg leading-tight pr-8 line-clamp-2">${escapeHtml(note.title)}</h3>
${aiBadge}
</div>
<p class="text-gray-700 text-sm leading-relaxed mb-4 line-clamp-3 whitespace-pre-wrap">${escapeHtml(note.content)}</p>
<div class="flex items-center justify-between pt-3 border-t border-black border-opacity-10">
<span class="text-xs text-gray-600 font-medium">${date}</span>
<div class="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
<button onclick="deleteNote('${note.id}')" class="action-btn p-2 hover:bg-black hover:bg-opacity-10 rounded-full transition-colors text-gray-700">
<i data-lucide="trash-2" class="w-4 h-4"></i>
</button>
</div>
</div>
`;
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 = '<div class="animate-spin w-4 h-4 border-2 border-white border-t-transparent rounded-full"></div>';
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 = '<i data-lucide="search" class="w-4 h-4"></i><span>Search</span>';
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 = '<i data-lucide="pin" class="w-5 h-5 fill-current"></i>';
} else {
btn.classList.remove('pin-active');
btn.innerHTML = '<i data-lucide="pin" class="w-5 h-5"></i>';
}
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);
} |