timetablev2 / frontend /src /components /ModuleInput.js
notha99y's picture
init
c398d0b
Raw History Blame Contribute Delete
15.1 kB
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&#10;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;