Explore / Programming En el contexto de un proyecto Angular, el objetivo es modificar un componente que… Save Share Download ▾ ReportEn el contexto de un proyecto Angular, el objetivo es modificar un componente que incluye un grid designer, de tal manera que los botones de opciones dentro de cada celda se muestren o se oculten según los valores devueltos por el endpoint getKPI. El endpoint proporciona un objeto con propiedades booleanas que determinan la visibilidad de cada botón: drillDown, uso, descripcion y fullSize. Si todos los botones están configurados como false, el botón que despliega el submenú debe permanecer invisible. A continuación, deberás implementar la lógica en el archivo TypeScript y en la plantilla HTML del componente. Necesitarás usar la respuesta del endpoint para condicionar la visibilidad de los botones. Asegúrate de optimizar el código y proporciona una guía clara sobre dónde realizar las modificaciones. Por favor, proporciona el código actual de tu componente, incluyendo tanto el archivo HTML como el archivo TypeScript, y a continuación indícame las secciones específicas que necesitan cambios. También, si es necesario agregar nuevo código, especifica la ubicación exacta donde debe ser insertado. Además, el formato de la respuesta debe incluir: 1. El código antiguo que debe ser modificado. 2. El nuevo código necesario para la funcionalidad deseada. 3. Comentarios explicativos sobre los cambios realizados y su propósito.
Ejemplo del endpoint getKPI 1. botones: {drillDown: true, uso: true, descripcion: true, fullSize: true} 1. descripcion: true 2. drillDown: true 3. fullSize: true 4. uso: true 2. data: {table: [{mes: "2023/01", vehiculos_unicos: 1732, vehiculos_unicos_aa: 0},…]} 3. kpi: 6 4. nombre: "Vehículos Atendidos" 5. propiedades: {} 6. propiedadesEcharts: {seriesCategoria: "mes", seriesDatos: "vehiculos_unicos", seriesColor: "55c7cc", seriesShowLabel: "1",…} 7. representacion: "bar"
deben mostrarse si su endpoint correspondiente es true info = uso table_view = drillDown expand = fullSize
Quiero que cuando recojas los valores del endpoint los añadas a la col actual en forma d eun array de buttons con cada valor correspondiente para que así el html solo tenga que leer ese valor del json.
IMPORTANTE: Dame la forma mas sencilla de hacerlo, no lo enredes mucho
<button *ngIf="!col.isCard" class="cell-button" (click)="toggleOptionsMenu(col, $event)">
more_vert
Show full message · 1,140 lines Assistant2024-10-10 11:20 UTC Copy response
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language es
Conversation date Oct 10, 2024
Added to archive Nov 16, 2026
ID 01m7h41x6f9m7z9rvdkmv4gw44Source & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: db85f6eb175d161a99062a6e167dceb7
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
<!-- 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>
</div>
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;
@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();
});
}
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-i t e m . i d K P I − {item.idKPI} - i t e m . i d K P I − {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,
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%',
}));
}
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 = {
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: [
{
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 {
this.spinner.show();
try {
const spinnerName = spinner-r o w I n d e x − {rowIndex}- r o w I n d e x − {colIndex};
this.spinner.show(spinnerName);
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-r o w I n d e x − {rowIndex}- r o w I n d e x − {colIndex});
this.toastr.error(Error al crear el componente.);
console.error('Error al crear el componente:', error);
}
}
private async loadDynamicComponent(componentName: string): Promise {
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: c o m p o n e n t N a m e ) ; t h r o w n e w E r r o r ( N o s e e n c u e n t r a " r e p r e s e n t a c i o n " e n e l j s o n p a r a : {componentName}
);
throw new Error(
No se encuentra "representacion" en el json para: co m p o n e n tN am e ) ; t h r o w n e w E r r or ( N osee n c u e n t r a " r e p r ese n t a c i o n " e n e l j so n p a r a : {componentName}
);
}
console.log('🔰 ~ loadDynamicComponent ~ representacion:', representacion);
try {
if (kpiNumber === 1001) {
representacion = 'img';
}
if (kpiNumber === 1002) {
representacion = 'cardObj';
}
const module = await import(
../kpi-components/kpi-r e p r e s e n t a c i o n / k p i − {representacion}/kpi- r e p r ese n t a c i o n / k p i − {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: e r r o r ) ; t h i s . t o a s t r . e r r o r ( N o s e p u d o c a r g a r e l c o m p o n e n t e p a r a : {error});
this.toastr.error(
No se pudo cargar el componente para: er r or ) ; t hi s . t o a s t r . er r or ( N ose p u d oc a r g a r e l co m p o n e n t e p a r a : {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, cgemos 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];
code Copy code
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];
code Copy code
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;
}
// 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;
}
// 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);
}
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-r o w I n d e x − {rowIndex}- r o w I n d e x − {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-r o w I n d e x − {rowIndex}- r o w I n d e x − {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;
}
});
});
}
}
Para lograr que los botones de opciones dentro de cada celda del grid designer se muestren u oculten según los valores devueltos por el endpoint getKPI, seguiremos estos pasos:
Modificar el archivo TypeScript para:
Recuperar los valores de visibilidad de los botones desde la respuesta del endpoint getKPI.
Asignar estos valores a un array buttons dentro de cada columna (col).
Actualizar la plantilla HTML para:
Mostrar u ocultar el botón de opciones (more_vert) basado en la existencia de botones en el array buttons.
Renderizar dinámicamente los botones dentro del menú de opciones utilizando *ngFor.
A continuación, se detalla cada paso con el código antiguo, el nuevo código necesario y una explicación de los cambios realizados.
1. Modificaciones en el Archivo TypeScript (grid-designer.component.ts)
1.1 Código Antiguo que Debe Modificarse
Dentro del método createComponent, después de obtener la respuesta del endpoint getKPI, no se manejan los botones de opciones basados en la respuesta botones. Actualmente, el método se ve así:
typescript Copy code
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 {
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;
(componentRef.instance as any).theme = this.selectedTheme.value;
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);
}
}
1.2 Nuevo Código Necesario
a. Actualizar el Método createComponent para Asignar el Array de Botones
Añade lógica para mapear la respuesta botones del endpoint getKPI a un array de botones y asignarlo a la columna actual (col.buttons). Si todos los botones están configurados como false, el array estará vacío.
typescript Copy code
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 {
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;
(componentRef.instance as any).theme = this.selectedTheme.value;
// Asignar el array de botones basado en la respuesta del endpoint
const botones = (componentRef.instance as any).botones; // Asumiendo que el componente dinámico expone 'botones'
col.buttons = this.mapBotonesToArray(botones);
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);
}
}
/**
* Mapea el objeto 'botones' a un array de botones con sus propiedades
* @param botones Objeto con propiedades booleanas: drillDown, uso, descripcion, fullSize
* @returns Array de botones a mostrar
*/
mapBotonesToArray(botones: any): any[] {
const buttons = [];
if (botones.drillDown) {
buttons.push({
name: 'Drill Down',
icon: 'table_view',
action: () => this.onDrillDown()
});
}
if (botones.uso) {
buttons.push({
name: 'Uso',
icon: 'info',
action: () => this.onUso()
});
}
if (botones.descripcion) {
buttons.push({
name: 'Descripción',
icon: 'description',
action: () => this.onDescripcion()
});
}
if (botones.fullSize) {
buttons.push({
name: 'Full Size',
icon: 'fullscreen',
action: () => this.onFullSize()
});
}
return buttons;
}
/* Agrega los métodos para manejar las acciones de los botones */
onDrillDown() {
// Implementa la lógica para Drill Down
this.toastr.info('Acción Drill Down ejecutada.');
}
onUso() {
// Implementa la lógica para Uso
this.toastr.info('Acción Uso ejecutada.');
}
onDescripcion() {
// Implementa la lógica para Descripción
this.toastr.info('Acción Descripción ejecutada.');
}
onFullSize() {
// Implementa la lógica para Full Size
this.toastr.info('Acción Full Size ejecutada.');
}
b. Inicializar el Array buttons en initializeGridData
Para asegurarnos de que cada columna tenga un array buttons inicializado, actualizamos el método initializeGridData:
typescript Copy code
private initializeGridData(data: any[]): any[] {
return data.map((row) => ({
...row,
columns: row.columns.map((col: any) => ({
...col,
// Inicializar el array de botones como vacío
buttons: [],
// ... 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,
activeContentOptions: [],
selectedContentIndex: 0,
showOptionsMenu: true,
})),
height: row.height || '20%',
}));
}
1.3 Comentarios Explicativos sobre los Cambios Realizados
Asignación del Array buttons:
Después de crear dinámicamente el componente KPI (createComponent), se asume que el componente expone una propiedad botones que contiene las propiedades booleanas (drillDown, uso, descripcion, fullSize).
Se utiliza el método mapBotonesToArray para convertir este objeto en un array de botones con sus propiedades (name, icon, action).
Este array se asigna a col.buttons, que será usado en la plantilla HTML para renderizar los botones.
Mapeo de Acciones:
Cada botón tiene una propiedad action que es una función que maneja la lógica correspondiente cuando se hace clic en el botón. Estos métodos (onDrillDown, onUso, onDescripcion, onFullSize) deben implementarse para realizar las acciones deseadas.
Inicialización de buttons:
En initializeGridData, se inicializa el array buttons como vacío para cada columna para evitar errores en la plantilla antes de que se asigne el array real.
2. Actualizaciones en la Plantilla HTML (grid-designer.component.html)
2.1 Código Antiguo que Debe Modificarse
Actualmente, la sección de botones en cada celda está codificada de forma estática. El código existente es el siguiente:
html Copy code
<div class="cell-options-container flex-row"
[ngClass]="{'no-ng-select': !col.multiSelection && col.isCard}">
<button *ngIf="!col.isCard" class="cell-button" (click)="toggleOptionsMenu(col, $event)">
more_vert
</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>
</div>
2.2 Nuevo Código Necesario
a. Actualizar la Visualización de los Botones Basados en col.buttons
Reemplazaremos los botones estáticos con una renderización dinámica utilizando *ngFor en el array col.buttons. Además, ocultaremos el botón de opciones (more_vert) si el array buttons está vacío.
html Copy code
<div class="cell-options-container flex-row"
[ngClass]="{'no-ng-select': !col.multiSelection && col.isCard}">
<!-- Botón de Opciones solo si hay botones para mostrar -->
<button *ngIf="!col.isCard && col.buttons.length > 0" class="cell-button" (click)="toggleOptionsMenu(col, $event)">
more_vert
</button>
<!-- Menú de opciones -->
<div class="options-menu" [ngClass]="{'show': col.showOptionsMenu}"
(click)="$event.stopPropagation()">
<button *ngFor="let button of col.buttons" class="options-menu-item"
(click)="button.action(); toggleOptionsMenu(col, $event)">
<span class="material-symbols-outlined">{{ button.icon }}</span>
<span>{{ button.name }}</span>
</button>
</div>
</div>
2.3 Comentarios Explicativos sobre los Cambios Realizados
Condición para Mostrar el Botón de Opciones (more_vert):
Se agregó una condición *ngIf="!col.isCard && col.buttons.length > 0" para asegurarse de que el botón de opciones solo se muestre si la columna no es una tarjeta (!col.isCard) y si hay al menos un botón en el array buttons.
Renderización Dinámica de los Botones:
Utilizando *ngFor="let button of col.buttons", iteramos sobre cada botón definido en el array buttons de la columna.
Cada botón renderizado muestra su icono y nombre basado en las propiedades icon y name.
La acción asociada al botón se ejecuta al hacer clic mediante (click)="button.action(); toggleOptionsMenu(col, $event)", lo que llama a la función correspondiente y cierra el menú de opciones.
Eliminar los Botones Estáticos:
Se eliminaron los botones estáticos (Información, Mostrar datos, Expandir/Restaurar) para permitir una configuración dinámica basada en la respuesta del endpoint getKPI.
3. Código Completo con las Modificaciones
A continuación, se presenta el código completo con las modificaciones realizadas.
3.1 Archivo TypeScript (grid-designer.component.ts)
3.2 Archivo HTML (grid-designer.component.html)
html Copy code
<div class="cell-options-container flex-row"
[ngClass]="{'no-ng-select': !col.multiSelection && col.isCard}">
<!-- Botón de Opciones solo si hay botones para mostrar -->
<button *ngIf="!col.isCard && col.buttons.length > 0" class="cell-button" (click)="toggleOptionsMenu(col, $event)">
more_vert
</button>
<!-- Menú de opciones -->
<div class="options-menu" [ngClass]="{'show': col.showOptionsMenu}"
(click)="$event.stopPropagation()">
<button *ngFor="let button of col.buttons" class="options-menu-item"
(click)="button.action(); toggleOptionsMenu(col, $event)">
<span class="material-symbols-outlined">{{ button.icon }}</span>
<span>{{ button.name }}</span>
</button>
</div>
</div>
4. Resumen de los Cambios Realizados
TypeScript:
HTML:
Consideraciones Adicionales:
5. Conclusión
Con estas modificaciones, el grid designer ahora muestra u oculta los botones de opciones en cada celda basándose en la configuración proporcionada por el endpoint getKPI. Si todos los botones están deshabilitados (false), el botón de opciones (more_vert) no se mostrará, manteniendo así la interfaz limpia y relevante para el usuario.
Recuerda probar exhaustivamente estas modificaciones para asegurar que todas las acciones de los botones funcionan correctamente y que la lógica de visibilidad se comporta según lo esperado.
Show full message · 1,547 lines Copy first response
Not yet included in a published release.
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();
});
}
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,
// Inicializar el array de botones como vacío
buttons: [],
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,
activeContentOptions: [],
selectedContentIndex: 0,
showOptionsMenu: true,
})),
height: row.height || '20%',
}));
}
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 = {
width: 'auto',
content: '',
colSpan: 1,
rowSpan: 1,
isComponent: false,
multiSelection: false,
switchLeftText: 'Izquierda',
switchRightText: 'Derecha',
switchActiveSide: 'left',
showOptionsMenu: true,
buttons: [], // Inicializar botones como vacío
};
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: [
{
width: '100%',
content: '',
colSpan: 1,
rowSpan: 1,
isComponent: false,
multiSelection: false,
switchLeftText: 'Izquierda',
switchRightText: 'Derecha',
switchActiveSide: 'left',
showOptionsMenu: true,
buttons: [], // Inicializar botones como vacío
},
],
};
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 {
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;
(componentRef.instance as any).theme = this.selectedTheme.value;
// Asignar el array de botones basado en la respuesta del endpoint
const botones = (componentRef.instance as any).botones; // Asegúrate de que el componente dinámico exponga 'botones'
col.buttons = this.mapBotonesToArray(botones);
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.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, tomamos 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;
// 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;
// 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
}
}
// Método para alternar el menú de opciones
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;
}
});
});
}
}
/**
* Mapea el objeto 'botones' a un array de botones con sus propiedades
* @param botones Objeto con propiedades booleanas: drillDown, uso, descripcion, fullSize
* @returns Array de botones a mostrar
*/
mapBotonesToArray(botones: any): any[] {
const buttons = [];
if (botones.drillDown) {
buttons.push({
name: 'Drill Down',
icon: 'table_view',
action: () => this.onDrillDown()
});
}
if (botones.uso) {
buttons.push({
name: 'Uso',
icon: 'info',
action: () => this.onUso()
});
}
if (botones.descripcion) {
buttons.push({
name: 'Descripción',
icon: 'description',
action: () => this.onDescripcion()
});
}
if (botones.fullSize) {
buttons.push({
name: 'Full Size',
icon: 'fullscreen',
action: () => this.onFullSize()
});
}
return buttons;
}
/* Métodos para manejar las acciones de los botones */
onDrillDown() {
// Implementa la lógica para Drill Down
this.toastr.info('Acción Drill Down ejecutada.');
}
onUso() {
// Implementa la lógica para Uso
this.toastr.info('Acción Uso ejecutada.');
}
onDescripcion() {
// Implementa la lógica para Descripción
this.toastr.info('Acción Descripción ejecutada.');
}
onFullSize() {
// Implementa la lógica para Full Size
this.toastr.info('Acción Full Size ejecutada.');
}
}
Seguridad y Rendimiento:
Asegúrate de que el componente dinámico (ComponentType) exponga la propiedad botones que contiene la configuración de los botones.
Verifica que las rutas de importación dinámica sean correctas y que los componentes KPI cargados cumplan con la estructura esperada.