Spaces:
Sleeping
Sleeping
File size: 8,916 Bytes
7d51e81 | 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 | "use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { FiEdit3, FiSend, FiX, FiUser, FiLink, FiAlertCircle, FiCheckCircle, FiImage, FiTrash2, FiUpload } from "react-icons/fi";
import './styles/AddUpdateForm.css';
export default function AddUpdateForm() {
const [title, setTitle] = useState("");
const [content, setContent] = useState("");
const [linksText, setLinksText] = useState("");
const [userId, setUserId] = useState(null);
const [uploadedFiles, setUploadedFiles] = useState([]);
const [isUploadingFiles, setIsUploadingFiles] = useState(false);
const [loading, setLoading] = useState(false);
const [toast, setToast] = useState(null);
const router = useRouter();
useEffect(() => {
const usn = typeof window !== 'undefined' ? localStorage.getItem('usn') : null;
if (!usn) return;
(async () => {
try {
const res = await fetch(`/api/user/id?usn=${encodeURIComponent(usn)}`);
if (res.ok) {
const data = await res.json();
if (data?.userId) setUserId(data.userId);
}
} catch (err) {
console.error('Failed to resolve user id', err);
}
})();
}, []);
const showToast = (msg, type = 'info') => {
setToast({ message: msg, type });
setTimeout(() => setToast(null), 3500);
};
const parseLinks = (text) => {
if (!text) return [];
return text
.split(/[,\n]+/)
.map(s => s.trim())
.filter(Boolean);
};
const handleSubmit = async (e) => {
e.preventDefault();
if (!title.trim() || !content.trim()) {
showToast('Please enter title and content', 'error');
return;
}
setLoading(true);
const links = parseLinks(linksText);
try {
const res = await fetch('/api/updates', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: title.trim(), content: content.trim(), links, userId, files: uploadedFiles }),
});
const data = await res.json();
if (res.ok) {
showToast('Update created successfully', 'success');
setTitle('');
setContent('');
setLinksText('');
setUploadedFiles([]);
// Optionally navigate to updates list
// router.push('/updates');
} else {
showToast(data?.error || 'Failed to create update', 'error');
}
} catch (err) {
console.error(err);
showToast('Network error', 'error');
} finally {
setLoading(false);
}
};
const handleFilesSelected = async (e) => {
const files = Array.from(e.target.files || []);
if (!files.length) return;
setIsUploadingFiles(true);
try {
for (let i = 0; i < files.length; i++) {
const f = files[i];
const fd = new FormData();
fd.append('file', f);
if (userId) fd.append('userId', userId);
const res = await fetch('/api/updates/upload', { method: 'POST', body: fd });
const data = await res.json();
if (res.ok && data?.file) {
setUploadedFiles((p) => [...p, data.file]);
} else {
showToast(data?.error || `Failed to upload ${f.name}`, 'error');
}
}
} catch (err) {
console.error('File upload error', err);
showToast('File upload failed', 'error');
} finally {
setIsUploadingFiles(false);
// clear file input
e.target.value = null;
}
};
const removeUploadedFile = (idx) => {
setUploadedFiles((p) => p.filter((_, i) => i !== idx));
};
const handleClear = () => {
setTitle('');
setContent('');
setLinksText('');
};
return (
<div className="auf-container">
{/* Header */}
<div className="auf-header">
<div className="auf-header-icon">
<FiEdit3 />
</div>
<h3 className="auf-header-title">Create Update</h3>
</div>
{/* Toast Notification */}
{toast && (
<div className={`auf-toast auf-toast-${toast.type}`}>
{toast.type === 'success' ? (
<FiCheckCircle className="auf-toast-icon" />
) : (
<FiAlertCircle className="auf-toast-icon" />
)}
<span>{toast.message}</span>
</div>
)}
{/* Form Card */}
<div className="auf-card">
<form onSubmit={handleSubmit} className="auf-form">
{/* Title Field */}
<div className="auf-field">
<label className="auf-label">
<FiEdit3 className="auf-label-icon" />
<span>Title</span>
<span className="auf-required">*</span>
</label>
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="Enter update title..."
className="auf-input"
required
/>
</div>
{/* Files / Raw Upload Field */}
<label className="auf-label">
<FiImage className="auf-label-icon" />
<span>Files (optional)</span>
</label>
<div className="auf-file-row">
<label className="auf-file-btn">
<FiUpload />
<span>Upload files</span>
<input type="file" multiple onChange={handleFilesSelected} className="auf-hidden-input" />
</label>
{isUploadingFiles && <span className="auf-file-uploading">Uploading…</span>}
</div>
{uploadedFiles.length > 0 && (
<div className="auf-uploaded-files">
{uploadedFiles.map((f, i) => (
<div key={i} className="auf-uploaded-file">
<a href={f.url} target="_blank" rel="noreferrer noopener" className="auf-uploaded-link">
<span className="auf-file-name">{f.name || f.url}</span>
</a>
<button type="button" className="auf-file-remove" onClick={() => removeUploadedFile(i)}>
<FiTrash2 />
</button>
</div>
))}
</div>
)}
{/* Content Field */}
<div className="auf-field">
<label className="auf-label">
<FiEdit3 className="auf-label-icon" />
<span>Content</span>
<span className="auf-required">*</span>
</label>
<textarea
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder="Write your update content here..."
rows={6}
className="auf-textarea"
required
/>
<div className="auf-hint">
Share information, announcements, or resources with the community
</div>
</div>
{/* Links Field */}
<div className="auf-field">
<label className="auf-label">
<FiLink className="auf-label-icon" />
<span>Links (optional)</span>
</label>
<textarea
value={linksText}
onChange={(e) => setLinksText(e.target.value)}
placeholder="/internal/path or https://external-link.com Separate multiple links with commas or new lines"
rows={3}
className="auf-textarea auf-textarea-links"
/>
<div className="auf-hint">
Add internal paths (starting with /) or external URLs
</div>
</div>
{/* Action Bar */}
<div className="auf-actions">
<div className="auf-user-status">
<FiUser className="auf-status-icon" />
<span className={userId ? 'auf-status-active' : 'auf-status-inactive'}>
{userId ? 'Signed in' : 'Not signed in'}
</span>
</div>
<div className="auf-buttons">
<button
type="button"
onClick={handleClear}
className="auf-btn auf-btn-clear"
disabled={loading}
>
<FiX />
<span>Clear</span>
</button>
<button
type="submit"
className="auf-btn auf-btn-submit"
disabled={loading}
>
{loading ? (
<>
<span className="auf-spinner"></span>
<span>Saving...</span>
</>
) : (
<>
<FiSend />
<span>Create Update</span>
</>
)}
</button>
</div>
</div>
</form>
</div>
</div>
);
} |