add init demos

This commit is contained in:
2025-10-16 02:52:04 +08:00
parent 943d664c36
commit 5a3d11c6bc
38 changed files with 6810 additions and 121 deletions

View File

@@ -0,0 +1,179 @@
import { useShallow } from "zustand/shallow";
import { useState, useEffect } from "react";
import { Code } from "lucide-react";
import { useFileStore } from "../store/useFileStore";
import hljs from 'highlight.js';
import 'highlight.js/styles/github.css'; // 可以选择其他主题
type ShowCodeProps = {
filename: string;
}
export const ShowCode = (props: ShowCodeProps) => {
const [isModalOpen, setIsModalOpen] = useState(false);
const [codeContent, setCodeContent] = useState<string>("");
const [loading, setLoading] = useState(false);
const fileCode = useFileStore(useShallow((state) => ({
getFileContent: state.getFileContent,
})))
// 获取文件扩展名来确定语言类型
const getLanguageFromFilename = (filename: string) => {
const ext = filename.split('.').pop()?.toLowerCase();
const languageMap: { [key: string]: string } = {
'ts': 'typescript',
'tsx': 'typescript',
'js': 'javascript',
'jsx': 'javascript',
'py': 'python',
'java': 'java',
'c': 'c',
'cpp': 'cpp',
'cs': 'csharp',
'php': 'php',
'rb': 'ruby',
'go': 'go',
'rs': 'rust',
'html': 'html',
'css': 'css',
'scss': 'scss',
'json': 'json',
'xml': 'xml',
'sql': 'sql',
'sh': 'bash',
'yml': 'yaml',
'yaml': 'yaml',
'md': 'markdown',
};
return languageMap[ext || ''] || 'plaintext';
};
const handleCodeIconClick = async () => {
setLoading(true);
setIsModalOpen(true);
try {
if (fileCode.getFileContent) {
const content = await fileCode.getFileContent(props.filename);
setCodeContent(content || "未找到文件内容");
} else {
setCodeContent("getFileContent 方法不可用");
}
} catch (error) {
setCodeContent("加载文件内容失败");
console.error("获取文件内容失败:", error);
} finally {
setLoading(false);
}
};
const closeModal = () => {
setIsModalOpen(false);
setCodeContent("");
};
// 使用 highlight.js 进行代码高亮
const highlightCode = (code: string) => {
if (!code) return '';
const language = getLanguageFromFilename(props.filename);
try {
const highlighted = hljs.highlight(code, { language }).value;
return highlighted;
} catch (error) {
// 如果特定语言高亮失败,使用自动检测
try {
const highlighted = hljs.highlightAuto(code).value;
return highlighted;
} catch (autoError) {
// 如果都失败了,返回转义的纯文本
return hljs.highlight(code, { language: 'plaintext' }).value;
}
}
};
return (
<div className="flex items-center gap-2">
{/* <span>{props.filename}</span> */}
<button
onClick={handleCodeIconClick}
className="p-1 hover:bg-gray-100 rounded-md transition-colors duration-200"
title={`查看 ${props.filename} 的代码`}
>
<Code size={16} className="text-blue-600 hover:text-blue-800" />
</button>
{/* 弹窗 */}
{isModalOpen && (
<div className="code-modal-overlay">
<div className="code-modal">
{/* 头部 */}
<div className="code-modal-header">
<h3 className="code-modal-title">
{props.filename}
</h3>
<button
onClick={closeModal}
className="code-modal-close"
>
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
{/* 内容 */}
<div className="code-modal-content">
{loading ? (
<div className="flex items-center justify-center py-8">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
<span className="ml-2 text-gray-600">...</span>
</div>
) : (
<pre className="code-display">
<code
className={`language-${getLanguageFromFilename(props.filename)} hljs`}
dangerouslySetInnerHTML={{ __html: highlightCode(codeContent) }}
/>
</pre>
)}
</div>
{/* 底部 */}
<div className="code-modal-footer">
<button
onClick={closeModal}
className="px-4 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700 transition-colors"
>
</button>
</div>
</div>
</div>
)}
</div>
)
}
export const ShowJson = (props: { data: any }) => {
const highlightJson = (data: any) => {
const jsonString = JSON.stringify(data, null, 2);
try {
const highlighted = hljs.highlight(jsonString, { language: 'json' }).value;
return highlighted;
} catch (error) {
// 如果高亮失败,返回原始 JSON 字符串
return hljs.highlight(jsonString, { language: 'plaintext' }).value;
}
};
return (
<pre className="p-4 bg-gray-100 rounded-md overflow-auto">
<code
className="language-json hljs"
dangerouslySetInnerHTML={{ __html: highlightJson(props.data) }}
/>
</pre>
);
}

308
web/src/apps/test/run.tsx Normal file
View File

@@ -0,0 +1,308 @@
import { query, call } from '@/modules/query'
import { useEffect, useState } from 'react'
import { Edit2, Check, X } from 'lucide-react'
import { useFileStore } from './store/useFileStore'
import { useShallow } from 'zustand/shallow'
import { ShowCode, ShowJson } from './modules/ShowCode'
export type CallProps<T = any> = {
filename: string
title?: string
description?: string
data?: T
}
const useData = (params: any) => {
const [value, setValue] = useState<any>(null)
const [loading, setLoading] = useState<boolean>(false)
const [error, setError] = useState<string | null>(null)
const [queryData, setQueryData] = useState<any>(params || {})
const [isEditing, setIsEditing] = useState<boolean>(false)
const [editingData, setEditingData] = useState<string>('')
const [jsonError, setJsonError] = useState<string | null>(null)
const [isEditingFilename, setIsEditingFilename] = useState<boolean>(false)
const [editingFilename, setEditingFilename] = useState<string>('')
return {
value, setValue, loading, setLoading,
error, setError, queryData, setQueryData,
isEditing, setIsEditing, editingData, setEditingData,
jsonError, setJsonError, isEditingFilename, setIsEditingFilename,
editingFilename, setEditingFilename
}
}
export const Call = (props: CallProps) => {
const {
value, setValue, loading, setLoading, error, setError,
queryData, setQueryData, isEditing, setIsEditing,
editingData, setEditingData, jsonError, setJsonError,
isEditingFilename, setIsEditingFilename, editingFilename, setEditingFilename
} = useData(props.data)
const fileCode = useFileStore(useShallow((state) => ({
fetchFiles: state.fetchFiles,
getFileContent: state.getFileContent,
files: state.files
})))
const [filename, setFilename] = useState<string>(props.filename)
useEffect(() => {
fileCode.fetchFiles()
}, [])
const callTest = async () => {
setLoading(true)
setError(null)
try {
const res = await call(filename, queryData)
setValue(res)
} catch (err) {
setError(err instanceof Error ? err.message : '请求失败')
console.error('调用接口失败:', err)
} finally {
setLoading(false)
}
}
const clearResult = () => {
setValue(null)
setError(null)
}
const copyToClipboard = async (text: string) => {
try {
await navigator.clipboard.writeText(text)
// 可以添加一个临时的成功提示
} catch (err) {
console.error('复制失败:', err)
}
}
const startEditing = () => {
setEditingData(JSON.stringify(queryData, null, 2))
setIsEditing(true)
setJsonError(null)
}
const cancelEditing = () => {
setIsEditing(false)
setEditingData('')
setJsonError(null)
}
const confirmEditing = () => {
try {
const parsedData = JSON.parse(editingData)
setQueryData(parsedData)
setIsEditing(false)
setEditingData('')
setJsonError(null)
} catch (err) {
setJsonError('JSON 格式错误,请检查输入的数据')
}
}
const startEditingFilename = () => {
setEditingFilename(filename)
setIsEditingFilename(true)
}
const cancelEditingFilename = () => {
setIsEditingFilename(false)
setEditingFilename('')
}
const confirmEditingFilename = () => {
if (editingFilename.trim()) {
setFilename(editingFilename.trim())
setIsEditingFilename(false)
setEditingFilename('')
}
}
return (
<div className="max-w-4xl mx-auto p-6 space-y-6 border rounded-lg bg-background mb-1">
{/* 头部信息卡片 */}
<div className="bg-card rounded-lg border p-6 shadow-sm">
<h2 className="text-xl font-semibold text-foreground mb-4">API {props.title ? '--' + props.title : ''}</h2>
<div className="grid gap-4">
<div className="flex items-center gap-2">
<span className="text-sm font-medium text-muted-foreground min-w-[80px] flex gap-1">:
<ShowCode filename={filename} />
</span>
{isEditingFilename ? (
<div className="flex items-center gap-2 flex-1">
<input
type="text"
value={editingFilename}
onChange={(e) => setEditingFilename(e.target.value)}
className="text-sm bg-muted px-2 py-1 rounded font-mono border focus:outline-none focus:ring-2 focus:ring-primary flex-1"
placeholder="输入文件名"
onKeyDown={(e) => {
if (e.key === 'Enter') confirmEditingFilename()
if (e.key === 'Escape') cancelEditingFilename()
}}
autoFocus
/>
<div className="flex gap-1">
<button
onClick={confirmEditingFilename}
className="flex items-center gap-1 px-2 py-1 text-xs bg-primary text-primary-foreground hover:bg-primary/90 rounded transition-colors"
>
<Check className="w-3 h-3" />
</button>
<button
onClick={cancelEditingFilename}
className="flex items-center gap-1 px-2 py-1 text-xs bg-secondary text-secondary-foreground hover:bg-secondary/90 rounded transition-colors"
>
<X className="w-3 h-3" />
</button>
</div>
</div>
) : (
<div className="relative group flex-1">
<code className="text-sm bg-muted px-2 py-1 rounded font-mono">
{filename}
</code>
<button
onClick={startEditingFilename}
className="absolute top-0 right-0 flex items-center gap-1 px-1 py-0.5 text-xs bg-background/80 hover:bg-background border rounded opacity-0 group-hover:opacity-100 transition-opacity translate-x-1 -translate-y-1"
title="编辑文件名"
>
<Edit2 className="w-3 h-3" />
</button>
</div>
)}
</div>
{props.description && (
<div className="flex items-start gap-2">
<span className="text-sm font-medium text-muted-foreground min-w-[80px]">:</span>
<span className="text-sm text-foreground">{props.description}</span>
</div>
)}
{queryData && (
<div className="flex items-start gap-2">
<span className="text-sm font-medium text-muted-foreground min-w-[80px]">:</span>
<div className="flex-1">
{isEditing ? (
<div className="space-y-2">
<textarea
value={editingData}
onChange={(e) => setEditingData(e.target.value)}
className="w-full h-32 text-sm bg-muted p-3 rounded font-mono border resize-vertical focus:outline-none focus:ring-2 focus:ring-primary"
placeholder="输入 JSON 数据"
/>
{jsonError && (
<p className="text-sm text-destructive">{jsonError}</p>
)}
<div className="flex gap-2">
<button
onClick={confirmEditing}
className="flex items-center gap-1 px-3 py-1.5 text-sm bg-primary text-primary-foreground hover:bg-primary/90 rounded transition-colors"
>
<Check className="w-3 h-3" />
</button>
<button
onClick={cancelEditing}
className="flex items-center gap-1 px-3 py-1.5 text-sm bg-secondary text-secondary-foreground hover:bg-secondary/90 rounded transition-colors"
>
<X className="w-3 h-3" />
</button>
</div>
</div>
) : (
<div className="relative group">
<pre className="text-sm bg-muted p-3 rounded font-mono overflow-x-auto border" onClick={startEditing}>
{JSON.stringify(queryData, null, 2)}
</pre>
<button
onClick={startEditing}
className="absolute top-2 right-2 flex items-center gap-1 px-2 py-1 text-xs bg-background/80 hover:bg-background border rounded opacity-0 group-hover:opacity-100 transition-opacity"
title="编辑数据"
>
<Edit2 className="w-3 h-3" />
</button>
</div>
)}
</div>
</div>
)}
</div>
</div>
{/* 操作按钮 */}
<div className="flex gap-3">
<button
onClick={callTest}
disabled={loading}
className="flex items-center gap-2 px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
{loading ? (
<>
<div className="w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin"></div>
...
</>
) : (
<>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
</svg>
</>
)}
</button>
{(value || error) && (
<button
onClick={clearResult}
className="flex items-center gap-2 px-4 py-2 bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/90 transition-colors"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
</button>
)}
</div>
{/* 错误提示 */}
{error && (
<div className="bg-destructive/10 border border-destructive/20 rounded-lg p-4">
<div className="flex items-center gap-2 text-destructive">
<svg className="w-5 h-5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<span className="font-medium"></span>
</div>
<p className="mt-2 text-sm text-destructive/80">{error}</p>
</div>
)}
{/* 响应结果 */}
{value && (
<div className="bg-card rounded-lg border shadow-sm">
<div className="flex items-center justify-between p-4 border-b">
<h3 className="text-lg font-medium text-foreground"></h3>
<button
onClick={() => copyToClipboard(JSON.stringify(value, null, 2))}
className="flex items-center gap-1 px-3 py-1.5 text-sm bg-muted hover:bg-muted/80 rounded transition-colors"
title="复制到剪贴板"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
</svg>
</button>
</div>
<div className="p-4">
{value && <ShowJson data={value} />}
</div>
</div>
)}
</div>
)
}

View File

@@ -0,0 +1,50 @@
import { create } from 'zustand'
import { query } from '../../../modules/query'
import { timeout } from 'es-toolkit'
interface FileStore {
files: Array<{ path: string; content: string }>
loading: boolean
error: string | null
fetchFiles: () => Promise<void>
loaded?: boolean
getFileContent?: (path: string) => Promise<string | undefined>
}
export const useFileStore = create<FileStore>((set, get) => ({
files: [],
loading: false,
error: null,
loaded: false,
fetchFiles: async () => {
const loading = get().loading
if (loading) return
set({ loading: true, error: null })
const loaded = get().loaded
if (loaded) {
set({ loading: false })
return
}
try {
const res = await query.post({ path: 'file-code' })
set({ files: res.data, loading: false, loaded: true })
} catch (err) {
const errorMessage = err instanceof Error ? err.message : '获取文件列表失败'
set({ error: errorMessage, loading: false, loaded: false })
console.error('获取文件列表失败:', err)
}
},
getFileContent: async (path) => {
const loaded = get().loaded
if (!loaded) {
console.warn('文件未加载,无法获取内容')
await get().fetchFiles()
await timeout(2000);
}
const files = get().files
const file = files.find((f) => f.path === path)
return file ? file.content : undefined
}
}))