/** * a2host - Reactive State Store (ES Module) * Proporciona un almacén reactivo centralizado ligero para desacoplar componentes y vistas. */ class StateStore { constructor() { this.state = { currentUser: null, activeTab: 'subdomains', subdomains: [], subdomainsLoading: false, subdomainsFilter: { search: '', mode: 'all', // 'all' | 'static' | 'proxy' status: 'all' // 'all' | 'enabled' | 'disabled' }, folders: [], foldersLoading: false, foldersSearch: '', selectedFolderFiles: null, fileManager: { folderName: '', currentPath: '', files: [], loading: false }, codeEditor: { folderName: '', filePath: '', fileName: '', content: '', isDirty: false }, terminalInfo: null, terminalHistory: [], monitorProcesses: [], monitorIntervalId: null, users: [], usersLoading: false, stats: null, docs: [], selectedDoc: null, docsLoading: false, docsSearch: '' }; this.listeners = new Map(); } /** * Obtiene una copia superficial del estado actual o de una propiedad * @param {string} [key] */ getState(key) { if (key) { return this.state[key]; } return { ...this.state }; } /** * Actualiza el estado y notifica a los suscriptores correspondientes * @param {Partial} updates */ setState(updates) { const changedKeys = []; for (const [key, value] of Object.entries(updates)) { if (this.state[key] !== value) { this.state[key] = value; changedKeys.push(key); } } if (changedKeys.length > 0) { this.notify(changedKeys); } } /** * Suscribe una función para reaccionar a cambios en claves específicas o globales * @param {string|string[]} keys - Clave o array de claves a observar ('*' para todas) * @param {Function} callback - Función a ejecutar con el nuevo estado * @returns {Function} Función para cancelar la suscripción */ subscribe(keys, callback) { const keyArray = Array.isArray(keys) ? keys : [keys]; for (const key of keyArray) { if (!this.listeners.has(key)) { this.listeners.set(key, new Set()); } this.listeners.get(key).add(callback); } return () => { for (const key of keyArray) { if (this.listeners.has(key)) { this.listeners.get(key).delete(callback); } } }; } /** * Notifica a los suscriptores afectados * @private * @param {string[]} changedKeys */ notify(changedKeys) { const callbacksToRun = new Set(); for (const key of changedKeys) { const listenersForKey = this.listeners.get(key); if (listenersForKey) { for (const cb of listenersForKey) { callbacksToRun.add(cb); } } } // Suscriptores globales ('*') const globalListeners = this.listeners.get('*'); if (globalListeners) { for (const cb of globalListeners) { callbacksToRun.add(cb); } } for (const cb of callbacksToRun) { try { cb(this.state, changedKeys); } catch (err) { console.error('[StateStore] Error en callback de suscripción:', err); } } } } export const store = new StateStore(); export default store;