Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3d59c9a975 | ||
|
|
14317a44a2 | ||
|
|
bac19202b7 | ||
|
|
8b7ab976d8 | ||
|
|
0a3b075644 | ||
|
|
437e707893 | ||
|
|
0ff0aff87b | ||
|
|
c03d6c3fe2 | ||
|
|
a122a498e1 |
@@ -52,6 +52,8 @@ DEFAULT_CONFIG = {
|
||||
], ensure_ascii=False),
|
||||
"footer_text": "NBA球迷大全 · 数据为模拟演示数据(2025-26 赛季) · LLM: DeepSeek · 向量: Chroma + bge-large-zh",
|
||||
"admin_password": "admin123",
|
||||
"entity_mark_mode": "first", # 实体标记:first=只标记首次出现 / all=全部标记
|
||||
"suggestion_count": "3", # 对话中底部快捷问题预测个数(默认3)
|
||||
}
|
||||
|
||||
SEARCHABLE = { # 每个表可搜索的 TEXT 字段
|
||||
@@ -189,7 +191,15 @@ def list_rows(table):
|
||||
page = max(1, int(request.args.get("page", 1)))
|
||||
size = min(100, max(1, int(request.args.get("size", 20))))
|
||||
q = (request.args.get("q") or "").strip()
|
||||
# 排序:字段白名单校验(防注入),默认 id 降序
|
||||
cols = _columns(table)
|
||||
valid_fields = {c["name"] for c in cols}
|
||||
sort = request.args.get("sort", "") or "id"
|
||||
if sort not in valid_fields:
|
||||
sort = "id"
|
||||
order = (request.args.get("order", "") or "desc").lower()
|
||||
if order not in ("asc", "desc"):
|
||||
order = "desc"
|
||||
where, args = "", []
|
||||
if q:
|
||||
fields = SEARCHABLE.get(table) or ()
|
||||
@@ -198,10 +208,11 @@ def list_rows(table):
|
||||
where = "WHERE " + " OR ".join(f"{f} LIKE ? ESCAPE '\\'" for f in fields)
|
||||
args = [like] * len(fields)
|
||||
total = query_one(f"SELECT COUNT(*) AS c FROM {table} {where}", args)["c"]
|
||||
rows = query(f"SELECT * FROM {table} {where} ORDER BY id DESC LIMIT ? OFFSET ?",
|
||||
rows = query(f"SELECT * FROM {table} {where} ORDER BY {sort} {order.upper()}, id {order.upper()} LIMIT ? OFFSET ?",
|
||||
args + [size, (page - 1) * size])
|
||||
return jsonify({"table": table, "cn": TABLES[table], "columns": cols,
|
||||
"total": total, "page": page, "size": size, "rows": rows})
|
||||
"total": total, "page": page, "size": size, "rows": rows,
|
||||
"sort": sort, "order": order})
|
||||
|
||||
|
||||
def get_row(table, rid):
|
||||
|
||||
@@ -64,6 +64,22 @@ def boot():
|
||||
return jsonify(chat.boot_info())
|
||||
|
||||
|
||||
@app.route("/api/suggest", methods=["POST"])
|
||||
def api_suggest():
|
||||
"""基于对话历史预测底部快捷问题(个数后台可配,默认3)"""
|
||||
body = request.get_json(force=True, silent=True) or {}
|
||||
history = body.get("history") or []
|
||||
try:
|
||||
n = int(admin_mod.get_config().get("suggestion_count", "3") or "3")
|
||||
except Exception:
|
||||
n = 3
|
||||
try:
|
||||
return jsonify({"suggestions": chat.predict_suggestions(history, n)})
|
||||
except Exception as e:
|
||||
log.exception("suggest error")
|
||||
return jsonify({"suggestions": chat.suggest_questions()[:n]}), 200
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ 对话
|
||||
@app.route("/api/chat", methods=["POST"])
|
||||
def api_chat():
|
||||
@@ -78,7 +94,8 @@ def api_chat():
|
||||
game_refs = [it for s in sources
|
||||
if s.get("tool") in ("search_games", "get_game_detail")
|
||||
for it in s.get("items", [])]
|
||||
spans, cards = entity_linker.link_entities(reply, game_refs=game_refs)
|
||||
mark_mode = admin_mod.get_config().get("entity_mark_mode", "first")
|
||||
spans, cards = entity_linker.link_entities(reply, game_refs=game_refs, mark_mode=mark_mode)
|
||||
return jsonify({"reply": reply, "sources": sources, "used_tools": used_tools,
|
||||
"news_refs": news_refs, "entities": spans, "cards": cards})
|
||||
except Exception as e:
|
||||
@@ -112,8 +129,10 @@ def api_team(tid):
|
||||
@app.route("/api/players")
|
||||
def api_players():
|
||||
q = request.args.get("q", "")
|
||||
r = tools.search_players(q, limit=int(request.args.get("limit", 60)))
|
||||
return jsonify(r.get("results", []))
|
||||
position = request.args.get("position", "")
|
||||
page = max(1, int(request.args.get("page", 1)))
|
||||
size = min(60, max(1, int(request.args.get("size", 24))))
|
||||
return jsonify(tools.list_players(q, position=position, page=page, size=size))
|
||||
|
||||
|
||||
@app.route("/api/players/<int:pid>")
|
||||
@@ -130,12 +149,9 @@ def api_player(pid):
|
||||
def api_games():
|
||||
q = request.args.get("q", "")
|
||||
status = request.args.get("status", "")
|
||||
limit = int(request.args.get("limit", 30))
|
||||
r = tools.search_games(q, limit=limit)
|
||||
results = r.get("results", [])
|
||||
if status:
|
||||
results = [g for g in results if g["status"] == status]
|
||||
return jsonify(results)
|
||||
page = max(1, int(request.args.get("page", 1)))
|
||||
size = min(40, max(1, int(request.args.get("size", 12))))
|
||||
return jsonify(tools.list_games(q, status=status, page=page, size=size))
|
||||
|
||||
|
||||
@app.route("/api/games/<int:gid>")
|
||||
|
||||
@@ -272,3 +272,53 @@ def boot_info():
|
||||
"suggestions": suggest_questions(),
|
||||
"footer_text": cfg.get("footer_text", "NBA球迷大全 · 数据为模拟演示数据(2025-26 赛季)"),
|
||||
}
|
||||
|
||||
|
||||
def _parse_json_array(text):
|
||||
"""从 LLM 输出中解析 JSON 数组(容错:直接 JSON / 提取中括号段)"""
|
||||
if not text:
|
||||
return []
|
||||
text = text.strip()
|
||||
try:
|
||||
arr = json.loads(text)
|
||||
if isinstance(arr, list):
|
||||
return arr
|
||||
except Exception:
|
||||
pass
|
||||
m = re.search(r"\[.*\]", text, re.S)
|
||||
if m:
|
||||
try:
|
||||
arr = json.loads(m.group(0))
|
||||
if isinstance(arr, list):
|
||||
return arr
|
||||
except Exception:
|
||||
pass
|
||||
return []
|
||||
|
||||
|
||||
def predict_suggestions(history=None, n=3):
|
||||
"""基于对话历史,让大模型预测用户接下来最可能追问的 n 个问题(底部快捷语句)。
|
||||
每个问题不超过 30 字;LLM 异常时回退到默认快捷问题。"""
|
||||
n = max(1, min(int(n or 3), 6))
|
||||
history = history or []
|
||||
msgs = [{"role": "system", "content": (
|
||||
f"你是「NBA球迷大全」智能助手。根据对话历史,站在用户角度预测他接下来最可能追问的{n}个问题。\n"
|
||||
"要求:\n"
|
||||
"1. 每个问题不超过30个汉字,简洁口语化\n"
|
||||
"2. 必须是用户会直接发送的提问,不要编号、不要引号、不要解释\n"
|
||||
"3. 只输出JSON数组,例如:[\"库里今天拿了几分\",\"湖人下一场什么时候\"],不要输出任何其他内容")}]
|
||||
for h in history[-6:]:
|
||||
msgs.append({"role": "user", "content": h.get("user", "")})
|
||||
if h.get("assistant"):
|
||||
msgs.append({"role": "assistant", "content": str(h["assistant"])[:600]})
|
||||
if len(msgs) == 1:
|
||||
return DEFAULT_SUGGESTIONS[:n]
|
||||
try:
|
||||
resp = llm.chat(msgs, temperature=0.9, max_tokens=200)
|
||||
arr = _parse_json_array(llm.parse_content(resp))
|
||||
out = [str(x).strip()[:30] for x in arr if str(x).strip()][:n]
|
||||
if out:
|
||||
return out
|
||||
except Exception as e:
|
||||
log.warning("快捷问题预测失败(%s),回退默认", e)
|
||||
return DEFAULT_SUGGESTIONS[:n]
|
||||
+11
-1
@@ -164,13 +164,23 @@ def _match_games(text, game_refs):
|
||||
return cards
|
||||
|
||||
|
||||
def link_entities(text, game_refs=None):
|
||||
def link_entities(text, game_refs=None, mark_mode="first"):
|
||||
"""主入口:扫描回答文本。
|
||||
返回 (spans, cards)
|
||||
spans: 实体命中区间(前端高亮标记用),按 start 升序、互不重叠
|
||||
mark_mode="first" 时同一实体(type,id)只保留首次出现;"all" 时全部标记
|
||||
cards: 快速查看卡片数据(每类限量,避免刷屏)
|
||||
"""
|
||||
spans = _find_spans(text or "")
|
||||
if mark_mode == "first":
|
||||
seen, kept = set(), []
|
||||
for sp in spans: # spans 已按 start 升序 → 保留首次
|
||||
key = (sp["type"], sp["id"])
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
kept.append(sp)
|
||||
spans = kept
|
||||
cards = []
|
||||
seen_cards = set()
|
||||
for sp in spans:
|
||||
|
||||
@@ -46,6 +46,9 @@ body { background:var(--bg); color:var(--txt); font-family:"PingFang SC","Micros
|
||||
table { width:100%; border-collapse:collapse; }
|
||||
th, td { padding:9px 11px; text-align:left; font-size:13px; border-bottom:1px solid var(--line); white-space:nowrap; max-width:260px; overflow:hidden; text-overflow:ellipsis; }
|
||||
th { background:var(--bg2); color:var(--sub); font-weight:600; font-size:12px; position:sticky; top:0; }
|
||||
th.sortable { cursor:pointer; user-select:none; transition:.15s; }
|
||||
th.sortable:hover { color:var(--orange2); }
|
||||
th.sort-active { color:var(--orange2); }
|
||||
tr:hover td { background:rgba(249,115,22,.05); }
|
||||
td.num { text-align:center; }
|
||||
.row-ops { display:flex; gap:6px; }
|
||||
@@ -157,8 +160,17 @@ td.num { text-align:center; }
|
||||
<textarea id="cfg-suggestions" style="min-height:160px"></textarea>
|
||||
<div class="tip">💡 一行一个问题。保存后刷新前台页面即可看到新的快捷问题。</div>
|
||||
</div>
|
||||
<div class="row2">
|
||||
<div><label>对话中底部快捷问题预测个数(默认3,范围1-6)</label><input type="number" id="cfg-suggestion_count" min="1" max="6">
|
||||
<div class="tip">对话进行中,大模型根据上下文预测用户可能追问的问题数量(每个≤30字)</div></div>
|
||||
</div>
|
||||
<div class="row2">
|
||||
<div><label>管理员密码(留空则不修改)</label><input type="password" id="cfg-admin_password" placeholder="••••••"></div>
|
||||
<div><label>实体标记模式</label><select id="cfg-entity_mark_mode">
|
||||
<option value="first">只标记首次出现(推荐)</option>
|
||||
<option value="all">全部标记</option>
|
||||
</select>
|
||||
<div class="tip">对话回答中球队/球员/人物等特殊标记策略</div></div>
|
||||
</div>
|
||||
<div class="form-actions">
|
||||
<button class="btn" id="cfg-save">💾 保存配置</button>
|
||||
|
||||
+24
-5
@@ -4,7 +4,7 @@ const $$ = (s) => [...document.querySelectorAll(s)];
|
||||
const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
|
||||
|
||||
let TOKEN = localStorage.getItem("nba_admin_token") || "";
|
||||
let CUR = { table: "", page: 1, q: "" };
|
||||
let CUR = { table: "", page: 1, q: "", sort: "id", order: "desc" };
|
||||
let LOOKUPS = {}; // teams/players/leagues/sports → {id: name}
|
||||
|
||||
/* 字段中文名 */
|
||||
@@ -79,7 +79,7 @@ function switchPage(p) {
|
||||
$("#page-config").classList.toggle("hidden", p !== "config");
|
||||
if (p === "stats") loadStats();
|
||||
else if (p === "config") loadConfig();
|
||||
else { CUR = { table: p, page: 1, q: "" }; $("#tbl-search").value = ""; loadTable(); }
|
||||
else { CUR = { table: p, page: 1, q: "", sort: "id", order: "desc" }; $("#tbl-search").value = ""; loadTable(); }
|
||||
}
|
||||
|
||||
/* ================= 仪表盘 ================= */
|
||||
@@ -108,16 +108,20 @@ async function loadLookups() {
|
||||
|
||||
async function loadTable() {
|
||||
$("#table-title").textContent = TITLE_CN[CUR.table] || CUR.table;
|
||||
const d = await api(`/api/admin/${CUR.table}?page=${CUR.page}&size=20&q=${encodeURIComponent(CUR.q)}`);
|
||||
const d = await api(`/api/admin/${CUR.table}?page=${CUR.page}&size=20&q=${encodeURIComponent(CUR.q)}&sort=${encodeURIComponent(CUR.sort)}&order=${CUR.order}`);
|
||||
const cols = d.columns.filter((c) => c.name !== "created_at");
|
||||
const rows = d.rows;
|
||||
if (!Object.keys(LOOKUPS).length) await loadLookups().catch(() => {});
|
||||
const thead = `<tr>${cols.map((c) => `<th>${esc(FIELD_CN[CUR.table]?.[c.name] || c.name)}</th>`).join("")}<th>操作</th></tr>`;
|
||||
const thead = `<tr>${cols.map((c) => {
|
||||
const active = CUR.sort === c.name;
|
||||
const arrow = active ? (CUR.order === "asc" ? " ▲" : " ▼") : "";
|
||||
return `<th class="sortable ${active ? "sort-active" : ""}" data-sort="${c.name}" title="点击排序">${esc(FIELD_CN[CUR.table]?.[c.name] || c.name)}${arrow}</th>`;
|
||||
}).join("")}<th>操作</th></tr>`;
|
||||
const tbody = rows.map((r) => {
|
||||
const tds = cols.map((c) => {
|
||||
let v = r[c.name];
|
||||
if (v === null || v === undefined) v = "";
|
||||
if (c.name === "id") v = `<span class="badge">#${v}</span>`;
|
||||
if (c.name === "id") v = v; // ID 列纯数值显示
|
||||
else if (["team_id", "home_team_id", "away_team_id"].includes(c.name)) v = (LOOKUPS.teams || {})[v] || v;
|
||||
else if (c.name === "player_id") v = (LOOKUPS.players || {})[v] || v;
|
||||
else if (c.name === "league_id") v = (LOOKUPS.leagues || {})[v] || v;
|
||||
@@ -141,6 +145,17 @@ $("#tbl-search-btn").addEventListener("click", () => { CUR.q = $("#tbl-search").
|
||||
$("#tbl-search").addEventListener("keydown", (e) => { if (e.key === "Enter") $("#tbl-search-btn").click(); });
|
||||
$("#tbl-add").addEventListener("click", () => openEdit(CUR.table, null));
|
||||
|
||||
/* 表头点击排序:首次点击升序,再点切降序,循环 */
|
||||
$("#tbl-wrap").addEventListener("click", (e) => {
|
||||
const th = e.target.closest("th[data-sort]");
|
||||
if (!th) return;
|
||||
const f = th.dataset.sort;
|
||||
if (CUR.sort === f) CUR.order = CUR.order === "asc" ? "desc" : "asc";
|
||||
else { CUR.sort = f; CUR.order = "asc"; }
|
||||
CUR.page = 1;
|
||||
loadTable();
|
||||
});
|
||||
|
||||
/* ================= 编辑弹窗 ================= */
|
||||
let EDIT = { table: "", id: null };
|
||||
|
||||
@@ -207,6 +222,8 @@ async function loadConfig() {
|
||||
$("#cfg-welcome_hint").value = d.welcome_hint || "";
|
||||
$("#cfg-footer_text").value = d.footer_text || "";
|
||||
$("#cfg-admin_password").value = "";
|
||||
$("#cfg-entity_mark_mode").value = d.entity_mark_mode === "all" ? "all" : "first";
|
||||
$("#cfg-suggestion_count").value = d.suggestion_count || "3";
|
||||
try { $("#cfg-suggestions").value = JSON.parse(d.suggestions || "[]").join("\n"); }
|
||||
catch (e) { $("#cfg-suggestions").value = ""; }
|
||||
$("#cfg-msg").textContent = "";
|
||||
@@ -222,6 +239,8 @@ $("#cfg-save").addEventListener("click", async () => {
|
||||
};
|
||||
const pw = $("#cfg-admin_password").value;
|
||||
if (pw) payload.admin_password = pw;
|
||||
payload.entity_mark_mode = $("#cfg-entity_mark_mode").value;
|
||||
payload.suggestion_count = String(Math.min(6, Math.max(1, parseInt($("#cfg-suggestion_count").value || "3"))));
|
||||
try {
|
||||
await api("/api/admin/config", { method: "PUT", body: JSON.stringify(payload) });
|
||||
$("#cfg-msg").textContent = "✅ 保存成功,前台刷新后生效";
|
||||
|
||||
+247
-40
@@ -6,6 +6,36 @@ const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "
|
||||
const chatHistory = [];
|
||||
let chatBusy = false;
|
||||
|
||||
/* 简洁版当前时间 HH:MM */
|
||||
function nowTime() {
|
||||
const d = new Date();
|
||||
return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
/* 轻提示 */
|
||||
function toast(msg) {
|
||||
let t = document.getElementById("toast");
|
||||
if (!t) { t = document.createElement("div"); t.id = "toast"; document.body.appendChild(t); }
|
||||
t.textContent = msg;
|
||||
t.classList.add("show");
|
||||
clearTimeout(t._timer);
|
||||
t._timer = setTimeout(() => t.classList.remove("show"), 1800);
|
||||
}
|
||||
|
||||
/* 复制文本(Clipboard API + 降级) */
|
||||
async function copyText(text) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
} catch (e) {
|
||||
const ta = document.createElement("textarea");
|
||||
ta.value = text; ta.style.position = "fixed"; ta.style.opacity = "0";
|
||||
document.body.appendChild(ta); ta.select();
|
||||
document.execCommand("copy");
|
||||
ta.remove();
|
||||
}
|
||||
toast("✅ 已复制");
|
||||
}
|
||||
|
||||
/* ================= Markdown 渲染(marked 本地库,先转义防 XSS) ================= */
|
||||
function md(text) {
|
||||
if (window.marked) {
|
||||
@@ -50,8 +80,18 @@ $$(".tab").forEach((t) => t.addEventListener("click", () => {
|
||||
|
||||
function loadView(v) {
|
||||
if (v === "teams") loadTeams();
|
||||
else if (v === "players") loadPlayers("");
|
||||
else if (v === "games") loadGames("");
|
||||
else if (v === "players") {
|
||||
playersPage = 1; playersQ = ""; playersPos = "";
|
||||
$("#search-players").value = "";
|
||||
$$("#view-players .btn.small").forEach((x) => x.classList.toggle("active", x.dataset.pos === ""));
|
||||
loadPlayers();
|
||||
}
|
||||
else if (v === "games") {
|
||||
gamesPage = 1; gamesQ = ""; gamesStatus = "";
|
||||
$("#search-games").value = "";
|
||||
$$("#view-games .btn.small").forEach((x) => x.classList.toggle("active", x.dataset.status === ""));
|
||||
loadGames();
|
||||
}
|
||||
else if (v === "news") loadNews("");
|
||||
else if (v === "persons") loadPersons("");
|
||||
else if (v === "standings") {
|
||||
@@ -61,10 +101,14 @@ function loadView(v) {
|
||||
}
|
||||
|
||||
/* ================= 对话 ================= */
|
||||
function addMsg(role, html) {
|
||||
function addMsg(role, html, opts = {}) {
|
||||
const div = document.createElement("div");
|
||||
div.className = `msg ${role}`;
|
||||
div.innerHTML = `<div class="avatar">${role === "user" ? "🧑" : "🤖"}</div><div class="bubble">${html}</div>`;
|
||||
if (opts.idx !== undefined) div.dataset.idx = opts.idx;
|
||||
const actions = role === "bot"
|
||||
? `<div class="msg-actions"><button class="act-btn" title="复制回答">📋</button><button class="act-btn" title="重新生成">🔄</button><span class="msg-time">${nowTime()}</span></div>`
|
||||
: `<div class="msg-actions user-time"><span class="msg-time">${nowTime()}</span></div>`;
|
||||
div.innerHTML = `<div class="avatar">${role === "user" ? "🧑" : "🤖"}</div><div class="msg-body"><div class="bubble">${html}</div>${actions}</div>`;
|
||||
$("#chat-list").appendChild(div);
|
||||
$("#chat-list").scrollTop = $("#chat-list").scrollHeight;
|
||||
return div;
|
||||
@@ -72,7 +116,7 @@ function addMsg(role, html) {
|
||||
function showTyping() {
|
||||
const div = document.createElement("div");
|
||||
div.className = "msg bot";
|
||||
div.innerHTML = `<div class="avatar">🤖</div><div class="bubble"><span class="typing"><i></i><i></i><i></i></span></div>`;
|
||||
div.innerHTML = `<div class="avatar">🤖</div><div class="msg-body"><div class="bubble"><span class="typing"><i></i><i></i><i></i></span></div></div>`;
|
||||
$("#chat-list").appendChild(div);
|
||||
$("#chat-list").scrollTop = $("#chat-list").scrollHeight;
|
||||
return div;
|
||||
@@ -90,6 +134,28 @@ function cardHtml(c) {
|
||||
return "";
|
||||
}
|
||||
|
||||
/* 组装回答气泡 HTML(参考资讯 + markdown实体 + 卡片 + 来源) */
|
||||
function buildBotHtml(d) {
|
||||
let html = "";
|
||||
// 需求4:参考资讯(新闻/百科链接),默认折叠,位于回答块上方
|
||||
if (d.news_refs && d.news_refs.length) {
|
||||
html += `<details class="refs"><summary>📰 参考资讯(${d.news_refs.length})</summary><ul>` +
|
||||
d.news_refs.map((n) => `<li><a href="#" data-news="${n.id}">${esc(n.title)}</a>` +
|
||||
(n.source ? `<span class="ref-src">${esc(n.source)}${n.publish_time ? " · " + esc(n.publish_time.slice(0, 10)) : ""}</span>` : "") + `</li>`).join("") +
|
||||
`</ul></details>`;
|
||||
}
|
||||
// 需求3:markdown 渲染 + 需求5:实体特殊标记
|
||||
html += `<div class="md">${renderMdWithEntities(d.reply, d.entities)}</div>`;
|
||||
// 需求5:快速查看入口卡片
|
||||
if (d.cards && d.cards.length) {
|
||||
html += `<div class="entity-cards">${d.cards.map(cardHtml).join("")}</div>`;
|
||||
}
|
||||
if (d.sources && d.sources.length) {
|
||||
html += "<div class='src-line'>" + d.sources.map((s) => `<span class="src-tag">来源:${esc(s.tool)}</span>`).join("") + "</div>";
|
||||
}
|
||||
return html;
|
||||
}
|
||||
|
||||
async function sendChat(text) {
|
||||
if (chatBusy) return;
|
||||
chatBusy = true;
|
||||
@@ -102,26 +168,21 @@ async function sendChat(text) {
|
||||
const d = await r.json();
|
||||
typing.remove();
|
||||
if (d.error) { addMsg("bot", `⚠️ ${esc(d.error)}`); return; }
|
||||
let html = "";
|
||||
// 需求4:参考资讯(新闻/百科链接),默认折叠,位于回答块上方
|
||||
if (d.news_refs && d.news_refs.length) {
|
||||
html += `<details class="refs"><summary>📰 参考资讯(${d.news_refs.length})</summary><ul>` +
|
||||
d.news_refs.map((n) => `<li><a href="#" data-news="${n.id}">${esc(n.title)}</a>` +
|
||||
(n.source ? `<span class="ref-src">${esc(n.source)}${n.publish_time ? " · " + esc(n.publish_time.slice(0, 10)) : ""}</span>` : "") + `</li>`).join("") +
|
||||
`</ul></details>`;
|
||||
}
|
||||
// 需求3:markdown 渲染 + 需求5:实体特殊标记
|
||||
html += `<div class="md">${renderMdWithEntities(d.reply, d.entities)}</div>`;
|
||||
// 需求5:快速查看入口卡片
|
||||
if (d.cards && d.cards.length) {
|
||||
html += `<div class="entity-cards">${d.cards.map(cardHtml).join("")}</div>`;
|
||||
}
|
||||
if (d.sources && d.sources.length) {
|
||||
html += "<div class='src-line'>" + d.sources.map((s) => `<span class="src-tag">来源:${esc(s.tool)}</span>`).join("") + "</div>";
|
||||
}
|
||||
addMsg("bot", html);
|
||||
chatHistory.push({ user: text, assistant: d.reply });
|
||||
if (chatHistory.length > 20) chatHistory.splice(0, chatHistory.length - 20);
|
||||
const idx = chatHistory.length - 1;
|
||||
addMsg("bot", buildBotHtml(d), { idx });
|
||||
if (chatHistory.length > 20) {
|
||||
const removed = chatHistory.length - 20;
|
||||
chatHistory.splice(0, removed);
|
||||
document.querySelectorAll("#chat-list .msg[data-idx]").forEach((m) => {
|
||||
const i = parseInt(m.dataset.idx);
|
||||
if (i < removed) m.remove();
|
||||
else m.dataset.idx = i - removed;
|
||||
});
|
||||
}
|
||||
// 大模型预测下一轮快捷问题(异步刷新底部 chips)
|
||||
const mark = chatHistory.length;
|
||||
refreshChips(mark);
|
||||
} catch (e) {
|
||||
typing.remove();
|
||||
addMsg("bot", "⚠️ 网络异常,请稍后再试。");
|
||||
@@ -130,17 +191,124 @@ async function sendChat(text) {
|
||||
$("#send-btn").disabled = false;
|
||||
}
|
||||
}
|
||||
$("#send-btn").addEventListener("click", () => { const v = $("#chat-input").value.trim(); if (v) { $("#chat-input").value = ""; sendChat(v); } });
|
||||
$("#chat-input").addEventListener("keydown", (e) => { if (e.key === "Enter") $("#send-btn").click(); });
|
||||
$("#send-btn").addEventListener("click", () => { const v = $("#chat-input").value.trim(); if (v) { $("#chat-input").value = ""; autoResizeInput(); sendChat(v); } });
|
||||
|
||||
/* 输入框多行自适应:超一行自动增高,最多 4 行(约90px);Enter 发送,Shift+Enter 换行 */
|
||||
const chatInput = $("#chat-input");
|
||||
const INPUT_MAX_H = 90;
|
||||
function autoResizeInput() {
|
||||
chatInput.style.height = "auto";
|
||||
chatInput.style.height = Math.min(chatInput.scrollHeight, INPUT_MAX_H) + "px";
|
||||
}
|
||||
chatInput.addEventListener("input", autoResizeInput);
|
||||
chatInput.addEventListener("keydown", (e) => {
|
||||
if (e.key === "Enter" && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
$("#send-btn").click();
|
||||
}
|
||||
});
|
||||
|
||||
/* 复制当前回答(纯文本) */
|
||||
function copyMsg(btn) {
|
||||
const bubble = btn.closest(".msg").querySelector(".bubble");
|
||||
copyText(bubble.innerText.trim());
|
||||
}
|
||||
|
||||
/* 重新生成:以该轮之前的上下文重新提问,替换本条回答,截断后续对话 */
|
||||
async function regenerate(btn) {
|
||||
const msgEl = btn.closest(".msg");
|
||||
const idx = parseInt(msgEl.dataset.idx);
|
||||
if (isNaN(idx) || chatBusy) return;
|
||||
if (idx >= chatHistory.length) return;
|
||||
// 截断:删除该条之后的对话(上下文已变)
|
||||
chatHistory.splice(idx + 1);
|
||||
document.querySelectorAll("#chat-list .msg[data-idx]").forEach((m) => {
|
||||
if (parseInt(m.dataset.idx) > idx) m.remove();
|
||||
});
|
||||
const userText = chatHistory[idx].user;
|
||||
const body = msgEl.querySelector(".msg-body");
|
||||
const bubble = msgEl.querySelector(".bubble");
|
||||
bubble.innerHTML = `<span class="typing"><i></i><i></i><i></i></span>`;
|
||||
msgEl.querySelector(".msg-actions")?.remove();
|
||||
chatBusy = true;
|
||||
try {
|
||||
const r = await fetch("/api/chat", { method: "POST", headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ message: userText, history: chatHistory.slice(0, idx).map((h) => ({ user: h.user, assistant: h.assistant })) }) });
|
||||
const d = await r.json();
|
||||
if (d.error) { bubble.innerHTML = `⚠️ ${esc(d.error)}`; return; }
|
||||
bubble.innerHTML = buildBotHtml(d);
|
||||
const actions = document.createElement("div");
|
||||
actions.className = "msg-actions";
|
||||
actions.innerHTML = `<button class="act-btn" title="复制回答">📋</button><button class="act-btn" title="重新生成">🔄</button><span class="msg-time">${nowTime()}</span>`;
|
||||
body.appendChild(actions);
|
||||
chatHistory[idx] = { user: userText, assistant: d.reply };
|
||||
refreshChips(chatHistory.length);
|
||||
} catch (e) {
|
||||
bubble.innerHTML = "⚠️ 网络异常,请稍后再试。";
|
||||
} finally {
|
||||
chatBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
/* 分享:弹窗展示对话全文 + 一键复制 */
|
||||
function shareChat() {
|
||||
if (!chatHistory.length) { toast("还没有对话内容"); return; }
|
||||
const text = chatHistory.map((h) => `🧑 ${h.user}\n🤖 ${h.assistant}`).join("\n\n");
|
||||
openModal(`
|
||||
<h2>🔗 分享对话</h2>
|
||||
<div class="en">共 ${chatHistory.length} 轮 · 复制后粘贴到任意聊天或文档</div>
|
||||
<textarea readonly class="share-box" style="width:100%;height:280px;margin-top:10px;background:var(--bg);border:1px solid var(--line);border-radius:10px;padding:12px;color:var(--txt);font-size:13px;line-height:1.7;resize:vertical">${esc(text)}</textarea>
|
||||
<div style="margin-top:12px;text-align:right"><button class="btn" onclick="copyShare()">📋 复制全文</button></div>
|
||||
`);
|
||||
}
|
||||
function copyShare() {
|
||||
const ta = document.querySelector(".share-box");
|
||||
if (ta) copyText(ta.value);
|
||||
}
|
||||
|
||||
/* 清空对话从头开始 */
|
||||
function clearChat() {
|
||||
if (!chatHistory.length) { toast("对话已经是空的"); return; }
|
||||
if (!confirm("确定清空当前对话吗?将从头开始。")) return;
|
||||
chatHistory.length = 0;
|
||||
const list = $("#chat-list");
|
||||
const welcome = document.getElementById("welcome-msg");
|
||||
const w = welcome ? welcome.outerHTML : "";
|
||||
list.innerHTML = w;
|
||||
loadBoot();
|
||||
toast("🗑️ 对话已清空");
|
||||
}
|
||||
$("#share-btn").addEventListener("click", shareChat);
|
||||
$("#clear-btn").addEventListener("click", clearChat);
|
||||
|
||||
/* 快捷问题:点击 → 自动填入输入框并自动提交(需求2) */
|
||||
function askQuick(q) {
|
||||
$("#chat-input").value = q;
|
||||
autoResizeInput();
|
||||
sendChat(q);
|
||||
}
|
||||
|
||||
/* 聊天区事件委托:快捷语句 / 实体标记 / 新闻链接 / 卡片 */
|
||||
/* 底部快捷问题:对话进行中由大模型预测用户可能追问的问题(异步刷新) */
|
||||
async function refreshChips(mark) {
|
||||
try {
|
||||
const r = await fetch("/api/suggest", { method: "POST", headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ history: chatHistory.slice(-6) }) });
|
||||
const d = await r.json();
|
||||
if (!d.suggestions || !d.suggestions.length) return;
|
||||
if (mark !== chatHistory.length) return; // 期间用户又发了新消息 → 丢弃过期预测
|
||||
$("#chips").innerHTML = d.suggestions.map((q) => `<button>${esc(q)}</button>`).join("");
|
||||
$$("#chips button").forEach((b) => b.addEventListener("click", () => askQuick(b.textContent)));
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
/* 聊天区事件委托:快捷语句 / 操作按钮(复制·重新生成) / 实体标记 / 新闻链接 / 卡片 */
|
||||
$("#chat-list").addEventListener("click", (e) => {
|
||||
const act = e.target.closest(".act-btn");
|
||||
if (act) {
|
||||
if (act.title.includes("复制")) copyMsg(act);
|
||||
else if (act.title.includes("重新生成")) regenerate(act);
|
||||
return;
|
||||
}
|
||||
const q = e.target.closest(".quick-q");
|
||||
if (q) { e.preventDefault(); askQuick(q.textContent); return; }
|
||||
const ent = e.target.closest(".entity, .ecard");
|
||||
@@ -205,17 +373,55 @@ async function openTeam(id) {
|
||||
}
|
||||
|
||||
/* ================= 球员 ================= */
|
||||
async function loadPlayers(q) {
|
||||
const players = await getJSON(`/api/players?q=${encodeURIComponent(q)}&limit=60`);
|
||||
let playersPage = 1, playersQ = "", playersPos = "";
|
||||
const POS_CN = { PG: "控卫", SG: "分卫", SF: "小前", PF: "大前", C: "中锋" };
|
||||
|
||||
async function loadPlayers() {
|
||||
const d = await getJSON(`/api/players?q=${encodeURIComponent(playersQ)}&position=${playersPos}&page=${playersPage}&size=24`);
|
||||
const players = d.results || [];
|
||||
$("#grid-players").innerHTML = players.map((p) => `
|
||||
<div class="card" onclick="openPlayer(${p.id})">
|
||||
<h3>${esc(p.name)} <span class="en">${esc(p.position)} #${p.number}</span></h3>
|
||||
<h3>${esc(p.name)} <span class="en">${esc(POS_CN[p.position] || p.position)} #${p.number}</span></h3>
|
||||
<div class="en">${esc(p.team || "")} · ${esc(p.country)}</div>
|
||||
<div class="meta">本季:<span class="big-num">${p.season.pts}</span> 分 / ${p.season.reb} 板 / ${p.season.ast} 助</div>
|
||||
</div>`).join("");
|
||||
renderPager(d, "players");
|
||||
}
|
||||
$("#btn-players").addEventListener("click", () => loadPlayers($("#search-players").value.trim()));
|
||||
|
||||
/* 通用分页控件 */
|
||||
function renderPager(d, key) {
|
||||
const pages = Math.max(1, Math.ceil(d.total / d.size));
|
||||
const cur = d.page;
|
||||
const el = document.getElementById(`pager-${key}`);
|
||||
if (!el) return;
|
||||
const nums = [];
|
||||
for (let i = 1; i <= pages; i++) {
|
||||
if (pages > 9 && i !== 1 && i !== pages && Math.abs(i - cur) > 2) {
|
||||
if (nums[nums.length - 1] !== "…") nums.push("…");
|
||||
continue;
|
||||
}
|
||||
nums.push(i);
|
||||
}
|
||||
el.innerHTML = `
|
||||
<button ${cur <= 1 ? "disabled" : ""} onclick="goPage('${key}', ${cur - 1})">← 上一页</button>
|
||||
${nums.map((n) => n === "…" ? `<span>…</span>` : `<button class="${n === cur ? "active" : ""}" onclick="goPage('${key}', ${n})">${n}</button>`).join("")}
|
||||
<button ${cur >= pages ? "disabled" : ""} onclick="goPage('${key}', ${cur + 1})">下一页 →</button>
|
||||
<span>共 ${d.total} 条</span>`;
|
||||
}
|
||||
function goPage(key, p) {
|
||||
if (key === "players") { playersPage = p; loadPlayers(); }
|
||||
else if (key === "games") { gamesPage = p; loadGames(); }
|
||||
}
|
||||
|
||||
$("#btn-players").addEventListener("click", () => { playersQ = $("#search-players").value.trim(); playersPage = 1; loadPlayers(); });
|
||||
$("#search-players").addEventListener("keydown", (e) => { if (e.key === "Enter") $("#btn-players").click(); });
|
||||
$$("#view-players .btn.small").forEach((b) => b.addEventListener("click", () => {
|
||||
$$("#view-players .btn.small").forEach((x) => x.classList.remove("active"));
|
||||
b.classList.add("active");
|
||||
playersPos = b.dataset.pos;
|
||||
playersPage = 1;
|
||||
loadPlayers();
|
||||
}));
|
||||
async function openPlayer(id) {
|
||||
const p = await getJSON(`/api/players/${id}`);
|
||||
openModal(`
|
||||
@@ -238,12 +444,11 @@ async function openPlayer(id) {
|
||||
}
|
||||
|
||||
/* ================= 比赛 ================= */
|
||||
let gameStatusFilter = "";
|
||||
async function loadGames(q) {
|
||||
const url = `/api/games?q=${encodeURIComponent(q)}&limit=40`;
|
||||
const games = await getJSON(url);
|
||||
const list = games.filter((g) => !gameStatusFilter || g.status === gameStatusFilter);
|
||||
$("#list-games").innerHTML = list.map((g) => {
|
||||
let gamesPage = 1, gamesQ = "", gamesStatus = "";
|
||||
async function loadGames() {
|
||||
const d = await getJSON(`/api/games?q=${encodeURIComponent(gamesQ)}&status=${gamesStatus}&page=${gamesPage}&size=12`);
|
||||
const games = d.results || [];
|
||||
$("#list-games").innerHTML = games.map((g) => {
|
||||
const finished = g.status === "finished";
|
||||
const score = finished ? `<span class="score-big">${g.away_score}</span> : <span class="score-big">${g.home_score}</span>` : "VS";
|
||||
return `<div class="list-item" onclick="openGame(${g.id})">
|
||||
@@ -259,14 +464,16 @@ async function loadGames(q) {
|
||||
<div class="meta">🕐 ${esc(g.game_time)} · ${esc(g.venue)} · ${esc(g.broadcast)}</div>
|
||||
</div>`;
|
||||
}).join("") || '<div class="meta">没有符合条件的比赛</div>';
|
||||
renderPager(d, "games");
|
||||
}
|
||||
$$("#view-games .btn.small").forEach((b) => b.addEventListener("click", () => {
|
||||
$$("#view-games .btn.small").forEach((x) => x.classList.remove("active"));
|
||||
b.classList.add("active");
|
||||
gameStatusFilter = b.dataset.status;
|
||||
loadGames($("#search-games").value.trim());
|
||||
gamesStatus = b.dataset.status;
|
||||
gamesPage = 1;
|
||||
loadGames();
|
||||
}));
|
||||
$("#btn-games").addEventListener("click", () => loadGames($("#search-games").value.trim()));
|
||||
$("#btn-games").addEventListener("click", () => { gamesQ = $("#search-games").value.trim(); gamesPage = 1; loadGames(); });
|
||||
$("#search-games").addEventListener("keydown", (e) => { if (e.key === "Enter") $("#btn-games").click(); });
|
||||
async function openGame(id) {
|
||||
const g = await getJSON(`/api/games/${id}`);
|
||||
|
||||
+20
-4
@@ -25,13 +25,19 @@
|
||||
<button class="tab" data-view="persons">👥 人物</button>
|
||||
<button class="tab" data-view="standings">🏆 排名</button>
|
||||
</nav>
|
||||
<a class="admin-link" href="/admin" title="管理后台">⚙️</a>
|
||||
</header>
|
||||
|
||||
<main>
|
||||
<!-- ================= 对话 ================= -->
|
||||
<section id="view-chat" class="view active">
|
||||
<div class="chat-wrap">
|
||||
<div class="chat-toolbar">
|
||||
<span class="ct-title">💬 对话</span>
|
||||
<div>
|
||||
<button class="tool-btn" id="share-btn" title="分享对话">🔗 分享</button>
|
||||
<button class="tool-btn" id="clear-btn" title="清空对话从头开始">🗑️ 清空</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="chat-list" class="chat-list">
|
||||
<div class="msg bot" id="welcome-msg">
|
||||
<div class="avatar">🤖</div>
|
||||
@@ -43,7 +49,7 @@
|
||||
</div>
|
||||
<div class="chips" id="chips"></div>
|
||||
<div class="input-bar">
|
||||
<input id="chat-input" type="text" placeholder="输入问题,如:湖人最近比赛怎么样?" autocomplete="off">
|
||||
<textarea id="chat-input" rows="1" placeholder="输入问题,如:湖人最近比赛怎么样?(Enter 发送,Shift+Enter 换行)" autocomplete="off"></textarea>
|
||||
<button id="send-btn">发送</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -52,8 +58,17 @@
|
||||
<!-- ================= 数据浏览 ================= -->
|
||||
<section id="view-teams" class="view"><div class="grid" id="grid-teams"></div></section>
|
||||
<section id="view-players" class="view">
|
||||
<div class="toolbar"><input class="search" id="search-players" placeholder="搜索球员(中文/英文/球队)"><button class="btn" id="btn-players">搜索</button></div>
|
||||
<div class="toolbar">
|
||||
<button class="btn small active" data-pos="">全部</button>
|
||||
<button class="btn small" data-pos="PG">控卫</button>
|
||||
<button class="btn small" data-pos="SG">分卫</button>
|
||||
<button class="btn small" data-pos="SF">小前</button>
|
||||
<button class="btn small" data-pos="PF">大前</button>
|
||||
<button class="btn small" data-pos="C">中锋</button>
|
||||
<input class="search" id="search-players" placeholder="搜索球员(中文/英文/球队)"><button class="btn" id="btn-players">搜索</button>
|
||||
</div>
|
||||
<div class="grid" id="grid-players"></div>
|
||||
<div class="pager" id="pager-players"></div>
|
||||
</section>
|
||||
<section id="view-games" class="view">
|
||||
<div class="toolbar">
|
||||
@@ -63,7 +78,8 @@
|
||||
<input class="search" id="search-games" placeholder="搜索:如 湖人 最近">
|
||||
<button class="btn" id="btn-games">搜索</button>
|
||||
</div>
|
||||
<div class="list" id="list-games"></div>
|
||||
<div class="grid games-grid" id="list-games"></div>
|
||||
<div class="pager" id="pager-games"></div>
|
||||
</section>
|
||||
<section id="view-news" class="view">
|
||||
<div class="toolbar"><input class="search" id="search-news" placeholder="搜索新闻关键词"><button class="btn" id="btn-news">搜索</button></div>
|
||||
|
||||
+42
-16
@@ -25,37 +25,49 @@ main { flex: 1; width: 100%; max-width: 1200px; margin: 0 auto; padding: 20px 16
|
||||
|
||||
/* ---------- 对话 ---------- */
|
||||
.chat-wrap { display: flex; flex-direction: column; height: calc(100vh - 190px); min-height: 480px; }
|
||||
.chat-toolbar { display: flex; align-items: center; justify-content: space-between; margin-bottom: 6px; padding: 0 4px; }
|
||||
.ct-title { color: var(--sub); font-size: 13px; font-weight: 600; letter-spacing: 1px; }
|
||||
.tool-btn { background: var(--bg2); border: 1px solid var(--line); color: var(--sub); border-radius: 999px; padding: 5px 12px; font-size: 12.5px; cursor: pointer; margin-left: 6px; transition: .15s; }
|
||||
.tool-btn:hover { color: var(--orange2); border-color: var(--orange2); }
|
||||
.msg-body { flex: 1; min-width: 0; }
|
||||
.msg-actions { display: flex; align-items: center; gap: 2px; margin-top: 5px; padding-left: 4px; opacity: .8; }
|
||||
.msg.user .msg-actions { justify-content: flex-end; padding-left: 0; padding-right: 4px; }
|
||||
.act-btn { background: transparent; border: none; color: var(--sub); font-size: 13px; cursor: pointer; padding: 3px 6px; border-radius: 6px; line-height: 1; transition: .15s; }
|
||||
.act-btn:hover { color: var(--orange2); background: rgba(249,115,22,.12); }
|
||||
.msg-time { font-size: 11px; color: var(--sub); margin-left: 6px; }
|
||||
#toast { position: fixed; left: 50%; bottom: 100px; transform: translateX(-50%) translateY(12px); background: var(--bg2); border: 1px solid var(--line); color: var(--txt); padding: 9px 20px; border-radius: 999px; font-size: 13px; opacity: 0; pointer-events: none; transition: .25s; z-index: 300; box-shadow: 0 6px 24px rgba(0,0,0,.5); }
|
||||
#toast.show { opacity: 1; transform: translateX(-50%) translateY(0); }
|
||||
.chat-list { flex: 1; overflow-y: auto; padding: 8px 4px 16px; display: flex; flex-direction: column; gap: 14px; scroll-behavior: smooth; }
|
||||
.msg { display: flex; gap: 10px; max-width: 88%; }
|
||||
.msg.user { align-self: flex-end; flex-direction: row-reverse; }
|
||||
.avatar { width: 38px; height: 38px; border-radius: 50%; background: var(--card); border: 1px solid var(--line); display: flex; align-items: center; justify-content: center; font-size: 19px; flex-shrink: 0; }
|
||||
.msg.user .avatar { background: linear-gradient(135deg, #f97316, #ea580c); border: none; }
|
||||
.bubble { background: var(--card); border: 1px solid var(--line); border-radius: 14px; padding: 12px 16px; font-size: 14.5px; line-height: 1.75; white-space: pre-wrap; word-break: break-word; }
|
||||
.msg.user .bubble { background: #2a1c10; border-color: #7c3a1e; }
|
||||
.bubble { background: var(--card); border: 1px solid var(--line); border-radius: 14px; padding: 12px 16px; font-size: 14.5px; line-height: 1.55; white-space: normal; word-break: break-word; }
|
||||
.msg.user .bubble { background: #2a1c10; border-color: #7c3a1e; white-space: pre-wrap; }
|
||||
.bubble b { color: var(--orange2); }
|
||||
.bubble em { color: var(--blue); font-style: normal; }
|
||||
.bubble .hint { color: var(--sub); font-size: 13px; margin-top: 6px; }
|
||||
.bubble .quick-q { color: var(--blue); cursor: pointer; text-decoration: none; border-bottom: 1px dashed var(--blue); }
|
||||
.bubble .quick-q:hover { color: var(--orange2); border-bottom-color: var(--orange2); }
|
||||
.bubble ul { margin: 6px 0 6px 18px; }
|
||||
.bubble li { margin: 3px 0; }
|
||||
.bubble ul { margin: 4px 0 4px 18px; }
|
||||
.bubble li { margin: 2px 0; }
|
||||
|
||||
/* ---------- Markdown 渲染(需求3) ---------- */
|
||||
.md { line-height: 1.8; }
|
||||
.md h1, .md h2, .md h3, .md h4 { margin: 12px 0 6px; line-height: 1.4; }
|
||||
.md h1 { font-size: 17px; } .md h2 { font-size: 16px; } .md h3, .md h4 { font-size: 15px; }
|
||||
.md { line-height: 1.6; }
|
||||
.md h1, .md h2, .md h3, .md h4 { margin: 10px 0 4px; line-height: 1.35; }
|
||||
.md h1 { font-size: 16.5px; } .md h2 { font-size: 15.5px; } .md h3, .md h4 { font-size: 14.5px; }
|
||||
.md h1::before, .md h2::before { content: ""; }
|
||||
.md p { margin: 6px 0; }
|
||||
.md ul, .md ol { margin: 6px 0 6px 20px; }
|
||||
.md li { margin: 3px 0; }
|
||||
.md p { margin: 4px 0; }
|
||||
.md ul, .md ol { margin: 4px 0 4px 20px; }
|
||||
.md li { margin: 2px 0; }
|
||||
.md code { background: #0d1117; border: 1px solid var(--line); border-radius: 5px; padding: 1px 6px; font-size: 12.5px; font-family: Consolas, monospace; color: var(--green); }
|
||||
.md pre { background: #0d1117; border: 1px solid var(--line); border-radius: 10px; padding: 12px; overflow-x: auto; margin: 8px 0; }
|
||||
.md pre { background: #0d1117; border: 1px solid var(--line); border-radius: 10px; padding: 10px; overflow-x: auto; margin: 6px 0; }
|
||||
.md pre code { background: transparent; border: none; padding: 0; color: var(--txt); }
|
||||
.md blockquote { border-left: 3px solid var(--orange2); padding: 2px 12px; margin: 8px 0; color: var(--sub); background: rgba(249,115,22,.06); border-radius: 0 8px 8px 0; }
|
||||
.md table { display: block; width: 100%; overflow-x: auto; margin: 10px 0; }
|
||||
.md table th, .md table td { padding: 7px 10px; font-size: 12.5px; }
|
||||
.md blockquote { border-left: 3px solid var(--orange2); padding: 2px 12px; margin: 6px 0; color: var(--sub); background: rgba(249,115,22,.06); border-radius: 0 8px 8px 0; }
|
||||
.md table { display: block; width: 100%; overflow-x: auto; margin: 8px 0; }
|
||||
.md table th, .md table td { padding: 6px 9px; font-size: 12.5px; }
|
||||
.md table th { background: var(--bg2); color: var(--orange2); }
|
||||
.md hr { border: none; border-top: 1px solid var(--line); margin: 10px 0; }
|
||||
.md hr { border: none; border-top: 1px solid var(--line); margin: 8px 0; }
|
||||
.md a { color: var(--blue); text-decoration: none; }
|
||||
.md a:hover { text-decoration: underline; }
|
||||
|
||||
@@ -97,7 +109,9 @@ main { flex: 1; width: 100%; max-width: 1200px; margin: 0 auto; padding: 20px 16
|
||||
.chips button:hover { border-color: var(--orange2); color: var(--orange2); }
|
||||
|
||||
.input-bar { display: flex; gap: 10px; background: var(--bg2); border: 1px solid var(--line); border-radius: 999px; padding: 8px 10px 8px 18px; }
|
||||
#chat-input { flex: 1; background: transparent; border: none; outline: none; color: var(--txt); font-size: 15px; }
|
||||
#chat-input { flex: 1; background: transparent; border: none; outline: none; color: var(--txt); font-size: 15px; line-height: 1.5; resize: none; overflow-y: auto; max-height: 90px; padding: 5px 0; font-family: inherit; }
|
||||
#chat-input::-webkit-scrollbar { width: 5px; }
|
||||
#chat-input::-webkit-scrollbar-thumb { background: var(--line); border-radius: 3px; }
|
||||
#send-btn { background: linear-gradient(135deg, #f97316, #ea580c); border: none; color: #fff; padding: 10px 24px; border-radius: 999px; cursor: pointer; font-size: 14px; font-weight: 600; }
|
||||
#send-btn:disabled { opacity: .5; cursor: wait; }
|
||||
|
||||
@@ -110,6 +124,18 @@ main { flex: 1; width: 100%; max-width: 1200px; margin: 0 auto; padding: 20px 16
|
||||
.btn.small.active { color: var(--orange2); border-color: var(--orange2); background: rgba(249,115,22,.08); }
|
||||
|
||||
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(230px, 1fr)); gap: 14px; }
|
||||
|
||||
/* ---------- 分页控件 ---------- */
|
||||
.pager { display: flex; align-items: center; justify-content: center; gap: 6px; margin-top: 18px; color: var(--sub); font-size: 12.5px; flex-wrap: wrap; }
|
||||
.pager button { background: var(--bg2); border: 1px solid var(--line); color: var(--txt); border-radius: 999px; padding: 6px 14px; cursor: pointer; font-size: 12.5px; transition: .15s; }
|
||||
.pager button:hover:not(:disabled) { border-color: var(--orange2); color: var(--orange2); }
|
||||
.pager button.active { background: linear-gradient(135deg, #f97316, #ea580c); color: #fff; border-color: transparent; }
|
||||
.pager button:disabled { opacity: .35; cursor: default; }
|
||||
.pager span { margin: 0 4px; }
|
||||
|
||||
/* ---------- 比赛网格卡片(固定宽度,宽度足够一行多个) ---------- */
|
||||
.games-grid { grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); align-items: stretch; }
|
||||
.games-grid .list-item { display: flex; flex-direction: column; justify-content: space-between; gap: 8px; height: 100%; padding: 14px 16px; }
|
||||
.card { background: var(--card); border: 1px solid var(--line); border-radius: var(--radius); padding: 14px 16px; cursor: pointer; transition: .18s; }
|
||||
.card:hover { transform: translateY(-3px); border-color: var(--orange2); box-shadow: 0 6px 20px rgba(0,0,0,.35); }
|
||||
.card h3 { font-size: 15.5px; margin-bottom: 4px; }
|
||||
|
||||
@@ -157,6 +157,26 @@ def get_player(player_id):
|
||||
return _fmt_player(p) if p else None
|
||||
|
||||
|
||||
# ================================================================== 球员列表(前台分页版)
|
||||
def list_players(q="", position="", page=1, size=24):
|
||||
"""前台球员列表:关键词 + 位置筛选 + 分页(区别于 search_players 工具版)"""
|
||||
q = expand_aliases((q or "").strip())
|
||||
conds, args = [], []
|
||||
if q:
|
||||
like = f"%{fuzzy(q)}%"
|
||||
conds.append("(p.name LIKE ? ESCAPE '\\' OR p.name_en LIKE ? ESCAPE '\\' OR t.name LIKE ? ESCAPE '\\')")
|
||||
args += [like, like, like]
|
||||
if position:
|
||||
conds.append("p.position=?")
|
||||
args.append(position)
|
||||
where = ("WHERE " + " AND ".join(conds)) if conds else ""
|
||||
total = query_one(f"SELECT COUNT(*) AS c FROM players p LEFT JOIN teams t ON p.team_id=t.id {where}", args)["c"]
|
||||
rows = query(f"""SELECT p.*, t.name AS team_name FROM players p LEFT JOIN teams t ON p.team_id=t.id
|
||||
{where} ORDER BY p.season_pts DESC LIMIT ? OFFSET ?""",
|
||||
args + [size, (page - 1) * size])
|
||||
return {"results": [_fmt_player(r) for r in rows], "total": total, "page": page, "size": size}
|
||||
|
||||
|
||||
# ================================================================== 比赛
|
||||
_TEAM_PAT = None
|
||||
|
||||
@@ -259,6 +279,18 @@ def get_game_detail(game_id):
|
||||
return detail
|
||||
|
||||
|
||||
# ================================================================== 比赛列表(前台分页版)
|
||||
def list_games(q="", status="", page=1, size=12):
|
||||
"""前台比赛列表:关键词 + 状态筛选 + 分页(数据量小,全量匹配后切片)"""
|
||||
r = search_games(q, limit=500)
|
||||
results = r.get("results", [])
|
||||
if status:
|
||||
results = [g for g in results if g["status"] == status]
|
||||
total = len(results)
|
||||
start = (page - 1) * size
|
||||
return {"results": results[start:start + size], "total": total, "page": page, "size": size}
|
||||
|
||||
|
||||
# ================================================================== 排名
|
||||
def search_standings(query_text, limit=20, season=None):
|
||||
q = (query_text or "").strip()
|
||||
|
||||
Reference in New Issue
Block a user