Spaces:
Sleeping
Sleeping
File size: 9,861 Bytes
7644eac |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 |
/**
* Server-Sent Events (SSE) Progress Handler
* Handles real-time streaming updates for learning path generation
*/
let eventSource = null;
let progressModal = null;
let progressBar = null;
let progressMessage = null;
let cancelButton = null;
// Initialize SSE progress handler
function initSSEProgress() {
// Create progress modal HTML
const modalHTML = `
<div id="progress-modal" class="fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center z-50" style="backdrop-filter: blur(4px);">
<div class="glass-card p-8 max-w-md w-full mx-4 fade-in">
<h3 class="text-2xl font-bold text-white mb-6 text-center">Generating Your Learning Path</h3>
<!-- Progress Bar -->
<div class="mb-6">
<div class="w-full bg-gray-700 bg-opacity-50 rounded-full h-4 overflow-hidden">
<div id="progress-bar" class="h-4 bg-gradient-to-r from-neon-cyan to-neon-purple rounded-full transition-all duration-500 ease-out" style="width: 0%"></div>
</div>
<div class="flex justify-between mt-2">
<span id="progress-percent" class="text-neon-cyan text-sm font-medium">0%</span>
<span class="text-secondary text-sm">Please wait...</span>
</div>
</div>
<!-- Progress Message -->
<div class="mb-6">
<p id="progress-message" class="text-secondary text-center min-h-[24px]">Initializing...</p>
</div>
<!-- Animated Icon -->
<div class="flex justify-center mb-6">
<div class="relative">
<div class="w-16 h-16 border-4 border-neon-cyan border-t-transparent rounded-full animate-spin"></div>
<div class="absolute inset-0 flex items-center justify-center">
<svg class="w-8 h-8 text-neon-cyan" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
</svg>
</div>
</div>
</div>
<!-- Cancel Button -->
<button id="cancel-generation" class="w-full px-4 py-2 border border-status-error text-status-error rounded-lg hover:bg-status-error hover:bg-opacity-10 transition">
Cancel Generation
</button>
</div>
</div>
`;
// Add modal to body
document.body.insertAdjacentHTML('beforeend', modalHTML);
// Get references
progressModal = document.getElementById('progress-modal');
progressBar = document.getElementById('progress-bar');
progressMessage = document.getElementById('progress-message');
cancelButton = document.getElementById('cancel-generation');
// Cancel button handler
cancelButton.addEventListener('click', cancelGeneration);
}
// Show progress modal
function showProgressModal() {
if (progressModal) {
progressModal.classList.remove('hidden');
progressModal.classList.add('flex');
resetProgress();
}
}
// Hide progress modal
function hideProgressModal() {
if (progressModal) {
progressModal.classList.add('hidden');
progressModal.classList.remove('flex');
}
}
// Reset progress
function resetProgress() {
if (progressBar) progressBar.style.width = '0%';
if (progressMessage) progressMessage.textContent = 'Initializing...';
document.getElementById('progress-percent').textContent = '0%';
}
// Update progress
function updateProgress(progress, message) {
if (progressBar) {
progressBar.style.width = `${progress}%`;
}
if (progressMessage) {
progressMessage.textContent = message;
}
document.getElementById('progress-percent').textContent = `${progress}%`;
}
// Show error
function showError(errorMessage) {
if (progressMessage) {
progressMessage.innerHTML = `<span class="text-status-error">❌ ${errorMessage}</span>`;
}
if (progressBar) {
progressBar.classList.remove('bg-gradient-to-r', 'from-neon-cyan', 'to-neon-purple');
progressBar.classList.add('bg-status-error');
}
// Change cancel button to "Close"
if (cancelButton) {
cancelButton.textContent = 'Close';
cancelButton.classList.remove('border-status-error', 'text-status-error');
cancelButton.classList.add('border-neon-cyan', 'text-neon-cyan');
}
}
// Cancel generation
function cancelGeneration() {
if (eventSource) {
eventSource.close();
eventSource = null;
}
hideProgressModal();
}
// Start SSE streaming
function startSSEGeneration(formData) {
// Show progress modal
showProgressModal();
// Close any existing connection
if (eventSource) {
eventSource.close();
}
// Create FormData for POST request
const urlParams = new URLSearchParams(formData);
// Create EventSource with POST data (using a workaround)
// Note: EventSource only supports GET, so we'll use fetch with streaming
fetch('/generate-stream', {
method: 'POST',
body: urlParams,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
}).then(response => {
const reader = response.body.getReader();
const decoder = new TextDecoder();
function readStream() {
reader.read().then(({ done, value }) => {
if (done) {
console.log('Stream complete');
return;
}
// Decode the chunk
const chunk = decoder.decode(value, { stream: true });
// Split by SSE message delimiter
const messages = chunk.split('\n\n');
messages.forEach(message => {
if (message.startsWith('data: ')) {
const data = message.substring(6);
try {
const parsed = JSON.parse(data);
handleSSEMessage(parsed);
} catch (e) {
console.error('Failed to parse SSE message:', data);
}
}
});
// Continue reading
readStream();
}).catch(error => {
console.error('Stream error:', error);
showError('Connection lost. Please try again.');
});
}
readStream();
}).catch(error => {
console.error('Fetch error:', error);
showError('Failed to start generation. Please try again.');
});
}
// Handle SSE message
function handleSSEMessage(data) {
console.log('SSE message:', data);
// Handle error
if (data.error) {
showError(data.error);
setTimeout(() => {
hideProgressModal();
}, 3000);
return;
}
// Update progress
if (data.progress !== undefined) {
updateProgress(data.progress, data.message || '');
}
// Handle completion
if (data.done) {
// Add success animation
if (progressBar) {
progressBar.classList.add('animate-pulse');
}
// Redirect after short delay
setTimeout(() => {
if (data.redirect_url) {
console.log('Redirecting to:', data.redirect_url);
window.location.href = data.redirect_url;
} else {
console.error('No redirect URL provided');
hideProgressModal();
}
}, 500);
}
}
// Attach to form submission
document.addEventListener('DOMContentLoaded', function() {
// Initialize SSE progress
initSSEProgress();
// Find the generation form
const form = document.querySelector('form[action="/generate"]');
if (form) {
// Add checkbox for streaming mode
const streamingCheckbox = document.createElement('div');
streamingCheckbox.className = 'flex items-center gap-2 mt-4';
streamingCheckbox.innerHTML = `
<input type="checkbox" id="use-streaming" class="w-4 h-4 rounded border-neon-cyan text-neon-cyan focus:ring-neon-cyan" checked>
<label for="use-streaming" class="text-sm text-secondary cursor-pointer">
Enable real-time progress updates
</label>
`;
// Insert before submit button
const submitButton = form.querySelector('button[type="submit"]');
if (submitButton) {
submitButton.parentNode.insertBefore(streamingCheckbox, submitButton);
}
// Intercept form submission
form.addEventListener('submit', function(e) {
const useStreaming = document.getElementById('use-streaming')?.checked;
if (useStreaming) {
e.preventDefault();
// Get form data
const formData = new FormData(form);
// Start SSE generation
startSSEGeneration(formData);
}
// If not using streaming, let form submit normally
});
}
});
|