-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1223 lines (1069 loc) · 41.8 KB
/
Copy pathapp.js
File metadata and controls
1223 lines (1069 loc) · 41.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
// ============================================
// CONFIGURACIÓN
// ============================================
const CONFIG = {
// URL que aparece en el pie de página al imprimir
footerUrl: 'https://aramcap.github.io/colorcal/'
};
// ============================================
// FUNCIONES DE TEMA
// ============================================
// Aplicar tema según preferencia
function applyTheme(theme) {
if (theme === 'system') {
// Usar preferencia del sistema
document.documentElement.removeAttribute('data-theme');
} else {
// Forzar tema claro u oscuro
document.documentElement.setAttribute('data-theme', theme);
}
// Guardar preferencia
localStorage.setItem('colorcal-theme', theme);
// Actualizar selector
const selector = document.getElementById('themeSelector');
if (selector) {
selector.value = theme;
}
// Re-renderizar calendario si existe
if (state.chart) {
// Pequeño delay para permitir que los estilos CSS se apliquen
setTimeout(() => {
renderCalendar();
}, 50);
}
}
// Cargar tema guardado
function loadTheme() {
const savedTheme = localStorage.getItem('colorcal-theme') || 'system';
applyTheme(savedTheme);
// Escuchar cambios en la preferencia del sistema
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
const currentTheme = localStorage.getItem('colorcal-theme') || 'system';
if (currentTheme === 'system' && state.chart) {
// Re-renderizar calendario cuando cambia el tema del sistema
setTimeout(() => {
renderCalendar();
}, 50);
}
});
}
// Obtener colores actuales del tema
function getThemeColors() {
// Si estamos en modo impresión, forzar colores claros
if (state.isPrinting) {
return getLightThemeColors();
}
const computedStyle = getComputedStyle(document.documentElement);
return {
bgPrimary: computedStyle.getPropertyValue('--bg-primary').trim() || '#f5f5f5',
bgSecondary: computedStyle.getPropertyValue('--bg-secondary').trim() || '#ffffff',
bgSidebarItem: computedStyle.getPropertyValue('--bg-sidebar-item').trim() || '#34495e',
textPrimary: computedStyle.getPropertyValue('--text-primary').trim() || '#333333',
textSecondary: computedStyle.getPropertyValue('--text-secondary').trim() || '#666666',
textMuted: computedStyle.getPropertyValue('--text-muted').trim() || '#95a5a6',
borderColor: computedStyle.getPropertyValue('--border-color').trim() || '#ddd',
accentPrimary: computedStyle.getPropertyValue('--accent-primary').trim() || '#3498db'
};
}
// Obtener colores del tema claro (para impresión)
function getLightThemeColors() {
return {
bgPrimary: '#f5f5f5',
bgSecondary: '#ffffff',
bgSidebarItem: '#34495e',
textPrimary: '#333333',
textSecondary: '#666666',
textMuted: '#95a5a6',
borderColor: '#ddd',
accentPrimary: '#3498db'
};
}
// ============================================
// FUNCIONES DE UTILIDAD
// ============================================
// Función para calcular luminosidad de un color y determinar si el texto debe ser claro u oscuro
function getContrastColor(hexColor) {
if (!hexColor) {
const colors = getThemeColors();
return colors.textPrimary;
}
// Remover # si existe
const hex = hexColor.replace('#', '');
// Convertir a RGB
const r = parseInt(hex.substring(0, 2), 16);
const g = parseInt(hex.substring(2, 4), 16);
const b = parseInt(hex.substring(4, 6), 16);
// Calcular luminosidad relativa (fórmula estándar)
const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
// Si el fondo es oscuro, usar texto blanco; si es claro, usar texto oscuro
return luminance < 0.5 ? '#ffffff' : '#333333';
}
// Obtener el color de fondo predominante para un día (primera etiqueta)
function getDayBackgroundColor(date, markedDays) {
const tags = markedDays[date];
if (!tags) return null;
const tagArray = Array.isArray(tags) ? tags : [tags];
if (tagArray.length === 0) return null;
return tagArray[0].color || null;
}
// Estado de la aplicación
const state = {
tags: [],
markedDays: {}, // { "2024-01-15": { tagId: "tag1", color: "#3498db", name: "Vacaciones" } }
periods: [], // { id: "period_123", tagId: "tag1", startDate: "2024-01-15", endDate: "2024-01-20", tagName: "Vacaciones", tagColor: "#3498db" }
startMonth: null,
monthsCount: 12,
chart: null,
highlightWeekends: false,
weekendColor: '#ffcccc',
isPrinting: false
};
// Inicializar la aplicación
document.addEventListener('DOMContentLoaded', function() {
loadTheme(); // Cargar tema antes de inicializar
initializeApp();
setupEventListeners();
});
function initializeApp() {
// Establecer mes actual como predeterminado
const today = new Date();
const currentMonth = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}`;
document.getElementById('startMonth').value = currentMonth;
state.startMonth = currentMonth;
// Cargar datos guardados
loadFromLocalStorage();
// Renderizar interfaz
renderTagsList();
renderTagsSelect();
renderPeriodsList();
renderCalendar();
}
function setupEventListeners() {
// Actualizar período
document.getElementById('updatePeriod').addEventListener('click', updatePeriod);
// Agregar etiqueta
document.getElementById('addTag').addEventListener('click', addTag);
// Marcar días
document.getElementById('markRange').addEventListener('click', markRange);
document.getElementById('clearSelection').addEventListener('click', clearSelection);
// Sincronizar fecha de fin con fecha de inicio
document.getElementById('startDate').addEventListener('change', function() {
const endInput = document.getElementById('endDate');
if (!endInput.value || endInput.value < this.value) {
endInput.value = this.value;
}
endInput.min = this.value;
});
// Validar que fecha fin no sea anterior a fecha inicio
document.getElementById('endDate').addEventListener('change', function() {
const startInput = document.getElementById('startDate');
if (startInput.value && this.value < startInput.value) {
this.value = startInput.value;
}
});
// Exportar/Importar
document.getElementById('exportData').addEventListener('click', exportData);
document.getElementById('importData').addEventListener('click', () => {
document.getElementById('importFile').click();
});
document.getElementById('importFile').addEventListener('change', importData);
// Opciones de visualización (fines de semana)
document.getElementById('highlightWeekends').addEventListener('change', function() {
state.highlightWeekends = this.checked;
saveToLocalStorage();
renderCalendar();
});
document.getElementById('weekendColor').addEventListener('change', function() {
state.weekendColor = this.value;
if (state.highlightWeekends) {
saveToLocalStorage();
renderCalendar();
}
});
// Validación del campo "meses a mostrar"
const monthsCountInput = document.getElementById('monthsCount');
monthsCountInput.addEventListener('input', function() {
// Eliminar caracteres no numéricos
this.value = this.value.replace(/[^0-9]/g, '');
let value = parseInt(this.value);
if (isNaN(value) || value < 1) {
this.value = 1;
} else if (value > 36) {
this.value = 36;
}
});
monthsCountInput.addEventListener('blur', function() {
// Asegurar valor válido al perder foco
let value = parseInt(this.value);
if (isNaN(value) || value < 1) {
this.value = 1;
} else if (value > 36) {
this.value = 36;
}
});
// Validación del campo "fecha inicio" del período
const startMonthInput = document.getElementById('startMonth');
startMonthInput.addEventListener('change', function() {
if (this.value) {
// Validar formato YYYY-MM
const regex = /^\d{4}-(0[1-9]|1[0-2])$/;
if (!regex.test(this.value)) {
alert('Formato de fecha no válido. Use el selector de mes.');
const today = new Date();
this.value = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}`;
return;
}
const [year] = this.value.split('-').map(Number);
if (year < 1900 || year > 2100) {
alert('El año debe estar entre 1900 y 2100');
const today = new Date();
this.value = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}`;
}
}
});
// Validación adicional al escribir en el campo de mes (prevenir entrada manual inválida)
startMonthInput.addEventListener('input', function() {
// Si el valor no está vacío y no coincide con el patrón parcial, limpiar
if (this.value && !/^\d{0,4}(-\d{0,2})?$/.test(this.value)) {
const today = new Date();
this.value = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}`;
}
});
// Selector de tema
document.getElementById('themeSelector').addEventListener('change', function() {
applyTheme(this.value);
});
// Generar leyenda antes de imprimir y forzar tema claro
window.addEventListener('beforeprint', prepareForPrint);
window.addEventListener('afterprint', restoreAfterPrint);
}
// Preparar para impresión: forzar tema claro y re-renderizar
function prepareForPrint() {
state.isPrinting = true;
// Re-renderizar calendario con colores claros
if (state.chart) {
renderCalendar();
}
// Generar leyenda
generatePrintLegend();
}
// Restaurar después de imprimir
function restoreAfterPrint() {
state.isPrinting = false;
// Pequeño delay para permitir que el layout se restaure completamente
setTimeout(() => {
// Re-renderizar calendario con colores del tema actual
if (state.chart) {
// Forzar resize para recalcular dimensiones correctas
state.chart.resize();
renderCalendar();
}
}, 100);
}
// Generar leyenda para impresión
function generatePrintLegend() {
const legendContent = document.getElementById('legendContent');
legendContent.innerHTML = '';
// Añadir etiquetas usadas
state.tags.forEach(tag => {
const dayCount = countDaysForTag(tag.id);
const dayText = dayCount === 1 ? '1 día' : `${dayCount} días`;
const item = document.createElement('div');
item.className = 'legend-item';
item.innerHTML = `
<span class="legend-color" style="background-color: ${tag.color};"></span>
<span class="legend-name">${tag.name} (${dayText})</span>
`;
legendContent.appendChild(item);
});
// Añadir fines de semana si está activado
if (state.highlightWeekends) {
const weekendItem = document.createElement('div');
weekendItem.className = 'legend-item';
weekendItem.innerHTML = `
<span class="legend-color" style="background-color: ${state.weekendColor};"></span>
<span class="legend-name">Fin de semana</span>
`;
legendContent.appendChild(weekendItem);
}
// Actualizar pie de página con la URL configurada
const footerLink = document.getElementById('footerLink');
if (footerLink) {
footerLink.href = CONFIG.footerUrl;
footerLink.textContent = CONFIG.footerUrl;
}
}
// Contar días marcados para una etiqueta específica
function countDaysForTag(tagId) {
let count = 0;
Object.values(state.markedDays).forEach(tags => {
const tagArray = Array.isArray(tags) ? tags : (tags ? [tags] : []);
if (tagArray.some(t => t.tagId === tagId)) {
count++;
}
});
return count;
}
// Gestión de etiquetas
function addTag() {
const nameInput = document.getElementById('tagName');
const colorInput = document.getElementById('tagColor');
const name = nameInput.value.trim();
const color = colorInput.value;
if (!name) {
alert('Por favor, ingresa un nombre para la etiqueta');
return;
}
const tag = {
id: `tag_${Date.now()}`,
name: name,
color: color
};
state.tags.push(tag);
// Limpiar inputs
nameInput.value = '';
colorInput.value = '#3498db';
// Actualizar interfaz
renderTagsList();
renderTagsSelect();
saveToLocalStorage();
}
function deleteTag(tagId) {
if (!confirm('¿Estás seguro de eliminar esta etiqueta? Los días y períodos marcados con esta etiqueta se eliminarán.')) {
return;
}
// Eliminar etiqueta
state.tags = state.tags.filter(tag => tag.id !== tagId);
// Eliminar marcas asociadas
removeMarksForTag(tagId);
// Eliminar períodos asociados
state.periods = state.periods.filter(p => p.tagId !== tagId);
// Actualizar interfaz
renderTagsList();
renderTagsSelect();
renderPeriodsList();
renderCalendar();
saveToLocalStorage();
}
function renderTagsList() {
const container = document.getElementById('tagsList');
if (state.tags.length === 0) {
container.innerHTML = '<p class="empty-message">No hay etiquetas</p>';
return;
}
container.innerHTML = state.tags.map(tag => {
const dayCount = countDaysForTag(tag.id);
const dayText = dayCount === 1 ? '1 día' : `${dayCount} días`;
return `
<div class="tag-item">
<div class="tag-info">
<div class="tag-color-box" style="background: ${tag.color};"></div>
<span class="tag-name">${tag.name}</span>
<span class="tag-day-count">(${dayText})</span>
</div>
<div class="tag-actions">
<button class="tag-edit" onclick="editTag('${tag.id}')" title="Editar etiqueta" aria-label="Editar">✏️</button>
<button class="tag-delete" onclick="deleteTag('${tag.id}')" aria-label="Eliminar">🗑️</button>
</div>
</div>
`;
}).join('');
}
function renderTagsSelect() {
const select = document.getElementById('selectedTag');
if (state.tags.length === 0) {
select.innerHTML = '<option value="">-- Sin etiquetas --</option>';
return;
}
select.innerHTML = '<option value="">-- Seleccionar --</option>' +
state.tags.map(tag => `
<option value="${tag.id}">${tag.name}</option>
`).join('');
}
// Marcar días
function markRange() {
const startInput = document.getElementById('startDate');
const endInput = document.getElementById('endDate');
const tagSelect = document.getElementById('selectedTag');
const startDate = new Date(startInput.value);
const endDate = new Date(endInput.value);
const tagId = tagSelect.value;
if (!startInput.value || !endInput.value) {
alert('Por favor, selecciona ambas fechas');
return;
}
if (!tagId) {
alert('Por favor, selecciona una etiqueta');
return;
}
if (startDate > endDate) {
alert('La fecha de inicio debe ser anterior a la fecha de fin');
return;
}
const tag = state.tags.find(t => t.id === tagId);
// Crear el período
const period = {
id: `period_${Date.now()}`,
tagId: tag.id,
startDate: startInput.value,
endDate: endInput.value,
tagName: tag.name,
tagColor: tag.color
};
state.periods.push(period);
// Marcar todos los días en el rango
let currentDate = new Date(startDate);
while (currentDate <= endDate) {
const dateStr = formatDate(currentDate);
const current = Array.isArray(state.markedDays[dateStr]) ? state.markedDays[dateStr] : (state.markedDays[dateStr] ? [state.markedDays[dateStr]] : []);
const exists = current.some(entry => entry.tagId === tag.id);
if (!exists) {
current.push({ tagId: tag.id, color: tag.color, name: tag.name, periodId: period.id });
}
state.markedDays[dateStr] = current;
currentDate.setDate(currentDate.getDate() + 1);
}
renderPeriodsList();
renderCalendar();
saveToLocalStorage();
// Limpiar inputs
startInput.value = '';
endInput.value = '';
}
function clearSelection() {
if (!confirm('¿Estás seguro de limpiar todos los días marcados?')) {
return;
}
state.markedDays = {};
state.periods = [];
renderPeriodsList();
renderCalendar();
saveToLocalStorage();
}
// Validar formato de mes (YYYY-MM)
function isValidMonthFormat(value) {
if (!value || typeof value !== 'string') return false;
const regex = /^\d{4}-(0[1-9]|1[0-2])$/;
if (!regex.test(value)) return false;
const [year] = value.split('-').map(Number);
return year >= 1900 && year <= 2100;
}
// Actualizar período
function updatePeriod() {
const startMonthInput = document.getElementById('startMonth');
const monthsCountInput = document.getElementById('monthsCount');
const monthValue = startMonthInput.value;
if (!monthValue || !isValidMonthFormat(monthValue)) {
alert('Por favor, selecciona un mes de inicio válido (formato: AAAA-MM)');
// Restablecer al mes actual si el valor no es válido
const today = new Date();
startMonthInput.value = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}`;
return;
}
state.startMonth = monthValue;
state.monthsCount = parseInt(monthsCountInput.value);
if (isNaN(state.monthsCount) || state.monthsCount < 1 || state.monthsCount > 36) {
alert('El número de meses debe estar entre 1 y 36');
monthsCountInput.value = 12;
state.monthsCount = 12;
return;
}
renderCalendar();
saveToLocalStorage();
}
// Renderizar calendario con ECharts
function renderCalendar() {
const container = document.getElementById('calendar');
if (!state.chart) {
state.chart = echarts.init(container);
}
// Calcular fechas
const [year, month] = state.startMonth.split('-').map(Number);
const startDate = new Date(year, month - 1, 1);
// Generar configuración de calendarios
const calendars = [];
const series = [];
const graphics = [];
const columns = Math.min(3, Math.max(1, state.monthsCount));
const widthPercent = 100 / columns;
const containerWidth = container.clientWidth || container.offsetWidth || 800;
const topOffsetPx = 120; // espacio para título general
const gapY = 90; // espacio entre filas de meses (incluye título)
const cellHeightPx = 26; // tamaño fijo de celda para todos los meses
const calendarPadPx = 30; // espacio extra para labels de días
const calendarWidthPx = (containerWidth * (widthPercent - 3) / 100);
const cellWidthPx = Math.max(18, calendarWidthPx / 7 - 2);
let currentTopPx = topOffsetPx;
let rowMaxHeight = 0;
for (let i = 0; i < state.monthsCount; i++) {
const currentYear = startDate.getFullYear();
const currentMonth = startDate.getMonth() + i;
const adjustedYear = currentYear + Math.floor(currentMonth / 12);
const adjustedMonth = (currentMonth % 12) + 1;
const row = Math.floor(i / columns);
const col = i % columns;
const weeks = getWeeksInMonth(adjustedYear, adjustedMonth);
// Altura calculada exactamente según semanas y tamaño de celda fijo
const calHeightPx = weeks * cellHeightPx + calendarPadPx;
// Si iniciamos una nueva fila, ajustamos top usando la altura máxima de la fila anterior
if (col === 0 && i !== 0) {
currentTopPx += rowMaxHeight + gapY;
rowMaxHeight = 0;
}
const topPx = currentTopPx;
const leftPercent = col * widthPercent + 2;
rowMaxHeight = Math.max(rowMaxHeight, calHeightPx);
const monthText = `${adjustedYear}-${String(adjustedMonth).padStart(2, '0')}`;
// Obtener colores del tema actual
const themeColors = getThemeColors();
calendars.push({
top: topPx,
left: `${leftPercent}%`,
width: `${widthPercent - 3}%`,
cellSize: [cellWidthPx, cellHeightPx], // tamaño fijo de celda
orient: 'vertical',
range: `${adjustedYear}-${String(adjustedMonth).padStart(2, '0')}`,
splitLine: {
show: true,
lineStyle: {
color: themeColors.borderColor,
width: 1,
type: 'solid'
}
},
yearLabel: { show: false },
dayLabel: {
nameMap: ['Dom', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb'],
firstDay: 1,
position: 'start',
color: themeColors.textSecondary
},
monthLabel: {
nameMap: 'es',
formatter: '{yyyy}-{MM}',
show: false
},
itemStyle: {
color: themeColors.bgSecondary,
borderWidth: 1,
borderColor: themeColors.borderColor
}
});
graphics.push({
type: 'text',
left: `${leftPercent}%`,
right: `${100 - leftPercent - (widthPercent - 3)}%`,
top: Math.max(0, topPx - 56),
style: {
text: monthText,
fill: themeColors.textPrimary,
fontWeight: 'bold',
fontSize: 14,
textAlign: 'center'
}
});
// Preparar datos para este mes
const monthRange = `${adjustedYear}-${String(adjustedMonth).padStart(2, '0')}`;
const monthData = [];
Object.entries(state.markedDays).forEach(([date, tags]) => {
if (date.startsWith(monthRange)) {
const tagArray = Array.isArray(tags) ? tags : (tags ? [tags] : []);
if (tagArray.length > 0) {
monthData.push({
date: date,
tags: tagArray.map(t => ({
color: t.color || '#3498db',
name: t.name || 'Etiqueta'
}))
});
}
}
});
// Crear series scatter para cada etiqueta
if (monthData.length > 0) {
monthData.forEach(item => {
const numTags = item.tags.length;
const stripeH = (cellHeightPx - 2) / numTags;
item.tags.forEach((tag, tagIdx) => {
// Calcular offset para apilar franjas
const offsetY = (tagIdx - (numTags - 1) / 2) * stripeH;
series.push({
type: 'scatter',
coordinateSystem: 'calendar',
calendarIndex: i,
data: [[item.date, 1]],
z: 10 + tagIdx,
symbol: 'rect',
symbolSize: [cellWidthPx - 4, stripeH],
symbolOffset: [0, offsetY],
itemStyle: {
color: tag.color,
borderColor: '#fff',
borderWidth: 0.5
},
tooltip: {
formatter: function() {
const lines = item.tags.map(t =>
`<span style="display:inline-block;width:12px;height:12px;background:${t.color};margin-right:8px;border-radius:2px;vertical-align:middle;"></span>${t.name}`
);
return `<strong>${item.date}</strong><br/>` + lines.join('<br/>');
}
}
});
});
});
}
// Serie de etiquetas de día (número visible en cada celda)
const daysInMonth = getDaysOfMonth(adjustedYear, adjustedMonth).map(d => {
const bgColor = getDayBackgroundColor(d, state.markedDays);
// Verificar si es fin de semana
const dateObj = new Date(d);
const dayOfWeek = dateObj.getDay(); // 0=Dom, 6=Sáb
const isWeekend = (dayOfWeek === 0 || dayOfWeek === 6);
const effectiveBgColor = bgColor || (state.highlightWeekends && isWeekend ? state.weekendColor : null);
const textColor = effectiveBgColor ? getContrastColor(effectiveBgColor) : themeColors.textPrimary;
return {
value: [d, 1],
label: {
color: textColor
}
};
});
// Serie para colorear fines de semana (si está activado)
if (state.highlightWeekends) {
const weekendDays = getDaysOfMonth(adjustedYear, adjustedMonth).filter(d => {
const dateObj = new Date(d);
const dayOfWeek = dateObj.getDay();
return (dayOfWeek === 0 || dayOfWeek === 6) && !state.markedDays[d];
});
if (weekendDays.length > 0) {
series.push({
type: 'scatter',
coordinateSystem: 'calendar',
calendarIndex: i,
data: weekendDays.map(d => [d, 1]),
z: 5,
symbol: 'rect',
symbolSize: [cellWidthPx - 2, cellHeightPx - 2],
itemStyle: {
color: state.weekendColor
},
tooltip: {
show: false
}
});
}
}
series.push({
type: 'scatter',
coordinateSystem: 'calendar',
calendarIndex: i,
data: daysInMonth,
symbolSize: 0,
z: 50,
label: {
show: true,
formatter: params => (params.value && params.value[0] ? params.value[0].split('-')[2].replace(/^0/, '') : ''),
color: themeColors.textPrimary,
fontSize: 10,
fontWeight: 700,
position: 'inside',
offset: [0, 0]
},
itemStyle: {
color: 'transparent'
},
tooltip: {
show: false
}
});
}
// Altura total para el contenedor del chart (para habilitar scroll)
const totalHeightPx = currentTopPx + rowMaxHeight + gapY + 40;
container.style.height = `${totalHeightPx}px`;
container.style.minHeight = `${totalHeightPx}px`;
const option = {
title: {
text: 'Calendario',
left: 'center',
top: 10,
textStyle: {
fontSize: 24,
fontWeight: 'bold',
color: getThemeColors().textPrimary
}
},
tooltip: {
trigger: 'item',
confine: true
},
calendar: calendars,
graphic: graphics,
series: series
};
state.chart.setOption(option, true);
state.chart.resize();
}
// Devuelve todas las fechas (YYYY-MM-DD) de un mes
function getDaysOfMonth(year, month) {
const days = [];
const total = new Date(year, month, 0).getDate();
for (let d = 1; d <= total; d++) {
days.push(`${year}-${String(month).padStart(2, '0')}-${String(d).padStart(2, '0')}`);
}
return days;
}
// Número de semanas (filas) de un mes considerando inicio en lunes
function getWeeksInMonth(year, month) {
const totalDays = new Date(year, month, 0).getDate();
const firstDay = new Date(year, month - 1, 1);
// getDay(): 0 domingo ... 6 sábado. Convertimos a lunes=0.
const offset = (firstDay.getDay() + 6) % 7;
return Math.ceil((offset + totalDays) / 7);
}
// Eliminar marcas de un tag sin borrar la etiqueta
function clearTagMarks(tagId) {
removeMarksForTag(tagId);
renderCalendar();
saveToLocalStorage();
}
// Renderizar lista de períodos
function renderPeriodsList() {
const container = document.getElementById('periodsList');
if (state.periods.length === 0) {
container.innerHTML = '<p class="empty-message">No hay períodos marcados</p>';
return;
}
container.innerHTML = state.periods.map(period => `
<div class="period-item" data-id="${period.id}">
<div class="period-info">
<div class="period-color-box" style="background: ${period.tagColor};"></div>
<div class="period-details">
<span class="period-tag-name">${period.tagName}</span>
<span class="period-dates">${formatDisplayDate(period.startDate)} - ${formatDisplayDate(period.endDate)}</span>
</div>
</div>
<div class="period-actions">
<button class="period-edit" onclick="editPeriod('${period.id}')" title="Editar período" aria-label="Editar">✏️</button>
<button class="period-delete" onclick="deletePeriod('${period.id}')" title="Eliminar período" aria-label="Eliminar">🗑️</button>
</div>
</div>
`).join('');
}
// Formatear fecha para mostrar (DD/MM/YYYY)
function formatDisplayDate(dateStr) {
const [year, month, day] = dateStr.split('-');
return `${day}/${month}/${year}`;
}
// Editar período
function editPeriod(periodId) {
const period = state.periods.find(p => p.id === periodId);
if (!period) return;
// Crear modal de edición
const modal = document.createElement('div');
modal.className = 'modal-overlay';
modal.id = 'editPeriodModal';
modal.innerHTML = `
<div class="modal-content">
<h3>Editar Período</h3>
<div class="modal-form">
<label>Etiqueta:</label>
<select id="editPeriodTag">
${state.tags.map(tag => `
<option value="${tag.id}" ${tag.id === period.tagId ? 'selected' : ''}>${tag.name}</option>
`).join('')}
</select>
<label>Fecha inicio:</label>
<input type="date" id="editPeriodStart" value="${period.startDate}" />
<label>Fecha fin:</label>
<input type="date" id="editPeriodEnd" value="${period.endDate}" min="${period.startDate}" />
<div class="modal-buttons">
<button class="btn-primary" onclick="savePeriodEdit('${periodId}')">Guardar</button>
<button class="btn-secondary" onclick="closeModal()">Cancelar</button>
</div>
</div>
</div>
`;
document.body.appendChild(modal);
// Sincronizar fecha de fin con fecha de inicio (mismo comportamiento que al crear períodos)
document.getElementById('editPeriodStart').addEventListener('change', function() {
const endInput = document.getElementById('editPeriodEnd');
if (!endInput.value || endInput.value < this.value) {
endInput.value = this.value;
}
endInput.min = this.value;
});
// Validar que fecha fin no sea anterior a fecha inicio
document.getElementById('editPeriodEnd').addEventListener('change', function() {
const startInput = document.getElementById('editPeriodStart');
if (startInput.value && this.value < startInput.value) {
this.value = startInput.value;
}
});
}
// Guardar edición de período
function savePeriodEdit(periodId) {
const period = state.periods.find(p => p.id === periodId);
if (!period) return;
const newTagId = document.getElementById('editPeriodTag').value;
const newStartDate = document.getElementById('editPeriodStart').value;
const newEndDate = document.getElementById('editPeriodEnd').value;
if (!newStartDate || !newEndDate) {
alert('Por favor, selecciona ambas fechas');
return;
}
if (new Date(newStartDate) > new Date(newEndDate)) {
alert('La fecha de inicio debe ser anterior a la fecha de fin');
return;
}
const newTag = state.tags.find(t => t.id === newTagId);
if (!newTag) {
alert('Por favor, selecciona una etiqueta válida');
return;
}
// Eliminar las marcas del período antiguo
removePeriodMarks(periodId);
// Actualizar el período
period.tagId = newTag.id;
period.tagName = newTag.name;
period.tagColor = newTag.color;
period.startDate = newStartDate;
period.endDate = newEndDate;
// Remarcar los días con el período actualizado
let currentDate = new Date(newStartDate);
const endDate = new Date(newEndDate);
while (currentDate <= endDate) {
const dateStr = formatDate(currentDate);
const current = Array.isArray(state.markedDays[dateStr]) ? state.markedDays[dateStr] : (state.markedDays[dateStr] ? [state.markedDays[dateStr]] : []);
const exists = current.some(entry => entry.periodId === periodId);
if (!exists) {
current.push({ tagId: newTag.id, color: newTag.color, name: newTag.name, periodId: periodId });
}
state.markedDays[dateStr] = current;
currentDate.setDate(currentDate.getDate() + 1);
}
closeModal();
renderPeriodsList();
renderCalendar();
saveToLocalStorage();
}
// Eliminar período
function deletePeriod(periodId) {
if (!confirm('¿Estás seguro de eliminar este período?')) {
return;
}
// Eliminar las marcas del período
removePeriodMarks(periodId);
// Eliminar el período de la lista
state.periods = state.periods.filter(p => p.id !== periodId);
renderPeriodsList();
renderCalendar();
saveToLocalStorage();
}
// Eliminar marcas de un período específico
function removePeriodMarks(periodId) {
for (const date of Object.keys(state.markedDays)) {
const val = state.markedDays[date];
const arr = Array.isArray(val) ? val : (val ? [val] : []);
const filtered = arr.filter(entry => entry.periodId !== periodId);
if (filtered.length === 0) {
delete state.markedDays[date];
} else {
state.markedDays[date] = filtered;
}
}
}