feat: 分类/变体体系 + 用户认证 + 管理后台

- 运行时分类体系:Shell/Python/JavaScript/Ruby/PHP 各含变体
- 用户注册/登录(JWT + bcrypt),首个注册用户为管理员
- 管理后台 /admin 动态管理分类和变体
- 脚本市场支持按分类筛选
- CodeMirror 语言模式根据分类名称自动切换
- 结果页展示该分类下所有变体的运行命令
- source 命令变体用于 Shell 类继承环境变量

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
2026-05-29 15:02:20 +08:00
parent 58a80cb196
commit 5414c9c865
24 changed files with 1309 additions and 295 deletions

View File

@@ -3,8 +3,14 @@ import Home from './pages/Home'
import ScriptDetail from './pages/ScriptDetail'
import DeleteScript from './pages/DeleteScript'
import Market from './pages/Market'
import Login from './pages/Login'
import Register from './pages/Register'
import Admin from './pages/Admin'
import { isLoggedIn } from './lib/api'
export default function App() {
const loggedIn = isLoggedIn()
return (
<div className="min-h-screen flex flex-col">
<header className="border-b border-gray-800">
@@ -15,6 +21,16 @@ export default function App() {
<nav className="flex gap-4 text-sm">
<Link to="/" className="text-gray-400 hover:text-blue-400 transition-colors"></Link>
<Link to="/create" className="text-gray-400 hover:text-blue-400 transition-colors"></Link>
{loggedIn ? (
<>
<Link to="/admin" className="text-gray-400 hover:text-blue-400 transition-colors"></Link>
<button onClick={() => { localStorage.removeItem('token'); window.location.reload() }} className="text-gray-500 hover:text-red-400 transition-colors cursor-pointer bg-transparent border-none text-sm">
退
</button>
</>
) : (
<Link to="/login" className="text-gray-400 hover:text-blue-400 transition-colors"></Link>
)}
</nav>
</div>
</header>
@@ -25,6 +41,9 @@ export default function App() {
<Route path="/create" element={<Home />} />
<Route path="/s/:id" element={<ScriptDetail />} />
<Route path="/s/:id/delete" element={<DeleteScript />} />
<Route path="/login" element={<Login />} />
<Route path="/register" element={<Register />} />
<Route path="/admin" element={<Admin />} />
</Routes>
</main>

View File

@@ -11,19 +11,18 @@ import { closeBrackets, closeBracketsKeymap } from '@codemirror/autocomplete'
import { lintKeymap } from '@codemirror/lint'
import { searchKeymap, highlightSelectionMatches } from '@codemirror/search'
// Legacy mode imports - use require-style to avoid TS path issues
// @ts-ignore
import { shell } from '@codemirror/legacy-modes/mode/shell'
// @ts-ignore
import { ruby } from '@codemirror/legacy-modes/mode/ruby'
function getLanguageExtension(runtime: string) {
switch (runtime) {
case 'bash': case 'zsh': case 'sh': case 'fish':
function getLanguageExtension(categoryName: string) {
switch (categoryName) {
case 'shell':
return StreamLanguage.define(shell)
case 'python3':
case 'python':
return python()
case 'node':
case 'javascript':
return javascript()
case 'ruby':
return StreamLanguage.define(ruby)
@@ -37,10 +36,10 @@ function getLanguageExtension(runtime: string) {
interface Props {
value: string
onChange: (value: string) => void
runtime: string
categoryName: string
}
export default function CodeEditor({ value, onChange, runtime }: Props) {
export default function CodeEditor({ value, onChange, categoryName }: Props) {
const ref = useRef<HTMLDivElement>(null)
const viewRef = useRef<EditorView | null>(null)
@@ -67,7 +66,7 @@ export default function CodeEditor({ value, onChange, runtime }: Props) {
...lintKeymap,
indentWithTab,
]),
getLanguageExtension(runtime),
getLanguageExtension(categoryName),
oneDark,
EditorView.updateListener.of((update) => {
if (update.docChanged) {
@@ -88,7 +87,7 @@ export default function CodeEditor({ value, onChange, runtime }: Props) {
view.destroy()
viewRef.current = null
}
}, [runtime])
}, [categoryName])
useEffect(() => {
const view = viewRef.current

View File

@@ -1,5 +1,5 @@
import { CreateScriptResponse, isShellRuntime, getSourceCommand } from '../types'
import CommandCard from './CommandCard'
import { CreateScriptResponse } from '../types'
import { Link } from 'react-router-dom'
interface Props {
result: CreateScriptResponse
@@ -7,10 +7,6 @@ interface Props {
}
export default function ResultCard({ result, onReset }: Props) {
const detailUrl = `${window.location.origin}/s/${result.id}`
const showSource = isShellRuntime(result.runtime)
const sourceCommand = showSource ? getSourceCommand(result.url, result.runtime) : null
return (
<div className="space-y-6">
<div className="text-center">
@@ -20,21 +16,6 @@ export default function ResultCard({ result, onReset }: Props) {
</h2>
</div>
<CommandCard command={result.command} />
{showSource && sourceCommand && (
<div>
<p className="text-xs text-gray-500 mb-2">
使 shell
</p>
<CommandCard
command={sourceCommand}
label="继承环境变量"
variant="secondary"
/>
</div>
)}
<div className="bg-gray-800/50 border border-gray-700 rounded-lg p-4 space-y-3">
<div className="flex justify-between text-sm">
<span className="text-gray-400"></span>
@@ -45,8 +26,10 @@ export default function ResultCard({ result, onReset }: Props) {
<span className="font-mono text-blue-400">{result.id}</span>
</div>
<div className="flex justify-between text-sm">
<span className="text-gray-400"></span>
<span>{result.runtime}</span>
<span className="text-gray-400"></span>
<a href={result.url} target="_blank" rel="noreferrer" className="font-mono text-blue-400 hover:underline break-all text-right max-w-[70%]">
{result.url}
</a>
</div>
<div className="flex justify-between text-sm">
<span className="text-gray-400"></span>
@@ -73,24 +56,12 @@ export default function ResultCard({ result, onReset }: Props) {
>
</button>
<a
href={detailUrl}
target="_blank"
rel="noreferrer"
<Link
to={`/s/${result.id}`}
className="px-4 py-2 bg-blue-600 hover:bg-blue-700 rounded-lg text-sm transition-colors"
>
</a>
{result.status === 'published' && (
<a
href={`${window.location.origin}/market`}
target="_blank"
rel="noreferrer"
className="px-4 py-2 bg-green-600/80 hover:bg-green-600 rounded-lg text-sm transition-colors"
>
</a>
)}
</Link>
</div>
</div>
)

View File

@@ -1,13 +1,21 @@
interface Props {
content: string
runtime: string
categoryName: string
}
export default function ScriptViewer({ content, runtime }: Props) {
const extMap: Record<string, string> = {
shell: 'sh',
python: 'py',
javascript: 'js',
ruby: 'rb',
php: 'php',
}
export default function ScriptViewer({ content, categoryName }: Props) {
return (
<div className="bg-gray-900 border border-gray-700 rounded-lg overflow-hidden">
<div className="flex items-center justify-between px-4 py-2 bg-gray-800/50 border-b border-gray-700">
<span className="text-xs text-gray-400 font-mono">script.{runtime === 'node' ? 'js' : runtime === 'python3' ? 'py' : runtime}</span>
<span className="text-xs text-gray-400 font-mono">script.{extMap[categoryName] || categoryName}</span>
<button
onClick={() => navigator.clipboard.writeText(content)}
className="text-xs text-gray-500 hover:text-blue-400 transition-colors"
@@ -20,4 +28,4 @@ export default function ScriptViewer({ content, runtime }: Props) {
</pre>
</div>
)
}
}

View File

@@ -1,4 +1,4 @@
import { CreateScriptResponse, ScriptDetail, RuntimeOption, ExpiresIn, MarketResponse } from '../types'
import { CreateScriptResponse, ScriptDetail, ExpiresIn, MarketResponse, RuntimeCategory, RuntimeVariant, AuthResponse } from '../types'
async function request<T>(url: string, options?: RequestInit): Promise<T> {
const res = await fetch(url, {
@@ -12,16 +12,21 @@ async function request<T>(url: string, options?: RequestInit): Promise<T> {
return res.json()
}
function getToken(): string {
return localStorage.getItem('token') || ''
}
export async function createScript(params: {
title: string
description?: string
content: string
runtime: RuntimeOption
category_id: number
expires_in: ExpiresIn
publish: boolean
}): Promise<CreateScriptResponse> {
return request('/api/scripts', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${getToken()}` },
body: JSON.stringify(params),
})
}
@@ -40,22 +45,109 @@ export async function deleteScript(id: string, token: string): Promise<void> {
await fetch(`/api/scripts/${id}?token=${encodeURIComponent(token)}`, {
method: 'DELETE',
}).then((res) => {
if (!res.ok && res.status !== 204) {
throw new Error('delete failed')
}
if (!res.ok && res.status !== 204) throw new Error('delete failed')
})
}
export async function listMarket(params: {
page?: number
per_page?: number
runtime?: string
category_id?: number
search?: string
}): Promise<MarketResponse> {
const query = new URLSearchParams()
if (params.page) query.set('page', String(params.page))
if (params.per_page) query.set('per_page', String(params.per_page))
if (params.runtime) query.set('runtime', params.runtime)
if (params.category_id) query.set('category_id', String(params.category_id))
if (params.search) query.set('search', params.search)
return request(`/api/market?${query.toString()}`)
}
export async function listCategories(): Promise<RuntimeCategory[]> {
const res = await request<{ categories: RuntimeCategory[] }>('/api/categories')
return res.categories || []
}
export async function register(username: string, password: string): Promise<AuthResponse> {
const res = await request<AuthResponse>('/api/auth/register', {
method: 'POST',
body: JSON.stringify({ username, password }),
})
localStorage.setItem('token', res.token)
return res
}
export async function login(username: string, password: string): Promise<AuthResponse> {
const res = await request<AuthResponse>('/api/auth/login', {
method: 'POST',
body: JSON.stringify({ username, password }),
})
localStorage.setItem('token', res.token)
return res
}
export async function getMe(): Promise<{ id: number; username: string; role: string }> {
return request('/api/auth/me', {
headers: { 'Authorization': `Bearer ${getToken()}` },
})
}
export function isLoggedIn(): boolean {
return !!localStorage.getItem('token')
}
export function logout(): void {
localStorage.removeItem('token')
}
// --- Admin API ---
export async function adminCreateCategory(cat: Partial<RuntimeCategory>): Promise<RuntimeCategory> {
const res = await request<{ category: RuntimeCategory }>('/api/admin/categories', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${getToken()}` },
body: JSON.stringify(cat),
})
return res.category
}
export async function adminUpdateCategory(id: number, cat: Partial<RuntimeCategory>): Promise<RuntimeCategory> {
const res = await request<{ category: RuntimeCategory }>(`/api/admin/categories/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${getToken()}` },
body: JSON.stringify(cat),
})
return res.category
}
export async function adminDeleteCategory(id: number): Promise<void> {
await request(`/api/admin/categories/${id}`, {
method: 'DELETE',
headers: { 'Authorization': `Bearer ${getToken()}` },
})
}
export async function adminCreateVariant(categoryId: number, variant: Partial<RuntimeVariant>): Promise<RuntimeVariant> {
const res = await request<{ variant: RuntimeVariant }>(`/api/admin/categories/${categoryId}/variants`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${getToken()}` },
body: JSON.stringify(variant),
})
return res.variant
}
export async function adminUpdateVariant(id: number, variant: Partial<RuntimeVariant>): Promise<RuntimeVariant> {
const res = await request<{ variant: RuntimeVariant }>(`/api/admin/variants/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${getToken()}` },
body: JSON.stringify(variant),
})
return res.variant
}
export async function adminDeleteVariant(id: number): Promise<void> {
await request(`/api/admin/variants/${id}`, {
method: 'DELETE',
headers: { 'Authorization': `Bearer ${getToken()}` },
})
}

View File

@@ -0,0 +1,247 @@
import { useState, useEffect } from 'react'
import { listCategories, getMe, logout, adminCreateCategory, adminUpdateCategory, adminDeleteCategory, adminCreateVariant, adminUpdateVariant, adminDeleteVariant } from '../lib/api'
import { RuntimeCategory, RuntimeVariant } from '../types'
export default function Admin() {
const [categories, setCategories] = useState<RuntimeCategory[]>([])
const [user, setUser] = useState<{ id: number; username: string; role: string } | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
// Category form
const [editingCat, setEditingCat] = useState<RuntimeCategory | null>(null)
const [catName, setCatName] = useState('')
const [catLabel, setCatLabel] = useState('')
const [catIcon, setCatIcon] = useState('')
const [catOrder, setCatOrder] = useState(0)
// Variant form
const [selectedCatId, setSelectedCatId] = useState<number>(0)
const [editingVariant, setEditingVariant] = useState<RuntimeVariant | null>(null)
const [vName, setVName] = useState('')
const [vLabel, setVLabel] = useState('')
const [vExt, setVExt] = useState('')
const [vMime, setVMime] = useState('')
const [vCmd, setVCmd] = useState('')
const [vSrcCmd, setVSrcCmd] = useState('')
const [vDefault, setVDefault] = useState(false)
const [vOrder, setVOrder] = useState(0)
useEffect(() => {
Promise.all([
getMe().catch(() => null),
listCategories().catch(() => [] as RuntimeCategory[]),
]).then(([u, cats]) => {
setUser(u)
setCategories(cats)
setLoading(false)
if (!u || u.role !== 'admin') setError('无权访问管理后台')
})
}, [])
const refresh = () => listCategories().then(setCategories)
const resetCatForm = () => {
setEditingCat(null)
setCatName('')
setCatLabel('')
setCatIcon('')
setCatOrder(0)
}
const editCat = (cat: RuntimeCategory) => {
setEditingCat(cat)
setCatName(cat.Name)
setCatLabel(cat.Label)
setCatIcon(cat.Icon)
setCatOrder(cat.SortOrder)
}
const saveCategory = async () => {
try {
if (editingCat) {
await adminUpdateCategory(editingCat.ID, { Name: catName, Label: catLabel, Icon: catIcon, SortOrder: catOrder })
} else {
await adminCreateCategory({ Name: catName, Label: catLabel, Icon: catIcon, SortOrder: catOrder })
}
resetCatForm()
await refresh()
} catch (e) {
alert('操作失败')
}
}
const deleteCategory = async (id: number) => {
if (!confirm('确定删除此分类?相关变体也会被删除。')) return
try {
await adminDeleteCategory(id)
await refresh()
} catch { alert('删除失败') }
}
const resetVForm = () => {
setEditingVariant(null)
setVName('')
setVLabel('')
setVExt('')
setVMime('')
setVCmd('')
setVSrcCmd('')
setVDefault(false)
setVOrder(0)
}
const editVariant = (v: RuntimeVariant) => {
setEditingVariant(v)
setSelectedCatId(v.CategoryID)
setVName(v.Name)
setVLabel(v.Label)
setVExt(v.Extension)
setVMime(v.MIMEType)
setVCmd(v.CommandTemplate)
setVSrcCmd(v.SourceTemplate)
setVDefault(v.IsDefault)
setVOrder(v.SortOrder)
}
const saveVariant = async () => {
try {
const payload = {
Name: vName,
Label: vLabel,
Extension: vExt,
MIMEType: vMime,
CommandTemplate: vCmd,
SourceTemplate: vSrcCmd,
IsDefault: vDefault,
SortOrder: vOrder,
}
if (editingVariant) {
await adminUpdateVariant(editingVariant.ID, payload)
} else {
await adminCreateVariant(selectedCatId, payload)
}
resetVForm()
await refresh()
} catch { alert('操作失败') }
}
const deleteVariant = async (id: number) => {
if (!confirm('确定删除此变体?')) return
try {
await adminDeleteVariant(id)
await refresh()
} catch { alert('删除失败') }
}
if (loading) return <div className="text-center py-20 text-gray-500 animate-pulse">...</div>
if (error || !user || user.role !== 'admin') {
return (
<div className="text-center py-20">
<div className="text-6xl mb-4">🔒</div>
<h2 className="text-xl font-bold mb-2">访</h2>
<p className="text-gray-400 mb-4">{error || '请使用管理员账号登录'}</p>
<a href="/login" className="text-blue-400 hover:underline"></a>
</div>
)
}
const selectedCat = categories.find(c => c.ID === selectedCatId)
return (
<div className="space-y-8">
<div className="flex items-center justify-between">
<h1 className="text-2xl font-bold"></h1>
<div className="flex items-center gap-3 text-sm">
<span className="text-gray-400">{user.username}</span>
<button onClick={() => { logout(); window.location.href = '/' }} className="text-gray-500 hover:text-red-400 transition-colors">退</button>
</div>
</div>
{/* Category Form */}
<div className="bg-gray-800/50 border border-gray-700 rounded-lg p-4">
<h2 className="text-sm font-medium mb-3">{editingCat ? '编辑分类' : '新增分类'}</h2>
<div className="grid grid-cols-4 gap-3">
<input value={catName} onChange={e => setCatName(e.target.value)} placeholder="名称 (shell)" className="px-3 py-2 bg-gray-800 border border-gray-700 rounded text-xs" />
<input value={catLabel} onChange={e => setCatLabel(e.target.value)} placeholder="标签 (Shell)" className="px-3 py-2 bg-gray-800 border border-gray-700 rounded text-xs" />
<input value={catIcon} onChange={e => setCatIcon(e.target.value)} placeholder="图标 (🐚)" className="px-3 py-2 bg-gray-800 border border-gray-700 rounded text-xs" />
<input value={catOrder} onChange={e => setCatOrder(Number(e.target.value))} placeholder="排序" type="number" className="px-3 py-2 bg-gray-800 border border-gray-700 rounded text-xs" />
</div>
<div className="flex gap-2 mt-3">
<button onClick={saveCategory} className="px-3 py-1.5 bg-blue-600 hover:bg-blue-700 rounded text-xs">{editingCat ? '更新' : '创建'}</button>
{editingCat && <button onClick={resetCatForm} className="px-3 py-1.5 bg-gray-700 hover:bg-gray-600 rounded text-xs"></button>}
</div>
</div>
{/* Categories List */}
{categories.map(cat => (
<div key={cat.ID} className="bg-gray-800/30 border border-gray-700 rounded-lg p-4">
<div className="flex items-center justify-between mb-3">
<div className="flex items-center gap-2">
<span className="text-lg">{cat.Icon}</span>
<span className="font-medium">{cat.Label}</span>
<span className="text-xs text-gray-500 font-mono">({cat.Name})</span>
<span className="text-xs text-gray-600">: {cat.SortOrder}</span>
</div>
<div className="flex gap-2">
<button onClick={() => editCat(cat)} className="px-2 py-1 bg-gray-700 hover:bg-gray-600 rounded text-xs"></button>
<button onClick={() => deleteCategory(cat.ID)} className="px-2 py-1 bg-red-700 hover:bg-red-600 rounded text-xs"></button>
</div>
</div>
{/* Variants */}
<div className="ml-4 space-y-2">
{cat.Variants?.map(v => (
<div key={v.ID} className="flex items-center justify-between bg-gray-900/50 rounded px-3 py-2">
<div className="flex items-center gap-3 text-xs">
<span className="font-mono text-blue-400">{v.Name}</span>
<span className="text-gray-400">{v.Label}</span>
<span className="text-gray-600">.{v.Extension}</span>
{v.IsDefault && <span className="text-green-500"></span>}
</div>
<div className="flex gap-2">
<button onClick={() => { setSelectedCatId(cat.ID); editVariant(v) }} className="px-2 py-0.5 bg-gray-700 hover:bg-gray-600 rounded text-xs"></button>
<button onClick={() => deleteVariant(v.ID)} className="px-2 py-0.5 bg-red-700 hover:bg-red-600 rounded text-xs"></button>
</div>
</div>
))}
<button onClick={() => { resetVForm(); setSelectedCatId(cat.ID) }} className="text-xs text-blue-400 hover:underline">+ </button>
</div>
</div>
))}
{/* Variant Form */}
{(selectedCatId > 0 || editingVariant) && (
<div className="bg-gray-800/50 border border-gray-700 rounded-lg p-4">
<h2 className="text-sm font-medium mb-3">
{editingVariant ? '编辑变体' : `${selectedCat?.Label || selectedCatId} 添加变体`}
</h2>
<div className="grid grid-cols-4 gap-3">
<input value={vName} onChange={e => setVName(e.target.value)} placeholder="名称 (bash)" className="px-3 py-2 bg-gray-800 border border-gray-700 rounded text-xs" />
<input value={vLabel} onChange={e => setVLabel(e.target.value)} placeholder="标签 (Bash)" className="px-3 py-2 bg-gray-800 border border-gray-700 rounded text-xs" />
<input value={vExt} onChange={e => setVExt(e.target.value)} placeholder="扩展名 (.sh)" className="px-3 py-2 bg-gray-800 border border-gray-700 rounded text-xs" />
<input value={vMime} onChange={e => setVMime(e.target.value)} placeholder="MIME" className="px-3 py-2 bg-gray-800 border border-gray-700 rounded text-xs" />
</div>
<div className="grid grid-cols-2 gap-3 mt-3">
<input value={vCmd} onChange={e => setVCmd(e.target.value)} placeholder="命令模板 (curl {url} | bash)" className="px-3 py-2 bg-gray-800 border border-gray-700 rounded text-xs" />
<input value={vSrcCmd} onChange={e => setVSrcCmd(e.target.value)} placeholder="source模板 (可选)" className="px-3 py-2 bg-gray-800 border border-gray-700 rounded text-xs" />
</div>
<div className="flex items-center gap-6 mt-3">
<div className="flex items-center gap-2">
<input type="number" value={vOrder} onChange={e => setVOrder(Number(e.target.value))} placeholder="排序" className="w-20 px-3 py-2 bg-gray-800 border border-gray-700 rounded text-xs" />
</div>
<label className="flex items-center gap-2 text-xs text-gray-400">
<input type="checkbox" checked={vDefault} onChange={e => setVDefault(e.target.checked)} className="w-3 h-3" />
</label>
</div>
<div className="flex gap-2 mt-3">
<button onClick={saveVariant} className="px-3 py-1.5 bg-blue-600 hover:bg-blue-700 rounded text-xs">{editingVariant ? '更新' : '创建'}</button>
<button onClick={resetVForm} className="px-3 py-1.5 bg-gray-700 hover:bg-gray-600 rounded text-xs"></button>
</div>
</div>
)}
</div>
)
}

View File

@@ -1,11 +1,12 @@
import { useState, useCallback } from 'react'
import { useState, useEffect, useCallback } from 'react'
import CodeEditor from '../components/CodeEditor'
import ResultCard from '../components/ResultCard'
import { createScript } from '../lib/api'
import { CreateScriptResponse, RuntimeOption, ExpiresIn, RUNTIME_OPTIONS, EXPIRES_OPTIONS } from '../types'
import { createScript, listCategories } from '../lib/api'
import { CreateScriptResponse, ExpiresIn, EXPIRES_OPTIONS, RuntimeCategory } from '../types'
export default function Home() {
const [runtime, setRuntime] = useState<RuntimeOption>('bash')
const [categories, setCategories] = useState<RuntimeCategory[]>([])
const [categoryId, setCategoryId] = useState<number>(0)
const [title, setTitle] = useState('')
const [description, setDescription] = useState('')
const [content, setContent] = useState('')
@@ -15,8 +16,15 @@ export default function Home() {
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
useEffect(() => {
listCategories().then(setCategories).catch(() => {})
}, [])
const selectedCategory = categories.find(c => c.ID === categoryId)
const categoryName = selectedCategory?.Name || 'shell'
const handleSubmit = useCallback(async () => {
if (!title.trim() || !content.trim()) return
if (!title.trim() || !content.trim() || !categoryId) return
setLoading(true)
setError(null)
try {
@@ -24,7 +32,7 @@ export default function Home() {
title: title.trim(),
description: description.trim(),
content,
runtime,
category_id: categoryId,
expires_in: expiresIn,
publish,
})
@@ -34,7 +42,7 @@ export default function Home() {
} finally {
setLoading(false)
}
}, [title, description, content, runtime, expiresIn, publish])
}, [title, description, content, categoryId, expiresIn, publish])
const handleReset = useCallback(() => {
setResult(null)
@@ -48,7 +56,7 @@ export default function Home() {
return <ResultCard result={result} onReset={handleReset} />
}
const canSubmit = title.trim().length > 0 && content.trim().length > 0 && content.length <= 16384
const canSubmit = title.trim().length > 0 && content.trim().length > 0 && content.length <= 16384 && categoryId > 0
return (
<div className="space-y-6">
@@ -57,17 +65,18 @@ export default function Home() {
<p className="text-gray-400 text-sm"></p>
</div>
{/* Runtime + Expires */}
{/* Category + Expires */}
<div className="flex gap-4 flex-wrap">
<div className="flex-1 min-w-[160px]">
<label className="block text-xs text-gray-500 mb-1"></label>
<label className="block text-xs text-gray-500 mb-1"> <span className="text-red-400">*</span></label>
<select
value={runtime}
onChange={(e) => setRuntime(e.target.value as RuntimeOption)}
value={categoryId}
onChange={(e) => setCategoryId(Number(e.target.value))}
className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded-lg text-sm focus:outline-none focus:border-blue-500"
>
{RUNTIME_OPTIONS.map((opt) => (
<option key={opt.value} value={opt.value}>{opt.label}</option>
<option value={0}></option>
{categories.map((cat) => (
<option key={cat.ID} value={cat.ID}>{cat.Icon} {cat.Label}</option>
))}
</select>
</div>
@@ -119,7 +128,7 @@ export default function Home() {
{content.length > 16384 && <span className="text-red-400 ml-1"></span>}
</label>
<div className="border border-gray-700 rounded-lg overflow-hidden" style={{ height: '320px' }}>
<CodeEditor value={content} onChange={setContent} runtime={runtime} />
<CodeEditor value={content} onChange={setContent} categoryName={categoryName} />
</div>
</div>

View File

@@ -0,0 +1,59 @@
import { useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { login } from '../lib/api'
export default function Login() {
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [error, setError] = useState<string | null>(null)
const [loading, setLoading] = useState(false)
const navigate = useNavigate()
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
if (!username.trim() || !password) return
setLoading(true)
setError(null)
try {
await login(username.trim(), password)
navigate('/')
} catch (e) {
setError(e instanceof Error ? e.message : '登录失败')
} finally {
setLoading(false)
}
}
return (
<div className="max-w-sm mx-auto py-12">
<h1 className="text-xl font-bold mb-6 text-center"></h1>
<form onSubmit={handleSubmit} className="space-y-4">
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="用户名"
className="w-full px-4 py-2.5 bg-gray-800 border border-gray-700 rounded-lg text-sm focus:outline-none focus:border-blue-500"
/>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="密码"
className="w-full px-4 py-2.5 bg-gray-800 border border-gray-700 rounded-lg text-sm focus:outline-none focus:border-blue-500"
/>
{error && <p className="text-red-400 text-sm">{error}</p>}
<button
type="submit"
disabled={loading || !username.trim() || !password}
className="w-full px-4 py-2.5 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-700 disabled:text-gray-500 rounded-lg text-sm font-medium transition-colors"
>
{loading ? '登录中...' : '登录'}
</button>
</form>
<p className="text-center text-sm text-gray-500 mt-4">
<Link to="/register" className="text-blue-400 hover:underline"></Link>
</p>
</div>
)
}

View File

@@ -1,20 +1,30 @@
import { useState, useEffect, useCallback } from 'react'
import { Link } from 'react-router-dom'
import { listMarket } from '../lib/api'
import { MarketItem, RUNTIME_OPTIONS } from '../types'
import { listMarket, listCategories } from '../lib/api'
import { MarketItem, RuntimeCategory } from '../types'
export default function Market() {
const [items, setItems] = useState<MarketItem[]>([])
const [categories, setCategories] = useState<RuntimeCategory[]>([])
const [total, setTotal] = useState(0)
const [page, setPage] = useState(1)
const [runtime, setRuntime] = useState('')
const [categoryId, setCategoryId] = useState(0)
const [search, setSearch] = useState('')
const [loading, setLoading] = useState(true)
useEffect(() => {
listCategories().then(setCategories).catch(() => {})
}, [])
const fetchMarket = useCallback(async () => {
setLoading(true)
try {
const res = await listMarket({ page, per_page: 20, runtime, search })
const res = await listMarket({
page,
per_page: 20,
category_id: categoryId || undefined,
search: search || undefined,
})
setItems(res.items)
setTotal(res.total)
} catch {
@@ -22,7 +32,7 @@ export default function Market() {
} finally {
setLoading(false)
}
}, [page, runtime, search])
}, [page, categoryId, search])
useEffect(() => { fetchMarket() }, [fetchMarket])
@@ -45,13 +55,13 @@ export default function Market() {
className="flex-1 px-4 py-2.5 bg-gray-800 border border-gray-700 rounded-lg text-sm focus:outline-none focus:border-blue-500"
/>
<select
value={runtime}
onChange={(e) => { setRuntime(e.target.value); setPage(1) }}
value={categoryId}
onChange={(e) => { setCategoryId(Number(e.target.value)); setPage(1) }}
className="px-3 py-2.5 bg-gray-800 border border-gray-700 rounded-lg text-sm focus:outline-none focus:border-blue-500"
>
<option value=""></option>
{RUNTIME_OPTIONS.map((opt) => (
<option key={opt.value} value={opt.value}>{opt.label}</option>
<option value={0}></option>
{categories.map((cat) => (
<option key={cat.ID} value={cat.ID}>{cat.Icon} {cat.Label}</option>
))}
</select>
</div>
@@ -77,7 +87,7 @@ export default function Market() {
{item.title}
</span>
<span className="px-1.5 py-0.5 bg-blue-600/20 text-blue-400 text-xs rounded border border-blue-600/30">
{item.runtime}
{item.category_icon} {item.category_label}
</span>
</div>
{item.description && (

View File

@@ -0,0 +1,59 @@
import { useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { register } from '../lib/api'
export default function Register() {
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [error, setError] = useState<string | null>(null)
const [loading, setLoading] = useState(false)
const navigate = useNavigate()
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
if (!username.trim() || password.length < 6) return
setLoading(true)
setError(null)
try {
await register(username.trim(), password)
navigate('/')
} catch (e) {
setError(e instanceof Error ? e.message : '注册失败')
} finally {
setLoading(false)
}
}
return (
<div className="max-w-sm mx-auto py-12">
<h1 className="text-xl font-bold mb-6 text-center"></h1>
<form onSubmit={handleSubmit} className="space-y-4">
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="用户名3-32位"
className="w-full px-4 py-2.5 bg-gray-800 border border-gray-700 rounded-lg text-sm focus:outline-none focus:border-blue-500"
/>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="密码至少6位"
className="w-full px-4 py-2.5 bg-gray-800 border border-gray-700 rounded-lg text-sm focus:outline-none focus:border-blue-500"
/>
{error && <p className="text-red-400 text-sm">{error}</p>}
<button
type="submit"
disabled={loading || username.trim().length < 3 || password.length < 6}
className="w-full px-4 py-2.5 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-700 disabled:text-gray-500 rounded-lg text-sm font-medium transition-colors"
>
{loading ? '注册中...' : '注册'}
</button>
</form>
<p className="text-center text-sm text-gray-500 mt-4">
<Link to="/login" className="text-blue-400 hover:underline"></Link>
</p>
</div>
)
}

View File

@@ -3,7 +3,7 @@ import { useParams, Link } from 'react-router-dom'
import ScriptViewer from '../components/ScriptViewer'
import CommandCard from '../components/CommandCard'
import { getScript, publishScript } from '../lib/api'
import { ScriptDetail as ScriptDetailType, isShellRuntime, getSourceCommand } from '../types'
import { ScriptDetail as ScriptDetailType } from '../types'
export default function ScriptDetail() {
const { id } = useParams<{ id: string }>()
@@ -36,11 +36,6 @@ export default function ScriptDetail() {
)
}
const rawUrl = `${window.location.origin}/raw/${script.id}`
const command = `curl ${rawUrl} | ${script.runtime}`
const showSource = isShellRuntime(script.runtime)
const sourceCommand = showSource ? getSourceCommand(rawUrl, script.runtime) : null
const handlePublish = async () => {
if (!adminToken.trim()) return
setPublishing(true)
@@ -59,8 +54,8 @@ export default function ScriptDetail() {
return (
<div>
<div className="mb-6">
<Link to="/create" className="text-sm text-gray-500 hover:text-blue-400 transition-colors">&larr; </Link>
<Link to="/market" className="text-sm text-gray-500 hover:text-blue-400 transition-colors ml-4"></Link>
<Link to="/" className="text-sm text-gray-500 hover:text-blue-400 transition-colors">&larr; </Link>
<Link to="/create" className="text-sm text-gray-500 hover:text-blue-400 transition-colors ml-4"></Link>
</div>
<div className="mb-4">
@@ -71,7 +66,7 @@ export default function ScriptDetail() {
<div className="flex items-center gap-3 mb-6">
<span className="font-mono text-blue-400 text-sm">{script.id}</span>
<span className="px-2 py-0.5 bg-blue-600/20 text-blue-400 text-xs rounded-full border border-blue-600/30">
{script.runtime}
{script.category_icon} {script.category_label}
</span>
<span className={`px-2 py-0.5 text-xs rounded-full ${
script.status === 'published'
@@ -85,18 +80,26 @@ export default function ScriptDetail() {
</span>
</div>
<ScriptViewer content={script.content} runtime={script.runtime} />
<ScriptViewer content={script.content} categoryName={script.category_name} />
<div className="mt-8">
<CommandCard command={command} />
{showSource && sourceCommand && (
<div className="mt-4">
<p className="text-xs text-gray-500 mb-2">
使 shell
</p>
<CommandCard command={sourceCommand} label="继承环境变量" variant="secondary" />
{/* Commands */}
<div className="mt-8 space-y-4">
<h3 className="text-sm font-medium text-gray-300"></h3>
{script.commands.map((cmd, i) => (
<div key={cmd.variant}>
<CommandCard
command={cmd.command}
label={cmd.label}
variant={i === 0 ? 'primary' : 'secondary'}
/>
{cmd.source_command && (
<div className="mt-2">
<p className="text-xs text-gray-500 mb-1">source </p>
<CommandCard command={cmd.source_command} label={`${cmd.label} (source)`} variant="secondary" />
</div>
)}
</div>
)}
))}
</div>
{/* Publish section for drafts */}

View File

@@ -2,55 +2,69 @@ export interface CreateScriptResponse {
id: string
title: string
description: string
category_id: number
admin_token: string
url: string
command: string
source_command: string
runtime: string
status: string
expires_at: string
}
export interface CommandVariant {
variant: string
label: string
command: string
source_command?: string
}
export interface ScriptDetail {
id: string
title: string
description: string
runtime: string
category_id: number
category_name: string
category_label: string
category_icon: string
content: string
content_length: number
status: string
created_at: string
commands: CommandVariant[]
expires_at: string
published_at: string | null
expired: boolean
}
export type RuntimeOption = 'bash' | 'zsh' | 'sh' | 'fish' | 'python3' | 'node' | 'ruby' | 'php'
export type ExpiresIn = '1h' | '24h' | '7d' | '30d'
export const RUNTIME_OPTIONS: { value: RuntimeOption; label: string }[] = [
{ value: 'bash', label: 'Bash' },
{ value: 'zsh', label: 'Zsh' },
{ value: 'sh', label: 'Sh' },
{ value: 'fish', label: 'Fish' },
{ value: 'python3', label: 'Python 3' },
{ value: 'node', label: 'Node.js' },
{ value: 'ruby', label: 'Ruby' },
{ value: 'php', label: 'PHP' },
]
export interface RuntimeCategory {
ID: number
Name: string
Label: string
Icon: string
SortOrder: number
Variants: RuntimeVariant[]
}
export const EXPIRES_OPTIONS: { value: ExpiresIn; label: string }[] = [
{ value: '1h', label: '1 小时' },
{ value: '24h', label: '24 小时' },
{ value: '7d', label: '7 天' },
{ value: '30d', label: '30 天' },
]
export interface RuntimeVariant {
ID: number
CategoryID: number
Name: string
Label: string
Extension: string
MIMEType: string
CommandTemplate: string
SourceTemplate: string
IsDefault: boolean
SortOrder: number
}
export interface MarketItem {
id: string
title: string
description: string
runtime: string
category_id: number
category_name: string
category_label: string
category_icon: string
published_at: string | null
}
@@ -61,17 +75,16 @@ export interface MarketResponse {
per_page: number
}
const SOURCE_TEMPLATES: Record<string, string> = {
bash: 'source <(curl {url})',
zsh: 'source <(curl {url})',
sh: '. <(curl {url})',
fish: 'curl {url} | source',
export interface AuthResponse {
id: number
username: string
role: string
token: string
}
export function isShellRuntime(runtime: string): boolean {
return runtime in SOURCE_TEMPLATES
}
export function getSourceCommand(url: string, runtime: string): string {
return (SOURCE_TEMPLATES[runtime] ?? 'source <(curl {url})').replace('{url}', url)
}
export const EXPIRES_OPTIONS: { value: ExpiresIn; label: string }[] = [
{ value: '1h', label: '1 小时' },
{ value: '24h', label: '24 小时' },
{ value: '7d', label: '7 天' },
{ value: '30d', label: '30 天' },
]