oggui/ogWebconsole/src/app/components/menus/create-menu/create-menu.component.ts

235 lines
8.2 KiB
TypeScript

import { inject } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { Component, Inject, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { HttpClient } from "@angular/common/http";
import { MAT_DIALOG_DATA, MatDialogRef } from "@angular/material/dialog";
import { ToastrService } from "ngx-toastr";
import { DataService } from "../data.service";
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
import { ConfigService } from '@services/config.service';
@Component({
selector: 'app-create-menu',
templateUrl: './create-menu.component.html',
styleUrl: './create-menu.component.css'
})
export class CreateMenuComponent implements OnInit {
public translate = inject(TranslateService);
baseUrl: string;
menuForm: FormGroup<any>;
menuId: string | null = null;
softwareProfiles: any[] = [];
safeUrl: SafeResourceUrl | null = null;
selectedFile: File | null = null;
fileContent: string | null = null;
isEditingHtml: boolean = false;
htmlEditorContent: string = '';
isGlobalView: boolean = false;
constructor(
private fb: FormBuilder,
private http: HttpClient,
public dialogRef: MatDialogRef<CreateMenuComponent>,
private toastService: ToastrService,
private dataService: DataService,
private configService: ConfigService,
private sanitizer: DomSanitizer,
@Inject(MAT_DIALOG_DATA) public data: any
) {
this.baseUrl = this.configService.apiUrl;
this.menuForm = this.fb.group({
name: ['', Validators.required],
publicUrl: ['', Validators.required],
resolution: ['', Validators.required],
isDefault: [false],
comments: [''],
});
}
updateSafeUrl(): void {
const url = `${this.baseUrl}/menu/${this.menuForm.get('publicUrl')?.value}?gui=1`;
if (url && this.menuForm.get('publicUrl')?.value) {
this.safeUrl = this.sanitizer.bypassSecurityTrustResourceUrl(url);
} else {
this.safeUrl = null;
}
}
onFileSelected(event: any): void {
const file = event.target.files[0];
if (file) {
this.selectedFile = file;
const reader = new FileReader();
reader.onload = (e: any) => {
// e.target.result será un string en formato 'data:text/html;base64,.....'
// Nos quedamos solo con la parte Base64 dividiendo por la coma
const base64String = e.target.result.split(',')[1];
this.fileContent = base64String;
};
reader.readAsDataURL(file);
} else {
this.selectedFile = null;
this.fileContent = null;
}
}
editHtml(): void {
if (this.fileContent) {
// Decode Base64 content to text
try {
// Modern approach to decode Base64 ensuring UTF-8
const binaryStr = window.atob(this.fileContent);
const bytes = new Uint8Array(binaryStr.length);
for (let i = 0; i < binaryStr.length; i++) {
bytes[i] = binaryStr.charCodeAt(i);
}
this.htmlEditorContent = new TextDecoder('utf-8').decode(bytes);
} catch (e) {
console.error(this.translate.instant('failedToDecodePreviousFilecontent'), e);
this.htmlEditorContent = '<!-- Error decodificando HTML anterior -->';
}
this.isEditingHtml = true;
} else if (this.menuForm.get('publicUrl')?.value) {
// Fetch the actual raw HTML/Twig template if it exists and no file was manually uploaded yet
const publicUrl = this.menuForm.get('publicUrl')?.value;
this.dataService.getRawMenuTemplate(publicUrl).subscribe({
next: (htmlStr) => {
this.htmlEditorContent = htmlStr;
this.isEditingHtml = true;
},
error: (err) => {
this.toastService.error(this.translate.instant('couldNotDownload'));
console.error(err);
}
});
}
}
applyHtmlChanges(): void {
if (this.htmlEditorContent) {
// Encode the drafted Twig code back into Base64 enforcing UTF-8 compatibility
try {
const bytes = new TextEncoder().encode(this.htmlEditorContent);
const binaryStr = Array.from(bytes).map(byte => String.fromCharCode(byte)).join('');
const base64Content = window.btoa(binaryStr);
// This holds the RAW twig that will be sent via PUT/POST on save
this.fileContent = base64Content;
// Ask the backend to compile a preview using this encoded Twig
this.dataService.previewMenuTemplate(base64Content).subscribe({
next: (renderedHtml) => {
const renderedBytes = new TextEncoder().encode(renderedHtml);
const renderedBinaryStr = Array.from(renderedBytes).map(byte => String.fromCharCode(byte)).join('');
const renderedBase64 = window.btoa(renderedBinaryStr);
this.isEditingHtml = false;
const dataUrl = `data:text/html;base64,${renderedBase64}`;
this.safeUrl = this.sanitizer.bypassSecurityTrustResourceUrl(dataUrl);
this.toastService.success(this.translate.instant('generatedPreviewPressSave'));
},
error: (err) => {
console.error(this.translate.instant('failedToPreviewGeneratedHtml'), err);
const msg = err.error?.message || 'Error compilando la plantilla Twig.';
this.toastService.error(msg);
}
});
} catch (e) {
console.error(this.translate.instant('failedToEncodeUpdatedHtml'), e);
this.toastService.error(this.translate.instant('thereWasAProblemProcessingThe'));
}
}
}
cancelHtmlChanges(): void {
this.isEditingHtml = false;
this.htmlEditorContent = '';
}
toggleGlobalView(): void {
this.isGlobalView = !this.isGlobalView;
}
ngOnInit() {
if (this.data) {
this.load()
}
}
load(): void {
this.dataService.getMenu(this.data).subscribe({
next: (response) => {
this.menuForm = this.fb.group({
name: [response.name, Validators.required],
publicUrl: [response.publicUrl, Validators.required],
resolution: [response.resolution, Validators.required],
comments: [response.comments],
isDefault: [response.isDefault],
});
this.menuId = response['@id'];
this.updateSafeUrl()
},
error: (err) => {
console.error(this.translate.instant('errorFetchingRemoteCalendar'), err);
}
});
}
save(): void {
const payload: any = {
name: this.menuForm.value.name,
publicUrl: this.menuForm.value.publicUrl,
resolution: this.menuForm.value.resolution,
comments: this.menuForm.value.comments,
isDefault: this.menuForm.value.isDefault,
};
// Si el usuario le da a Guardar mientras está editando el HTML (sin haberle dado a Aplicar Cambios),
// guardamos automáticamente lo que haya en el editor de texto.
if (this.isEditingHtml && this.htmlEditorContent) {
try {
const bytes = new TextEncoder().encode(this.htmlEditorContent);
const binaryStr = Array.from(bytes).map(byte => String.fromCharCode(byte)).join('');
this.fileContent = window.btoa(binaryStr);
} catch (e) {
console.error('Failed to encode HTML content before saving', e);
}
}
if (this.fileContent) {
payload.menuHtmlContent = this.fileContent;
}
if (this.menuId) {
this.http.put(`${this.baseUrl}${this.menuId}`, payload).subscribe(
(response) => {
this.toastService.success(this.translate.instant('menuEditedCorrectly'));
this.dialogRef.close();
},
(error) => {
this.toastService.error(error['error']['hydra:description']);
console.error(this.translate.instant('errorWhenEditingImage'), error);
}
);
} else {
this.http.post(`${this.baseUrl}/menus`, payload).subscribe(
(response) => {
this.toastService.success(this.translate.instant('menuAddedSuccessfully'));
this.dialogRef.close();
},
(error) => {
this.toastService.error(error['error']['hydra:description']);
console.error(this.translate.instant('errorAddingMenu'), error);
}
);
}
}
close(): void {
this.dialogRef.close();
}
}