data-page技能+服务端承载:①executor抽出runTaskSql统一SQL执行核心(db工具exec/query与HTTP API共用,prepare挡多语句/reader读写分流/BEGIN事务/DDL判定单一事实源;读取iterate到量截断防大表SELECT*物化OOM,工具超限给截断信封、API超限报error引导分页,query信封不再报total_rows)②新路由/app/{task_id}/静态托管任务app/子树(index兜底、不给列目录)+POST /api/db/{task_id}/query任意单语句,失败200+{error}按SKILL.md契约,挂登录态后、不加CORS头③技能run.py幂等复制templates到app/templates(dest由manager预转绝对路径防本地模式cwd落技能目录),SKILL.md补front matter(op=list描述+input_schema)与lastInsertRowid示例
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
// data-page 技能的服务端承载,两条通道(配套 skills/data-page/SKILL.md 的契约):
|
||||
// 1. GET /app/{task_id}/... —— 静态托管任务目录的 app/ 子树(index.html 兜底,不给列目录);
|
||||
// 只暴露 app/ 而非整个任务目录,其余任务文件不从 URL 泄漏。
|
||||
// 2. POST /api/db/{task_id}/query —— 任务 data.db 的 SQL API(页面前端 fetch 调):任意单语句,
|
||||
// 执行核心与 db 工具共用 runTaskSql(executor.js),语义单一事实源。
|
||||
// 认证:挂在 server.js 的 auth.middleware 之后——信任模型与 files 路由一致(登录 ≈ 运维,可跨会话)。
|
||||
// 刻意不加任何 CORS 头:跨站 application/json POST 会被预检挡下,不带 cookie 的匿名页也调不动。
|
||||
// 响应契约(SKILL.md 原文):SELECT→行数组;写→{rowsAffected,lastInsertRowid};DDL→{ok:true};
|
||||
// 失败→HTTP 200 + {error}(前端统一查 error 字段)。会话/路径级错误才用 4xx。
|
||||
const express = require('express');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const engine = require('../engine');
|
||||
const { resolveInTask, runTaskSql } = require('../tools/executor');
|
||||
|
||||
// 页面忘写 LIMIT 的服务端兜底:iterate 到量即停(不全量物化),超限报错引导分页。
|
||||
const API_MAX_ROWS = 2000;
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
function notFound(res, msg) {
|
||||
res.status(404).json({ error: msg });
|
||||
}
|
||||
|
||||
// ---------- /app/{task_id}/...:任务 app/ 子树静态托管 ----------
|
||||
router.use('/app', (req, res) => {
|
||||
try {
|
||||
const segs = req.path.replace(/^\/+/, '').split('/');
|
||||
const sessionId = segs[0];
|
||||
if (!sessionId) return notFound(res, '会话不存在');
|
||||
if (!engine.getSession(sessionId)) return notFound(res, '会话不存在');
|
||||
const appRoot = path.join(engine.taskDirOf(sessionId), 'app');
|
||||
let abs;
|
||||
try {
|
||||
abs = resolveInTask(appRoot, segs.slice(1).join('/') || 'index.html'); // 越界即挡,限 app/ 子树
|
||||
} catch (_) {
|
||||
return notFound(res, '非法路径');
|
||||
}
|
||||
let st;
|
||||
try { st = fs.statSync(abs); } catch (_) { return notFound(res, '页面不存在'); }
|
||||
if (st.isDirectory()) {
|
||||
abs = path.join(abs, 'index.html'); // 目录请求补 index.html,仍无则 404
|
||||
try { st = fs.statSync(abs); } catch (_) { return notFound(res, '页面不存在'); }
|
||||
}
|
||||
if (!st.isFile()) return notFound(res, '页面不存在');
|
||||
res.sendFile(abs, err => {
|
||||
if (err && !res.headersSent) notFound(res, '页面不存在');
|
||||
});
|
||||
} catch (err) {
|
||||
if (!res.headersSent) res.status(400).json({ error: (err && err.message) || String(err) });
|
||||
}
|
||||
});
|
||||
|
||||
// ---------- POST /api/db/{task_id}/query:任务 data.db 的 SQL API ----------
|
||||
router.post('/api/db/:id/query', (req, res) => {
|
||||
if (!engine.getSession(req.params.id)) return notFound(res, '会话不存在');
|
||||
const body = req.body || {};
|
||||
let r;
|
||||
try {
|
||||
r = runTaskSql(engine.taskDirOf(req.params.id), String(body.sql || ''), body.params, 'any', API_MAX_ROWS);
|
||||
} catch (err) {
|
||||
// SQL 语义错误走 200 + {error}(SKILL.md 契约:前端只查 error 字段,不分状态码)
|
||||
return res.json({ error: (err && err.message) || String(err) });
|
||||
}
|
||||
if (r.kind === 'read') {
|
||||
if (r.overflow) return res.json({ error: '结果超过 ' + API_MAX_ROWS + ' 行,请加 LIMIT/OFFSET 分页' });
|
||||
return res.json(r.rows);
|
||||
}
|
||||
return res.json(r.out);
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -51,6 +51,9 @@ app.use('/api/skills', require('./routes/skills'));
|
||||
app.use('/api/config', require('./routes/config'));
|
||||
app.use('/api/platforms', require('./routes/platforms'));
|
||||
app.use('/api/system', require('./routes/system'));
|
||||
// data-page 技能配套:任务 app/ 子树页面向导 /app/{task_id}/ + 数据 API /api/db/{task_id}/query。
|
||||
// 随其余业务路由一样挂在 auth.middleware 之后(登录态才能访问)。
|
||||
app.use(require('./routes/data-page'));
|
||||
|
||||
// 模型池状态(前端可展示空闲/占用)+ 每模型 token 用量(今日/累计,输入/输出分开)。
|
||||
// 从生效配置补齐平台维度字段(platform/mid/vision/type + 平台 key 数 key_count):
|
||||
|
||||
@@ -814,16 +814,20 @@ function toolScheduleTask(ctx, args) {
|
||||
// 列名先对 sqlite_master 真实列校验再 quoteIdent 转义,值全部走 ? 绑定。
|
||||
// update/delete 不做结构化 op(单行 SQL 本身简单、错误率低,且 AND 等值 where 表达力
|
||||
// 不够还要回退 exec):继续走 exec,入口不拦写语句,兑底通道保持全能力。
|
||||
// runTaskSql 是本工具与 routes/data-page.js(/api/db/{task_id}/query,页面前端调)共用的
|
||||
// 唯一 SQL 执行入口:prepare/读写分流/事务/DDL 判定两处同一事实源,不漂移。
|
||||
const DB_MAX_ROWS = 500; // query 行数上限(docs 要求:防爆上下文)
|
||||
const DB_MAX_BYTES = 100 * 1024; // query 序列化字节上限
|
||||
|
||||
function openTaskDb(ctx) {
|
||||
fs.mkdirSync(ctx.taskDir, { recursive: true });
|
||||
const db = new Database(path.join(ctx.taskDir, 'data.db'));
|
||||
function openTaskDbAt(taskDir) {
|
||||
fs.mkdirSync(taskDir, { recursive: true });
|
||||
const db = new Database(path.join(taskDir, 'data.db'));
|
||||
db.pragma('busy_timeout = 5000');
|
||||
return db;
|
||||
}
|
||||
|
||||
function openTaskDb(ctx) { return openTaskDbAt(ctx.taskDir); }
|
||||
|
||||
// better-sqlite3 不接受 boolean/array/object 绑定;JSON 世界 true/false ↔ SQLite 0/1 是强约定。
|
||||
// 所有进入绑定位的值(params / rows / set / where)统一过这里。
|
||||
function dbValue(v, label) {
|
||||
@@ -871,10 +875,11 @@ function jsonSafeRows(rows) {
|
||||
}
|
||||
|
||||
// 500 行 / 100KB 双上限:未超限返回裸数组;超限改 {rows,...} 信封并附截断说明。
|
||||
function renderQueryResult(rows) {
|
||||
// overflow 由 runTaskSql 的行数截断给出(总行数不再探得,故信封只报 returned_rows 不报 total);
|
||||
// 字节线在此再收。
|
||||
function renderQueryResult(rows, overflow) {
|
||||
let shown = rows;
|
||||
let truncated = shown.length > DB_MAX_ROWS;
|
||||
if (truncated) shown = shown.slice(0, DB_MAX_ROWS);
|
||||
let truncated = !!overflow;
|
||||
if (Buffer.byteLength(JSON.stringify(shown, null, 2)) > DB_MAX_BYTES) {
|
||||
truncated = true;
|
||||
let bytes = 4; // "[\n]"
|
||||
@@ -891,12 +896,58 @@ function renderQueryResult(rows) {
|
||||
return JSON.stringify({
|
||||
rows: shown,
|
||||
returned_rows: shown.length,
|
||||
total_rows: rows.length,
|
||||
truncated: true,
|
||||
note: '结果已截断(上限 ' + DB_MAX_ROWS + ' 行或 ' + Math.floor(DB_MAX_BYTES / 1024) + ' KB)。用 WHERE 收窄列/行,或 LIMIT/OFFSET 分页。',
|
||||
}, null, 2);
|
||||
}
|
||||
|
||||
// 任务库单语句执行的统一入口。mode:'read' 只许读(op=query)| 'write' 只许写(op=exec)|
|
||||
// 'any' 按 stmt.reader 自动分流(HTTP API,SKILL.md 契约:任意单语句)。
|
||||
// maxRows>0 时读取走 iterate 到量即停(防大表 SELECT * 全量物化),overflow 处置交调用方:
|
||||
// 工具截断成信封,API 直接报错引导分页。错误一律抛出,不在此层包装返回形态。
|
||||
function runTaskSql(taskDir, sql, params, mode, maxRows) {
|
||||
const text = String(sql || '').trim();
|
||||
if (!text) throw new Error('db: sql 不能为空');
|
||||
const db = openTaskDbAt(taskDir);
|
||||
try {
|
||||
const stmt = db.prepare(text); // 多语句在此抛错(堆叠注入入口即挡)
|
||||
const bound = sanitizeDbParams(params);
|
||||
if (stmt.reader) {
|
||||
if (mode === 'write') throw new Error('db: op=exec 收到只读语句,读取请用 op=query');
|
||||
const rows = [];
|
||||
let overflow = false;
|
||||
if (maxRows > 0) {
|
||||
const it = stmt.iterate(...bound);
|
||||
try {
|
||||
for (const r of it) {
|
||||
if (rows.length >= maxRows) { overflow = true; break; }
|
||||
rows.push(r);
|
||||
}
|
||||
} finally { try { it.return(); } catch (_) {} }
|
||||
} else {
|
||||
for (const r of stmt.all(...bound)) rows.push(r);
|
||||
}
|
||||
return { kind: 'read', rows: jsonSafeRows(rows), overflow };
|
||||
}
|
||||
if (mode === 'read') throw new Error('db: op=query 只允许读语句(SELECT 等),写操作请用 op=exec');
|
||||
db.exec('BEGIN');
|
||||
try {
|
||||
const info = stmt.run(...bound);
|
||||
db.exec('COMMIT');
|
||||
const verb = text.split(/\s+/)[0].toLowerCase();
|
||||
const out = (verb === 'create' || verb === 'alter' || verb === 'drop')
|
||||
? { ok: true }
|
||||
: { rowsAffected: info.changes, lastInsertRowid: Number(info.lastInsertRowid) };
|
||||
return { kind: 'write', out };
|
||||
} catch (err) {
|
||||
try { db.exec('ROLLBACK'); } catch (_) {}
|
||||
throw err;
|
||||
}
|
||||
} finally {
|
||||
try { db.close(); } catch (_) {}
|
||||
}
|
||||
}
|
||||
|
||||
function toolDb(ctx, args) {
|
||||
const op = String(args.op || '').trim().toLowerCase();
|
||||
const sql = String(args.sql || '').trim();
|
||||
@@ -907,28 +958,13 @@ function toolDb(ctx, args) {
|
||||
switch (op) {
|
||||
case 'exec': {
|
||||
if (!sql) throw new Error('db: op=exec 缺少必填参数 sql');
|
||||
db = openTaskDb(ctx);
|
||||
const stmt = db.prepare(sql); // 多语句在此抛错
|
||||
if (stmt.reader) throw new Error('db: op=exec 收到只读语句,读取请用 op=query');
|
||||
const params = sanitizeDbParams(args.params);
|
||||
db.exec('BEGIN');
|
||||
try {
|
||||
const info = stmt.run(...params);
|
||||
db.exec('COMMIT');
|
||||
const verb = sql.split(/\s+/)[0].toLowerCase();
|
||||
if (verb === 'create' || verb === 'alter' || verb === 'drop') return JSON.stringify({ ok: true });
|
||||
return JSON.stringify({ rowsAffected: info.changes, lastInsertRowid: Number(info.lastInsertRowid) });
|
||||
} catch (err) {
|
||||
try { db.exec('ROLLBACK'); } catch (_) {}
|
||||
throw err;
|
||||
}
|
||||
const r = runTaskSql(ctx.taskDir, sql, args.params, 'write', 0);
|
||||
return JSON.stringify(r.out);
|
||||
}
|
||||
case 'query': {
|
||||
if (!sql) throw new Error('db: op=query 缺少必填参数 sql');
|
||||
db = openTaskDb(ctx);
|
||||
const stmt = db.prepare(sql);
|
||||
if (!stmt.reader) throw new Error('db: op=query 只允许读语句(SELECT 等),写操作请用 op=exec');
|
||||
return renderQueryResult(jsonSafeRows(stmt.all(...sanitizeDbParams(args.params))));
|
||||
const r = runTaskSql(ctx.taskDir, sql, args.params, 'read', DB_MAX_ROWS);
|
||||
return renderQueryResult(r.rows, r.overflow);
|
||||
}
|
||||
case 'insert': {
|
||||
if (!table) throw new Error('db: op=insert 缺少必填参数 table');
|
||||
@@ -1084,4 +1120,4 @@ async function executeTool(baseCtx, name, args) {
|
||||
return 'Error: 未知工具 ' + name;
|
||||
}
|
||||
|
||||
module.exports = { executeTool, resolveInTask, recordFile };
|
||||
module.exports = { executeTool, resolveInTask, recordFile, runTaskSql };
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
---
|
||||
name: data-page
|
||||
description: 数据页面脚手架:把 table/dashboard/kanban 模板复制到任务目录 app/templates/,配合 db 工具产出 /app/{task_id}/ 可访问、经 /api/db/{task_id}/query 读写 data.db 的查看/管理页
|
||||
input_schema:
|
||||
type: object
|
||||
properties:
|
||||
dest:
|
||||
type: string
|
||||
description: 模板输出目录(相对会话任务目录,自动预转绝对路径;缺省 app/templates,已存在的文件跳过不覆盖)
|
||||
---
|
||||
|
||||
# data-page
|
||||
|
||||
## 何时使用
|
||||
|
||||
当用户提出以下需求时使用本技能:
|
||||
|
||||
- 把数据整理到数据库
|
||||
- 生成数据查看页面
|
||||
- 生成数据管理页面
|
||||
- 数据统计展示
|
||||
|
||||
不适用:纯粹的文件读写、代码编写、信息检索。
|
||||
|
||||
## 环境约定
|
||||
|
||||
每个会话有独立的任务目录:
|
||||
|
||||
- 数据库:任务目录下的 `data.db`
|
||||
- 页面目录:任务目录下的 `app/`
|
||||
- 页面入口:`app/index.html`
|
||||
- 访问地址:`/app/{task_id}/`
|
||||
- 数据 API:`/api/db/{task_id}/query`
|
||||
|
||||
`{task_id}` 是任务目录的名称。页面通过 URL 动态解析,不要硬编码。
|
||||
|
||||
## 初始化
|
||||
|
||||
生成页面前,调用 `skill(name="data-page", op="run", input_args={"dest": "app/templates"})` 复制模板到任务目录的 `app/templates/`。已存在则跳过,不会覆盖修改过的文件(重跑幂等)。
|
||||
|
||||
## 数据 API
|
||||
|
||||
页面通过此接口读写数据。
|
||||
|
||||
### 请求
|
||||
|
||||
```
|
||||
POST /api/db/{task_id}/query
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"sql": "SELECT * FROM parts WHERE qty > ?",
|
||||
"params": [0]
|
||||
}
|
||||
```
|
||||
|
||||
- `sql`:任意 SQLite 语句
|
||||
- `params`:参数化绑定的值数组,可省略
|
||||
- 必须使用参数化,不要把用户输入拼进 SQL
|
||||
|
||||
### 响应
|
||||
|
||||
成功时返回 JSON:
|
||||
|
||||
- SELECT:行数组 `[{"id": 1, "name": "螺丝"}, ...]`
|
||||
- 写操作:`{"rowsAffected": 1, "lastInsertRowid": 3}`
|
||||
- 建表等 DDL:`{"ok": true}`
|
||||
|
||||
失败时返回 `{"error": "错误信息"}`,HTTP 状态码仍为 200。前端需要检查 `error` 字段。
|
||||
|
||||
### task_id 获取
|
||||
|
||||
```javascript
|
||||
const taskId = location.pathname.split('/').filter(Boolean)[1];
|
||||
```
|
||||
|
||||
## 页面生成流程
|
||||
|
||||
1. **明确数据结构**:与用户确认字段。如果描述模糊,可以建议合理的结构。
|
||||
2. **创建表并录入数据**:用 `db` 工具完成。
|
||||
3. **初始化模板**:调用 `skill(name="data-page", op="run", input_args={"dest": "app/templates"})`。
|
||||
4. **生成页面**:从 `app/templates/` 选合适的模板,根据表结构调整字段和 SQL,写入 `app/index.html`。
|
||||
5. **告知用户**:访问地址为 `/app/{task_id}/`,简要说明页面功能。
|
||||
|
||||
页面必须包含:
|
||||
|
||||
- HTML 骨架(`<!DOCTYPE html>`、`<meta viewport>`、UTF-8)
|
||||
- 移动端友好的样式
|
||||
- 通过 `fetch` 调用数据 API
|
||||
- 错误处理和加载状态
|
||||
|
||||
## 模板
|
||||
|
||||
模板位于 `app/templates/`。
|
||||
|
||||
- **table.html**:标准表格,适合清单、列表。含排序、搜索、分页。
|
||||
- **dashboard.html**:统计看板,顶部卡片 + 简单图表 + 明细表。
|
||||
- **kanban.html**:分组看板,按字段分列展示。
|
||||
|
||||
优先使用模板。模板都不合适时才从零写。
|
||||
|
||||
## 最小示例
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>采购清单</title>
|
||||
<style>
|
||||
body { font-family: system-ui, sans-serif; margin: 0; padding: 16px; background: #f5f5f5; }
|
||||
h1 { font-size: 20px; margin: 0 0 16px; }
|
||||
.card { background: white; border-radius: 12px; padding: 16px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
|
||||
table { width: 100%; border-collapse: collapse; }
|
||||
th, td { padding: 8px; text-align: left; border-bottom: 1px solid #eee; font-size: 14px; }
|
||||
th { color: #666; font-weight: 500; }
|
||||
.empty { text-align: center; color: #999; padding: 32px; }
|
||||
.error { color: #d33; padding: 12px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>采购清单</h1>
|
||||
<div class="card" id="content">加载中…</div>
|
||||
|
||||
<script>
|
||||
const taskId = location.pathname.split('/').filter(Boolean)[1];
|
||||
const API = `/api/db/${taskId}/query`;
|
||||
|
||||
async function query(sql, params = []) {
|
||||
const res = await fetch(API, {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({sql, params})
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
}
|
||||
|
||||
function escapeHtml(s) {
|
||||
return String(s ?? '').replace(/[&<>"']/g, c => ({
|
||||
'&':'&','<':'<','>':'>','"':'"',"'":'''
|
||||
}[c]));
|
||||
}
|
||||
|
||||
async function render() {
|
||||
const el = document.getElementById('content');
|
||||
try {
|
||||
const rows = await query('SELECT * FROM parts ORDER BY id');
|
||||
if (!rows.length) {
|
||||
el.innerHTML = '<div class="empty">暂无数据</div>';
|
||||
return;
|
||||
}
|
||||
el.innerHTML = `<table>
|
||||
<thead><tr><th>名称</th><th>规格</th><th>类别</th><th>数量</th><th>单位</th><th>备注</th></tr></thead>
|
||||
<tbody>${rows.map(r => `<tr>
|
||||
<td>${escapeHtml(r.name)}</td>
|
||||
<td>${escapeHtml(r.spec)}</td>
|
||||
<td>${escapeHtml(r.category)}</td>
|
||||
<td>${escapeHtml(r.qty)}</td>
|
||||
<td>${escapeHtml(r.unit)}</td>
|
||||
<td>${escapeHtml(r.note)}</td>
|
||||
</tr>`).join('')}</tbody>
|
||||
</table>`;
|
||||
} catch (e) {
|
||||
el.innerHTML = `<div class="error">加载失败:${escapeHtml(e.message)}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
render();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
## 最佳实践
|
||||
|
||||
**前端**
|
||||
|
||||
- 用原生 JS + fetch,不引入框架
|
||||
- 样式用内联 `<style>` 或独立 CSS,不依赖外部 CSS 库
|
||||
- 图表用纯 SVG 或 CSS 绘制
|
||||
- 移动优先
|
||||
- 显示加载状态和错误提示
|
||||
- 提交类按钮加禁用状态,避免重复点击
|
||||
|
||||
**数据库**
|
||||
|
||||
- 使用参数化查询
|
||||
- 大表查询加 `LIMIT`
|
||||
|
||||
**安全**
|
||||
|
||||
- 用户输入渲染到 HTML 时用 `textContent`,或用 `escapeHtml` 转义后再用 `innerHTML`
|
||||
|
||||
**用户体验**
|
||||
|
||||
- 页面标题反映数据内容
|
||||
- 空数据时显示友好提示
|
||||
- 操作有反馈(保存成功、删除确认)
|
||||
|
||||
## 常见错误
|
||||
|
||||
1. 硬编码 task_id —— 必须从 URL 解析
|
||||
2. 忘记 `await` —— fetch 返回 Promise
|
||||
3. 没检查 `error` 字段 —— API 错误时仍返回 200
|
||||
4. 表名或字段名拼错
|
||||
5. 引入 CDN 外部库 —— 容器可能无网络,优先纯原生
|
||||
6. 页面文件不在 `app/` 下 —— 无法通过 `/app/{task_id}/` 访问
|
||||
7. SQL 占位符与参数数量不匹配 —— 优先用结构化 insert,避免手写
|
||||
|
||||
## 检查清单
|
||||
|
||||
- [ ] 数据库表已创建
|
||||
- [ ] 数据已录入
|
||||
- [ ] `app/index.html` 已写入
|
||||
- [ ] 页面动态解析 task_id
|
||||
- [ ] 包含错误处理和加载状态
|
||||
- [ ] 用户输入渲染时已转义
|
||||
- [ ] 已告知用户访问地址 `/app/{task_id}/`
|
||||
@@ -0,0 +1,56 @@
|
||||
#!/usr/bin/env python3
|
||||
# data-page 技能入口:把技能自带 templates/*.html 复制到会话任务目录的 app/templates/。
|
||||
# 已存在的同名文件跳过不覆盖(AI 改过的模板要能经受重跑);纯 stdlib,无 requirements。
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def main():
|
||||
try:
|
||||
args = json.loads(sys.argv[1]) if len(sys.argv) >= 2 and sys.argv[1].strip() else {}
|
||||
if not isinstance(args, dict):
|
||||
raise ValueError('input_args 必须是 JSON 对象')
|
||||
except (ValueError, json.JSONDecodeError) as e:
|
||||
print('参数解析失败:' + str(e), file=sys.stderr)
|
||||
return 1
|
||||
|
||||
skill_dir = Path(__file__).resolve().parent
|
||||
src = skill_dir / 'templates'
|
||||
if not src.is_dir():
|
||||
print('技能自身缺少 templates/ 目录:' + str(src), file=sys.stderr)
|
||||
return 1
|
||||
tpl = sorted(src.glob('*.html'))
|
||||
if not tpl:
|
||||
print('templates/ 下没有 .html 模板', file=sys.stderr)
|
||||
return 1
|
||||
|
||||
# dest 建议显式传入(key 含 "dest",skill manager 会按会话目录预转绝对路径)。
|
||||
# 缺省退回 cwd:远端模式 cwd 即会话目录;若退到技能目录内则明确报错,避免污染技能。
|
||||
dest = Path(args.get('dest') or os.path.join(os.getcwd(), 'app', 'templates'))
|
||||
if not dest.is_absolute():
|
||||
dest = dest.resolve()
|
||||
if str(dest) == str(skill_dir) or str(dest).startswith(str(skill_dir) + os.sep):
|
||||
print('dest 必须落在会话任务目录(请传 input_args {"dest": "app/templates"})', file=sys.stderr)
|
||||
return 1
|
||||
|
||||
dest.mkdir(parents=True, exist_ok=True)
|
||||
copied, skipped = [], []
|
||||
for f in tpl:
|
||||
target = dest / f.name
|
||||
if target.exists():
|
||||
skipped.append(f.name)
|
||||
else:
|
||||
shutil.copy2(f, target)
|
||||
copied.append(f.name)
|
||||
|
||||
print('模板目录:' + str(dest))
|
||||
print('新复制 ' + str(len(copied)) + ' 个:' + (', '.join(copied) if copied else '无'))
|
||||
print('跳过(已存在,不覆盖)' + str(len(skipped)) + ' 个:' + (', '.join(skipped) if skipped else '无'))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,132 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<title>数据看板</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #f5f5f7; --surface: #fff; --border: #e8e8ed; --text: #1d1d1f;
|
||||
--text-2: #6e6e73; --accent: #0071e3; --accent-2: #5ac8fa; --accent-3: #af52de;
|
||||
--r: 12px; --shadow: 0 1px 3px rgba(0,0,0,0.04);
|
||||
}
|
||||
* { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
|
||||
html, body { margin: 0; }
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "PingFang SC", "Helvetica Neue", Arial, sans-serif;
|
||||
background: var(--bg); color: var(--text); font-size: 14px; line-height: 1.5;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
padding: 16px; padding-bottom: calc(16px + env(safe-area-inset-bottom));
|
||||
}
|
||||
.container { max-width: 820px; margin: 0 auto; }
|
||||
h1 { font-size: 20px; margin: 4px 0 20px; letter-spacing: -0.02em; }
|
||||
.stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 12px; margin-bottom: 16px; }
|
||||
.stat { background: var(--surface); border-radius: var(--r); box-shadow: var(--shadow); padding: 16px 18px; }
|
||||
.stat .lbl { color: var(--text-2); font-size: 12px; margin-bottom: 4px; }
|
||||
.stat .val { font-size: 24px; font-weight: 600; letter-spacing: -0.02em; font-variant-numeric: tabular-nums; }
|
||||
.card { background: var(--surface); border-radius: var(--r); box-shadow: var(--shadow); padding: 18px; margin-bottom: 16px; }
|
||||
.card h2 { font-size: 14px; font-weight: 600; margin: 0 0 14px; color: var(--text-2); text-transform: uppercase; letter-spacing: 0.05em; }
|
||||
.bars { display: flex; flex-direction: column; gap: 10px; }
|
||||
.bar-row { display: grid; grid-template-columns: minmax(80px, 140px) 1fr auto; gap: 12px; align-items: center; }
|
||||
.bar-row .k { font-size: 13px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.bar-row .bar { height: 8px; background: var(--bg); border-radius: 4px; overflow: hidden; }
|
||||
.bar-row .bar > i { display: block; height: 100%; background: var(--accent); border-radius: 4px; transition: width .4s ease; }
|
||||
.bar-row:nth-child(3n+2) .bar > i { background: var(--accent-2); }
|
||||
.bar-row:nth-child(3n) .bar > i { background: var(--accent-3); }
|
||||
.bar-row .v { font-size: 13px; font-variant-numeric: tabular-nums; color: var(--text-2); min-width: 40px; text-align: right; }
|
||||
table { width: 100%; border-collapse: collapse; font-size: 13px; }
|
||||
th, td { padding: 8px 0; text-align: left; border-bottom: 1px solid var(--border); white-space: nowrap; }
|
||||
th { color: var(--text-2); font-weight: 500; font-size: 12px; }
|
||||
tr:last-child td { border-bottom: none; }
|
||||
.msg { text-align: center; padding: 40px 20px; color: var(--text-2); }
|
||||
.msg.err { color: #d70015; }
|
||||
@media (max-width: 480px) {
|
||||
body { padding: 8px; }
|
||||
h1 { font-size: 18px; margin-bottom: 14px; }
|
||||
.stat .val { font-size: 20px; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<h1 id="title">数据看板</h1>
|
||||
<div class="stats" id="stats"></div>
|
||||
<div class="card" id="chartCard">
|
||||
<h2 id="chartTitle">分布</h2>
|
||||
<div class="bars" id="bars"></div>
|
||||
</div>
|
||||
<div class="card" id="tableCard">
|
||||
<h2>明细</h2>
|
||||
<div id="table"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const CONFIG = {
|
||||
table: 'items',
|
||||
pk: 'id',
|
||||
title: '数据看板',
|
||||
groupBy: 'category', // 分组维度(柱状图用)
|
||||
sumColumn: 'qty', // 求和的数值列
|
||||
sumLabel: '总量',
|
||||
detailColumns: ['name', 'category', 'qty'], // 明细表展示的列
|
||||
detailLimit: 20,
|
||||
};
|
||||
|
||||
const API = `/api/db/${location.pathname.split('/').filter(Boolean)[1]}/query`;
|
||||
const esc = s => String(s ?? '').replace(/[&<>"']/g, c =>
|
||||
({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
|
||||
async function q(sql, params = []) {
|
||||
const r = await fetch(API, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ sql, params }),
|
||||
});
|
||||
const d = await r.json();
|
||||
if (d.error) throw new Error(d.error);
|
||||
return d;
|
||||
}
|
||||
|
||||
async function init() {
|
||||
document.getElementById('title').textContent = CONFIG.title;
|
||||
try {
|
||||
const [cnt, sum, group, detail] = await Promise.all([
|
||||
q(`SELECT COUNT(*) AS v FROM ${CONFIG.table}`),
|
||||
q(`SELECT SUM(${CONFIG.sumColumn}) AS v FROM ${CONFIG.table}`),
|
||||
q(`SELECT ${CONFIG.groupBy} AS k, SUM(${CONFIG.sumColumn}) AS v
|
||||
FROM ${CONFIG.table} GROUP BY ${CONFIG.groupBy} ORDER BY v DESC LIMIT 20`),
|
||||
q(`SELECT * FROM ${CONFIG.table} LIMIT ${CONFIG.detailLimit}`),
|
||||
]);
|
||||
|
||||
document.getElementById('stats').innerHTML = `
|
||||
<div class="stat"><div class="lbl">总条数</div><div class="val">${cnt[0]?.v ?? 0}</div></div>
|
||||
<div class="stat"><div class="lbl">${esc(CONFIG.sumLabel)}</div><div class="val">${sum[0]?.v ?? 0}</div></div>
|
||||
<div class="stat"><div class="lbl">分组数</div><div class="val">${group.length}</div></div>
|
||||
`;
|
||||
|
||||
document.getElementById('chartTitle').textContent = `按 ${CONFIG.groupBy} 分布`;
|
||||
const max = Math.max(...group.map(g => g.v || 0), 1);
|
||||
document.getElementById('bars').innerHTML = group.length
|
||||
? group.map(g => `
|
||||
<div class="bar-row">
|
||||
<div class="k" title="${esc(g.k)}">${esc(g.k ?? '(空)')}</div>
|
||||
<div class="bar"><i style="width:${((g.v || 0) / max * 100).toFixed(1)}%"></i></div>
|
||||
<div class="v">${g.v ?? 0}</div>
|
||||
</div>`).join('')
|
||||
: '<div class="msg">暂无数据</div>';
|
||||
|
||||
document.getElementById('table').innerHTML = detail.length
|
||||
? `<table><thead><tr>${CONFIG.detailColumns.map(c => `<th>${esc(c)}</th>`).join('')}</tr></thead>
|
||||
<tbody>${detail.map(r => `<tr>${CONFIG.detailColumns.map(c => `<td>${esc(r[c])}</td>`).join('')}</tr>`).join('')}</tbody></table>`
|
||||
: '<div class="msg">暂无数据</div>';
|
||||
} catch (e) {
|
||||
document.getElementById('stats').innerHTML = '';
|
||||
document.getElementById('bars').innerHTML = `<div class="msg err">加载失败:${esc(e.message)}</div>`;
|
||||
document.getElementById('table').innerHTML = '';
|
||||
}
|
||||
}
|
||||
init();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,147 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<title>看板</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #f5f5f7; --surface: #fff; --border: #e8e8ed; --text: #1d1d1f;
|
||||
--text-2: #6e6e73; --accent: #0071e3; --r: 12px; --shadow: 0 1px 3px rgba(0,0,0,0.04);
|
||||
}
|
||||
* { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
|
||||
html, body { margin: 0; }
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "PingFang SC", "Helvetica Neue", Arial, sans-serif;
|
||||
background: var(--bg); color: var(--text); font-size: 14px; line-height: 1.5;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
padding: 16px; padding-bottom: calc(16px + env(safe-area-inset-bottom));
|
||||
}
|
||||
h1 { font-size: 20px; margin: 4px 0 20px; letter-spacing: -0.02em; }
|
||||
.board { display: flex; gap: 12px; overflow-x: auto; padding-bottom: 8px; scroll-snap-type: x proximity; }
|
||||
.col { flex: 0 0 260px; scroll-snap-align: start; background: var(--surface); border-radius: var(--r);
|
||||
box-shadow: var(--shadow); display: flex; flex-direction: column; max-height: calc(100vh - 140px); }
|
||||
.col-hd { display: flex; align-items: center; justify-content: space-between;
|
||||
padding: 12px 14px; border-bottom: 1px solid var(--border); font-size: 13px; font-weight: 600; }
|
||||
.col-hd .n { color: var(--text-2); font-weight: 400; font-size: 12px;
|
||||
background: var(--bg); padding: 1px 8px; border-radius: 999px; }
|
||||
.col-bd { padding: 10px; display: flex; flex-direction: column; gap: 8px; overflow-y: auto; flex: 1; }
|
||||
.card { background: var(--surface); border: 1px solid var(--border); border-radius: 10px; padding: 10px 12px;
|
||||
display: flex; flex-direction: column; gap: 8px; transition: box-shadow .15s, transform .05s; }
|
||||
.card:hover { box-shadow: 0 2px 8px rgba(0,0,0,0.06); }
|
||||
.card .t { font-size: 13px; font-weight: 500; line-height: 1.4; }
|
||||
.card .meta { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
.card .meta span { font-size: 11px; color: var(--text-2); background: var(--bg); padding: 2px 7px; border-radius: 999px; }
|
||||
.card .mv { display: flex; gap: 6px; margin-top: 2px; }
|
||||
.card .mv button { appearance: none; border: 1px solid var(--border); background: var(--surface);
|
||||
color: var(--text-2); cursor: pointer; font: inherit; font-size: 12px; padding: 3px 9px;
|
||||
border-radius: 6px; transition: all .15s; }
|
||||
.card .mv button:hover:not(:disabled) { border-color: var(--accent); color: var(--accent); }
|
||||
.card .mv button:disabled { opacity: .3; cursor: default; }
|
||||
.col-bd .empty { text-align: center; color: var(--text-2); padding: 20px 8px; font-size: 12px; }
|
||||
.msg { text-align: center; padding: 40px 20px; color: var(--text-2); }
|
||||
.msg.err { color: #d70015; }
|
||||
@media (max-width: 480px) { body { padding: 8px; } h1 { font-size: 18px; margin-bottom: 14px; } }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1 id="title">看板</h1>
|
||||
<div id="root"><div class="msg">加载中…</div></div>
|
||||
|
||||
<script>
|
||||
const CONFIG = {
|
||||
table: 'tasks',
|
||||
pk: 'id',
|
||||
title: '任务看板',
|
||||
groupField: 'status', // 用来分列的字段
|
||||
groups: ['待办', '进行中', '已完成'], // 列的顺序
|
||||
titleField: 'title', // 卡片主标题字段
|
||||
metaFields: ['assignee', 'due'], // 卡片上显示的次要字段
|
||||
};
|
||||
|
||||
const API = `/api/db/${location.pathname.split('/').filter(Boolean)[1]}/query`;
|
||||
const esc = s => String(s ?? '').replace(/[&<>"']/g, c =>
|
||||
({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
|
||||
async function q(sql, params = []) {
|
||||
const r = await fetch(API, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ sql, params }),
|
||||
});
|
||||
const d = await r.json();
|
||||
if (d.error) throw new Error(d.error);
|
||||
return d;
|
||||
}
|
||||
|
||||
let rows = [];
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
rows = await q(`SELECT * FROM ${CONFIG.table}`);
|
||||
render();
|
||||
} catch (e) {
|
||||
document.getElementById('root').innerHTML = `<div class="msg err">加载失败:${esc(e.message)}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
function render() {
|
||||
document.getElementById('title').textContent = CONFIG.title;
|
||||
const groups = CONFIG.groups;
|
||||
const html = `<div class="board">${groups.map((g, i) => {
|
||||
const items = rows.filter(r => String(r[CONFIG.groupField] ?? '') === g);
|
||||
return `<div class="col">
|
||||
<div class="col-hd"><span>${esc(g)}</span><span class="n">${items.length}</span></div>
|
||||
<div class="col-bd">
|
||||
${items.length ? items.map(r => card(r, i)).join('') : '<div class="empty">暂无</div>'}
|
||||
</div>
|
||||
</div>`;
|
||||
}).join('')}</div>`;
|
||||
document.getElementById('root').innerHTML = html;
|
||||
bind();
|
||||
}
|
||||
|
||||
function card(r, gi) {
|
||||
const meta = CONFIG.metaFields
|
||||
.filter(f => r[f] != null && r[f] !== '')
|
||||
.map(f => `<span>${esc(r[f])}</span>`).join('');
|
||||
return `<div class="card" data-pk="${esc(r[CONFIG.pk])}">
|
||||
<div class="t">${esc(r[CONFIG.titleField] ?? '(无标题)')}</div>
|
||||
${meta ? `<div class="meta">${meta}</div>` : ''}
|
||||
<div class="mv">
|
||||
<button data-dir="-1" ${gi === 0 ? 'disabled' : ''}>← 上一列</button>
|
||||
<button data-dir="1" ${gi === CONFIG.groups.length - 1 ? 'disabled' : ''}>下一列 →</button>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function bind() {
|
||||
document.querySelectorAll('.card').forEach(cardEl => {
|
||||
const pk = cardEl.dataset.pk;
|
||||
cardEl.querySelectorAll('.mv button').forEach(btn => {
|
||||
btn.onclick = async () => {
|
||||
const dir = Number(btn.dataset.dir);
|
||||
const row = rows.find(r => String(r[CONFIG.pk]) === String(pk));
|
||||
if (!row) return;
|
||||
const cur = CONFIG.groups.indexOf(String(row[CONFIG.groupField] ?? ''));
|
||||
const next = cur + dir;
|
||||
if (next < 0 || next >= CONFIG.groups.length) return;
|
||||
const newGroup = CONFIG.groups[next];
|
||||
btn.disabled = true;
|
||||
try {
|
||||
await q(`UPDATE ${CONFIG.table} SET ${CONFIG.groupField} = ? WHERE ${CONFIG.pk} = ?`, [newGroup, pk]);
|
||||
row[CONFIG.groupField] = newGroup;
|
||||
render();
|
||||
} catch (e) {
|
||||
alert('移动失败:' + e.message);
|
||||
btn.disabled = false;
|
||||
}
|
||||
};
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
load();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,272 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<title>数据表格</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #f5f5f7; --surface: #fff; --border: #e8e8ed; --text: #1d1d1f;
|
||||
--text-2: #6e6e73; --accent: #0071e3; --accent-h: #0077ed; --danger: #d70015;
|
||||
--r: 12px; --r-sm: 8px;
|
||||
--shadow: 0 1px 3px rgba(0,0,0,0.04);
|
||||
--shadow-lg: 0 8px 24px rgba(0,0,0,0.12);
|
||||
}
|
||||
* { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
|
||||
html, body { margin: 0; }
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "PingFang SC", "Helvetica Neue", Arial, sans-serif;
|
||||
background: var(--bg); color: var(--text); font-size: 14px; line-height: 1.5;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
padding: 16px; padding-bottom: calc(16px + env(safe-area-inset-bottom));
|
||||
}
|
||||
.container { max-width: 820px; margin: 0 auto; }
|
||||
.card { background: var(--surface); border-radius: var(--r); box-shadow: var(--shadow); overflow: hidden; }
|
||||
.hd { display: flex; align-items: center; justify-content: space-between; padding: 14px 18px; border-bottom: 1px solid var(--border); }
|
||||
.hd h1 { margin: 0; font-size: 16px; font-weight: 600; letter-spacing: -0.01em; }
|
||||
.btn { appearance: none; border: none; background: var(--accent); color: #fff; font: inherit; font-weight: 500;
|
||||
padding: 7px 14px; border-radius: 999px; cursor: pointer; transition: background .15s, transform .05s; }
|
||||
.btn:hover { background: var(--accent-h); }
|
||||
.btn:active { transform: scale(0.97); }
|
||||
.tb { padding: 10px 18px; border-bottom: 1px solid var(--border); }
|
||||
.search { width: 100%; border: 1px solid var(--border); background: var(--bg); border-radius: var(--r-sm);
|
||||
padding: 8px 12px; font: inherit; outline: none; transition: border-color .15s, background .15s; }
|
||||
.search:focus { border-color: var(--accent); background: var(--surface); }
|
||||
.tw { overflow-x: auto; }
|
||||
table { width: 100%; border-collapse: collapse; }
|
||||
th, td { padding: 10px 18px; text-align: left; border-bottom: 1px solid var(--border); white-space: nowrap; }
|
||||
th { color: var(--text-2); font-weight: 500; font-size: 13px; cursor: pointer; user-select: none; }
|
||||
th:hover { color: var(--text); }
|
||||
th .ar { font-size: 10px; margin-left: 4px; opacity: .7; }
|
||||
td.ed { cursor: text; }
|
||||
td.ed:hover { background: rgba(0,113,227,0.04); }
|
||||
tr:last-child td { border-bottom: none; }
|
||||
.col-ac { width: 40px; }
|
||||
.del { appearance: none; background: none; border: none; color: var(--text-2); cursor: pointer;
|
||||
font-size: 18px; line-height: 1; padding: 2px 8px; border-radius: 6px; }
|
||||
.del:hover { color: var(--danger); background: rgba(215,0,21,0.08); }
|
||||
.msg { text-align: center; padding: 56px 20px; color: var(--text-2); }
|
||||
.msg.err { color: var(--danger); }
|
||||
.pager { display: flex; align-items: center; justify-content: center; gap: 14px;
|
||||
padding: 12px; border-top: 1px solid var(--border); font-size: 13px; color: var(--text-2); }
|
||||
.pager button { appearance: none; border: 1px solid var(--border); background: var(--surface); font: inherit;
|
||||
padding: 5px 12px; border-radius: 999px; cursor: pointer; }
|
||||
.pager button:disabled { opacity: .4; cursor: default; }
|
||||
dialog { border: none; border-radius: var(--r); padding: 0; box-shadow: var(--shadow-lg);
|
||||
width: min(420px, calc(100vw - 32px)); }
|
||||
dialog::backdrop { background: rgba(0,0,0,0.35); }
|
||||
.form { padding: 22px; }
|
||||
.form h3 { margin: 0 0 18px; font-size: 16px; }
|
||||
.fld { margin-bottom: 14px; }
|
||||
.fld label { display: block; font-size: 12px; color: var(--text-2); margin-bottom: 4px; }
|
||||
.fld input { width: 100%; border: 1px solid var(--border); border-radius: var(--r-sm);
|
||||
padding: 8px 10px; font: inherit; outline: none; transition: border-color .15s; }
|
||||
.fld input:focus { border-color: var(--accent); }
|
||||
.acts { display: flex; gap: 8px; justify-content: flex-end; margin-top: 22px; }
|
||||
.acts button { font: inherit; padding: 8px 16px; border-radius: 999px; cursor: pointer;
|
||||
border: 1px solid var(--border); background: var(--surface); color: var(--text); }
|
||||
.acts .pri { background: var(--accent); color: #fff; border-color: var(--accent); }
|
||||
.acts .pri:hover { background: var(--accent-h); }
|
||||
@media (max-width: 480px) {
|
||||
body { padding: 8px; } th, td { padding: 8px 12px; font-size: 13px; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="card">
|
||||
<div class="hd">
|
||||
<h1 id="title">数据表格</h1>
|
||||
<button class="btn" id="addBtn">+ 新增</button>
|
||||
</div>
|
||||
<div class="tb">
|
||||
<input class="search" id="search" placeholder="搜索…" autocomplete="off">
|
||||
</div>
|
||||
<div id="root"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<dialog id="dlg">
|
||||
<form class="form" method="dialog" id="dlgForm">
|
||||
<h3>新增记录</h3>
|
||||
<div id="fields"></div>
|
||||
<div class="acts">
|
||||
<button value="cancel">取消</button>
|
||||
<button value="ok" class="pri">保存</button>
|
||||
</div>
|
||||
</form>
|
||||
</dialog>
|
||||
|
||||
<script>
|
||||
const CONFIG = {
|
||||
table: 'items', // ← 修改为你的表名
|
||||
pk: 'id', // ← 修改为主键列名
|
||||
title: '数据表格', // ← 修改为页面标题
|
||||
pageSize: 10,
|
||||
editable: true,
|
||||
};
|
||||
|
||||
const API = `/api/db/${location.pathname.split('/').filter(Boolean)[1]}/query`;
|
||||
const S = { cols: [], rows: [], sortKey: null, sortDir: 'asc', kw: '', page: 1, loading: true, err: null };
|
||||
|
||||
async function q(sql, params = []) {
|
||||
const r = await fetch(API, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ sql, params }),
|
||||
});
|
||||
const d = await r.json();
|
||||
if (d.error) throw new Error(d.error);
|
||||
return d;
|
||||
}
|
||||
const esc = s => String(s ?? '').replace(/[&<>"']/g, c =>
|
||||
({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
|
||||
async function load() {
|
||||
S.loading = true; S.err = null; render();
|
||||
try {
|
||||
const cols = await q(`SELECT name FROM pragma_table_info(?)`, [CONFIG.table]);
|
||||
S.cols = cols.map(c => c.name);
|
||||
S.rows = await q(`SELECT * FROM ${CONFIG.table}`);
|
||||
S.loading = false;
|
||||
} catch (e) { S.loading = false; S.err = e.message; }
|
||||
render();
|
||||
}
|
||||
|
||||
function view() {
|
||||
let r = S.rows;
|
||||
if (S.kw) {
|
||||
const k = S.kw.toLowerCase();
|
||||
r = r.filter(x => S.cols.some(c => String(x[c] ?? '').toLowerCase().includes(k)));
|
||||
}
|
||||
if (S.sortKey) {
|
||||
r = r.slice().sort((a, b) => {
|
||||
const x = a[S.sortKey], y = b[S.sortKey];
|
||||
if (x == null && y == null) return 0;
|
||||
if (x == null) return 1; if (y == null) return -1;
|
||||
const c = x < y ? -1 : x > y ? 1 : 0;
|
||||
return S.sortDir === 'asc' ? c : -c;
|
||||
});
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
function render() {
|
||||
const root = document.getElementById('root');
|
||||
if (S.loading) return void (root.innerHTML = '<div class="msg">加载中…</div>');
|
||||
if (S.err) return void (root.innerHTML = `<div class="msg err">加载失败:${esc(S.err)}</div>`);
|
||||
const rows = view();
|
||||
if (!rows.length) return void (root.innerHTML = `<div class="msg">${S.rows.length ? '没有匹配的记录' : '暂无数据'}</div>`);
|
||||
|
||||
const pages = Math.max(1, Math.ceil(rows.length / CONFIG.pageSize));
|
||||
if (S.page > pages) S.page = pages;
|
||||
const start = (S.page - 1) * CONFIG.pageSize;
|
||||
const cur = rows.slice(start, start + CONFIG.pageSize);
|
||||
|
||||
let h = '<div class="tw"><table><thead><tr>';
|
||||
for (const c of S.cols) {
|
||||
const ar = S.sortKey === c ? (S.sortDir === 'asc' ? '↑' : '↓') : '';
|
||||
h += `<th data-c="${esc(c)}">${esc(c)}<span class="ar">${ar}</span></th>`;
|
||||
}
|
||||
if (CONFIG.editable) h += '<th class="col-ac"></th>';
|
||||
h += '</tr></thead><tbody>';
|
||||
|
||||
for (const r of cur) {
|
||||
h += `<tr data-pk="${esc(r[CONFIG.pk])}">`;
|
||||
for (const c of S.cols) {
|
||||
const ed = CONFIG.editable && c !== CONFIG.pk ? ' class="ed"' : '';
|
||||
h += `<td${ed} data-c="${esc(c)}">${esc(r[c])}</td>`;
|
||||
}
|
||||
if (CONFIG.editable) h += '<td class="col-ac"><button class="del" title="删除">×</button></td>';
|
||||
h += '</tr>';
|
||||
}
|
||||
h += '</tbody></table></div>';
|
||||
|
||||
if (pages > 1) {
|
||||
h += `<div class="pager">
|
||||
<button id="prev" ${S.page === 1 ? 'disabled' : ''}>上一页</button>
|
||||
<span>${S.page} / ${pages}</span>
|
||||
<button id="next" ${S.page === pages ? 'disabled' : ''}>下一页</button>
|
||||
</div>`;
|
||||
}
|
||||
root.innerHTML = h;
|
||||
bind();
|
||||
}
|
||||
|
||||
function bind() {
|
||||
document.querySelectorAll('th[data-c]').forEach(th => th.onclick = () => {
|
||||
const c = th.dataset.c;
|
||||
if (S.sortKey === c) S.sortDir = S.sortDir === 'asc' ? 'desc' : 'asc';
|
||||
else { S.sortKey = c; S.sortDir = 'asc'; }
|
||||
render();
|
||||
});
|
||||
document.querySelectorAll('td.ed').forEach(td => td.ondblclick = () => edit(td));
|
||||
document.querySelectorAll('.del').forEach(b => b.onclick = () => del(b.closest('tr')));
|
||||
const p = document.getElementById('prev'), n = document.getElementById('next');
|
||||
if (p) p.onclick = () => { S.page--; render(); };
|
||||
if (n) n.onclick = () => { S.page++; render(); };
|
||||
}
|
||||
|
||||
function edit(td) {
|
||||
if (td.classList.contains('editing')) return;
|
||||
const tr = td.closest('tr'), col = td.dataset.c, pk = tr.dataset.pk, orig = td.textContent;
|
||||
td.classList.add('editing');
|
||||
td.innerHTML = `<input value="${esc(orig)}" style="width:100%;border:1px solid var(--accent);border-radius:4px;padding:2px 6px;font:inherit;outline:none">`;
|
||||
const inp = td.firstChild;
|
||||
inp.focus(); inp.select();
|
||||
let done = false;
|
||||
const finish = async (save) => {
|
||||
if (done) return; done = true;
|
||||
const v = inp.value;
|
||||
if (!save || v === orig) return void render();
|
||||
try {
|
||||
await q(`UPDATE ${CONFIG.table} SET ${col} = ? WHERE ${CONFIG.pk} = ?`, [v, pk]);
|
||||
const r = S.rows.find(x => String(x[CONFIG.pk]) === String(pk));
|
||||
if (r) r[col] = v;
|
||||
render();
|
||||
} catch (e) { alert('保存失败:' + e.message); render(); }
|
||||
};
|
||||
inp.onblur = () => finish(true);
|
||||
inp.onkeydown = e => {
|
||||
if (e.key === 'Enter') { e.preventDefault(); inp.blur(); }
|
||||
if (e.key === 'Escape') { e.preventDefault(); finish(false); }
|
||||
};
|
||||
}
|
||||
|
||||
async function del(tr) {
|
||||
const pk = tr.dataset.pk;
|
||||
if (!confirm('确定删除这条记录?')) return;
|
||||
try {
|
||||
await q(`DELETE FROM ${CONFIG.table} WHERE ${CONFIG.pk} = ?`, [pk]);
|
||||
S.rows = S.rows.filter(x => String(x[CONFIG.pk]) !== String(pk));
|
||||
render();
|
||||
} catch (e) { alert('删除失败:' + e.message); }
|
||||
}
|
||||
|
||||
document.getElementById('search').oninput = e => { S.kw = e.target.value.trim(); S.page = 1; render(); };
|
||||
document.getElementById('title').textContent = CONFIG.title;
|
||||
|
||||
document.getElementById('addBtn').onclick = () => {
|
||||
const dlg = document.getElementById('dlg'), flds = document.getElementById('fields');
|
||||
const cols = S.cols.filter(c => c !== CONFIG.pk);
|
||||
flds.innerHTML = cols.map(c => `<div class="fld"><label>${esc(c)}</label><input name="${esc(c)}" autocomplete="off"></div>`).join('');
|
||||
dlg.showModal();
|
||||
};
|
||||
|
||||
document.getElementById('dlgForm').onsubmit = async e => {
|
||||
if (e.submitter?.value !== 'ok') return;
|
||||
e.preventDefault();
|
||||
const form = e.target;
|
||||
const cols = S.cols.filter(c => c !== CONFIG.pk);
|
||||
const vals = cols.map(c => form.elements[c].value);
|
||||
try {
|
||||
await q(`INSERT INTO ${CONFIG.table} (${cols.join(',')}) VALUES (${cols.map(() => '?').join(',')})`, vals);
|
||||
document.getElementById('dlg').close();
|
||||
await load();
|
||||
} catch (e) { alert('新增失败:' + e.message); }
|
||||
};
|
||||
|
||||
load();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user