256 lines
8.2 KiB
JavaScript
256 lines
8.2 KiB
JavaScript
// frontend/static/js/main.js
|
|
|
|
// Global state
|
|
let currentProfile = null;
|
|
|
|
async function initializeApp() {
|
|
try {
|
|
console.log('Initializing app...');
|
|
|
|
// 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 initializing app:', error);
|
|
showError('Failed to initialize application');
|
|
}
|
|
}
|
|
|
|
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 || 'API request failed');
|
|
}
|
|
|
|
return await response.json();
|
|
} catch (error) {
|
|
console.error('API Error:', 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('Failed to load profiles');
|
|
}
|
|
}
|
|
|
|
async function selectProfile(profileId) {
|
|
try {
|
|
console.log('Selecting profile:', 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 in selectProfile:', error);
|
|
showError('Failed to load profile');
|
|
}
|
|
}
|
|
|
|
// 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('Work directory updated successfully');
|
|
}
|
|
} catch (error) {
|
|
console.error('Error in selectWorkDir:', error); // Debug
|
|
showError('Failed to update work directory');
|
|
}
|
|
}
|
|
|
|
// 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; |