前端:React 19 + Vite 8 + Tailwind 4 博客与管理后台 SPA
- 渲染管线(§8.2):react-markdown + remark-gfm + rehype-sanitize (GitHub schema 扩展 hljs class 与 checked)+ rehype-highlight 纯 class 高亮;链接强制 target=_blank + rel=nofollow noopener noreferrer; schema 快照与恶意 Markdown 冒烟测试(vitest 6 用例) - 编辑器:CodeMirror 6 源码编辑 + 分屏实时预览 + 工具栏 + 粘贴/拖拽图片上传;slug 首存定稿(冲突 409 就地高亮)、 摘要留空自动截取、2s 防抖自动保存 - 页面:博客首页(置顶/分页/标签云)、详情(面包屑/上一篇下一篇)、 标签页、登录、管理列表/回收站/设置/改密、404 - lib:api 客户端(统一包络 + 内存态 CSRF,禁 localStorage)、 AuthContext(/api/me 重取)、暗色主题(class 切换 + 系统跟随) - index.html 内嵌 Go template 占位符供服务端 meta 注入; vite base 固定 '/'(防深链白屏);/api 代理 127.0.0.1:8080
This commit is contained in:
@@ -0,0 +1,23 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<!--
|
||||||
|
以下占位符由服务端 internal/webui 以 html/template 渲染并自动转义(§8.3-4)。
|
||||||
|
所有字段服务端保证非空(含站点默认回退值)。
|
||||||
|
-->
|
||||||
|
<title>{{.Title}}</title>
|
||||||
|
<meta name="description" content="{{.Description}}" />
|
||||||
|
<meta property="og:title" content="{{.OGTitle}}" />
|
||||||
|
<meta property="og:description" content="{{.OGDescription}}" />
|
||||||
|
<meta property="og:type" content="{{.OGType}}" />
|
||||||
|
<meta property="og:url" content="{{.OGURL}}" />
|
||||||
|
<meta property="og:site_name" content="{{.SiteName}}" />
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Generated
+6365
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,41 @@
|
|||||||
|
{
|
||||||
|
"name": "pure-note-web",
|
||||||
|
"private": true,
|
||||||
|
"version": "1.0.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "tsc --noEmit && vite build",
|
||||||
|
"preview": "vite preview",
|
||||||
|
"test": "vitest run",
|
||||||
|
"test:watch": "vitest"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@codemirror/lang-markdown": "^6.5.2",
|
||||||
|
"@tanstack/react-query": "^5.102.8",
|
||||||
|
"@uiw/react-codemirror": "^4.25.11",
|
||||||
|
"lucide-react": "^1.42.0",
|
||||||
|
"react": "^19.2.8",
|
||||||
|
"react-dom": "^19.2.8",
|
||||||
|
"react-markdown": "^10.1.0",
|
||||||
|
"react-router": "^8.3.1",
|
||||||
|
"rehype-highlight": "^7.0.2",
|
||||||
|
"rehype-sanitize": "^6.0.0",
|
||||||
|
"remark-gfm": "^4.0.1"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@tailwindcss/typography": "^0.5.19",
|
||||||
|
"@tailwindcss/vite": "^4.3.3",
|
||||||
|
"@testing-library/dom": "^10.4.0",
|
||||||
|
"@testing-library/react": "^16.3.0",
|
||||||
|
"@types/react": "^19.2.0",
|
||||||
|
"@types/react-dom": "^19.2.0",
|
||||||
|
"@vitejs/plugin-react": "^5.0.0",
|
||||||
|
"highlight.js": "^11.11.1",
|
||||||
|
"tailwindcss": "^4.3.3",
|
||||||
|
"typescript": "^5.9.2",
|
||||||
|
"vite": "^8.2.2",
|
||||||
|
"vitest": "^3.2.4",
|
||||||
|
"jsdom": "^26.1.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="7" fill="#18181b"/><path d="M10 8h9a5 5 0 0 1 0 10h-5v6h-4V8zm4 4v4h4.5a2 2 0 0 0 0-4H14z" fill="#fafafa"/></svg>
|
||||||
|
After Width: | Height: | Size: 207 B |
@@ -0,0 +1,46 @@
|
|||||||
|
import { Navigate, Route, Routes } from 'react-router'
|
||||||
|
import type { ReactNode } from 'react'
|
||||||
|
import { useAuth } from './lib/auth'
|
||||||
|
import { BlogLayout, AdminLayout } from './components/Layout'
|
||||||
|
import Home from './pages/Home'
|
||||||
|
import Note from './pages/Note'
|
||||||
|
import TagPage from './pages/TagPage'
|
||||||
|
import Login from './pages/Login'
|
||||||
|
import AdminList from './pages/AdminList'
|
||||||
|
import AdminTrash from './pages/AdminTrash'
|
||||||
|
import AdminEdit from './pages/AdminEdit'
|
||||||
|
import AdminSettings from './pages/AdminSettings'
|
||||||
|
import NotFound from './pages/NotFound'
|
||||||
|
|
||||||
|
// 登录守卫:401 统一跳转 /admin/login(§8.2)
|
||||||
|
function RequireAuth({ children }: { children: ReactNode }) {
|
||||||
|
const { authenticated, loading } = useAuth()
|
||||||
|
if (loading) {
|
||||||
|
return <div className="flex min-h-screen items-center justify-center text-zinc-500">加载中…</div>
|
||||||
|
}
|
||||||
|
if (!authenticated) {
|
||||||
|
return <Navigate to="/admin/login" replace />
|
||||||
|
}
|
||||||
|
return <>{children}</>
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function App() {
|
||||||
|
return (
|
||||||
|
<Routes>
|
||||||
|
<Route element={<BlogLayout />}>
|
||||||
|
<Route path="/" element={<Home />} />
|
||||||
|
<Route path="/notes/:slug" element={<Note />} />
|
||||||
|
<Route path="/tags/:tag" element={<TagPage />} />
|
||||||
|
</Route>
|
||||||
|
<Route path="/admin/login" element={<Login />} />
|
||||||
|
<Route element={<RequireAuth><AdminLayout /></RequireAuth>}>
|
||||||
|
<Route path="/admin" element={<AdminList />} />
|
||||||
|
<Route path="/admin/trash" element={<AdminTrash />} />
|
||||||
|
<Route path="/admin/settings" element={<AdminSettings />} />
|
||||||
|
<Route path="/admin/notes/new" element={<AdminEdit />} />
|
||||||
|
<Route path="/admin/notes/:id/edit" element={<AdminEdit />} />
|
||||||
|
</Route>
|
||||||
|
<Route path="*" element={<NotFound />} />
|
||||||
|
</Routes>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
import { useCallback, useMemo, useRef, useState } from 'react'
|
||||||
|
import CodeMirror from '@uiw/react-codemirror'
|
||||||
|
import { markdown, markdownLanguage } from '@codemirror/lang-markdown'
|
||||||
|
import { EditorView } from '@codemirror/view'
|
||||||
|
import { api, ApiError } from '../lib/api'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Editor(编辑态,§8.2):CodeMirror 6 源码编辑 + 图片粘贴/拖拽上传。
|
||||||
|
* 粘贴/拖拽 → POST /api/admin/images(≤5MB,魔数校验)→ 光标处插入
|
||||||
|
* ``。
|
||||||
|
*/
|
||||||
|
|
||||||
|
interface UploadResult {
|
||||||
|
id: number
|
||||||
|
url: string
|
||||||
|
}
|
||||||
|
|
||||||
|
async function uploadImage(file: File): Promise<UploadResult> {
|
||||||
|
const form = new FormData()
|
||||||
|
form.append('file', file)
|
||||||
|
// multipart:让浏览器自动设置 Content-Type(含 boundary)
|
||||||
|
return api<UploadResult>('/api/admin/images', { method: 'POST', body: form })
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Editor({
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
onUploadStart,
|
||||||
|
onUploadEnd,
|
||||||
|
}: {
|
||||||
|
value: string
|
||||||
|
onChange: (v: string) => void
|
||||||
|
onUploadStart?: (name: string) => void
|
||||||
|
onUploadEnd?: (err: string | null) => void
|
||||||
|
}) {
|
||||||
|
const viewRef = useRef<{ view?: EditorView } | null>(null)
|
||||||
|
const [dragOver, setDragOver] = useState(false)
|
||||||
|
|
||||||
|
const extensions = useMemo(
|
||||||
|
() => [
|
||||||
|
markdown({ base: markdownLanguage }),
|
||||||
|
EditorView.lineWrapping,
|
||||||
|
],
|
||||||
|
[],
|
||||||
|
)
|
||||||
|
|
||||||
|
const insertAtCursor = useCallback(
|
||||||
|
(text: string) => {
|
||||||
|
const wrapper = viewRef.current
|
||||||
|
const view = wrapper?.view
|
||||||
|
if (!view) {
|
||||||
|
onChange(value + text)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const pos = view.state.selection.main.head
|
||||||
|
view.dispatch({
|
||||||
|
changes: { from: pos, insert: text },
|
||||||
|
selection: { anchor: pos + text.length },
|
||||||
|
})
|
||||||
|
},
|
||||||
|
[onChange, value],
|
||||||
|
)
|
||||||
|
|
||||||
|
const handleFiles = useCallback(
|
||||||
|
async (files: FileList | File[]) => {
|
||||||
|
for (const file of Array.from(files)) {
|
||||||
|
onUploadStart?.(file.name)
|
||||||
|
try {
|
||||||
|
const res = await uploadImage(file)
|
||||||
|
const alt = file.name.replace(/\.[^.]+$/, '')
|
||||||
|
insertAtCursor(``)
|
||||||
|
onUploadEnd?.(null)
|
||||||
|
} catch (e) {
|
||||||
|
const msg = e instanceof ApiError ? e.message : '上传失败'
|
||||||
|
onUploadEnd?.(msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[insertAtCursor, onUploadStart, onUploadEnd],
|
||||||
|
)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={`relative h-full overflow-hidden rounded-lg border ${
|
||||||
|
dragOver ? 'border-blue-500 bg-blue-50 dark:bg-blue-950' : 'border-zinc-200 dark:border-zinc-800'
|
||||||
|
}`}
|
||||||
|
onDragOver={(e) => {
|
||||||
|
e.preventDefault()
|
||||||
|
setDragOver(true)
|
||||||
|
}}
|
||||||
|
onDragLeave={() => setDragOver(false)}
|
||||||
|
onDrop={(e) => {
|
||||||
|
e.preventDefault()
|
||||||
|
setDragOver(false)
|
||||||
|
if (e.dataTransfer.files.length > 0) void handleFiles(e.dataTransfer.files)
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<CodeMirror
|
||||||
|
value={value}
|
||||||
|
onChange={onChange}
|
||||||
|
extensions={extensions}
|
||||||
|
basicSetup={{ lineNumbers: true, foldGutter: false, highlightActiveLine: true }}
|
||||||
|
theme="light"
|
||||||
|
height="100%"
|
||||||
|
style={{ height: '100%' }}
|
||||||
|
onCreateEditor={(view) => {
|
||||||
|
viewRef.current = { view }
|
||||||
|
}}
|
||||||
|
onPaste={(event: React.ClipboardEvent<HTMLDivElement>) => {
|
||||||
|
const files = event.clipboardData?.files
|
||||||
|
if (files && files.length > 0 && Array.from(files).every((f) => f.type.startsWith('image/'))) {
|
||||||
|
event.preventDefault()
|
||||||
|
void handleFiles(files)
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
{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">
|
||||||
|
松开以上传图片(≤5MB)
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
import { Link, NavLink, Outlet } from 'react-router'
|
||||||
|
import { Moon, Sun, Monitor } from 'lucide-react'
|
||||||
|
import { useSiteTitle } from '../features/site'
|
||||||
|
import { useTheme } from '../lib/theme'
|
||||||
|
|
||||||
|
export function SiteHeader() {
|
||||||
|
const { data } = useSiteTitle()
|
||||||
|
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 title = `主题:${mode === 'light' ? '浅色' : mode === 'dark' ? '深色' : '跟随系统'}(点击切换)`
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
title={title}
|
||||||
|
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} />}
|
||||||
|
</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() {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen">
|
||||||
|
<SiteHeader />
|
||||||
|
<main className="mx-auto max-w-3xl px-4 py-8">
|
||||||
|
<Outlet />
|
||||||
|
</main>
|
||||||
|
<SiteFooter />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const adminLinks = [
|
||||||
|
{ to: '/admin', label: '笔记', end: true },
|
||||||
|
{ to: '/admin/trash', label: '回收站', end: true },
|
||||||
|
{ to: '/admin/settings', label: '设置', end: true },
|
||||||
|
]
|
||||||
|
|
||||||
|
export function AdminLayout() {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen">
|
||||||
|
<SiteHeader />
|
||||||
|
<div className="mx-auto max-w-5xl px-4">
|
||||||
|
<nav className="flex gap-1 border-b border-zinc-200 py-2 dark:border-zinc-800">
|
||||||
|
{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>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import { memo } from 'react'
|
||||||
|
import ReactMarkdown from 'react-markdown'
|
||||||
|
import remarkGfm from 'remark-gfm'
|
||||||
|
import rehypeHighlight from 'rehype-highlight'
|
||||||
|
import { sanitizePlugin } from '../lib/sanitize'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* MarkdownViewer:浏览态渲染管线(§8.2),组件边界独立、可整体替换。
|
||||||
|
*
|
||||||
|
* Markdown 原文
|
||||||
|
* → remark-gfm(表格/任务列表/删除线/自动链接)
|
||||||
|
* → rehype-sanitize(白名单清洗,禁 script/iframe/style/事件属性/危险协议)
|
||||||
|
* → rehype-highlight(纯 class 高亮,主题 CSS 静态打包)
|
||||||
|
*
|
||||||
|
* 两处防线:本管线 + 服务端 CSP script-src 'self' 兜底。
|
||||||
|
*/
|
||||||
|
function CodeBlock(props: React.HTMLAttributes<HTMLPreElement>) {
|
||||||
|
return (
|
||||||
|
<div className="group relative">
|
||||||
|
<pre {...props} />
|
||||||
|
<CopyButton />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CopyButton() {
|
||||||
|
// 复制按钮在点击时读取最近兄弟 <pre> 的文本;不注入任何 HTML
|
||||||
|
return (
|
||||||
|
<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"
|
||||||
|
onClick={(e) => {
|
||||||
|
const pre = (e.currentTarget.parentElement as HTMLElement).querySelector('pre')
|
||||||
|
if (pre) void navigator.clipboard.writeText(pre.textContent ?? '')
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
复制
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const MarkdownViewer = memo(function MarkdownViewer({ source }: { source: string }) {
|
||||||
|
return (
|
||||||
|
<div className="prose prose-zinc max-w-none dark:prose-invert prose-pre:bg-zinc-100 dark:prose-pre:bg-zinc-900">
|
||||||
|
<ReactMarkdown
|
||||||
|
remarkPlugins={[remarkGfm]}
|
||||||
|
rehypePlugins={[sanitizePlugin, rehypeHighlight]}
|
||||||
|
components={{
|
||||||
|
// 链接强制新窗口 + 安全 rel(§8.2)
|
||||||
|
a: ({ node: _node, ...props }) => (
|
||||||
|
<a {...props} target="_blank" rel="nofollow noopener noreferrer" />
|
||||||
|
),
|
||||||
|
pre: CodeBlock,
|
||||||
|
// 任务列表 checkbox 只读
|
||||||
|
input: ({ node: _node, ...props }) => <input {...props} disabled readOnly />,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{source}
|
||||||
|
</ReactMarkdown>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
export default MarkdownViewer
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import { api } from '../lib/api'
|
||||||
|
import type { SiteSettings } from '../lib/api'
|
||||||
|
|
||||||
|
export function useSiteTitle() {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ['site'],
|
||||||
|
queryFn: () => api<SiteSettings>('/api/site'),
|
||||||
|
staleTime: 5 * 60_000,
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
@import "tailwindcss";
|
||||||
|
@plugin "@tailwindcss/typography";
|
||||||
|
|
||||||
|
/* 暗色主题:根元素 class 切换(§8.2) */
|
||||||
|
@custom-variant dark (&:where(.dark, .dark *));
|
||||||
|
|
||||||
|
@theme {
|
||||||
|
--font-sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto,
|
||||||
|
"Helvetica Neue", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif;
|
||||||
|
--font-mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
|
||||||
|
}
|
||||||
|
|
||||||
|
html {
|
||||||
|
@apply antialiased;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
@apply bg-white text-zinc-900 dark:bg-zinc-950 dark:text-zinc-100;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* CodeMirror 等宽 + 边框自适应暗色 */
|
||||||
|
.cm-editor {
|
||||||
|
@apply h-full bg-white dark:bg-zinc-950;
|
||||||
|
}
|
||||||
|
.cm-editor.cm-focused {
|
||||||
|
outline: none !important;
|
||||||
|
}
|
||||||
|
.cm-gutters {
|
||||||
|
@apply border-r border-zinc-200 bg-zinc-50 dark:border-zinc-800 dark:bg-zinc-900;
|
||||||
|
}
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
// API 客户端:统一包络解析、错误对象、CSRF 头注入(§8.2 数据与状态)。
|
||||||
|
// CSRF token 仅存内存(模块变量),刷新后经 /api/me 重取,禁止 localStorage。
|
||||||
|
|
||||||
|
export class ApiError extends Error {
|
||||||
|
status: number
|
||||||
|
code: string
|
||||||
|
field?: string
|
||||||
|
|
||||||
|
constructor(status: number, code: string, message: string, field?: string) {
|
||||||
|
super(message)
|
||||||
|
this.status = status
|
||||||
|
this.code = code
|
||||||
|
this.field = field
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 模块级内存态 CSRF token(不持久化)
|
||||||
|
let csrfToken: string | null = null
|
||||||
|
|
||||||
|
export function setCsrfToken(token: string | null) {
|
||||||
|
csrfToken = token
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getCsrfToken(): string | null {
|
||||||
|
return csrfToken
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Envelope<T> {
|
||||||
|
data?: T
|
||||||
|
error?: { code: string; message: string; field?: string }
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function api<T>(
|
||||||
|
path: string,
|
||||||
|
options: RequestInit = {},
|
||||||
|
): Promise<T> {
|
||||||
|
const method = (options.method ?? 'GET').toUpperCase()
|
||||||
|
const headers = new Headers(options.headers)
|
||||||
|
if (options.body && !headers.has('Content-Type')) {
|
||||||
|
headers.set('Content-Type', 'application/json')
|
||||||
|
}
|
||||||
|
if (method !== 'GET' && method !== 'HEAD' && csrfToken) {
|
||||||
|
headers.set('X-CSRF-Token', csrfToken)
|
||||||
|
}
|
||||||
|
const res = await fetch(path, { ...options, method, headers, credentials: 'same-origin' })
|
||||||
|
|
||||||
|
let body: Envelope<T> | null = null
|
||||||
|
try {
|
||||||
|
body = (await res.json()) as Envelope<T>
|
||||||
|
} catch {
|
||||||
|
/* 空/非 JSON 响应 */
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
const err = body?.error
|
||||||
|
if (res.status === 401) {
|
||||||
|
// 登录态失效:清内存态,统一由 AuthContext 跳登录页
|
||||||
|
setCsrfToken(null)
|
||||||
|
}
|
||||||
|
throw new ApiError(
|
||||||
|
res.status,
|
||||||
|
err?.code ?? 'unknown',
|
||||||
|
err?.message ?? `请求失败(${res.status})`,
|
||||||
|
err?.field,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return body!.data as T
|
||||||
|
}
|
||||||
|
|
||||||
|
export function jsonBody(payload: unknown): RequestInit {
|
||||||
|
return { body: JSON.stringify(payload) }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 领域类型 ----
|
||||||
|
|
||||||
|
export interface SiteSettings {
|
||||||
|
site_title: string
|
||||||
|
site_desc: string
|
||||||
|
page_size: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NoteItem {
|
||||||
|
id: number
|
||||||
|
slug: string
|
||||||
|
title: string
|
||||||
|
summary: string
|
||||||
|
status?: string
|
||||||
|
tags: string[]
|
||||||
|
pinned: boolean
|
||||||
|
deleted_at?: number | null
|
||||||
|
created_at: number
|
||||||
|
updated_at: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NoteDetail extends NoteItem {
|
||||||
|
content: string
|
||||||
|
prev: { slug: string; title: string } | null
|
||||||
|
next: { slug: string; title: string } | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NoteList {
|
||||||
|
items: NoteItem[]
|
||||||
|
page: number
|
||||||
|
page_size: number
|
||||||
|
total: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TagCount {
|
||||||
|
name: string
|
||||||
|
count: number
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
import { createContext, useCallback, useContext, useEffect, useState } from 'react'
|
||||||
|
import type { ReactNode } from 'react'
|
||||||
|
import { api, setCsrfToken } from './api'
|
||||||
|
|
||||||
|
interface Me {
|
||||||
|
authenticated: boolean
|
||||||
|
csrf_token?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AuthState {
|
||||||
|
loading: boolean
|
||||||
|
authenticated: boolean
|
||||||
|
login: (password: string) => Promise<void>
|
||||||
|
logout: () => Promise<void>
|
||||||
|
refresh: () => Promise<void>
|
||||||
|
}
|
||||||
|
|
||||||
|
const AuthContext = createContext<AuthState | null>(null)
|
||||||
|
|
||||||
|
// AuthContext:会话态 + CSRF 内存态(§8.2)。
|
||||||
|
// 刷新页面后由 /api/me 重取 CSRF token;明确禁止 localStorage 持久化。
|
||||||
|
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||||
|
const [loading, setLoading] = useState(true)
|
||||||
|
const [authenticated, setAuthenticated] = useState(false)
|
||||||
|
|
||||||
|
const refresh = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const me = await api<Me>('/api/me')
|
||||||
|
setAuthenticated(me.authenticated)
|
||||||
|
if (me.authenticated && me.csrf_token) {
|
||||||
|
setCsrfToken(me.csrf_token)
|
||||||
|
} else {
|
||||||
|
setCsrfToken(null)
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
setAuthenticated(false)
|
||||||
|
setCsrfToken(null)
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void refresh()
|
||||||
|
}, [refresh])
|
||||||
|
|
||||||
|
const login = useCallback(
|
||||||
|
async (password: string) => {
|
||||||
|
const res = await api<{ csrf_token: string }>('/api/auth/login', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ password }),
|
||||||
|
})
|
||||||
|
setCsrfToken(res.csrf_token)
|
||||||
|
setAuthenticated(true)
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
)
|
||||||
|
|
||||||
|
const logout = useCallback(async () => {
|
||||||
|
await api('/api/auth/logout', { method: 'POST' })
|
||||||
|
setCsrfToken(null)
|
||||||
|
setAuthenticated(false)
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AuthContext.Provider value={{ loading, authenticated, login, logout, refresh }}>
|
||||||
|
{children}
|
||||||
|
</AuthContext.Provider>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useAuth(): AuthState {
|
||||||
|
const ctx = useContext(AuthContext)
|
||||||
|
if (!ctx) throw new Error('useAuth 必须在 AuthProvider 内使用')
|
||||||
|
return ctx
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
// rehype-sanitize 白名单 schema(§8.2 渲染管线):
|
||||||
|
// - 默认 GitHub schema 之上扩展:任务列表 checkbox 所需属性、
|
||||||
|
// highlight.js 纯 class 高亮所需 className 白名单
|
||||||
|
// - 禁 script/iframe/style 属性/事件属性;链接协议白名单(javascript: 被剥除)
|
||||||
|
// - 链接 target/rel 由 <a> 组件强制(schema 不支持条件属性)
|
||||||
|
import { defaultSchema } from 'rehype-sanitize'
|
||||||
|
import rehypeSanitize from 'rehype-sanitize'
|
||||||
|
import type { Schema } from 'hast-util-sanitize'
|
||||||
|
import type { Pluggable } from 'unified'
|
||||||
|
|
||||||
|
export const sanitizeSchema: Schema = {
|
||||||
|
...defaultSchema,
|
||||||
|
tagNames: [
|
||||||
|
...(defaultSchema.tagNames ?? []),
|
||||||
|
// 允许任务列表所需的 input(GitHub schema 已含,显式声明以防上游变化)
|
||||||
|
'input',
|
||||||
|
],
|
||||||
|
attributes: {
|
||||||
|
...defaultSchema.attributes,
|
||||||
|
// 任务列表 checkbox:默认 schema 已含 ['type','checkbox'] 与 ['disabled',true],
|
||||||
|
// 显式补 'checked'
|
||||||
|
input: [
|
||||||
|
...(defaultSchema.attributes?.input ?? []),
|
||||||
|
['checked', true],
|
||||||
|
],
|
||||||
|
// highlight.js 输出纯 class(零内联样式,§3.2)
|
||||||
|
code: [
|
||||||
|
...(defaultSchema.attributes?.code ?? []),
|
||||||
|
['className', /^language-./, 'hljs'],
|
||||||
|
],
|
||||||
|
span: [
|
||||||
|
...(defaultSchema.attributes?.span ?? []),
|
||||||
|
['className', /^hljs(-\w+)?$/],
|
||||||
|
],
|
||||||
|
},
|
||||||
|
// 危险协议由默认 protocols 白名单(http/https/mailto/irc/xmpp…)剥除
|
||||||
|
clobberPrefix: defaultSchema.clobberPrefix ?? 'user-content-',
|
||||||
|
}
|
||||||
|
|
||||||
|
// rehypePlugins 元组:[rehypeSanitize, sanitizeSchema]
|
||||||
|
export const sanitizePlugin: Pluggable = [rehypeSanitize, sanitizeSchema]
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import { createContext, useContext, useEffect, useState } from 'react'
|
||||||
|
import type { ReactNode } from 'react'
|
||||||
|
|
||||||
|
type ThemeMode = 'light' | 'dark' | 'system'
|
||||||
|
|
||||||
|
const ThemeContext = createContext<{ mode: ThemeMode; setMode: (m: ThemeMode) => void } | null>(null)
|
||||||
|
|
||||||
|
function apply(mode: ThemeMode) {
|
||||||
|
const dark =
|
||||||
|
mode === 'dark' ||
|
||||||
|
(mode === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches)
|
||||||
|
document.documentElement.classList.toggle('dark', dark)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 暗色主题:根元素 class + localStorage 持久化 + 跟随系统(§8.2)。
|
||||||
|
export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||||
|
const [mode, setMode] = useState<ThemeMode>(() => {
|
||||||
|
const saved = localStorage.getItem('pn-theme')
|
||||||
|
return saved === 'dark' || saved === 'light' || saved === 'system' ? saved : 'system'
|
||||||
|
})
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
localStorage.setItem('pn-theme', mode)
|
||||||
|
apply(mode)
|
||||||
|
if (mode === 'system') {
|
||||||
|
const mq = window.matchMedia('(prefers-color-scheme: dark)')
|
||||||
|
const onChange = () => apply('system')
|
||||||
|
mq.addEventListener('change', onChange)
|
||||||
|
return () => mq.removeEventListener('change', onChange)
|
||||||
|
}
|
||||||
|
}, [mode])
|
||||||
|
|
||||||
|
return <ThemeContext.Provider value={{ mode, setMode }}>{children}</ThemeContext.Provider>
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useTheme() {
|
||||||
|
const ctx = useContext(ThemeContext)
|
||||||
|
if (!ctx) throw new Error('useTheme 必须在 ThemeProvider 内使用')
|
||||||
|
return ctx
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
export function cn(...parts: Array<string | false | null | undefined>): string {
|
||||||
|
return parts.filter(Boolean).join(' ')
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatDate(unix: number): string {
|
||||||
|
return new Date(unix * 1000).toLocaleDateString('zh-CN', {
|
||||||
|
year: 'numeric',
|
||||||
|
month: 'long',
|
||||||
|
day: 'numeric',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatDateTime(unix: number): string {
|
||||||
|
return new Date(unix * 1000).toLocaleString('zh-CN', {
|
||||||
|
year: 'numeric',
|
||||||
|
month: '2-digit',
|
||||||
|
day: '2-digit',
|
||||||
|
hour: '2-digit',
|
||||||
|
minute: '2-digit',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// 前端 slug 预览:与服务端 slugify 同规则(ASCII 部分),纯非 ASCII 时提示将自动生成
|
||||||
|
export function slugPreview(title: string, date: Date): string {
|
||||||
|
const t = title.trim().toLowerCase().replace(/_/g, '-').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').replace(/^-+|-+$/g, '')
|
||||||
|
if (t === '') return `post-${date.getFullYear()}${String(date.getMonth() + 1).padStart(2, '0')}${String(date.getDate()).padStart(2, '0')}`
|
||||||
|
return t.slice(0, 80).replace(/-+$/g, '')
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import { StrictMode } from 'react'
|
||||||
|
import { createRoot } from 'react-dom/client'
|
||||||
|
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||||
|
import { BrowserRouter } from 'react-router'
|
||||||
|
import './index.css'
|
||||||
|
import App from './App'
|
||||||
|
import { AuthProvider } from './lib/auth'
|
||||||
|
import { ThemeProvider } from './lib/theme'
|
||||||
|
|
||||||
|
const queryClient = new QueryClient({
|
||||||
|
defaultOptions: {
|
||||||
|
queries: {
|
||||||
|
retry: 1,
|
||||||
|
refetchOnWindowFocus: false,
|
||||||
|
staleTime: 30_000,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
createRoot(document.getElementById('root')!).render(
|
||||||
|
<StrictMode>
|
||||||
|
<QueryClientProvider client={queryClient}>
|
||||||
|
<ThemeProvider>
|
||||||
|
<AuthProvider>
|
||||||
|
<BrowserRouter>
|
||||||
|
<App />
|
||||||
|
</BrowserRouter>
|
||||||
|
</AuthProvider>
|
||||||
|
</ThemeProvider>
|
||||||
|
</QueryClientProvider>
|
||||||
|
</StrictMode>,
|
||||||
|
)
|
||||||
@@ -0,0 +1,297 @@
|
|||||||
|
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||||
|
import { useNavigate, useParams } from 'react-router'
|
||||||
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { Bold, Italic, Link2, Code, Table, Eye, EyeOff } from 'lucide-react'
|
||||||
|
import { api, ApiError } from '../lib/api'
|
||||||
|
import type { NoteItem } from '../lib/api'
|
||||||
|
import Editor from '../components/Editor'
|
||||||
|
import MarkdownViewer from '../components/MarkdownViewer'
|
||||||
|
import { slugPreview } from '../lib/utils'
|
||||||
|
|
||||||
|
interface NoteFull extends NoteItem {
|
||||||
|
content: string
|
||||||
|
prev?: unknown
|
||||||
|
next?: unknown
|
||||||
|
}
|
||||||
|
|
||||||
|
type Form = {
|
||||||
|
title: string
|
||||||
|
slug: string
|
||||||
|
summary: string
|
||||||
|
content: string
|
||||||
|
status: 'public' | 'private'
|
||||||
|
tags: string
|
||||||
|
pinned: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
const emptyForm: Form = {
|
||||||
|
title: '',
|
||||||
|
slug: '',
|
||||||
|
summary: '',
|
||||||
|
content: '',
|
||||||
|
status: 'private',
|
||||||
|
tags: '',
|
||||||
|
pinned: false,
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function AdminEdit() {
|
||||||
|
const { id } = useParams()
|
||||||
|
const noteId = id ? Number(id) : null
|
||||||
|
const isNew = noteId === null
|
||||||
|
const navigate = useNavigate()
|
||||||
|
const qc = useQueryClient()
|
||||||
|
|
||||||
|
const { data: existing, isLoading } = useQuery({
|
||||||
|
queryKey: ['admin', 'note', noteId],
|
||||||
|
queryFn: () => api<NoteFull>(`/api/admin/notes/${noteId}`),
|
||||||
|
enabled: !isNew,
|
||||||
|
})
|
||||||
|
|
||||||
|
const [form, setForm] = useState<Form>(emptyForm)
|
||||||
|
const [savedAt, setSavedAt] = useState<number | null>(null)
|
||||||
|
const [errorMsg, setErrorMsg] = useState<string | null>(null)
|
||||||
|
const [slugFieldError, setSlugFieldError] = useState<string | null>(null)
|
||||||
|
const [showPreview, setShowPreview] = useState(true)
|
||||||
|
const [uploadMsg, setUploadMsg] = useState<string | null>(null)
|
||||||
|
const dirtyRef = useRef(false)
|
||||||
|
const slugTouchedRef = useRef(false)
|
||||||
|
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (existing) {
|
||||||
|
setForm({
|
||||||
|
title: existing.title,
|
||||||
|
slug: existing.slug,
|
||||||
|
summary: existing.summary,
|
||||||
|
content: existing.content,
|
||||||
|
status: existing.status === 'public' ? 'public' : 'private',
|
||||||
|
tags: existing.tags.join(', '),
|
||||||
|
pinned: existing.pinned,
|
||||||
|
})
|
||||||
|
slugTouchedRef.current = false
|
||||||
|
dirtyRef.current = false
|
||||||
|
}
|
||||||
|
}, [existing])
|
||||||
|
|
||||||
|
const set = <K extends keyof Form>(key: K, value: Form[K]) => {
|
||||||
|
setForm((f) => ({ ...f, [key]: value }))
|
||||||
|
dirtyRef.current = true
|
||||||
|
if (key === 'slug') slugTouchedRef.current = true
|
||||||
|
setErrorMsg(null)
|
||||||
|
}
|
||||||
|
|
||||||
|
const save = useMutation({
|
||||||
|
mutationFn: async (f: Form) => {
|
||||||
|
const payload = {
|
||||||
|
title: f.title,
|
||||||
|
slug: f.slug,
|
||||||
|
summary: f.summary,
|
||||||
|
content: f.content,
|
||||||
|
status: f.status,
|
||||||
|
tags: f.tags.split(/[,,]/).map((t) => t.trim()).filter(Boolean),
|
||||||
|
pinned: f.pinned,
|
||||||
|
}
|
||||||
|
if (isNew) {
|
||||||
|
// 新建:slug 由服务端从标题自动生成(首次保存即定稿,§8.2)
|
||||||
|
return api<NoteFull>('/api/admin/notes', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ ...payload, slug: '' }),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return api<NoteFull>(`/api/admin/notes/${noteId}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
})
|
||||||
|
},
|
||||||
|
onSuccess: (saved) => {
|
||||||
|
setSavedAt(Date.now())
|
||||||
|
setSlugFieldError(null)
|
||||||
|
setErrorMsg(null)
|
||||||
|
dirtyRef.current = false
|
||||||
|
void qc.invalidateQueries({ queryKey: ['admin'] })
|
||||||
|
if (isNew) {
|
||||||
|
navigate(`/admin/notes/${saved.id}/edit`, { replace: true })
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onError: (e) => {
|
||||||
|
if (e instanceof ApiError && e.code === 'slug_conflict') {
|
||||||
|
setSlugFieldError(e.message)
|
||||||
|
} else {
|
||||||
|
setErrorMsg(e instanceof Error ? e.message : '保存失败')
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const canSave = form.title.trim().length > 0
|
||||||
|
const autosaveReady = !isNew || form.content.trim().length > 0
|
||||||
|
|
||||||
|
// 自动保存:防抖 2s(§8.2)
|
||||||
|
useEffect(() => {
|
||||||
|
if (!canSave || !autosaveReady || !dirtyRef.current) return
|
||||||
|
if (timerRef.current) clearTimeout(timerRef.current)
|
||||||
|
timerRef.current = setTimeout(() => {
|
||||||
|
if (dirtyRef.current) save.mutate(form)
|
||||||
|
}, 2000)
|
||||||
|
return () => {
|
||||||
|
if (timerRef.current) clearTimeout(timerRef.current)
|
||||||
|
}
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [form, canSave, autosaveReady])
|
||||||
|
|
||||||
|
const wrapSelection = useCallback(
|
||||||
|
(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) {
|
||||||
|
return <p className="py-12 text-center text-zinc-400">加载中…</p>
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex h-[calc(100vh-8rem)] flex-col">
|
||||||
|
<div className="mb-3 flex items-center gap-3">
|
||||||
|
<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
|
||||||
|
type="button"
|
||||||
|
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 ? '隐藏预览' : '显示预览'}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => save.mutate(form)}
|
||||||
|
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"
|
||||||
|
>
|
||||||
|
{save.isPending ? '保存中…' : '保存'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mb-2 flex flex-wrap items-center gap-2 text-xs text-zinc-400">
|
||||||
|
<button type="button" onClick={() => wrapSelection('**')} className="rounded p-1 hover:bg-zinc-100 dark:hover:bg-zinc-800"><Bold size={14} /></button>
|
||||||
|
<button type="button" onClick={() => wrapSelection('*')} className="rounded p-1 hover:bg-zinc-100 dark:hover:bg-zinc-800"><Italic size={14} /></button>
|
||||||
|
<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>
|
||||||
|
<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>
|
||||||
|
<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>
|
||||||
|
<span className="mx-1 text-zinc-300 dark:text-zinc-700">|</span>
|
||||||
|
<span>粘贴 / 拖拽图片即可上传</span>
|
||||||
|
<span className="ml-auto">
|
||||||
|
{save.isPending
|
||||||
|
? '保存中…'
|
||||||
|
: savedAt
|
||||||
|
? `已保存 ${new Date(savedAt).toLocaleTimeString('zh-CN')}`
|
||||||
|
: isNew
|
||||||
|
? '未保存'
|
||||||
|
: '无改动'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex min-h-0 flex-1 gap-3">
|
||||||
|
<div className="flex min-w-0 flex-1 flex-col gap-3">
|
||||||
|
<div className="min-h-0 flex-1">
|
||||||
|
<Editor
|
||||||
|
value={form.content}
|
||||||
|
onChange={(v) => set('content', v)}
|
||||||
|
onUploadStart={(name) => setUploadMsg(`上传中:${name}…`)}
|
||||||
|
onUploadEnd={(err) => setUploadMsg(err ?? null)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{uploadMsg && <p className="text-xs text-zinc-400">{uploadMsg}</p>}
|
||||||
|
{showPreview && (
|
||||||
|
<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} />
|
||||||
|
</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>
|
||||||
|
<label className="text-xs font-medium text-zinc-500">slug</label>
|
||||||
|
<input
|
||||||
|
value={form.slug}
|
||||||
|
onChange={(e) => set('slug', e.target.value)}
|
||||||
|
placeholder={form.title ? slugPreview(form.title, new Date()) : '保存后自动生成'}
|
||||||
|
className={`mt-1 w-full rounded-md border px-2 py-1.5 font-mono text-xs outline-none ${
|
||||||
|
slugFieldError
|
||||||
|
? 'border-red-500 bg-red-50 dark:bg-red-950'
|
||||||
|
: 'border-zinc-300 dark:border-zinc-700'
|
||||||
|
}`}
|
||||||
|
/>
|
||||||
|
{slugFieldError && <p className="mt-1 text-xs text-red-600">{slugFieldError}</p>}
|
||||||
|
<p className="mt-1 text-[10px] leading-relaxed text-zinc-400">
|
||||||
|
留空保持不变;首次保存自动生成后定稿
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="text-xs font-medium text-zinc-500">标签(逗号分隔)</label>
|
||||||
|
<input
|
||||||
|
value={form.tags}
|
||||||
|
onChange={(e) => set('tags', e.target.value)}
|
||||||
|
placeholder="随笔, go"
|
||||||
|
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>
|
||||||
|
<div>
|
||||||
|
<label className="text-xs font-medium text-zinc-500">摘要(留空自动截取正文)</label>
|
||||||
|
<textarea
|
||||||
|
value={form.summary}
|
||||||
|
onChange={(e) => set('summary', e.target.value)}
|
||||||
|
rows={3}
|
||||||
|
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>
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-xs font-medium text-zinc-500">公开</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
role="switch"
|
||||||
|
aria-checked={form.status === 'public'}
|
||||||
|
onClick={() => set('status', form.status === 'public' ? 'private' : 'public')}
|
||||||
|
className={`relative h-5 w-9 rounded-full transition ${
|
||||||
|
form.status === 'public' ? 'bg-green-500' : 'bg-zinc-300 dark:bg-zinc-700'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
className={`absolute top-0.5 h-4 w-4 rounded-full bg-white transition-all ${
|
||||||
|
form.status === 'public' ? 'left-[1.15rem]' : 'left-0.5'
|
||||||
|
}`}
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-xs font-medium text-zinc-500">置顶</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
role="switch"
|
||||||
|
aria-checked={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'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
className={`absolute top-0.5 h-4 w-4 rounded-full bg-white transition-all ${
|
||||||
|
form.pinned ? 'left-[1.15rem]' : 'left-0.5'
|
||||||
|
}`}
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{errorMsg && <p className="text-xs text-red-600">{errorMsg}</p>}
|
||||||
|
</aside>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
import { Link, useNavigate } from 'react-router'
|
||||||
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { Pencil, Plus, Trash2 } from 'lucide-react'
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { api } from '../lib/api'
|
||||||
|
import type { NoteItem } from '../lib/api'
|
||||||
|
import { useAuth } from '../lib/auth'
|
||||||
|
import { formatDateTime } from '../lib/utils'
|
||||||
|
|
||||||
|
function useAdminNotes() {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ['admin', 'notes'],
|
||||||
|
queryFn: () => api<{ items: NoteItem[]; total: number }>('/api/admin/notes'),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function AdminList() {
|
||||||
|
const { data, isLoading } = useAdminNotes()
|
||||||
|
const { logout } = useAuth()
|
||||||
|
const navigate = useNavigate()
|
||||||
|
const qc = useQueryClient()
|
||||||
|
const [confirmId, setConfirmId] = useState<number | null>(null)
|
||||||
|
|
||||||
|
const trashMutation = useMutation({
|
||||||
|
mutationFn: (id: number) => api(`/api/admin/notes/${id}`, { method: 'DELETE' }),
|
||||||
|
onSuccess: () => {
|
||||||
|
setConfirmId(null)
|
||||||
|
void qc.invalidateQueries({ queryKey: ['admin'] })
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const toggleStatus = useMutation({
|
||||||
|
mutationFn: async (note: NoteItem) => {
|
||||||
|
// 状态切换:读全文 → 翻转 status → PUT
|
||||||
|
const full = await api<NoteItem & { content: string }>(`/api/admin/notes/${note.id}`)
|
||||||
|
return api(`/api/admin/notes/${note.id}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify({
|
||||||
|
title: full.title,
|
||||||
|
slug: full.slug,
|
||||||
|
summary: full.summary,
|
||||||
|
content: full.content,
|
||||||
|
status: full.status === 'public' ? 'private' : 'public',
|
||||||
|
tags: full.tags,
|
||||||
|
pinned: full.pinned,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
},
|
||||||
|
onSuccess: () => void qc.invalidateQueries({ queryKey: ['admin'] }),
|
||||||
|
})
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div className="mb-4 flex items-center justify-between">
|
||||||
|
<h1 className="text-lg font-semibold">笔记管理({data?.total ?? 0})</h1>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Link
|
||||||
|
to="/admin/notes/new"
|
||||||
|
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"
|
||||||
|
>
|
||||||
|
<Plus size={15} /> 新建
|
||||||
|
</Link>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => void logout().then(() => navigate('/'))}
|
||||||
|
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"
|
||||||
|
>
|
||||||
|
登出
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{isLoading ? (
|
||||||
|
<p className="py-12 text-center text-zinc-400">加载中…</p>
|
||||||
|
) : !data || data.items.length === 0 ? (
|
||||||
|
<p className="py-12 text-center text-zinc-400">还没有笔记,点击「新建」开始</p>
|
||||||
|
) : (
|
||||||
|
<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) => (
|
||||||
|
<li key={n.id} className="flex items-center gap-3 px-4 py-3">
|
||||||
|
<span
|
||||||
|
className={`rounded px-1.5 py-0.5 text-xs ${
|
||||||
|
n.status === 'public'
|
||||||
|
? 'bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-400'
|
||||||
|
: 'bg-zinc-100 text-zinc-500 dark:bg-zinc-800 dark:text-zinc-400'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{n.status === 'public' ? '公开' : '私有'}
|
||||||
|
</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
|
||||||
|
type="button"
|
||||||
|
onClick={() => void toggleStatus.mutate(n)}
|
||||||
|
disabled={toggleStatus.isPending}
|
||||||
|
className="rounded px-2 py-1 text-xs text-zinc-500 hover:bg-zinc-100 disabled:opacity-50 dark:hover:bg-zinc-800"
|
||||||
|
>
|
||||||
|
{n.status === 'public' ? '转私有' : '转公开'}
|
||||||
|
</button>
|
||||||
|
<Link
|
||||||
|
to={`/admin/notes/${n.id}/edit`}
|
||||||
|
className="rounded p-1.5 text-zinc-500 hover:bg-zinc-100 dark:hover:bg-zinc-800"
|
||||||
|
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>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { api, ApiError } from '../lib/api'
|
||||||
|
import type { SiteSettings } from '../lib/api'
|
||||||
|
|
||||||
|
export default function AdminSettings() {
|
||||||
|
const qc = useQueryClient()
|
||||||
|
const { data } = useQuery({
|
||||||
|
queryKey: ['admin', 'settings'],
|
||||||
|
queryFn: () => api<SiteSettings>('/api/admin/settings'),
|
||||||
|
})
|
||||||
|
|
||||||
|
const [title, setTitle] = useState('')
|
||||||
|
const [desc, setDesc] = useState('')
|
||||||
|
const [pageSize, setPageSize] = useState(10)
|
||||||
|
const [msg, setMsg] = useState<string | null>(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (data) {
|
||||||
|
setTitle(data.site_title)
|
||||||
|
setDesc(data.site_desc)
|
||||||
|
setPageSize(data.page_size)
|
||||||
|
}
|
||||||
|
}, [data])
|
||||||
|
|
||||||
|
const saveSettings = useMutation({
|
||||||
|
mutationFn: () =>
|
||||||
|
api('/api/admin/settings', {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify({ site_title: title, site_desc: desc, page_size: pageSize }),
|
||||||
|
}),
|
||||||
|
onSuccess: () => {
|
||||||
|
setMsg('已保存')
|
||||||
|
void qc.invalidateQueries({ queryKey: ['site'] })
|
||||||
|
},
|
||||||
|
onError: (e) => setMsg(e instanceof ApiError ? e.message : '保存失败'),
|
||||||
|
})
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="max-w-lg space-y-10">
|
||||||
|
<section>
|
||||||
|
<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>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ChangePassword() {
|
||||||
|
const [oldPw, setOldPw] = useState('')
|
||||||
|
const [newPw, setNewPw] = useState('')
|
||||||
|
const [msg, setMsg] = useState<string | null>(null)
|
||||||
|
const [ok, setOk] = useState(false)
|
||||||
|
|
||||||
|
const change = useMutation({
|
||||||
|
mutationFn: () =>
|
||||||
|
api('/api/admin/password', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ old_password: oldPw, new_password: newPw }),
|
||||||
|
}),
|
||||||
|
onSuccess: () => {
|
||||||
|
setOk(true)
|
||||||
|
setMsg('密码已修改')
|
||||||
|
setOldPw('')
|
||||||
|
setNewPw('')
|
||||||
|
},
|
||||||
|
onError: (e) => {
|
||||||
|
setOk(false)
|
||||||
|
if (e instanceof ApiError) {
|
||||||
|
setMsg(e.code === 'weak_password' ? '新密码长度至少 12 个字符' : e.status === 429 ? '尝试过于频繁,请稍后再试' : '旧密码不正确')
|
||||||
|
} else {
|
||||||
|
setMsg('修改失败')
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section>
|
||||||
|
<h2 className="mb-4 text-lg font-semibold">修改密码</h2>
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<label className="text-xs font-medium text-zinc-500" htmlFor="old-pw">旧密码</label>
|
||||||
|
<input
|
||||||
|
id="old-pw"
|
||||||
|
type="password"
|
||||||
|
value={oldPw}
|
||||||
|
onChange={(e) => setOldPw(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="new-pw">新密码(≥12 字符)</label>
|
||||||
|
<input
|
||||||
|
id="new-pw"
|
||||||
|
type="password"
|
||||||
|
value={newPw}
|
||||||
|
onChange={(e) => setNewPw(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 className="flex items-center gap-3">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => change.mutate()}
|
||||||
|
disabled={change.isPending || oldPw.length === 0 || newPw.length === 0}
|
||||||
|
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"
|
||||||
|
>
|
||||||
|
{change.isPending ? '提交中…' : '修改密码'}
|
||||||
|
</button>
|
||||||
|
{msg && <span className={`text-sm ${ok ? 'text-green-600' : 'text-red-600'}`}>{msg}</span>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { RotateCcw } from 'lucide-react'
|
||||||
|
import { api } from '../lib/api'
|
||||||
|
import type { NoteItem } from '../lib/api'
|
||||||
|
import { formatDateTime } from '../lib/utils'
|
||||||
|
|
||||||
|
export default function AdminTrash() {
|
||||||
|
const qc = useQueryClient()
|
||||||
|
const { data, isLoading } = useQuery({
|
||||||
|
queryKey: ['admin', 'trash'],
|
||||||
|
queryFn: () => api<{ items: NoteItem[]; total: number }>('/api/admin/trash'),
|
||||||
|
})
|
||||||
|
|
||||||
|
const restore = useMutation({
|
||||||
|
mutationFn: (id: number) => api(`/api/admin/trash/${id}/restore`, { method: 'POST' }),
|
||||||
|
onSuccess: () => void qc.invalidateQueries({ queryKey: ['admin'] }),
|
||||||
|
})
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<h1 className="mb-4 text-lg font-semibold">回收站({data?.total ?? 0})</h1>
|
||||||
|
<p className="mb-4 text-sm text-zinc-400">软删除的笔记保留 30 天,到期由每日 gc 物理清除;恢复后图片引用天然保全。</p>
|
||||||
|
{isLoading ? (
|
||||||
|
<p className="py-12 text-center text-zinc-400">加载中…</p>
|
||||||
|
) : !data || data.items.length === 0 ? (
|
||||||
|
<p className="py-12 text-center text-zinc-400">回收站是空的</p>
|
||||||
|
) : (
|
||||||
|
<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) => (
|
||||||
|
<li key={n.id} className="flex items-center gap-3 px-4 py-3">
|
||||||
|
<span className="rounded bg-zinc-100 px-1.5 py-0.5 text-xs text-zinc-500 dark:bg-zinc-800">
|
||||||
|
{n.status === 'public' ? '公开' : '私有'}
|
||||||
|
</span>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<p className="truncate font-medium">{n.title}</p>
|
||||||
|
<p className="truncate text-xs text-zinc-400">
|
||||||
|
/{n.slug} · 删除于 {formatDateTime(n.deleted_at ?? 0)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => restore.mutate(n.id)}
|
||||||
|
disabled={restore.isPending}
|
||||||
|
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"
|
||||||
|
>
|
||||||
|
<RotateCcw size={13} /> 恢复
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
{restore.isError && <p className="mt-3 text-sm text-red-600">恢复失败,请重试</p>}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
import { useState } from 'react'
|
||||||
|
import { Link } from 'react-router'
|
||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import { Pin } from 'lucide-react'
|
||||||
|
import { api } from '../lib/api'
|
||||||
|
import type { NoteItem, NoteList, TagCount } from '../lib/api'
|
||||||
|
import { formatDate } from '../lib/utils'
|
||||||
|
|
||||||
|
function useNotes(page: number, tag?: string) {
|
||||||
|
const qs = new URLSearchParams({ page: String(page), page_size: '10' })
|
||||||
|
if (tag) qs.set('tag', tag)
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ['notes', page, tag ?? ''],
|
||||||
|
queryFn: () => api<NoteList>(`/api/notes?${qs}`),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function useTags() {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ['tags'],
|
||||||
|
queryFn: () => api<{ tags: TagCount[] }>('/api/tags'),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function NoteCard({ note }: { note: NoteItem }) {
|
||||||
|
return (
|
||||||
|
<article className="group border-b border-zinc-100 py-6 first:pt-0 dark:border-zinc-900">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
{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">
|
||||||
|
<Pin size={11} /> 置顶
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
<time className="text-xs text-zinc-400">{formatDate(note.updated_at)}</time>
|
||||||
|
</div>
|
||||||
|
<h2 className="mt-1 text-xl font-semibold leading-snug">
|
||||||
|
<Link
|
||||||
|
to={`/notes/${encodeURIComponent(note.slug)}`}
|
||||||
|
className="hover:text-blue-600 dark:hover:text-blue-400"
|
||||||
|
>
|
||||||
|
{note.title}
|
||||||
|
</Link>
|
||||||
|
</h2>
|
||||||
|
{note.summary && (
|
||||||
|
<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 && (
|
||||||
|
<div className="mt-3 flex flex-wrap gap-2">
|
||||||
|
{note.tags.map((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>
|
||||||
|
)}
|
||||||
|
</article>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Home() {
|
||||||
|
const [page, setPage] = useState(1)
|
||||||
|
const { data, isLoading } = useNotes(page)
|
||||||
|
const { data: tagsData } = useTags()
|
||||||
|
const totalPages = data ? Math.max(1, Math.ceil(data.total / data.page_size)) : 1
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col gap-8 lg:flex-row-reverse">
|
||||||
|
<aside className="lg:w-48 lg:shrink-0">
|
||||||
|
{tagsData && tagsData.tags.length > 0 && (
|
||||||
|
<div className="rounded-lg border border-zinc-200 p-4 dark:border-zinc-800">
|
||||||
|
<h3 className="mb-2 text-xs font-medium uppercase tracking-wider text-zinc-400">标签</h3>
|
||||||
|
<div className="flex flex-wrap gap-2 lg:flex-col lg:gap-1">
|
||||||
|
{tagsData.tags.map((t) => (
|
||||||
|
<Link
|
||||||
|
key={t.name}
|
||||||
|
to={`/tags/${encodeURIComponent(t.name)}`}
|
||||||
|
className="text-sm text-zinc-600 hover:text-blue-600 dark:text-zinc-400 dark:hover:text-blue-400"
|
||||||
|
>
|
||||||
|
#{t.name} <span className="text-zinc-400">({t.count})</span>
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</aside>
|
||||||
|
<section className="min-w-0 flex-1">
|
||||||
|
{isLoading ? (
|
||||||
|
<p className="py-12 text-center text-zinc-400">加载中…</p>
|
||||||
|
) : !data || data.items.length === 0 ? (
|
||||||
|
<p className="py-12 text-center text-zinc-400">还没有公开的笔记</p>
|
||||||
|
) : (
|
||||||
|
data.items.map((n) => <NoteCard 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>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
import { useState } from 'react'
|
||||||
|
import { useNavigate } from 'react-router'
|
||||||
|
import { Lock } from 'lucide-react'
|
||||||
|
import { useAuth } from '../lib/auth'
|
||||||
|
import { ApiError } from '../lib/api'
|
||||||
|
|
||||||
|
export default function Login() {
|
||||||
|
const { login, authenticated } = useAuth()
|
||||||
|
const navigate = useNavigate()
|
||||||
|
const [password, setPassword] = useState('')
|
||||||
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
const [submitting, setSubmitting] = useState(false)
|
||||||
|
|
||||||
|
if (authenticated) {
|
||||||
|
navigate('/admin', { replace: true })
|
||||||
|
}
|
||||||
|
|
||||||
|
const onSubmit = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault()
|
||||||
|
setError(null)
|
||||||
|
setSubmitting(true)
|
||||||
|
try {
|
||||||
|
await login(password)
|
||||||
|
navigate('/admin', { replace: true })
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof ApiError) {
|
||||||
|
setError(err.status === 429 ? '尝试过于频繁,请稍后再试' : '密码错误')
|
||||||
|
} else {
|
||||||
|
setError('登录失败,请重试')
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-screen items-center justify-center px-4">
|
||||||
|
<form
|
||||||
|
onSubmit={onSubmit}
|
||||||
|
className="w-full max-w-sm rounded-xl border border-zinc-200 p-8 dark:border-zinc-800"
|
||||||
|
>
|
||||||
|
<div className="mb-6 flex items-center justify-center gap-2 text-zinc-500">
|
||||||
|
<Lock size={18} />
|
||||||
|
<h1 className="text-lg font-semibold text-zinc-900 dark:text-zinc-100">管理员登录</h1>
|
||||||
|
</div>
|
||||||
|
<label className="block text-sm text-zinc-600 dark:text-zinc-400" htmlFor="password">
|
||||||
|
口令
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="password"
|
||||||
|
type="password"
|
||||||
|
autoFocus
|
||||||
|
required
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
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"
|
||||||
|
placeholder="输入管理员口令"
|
||||||
|
/>
|
||||||
|
{error && <p className="mt-2 text-sm text-red-600 dark:text-red-400">{error}</p>}
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={submitting || password.length === 0}
|
||||||
|
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"
|
||||||
|
>
|
||||||
|
{submitting ? '登录中…' : '登录'}
|
||||||
|
</button>
|
||||||
|
<p className="mt-4 text-center text-xs text-zinc-400">连续失败将被暂时锁定</p>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { Link } from 'react-router'
|
||||||
|
|
||||||
|
export default function NotFound() {
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-[60vh] flex-col items-center justify-center">
|
||||||
|
<p className="text-6xl font-bold text-zinc-200 dark:text-zinc-800">404</p>
|
||||||
|
<p className="mt-4 text-zinc-500">页面不存在</p>
|
||||||
|
<Link to="/" className="mt-6 text-sm text-blue-600 hover:underline">
|
||||||
|
← 返回首页
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
import { Link, useParams } from 'react-router'
|
||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import { AlertTriangle } from 'lucide-react'
|
||||||
|
import { api } from '../lib/api'
|
||||||
|
import type { NoteDetail } from '../lib/api'
|
||||||
|
import { useAuth } from '../lib/auth'
|
||||||
|
import MarkdownViewer from '../components/MarkdownViewer'
|
||||||
|
import { formatDate } from '../lib/utils'
|
||||||
|
|
||||||
|
export default function Note() {
|
||||||
|
const { slug = '' } = useParams()
|
||||||
|
const { authenticated } = useAuth()
|
||||||
|
const { data: note, isLoading, error } = useQuery({
|
||||||
|
queryKey: ['note', slug],
|
||||||
|
queryFn: () => api<NoteDetail>(`/api/notes/${encodeURIComponent(slug)}`),
|
||||||
|
retry: false,
|
||||||
|
})
|
||||||
|
|
||||||
|
if (isLoading) return <p className="py-12 text-center text-zinc-400">加载中…</p>
|
||||||
|
if (error || !note) {
|
||||||
|
return (
|
||||||
|
<div className="py-12 text-center">
|
||||||
|
<p className="text-4xl font-bold text-zinc-300 dark:text-zinc-700">404</p>
|
||||||
|
<p className="mt-2 text-zinc-500">笔记不存在或未公开</p>
|
||||||
|
<Link to="/" className="mt-4 inline-block text-sm text-blue-600 hover:underline">
|
||||||
|
← 返回首页
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const privatePreview = note.status === 'private'
|
||||||
|
|
||||||
|
return (
|
||||||
|
<article>
|
||||||
|
<nav className="mb-4 text-xs text-zinc-400">
|
||||||
|
<Link to="/" className="hover:text-zinc-600">首页</Link>
|
||||||
|
<span className="mx-1.5">/</span>
|
||||||
|
<span>{note.title}</span>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
{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">
|
||||||
|
<AlertTriangle size={16} />
|
||||||
|
私有预览:此笔记未公开,仅管理员可见
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<header className="mb-8">
|
||||||
|
<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">
|
||||||
|
<time>{formatDate(note.created_at)}</time>
|
||||||
|
{note.tags.map((t) => (
|
||||||
|
<Link
|
||||||
|
key={t}
|
||||||
|
to={`/tags/${encodeURIComponent(t)}`}
|
||||||
|
className="rounded-full bg-zinc-100 px-2 py-0.5 hover:bg-zinc-200 dark:bg-zinc-800 dark:hover:bg-zinc-700"
|
||||||
|
>
|
||||||
|
#{t}
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<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">
|
||||||
|
{note.prev ? (
|
||||||
|
<Link
|
||||||
|
to={`/notes/${encodeURIComponent(note.prev.slug)}`}
|
||||||
|
className="text-zinc-600 hover:text-blue-600 dark:text-zinc-400"
|
||||||
|
>
|
||||||
|
← {note.prev.title}
|
||||||
|
</Link>
|
||||||
|
) : (
|
||||||
|
<span />
|
||||||
|
)}
|
||||||
|
{note.next ? (
|
||||||
|
<Link
|
||||||
|
to={`/notes/${encodeURIComponent(note.next.slug)}`}
|
||||||
|
className="text-right text-zinc-600 hover:text-blue-600 dark:text-zinc-400"
|
||||||
|
>
|
||||||
|
{note.next.title} →
|
||||||
|
</Link>
|
||||||
|
) : (
|
||||||
|
<span />
|
||||||
|
)}
|
||||||
|
</nav>
|
||||||
|
</article>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import { Link, useParams } from 'react-router'
|
||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import { api } from '../lib/api'
|
||||||
|
import type { NoteList } from '../lib/api'
|
||||||
|
import { formatDate } from '../lib/utils'
|
||||||
|
|
||||||
|
export default function TagPage() {
|
||||||
|
const { tag = '' } = useParams()
|
||||||
|
const { data, isLoading } = useQuery({
|
||||||
|
queryKey: ['tag', tag],
|
||||||
|
queryFn: () => api<NoteList>(`/api/notes?tag=${encodeURIComponent(tag)}&page=1&page_size=100`),
|
||||||
|
})
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<header className="mb-6">
|
||||||
|
<nav className="mb-2 text-xs text-zinc-400">
|
||||||
|
<Link to="/" className="hover:text-zinc-600">首页</Link>
|
||||||
|
<span className="mx-1.5">/</span>
|
||||||
|
<span>标签</span>
|
||||||
|
</nav>
|
||||||
|
<h1 className="text-2xl font-bold">#{tag}</h1>
|
||||||
|
<p className="mt-1 text-sm text-zinc-400">{data?.total ?? 0} 篇</p>
|
||||||
|
</header>
|
||||||
|
{isLoading ? (
|
||||||
|
<p className="py-12 text-center text-zinc-400">加载中…</p>
|
||||||
|
) : !data || data.items.length === 0 ? (
|
||||||
|
<p className="py-12 text-center text-zinc-400">该标签下暂无公开笔记</p>
|
||||||
|
) : (
|
||||||
|
<ul className="divide-y divide-zinc-100 dark:divide-zinc-900">
|
||||||
|
{data.items.map((n) => (
|
||||||
|
<li key={n.slug} className="py-4">
|
||||||
|
<Link
|
||||||
|
to={`/notes/${encodeURIComponent(n.slug)}`}
|
||||||
|
className="font-medium hover:text-blue-600 dark:hover:text-blue-400"
|
||||||
|
>
|
||||||
|
{n.title}
|
||||||
|
</Link>
|
||||||
|
<time className="ml-3 text-xs text-zinc-400">{formatDate(n.updated_at)}</time>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
// 渲染管线安全测试(§13 前端测试组):
|
||||||
|
// 1) sanitize schema 快照:禁 script/iframe/style/事件属性,允许任务列表 checkbox;
|
||||||
|
// 2) 对恶意 Markdown 的冒烟用例:渲染输出无脚本执行面。
|
||||||
|
import { describe, it, expect } from 'vitest'
|
||||||
|
import { render } from '@testing-library/react'
|
||||||
|
import MarkdownViewer from '../src/components/MarkdownViewer'
|
||||||
|
import { sanitizeSchema } from '../src/lib/sanitize'
|
||||||
|
|
||||||
|
const tagNames = (sanitizeSchema as { tagNames?: string[] }).tagNames ?? []
|
||||||
|
|
||||||
|
describe('sanitize schema 白名单', () => {
|
||||||
|
it('禁止危险标签', () => {
|
||||||
|
for (const dangerous of ['script', 'iframe', 'object', 'embed', 'form', 'style', 'link', 'meta']) {
|
||||||
|
expect(tagNames).not.toContain(dangerous)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('允许任务列表 checkbox(input type=checkbox + checked/disabled)', () => {
|
||||||
|
const attrs = (sanitizeSchema as { attributes: Record<string, unknown> }).attributes
|
||||||
|
expect(attrs.input).toBeDefined()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('渲染管线对恶意 Markdown 的冒烟', () => {
|
||||||
|
const malicious = [
|
||||||
|
'<script>window.__xss=1</script>',
|
||||||
|
'<img src=x onerror="window.__xss=1">',
|
||||||
|
'[click](javascript:alert(1))',
|
||||||
|
'<iframe src="https://evil.example"></iframe>',
|
||||||
|
'<a href="javascript:alert(1)">x</a>',
|
||||||
|
'<div style="background:url(javascript:alert(1))">x</div>',
|
||||||
|
'<svg><script>alert(1)</script></svg>',
|
||||||
|
].join('\n\n')
|
||||||
|
|
||||||
|
it('输出不包含任何脚本/事件/危险协议', () => {
|
||||||
|
const { container } = render(<MarkdownViewer source={malicious} />)
|
||||||
|
expect(window.__xss).toBeUndefined()
|
||||||
|
expect(container.querySelector('script')).toBeNull()
|
||||||
|
expect(container.querySelector('iframe')).toBeNull()
|
||||||
|
expect(container.querySelectorAll('[onclick], [onerror], [onload]')).toHaveLength(0)
|
||||||
|
container.querySelectorAll('a').forEach((a) => {
|
||||||
|
const href = a.getAttribute('href') ?? ''
|
||||||
|
expect(href.startsWith('javascript:')).toBe(false)
|
||||||
|
})
|
||||||
|
expect(container.innerHTML.includes('style=')).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('任务列表渲染为 disabled checkbox', () => {
|
||||||
|
const { container } = render(<MarkdownViewer source={'- [x] 完成\n- [ ] 待办'} />)
|
||||||
|
const boxes = container.querySelectorAll('input[type="checkbox"]')
|
||||||
|
expect(boxes.length).toBe(2)
|
||||||
|
boxes.forEach((b) => expect(b.hasAttribute('disabled')).toBe(true))
|
||||||
|
})
|
||||||
|
|
||||||
|
it('普通 GFM(表格/删除线)正常渲染', () => {
|
||||||
|
const { container } = render(
|
||||||
|
<MarkdownViewer source={'| a | b |\n| --- | --- |\n| 1 | 2 |\n\n~~删除~~'} />,
|
||||||
|
)
|
||||||
|
expect(container.querySelector('table')).not.toBeNull()
|
||||||
|
expect(container.querySelector('del')).not.toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('不泄漏 react-markdown 的 node prop 到 DOM', () => {
|
||||||
|
const { container } = render(<MarkdownViewer source={'- [x] 完成\n\n[链接](https://example.com)'} />)
|
||||||
|
expect(container.innerHTML.includes('node=')).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// 供断言使用
|
||||||
|
declare global {
|
||||||
|
interface Window {
|
||||||
|
__xss?: number
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2022",
|
||||||
|
"useDefineForClassFields": true,
|
||||||
|
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||||
|
"module": "ESNext",
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
|
"verbatimModuleSyntax": true,
|
||||||
|
"moduleDetection": "force",
|
||||||
|
"noEmit": true,
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
"strict": true,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true,
|
||||||
|
"noFallthroughCasesInSwitch": true,
|
||||||
|
"types": ["vite/client"]
|
||||||
|
},
|
||||||
|
"include": ["src", "tests"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { defineConfig } from 'vite'
|
||||||
|
import react from '@vitejs/plugin-react'
|
||||||
|
import tailwindcss from '@tailwindcss/vite'
|
||||||
|
|
||||||
|
// https://vite.dev/config/
|
||||||
|
export default defineConfig({
|
||||||
|
// base 必须为默认 '/':相对 base 在 /notes/:slug 深链下会把资源解析到
|
||||||
|
// /notes/assets/… 导致白屏(设计 §8.3-2,禁止修改)
|
||||||
|
base: '/',
|
||||||
|
plugins: [react(), tailwindcss()],
|
||||||
|
server: {
|
||||||
|
proxy: {
|
||||||
|
// 同源是 Cookie/CSRF 成立的前提(§10.5)
|
||||||
|
'/api': 'http://127.0.0.1:8080',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
build: {
|
||||||
|
// 产物内容 hash 文件名(§8.3-5)
|
||||||
|
assetsDir: 'assets',
|
||||||
|
},
|
||||||
|
})
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { defineConfig } from 'vitest/config'
|
||||||
|
import react from '@vitejs/plugin-react'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [react()],
|
||||||
|
test: {
|
||||||
|
environment: 'jsdom',
|
||||||
|
include: ['tests/**/*.test.?(c|m)[jt]s?(x)'],
|
||||||
|
},
|
||||||
|
})
|
||||||
Reference in New Issue
Block a user