332 lines
12 KiB
JavaScript
332 lines
12 KiB
JavaScript
// DEMO-010 stays API First: this client owns presentation state only and sends
|
||
// every document/search operation through the versioned public REST contract.
|
||
const API_BASE = "/api/v1";
|
||
|
||
const statusLabels = {
|
||
uploaded: "Uploaded",
|
||
processing: "Processing",
|
||
ready: "Ready",
|
||
failed: "Failed",
|
||
};
|
||
|
||
const pageTitles = {
|
||
upload: "上传文档",
|
||
documents: "文档列表",
|
||
search: "Search Lab",
|
||
};
|
||
|
||
function currentPage() {
|
||
const route = window.location.pathname.split("/").filter(Boolean).at(-1);
|
||
return Object.hasOwn(pageTitles, route) ? route : "upload";
|
||
}
|
||
|
||
function showPage(page) {
|
||
document.querySelectorAll("[data-page]").forEach((section) => {
|
||
section.hidden = section.dataset.page !== page;
|
||
});
|
||
document.querySelectorAll("[data-nav]").forEach((link) => {
|
||
const active = link.dataset.nav === page;
|
||
link.classList.toggle("active", active);
|
||
if (active) link.setAttribute("aria-current", "page");
|
||
else link.removeAttribute("aria-current");
|
||
});
|
||
document.querySelector("#page-title").textContent = pageTitles[page];
|
||
}
|
||
|
||
function showNotice(message, kind = "success") {
|
||
const notice = document.querySelector("#notice");
|
||
notice.textContent = message;
|
||
notice.className = `notice ${kind}`;
|
||
notice.hidden = false;
|
||
window.clearTimeout(showNotice.timeout);
|
||
showNotice.timeout = window.setTimeout(() => {
|
||
notice.hidden = true;
|
||
}, 6000);
|
||
}
|
||
|
||
async function requestJson(path, options = {}) {
|
||
const response = await fetch(`${API_BASE}${path}`, options);
|
||
if (!response.ok) {
|
||
let message = `请求失败(HTTP ${response.status})`;
|
||
try {
|
||
const body = await response.json();
|
||
if (body.detail) message = body.detail;
|
||
} catch {
|
||
// A non-JSON upstream error is represented by the stable HTTP message above.
|
||
}
|
||
throw new Error(message);
|
||
}
|
||
return response.status === 204 ? null : response.json();
|
||
}
|
||
|
||
function formatDate(value) {
|
||
if (!value) return "—";
|
||
return new Intl.DateTimeFormat("zh-CN", {
|
||
dateStyle: "medium",
|
||
timeStyle: "short",
|
||
}).format(new Date(value));
|
||
}
|
||
|
||
function formatSize(bytes) {
|
||
if (bytes < 1024) return `${bytes} B`;
|
||
if (bytes < 1024 ** 2) return `${(bytes / 1024).toFixed(1)} KB`;
|
||
return `${(bytes / 1024 ** 2).toFixed(1)} MB`;
|
||
}
|
||
|
||
function statusPill(status) {
|
||
const pill = document.createElement("span");
|
||
pill.className = `status-pill status-${status}`;
|
||
pill.textContent = statusLabels[status] ?? status;
|
||
return pill;
|
||
}
|
||
|
||
function setButtonBusy(button, busy, busyText) {
|
||
if (!button.dataset.label) button.dataset.label = button.textContent;
|
||
button.disabled = busy;
|
||
button.textContent = busy ? busyText : button.dataset.label;
|
||
}
|
||
|
||
function initializeUpload() {
|
||
const form = document.querySelector("#upload-form");
|
||
const input = document.querySelector("#file-input");
|
||
const selected = document.querySelector("#selected-file");
|
||
const button = document.querySelector("#upload-button");
|
||
|
||
const updateFilename = () => {
|
||
selected.textContent = input.files[0]?.name ?? "尚未选择文件";
|
||
};
|
||
input.addEventListener("change", updateFilename);
|
||
|
||
form.addEventListener("submit", async (event) => {
|
||
event.preventDefault();
|
||
if (!input.files.length) return;
|
||
setButtonBusy(button, true, "处理中…");
|
||
try {
|
||
const formData = new FormData();
|
||
formData.append("file", input.files[0]);
|
||
const documentData = await requestJson("/documents", {
|
||
method: "POST",
|
||
body: formData,
|
||
});
|
||
renderUploadResult(documentData);
|
||
showNotice("文档已上传并完成处理。可以前往 Search Lab 检索。", "success");
|
||
form.reset();
|
||
updateFilename();
|
||
} catch (error) {
|
||
showNotice(`上传失败:${error.message}`, "error");
|
||
} finally {
|
||
setButtonBusy(button, false, "");
|
||
}
|
||
});
|
||
}
|
||
|
||
function renderUploadResult(documentData) {
|
||
const card = document.querySelector("#upload-result");
|
||
document.querySelector("#upload-filename").textContent = documentData.filename;
|
||
document.querySelector("#upload-type").textContent = documentData.media_type;
|
||
document.querySelector("#upload-size").textContent = formatSize(documentData.size_bytes);
|
||
document.querySelector("#upload-time").textContent = formatDate(documentData.created_at);
|
||
document.querySelector("#upload-status").replaceWith(statusPill(documentData.status));
|
||
const status = card.querySelector(".status-pill");
|
||
status.id = "upload-status";
|
||
card.hidden = false;
|
||
}
|
||
|
||
async function loadDocuments() {
|
||
const refresh = document.querySelector("#refresh-documents");
|
||
setButtonBusy(refresh, true, "加载中…");
|
||
try {
|
||
const documents = await requestJson("/documents");
|
||
renderDocuments(documents);
|
||
} catch (error) {
|
||
showNotice(`文档列表加载失败:${error.message}`, "error");
|
||
} finally {
|
||
setButtonBusy(refresh, false, "");
|
||
}
|
||
}
|
||
|
||
function renderDocuments(documents) {
|
||
const rows = document.querySelector("#document-rows");
|
||
const empty = document.querySelector("#document-empty");
|
||
rows.replaceChildren();
|
||
empty.hidden = documents.length !== 0;
|
||
document.querySelector("#document-count").textContent = `${documents.length} 个文档`;
|
||
document.querySelector("#document-refresh-time").textContent =
|
||
`更新于 ${new Intl.DateTimeFormat("zh-CN", { timeStyle: "short" }).format(new Date())}`;
|
||
|
||
documents.forEach((documentData) => {
|
||
const row = document.createElement("tr");
|
||
row.append(
|
||
tableCell(documentData.filename, "filename-cell"),
|
||
tableCell(documentData.media_type),
|
||
tableCell(formatDate(documentData.created_at)),
|
||
);
|
||
const statusCell = document.createElement("td");
|
||
statusCell.append(statusPill(documentData.status));
|
||
row.append(statusCell);
|
||
|
||
const actions = document.createElement("td");
|
||
actions.className = "row-actions";
|
||
const view = actionButton("查看", () => showDocumentDetail(documentData));
|
||
const remove = actionButton("删除", () => deleteDocument(documentData), "danger-link");
|
||
actions.append(view, remove);
|
||
row.append(actions);
|
||
rows.append(row);
|
||
});
|
||
}
|
||
|
||
function tableCell(value, className = "") {
|
||
const cell = document.createElement("td");
|
||
cell.textContent = value;
|
||
cell.className = className;
|
||
return cell;
|
||
}
|
||
|
||
function actionButton(label, handler, className = "") {
|
||
const button = document.createElement("button");
|
||
button.type = "button";
|
||
button.className = `table-action ${className}`;
|
||
button.textContent = label;
|
||
button.addEventListener("click", handler);
|
||
return button;
|
||
}
|
||
|
||
function showDocumentDetail(documentData) {
|
||
const dialog = document.querySelector("#document-dialog");
|
||
document.querySelector("#dialog-filename").textContent = documentData.filename;
|
||
const metadata = document.querySelector("#dialog-metadata");
|
||
metadata.replaceChildren();
|
||
[
|
||
["文档 ID", documentData.id],
|
||
["文件类型", documentData.media_type],
|
||
["文件大小", formatSize(documentData.size_bytes)],
|
||
["当前状态", statusLabels[documentData.status] ?? documentData.status],
|
||
["上传时间", formatDate(documentData.created_at)],
|
||
["更新时间", formatDate(documentData.updated_at)],
|
||
["错误信息", documentData.error_message ?? "无"],
|
||
].forEach(([term, value]) => {
|
||
const wrapper = document.createElement("div");
|
||
const dt = document.createElement("dt");
|
||
const dd = document.createElement("dd");
|
||
dt.textContent = term;
|
||
dd.textContent = value;
|
||
wrapper.append(dt, dd);
|
||
metadata.append(wrapper);
|
||
});
|
||
dialog.showModal();
|
||
}
|
||
|
||
async function deleteDocument(documentData) {
|
||
if (!window.confirm(`确认删除“${documentData.filename}”及其索引数据?`)) return;
|
||
try {
|
||
await requestJson(`/documents/${documentData.id}`, { method: "DELETE" });
|
||
showNotice(`已删除 ${documentData.filename}`, "success");
|
||
await loadDocuments();
|
||
} catch (error) {
|
||
showNotice(`删除失败:${error.message}`, "error");
|
||
}
|
||
}
|
||
|
||
function initializeSearch() {
|
||
const form = document.querySelector("#search-form");
|
||
const button = document.querySelector("#search-button");
|
||
form.addEventListener("submit", async (event) => {
|
||
event.preventDefault();
|
||
const query = document.querySelector("#search-query").value.trim();
|
||
const topK = Number(document.querySelector("#search-top-k").value);
|
||
if (!query) return;
|
||
setButtonBusy(button, true, "检索中…");
|
||
try {
|
||
const startedAt = performance.now();
|
||
const response = await requestJson("/search", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ query, top_k: topK }),
|
||
});
|
||
renderSearchResults(response.results, performance.now() - startedAt);
|
||
} catch (error) {
|
||
showNotice(`检索失败:${error.message}`, "error");
|
||
} finally {
|
||
setButtonBusy(button, false, "");
|
||
}
|
||
});
|
||
}
|
||
|
||
function renderSearchResults(results, elapsedMs) {
|
||
const container = document.querySelector("#search-results");
|
||
container.replaceChildren();
|
||
document.querySelector("#search-summary").textContent =
|
||
`${results.length} 条结果 · ${(elapsedMs / 1000).toFixed(2)} 秒`;
|
||
if (!results.length) {
|
||
const empty = document.createElement("div");
|
||
empty.className = "empty-state search-empty";
|
||
const strong = document.createElement("strong");
|
||
strong.textContent = "没有找到匹配内容";
|
||
const detail = document.createElement("span");
|
||
detail.textContent = "可以换一种问法,或先确认文档状态为 Ready。";
|
||
empty.append(strong, detail);
|
||
container.append(empty);
|
||
return;
|
||
}
|
||
|
||
results.forEach((result, index) => {
|
||
const card = document.createElement("article");
|
||
card.className = "search-result-card";
|
||
const rank = document.createElement("span");
|
||
rank.className = "rank";
|
||
rank.textContent = String(index + 1).padStart(2, "0");
|
||
const body = document.createElement("div");
|
||
body.className = "result-body";
|
||
const heading = document.createElement("div");
|
||
heading.className = "result-title-row";
|
||
const title = document.createElement("h4");
|
||
title.textContent = result.filename;
|
||
const sourceMeta = document.createElement("div");
|
||
sourceMeta.className = "source-meta";
|
||
sourceMeta.append(
|
||
metadataItem("Page", result.page == null ? "—" : String(result.page)),
|
||
metadataItem("Section", result.section ?? "—"),
|
||
);
|
||
heading.append(title, sourceMeta);
|
||
const content = document.createElement("p");
|
||
content.className = "chunk-content";
|
||
content.textContent = result.content;
|
||
const scores = document.createElement("div");
|
||
scores.className = "score-row";
|
||
scores.append(
|
||
scoreItem("Dense Score", result.score),
|
||
scoreItem("Rerank Score", result.rerank_score),
|
||
);
|
||
body.append(heading, content, scores);
|
||
card.append(rank, body);
|
||
container.append(card);
|
||
});
|
||
}
|
||
|
||
function scoreItem(label, value) {
|
||
const item = document.createElement("span");
|
||
const labelNode = document.createElement("small");
|
||
const valueNode = document.createElement("strong");
|
||
labelNode.textContent = label;
|
||
valueNode.textContent = Number(value).toFixed(4);
|
||
item.append(labelNode, valueNode);
|
||
return item;
|
||
}
|
||
|
||
function metadataItem(label, value) {
|
||
const item = document.createElement("span");
|
||
const labelNode = document.createElement("small");
|
||
const valueNode = document.createElement("strong");
|
||
labelNode.textContent = label;
|
||
valueNode.textContent = value;
|
||
item.append(labelNode, valueNode);
|
||
return item;
|
||
}
|
||
|
||
const page = currentPage();
|
||
showPage(page);
|
||
initializeUpload();
|
||
initializeSearch();
|
||
document.querySelector("#refresh-documents").addEventListener("click", loadDocuments);
|
||
if (page === "documents") loadDocuments();
|