-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
1643 lines (1420 loc) · 75.8 KB
/
Copy pathmain.js
File metadata and controls
1643 lines (1420 loc) · 75.8 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
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// main.js
import AuthService from "./services/AuthService.js";
import FirestoreService from "./services/FirestoreService.js";
import LocalStorageService from "./services/LocalStorageService.js";
import AppState from "./state/AppState.js"; // Importa la instancia singleton
import { debounce } from "./utils/helpers.js";
import { getElement, getElements } from "./utils/dom.js";
import { alertModal, confirmModal } from "./components/Modal.js"; // alertModal y confirmModal
import { noteListModal } from "./components/Modal.js"; // NUEVO: Importa el noteListModal
import ClockWidget from "./widgets/ClockWidget.js";
import CalendarWidget from "./widgets/CalendarWidget.js";
import TimerWidget from "./widgets/TimerWidget.js";
import YoutubeWidget from "./widgets/YoutubeWidget.js";
import QuoteWidget from "./widgets/QuoteWidget.js";
import TasksWidget from "./widgets/TasksWidget.js";
import WeatherWidget from "./widgets/WeatherWidget.js";
import Note from "./components/Note.js";
import Zone from "./components/Zone.js";
import { CONSTANTS, USE_FIREBASE } from "./config.js"; // Para usar constantes compartidas
// IMPORTACIÓN NUEVA: Monitoreo de estado de red
import { initNetworkStatusMonitor } from './utils/networkStatus.js';
// IMPORTACIÓN NUEVA: Animación del cielo
import { initSkyAnimation } from './utils/sky-animation.js';
class App {
constructor() {
this.state = AppState; // Usa la instancia singleton de AppState
this.authService = null; // Se inicializará en init() para evitar condiciones de carrera
this.dataService = null; // Servicio de datos (Firestore o LocalStorage)
this.DOMElements = {}; // Cache de los elementos DOM principales
this.widgets = {}; // Almacena instancias de los widgets
this.noteInstances = new Map(); // Almacena instancias de Note
this.zoneInstances = new Map(); // Almacena instancias de Zone
this.currentSliderZoneId = null; // NUEVO: para saber en qué zona estamos en el slider
// NUEVO: Estado para el pan y zoom del espacio de trabajo
this.pan = { x: 0, y: 0, scale: 1 };
this.isPanning = false;
this.lastMousePos = { x: 0, y: 0 };
// Debounce para guardar datos en Firestore
this.debounceRemoteSave = debounce(this._saveDataToRemote.bind(this), 1500);
}
init() {
this.cacheDOM();
this.applyInitialTheme();
if (localStorage.getItem('dashboardIsHidden') === 'true') {
this.DOMElements.body.classList.add('dashboard-hidden');
}
this.createSliderPlaceholder();
this.bindGlobalEvents();
this.setupWidgets();
if (USE_FIREBASE) {
this.authService = new AuthService(this.handleAuthStateChange.bind(this));
} else {
// En modo local, disparamos el cambio de estado manualmente
this.enterLocalMode();
}
}
cacheDOM() {
this.DOMElements.body = document.body;
this.DOMElements.appContainer = getElement('#app');
this.DOMElements.workspace = getElement('#workspace');
this.DOMElements.signInBtn = getElement('#google-signin-btn');
this.DOMElements.localSignInBtn = getElement('#local-signin-btn');
this.DOMElements.workspaceTitle = getElement('#workspace-title');
this.DOMElements.addNoteBtn = getElement('#addNoteBtn');
this.DOMElements.addZoneBtn = getElement('#addZoneBtn');
this.DOMElements.showGeneralBtn = getElement('#show-general-btn');
this.DOMElements.saveStatus = getElement('#save-status');
this.DOMElements.profileAvatar = getElement('#profile-avatar');
this.DOMElements.userName = getElement('#user-name');
this.DOMElements.signOutBtn = getElement('#signout-btn');
this.DOMElements.bottomDashboard = getElement('#bottom-dashboard');
this.DOMElements.sidebarToggleBtn = getElement('#sidebar-toggle-btn');
this.DOMElements.mobileSidebar = getElement('#mobile-sidebar');
this.DOMElements.sidebarOverlay = getElement('.sidebar-overlay');
this.DOMElements.sidebarContent = getElement('#mobile-sidebar .sidebar-content');
this.DOMElements.closeSidebarBtn = getElement('#close-sidebar-btn');
this.DOMElements.dashboardToggle = getElement('#dashboard-toggle');
this.DOMElements.fabContainer = getElement('#mobile-fab-container');
this.DOMElements.fabToggleBtn = getElement('#fab-toggle-btn');
this.DOMElements.fabAddNoteBtn = getElement('#fab-add-note');
this.DOMElements.fabAddZoneBtn = getElement('#fab-add-zone');
this.DOMElements.loaderOverlay = getElement('#loader-overlay');
this.DOMElements.themeToggleBtn = getElement('#theme-toggle-btn');
// NUEVO: Controles de zoom
this.DOMElements.zoomControls = getElement('#zoom-controls');
this.DOMElements.zoomInBtn = getElement('#zoom-in-btn');
this.DOMElements.zoomOutBtn = getElement('#zoom-out-btn');
this.DOMElements.zoomResetBtn = getElement('#zoom-reset-btn');
// NUEVO: Elementos para la funcionalidad de la lista de notas
this.DOMElements.statsWidget = getElement('#stats-widget');
this.DOMElements.noteListModalOverlay = getElement('#note-list-modal-overlay');
this.DOMElements.noteListContainer = getElement('#note-list-container', this.DOMElements.noteListModalOverlay);
this.DOMElements.noNotesMessage = getElement('.no-notes-message', this.DOMElements.noteListModalOverlay);
// NUEVO: Elementos para el slider de notas de zona
this.DOMElements.sliderOverlay = getElement('#slider-overlay');
this.DOMElements.sliderPanel = getElement('#zone-notes-slider');
this.DOMElements.sliderTitle = getElement('#slider-zone-title');
this.DOMElements.sliderCloseBtn = getElement('#slider-close-btn');
this.DOMElements.sliderNotesList = getElement('#slider-notes-list');
this.DOMElements.sliderNoteContent = getElement('#slider-note-content');
this.DOMElements.sliderAddNoteBtn = getElement('#slider-add-note-btn');
}
createSliderPlaceholder() {
const placeholder = document.createElement('div');
placeholder.className = 'slider-no-note-selected';
placeholder.innerHTML = '<p>Selecciona una nota de la lista para verla aquí.</p>';
this.DOMElements.sliderNoNoteSelected = placeholder;
}
bindGlobalEvents() {
if (this.DOMElements.signInBtn) {
this.DOMElements.signInBtn.addEventListener('click', () => { if (this.authService) this.authService.signIn(); });
}
if (this.DOMElements.localSignInBtn) {
this.DOMElements.localSignInBtn.addEventListener('click', () => this.enterLocalMode());
}
this.DOMElements.signOutBtn.addEventListener('click', () => { if (this.authService) this.authService.signOut(); });
this.DOMElements.addNoteBtn.addEventListener('click', () => this.addNote()); // Calls _triggerSave
this.DOMElements.addZoneBtn.addEventListener('click', () => this.addZone()); // Calls _triggerSave
this.DOMElements.showGeneralBtn.addEventListener('click', () => { this.showGeneralDashboard(); this.closeSidebar(); });
this.DOMElements.workspaceTitle.addEventListener('click', () => { if (window.innerWidth <= CONSTANTS.MOBILE_BREAKPOINT) { this.showGeneralDashboard(); this.closeSidebar(); } });
this.DOMElements.themeToggleBtn.addEventListener('click', () => this.toggleTheme());
const toggleSidebar = () => {
const isActive = this.DOMElements.body.classList.toggle('sidebar-active');
if (isActive && this.mobileWidgets.youtube) {
this.mobileWidgets.youtube.manualInit();
}
};
this.DOMElements.sidebarToggleBtn.addEventListener('click', toggleSidebar);
this.DOMElements.sidebarOverlay.addEventListener('click', toggleSidebar);
this.DOMElements.closeSidebarBtn.addEventListener('click', toggleSidebar);
this.DOMElements.dashboardToggle.addEventListener('click', () => {
const isHidden = this.DOMElements.body.classList.toggle('dashboard-hidden');
localStorage.setItem('dashboardIsHidden', isHidden);
});
this.DOMElements.fabToggleBtn.addEventListener('click', () => this.DOMElements.fabContainer.classList.toggle('fab-active'));
this.DOMElements.fabAddNoteBtn.addEventListener('click', () => { this.addNote(); this.DOMElements.fabContainer.classList.remove('fab-active'); });
this.DOMElements.fabAddZoneBtn.addEventListener('click', () => { this.addZone(); this.DOMElements.fabContainer.classList.remove('fab-active'); });
// NUEVO: Eventos de Pan y Zoom para el escritorio
if (window.innerWidth > CONSTANTS.MOBILE_BREAKPOINT) {
this.DOMElements.appContainer.addEventListener('mousedown', this.handlePanStart.bind(this));
this.DOMElements.appContainer.addEventListener('wheel', this.handleZoom.bind(this), { passive: false });
// Los listeners de movimiento y soltar se añaden al documento para capturar el movimiento fuera de la ventana
document.addEventListener('mousemove', this.handlePanMove.bind(this));
document.addEventListener('mouseup', this.handlePanEnd.bind(this));
document.addEventListener('mouseleave', this.handlePanEnd.bind(this)); // Termina el paneo si el ratón sale de la ventana
}
// Evento para el widget de notas (APLICADO AL ORIGINAL EN DESKTOP)
// El clonado en móvil tendrá su propio listener en setupWidgets()
if (this.DOMElements.statsWidget) {
this.DOMElements.statsWidget.addEventListener('click', () => this.showAllNotesList());
}
// NUEVO: Eventos para los botones de zoom
if (this.DOMElements.zoomInBtn) {
this.DOMElements.zoomInBtn.addEventListener('click', () => this.zoomIn());
this.DOMElements.zoomOutBtn.addEventListener('click', () => this.zoomOut());
this.DOMElements.zoomResetBtn.addEventListener('click', () => this.resetZoom());
}
// Listener para cerrar la vista de zoom de una nota al hacer clic fuera de ella.
document.addEventListener('click', (e) => {
if (this.DOMElements.body.classList.contains('note-view-active')) {
const zoomedNote = getElement('.note-zoomed');
// Si hay una nota con zoom y el clic fue fuera de ella, o si no hay nota con zoom (estado fantasma), limpiar.
if (zoomedNote && !zoomedNote.contains(e.target)) {
this.clearZoomState();
} else if (!zoomedNote) { // Corrige el estado de "desenfoque" si no hay nota ampliada
this.clearZoomState();
}
}
});
// NUEVO: Eventos para el slider de notas de zona
this.DOMElements.sliderCloseBtn.addEventListener('click', () => this.closeZoneNotesViewer());
this.DOMElements.sliderOverlay.addEventListener('click', () => this.closeZoneNotesViewer());
this.DOMElements.sliderAddNoteBtn.addEventListener('click', () => this.handleSliderAddNote());
// Evento para seleccionar una nota de la lista en el slider
this.DOMElements.sliderNotesList.addEventListener('click', e => {
const noteItem = e.target.closest('.slider-note-item');
if (noteItem && noteItem.dataset.noteId) {
const noteId = parseFloat(noteItem.dataset.noteId);
this.renderSliderContent(noteId);
}
});
// Evento para guardar el contenido de la nota al escribir en el slider
this.DOMElements.sliderNoteContent.addEventListener('input', e => {
const target = e.target; // Si se edita el contenido
if (target.tagName.toLowerCase() === 'textarea') {
this.handleSliderContentChange(target); // Si se edita el nombre de una pestaña
} else if (target.classList.contains('slider-note-tab')) {
this.handleSliderTabNameChange(target);
}
});
// NUEVO: Evento para cambiar de pestaña DENTRO del slider
this.DOMElements.sliderNoteContent.addEventListener('click', e => {
const tabBtn = e.target.closest('.slider-note-tab');
// Si se hace clic en una pestaña y NO es la que ya está activa, cambiar de pestaña.
// Si es la activa, no hacer nada para permitir que el usuario la edite.
if (tabBtn && !tabBtn.classList.contains('active')) {
const noteId = parseFloat(tabBtn.dataset.noteId);
const newTabIndex = parseInt(tabBtn.dataset.tabIndex);
const noteData = this.state.getNotes().find(n => n.id === noteId);
if (noteData && noteData.activeTabIndex !== newTabIndex) {
noteData.activeTabIndex = newTabIndex;
this.updateNote(noteData); // Guardar el cambio de pestaña activa
this.renderSliderContent(noteId); // Re-renderizar para mostrar el cambio
}
}
});
// NUEVO: Eventos para mejorar la edición de los nombres de las pestañas
this.DOMElements.sliderNoteContent.addEventListener('keydown', e => {
// Prevenir saltos de línea en los títulos de las pestañas
if (e.target.classList.contains('slider-note-tab') && e.key === 'Enter') {
e.preventDefault();
e.target.blur(); // Quita el foco para "confirmar" el cambio
}
});
this.DOMElements.sliderNoteContent.addEventListener('blur', e => {
// Si una pestaña queda vacía al perder el foco, restaurar un nombre por defecto
const target = e.target;
if (target.classList.contains('slider-note-tab') && target.innerText.trim() === '') {
const tabIndex = parseInt(target.dataset.tabIndex);
target.innerText = `Pestaña ${tabIndex + 1}`;
// Disparar el manejador de cambio manualmente para que se guarde el cambio
this.handleSliderTabNameChange(target);
}
}, true); // Usar captura para asegurar que se ejecute
// NUEVO: Scroll horizontal con la rueda del ratón en el dashboard
const widgetsContainer = getElement('#dashboard-widgets-container');
if (widgetsContainer) {
widgetsContainer.addEventListener('wheel', (e) => {
if (e.deltaY !== 0) {
e.preventDefault();
widgetsContainer.scrollLeft += e.deltaY;
}
}, { passive: false });
}
}
setupWidgets() {
// Instancia los widgets del dashboard principal (desktop)
this.widgets.clock = new ClockWidget('#clock-widget', this.state);
this.widgets.calendar = new CalendarWidget('#calendar-widget', this.state, this.handleCalendarDateSelect.bind(this));
this.widgets.timer = new TimerWidget('#timer-widget', this.state);
this.widgets.youtube = new YoutubeWidget('#youtube-widget', this.state, this.handleYoutubeUrlChange.bind(this));
this.widgets.quote = new QuoteWidget('#quote-widget', this.state);
this.widgets.tasks = new TasksWidget('#tasks-widget', this.state, this._triggerSave.bind(this));
this.widgets.weather = new WeatherWidget('#weather-widget', this.state);
// Clonar widgets para la barra lateral móvil y re-instanciar su lógica
const mainWidgets = this.DOMElements.bottomDashboard.querySelectorAll('.dashboard-widget');
this.mobileWidgets = {}; // Almacenar las instancias de los widgets móviles
mainWidgets.forEach(mainWidget => {
const clone = mainWidget.cloneNode(true);
// Instanciamos la lógica para el widget clonado.
// Usamos el ID del widget original para saber qué clase instanciar.
switch (mainWidget.id) {
case 'clock-widget':
this.mobileWidgets.clock = new ClockWidget(clone, this.state);
break;
case 'calendar-widget':
this.mobileWidgets.calendar = new CalendarWidget(clone, this.state, this.handleCalendarDateSelect.bind(this));
break;
case 'timer-widget':
this.mobileWidgets.timer = new TimerWidget(clone, this.state);
break;
case 'youtube-widget':
// YoutubeWidget necesita un tratamiento especial para el ID del reproductor
const playerDiv = clone.querySelector('#youtube-player');
if (playerDiv) {
playerDiv.id = 'youtube-player-mobile'; // Asignar un ID único
}
const input = clone.querySelector('#youtube-url-input');
if (input) {
input.id = 'youtube-url-input-mobile';
input.setAttribute('list', 'youtube-history-list-mobile');
}
const dataList = clone.querySelector('#youtube-history-list');
if (dataList) {
dataList.id = 'youtube-history-list-mobile';
}
this.mobileWidgets.youtube = new YoutubeWidget(clone, this.state, this.handleYoutubeUrlChange.bind(this));
break;
case 'stats-widget': // NUEVO: Manejo específico para el stats-widget clonado
// Asegurarse de que el widget clonado sea clickeable para abrir la lista de notas
clone.addEventListener('click', () => this.showAllNotesList());
break;
case 'quote-widget':
this.mobileWidgets.quote = new QuoteWidget(clone, this.state);
break;
case 'tasks-widget':
this.mobileWidgets.tasks = new TasksWidget(clone, this.state, this._triggerSave.bind(this));
break;
case 'weather-widget':
this.mobileWidgets.weather = new WeatherWidget(clone, this.state);
break;
}
this.DOMElements.sidebarContent.appendChild(clone);
});
}
// --- Métodos de Tema (Modo Oscuro/Claro) ---
applyInitialTheme() {
const savedTheme = localStorage.getItem('theme');
// Comprobar preferencia del sistema si no hay nada guardado
const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
if (savedTheme === 'dark' || (!savedTheme && prefersDark)) {
this.DOMElements.body.classList.add('dark-mode');
} else {
this.DOMElements.body.classList.remove('dark-mode');
}
}
toggleTheme() {
const isDarkMode = this.DOMElements.body.classList.toggle('dark-mode');
localStorage.setItem('theme', isDarkMode ? 'dark' : 'light');
}
// --- Métodos de Autenticación y Carga de Datos ---
async handleAuthStateChange(user) {
const wasLoggedIn = !!this.state.getCurrentUser();
// --- LÓGICA DE MODO LOCAL ---
if (!USE_FIREBASE) {
user = {
uid: 'local_user_default',
displayName: 'Usuario Local',
photoURL: null
};
}
this.state.setCurrentUser(user);
this.currentUID = user ? user.uid : null;
// Si es un usuario local o estamos en modo local forzado
const isActuallyLocal = !user || user.uid === 'local-user' || !USE_FIREBASE;
if (user) {
// Elegir el servicio de datos según la configuración o el tipo de usuario
if (USE_FIREBASE && user.uid !== 'local-user') {
this.dataService = new FirestoreService(this.authService.getFirebaseApp());
} else {
this.dataService = new LocalStorageService();
}
this.DOMElements.loaderOverlay.classList.add('visible');
this.updateUserProfile(user);
this.DOMElements.body.classList.remove('logged-out');
this.DOMElements.body.classList.add('logged-in');
// Si estamos en modo local, ocultar botones de login/perfil innecesarios
if (isActuallyLocal) {
if (this.DOMElements.signInBtn) this.DOMElements.signInBtn.style.display = 'none';
if (this.DOMElements.localSignInBtn) this.DOMElements.localSignInBtn.style.display = 'none';
if (this.DOMElements.signOutBtn) {
// Cambiamos el texto de cerrar sesión para modo local
this.DOMElements.signOutBtn.querySelector('span').textContent = '🏠';
this.DOMElements.signOutBtn.innerHTML = '<span>🏠</span> Salir al Menú';
this.DOMElements.signOutBtn.addEventListener('click', () => location.reload());
}
}
setTimeout(() => this.loadData(), 50);
} else {
this.DOMElements.body.classList.add('logged-out');
this.DOMElements.body.classList.remove('logged-in');
this.clearWorkspace();
// CORRECCIÓN: Forzar el reinicio de la animación de la bandera SÓLO al cerrar sesión,
// no en la carga inicial de la página. Si 'wasLoggedIn' es true, significa que
// estamos pasando de un estado logueado a uno deslogueado.
if (wasLoggedIn) {
// Al cerrar sesión, reiniciamos las animaciones del fondo (nubes y bandera)
// forzando al navegador a re-renderizar el contenido.
const loginBackground = getElement('#login-background');
if (loginBackground) {
const backgroundHTML = loginBackground.innerHTML;
loginBackground.innerHTML = ''; // Vaciarlo
// En el siguiente "tick" del navegador, lo volvemos a llenar.
setTimeout(() => {
loginBackground.innerHTML = backgroundHTML;
// Re-inicializar la animación del cielo después de reconstruir el DOM
initSkyAnimation();
}, 0);
}
}
// Asegurarse de que el texto original esté presente si se desloguea de Firebase
this.DOMElements.signInBtn.textContent = '🚀 Iniciar Sesión con Google';
}
// FIN DE LA MODIFICACIÓN
}
applyData(data) {
this.state.setNotes(data.notes || []);
this.state.setZones(data.zones || []);
this.state.setTasks(data.tasks || []);
this.state.setYoutubeUrl(data.youtubeUrl || '');
this.state.youtubeUrlHistory = data.youtubeUrlHistory || [];
// NUEVO: Cargar estado de pan y zoom
this.pan.x = data.panX || 0;
this.pan.y = data.panY || 0;
this.pan.scale = data.zoom || 1;
this.state.setIsDataLoaded(true);
this.renderWorkspace();
this.widgets.calendar.render();
if (this.mobileWidgets.calendar) this.mobileWidgets.calendar.render(); // Actualizar calendario móvil
this.widgets.youtube.initializePlayer();
if (this.mobileWidgets.youtube) this.mobileWidgets.youtube.initializePlayer(); // Inicializar reproductor móvil
// Re-renderizar tareas si existen
if (this.widgets.tasks) this.widgets.tasks.render();
if (this.mobileWidgets.tasks) this.mobileWidgets.tasks.render();
}
updateUserProfile(user) {
if (user) {
this.DOMElements.userName.textContent = user.displayName || 'Usuario';
this.DOMElements.profileAvatar.src = user.photoURL || `https://ui-avatars.com/api/?name=${encodeURIComponent(user.displayName || 'U')}&background=6366f1&color=fff`;
}
}
enterLocalMode() {
// Simulamos un usuario local para la persistencia
const localUser = {
uid: 'local-user',
displayName: 'Espacio Local',
photoURL: 'https://ui-avatars.com/api/?name=L&background=10b981&color=fff'
};
this.handleAuthStateChange(localUser);
}
async loadData() {
if (!this.state.getCurrentUser()) return;
const uid = this.state.getCurrentUser().uid;
// Lógica de "Cache-First" para cuando se usa Firebase
const localCacheKey = `userDataCache_${uid}`;
let isCacheApplied = false;
// 1. Carga Rápida desde LocalStorage (Cache)
try {
const cachedDataJSON = localStorage.getItem(localCacheKey);
if (cachedDataJSON) {
console.log("Cargando datos desde el caché local...");
const data = JSON.parse(cachedDataJSON);
this.applyData(data); // Renderiza la UI inmediatamente con datos cacheados
isCacheApplied = true;
}
} catch (error) {
console.error("Error al cargar datos del caché:", error);
}
if (!isCacheApplied) {
this.DOMElements.loaderOverlay.classList.add('visible');
}
// 2. Carga y Sincronización desde Firestore en segundo plano
try {
console.log("Sincronizando con la nube...");
const firestoreData = await this.dataService.loadUserData(uid);
localStorage.setItem(localCacheKey, JSON.stringify(firestoreData)); // Actualiza el caché
this.applyData(firestoreData); // Re-renderiza con datos frescos
console.log("Sincronización completada.");
} catch (error) {
console.error("Error al sincronizar con Firestore:", error);
if (!isCacheApplied) {
// MEJORA: Mensaje de error más específico para problemas de permisos.
if (error.code === 'permission-denied') {
alertModal.open(
'Error de Permisos',
'La aplicación no tiene permisos para leer tus datos. Es muy probable que las reglas de seguridad de Firestore no estén configuradas. Por favor, revisa la configuración de tu proyecto en Firebase.'
);
} else {
alertModal.open(
'Error de Red',
'No se pudieron cargar los datos de la nube. Se muestra la última versión guardada localmente, si existe.'
);
}
}
} finally {
this.DOMElements.loaderOverlay.classList.remove('visible');
}
}
_saveDataToLocal() {
if (!this.state.getCurrentUser() || !this.state.isDataLoaded) return;
try {
const uid = this.state.getCurrentUser().uid;
const localCacheKey = `userDataCache_${uid}`;
const dataToSave = {
notes: this.state.getNotes(),
zones: this.state.getZones(),
youtubeUrl: this.state.getYoutubeUrl(),
youtubeUrlHistory: this.state.youtubeUrlHistory || [], // Guardar historial
panX: this.pan.x,
panY: this.pan.y,
zoom: this.pan.scale
};
localStorage.setItem(localCacheKey, JSON.stringify(dataToSave));
} catch (error) {
console.error("Error al guardar datos en el caché local:", error);
}
}
_saveDataToRemote() {
if (!this.state.getCurrentUser() || !this.state.isDataLoaded) return;
// En modo local, this.dataService es LocalStorageService, así que esto funciona para ambos casos.
// El debounce es útil en ambos para evitar escrituras excesivas.
this.DOMElements.saveStatus.textContent = 'Guardando...';
try {
const dataToSave = {
notes: this.state.getNotes(),
zones: this.state.getZones(),
youtubeUrl: this.state.getYoutubeUrl(),
youtubeUrlHistory: this.state.youtubeUrlHistory || [],
panX: this.pan.x,
panY: this.pan.y,
zoom: this.pan.scale
};
this.dataService.saveUserData(this.state.getCurrentUser().uid, dataToSave)
.then(() => {
this.DOMElements.saveStatus.textContent = 'Guardado ✓';
setTimeout(() => this.DOMElements.saveStatus.textContent = '', 2000);
})
.catch(error => {
console.error("Error al guardar datos:", error);
this.DOMElements.saveStatus.textContent = 'Error al guardar';
});
} catch (error) {
console.error("Error al preparar datos para guardar:", error);
this.DOMElements.saveStatus.textContent = 'Error al guardar';
}
}
_triggerSave() {
this._saveDataToLocal(); // Guarda en caché local al instante.
this.debounceRemoteSave(); // Programa el guardado en la nube.
}
// --- NUEVO: Métodos para Pan y Zoom ---
applyWorkspaceTransform() {
if (this.DOMElements.workspace) {
this.DOMElements.workspace.style.transform = `translate(${this.pan.x}px, ${this.pan.y}px) scale(${this.pan.scale})`;
}
}
handlePanStart(e) {
// Solo inicia el paneo si se hace clic en el fondo, no en una nota o zona.
if (e.target !== this.DOMElements.appContainer && e.target !== this.DOMElements.workspace) {
return;
}
e.preventDefault();
this.isPanning = true;
this.lastMousePos = { x: e.clientX, y: e.clientY };
this.DOMElements.appContainer.classList.add('panning');
}
handlePanMove(e) {
if (!this.isPanning) return;
e.preventDefault();
const dx = e.clientX - this.lastMousePos.x;
const dy = e.clientY - this.lastMousePos.y;
this.pan.x += dx;
this.pan.y += dy;
this.lastMousePos = { x: e.clientX, y: e.clientY };
this.applyWorkspaceTransform();
}
handlePanEnd(e) {
if (!this.isPanning) return;
this.isPanning = false;
this.DOMElements.appContainer.classList.remove('panning');
this._triggerSave(); // Guarda la nueva posición
}
handleZoom(e) {
// Solo permite zoom si el cursor está sobre el fondo
if (e.target !== this.DOMElements.appContainer && e.target !== this.DOMElements.workspace) {
return;
}
e.preventDefault();
const zoomSpeed = 0.1;
const minZoom = 0.2;
const maxZoom = 2.5;
const oldScale = this.pan.scale;
const delta = e.deltaY > 0 ? -1 : 1; // Hacia abajo aleja, hacia arriba acerca
const newScale = Math.max(minZoom, Math.min(maxZoom, oldScale + delta * zoomSpeed * oldScale));
if (newScale === oldScale) return;
const rect = this.DOMElements.appContainer.getBoundingClientRect();
const mouseX = e.clientX - rect.left;
const mouseY = e.clientY - rect.top;
this.pan.x = mouseX - (mouseX - this.pan.x) * (newScale / oldScale);
this.pan.y = mouseY - (mouseY - this.pan.y) * (newScale / oldScale);
this.pan.scale = newScale;
this.applyWorkspaceTransform();
this._triggerSave(); // Guarda el nuevo estado de zoom y pan
}
// NUEVO: Métodos para los botones de control de zoom
zoom(direction) {
const zoomSpeed = 0.2; // Un poco más rápido para los clics de botón
const minZoom = 0.2;
const maxZoom = 2.5;
const oldScale = this.pan.scale;
// direction es 1 para acercar, -1 para alejar
const newScale = Math.max(minZoom, Math.min(maxZoom, oldScale + direction * zoomSpeed * oldScale));
if (newScale === oldScale) return;
// Zoom hacia el centro de la ventana
const rect = this.DOMElements.appContainer.getBoundingClientRect();
const centerX = rect.width / 2;
const centerY = rect.height / 2;
this.pan.x = centerX - (centerX - this.pan.x) * (newScale / oldScale);
this.pan.y = centerY - (centerY - this.pan.y) * (newScale / oldScale);
this.pan.scale = newScale;
this.applyWorkspaceTransform();
this._triggerSave();
}
zoomIn() { this.zoom(1); }
zoomOut() { this.zoom(-1); }
resetZoom() {
this.pan.x = 0;
this.pan.y = 0;
this.pan.scale = 1;
this.applyWorkspaceTransform();
this._triggerSave();
}
// --- Métodos de gestión de la vista de Zoom ---
handleNoteZoomToggle(noteId) {
const noteInstance = this.noteInstances.get(noteId);
const noteData = this.state.getNotes().find(n => n.id === noteId);
if (!noteData) return;
// NUEVO: Si la nota pertenece a una zona, abre el nuevo slider lateral.
if (noteData.zoneId) {
this.openZoneNotesViewer(noteId);
} else {
// Si es una nota independiente, usa el comportamiento de zoom anterior.
const isZoomed = noteInstance.getDomElement().classList.contains('note-zoomed');
if (isZoomed) {
this.clearZoomState();
} else {
this.clearZoomState();
noteInstance.getDomElement().classList.add('note-zoomed');
this.DOMElements.body.classList.add('note-view-active');
// El resaltado de la zona padre ya no es necesario aquí,
// porque esta ruta solo se toma para notas sin zona.
}
}
}
clearZoomState() {
getElement('.note-zoomed')?.classList.remove('note-zoomed');
getElement('.parent-of-zoomed')?.classList.remove('parent-of-zoomed');
this.DOMElements.body.classList.remove('note-view-active');
}
// --- Métodos para el slider de notas de zona ---
openZoneNotesViewer(clickedNoteId) {
const clickedNoteData = this.state.getNotes().find(n => n.id === clickedNoteId);
if (!clickedNoteData || !clickedNoteData.zoneId) return;
const zoneData = this.state.getZones().find(z => z.id === clickedNoteData.zoneId);
if (!zoneData) return;
this.currentSliderZoneId = zoneData.id; // NUEVO: Guardar el ID de la zona actual
const notesInZone = this.state.getNotes().filter(n => n.zoneId === zoneData.id);
this.DOMElements.sliderTitle.textContent = zoneData.title;
const listContainer = this.DOMElements.sliderNotesList;
listContainer.innerHTML = ''; // Limpiar
notesInZone.forEach(noteData => {
const activeTab = noteData.tabs[noteData.activeTabIndex || 0];
const tabName = activeTab.name || 'Nota sin título';
const item = document.createElement('div');
item.className = 'slider-note-item';
item.dataset.noteId = noteData.id;
item.textContent = tabName;
item.title = tabName;
listContainer.appendChild(item);
});
// Renderizar el contenido de la nota en la que se hizo clic
this.renderSliderContent(clickedNoteId);
// Mostrar el slider
this.DOMElements.body.classList.add('slider-active');
this.DOMElements.body.style.overflow = 'hidden';
}
// NUEVO: Métodos para manejar cambios en el slider
handleSliderContentChange(target) {
const noteId = parseFloat(target.dataset.noteId);
const tabIndex = parseInt(target.dataset.tabIndex);
const content = target.value;
const noteToUpdate = this.state.getNotes().find(n => n.id === noteId);
if (noteToUpdate && noteToUpdate.tabs[tabIndex]) {
noteToUpdate.tabs[tabIndex].content = content;
this._triggerSave(); // Guarda el estado actualizado
}
}
handleSliderTabNameChange(target) {
const noteId = parseFloat(target.dataset.noteId);
const tabIndex = parseInt(target.dataset.tabIndex);
const newName = target.innerText;
const noteToUpdate = this.state.getNotes().find(n => n.id === noteId);
if (noteToUpdate && noteToUpdate.tabs[tabIndex]) {
noteToUpdate.tabs[tabIndex].name = newName;
// Si esta es la pestaña activa de la nota, actualiza el nombre en la lista de la izquierda
if (noteToUpdate.activeTabIndex === tabIndex) {
const noteListItem = this.DOMElements.sliderNotesList.querySelector(`.slider-note-item[data-note-id="${noteId}"]`);
if (noteListItem) {
const displayName = newName.trim() || 'Nota sin título';
noteListItem.textContent = displayName;
noteListItem.title = displayName;
}
}
this._triggerSave(); // Guarda el estado actualizado
}
}
renderSliderContent(noteId) {
// Resaltar el item activo en la lista
this.DOMElements.sliderNotesList.querySelectorAll('.slider-note-item').forEach(item => {
item.classList.toggle('active', parseFloat(item.dataset.noteId) === noteId);
});
const noteData = this.state.getNotes().find(n => n.id === noteId);
const contentContainer = this.DOMElements.sliderNoteContent;
contentContainer.innerHTML = ''; // Limpiar contenido anterior
if (noteData) {
// Crear contenedor de pestañas y paneles
const tabsContainer = document.createElement('div');
tabsContainer.className = 'slider-note-tabs';
const panelsContainer = document.createElement('div');
panelsContainer.className = 'slider-note-content-panels';
noteData.tabs.forEach((tab, index) => {
// Crear botón de pestaña
const tabBtn = document.createElement('div');
tabBtn.className = 'slider-note-tab';
tabBtn.innerText = tab.name || `Pestaña ${index + 1}`;
tabBtn.dataset.noteId = noteData.id;
tabBtn.dataset.tabIndex = index;
tabBtn.contentEditable = true;
if (index === noteData.activeTabIndex) {
tabBtn.classList.add('active');
}
tabsContainer.appendChild(tabBtn);
// Crear panel de contenido
const panel = document.createElement('textarea');
panel.className = 'slider-note-content-panel';
panel.dataset.noteId = noteData.id;
panel.dataset.tabIndex = index;
panel.placeholder = "Escribe algo...";
panel.value = tab.content || '';
if (index === noteData.activeTabIndex) {
panel.classList.add('active');
}
panelsContainer.appendChild(panel);
});
contentContainer.appendChild(tabsContainer);
contentContainer.appendChild(panelsContainer);
} else {
// Si no hay nota (o se borró), mostrar el mensaje por defecto
contentContainer.appendChild(this.DOMElements.sliderNoNoteSelected);
}
}
closeZoneNotesViewer() {
this.DOMElements.body.classList.remove('slider-active');
this.DOMElements.body.style.overflow = '';
this.currentSliderZoneId = null; // Limpiar el ID de la zona
// Resetear el contenido del slider para la próxima vez
this.DOMElements.sliderNoteContent.innerHTML = '';
this.DOMElements.sliderNoteContent.appendChild(this.DOMElements.sliderNoNoteSelected);
}
// NUEVO: Manejador para el botón de añadir nota en el slider
handleSliderAddNote() {
if (!this.currentSliderZoneId) return;
const newNote = this.addNote(this.currentSliderZoneId, true); // true para indicar que es desde el slider
if (newNote) {
// Refrescar la vista del slider para mostrar la nueva nota y seleccionarla
this.openZoneNotesViewer(newNote.id);
}
}
// NUEVO: Proporciona el estado de pan/zoom a los componentes que lo necesiten
getPanState() {
return this.pan;
}
_getNewItemDesktopPosition(newItemIsZone = false) {
// --- Parámetros del layout inteligente ---
// NUEVO: Calcular el área visible del workspace en coordenadas del workspace
const viewRect = {
x: -this.pan.x / this.pan.scale,
y: -this.pan.y / this.pan.scale,
width: this.DOMElements.appContainer.clientWidth / this.pan.scale,
height: this.DOMElements.appContainer.clientHeight / this.pan.scale
};
const layout = {
// El punto de inicio de la búsqueda ahora está dentro de la vista actual
startX: viewRect.x + 80,
startY: viewRect.y + 80,
gap: 30,
columnWidth: CONSTANTS.DEFAULT_NOTE_WIDTH + 30,
// El número de columnas se basa en el ancho visible
numColumns: Math.max(1, Math.floor(viewRect.width / (CONSTANTS.DEFAULT_NOTE_WIDTH + 30)))
};
const notesOnDate = this.state.getNotes().filter(note => note.date === this.state.getSelectedDate());
const zonesOnDate = this.state.getZones().filter(zone => zone.date === this.state.getSelectedDate());
const topLevelItems = [
...notesOnDate.filter(n => !n.zoneId),
...zonesOnDate
];
// Si no hay elementos en la fecha actual, colocar en la esquina superior de la vista.
if (topLevelItems.length === 0) {
return { x: layout.startX, y: layout.startY };
}
// Encontrar el punto más bajo de todos los elementos para saber hasta dónde buscar.
const layoutHeight = topLevelItems.reduce((max, item) => Math.max(max, item.y + (item.height || CONSTANTS.DEFAULT_NOTE_HEIGHT)), 0);
// El bucle de búsqueda ahora comienza desde la parte superior de la vista actual.
// Y busca hasta el final del contenido existente o el final de la vista, lo que sea mayor.
for (let y = layout.startY; y < Math.max(layoutHeight, viewRect.y + viewRect.height) + 1000; y += layout.gap) { // Iterar por filas
for (let col = 0; col < layout.numColumns; col++) { // Iterar por columnas
const probeX = layout.startX + col * layout.columnWidth;
const probeY = y;
// Comprobar si este punto (probeX, probeY) está ocupado por otro elemento.
const isOccupied = topLevelItems.some(item => {
const itemWidth = item.width || (item.title ? CONSTANTS.DEFAULT_ZONE_WIDTH : CONSTANTS.DEFAULT_NOTE_WIDTH);
const itemHeight = item.height || (item.title ? CONSTANTS.DEFAULT_ZONE_HEIGHT : CONSTANTS.DEFAULT_NOTE_HEIGHT);
const newItemWidth = newItemIsZone ? CONSTANTS.DEFAULT_ZONE_WIDTH : CONSTANTS.DEFAULT_NOTE_WIDTH;
const newItemHeight = newItemIsZone ? CONSTANTS.DEFAULT_ZONE_HEIGHT : CONSTANTS.DEFAULT_NOTE_HEIGHT;
// Lógica de colisión de rectángulos (AABB intersection).
// Se añade un "gap" al tamaño de los rectángulos para asegurar que no se toquen.
return (
probeX < (item.x + itemWidth + layout.gap) &&
(probeX + newItemWidth + layout.gap) > item.x &&
probeY < (item.y + itemHeight + layout.gap) &&
(probeY + newItemHeight + layout.gap) > item.y
);
});
if (!isOccupied) {
// Encontramos un hueco. Devolvemos estas coordenadas.
return { x: probeX, y: probeY };
}
}
}
// Fallback: si no se encuentra hueco, apilar al final del contenido existente, pero no por encima de la vista actual.
const lowestPoint = topLevelItems.reduce((maxY, item) => Math.max(maxY, (item.y || 0) + (item.height || 240)), 0);
return { x: layout.startX, y: Math.max(lowestPoint + layout.gap, layout.startY) };
}
// --- Métodos de Gestión de Notas/Zonas ---
addNote(zoneId = null, fromSlider = false) {
let position;
if (zoneId) {
// Lógica para añadir una nota DENTRO de una zona (funciona para móvil y escritorio)
const parentZone = this.state.getZones().find(z => z.id === zoneId);
if (parentZone) {
// NUEVA LÓGICA: Colocar la nota en la primera celda vacía de la cuadrícula de la zona.
const notesInZone = this.state.getNotes().filter(n => n.zoneId === zoneId);
const numCols = 4;
const numRows = 2;
const grid = Array(numRows).fill(null).map(() => Array(numCols).fill(false));
// Coordenadas y dimensiones de la cuadrícula interna de la zona
const gridX = parentZone.x + 15;
const gridY = parentZone.y + 45;
const gridW = parentZone.width - 30;
const gridH = parentZone.height - 60;
const cellWidth = gridW / numCols;
const cellHeight = gridH / numRows;
// Marcar las celdas que ya están ocupadas por otras notas
notesInZone.forEach(note => {
const noteCenterX = note.x + (note.width / 2);
const noteCenterY = note.y + (note.height / 2);
const relativeX = noteCenterX - gridX;
const relativeY = noteCenterY - gridY;
const col = Math.floor(relativeX / cellWidth);
const row = Math.floor(relativeY / cellHeight);
if (row >= 0 && row < numRows && col >= 0 && col < numCols) {
grid[row][col] = true; // Marcar celda como ocupada
}
});
// Encontrar la primera celda vacía (de arriba a abajo, de izquierda a derecha)
let targetRow = -1, targetCol = -1;
for (let r = 0; r < numRows; r++) {
for (let c = 0; c < numCols; c++) {
if (!grid[r][c]) {
targetRow = r;
targetCol = c;
break;
}
}
if (targetRow !== -1) break;
}
if (targetRow !== -1 && targetCol !== -1) {
// Si se encuentra una celda vacía, calcular la posición para centrar la nueva nota en ella
const noteWidth = CONSTANTS.DEFAULT_NOTE_WIDTH;
const noteHeight = CONSTANTS.DEFAULT_NOTE_HEIGHT;
const cellCenterX = gridX + (targetCol * cellWidth) + (cellWidth / 2);
const cellCenterY = gridY + (targetRow * cellHeight) + (cellHeight / 2);
position = {
x: cellCenterX - (noteWidth / 2),
y: cellCenterY - (noteHeight / 2)
};
} else {
// Fallback: si la cuadrícula está llena, apilar la nota debajo de la zona para que sea visible
position = { x: parentZone.x, y: parentZone.y + parentZone.height + 20 };
}
} else {
// Fallback si la zona no se encuentra (no debería pasar)
position = this._getNewItemDesktopPosition(false);
}
} else {
// Lógica para añadir una nota INDEPENDIENTE (funciona para móvil y escritorio)
// Usa el layout inteligente que ahora considera la vista actual.
position = this._getNewItemDesktopPosition(false);
}
const newNote = {
id: Date.now() + Math.random(),