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

1
.dockerignore Normal file
View File

@@ -0,0 +1 @@
node_modules

22
.gitignore vendored
View File

@@ -2,24 +2,10 @@ node_modules
dist
app.config.json5
apps.config.json
deploy.tar.gz
cache-file
/apps
logs
release/*
!release/.gitkeep
.turbo
.env*
!.env.example
filebrowser
pack-dist
app.config.json5.envision
filebrowser.db
/data

24
Dockerfile Normal file
View File

@@ -0,0 +1,24 @@
FROM oven/bun:alpine
# From bun:latest
# 创建应用目录
WORKDIR /app
COPY server/package.json ./
# 复制源码
COPY ./server ./
RUN bun install
# 构建(可选)
# RUN bun run build
# 暴露端口
EXPOSE 4005
# 启动服务
CMD ["bun", "start"]
# 保持容器运行
# CMD ["tail", "-f", "/dev/null"]

23
compose.yml Normal file
View File

@@ -0,0 +1,23 @@
services:
light-code:
image: 'kevisual/light-code:latest'
user: root
volumes:
- ./data/code:/app/code
ports:
- '3005:4005'
restart: always
filebrowser:
image: 'filebrowser/filebrowser'
user: root
volumes:
- ./data/code:/srv
- ./data/database:/database
- ./data/config:/config
restart: unless-stopped
ports:
- '8080:80'
environment:
- PUID=1000
- PGID=1000

View File

@@ -1,14 +1,21 @@
{
"name": "light-code",
"name": "@kevisual/light-code",
"version": "0.0.1",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"dev": "pnpm run dev:server & pnpm run dev:web",
"dev:server": "cd server && pnpm dev",
"dev:web": "cd web && pnpm dev",
"docker:build": "docker build -t kevisual/light-code .",
"build": "turbo build"
},
"keywords": [],
"author": "abearxiong <xiongxiao@xiongxiao.me> (https://www.xiongxiao.me)",
"license": "MIT",
"packageManager": "pnpm@10.16.1",
"type": "module"
}
"packageManager": "pnpm@10.18.3",
"type": "module",
"dependencies": {
"turbo": "^2.5.8"
}
}

5479
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,3 +1,8 @@
packages:
- 'web'
- 'server'
packages:
- web
- server
onlyBuiltDependencies:
- '@tailwindcss/oxide'
- esbuild
- sharp

8
readme.md Normal file
View File

@@ -0,0 +1,8 @@
# light-code
[介绍](https://docmost.xiongxiao.me/share/vh4ff05fru/p/2025-10-15-light-code-HyZh9ERDN1)
## 文件管理工具
[filebrowser](https://github.com/filebrowser/filebrowser/releases)

25
server/.gitignore vendored Normal file
View File

@@ -0,0 +1,25 @@
node_modules
dist
app.config.json5
apps.config.json
deploy.tar.gz
cache-file
/apps
logs
release/*
!release/.gitkeep
.turbo
.env*
!.env.example
pack-dist
app.config.json5.envision

View File

@@ -8,6 +8,7 @@ const external = ['sequelize', 'pg', 'ioredis', 'pm2'];
/**
* @type {import('bun').BuildConfig}
*/
// @ts-ignore
await Bun.build({
target: 'node',
format: 'esm',

View File

@@ -0,0 +1,24 @@
import { QueryRouterServer } from "@kevisual/router";
const app = new QueryRouterServer();
app.route({
path: 'main'
}).define(async (ctx) => {
ctx.body = {
message: 'this is main. filename: root/light-code-demo/main.ts',
params: ctx.query
}
}).addTo(app)
app.route({
path: 'main2'
}).define(async (ctx) => {
ctx.body = {
message: 'this is main2. filename: root/light-code-demo/main.ts',
params: ctx.query
}
}).addTo(app)
app.wait()

View File

@@ -0,0 +1,46 @@
import { QueryRouterServer as Mini } from "@kevisual/router";
import { NocoApi } from "@kevisual/noco";
const config = {
NOCODB_URL: process.env.NOCODB_URL || 'https://nocodb.xiongxiao.me',
NOCODB_API_KEY: process.env.NOCODB_API_KEY || 'uca1Zx3p_0pnNUBV6ot9mBP6JCPqQ0X1TF3N3R7s'
}
const table = 'mcby44q8zrayvn9'
const nocoAPi = new NocoApi({
baseURL: config.NOCODB_URL,
token: config.NOCODB_API_KEY,
table,
});
console.log('nocoAPi', await nocoAPi.record.list())
const app = new Mini();
app.route({
path: 'sign'
}).define(async (ctx) => {
const { Title, Description } = ctx.query
// 这里可以处理签到
await nocoAPi.record.create({ Title, Description })
const list = await nocoAPi.record.list({ sort: '-CreatedAt' })
ctx.body = { message: '签到成功', list }
}).addTo(app)
app.route({
path: 'sign',
key: 'list'
}).define(async (ctx) => {
// 这里可以处理签到
ctx.body = await nocoAPi.record.list()
}).addTo(app)
app.route({
path: 'sign',
key: 'delete'
}).define(async (ctx) => {
const { id } = ctx.query
// 这里可以处理签到
await nocoAPi.record.delete({ Id: id })
const list = await nocoAPi.record.list({ sort: '-CreatedAt' })
ctx.body = { message: '删除成功', list }
}).addTo(app)
app.wait()

View File

@@ -0,0 +1,56 @@
const weatherHost = 'n65khufe5n.re.qweatherapi.com';
const token = 'fdad5aeb2ba54949a8a1df2a0f3d1efb'
const xihu = '101210113'; // 西湖
export const getWeather = async (location: string = xihu) => {
const url = `https://${weatherHost}/v7/weather/3d?location=${location}`;
const headers = {
'Authorization': `Bearer ${token}`
};
const res = await fetch(url, { headers });
if (!res.ok) {
throw new Error(`HTTP error! status: ${res.status}`);
}
const data = await res.json();
return data;
}
// getWeather().then(console.log).catch(console.error);
// https://dev.qweather.com/
class Weather {
host: string;
token: string;
constructor(opts: { host: string; token: string }) {
this.host = opts.host;
this.token = opts.token;
console.log(this.host, this.token);
}
getWeather(location: string) {
return fetch(`https://${this.host}/v7/weather/now?location=${location}`, {
headers: {
'Content-Type': 'application/json',
'X-QW-Api-Key': '<KEY>'.replace('<KEY>', this.token),
},
}).then((res) => res.json());
}
}
const newWeather = new Weather({
host: process.env?.QWEATHER_HOST || weatherHost,
token: process.env?.QWEATHER_TOKEN || token,
});
// newWeather.getWeather(xihu).then(console.log).catch(console.error);
import { QueryRouterServer as Mini } from "@kevisual/router";
const app = new Mini();
app.route({
path: 'main'
}).define(async (ctx) => {
ctx.body = await newWeather.getWeather(xihu);
}).addTo(app)
app.wait()

View File

@@ -1,10 +1,9 @@
import fs from 'node:fs'
const main = () => {
const random = Math.random().toString(36).slice(-6)
return 'hello a' + random
return 'hello a ' + random
}
fs.writeFileSync('./a.txt', main() + '\n', { flag: 'a' })
// fs.writeFileSync('./a.txt', main() + '\n', { flag: 'a' })
console.log('pwd', process.cwd())
// const value = fs.readFileSync('./bun.config.ts', 'utf-8')
// console.log('a.txt 内容:', value)
@@ -29,10 +28,10 @@ const listen = async () => {
// 发送结果回主进程
const response = {
success: true,
foo: 'bar',
params,
main: result,
success: true,
data: { code: 200, data: result },
timestamp: new Date().toISOString()
}

View File

@@ -0,0 +1,14 @@
import { QueryRouterServer } from "@kevisual/router";
const app = new QueryRouterServer();
app.route({
path: 'main'
}).define(async (ctx) => {
ctx.body = {
message: 'this is main. filename: root/listen-demo/router.ts',
params: ctx.query
}
}).addTo(app)
app.wait()

View File

@@ -0,0 +1 @@
测试静态页面

View File

@@ -5,6 +5,7 @@
"main": "index.js",
"scripts": {
"dev": "bun run --watch --hot src/index.ts",
"start": "bun run src/index.ts",
"build": "NODE_ENV=production bun bun.config.ts"
},
"keywords": [],
@@ -13,12 +14,14 @@
"packageManager": "pnpm@10.16.1",
"type": "module",
"devDependencies": {
"@kevisual/local-proxy": "^0.0.6",
"@kevisual/types": "^0.0.10",
"@kevisual/use-config": "^1.0.19",
"@types/bun": "^1.3.0",
"bun": "^1.3.0"
"@types/bun": "^1.3.0"
},
"dependencies": {
"@kevisual/router": "^0.0.28"
"@kevisual/noco": "^0.0.1",
"@kevisual/router": "^0.0.29",
"fast-glob": "^3.3.3"
}
}

3
server/src/app.ts Normal file
View File

@@ -0,0 +1,3 @@
import { App } from '@kevisual/router'
export const app = new App()

View File

@@ -1,38 +0,0 @@
import { App } from '@kevisual/router'
import { fork } from 'child_process'
const app = new App()
import path from 'path'
// http://localhost:3000/api/router?path=call
app.route({
path: 'call'
}).define(async (ctx) => {
ctx.body = 'Hello World'
const pwd = process.cwd()
const testA = path.join(pwd, 'src/test/a.ts')
const child = fork(testA, {
})
console.log('Child process started with PID:', child.pid)
child.on('message', (msg) => {
console.log('Message from child', msg)
setTimeout(() => {
console.log('child process connected:', child.connected)
console.log('child process killed:', child.killed)
console.log('child process exit code:', child.exitCode)
}, 20)
})
child.on('exit', (code, signal) => {
console.log('子进程已退出,退出码:', code, '信号:', signal)
})
child.on('close', (code, signal) => {
console.log('子进程已关闭,退出码:', code, '信号:', signal)
})
child.send({ hello: 'world' })
}).addTo(app)
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000')
})

View File

@@ -1,51 +1,16 @@
import { App } from '@kevisual/router'
import { fork } from 'child_process'
const app = new App()
import path from 'path'
import { proxyRoute, initProxy } from '@kevisual/local-proxy/proxy.ts';
// http://localhost:4005/test/a/index.html
initProxy({
pagesDir: './demo',
watch: true,
});
// http://localhost:3000/api/router?path=call
app.route({
path: 'call'
}).define(async (ctx) => {
ctx.body = 'Hello World'
const pwd = process.cwd()
const testA = path.join(pwd, 'src/test/a.ts')
import { app } from './app.ts'
import './routes/index.ts'
// 使用 Bun 的 fork 模式启动子进程
const child = fork(testA, [], {
execArgv: [],
cwd: "/tmp", // 限制工作目录
})
console.log('Child process started with PID:', child.pid)
app.listen(4005, () => {
console.log('Server is running on http://localhost:4005')
})
// 监听来自子进程的消息
child.on('message', (msg) => {
console.log('Message from child:', msg)
setTimeout(() => {
console.log('child process connected:', child.connected)
console.log('child process killed:', child.killed)
console.log('child process exit code:', child.exitCode)
}, 20)
})
child.on('exit', (code, signal) => {
console.log('子进程已退出,退出码:', code, '信号:', signal)
})
child.on('close', (code, signal) => {
console.log('子进程已关闭,退出码:', code, '信号:', signal)
})
child.on('error', (error) => {
console.error('子进程错误:', error)
})
// 向子进程发送消息
child.send({ hello: 'world' })
}).addTo(app)
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000')
})
app.onServerRequest(proxyRoute);

View File

@@ -0,0 +1,50 @@
import { fork } from 'child_process'
export type RunCodeParams = {
path?: string;
key?: string;
payload?: string;
[key: string]: any
}
type RunCode = {
// 调用进程的功能
success?: boolean
data?: {
// 调用router的结果
code?: number
data?: any
message?: string
[key: string]: any
};
error?: any
timestamp?: string
[key: string]: any
}
export const runCode = async (tsPath: string, params: RunCodeParams = {}): Promise<RunCode> => {
return new Promise((resolve, reject) => {
// 使用 Bun 的 fork 模式启动子进程
const child = fork(tsPath)
// 监听来自子进程的消息
child.on('message', (msg: RunCode) => {
resolve(msg)
})
// child.on('exit', (code, signal) => {
// console.log('子进程已退出,退出码:', code, '信号:', signal)
// })
// child.on('close', (code, signal) => {
// console.log('子进程已关闭,退出码:', code, '信号:', signal)
// })
child.on('error', (error) => {
resolve({
success: false, error: error?.message
})
})
// 向子进程发送消息
child.send(params)
});
}

View File

@@ -0,0 +1,24 @@
import { app } from '../../app.ts'
import path from 'path'
import { runCode } from '../../modules/run-code/run.ts'
// http://localhost:4005/api/router?path=call
app.route({
path: 'call'
}).define(async (ctx) => {
const filename = ctx.query?.filename || 'root/listen-demo/router.ts'
const data = ctx.query?.data || {}
const pwd = process.cwd()
const testA = path.join(pwd, 'code', filename)
const resulst = await runCode(testA, data)
if (resulst.success) {
const callResult = resulst.data;
if (callResult.code === 200) ctx.body = callResult.data
else {
const callError = `调用程序错误: ${callResult.message}`
ctx.throw(callResult.code, callError)
}
} else {
ctx.body = `执行脚本错误: ${resulst.error}`
}
}).addTo(app)

View File

@@ -0,0 +1,28 @@
import { app } from '@/app.ts';
import path from 'node:path'
import glob from 'fast-glob';
import fs from 'node:fs'
const list = async () => {
const root = path.join(process.cwd(), 'code');
const files = await glob('**/*.ts', { cwd: root });
type FileContent = {
path: string;
content: string;
}
const filesContent: FileContent[] = [];
for (const file of files) {
if (file.startsWith('node_modules') || file.startsWith('dist') || file.startsWith('.git')) continue;
const fullPath = path.join(root, file);
const content = fs.readFileSync(fullPath, 'utf-8');
if (content) {
filesContent.push({ path: file, content: content });
}
}
return filesContent;
}
app.route({
path: 'file-code'
}).define(async (ctx) => {
const files = await list();
ctx.body = files
}).addTo(app);

View File

@@ -0,0 +1,3 @@
import './call/index.ts';
import './file-code/index.ts';

View File

@@ -9,11 +9,11 @@
],
"paths": {
"@/*": [
"server/src/*"
"src/*"
]
},
},
"include": [
"server/src/**/*",
"src/**/*", "code/**/*",
],
}

18
turbo.json Normal file
View File

@@ -0,0 +1,18 @@
{
"$schema": "https://turbo.build/schema.json",
"tasks": {
"build": {
"outputs": [
"dist/**"
]
},
"dev": {
"cache": false
},
"build:app": {
"outputs": [
"dist/**"
]
}
}
}

6
web/.gitignore vendored Normal file
View File

@@ -0,0 +1,6 @@
node_modules
.DS_Store
.astro
dist

36
web/astro.config.mjs Normal file
View File

@@ -0,0 +1,36 @@
import { defineConfig } from 'astro/config';
import mdx from '@astrojs/mdx';
import react from '@astrojs/react';
import sitemap from '@astrojs/sitemap';
import pkgs from './package.json';
import tailwindcss from '@tailwindcss/vite';
const isDev = process.env.NODE_ENV === 'development';
let target = process.env.VITE_API_URL || 'http://localhost:4005';
const apiProxy = { target: target, changeOrigin: true, ws: true, rewriteWsOrigin: true, secure: false, cookieDomainRewrite: 'localhost' };
let proxy = {
'/root/': {
target: `${target}/root/`,
},
'/api': apiProxy,
};
export default defineConfig({
base: isDev ? undefined : pkgs.basename,
integrations: [
mdx(),
react(), //
// sitemap(), // sitemap must be site has a domain
],
vite: {
plugins: [tailwindcss()],
server: {
port: 7008,
host: '0.0.0.0',
allowedHosts: true,
proxy,
},
},
});

63
web/package.json Normal file
View File

@@ -0,0 +1,63 @@
{
"name": "@kevisual/light-code-center",
"version": "0.0.1",
"description": "",
"main": "index.js",
"basename": "/root/light-code-center",
"scripts": {
"dev": "astro dev",
"build": "astro build",
"preview": "astro preview",
"pub": "envision deploy ./dist -k light-code-center -v 0.0.1 -u",
"sn": "pnpm dlx shadcn@latest add "
},
"keywords": [],
"author": "abearxiong <xiongxiao@xiongxiao.me> (https://www.xiongxiao.me)",
"license": "MIT",
"type": "module",
"dependencies": {
"@astrojs/mdx": "^4.3.7",
"@astrojs/react": "^4.4.0",
"@astrojs/sitemap": "^3.6.0",
"@kevisual/noco": "^0.0.1",
"@kevisual/query": "^0.0.29",
"@kevisual/query-login": "^0.0.6",
"@kevisual/registry": "^0.0.1",
"@tailwindcss/vite": "^4.1.14",
"astro": "^5.14.4",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"dayjs": "^1.11.18",
"es-toolkit": "^1.40.0",
"highlight.js": "^11.11.1",
"lodash-es": "^4.17.21",
"lucide-react": "^0.545.0",
"nanoid": "^5.1.6",
"react": "^19.2.0",
"react-dom": "^19.2.0",
"react-toastify": "^11.0.5",
"tailwind-merge": "^3.3.1",
"three": "^0.180.0",
"wavesurfer.js": "^7.11.0",
"zustand": "^5.0.8"
},
"publishConfig": {
"access": "public"
},
"devDependencies": {
"@kevisual/types": "^0.0.10",
"@types/react": "^19.2.2",
"@types/react-dom": "^19.2.2",
"@types/three": "^0.180.0",
"@vitejs/plugin-basic-ssl": "^2.1.0",
"dotenv": "^17.2.3",
"tailwindcss": "^4.1.14",
"tw-animate-css": "^1.4.0"
},
"packageManager": "pnpm@10.18.3",
"onlyBuiltDependencies": [
"@tailwindcss/oxide",
"esbuild",
"sharp"
]
}

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
}
}))

View File

@@ -0,0 +1,46 @@
---
import '../styles/global.css';
export interface Props {
title?: string;
description?: string;
lang?: string;
charset?: string;
}
const { title = 'Light Code', description = 'A lightweight code editor', lang = 'zh-CN', charset = 'UTF-8' } = Astro.props;
---
<!doctype html>
<html lang={lang}>
<head>
<meta charset={charset} />
<meta name='viewport' content='width=device-width, initial-scale=1.0' />
<meta name='description' content={description} />
<title>{title}</title>
<!-- 样式 -->
<slot name='head' />
</head>
<body>
<slot />
<!-- 脚本 -->
<slot name='scripts' />
</body>
</html>
<style>
html {
font-family: system-ui, sans-serif;
}
html,
body {
margin: 0;
padding: 0;
min-height: 100vh;
}
* {
box-sizing: border-box;
}
</style>

8
web/src/modules/query.ts Normal file
View File

@@ -0,0 +1,8 @@
import { Query } from '@kevisual/query';
export const query = new Query();
export const call = async (filename: string, data?: any) => {
console.log('call', filename, data)
return await query.post({ path: 'call', filename, data });
}

55
web/src/pages/index.astro Normal file
View File

@@ -0,0 +1,55 @@
---
import Html from '@/components/html.astro';
import { Call, CallProps } from '@/apps/test/run';
const callDocs: CallProps[] = [
{
filename: 'root/listen-demo/router.ts',
title: 'Listen Demo Simple',
description: '最简单的监听函数的功能, app的函数, 执行什么功能,返回body的内容.',
data: { foo: 'bar' },
},
{
filename: 'root/listen-demo/origin.ts',
title: 'Listen Demo Origin',
data: {},
description: '原生模块, 使用process传递信息的代码.',
},
{
filename: 'root/light-code-demo/main.ts',
title: '根据path调用不同的函数',
data: { path: 'main2' },
description: '使用router监听内容, 根据不同的path去调用不同的route的函数模块,main为默认的,main2是修改的另一个函数.',
},
{
filename: 'root/light-code-demo/weather.ts',
title: '获取天气',
data: {},
description: '获取西湖的3天内的天气的功能.',
},
{
filename: 'root/light-code-demo/sign.ts',
title: '用户签到',
data: { Title: '签到名字', Description: '用户签到', path: 'sign' },
description: '签到功能, 传递Title和Description, 返回签到的结果',
},
{
filename: 'root/light-code-demo/sign.ts',
title: '获取签到列表',
data: { path: 'sign', key: 'list' },
description: '获取签到列表的功能, 传递key为list, 返回签到的列表',
},
{
filename: 'root/light-code-demo/sign.ts',
title: '获取签到描述列表',
data: { path: 'sign', key: 'delete', id: 3 },
description: '获取签到描述列表的功能, 传递key为delete, 返回签到的列表',
},
];
---
<Html>
<main>
{callDocs.map((doc) => <Call {...doc} client:only />)}
</main>
</Html>

View File

@@ -0,0 +1,12 @@
---
import Html from '../../components/html.astro';
import '../../styles/global.css';
import { Call as CallComponent } from '@/apps/test/run';
---
<Html title='Call Test' description='Call functionality test page'>
<main>
<p class="text-center py-4 ">这是一个用于测试调用功能的页面</p>
<CallComponent filename='root/listen-demo/router.ts' data={{ foo: 'bar' }} client:only />
</main>
</Html>

157
web/src/styles/global.css Normal file
View File

@@ -0,0 +1,157 @@
@import 'tailwindcss';
@import "tw-animate-css";
@custom-variant dark (&:is(.dark *));
@theme inline {
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
--color-chart-1: var(--chart-1);
--color-chart-2: var(--chart-2);
--color-chart-3: var(--chart-3);
--color-chart-4: var(--chart-4);
--color-chart-5: var(--chart-5);
--color-sidebar: var(--sidebar);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-ring: var(--sidebar-ring);
}
:root {
--radius: 0.625rem;
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392);
--chart-4: oklch(0.828 0.189 84.429);
--chart-5: oklch(0.769 0.188 70.08);
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.205 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.922 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08);
--chart-4: oklch(0.627 0.265 303.9);
--chart-5: oklch(0.645 0.246 16.439);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.556 0 0);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
}
/* 代码弹窗样式 */
@layer components {
.code-modal-overlay {
@apply fixed inset-0 bg-black/50 flex items-center justify-center z-50;
}
.code-modal {
@apply bg-white rounded-lg shadow-xl max-w-4xl w-full mx-4 max-h-[80vh] flex flex-col;
}
.code-modal-header {
@apply flex items-center justify-between p-4 border-b;
}
.code-modal-title {
@apply text-lg font-semibold text-gray-900;
}
.code-modal-close {
@apply text-gray-400 hover:text-gray-600 transition-colors;
}
.code-modal-content {
@apply p-4 flex-1 overflow-auto;
}
.code-modal-footer {
@apply p-4 border-t bg-gray-50 flex justify-end;
}
.code-display {
@apply bg-gray-50 p-4 rounded-lg overflow-auto text-sm font-mono whitespace-pre-wrap border;
line-height: 1.5;
}
}

14
web/tsconfig.json Normal file
View File

@@ -0,0 +1,14 @@
{
"extends": "@kevisual/types/json/frontend.json",
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": [
"./src/*"
]
},
},
"include": [
"src/**/*",
],
}