'use client'; // 发帖页 import { useState, useEffect, useRef } from 'react'; import { useTranslation } from 'react-i18next'; import { API, generateCaptcha, uploadImage } from '@/lib/api'; import { useApp } from './AppProvider'; import { Icon } from './Icons'; import { useToast } from './Toast'; import CaptchaImage from './CaptchaImage'; export default function NewPost() { const { currentUser, navigate, refresh } = useApp(); const { t } = useTranslation(); const { toast } = useToast(); const [title, setTitle] = useState(''); const [content, setContent] = useState(''); const [images, setImages] = useState([]); // 上传后的 URL 列表 const [previews, setPreviews] = useState([]); // 本地预览 dataURL const [captcha, setCaptcha] = useState(null); const [captchaInput, setCaptchaInput] = useState(''); const [uploading, setUploading] = useState(false); useEffect(() => { setCaptcha(generateCaptcha()); }, []); const handleFiles = async (files) => { setUploading(true); try { const newPreviews = []; for (const file of files) { if (!file.type.startsWith('image/')) continue; if (file.size > 5 * 1024 * 1024) { alert('图片 ' + file.name + ' 超过 5MB,请压缩后上传'); continue; } const dataUrl = await new Promise((resolve) => { const reader = new FileReader(); reader.onload = (e) => resolve(e.target.result); reader.readAsDataURL(file); }); newPreviews.push(dataUrl); const url = await uploadImage(file); setImages((prev) => [...prev, url]); } setPreviews((prev) => [...prev, ...newPreviews]); } catch (err) { alert('上传失败:' + err.message); } finally { setUploading(false); } }; // 拖拽上传 const [dragOver, setDragOver] = useState(false); const fileInputRef = useRef(null); const dropZoneStyle = { border: '2px dashed ' + (dragOver ? 'var(--primary)' : 'var(--border)'), borderRadius: 8, padding: 24, textAlign: 'center', cursor: 'pointer', transition: 'all 0.3s', margin: '8px 0 12px', background: dragOver ? 'var(--primary-bg)' : 'var(--bg)', }; const handleSubmit = async () => { if (!currentUser || !currentUser.id) { toast('请先登录', 'error'); navigate('feed'); return; } if (!content.trim()) { toast('请填写内容', 'error'); return; } if (!captcha || parseInt(captchaInput) !== captcha.answer) { toast('验证码错误,请重新计算', 'error'); setCaptcha(generateCaptcha()); setCaptchaInput(''); return; } try { await API.createPost(title.trim() || '无标题', content.trim(), images); API.logEvent('create_post').catch(() => {}); toast('发布成功', 'success'); navigate('feed'); refresh(); } catch (err) { toast('发布失败:' + err.message, 'error'); } }; return (