-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp_1.js
More file actions
863 lines (743 loc) · 29 KB
/
app_1.js
File metadata and controls
863 lines (743 loc) · 29 KB
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
// Datos de ejemplo y configuración
const ejemplosTranscripcion = [
"Esta es una nota dictada sobre el proyecto de desarrollo web que estamos trabajando en la oficina.",
"Reunión de equipo programada para mañana a las 10:00 AM para revisar el progreso del trimestre.",
"Ideas para mejorar la experiencia del usuario en la aplicación móvil que estamos desarrollando.",
"Lista de tareas pendientes: revisar código, actualizar documentación, preparar presentación para clientes.",
"Notas de la conferencia sobre inteligencia artificial y sus aplicaciones en el desarrollo web moderno.",
"Brainstorming de características nuevas para implementar en la próxima versión de la aplicación."
];
const configuracionMejoras = {
claridad: {
nombre: "Mejorar Claridad",
descripcion: "Hace el texto más claro y directo",
icono: "✨",
visible: true
},
formal: {
nombre: "Hacer Formal",
descripcion: "Convierte el texto a un tono más formal",
icono: "🎩",
visible: false
},
casual: {
nombre: "Hacer Casual",
descripcion: "Convierte el texto a un tono más casual",
icono: "😊",
visible: false
},
narrativo: {
nombre: "Narrativo",
descripcion: "Mejora textos narrativos y diálogos de novela",
icono: "📖",
visible: false
},
academico_v2: {
nombre: "Académico v2",
descripcion: "Mejora académica con cambios mínimos, preservando palabras del autor",
icono: "🎓",
visible: true
},
resumir: {
nombre: "Resumir",
descripcion: "Crea un resumen conciso del texto",
icono: "📝",
visible: false
},
expandir: {
nombre: "Expandir",
descripcion: "Añade más detalles y contexto",
icono: "✚",
visible: true
}
};
function safeSetInnerHTML(element, html) {
element.innerHTML = DOMPurify.sanitize(html);
}
// Clase principal de la aplicación
class NotesApp {
constructor() {
this.notes = [];
this.currentNote = null;
this.noteToDelete = null;
this.isRecording = false;
this.autoSaveTimeout = null;
this.searchTerm = '';
this.selectedText = '';
this.selectedRange = null;
this.init();
}
async init() {
this.loadNotes();
this.setupEventListeners();
this.renderNotesList();
this.setupDefaultNote();
// Migrar notas existentes sin ID
await this.migrateExistingNotes();
}
async migrateExistingNotes() {
try {
const response = await fetch('/api/cleanup-notes', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});
if (response.ok) {
const result = await response.json();
if (result.migrated_count > 0) {
console.log(`Migradas ${result.migrated_count} notas a la nueva estructura`);
}
}
} catch (error) {
console.log('Error al migrar notas existentes:', error);
}
}
// Configurar event listeners
setupEventListeners() {
// Botón nueva nota
document.getElementById('new-note-btn').addEventListener('click', () => {
this.createNewNote();
});
// Búsqueda
document.getElementById('search-input').addEventListener('input', (e) => {
this.searchTerm = e.target.value.toLowerCase();
this.renderNotesList();
});
// Grabación
document.getElementById('record-btn').addEventListener('click', () => {
this.toggleRecording();
});
// Botones de IA
document.querySelectorAll('.ai-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
const action = e.currentTarget.dataset.action;
this.improveText(action);
});
});
// Editor
const editor = document.getElementById('editor');
editor.addEventListener('input', () => {
this.handleEditorChange();
});
// Selección de texto en el editor
editor.addEventListener('mouseup', () => {
this.updateSelectedText();
});
editor.addEventListener('keyup', () => {
this.updateSelectedText();
});
// Título de nota
document.getElementById('note-title').addEventListener('input', () => {
this.handleTitleChange();
});
// Botones de formato
document.querySelectorAll('.format-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
const format = e.currentTarget.dataset.format;
this.applyFormat(format);
});
});
// Botones de acción
document.getElementById('save-btn').addEventListener('click', () => {
this.saveCurrentNote();
});
document.getElementById('delete-btn').addEventListener('click', () => {
this.showDeleteModal();
});
// Modal de confirmación
document.getElementById('cancel-delete').addEventListener('click', () => {
this.hideDeleteModal();
});
document.getElementById('confirm-delete').addEventListener('click', () => {
if (this.noteToDelete) {
// Deleting a specific note
this.deleteSpecificNote(this.noteToDelete);
this.noteToDelete = null;
} else {
// Deleting the current note
this.deleteCurrentNote();
}
});
// Auto-guardado cada 30 segundos
setInterval(() => {
if (this.currentNote) {
this.saveCurrentNote(true);
}
}, 30000);
}
// Actualizar texto seleccionado
updateSelectedText() {
const selection = window.getSelection();
this.selectedText = selection.toString().trim();
if (this.selectedText && selection.rangeCount > 0) {
this.selectedRange = selection.getRangeAt(0).cloneRange();
this.updateAIButtonsState(false);
} else {
this.selectedRange = null;
this.updateAIButtonsState(true);
}
}
// Actualizar estado de botones de IA
updateAIButtonsState(disabled) {
document.querySelectorAll('.ai-btn').forEach(btn => {
btn.disabled = disabled;
btn.style.opacity = disabled ? '0.5' : '1';
});
}
// Gestión de notas
loadNotes() {
const saved = localStorage.getItem('notes-app-data');
if (saved) {
this.notes = JSON.parse(saved);
} else {
// Example note on first run
this.notes = [{
id: 1,
title: "Example Note",
content: "This is a sample note to demonstrate the application's features. You can edit it, delete it or create new notes.",
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString()
}];
this.saveToStorage();
}
}
saveToStorage() {
localStorage.setItem('notes-app-data', JSON.stringify(this.notes));
}
createNewNote() {
const now = new Date();
const newNote = {
id: Date.now(),
title: `Note ${now.toLocaleDateString()} ${now.toLocaleTimeString()}`,
content: '',
createdAt: now.toISOString(),
updatedAt: now.toISOString()
};
this.notes.unshift(newNote);
this.saveToStorage();
this.renderNotesList();
this.selectNote(newNote.id);
// Enfocar el título para edición
setTimeout(() => {
document.getElementById('note-title').focus();
document.getElementById('note-title').select();
}, 100);
}
selectNote(noteId) {
this.currentNote = this.notes.find(note => note.id === noteId);
if (this.currentNote) {
this.loadNoteToEditor();
this.updateNoteSelection();
}
}
loadNoteToEditor() {
if (!this.currentNote) return;
document.getElementById('note-title').value = this.currentNote.title;
safeSetInnerHTML(document.getElementById('editor'), this.currentNote.content);
// Habilitar botones
document.getElementById('save-btn').disabled = false;
document.getElementById('delete-btn').disabled = false;
// Restablecer selección
this.selectedText = '';
this.selectedRange = null;
this.updateAIButtonsState(true);
}
updateNoteSelection() {
document.querySelectorAll('.note-item').forEach(item => {
item.classList.remove('active');
});
if (this.currentNote) {
const activeItem = document.querySelector(`[data-note-id="${this.currentNote.id}"]`);
if (activeItem) {
activeItem.classList.add('active');
}
}
}
handleEditorChange() {
if (!this.currentNote) return;
clearTimeout(this.autoSaveTimeout);
this.autoSaveTimeout = setTimeout(() => {
this.saveCurrentNote(true);
}, 2000);
}
handleTitleChange() {
if (!this.currentNote) return;
clearTimeout(this.autoSaveTimeout);
this.autoSaveTimeout = setTimeout(() => {
this.saveCurrentNote(true);
}, 1000);
}
saveCurrentNote(silent = false) {
if (!this.currentNote) return;
const title = document.getElementById('note-title').value.trim();
const content = document.getElementById('editor').innerHTML;
this.currentNote.title = title || 'Untitled Note';
this.currentNote.content = content;
this.currentNote.updatedAt = new Date().toISOString();
// Save to local storage
this.saveToStorage();
this.renderNotesList();
this.updateNoteSelection();
// Save to server as markdown file
this.saveNoteToServer(silent);
if (!silent) {
this.showNotification('Note saved successfully');
}
}
async saveNoteToServer(silent = false) {
if (!this.currentNote) return;
try {
const response = await fetch('/api/save-note', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
id: this.currentNote.id,
title: this.currentNote.title,
content: this.currentNote.content
})
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
if (!silent && result.success) {
console.log(`Note saved on server: ${result.filename}`);
}
} catch (error) {
console.error('Error al guardar nota en servidor:', error);
if (!silent) {
this.showNotification('Error al guardar nota en servidor', 'error');
}
}
}
deleteCurrentNote() {
if (!this.currentNote) return;
// Store the note ID before removing it from the array
const noteIdToDelete = this.currentNote.id;
this.notes = this.notes.filter(note => note.id !== this.currentNote.id);
this.saveToStorage();
this.renderNotesList();
// Delete from server
this.deleteNoteFromServer(noteIdToDelete);
this.currentNote = null;
this.setupDefaultNote();
this.hideDeleteModal();
this.showNotification('Note deleted');
}
async deleteNoteFromServer(noteId) {
try {
const response = await fetch('/api/delete-note', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
id: noteId
})
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
if (result.success && result.filename) {
console.log(`Archivo eliminado del servidor: ${result.filename}`);
}
} catch (error) {
console.error('Error al eliminar nota del servidor:', error);
}
}
setupDefaultNote() {
if (this.notes.length > 0) {
this.selectNote(this.notes[0].id);
} else {
document.getElementById('note-title').value = '';
document.getElementById('editor').innerHTML = '';
document.getElementById('save-btn').disabled = true;
document.getElementById('delete-btn').disabled = true;
}
}
// Renderizado de lista
renderNotesList() {
const container = document.getElementById('notes-list');
let filteredNotes = this.notes;
if (this.searchTerm) {
filteredNotes = this.notes.filter(note =>
note.title.toLowerCase().includes(this.searchTerm) ||
note.content.toLowerCase().includes(this.searchTerm)
);
}
if (filteredNotes.length === 0) {
container.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon">📝</div>
<h3>No notes yet</h3>
<p>Create your first note to get started</p>
</div>
`;
return;
}
safeSetInnerHTML(container, filteredNotes.map(note => {
const preview = this.getTextPreview(note.content);
const date = new Date(note.createdAt).toLocaleDateString();
return `
<div class="note-item fade-in" data-note-id="${note.id}">
<div class="note-item-content">
<div class="note-item-title">${note.title}</div>
<div class="note-item-preview">${preview}</div>
<div class="note-item-date">${date}</div>
</div>
<div class="note-item-actions">
<button class="note-delete-btn" data-note-id="${note.id}" title="Delete note">
<i class="fas fa-trash"></i>
</button>
</div>
</div>
`;
}).join(''));
// Agregar event listeners a los items
container.querySelectorAll('.note-item').forEach(item => {
// Click event for the note content (not the delete button)
const noteContent = item.querySelector('.note-item-content');
if (noteContent) {
noteContent.addEventListener('click', () => {
const noteId = parseInt(item.dataset.noteId);
this.selectNote(noteId);
});
}
});
// Add event listeners for delete buttons
container.querySelectorAll('.note-delete-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
e.stopPropagation();
const noteId = parseInt(btn.dataset.noteId);
this.showDeleteNoteModal(noteId);
});
});
}
getTextPreview(html) {
const temp = document.createElement('div');
safeSetInnerHTML(temp, html);
const text = temp.textContent || temp.innerText || '';
return text.length > 100 ? text.substring(0, 100) + '...' : text;
}
// Transcripción
toggleRecording() {
if (this.isRecording) {
this.stopRecording();
} else {
this.startRecording();
}
}
startRecording() {
this.isRecording = true;
const recordBtn = document.getElementById('record-btn');
const recordIcon = document.getElementById('record-icon');
const recordText = document.getElementById('record-text');
const recordingStatus = document.getElementById('recording-status');
const recordingIndicator = document.getElementById('recording-indicator');
recordBtn.classList.add('btn--error');
recordIcon.className = 'fas fa-stop';
recordText.textContent = 'Detener';
recordingStatus.querySelector('.status-text').textContent = 'Grabando...';
recordingIndicator.classList.add('active');
// Simular transcripción después de 3-5 segundos
const duration = 3000 + Math.random() * 2000;
setTimeout(() => {
if (this.isRecording) {
this.stopRecording();
}
}, duration);
}
stopRecording() {
this.isRecording = false;
const recordBtn = document.getElementById('record-btn');
const recordIcon = document.getElementById('record-icon');
const recordText = document.getElementById('record-text');
const recordingStatus = document.getElementById('recording-status');
const recordingIndicator = document.getElementById('recording-indicator');
recordBtn.classList.remove('btn--error');
recordIcon.className = 'fas fa-microphone';
recordText.textContent = 'Record';
recordingStatus.querySelector('.status-text').textContent = 'Transcribing...';
recordingIndicator.classList.remove('active');
// Simular procesamiento
setTimeout(() => {
this.insertTranscription();
recordingStatus.querySelector('.status-text').textContent = 'Ready to record';
}, 1500);
}
insertTranscription() {
const transcription = ejemplosTranscripcion[Math.floor(Math.random() * ejemplosTranscripcion.length)];
const editor = document.getElementById('editor');
// Enfocar el editor
editor.focus();
// Obtener posición del cursor o insertar al final
const selection = window.getSelection();
let range;
if (selection.rangeCount > 0) {
range = selection.getRangeAt(0);
} else {
range = document.createRange();
range.selectNodeContents(editor);
range.collapse(false);
}
// Insertar texto
const textNode = document.createTextNode(transcription + ' ');
range.insertNode(textNode);
range.setStartAfter(textNode);
range.setEndAfter(textNode);
selection.removeAllRanges();
selection.addRange(range);
// Disparar evento de cambio
this.handleEditorChange();
this.showNotification('Transcripción completada');
}
// Mejora con IA
improveText(action) {
// Verificar si hay texto seleccionado
if (!this.selectedText || !this.selectedRange) {
this.showNotification('Please select text to improve with AI', 'warning');
return;
}
this.showProcessingOverlay(`Improving text with AI...`);
// Simular procesamiento de IA
setTimeout(() => {
const improvedText = this.applyAIImprovement(this.selectedText, action);
// Restaurar selección y reemplazar texto
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(this.selectedRange);
// Reemplazar texto seleccionado
this.selectedRange.deleteContents();
this.selectedRange.insertNode(document.createTextNode(improvedText));
// Limpiar selección
selection.removeAllRanges();
this.selectedText = '';
this.selectedRange = null;
this.updateAIButtonsState(true);
this.hideProcessingOverlay();
this.showNotification(`Texto mejorado: ${configuracionMejoras[action].nombre}`);
this.handleEditorChange();
}, 2000);
}
applyAIImprovement(text, action) {
const mejoras = {
claridad: (texto) => {
return texto
.replace(/eh|um|ah|mmm|ahhh/g, '')
.replace(/\s+/g, ' ')
.trim() + ' [Texto mejorado para mayor claridad]';
},
formal: (texto) => {
return texto
.replace(/eh|um|ah|mmm|ahhh/g, '')
.replace(/muy/g, 'sumamente')
.replace(/bueno/g, 'excelente')
.replace(/bien/g, 'de manera adecuada')
.replace(/creo que/g, 'considero que') + ' [Versión formal]';
},
casual: (texto) => {
return texto
.replace(/eh|um|ah|mmm|ahhh/g, '')
.replace(/sumamente/g, 'súper')
.replace(/excelente/g, 'genial')
.replace(/considero que/g, 'creo que') + ' [Versión casual]';
},
narrativo: (texto) => {
return texto
.replace(/\b(y entonces|y luego)\b/g, 'después')
.replace(/\b(muy)\b/g, 'sumamente')
.replace(/\bdijo\b/g, 'murmuró') + ' [Versión narrativa mejorada]';
},
academico_v2: (texto) => {
return texto
.replace(/eh|um|ah|mmm|ahhh/g, '')
.replace(/\s+/g, ' ')
.trim() + ' [Mejora académica con cambios mínimos]';
},
resumir: (texto) => {
const words = texto.split(' ');
const summary = words.slice(0, Math.min(20, words.length)).join(' ');
return `Resumen: ${summary}${words.length > 20 ? '...' : ''}`;
},
expandir: (texto) => {
return texto + ' [Se han añadido detalles adicionales y contexto relevante para enriquecer el contenido y proporcionar una comprensión más completa del tema tratado.]';
}
};
return mejoras[action] ? mejoras[action](text) : text;
}
// Formato de texto
applyFormat(format) {
const editor = document.getElementById('editor');
editor.focus();
switch (format) {
case 'bold':
document.execCommand('bold', false, null);
break;
case 'italic':
document.execCommand('italic', false, null);
break;
case 'underline':
document.execCommand('underline', false, null);
break;
case 'ul':
document.execCommand('insertUnorderedList', false, null);
break;
case 'ol':
document.execCommand('insertOrderedList', false, null);
break;
}
this.updateFormatButtons();
this.handleEditorChange();
}
updateFormatButtons() {
const formatButtons = document.querySelectorAll('.format-btn');
formatButtons.forEach(btn => {
const format = btn.dataset.format;
let isActive = false;
switch (format) {
case 'bold':
isActive = document.queryCommandState('bold');
break;
case 'italic':
isActive = document.queryCommandState('italic');
break;
case 'underline':
isActive = document.queryCommandState('underline');
break;
}
btn.classList.toggle('active', isActive);
});
}
// Modales y overlays
showDeleteModal() {
const modal = document.getElementById('delete-modal');
modal.classList.add('active');
}
hideDeleteModal() {
const modal = document.getElementById('delete-modal');
modal.classList.remove('active');
}
showDeleteNoteModal(noteId) {
this.noteToDelete = noteId;
const modal = document.getElementById('delete-modal');
modal.classList.add('active');
}
async deleteSpecificNote(noteId) {
// Store the note to delete
const noteToDelete = this.notes.find(note => note.id === noteId);
if (!noteToDelete) {
console.error('Note not found');
return;
}
// Remove from notes array
this.notes = this.notes.filter(note => note.id !== noteId);
this.saveToStorage();
// If this was the current note, clear it
if (this.currentNote && this.currentNote.id === noteId) {
this.currentNote = null;
this.setupDefaultNote();
}
// Refresh current view
this.renderNotesList();
// Delete from server
this.deleteNoteFromServer(noteId);
this.hideDeleteModal();
this.showNotification('Note deleted');
}
showProcessingOverlay(text) {
const overlay = document.getElementById('processing-overlay');
const textElement = document.getElementById('processing-text');
textElement.textContent = text;
overlay.classList.add('active');
}
hideProcessingOverlay() {
const overlay = document.getElementById('processing-overlay');
overlay.classList.remove('active');
}
// Notificaciones
showNotification(message, type = 'success') {
// Crear elemento de notificación
const notification = document.createElement('div');
notification.className = `notification notification--${type}`;
safeSetInnerHTML(notification, `
<div class="notification-content">
<span class="notification-icon">${type === 'success' ? '✓' : type === 'warning' ? '⚠' : 'ℹ'}</span>
<span class="notification-message">${message}</span>
</div>
`);
// Estilos inline para la notificación
Object.assign(notification.style, {
position: 'fixed',
top: '20px',
right: '20px',
padding: '12px 16px',
borderRadius: '8px',
backgroundColor: type === 'success' ? 'var(--color-success)' :
type === 'warning' ? 'var(--color-warning)' : 'var(--color-info)',
color: 'white',
fontSize: '14px',
fontWeight: '500',
zIndex: '3000',
opacity: '0',
transform: 'translateY(-10px)',
transition: 'all 0.3s ease',
boxShadow: '0 4px 12px rgba(0, 0, 0, 0.1)'
});
document.body.appendChild(notification);
// Animar entrada
setTimeout(() => {
notification.style.opacity = '1';
notification.style.transform = 'translateY(0)';
}, 100);
// Remover después de 3 segundos
setTimeout(() => {
notification.style.opacity = '0';
notification.style.transform = 'translateY(-10px)';
setTimeout(() => {
if (notification.parentNode) {
notification.parentNode.removeChild(notification);
}
}, 300);
}, 3000);
}
}
// Inicializar la aplicación cuando se carga la página
document.addEventListener('DOMContentLoaded', () => {
window.notesApp = new NotesApp();
});
// Actualizar botones de formato cuando cambia la selección
document.addEventListener('selectionchange', () => {
const editor = document.getElementById('editor');
if (editor && editor.contains(document.getSelection().anchorNode)) {
// Pequeño delay para que se actualice el estado
setTimeout(() => {
if (window.notesApp) {
window.notesApp.updateFormatButtons();
window.notesApp.updateSelectedText();
}
}, 10);
}
});
// Manejar atajos de teclado
document.addEventListener('keydown', (e) => {
if (e.ctrlKey || e.metaKey) {
switch (e.key) {
case 's':
e.preventDefault();
if (window.notesApp && window.notesApp.currentNote) {
window.notesApp.saveCurrentNote();
}
break;
case 'n':
e.preventDefault();
if (window.notesApp) {
window.notesApp.createNewNote();
}
break;
}
}
});