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

117 lines
4.8 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">
<style>
.container { max-width: 1080px; }
</style>
</head>
<body>
<div class="container">
<div class="page-hd">
<a class="crumb" href="./" title="返回导航">‹</a>
<h1 id="title">数据看板</h1>
</div>
<div class="stats" id="stats"></div>
<div class="card card-pad">
<h2 id="chartTitle">分布</h2>
<div class="bars" id="bars"></div>
</div>
<div class="card card-pad">
<h2>明细</h2>
<div class="table-scroll" id="table"></div>
</div>
</div>
<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>
<script src="./config-dashboard.js"></script>
<script>
const DEFAULT = {
table: 'items', pk: 'id', title: '数据看板',
groupBy: 'category',
metric: { type: 'count' },
detailColumns: ['name', 'category', 'qty'],
detailLimit: 20,
};
const CONFIG = Object.assign({}, DEFAULT, window.PAGE_CONFIG || {});
if (window.PAGE_CONFIG && window.PAGE_CONFIG.metric) {
CONFIG.metric = Object.assign({}, DEFAULT.metric, window.PAGE_CONFIG.metric);
}
const API = `/api/db/${location.pathname.split('/').filter(Boolean)[1]}/query`;
const esc = s => String(s ?? '').replace(/[&<>"']/g, c =>
({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[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;
const isCount = CONFIG.metric.type !== 'sum';
const expr = isCount ? 'COUNT(*)' : `SUM(${CONFIG.metric.column})`;
const metricLabel = isCount ? '总条数' : (CONFIG.metric.label || `合计 ${CONFIG.metric.column}`);
try {
const [cnt, metric, group, detail] = await Promise.all([
q(`SELECT COUNT(*) AS v FROM ${CONFIG.table}`),
isCount ? null : q(`SELECT ${expr} AS v FROM ${CONFIG.table}`),
q(`SELECT ${CONFIG.groupBy} AS k, ${expr} AS v
FROM ${CONFIG.table} GROUP BY ${CONFIG.groupBy} ORDER BY v DESC LIMIT 20`),
q(`SELECT * FROM ${CONFIG.table} LIMIT ${CONFIG.detailLimit}`),
]);
// count 模式下 metric 就是总条数,不重复渲染第三张卡(也省一条同值 SQL);sum 模式才三张
const statsCards = [`<div class="stat"><div class="lbl">总条数</div><div class="val">${cnt[0]?.v ?? 0}</div></div>`];
if (!isCount) statsCards.push(`<div class="stat"><div class="lbl">${esc(metricLabel)}</div><div class="val">${metric[0]?.v ?? 0}</div></div>`);
statsCards.push(`<div class="stat"><div class="lbl">分组数</div><div class="val">${group.length}</div></div>`);
document.getElementById('stats').innerHTML = statsCards.join('');
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 = '';
}
}
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(); }
init();
</script>
</body>
</html>