feat(web): use history routing and preserve scroll on filter changes

This commit is contained in:
kairee committed 2026-11-01 01:55:37 +08:00
1 parent 1b08854b25
commit 52a8d90c47
9 files changed
+113 -33

No files matched your search

+1 -1
View File
@@ -43,7 +43,7 @@ function icon(name) {
function renderNav() {
const nav = document.querySelector("#bottom-nav");
nav.innerHTML = NAV_ITEMS.map((item) => `
<a class="nav-item" href="#${item.path}" data-nav="${item.path}">
<a class="nav-item" href="${item.path}" data-nav="${item.path}">
${icon(item.icon)}<span class="nav-label">${item.label}</span>
</a>`).join("");
}
+2 -2
View File
@@ -32,7 +32,7 @@ export function videoCard(item, { rank = null, primary = "view", showStatus = fa
const status = showStatus && item.status
? `<span class="badge status-${escapeAttr(item.status)}">${escapeHtml(statusLabel(item.status))}</span>` : "";
return `
<a class="video-card${rank ? "" : " no-rank"}" href="#/video/${item.aid}" data-aid="${item.aid}">
<a class="video-card${rank ? "" : " no-rank"}" href="/video/${item.aid}" data-aid="${item.aid}">
${rankBadge(rank)}
${cover(item, "video-thumb")}
<div class="video-card-body">
@@ -65,7 +65,7 @@ export function upCard(item, { rank = null } = {}) {
"video-thumb up-thumb",
);
return `
<a class="up-card" href="#/up/${item.up_mid}">
<a class="up-card" href="/up/${item.up_mid}">
${rankBadge(rank)}
${displayCover}
<div class="up-card-body">
+1 -1
View File
@@ -13,7 +13,7 @@
<body>
<div class="app" id="app">
<header class="topbar">
<a class="brand" href="#/home">
<a class="brand" href="/home">
<span class="brand-mark">咻</span>
<span class="brand-text">
<strong>Reaction 看板</strong>
+83 -17
View File
@@ -5,15 +5,25 @@ let rootElement = null;
let routeElement = null;
let current = null;
let routeTable = [];
let rendering = false;
let pendingRender = null;
export function parseLocation() {
const raw = window.location.hash.replace(/^#/, "") || "/home";
const [pathPart, queryPart = ""] = raw.split("?");
const path = pathPart.startsWith("/") ? pathPart : `/${pathPart}`;
return { path, query: new URLSearchParams(queryPart) };
// 兼容旧的 #/home 链接:读取后由 startRouter 替换成干净的路径。
if (window.location.hash.startsWith("#/")) {
const raw = window.location.hash.slice(1);
const [pathPart, queryPart = ""] = raw.split("?");
return {
path: pathPart.startsWith("/") ? pathPart : `/${pathPart}`,
query: new URLSearchParams(queryPart),
legacyHash: true,
};
}
const path = window.location.pathname === "/" ? "/home" : window.location.pathname;
return { path, query: new URLSearchParams(window.location.search), legacyHash: false };
}
export function navigate(path, query) {
function setUrl(path, query, { replace = false } = {}) {
const params = new URLSearchParams();
if (query) {
for (const [key, value] of Object.entries(query)) {
@@ -22,7 +32,14 @@ export function navigate(path, query) {
}
}
const text = params.toString();
window.location.hash = `${path}${text ? `?${text}` : ""}`;
const url = `${path}${text ? `?${text}` : ""}`;
if (replace) window.history.replaceState({ path }, "", url);
else window.history.pushState({ path }, "", url);
}
export function navigate(path, query) {
setUrl(path, query);
render({ scrollTop: true });
}
export function replaceQuery(changes) {
@@ -31,8 +48,9 @@ export function replaceQuery(changes) {
if (value === null || value === undefined || value === "") query.delete(key);
else query.set(key, String(value));
}
const text = query.toString();
window.location.hash = `${path}${text ? `?${text}` : ""}`;
const flat = Object.fromEntries(query.entries());
setUrl(path, flat, { replace: true });
render({ preserveScroll: true });
}
export function onRoute(listener) {
@@ -43,8 +61,37 @@ export function startRouter({ root, outlet, routes }) {
rootElement = root;
routeElement = outlet;
routeTable = routes;
window.addEventListener("hashchange", render);
render();
if ("scrollRestoration" in window.history) {
window.history.scrollRestoration = "manual";
}
window.addEventListener("popstate", () => render({ scrollTop: false }));
document.addEventListener("click", handleClick);
const initial = parseLocation();
if (initial.legacyHash) {
setUrl(initial.path, Object.fromEntries(initial.query.entries()), { replace: true });
} else if (window.location.pathname === "/") {
setUrl("/home", null, { replace: true });
}
render({ scrollTop: true });
}
function handleClick(event) {
if (event.defaultPrevented || event.button !== 0) return;
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
const anchor = event.target.closest("a[href]");
if (!anchor || anchor.target || anchor.hasAttribute("download")) return;
const url = new URL(anchor.href, window.location.origin);
if (url.origin !== window.location.origin) return;
if (
url.pathname.startsWith("/api/") ||
url.pathname.startsWith("/static/") ||
url.pathname === "/login" ||
url.pathname === "/logout"
) {
return;
}
event.preventDefault();
navigate(url.pathname, Object.fromEntries(url.searchParams.entries()));
}
export function currentRoute() {
@@ -59,19 +106,23 @@ function matchRoute(path, routes) {
return null;
}
async function render() {
const { path, query } = parseLocation();
if (!path || path === "/") {
navigate("/home");
async function render(options = {}) {
if (rendering) {
pendingRender = options;
return;
}
rendering = true;
const { scrollTop = false, preserveScroll = false } = options;
const previousScroll = window.scrollY;
const { path, query } = parseLocation();
const matched = matchRoute(path, routeTable);
if (!matched) {
routeElement.innerHTML = `
<section class="page">
<div class="empty-state"><strong>页面不存在</strong>
<p>${escapeHtml(path)}</p><a class="button" href="#/home">回到首页</a></div>
<p>${escapeHtml(path)}</p><a class="button" href="/home">回到首页</a></div>
</section>`;
finishRender();
return;
}
current = { path, query, route: matched.route };
@@ -82,7 +133,9 @@ async function render() {
// 导航状态更新不应阻断页面渲染
}
}
window.scrollTo({ top: 0, behavior: "auto" });
if (scrollTop && !preserveScroll) {
window.scrollTo({ top: 0, behavior: "auto" });
}
routeElement.innerHTML = `<div class="page-loading"><div class="skeleton skeleton-title"></div>
<div class="skeleton skeleton-card"></div><div class="skeleton skeleton-card"></div></div>`;
try {
@@ -100,7 +153,20 @@ async function render() {
<button class="button" id="retry-button" type="button">重试</button>
</div>
</section>`;
routeElement.querySelector("#retry-button")?.addEventListener("click", render);
routeElement.querySelector("#retry-button")?.addEventListener("click", () => render({ scrollTop: true }));
}
if (preserveScroll) {
window.scrollTo({ top: previousScroll, behavior: "auto" });
}
rootElement?.classList.remove("is-loading");
finishRender();
}
function finishRender() {
rendering = false;
if (pendingRender) {
const next = pendingRender;
pendingRender = null;
render(next);
}
}
+7 -7
View File
@@ -17,7 +17,7 @@ function heatStrip(items) {
if (!items.length) return emptyState("暂无热度数据", "完成一次快照后这里会出现榜单。");
return `<div class="heat-strip">
${items.map((item, index) => `
<a class="heat-card" href="#/video/${item.aid}">
<a class="heat-card" href="/video/${item.aid}">
<span class="heat-rank">${index + 1}</span>
${cover(item, "heat-thumb")}
<strong class="heat-title">${escapeHtml(item.title)}</strong>
@@ -82,7 +82,7 @@ export async function renderHome(root) {
${statChip("待确认候选", formatCount(pending), pending ? "warning" : "")}
</div>
${pending ? `<a class="notice-row" href="#/candidates">
${pending ? `<a class="notice-row" href="/candidates">
<strong>${formatCount(pending)} 条候选待确认</strong>
<span>请在 Telegram 中处理 →</span>
</a>` : ""}
@@ -90,7 +90,7 @@ export async function renderHome(root) {
<section class="panel">
<div class="section-head">
<h2>最新入库</h2>
<a class="text-link" href="#/rank?scope=video&sort=added&within_days=7">查看全部</a>
<a class="text-link" href="/rank?scope=video&sort=added&within_days=7">查看全部</a>
</div>
${addedNote}
<div class="video-list">
@@ -102,7 +102,7 @@ export async function renderHome(root) {
<section class="panel">
<div class="section-head">
<h2>最近发布</h2>
<a class="text-link" href="#/rank?scope=video&sort=published&within_days=14">查看全部</a>
<a class="text-link" href="/rank?scope=video&sort=published&within_days=14">查看全部</a>
</div>
<p class="section-note">按视频发布时间排序,与入库时间无关。</p>
<div class="video-list">
@@ -114,7 +114,7 @@ export async function renderHome(root) {
<section class="panel">
<div class="section-head">
<h2>增长动态</h2>
<a class="text-link" href="#/rank?scope=video&sort=growth&growth_days=7">增长榜</a>
<a class="text-link" href="/rank?scope=video&sort=growth&growth_days=7">增长榜</a>
</div>
${growth.available && growth.items.length
? `<div class="video-list">${growth.items.map((item, index) => videoCard(item, { rank: index + 1 })).join("")}</div>`
@@ -124,7 +124,7 @@ export async function renderHome(root) {
<section class="panel">
<div class="section-head">
<h2>热度速览</h2>
<a class="text-link" href="#/rank?scope=video&sort=heat">完整榜单</a>
<a class="text-link" href="/rank?scope=video&sort=heat">完整榜单</a>
</div>
${heatStrip(heat.items)}
</section>
@@ -141,7 +141,7 @@ export async function renderHome(root) {
<div><span>最近快照</span><strong>${escapeHtml(formatDateTime(overview.tasks?.snapshot?.finished_at))}</strong></div>
<div><span>最近发现</span><strong>${escapeHtml(formatDateTime(overview.tasks?.discovery?.finished_at))}</strong></div>
</div>
<a class="text-link" href="#/system">查看系统状态 →</a>
<a class="text-link" href="/system">查看系统状态 →</a>
</section>
</section>`;
+1 -1
View File
@@ -35,7 +35,7 @@ export async function renderUp(root, { params, query }) {
root.innerHTML = `<section class="page up-page">
<header class="page-head">
<a class="back-link" href="#/rank?scope=up&sort=avg_views">← 返回 UP 榜</a>
<a class="back-link" href="/rank?scope=up&sort=avg_views">← 返回 UP 榜</a>
<a class="button ghost" href="${escapeAttr(up.space_url)}" target="_blank" rel="noreferrer">B 站空间</a>
</header>
+3 -3
View File
@@ -46,7 +46,7 @@ export async function renderVideo(root, { params, query }) {
root.innerHTML = `<section class="page video-page">
<header class="page-head">
<a class="back-link" href="#/rank?scope=video&sort=heat">← 返回榜单</a>
<a class="back-link" href="/rank?scope=video&sort=heat">← 返回榜单</a>
<div class="head-actions">
${detail.url ? `<a class="button ghost" href="${escapeAttr(detail.url)}" target="_blank" rel="noreferrer">打开 B 站</a>` : ""}
</div>
@@ -57,7 +57,7 @@ export async function renderVideo(root, { params, query }) {
<div class="detail-hero-body">
<h1>${escapeHtml(detail.title)}</h1>
<div class="detail-meta">
${detail.up_mid ? `<a class="inline-link" href="#/up/${detail.up_mid}">${escapeHtml(detail.up_name || "未知 UP")}</a>` : escapeHtml(detail.up_name || "未知 UP")}
${detail.up_mid ? `<a class="inline-link" href="/up/${detail.up_mid}">${escapeHtml(detail.up_name || "未知 UP")}</a>` : escapeHtml(detail.up_name || "未知 UP")}
<span>${escapeHtml(formatDate(detail.pubdate))}</span>
<span>${escapeHtml(formatDuration(detail.duration))}</span>
${detail.folder_title ? badge(detail.folder_title) : ""}
@@ -98,7 +98,7 @@ export async function renderVideo(root, { params, query }) {
${up ? `<section class="panel">
<div class="section-head">
<h2>该 UP 的其他视频</h2>
<a class="text-link" href="#/up/${detail.up_mid}">查看 UP 页 →</a>
<a class="text-link" href="/up/${detail.up_mid}">查看 UP 页 →</a>
</div>
<div class="video-list">
${others.length ? others.map((item) => videoCard(item)).join("") : emptyState("没有其他视频")}