-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhojas.gs
More file actions
843 lines (684 loc) · 32.4 KB
/
Copy pathhojas.gs
File metadata and controls
843 lines (684 loc) · 32.4 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
// Envoltorios para funciones invocadas por menú mostrar hojas por color
function mostrarHojasAzul() { conmutarHojasColor(COLORES_HOJAS.azul, true, false); }
function mostrarHojasMorado() { conmutarHojasColor(COLORES_HOJAS.morado, true, false); }
function mostrarHojasVerde() { conmutarHojasColor(COLORES_HOJAS.verde, true, false); }
function mostrarHojasNaranja() { conmutarHojasColor(COLORES_HOJAS.naranja, true, false); }
function mostrarHojasRojo() { conmutarHojasColor(COLORES_HOJAS.rojo, true, false); }
// Envoltorios para funciones invocadas por menú mostrar solo hojas por color
function mostrarSoloHojasAzul() { conmutarHojasColor(COLORES_HOJAS.azul, true, true); }
function mostrarSoloHojasMorado() { conmutarHojasColor(COLORES_HOJAS.morado, true, true); }
function mostrarSoloHojasVerde() { conmutarHojasColor(COLORES_HOJAS.verde, true, true); }
function mostrarSoloHojasNaranja() { conmutarHojasColor(COLORES_HOJAS.naranja, true, true); }
function mostrarSoloHojasRojo() { conmutarHojasColor(COLORES_HOJAS.rojo, true, true); }
// Envoltorios para funciones invocadas por menú ocultar hojas por color
function ocultarHojasAzul() { conmutarHojasColor(COLORES_HOJAS.azul, false, false); }
function ocultarHojasMorado() { conmutarHojasColor(COLORES_HOJAS.morado, false, false); }
function ocultarHojasVerde() { conmutarHojasColor(COLORES_HOJAS.verde, false, false); }
function ocultarHojasNaranja() { conmutarHojasColor(COLORES_HOJAS.naranja, false, false); }
function ocultarHojasRojo() { conmutarHojasColor(COLORES_HOJAS.rojo, false, false); }
// Envoltorios para funciones invocadas por menú eliminar hojas por color
function eliminarHojasAzul() { eliminarHojasColor(COLORES_HOJAS.azul); }
function eliminarHojasMorado() { eliminarHojasColor(COLORES_HOJAS.morado); }
function eliminarHojasVerde() { eliminarHojasColor(COLORES_HOJAS.verde); }
function eliminarHojasNaranja() { eliminarHojasColor(COLORES_HOJAS.naranja); }
function eliminarHojasRojo() { eliminarHojasColor(COLORES_HOJAS.rojo); }
// Envoltorios para funciones invocadas por menú ordenar hojas asc/dsc
function ordenarHojasAsc() { ordenarHojasServicio(true); }
function ordenarHojasDesc() { ordenarHojasServicio(false); }
/**
* Ordena las hojas alfabéticamente en sentido ascendente o descendente
* @param {boolean} [ascendente]
*/
function ordenarHojasServicio(ascendente = true) {
const hdc = SpreadsheetApp.getActiveSpreadsheet();
const ui = SpreadsheetApp.getUi();
// Precisamos únicamente el código del idioma (idioma_región)
const collator = new Intl.Collator(hdc.getSpreadsheetLocale().split('_')[0], { numeric: true, sensitivity: 'base' });
// Vector { hoja, nombre } para evitar múltiples llamadas a getName() en la función del sort().
const hojasOrdenadas = hdc.getSheets()
.map(hoja => ({ objeto: hoja, nombre: hoja.getName() }))
.sort((hoja1, hoja2) => Math.pow(-1, !ascendente) * collator.compare(hoja1.nombre, hoja2.nombre));
const hojasPorOcultar = [];
const hojaActual = hdc.getActiveSheet();
try {
hojasOrdenadas.forEach((hoja, pos) => {
if (hoja.objeto.isSheetHidden()) hojasPorOcultar.push(hoja.objeto);
hdc.setActiveSheet(hoja.objeto);
hdc.moveActiveSheet(pos + 1);
});
// Necesario confirmar cambios antes de procesar hojas a ocultar
SpreadsheetApp.flush();
// Sin esta pausa en ocasiones alguna hoja oculta queda visible
Utilities.sleep(1000);
if (hojasPorOcultar.length > 0) hojasPorOcultar.forEach(hoja => hoja.hideSheet());
hdc.setActiveSheet(hojaActual);
SpreadsheetApp.flush();
ui.alert(ENCABEZADO_ALERTAS, `Se han ordenado alfabéticamente ${hojasOrdenadas.length} hojas en sentido ${ascendente ? 'ascendente' : 'descendente'}.`, ui.ButtonSet.OK);
} catch (e) {
ui.alert(ENCABEZADO_ALERTAS, `Se ha producido un error inesperado al ordenar las hojas, inténtalo de nuevo.
⚠️ ${e.message}`, ui.ButtonSet.OK);
}
}
/**
* Ordena las hojas alfabéticamente en sentido ascendente o descendente usando la API de Sheets.
* Mucho más rapido, pero ***NO USADO*** por el momento, dado que requiere https://www.googleapis.com/auth/spreadsheets.
* @param {boolean} [ascendente]
*/
function ordenarHojasApi(ascendente = true) {
const hdc = SpreadsheetApp.getActiveSpreadsheet();
const ui = SpreadsheetApp.getUi();
// Precisamos únicamente el código del idioma (idioma_región)
const collator = new Intl.Collator(hdc.getSpreadsheetLocale().split('_')[0], { numeric: true, sensitivity: 'base' });
try {
// Obtiene vector de propiedades de hojas (nombre, índice)
const hojasOrdenadas = Sheets.Spreadsheets.get(
SpreadsheetApp.getActiveSpreadsheet().getId(), { fields: 'sheets.properties(sheetId,title,index)' }
).sheets.sort((hoja1, hoja2) =>
Math.pow(-1, !ascendente) * collator.compare(hoja1.properties.title, hoja2.properties.title)
);
const hojaActual = hdc.getActiveSheet();
Sheets.Spreadsheets.batchUpdate(
{
requests: hojasOrdenadas.map(({ properties: { sheetId } }, pos) => (
{ updateSheetProperties: { properties: { sheetId, index: pos }, fields: 'index' } }
)),
includeSpreadsheetInResponse: false
},
hdc.getId()
);
hdc.setActiveSheet(hojaActual);
SpreadsheetApp.flush();
ui.alert(ENCABEZADO_ALERTAS, `Se han ordenado alfabéticamente ${hojasOrdenadas.length} hojas en sentido ${ascendente ? 'ascendente' : 'descendente'}.`, ui.ButtonSet.OK);
} catch (e) {
ui.alert(ENCABEZADO_ALERTAS, `Se ha producido un error inesperado al ordenar las hojas, inténtalo de nuevo.
⚠️ ${e.message}`, ui.ButtonSet.OK);
}
}
/**
* Desordena las hojas de una hoja de cálculo de forma aleatoria
* utilizando el servicio integrado de hojas de cálculo.
* Mantiene el estado de visibilidad de las hojas y restaura la hoja activa.
*
* Generado por Gemini 2.5 Pro (experimental) a partir de la función de ordenación ordenarHojasServicio().
* https://pablofelip.online/velocidad-permisos-ordenando-pestanas-apps-script/
*/
function desordenarHojas() {
const hdc = SpreadsheetApp.getActiveSpreadsheet();
const ui = SpreadsheetApp.getUi();
try {
const hojas = hdc.getSheets();
const numHojas = hojas.length;
// --- Inicio: Algoritmo de Fisher-Yates (Knuth) Shuffle ---
// Recorre el array desde el final hacia el principio
for (let i = numHojas - 1; i > 0; i--) {
// Elige un índice aleatorio j entre 0 e i (inclusive)
const j = Math.floor(Math.random() * (i + 1));
// Intercambia el elemento en i con el elemento en j
[hojas[i], hojas[j]] = [hojas[j], hojas[i]];
}
// --- Fin: Algoritmo de Fisher-Yates ---
// Ahora el array 'hojas' contiene los objetos Sheet en un orden aleatorio.
const hojasPorOcultar = [];
const hojaActual = hdc.getActiveSheet(); // Guarda la hoja activa actual
// Mueve las hojas a su nueva posición aleatoria
hojas.forEach((hoja, pos) => {
// Comprueba si la hoja estaba oculta ANTES de moverla
// (moverla la hará visible temporalmente si estaba oculta)
if (hoja.isSheetHidden()) {
hojasPorOcultar.push(hoja); // Añade el objeto hoja a la lista para ocultar después
}
hdc.setActiveSheet(hoja); // Activa la hoja para poder moverla
hdc.moveActiveSheet(pos + 1); // Mueve la hoja a su nueva posición (índice + 1)
});
// Necesario confirmar cambios antes de procesar hojas a ocultar
SpreadsheetApp.flush();
// Mantenemos la pausa por consistencia con la función original,
// por si hay problemas de sincronización al ocultar rápidamente.
Utilities.sleep(1000);
// Vuelve a ocultar las hojas que estaban ocultas originalmente
hojasPorOcultar.forEach(hoja => hoja.hideSheet());
// Restaura la hoja que estaba activa al principio
hdc.setActiveSheet(hojaActual);
SpreadsheetApp.flush(); // Asegura que la activación final se aplique
ui.alert(ENCABEZADO_ALERTAS, `Se han desordenado aleatoriamente ${numHojas} hoja(s).`, ui.ButtonSet.OK);
} catch (e) {
// Mismo manejo de errores que la función original
ui.alert(ENCABEZADO_ALERTAS, `Se ha producido un error inesperado al desordenar las hojas, inténtalo de nuevo.
⚠️ ${e.message}`, ui.ButtonSet.OK);
}
}
/**
* Hace visible u oculta las hojas de uno de los colores parametrizados, ocultando el resto si se desea
* @param {Object} color Objeto que representa el color como { nombre: 'nombre_color', hex:'#rrggbb' }
* @param {boolean} visible true para mostrar, false para ocultar
* @param {boolean} ocultarResto true para ocultar el resto de hojas (se ignora si visible = false)
*/
function conmutarHojasColor(color, visible, ocultarResto) {
// Formato canónico de color hex, con canal alfa y en mayúsculas
const colorHex = color.hex.toUpperCase().slice(1).padStart(9, '#FF');
const ui = SpreadsheetApp.getUi();
const hojas = SpreadsheetApp.getActiveSpreadsheet().getSheets();
// Se ignora ocultarResto en operaciones de ocultación de hojas de color
ocultarResto = ocultarResto && visible;
let hojasColorProcesar = []; // hojas del color seleccionado cuya visibilidad actual hace que deban procesarse
let otrasHojasOcultar = []; // resto de hojas de otros colores a procesar (ocultar)
let numHojasVisibles = 0; // número total de hojas visibles
let numHojasColor = 0; // número de hojas del color seleccionado, con independencia de su visibilidad actual
// Identificar hojas a procesar y elementos auxiliares
hojas.forEach(hoja => {
if (!hoja.isSheetHidden()) numHojasVisibles++;
if (hoja.getTabColorObject().getColorType() == SpreadsheetApp.ColorType.RGB &&
hoja.getTabColorObject().asRgbColor().asHexString().toUpperCase().slice(1).padStart(9, '#FF') == colorHex) {
numHojasColor++;
// XOR (^) para invertir resultado booleano de isSheetHidden()
if (hoja.isSheetHidden() ^ !visible) hojasColorProcesar.push(hoja);
} else if (ocultarResto && !hoja.isSheetHidden()) otrasHojasOcultar.push(hoja);
});
if (!visible && (hojasColorProcesar.length == numHojasVisibles)) ui.alert(ENCABEZADO_ALERTAS, 'No puedes ocultar todas las hojas visibles.', ui.ButtonSet.OK)
else if (numHojasColor == 0) ui.alert(ENCABEZADO_ALERTAS, `${color.icono} No hay hojas de color ${color.nombre}.`, ui.ButtonSet.OK);
else if (hojasColorProcesar.length == 0 && otrasHojasOcultar.length == 0) ui.alert(ENCABEZADO_ALERTAS, `${color.icono} No hay hojas ${visible ? 'ocultas' : 'visibles'} de color ${color.nombre}.`, ui.ButtonSet.OK);
else try {
// Vector utilizado para construir el mensaje de estado al finalizar
let mensajeResultado = [];
// Ajustar visibilidad de hojas del color designado
if (hojasColorProcesar.length > 0) {
hojasColorProcesar.forEach(hoja => visible ? hoja.showSheet() : hoja.hideSheet());
mensajeResultado.push(`Se han ${visible ? 'hecho visibles' : 'ocultado'} ${hojasColorProcesar.length} hojas de color ${color.nombre}.`);
}
// Ocultar en su caso el resto de hojas
if (otrasHojasOcultar.length > 0) {
otrasHojasOcultar.forEach(hoja => hoja.hideSheet());
mensajeResultado.push(`Se han ocultado ${otrasHojasOcultar.length} hojas de color distinto al ${color.nombre}.`);
}
SpreadsheetApp.flush();
ui.alert(ENCABEZADO_ALERTAS, `${color.icono} ${mensajeResultado.join(' ')}`, ui.ButtonSet.OK);
} catch (e) {
ui.alert(ENCABEZADO_ALERTAS, `Se ha producido un error inesperado al ajustar la visibilidad de las hojas, inténtalo de nuevo.
⚠️ ${e.message}`, ui.ButtonSet.OK);
}
}
/**
* Elimina todas la hojas de un color determinado
* @param {Object} color Objeto que representa el color como { nombre: 'nombre_color', hex:'#rrggbb' }
*/
function eliminarHojasColor(color) {
// Formato canónico de color hex, con canal alfa y en mayúsculas
const colorHex = color.hex.toUpperCase().slice(1).padStart(9, '#FF');
const hdc = SpreadsheetApp.getActiveSpreadsheet();
const ui = SpreadsheetApp.getUi();
let hojasColorEliminar = []; // hojas del color seleccionado a eliminar
let numHojasVisibles = 0; // número total de hojas visibles
let numHojasColorVisibles = 0 // número de hojas del color seleccionado a eliminar que son visibles
let numHojasColorOcultas = 0 // número de hojas del color seleccionado a eliminar que están ocultas
// Identificar hojas a procesar y elementos auxiliares
hdc.getSheets().forEach(hoja => {
if (!hoja.isSheetHidden()) numHojasVisibles++;
if (hoja.getTabColorObject().getColorType() == SpreadsheetApp.ColorType.RGB &&
hoja.getTabColorObject().asRgbColor().asHexString().toUpperCase().slice(1).padStart(9, '#FF') == colorHex) {
if (hoja.isSheetHidden()) numHojasColorOcultas++;
else numHojasColorVisibles++;
hojasColorEliminar.push(hoja);
}
});
if (hojasColorEliminar.length == 0) ui.alert(ENCABEZADO_ALERTAS, `${color.icono} No hay hojas de color ${color.nombre} que eliminar.`, ui.ButtonSet.OK);
else if (numHojasVisibles == numHojasColorVisibles) ui.alert(ENCABEZADO_ALERTAS, `No es posible eliminar todas las hojas visibles.`, ui.ButtonSet.OK);
else try {
// Vector utilizado para construir el mensaje de estado al finalizar
let mensajeResultado = [];
if (numHojasColorVisibles > 0) mensajeResultado.push(`${numHojasColorVisibles} hojas visibles`);
if (numHojasColorOcultas > 0) mensajeResultado.push(`${numHojasColorOcultas} hojas ocultas`);
if (ui.alert(ENCABEZADO_ALERTAS, `⚠️ ¿Eliminar hojas de color ${color.nombre}?
${color.icono} Se van a eliminar ${mensajeResultado.join(' y ')} de color ${color.nombre}.
Puedes revertir el proceso utilizando el comando deshacer tantas veces como sea necesario.`,
ui.ButtonSet.OK_CANCEL) == ui.Button.OK) hojasColorEliminar.forEach(hoja => hdc.deleteSheet(hoja));
} catch (e) {
ui.alert(ENCABEZADO_ALERTAS, `Se ha producido un error inesperado al eliminar las hojas, inténtalo de nuevo.
⚠️ ${e.message}`, ui.ButtonSet.OK);
}
}
/**
* Elimina todas la hojas ocultas
*/
function eliminarHojasOcultas() {
const ui = SpreadsheetApp.getUi();
const hdc = SpreadsheetApp.getActiveSpreadsheet();
const hojasEliminar = hdc.getSheets().filter(hoja => hoja.isSheetHidden());
if (hojasEliminar.length == 0) ui.alert(ENCABEZADO_ALERTAS, 'No hay hojas ocultas que eliminar.', ui.ButtonSet.OK);
else try {
// Se usa try para fallar graciosamente cuando en un escenario de concurrencia se eliminan
// algunas de las hojas mientras el usuario visualiza la alerta de confirmación
if (ui.alert(ENCABEZADO_ALERTAS, `⚠️ ¿Eliminar hojas ocultas?
Se van a eliminar ${hojasEliminar.length} hojas no visibles de la hoja de cálculo.
Puedes revertir el proceso utilizando el comando deshacer tantas veces como sea necesario.`,
ui.ButtonSet.OK_CANCEL) == ui.Button.OK) hojasEliminar.forEach(hoja => hdc.deleteSheet(hoja));
} catch (e) {
ui.alert(ENCABEZADO_ALERTAS, `Se ha producido un error inesperado al eliminar las hojas, inténtalo de nuevo.
⚠️ ${e.message}`, ui.ButtonSet.OK);
}
}
/**
* Elimina todas las hojas de la hdc excepto la activa
*/
function eliminarHojas() {
const ui = SpreadsheetApp.getUi();
const hdc = SpreadsheetApp.getActiveSpreadsheet();
const idHojaActual = hdc.getActiveSheet().getSheetId();
const hojasEliminar = hdc.getSheets().filter(hoja => hoja.getSheetId() != idHojaActual);
if (hojasEliminar.length == 0) ui.alert(ENCABEZADO_ALERTAS, 'No hay más hojas que puedan eliminarse.', ui.ButtonSet.OK);
else try {
if (ui.alert(ENCABEZADO_ALERTAS, `⚠️ ¿Eliminar otras hojas?
Se van a eliminar ${hojasEliminar.length} hojas de la hoja de cálculo.
Puedes revertir el proceso utilizando el comando deshacer tantas veces como sea necesario.`,
ui.ButtonSet.OK_CANCEL) == ui.Button.OK) hojasEliminar.forEach(hoja => hdc.deleteSheet(hoja));
} catch (e) {
ui.alert(ENCABEZADO_ALERTAS, `Se ha producido un error inesperado al eliminar las hojas, inténtalo de nuevo.
⚠️ ${e.message}`, ui.ButtonSet.OK);
}
}
/**
* Oculta todas las hojas de la hdc excepto la activa
*/
function mostrarSoloActiva() {
const ui = SpreadsheetApp.getUi();
const hdc = SpreadsheetApp.getActiveSpreadsheet();
if (hdc.getSheets().length == 1) ui.alert(ENCABEZADO_ALERTAS, 'No hay más hojas que puedan ocultarse.', ui.ButtonSet.OK);
else {
const idHojaActual = SpreadsheetApp.getActiveSheet().getSheetId();
const hojasVisibles = SpreadsheetApp.getActiveSpreadsheet().getSheets().filter(hoja => !hoja.isSheetHidden() && hoja.getSheetId() != idHojaActual);
if (hojasVisibles.length == 0) ui.alert(ENCABEZADO_ALERTAS, 'No hay más hojas visibles que ocultar.', ui.ButtonSet.OK);
else try {
hojasVisibles.forEach(hoja => hoja.hideSheet());
SpreadsheetApp.flush();
ui.alert(ENCABEZADO_ALERTAS, `Se han ocultado ${hojasVisibles.length} hojas.`, ui.ButtonSet.OK);
} catch (e) {
ui.alert(ENCABEZADO_ALERTAS, `Se ha producido un error inesperado al ajustar la visibilidad de las hojas, inténtalo de nuevo.
⚠️ ${e.message}`, ui.ButtonSet.OK);
}
}
}
/**
* Hace visibles todas las hojas de la hdc
*/
function mostrarHojas() {
const ui = SpreadsheetApp.getUi();
const hdc = SpreadsheetApp.getActiveSpreadsheet();
const hojasOcultas = hdc.getSheets().filter(hoja => hoja.isSheetHidden());
if (hojasOcultas.length == 0) ui.alert(ENCABEZADO_ALERTAS, 'No hay hojas ocultas que mostrar.', ui.ButtonSet.OK);
else try {
hojasOcultas.forEach(hoja => hoja.showSheet());
SpreadsheetApp.flush();
ui.alert(ENCABEZADO_ALERTAS, `Se han hecho visibles ${hojasOcultas.length} hojas.`, ui.ButtonSet.OK);
} catch (e) {
ui.alert(ENCABEZADO_ALERTAS, `Se ha producido un error inesperado al ajustar la visibilidad de las hojas, inténtalo de nuevo.
⚠️ ${e.message}`, ui.ButtonSet.OK);
}
}
/**
* Hace visibles todas las hojas de la hdc excepto la activa
*/
function mostrarTodasMenosActual() {
const ui = SpreadsheetApp.getUi();
const hdc = SpreadsheetApp.getActiveSpreadsheet();
const hojaActual = SpreadsheetApp.getActiveSheet();
if (hdc.getSheets().length == 1) ui.alert(ENCABEZADO_ALERTAS, 'No es posible ocultar la única hoja existente.', ui.ButtonSet.OK);
else {
const hojasOcultas = SpreadsheetApp.getActiveSpreadsheet().getSheets().filter(hoja => hoja.isSheetHidden());
try {
hojasOcultas.forEach(hoja => hoja.showSheet());
hojaActual.hideSheet();
if (hojasOcultas.length > 0) {
SpreadsheetApp.flush();
ui.alert(ENCABEZADO_ALERTAS, `Se han hecho visibles ${hojasOcultas.length} hojas.`, ui.ButtonSet.OK);
}
} catch (e) {
ui.alert(ENCABEZADO_ALERTAS, `Se ha producido un error inesperado al ajustar la visibilidad de las hojas, inténtalo de nuevo.
⚠️ ${e.message}`, ui.ButtonSet.OK);
}
}
}
/**
* Conmuta la visibilidad de todas las hojas existentes
*/
function conmutarVisibilidadHojas() {
const ui = SpreadsheetApp.getUi();
const hdc = SpreadsheetApp.getActiveSpreadsheet();
const hojas = hdc.getSheets();
const hojasOcultas = hojas.filter(hoja => hoja.isSheetHidden());
const hojasVisibles = hojas.filter(hoja => !hoja.isSheetHidden());
if (hojasVisibles.length == 1 && hojasOcultas.length == 0) ui.alert(ENCABEZADO_ALERTAS, 'No es posible ocultar la única hoja existente.', ui.ButtonSet.OK);
else if (hojasOcultas.length == 0) ui.alert(ENCABEZADO_ALERTAS, 'No hay hojas ocultas que mostrar.', ui.ButtonSet.OK);
else try {
hojasOcultas.forEach(hoja => hoja.showSheet());
hojasVisibles.forEach(hoja => hoja.hideSheet());
SpreadsheetApp.flush();
ui.alert(ENCABEZADO_ALERTAS, `Se han ocultado ${hojasVisibles.length} hojas y se han hecho visibles otras ${hojasOcultas.length}.`, ui.ButtonSet.OK);
} catch (e) {
ui.alert(ENCABEZADO_ALERTAS, `Se ha producido un error inesperado al ajustar la visibilidad de las hojas, inténtalo de nuevo.
⚠️ ${e.message}`, ui.ButtonSet.OK);
}
}
// --- FUNCIONES PARA LA CONSOLA DE PESTAÑAS (GESTIÓN AVANZADA) ---
/**
* Abre el diálogo de gestión avanzada de hojas
*/
function abrirConsolaPestañas() {
const html = HtmlService.createTemplateFromFile('dialogoGestionarHojas')
.evaluate()
.setWidth(750)
.setHeight(600)
.setTitle('📁 Consola de Pestañas | HdC+');
SpreadsheetApp.getUi().showModalDialog(html, ' ');
}
/**
* Abre el diálogo modal para crear marcos de color
*/
function abrirDialogoMarcoColor() {
const html = HtmlService.createTemplateFromFile('dialogoMarcoColor')
.evaluate()
.setWidth(450)
.setHeight(800)
.setTitle('🖼️ Crear marco de color | HdC+');
SpreadsheetApp.getUi().showModalDialog(html, ' ');
}
/**
* Aplica un marco de color a la hoja activa basándose en la configuración
*/
function aplicarMarcoColor(config) {
const hdc = SpreadsheetApp.getActiveSpreadsheet();
const hoja = hdc.getActiveSheet();
// 1. Parámetros de la configuración
const color = config.color;
const pixelAncho = config.mantenerTamano ? 21 : (parseInt(config.ancho) || 21);
const pixelAlto = config.mantenerTamano ? 21 : (parseInt(config.alto) || 21);
const numPadding = config.conPadding ? (parseInt(config.padding) || 0) : 0;
if (color === '#FFFFFF') {
return "💡 Utiliza el comando 'Recortar' para eliminar marcos existentes.";
}
// 2. ENCUADRE PREVIO (Si se solicita y estamos en modo Data Range)
if (config.soloDataRange) {
const modoRecorte = config.encuadrePosterior ? 3 : 0; // 3 = Filas y columnas sobrantes, 0 = nada
const encuadreAnterior = config.encuadreAnterior;
if (modoRecorte > 0 || encuadreAnterior) {
procesarRecorteHoja_(hoja, modoRecorte, encuadreAnterior);
SpreadsheetApp.flush();
}
}
// 3. Definir área de aplicación (Toda la hoja o Data Range actualizado)
let rowInit, rowEnd, colInit, colEnd;
if (config.soloDataRange) {
const range = hoja.getDataRange();
rowInit = range.getRow();
rowEnd = range.getLastRow();
colInit = range.getColumn();
colEnd = range.getLastColumn();
} else {
rowInit = 1;
rowEnd = hoja.getMaxRows();
colInit = 1;
colEnd = hoja.getMaxColumns();
}
// 3. Inserciones geométricas (1 celda para el borde + N celdas para padding)
const totalInsert = 1 + numPadding;
// Filas (Arriba y Abajo del área seleccionada)
hoja.insertRowsBefore(rowInit, totalInsert);
hoja.insertRowsAfter(rowEnd + totalInsert, totalInsert); // +totalInsert porque la hoja se ha desplazado
// Columnas (Izquierda y Derecha)
hoja.insertColumnsBefore(colInit, totalInsert);
hoja.insertColumnsAfter(colEnd + totalInsert, totalInsert);
SpreadsheetApp.flush();
// 4. Ajustar tamaños y aplicar Colores
const maxR = hoja.getMaxRows();
const maxC = hoja.getMaxColumns();
// Coordenadas del borde exterior (son la primera y última fila/columna del área expandida)
const bFilSup = rowInit;
const bFilInf = rowEnd + (totalInsert * 2);
const bColIzq = colInit;
const bColDer = colEnd + (totalInsert * 2);
// Aplicar tamaños en píxeles al borde
hoja.setRowHeight(bFilSup, pixelAlto);
hoja.setRowHeight(bFilInf, pixelAlto);
hoja.setColumnWidth(bColIzq, pixelAncho);
hoja.setColumnWidth(bColDer, pixelAncho);
// Si hay margen sincronizado, aplicar también el tamaño a las filas de padding
if (config.conPadding && config.syncPadding) {
for (let i = 1; i <= numPadding; i++) {
hoja.setRowHeight(bFilSup + i, pixelAlto);
hoja.setRowHeight(bFilInf - i, pixelAlto);
hoja.setColumnWidth(bColIzq + i, pixelAncho);
hoja.setColumnWidth(bColDer - i, pixelAncho);
}
}
// 5. Aplicar fondos de color al borde
// Superior e Inferior
hoja.getRange(bFilSup, bColIzq, 1, bColDer - bColIzq + 1).setBackground(color);
hoja.getRange(bFilInf, bColIzq, 1, bColDer - bColIzq + 1).setBackground(color);
// Laterales (ajustados para no solapar)
hoja.getRange(bFilSup + 1, bColIzq, bFilInf - bFilSup - 1, 1).setBackground(color);
hoja.getRange(bFilSup + 1, bColDer, bFilInf - bFilSup - 1, 1).setBackground(color);
// 6. Combinación (Merge)
if (config.combinar) {
if (config.dominancia === 'horizontal') {
hoja.getRange(bFilSup, bColIzq, 1, bColDer - bColIzq + 1).merge();
hoja.getRange(bFilInf, bColIzq, 1, bColDer - bColIzq + 1).merge();
hoja.getRange(bFilSup + 1, bColIzq, bFilInf - bFilSup - 1, 1).merge();
hoja.getRange(bFilSup + 1, bColDer, bFilInf - bFilSup - 1, 1).merge();
} else {
hoja.getRange(bFilSup, bColIzq, bFilInf - bFilSup + 1, 1).merge();
hoja.getRange(bFilSup, bColDer, bFilInf - bFilSup + 1, 1).merge();
hoja.getRange(bFilSup, bColIzq + 1, 1, bColDer - bColIzq - 1).merge();
hoja.getRange(bFilInf, bColIzq + 1, 1, bColDer - bColIzq - 1).merge();
}
}
return "✅ Marco de color aplicado correctamente.";
}
/**
* Obtiene metadatos de todas las hojas incluyendo su pertenencia a grupos
*/
function getHojasMetaData() {
const hdc = SpreadsheetApp.getActiveSpreadsheet();
const hojas = hdc.getSheets();
const grupos = JSON.parse(PropertiesService.getDocumentProperties().getProperty('HDC_GRUPOS_HOJAS') || '{}');
// Mapeo inverso de ID de hoja a nombre de grupo
const idAGrupo = {};
for (const nombreGrupo in grupos) {
if (Array.isArray(grupos[nombreGrupo])) {
grupos[nombreGrupo].forEach(id => idAGrupo[id] = nombreGrupo);
}
}
return hojas.map(h => {
const id = h.getSheetId();
let color = '#FFFFFF';
const colorObj = h.getTabColorObject();
if (colorObj.getColorType() === SpreadsheetApp.ColorType.RGB) {
color = colorObj.asRgbColor().asHexString();
}
return {
id: id,
nombre: h.getName(),
oculta: h.isSheetHidden(),
color: color,
grupo: idAGrupo[id] || '',
activa: h.getName() === hdc.getActiveSheet().getName()
};
});
}
/**
* Guarda la configuración de grupos
* @param {Object} grupos { "NombreGrupo": [id1, id2], ... }
*/
function guardarGruposHojas(grupos) {
PropertiesService.getDocumentProperties().setProperty('HDC_GRUPOS_HOJAS', JSON.stringify(grupos));
return "✅ Grupos guardados correctamente.";
}
/**
* Aplica cambios masivos desde la consola (visibilidad, color, grupos, orden)
*/
function aplicarCambiosConsola(cambios) {
const hdc = SpreadsheetApp.getActiveSpreadsheet();
const hojas = hdc.getSheets();
const hojasMap = hojas.reduce((acc, h) => { acc[h.getSheetId()] = h; return acc; }, {});
let hojaActual = hdc.getActiveSheet();
const idActiva = hojaActual.getSheetId();
// 1. Gestión de seguridad: Si la activa se va a ocultar, buscamos sustituta visible
const cambioActiva = cambios.hojas ? cambios.hojas.find(c => c.id == idActiva) : null;
if (cambioActiva && cambioActiva.oculta) {
const sustituta = hojas.find(h => {
const c = cambios.hojas.find(ch => ch.id == h.getSheetId());
return c ? !c.oculta : !h.isSheetHidden();
});
if (sustituta) {
hdc.setActiveSheet(sustituta);
hojaActual = sustituta; // La nueva activa para la restauración final
}
}
// 2. Aplicar visibilidad y color
if (cambios.hojas) {
cambios.hojas.forEach(c => {
const hoja = hojasMap[c.id];
if (hoja) {
if (c.oculta !== undefined) c.oculta ? hoja.hideSheet() : hoja.showSheet();
if (c.color !== undefined) hoja.setTabColor(c.color === '#FFFFFF' ? null : c.color);
}
});
}
// 3. Aplicar orden (si se proporciona)
if (cambios.ordenIds && cambios.ordenIds.length > 0) {
cambios.ordenIds.forEach((id, pos) => {
const hoja = hojasMap[id];
if (hoja) {
hdc.setActiveSheet(hoja);
hdc.moveActiveSheet(pos + 1);
}
});
// Restaurar la que definimos como activa (sea la original o la sustituta)
hdc.setActiveSheet(hojaActual);
}
// 4. Guardar grupos
if (cambios.grupos) guardarGruposHojas(cambios.grupos);
SpreadsheetApp.flush();
return "✅ Cambios aplicados con éxito.";
}
/**
* Elimina las hojas seleccionadas por ID
*/
function eliminarHojasPorId(ids) {
const hdc = SpreadsheetApp.getActiveSpreadsheet();
const hojas = hdc.getSheets();
const aEliminar = hojas.filter(h => ids.includes(h.getSheetId()));
if (aEliminar.length >= hojas.length) {
throw new Error("No puedes eliminar todas las hojas del documento.");
}
aEliminar.forEach(h => hdc.deleteSheet(h));
return `✅ Se han eliminado ${aEliminar.length} hojas.`;
}
/**
* Activa una hoja específica por su ID
*/
function activarHojaPorId(id) {
const hdc = SpreadsheetApp.getActiveSpreadsheet();
const hoja = hdc.getSheets().find(h => h.getSheetId() == id);
if (hoja) {
hdc.setActiveSheet(hoja);
return `Pestaña "${hoja.getName()}" activada.`;
}
throw new Error("No se pudo encontrar la pestaña.");
}
// --- GENERADOR DE ÍNDICES ---
/**
* Genera un índice completo en una pestaña dedicada 'Índice HdC+'
*/
function generarIndiceCompleto() {
const hdc = SpreadsheetApp.getActiveSpreadsheet();
const ui = SpreadsheetApp.getUi();
let hojaIndice = hdc.getSheetByName(NOMBRE_INDICE);
// Advertir sobre la sobreescritura total si la pestaña ya existe
if (hojaIndice) {
if (ui.alert(ENCABEZADO_ALERTAS, `⚠️ ¿Actualizar pestaña de índice?
Se va a sobreescribir por completo el contenido y el formato de la pestaña [${NOMBRE_INDICE}].`, ui.ButtonSet.OK_CANCEL) !== ui.Button.OK) {
return;
}
hojaIndice.clear().clearNotes();
} else {
hojaIndice = hdc.insertSheet(NOMBRE_INDICE, 0);
}
const cabeceras = [['Pestaña', 'Estado', 'Grupo']];
const datos = obtenerDatosIndice_(true);
if (datos.length === 0) {
ui.alert(ENCABEZADO_ALERTAS, 'No hay otras pestañas para indexar.', ui.ButtonSet.OK);
return;
}
// Escribir cabeceras
hojaIndice.getRange(1, 1, 1, 3).setValues(cabeceras).setFontWeight('bold').setBackground('#f3f3f3');
// Escribir datos (nombres/enlaces en la columna 1, metadatos en 2 y 3)
const nombresRichText = datos.map(fila => [fila[0]]);
const metadatos = datos.map(fila => [fila[1], fila[2]]);
hojaIndice.getRange(2, 1, datos.length, 1).setRichTextValues(nombresRichText);
hojaIndice.getRange(2, 2, datos.length, 2).setValues(metadatos);
// Formato
hojaIndice.autoResizeColumns(1, 3);
hojaIndice.getRange('A1').setNote(`Última actualización: ${new Date().toLocaleString()}`);
hdc.toast('Índice generado con éxito.', '📑 HdC+', 5);
}
/**
* Inserta un índice ligero (solo enlaces) a partir de la celda activa
*/
function insertarIndiceLigero() {
const hdc = SpreadsheetApp.getActiveSpreadsheet();
const celdaActiva = hdc.getActiveCell();
const ui = SpreadsheetApp.getUi();
const datos = obtenerDatosIndice_(false);
if (datos.length === 0) {
ui.alert(ENCABEZADO_ALERTAS, 'No hay otras pestañas para indexar.', ui.ButtonSet.OK);
return;
}
// Comprobar si hay riesgo de sobreescribir datos
const rangoDestino = celdaActiva.offset(0, 0, datos.length, 1);
const valoresExistentes = rangoDestino.getValues();
const tieneDatos = valoresExistentes.some(fila => fila[0] !== '');
if (tieneDatos) {
if (ui.alert(ENCABEZADO_ALERTAS, `⚠️ ¿Sobreescribir datos?
El rango donde se insertará el índice ya contiene información. ¿Deseas continuar?`, ui.ButtonSet.OK_CANCEL) !== ui.Button.OK) {
return;
}
}
rangoDestino.setRichTextValues(datos.map(fila => [fila[0]]));
hdc.toast('Índice insertado.', '📌 HdC+', 5);
}
/**
* Función interna para recopilar datos de pestañas y generar enlaces RichText
* @private
*/
function obtenerDatosIndice_(incluirMetadatos) {
const hdc = SpreadsheetApp.getActiveSpreadsheet();
const hojas = hdc.getSheets();
// Obtener grupos para los metadatos
let idAGrupo = {};
if (incluirMetadatos) {
const grupos = JSON.parse(PropertiesService.getDocumentProperties().getProperty('HDC_GRUPOS_HOJAS') || '{}');
for (const nombreGrupo in grupos) {
if (Array.isArray(grupos[nombreGrupo])) {
grupos[nombreGrupo].forEach(id => idAGrupo[id] = nombreGrupo);
}
}
}
const filas = [];
hojas.forEach(hoja => {
if (hoja.getName() !== NOMBRE_INDICE) {
const id = hoja.getSheetId();
const nombre = hoja.getName();
// Crear valor RichText con enlace nativo (#gid=ID)
const rt = SpreadsheetApp.newRichTextValue()
.setText(nombre)
.setLinkUrl(`#gid=${id}`)
.build();
if (incluirMetadatos) {
const estado = hoja.isSheetHidden() ? '🙈 Oculta' : '👁️ Visible';
const grupo = idAGrupo[id] || '-';
filas.push([rt, estado, grupo]);
} else {
filas.push([rt]);
}
}
});
return filas;
}