Para cumplir con el objetivo de condicionar la visibilidad de los botones dentro de cada celda según la respuesta del endpoint getKPI, se deben realizar modificaciones tanto en el archivo TypeScript como en la plantilla HTML del componente GridDesignerComponent. A continuación, se detallan los cambios necesarios, incluyendo el código antiguo, el nuevo código con las modificaciones y comentarios explicativos para una mejor comprensión.
1. Modificaciones en el Archivo TypeScript (grid-designer.component.ts)
a. Definir la Estructura de botones en las Columnas
Código Antiguo:
Actualmente, las columnas no tienen una propiedad dedicada para almacenar la información de visibilidad de los botones.
Código Nuevo:
Agregar una propiedad botones a cada columna para almacenar la visibilidad de los botones según la respuesta del endpoint getKPI.
private initializeGridData(data: any[]): any[] {
return data.map((row) => ({
...row,
columns: row.columns.map((col: any) => ({
...col,
botones: { // Nueva propiedad para almacenar la visibilidad de los botones
drillDown: false,
uso: false,
descripcion: false,
fullSize: false
},
// ... otras propiedades existentes
content: Array.isArray(col.content)
? col.content
: col.content
? [col.content]
: [],
alternativeContent: Array.isArray(col.alternativeContent)
? col.alternativeContent
: col.alternativeContent
? [col.alternativeContent]
: [],
showSwitch: col.showSwitch || false,
switchLeftText: col.switchLeftText || 'Izquierda',
switchRightText: col.switchRightText || 'Derecha',
switchActiveSide: col.switchActiveSide || 'left',
multiSelection: col.multiSelection || false,
contentOptions: [],
alternativeContentOptions: [],
selectedContent: null,
alternativeSelectedContent: null,
activeSelectedContent: null,
activeContentOptions: [],
selectedContentIndex: 0,
showOptionsMenu: true,
})),
height: row.height || '20%',
}));
}
Comentarios Explicativos:
- Se agrega la propiedad
botones a cada columna con valores por defecto false para drillDown, uso, descripcion y fullSize. Estos valores se actualizarán posteriormente con la respuesta del endpoint getKPI.
b. Actualizar applyKPI para Obtener la Configuración de Botones
Código Antiguo:
La función applyKPI actualmente se encarga de aplicar el KPI seleccionado a la celda pero no maneja la lógica para obtener la visibilidad de los botones.
applyKPI() {
const cell = this.editingCell;
// ... lógica existente para aplicar el KPI
}
Código Nuevo:
Modificar la función applyKPI para que, después de aplicar el KPI, llame al endpoint getKPI y actualice la propiedad botones de la columna.
applyKPI() {
const cell = this.editingCell;
// ... lógica existente para aplicar el KPI
// Obtener el número de KPI aplicado
const kpiNumber = this.extractKpiNumber(cell.selectedContent.value);
// Llamar al endpoint getKPI para obtener la visibilidad de los botones
this.kpiService.getKPIButtons(kpiNumber).subscribe(
(response: any) => {
// Asignar la respuesta del endpoint a la propiedad botones de la columna
cell.botones = response.botones;
// Verificar si todos los botones están en false para ocultar el botón de opciones
const { drillDown, uso, descripcion, fullSize } = cell.botones;
cell.showOptionsButton = drillDown || uso || descripcion || fullSize;
// Actualizar la interfaz si es necesario
this.renderDynamicComponents();
},
(error: any) => {
// Manejo de errores
console.error('Error al obtener la configuración de botones:', error);
// Por defecto ocultar el botón de opciones en caso de error
cell.showOptionsButton = false;
}
);
// Continuar con la lógica existente para actualizar el gridDataString
// ... lógica existente para actualizar gridDataString
}
Comentarios Explicativos:
- Se asume que el servicio
KpiService tiene un método getKPIButtons que realiza la llamada al endpoint getKPI y devuelve la estructura de botones.
- Después de obtener la respuesta, se asigna el objeto
botones a la columna correspondiente.
- Se introduce una nueva propiedad
showOptionsButton para determinar si el botón de opciones debe mostrarse, basado en si al menos uno de los botones está habilitado.
- En caso de error al llamar al endpoint, se oculta el botón de opciones por defecto.
Nota: Asegúrate de que el servicio KpiService tenga el método getKPIButtons. Si no existe, debes implementarlo como se muestra a continuación.
c. Implementar el Método getKPIButtons en KpiService
Código Nuevo:
// En kpi.service.ts
getKPIButtons(kpiNumber: number): Observable<any> {
return this.http.get<any>(`/api/getKPI/${kpiNumber}`);
}
Comentarios Explicativos:
- Este método realiza una solicitud GET al endpoint
/api/getKPI/:kpiNumber para obtener la configuración de botones para un KPI específico.
- Asegúrate de que la URL del endpoint sea correcta según tu configuración de backend.
d. Inicializar showOptionsButton en las Columnas
Código Nuevo:
Actualizar la inicialización de gridData para incluir la propiedad showOptionsButton, inicializada en false.
private initializeGridData(data: any[]): any[] {
return data.map((row) => ({
...row,
columns: row.columns.map((col: any) => ({
...col,
botones: { // Nueva propiedad para almacenar la visibilidad de los botones
drillDown: false,
uso: false,
descripcion: false,
fullSize: false
},
showOptionsButton: false, // Nueva propiedad para controlar la visibilidad del botón de opciones
// ... otras propiedades existentes
content: Array.isArray(col.content)
? col.content
: col.content
? [col.content]
: [],
alternativeContent: Array.isArray(col.alternativeContent)
? col.alternativeContent
: col.alternativeContent
? [col.alternativeContent]
: [],
showSwitch: col.showSwitch || false,
switchLeftText: col.switchLeftText || 'Izquierda',
switchRightText: col.switchRightText || 'Derecha',
switchActiveSide: col.switchActiveSide || 'left',
multiSelection: col.multiSelection || false,
contentOptions: [],
alternativeContentOptions: [],
selectedContent: null,
alternativeSelectedContent: null,
activeSelectedContent: null,
activeContentOptions: [],
selectedContentIndex: 0,
showOptionsMenu: true,
})),
height: row.height || '20%',
}));
}
Comentarios Explicativos:
- Se agrega la propiedad
showOptionsButton para cada columna, la cual controlará la visibilidad del botón de opciones en la interfaz.
2. Modificaciones en la Plantilla HTML (grid-designer.component.html)
a. Condicionar la Visibilidad del Botón de Opciones y los Botones del Menú
Código Antiguo:
<!-- Botón de Opciones (More Vert) -->
<button class="cell-button" (click)="toggleOptionsMenu(col, $event)">
<span class="material-symbols-outlined">
more_vert <!-- Icono de tres puntos verticales de Google Fonts -->
</span>
</button>
<!-- Menú de Opciones -->
<div class="options-menu" [ngClass]="{'show': col.showOptionsMenu}"
(click)="$event.stopPropagation()">
<button class="options-menu-item"
(click)="showInfoPanel(col, rowIndex, colIndex); toggleOptionsMenu(col, $event)">
<span class="material-symbols-outlined">info</span>
<span>Información</span>
</button>
<button class="options-menu-item" (click)="cellclicktemp(); toggleOptionsMenu(col, $event)">
<span class="material-symbols-outlined">table_view</span>
<span>Mostrar datos</span>
</button>
<button class="options-menu-item"
(click)="toggleCellExpansion(col); toggleOptionsMenu(col, $event)">
<span class="material-symbols-outlined">{{ col.isExpanded ? 'close_fullscreen' : 'open_in_full'
}}</span>
<span>{{ col.isExpanded ? 'Restaurar' : 'Expandir' }}</span>
</button>
</div>
Código Nuevo:
<!-- Botón de Opciones (More Vert) Condicionado -->
<button *ngIf="col.showOptionsButton" class="cell-button" (click)="toggleOptionsMenu(col, $event)">
<span class="material-symbols-outlined">
more_vert <!-- Icono de tres puntos verticales de Google Fonts -->
</span>
</button>
<!-- Menú de Opciones -->
<div class="options-menu" [ngClass]="{'show': col.showOptionsMenu}"
(click)="$event.stopPropagation()">
<!-- Botón Información (uso) -->
<button *ngIf="col.botones.uso" class="options-menu-item"
(click)="showInfoPanel(col, rowIndex, colIndex); toggleOptionsMenu(col, $event)">
<span class="material-symbols-outlined">info</span>
<span>Información</span>
</button>
<!-- Botón Mostrar Datos (drillDown) -->
<button *ngIf="col.botones.drillDown" class="options-menu-item"
(click)="cellclicktemp(); toggleOptionsMenu(col, $event)">
<span class="material-symbols-outlined">table_view</span>
<span>Mostrar datos</span>
</button>
<!-- Botón Expandir/Restaurar (fullSize) -->
<button *ngIf="col.botones.fullSize" class="options-menu-item"
(click)="toggleCellExpansion(col); toggleOptionsMenu(col, $event)">
<span class="material-symbols-outlined">
{{ col.isExpanded ? 'close_fullscreen' : 'open_in_full' }}
</span>
<span>{{ col.isExpanded ? 'Restaurar' : 'Expandir' }}</span>
</button>
</div>
Comentarios Explicativos:
-
Botón de Opciones (more_vert):
- Cambio: Se agrega la directiva
*ngIf="col.showOptionsButton" al botón de opciones.
- Propósito: Mostrar el botón de opciones únicamente si al menos uno de los botones (
uso, drillDown, fullSize) está habilitado según la respuesta del endpoint getKPI.
-
Botones del Menú de Opciones:
-
Cambio: Cada botón dentro del menú de opciones (Información, Mostrar datos, Expandir/Restaurar) ahora tiene una directiva *ngIf que verifica la propiedad correspondiente en col.botones.
-
Propósito: Mostrar u ocultar cada botón del menú de opciones según la configuración obtenida del endpoint getKPI.
-
Mapping de Propiedades:
info está mapeado a uso (col.botones.uso).
table_view está mapeado a drillDown (col.botones.drillDown).
expand está mapeado a fullSize (col.botones.fullSize).
b. Agregar la Propiedad showOptionsButton al Objeto column en TypeScript
Código Nuevo:
Asegúrate de que cada columna tenga la propiedad showOptionsButton para controlar la visibilidad del botón de opciones.
// Dentro de initializeGridData o al aplicar un KPI
cell.showOptionsButton = cell.botones.drillDown || cell.botones.uso || cell.botones.fullSize;
Comentarios Explicativos:
- La propiedad
showOptionsButton se establece en true si al menos uno de los botones (drillDown, uso, fullSize) está habilitado.
- Esto asegura que el botón de opciones solo se muestre si hay al menos una acción disponible.
c. Modificar renderDynamicComponents para Considerar showOptionsButton
Si en algún punto los componentes dinámicos afectan la visibilidad de los botones, asegúrate de que renderDynamicComponents tenga en cuenta la propiedad showOptionsButton. Sin embargo, según el código proporcionado, esto no parece ser necesario a menos que se dinámicamente agreguen o remuevan botones en tiempo real.
3. Resumen de Cambios
TypeScript (grid-designer.component.ts):
-
Agregar la Propiedad botones y showOptionsButton a las Columnas:
- Se añade una estructura para almacenar la configuración de visibilidad de los botones.
- Se inicializa
showOptionsButton en función de las propiedades de botones.
-
Actualizar la Función applyKPI:
- Después de aplicar el KPI, se llama al endpoint
getKPIButtons para obtener la configuración de visibilidad de los botones.
- Se actualiza las propiedades
botones y showOptionsButton de la columna correspondiente.
-
Implementar getKPIButtons en KpiService:
- Se implementa un método que realiza una solicitud al endpoint
getKPI para obtener la configuración de botones.
HTML (grid-designer.component.html):
-
Condicionar la Visibilidad del Botón de Opciones:
- El botón de opciones (
more_vert) ahora solo se muestra si col.showOptionsButton es true.
-
Condicionar la Visibilidad de los Botones del Menú de Opciones:
- Cada botón dentro del menú de opciones (
Información, Mostrar datos, Expandir/Restaurar) ahora se muestra u oculta en función de las propiedades correspondientes en col.botones.
4. Ejemplo Completo de las Modificaciones
a. Archivo TypeScript Completo Modificado (grid-designer.component.ts):
import {
Component,
OnInit,
ViewContainerRef,
ViewChildren,
QueryList,
AfterViewInit,
NgModule,
HostListener,
ViewChild,
ElementRef,
inject,
} from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { ToastrService } from 'ngx-toastr';
import { NgxSpinnerModule, NgxSpinnerService } from 'ngx-spinner';
import * as ace from 'ace-builds';
import 'ace-builds/src-noconflict/mode-json';
import 'ace-builds/src-noconflict/theme-dracula';
import { GaugeComponent } from '../gauge/gauge.component';
import { DataGridComponent } from '../data-grid/data-grid.component';
import { KpiListComponent } from '../kpis/kpi-list.component';
import { KpiService } from '../../services/kpi.services';
import { NgSelectModule } from '@ng-select/ng-select';
import { MatTooltipModule } from '@angular/material/tooltip';
@Component({
selector: 'app-grid-designer',
standalone: true,
imports: [
CommonModule,
FormsModule,
NgSelectModule,
NgxSpinnerModule,
MatTooltipModule,
],
templateUrl: './grid-designer.component.html',
styleUrl: './grid-designer.component.scss',
})
export class GridDesignerComponent implements OnInit, AfterViewInit {
@ViewChildren('dynamicComponentContainer', { read: ViewContainerRef })
dynamicComponentContainers!: QueryList<ViewContainerRef>;
@ViewChild('contextMenu') contextMenuElement!: ElementRef;
private kpiService = inject(KpiService);
gridData: any[] = [];
gridDataString: string = '';
isHidden = false;
jsonValid: boolean | null = null;
private editor: ace.Ace.Editor | null = null;
editingCell: any = null;
contextMenuVisible = false;
contextMenuX = 0;
contextMenuY = 0;
selectedCell: any = null;
componentOptions: { label: string; value: any }[] = [];
activeCellInfo: { rowIndex: number; colIndex: number; col: any } | null =
null;
expandedCell: { rowIndex: number; colIndex: number } | null = null;
availableThemes = [
{ value: 'default', label: 'Básico', color: '#9cdc82' },
{ value: 'custommsi', label: 'MSI', color: '#3f3f86' },
{ value: 'vintage', label: 'Vintage', color: '#c2994f' },
{ value: 'macarons', label: 'Pastel', color: '#28c5c5' },
{ value: 'wonderland', label: 'Esmeralda', color: '#55b3a6' },
{ value: 'essos', label: 'Essos', color: '#ee6058' },
{ value: 'westeros', label: 'Poniente', color: '#c14089' },
{ value: 'dark', label: 'Oscuro', color: '#000000' },
{ value: 'chalk', label: 'Tiza', color: '#c4ccd3' }
];
selectedTheme = this.availableThemes[0];
isCustommsiTheme: boolean = false; // Nueva propiedad para detectar el tema "custommsi"
// Arreglo para almacenar referencias a los componentes dinámicos creados
private dynamicComponents: { componentRef: any, rowIndex: number, colIndex: number }[] = [];
constructor(
private http: HttpClient,
private toastr: ToastrService,
private spinner: NgxSpinnerService
) { }
ngOnInit(): void {
this.getListKPI();
this.http.get('assets/grid-default.json').subscribe((data: any) => {
this.gridData = this.initializeGridData(data);
this.gridDataString = JSON.stringify(this.gridData, null, 2);
this.updateEditorValue();
this.configToastr();
// Opcional: Inicializar la visibilidad de los botones para celdas predefinidas
this.initializeButtonsVisibility();
});
}
ngAfterViewInit(): void {
this.initAceEditor();
setTimeout(() => this.renderDynamicComponents(), 100);
}
ngOnDestroy() {
this.hideInfoPanel();
if (this.expandedCell) {
const expandedCol =
this.gridData[this.expandedCell.rowIndex].columns[
this.expandedCell.colIndex
];
expandedCol.isExpanded = false;
this.expandedCell = null;
}
}
onThemeChange() {
console.log("🔰 ~ onThemeChange ~ this.selectedTheme.value:", this.selectedTheme.value);
// Actualizar el tema en todos los componentes dinámicos
this.dynamicComponents.forEach(item => {
(item.componentRef.instance as any).theme = this.selectedTheme.value;
});
// Actualizar la propiedad iscustommsiTheme
this.isCustommsiTheme = this.selectedTheme.value === 'custommsi';
}
getListKPI(): void {
this.kpiService.getListKPI().subscribe(
(data: any[]) => {
this.componentOptions = data.map((item) => ({
label: `kpi-${item.idKPI} - ${item.representacion} - ${item.nombre}`,
value: item.idKPI,
}));
this.componentOptions.push({
label: `kpi-1001 - img - test_image`,
value: 1001,
});
this.componentOptions.push({
label: `kpi-1002 - cardobj - test_image`,
value: 1002,
});
},
(error: any) => {
// Manejo de errores
}
);
}
getLabelTitle(label: string): string {
const parts = label.split(' - ');
return parts[parts.length - 1];
}
onMultiselectionListChange(e: any, col: any) {
if (col.multiSelection && col.showSwitch) {
this.onMultiselectionListChangeWithSwitch(e, col);
} else {
col.selectedContent = e;
col.activeSelectedContent = col.selectedContent;
const { rowIndex, colIndex } = this.getCellIndices(col);
this.renderDynamicComponents(rowIndex, colIndex);
}
}
onMultiselectionListChangeWithSwitch(e: any, col: any) {
const index = col.activeContentOptions.findIndex(
(option: any) => option.value === e.value
);
col.selectedContentIndex = index;
if (col.switchActiveSide === 'left') {
col.selectedContent = col.contentOptions[index];
col.alternativeSelectedContent =
col.alternativeContentOptions[index] ||
col.alternativeContentOptions[0];
col.activeSelectedContent = col.selectedContent;
} else {
col.alternativeSelectedContent = col.alternativeContentOptions[index];
col.selectedContent = col.contentOptions[index] || col.contentOptions[0];
col.activeSelectedContent = col.alternativeSelectedContent;
}
const { rowIndex, colIndex } = this.getCellIndices(col);
this.renderDynamicComponents(rowIndex, colIndex);
}
getCellIndices(cell: any): { rowIndex: number; colIndex: number } {
for (let i = 0; i < this.gridData.length; i++) {
const row = this.gridData[i];
const columns = row.columns;
for (let j = 0; j < columns.length; j++) {
if (columns[j] === cell) {
return { rowIndex: i, colIndex: j };
}
}
}
return { rowIndex: -1, colIndex: -1 }; // Si no se encuentra
}
private initializeGridData(data: any[]): any[] {
return data.map((row) => ({
...row,
columns: row.columns.map((col: any) => ({
...col,
botones: { // Nueva propiedad para almacenar la visibilidad de los botones
drillDown: false,
uso: false,
descripcion: false,
fullSize: false
},
showOptionsButton: false, // Nueva propiedad para controlar la visibilidad del botón de opciones
content: Array.isArray(col.content)
? col.content
: col.content
? [col.content]
: [],
alternativeContent: Array.isArray(col.alternativeContent)
? col.alternativeContent
: col.alternativeContent
? [col.alternativeContent]
: [],
showSwitch: col.showSwitch || false,
switchLeftText: col.switchLeftText || 'Izquierda',
switchRightText: col.switchRightText || 'Derecha',
switchActiveSide: col.switchActiveSide || 'left',
multiSelection: col.multiSelection || false,
contentOptions: [],
alternativeContentOptions: [],
selectedContent: null,
alternativeSelectedContent: null,
activeSelectedContent: null,
activeContentOptions: [],
selectedContentIndex: 0,
showOptionsMenu: true,
})),
height: row.height || '20%',
}));
}
// Opcional: Inicializar la visibilidad de los botones para celdas predefinidas
private initializeButtonsVisibility(): void {
this.gridData.forEach((row, rowIndex) => {
row.columns.forEach((col: any, colIndex: number) => {
if (col.isComponent && col.selectedContent) {
const kpiNumber = this.extractKpiNumber(col.selectedContent.value);
this.kpiService.getKPIButtons(kpiNumber).subscribe(
(response: any) => {
col.botones = response.botones;
const { drillDown, uso, descripcion, fullSize } = col.botones;
col.showOptionsButton = drillDown || uso || descripcion || fullSize;
this.renderDynamicComponents(rowIndex, colIndex);
},
(error: any) => {
console.error('Error al obtener la configuración de botones:', error);
col.showOptionsButton = false;
}
);
}
});
});
}
private initAceEditor(): void {
const editorElement = document.getElementById('editor');
if (editorElement) {
this.editor = ace.edit(editorElement);
this.editor.setTheme('ace/theme/dracula');
this.editor.session.setMode('ace/mode/json');
this.editor.setOptions({
fontSize: '14px',
showPrintMargin: false,
showGutter: true,
highlightActiveLine: true,
enableBasicAutocompletion: true,
enableLiveAutocompletion: true,
enableSnippets: true,
});
this.updateEditorValue();
this.editor.getSession().on('change', () => {
this.gridDataString = this.editor?.getValue() ?? '';
this.jsonValid = false;
});
} else {
console.error('Error al inicializar el Editor Ace');
}
}
onRightClick(event: MouseEvent, cell: any) {
event.preventDefault();
this.contextMenuVisible = true;
this.contextMenuX = event.clientX;
this.contextMenuY = event.clientY;
this.selectedCell = cell;
}
@HostListener('document:click', ['$event'])
public onDocumentClick(event: Event): void {
// Cierra los menús de opciones en las celdas
this.gridData.forEach(row => {
row.columns.forEach((col: any) => {
col.showOptionsMenu = false;
});
});
// Cierra el menú contextual si está visible
if (this.contextMenuVisible) {
this.contextMenuVisible = false;
}
}
public onContextMenuClick(event: Event): void {
event.stopPropagation();
}
addColumnToRow() {
if (this.selectedCell) {
const rowIndex = this.gridData.findIndex((row) =>
row.columns.includes(this.selectedCell)
);
if (rowIndex !== -1) {
const newColumn = {
botones: { // Inicializar la propiedad botones para la nueva columna
drillDown: false,
uso: false,
descripcion: false,
fullSize: false
},
showOptionsButton: false, // Inicializar showOptionsButton
width: 'auto',
content: '',
colSpan: 1,
rowSpan: 1,
isComponent: false,
multiSelection: false,
switchLeftText: 'Izquierda',
switchRightText: 'Derecha',
switchActiveSide: 'left',
showOptionsMenu: true,
};
this.gridData[rowIndex].columns.push(newColumn);
this.updateJsonAndEditor();
}
}
this.contextMenuVisible = false;
this.toastr.success(`Nueva columna añadida.`);
}
changeRowHeight(event: Event, row: any) {
const inputElement = event.target as HTMLInputElement;
row.height = this.validateHeight(inputElement.value);
this.updateJsonAndEditor();
}
private validateHeight(value: string): string {
if (value.endsWith('px') || value.endsWith('%')) {
return value;
}
const num = parseInt(value);
if (isNaN(num)) return '20%';
return `${Math.max(5, Math.min(100, num))}%`;
}
changeWidth(event: Event) {
if (this.selectedCell) {
const inputElement = event.target as HTMLInputElement;
this.selectedCell.width = this.validateWidth(inputElement.value);
this.updateJsonAndEditor();
}
}
private validateWidth(value: string): string {
if (value.endsWith('px') || value.endsWith('%')) {
return value;
}
const num = parseInt(value);
if (isNaN(num)) return '100%';
return `${Math.max(10, Math.min(100, num))}%`;
}
adjustWidth(change: number) {
if (this.selectedCell) {
if (!this.selectedCell.width || this.selectedCell.width === 'auto') {
this.selectedCell.width = '100%';
}
if (this.selectedCell.width.endsWith('px')) {
const currentPx = parseInt(this.selectedCell.width);
this.selectedCell.width = `${Math.max(50, currentPx + change)}px`;
} else {
const currentPercent = parseInt(this.selectedCell.width);
this.selectedCell.width = `${Math.max(
10,
Math.min(100, currentPercent + change)
)}%`;
}
this.updateJsonAndEditor();
}
}
adjustRow(row: any, change: number) {
if (!row.height || row.height === 'auto') {
row.height = '20%';
}
if (row.height.endsWith('px')) {
const currentPx = parseInt(row.height);
row.height = `${Math.max(50, Math.min(900, currentPx + change))}px`;
} else {
const currentPercent = parseInt(row.height);
row.height = `${Math.max(5, Math.min(100, currentPercent + change))}%`;
}
this.updateJsonAndEditor();
}
getSelectedRow(): any {
return this.gridData.find((row) => row.columns.includes(this.selectedCell));
}
adjustColSpan(change: number) {
if (this.selectedCell) {
this.selectedCell.colSpan = Math.max(
1,
(this.selectedCell.colSpan || 1) + change
);
this.updateJsonAndEditor();
}
}
adjustRowSpan(change: number) {
if (this.selectedCell) {
this.selectedCell.rowSpan = Math.max(
1,
(this.selectedCell.rowSpan || 1) + change
);
this.updateJsonAndEditor();
}
}
deleteCell() {
if (this.selectedCell) {
const rowIndex = this.gridData.findIndex((row) =>
row.columns.includes(this.selectedCell)
);
if (rowIndex !== -1) {
const columnIndex = this.gridData[rowIndex].columns.indexOf(
this.selectedCell
);
this.gridData[rowIndex].columns.splice(columnIndex, 1);
if (this.gridData[rowIndex].columns.length === 0) {
this.gridData.splice(rowIndex, 1);
}
this.updateJsonAndEditor();
}
}
this.contextMenuVisible = false;
this.toastr.success(`Celda eliminada.`);
}
addRow() {
const newRow = {
height: '100px',
columns: [
{
botones: { // Inicializar botones para la nueva columna
drillDown: false,
uso: false,
descripcion: false,
fullSize: false
},
showOptionsButton: false, // Inicializar showOptionsButton
width: '100%',
content: '',
colSpan: 1,
rowSpan: 1,
isComponent: false,
multiSelection: false,
switchLeftText: 'Izquierda',
switchRightText: 'Derecha',
switchActiveSide: 'left',
showOptionsMenu: true,
},
],
};
this.gridData.push(newRow);
this.contextMenuVisible = false;
this.toastr.success(`Nueva fila añadida.`);
this.updateJsonAndEditor();
}
updateJsonAndEditor() {
const jsonReplacer = (key: any, value: any) => {
if (value && typeof value === 'object' && !Array.isArray(value)) {
const ordered: any = {};
if (value.hasOwnProperty('content'))
ordered['content'] = value['content'];
if (value.hasOwnProperty('alternativeContent'))
ordered['alternativeContent'] = value['alternativeContent'];
for (const k of Object.keys(value)) {
if (k !== 'content' && k !== 'alternativeContent') {
ordered[k] = value[k];
}
}
return ordered;
}
return value;
};
this.gridDataString = JSON.stringify(this.gridData, jsonReplacer, 2);
this.updateEditorValue();
}
private updateEditorValue(): void {
if (this.editor && this.gridDataString) {
this.editor.setValue(this.gridDataString);
this.editor.clearSelection();
}
}
configToastr() {
this.toastr.toastrConfig.positionClass = 'toast-top-full-width';
this.toastr.toastrConfig.extendedTimeOut = 0;
this.toastr.toastrConfig.timeOut = 2900;
}
toggleSidebar() {
this.isHidden = !this.isHidden;
}
getGridTemplateColumns(columns: any[]): string {
return columns.map((col) => col.width).join(' ');
}
getGridTemplateRows(): string {
return this.gridData.map((row) => row.height).join(' ');
}
validateAndApplyJson() {
try {
const parsedData = JSON.parse(this.gridDataString);
this.gridData = parsedData;
this.jsonValid = true;
setTimeout(() => this.renderDynamicComponents(), 100);
} catch (error) {
this.jsonValid = false;
this.toastr.warning(`Error al procesar el JSON: ${error}`, 'Advertencia');
}
}
renderDynamicComponents(
specificRowIndex?: number,
specificColIndex?: number
): void {
console.log(
'🔰 ~ renderDynamicComponents ~ specificRowIndex:',
specificRowIndex,
'specificColIndex:',
specificColIndex
);
setTimeout(() => {
if (!this.dynamicComponentContainers) return;
let containerIndex = 0;
this.gridData.forEach((row, rowIndex) => {
row.columns.forEach((col: any, colIndex: number) => {
if (col.isComponent) {
if (
specificRowIndex === undefined ||
(rowIndex === specificRowIndex && colIndex === specificColIndex)
) {
const container =
this.dynamicComponentContainers.get(containerIndex);
if (container) {
container.clear();
this.createComponent(container, col, rowIndex, colIndex);
}
}
containerIndex++;
}
});
});
}, 100);
}
async createComponent(
container: ViewContainerRef,
col: any,
rowIndex: number,
colIndex: number
): Promise<void> {
this.spinner.show();
try {
const spinnerName = `spinner-${rowIndex}-${colIndex}`;
this.spinner.show(spinnerName);
let kpiNumber;
if (col.activeSelectedContent) {
kpiNumber = col.activeSelectedContent.value;
} else {
// Si por alguna razón no está definido, intentar asignarlo
// Posibles casos de selección simple sin switch
if (col.selectedContent) {
kpiNumber = col.selectedContent.value;
} else {
throw new Error('No se pudo determinar el kpiNumber');
}
}
const ComponentType = await this.loadDynamicComponent(`kpi-${kpiNumber}`);
const componentRef = container.createComponent(ComponentType);
(componentRef.instance as any).kpiNumber = kpiNumber;
// Asignar el tema seleccionado al componente
(componentRef.instance as any).theme = this.selectedTheme.value;
// Almacenar la referencia del componente dinámico
this.dynamicComponents.push({
componentRef: componentRef,
rowIndex: rowIndex,
colIndex: colIndex
});
if ((componentRef.instance as any).isCard) {
col.isCard = true;
} else {
col.isCard = false;
}
this.spinner.hide(spinnerName);
} catch (error) {
this.spinner.hide(`spinner-${rowIndex}-${colIndex}`);
this.toastr.error(`Error al crear el componente.`);
console.error('Error al crear el componente:', error);
}
}
private async loadDynamicComponent(componentName: string): Promise<any> {
const kpiNumber = parseInt(componentName.split('-')[1]);
const kpiRequest = {
listKpi: [kpiNumber > 1000 ? 34 : kpiNumber],
filtros: {
w: {
fechaDesde: '2023-01-01',
fechaHasta: '2023-12-31',
},
},
};
const data = await this.kpiService.getKPI(kpiRequest).toPromise();
console.log('🔰 ~ loadDynamicComponent ~ data:', data);
let representacion: string | null = null;
if (data.representacion) {
representacion = data.representacion.toLowerCase();
}
if (!representacion) {
this.toastr.error(
`No se encuentra "representacion" en el json para: ${componentName}`
);
throw new Error(
`No se encuentra "representacion" en el json para: ${componentName}`
);
}
console.log('🔰 ~ loadDynamicComponent ~ representacion:', representacion);
try {
if (kpiNumber === 1001) {
representacion = 'img';
}
if (kpiNumber === 1002) {
representacion = 'cardObj';
}
const module = await import(
`../kpi-components/kpi-${representacion}/kpi-${representacion}.component`
);
const componentKey = Object.keys(module).find(
(key) =>
key.toLowerCase() === `kpi${representacion?.toLowerCase()}component`
);
console.log(module);
if (!componentKey) {
throw new Error(`No se encontró el componente para: ${representacion}`);
}
return module[componentKey];
} catch (error) {
console.error(`Error al cargar el componente: ${error}`);
this.toastr.error(
`No se pudo cargar el componente para: ${representacion}`
);
throw error;
}
}
editKPI(col: any) {
console.log('🔰 ~ editKPI ~ col:', col);
// Limpiar los ng-select al entrar en modo edición
col.content = [];
col.alternativeContent = [];
col.selectedContent = null;
col.alternativeSelectedContent = null;
col.contentOptions = [];
col.alternativeContentOptions = [];
col.activeContentOptions = [];
col.activeSelectedContent = null;
col.selectedContentIndex = 0;
col.switchLeftText = col.switchLeftText || 'Izquierda';
col.switchRightText = col.switchRightText || 'Derecha';
this.editingCell = col;
}
toggleMultiSelection(col: any) {
col.multiSelection = !col.multiSelection;
if (col.multiSelection) {
// Al activar la multiselección, vaciamos 'col.content', 'col.contentOptions', y 'col.selectedContent'
col.content = [];
col.contentOptions = [];
col.selectedContent = null;
} else {
// Mantener col.content como array incluso en selección simple
if (col.content.length > 1) {
// Si hay más de un elemento, cogemos el primero
col.content = [col.content[0]];
col.contentOptions = [col.contentOptions[0]];
col.selectedContent = col.contentOptions[0] || null;
} else if (col.content.length === 0) {
// Si está vacío, inicializamos
col.content = [];
col.contentOptions = [];
col.selectedContent = null;
}
}
}
switchComponent(col: any, side: string) {
col.switchActiveSide = side;
if (col.multiSelection && col.showSwitch) {
// Ambos activos
if (col.selectedContentIndex === undefined) {
col.selectedContentIndex = 0;
}
if (side === 'left') {
col.activeContentOptions = col.contentOptions;
col.activeSelectedContent =
col.contentOptions[col.selectedContentIndex] || col.contentOptions[0];
col.selectedContent = col.activeSelectedContent;
} else {
col.activeContentOptions = col.alternativeContentOptions;
col.activeSelectedContent =
col.alternativeContentOptions[col.selectedContentIndex] ||
col.alternativeContentOptions[0];
col.alternativeSelectedContent = col.activeSelectedContent;
}
} else if (col.showSwitch) {
// Solo switch
if (side === 'left') {
col.activeSelectedContent = col.selectedContent;
} else {
col.activeSelectedContent = col.alternativeSelectedContent;
}
}
const { rowIndex, colIndex } = this.getCellIndices(col);
this.renderDynamicComponents(rowIndex, colIndex);
}
isApplyDisabled(): boolean {
if (this.editingCell.multiSelection && this.editingCell.showSwitch) {
const leftLength = Array.isArray(this.editingCell.content)
? this.editingCell.content.length
: 0;
const rightLength = Array.isArray(this.editingCell.alternativeContent)
? this.editingCell.alternativeContent.length
: 0;
return leftLength !== rightLength;
}
return false;
}
applyKPI() {
const cell = this.editingCell;
if (cell.multiSelection && cell.showSwitch) {
// Si multiselección y switch están activos
// Procesar el lado izquierdo del switch
let kpiNumbersLeft = Array.isArray(cell.content)
? cell.content
: [cell.content];
kpiNumbersLeft = kpiNumbersLeft.map((item: any) =>
this.extractKpiNumber(item.toString())
);
cell.content = kpiNumbersLeft;
// Procesar el lado derecho del switch
let kpiNumbersRight = Array.isArray(cell.alternativeContent)
? cell.alternativeContent
: [cell.alternativeContent];
kpiNumbersRight = kpiNumbersRight.map((item: any) =>
this.extractKpiNumber(item.toString())
);
cell.alternativeContent = kpiNumbersRight;
if (cell.content.length !== cell.alternativeContent.length) {
this.toastr.warning(
'Las listas de componentes deben tener el mismo número de elementos',
'Advertencia'
);
return;
}
// Continuar si las listas tienen la misma cantidad de componentes
cell.contentOptions = cell.content.map((value: any) =>
this.componentOptions.find((option) => option.value === value)
);
cell.selectedContent = cell.contentOptions[0] || null;
cell.alternativeContentOptions = cell.alternativeContent.map(
(value: any) =>
this.componentOptions.find((option) => option.value === value)
);
cell.alternativeSelectedContent =
cell.alternativeContentOptions[0] || null;
// Inicializar el índice elegido, 0 por defecto
cell.selectedContentIndex = 0;
} else {
// Otros casos (solo multiselección, solo switch y selección simple)
if (cell.content) {
let kpiNumbers = Array.isArray(cell.content)
? cell.content
: [cell.content];
kpiNumbers = kpiNumbers.map((item: any) =>
this.extractKpiNumber(item.toString())
);
cell.content = kpiNumbers;
if (cell.multiSelection) {
// Multiselección sin switch
cell.contentOptions = cell.content.map((value: any) =>
this.componentOptions.find((option) => option.value === value)
);
cell.selectedContent = cell.contentOptions[0] || null;
} else {
// Selección simple
const kpiNumber = kpiNumbers[0];
cell.contentOptions = [
this.componentOptions.find(
(option) => option.value === kpiNumber
) || null,
];
cell.selectedContent = cell.contentOptions[0];
}
}
if (cell.showSwitch && cell.alternativeContent) {
let altKpiNumbers = Array.isArray(cell.alternativeContent)
? cell.alternativeContent
: [cell.alternativeContent];
altKpiNumbers = altKpiNumbers.map((item: any) =>
this.extractKpiNumber(item.toString())
);
cell.alternativeContent = altKpiNumbers;
if (cell.multiSelection) {
// Manejado arriba cuando ambos están activos
} else {
// Selección simple con switch
const altKpiNumber = altKpiNumbers[0];
cell.alternativeContentOptions = [
this.componentOptions.find(
(option) => option.value === altKpiNumber
) || null,
];
cell.alternativeSelectedContent = cell.alternativeContentOptions[0];
}
}
}
// Establecer activeSelectedContent y activeContentOptions para todos los casos
if (cell.multiSelection && cell.showSwitch) {
// Ambos activos
if (cell.switchActiveSide === 'left') {
cell.activeContentOptions = cell.contentOptions;
cell.activeSelectedContent = cell.selectedContent;
} else {
cell.activeContentOptions = cell.alternativeContentOptions;
cell.activeSelectedContent = cell.alternativeSelectedContent;
}
} else if (cell.multiSelection) {
// Solo multiselección
cell.activeContentOptions = cell.contentOptions;
cell.activeSelectedContent = cell.selectedContent;
} else if (cell.showSwitch) {
// Solo switch
if (cell.switchActiveSide === 'left') {
cell.activeSelectedContent = cell.selectedContent;
} else {
cell.activeSelectedContent = cell.alternativeSelectedContent;
}
} else {
// Selección simple sin multiselección ni switch
cell.activeSelectedContent = cell.selectedContent;
}
cell.isComponent = true;
// Obtener el número de KPI aplicado
const kpiNumber = cell.selectedContent ? this.extractKpiNumber(cell.selectedContent.value) : null;
if (kpiNumber !== null) {
// Llamar al endpoint getKPI para obtener la visibilidad de los botones
this.kpiService.getKPIButtons(kpiNumber).subscribe(
(response: any) => {
// Asignar la respuesta del endpoint a la propiedad botones de la columna
cell.botones = response.botones;
// Verificar si al menos un botón está habilitado
const { drillDown, uso, descripcion, fullSize } = cell.botones;
cell.showOptionsButton = drillDown || uso || descripcion || fullSize;
// Actualizar gridData y gridDataString
const { rowIndex, colIndex } = this.getEditingCellIndices();
let gridDataStringObj = JSON.parse(this.gridDataString);
gridDataStringObj[rowIndex].columns[colIndex] = {
...gridDataStringObj[rowIndex].columns[colIndex],
...cell,
};
this.gridDataString = JSON.stringify(gridDataStringObj, null, 2);
this.gridData[rowIndex].columns[colIndex] =
gridDataStringObj[rowIndex].columns[colIndex];
this.updateEditorValue();
this.renderDynamicComponents(rowIndex, colIndex);
this.editingCell = null;
},
(error: any) => {
// Manejo de errores
console.error('Error al obtener la configuración de botones:', error);
cell.showOptionsButton = false;
// Actualizar gridData y gridDataString
const { rowIndex, colIndex } = this.getEditingCellIndices();
let gridDataStringObj = JSON.parse(this.gridDataString);
gridDataStringObj[rowIndex].columns[colIndex] = {
...gridDataStringObj[rowIndex].columns[colIndex],
...cell,
};
this.gridDataString = JSON.stringify(gridDataStringObj, null, 2);
this.gridData[rowIndex].columns[colIndex] =
gridDataStringObj[rowIndex].columns[colIndex];
this.updateEditorValue();
this.renderDynamicComponents(rowIndex, colIndex);
this.editingCell = null;
}
);
} else {
// Sin KPI seleccionado, ocultar el botón de opciones
cell.showOptionsButton = false;
// Actualizar gridData y gridDataString
const { rowIndex, colIndex } = this.getEditingCellIndices();
let gridDataStringObj = JSON.parse(this.gridDataString);
gridDataStringObj[rowIndex].columns[colIndex] = {
...gridDataStringObj[rowIndex].columns[colIndex],
...cell,
};
this.gridDataString = JSON.stringify(gridDataStringObj, null, 2);
this.gridData[rowIndex].columns[colIndex] =
gridDataStringObj[rowIndex].columns[colIndex];
this.updateEditorValue();
this.renderDynamicComponents(rowIndex, colIndex);
this.editingCell = null;
}
}
applyKPIWithMultiSelectionAndSwitch() {
const cell = this.editingCell;
// Procesar contenido para el lado izquierdo
let kpiNumbersLeft = Array.isArray(cell.content)
? cell.content
: [cell.content];
kpiNumbersLeft = kpiNumbersLeft.map((item: any) =>
this.extractKpiNumber(item.toString())
);
cell.content = kpiNumbersLeft;
cell.contentOptions = cell.content.map((value: any) =>
this.componentOptions.find((option) => option.value === value)
);
cell.selectedContent = cell.contentOptions[0] || null;
// Procesar contenido para el lado derecho
let kpiNumbersRight = Array.isArray(cell.alternativeContent)
? cell.alternativeContent
: [cell.alternativeContent];
kpiNumbersRight = kpiNumbersRight.map((item: any) =>
this.extractKpiNumber(item.toString())
);
cell.alternativeContent = kpiNumbersRight;
cell.alternativeContentOptions = cell.alternativeContent.map((value: any) =>
this.componentOptions.find((option) => option.value === value)
);
cell.alternativeSelectedContent =
cell.alternativeContentOptions[0] || null;
// Inicializar contenido activo y el índice seleccionado
cell.selectedContentIndex = 0;
if (cell.switchActiveSide === 'left') {
cell.activeContentOptions = cell.contentOptions;
cell.activeSelectedContent = cell.selectedContent;
} else {
cell.activeContentOptions = cell.alternativeContentOptions;
cell.activeSelectedContent = cell.alternativeSelectedContent;
}
cell.isComponent = true;
// Obtener el número de KPI aplicado
const kpiNumber = cell.selectedContent ? this.extractKpiNumber(cell.selectedContent.value) : null;
if (kpiNumber !== null) {
// Llamar al endpoint getKPI para obtener la visibilidad de los botones
this.kpiService.getKPIButtons(kpiNumber).subscribe(
(response: any) => {
// Asignar la respuesta del endpoint a la propiedad botones de la columna
cell.botones = response.botones;
// Verificar si al menos un botón está habilitado
const { drillDown, uso, descripcion, fullSize } = cell.botones;
cell.showOptionsButton = drillDown || uso || descripcion || fullSize;
// Actualizar gridData y gridDataString
const { rowIndex, colIndex } = this.getEditingCellIndices();
let gridDataStringObj = JSON.parse(this.gridDataString);
gridDataStringObj[rowIndex].columns[colIndex] = {
...gridDataStringObj[rowIndex].columns[colIndex],
...cell,
};
this.gridDataString = JSON.stringify(gridDataStringObj, null, 2);
this.gridData[rowIndex].columns[colIndex] =
gridDataStringObj[rowIndex].columns[colIndex];
this.updateEditorValue();
this.renderDynamicComponents(rowIndex, colIndex);
this.editingCell = null;
},
(error: any) => {
// Manejo de errores
console.error('Error al obtener la configuración de botones:', error);
cell.showOptionsButton = false;
// Actualizar gridData y gridDataString
const { rowIndex, colIndex } = this.getEditingCellIndices();
let gridDataStringObj = JSON.parse(this.gridDataString);
gridDataStringObj[rowIndex].columns[colIndex] = {
...gridDataStringObj[rowIndex].columns[colIndex],
...cell,
};
this.gridDataString = JSON.stringify(gridDataStringObj, null, 2);
this.gridData[rowIndex].columns[colIndex] =
gridDataStringObj[rowIndex].columns[colIndex];
this.updateEditorValue();
this.renderDynamicComponents(rowIndex, colIndex);
this.editingCell = null;
}
);
} else {
// Sin KPI seleccionado, ocultar el botón de opciones
cell.showOptionsButton = false;
// Actualizar gridData y gridDataString
const { rowIndex, colIndex } = this.getEditingCellIndices();
let gridDataStringObj = JSON.parse(this.gridDataString);
gridDataStringObj[rowIndex].columns[colIndex] = {
...gridDataStringObj[rowIndex].columns[colIndex],
...cell,
};
this.gridDataString = JSON.stringify(gridDataStringObj, null, 2);
this.gridData[rowIndex].columns[colIndex] =
gridDataStringObj[rowIndex].columns[colIndex];
this.updateEditorValue();
this.renderDynamicComponents(rowIndex, colIndex);
this.editingCell = null;
}
}
getEditingCellIndices() {
let rowIndex = -1;
let colIndex = -1;
for (let i = 0; i < this.gridData.length; i++) {
const columns = this.gridData[i].columns;
for (let j = 0; j < columns.length; j++) {
if (columns[j] === this.editingCell) {
rowIndex = i;
colIndex = j;
return { rowIndex, colIndex };
}
}
}
return { rowIndex, colIndex };
}
private extractKpiNumber(value: string | number): number {
if (typeof value === 'number') {
return value;
}
const match = value.match(/\d+/);
return match ? parseInt(match[0], 10) : 0;
}
cellclicktemp() {
this.toastr.info(`CLICK EN BOTÓN`);
}
showCellInfo() { }
showInfoPanel(col: any, rowIndex: number, colIndex: number) {
// Si el panel que se intenta abrir ya está abierto, lo cerramos
if (
this.activeCellInfo &&
this.activeCellInfo.rowIndex === rowIndex &&
this.activeCellInfo.colIndex === colIndex
) {
this.hideInfoPanel();
return;
}
// Cerrar el panel activo si existe
this.hideInfoPanel();
// Abrir el nuevo panel
this.activeCellInfo = { rowIndex, colIndex, col };
col.showInfoPanel = true;
setTimeout(() => {
const infoPanel = document.querySelector(
`.info-panel-${rowIndex}-${colIndex}`
) as HTMLElement;
if (infoPanel) {
infoPanel.classList.add('show');
}
}, 0);
}
hideInfoPanel() {
if (!this.activeCellInfo) return;
const { rowIndex, colIndex, col } = this.activeCellInfo;
const infoPanel = document.querySelector(
`.info-panel-${rowIndex}-${colIndex}`
) as HTMLElement;
if (infoPanel) {
infoPanel.classList.remove('show');
}
col.showInfoPanel = false;
this.activeCellInfo = null;
}
toggleCellExpansion(col: any) {
if (col.isExpanded) {
col.isContracting = true;
setTimeout(() => {
col.isExpanded = false;
col.isContracting = false;
}, 200); // Duración de la animación
} else {
col.isExpanding = true;
setTimeout(() => {
col.isExpanded = true;
col.isExpanding = false;
}, 200); // Duración de la animación
}
}
// En tu componente TypeScript
public toggleOptionsMenu(col: any, event: Event): void {
// Prevenir que el evento clic se propague y cierre el menú inmediatamente
event.stopPropagation();
// Alterna la visibilidad del menú para la columna actual
col.showOptionsMenu = !col.showOptionsMenu;
if (col.showOptionsMenu) {
// Cierra los menús de las demás columnas
this.gridData.forEach(row => {
row.columns.forEach((c: any) => {
if (c !== col) {
c.showOptionsMenu = false;
}
});
});
}
}
}
Comentarios Explicativos:
b. Archivo HTML Completo Modificado (grid-designer.component.html):
<div class="dashboard-container">
<!-- Sidebar al mismo nivel que main-container -->
<div class="sidebar" [ngClass]="{ hidden: isHidden }">
<!-- ...contenido del sidebar... -->
<div id="editor" class="editor-size"></div>
<button class="button-apply-json" (click)="validateAndApplyJson()">
Aceptar
</button>
</div>
<!-- Nuevo contenedor para navbar y main -->
<div class="main-container">
<!-- Navbar dentro de main-container -->
<div class="navbar">
<button class="slider-button left" (click)="toggleSidebar()">
<i class="material-icons" [ngClass]="{ inverted: !isHidden }">slideshow</i>
</button>
<div class="theme-selector right">
<ng-select id="themeSelect" [items]="availableThemes" bindLabel="label" [(ngModel)]="selectedTheme"
[searchable]="false" [clearable]="false" (change)="onThemeChange()" class="theme-select-icon-only">
<ng-template ng-label-tmp let-item="item">
<div class="theme-icon-circle" matTooltip="Tema: {{ item.label }}">
<i class="material-icons" [style.color]="item.color">format_paint</i>
</div>
</ng-template>
<ng-template ng-option-tmp let-item="item" let-index="index">
<span class="theme-icon" [style.background-color]="item.color"></span>
{{ item.label }}
</ng-template>
</ng-select>
</div>
</div>
<div class="main" [ngClass]="{'custommsi': isCustommsiTheme}" [style.grid-template-rows]="getGridTemplateRows()">
<div *ngFor="let row of gridData; let rowIndex = index" class="row"
[ngStyle]="{ 'grid-template-columns': getGridTemplateColumns(row.columns) }">
<div *ngFor="let col of row.columns; let colIndex = index" class="column" [ngClass]="{
'expanded': col.isExpanded,
'expanding': col.isExpanding,
'contracting': col.isContracting,
'custommsi': isCustommsiTheme
}" [ngStyle]="{
'grid-row': col.rowSpan ? 'span ' + col.rowSpan : 'auto',
'grid-column': col.colSpan ? 'span ' + col.colSpan : 'auto',
'border': col.isCard ? '0' : null
}" (contextmenu)="onRightClick($event, col)">
<button *ngIf="col != editingCell" class="buttonAddKpi" (click)="editKPI(col)">
<i class="material-icons">build</i>
</button>
<div [ngClass]="{'edit-container': true, 'hidden': col !== editingCell}">
<div class="cell-options-container">
<label>
<input type="checkbox" (click)="toggleMultiSelection(col)" [(ngModel)]="col.MultiSelection">
Activar multiselección
</label>
</div>
<div class="cell-options-container">
<label>
<input type="checkbox" [(ngModel)]="col.showSwitch">
Activar switch
</label>
</div>
<!-- listbox del primer kpi -->
<ng-select appendTo="body" class="kpi-select-designer1" [searchable]="true" [(ngModel)]="col.content"
*ngIf="col === editingCell" [items]="componentOptions" bindLabel="label" bindValue="value"
[multiple]="col.multiSelection" placeholder="Elige uno o más KPIs">
</ng-select>
<!-- listbox del kpi alternativo -->
<ng-select appendTo="body" *ngIf="col.showSwitch" class="kpi-select-designer1" [searchable]="true"
[(ngModel)]="col.alternativeContent" [items]="componentOptions" bindLabel="label" bindValue="value"
[multiple]="col.multiSelection" placeholder="Componente alternativo"></ng-select>
<div class="button-container">
<button class="button-apply" (click)="applyKPI()">
Aplicar
</button>
</div>
</div>
<ng-container *ngIf="!col.isComponent">{{ col.content[0] }}</ng-container>
<ng-container *ngIf="col.isComponent">
<div class="cell-content">
<!-- ng-select for single selection in non-multiselection mode -->
<div class="cell-options-container flex-row"
[ngClass]="{'no-ng-select': !col.multiSelection && col.isCard}">
<div class="cell-menu-container">
<!-- Botón de Opciones Condicionado -->
<button *ngIf="col.showOptionsButton" class="cell-button" (click)="toggleOptionsMenu(col, $event)">
<span class="material-symbols-outlined">
more_vert <!-- Icono de tres puntos verticales de Google Fonts -->
</span>
</button>
<!-- Menú de opciones -->
<div class="options-menu" [ngClass]="{'show': col.showOptionsMenu}"
(click)="$event.stopPropagation()">
<!-- Botón Información (uso) -->
<button *ngIf="col.botones.uso" class="options-menu-item"
(click)="showInfoPanel(col, rowIndex, colIndex); toggleOptionsMenu(col, $event)">
<span class="material-symbols-outlined">info</span>
<span>Información</span>
</button>
<!-- Botón Mostrar Datos (drillDown) -->
<button *ngIf="col.botones.drillDown" class="options-menu-item"
(click)="cellclicktemp(); toggleOptionsMenu(col, $event)">
<span class="material-symbols-outlined">table_view</span>
<span>Mostrar datos</span>
</button>
<!-- Botón Expandir/Restaurar (fullSize) -->
<button *ngIf="col.botones.fullSize" class="options-menu-item"
(click)="toggleCellExpansion(col); toggleOptionsMenu(col, $event)">
<span class="material-symbols-outlined">
{{ col.isExpanded ? 'close_fullscreen' : 'open_in_full' }}
</span>
<span>{{ col.isExpanded ? 'Restaurar' : 'Expandir' }}</span>
</button>
</div>
</div>
<!-- Ng-Select para selección simple -->
<ng-select *ngIf="col.multiSelection === false && !col.isCard" class="kpi-select-disabled"
id="kpi-select-viewer" [(ngModel)]="col.selectedContent" [items]="col.contentOptions"
[disabled]="true" [multiple]="false" [clearable]="false" [searchable]="false"
(change)="onMultiselectionListChange($event, col)">
<ng-template ng-label-tmp let-item="item">
{{ getLabelTitle(item.label) }}
</ng-template>
</ng-select>
<!-- Ng-Select para multiselección -->
<!-- Ng-Select para multiselección con soporte para Switch -->
<ng-select *ngIf="col.multiSelection" class="kpi-select-multi" id="kpi-select-viewer"
[(ngModel)]="col.activeSelectedContent" [items]="col.activeContentOptions" [multiple]="false"
[clearable]="false" [searchable]="false" (change)="onMultiselectionListChange($event, col)">
<ng-template ng-label-tmp let-item="item">
{{ getLabelTitle(item.label) }}
</ng-template>
</ng-select>
<!-- Switch -->
<div *ngIf="col.showSwitch" class="switch">
<div class="left" [class.active]="col.switchActiveSide === 'left'"
(click)="switchComponent(col,'left')">
{{ col.switchLeftText }}
</div>
<div class="right" [class.active]="col.switchActiveSide === 'right'"
(click)="switchComponent(col,'right')">
{{ col.switchRightText }}
</div>
</div>
<!-- Info Panel -->
<div class="info-panel info-panel-{{rowIndex}}-{{colIndex}}" *ngIf="col.showInfoPanel">
<div class="info-icon">
<span class="material-symbols-outlined">
info
</span>
</div>
<div class="info-text">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus fermentum elit sit amet magna
convallis, sed dictum lacus vehicula. Quisque non tellus id erat luctus interdum.</p>
<button (click)="hideInfoPanel()">Cerrar</button>
</div>
</div>
</div>
<div class="component-container">
<ng-container #dynamicComponentContainer>
<ngx-spinner [name]="'spinner-' + rowIndex + '-' + colIndex" bdColor="rgba(51,51,51,0.3)"
size="medium" color="#fff" type="ball-scale-multiple" [fullScreen]="false">
</ngx-spinner>
</ng-container>
</div>
</div>
</ng-container>
</div>
</div>
</div>
<div class="context-menu" *ngIf="contextMenuVisible" [style.left.px]="contextMenuX" [style.top.px]="contextMenuY"
(click)="onContextMenuClick($event)">
<div class="context-menu-item">
<span class="label">ColSpan</span>
<div class="controls">
<button (click)="adjustColSpan(-1)">-</button>
<span>{{ selectedCell?.colSpan || 1 }}</span>
<button (click)="adjustColSpan(1)">+</button>
</div>
</div>
<div class="context-menu-item">
<span class="label">RowSpan</span>
<div class="controls">
<button (click)="adjustRowSpan(-1)">-</button>
<span>{{ selectedCell?.rowSpan || 1 }}</span>
<button (click)="adjustRowSpan(1)">+</button>
</div>
</div>
<div class="context-menu-item">
<span class="label">Ancho</span>
<div class="controls">
<button (click)="adjustWidth(-5)">-</button>
<input type="text" [value]="selectedCell?.width || ''" (change)="changeWidth($event)" />
<button (click)="adjustWidth(5)">+</button>
</div>
</div>
<div class="context-menu-item">
<span class="label">Alto Fila</span>
<div class="controls">
<button (click)="adjustRow(getSelectedRow(), -5)">-</button>
<input type="text" [value]="getSelectedRow()?.height || ''"
(change)="changeRowHeight($event, getSelectedRow())" />
<button (click)="adjustRow(getSelectedRow(), 5)">+</button>
</div>
</div>
<div class="context-menu-item add" (click)="addColumnToRow()">
<span class="label">Añadir Columna</span>
</div>
<div class="context-menu-item add" (click)="addRow()">
<span class="label">Añadir Fila (Al final)</span>
</div>
<div class="context-menu-item delete" (click)="deleteCell()">
<span class="label">Eliminar Celda</span>
</div>
</div>
</div>
</div>
Comentarios Explicativos:
-
Botón de Opciones (more_vert):
- Se añade
*ngIf="col.showOptionsButton" para controlar la visibilidad del botón de opciones basado en la configuración de botones de la columna.
-
Botones del Menú de Opciones:
- Cada botón dentro del menú de opciones ahora tiene una directiva
*ngIf que verifica la propiedad correspondiente en col.botones.
- Información:
<button *ngIf="col.botones.uso" ...>Información</button>
- Mostrar Datos:
<button *ngIf="col.botones.drillDown" ...>Mostrar datos</button>
- Expandir/Restaurar:
<button *ngIf="col.botones.fullSize" ...>Expandir/Restaurar</button>
-
Propiedad descripcion:
- Actualmente no se utiliza para mostrar botones, por lo que se omite en el HTML. En el futuro, si se requiere, se puede añadir de manera similar.
5. Consideraciones Finales
-
Asincronía de las Llamadas al Endpoint:
- Las llamadas al endpoint
getKPIButtons son asincrónicas. Asegúrate de manejar adecuadamente los estados de carga y posibles errores para mejorar la experiencia del usuario.
-
Optimización de Rendimiento:
- Si el grid es muy grande, realizar una llamada al endpoint por cada celda puede impactar el rendimiento. Considera optimizar esto mediante técnicas como caching o agrupando las solicitudes.
-
Actualización de Datos Predefinidos:
- La función
initializeButtonsVisibility es opcional y se puede utilizar para inicializar la visibilidad de los botones para celdas que ya contienen KPIs al cargar el grid por primera vez.
-
Estilos y Design:
- Asegúrate de que los estilos CSS asociados a las clases utilizadas (
cell-button, options-menu-item, etc.) estén correctamente definidos para reflejar los cambios en la interfaz.
-
Pruebas:
- Después de implementar los cambios, realiza pruebas exhaustivas para asegurarte de que los botones se muestran y ocultan correctamente según la configuración obtenida del endpoint.
Con estas modificaciones, los botones dentro de cada celda del grid se mostrarán u ocultarán automáticamente según la configuración proporcionada por el endpoint getKPI. Además, el botón de opciones (more_vert) solo será visible si al menos uno de los botones de acción está habilitado, cumpliendo así con el requerimiento de mantenerlo invisible cuando todos los botones están configurados como false.