// SPORE UI Components // Primary Node Component class PrimaryNodeComponent extends Component { constructor(container, viewModel, eventBus) { super(container, viewModel, eventBus); } setupEventListeners() { const refreshBtn = this.findElement('.primary-node-refresh'); if (refreshBtn) { this.addEventListener(refreshBtn, 'click', this.handleRandomSelection.bind(this)); } } setupViewModelListeners() { // Listen to primary node changes this.subscribeToProperty('primaryNode', this.render.bind(this)); this.subscribeToProperty('clientInitialized', this.render.bind(this)); this.subscribeToProperty('totalNodes', this.render.bind(this)); this.subscribeToProperty('error', this.render.bind(this)); } render() { const primaryNode = this.viewModel.get('primaryNode'); const clientInitialized = this.viewModel.get('clientInitialized'); const totalNodes = this.viewModel.get('totalNodes'); const error = this.viewModel.get('error'); if (error) { this.setText('#primary-node-ip', '❌ Discovery Failed'); this.setClass('#primary-node-ip', 'error', true); this.setClass('#primary-node-ip', 'discovering', false); this.setClass('#primary-node-ip', 'selecting', false); return; } if (!primaryNode) { this.setText('#primary-node-ip', '🔍 No Nodes Found'); this.setClass('#primary-node-ip', 'error', true); this.setClass('#primary-node-ip', 'discovering', false); this.setClass('#primary-node-ip', 'selecting', false); return; } const status = clientInitialized ? '✅' : '⚠️'; const nodeCount = totalNodes > 1 ? ` (${totalNodes} nodes)` : ''; this.setText('#primary-node-ip', `${status} ${primaryNode}${nodeCount}`); this.setClass('#primary-node-ip', 'error', false); this.setClass('#primary-node-ip', 'discovering', false); this.setClass('#primary-node-ip', 'selecting', false); } async handleRandomSelection() { try { // Show selecting state this.setText('#primary-node-ip', '🎲 Selecting...'); this.setClass('#primary-node-ip', 'selecting', true); this.setClass('#primary-node-ip', 'discovering', false); this.setClass('#primary-node-ip', 'error', false); await this.viewModel.selectRandomPrimaryNode(); // Show success briefly this.setText('#primary-node-ip', '🎯 Selection Complete'); // Update display after delay setTimeout(() => { this.viewModel.updatePrimaryNodeDisplay(); }, 1500); } catch (error) { console.error('Failed to select random primary node:', error); this.setText('#primary-node-ip', '❌ Selection Failed'); this.setClass('#primary-node-ip', 'error', true); this.setClass('#primary-node-ip', 'selecting', false); this.setClass('#primary-node-ip', 'discovering', false); // Revert to normal display after error setTimeout(() => { this.viewModel.updatePrimaryNodeDisplay(); }, 2000); } } } // Cluster Members Component with enhanced state preservation class ClusterMembersComponent extends Component { constructor(container, viewModel, eventBus) { super(container, viewModel, eventBus); console.log('ClusterMembersComponent: Constructor called'); console.log('ClusterMembersComponent: Container:', container); console.log('ClusterMembersComponent: Container ID:', container?.id); console.log('ClusterMembersComponent: Container innerHTML:', container?.innerHTML); // Track if we're in the middle of a render operation this.renderInProgress = false; this.lastRenderData = null; // Ensure initial render happens even if no data setTimeout(() => { if (this.isMounted && !this.renderInProgress) { console.log('ClusterMembersComponent: Performing initial render check'); this.render(); } }, 200); } mount() { console.log('ClusterMembersComponent: Starting mount...'); super.mount(); // Show loading state immediately when mounted console.log('ClusterMembersComponent: Showing initial loading state'); this.showLoadingState(); // Set up loading timeout safeguard this.setupLoadingTimeout(); console.log('ClusterMembersComponent: Mounted successfully'); } // Setup loading timeout safeguard to prevent getting stuck in loading state setupLoadingTimeout() { this.loadingTimeout = setTimeout(() => { const isLoading = this.viewModel.get('isLoading'); if (isLoading) { console.warn('ClusterMembersComponent: Loading timeout reached, forcing render check'); this.forceRenderCheck(); } }, 10000); // 10 second timeout } // Force a render check when loading gets stuck forceRenderCheck() { console.log('ClusterMembersComponent: Force render check called'); const members = this.viewModel.get('members'); const error = this.viewModel.get('error'); const isLoading = this.viewModel.get('isLoading'); console.log('ClusterMembersComponent: Force render check state:', { members, error, isLoading }); if (error) { this.showErrorState(error); } else if (members && members.length > 0) { this.renderMembers(members); } else if (!isLoading) { this.showEmptyState(); } } setupEventListeners() { console.log('ClusterMembersComponent: Setting up event listeners...'); // Note: Refresh button is now handled by ClusterViewComponent // since it's in the cluster header, not in the members container } setupViewModelListeners() { console.log('ClusterMembersComponent: Setting up view model listeners...'); // Listen to cluster members changes with change detection this.subscribeToProperty('members', this.handleMembersUpdate.bind(this)); this.subscribeToProperty('isLoading', this.handleLoadingUpdate.bind(this)); this.subscribeToProperty('error', this.handleErrorUpdate.bind(this)); console.log('ClusterMembersComponent: View model listeners set up'); } // Handle members update with state preservation handleMembersUpdate(newMembers, previousMembers) { console.log('ClusterMembersComponent: Members updated:', { newMembers, previousMembers }); // Prevent multiple simultaneous renders if (this.renderInProgress) { console.log('ClusterMembersComponent: Render already in progress, skipping update'); return; } // Check if we're currently loading - if so, let the loading handler deal with it const isLoading = this.viewModel.get('isLoading'); if (isLoading) { console.log('ClusterMembersComponent: Currently loading, skipping members update (will be handled by loading completion)'); return; } // On first load (no previous members), always render if (!previousMembers || !Array.isArray(previousMembers) || previousMembers.length === 0) { console.log('ClusterMembersComponent: First load or no previous members, performing full render'); this.render(); return; } if (this.shouldPreserveState(newMembers, previousMembers)) { // Perform partial update to preserve UI state console.log('ClusterMembersComponent: Preserving state, performing partial update'); this.updateMembersPartially(newMembers, previousMembers); } else { // Full re-render if structure changed significantly console.log('ClusterMembersComponent: Structure changed, performing full re-render'); this.render(); } } // Handle loading state update handleLoadingUpdate(isLoading) { console.log('ClusterMembersComponent: Loading state changed:', isLoading); if (isLoading) { console.log('ClusterMembersComponent: Showing loading state'); this.showLoadingState(); // Set up a loading completion check this.checkLoadingCompletion(); } else { console.log('ClusterMembersComponent: Loading completed, checking if we need to render'); // When loading completes, check if we have data to render this.handleLoadingCompletion(); } } // Check if loading has completed and handle accordingly handleLoadingCompletion() { const members = this.viewModel.get('members'); const error = this.viewModel.get('error'); const isLoading = this.viewModel.get('isLoading'); console.log('ClusterMembersComponent: Handling loading completion:', { members, error, isLoading }); if (error) { console.log('ClusterMembersComponent: Loading completed with error, showing error state'); this.showErrorState(error); } else if (members && members.length > 0) { console.log('ClusterMembersComponent: Loading completed with data, rendering members'); this.renderMembers(members); } else if (!isLoading) { console.log('ClusterMembersComponent: Loading completed but no data, showing empty state'); this.showEmptyState(); } } // Set up a check to ensure loading completion is handled checkLoadingCompletion() { // Clear any existing completion check if (this.loadingCompletionCheck) { clearTimeout(this.loadingCompletionCheck); } // Set up a completion check that runs after a short delay this.loadingCompletionCheck = setTimeout(() => { const isLoading = this.viewModel.get('isLoading'); if (!isLoading) { console.log('ClusterMembersComponent: Loading completion check triggered'); this.handleLoadingCompletion(); } }, 1000); // Check after 1 second } // Handle error state update handleErrorUpdate(error) { if (error) { this.showErrorState(error); } } // Check if we should preserve UI state during update shouldPreserveState(newMembers, previousMembers) { if (!previousMembers || !Array.isArray(previousMembers)) return false; if (!Array.isArray(newMembers)) return false; // If member count changed, we need to re-render if (newMembers.length !== previousMembers.length) return false; // Check if member IPs are the same (same nodes) const newIps = new Set(newMembers.map(m => m.ip)); const prevIps = new Set(previousMembers.map(m => m.ip)); // If IPs are the same, we can preserve state return newIps.size === prevIps.size && [...newIps].every(ip => prevIps.has(ip)); } // Check if we should skip rendering during view switches shouldSkipRender() { // Skip rendering if we're in the middle of a view switch const isViewSwitching = document.querySelectorAll('.view-content.active').length === 0; if (isViewSwitching) { console.log('ClusterMembersComponent: View switching in progress, skipping render'); return true; } // Skip rendering if the component is not visible const isVisible = this.container.style.display !== 'none' && this.container.style.opacity !== '0' && this.container.classList.contains('active'); if (!isVisible) { console.log('ClusterMembersComponent: Component not visible, skipping render'); return true; } return false; } // Update members partially to preserve UI state updateMembersPartially(newMembers, previousMembers) { console.log('ClusterMembersComponent: Performing partial update to preserve UI state'); // Update only the data that changed, preserving expanded states and active tabs newMembers.forEach((newMember, index) => { const prevMember = previousMembers[index]; if (prevMember && this.hasMemberChanged(newMember, prevMember)) { this.updateMemberCard(newMember, index); } }); } // Check if a specific member has changed hasMemberChanged(newMember, prevMember) { return newMember.status !== prevMember.status || newMember.latency !== prevMember.latency || newMember.hostname !== prevMember.hostname; } // Update a specific member card without re-rendering the entire component updateMemberCard(member, index) { const card = this.findElement(`[data-member-ip="${member.ip}"]`); if (!card) return; // Update status const statusElement = card.querySelector('.member-status'); if (statusElement) { const statusClass = member.status === 'active' ? 'status-online' : 'status-offline'; const statusText = member.status === 'active' ? 'Online' : 'Offline'; const statusIcon = member.status === 'active' ? '🟢' : '🔴'; statusElement.className = `member-status ${statusClass}`; statusElement.innerHTML = `${statusIcon} ${statusText}`; } // Update latency const latencyElement = card.querySelector('.latency-value'); if (latencyElement) { latencyElement.textContent = member.latency ? member.latency + 'ms' : 'N/A'; } // Update hostname if changed const hostnameElement = card.querySelector('.member-name'); if (hostnameElement && member.hostname !== hostnameElement.textContent) { hostnameElement.textContent = member.hostname || 'Unknown Device'; } } render() { if (this.renderInProgress) { console.log('ClusterMembersComponent: Render already in progress, skipping'); return; } // Check if we should skip rendering during view switches if (this.shouldSkipRender()) { return; } this.renderInProgress = true; try { console.log('ClusterMembersComponent: render() called'); console.log('ClusterMembersComponent: Container element:', this.container); console.log('ClusterMembersComponent: Is mounted:', this.isMounted); const members = this.viewModel.get('members'); const isLoading = this.viewModel.get('isLoading'); const error = this.viewModel.get('error'); console.log('ClusterMembersComponent: render data:', { members, isLoading, error }); if (isLoading) { console.log('ClusterMembersComponent: Showing loading state'); this.showLoadingState(); return; } if (error) { console.log('ClusterMembersComponent: Showing error state'); this.showErrorState(error); return; } if (!members || members.length === 0) { console.log('ClusterMembersComponent: Showing empty state'); this.showEmptyState(); return; } console.log('ClusterMembersComponent: Rendering members:', members); this.renderMembers(members); } finally { this.renderInProgress = false; } } // Show loading state showLoadingState() { console.log('ClusterMembersComponent: showLoadingState() called'); this.setHTML('', `
Loading cluster members...
`); } // Show error state showErrorState(error) { console.log('ClusterMembersComponent: showErrorState() called with error:', error); this.setHTML('', `
Error loading cluster members:
${error}
`); } // Show empty state showEmptyState() { console.log('ClusterMembersComponent: showEmptyState() called'); this.setHTML('', `
🌐
No cluster members found
The cluster might be empty or not yet discovered
`); } renderMembers(members) { console.log('ClusterMembersComponent: renderMembers() called with', members.length, 'members'); const membersHTML = members.map(member => { const statusClass = member.status === 'active' ? 'status-online' : 'status-offline'; const statusText = member.status === 'active' ? 'Online' : 'Offline'; const statusIcon = member.status === 'active' ? '🟢' : '🔴'; console.log('ClusterMembersComponent: Rendering member:', member); return `
${member.hostname || 'Unknown Device'}
${member.ip || 'No IP'}
${statusIcon} ${statusText}
Latency: ${member.latency ? member.latency + 'ms' : 'N/A'}
Loading detailed information...
`; }).join(''); console.log('ClusterMembersComponent: Setting HTML, length:', membersHTML.length); this.setHTML('', membersHTML); console.log('ClusterMembersComponent: HTML set, setting up member cards...'); this.setupMemberCards(members); } setupMemberCards(members) { setTimeout(() => { this.findAllElements('.member-card').forEach((card, index) => { const expandIcon = card.querySelector('.expand-icon'); const memberDetails = card.querySelector('.member-details'); const memberIp = card.dataset.memberIp; // Ensure all cards start collapsed by default card.classList.remove('expanded'); if (expandIcon) { expandIcon.classList.remove('expanded'); } // Clear any previous content memberDetails.innerHTML = '
Loading detailed information...
'; // Make the entire card clickable this.addEventListener(card, 'click', async (e) => { if (e.target === expandIcon) return; const isExpanding = !card.classList.contains('expanded'); if (isExpanding) { await this.expandCard(card, memberIp, memberDetails); } else { this.collapseCard(card, expandIcon); } }); // Keep the expand icon click handler for visual feedback if (expandIcon) { this.addEventListener(expandIcon, 'click', async (e) => { e.stopPropagation(); const isExpanding = !card.classList.contains('expanded'); if (isExpanding) { await this.expandCard(card, memberIp, memberDetails); } else { this.collapseCard(card, expandIcon); } }); } }); }, 100); } async expandCard(card, memberIp, memberDetails) { try { // Create node details view model and component const nodeDetailsVM = new NodeDetailsViewModel(); const nodeDetailsComponent = new NodeDetailsComponent(memberDetails, nodeDetailsVM, this.eventBus); // Load node details await nodeDetailsVM.loadNodeDetails(memberIp); // Mount the component nodeDetailsComponent.mount(); // Update UI card.classList.add('expanded'); const expandIcon = card.querySelector('.expand-icon'); if (expandIcon) { expandIcon.classList.add('expanded'); } } catch (error) { console.error('Failed to expand card:', error); memberDetails.innerHTML = `
Error loading node details:
${error.message}
`; } } collapseCard(card, expandIcon) { card.classList.remove('expanded'); if (expandIcon) { expandIcon.classList.remove('expanded'); } } setupTabs(container) { const tabButtons = container.querySelectorAll('.tab-button'); const tabContents = container.querySelectorAll('.tab-content'); tabButtons.forEach(button => { this.addEventListener(button, 'click', (e) => { e.stopPropagation(); const targetTab = button.dataset.tab; // Remove active class from all buttons and contents tabButtons.forEach(btn => btn.classList.remove('active')); tabContents.forEach(content => content.classList.remove('active')); // Add active class to clicked button and corresponding content button.classList.add('active'); const targetContent = container.querySelector(`#${targetTab}-tab`); if (targetContent) { targetContent.classList.add('active'); } // Store active tab state const memberCard = container.closest('.member-card'); if (memberCard) { const memberIp = memberCard.dataset.memberIp; this.viewModel.storeActiveTab(memberIp, targetTab); } }); }); // Also prevent event propagation on tab content areas tabContents.forEach(content => { this.addEventListener(content, 'click', (e) => { e.stopPropagation(); }); }); } // Restore active tab state restoreActiveTab(container, activeTab) { const tabButtons = container.querySelectorAll('.tab-button'); const tabContents = container.querySelectorAll('.tab-content'); // Remove active class from all buttons and contents tabButtons.forEach(btn => btn.classList.remove('active')); tabContents.forEach(content => content.classList.remove('active')); // Add active class to the restored tab const activeButton = container.querySelector(`[data-tab="${activeTab}"]`); const activeContent = container.querySelector(`#${activeTab}-tab`); if (activeButton) activeButton.classList.add('active'); if (activeContent) activeContent.classList.add('active'); } // Note: handleRefresh method has been moved to ClusterViewComponent // since the refresh button is in the cluster header, not in the members container // Debug method to check component state debugState() { const members = this.viewModel.get('members'); const isLoading = this.viewModel.get('isLoading'); const error = this.viewModel.get('error'); const expandedCards = this.viewModel.get('expandedCards'); const activeTabs = this.viewModel.get('activeTabs'); console.log('ClusterMembersComponent: Debug State:', { isMounted: this.isMounted, container: this.container, members: members, membersCount: members?.length || 0, isLoading: isLoading, error: error, expandedCardsCount: expandedCards?.size || 0, activeTabsCount: activeTabs?.size || 0, loadingTimeout: this.loadingTimeout }); return { members, isLoading, error, expandedCards, activeTabs }; } // Manual refresh method that bypasses potential state conflicts async manualRefresh() { console.log('ClusterMembersComponent: Manual refresh called'); try { // Clear any existing loading state this.viewModel.set('isLoading', false); this.viewModel.set('error', null); // Force a fresh data load await this.viewModel.updateClusterMembers(); console.log('ClusterMembersComponent: Manual refresh completed'); } catch (error) { console.error('ClusterMembersComponent: Manual refresh failed:', error); this.showErrorState(error.message); } } unmount() { if (!this.isMounted) return; this.isMounted = false; // Clear any pending timeouts if (this.loadingTimeout) { clearTimeout(this.loadingTimeout); this.loadingTimeout = null; } if (this.loadingCompletionCheck) { clearTimeout(this.loadingCompletionCheck); this.loadingCompletionCheck = null; } // Clear any pending render operations this.renderInProgress = false; this.cleanupEventListeners(); this.cleanupViewModelListeners(); console.log(`${this.constructor.name} unmounted`); } // Override pause method to handle timeouts and operations onPause() { console.log('ClusterMembersComponent: Pausing...'); // Clear any pending timeouts if (this.loadingTimeout) { clearTimeout(this.loadingTimeout); this.loadingTimeout = null; } if (this.loadingCompletionCheck) { clearTimeout(this.loadingCompletionCheck); this.loadingCompletionCheck = null; } // Mark as paused to prevent new operations this.isPaused = true; } // Override resume method to restore functionality onResume() { console.log('ClusterMembersComponent: Resuming...'); this.isPaused = false; // Re-setup loading timeout if needed if (!this.loadingTimeout) { this.setupLoadingTimeout(); } // Check if we need to handle any pending operations this.checkPendingOperations(); } // Check for any operations that need to be handled after resume checkPendingOperations() { const isLoading = this.viewModel.get('isLoading'); const members = this.viewModel.get('members'); // If we were loading and it completed while paused, handle the completion if (!isLoading && members && members.length > 0) { console.log('ClusterMembersComponent: Handling pending loading completion after resume'); this.handleLoadingCompletion(); } } // Override to determine if re-render is needed on resume shouldRenderOnResume() { // Don't re-render on resume - maintain current state return false; } } // Node Details Component with enhanced state preservation class NodeDetailsComponent extends Component { constructor(container, viewModel, eventBus) { super(container, viewModel, eventBus); } setupViewModelListeners() { this.subscribeToProperty('nodeStatus', this.handleNodeStatusUpdate.bind(this)); this.subscribeToProperty('tasks', this.handleTasksUpdate.bind(this)); this.subscribeToProperty('isLoading', this.handleLoadingUpdate.bind(this)); this.subscribeToProperty('error', this.handleErrorUpdate.bind(this)); this.subscribeToProperty('activeTab', this.handleActiveTabUpdate.bind(this)); } // Handle node status update with state preservation handleNodeStatusUpdate(newStatus, previousStatus) { if (newStatus && !this.viewModel.get('isLoading')) { this.renderNodeDetails(newStatus, this.viewModel.get('tasks')); } } // Handle tasks update with state preservation handleTasksUpdate(newTasks, previousTasks) { const nodeStatus = this.viewModel.get('nodeStatus'); if (nodeStatus && !this.viewModel.get('isLoading')) { this.renderNodeDetails(nodeStatus, newTasks); } } // Handle loading state update handleLoadingUpdate(isLoading) { if (isLoading) { this.setHTML('', '
Loading detailed information...
'); } } // Handle error state update handleErrorUpdate(error) { if (error) { this.setHTML('', `
Error loading node details:
${error}
`); } } // Handle active tab update handleActiveTabUpdate(newTab, previousTab) { // Update tab UI without full re-render this.updateActiveTab(newTab, previousTab); } render() { const nodeStatus = this.viewModel.get('nodeStatus'); const tasks = this.viewModel.get('tasks'); const isLoading = this.viewModel.get('isLoading'); const error = this.viewModel.get('error'); if (isLoading) { this.setHTML('', '
Loading detailed information...
'); return; } if (error) { this.setHTML('', `
Error loading node details:
${error}
`); return; } if (!nodeStatus) { this.setHTML('', '
No node status available
'); return; } this.renderNodeDetails(nodeStatus, tasks); } renderNodeDetails(nodeStatus, tasks) { // Always start with 'status' tab, don't restore previous state const activeTab = 'status'; console.log('NodeDetailsComponent: Rendering with activeTab:', activeTab); const html = `
Free Heap: ${Math.round(nodeStatus.freeHeap / 1024)}KB
Chip ID: ${nodeStatus.chipId}
SDK Version: ${nodeStatus.sdkVersion}
CPU Frequency: ${nodeStatus.cpuFreqMHz}MHz
Flash Size: ${Math.round(nodeStatus.flashChipSize / 1024)}KB

Available API Endpoints:

${nodeStatus.api ? nodeStatus.api.map(endpoint => `
${endpoint.method === 1 ? 'GET' : 'POST'} ${endpoint.uri}
` ).join('') : '
No API endpoints available
'}
${this.renderTasksTab(tasks)}
${this.renderFirmwareTab()}
`; this.setHTML('', html); this.setupTabs(); this.setupFirmwareUpload(); } renderTasksTab(tasks) { if (tasks && tasks.length > 0) { const tasksHTML = tasks.map(task => `
${task.name || 'Unknown Task'} ${task.running ? '🟢 Running' : '🔴 Stopped'}
Interval: ${task.interval}ms ${task.enabled ? '🟢 Enabled' : '🔴 Disabled'}
`).join(''); return `

Active Tasks

${tasksHTML} `; } else { return `
📋 No active tasks found
This node has no running tasks
`; } } renderFirmwareTab() { return `

Firmware Update

Select a .bin or .hex file to upload
`; } setupTabs() { console.log('NodeDetailsComponent: Setting up tabs'); const tabButtons = this.findAllElements('.tab-button'); const tabContents = this.findAllElements('.tab-content'); tabButtons.forEach(button => { this.addEventListener(button, 'click', (e) => { e.stopPropagation(); const targetTab = button.dataset.tab; console.log('NodeDetailsComponent: Tab clicked:', targetTab); // Update tab UI locally, don't store in view model this.updateActiveTab(targetTab); }); }); // Also prevent event propagation on tab content areas tabContents.forEach(content => { this.addEventListener(content, 'click', (e) => { e.stopPropagation(); }); }); } // Update active tab without full re-render updateActiveTab(newTab, previousTab = null) { const tabButtons = this.findAllElements('.tab-button'); const tabContents = this.findAllElements('.tab-content'); // Remove active class from all buttons and contents tabButtons.forEach(btn => btn.classList.remove('active')); tabContents.forEach(content => content.classList.remove('active')); // Add active class to new active tab const activeButton = this.findElement(`[data-tab="${newTab}"]`); const activeContent = this.findElement(`#${newTab}-tab`); if (activeButton) activeButton.classList.add('active'); if (activeContent) activeContent.classList.add('active'); console.log(`NodeDetailsComponent: Active tab updated to '${newTab}'`); } setupFirmwareUpload() { const uploadBtn = this.findElement('.upload-btn[data-action="select-file"]'); if (uploadBtn) { this.addEventListener(uploadBtn, 'click', (e) => { e.stopPropagation(); const fileInput = this.findElement('#firmware-file'); if (fileInput) { fileInput.click(); } }); // Set up file input change handler const fileInput = this.findElement('#firmware-file'); if (fileInput) { this.addEventListener(fileInput, 'change', async (e) => { e.stopPropagation(); const file = e.target.files[0]; if (file) { await this.uploadFirmware(file); } }); } } } async uploadFirmware(file) { const uploadStatus = this.findElement('#upload-status'); const uploadBtn = this.findElement('.upload-btn'); const originalText = uploadBtn.textContent; try { // Show upload status uploadStatus.style.display = 'block'; uploadStatus.innerHTML = `
📤 Uploading ${file.name}...
Size: ${(file.size / 1024).toFixed(1)}KB
`; // Disable upload button uploadBtn.disabled = true; uploadBtn.textContent = '⏳ Uploading...'; // Get the member IP from the card const memberCard = this.container.closest('.member-card'); const memberIp = memberCard.dataset.memberIp; if (!memberIp) { throw new Error('Could not determine target node IP address'); } // Upload firmware const result = await this.viewModel.uploadFirmware(file, memberIp); // Show success uploadStatus.innerHTML = `
✅ Firmware uploaded successfully!
Node: ${memberIp}
Size: ${(file.size / 1024).toFixed(1)}KB
`; console.log('Firmware upload successful:', result); } catch (error) { console.error('Firmware upload failed:', error); // Show error uploadStatus.innerHTML = `
❌ Upload failed: ${error.message}
`; } finally { // Re-enable upload button uploadBtn.disabled = false; uploadBtn.textContent = originalText; // Clear file input const fileInput = this.findElement('#firmware-file'); if (fileInput) { fileInput.value = ''; } } } } // Firmware Component class FirmwareComponent extends Component { constructor(container, viewModel, eventBus) { super(container, viewModel, eventBus); } setupEventListeners() { // Setup global firmware file input const globalFirmwareFile = this.findElement('#global-firmware-file'); if (globalFirmwareFile) { this.addEventListener(globalFirmwareFile, 'change', this.handleFileSelect.bind(this)); } // Setup target selection const targetRadios = this.findAllElements('input[name="target-type"]'); targetRadios.forEach(radio => { this.addEventListener(radio, 'change', this.handleTargetChange.bind(this)); }); // Setup specific node select change handler const specificNodeSelect = this.findElement('#specific-node-select'); if (specificNodeSelect) { this.addEventListener(specificNodeSelect, 'change', this.handleNodeSelect.bind(this)); } // Setup deploy button const deployBtn = this.findElement('#deploy-btn'); if (deployBtn) { this.addEventListener(deployBtn, 'click', this.handleDeploy.bind(this)); } } setupViewModelListeners() { this.subscribeToProperty('selectedFile', () => { this.updateFileInfo(); this.updateDeployButton(); }); this.subscribeToProperty('targetType', () => { this.updateTargetVisibility(); this.updateDeployButton(); }); this.subscribeToProperty('specificNode', this.updateDeployButton.bind(this)); this.subscribeToProperty('availableNodes', () => { this.populateNodeSelect(); this.updateDeployButton(); }); this.subscribeToProperty('uploadProgress', this.updateUploadProgress.bind(this)); this.subscribeToProperty('uploadResults', this.updateUploadResults.bind(this)); this.subscribeToProperty('isUploading', this.updateUploadState.bind(this)); } render() { // Initial render is handled by the HTML template this.updateDeployButton(); } handleFileSelect(event) { const file = event.target.files[0]; this.viewModel.setSelectedFile(file); } handleTargetChange(event) { const targetType = event.target.value; this.viewModel.setTargetType(targetType); } handleNodeSelect(event) { const nodeIp = event.target.value; this.viewModel.setSpecificNode(nodeIp); } async handleDeploy() { const file = this.viewModel.get('selectedFile'); const targetType = this.viewModel.get('targetType'); const specificNode = this.viewModel.get('specificNode'); if (!file) { alert('Please select a firmware file first.'); return; } if (targetType === 'specific' && !specificNode) { alert('Please select a specific node to update.'); return; } try { this.viewModel.startUpload(); if (targetType === 'all') { await this.uploadToAllNodes(file); } else { await this.uploadToSpecificNode(file, specificNode); } // Reset interface after successful upload this.viewModel.resetUploadState(); } catch (error) { console.error('Firmware deployment failed:', error); alert(`Deployment failed: ${error.message}`); } finally { this.viewModel.completeUpload(); } } async uploadToAllNodes(file) { try { // Get current cluster members const response = await window.apiClient.getClusterMembers(); const nodes = response.members || []; if (nodes.length === 0) { alert('No nodes available for firmware update.'); return; } const confirmed = confirm(`Upload firmware to all ${nodes.length} nodes? This will update: ${nodes.map(n => n.hostname || n.ip).join(', ')}`); if (!confirmed) return; // Show upload progress area this.showUploadProgress(file, nodes); // Start batch upload const results = await this.performBatchUpload(file, nodes); // Display results this.displayUploadResults(results); } catch (error) { console.error('Failed to upload firmware to all nodes:', error); throw error; } } async uploadToSpecificNode(file, nodeIp) { try { const confirmed = confirm(`Upload firmware to node ${nodeIp}?`); if (!confirmed) return; // Show upload progress area this.showUploadProgress(file, [{ ip: nodeIp, hostname: nodeIp }]); // Perform single node upload const result = await this.performSingleUpload(file, nodeIp); // Display results this.displayUploadResults([result]); } catch (error) { console.error(`Failed to upload firmware to node ${nodeIp}:`, error); throw error; } } async performBatchUpload(file, nodes) { const results = []; const totalNodes = nodes.length; let successfulUploads = 0; for (let i = 0; i < nodes.length; i++) { const node = nodes[i]; const nodeIp = node.ip; try { // Update progress this.updateNodeProgress(i + 1, totalNodes, nodeIp, 'Uploading...'); // Upload to this node const result = await this.performSingleUpload(file, nodeIp); results.push(result); successfulUploads++; // Update progress this.updateNodeProgress(i + 1, totalNodes, nodeIp, 'Completed'); this.updateOverallProgress(successfulUploads, totalNodes); } catch (error) { console.error(`Failed to upload to node ${nodeIp}:`, error); const errorResult = { nodeIp: nodeIp, hostname: node.hostname || nodeIp, success: false, error: error.message, timestamp: new Date().toISOString() }; results.push(errorResult); // Update progress this.updateNodeProgress(i + 1, totalNodes, nodeIp, 'Failed'); this.updateOverallProgress(successfulUploads, totalNodes); } // Small delay between uploads if (i < nodes.length - 1) { await new Promise(resolve => setTimeout(resolve, 1000)); } } return results; } async performSingleUpload(file, nodeIp) { try { const result = await window.apiClient.uploadFirmware(file, nodeIp); return { nodeIp: nodeIp, hostname: nodeIp, success: true, result: result, timestamp: new Date().toISOString() }; } catch (error) { throw new Error(`Upload to ${nodeIp} failed: ${error.message}`); } } showUploadProgress(file, nodes) { const container = this.findElement('#firmware-nodes-list'); const progressHTML = `

📤 Firmware Upload Progress

File: ${file.name} Size: ${(file.size / 1024).toFixed(1)}KB Targets: ${nodes.length} node(s)
0/0 Successful (0%)
Status: Preparing upload...
${nodes.map(node => `
${node.hostname || node.ip} ${node.ip}
Pending...
`).join('')}
`; container.innerHTML = progressHTML; } updateNodeProgress(current, total, nodeIp, status) { const progressItem = this.findElement(`[data-node-ip="${nodeIp}"]`); if (progressItem) { const statusElement = progressItem.querySelector('.progress-status'); const timeElement = progressItem.querySelector('.progress-time'); if (statusElement) { statusElement.textContent = status; // Add status-specific styling statusElement.className = 'progress-status'; if (status === 'Completed') { statusElement.classList.add('success'); if (timeElement) { timeElement.textContent = new Date().toLocaleTimeString(); } } else if (status === 'Failed') { statusElement.classList.add('error'); if (timeElement) { timeElement.textContent = new Date().toLocaleTimeString(); } } else if (status === 'Uploading...') { statusElement.classList.add('uploading'); if (timeElement) { timeElement.textContent = 'Started: ' + new Date().toLocaleTimeString(); } } } } } updateOverallProgress(successfulUploads, totalNodes) { const progressBar = this.findElement('#overall-progress-bar'); const progressText = this.findElement('.progress-text'); if (progressBar && progressText) { const successPercentage = Math.round((successfulUploads / totalNodes) * 100); progressBar.style.width = `${successPercentage}%`; progressText.textContent = `${successfulUploads}/${totalNodes} Successful (${successPercentage}%)`; // Update progress bar color based on completion if (successPercentage === 100) { progressBar.style.backgroundColor = '#4ade80'; } else if (successPercentage > 50) { progressBar.style.backgroundColor = '#60a5fa'; } else { progressBar.style.backgroundColor = '#fbbf24'; } } } displayUploadResults(results) { const progressHeader = this.findElement('.progress-header h3'); const progressSummary = this.findElement('#progress-summary'); if (progressHeader && progressSummary) { const successCount = results.filter(r => r.success).length; const totalCount = results.length; const successRate = Math.round((successCount / totalCount) * 100); if (successCount === totalCount) { progressHeader.textContent = `📤 Firmware Upload Complete (${successCount}/${totalCount} Successful)`; progressSummary.innerHTML = `✅ All uploads completed successfully at ${new Date().toLocaleTimeString()}`; } else { progressHeader.textContent = `📤 Firmware Upload Results (${successCount}/${totalCount} Successful)`; progressSummary.innerHTML = `⚠️ Upload completed with ${totalCount - successCount} failure(s) at ${new Date().toLocaleTimeString()}`; } } } updateFileInfo() { const file = this.viewModel.get('selectedFile'); const fileInfo = this.findElement('#file-info'); const deployBtn = this.findElement('#deploy-btn'); if (file) { fileInfo.textContent = `${file.name} (${(file.size / 1024).toFixed(1)}KB)`; fileInfo.classList.add('has-file'); } else { fileInfo.textContent = 'No file selected'; fileInfo.classList.remove('has-file'); } this.updateDeployButton(); } updateTargetVisibility() { const targetType = this.viewModel.get('targetType'); const specificNodeSelect = this.findElement('#specific-node-select'); if (targetType === 'specific') { specificNodeSelect.style.visibility = 'visible'; specificNodeSelect.style.opacity = '1'; this.populateNodeSelect(); } else { specificNodeSelect.style.visibility = 'hidden'; specificNodeSelect.style.opacity = '0'; } this.updateDeployButton(); } handleNodeSelect() { this.updateDeployButton(); } updateDeployButton() { const deployBtn = this.findElement('#deploy-btn'); if (deployBtn) { deployBtn.disabled = !this.viewModel.isDeployEnabled(); } } populateNodeSelect() { const select = this.findElement('#specific-node-select'); if (!select) return; // Clear existing options select.innerHTML = ''; // Get available nodes from the view model const availableNodes = this.viewModel.get('availableNodes'); if (!availableNodes || availableNodes.length === 0) { // No nodes available const option = document.createElement('option'); option.value = ""; option.textContent = "No nodes available"; option.disabled = true; select.appendChild(option); return; } availableNodes.forEach(node => { const option = document.createElement('option'); option.value = node.ip; option.textContent = `${node.hostname} (${node.ip})`; select.appendChild(option); }); } updateUploadProgress() { // This will be implemented when we add upload progress tracking } updateUploadResults() { // This will be implemented when we add upload results display } updateUploadState() { const isUploading = this.viewModel.get('isUploading'); const deployBtn = this.findElement('#deploy-btn'); if (deployBtn) { deployBtn.disabled = isUploading; if (isUploading) { deployBtn.classList.add('loading'); deployBtn.textContent = '⏳ Deploying...'; } else { deployBtn.classList.remove('loading'); deployBtn.textContent = '🚀 Deploy'; } } this.updateDeployButton(); } } // Cluster View Component class ClusterViewComponent extends Component { constructor(container, viewModel, eventBus) { super(container, viewModel, eventBus); console.log('ClusterViewComponent: Constructor called'); console.log('ClusterViewComponent: Container:', container); console.log('ClusterViewComponent: Container ID:', container?.id); // Find elements for sub-components const primaryNodeContainer = this.findElement('.primary-node-info'); const clusterMembersContainer = this.findElement('#cluster-members-container'); console.log('ClusterViewComponent: Primary node container:', primaryNodeContainer); console.log('ClusterViewComponent: Cluster members container:', clusterMembersContainer); console.log('ClusterViewComponent: Cluster members container ID:', clusterMembersContainer?.id); console.log('ClusterViewComponent: Cluster members container innerHTML:', clusterMembersContainer?.innerHTML); // Create sub-components this.primaryNodeComponent = new PrimaryNodeComponent( primaryNodeContainer, viewModel, eventBus ); this.clusterMembersComponent = new ClusterMembersComponent( clusterMembersContainer, viewModel, eventBus ); console.log('ClusterViewComponent: Sub-components created'); // Track if we've already loaded data to prevent unnecessary reloads this.dataLoaded = false; } mount() { console.log('ClusterViewComponent: Mounting...'); super.mount(); console.log('ClusterViewComponent: Mounting sub-components...'); // Mount sub-components this.primaryNodeComponent.mount(); this.clusterMembersComponent.mount(); // Set up refresh button event listener (since it's in the cluster header, not in the members container) this.setupRefreshButton(); // Only load data if we haven't already or if the view model is empty const members = this.viewModel.get('members'); const shouldLoadData = !this.dataLoaded || !members || members.length === 0; if (shouldLoadData) { console.log('ClusterViewComponent: Starting initial data load...'); // Initial data load - ensure it happens after mounting setTimeout(() => { this.viewModel.updateClusterMembers().then(() => { this.dataLoaded = true; }).catch(error => { console.error('ClusterViewComponent: Failed to load initial data:', error); }); }, 100); } else { console.log('ClusterViewComponent: Data already loaded, skipping initial load'); } // Set up periodic updates // this.setupPeriodicUpdates(); // Disabled automatic refresh console.log('ClusterViewComponent: Mounted successfully'); } setupRefreshButton() { console.log('ClusterViewComponent: Setting up refresh button...'); const refreshBtn = this.findElement('.refresh-btn'); console.log('ClusterViewComponent: Found refresh button:', !!refreshBtn, refreshBtn); if (refreshBtn) { console.log('ClusterViewComponent: Adding click event listener to refresh button'); this.addEventListener(refreshBtn, 'click', this.handleRefresh.bind(this)); console.log('ClusterViewComponent: Event listener added successfully'); } else { console.error('ClusterViewComponent: Refresh button not found!'); console.log('ClusterViewComponent: Container HTML:', this.container.innerHTML); console.log('ClusterViewComponent: All buttons in container:', this.container.querySelectorAll('button')); } } async handleRefresh() { console.log('ClusterViewComponent: Refresh button clicked, performing full refresh...'); // Get the refresh button and show loading state const refreshBtn = this.findElement('.refresh-btn'); console.log('ClusterViewComponent: Found refresh button for loading state:', !!refreshBtn); if (refreshBtn) { const originalText = refreshBtn.innerHTML; console.log('ClusterViewComponent: Original button text:', originalText); refreshBtn.innerHTML = ` Refreshing... `; refreshBtn.disabled = true; try { console.log('ClusterViewComponent: Starting cluster members update...'); // Always perform a full refresh when user clicks refresh button await this.viewModel.updateClusterMembers(); console.log('ClusterViewComponent: Cluster members update completed successfully'); } catch (error) { console.error('ClusterViewComponent: Error during refresh:', error); // Show error state if (this.clusterMembersComponent && this.clusterMembersComponent.showErrorState) { this.clusterMembersComponent.showErrorState(error.message || 'Refresh failed'); } } finally { console.log('ClusterViewComponent: Restoring button state...'); // Restore button state refreshBtn.innerHTML = originalText; refreshBtn.disabled = false; } } else { console.warn('ClusterViewComponent: Refresh button not found, using fallback refresh'); // Fallback if button not found try { await this.viewModel.updateClusterMembers(); } catch (error) { console.error('ClusterViewComponent: Fallback refresh failed:', error); if (this.clusterMembersComponent && this.clusterMembersComponent.showErrorState) { this.clusterMembersComponent.showErrorState(error.message || 'Refresh failed'); } } } } unmount() { console.log('ClusterViewComponent: Unmounting...'); // Unmount sub-components if (this.primaryNodeComponent) { this.primaryNodeComponent.unmount(); } if (this.clusterMembersComponent) { this.clusterMembersComponent.unmount(); } // Clear intervals if (this.updateInterval) { clearInterval(this.updateInterval); } super.unmount(); console.log('ClusterViewComponent: Unmounted'); } // Override pause method to handle sub-components onPause() { console.log('ClusterViewComponent: Pausing...'); // Pause sub-components if (this.primaryNodeComponent && this.primaryNodeComponent.isMounted) { this.primaryNodeComponent.pause(); } if (this.clusterMembersComponent && this.clusterMembersComponent.isMounted) { this.clusterMembersComponent.pause(); } // Clear any active intervals if (this.updateInterval) { clearInterval(this.updateInterval); this.updateInterval = null; } } // Override resume method to handle sub-components onResume() { console.log('ClusterViewComponent: Resuming...'); // Resume sub-components if (this.primaryNodeComponent && this.primaryNodeComponent.isMounted) { this.primaryNodeComponent.resume(); } if (this.clusterMembersComponent && this.clusterMembersComponent.isMounted) { this.clusterMembersComponent.resume(); } // Restart periodic updates if needed // this.setupPeriodicUpdates(); // Disabled automatic refresh } // Override to determine if re-render is needed on resume shouldRenderOnResume() { // Don't re-render on resume - the component should maintain its state return false; } setupPeriodicUpdates() { // Update primary node display every 10 seconds this.updateInterval = setInterval(() => { this.viewModel.updatePrimaryNodeDisplay(); }, 10000); } } // Firmware View Component class FirmwareViewComponent extends Component { constructor(container, viewModel, eventBus) { super(container, viewModel, eventBus); this.firmwareComponent = new FirmwareComponent( this.findElement('#firmware-container'), viewModel, eventBus ); } mount() { super.mount(); // Mount sub-component this.firmwareComponent.mount(); // Update available nodes this.updateAvailableNodes(); } unmount() { // Unmount sub-component if (this.firmwareComponent) { this.firmwareComponent.unmount(); } super.unmount(); } // Override pause method to handle sub-components onPause() { console.log('FirmwareViewComponent: Pausing...'); // Pause sub-component if (this.firmwareComponent && this.firmwareComponent.isMounted) { this.firmwareComponent.pause(); } } // Override resume method to handle sub-components onResume() { console.log('FirmwareViewComponent: Resuming...'); // Resume sub-component if (this.firmwareComponent && this.firmwareComponent.isMounted) { this.firmwareComponent.resume(); } } // Override to determine if re-render is needed on resume shouldRenderOnResume() { // Don't re-render on resume - maintain current state return false; } async updateAvailableNodes() { try { const response = await window.apiClient.getClusterMembers(); const nodes = response.members || []; this.viewModel.updateAvailableNodes(nodes); } catch (error) { console.error('Failed to update available nodes:', error); } } }