Peach: Local-first video metadata scraper and media manager.
fix: 侧栏跟随视频集合并复用在线关注详情
longmeidaoe72493781b14
diff --git a/docs/REUSE.md b/docs/REUSE.mdindex 8b19e04aa..ab344031a 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -15,6 +15,7 @@- 独立 Windows 测试包复用 PyInstaller 6.22.2(GPL-2.0-or-later,带分发 bootloader 例外)的 [onedir 与自启动子进程](https://pyinstaller.org/en/stable/common-issues-and-pitfalls.html);使用已有精确固定的 build 依赖。Python 3.14 / Windows x64 在清除开发工具 PATH、隔离数据目录下实测初始化、页面与 API。保留 Peach 的进程所有权、数据目录、配置和扫描策略;onefile 的托盘入口只用于既有源码部署,独立包采用完整目录以共享资源并避免重复解包。没有新增运行时依赖。- 运行一致性复评:复用 `LedgerDatabase.write_transaction` 的提交边界和标准库 `OrderedDict`;HTTP 导航复用 FastAPI/Starlette,图片复验复用 `StaticFiles.is_not_modified` 与 `FileResponse` 的 ETag。列表使用 SQLite 的 IN/UNION 保留隐藏标签与多标签组合,不引入查询框架。+- 馆藏侧栏复用 `catalog_filter` 的列表条件,已保存在线卡片复用关注来源的标签与封面投影,详情复用 `openFollowDetail`、Video.js 和媒体队列。导航范围与标签计数位于 `frontend/src/sidebar.ts`;不新增依赖。截图所示 F95 合集的只读核对结果为无封面、无标签、无已解析媒体,详情按现有来源信息展示。- wheel 资源复用 setuptools 84.0.0 的 `build_py.copy_tree`,资源位置遵循[官方包内数据建议](https://setuptools.pypa.io/en/stable/userguide/datafiles.html)。自定义钩子仅复制三个既有资源目录,因为源码、桌面构建和前端产物仍共用其维护位置;Windows 基础依赖全新安装及仓库外 API 冒烟已验证。- 先用真实输入做无写入 POC,再决定“直接依赖、固定来源实现、保留自研”三者之一。diff --git a/docs/STATUS.md b/docs/STATUS.mdindex df9757967..883509378 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -28,7 +28,7 @@- 本地浏览器支持 MP4/WebM/Ogg,AVI 等由 `TranscodeService` 缓存成 H.264/AAC MP4,永不改写原媒体;ffprobe 探测后可直接复制的流不重编码,其余在 Windows 走 CUDA/NVDEC。- 远端 MP4 默认走标准 Range,显式开启的 HLS 使用关键帧对齐片段并在失败时回退 Range。-- 所有页面共用同一 SPA 与 JSON 契约,文本 gzip、资产 ETag;路由清单在 `README.md`。+- 页面共用 SPA、JSON 与 gzip/ETag;侧栏随当前视频集合,已保存在线作品复用关注详情。- Logo、侧栏「首页」和沉浸模式关闭统一清除分类、搜索与 JAV 筛选,首页默认稳定随机、换批才换种子,再点当前排序回到随机。- 桌面与 390×844 手机同在验收范围内,手机操作按钮保持 44 px 命中区。- 同番号的分卷派生(A/B、1/2、CD/Disc/DVD/Part/Vol、「首卷裸名 + 后续卷 `-2`/`-3`」)折叠成一张卡并按时长排除完整版;首页、搜索、资料页网格与版次队列、角标计数共用同一套判定。diff --git a/frontend/src/islands.ts b/frontend/src/islands.tsindex ab163d22f..850120784 100644--- a/frontend/src/islands.ts+++ b/frontend/src/islands.ts@@ -25,6 +25,7 @@ import type { QualityGoalsData } from './state/quality-goals';* 怎么写一个 store 见 `./state/index.ts` 和 `docs/FRONTEND.md`。 */export { refreshStore, storeNames } from './state';export { watchJob, followJobProgress } from './jobs';+export { syncSidebarSurface, sidebarTagCounts, sidebarHasCatalogContent } from './sidebar';export type { StoreName } from './state';/** 首屏取数的结果。`data` 与 `error` 恰有一个成立。 */diff --git a/frontend/src/sidebar.ts b/frontend/src/sidebar.tsnew file mode 100644index 000000000..2abcf71af--- /dev/null+++ b/frontend/src/sidebar.ts@@ -0,0 +1,23 @@+/** 侧栏筛选属于当前地址对应的内容集合。导航由遗留外壳同步绘制。 */+export function sidebarHasCatalogContent(path: string): boolean {+ return ['/', '/unseen', '/watch-later', '/flagged', '/trash', '/junk-files'].includes(path)+ || /^\/(item|mix|parts|editions)\//.test(path)+ || /^\/playlists\/\d+\/\d+$/.test(path)+ || /^\/(performers|studios|creators|series|agencies)\/.+/.test(path);+}++export function syncSidebarSurface(drawer: HTMLElement, key: string): boolean {+ if (drawer.dataset.surface === key && drawer.querySelector('.dnav')) return false;+ drawer.dataset.surface = key;+ drawer.replaceChildren();+ return true;+}++/** 一条内容的同名标签只计一次。调用者传入当前实际展示的媒体。 */+export function sidebarTagCounts(items: { tags?: string[] }[]): [string, number][] {+ const counts = new Map<string, number>();+ for (const item of items) {+ for (const tag of new Set(item.tags || [])) counts.set(tag, (counts.get(tag) || 0) + 1);+ }+ return [...counts].sort((a, b) => b[1] - a[1]).slice(0, 30);+}diff --git a/frontend/test/sidebar.test.ts b/frontend/test/sidebar.test.tsnew file mode 100644index 000000000..48f754f65--- /dev/null+++ b/frontend/test/sidebar.test.ts@@ -0,0 +1,38 @@+import { describe, expect, it } from 'vitest';+import { sidebarTagCounts, syncSidebarSurface, sidebarHasCatalogContent } from '../src/sidebar';++describe('侧栏内容范围', () => {+ it('视频集合提供馆藏筛选,管理与索引页只提供导航', () => {+ for (const path of ['/', '/unseen', '/trash', '/item/1', '/creators/Demo', '/parts/1/2'])+ expect(sidebarHasCatalogContent(path)).toBe(true);+ for (const path of ['/follow-manage', '/stats', '/follow', '/tags', '/data-cleanup', '/creators'])+ expect(sidebarHasCatalogContent(path)).toBe(false);+ });+ it('管理页直达即建立导航,导航切换清除上一页标签', () => {+ const drawer = document.createElement('aside');+ expect(syncSidebarSurface(drawer, '/follow-manage')).toBe(true);+ drawer.innerHTML = '<div class="dnav">导航</div>';+ expect(syncSidebarSurface(drawer, '/follow-manage')).toBe(false);+ expect(drawer.textContent).toBe('导航');+ expect(syncSidebarSurface(drawer, '/')).toBe(true);+ drawer.innerHTML = '<div class="dnav">导航</div><div class="sec">视频标签</div>';+ expect(syncSidebarSurface(drawer, '/follow-manage')).toBe(true);+ expect(drawer.querySelector('.sec')).toBeNull();+ });++ it('相同页面保留筛选,查询变化清除旧集合', () => {+ const drawer = document.createElement('aside');+ syncSidebarSurface(drawer, '/?tag=a');+ drawer.innerHTML = '<div class="dnav"></div><div class="sec">a</div>';+ expect(syncSidebarSurface(drawer, '/?tag=a')).toBe(false);+ expect(drawer.querySelector('.sec')).not.toBeNull();+ expect(syncSidebarSurface(drawer, '/?tag=b')).toBe(true);+ expect(drawer.querySelector('.sec')).toBeNull();+ });++ it('只计当前内容的标签,空内容没有标签', () => {+ expect(sidebarTagCounts([{tags: ['a', 'a', 'b']}, {tags: ['b']}, {}]))+ .toEqual([['b', 2], ['a', 1]]);+ expect(sidebarTagCounts([])).toEqual([]);+ });+});diff --git a/src/peach/web_catalog.py b/src/peach/web_catalog.pyindex 554747fda..b582643e8 100644--- a/src/peach/web_catalog.py+++ b/src/peach/web_catalog.py@@ -115,7 +115,8 @@ AGENCY_SEARCH_CLAUSE = ()-def q_items(contract: WebContract, args):+def catalog_filter(contract: WebContract, args):+ """视频列表与侧栏使用同一组筛选条件。"""trash = args.get("state") == "trash"# 普通馆藏仍是视频表面;回收站必须展示所有文件类型,否则从垃圾复核移入的# 图片、网址快捷方式等会变成不可见、不可恢复,只能被「清空回收站」直接删掉。@@ -221,6 +222,11 @@ def q_items(contract: WebContract, args):# 「在线 1」,点进去却永远是 0 条。where.append("(a.snapshot_path IS NOT NULL OR a.location = 'online')")+ return where, par+++def q_items(contract: WebContract, args):+ where, par = catalog_filter(contract, args)requested = str(args.get("sort") or "")sort_key, legacy_dir = SORT_LEGACY_KEYS.get(requested, (requested, ""))direction = "ASC" if (str(args.get("dir") or "").lower() or legacy_dir) == "asc" else "DESC"@@ -308,6 +314,7 @@ def q_items(contract: WebContract, args):r["cover_frame"] = contract.cover_frame(r.get("code"))r.pop("snapshot_path", None)r.pop("path", None) # 路径不外发,串流走 id+ attach_saved_follow_cards(contract, rows)attach_multipart_groups(contract, rows)attach_edition_groups(contract, rows)return {"total": cnt, "bytes": total_bytes, "items": rows, "has_more": has_more}@@ -364,6 +371,7 @@ def attach_card_performers(contract: WebContract, rows):"""给各类视频卡片补同一份表演者资料,避免首页/相关/复核卡片各说各话。"""if not rows:return+ attach_saved_follow_cards(contract, rows)ids = [row["id"] for row in rows]qm = ",".join("?" * len(ids))names: dict[int, list[str]] = {}@@ -380,6 +388,32 @@ def attach_card_performers(contract: WebContract, rows):row["performer_total"] = len(names.get(row["id"], []))+def attach_saved_follow_cards(contract: WebContract, rows):+ """已保存在线卡片使用关注来源的封面与内容标签。"""+ from .follow_store import FollowStore+ from .web_follow import _item_tags, _thumb_url++ ids = [row["id"] for row in rows if row.get("location") == "online"]+ if not ids:+ return+ marks = ",".join("?" * len(ids))+ with contract.read_connection() as connection:+ linked = connection.execute(+ FollowStore._SELECT + f" WHERE i.asset_id IN ({marks}) ORDER BY i.id", ids,+ ).fetchall()+ by_asset = {}+ for record in linked:+ item = FollowStore._row(record)+ by_asset.setdefault(item.asset_id, item)+ for row in rows:+ item = by_asset.get(row["id"])+ if item is None or row.get("location") != "online":+ continue+ row["follow_item_id"] = item.id+ row["follow_thumb_url"] = _thumb_url(item)+ row["follow_tags"] = _item_tags(item)++#: 版次的展示次序:正片在前,处理过的在后。这不是偏好排序,只是要一个稳定的#: 锚点——卡片标题取第一个,次序一变卡片就换名字。EDITION_ORDER = ("有码", "中字", "无码", "无码破解")@@ -858,6 +892,7 @@ def q_facets(scope_name: str = "",asset_id: int | None = None,state: str = "",+ filters: dict | None = None,):"""返回当前浏览集合真正存在的筛选项。@@ -892,6 +927,10 @@ def q_facets("SUM(CASE WHEN a.play_count>0 THEN 1 ELSE 0 END) AS played ""FROM asset a WHERE a.medium='video' " + scope +"GROUP BY a.location ORDER BY n DESC", scope_params)]+ if filters is not None and asset_id is None:+ conditions, parameters = catalog_filter(contract, {**filters, "state": state})+ scope += "AND " + " AND ".join(conditions) + " "+ scope_params.extend(parameters)out["orientations"] = [dict(r) for r in c.execute("SELECT a.ctx_orient AS k,count(*) AS n FROM asset a ""WHERE a.medium='video' AND a.ctx_orient IS NOT NULL AND a.ctx_orient<>'' " + scope +@@ -935,6 +974,16 @@ def q_facets("FROM asset a WHERE a.medium='video' AND (a.disposal IS NULL OR a.disposal<>'trash') "+ scope, scope_params).fetchone()out["stats"] = dict(st)+ saved = [dict(row) for row in c.execute(+ "SELECT a.id,a.location FROM asset a WHERE a.medium='video' "+ "AND a.location='online' " + scope, scope_params)]+ attach_saved_follow_cards(contract, saved)+ follow_counts: dict[str, int] = {}+ for item in saved:+ for tag in set(item.get("follow_tags", [])):+ follow_counts[tag] = follow_counts.get(tag, 0) + 1+ out["follow_tags"] = [{"k": tag, "n": count} for tag, count in+ sorted(follow_counts.items(), key=lambda row: (-row[1], row[0]))[:30]]return out# ────────────────────────────── 写入 ──────────────────────────────diff --git a/src/peach/web_router.py b/src/peach/web_router.pyindex 0a97aadaa..17da162ac 100644--- a/src/peach/web_router.py+++ b/src/peach/web_router.py@@ -129,12 +129,17 @@ def _get_facets(contract, args):asset_id = int(args["id"]) if args.get("id") else Nonestate = str(args.get("state", ""))scope_key = f"{scope_kind}:{scope_name}:{asset_id or ''}:{state}"+ filters = {key: args[key] for key in (+ 'loc', 'creator', 'performer', 'studio', 'series', 'agency', 'tag', 'tag_match',+ 'len', 'dur_min', 'dur_max', 'orient', 'exclude_vertical', 'q', 'thumb',+ ) if args.get(key)}+ scope_key += repr(sorted(filters.items()))return contract.cached(f"facets{'-jav' if jav else ''}:{scope_key}",lambda: q_facets(contract,jav=jav, scope_kind=scope_kind, scope_name=scope_name, asset_id=asset_id,- state=state,+ state=state, filters=filters or None,),)diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.pyindex 749ac6e88..39645e926 100644--- a/tests/test_fastapi_api.py+++ b/tests/test_fastapi_api.py@@ -184,6 +184,8 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):(self.root / "dist" / "peach-ui.css").write_text(".island{}", encoding="utf-8")con = sqlite3.connect(self.db)con.executescript(BASE_SCHEMA)+ con.executescript((ROOT / "migrations" / "0018_online_follow.sql").read_text(+ encoding="utf-8"))con.execute("""INSERT INTO asset(id,location,path,name,medium,size,creator,studio,duration,width,height,ctx_orient,snapshot_path,first_seen)diff --git a/tests/test_follow_web.py b/tests/test_follow_web.pyindex 31c1d67f6..8b4fccee7 100644--- a/tests/test_follow_web.py+++ b/tests/test_follow_web.py@@ -176,6 +176,41 @@ class FollowContractTests(unittest.TestCase):def _post(self, path, body):return dispatch_api_post(self.contract, path, body)+ def test_saved_catalog_media_uses_the_follow_cover_and_content_tags(self):+ self._seed(candidates=(FollowCandidate(+ provider='rule34video', external_id='saved-media', title='Demo video',+ url='https://example.test/post', media_url='https://example.test/movie.mp4',+ thumb_url='https://example.test/cover.jpg', duration=20,+ extra={'tags': ['animation', 'artist_name'],+ 'tag_types': {'animation': 'general', 'artist_name': 'artist'}},+ ),))+ with self.contract.database.write_transaction() as connection:+ store = FollowStore(lambda: connection)+ item = store.items()[0]+ asset_id = store.save_asset(item.id, confirm=True)+ follow = self._get(item=str(item.id))['groups'][0]['primary']+ catalog = self._get('/api/items', loc='online')['items'][0]+ self.assertEqual(catalog['id'], asset_id)+ self.assertEqual(catalog['follow_item_id'], item.id)+ self.assertEqual(catalog['follow_thumb_url'], follow['thumb_url'])+ self.assertEqual(catalog['follow_tags'], follow['tags'])+ self.assertNotIn('artist_name', catalog['follow_tags'])+ detail = self._get('/api/item', id=str(asset_id))+ self.assertEqual(detail['follow_item_id'], item.id)+ online = self._get('/api/facets', loc='online')+ self.assertEqual([row['k'] for row in online['follow_tags']], follow['tags'])+ self.assertEqual(self._get('/api/facets', loc='local')['follow_tags'], [])++ def test_unsaved_follow_tags_do_not_enter_catalog_facets(self):+ self._seed(candidates=(FollowCandidate(+ provider='rule34video', external_id='unsaved', title='Demo video',+ url='https://example.test/unsaved', duration=20,+ extra={'tags': ['animation'], 'tag_types': {'animation': 'general'}},+ ),))+ self.assertTrue(self._get('/api/follow/tags')['items'])+ self.assertEqual(self._get('/api/facets')['tags'], [])+ self.assertEqual(self._get('/api/facets')['follow_tags'], [])+def test_paging_back_advances_the_cursor_without_touching_the_etag(self):"""往回抓推进游标,但**绝不覆盖 etag**。diff --git a/tests/test_rm_web.py b/tests/test_rm_web.pyindex c5477fd10..d4f12ab22 100644--- a/tests/test_rm_web.py+++ b/tests/test_rm_web.py@@ -304,6 +304,16 @@ class WebDataTests(unittest.TestCase):flagged = rm_web.q_facets(self.contract, state="flagged")self.assertEqual({row["k"] for row in flagged["locations"]}, {"115"})self.assertEqual({row["k"] for row in flagged["orientations"]}, {"竖屏"})+ local = rm_web.q_facets(self.contract, filters={"loc": "local"})+ remote = rm_web.q_facets(self.contract, filters={"loc": "115"})+ self.assertEqual(local['stats']['total'], 1)+ self.assertEqual(remote['stats']['total'], 1)+ self.assertEqual({row['k'] for row in local['locations']}, {'local', '115'})+ self.assertNotEqual(local['orientations'], remote['orientations'])+ empty = rm_web.q_facets(self.contract, filters={"q": "no-matching-demo"})+ self.assertEqual(empty['tags'], [])+ self.assertEqual(empty['creators'], [])+ self.assertEqual(empty['stats']['total'], 0)self.assertNotIn("足交", [row["k"] for row in flagged["tags"]])# 顶部三层同一口径:Alice 只在 1 号上,应该整个消失;diff --git a/tests/test_web_ui.py b/tests/test_web_ui.pyindex b8605d305..38f976388 100644--- a/tests/test_web_ui.py+++ b/tests/test_web_ui.py@@ -851,7 +851,7 @@ class WebUiSourceTests(unittest.TestCase):# 目录页四个筛选态的标题就是筛选名本身,和侧栏取同一份 STATE_LABELS。self.assertPageContains("title:STATE_LABELS[key],open:()=>openCatalog(path)")self.assertPageContains('syncPageTitle(path);')- self.assertPageContains('queueMicrotask(()=>{syncHeaderActions();paintListTitle()})')+ self.assertPageContains('queueMicrotask(()=>{syncHeaderActions();paintListTitle();buildDrawerNavigation()})')self.assertPageContains("queueMicrotask(()=>$('#settingsClose').focus())")self.assertPageContains('if(settingsReturnFocus&&document.contains(settingsReturnFocus))')self.assertPageContains("if(e.key!=='Tab')return")@@ -1285,6 +1285,11 @@ class WebUiSourceTests(unittest.TestCase):"return it.location==='online'&&it.follow_item_id")self.assertPageContains("const proxied=followStreamSource(it);")self.assertPageContains("const onlineGated=online&&!it.follow_item_id;")+ self.assertPageContains("if(it.location==='online'&&it.follow_item_id){")+ self.assertPageContains('await openFollowDetail(it.follow_item_id,false,null,true)')+ self.assertPageContains("if(location.pathname!=='/follow'){await restoreRoute();return}")+ self.assertPageContains('it.follow_thumb_url')+ self.assertPageContains('it.follow_tags||it.tags||[]')self.assertPageLacks("这条内容从关注候选保存;媒体与原始页面在关注详情中查看。")def test_follow_detail_has_an_explicit_download(self):@@ -4167,6 +4172,14 @@ class WebUiSourceTests(unittest.TestCase):self.assertPageContains("foldName(t.k)===key&&foldName(previous.k)!==key")def test_drawer_filters_follow_entity_and_detail_context(self):+ self.assertPageContains('function buildDrawerNavigation()')+ self.assertPageContains('syncSidebarSurface(drawer,key)')+ self.assertCode('surfaceEpoch++;\n barsRequestSeq++;')+ self.assertPageContains('key=surfacePath()+location.search')+ self.assertPageLacks("api('/api/follow/tags?limit=30')")+ self.assertPageContains('renderFollowDrawer(visible.flatMap(group=>followCollectionItems(group)))')+ self.assertPageContains('renderFollowDrawer([item])')+ self.assertPageContains("if(!sidebarHasCatalogContent(location.pathname))return;")# 实体页 facets 必须按当前实体取数;详情页则按单个作品取数,不能继续复用首页全库。self.assertPageContains("facetParams.set('scope_kind',context.kind)")self.assertPageContains("facetParams.set('scope_name',context.name)")@@ -5983,7 +5996,7 @@ class WebUiSourceTests(unittest.TestCase):self.assertPageContains("followFilter='',followBusy=false")# 「返回关注页」和「回到关注首屏」两处重置也得落在同一个默认上。self.assertEqual(self.page.count(- "followMediaView='videos';followFilter='';"), 2,+ "followMediaView='videos';followFilter='';"), 1,"有重置分支还在把筛选推回旧默认")self.assertPageContains("[['','全部'],['new','未看']")diff --git a/web/app.js b/web/app.jsindex 737c030c6..7206faf3f 100644--- a/web/app.js+++ b/web/app.js@@ -4,6 +4,7 @@ import { javDisplayName, javTitleHtml } from './js/jav-title.js';import { matchRoute, routeLabel } from './js/routes.js';import { initMiddleTruncate } from './js/middle-truncate.js';import { tagLabel } from './js/tags.js';+import { syncSidebarSurface, sidebarTagCounts, sidebarHasCatalogContent } from './dist/peach-ui.js';import {breadcrumbHtml, checkboxHtml, closeAnchoredMenu, confirmModal, emptyStateHtml, fieldsetTitle,fillSkeletonTier, fitSkeleton, iconSwitchHtml, loadingDotsHtml,@@ -302,9 +303,10 @@ const surfaceApi=(token,path,options)=>api(path,{...options,signal:token.signal}.catch(error=>{if(isAbort(error))return null;throw error});const route=(path,replace=false)=>{surfaceEpoch++;+ barsRequestSeq++;history[replace?'replaceState':'pushState']({},'',path);syncPageTitle(path);lastRoutePath=decodeURIComponent(new URL(path,location.href).pathname);- queueMicrotask(()=>{syncHeaderActions();paintListTitle()});+ queueMicrotask(()=>{syncHeaderActions();paintListTitle();buildDrawerNavigation()});};/* ── 脱盘模式 ─────────────────────────────────────────────────────────────────@@ -1848,6 +1850,8 @@ function cardHtml(it,cls){const thumb=useCover? coverImage(it,layout)+ : it.follow_thumb_url+ ? `<img class="poster" src="${esc(it.follow_thumb_url)}" alt="" loading="lazy" referrerpolicy="no-referrer">`: (it.has_thumb? `<img class="poster" src="/poster?id=${it.id}&c=4" alt="" loading="lazy">`: `<span class="nopic">无预览</span>`);@@ -1866,7 +1870,7 @@ function cardHtml(it,cls){? `<div class="watchprogress" role="progressbar" aria-label="观看进度" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${Math.round(watchedRatio*100)}"><i style="width:${(watchedRatio*100).toFixed(1)}%"></i></div>`: (it.leave_ratio!=null?`<div class="scrub"><i style="width:${Math.round(it.leave_ratio*100)}%"></i></div>`:'');const sizeText=Number(shownSize)>0?fmtSize(Number(shownSize)):'大小未知';- const tgs=(it.tags||[]).slice(0,3).map(x=>`<span class="tg general" data-tag="${esc(x)}">${esc(tagLabel(x))}</span>`).join('');+ const tgs=(it.follow_tags||it.tags||[]).slice(0,3).map(x=>`<span class="tg general"${it.follow_item_id?'':` data-tag="${esc(x)}"`}>${esc(tagLabel(x))}</span>`).join('');const laterTool=`<div class="hovertools later-tools"><button class="laterbtn" data-later aria-pressed="${!!it.watch_later}" title="稍后看" aria-label="稍后看">${it.watch_later?icon('check'):icon('bookmark-plus')}</button></div>`;/* 分卷卡悬浮翻的是各卷首帧,没有可控的视频:倒计时环和快退/快进那三颗留着的话,@@ -2286,6 +2290,12 @@ async function getBarsData(context=barsContext){// 已标记/稍后看这类状态页也是一个更窄的集合。不传的话,上面那排头像和// 标签条走的是全库口径,列出来的人和标签在本页一个作品都没有。if(context.type==='home'&&state.state)facetParams.set('state',state.state);+ if(context.type!=='item'){+ const filters=activeFilterState();+ ['loc','creator','studio','tag','tag_match','len','dur_min','dur_max','orient','q','thumb'].forEach(key=>{+ if(filters[key])facetParams.set(key,filters[key]);+ });+ }const scope=facetParams.toString();if(scope!==barsDataScope){barsDataCache=null;barsDataPromise=null;barsDataScope=scope}if(barsDataCache&&Date.now()-barsDataAt<30000)return barsDataCache;@@ -2318,18 +2328,6 @@ function commitContextFilter(mutate){}mutate(state);route(homePath());buildBars();load(true)}-/* 关注标签和目录标签是两套词表:一个来自关注库的在线更新,一个来自 ledger 里已入库- 的作品,连计数的含义都不同,所以单独取一份。缓存窗口与 getBarsData 对齐——抽屉每- 次导航都重建,不该每次都问一遍。取不到就当没有,抽屉少一节,不挡其余筛选。 */-let followTagCache=null,followTagCacheAt=0;-const followTagFacet=async()=>{- if(followTagCache&&Date.now()-followTagCacheAt<30000)return followTagCache;- try{- const data=await api('/api/follow/tags?limit=30');- followTagCache=data.items||[];followTagCacheAt=Date.now();- }catch(_e){followTagCache=followTagCache||[]}- return followTagCache;-};/* 首屏时顶部三层和标签条还是两个空 div,而这一次请求要花约一秒。Geist 的判据是骨架宽高必须等于最终内容——「200×20 的块变成 80×16 的字读起来像故障」——所以这里直接套真实类名,让几何自己对上。只在还空着时画:导航到已经有内容的页面@@ -2362,13 +2360,15 @@ function renderBarsLoading(filterState){}async function buildBars(){const requestSeq=++barsRequestSeq;+ buildDrawerNavigation();+ if(!sidebarHasCatalogContent(location.pathname))return;const context=barsContext,filterState=activeFilterState();renderBarsLoading(filterState);// 两个聚合查询互不依赖。冷启动各需约 1 秒,串行会让手机首屏白等;// 并行取回后再一次性绘制顶部与抽屉。- const [[facetData,tops],followTagRows]=await Promise.all([- getBarsData(context),followTagFacet()]);+ const [facetData,tops]=await getBarsData(context);if(requestSeq!==barsRequestSeq)return;+ const followTagRows=facetData.follow_tags||[];if(context.type==='home')facets=facetData;// 详情抽屉继续只展示当前作品的真实标签;作品没有内容标签时,顶部发现栏// 回退到返回首页的推荐口径,避免把全库标签伪装成作品元数据。@@ -2465,18 +2465,15 @@ async function buildBars(){+sec('创作者',chips(scopedCreators,'creator',false,26),scopedCreators.length>26?'<button data-more="creator">更多</button>':'','artist')+sec('内容标签',chips(facetData.tags,'tag',false,30),facetData.tags.length>30?'<button data-more="tag">更多</button>':'','general')+sec('影片属性',chips(facetData.tech,'tag',false,16),'','meta')- /* 单独一节而不是并进「内容标签」:这些标签指向还没入库的在线更新,混在一起- 点下去会得到一屏空结果。它们也不能走 chips——那套拼的是目录筛选。 */+sec('关注标签',followTagRows.length?`<div class="chips">`+followTagRows.map(row=>- `<button class="chip online" data-follow-drawer-tag="${esc(row.k)}">${esc(row.k)}<span class="n">${row.n.toLocaleString()}</span></button>`+ `<button class="chip online" data-follow-drawer-tag="${esc(row.k)}">${esc(tagLabel(row.k))}<span class="n">${row.n.toLocaleString()}</span></button>`).join('')+`</div>`:'','','online');const dc=$('#drawerClose'); if(dc)dc.onclick=()=>openDrawer(false);$('#drawer').querySelectorAll('[data-page]').forEach(b=>b.onclick=()=>{openIndex(b.dataset.page); closeDrawerAfterNav()});$('#drawer').querySelectorAll('[data-nav]').forEach(b=>b.onclick=()=>navTo(b.dataset.nav));$('#drawer').querySelectorAll('[data-follow-drawer-tag]').forEach(b=>b.onclick=()=>{- // 关注标签只在关注页成立,直接过去;它不是目录筛选,不能走 commitContextFilter。- followAuthor='';followProvider='';followMediaView='videos';followFilter='';+ followAuthor='';followProvider='';followMediaView='videos';followFilter='saved';followTags=new Set([b.dataset.followDrawerTag]);openDrawer(false);route(followViewPath());openFollow(false)});wireNavigationDrag($('#drawer').querySelector('.dnav'));@@ -3874,9 +3871,10 @@ async function followItemById(id){async function openFollowDetail(id,push=true,mediaIndex=null,preserveReturn=false){releaseHoverPreviews();const entering=!location.pathname.startsWith('/follow/item/');- if(push&&entering)followDetailReturnPath=location.pathname+location.search;+ if(push&&entering&&!preserveReturn)followDetailReturnPath=location.pathname+location.search;if(!push&&!preserveReturn)followDetailReturnPath='/follow';- const item=await followItemById(+id);if(!item)return;+ const surface=surfaceToken(surfacePath());+ const item=await followItemById(+id);if(!item||!surfaceCurrent(surface))return;const group=followGroupByItemId.get(item.id);const embedded=item.media_items||[];const preferredKind=followMediaView==='images'?'image':'video';@@ -3891,6 +3889,7 @@ async function openFollowDetail(id,push=true,mediaIndex=null,preserveReturn=falsconst collection=!embedded.length&&group&&followVideoItems(group).length>1?group:null;disposeStage(false);if(push)route(`/follow/item/${item.id}`);+ renderFollowDrawer([item]);const source=(followData?.sources||[]).find(row=>row.id===item.source_id);const authorSources=(followData?.sources||[]).filter(row=>source?.author_key&&row.author_key===source.author_key);@@ -3898,7 +3897,7 @@ async function openFollowDetail(id,push=true,mediaIndex=null,preserveReturn=falsconst src=item.playable?`/follow-stream?id=${item.id}${selectedMedia?`&media=${selectedMedia.index}`:''}`:'';const selectedKind=selectedMedia?.media_kind||item.media_kind;const media=item.playable&&selectedKind==='video'- ?`<video class="video-js vjs-big-play-centered" controls playsinline preload="metadata"></video>`+ ?`<video class="video-js vjs-big-play-centered" controls playsinline preload="metadata"${item.thumb_url?` poster="${esc(item.thumb_url)}"`:''}></video>`:item.playable&&selectedKind==='image'?`<img class="followdetailposter" src="${src}" alt="${esc(item.title)}">`:item.thumb_url@@ -3935,6 +3934,8 @@ async function openFollowDetail(id,push=true,mediaIndex=null,preserveReturn=falslast.after($('#stage'));}else if(followList){followList.before($('#stage'));+ }else{+ placeItemDetail(detailOriginAnchor,detailOriginAbove);}$('#stage').hidden=false;document.body.classList.add('detail-open');$('#stage').innerHTML=`<div class="sgrid followdetailgrid${collection||embeddedQueue?' mixgrid':''}">@@ -3966,12 +3967,13 @@ async function openFollowDetail(id,push=true,mediaIndex=null,preserveReturn=falsconst closeDetail=async()=>{disposeStage(false);route(followDetailReturnPath||'/follow');+ if(location.pathname!=='/follow'){await restoreRoute();return}if(followData)renderFollow();else await openFollow(false);};$('#closeStage').onclick=closeDetail;$('#stage').querySelectorAll('[data-follow-queue-close]').forEach(button=>button.onclick=closeDetail);$('#stage').querySelectorAll('[data-follow-queue-item]').forEach(button=>button.onclick=()=>- openFollowDetail(+button.dataset.followQueueItem,true));+ openFollowDetail(+button.dataset.followQueueItem,true,null,true));$('#stage').querySelectorAll('[data-follow-media-item]').forEach(button=>button.onclick=()=>openFollowDetail(+(button.dataset.followMediaOwner||item.id),false,+button.dataset.followMediaItem,true));@@ -4269,6 +4271,7 @@ function renderFollow(){mediaCounts[kind==='image'?'images':'videos']++));const wantedKind=followMediaView==='images'?'image':'video';const visible=groups.filter(group=>followMediaKinds(group).has(wantedKind));+ renderFollowDrawer(visible.flatMap(group=>followCollectionItems(group)));const providerPills=[...providers].map(([key,label])=>`<button class="pill sourcepill" data-follow-provider="${esc(key)}" aria-pressed="${key===followProvider}"title="${esc(label)}" aria-label="来源:${esc(label)}">${sourceIcon(key)}</button>`).join('');@@ -6091,6 +6094,34 @@ async function openEntity(kind,name,push=true){}let drawerSuppressUntil=0;+function buildDrawerNavigation(){+ const drawer=$('#drawer'),key=surfacePath()+location.search;+ if(!syncSidebarSurface(drawer,key)){+ drawer.querySelectorAll('[data-nav]').forEach(button=>+ button.setAttribute('aria-pressed',String(navOn(button.dataset.nav))));+ return;+ }+ drawer.innerHTML=`<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:10px">+ <b class="disp" style="font-size:15px;letter-spacing:.1em">导航与筛选</b>+ <button id="drawerClose" class="ib" title="收起" aria-label="收起导航">${icon('x')}</button></div>+ <div class="dnav">${orderedEdgeIcons().map(([k,label,ic])=>+ `<button data-nav="${k}" draggable="true" aria-pressed="${navOn(k)}">${icon(ic)}<span>${label}</span></button>`).join('')}</div>`;+ $('#drawerClose').onclick=()=>openDrawer(false);+ $('#drawer').querySelectorAll('[data-nav]').forEach(b=>b.onclick=()=>navTo(b.dataset.nav));+ wireNavigationDrag(drawer.querySelector('.dnav'));+}+function renderFollowDrawer(items){+ buildDrawerNavigation();+ $('#drawer').querySelectorAll('.sec').forEach(section=>section.remove());+ const counts=sidebarTagCounts(items.map(item=>({tags:followCardTags(item)})));+ if(!counts.length)return;+ $('#drawer').insertAdjacentHTML('beforeend',`<div class="sec cat-online"><h3>内容标签</h3><div class="chips">${+ counts.map(([tag,n])=>+ `<button class="chip online" data-follow-drawer-tag="${esc(tag)}" aria-pressed="${followTags.has(tag)}">${esc(tagLabel(tag))}<span class="n">${n}</span></button>`).join('')}</div></div>`);+ $('#drawer').querySelectorAll('[data-follow-drawer-tag]').forEach(b=>b.onclick=()=>{+ followTags=new Set([b.dataset.followDrawerTag]);+ openDrawer(false);route(followViewPath());openFollow(false)});+}function openDrawer(v){$('#drawer').classList.toggle('open',v);$('#scrim').classList.toggle('on',v);document.body.classList.toggle('drawer-open',!!v)}function closeDrawerAfterNav(){drawerSuppressUntil=Date.now()+650;openDrawer(false)}@@ -6522,6 +6553,7 @@ function syncHeaderActions(){if(!canSelect&&selectMode)setSelectMode(false,true);}function buildEdge(){+ buildDrawerNavigation();$('#edge').innerHTML=orderedEdgeIcons().map(([k,t,ic])=>`<button data-nav="${k}" draggable="true" title="${t}" aria-pressed="${navOn(k)}">${icon(ic)}</button>`).join('')@@ -6891,6 +6923,11 @@ async function openItem(id,push=true,queueContext=null,anchor=null){const it=await surfaceApi(detailSurface,'/api/item?id='+id);if(!surfaceCurrent(detailSurface))return;if(it.error)return;+ if(it.location==='online'&&it.follow_item_id){+ followDetailReturnPath=detailReturnPath||'/';+ await openFollowDetail(it.follow_item_id,false,null,true);+ return;+ }/* 卷标只有分卷队列知道:`/api/item` 是单条口径,它答不出「这是第几卷」。不补的话标题栏里的卷号在深链进来和点开队列另一条时都不出现。 */if(queueContext?.kind==='parts')@@ -6898,7 +6935,7 @@ async function openItem(id,push=true,queueContext=null,anchor=null){current=it; CACHE[it.id]=it;barsContext={type:'item',id:it.id,filters:returnBars?.type==='entity'? {...returnBars.filters}:emptyEntityFilters()};- const gated=it.cost==='metered';+ const gated=it.cost==='metered'&&it.location!=='online';const offline=sourceOffline(it.location);const online=it.location==='online';/* 保存过的在线资产照常播;只有反查不到关注条目时才拦下来说明原因。 */@@ -7839,7 +7876,9 @@ function immerseStartId(){async function restoreRoute(){surfaceEpoch++;+ barsRequestSeq++;syncPageTitle(location.href);+ buildDrawerNavigation();const path=decodeURIComponent(location.pathname);if(path==='/'&&new URLSearchParams(location.search).get('state')==='ads'){route(junkPath(),true);await restoreRoute();return;diff --git a/web/dist/peach-ui.js b/web/dist/peach-ui.jsindex ee3a1e070..cf7639203 100644--- a/web/dist/peach-ui.js+++ b/web/dist/peach-ui.js@@ -960,15 +960,35 @@ function Ct(e) {});}//#endregion+//#region src/sidebar.ts+function wt(e) {+ return [+ "/",+ "/unseen",+ "/watch-later",+ "/flagged",+ "/trash",+ "/junk-files"+ ].includes(e) || /^\/(item|mix|parts|editions)\//.test(e) || /^\/playlists\/\d+\/\d+$/.test(e) || /^\/(performers|studios|creators|series|agencies)\/.+/.test(e);+}+function Tt(e, t) {+ return e.dataset.surface === t && e.querySelector(".dnav") ? !1 : (e.dataset.surface = t, e.replaceChildren(), !0);+}+function Et(e) {+ let t = /* @__PURE__ */ new Map();+ for (let n of e) for (let e of new Set(n.tags || [])) t.set(e, (t.get(e) || 0) + 1);+ return [...t].sort((e, t) => t[1] - e[1]).slice(0, 30);+}+//#endregion//#region src/islands.ts-var wt = { "quality-goals": {+var Dt = { "quality-goals": {load: gt,component: vt-} }, Tt = () => Object.keys(wt), $ = /* @__PURE__ */ new Map();-async function Et(e, t, n, r = {}) {- let i = wt[e];+} }, Ot = () => Object.keys(Dt), $ = /* @__PURE__ */ new Map();+async function kt(e, t, n, r = {}) {+ let i = Dt[e];if (!i) throw Error(`未注册的 island:${String(e)}`);- Dt(t);+ At(t);let a = {controller: new AbortController(),painted: !1@@ -998,9 +1018,9 @@ async function Et(e, t, n, r = {}) {}), t);}}-function Dt(e) {+function At(e) {let t = $.get(e);t && (t.controller.abort(), $.delete(e), t.painted && _e(null, e));}//#endregion-export { Ct as followJobProgress, Tt as islandNames, Et as mountIsland, xt as refreshStore, bt as storeNames, Dt as unmountIsland, St as watchJob };+export { Ct as followJobProgress, Ot as islandNames, kt as mountIsland, xt as refreshStore, wt as sidebarHasCatalogContent, Et as sidebarTagCounts, bt as storeNames, Tt as syncSidebarSurface, At as unmountIsland, St as watchJob };