Spaces:
Sleeping
Sleeping
File size: 15,149 Bytes
c398d0b | 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 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 | import React, { useState, useEffect } from 'react';
import { Plus, Upload, Search, Trash2, X } from 'lucide-react';
import toast from 'react-hot-toast';
import { searchTimetable, uploadCSV } from '../services/api';
const ModuleInput = ({ onResults, isLoading, setIsLoading }) => {
const [modules, setModules] = useState([
{ module: '', class_name: '', lecture: '', tutorial: '' }
]);
const [numCombinations, setNumCombinations] = useState(4);
const [restrictBackToBack, setRestrictBackToBack] = useState(false);
const addModule = () => {
setModules([...modules, { module: '', class_name: '', lecture: '', tutorial: '' }]);
};
const clearAll = () => {
setModules([{ module: '', class_name: '', lecture: '', tutorial: '' }]);
setNumCombinations(4);
setRestrictBackToBack(false);
onResults(null); // Clear search results
// Clear the paste textarea
const textarea = document.querySelector('textarea[placeholder*="Module"]');
if (textarea) {
textarea.value = '';
}
toast.success('All data cleared!');
};
// Add keyboard shortcut for clearing (Ctrl+Shift+C)
useEffect(() => {
const handleKeyDown = (event) => {
if (event.ctrlKey && event.shiftKey && event.key === 'C') {
event.preventDefault();
clearAll();
}
};
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}, []);
const removeModule = (index) => {
if (modules.length > 1) {
setModules(modules.filter((_, i) => i !== index));
}
};
const updateModule = (index, field, value) => {
const updated = [...modules];
updated[index][field] = value;
setModules(updated);
};
const handleSearch = async () => {
// Validate inputs
const validModules = modules.filter(m =>
m.module.trim() && m.class_name.trim() && m.lecture.trim() && m.tutorial.trim()
);
if (validModules.length === 0) {
toast.error('Please add at least one complete module');
return;
}
// Validate time formats and provide helpful error messages
for (let i = 0; i < validModules.length; i++) {
const module = validModules[i];
// Check if lecture field looks like a time (contains "to" or day names)
if (!module.lecture.toLowerCase().includes('to') &&
!/(mon|tue|wed|thu|fri|sat|sun)/i.test(module.lecture)) {
toast.error(`Module ${i + 1}: Lecture field "${module.lecture}" doesn't look like a time format. Expected: "Mon 9am to 11am"`);
return;
}
// Check if tutorial field looks like a time
if (!module.tutorial.toLowerCase().includes('to') &&
!/(mon|tue|wed|thu|fri|sat|sun)/i.test(module.tutorial)) {
toast.error(`Module ${i + 1}: Tutorial field "${module.tutorial}" doesn't look like a time format. Expected: "Tue 2pm to 4pm"`);
return;
}
}
setIsLoading(true);
// Show progress toast
const searchToast = toast.loading('Searching for combinations...', {
duration: 30000
});
try {
const response = await searchTimetable({
modules: validModules,
num_combinations: numCombinations,
restrict_back_to_back: restrictBackToBack
});
toast.dismiss(searchToast);
if (response.success) {
onResults(response);
toast.success(response.message || `Found ${response.combinations.length} combinations!`);
} else {
toast.error(response.message || 'No valid combinations found', {
duration: 6000
});
onResults(null);
}
} catch (error) {
toast.dismiss(searchToast);
toast.error('Error searching for combinations');
console.error(error);
onResults(null);
} finally {
setIsLoading(false);
}
};
const handleFileUpload = async (event) => {
const file = event.target.files[0];
if (!file) return;
try {
const response = await uploadCSV(file);
if (response.success) {
setModules(response.modules);
toast.success('CSV uploaded successfully!');
} else {
toast.error('Error uploading CSV');
}
} catch (error) {
toast.error('Error uploading file');
console.error(error);
}
};
const handlePasteData = (event) => {
const pastedText = event.target.value;
if (!pastedText.trim()) return;
const lines = pastedText.trim().split('\n');
const newModules = lines.map(line => {
const parts = line.split('\t');
let module = parts[0] || '';
let class_name = parts[1] || '';
let lecture = parts[2] || '';
let tutorial = parts[3] || '';
// Auto-detect and fix swapped columns
// If lecture field looks like a class name and class field looks like a time, swap them
if (lecture && !lecture.toLowerCase().includes('to') &&
!/^(mon|tue|wed|thu|fri|sat|sun)/i.test(lecture) &&
class_name && (class_name.toLowerCase().includes('to') || /^(mon|tue|wed|thu|fri|sat|sun)/i.test(class_name))) {
// Swap lecture and class_name
[lecture, class_name] = [class_name, lecture];
console.log(`Auto-corrected swapped columns for module: ${module}`);
}
return {
module,
class_name,
lecture,
tutorial
};
});
setModules(newModules);
event.target.value = ''; // Clear the textarea
// Show a helpful message about the expected format
toast.success('Data pasted! Please verify the time formats are correct.');
};
return (
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-md p-6 mb-8 transition-colors duration-200">
<h2 className="text-2xl font-semibold mb-6 text-gray-900 dark:text-white">Module Information</h2>
{/* Instructions */}
<div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4 mb-6">
<h3 className="font-medium text-blue-900 dark:text-blue-100 mb-2">Instructions:</h3>
<ul className="text-sm text-blue-800 dark:text-blue-200 space-y-1">
<li>• Enter module details manually or upload a CSV file</li>
<li>• <strong>Time format:</strong> "Day HH.MMam/pm to HH.MMam/pm" (e.g., "Mon 4.30pm to 6pm")</li>
<li>• <strong>Column order:</strong> Module | Class | Lecture Time | Tutorial Time</li>
<li>• You can paste tab-separated data in the text area below</li>
<li>• <strong>🔄 Search limit:</strong> Maximum 1000 attempts to find combinations</li>
</ul>
</div>
{/* Paste Area */}
<div className="mb-6">
<div className="flex items-center justify-between mb-2">
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300">
Paste Tab-Separated Data (Optional)
</label>
<button
type="button"
onClick={() => {
const sampleData = "COMP1000\tLec01\tMon 9am to 11am\tTue 2pm to 4pm\nMATH1001\tLec02\tWed 1pm to 3pm\tThu 10am to 12pm";
document.querySelector('textarea[placeholder*="Module"]').value = sampleData;
handlePasteData({ target: { value: sampleData } });
}}
className="text-xs px-3 py-1 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 rounded hover:bg-blue-200 dark:hover:bg-blue-900/50 transition-colors duration-200"
>
Load Sample Data
</button>
</div>
<textarea
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
rows="4"
placeholder="Module Class Lecture Tutorial COMP1000 Lec01 Mon 9am to 11am Tue 2pm to 4pm"
onChange={handlePasteData}
/>
</div>
{/* File Upload */}
<div className="mb-6">
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Upload CSV File (Optional)
</label>
<div className="flex items-center space-x-4">
<input
type="file"
accept=".csv"
onChange={handleFileUpload}
className="hidden"
id="csv-upload"
/>
<label
htmlFor="csv-upload"
className="flex items-center px-4 py-2 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-md hover:bg-gray-200 dark:hover:bg-gray-600 cursor-pointer transition-colors duration-200"
>
<Upload className="h-4 w-4 mr-2" />
Choose CSV File
</label>
</div>
</div>
{/* Module Entries */}
<div className="space-y-4 mb-6">
{modules.map((module, index) => (
<div key={index} className="grid grid-cols-1 md:grid-cols-5 gap-4 p-4 border border-gray-200 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-700/50">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Module</label>
<input
type="text"
value={module.module}
onChange={(e) => updateModule(index, 'module', e.target.value)}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
placeholder="e.g., COMP1000"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Class</label>
<input
type="text"
value={module.class_name}
onChange={(e) => updateModule(index, 'class_name', e.target.value)}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
placeholder="e.g., Lec01"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Lecture</label>
<input
type="text"
value={module.lecture}
onChange={(e) => updateModule(index, 'lecture', e.target.value)}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
placeholder="Mon 9am to 11am"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Tutorial</label>
<input
type="text"
value={module.tutorial}
onChange={(e) => updateModule(index, 'tutorial', e.target.value)}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
placeholder="Tue 2pm to 4pm"
/>
</div>
<div className="flex items-end">
<button
onClick={() => removeModule(index)}
disabled={modules.length === 1}
className="w-full px-3 py-2 bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-400 rounded-md hover:bg-red-200 dark:hover:bg-red-900/50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-200"
>
<Trash2 className="h-4 w-4 mx-auto" />
</button>
</div>
</div>
))}
</div>
{/* Action Buttons */}
<div className="flex flex-wrap gap-3 mb-6">
<button
onClick={addModule}
className="flex items-center px-4 py-2 bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400 rounded-md hover:bg-green-200 dark:hover:bg-green-900/50 transition-colors duration-200"
>
<Plus className="h-4 w-4 mr-2" />
Add Module
</button>
<button
onClick={clearAll}
title="Clear all data (Ctrl+Shift+C)"
className="flex items-center px-4 py-2 bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-400 rounded-md hover:bg-red-200 dark:hover:bg-red-900/50 transition-colors duration-200"
>
<Trash2 className="h-4 w-4 mr-2" />
Clear All
</button>
</div>
{/* Search Options */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Number of Combinations
</label>
<input
type="number"
min="1"
max="20"
value={numCombinations}
onChange={(e) => setNumCombinations(parseInt(e.target.value))}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
/>
</div>
<div className="flex items-center">
<input
type="checkbox"
id="restrict-back-to-back"
checked={restrictBackToBack}
onChange={(e) => setRestrictBackToBack(e.target.checked)}
className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700"
/>
<label htmlFor="restrict-back-to-back" className="ml-2 text-sm text-gray-700 dark:text-gray-300">
Restrict back-to-back classes
</label>
</div>
</div>
{/* Search Button */}
<div className="space-y-3">
<button
onClick={handleSearch}
disabled={isLoading}
className="w-full flex items-center justify-center px-6 py-3 bg-blue-600 dark:bg-blue-700 text-white rounded-md hover:bg-blue-700 dark:hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-200"
>
<Search className="h-5 w-5 mr-2" />
{isLoading ? 'Searching...' : 'Find Combinations'}
</button>
{isLoading && (
<div className="text-center">
<div className="inline-flex items-center text-sm text-gray-600 dark:text-gray-400">
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600 mr-2"></div>
Searching for combinations...
</div>
</div>
)}
</div>
</div>
);
};
export default ModuleInput; |