264 lines
8.8 KiB
JavaScript
264 lines
8.8 KiB
JavaScript
|
// frontend/static/js/main.js
|
||
|
|
||
|
// Global state
|
||
|
let currentProfile = null;
|
||
|
|
||
|
// Definir clases comunes para inputs
|
||
|
const STYLES = {
|
||
|
editableInput: "mt-1 block w-full rounded-md border-2 border-gray-300 bg-green-50 px-3 py-2 shadow-sm focus:border-indigo-500 focus:ring-indigo-500",
|
||
|
readonlyInput: "mt-1 block w-full rounded-md border-2 border-gray-200 bg-gray-100 px-3 py-2 shadow-sm",
|
||
|
button: "px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600",
|
||
|
buttonSecondary: "px-4 py-2 bg-gray-200 text-gray-800 rounded-md hover:bg-gray-300"
|
||
|
};
|
||
|
|
||
|
async function initializeApp() {
|
||
|
try {
|
||
|
console.log('Inicializando aplicación...');
|
||
|
|
||
|
// Cargar perfiles
|
||
|
const profiles = await apiRequest('/profiles');
|
||
|
console.log('Profiles loaded:', profiles);
|
||
|
|
||
|
// Obtener último perfil usado
|
||
|
const lastProfileId = localStorage.getItem('lastProfileId') || 'default';
|
||
|
console.log('Last profile ID:', lastProfileId);
|
||
|
|
||
|
// Actualizar selector de perfiles
|
||
|
updateProfileSelector(profiles);
|
||
|
|
||
|
// Seleccionar el último perfil usado
|
||
|
const selectedProfile = profiles.find(p => p.id === lastProfileId) || profiles[0];
|
||
|
if (selectedProfile) {
|
||
|
console.log('Selecting profile:', selectedProfile.id);
|
||
|
await selectProfile(selectedProfile.id);
|
||
|
}
|
||
|
|
||
|
// Cargar grupos de scripts y restaurar la última selección
|
||
|
await restoreScriptGroup();
|
||
|
|
||
|
// Actualizar la interfaz
|
||
|
updateWorkDirDisplay();
|
||
|
|
||
|
} catch (error) {
|
||
|
console.error('Error al inicializar la aplicación:', error);
|
||
|
showError('Error al inicializar la aplicación');
|
||
|
}
|
||
|
}
|
||
|
|
||
|
async function restoreScriptGroup() {
|
||
|
try {
|
||
|
// Primero cargar los grupos disponibles
|
||
|
await loadScriptGroups();
|
||
|
|
||
|
// Luego intentar restaurar el último grupo seleccionado
|
||
|
const lastGroupId = localStorage.getItem('lastGroupId');
|
||
|
if (lastGroupId) {
|
||
|
console.log('Restoring last group:', lastGroupId);
|
||
|
const groupSelect = document.getElementById('groupSelect');
|
||
|
if (groupSelect) {
|
||
|
groupSelect.value = lastGroupId;
|
||
|
if (groupSelect.value) { // Verifica que el valor se haya establecido correctamente
|
||
|
await loadGroupScripts(lastGroupId);
|
||
|
} else {
|
||
|
console.log('Selected group no longer exists:', lastGroupId);
|
||
|
localStorage.removeItem('lastGroupId');
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
} catch (error) {
|
||
|
console.error('Error restoring script group:', error);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// Función para restaurar el último estado
|
||
|
async function restoreLastState() {
|
||
|
const lastProfileId = localStorage.getItem('lastProfileId');
|
||
|
const lastGroupId = localStorage.getItem('lastGroupId');
|
||
|
|
||
|
console.log('Restoring last state:', { lastProfileId, lastGroupId });
|
||
|
|
||
|
if (lastProfileId) {
|
||
|
const profileSelect = document.getElementById('profileSelect');
|
||
|
profileSelect.value = lastProfileId;
|
||
|
await selectProfile(lastProfileId);
|
||
|
}
|
||
|
|
||
|
if (lastGroupId) {
|
||
|
const groupSelect = document.getElementById('groupSelect');
|
||
|
if (groupSelect) {
|
||
|
groupSelect.value = lastGroupId;
|
||
|
await loadGroupScripts(lastGroupId);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// API functions
|
||
|
async function apiRequest(endpoint, options = {}) {
|
||
|
try {
|
||
|
const response = await fetch(`/api${endpoint}`, {
|
||
|
...options,
|
||
|
headers: {
|
||
|
'Content-Type': 'application/json',
|
||
|
...options.headers
|
||
|
}
|
||
|
});
|
||
|
|
||
|
if (!response.ok) {
|
||
|
const error = await response.json();
|
||
|
throw new Error(error.error || 'Error en la solicitud API');
|
||
|
}
|
||
|
|
||
|
return await response.json();
|
||
|
} catch (error) {
|
||
|
console.error('Error API:', error);
|
||
|
showError(error.message);
|
||
|
throw error;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
async function loadProfiles() {
|
||
|
try {
|
||
|
const profiles = await apiRequest('/profiles');
|
||
|
updateProfileSelector(profiles);
|
||
|
|
||
|
// Obtener último perfil usado
|
||
|
const lastProfileId = localStorage.getItem('lastProfileId');
|
||
|
|
||
|
// Seleccionar perfil guardado o el default
|
||
|
const defaultProfile = profiles.find(p => p.id === (lastProfileId || 'default')) || profiles[0];
|
||
|
if (defaultProfile) {
|
||
|
await selectProfile(defaultProfile.id);
|
||
|
}
|
||
|
} catch (error) {
|
||
|
showError('Error al cargar los perfiles');
|
||
|
}
|
||
|
}
|
||
|
|
||
|
async function selectProfile(profileId) {
|
||
|
try {
|
||
|
console.log('Seleccionando perfil:', profileId);
|
||
|
currentProfile = await apiRequest(`/profiles/${profileId}`);
|
||
|
|
||
|
// Guardar en localStorage
|
||
|
localStorage.setItem('lastProfileId', profileId);
|
||
|
console.log('Profile ID saved to storage:', profileId);
|
||
|
|
||
|
// Actualizar explícitamente el valor del combo
|
||
|
const select = document.getElementById('profileSelect');
|
||
|
if (select) {
|
||
|
select.value = profileId;
|
||
|
console.log('Updated profileSelect value to:', profileId);
|
||
|
}
|
||
|
|
||
|
updateWorkDirDisplay();
|
||
|
|
||
|
// Recargar scripts con el último grupo seleccionado
|
||
|
await restoreScriptGroup();
|
||
|
} catch (error) {
|
||
|
console.error('Error al seleccionar perfil:', error);
|
||
|
showError('Error al cargar el perfil');
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// Initialize when page loads
|
||
|
document.addEventListener('DOMContentLoaded', initializeApp);
|
||
|
|
||
|
function updateProfileSelector(profiles) {
|
||
|
const select = document.getElementById('profileSelect');
|
||
|
const lastProfileId = localStorage.getItem('lastProfileId') || 'default';
|
||
|
|
||
|
console.log('Updating profile selector. Last profile ID:', lastProfileId);
|
||
|
|
||
|
// Construir las opciones
|
||
|
select.innerHTML = profiles.map(profile => `
|
||
|
<option value="${profile.id}" ${profile.id === lastProfileId ? 'selected' : ''}>
|
||
|
${profile.name}
|
||
|
</option>
|
||
|
`).join('');
|
||
|
|
||
|
// Asegurar que el valor seleccionado sea correcto
|
||
|
select.value = lastProfileId;
|
||
|
console.log('Set profileSelect value to:', lastProfileId);
|
||
|
}
|
||
|
|
||
|
async function changeProfile() {
|
||
|
const select = document.getElementById('profileSelect');
|
||
|
if (select.value) {
|
||
|
await selectProfile(select.value);
|
||
|
await loadScriptGroups(); // Reload scripts when profile changes
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// Work directory functions
|
||
|
function updateWorkDirDisplay() {
|
||
|
const input = document.getElementById('workDirPath');
|
||
|
if (input && currentProfile) {
|
||
|
input.value = currentProfile.work_dir || '';
|
||
|
}
|
||
|
}
|
||
|
|
||
|
async function selectWorkDir() {
|
||
|
try {
|
||
|
console.log('Requesting directory selection...'); // Debug
|
||
|
const response = await apiRequest('/select-directory');
|
||
|
console.log('Directory selection response:', response); // Debug
|
||
|
|
||
|
if (response.path) {
|
||
|
console.log('Updating profile with new work_dir:', response.path); // Debug
|
||
|
const updateResponse = await apiRequest(`/profiles/${currentProfile.id}`, {
|
||
|
method: 'PUT',
|
||
|
body: JSON.stringify({
|
||
|
...currentProfile,
|
||
|
work_dir: response.path
|
||
|
})
|
||
|
});
|
||
|
console.log('Profile update response:', updateResponse); // Debug
|
||
|
|
||
|
await selectProfile(currentProfile.id);
|
||
|
showSuccess('Directorio de trabajo actualizado correctamente');
|
||
|
}
|
||
|
} catch (error) {
|
||
|
console.error('Error al seleccionar directorio:', error); // Debug
|
||
|
showError('Error al actualizar el directorio de trabajo');
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// Output functions
|
||
|
function showError(message) {
|
||
|
const output = document.getElementById('outputArea');
|
||
|
const timestamp = new Date().toLocaleTimeString();
|
||
|
output.innerHTML += `\n[${timestamp}] ERROR: ${message}`;
|
||
|
output.scrollTop = output.scrollHeight;
|
||
|
}
|
||
|
|
||
|
function showSuccess(message) {
|
||
|
const output = document.getElementById('outputArea');
|
||
|
const timestamp = new Date().toLocaleTimeString();
|
||
|
output.innerHTML += `\n[${timestamp}] SUCCESS: ${message}`;
|
||
|
output.scrollTop = output.scrollHeight;
|
||
|
}
|
||
|
|
||
|
function clearOutput() {
|
||
|
const output = document.getElementById('outputArea');
|
||
|
output.innerHTML = '';
|
||
|
}
|
||
|
|
||
|
// Modal helper functions
|
||
|
function closeModal(button) {
|
||
|
const modal = button.closest('.modal');
|
||
|
if (modal) {
|
||
|
modal.remove();
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// Global error handler
|
||
|
window.addEventListener('unhandledrejection', function(event) {
|
||
|
console.error('Unhandled promise rejection:', event.reason);
|
||
|
showError('An unexpected error occurred');
|
||
|
});
|
||
|
|
||
|
// Export functions for use in other modules
|
||
|
window.showError = showError;
|
||
|
window.showSuccess = showSuccess;
|
||
|
window.closeModal = closeModal;
|
||
|
window.currentProfile = currentProfile;
|