Compare commits

..
3 Commits
Author SHA1 Message Date
wangairnan f16f583978 docs: 补充 README 界面功能、Safari 登录注意事项与前端架构
- 功能清单补「界面」条目:9 页面响应式 SPA 与三态主题
- 开发模式说明为何明文 HTTP 必须带 --dev(WebKit 无 Secure Cookie
  localhost 豁免)及生产 HTTPS 的自动加固行为
- 架构树展开 web/ 前端子目录(pages/components/lib)
2026-09-08 21:46:31 +08:00
wangairnan dda5ad1e5a fix(web): 登录表单补充隐藏用户名字段以兼容 Safari 密码管理器
Safari/WebKit 在明文 HTTP 下不保存 Secure Cookie(无 localhost 豁免,
Chrome/Firefox 有),__Host- 会话被静默丢弃导致登录成功后仍弹回登录页;
本机调试需以 --dev 启动(pn_session 无 Secure,loopback-only 守卫,§7.3-3)。
纯密码表单另令 Safari 保存密码弹窗要求手动输入用户名:补充 sr-only 用户名
输入(autoComplete=username,只读预填 admin),弹窗不再阻断登录。
新增 login.test.tsx 回归测试锁定用户名/密码字段的自动填充标记。
2026-09-08 21:42:52 +08:00
wangairnan 51f528f516 feat(web): 重构 9 页面界面并统一设计令牌与响应式布局
- index.css 以 Tailwind 4 @theme 落地设计令牌,全部页面按新设计稿重写
  样式:首页/笔记详情/标签页/登录/后台列表/编辑/回收站/设置/404
- Layout 重构导航与主题切换;新增 Toast 轻提示组件
- 移除 vite 手动 codeSplitting:分组 chunk 会被提升进入口静态依赖并对
  HTML 发出 modulepreload,lazy 路由的 CodeMirror 在所有页面被预加载
  (Lighthouse unused-javascript 549KiB 的根因)
- vite dev 代理补 changeOrigin:false,保留浏览器原始 Host,避免后端
  Origin 校验误判跨源 403
2026-09-08 21:41:05 +08:00
20 changed files with 3867 additions and 682 deletions
+6
View File
@@ -11,6 +11,7 @@
- **博客**:首页(置顶优先 + 分页 + 标签云)、详情(上一篇/下一篇)、标签页、RSS、sitemap、SEO meta 注入(仅公开内容) - **博客**:首页(置顶优先 + 分页 + 标签云)、详情(上一篇/下一篇)、标签页、RSS、sitemap、SEO meta 注入(仅公开内容)
- **管理**:单管理员口令登录(Argon2id)、会话 7 天滑动续期(CSRF 轮换保持不变)、防爆破限流(per-IP + per-账号)、改密 - **管理**:单管理员口令登录(Argon2id)、会话 7 天滑动续期(CSRF 轮换保持不变)、防爆破限流(per-IP + per-账号)、改密
- **回收站**:删除 = 软删除,30 天内可恢复,`gc` 到期物理清除 - **回收站**:删除 = 软删除,30 天内可恢复,`gc` 到期物理清除
- **界面**:9 页面响应式 SPA(React 19 + Tailwind 4),深色/浅色/跟随系统三态主题
- **运维**:`init` / `passwd`(重设口令并吊销全部会话)/ `start` / `backup`(在线一致快照)/ `gc`(默认 dry-run)/ `version`(亦可 `-v`) - **运维**:`init` / `passwd`(重设口令并吊销全部会话)/ `start` / `backup`(在线一致快照)/ `gc`(默认 dry-run)/ `version`(亦可 `-v`)
## 快速开始 ## 快速开始
@@ -39,6 +40,8 @@ make build
cd web && npm install && npm run dev # /api 代理到 127.0.0.1:8080 cd web && npm install && npm run dev # /api 代理到 127.0.0.1:8080
``` ```
> **为什么必须带 `--dev`**:明文 HTTP 下 Safari/WebKit 不保存 `Secure` Cookie(Chrome/Firefox 有 localhost 豁免,Safari 没有),不带 `--dev` 时 `__Host-` 会话被静默丢弃,Safari 登录成功后仍会被弹回登录页。`--dev` 改用无 `Secure` 的 `pn_session` Cookie 并强制仅监听 loopback(§7.3-3);生产走 HTTPS 不带 `--dev`,自动恢复 `__Host-` + `Secure` 完整加固。
忘记口令(CLI 可达即具备服务器权限,可直接重设;重设后全部会话被吊销): 忘记口令(CLI 可达即具备服务器权限,可直接重设;重设后全部会话被吊销):
```bash ```bash
@@ -87,6 +90,9 @@ internal/middleware/ 安全头 / 日志 / 限流 / Origin 校验 / MaxBytes
internal/httpapi/ 路由与 handler(公共 / 认证 / 管理 / feed) internal/httpapi/ 路由与 handler(公共 / 认证 / 管理 / feed)
internal/webui/ go:embed 前端产物 + SPA fallback + index.html meta 注入 internal/webui/ go:embed 前端产物 + SPA fallback + index.html meta 注入
web/ React 19 + Vite + Tailwind 4 前端 web/ React 19 + Vite + Tailwind 4 前端
├─ src/pages/ 9 页面:首页 / 笔记详情 / 标签页 / 登录 / 后台列表 / 编辑 / 回收站 / 设置 / 404
├─ src/components/ Layout(导航与主题切换)、Editor、MarkdownViewer、Toast
└─ src/lib/ api(CSRF 注入)/ auth(会话上下文)/ theme(三态主题)/ sanitize / invalidate
deploy/ systemd 单元 ×3 + Caddyfile deploy/ systemd 单元 ×3 + Caddyfile
``` ```
+3 -2
View File
@@ -20,7 +20,7 @@ const AdminEdit = lazy(() => import('./pages/AdminEdit'))
function RequireAuth({ children }: { children: ReactNode }) { function RequireAuth({ children }: { children: ReactNode }) {
const { authenticated, loading } = useAuth() const { authenticated, loading } = useAuth()
if (loading) { if (loading) {
return <div className="flex min-h-screen items-center justify-center text-zinc-500">加载中…</div> return <div className="pn-loading">加载中…</div>
} }
if (!authenticated) { if (!authenticated) {
return <Navigate to="/admin/login" replace /> return <Navigate to="/admin/login" replace />
@@ -30,11 +30,12 @@ function RequireAuth({ children }: { children: ReactNode }) {
export default function App() { export default function App() {
return ( return (
<Suspense fallback={<div className="flex min-h-screen items-center justify-center text-zinc-500">加载中…</div>}> <Suspense fallback={<div className="pn-loading">加载中…</div>}>
<Routes> <Routes>
<Route element={<BlogLayout />}> <Route element={<BlogLayout />}>
<Route path="/" element={<Home />} /> <Route path="/" element={<Home />} />
<Route path="/notes/:slug" element={<Note />} /> <Route path="/notes/:slug" element={<Note />} />
<Route path="/tags" element={<TagPage />} />
<Route path="/tags/:tag" element={<TagPage />} /> <Route path="/tags/:tag" element={<TagPage />} />
</Route> </Route>
<Route path="/admin/login" element={<Login />} /> <Route path="/admin/login" element={<Login />} />
+13 -6
View File
@@ -3,6 +3,7 @@ import CodeMirror from '@uiw/react-codemirror'
import { markdown, markdownLanguage } from '@codemirror/lang-markdown' import { markdown, markdownLanguage } from '@codemirror/lang-markdown'
import { EditorView } from '@codemirror/view' import { EditorView } from '@codemirror/view'
import { api, ApiError } from '../lib/api' import { api, ApiError } from '../lib/api'
import { useTheme } from '../lib/theme'
/** /**
* Editor(编辑态,§8.2):CodeMirror 6 源码编辑 + 图片粘贴/拖拽上传。 * Editor(编辑态,§8.2):CodeMirror 6 源码编辑 + 图片粘贴/拖拽上传。
@@ -22,6 +23,12 @@ async function uploadImage(file: File): Promise<UploadResult> {
return api<UploadResult>('/api/admin/images', { method: 'POST', body: form }) return api<UploadResult>('/api/admin/images', { method: 'POST', body: form })
} }
function isDarkMode(mode: 'light' | 'dark' | 'system'): boolean {
if (mode === 'dark') return true
if (mode === 'light') return false
return typeof window !== 'undefined' && window.matchMedia('(prefers-color-scheme: dark)').matches
}
export default function Editor({ export default function Editor({
value, value,
onChange, onChange,
@@ -35,6 +42,7 @@ export default function Editor({
}) { }) {
const viewRef = useRef<{ view?: EditorView } | null>(null) const viewRef = useRef<{ view?: EditorView } | null>(null)
const [dragOver, setDragOver] = useState(false) const [dragOver, setDragOver] = useState(false)
const { mode } = useTheme()
const extensions = useMemo( const extensions = useMemo(
() => [ () => [
@@ -81,9 +89,8 @@ export default function Editor({
return ( return (
<div <div
className={`relative h-full overflow-hidden rounded-lg border ${ className={dragOver ? 'pn-cm-drag' : undefined}
dragOver ? 'border-blue-500 bg-blue-50 dark:bg-blue-950' : 'border-zinc-200 dark:border-zinc-800' style={{ position: 'relative', height: '100%', overflow: 'hidden', borderRadius: 'var(--radius-sm)' }}
}`}
onDragOver={(e) => { onDragOver={(e) => {
e.preventDefault() e.preventDefault()
setDragOver(true) setDragOver(true)
@@ -100,9 +107,9 @@ export default function Editor({
onChange={onChange} onChange={onChange}
extensions={extensions} extensions={extensions}
basicSetup={{ lineNumbers: true, foldGutter: false, highlightActiveLine: true }} basicSetup={{ lineNumbers: true, foldGutter: false, highlightActiveLine: true }}
theme="light" theme={isDarkMode(mode) ? 'dark' : 'light'}
height="100%" height="100%"
style={{ height: '100%' }} style={{ height: '100%', minHeight: 420 }}
onCreateEditor={(view) => { onCreateEditor={(view) => {
viewRef.current = { view } viewRef.current = { view }
}} }}
@@ -115,7 +122,7 @@ export default function Editor({
}} }}
/> />
{dragOver && ( {dragOver && (
<div className="pointer-events-none absolute inset-0 flex items-center justify-center bg-blue-500/10 text-sm font-medium text-blue-600"> <div className="pn-cm-drag-overlay">
松开以上传图片(≤5MB) 松开以上传图片(≤5MB)
</div> </div>
)} )}
+128 -69
View File
@@ -1,101 +1,160 @@
import { Link, NavLink, Outlet } from 'react-router' import { Link, NavLink, Outlet, useLocation, useNavigate } from 'react-router'
import { Moon, Sun, Monitor } from 'lucide-react' import { Moon, Sun, Monitor, ExternalLink, House, PenLine, Trash2, Settings, LogOut } from 'lucide-react'
import { useSiteTitle } from '../features/site' import { useSiteTitle } from '../features/site'
import { useTheme } from '../lib/theme' import { useTheme } from '../lib/theme'
import { useAuth } from '../lib/auth'
export function SiteHeader() { /* ── 博客端:居中单栏 720px 布局(博客系列设计稿) ─────────── */
const { data } = useSiteTitle()
function ThemeButton() {
const { mode, setMode } = useTheme() const { mode, setMode } = useTheme()
return (
<header className="border-b border-zinc-200 dark:border-zinc-800">
<div className="mx-auto flex max-w-3xl items-center justify-between px-4 py-4">
<Link to="/" className="text-xl font-bold tracking-tight hover:opacity-80">
{data?.site_title ?? 'Pure Note'}
</Link>
<div className="flex items-center gap-1">
<ThemeButton mode={mode} setMode={setMode} />
</div>
</div>
</header>
)
}
function ThemeButton({
mode,
setMode,
}: {
mode: 'light' | 'dark' | 'system'
setMode: (m: 'light' | 'dark' | 'system') => void
}) {
const next = mode === 'light' ? 'dark' : mode === 'dark' ? 'system' : 'light' const next = mode === 'light' ? 'dark' : mode === 'dark' ? 'system' : 'light'
const title = `主题:${mode === 'light' ? '浅色' : mode === 'dark' ? '深色' : '跟随系统'}(点击切换)` const title = `主题:${mode === 'light' ? '浅色' : mode === 'dark' ? '深色' : '跟随系统'}(点击切换)`
return ( return (
<button <button
type="button" type="button"
className="pn-site-navlink"
title={title} title={title}
aria-label={title}
onClick={() => setMode(next)} onClick={() => setMode(next)}
className="rounded p-2 text-zinc-500 hover:bg-zinc-100 hover:text-zinc-900 dark:hover:bg-zinc-800 dark:hover:text-zinc-100"
> >
{mode === 'light' ? <Sun size={16} /> : mode === 'dark' ? <Moon size={16} /> : <Monitor size={16} />} {mode === 'light' ? <Sun size={14} /> : mode === 'dark' ? <Moon size={14} /> : <Monitor size={14} />}
</button> </button>
) )
} }
export function SiteFooter() {
return (
<footer className="mt-16 border-t border-zinc-200 py-8 text-center text-xs text-zinc-400 dark:border-zinc-800">
<a href="/feed.xml" className="hover:text-zinc-600">RSS</a>
<span className="mx-2">·</span>
<a href="/sitemap.xml" className="hover:text-zinc-600">Sitemap</a>
</footer>
)
}
export function BlogLayout() { export function BlogLayout() {
const { data } = useSiteTitle()
const title = data?.site_title ?? 'Pure Note'
return ( return (
<div className="min-h-screen"> <div className="pn-site-page">
<SiteHeader /> <header className="pn-site-header">
<main className="mx-auto max-w-3xl px-4 py-8"> <div className="pn-site-header-inner">
<Link to="/" className="pn-site-wordmark">{title}</Link>
<nav className="pn-site-nav" aria-label="站点导航">
<NavLink to="/" end className="pn-site-navlink hide-sm">首页</NavLink>
<NavLink to="/tags" className="pn-site-navlink hide-sm">标签</NavLink>
<NavLink to="/admin" className="pn-site-navlink">
<ExternalLink size={14} />管理
</NavLink>
<ThemeButton />
</nav>
</div>
</header>
<main className="pn-site-main">
<Outlet /> <Outlet />
</main> </main>
<SiteFooter /> <footer className="pn-site-footer">
<div className="pn-site-footer-inner">
© {new Date().getFullYear()} {title} · 纯文本驱动 · <a href="/feed.xml">RSS</a>
</div>
</footer>
</div> </div>
) )
} }
const adminLinks = [ /* ── 管理端:sidebar + topbar + 移动端 tabbar(dashboard 设计稿) ── */
{ to: '/admin', label: '笔记', end: true },
{ to: '/admin/trash', label: '回收站', end: true }, export function AdminTopbar({ title, children }: { title: string; children?: React.ReactNode }) {
{ to: '/admin/settings', label: '设置', end: true }, return (
<header className="pn-admin-topbar">
<h1>{title}</h1>
{children && <div className="pn-admin-actions">{children}</div>}
</header>
)
}
const adminNav = [
{ to: '/admin', label: '笔记管理', icon: House, end: true, match: 'exact' as const },
{ to: '/admin/notes/new', label: '新建笔记', icon: PenLine, end: false, match: 'prefix' as const },
{ to: '/admin/trash', label: '回收站', icon: Trash2, end: true, match: 'exact' as const },
{ to: '/admin/settings', label: '设置', icon: Settings, end: true, match: 'exact' as const },
] ]
function AdminSidebar() {
const { logout } = useAuth()
const navigate = useNavigate()
const location = useLocation()
// 新建/编辑共用「新建笔记」高亮(设计稿:编辑页高亮新建入口)
const editing = location.pathname.startsWith('/admin/notes')
return (
<aside className="pn-admin-sidebar">
<Link to="/admin" className="pn-admin-brand">
<span className="pn-admin-brand-mark">P</span>
<span className="pn-admin-brand-copy">
<span className="pn-admin-eyebrow">PURE NOTE</span>
<strong>管理后台</strong>
</span>
</Link>
<div className="pn-admin-section">内容</div>
<nav className="pn-admin-nav" aria-label="内容">
<NavLink to="/admin" end className="pn-admin-item">
<House size={15} /><span>笔记管理</span>
</NavLink>
<Link to="/admin/notes/new" className={`pn-admin-item${editing ? ' active' : ''}`} aria-current={editing ? 'page' : undefined}>
<PenLine size={15} /><span>新建笔记</span>
</Link>
</nav>
<div className="pn-admin-section">系统</div>
<nav className="pn-admin-nav" aria-label="系统">
<NavLink to="/admin/trash" className="pn-admin-item">
<Trash2 size={15} /><span>回收站</span>
</NavLink>
<NavLink to="/admin/settings" className="pn-admin-item">
<Settings size={15} /><span>设置</span>
</NavLink>
</nav>
<div className="pn-admin-foot">
<Link to="/" className="pn-admin-item">
<ExternalLink size={15} /><span>返回博客</span>
</Link>
<button
type="button"
className="pn-admin-item"
onClick={() => void logout().then(() => navigate('/'))}
>
<LogOut size={15} /><span>退出登录</span>
</button>
<div className="pn-admin-user">
<span className="pn-admin-avatar">管</span>
<span className="pn-admin-user-meta">
<span className="pn-admin-user-name">管理员</span>
<span className="pn-admin-user-role">站点所有者</span>
</span>
</div>
</div>
</aside>
)
}
function AdminTabbar() {
const location = useLocation()
const editing = location.pathname.startsWith('/admin/notes')
return (
<nav className="pn-admin-tabbar" aria-label="后台导航">
{adminNav.map(({ to, label, icon: Icon, match }) => {
const active = match === 'exact' ? location.pathname === to : editing
return (
<Link key={to} to={to} className={active ? 'is-active' : undefined} aria-current={active ? 'page' : undefined}>
<Icon size={18} /><span>{label === '笔记管理' ? '笔记' : label === '新建笔记' ? '新建' : label}</span>
</Link>
)
})}
</nav>
)
}
export function AdminLayout() { export function AdminLayout() {
return ( return (
<div className="min-h-screen"> <div className="pn-admin-shell">
<SiteHeader /> <AdminSidebar />
<div className="mx-auto max-w-5xl px-4"> <div className="pn-admin-main">
<nav className="flex gap-1 border-b border-zinc-200 py-2 dark:border-zinc-800"> <Outlet />
{adminLinks.map((l) => (
<NavLink
key={l.to}
to={l.to}
end={l.end}
className={({ isActive }) =>
`rounded px-3 py-1.5 text-sm ${
isActive
? 'bg-zinc-900 text-white dark:bg-zinc-100 dark:text-zinc-900'
: 'text-zinc-600 hover:bg-zinc-100 dark:text-zinc-400 dark:hover:bg-zinc-800'
}`
}
>
{l.label}
</NavLink>
))}
</nav>
<main className="py-6">
<Outlet />
</main>
</div> </div>
<AdminTabbar />
</div> </div>
) )
} }
+4 -3
View File
@@ -6,6 +6,7 @@ import { sanitizePlugin } from '../lib/sanitize'
/** /**
* MarkdownViewer:浏览态渲染管线(§8.2),组件边界独立、可整体替换。 * MarkdownViewer:浏览态渲染管线(§8.2),组件边界独立、可整体替换。
* 排版样式由 index.css 的 .pn-note-body 提供(设计稿正文排版契约)。
* *
* Markdown 原文 * Markdown 原文
* → remark-gfm(表格/任务列表/删除线/自动链接) * → remark-gfm(表格/任务列表/删除线/自动链接)
@@ -16,7 +17,7 @@ import { sanitizePlugin } from '../lib/sanitize'
*/ */
function CodeBlock(props: React.HTMLAttributes<HTMLPreElement>) { function CodeBlock(props: React.HTMLAttributes<HTMLPreElement>) {
return ( return (
<div className="group relative"> <div>
<pre {...props} /> <pre {...props} />
<CopyButton /> <CopyButton />
</div> </div>
@@ -28,7 +29,7 @@ function CopyButton() {
return ( return (
<button <button
type="button" type="button"
className="absolute right-2 top-2 rounded border border-zinc-300 bg-white px-2 py-0.5 text-xs opacity-0 transition group-hover:opacity-100 dark:border-zinc-700 dark:bg-zinc-900" className="pn-copy-btn"
onClick={(e) => { onClick={(e) => {
const pre = (e.currentTarget.parentElement as HTMLElement).querySelector('pre') const pre = (e.currentTarget.parentElement as HTMLElement).querySelector('pre')
if (pre) void navigator.clipboard.writeText(pre.textContent ?? '') if (pre) void navigator.clipboard.writeText(pre.textContent ?? '')
@@ -41,7 +42,7 @@ function CopyButton() {
const MarkdownViewer = memo(function MarkdownViewer({ source }: { source: string }) { const MarkdownViewer = memo(function MarkdownViewer({ source }: { source: string }) {
return ( return (
<div className="prose prose-zinc max-w-none dark:prose-invert prose-pre:bg-zinc-100 dark:prose-pre:bg-zinc-900"> <div className="pn-note-body">
<ReactMarkdown <ReactMarkdown
remarkPlugins={[remarkGfm]} remarkPlugins={[remarkGfm]}
rehypePlugins={[sanitizePlugin, rehypeHighlight]} rehypePlugins={[sanitizePlugin, rehypeHighlight]}
+30
View File
@@ -0,0 +1,30 @@
import { useEffect } from 'react'
import { CircleCheck, TriangleAlert } from 'lucide-react'
/**
* Toast:右下角操作反馈(设计稿 toast 契约)。
* message 为 null 时隐藏;展示 2.6s 后调用 onDone 清除。
*/
export default function Toast({
message,
kind = 'success',
onDone,
}: {
message: string | null
kind?: 'success' | 'error'
onDone: () => void
}) {
useEffect(() => {
if (!message) return
const t = setTimeout(onDone, 2600)
return () => clearTimeout(t)
}, [message, onDone])
if (!message) return null
return (
<div className={`pn-toast${kind === 'error' ? ' is-error' : ''}`} role="status">
{kind === 'error' ? <TriangleAlert size={16} /> : <CircleCheck size={16} />}
<span>{message}</span>
</div>
)
}
+15
View File
@@ -1,3 +1,4 @@
import { useEffect } from 'react'
import { useQuery } from '@tanstack/react-query' import { useQuery } from '@tanstack/react-query'
import { api } from '../lib/api' import { api } from '../lib/api'
import type { SiteSettings } from '../lib/api' import type { SiteSettings } from '../lib/api'
@@ -9,3 +10,17 @@ export function useSiteTitle() {
staleTime: 5 * 60_000, staleTime: 5 * 60_000,
}) })
} }
/**
* 设置浏览器标签页标题。
* - 生产环境首帧由服务端注入首页标题;SPA 路由切换后由此 hook 接管。
* - dev 环境 index.html 占位符 `{{.Title}}` 也依赖此 hook 替换。
* pageTitle 缺省时仅显示站点名。
*/
export function useDocumentTitle(pageTitle?: string) {
const { data } = useSiteTitle()
const siteName = data?.site_title ?? 'Pure Note'
useEffect(() => {
document.title = pageTitle ? `${pageTitle} · ${siteName}` : siteName
}, [pageTitle, siteName])
}
+2677 -7
View File
File diff suppressed because it is too large Load Diff
+18
View File
@@ -20,6 +20,24 @@ export function formatDateTime(unix: number): string {
}) })
} }
// 设计稿统一使用 YYYY-MM-DD 等宽日期
export function formatDateISO(unix: number): string {
const d = new Date(unix * 1000)
const p = (n: number) => String(n).padStart(2, '0')
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`
}
// 阅读时长估算:中文约 400 字/分钟
export function readingMinutes(content: string): number {
return Math.max(1, Math.round(content.length / 400))
}
// 回收站剩余保留天数(30 天保留期)
export function daysRemaining(deletedAt: number): number {
const elapsedDays = Math.floor((Date.now() / 1000 - deletedAt) / 86400)
return Math.max(0, 30 - elapsedDays)
}
// 前端 slug 预览:与服务端 slugify 同规则(ASCII 部分),纯非 ASCII 时提示将自动生成 // 前端 slug 预览:与服务端 slugify 同规则(ASCII 部分),纯非 ASCII 时提示将自动生成
export function slugPreview(title: string, date: Date): string { export function slugPreview(title: string, date: Date): string {
const t = title.trim().toLowerCase().replace(/_/g, '-').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').replace(/^-+|-+$/g, '') const t = title.trim().toLowerCase().replace(/_/g, '-').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').replace(/^-+|-+$/g, '')
+231 -149
View File
@@ -1,12 +1,18 @@
import { lazy, Suspense, useCallback, useEffect, useRef, useState } from 'react' import { lazy, Suspense, useEffect, useRef, useState } from 'react'
import { useNavigate, useParams } from 'react-router' import { useNavigate, useParams } from 'react-router'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { Bold, Italic, Link2, Code, Table, Eye, EyeOff } from 'lucide-react' import {
Bold, Calendar, CirclePlus, Code, Eye, EyeOff, Italic, Link2, List, Quote,
Save, Table, Trash2, X,
} from 'lucide-react'
import { api, ApiError } from '../lib/api' import { api, ApiError } from '../lib/api'
import type { NoteItem } from '../lib/api' import type { NoteItem } from '../lib/api'
import { invalidatePublic } from '../lib/invalidate' import { invalidatePublic } from '../lib/invalidate'
import { useDocumentTitle } from '../features/site'
import MarkdownViewer from '../components/MarkdownViewer' import MarkdownViewer from '../components/MarkdownViewer'
import { slugPreview } from '../lib/utils' import Toast from '../components/Toast'
import { AdminTopbar } from '../components/Layout'
import { formatDateISO, slugPreview } from '../lib/utils'
// CodeMirror 体积大,单独拆 chunk,编辑器在首帧后异步加载 // CodeMirror 体积大,单独拆 chunk,编辑器在首帧后异步加载
const Editor = lazy(() => import('../components/Editor')) const Editor = lazy(() => import('../components/Editor'))
@@ -23,7 +29,7 @@ type Form = {
summary: string summary: string
content: string content: string
status: 'public' | 'private' status: 'public' | 'private'
tags: string tags: string[]
pinned: boolean pinned: boolean
} }
@@ -33,7 +39,7 @@ const emptyForm: Form = {
summary: '', summary: '',
content: '', content: '',
status: 'private', status: 'private',
tags: '', tags: [],
pinned: false, pinned: false,
} }
@@ -41,6 +47,7 @@ export default function AdminEdit() {
const { id } = useParams() const { id } = useParams()
const noteId = id ? Number(id) : null const noteId = id ? Number(id) : null
const isNew = noteId === null const isNew = noteId === null
useDocumentTitle(isNew ? '新建笔记' : '编辑笔记')
const navigate = useNavigate() const navigate = useNavigate()
const qc = useQueryClient() const qc = useQueryClient()
@@ -54,8 +61,10 @@ export default function AdminEdit() {
const [savedAt, setSavedAt] = useState<number | null>(null) const [savedAt, setSavedAt] = useState<number | null>(null)
const [errorMsg, setErrorMsg] = useState<string | null>(null) const [errorMsg, setErrorMsg] = useState<string | null>(null)
const [slugFieldError, setSlugFieldError] = useState<string | null>(null) const [slugFieldError, setSlugFieldError] = useState<string | null>(null)
const [showPreview, setShowPreview] = useState(true) const [showPreview, setShowPreview] = useState(false)
const [uploadMsg, setUploadMsg] = useState<string | null>(null) const [uploadMsg, setUploadMsg] = useState<string | null>(null)
const [tagInput, setTagInput] = useState<string | null>(null)
const [toast, setToast] = useState<{ msg: string; kind: 'success' | 'error' } | null>(null)
const dirtyRef = useRef(false) const dirtyRef = useRef(false)
const slugTouchedRef = useRef(false) const slugTouchedRef = useRef(false)
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null) const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
@@ -68,7 +77,7 @@ export default function AdminEdit() {
summary: existing.summary, summary: existing.summary,
content: existing.content, content: existing.content,
status: existing.status === 'public' ? 'public' : 'private', status: existing.status === 'public' ? 'public' : 'private',
tags: existing.tags.join(', '), tags: existing.tags,
pinned: existing.pinned, pinned: existing.pinned,
}) })
slugTouchedRef.current = false slugTouchedRef.current = false
@@ -84,14 +93,15 @@ export default function AdminEdit() {
} }
const save = useMutation({ const save = useMutation({
mutationFn: async (f: Form) => { mutationFn: async (vars: { f: Form; auto: boolean }) => {
const { f } = vars
const payload = { const payload = {
title: f.title, title: f.title,
slug: f.slug, slug: f.slug,
summary: f.summary, summary: f.summary,
content: f.content, content: f.content,
status: f.status, status: f.status,
tags: f.tags.split(/[,,]/).map((t) => t.trim()).filter(Boolean), tags: f.tags,
pinned: f.pinned, pinned: f.pinned,
} }
if (isNew) { if (isNew) {
@@ -106,11 +116,12 @@ export default function AdminEdit() {
body: JSON.stringify(payload), body: JSON.stringify(payload),
}) })
}, },
onSuccess: (saved) => { onSuccess: (saved, vars) => {
setSavedAt(Date.now()) setSavedAt(Date.now())
setSlugFieldError(null) setSlugFieldError(null)
setErrorMsg(null) setErrorMsg(null)
dirtyRef.current = false dirtyRef.current = false
setToast({ msg: vars.auto ? '已自动保存' : '已保存', kind: 'success' })
// 仅失效列表与公共缓存;不失效当前编辑详情(['admin','note',id]), // 仅失效列表与公共缓存;不失效当前编辑详情(['admin','note',id]),
// 防 refetch 回滚保存期间继续输入的内容并抑制下一轮自动保存(评审 round2 P1-4) // 防 refetch 回滚保存期间继续输入的内容并抑制下一轮自动保存(评审 round2 P1-4)
void qc.invalidateQueries({ queryKey: ['admin', 'notes'] }) void qc.invalidateQueries({ queryKey: ['admin', 'notes'] })
@@ -120,6 +131,7 @@ export default function AdminEdit() {
} }
}, },
onError: (e) => { onError: (e) => {
setToast({ msg: '保存失败,请重试', kind: 'error' })
if (e instanceof ApiError && e.code === 'slug_conflict') { if (e instanceof ApiError && e.code === 'slug_conflict') {
setSlugFieldError(e.message) setSlugFieldError(e.message)
} else { } else {
@@ -128,6 +140,16 @@ export default function AdminEdit() {
}, },
}) })
const trashMutation = useMutation({
mutationFn: () => api(`/api/admin/notes/${noteId}`, { method: 'DELETE' }),
onSuccess: () => {
void qc.invalidateQueries({ queryKey: ['admin'] })
invalidatePublic(qc)
navigate('/admin')
},
onError: () => setToast({ msg: '操作失败,请重试', kind: 'error' }),
})
const canSave = form.title.trim().length > 0 const canSave = form.title.trim().length > 0
const autosaveReady = !isNew || form.content.trim().length > 0 const autosaveReady = !isNew || form.content.trim().length > 0
@@ -136,7 +158,9 @@ export default function AdminEdit() {
if (!canSave || !autosaveReady || !dirtyRef.current) return if (!canSave || !autosaveReady || !dirtyRef.current) return
if (timerRef.current) clearTimeout(timerRef.current) if (timerRef.current) clearTimeout(timerRef.current)
timerRef.current = setTimeout(() => { timerRef.current = setTimeout(() => {
if (dirtyRef.current) save.mutate(form) if (dirtyRef.current) {
save.mutate({ f: form, auto: true })
}
}, 2000) }, 2000)
return () => { return () => {
if (timerRef.current) clearTimeout(timerRef.current) if (timerRef.current) clearTimeout(timerRef.current)
@@ -144,162 +168,220 @@ export default function AdminEdit() {
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [form, canSave, autosaveReady]) }, [form, canSave, autosaveReady])
const wrapSelection = useCallback( const insert = (snippet: string) => set('content', form.content + snippet)
(before: string, after = before, placeholder = '文本') => {
const el = document.querySelector<HTMLElement>('.cm-content')
// 简化实现:在内容末尾/光标处理由 CodeMirror 自行接管,这里直接改源码
void el
set('content', form.content + `${before}${placeholder}${after}`)
},
[form.content],
)
if (!isNew && isLoading) { const addTag = () => {
return <p className="py-12 text-center text-zinc-400">加载中…</p> const t = (tagInput ?? '').trim()
if (t && !form.tags.includes(t)) {
set('tags', [...form.tags, t])
}
setTagInput(null)
} }
if (!isNew && isLoading) {
return (
<>
<AdminTopbar title="编辑笔记" />
<div className="pn-admin-content"><div className="table-card empty">加载中…</div></div>
</>
)
}
const slugDisplay = form.slug || (form.title ? slugPreview(form.title, new Date()) : '保存后自动生成')
return ( return (
<div className="flex h-[calc(100vh-8rem)] flex-col"> <>
<div className="mb-3 flex items-center gap-3"> <AdminTopbar title={isNew ? '新建笔记' : '编辑笔记'}>
<input
value={form.title}
onChange={(e) => set('title', e.target.value)}
placeholder="标题(必填)"
className="min-w-0 flex-1 rounded-lg border border-transparent bg-transparent px-2 py-1.5 text-xl font-semibold outline-none hover:border-zinc-200 focus:border-blue-500 dark:hover:border-zinc-800"
/>
<button <button
type="button" type="button"
className="btn ghost"
onClick={() => setShowPreview((v) => !v)} onClick={() => setShowPreview((v) => !v)}
className="inline-flex items-center gap-1 rounded-lg border border-zinc-300 px-2.5 py-1.5 text-xs text-zinc-600 dark:border-zinc-700 dark:text-zinc-400"
title="切换预览"
> >
{showPreview ? <EyeOff size={13} /> : <Eye size={13} />} {showPreview ? <EyeOff size={15} /> : <Eye size={15} />}
{showPreview ? '隐藏预览' : '显示预览'} <span>{showPreview ? '隐藏预览' : '预览'}</span>
</button> </button>
<button <button
type="button" type="button"
onClick={() => save.mutate(form)} className="btn primary"
disabled={!canSave || save.isPending} disabled={!canSave || save.isPending}
className="rounded-lg bg-zinc-900 px-4 py-1.5 text-sm font-medium text-white disabled:opacity-50 dark:bg-zinc-100 dark:text-zinc-900" onClick={() => save.mutate({ f: form, auto: false })}
> >
{save.isPending ? '保存中…' : '保存'} <Save size={15} />
<span>{save.isPending ? '保存中…' : isNew ? '保存草稿' : '保存'}</span>
</button> </button>
</div> </AdminTopbar>
<div className="mb-2 flex flex-wrap items-center gap-2 text-xs text-zinc-400"> <div className="pn-admin-content">
<button type="button" onClick={() => wrapSelection('**')} className="rounded p-1 hover:bg-zinc-100 dark:hover:bg-zinc-800"><Bold size={14} /></button> <div className="pn-ae-grid">
<button type="button" onClick={() => wrapSelection('*')} className="rounded p-1 hover:bg-zinc-100 dark:hover:bg-zinc-800"><Italic size={14} /></button> <article className="card pn-ae-editor">
<button type="button" onClick={() => set('content', form.content + '[标题](https://)')} className="rounded p-1 hover:bg-zinc-100 dark:hover:bg-zinc-800"><Link2 size={14} /></button> <input
<button type="button" onClick={() => set('content', form.content + '\n```\n代码\n```\n')} className="rounded p-1 hover:bg-zinc-100 dark:hover:bg-zinc-800"><Code size={14} /></button> className="pn-ae-title-input"
<button type="button" onClick={() => set('content', form.content + '\n| 列1 | 列2 |\n| --- | --- |\n| a | b |\n')} className="rounded p-1 hover:bg-zinc-100 dark:hover:bg-zinc-800"><Table size={14} /></button> type="text"
<span className="mx-1 text-zinc-300 dark:text-zinc-700">|</span> value={form.title}
<span>粘贴 / 拖拽图片即可上传</span> onChange={(e) => set('title', e.target.value)}
<span className="ml-auto"> placeholder="输入标题…"
{save.isPending aria-label="笔记标题"
? '保存中…' />
: savedAt
? `已保存 ${new Date(savedAt).toLocaleTimeString('zh-CN')}`
: isNew
? '未保存'
: '无改动'}
</span>
</div>
<div className="flex min-h-0 flex-1 gap-3"> <div className="pn-ae-meta">
<div className="flex min-w-0 flex-1 flex-col gap-3"> <span className="pn-ae-slug" title={`/notes/${slugDisplay}`}>
<div className="min-h-0 flex-1"> <Link2 size={12} />
<Suspense fallback={<div className="flex h-full items-center justify-center text-sm text-zinc-500">编辑器加载中…</div>}> <span>/notes/{slugDisplay}</span>
<Editor </span>
value={form.content} <div className="pn-ae-tags">
onChange={(v) => set('content', v)} {form.tags.map((t) => (
onUploadStart={(name) => setUploadMsg(`上传中:${name}…`)} <span key={t} className="pill pn-ae-tag">
onUploadEnd={(err) => setUploadMsg(err ?? null)} {t}
/> <button
</Suspense> type="button"
</div> className="pn-ae-tag-x"
{uploadMsg && <p className="text-xs text-zinc-400">{uploadMsg}</p>} aria-label={`移除标签:${t}`}
{showPreview && ( onClick={() => set('tags', form.tags.filter((x) => x !== t))}
<div className="hidden min-h-0 flex-1 overflow-auto rounded-lg border border-zinc-200 p-4 lg:block dark:border-zinc-800"> >
<MarkdownViewer source={form.content} /> <X size={12} />
</button>
</span>
))}
{tagInput === null ? (
<button type="button" className="btn ghost pn-ae-add-tag" onClick={() => setTagInput('')}>
<CirclePlus size={13} /><span>添加标签</span>
</button>
) : (
<input
className="pn-ae-tag-input"
autoFocus
value={tagInput}
placeholder="标签名"
aria-label="新标签名"
onChange={(e) => setTagInput(e.target.value)}
onBlur={addTag}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault()
addTag()
}
if (e.key === 'Escape') setTagInput(null)
}}
/>
)}
</div>
</div> </div>
)}
</div>
<aside className="w-64 shrink-0 space-y-4 overflow-auto rounded-lg border border-zinc-200 p-4 dark:border-zinc-800"> <div className="pn-ae-toolbar" role="toolbar" aria-label="格式工具">
<div> <button type="button" className="btn ghost pn-ae-tool" aria-label="加粗" title="加粗" onClick={() => insert('**文本**')}><Bold size={15} /></button>
<label className="text-xs font-medium text-zinc-500">slug</label> <button type="button" className="btn ghost pn-ae-tool" aria-label="斜体" title="斜体" onClick={() => insert('*文本*')}><Italic size={15} /></button>
<input <button type="button" className="btn ghost pn-ae-tool" aria-label="插入链接" title="插入链接" onClick={() => insert('[标题](https://)')}><Link2 size={15} /></button>
value={form.slug} <button type="button" className="btn ghost pn-ae-tool" aria-label="插入代码" title="插入代码" onClick={() => insert('\n```\n代码\n```\n')}><Code size={15} /></button>
onChange={(e) => set('slug', e.target.value)} <button type="button" className="btn ghost pn-ae-tool" aria-label="无序列表" title="无序列表" onClick={() => insert('\n- 列表项\n')}><List size={15} /></button>
placeholder={form.title ? slugPreview(form.title, new Date()) : '保存后自动生成'} <button type="button" className="btn ghost pn-ae-tool" aria-label="引用" title="引用" onClick={() => insert('\n> 引用\n')}><Quote size={15} /></button>
className={`mt-1 w-full rounded-md border px-2 py-1.5 font-mono text-xs outline-none ${ <button type="button" className="btn ghost pn-ae-tool" aria-label="插入表格" title="插入表格" onClick={() => insert('\n| 列1 | 列2 |\n| --- | --- |\n| a | b |\n')}><Table size={15} /></button>
slugFieldError <span className="pn-ae-tool-hint">纯文本 · Markdown</span>
? 'border-red-500 bg-red-50 dark:bg-red-950' </div>
: 'border-zinc-300 dark:border-zinc-700'
}`} <div className="pn-ae-body-wrap">
/> <Suspense fallback={<div className="table-card empty" style={{ minHeight: 420 }}>编辑器加载中…</div>}>
{slugFieldError && <p className="mt-1 text-xs text-red-600">{slugFieldError}</p>} <Editor
<p className="mt-1 text-[10px] leading-relaxed text-zinc-400"> value={form.content}
留空保持不变;首次保存自动生成后定稿 onChange={(v) => set('content', v)}
</p> onUploadStart={(name) => setUploadMsg(`上传中:${name}…`)}
</div> onUploadEnd={(err) => setUploadMsg(err ?? null)}
<div> />
<label className="text-xs font-medium text-zinc-500">标签(逗号分隔)</label> </Suspense>
<input </div>
value={form.tags} {uploadMsg && <p className="pn-ae-upload-msg">{uploadMsg}</p>}
onChange={(e) => set('tags', e.target.value)}
placeholder="随笔, go" {showPreview && (
className="mt-1 w-full rounded-md border border-zinc-300 px-2 py-1.5 text-xs outline-none focus:border-blue-500 dark:border-zinc-700" <div className="pn-ae-preview">
/> <MarkdownViewer source={form.content} />
</div> </div>
<div> )}
<label className="text-xs font-medium text-zinc-500">摘要(留空自动截取正文)</label> </article>
<textarea
value={form.summary} <aside className="pn-ae-side">
onChange={(e) => set('summary', e.target.value)} <section className="card pn-ae-publish">
rows={3} <span className="title">发布设置</span>
className="mt-1 w-full resize-none rounded-md border border-zinc-300 px-2 py-1.5 text-xs outline-none focus:border-blue-500 dark:border-zinc-700"
/> <div className="pn-ae-prow">
</div> <span className="pn-ae-plabel">状态</span>
<div className="flex items-center justify-between"> <span
<span className="text-xs font-medium text-zinc-500">公开</span> className={`pn-ae-pvalue pn-ae-mono ${form.status === 'public' ? '' : 'is-muted'}`}
<button style={form.status === 'public' ? { color: 'var(--success-text)' } : undefined}
type="button" >
role="switch" <span className="dot" />{form.status === 'public' ? '公开' : '私有'}
aria-checked={form.status === 'public'} </span>
onClick={() => set('status', form.status === 'public' ? 'private' : 'public')} <button
className={`relative h-5 w-9 rounded-full transition ${ type="button"
form.status === 'public' ? 'bg-green-500' : 'bg-zinc-300 dark:bg-zinc-700' role="switch"
}`} className="pn-switch"
> aria-checked={form.status === 'public'}
<span aria-label="公开笔记"
className={`absolute top-0.5 h-4 w-4 rounded-full bg-white transition-all ${ onClick={() => set('status', form.status === 'public' ? 'private' : 'public')}
form.status === 'public' ? 'left-[1.15rem]' : 'left-0.5' />
}`} </div>
/>
</button> <div className="pn-ae-prow">
</div> <span className="pn-ae-plabel">置顶</span>
<div className="flex items-center justify-between"> <button
<span className="text-xs font-medium text-zinc-500">置顶</span> type="button"
<button role="switch"
type="button" className="pn-switch"
role="switch" aria-checked={form.pinned}
aria-checked={form.pinned} aria-label="置顶笔记"
onClick={() => set('pinned', !form.pinned)} onClick={() => set('pinned', !form.pinned)}
className={`relative h-5 w-9 rounded-full transition ${ />
form.pinned ? 'bg-amber-500' : 'bg-zinc-300 dark:bg-zinc-700' </div>
}`}
> <div className="pn-ae-prow">
<span <span className="pn-ae-plabel">日期</span>
className={`absolute top-0.5 h-4 w-4 rounded-full bg-white transition-all ${ <span className="pn-ae-pvalue pn-ae-mono">
form.pinned ? 'left-[1.15rem]' : 'left-0.5' <Calendar size={14} />{formatDateISO(savedAt ? Math.floor(savedAt / 1000) : (existing?.updated_at ?? Math.floor(Date.now() / 1000)))}
}`} </span>
/> </div>
</button>
</div> <div className="pn-ae-pfield">
{errorMsg && <p className="text-xs text-red-600">{errorMsg}</p>} <label htmlFor="pn-ae-slug-input">固定链接</label>
</aside> <input
id="pn-ae-slug-input"
className={`pn-ae-input${slugFieldError ? ' is-error' : ''}`}
type="text"
value={form.slug}
spellCheck={false}
placeholder={form.title ? slugPreview(form.title, new Date()) : '保存后自动生成'}
onChange={(e) => set('slug', e.target.value)}
/>
<span className="pn-ae-phint">留空保持不变;首次保存自动生成后定稿</span>
{slugFieldError && <span className="pn-ae-error">{slugFieldError}</span>}
</div>
<div className="pn-ae-pfield">
<label htmlFor="pn-ae-summary">摘要</label>
<textarea
id="pn-ae-summary"
className="pn-ae-input pn-ae-textarea"
rows={3}
value={form.summary}
placeholder="留空自动截取正文"
onChange={(e) => set('summary', e.target.value)}
/>
</div>
{errorMsg && <p className="pn-ae-error">{errorMsg}</p>}
{!isNew && (
<>
<hr className="divider pn-ae-divider" />
<button type="button" className="pn-ae-danger" disabled={trashMutation.isPending} onClick={() => trashMutation.mutate()}>
<Trash2 size={15} />
<span>{trashMutation.isPending ? '删除中…' : '移至回收站'}</span>
</button>
</>
)}
</section>
</aside>
</div>
</div> </div>
</div>
<Toast message={toast?.msg ?? null} kind={toast?.kind} onDone={() => setToast(null)} />
</>
) )
} }
+205 -109
View File
@@ -1,12 +1,16 @@
import { Link, useNavigate } from 'react-router' import { Link } from 'react-router'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { Pencil, Plus, Trash2 } from 'lucide-react' import { CirclePlus, Eye, EyeOff, Pencil, Pin, Search, Trash2 } from 'lucide-react'
import { useState } from 'react' import { useMemo, useState } from 'react'
import { api } from '../lib/api' import { api } from '../lib/api'
import type { NoteItem } from '../lib/api' import type { NoteItem } from '../lib/api'
import { invalidatePublic } from '../lib/invalidate' import { invalidatePublic } from '../lib/invalidate'
import { useAuth } from '../lib/auth' import { useDocumentTitle } from '../features/site'
import { formatDateTime } from '../lib/utils' import { formatDateISO } from '../lib/utils'
import { AdminTopbar } from '../components/Layout'
import Toast from '../components/Toast'
type StatusFilter = 'all' | 'public' | 'private'
function useAdminNotes() { function useAdminNotes() {
return useQuery({ return useQuery({
@@ -16,19 +20,23 @@ function useAdminNotes() {
} }
export default function AdminList() { export default function AdminList() {
useDocumentTitle('笔记管理')
const { data, isLoading } = useAdminNotes() const { data, isLoading } = useAdminNotes()
const { logout } = useAuth()
const navigate = useNavigate()
const qc = useQueryClient() const qc = useQueryClient()
const [confirmId, setConfirmId] = useState<number | null>(null) const [confirmNote, setConfirmNote] = useState<NoteItem | null>(null)
const [filter, setFilter] = useState<StatusFilter>('all')
const [query, setQuery] = useState('')
const [toast, setToast] = useState<{ msg: string; kind: 'success' | 'error' } | null>(null)
const trashMutation = useMutation({ const trashMutation = useMutation({
mutationFn: (id: number) => api(`/api/admin/notes/${id}`, { method: 'DELETE' }), mutationFn: (id: number) => api(`/api/admin/notes/${id}`, { method: 'DELETE' }),
onSuccess: () => { onSuccess: () => {
setConfirmId(null) setConfirmNote(null)
setToast({ msg: '笔记已移至回收站', kind: 'success' })
void qc.invalidateQueries({ queryKey: ['admin'] }) void qc.invalidateQueries({ queryKey: ['admin'] })
invalidatePublic(qc) invalidatePublic(qc)
}, },
onError: () => setToast({ msg: '操作失败,请重试', kind: 'error' }),
}) })
const toggleStatus = useMutation({ const toggleStatus = useMutation({
@@ -48,117 +56,205 @@ export default function AdminList() {
}), }),
}) })
}, },
onSuccess: () => { onSuccess: (_d, note) => {
setToast({ msg: note.status === 'public' ? '已转为私有' : '已转为公开', kind: 'success' })
void qc.invalidateQueries({ queryKey: ['admin'] }) void qc.invalidateQueries({ queryKey: ['admin'] })
invalidatePublic(qc) invalidatePublic(qc)
}, },
onError: () => setToast({ msg: '操作失败,请重试', kind: 'error' }),
}) })
const items = data?.items ?? []
const publicCount = items.filter((n) => n.status === 'public').length
const privateCount = items.length - publicCount
const visible = useMemo(() => {
const q = query.trim().toLowerCase()
return items.filter((n) => {
if (filter === 'public' && n.status !== 'public') return false
if (filter === 'private' && n.status === 'public') return false
if (q) {
const hay = `${n.title} ${n.slug} ${n.tags.join(' ')}`.toLowerCase()
if (!hay.includes(q)) return false
}
return true
})
}, [items, filter, query])
return ( return (
<div> <>
<div className="mb-4 flex items-center justify-between"> <AdminTopbar title="笔记管理">
<h1 className="text-lg font-semibold">笔记管理({data?.total ?? 0})</h1> <label className="pn-admin-search">
<div className="flex gap-2"> <Search size={14} aria-hidden />
<Link <input
to="/admin/notes/new" type="search"
className="inline-flex items-center gap-1 rounded-lg bg-zinc-900 px-3 py-1.5 text-sm font-medium text-white hover:bg-zinc-800 dark:bg-zinc-100 dark:text-zinc-900 dark:hover:bg-zinc-200" placeholder="搜索笔记…"
> aria-label="搜索笔记"
<Plus size={15} /> 新建 value={query}
</Link> onChange={(e) => setQuery(e.target.value)}
<button />
type="button" </label>
onClick={() => void logout().then(() => navigate('/'))} <Link to="/admin/notes/new" className="btn primary">
className="rounded-lg border border-zinc-300 px-3 py-1.5 text-sm text-zinc-600 hover:bg-zinc-50 dark:border-zinc-700 dark:text-zinc-400 dark:hover:bg-zinc-800" <CirclePlus size={15} />
> <span>新建笔记</span>
登出 </Link>
</button> </AdminTopbar>
</div>
<div className="pn-admin-content">
<section className="pn-al-metrics">
<article className="card metric">
<span className="eyebrow">笔记</span>
<strong className="value">{data?.total ?? items.length}</strong>
<span className="meta">全部笔记,含 {privateCount} 篇私有</span>
</article>
<article className="card metric">
<span className="eyebrow">已发布</span>
<strong className="value">{publicCount}</strong>
<span className="meta">对外公开的笔记</span>
</article>
<article className="card metric">
<span className="eyebrow">私有</span>
<strong className="value">{privateCount}</strong>
<span className="meta">尚未公开,仅自己可见</span>
</article>
</section>
<section className="table-card pn-al-table-card">
<div className="pn-al-table-head">
<nav className="tabs" aria-label="笔记筛选">
<button type="button" className={filter === 'all' ? 'active' : undefined} onClick={() => setFilter('all')}>
全部<span className="pn-al-tab-num">{items.length}</span>
</button>
<button type="button" className={filter === 'public' ? 'active' : undefined} onClick={() => setFilter('public')}>
已发布<span className="pn-al-tab-num">{publicCount}</span>
</button>
<button type="button" className={filter === 'private' ? 'active' : undefined} onClick={() => setFilter('private')}>
私有<span className="pn-al-tab-num">{privateCount}</span>
</button>
</nav>
<span className="pn-al-table-note">共 {visible.length} 篇笔记</span>
</div>
{isLoading ? (
<div className="empty">加载中…</div>
) : visible.length === 0 ? (
<div className="empty">
{items.length === 0 ? '还没有笔记,点击「新建笔记」开始' : '没有符合筛选条件的笔记'}
</div>
) : (
<div className="pn-table-scroll">
<table className="table" aria-label="笔记列表">
<thead>
<tr>
<th>标题</th>
<th>标签</th>
<th>日期</th>
<th>状态</th>
<th className="pn-al-col-actions">操作</th>
</tr>
</thead>
<tbody>
{visible.map((n) => {
const isPublic = n.status === 'public'
return (
<tr key={n.id} className={isPublic ? undefined : 'pn-al-is-draft'}>
<td>
<Link to={`/admin/notes/${n.id}/edit`} className="pn-al-note-title" style={{ textDecoration: 'none' }}>
{n.pinned && <Pin size={12} aria-label="置顶" />}
<span>{n.title}</span>
</Link>
<span className="pn-al-note-slug">/{n.slug}</span>
</td>
<td>
{n.tags.length > 0 ? (
<div className="pn-al-tags">
{n.tags.map((t) => <span key={t} className="pn-al-tag">{t}</span>)}
</div>
) : (
<span className="pn-al-note-slug">—</span>
)}
</td>
<td><span className="pn-al-date">{formatDateISO(n.updated_at)}</span></td>
<td>
<span className={`pn-al-status ${isPublic ? 'pn-al-is-public' : 'pn-al-is-draft'}`}>
<span className="dot" />{isPublic ? '已发布' : '私有'}
</span>
</td>
<td>
<div className="pn-al-actions-cell">
<button
type="button"
className="btn ghost pn-icon-btn"
title={isPublic ? '转为私有' : '转为公开'}
aria-label={isPublic ? '转为私有' : '转为公开'}
disabled={toggleStatus.isPending}
onClick={() => void toggleStatus.mutate(n)}
>
{isPublic ? <EyeOff size={15} /> : <Eye size={15} />}
</button>
<Link
to={`/admin/notes/${n.id}/edit`}
className="btn ghost pn-icon-btn"
title="编辑"
aria-label={`编辑笔记:${n.title}`}
>
<Pencil size={15} />
</Link>
<button
type="button"
className="btn ghost pn-icon-btn danger"
title="移至回收站"
aria-label={`移至回收站:${n.title}`}
onClick={() => setConfirmNote(n)}
>
<Trash2 size={15} />
</button>
</div>
</td>
</tr>
)
})}
</tbody>
</table>
</div>
)}
<div className="pn-al-table-foot">
<span className="pn-al-foot-note">共 {data?.total ?? 0} 篇 · 显示 {visible.length} 篇</span>
</div>
</section>
</div> </div>
{isLoading ? ( {confirmNote && (
<p className="py-12 text-center text-zinc-400">加载中…</p> <div
) : !data || data.items.length === 0 ? ( className="pn-modal-overlay"
<p className="py-12 text-center text-zinc-400">还没有笔记,点击「新建」开始</p> role="dialog"
) : ( aria-modal="true"
<ul className="divide-y divide-zinc-100 rounded-lg border border-zinc-200 dark:divide-zinc-900 dark:border-zinc-800"> aria-label="移入回收站"
{data.items.map((n) => ( onClick={(e) => {
<li key={n.id} className="flex items-center gap-3 px-4 py-3"> if (e.target === e.currentTarget) setConfirmNote(null)
<span }}
className={`rounded px-1.5 py-0.5 text-xs ${ >
n.status === 'public' <div className="card pn-modal">
? 'bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-400' <h3>移入回收站?</h3>
: 'bg-zinc-100 text-zinc-500 dark:bg-zinc-800 dark:text-zinc-400' <p>「{confirmNote.title}」将被软删除,30 天内可在回收站恢复。</p>
}`} {trashMutation.isError && <p style={{ color: 'var(--destructive-text)' }}>操作失败,请重试</p>}
> <div className="pn-modal-actions">
{n.status === 'public' ? '公开' : '私有'} <button type="button" className="btn secondary" onClick={() => setConfirmNote(null)}>取消</button>
</span>
{n.pinned && <span className="text-xs text-amber-600">置顶</span>}
<div className="min-w-0 flex-1">
<Link to={`/admin/notes/${n.id}/edit`} className="block truncate font-medium hover:text-blue-600">
{n.title}
</Link>
<p className="truncate text-xs text-zinc-400">
/{n.slug} · {formatDateTime(n.updated_at)}
{n.tags.length > 0 && ' · ' + n.tags.map((t) => '#' + t).join(' ')}
</p>
</div>
<button <button
type="button" type="button"
onClick={() => void toggleStatus.mutate(n)} className="btn danger"
disabled={toggleStatus.isPending} disabled={trashMutation.isPending}
className="rounded px-2 py-1 text-xs text-zinc-500 hover:bg-zinc-100 disabled:opacity-50 dark:hover:bg-zinc-800" onClick={() => trashMutation.mutate(confirmNote.id)}
> >
{n.status === 'public' ? '转私有' : '转公开'} {trashMutation.isPending ? '删除中…' : '确认删除'}
</button> </button>
<Link </div>
to={`/admin/notes/${n.id}/edit`} </div>
className="rounded p-1.5 text-zinc-500 hover:bg-zinc-100 dark:hover:bg-zinc-800" </div>
title="编辑"
>
<Pencil size={15} />
</Link>
<button
type="button"
onClick={() => setConfirmId(n.id)}
className="rounded p-1.5 text-red-500 hover:bg-red-50 dark:hover:bg-red-950"
title="删除(进回收站)"
>
<Trash2 size={15} />
</button>
{confirmId === n.id && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 px-4">
<div className="w-full max-w-sm rounded-xl bg-white p-6 dark:bg-zinc-900">
<h3 className="font-semibold">移入回收站?</h3>
<p className="mt-1 text-sm text-zinc-500">
「{n.title}」将被软删除,30 天内可在回收站恢复。
</p>
{trashMutation.isError && (
<p className="mt-2 text-sm text-red-600">操作失败,请重试</p>
)}
<div className="mt-4 flex justify-end gap-2">
<button
type="button"
onClick={() => setConfirmId(null)}
className="rounded-lg border border-zinc-300 px-3 py-1.5 text-sm dark:border-zinc-700"
>
取消
</button>
<button
type="button"
onClick={() => trashMutation.mutate(n.id)}
disabled={trashMutation.isPending}
className="rounded-lg bg-red-600 px-3 py-1.5 text-sm text-white hover:bg-red-700 disabled:opacity-50"
>
{trashMutation.isPending ? '删除中…' : '确认删除'}
</button>
</div>
</div>
</div>
)}
</li>
))}
</ul>
)} )}
</div>
<Toast message={toast?.msg ?? null} kind={toast?.kind} onDone={() => setToast(null)} />
</>
) )
} }
+143 -94
View File
@@ -1,10 +1,15 @@
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { Eye, EyeOff, KeyRound, Lock, Save } from 'lucide-react'
import { api, ApiError } from '../lib/api' import { api, ApiError } from '../lib/api'
import type { SiteSettings } from '../lib/api' import type { SiteSettings } from '../lib/api'
import { invalidatePublic } from '../lib/invalidate' import { invalidatePublic } from '../lib/invalidate'
import { useDocumentTitle } from '../features/site'
import { AdminTopbar } from '../components/Layout'
import Toast from '../components/Toast'
export default function AdminSettings() { export default function AdminSettings() {
useDocumentTitle('设置')
const qc = useQueryClient() const qc = useQueryClient()
const { data } = useQuery({ const { data } = useQuery({
queryKey: ['admin', 'settings'], queryKey: ['admin', 'settings'],
@@ -14,7 +19,7 @@ export default function AdminSettings() {
const [title, setTitle] = useState('') const [title, setTitle] = useState('')
const [desc, setDesc] = useState('') const [desc, setDesc] = useState('')
const [pageSize, setPageSize] = useState(10) const [pageSize, setPageSize] = useState(10)
const [msg, setMsg] = useState<string | null>(null) const [toast, setToast] = useState<{ msg: string; kind: 'success' | 'error' } | null>(null)
useEffect(() => { useEffect(() => {
if (data) { if (data) {
@@ -31,73 +36,89 @@ export default function AdminSettings() {
body: JSON.stringify({ site_title: title, site_desc: desc, page_size: pageSize }), body: JSON.stringify({ site_title: title, site_desc: desc, page_size: pageSize }),
}), }),
onSuccess: () => { onSuccess: () => {
setMsg('已保存') setToast({ msg: '设置已保存', kind: 'success' })
void qc.invalidateQueries({ queryKey: ['site'] }) void qc.invalidateQueries({ queryKey: ['site'] })
invalidatePublic(qc) // page_size 等设置影响公共列表 invalidatePublic(qc) // page_size 等设置影响公共列表
}, },
onError: (e) => setMsg(e instanceof ApiError ? e.message : '保存失败'), onError: (e) => setToast({ msg: e instanceof ApiError ? e.message : '保存失败', kind: 'error' }),
}) })
return ( return (
<div className="max-w-lg space-y-10"> <>
<section> <AdminTopbar title="站点设置" />
<h1 className="mb-4 text-lg font-semibold">站点设置</h1>
<div className="space-y-4">
<div>
<label className="text-xs font-medium text-zinc-500" htmlFor="site-title">站点标题</label>
<input
id="site-title"
value={title}
onChange={(e) => setTitle(e.target.value)}
className="mt-1 w-full rounded-lg border border-zinc-300 bg-transparent px-3 py-2 text-sm outline-none focus:border-blue-500 dark:border-zinc-700"
/>
</div>
<div>
<label className="text-xs font-medium text-zinc-500" htmlFor="site-desc">副标题 / 描述</label>
<textarea
id="site-desc"
value={desc}
onChange={(e) => setDesc(e.target.value)}
rows={2}
className="mt-1 w-full resize-none rounded-lg border border-zinc-300 bg-transparent px-3 py-2 text-sm outline-none focus:border-blue-500 dark:border-zinc-700"
/>
</div>
<div>
<label className="text-xs font-medium text-zinc-500" htmlFor="page-size">首页每页条数(1–100)</label>
<input
id="page-size"
type="number"
min={1}
max={100}
value={pageSize}
onChange={(e) => setPageSize(Number(e.target.value))}
className="mt-1 w-28 rounded-lg border border-zinc-300 bg-transparent px-3 py-2 text-sm outline-none focus:border-blue-500 dark:border-zinc-700"
/>
</div>
<div className="flex items-center gap-3">
<button
type="button"
onClick={() => saveSettings.mutate()}
disabled={saveSettings.isPending}
className="rounded-lg bg-zinc-900 px-4 py-1.5 text-sm font-medium text-white disabled:opacity-50 dark:bg-zinc-100 dark:text-zinc-900"
>
{saveSettings.isPending ? '保存中…' : '保存设置'}
</button>
{msg && <span className="text-sm text-zinc-500">{msg}</span>}
</div>
</div>
</section>
<ChangePassword /> <div className="pn-admin-content pn-as-content">
</div> <section className="card pn-as-card">
<div className="pn-as-card-head">
<h2 className="title">站点信息</h2>
<p className="meta">这些信息会显示在博客的公开页面</p>
</div>
<hr className="divider" />
<div className="pn-as-fields">
<div className="pn-as-field">
<label className="pn-as-label" htmlFor="site-title">站点名称</label>
<input
id="site-title"
className="pn-as-input"
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
</div>
<div className="pn-as-field">
<label className="pn-as-label" htmlFor="site-desc">站点描述</label>
<textarea
id="site-desc"
className="pn-as-input"
rows={3}
value={desc}
onChange={(e) => setDesc(e.target.value)}
/>
</div>
<div className="pn-as-field">
<label className="pn-as-label" htmlFor="page-size">首页每页条数(1–100)</label>
<input
id="page-size"
className="pn-as-input"
type="number"
min={1}
max={100}
style={{ width: 140 }}
value={pageSize}
onChange={(e) => setPageSize(Number(e.target.value))}
/>
</div>
</div>
</section>
<ChangePassword onToast={setToast} />
<div className="pn-as-save-bar">
<span className="pn-as-save-hint">更改将在保存后应用到公开站点</span>
<button
type="button"
className="btn primary"
disabled={saveSettings.isPending}
onClick={() => saveSettings.mutate()}
>
<Save size={15} />
{saveSettings.isPending ? '保存中…' : '保存更改'}
</button>
</div>
</div>
<Toast message={toast?.msg ?? null} kind={toast?.kind} onDone={() => setToast(null)} />
</>
) )
} }
function ChangePassword() { function ChangePassword({
onToast,
}: {
onToast: (t: { msg: string; kind: 'success' | 'error' } | null) => void
}) {
const [oldPw, setOldPw] = useState('') const [oldPw, setOldPw] = useState('')
const [newPw, setNewPw] = useState('') const [newPw, setNewPw] = useState('')
const [msg, setMsg] = useState<string | null>(null) const [showPw, setShowPw] = useState(false)
const [ok, setOk] = useState(false)
const change = useMutation({ const change = useMutation({
mutationFn: () => mutationFn: () =>
@@ -106,57 +127,85 @@ function ChangePassword() {
body: JSON.stringify({ old_password: oldPw, new_password: newPw }), body: JSON.stringify({ old_password: oldPw, new_password: newPw }),
}), }),
onSuccess: () => { onSuccess: () => {
setOk(true) onToast({ msg: '密码已修改', kind: 'success' })
setMsg('密码已修改')
setOldPw('') setOldPw('')
setNewPw('') setNewPw('')
}, },
onError: (e) => { onError: (e) => {
setOk(false)
if (e instanceof ApiError) { if (e instanceof ApiError) {
setMsg(e.code === 'weak_password' ? '新密码长度至少 12 个字符' : e.status === 429 ? '尝试过于频繁,请稍后再试' : '旧密码不正确') onToast({
msg:
e.code === 'weak_password'
? '新密码长度至少 12 个字符'
: e.status === 429
? '尝试过于频繁,请稍后再试'
: '旧密码不正确',
kind: 'error',
})
} else { } else {
setMsg('修改失败') onToast({ msg: '修改失败', kind: 'error' })
} }
}, },
}) })
return ( return (
<section> <section className="card pn-as-card">
<h2 className="mb-4 text-lg font-semibold">修改密码</h2> <div className="pn-as-card-head">
<div className="space-y-4"> <h2 className="title">修改密码</h2>
<div> <p className="meta">更新管理后台的登录密码</p>
<label className="text-xs font-medium text-zinc-500" htmlFor="old-pw">旧密码</label> </div>
<input <hr className="divider" />
id="old-pw" <div className="pn-as-fields">
type="password" <div className="pn-as-field">
value={oldPw} <label className="pn-as-label" htmlFor="old-pw">旧密码</label>
onChange={(e) => setOldPw(e.target.value)} <div className="pn-as-control">
className="mt-1 w-full rounded-lg border border-zinc-300 bg-transparent px-3 py-2 text-sm outline-none focus:border-blue-500 dark:border-zinc-700" <Lock size={15} className="pn-as-leading-icon" aria-hidden />
/> <input
id="old-pw"
className="pn-as-input"
type={showPw ? 'text' : 'password'}
autoComplete="current-password"
value={oldPw}
onChange={(e) => setOldPw(e.target.value)}
/>
</div>
</div> </div>
<div> <div className="pn-as-field">
<label className="text-xs font-medium text-zinc-500" htmlFor="new-pw">新密码(≥12 字符)</label> <label className="pn-as-label" htmlFor="new-pw">新密码(≥12 字符)</label>
<input <div className="pn-as-control has-toggle">
id="new-pw" <Lock size={15} className="pn-as-leading-icon" aria-hidden />
type="password" <input
value={newPw} id="new-pw"
onChange={(e) => setNewPw(e.target.value)} className="pn-as-input"
className="mt-1 w-full rounded-lg border border-zinc-300 bg-transparent px-3 py-2 text-sm outline-none focus:border-blue-500 dark:border-zinc-700" type={showPw ? 'text' : 'password'}
/> autoComplete="new-password"
</div> placeholder="请输入新密码,至少 12 个字符"
<div className="flex items-center gap-3"> value={newPw}
<button onChange={(e) => setNewPw(e.target.value)}
type="button" />
onClick={() => change.mutate()} <button
disabled={change.isPending || oldPw.length === 0 || newPw.length === 0} type="button"
className="rounded-lg bg-zinc-900 px-4 py-1.5 text-sm font-medium text-white disabled:opacity-50 dark:bg-zinc-100 dark:text-zinc-900" className="pn-as-eye"
> aria-label={showPw ? '隐藏密码' : '显示密码'}
{change.isPending ? '提交中…' : '修改密码'} onClick={() => setShowPw((v) => !v)}
</button> >
{msg && <span className={`text-sm ${ok ? 'text-green-600' : 'text-red-600'}`}>{msg}</span>} {showPw ? <EyeOff size={15} /> : <Eye size={15} />}
</button>
</div>
<p className="pn-as-hint">新密码长度至少 12 个字符,建议混合字母、数字与符号。</p>
</div> </div>
</div> </div>
<div className="pn-as-card-foot">
<button
type="button"
className="btn secondary"
disabled={change.isPending || oldPw.length === 0 || newPw.length === 0}
onClick={() => change.mutate()}
>
<KeyRound size={15} />
{change.isPending ? '提交中…' : '修改密码'}
</button>
</div>
</section> </section>
) )
} }
+81 -37
View File
@@ -1,12 +1,18 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { RotateCcw } from 'lucide-react' import { Info, RotateCcw } from 'lucide-react'
import { useState } from 'react'
import { api } from '../lib/api' import { api } from '../lib/api'
import type { NoteItem } from '../lib/api' import type { NoteItem } from '../lib/api'
import { invalidatePublic } from '../lib/invalidate' import { invalidatePublic } from '../lib/invalidate'
import { formatDateTime } from '../lib/utils' import { useDocumentTitle } from '../features/site'
import { daysRemaining, formatDateISO } from '../lib/utils'
import { AdminTopbar } from '../components/Layout'
import Toast from '../components/Toast'
export default function AdminTrash() { export default function AdminTrash() {
useDocumentTitle('回收站')
const qc = useQueryClient() const qc = useQueryClient()
const [toast, setToast] = useState<{ msg: string; kind: 'success' | 'error' } | null>(null)
const { data, isLoading } = useQuery({ const { data, isLoading } = useQuery({
queryKey: ['admin', 'trash'], queryKey: ['admin', 'trash'],
queryFn: () => api<{ items: NoteItem[]; total: number }>('/api/admin/trash'), queryFn: () => api<{ items: NoteItem[]; total: number }>('/api/admin/trash'),
@@ -15,45 +21,83 @@ export default function AdminTrash() {
const restore = useMutation({ const restore = useMutation({
mutationFn: (id: number) => api(`/api/admin/trash/${id}/restore`, { method: 'POST' }), mutationFn: (id: number) => api(`/api/admin/trash/${id}/restore`, { method: 'POST' }),
onSuccess: () => { onSuccess: () => {
setToast({ msg: '笔记已恢复', kind: 'success' })
void qc.invalidateQueries({ queryKey: ['admin'] }) void qc.invalidateQueries({ queryKey: ['admin'] })
invalidatePublic(qc) invalidatePublic(qc)
}, },
onError: () => setToast({ msg: '恢复失败,请重试', kind: 'error' }),
}) })
const items = data?.items ?? []
return ( return (
<div> <>
<h1 className="mb-4 text-lg font-semibold">回收站({data?.total ?? 0})</h1> <AdminTopbar title="回收站" />
<p className="mb-4 text-sm text-zinc-400">软删除的笔记保留 30 天,到期由每日 gc 物理清除;恢复后图片引用天然保全。</p>
{isLoading ? ( <div className="pn-admin-content">
<p className="py-12 text-center text-zinc-400">加载中…</p> <div className="pn-at-alert" role="note">
) : !data || data.items.length === 0 ? ( <Info size={16} />
<p className="py-12 text-center text-zinc-400">回收站是空的</p> <p>回收站中的笔记会在删除 30 天后永久删除,请及时恢复需要的内容。</p>
) : ( </div>
<ul className="divide-y divide-zinc-100 rounded-lg border border-zinc-200 dark:divide-zinc-900 dark:border-zinc-800">
{data.items.map((n) => ( <section className="table-card pn-at-table-card">
<li key={n.id} className="flex items-center gap-3 px-4 py-3"> {isLoading ? (
<span className="rounded bg-zinc-100 px-1.5 py-0.5 text-xs text-zinc-500 dark:bg-zinc-800"> <div className="empty">加载中…</div>
{n.status === 'public' ? '公开' : '私有'} ) : items.length === 0 ? (
</span> <div className="empty">回收站是空的</div>
<div className="min-w-0 flex-1"> ) : (
<p className="truncate font-medium">{n.title}</p> <div className="pn-table-scroll">
<p className="truncate text-xs text-zinc-400"> <table className="table" aria-label="回收站笔记列表">
/{n.slug} · 删除于 {formatDateTime(n.deleted_at ?? 0)} <thead>
</p> <tr>
</div> <th>标题</th>
<button <th>删除时间</th>
type="button" <th>剩余天数</th>
onClick={() => restore.mutate(n.id)} <th className="pn-al-col-actions">操作</th>
disabled={restore.isPending} </tr>
className="inline-flex items-center gap-1 rounded px-2 py-1 text-xs text-zinc-600 hover:bg-zinc-100 disabled:opacity-50 dark:text-zinc-400 dark:hover:bg-zinc-800" </thead>
> <tbody>
<RotateCcw size={13} /> 恢复 {items.map((n) => {
</button> const left = n.deleted_at ? daysRemaining(n.deleted_at) : 0
</li> return (
))} <tr key={n.id}>
</ul> <td className="pn-at-title-cell">
)} <span className="pn-at-note-title">{n.title}</span>
{restore.isError && <p className="mt-3 text-sm text-red-600">恢复失败,请重试</p>} <span className="pn-at-note-slug">/{n.slug}</span>
</div> </td>
<td>
<span className="pn-at-mono">{n.deleted_at ? formatDateISO(n.deleted_at) : '—'}</span>
</td>
<td>
<span className={`pn-at-days${left <= 3 ? ' pn-at-days-urgent' : ''}`}>{left} 天</span>
</td>
<td>
<div className="pn-at-actions">
<button
type="button"
className="btn ghost"
disabled={restore.isPending}
onClick={() => restore.mutate(n.id)}
>
<RotateCcw size={14} />恢复
</button>
</div>
</td>
</tr>
)
})}
</tbody>
</table>
</div>
)}
<div className="pn-al-table-foot">
<span className="pn-al-foot-note">共 {data?.total ?? 0} 篇已删除笔记</span>
</div>
</section>
</div>
<Toast message={toast?.msg ?? null} kind={toast?.kind} onDone={() => setToast(null)} />
</>
) )
} }
+79 -78
View File
@@ -1,18 +1,17 @@
import { useState } from 'react' import { useState } from 'react'
import { Link } from 'react-router' import { Link } from 'react-router'
import { useQuery } from '@tanstack/react-query' import { useQuery } from '@tanstack/react-query'
import { Pin } from 'lucide-react' import { ArrowRight, ChevronLeft, ChevronRight, Pin } from 'lucide-react'
import { api } from '../lib/api' import { api } from '../lib/api'
import type { NoteItem, NoteList, TagCount } from '../lib/api' import type { NoteItem, NoteList, TagCount } from '../lib/api'
import { formatDate } from '../lib/utils' import { useDocumentTitle } from '../features/site'
import { formatDateISO } from '../lib/utils'
function useNotes(page: number, tag?: string) { function useNotes(page: number) {
// 不传 page_size:服务端默认值即站点设置(管理员可改),首页随设置生效 // 不传 page_size:服务端默认值即站点设置(管理员可改),首页随设置生效
const qs = new URLSearchParams({ page: String(page) })
if (tag) qs.set('tag', tag)
return useQuery({ return useQuery({
queryKey: ['notes', page, tag ?? ''], queryKey: ['notes', page],
queryFn: () => api<NoteList>(`/api/notes?${qs}`), queryFn: () => api<NoteList>(`/api/notes?page=${page}`),
}) })
} }
@@ -23,40 +22,28 @@ function useTags() {
}) })
} }
function NoteCard({ note }: { note: NoteItem }) { function NotePost({ note }: { note: NoteItem }) {
return ( return (
<article className="group border-b border-zinc-100 py-6 first:pt-0 dark:border-zinc-900"> <article className="pn-home-post">
<div className="flex items-center gap-2"> <time className="pn-home-date" dateTime={formatDateISO(note.updated_at)}>
{note.pinned && ( {note.pinned && (
<span className="inline-flex items-center gap-1 rounded bg-amber-100 px-1.5 py-0.5 text-xs text-amber-700 dark:bg-amber-900/40 dark:text-amber-400"> <span className="pn-home-pin">
<Pin size={11} /> 置顶 <Pin size={11} aria-hidden />置顶
</span> </span>
)} )}
<time className="text-xs text-zinc-400">{formatDate(note.updated_at)}</time> {formatDateISO(note.updated_at)}
</div> </time>
<h2 className="mt-1 text-xl font-semibold leading-snug"> <h2 className="pn-home-post-title">
<Link <Link to={`/notes/${encodeURIComponent(note.slug)}`}>
to={`/notes/${encodeURIComponent(note.slug)}`}
className="hover:text-blue-600 dark:hover:text-blue-400"
>
{note.title} {note.title}
<ArrowRight className="pn-home-arrow" size={17} aria-hidden />
</Link> </Link>
</h2> </h2>
{note.summary && ( {note.summary && <p className="pn-home-summary">{note.summary}</p>}
<p className="mt-2 line-clamp-3 text-sm leading-relaxed text-zinc-600 dark:text-zinc-400">
{note.summary}
</p>
)}
{note.tags.length > 0 && ( {note.tags.length > 0 && (
<div className="mt-3 flex flex-wrap gap-2"> <div className="pn-home-tags">
{note.tags.map((t) => ( {note.tags.map((t) => (
<Link <Link key={t} to={`/tags/${encodeURIComponent(t)}`} className="pn-home-tag">{t}</Link>
key={t}
to={`/tags/${encodeURIComponent(t)}`}
className="rounded-full bg-zinc-100 px-2.5 py-0.5 text-xs text-zinc-600 hover:bg-zinc-200 dark:bg-zinc-800 dark:text-zinc-400 dark:hover:bg-zinc-700"
>
#{t}
</Link>
))} ))}
</div> </div>
)} )}
@@ -66,62 +53,76 @@ function NoteCard({ note }: { note: NoteItem }) {
export default function Home() { export default function Home() {
const [page, setPage] = useState(1) const [page, setPage] = useState(1)
useDocumentTitle()
const { data, isLoading } = useNotes(page) const { data, isLoading } = useNotes(page)
const { data: tagsData } = useTags() const { data: tagsData } = useTags()
const totalPages = data ? Math.max(1, Math.ceil(data.total / data.page_size)) : 1 const totalPages = data ? Math.max(1, Math.ceil(data.total / data.page_size)) : 1
const topTags = (tagsData?.tags ?? []).slice(0, 4)
return ( return (
<div className="flex flex-col gap-8 lg:flex-row-reverse"> <div className="pn-home-content">
<aside className="lg:w-48 lg:shrink-0"> <section className="pn-home-hero">
{tagsData && tagsData.tags.length > 0 && ( <p className="pn-home-eyebrow">PURE NOTE · 极简笔记</p>
<div className="rounded-lg border border-zinc-200 p-4 dark:border-zinc-800"> <h1 className="pn-home-title">记录,而不打扰。</h1>
<h3 className="mb-2 text-xs font-medium uppercase tracking-wider text-zinc-400">标签</h3> <p className="pn-home-desc">Pure Note 是一个纯文本驱动的极简笔记工具,这里是公开的笔记。</p>
<div className="flex flex-wrap gap-2 lg:flex-col lg:gap-1"> </section>
{tagsData.tags.map((t) => (
<Link {topTags.length > 0 && (
key={t.name} <nav className="tabs pn-home-filter" aria-label="按标签筛选笔记">
to={`/tags/${encodeURIComponent(t.name)}`} <Link to="/" className={page === 1 ? 'active' : undefined}>全部</Link>
className="text-sm text-zinc-600 hover:text-blue-600 dark:text-zinc-400 dark:hover:text-blue-400" {topTags.map((t) => (
> <Link key={t.name} to={`/tags/${encodeURIComponent(t.name)}`}>{t.name}</Link>
#{t.name} <span className="text-zinc-400">({t.count})</span> ))}
</Link> </nav>
))} )}
</div>
</div> <section aria-label="笔记列表">
)}
</aside>
<section className="min-w-0 flex-1">
{isLoading ? ( {isLoading ? (
<p className="py-12 text-center text-zinc-400">加载中…</p> <p className="pn-home-list-empty">加载中…</p>
) : !data || data.items.length === 0 ? ( ) : !data || data.items.length === 0 ? (
<p className="py-12 text-center text-zinc-400">还没有公开的笔记</p> <p className="pn-home-list-empty">还没有公开的笔记</p>
) : ( ) : (
data.items.map((n) => <NoteCard key={n.slug} note={n} />) data.items.map((n) => <NotePost key={n.slug} note={n} />)
)}
{totalPages > 1 && (
<nav className="mt-8 flex items-center justify-between text-sm">
<button
type="button"
disabled={page <= 1}
onClick={() => setPage((p) => p - 1)}
className="rounded px-3 py-1.5 disabled:opacity-40 hover:bg-zinc-100 dark:hover:bg-zinc-800"
>
← 上一页
</button>
<span className="text-zinc-400">
{page} / {totalPages}
</span>
<button
type="button"
disabled={page >= totalPages}
onClick={() => setPage((p) => p + 1)}
className="rounded px-3 py-1.5 disabled:opacity-40 hover:bg-zinc-100 dark:hover:bg-zinc-800"
>
下一页 →
</button>
</nav>
)} )}
</section> </section>
{totalPages > 1 && (
<nav className="pn-home-pager" aria-label="分页">
<span className="pn-home-pager-note">
共 {data?.total ?? 0} 篇 · 第 {page} 页 / 共 {totalPages} 页
</span>
<div className="pn-pager">
<button
type="button"
className="btn ghost"
aria-label="上一页"
disabled={page <= 1}
onClick={() => setPage((p) => p - 1)}
>
<ChevronLeft size={16} />
</button>
{Array.from({ length: totalPages }, (_, i) => i + 1).map((p) => (
<button
key={p}
type="button"
className={`pn-page-btn${p === page ? ' is-active' : ''}`}
onClick={() => setPage(p)}
>
{p}
</button>
))}
<button
type="button"
className="btn ghost"
aria-label="下一页"
disabled={page >= totalPages}
onClick={() => setPage((p) => p + 1)}
>
<ChevronRight size={16} />
</button>
</div>
</nav>
)}
</div> </div>
) )
} }
+70 -31
View File
@@ -1,13 +1,16 @@
import { useState } from 'react' import { useState } from 'react'
import { useNavigate } from 'react-router' import { Link, useNavigate } from 'react-router'
import { Lock } from 'lucide-react' import { ArrowLeft, ArrowRight, CircleAlert, Eye, EyeOff, Lock } from 'lucide-react'
import { useAuth } from '../lib/auth' import { useAuth } from '../lib/auth'
import { ApiError } from '../lib/api' import { ApiError } from '../lib/api'
import { useDocumentTitle } from '../features/site'
export default function Login() { export default function Login() {
useDocumentTitle('管理员登录')
const { login, authenticated } = useAuth() const { login, authenticated } = useAuth()
const navigate = useNavigate() const navigate = useNavigate()
const [password, setPassword] = useState('') const [password, setPassword] = useState('')
const [showPw, setShowPw] = useState(false)
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null)
const [submitting, setSubmitting] = useState(false) const [submitting, setSubmitting] = useState(false)
@@ -24,7 +27,9 @@ export default function Login() {
navigate('/admin', { replace: true }) navigate('/admin', { replace: true })
} catch (err) { } catch (err) {
if (err instanceof ApiError) { if (err instanceof ApiError) {
setError(err.status === 429 ? '尝试过于频繁,请稍后再试' : '密码错误') if (err.status === 429) setError('尝试过于频繁,请稍后再试')
else if (err.status === 403) setError('请求被安全策略拦截,请刷新页面后重试')
else setError('密码错误,请重试')
} else { } else {
setError('登录失败,请重试') setError('登录失败,请重试')
} }
@@ -34,38 +39,72 @@ export default function Login() {
} }
return ( return (
<div className="flex min-h-screen items-center justify-center px-4"> <div className="pn-login-wrap">
<form <div className="pn-login-brand">
onSubmit={onSubmit} <span className="pn-login-eyebrow">ADMIN</span>
className="w-full max-w-sm rounded-xl border border-zinc-200 p-8 dark:border-zinc-800" <span className="pn-login-wordmark">Pure Note</span>
> </div>
<div className="mb-6 flex items-center justify-center gap-2 text-zinc-500">
<Lock size={18} /> <form className="card pn-login-card" onSubmit={onSubmit}>
<h1 className="text-lg font-semibold text-zinc-900 dark:text-zinc-100">管理员登录</h1> <h1 className="pn-login-title">管理员登录</h1>
</div> <p className="pn-login-sub">请输入管理密码以继续</p>
<label className="block text-sm text-zinc-600 dark:text-zinc-400" htmlFor="password">
口令 <label htmlFor="pn-login-username" className="sr-only">用户名</label>
</label>
<input <input
id="password" id="pn-login-username"
type="password" className="sr-only"
autoFocus type="text"
required name="username"
value={password} autoComplete="username"
onChange={(e) => setPassword(e.target.value)} value="admin"
className="mt-1.5 w-full rounded-lg border border-zinc-300 bg-transparent px-3 py-2 text-sm outline-none focus:border-blue-500 dark:border-zinc-700" readOnly
placeholder="输入管理员口令" tabIndex={-1}
/> />
{error && <p className="mt-2 text-sm text-red-600 dark:text-red-400">{error}</p>}
<button <label htmlFor="pn-login-password" className="sr-only">管理密码</label>
type="submit" <div className="pn-login-field">
disabled={submitting || password.length === 0} <Lock size={16} className="pn-login-icon" aria-hidden />
className="mt-4 w-full rounded-lg bg-zinc-900 py-2 text-sm font-medium text-white hover:bg-zinc-800 disabled:opacity-50 dark:bg-zinc-100 dark:text-zinc-900 dark:hover:bg-zinc-200" <input
> id="pn-login-password"
{submitting ? '登录中…' : '登录'} className="pn-login-input"
type={showPw ? 'text' : 'password'}
name="password"
placeholder="请输入管理密码"
autoComplete="current-password"
autoFocus
required
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<button
type="button"
className="pn-login-eye"
aria-label={showPw ? '隐藏密码' : '显示密码'}
onClick={() => setShowPw((v) => !v)}
>
{showPw ? <EyeOff size={16} /> : <Eye size={16} />}
</button>
</div>
{error && (
<div className="pn-login-error" role="alert">
<CircleAlert size={15} />
<span>{error}</span>
</div>
)}
<button type="submit" className="btn primary pn-login-submit" disabled={submitting || password.length === 0}>
<span>{submitting ? '登录中…' : '登录'}</span>
<ArrowRight size={16} />
</button> </button>
<p className="mt-4 text-center text-xs text-zinc-400">连续失败将被暂时锁定</p>
<p className="pn-login-hint">连续失败将被暂时锁定</p>
</form> </form>
<Link to="/" className="btn ghost pn-login-back">
<ArrowLeft size={14} />
<span>返回博客</span>
</Link>
</div> </div>
) )
} }
+13 -6
View File
@@ -1,13 +1,20 @@
import { Link } from 'react-router' import { Link } from 'react-router'
import { ArrowLeft } from 'lucide-react'
import { useDocumentTitle } from '../features/site'
export default function NotFound() { export default function NotFound() {
useDocumentTitle('页面不存在')
return ( return (
<div className="flex min-h-[60vh] flex-col items-center justify-center"> <div className="pn-404-page">
<p className="text-6xl font-bold text-zinc-200 dark:text-zinc-800">404</p> <p className="pn-404-code">404</p>
<p className="mt-4 text-zinc-500">页面不存在</p> <h1 className="pn-404-title">页面不存在</h1>
<Link to="/" className="mt-6 text-sm text-blue-600 hover:underline"> <p className="pn-404-desc">这篇笔记可能已被删除,或链接有误。</p>
← 返回首页 <div className="pn-404-actions">
</Link> <Link to="/" className="btn primary">
<ArrowLeft size={16} />
返回首页
</Link>
</div>
</div> </div>
) )
} }
+40 -43
View File
@@ -1,11 +1,12 @@
import { Link, useParams } from 'react-router' import { Link, useParams } from 'react-router'
import { useQuery } from '@tanstack/react-query' import { useQuery } from '@tanstack/react-query'
import { AlertTriangle } from 'lucide-react' import { ArrowLeft, ArrowRight, Clock, Eye } from 'lucide-react'
import { api } from '../lib/api' import { api } from '../lib/api'
import type { NoteDetail } from '../lib/api' import type { NoteDetail } from '../lib/api'
import { useAuth } from '../lib/auth' import { useAuth } from '../lib/auth'
import { useDocumentTitle } from '../features/site'
import MarkdownViewer from '../components/MarkdownViewer' import MarkdownViewer from '../components/MarkdownViewer'
import { formatDate } from '../lib/utils' import { formatDateISO, readingMinutes } from '../lib/utils'
export default function Note() { export default function Note() {
const { slug = '' } = useParams() const { slug = '' } = useParams()
@@ -15,16 +16,16 @@ export default function Note() {
queryFn: () => api<NoteDetail>(`/api/notes/${encodeURIComponent(slug)}`), queryFn: () => api<NoteDetail>(`/api/notes/${encodeURIComponent(slug)}`),
retry: false, retry: false,
}) })
useDocumentTitle(note?.title)
if (isLoading) return <p className="py-12 text-center text-zinc-400">加载中…</p> if (isLoading) return <p className="pn-home-list-empty">加载中…</p>
if (error || !note) { if (error || !note) {
return ( return (
<div className="py-12 text-center"> <div className="pn-note-article">
<p className="text-4xl font-bold text-zinc-300 dark:text-zinc-700">404</p> <p className="pn-home-list-empty">笔记不存在或未公开</p>
<p className="mt-2 text-zinc-500">笔记不存在或未公开</p> <p style={{ textAlign: 'center', marginTop: -40 }}>
<Link to="/" className="mt-4 inline-block text-sm text-blue-600 hover:underline"> <Link to="/" className="btn ghost pn-note-back"><ArrowLeft size={14} />返回首页</Link>
← 返回首页 </p>
</Link>
</div> </div>
) )
} }
@@ -32,55 +33,51 @@ export default function Note() {
const privatePreview = note.status === 'private' const privatePreview = note.status === 'private'
return ( return (
<article> <article className="pn-note-article">
<nav className="mb-4 text-xs text-zinc-400"> <Link to="/" className="btn ghost pn-note-back">
<Link to="/" className="hover:text-zinc-600">首页</Link> <ArrowLeft size={14} />返回首页
<span className="mx-1.5">/</span> </Link>
<span>{note.title}</span>
</nav>
{privatePreview && authenticated && ( {privatePreview && authenticated && (
<div className="mb-6 flex items-center gap-2 rounded-lg border border-amber-300 bg-amber-50 px-4 py-2.5 text-sm text-amber-800 dark:border-amber-800 dark:bg-amber-950 dark:text-amber-300"> <div className="pn-note-private" role="note">
<AlertTriangle size={16} /> <Eye size={15} />
私有预览:此笔记未公开,仅管理员可见 私有预览:此笔记未公开,仅管理员可见
</div> </div>
)} )}
<header className="mb-8"> <h1 className="pn-note-title">{note.title}</h1>
<h1 className="text-3xl font-bold leading-tight">{note.title}</h1>
<div className="mt-2 flex flex-wrap items-center gap-3 text-xs text-zinc-400"> <div className="pn-note-meta">
<time>{formatDate(note.created_at)}</time> <time className="pn-note-meta-date" dateTime={formatDateISO(note.created_at)}>
{note.tags.map((t) => ( {formatDateISO(note.created_at)}
<Link </time>
key={t} <span className="pn-note-meta-sep">·</span>
to={`/tags/${encodeURIComponent(t)}`} <span className="pn-note-meta-read"><Clock size={14} />约 {readingMinutes(note.content)} 分钟阅读</span>
className="rounded-full bg-zinc-100 px-2 py-0.5 hover:bg-zinc-200 dark:bg-zinc-800 dark:hover:bg-zinc-700" {note.tags.length > 0 && (
> <>
#{t} <span className="pn-note-meta-sep">·</span>
</Link> {note.tags.map((t) => (
))} <Link key={t} to={`/tags/${encodeURIComponent(t)}`} className="pn-note-tag">{t}</Link>
</div> ))}
</header> </>
)}
</div>
<MarkdownViewer source={note.content} /> <MarkdownViewer source={note.content} />
<nav className="mt-12 flex justify-between gap-4 border-t border-zinc-100 pt-6 text-sm dark:border-zinc-900"> <nav className="pn-note-postnav" aria-label="笔记导航">
{note.prev ? ( {note.prev ? (
<Link <Link to={`/notes/${encodeURIComponent(note.prev.slug)}`} className="card pn-note-nav-card">
to={`/notes/${encodeURIComponent(note.prev.slug)}`} <span className="pn-note-nav-label"><ArrowLeft size={14} />上一篇</span>
className="text-zinc-600 hover:text-blue-600 dark:text-zinc-400" <span className="pn-note-nav-title">{note.prev.title}</span>
>
← {note.prev.title}
</Link> </Link>
) : ( ) : (
<span /> <span />
)} )}
{note.next ? ( {note.next ? (
<Link <Link to={`/notes/${encodeURIComponent(note.next.slug)}`} className="card pn-note-nav-card pn-note-nav-next">
to={`/notes/${encodeURIComponent(note.next.slug)}`} <span className="pn-note-nav-label">下一篇<ArrowRight size={14} /></span>
className="text-right text-zinc-600 hover:text-blue-600 dark:text-zinc-400" <span className="pn-note-nav-title">{note.next.title}</span>
>
{note.next.title} →
</Link> </Link>
) : ( ) : (
<span /> <span />
+72 -35
View File
@@ -1,47 +1,84 @@
import { Link, useParams } from 'react-router' import { Link, useParams } from 'react-router'
import { useQuery } from '@tanstack/react-query' import { useQuery } from '@tanstack/react-query'
import { ArrowRight, Tag } from 'lucide-react'
import { api } from '../lib/api' import { api } from '../lib/api'
import type { NoteList } from '../lib/api' import type { NoteList, TagCount } from '../lib/api'
import { formatDate } from '../lib/utils' import { useDocumentTitle } from '../features/site'
import { formatDateISO } from '../lib/utils'
function useTags() {
return useQuery({
queryKey: ['tags'],
queryFn: () => api<{ tags: TagCount[] }>('/api/tags'),
})
}
export default function TagPage() { export default function TagPage() {
const { tag = '' } = useParams() const { tag } = useParams()
useDocumentTitle(tag ? `标签:${tag}` : '标签')
const { data: tagsData } = useTags()
const { data, isLoading, error } = useQuery({ const { data, isLoading, error } = useQuery({
queryKey: ['tag', tag], queryKey: ['tag', tag ?? ''],
queryFn: () => api<NoteList>(`/api/notes?tag=${encodeURIComponent(tag)}&page=1&page_size=100`), queryFn: () =>
api<NoteList>(`/api/notes?tag=${encodeURIComponent(tag ?? '')}&page=1&page_size=100`),
enabled: tag !== undefined,
}) })
return ( return (
<div> <div className="pn-tag-content">
<header className="mb-6"> <section className="pn-tag-pagehead">
<nav className="mb-2 text-xs text-zinc-400"> <h1>标签</h1>
<Link to="/" className="hover:text-zinc-600">首页</Link> <p>按主题浏览所有公开笔记</p>
<span className="mx-1.5">/</span> </section>
<span>标签</span>
</nav> <nav className="pn-tag-cloud" aria-label="全部标签">
<h1 className="text-2xl font-bold">#{tag}</h1> {tagsData?.tags.map((t) => (
<p className="mt-1 text-sm text-zinc-400">{data?.total ?? 0} 篇</p> <Link
</header> key={t.name}
{isLoading ? ( to={`/tags/${encodeURIComponent(t.name)}`}
<p className="py-12 text-center text-zinc-400">加载中…</p> className={`pn-tag-pill${t.name === tag ? ' active' : ''}`}
) : error ? ( aria-current={t.name === tag ? 'true' : undefined}
<p className="py-12 text-center text-red-500">加载失败,请稍后重试</p> >
) : !data || data.items.length === 0 ? ( <Tag size={14} />
<p className="py-12 text-center text-zinc-400">该标签下暂无公开笔记</p> <span>{t.name}</span>
) : ( <span className="pn-tag-count">{t.count}</span>
<ul className="divide-y divide-zinc-100 dark:divide-zinc-900"> </Link>
{data.items.map((n) => ( ))}
<li key={n.slug} className="py-4"> {!tagsData && (
<Link <span className="pn-tag-count" style={{ padding: 8 }}>加载中…</span>
to={`/notes/${encodeURIComponent(n.slug)}`} )}
className="font-medium hover:text-blue-600 dark:hover:text-blue-400" {tagsData && tagsData.tags.length === 0 && (
> <span className="pn-tag-count" style={{ padding: 8 }}>还没有标签</span>
{n.title} )}
</Link> </nav>
<time className="ml-3 text-xs text-zinc-400">{formatDate(n.updated_at)}</time>
</li> {tag === undefined && tagsData && (
))} <p className="pn-home-list-empty" style={{ marginTop: 48 }}>选择一个标签,查看对应笔记</p>
</ul> )}
{tag && (
<section className="pn-tag-groups">
<section>
<h3 className="pn-tag-group-title"><Tag size={16} />{tag}</h3>
<div className="pn-tag-rows">
{isLoading ? (
<p className="pn-home-list-empty">加载中…</p>
) : error ? (
<p className="pn-home-list-empty">加载失败,请稍后重试</p>
) : !data || data.items.length === 0 ? (
<p className="pn-home-list-empty">该标签下暂无公开笔记</p>
) : (
data.items.map((n) => (
<Link key={n.slug} to={`/notes/${encodeURIComponent(n.slug)}`} className="pn-tag-row">
<time className="pn-tag-date">{formatDateISO(n.updated_at)}</time>
<span className="pn-tag-title">{n.title}</span>
<span className="pn-tag-arrow" aria-hidden><ArrowRight size={16} /></span>
</Link>
))
)}
</div>
</section>
</section>
)} )}
</div> </div>
) )
+30
View File
@@ -0,0 +1,30 @@
import { describe, expect, it, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
import { MemoryRouter } from 'react-router'
import Login from '../src/pages/Login'
vi.mock('../src/lib/auth', () => ({
useAuth: () => ({ login: vi.fn(), authenticated: false }),
}))
vi.mock('../src/features/site', () => ({
useDocumentTitle: () => {},
}))
describe('Login 表单密码管理器适配', () => {
it('暴露隐藏用户名字段与 current-password 自动填充标记', () => {
render(
<MemoryRouter>
<Login />
</MemoryRouter>,
)
const username = screen.getByLabelText('用户名') as HTMLInputElement
expect(username.type).toBe('text')
expect(username.value).toBe('admin')
expect(username.readOnly).toBe(true)
expect(username.getAttribute('autocomplete')).toBe('username')
const password = screen.getByLabelText('管理密码') as HTMLInputElement
expect(password.getAttribute('autocomplete')).toBe('current-password')
})
})
+9 -13
View File
@@ -11,23 +11,19 @@ export default defineConfig({
server: { server: {
proxy: { proxy: {
// 同源是 Cookie/CSRF 成立的前提(§10.5) // 同源是 Cookie/CSRF 成立的前提(§10.5)
'/api': 'http://127.0.0.1:8080', // changeOrigin:false —— 保留浏览器原始 Host(localhost:5173),
// 否则后端 Origin 校验会因 Host 被改写为 127.0.0.1:8080 而判定跨源 403。
'/api': {
target: 'http://127.0.0.1:8080',
changeOrigin: false,
},
}, },
}, },
build: { build: {
// 产物内容 hash 文件名(§8.3-5) // 产物内容 hash 文件名(§8.3-5)
assetsDir: 'assets', assetsDir: 'assets',
rolldownOptions: { // 不做手动 codeSplitting 分组:分组 chunk 会被提升进入口静态依赖,
output: { // HTML 对其发出 modulepreload,导致 lazy() 路由的 CodeMirror 在
// CodeMirror 体积过大,手动拆分避免单 chunk 超 500kB: // 所有页面被预加载(Lighthouse unused-javascript 549KiB 的根因)。
// @codemirror/view 是最大的包,单独成组,其余 cm/lezer/uiw 归一组
codeSplitting: {
groups: [
{ name: 'codemirror-view', test: /node_modules[\\/](@codemirror[\\/]view|style-mod|w3c-keyname)/ },
{ name: 'codemirror', test: /node_modules[\\/](@codemirror|@lezer|@uiw)/ },
],
},
},
},
}, },
}) })