Files
agent/skills/data-page/templates/table.html
T

251 lines
9.3 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!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>
<link rel="stylesheet" href="./base.css">
</head>
<body>
<div class="container">
<div class="card">
<div class="hd">
<a class="crumb" href="./" title="返回导航">‹</a>
<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>
<button class="fab" aria-label="返回对话" title="返回发起本数据的对话" onclick="backToApp()">
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 10.5 12 3l9 7.5"/><path d="M5 9.5V21h14V9.5"/></svg>
</button>
<style>
/* 表格页面特有样式 */
.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; flex: 1; }
.tb { padding: 10px 18px; border-bottom: 1px solid var(--border); }
</style>
<script src="./config-table.js"></script>
<script>
const DEFAULT = {
table: 'items', pk: 'id', title: '数据表格', pageSize: 10, editable: true,
labels: {}, numCols: [], options: {}, pills: {},
};
const CONFIG = Object.assign({}, DEFAULT, window.PAGE_CONFIG || {});
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 =>
({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[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 fmt(c, v) {
const pm = CONFIG.pills[c];
if (pm && v != null && pm[v]) return `<span class="pill ${pm[v]}">${esc(v)}</span>`;
return esc(v);
}
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 isNum = CONFIG.numCols.includes(c);
const lb = CONFIG.labels[c] || c;
const ar = S.sortKey === c ? (S.sortDir === 'asc' ? '↑' : '↓') : '';
h += `<th data-c="${esc(c)}"${isNum ? ' class="num"' : ''}>${esc(lb)}<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 cls = [];
if (CONFIG.editable && c !== CONFIG.pk) cls.push('ed');
if (CONFIG.numCols.includes(c)) cls.push('num');
h += `<td${cls.length ? ` class="${cls.join(' ')}"` : ''} data-c="${esc(c)}">${fmt(c, 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');
const opt = CONFIG.options[col];
const style = 'width:100%;border:1px solid var(--accent);border-radius:4px;padding:2px 6px;font:inherit;outline:none;background:var(--surface)';
const ctl = opt
? `<select style="${style}">${opt.map(o => `<option${o === orig ? ' selected' : ''}>${esc(o)}</option>`).join('')}</select>`
: `<input value="${esc(orig)}" type="${CONFIG.numCols.includes(col) ? 'number' : 'text'}" style="${style}">`;
td.innerHTML = ctl;
const inp = td.firstChild;
inp.focus(); if (inp.select) 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] = CONFIG.numCols.includes(col) ? Number(v) : 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 => {
const lb = CONFIG.labels[c] || c;
const opt = CONFIG.options[c];
const ctl = opt
? `<select name="${esc(c)}">${opt.map(o => `<option>${esc(o)}</option>`).join('')}</select>`
: `<input name="${esc(c)}" type="${CONFIG.numCols.includes(c) ? 'number' : 'text'}" autocomplete="off">`;
return `<div class="fld"><label>${esc(lb)}</label>${ctl}</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 => {
const v = form.elements[c].value;
return CONFIG.numCols.includes(c) && v !== '' ? Number(v) : v;
});
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); }
};
function backToApp() {
const id = location.pathname.split('/').filter(Boolean)[1];
location.href = id ? '/?s=' + encodeURIComponent(id) : '/';
}
// 单页场景:本页的副本就是 index.html,标题行返回键指向自身 → 移除(多页导航不受影响)
if (/\/(index\.html)?$/.test(location.pathname)) { const c = document.querySelector('.crumb'); if (c) c.remove(); }
load();
</script>
</body>
</html>