feat: toast notifications, canvas captcha, super admin, mobile fixes
- Toast system (ToastProvider + useToast): right-top colored toasts replace alert for publish success/error; CSS + layout mount - Captcha as canvas image (noise + distortion) in NewPost/ReplyList/ register modal — blocks bots, click to refresh - Super admin: first registered user cannot be demoted (isFirstUser by created_at, DB-agnostic) - Admins can delete others' posts/replies (UI buttons shown for admin) - Mobile: post-actions wrap + compact, feed excerpt 2.5 lines - Fix: missing sun icon in Icons (dark mode toggle showed nothing) - Feed long posts: gradient fade mask instead of line-clamp
This commit is contained in:
1 parent
c059ad0979
commit
80eb313604
12 files changed
+262
-31
No files matched your search
@@ -0,0 +1,68 @@
|
||||
'use client';
|
||||
|
||||
// 图片验证码:用 canvas 绘制算式(带噪点/干扰线,挡一部分人机)
|
||||
// 点击图片可刷新验证码
|
||||
import { useEffect, useRef } from 'react';
|
||||
|
||||
export default function CaptchaImage({ captcha, onRefresh }) {
|
||||
const canvasRef = useRef(null);
|
||||
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas || !captcha) return;
|
||||
const ctx = canvas.getContext('2d');
|
||||
const W = canvas.width;
|
||||
const H = canvas.height;
|
||||
|
||||
// 背景(半透明玻璃感)
|
||||
ctx.clearRect(0, 0, W, H);
|
||||
ctx.fillStyle = 'rgba(91, 155, 213, 0.10)';
|
||||
ctx.fillRect(0, 0, W, H);
|
||||
|
||||
// 干扰线
|
||||
for (let i = 0; i < 4; i++) {
|
||||
ctx.strokeStyle = `rgba(${80 + Math.random() * 120}, ${80 + Math.random() * 120}, 200, ${0.2 + Math.random() * 0.3})`;
|
||||
ctx.lineWidth = 1 + Math.random();
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(Math.random() * W, Math.random() * H);
|
||||
ctx.lineTo(Math.random() * W, Math.random() * H);
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
// 噪点
|
||||
for (let i = 0; i < 30; i++) {
|
||||
ctx.fillStyle = `rgba(${Math.random() * 200}, ${Math.random() * 200}, 220, ${0.3 + Math.random() * 0.5})`;
|
||||
ctx.beginPath();
|
||||
ctx.arc(Math.random() * W, Math.random() * H, 1 + Math.random() * 1.5, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
}
|
||||
|
||||
// 算式文字(每个字符轻微旋转/位移,增加识别难度)
|
||||
const text = captcha.question.replace(' = ?', '');
|
||||
const chars = text.split('');
|
||||
const fontSize = Math.floor(H * 0.52);
|
||||
const step = W / (chars.length + 1);
|
||||
chars.forEach((ch, i) => {
|
||||
ctx.save();
|
||||
ctx.translate(step * (i + 1) + (Math.random() - 0.5) * 6, H / 2 + (Math.random() - 0.5) * 6);
|
||||
ctx.rotate((Math.random() - 0.5) * 0.25);
|
||||
ctx.font = `bold ${fontSize}px -apple-system, "SF Pro Display", "Segoe UI", Roboto, sans-serif`;
|
||||
ctx.fillStyle = `rgba(${40 + Math.random() * 60}, ${50 + Math.random() * 50}, 90, 0.9)`;
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.fillText(ch, 0, 0);
|
||||
ctx.restore();
|
||||
});
|
||||
}, [captcha]);
|
||||
|
||||
return (
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
width={120}
|
||||
height={40}
|
||||
onClick={onRefresh}
|
||||
title="看不清?点击刷新"
|
||||
style={{ cursor: 'pointer', borderRadius: 6, border: '1px solid var(--glass-border)', verticalAlign: 'middle' }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
+17
-3
@@ -1,7 +1,7 @@
|
||||
'use client';
|
||||
|
||||
// 信息流:帖子列表 + 排序 tab + 发布新帖按钮
|
||||
import { useEffect, useState, useCallback } from 'react';
|
||||
import { useEffect, useState, useCallback, useRef } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
import { useApp } from './AppProvider';
|
||||
import { Icon } from './Icons';
|
||||
@@ -21,6 +21,7 @@ export default function Feed({ onOpenModal, onReport }) {
|
||||
const [page, setPage] = useState(1);
|
||||
const [totalPages, setTotalPages] = useState(1);
|
||||
const [viewerSrc, setViewerSrc] = useState(null);
|
||||
const postListRef = useRef(null);
|
||||
const PAGE_SIZE = 20;
|
||||
|
||||
const load = useCallback(async (targetPage) => {
|
||||
@@ -39,6 +40,19 @@ export default function Feed({ onOpenModal, onReport }) {
|
||||
|
||||
useEffect(() => { load(page); }, [load]);
|
||||
|
||||
// 长帖内容:超过 3 行时加 .has-fade(底部渐变遮罩提示还有更多内容)
|
||||
useEffect(() => {
|
||||
if (!posts || posts.length === 0 || !postListRef.current) return;
|
||||
const els = postListRef.current.querySelectorAll('.post-content');
|
||||
els.forEach((el) => {
|
||||
if (el.scrollHeight > el.clientHeight + 4) {
|
||||
el.classList.add('has-fade');
|
||||
} else {
|
||||
el.classList.remove('has-fade');
|
||||
}
|
||||
});
|
||||
}, [posts]);
|
||||
|
||||
// 排序切换时回第一页
|
||||
useEffect(() => { setPage(1); }, [sort]);
|
||||
|
||||
@@ -69,7 +83,7 @@ export default function Feed({ onOpenModal, onReport }) {
|
||||
<Icon name="plus" /> 发布新帖
|
||||
</button>
|
||||
</div>
|
||||
<div id="postList">
|
||||
<div id="postList" ref={postListRef}>
|
||||
{posts === null ? (
|
||||
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>加载中...</div>
|
||||
) : error ? (
|
||||
@@ -119,7 +133,7 @@ export default function Feed({ onOpenModal, onReport }) {
|
||||
}}>
|
||||
<Icon name="flag" size={14} /> 举报
|
||||
</button>
|
||||
{currentUser && currentUser.id === p.user_id && (
|
||||
{currentUser && (currentUser.id === p.user_id || currentUser.role === 'admin') && (
|
||||
<button className="action-delete" onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleDelete(p.id);
|
||||
|
||||
@@ -32,6 +32,11 @@ const PATHS = {
|
||||
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>
|
||||
</>
|
||||
),
|
||||
sun: (
|
||||
<>
|
||||
<circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/>
|
||||
</>
|
||||
),
|
||||
logout: (
|
||||
<>
|
||||
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/>
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useState, useEffect } from 'react';
|
||||
import { API, generateCaptcha } from '@/lib/api';
|
||||
import { useApp } from './AppProvider';
|
||||
import { Icon } from './Icons';
|
||||
import CaptchaImage from './CaptchaImage';
|
||||
|
||||
export default function Modals({ modal, onClose, reportPostId }) {
|
||||
const { login, register, currentUser, refresh } = useApp();
|
||||
@@ -106,11 +107,13 @@ export default function Modals({ modal, onClose, reportPostId }) {
|
||||
<input type="text" placeholder="用户名" value={regUsername} onChange={(e) => setRegUsername(e.target.value)} />
|
||||
<input type="email" placeholder="邮箱" value={regEmail} onChange={(e) => setRegEmail(e.target.value)} />
|
||||
<input type="password" placeholder="密码(至少6位)" value={regPassword} onChange={(e) => setRegPassword(e.target.value)} />
|
||||
<div className="captcha-row">
|
||||
<span onClick={() => setRegCaptcha(generateCaptcha())} style={{ cursor: 'pointer' }}>
|
||||
{regCaptcha ? regCaptcha.question : ''}
|
||||
</span>
|
||||
<input type="text" placeholder="答案" style={{ width: 80 }} value={regCaptchaInput} onChange={(e) => setRegCaptchaInput(e.target.value)} />
|
||||
<div className="captcha-row" style={{ display: 'flex', alignItems: 'center', gap: 10, margin: '12px 0' }}>
|
||||
{regCaptcha ? (
|
||||
<CaptchaImage captcha={regCaptcha} onRefresh={() => { setRegCaptcha(generateCaptcha()); setRegCaptchaInput(''); }} />
|
||||
) : (
|
||||
<span style={{ color: 'var(--text-light)' }}>验证码加载中...</span>
|
||||
)}
|
||||
<input type="text" placeholder="答案" style={{ width: 80, background: 'var(--bg)', color: 'var(--text)', border: '1px solid var(--border)', padding: '8px 12px', borderRadius: 4 }} value={regCaptchaInput} onChange={(e) => setRegCaptchaInput(e.target.value)} />
|
||||
</div>
|
||||
<button className="btn-primary" style={{ width: '100%' }} onClick={handleRegister}>注册</button>
|
||||
</div>
|
||||
|
||||
+14
-9
@@ -5,9 +5,12 @@ import { useState, useEffect, useRef } from 'react';
|
||||
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 { toast } = useToast();
|
||||
const [title, setTitle] = useState('');
|
||||
const [content, setContent] = useState('');
|
||||
const [images, setImages] = useState([]); // 上传后的 URL 列表
|
||||
@@ -57,13 +60,13 @@ export default function NewPost() {
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!currentUser || !currentUser.id) {
|
||||
alert('请先登录');
|
||||
toast('请先登录', 'error');
|
||||
navigate('feed');
|
||||
return;
|
||||
}
|
||||
if (!content.trim()) { alert('请填写内容'); return; }
|
||||
if (!content.trim()) { toast('请填写内容', 'error'); return; }
|
||||
if (!captcha || parseInt(captchaInput) !== captcha.answer) {
|
||||
alert('验证码错误,请重新计算');
|
||||
toast('验证码错误,请重新计算', 'error');
|
||||
setCaptcha(generateCaptcha());
|
||||
setCaptchaInput('');
|
||||
return;
|
||||
@@ -71,11 +74,11 @@ export default function NewPost() {
|
||||
try {
|
||||
await API.createPost(title.trim() || '无标题', content.trim(), images);
|
||||
API.logEvent('create_post').catch(() => {});
|
||||
alert('发布成功!');
|
||||
toast('发布成功', 'success');
|
||||
navigate('feed');
|
||||
refresh();
|
||||
} catch (err) {
|
||||
alert('发布失败:' + err.message);
|
||||
toast('发布失败:' + err.message, 'error');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -125,10 +128,12 @@ export default function NewPost() {
|
||||
style={{ display: 'none' }}
|
||||
onChange={(e) => { if (e.target.files) handleFiles(Array.from(e.target.files)); }}
|
||||
/>
|
||||
<div className="captcha-row" style={{ margin: '12px 0' }}>
|
||||
<span onClick={() => setCaptcha(generateCaptcha())} style={{ cursor: 'pointer' }}>
|
||||
{captcha ? captcha.question : ''}
|
||||
</span>
|
||||
<div className="captcha-row" style={{ margin: '12px 0', display: 'flex', alignItems: 'center', gap: 10 }}>
|
||||
{captcha ? (
|
||||
<CaptchaImage captcha={captcha} onRefresh={() => { setCaptcha(generateCaptcha()); setCaptchaInput(''); }} />
|
||||
) : (
|
||||
<span style={{ color: 'var(--text-light)' }}>验证码加载中...</span>
|
||||
)}
|
||||
<input
|
||||
type="text"
|
||||
placeholder="答案"
|
||||
|
||||
@@ -47,7 +47,8 @@ export default function PostDetail({ postId }) {
|
||||
}
|
||||
|
||||
const time = post.created_at ? new Date(post.created_at).toLocaleString('zh-CN') : '';
|
||||
const canDelete = currentUser && currentUser.id === post.user_id;
|
||||
// 作者本人 或 管理员 可删除/编辑
|
||||
const canDelete = currentUser && (currentUser.id === post.user_id || currentUser.role === 'admin');
|
||||
const canEdit = currentUser && currentUser.id === post.user_id;
|
||||
|
||||
const handleDelete = async () => {
|
||||
|
||||
@@ -6,6 +6,7 @@ import { API, generateCaptcha } from '@/lib/api';
|
||||
import { useApp } from './AppProvider';
|
||||
import { Icon } from './Icons';
|
||||
import { renderMarkdown } from '@/lib/markdown';
|
||||
import CaptchaImage from './CaptchaImage';
|
||||
|
||||
function avatar(username) {
|
||||
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || '匿名用户') +
|
||||
@@ -84,7 +85,7 @@ export default function ReplyList({ postId, onRefresh }) {
|
||||
{r.username || '匿名用户'}
|
||||
</span>
|
||||
<span className="reply-time">{rTime}</span>
|
||||
{currentUser && currentUser.id === r.user_id && (
|
||||
{currentUser && (currentUser.id === r.user_id || currentUser.role === 'admin') && (
|
||||
<button className="btn-sm btn-danger reply-delete-btn" onClick={() => handleDelete(r.id)}>
|
||||
<Icon name="trash" size={12} /> 删除
|
||||
</button>
|
||||
@@ -107,10 +108,12 @@ export default function ReplyList({ postId, onRefresh }) {
|
||||
onChange={(e) => setContent(e.target.value)}
|
||||
onKeyDown={(e) => { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) handleSubmit(); }}
|
||||
/>
|
||||
<div className="captcha-row" style={{ margin: '10px 0' }}>
|
||||
<span onClick={() => setCaptcha(generateCaptcha())} style={{ cursor: 'pointer' }}>
|
||||
{captcha ? captcha.question : ''}
|
||||
</span>
|
||||
<div className="captcha-row" style={{ margin: '10px 0', display: 'flex', alignItems: 'center', gap: 10 }}>
|
||||
{captcha ? (
|
||||
<CaptchaImage captcha={captcha} onRefresh={() => { setCaptcha(generateCaptcha()); setCaptchaInput(''); }} />
|
||||
) : (
|
||||
<span style={{ color: 'var(--text-light)' }}>验证码加载中...</span>
|
||||
)}
|
||||
<input
|
||||
type="text"
|
||||
placeholder="答案"
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
'use client';
|
||||
|
||||
// Toast 通知系统:右上角弹出,自动消失(替代 alert)
|
||||
// 用法:const { toast } = useToast(); toast('发布成功', 'success');
|
||||
import { createContext, useContext, useState, useCallback, useRef } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
|
||||
const ToastContext = createContext(null);
|
||||
|
||||
export function useToast() {
|
||||
return useContext(ToastContext);
|
||||
}
|
||||
|
||||
let idCounter = 0;
|
||||
|
||||
export function ToastProvider({ children }) {
|
||||
const [toasts, setToasts] = useState([]);
|
||||
const timersRef = useRef({});
|
||||
|
||||
const toast = useCallback((message, type = 'success', duration = 3000) => {
|
||||
const id = ++idCounter;
|
||||
setToasts((prev) => [...prev, { id, message, type }]);
|
||||
if (timersRef.current[id]) clearTimeout(timersRef.current[id]);
|
||||
timersRef.current[id] = setTimeout(() => {
|
||||
setToasts((prev) => prev.filter((t) => t.id !== id));
|
||||
delete timersRef.current[id];
|
||||
}, duration);
|
||||
}, []);
|
||||
|
||||
const dismiss = useCallback((id) => {
|
||||
setToasts((prev) => prev.filter((t) => t.id !== id));
|
||||
if (timersRef.current[id]) { clearTimeout(timersRef.current[id]); delete timersRef.current[id]; }
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<ToastContext.Provider value={{ toast }}>
|
||||
{children}
|
||||
{typeof document !== 'undefined' && createPortal(
|
||||
<div className="toast-container">
|
||||
{toasts.map((t) => (
|
||||
<div key={t.id} className={'toast toast-' + t.type} onClick={() => dismiss(t.id)}>
|
||||
{t.message}
|
||||
</div>
|
||||
))}
|
||||
</div>,
|
||||
document.body
|
||||
)}
|
||||
</ToastContext.Provider>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user