Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

perf: bound collection rendering and entity queries

Peach local maintenanceb4214aebc853
diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md
index 584c73239..85d8c9790 100644
--- a/docs/HANDOFF.md
+++ b/docs/HANDOFF.md
@@ -143,6 +143,15 @@ Claude 的 `.claude/settings.json` 已配置 Stop、StopFailure、SessionEnd hoo
- `/tags` 是独立标签管理页,默认字母表模式,也可切换标签云;两种模式都显示数量并进入首页组合筛选。
- 高潮按钮复用 Health Icons 官方 `outline-24px/contraceptives/sperm.svg`,来源 `resolvetosavelives/healthicons`,CC0。一般操作继续使用本地 Lucide 子集。
+## Web 性能边界
+
+- 页面不得按结果总数一次构建全部卡片。首页每批 60、短片栏 18、相关推荐 20、沉浸队列 60、实体作品 48、艺人索引 120、标签索引 180;疑似广告候选可在服务端统一评分,但浏览器每次只追加 60 张卡片。
+- 实体页的总数只用于标题和首批分页判断,第二页起请求使用 `count=0`,通过多取一条判断是否还有下一页,不得重复执行全量 `COUNT(*)`。首页无限滚动同样只在首批计算总数。
+- `q_tops`、艺人索引和实体关联艺人的代表图必须使用单条相关子查询取得,禁止按每个人物再发一次 SQL 的 N+1 实现。
+- 首页聚合数据在浏览器会话中合并并缓存 30 秒;相邻筛选复用同一进行中的请求。首页、顶部聚合、索引和实体页都有请求序号,迟到的旧响应不得覆盖新状态或再次重建 DOM。
+- 无限滚动同一时间只允许一个追加请求;先判断加载锁再递增 offset,避免快速触发时跳页。图片继续使用原生 `loading=lazy`,hover 视频在滚动中必须立即停止并释放 `src`。
+- 2026-08-15 实测:Prestige 显示 248 个总结果时首屏只构建 48 张卡片,点击“载入更多”后为 96;艺人索引 120 条约 311 ms,Prestige 第二页 48 条且跳过总数统计约 94 ms。具体耗时随 ledger 和磁盘状态变化,只把批量边界作为稳定契约。
+
## 恢复入口
项目重构时已从活动目录删除 deprecated 脚本和按日期文档,Git 历史仍可恢复。旧 `_SHARED_STATE` 已迁到 `R:\peach-data\state`。重构前根仓库元数据暂存于 `R:\peach-data\archive\peach-root-repo-backup-20260814`,仅作恢复证据。
diff --git a/src/peach/__init__.py b/src/peach/__init__.py
index 6ae9265fb..37cef4ddd 100644
--- a/src/peach/__init__.py
+++ b/src/peach/__init__.py
@@ -1,3 +1,3 @@
"""Peach application package."""
-__version__ = "0.5.2"
+__version__ = "0.5.3"
diff --git a/src/peach/web_contract.py b/src/peach/web_contract.py
index 1bc2b4b16..fc7427a30 100644
--- a/src/peach/web_contract.py
+++ b/src/peach/web_contract.py
@@ -180,6 +180,8 @@ def q_items(contract: WebContract, args):
order = "a.id DESC"
lim = min(int(args.get("limit", 60)), 200)
off = int(args.get("offset", 0))
+ include_total = args.get("count", "1") != "0"
+ fetch_limit = lim if include_total else lim + 1
sql = ("SELECT a.id,a.location,a.path,a.name,a.creator,a.studio,a.code,a.size,"
"a.duration,a.width,a.height,a.ctx_length,a.ctx_orient,a.snapshot_path,"
"a.play_count,a.leave_ratio,a.feedback,a.disposal,a.rating,a.o_count,"
@@ -188,8 +190,11 @@ def q_items(contract: WebContract, args):
"AND w.profile_id='local-default') AS watch_later "
"FROM asset a WHERE " + " AND ".join(where) + f" ORDER BY {order} LIMIT ? OFFSET ?")
c = contract.db()
- rows = [dict(r) for r in c.execute(sql, par + [lim, off])]
- cnt = c.execute("SELECT count(*) FROM asset a WHERE " + " AND ".join(where), par).fetchone()[0]
+ rows = [dict(r) for r in c.execute(sql, par + [fetch_limit, off])]
+ has_more = len(rows) > lim if not include_total else None
+ rows = rows[:lim]
+ cnt = (c.execute("SELECT count(*) FROM asset a WHERE " + " AND ".join(where), par).fetchone()[0]
+ if include_total else None)
c.close()
# 卡片要显示出镜者和高权重标签,不能只有番号 —— 一次批量取,别 N+1
if rows:
@@ -223,7 +228,7 @@ def q_items(contract: WebContract, args):
r["has_thumb"] = contract.has_snapshot(r["snapshot_path"])
r.pop("snapshot_path", None)
r.pop("path", None) # 路径不外发,串流走 id
- return {"total": cnt, "items": rows}
+ return {"total": cnt, "items": rows, "has_more": has_more}
def con_tags(contract: WebContract, ids, qm):
c = contract.db()
@@ -327,7 +332,7 @@ def q_item(contract: WebContract, aid):
return d
# ── 标签语义分级 ──
-LENGTH_TAGS = {"短片-2分内", "中片-10分内", "长片-30分内", "超长片"}
+LENGTH_TAGS = {"短片-2分内", "中片-10分内", "长片-30分内", "超长片-30分上"}
TECH_TAGS = {"1080P", "720P", "4K", "2K", "2160P", "480P", "低画质", "高帧率",
"横屏", "竖屏",
"真人", "混合集", "身份待确认", "R-18", "有码", "无码"}
@@ -345,7 +350,7 @@ def tag_cat(t):
if re.search(r"(ちゃん|さん|酱|娘)$", t) and len(t) <= 8: return "character"
return "general"
-def q_ads(contract: WebContract, limit=200):
+def q_ads(contract: WebContract, limit=200, offset=0):
"""疑似广告复核队列 —— **不自动删**,只排队让人看接触印相确认。
没有可靠的单一判据(试过「同番号短版」会误伤 CD2/part1 分卷,
@@ -387,7 +392,7 @@ def q_ads(contract: WebContract, limit=200):
out.append(d)
c.close()
out.sort(key=lambda x: (-x["score"], -(x["size"] or 0)))
- items = out[:limit]
+ items = out[offset:offset + limit]
attach_card_performers(contract, items)
return {"total": len(out), "items": items}
@@ -454,30 +459,23 @@ def q_tops(contract: WebContract, n=28):
缓存的人物肖像由前端优先使用;缺失时才回退到代表作接触印相裁切。"""
c = contract.db()
- def rep(entity_id):
- r = c.execute(
- "SELECT a.id FROM asset_entity ae JOIN asset a ON a.id=ae.asset_id "
- "WHERE ae.entity_id=? AND a.medium='video' AND a.snapshot_path IS NOT NULL "
- "ORDER BY (a.play_count IS NULL), a.size DESC LIMIT 1", (entity_id,),
- ).fetchone()
- return r[0] if r else None
+ base = (
+ "SELECT e.id,e.canonical_name,count(DISTINCT ae.asset_id) n,"
+ "(SELECT a2.id FROM asset_entity ae2 JOIN asset a2 ON a2.id=ae2.asset_id "
+ " WHERE ae2.entity_id=e.id AND a2.medium='video' AND a2.snapshot_path IS NOT NULL "
+ " ORDER BY (a2.play_count IS NULL),a2.size DESC LIMIT 1) rep "
+ "FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "
+ "JOIN asset a ON a.id=ae.asset_id "
+ "WHERE a.medium='video' AND e.kind=? "
+ "GROUP BY e.id,e.canonical_name ORDER BY n DESC LIMIT ?"
+ )
out = {}
out["performers"] = []
- for entity_id, k, cnt in c.execute(
- "SELECT e.id,e.canonical_name,count(DISTINCT ae.asset_id) n "
- "FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "
- "JOIN asset a ON a.id=ae.asset_id "
- "WHERE a.medium='video' AND e.kind='performer' "
- "GROUP BY e.id,e.canonical_name ORDER BY n DESC LIMIT ?", (n,)):
- out["performers"].append({"id": entity_id, "k": k, "n": cnt, "rep": rep(entity_id)})
+ for entity_id, k, cnt, representative in c.execute(base, ("performer", n)):
+ out["performers"].append({"id": entity_id, "k": k, "n": cnt, "rep": representative})
out["studios"] = []
- for entity_id, k, cnt in c.execute(
- "SELECT e.id,e.canonical_name,count(DISTINCT ae.asset_id) n "
- "FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "
- "JOIN asset a ON a.id=ae.asset_id "
- "WHERE a.medium='video' AND e.kind='studio' "
- "GROUP BY e.id,e.canonical_name ORDER BY n DESC LIMIT ?", (n,)):
- out["studios"].append({"id": entity_id, "k": k, "n": cnt, "rep": rep(entity_id)})
+ for entity_id, k, cnt, representative in c.execute(base, ("studio", n)):
+ out["studios"].append({"id": entity_id, "k": k, "n": cnt, "rep": representative})
c.close()
return out
@@ -556,16 +554,20 @@ def q_entity(contract: WebContract, args):
"JOIN entity tag ON tag.id=tagged.entity_id "
"JOIN asset a ON a.id=scope.asset_id "
"WHERE scope.entity_id=? AND a.medium='video' AND tag.kind='tag' "
- "AND tag.canonical_name NOT IN ('短片-2分内','中片-10分内','长片-30分内','超长片') "
+ f"AND tag.canonical_name NOT IN ({','.join('?' for _ in LENGTH_TAGS)}) "
"AND NOT EXISTS(SELECT 1 FROM asset_tag_preference p "
" WHERE p.asset_id=scope.asset_id AND p.profile_id='local-default' "
" AND p.hidden=1 AND p.normalized_tag=tag.normalized_name) "
"GROUP BY tag.id,tag.canonical_name ORDER BY n DESC,tag.canonical_name LIMIT 36",
- (d["id"],),
+ (d["id"], *sorted(LENGTH_TAGS)),
)]
related = []
for performer in c.execute(
- "SELECT person.id,person.canonical_name k,count(DISTINCT scope.asset_id) n "
+ "SELECT person.id,person.canonical_name k,count(DISTINCT scope.asset_id) n,"
+ "(SELECT a2.id FROM asset_entity ae2 JOIN asset a2 ON a2.id=ae2.asset_id "
+ " WHERE ae2.entity_id=person.id AND a2.medium='video' AND a2.snapshot_path IS NOT NULL "
+ " ORDER BY COALESCE(a2.play_count,0) DESC,COALESCE(a2.play_seconds,0) DESC,"
+ " COALESCE(a2.width,0)*COALESCE(a2.height,0) DESC,a2.size DESC LIMIT 1) rep "
"FROM asset_entity scope "
"JOIN asset_entity co ON co.asset_id=scope.asset_id "
"JOIN entity person ON person.id=co.entity_id "
@@ -575,55 +577,49 @@ def q_entity(contract: WebContract, args):
"GROUP BY person.id,person.canonical_name ORDER BY n DESC,person.canonical_name LIMIT 18",
(d["id"], d["id"]),
):
- item = dict(performer)
- representative = c.execute(
- "SELECT a.id FROM asset_entity ae JOIN asset a ON a.id=ae.asset_id "
- "WHERE ae.entity_id=? AND a.medium='video' AND a.snapshot_path IS NOT NULL "
- "ORDER BY COALESCE(a.play_count,0) DESC,COALESCE(a.play_seconds,0) DESC,"
- "COALESCE(a.width,0)*COALESCE(a.height,0) DESC,a.size DESC LIMIT 1",
- (item["id"],),
- ).fetchone()
- item["rep"] = representative[0] if representative else None
- related.append(item)
+ related.append(dict(performer))
d["related_performers"] = related
c.close()
return d
-def q_index(contract: WebContract, kind, q="", limit=600):
+def q_index(contract: WebContract, kind, q="", limit=600, offset=0, category=""):
"""全部艺人 / 创作者 / 标签的索引页数据。"""
c = contract.db()
if kind in {"creators", "performers"}:
entity_kind = "creator" if kind == "creators" else "performer"
- sql = ("SELECT e.id entity_id,e.canonical_name k,count(DISTINCT ae.asset_id) n "
+ sql = ("SELECT e.id entity_id,e.canonical_name k,count(DISTINCT ae.asset_id) n,"
+ "(SELECT a2.id FROM asset_entity ae2 JOIN asset a2 ON a2.id=ae2.asset_id "
+ " WHERE ae2.entity_id=e.id AND a2.medium='video' AND a2.snapshot_path IS NOT NULL "
+ " ORDER BY COALESCE(a2.play_count,0) DESC,COALESCE(a2.play_seconds,0) DESC,"
+ " COALESCE(a2.width,0)*COALESCE(a2.height,0) DESC,a2.size DESC LIMIT 1) rep "
"FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "
"JOIN asset a ON a.id=ae.asset_id "
"WHERE a.medium='video' AND e.kind=? ")
par = [entity_kind]
if q: sql += "AND e.canonical_name LIKE ? "; par.append(f"%{q}%")
- sql += "GROUP BY e.id,e.canonical_name ORDER BY n DESC LIMIT ?"; par.append(limit)
+ sql += "GROUP BY e.id,e.canonical_name ORDER BY n DESC LIMIT ? OFFSET ?"
+ par.extend((limit + 1, offset))
rows = [dict(r) for r in c.execute(sql, par)]
- for r in rows:
- g = c.execute(
- "SELECT a.id FROM asset_entity ae JOIN asset a ON a.id=ae.asset_id "
- "WHERE ae.entity_id=? AND a.medium='video' AND a.snapshot_path IS NOT NULL "
- "ORDER BY COALESCE(a.play_count,0) DESC,COALESCE(a.play_seconds,0) DESC,"
- "COALESCE(a.width,0)*COALESCE(a.height,0) DESC,a.size DESC LIMIT 1",
- (r["entity_id"],),
- ).fetchone()
- r["rep"] = g[0] if g else None
+ has_more = len(rows) > limit
+ rows = rows[:limit]
else:
sql = ("SELECT e.canonical_name k, count(DISTINCT ae.asset_id) n "
"FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "
"JOIN asset a ON a.id=ae.asset_id WHERE a.medium='video' AND e.kind='tag' "
+ f"AND e.canonical_name NOT IN ({','.join('?' for _ in LENGTH_TAGS)}) "
"AND NOT EXISTS(SELECT 1 FROM asset_tag_preference p "
"WHERE p.asset_id=ae.asset_id AND p.profile_id='local-default' "
"AND p.hidden=1 AND p.normalized_tag=e.normalized_name) ")
- par = []
+ par = sorted(LENGTH_TAGS)
if q: sql += "AND e.canonical_name LIKE ? "; par.append(f"%{q}%")
- sql += "GROUP BY e.id,e.canonical_name ORDER BY n DESC LIMIT ?"; par.append(limit)
- rows = [dict(r, cat=tag_cat(r["k"])) for r in c.execute(sql, par)]
+ sql += "GROUP BY e.id,e.canonical_name ORDER BY n DESC"
+ all_rows = [dict(r, cat=tag_cat(r["k"])) for r in c.execute(sql, par)]
+ if category and category != "all":
+ all_rows = [row for row in all_rows if row["cat"] == category]
+ rows = all_rows[offset:offset + limit]
+ has_more = offset + limit < len(all_rows)
c.close()
- return {"kind": kind, "items": rows}
+ return {"kind": kind, "items": rows, "has_more": has_more}
def q_stats(contract: WebContract):
"""统计页:库存 / 归属 / 标签 / 消费 / 磁盘。原来挤在顶栏右上角,信息量太小又碍眼。"""
@@ -955,14 +951,25 @@ def dispatch_api_get(contract: WebContract, path, args):
if path == "/api/entity":
return q_entity(contract, args)
if path == "/api/index":
- return q_index(contract, args.get("kind", "tags"), args.get("q", ""))
+ return q_index(
+ contract,
+ args.get("kind", "tags"),
+ args.get("q", ""),
+ min(max(int(args.get("limit", "180")), 1), 600),
+ max(int(args.get("offset", "0")), 0),
+ args.get("category", ""),
+ )
if path == "/api/stats":
return contract.cached("stats", lambda: q_stats(contract))
if path == "/api/tops":
n = min(int(args.get("n", "28")), 60)
return contract.cached(f"tops{n}", lambda: q_tops(contract, n))
if path == "/api/ads":
- return q_ads(contract, min(int(args.get("limit", "200")), 400))
+ return q_ads(
+ contract,
+ min(int(args.get("limit", "60")), 200),
+ max(int(args.get("offset", "0")), 0),
+ )
if path == "/api/related":
return q_related(contract, int(args["id"]), min(int(args.get("limit", "24")), 60))
if path == "/api/facets":
diff --git a/tests/test_rm_web.py b/tests/test_rm_web.py
index 9171ad798..ade7bd5e2 100644
--- a/tests/test_rm_web.py
+++ b/tests/test_rm_web.py
@@ -151,6 +151,14 @@ class WebDataTests(unittest.TestCase):
)
self.assertEqual([item["id"] for item in result["items"]], [1])
+ def test_items_can_skip_repeated_total_count_on_later_pages(self):
+ result = rm_web.q_items(
+ self.contract, {"limit": "1", "offset": "0", "count": "0"},
+ )
+ self.assertIsNone(result["total"])
+ self.assertEqual(len(result["items"]), 1)
+ self.assertTrue(result["has_more"])
+
def test_legacy_length_tags_are_hidden_in_favor_of_numeric_minutes(self):
con = sqlite3.connect(self.db_path)
con.execute(
@@ -160,11 +168,25 @@ class WebDataTests(unittest.TestCase):
"INSERT INTO asset_entity(asset_id,entity_id,role,source,confidence) "
"VALUES(1,14,'tag','test',1.0)"
)
+ con.execute(
+ "INSERT INTO entity(id,kind,canonical_name,normalized_name) VALUES(15,'tag','测试分页标签','测试分页标签')"
+ )
+ con.execute(
+ "INSERT INTO asset_entity(asset_id,entity_id,role,source,confidence) "
+ "VALUES(1,15,'tag','test',1.0)"
+ )
con.commit(); con.close()
self.assertNotIn("短片-2分内", [tag["k"] for tag in rm_web.q_item(self.contract, 1)["tags"]])
facets = rm_web.q_facets(self.contract)
visible = {row["k"] for row in facets["tags"] + facets["tech"]}
self.assertNotIn("短片-2分内", visible)
+ index = rm_web.q_index(self.contract, "tags")
+ self.assertNotIn("短片-2分内", {row["k"] for row in index["items"]})
+ self.assertIn("超长片-30分上", rm_web.LENGTH_TAGS)
+ first_page = rm_web.q_index(self.contract, "tags", limit=1)
+ second_page = rm_web.q_index(self.contract, "tags", limit=1, offset=1)
+ self.assertTrue(first_page["has_more"])
+ self.assertNotEqual(first_page["items"][0]["k"], second_page["items"][0]["k"])
def test_activity_accumulates_real_play_time_and_max_position(self):
first = rm_web.w_activity(self.contract, {
diff --git a/tests/test_web_ui.py b/tests/test_web_ui.py
index b488d1dd0..8b567d5b2 100644
--- a/tests/test_web_ui.py
+++ b/tests/test_web_ui.py
@@ -82,13 +82,37 @@ class WebUiSourceTests(unittest.TestCase):
def test_entity_tags_filter_inside_the_current_entity_page(self):
self.assertIn("if(entityTag)p.set('tag',entityTag)", self.page)
- self.assertIn("openEntity(kind,name,true,next)", self.page)
- self.assertIn("wireCards($('#index'),undefined,tag=>openEntity(kind,name,true", self.page)
+ self.assertIn("async function updateEntityCollection", self.page)
+ self.assertIn("updateEntityCollection(kind,name,next,true)", self.page)
+ self.assertIn("renderEntityCollection(kind,name,items,entityTag)", self.page)
+ self.assertNotIn("openEntity(kind,name,true,next)", self.page)
self.assertNotIn(
"document.body.classList.remove('entity-open');$('#index').hidden=true;state.tag=b.dataset.entityTag",
self.page,
)
+ def test_large_collections_render_in_bounded_batches(self):
+ self.assertIn("p.set('limit','48')", self.page)
+ self.assertIn("if(offset)p.set('count','0')", self.page)
+ self.assertIn('class="entitymore"', self.page)
+ self.assertIn("const indexLimit=people?120:180", self.page)
+ self.assertIn('class="indexmore"', self.page)
+ self.assertIn("adsBatch.items.slice(offset,offset+60)", self.page)
+ self.assertIn("if(!reset)p.set('count','0')", self.page)
+ self.assertIn("!listLoading&&!$('#loadSentinel').hidden", self.page)
+ self.assertIn("indexRequestSeq", self.page)
+ self.assertIn("barsRequestSeq", self.page)
+ self.assertIn("async function getBarsData()", self.page)
+ self.assertIn("Date.now()-barsDataAt<30000", self.page)
+ self.assertNotIn("p.set('limit','120')", self.page)
+
+ def test_entity_profile_uses_logo_links_without_a_redundant_back_row(self):
+ self.assertIn("const faviconUrl=url=>", self.page)
+ self.assertIn('class="entitylinkicon"', self.page)
+ self.assertIn('class="entitylinklabel"', self.page)
+ self.assertIn("img.dataset.studio&&!img.dataset.fallback", self.page)
+ self.assertNotIn('<span class="mono" style="color:var(--muted)">${labels[kind]||kind}资料页</span>', self.page)
+
def test_status_tags_are_separated_and_nonessential_states_are_hidden(self):
self.assertIn(".sep{flex:none;width:1px;height:19px", self.page)
self.assertIn("{k:'later',label:'稍后看'},{k:'flagged',label:'已标记'}", self.page)
@@ -105,6 +129,15 @@ class WebUiSourceTests(unittest.TestCase):
self.assertIn('data-tag-view="cloud"', self.page)
self.assertIn('data-tag-view="alphabet"', self.page)
self.assertIn('class="alphabet"', self.page)
+ self.assertIn('data-tag-category=', self.page)
+ self.assertIn("['general','内容']", self.page)
+ self.assertIn("['artist','人物']", self.page)
+ self.assertIn("category=params.get('category')", self.page)
+
+ def test_secondary_back_controls_are_icon_only(self):
+ self.assertIn('id="i-arrow-left"', self.page)
+ self.assertIn("${icon('arrow-left')}</button>", self.page)
+ self.assertNotIn("${icon('chevron-left')}<span>返回</span>", self.page)
def test_climax_uses_pinned_healthicons_symbol(self):
self.assertIn('id="i-sperm"', self.page)
diff --git a/web/index.html b/web/index.html
index b0da53029..1b608bd6b 100644
--- a/web/index.html
+++ b/web/index.html
@@ -179,16 +179,15 @@ button,input,textarea{font:inherit;color:inherit}
.big{font-size:30px;font-weight:600;font-variant-numeric:tabular-nums;line-height:1.1}
.bigsub{color:var(--muted);font-size:12px;margin-top:3px}
/* 索引页:全部创作者 / 全部标签 */
-.index{padding:4px 0 20px}
+.index{padding:4px 0 20px;min-width:0;max-width:100%;overflow-x:clip}
.index .ihead{display:flex;align-items:center;gap:12px;margin-bottom:14px}
-.index .ihead h2{margin:0;font-size:20px}
+.index .ihead h2{margin:0;font-size:20px;font-weight:500}
.index .ihead .isearch{margin-left:auto}
-.backbtn{width:auto;min-width:92px;height:40px;padding:0 14px;border:1px solid var(--line);
- border-radius:8px;background:var(--surface);display:inline-flex;align-items:center;
- justify-content:center;gap:8px;cursor:pointer;color:var(--ink-2);white-space:nowrap;line-height:1}
-.backbtn svg{width:18px;height:18px;stroke:currentColor;fill:none;stroke-width:2;
+.backbtn{width:42px;height:42px;padding:0;border:0;border-radius:12px;background:transparent;
+ display:inline-grid;place-items:center;cursor:pointer;color:var(--ink-2);line-height:1;flex:none}
+.backbtn svg{width:26px;height:26px;stroke:currentColor;fill:none;stroke-width:1.7;
stroke-linecap:round;stroke-linejoin:round;flex:none}
-.backbtn:hover{border-color:var(--ink-2);color:var(--ink);background:var(--hover)}
+.backbtn:hover{color:var(--ink);background:var(--hover);transform:translateX(-2px)}
.index .isearch{flex:1;max-width:320px;background:var(--sunk);border:1px solid var(--line);
border-radius:18px;padding:6px 14px}
.index .isearch input{background:none;border:0;outline:none;width:100%}
@@ -207,29 +206,56 @@ button,input,textarea{font:inherit;color:inherit}
.tagmodes{display:flex;gap:4px;padding:3px;border:1px solid var(--line-soft);border-radius:10px;background:var(--surface)}
.tagmodes button{border:0;border-radius:7px;background:transparent;color:var(--muted);padding:6px 10px;cursor:pointer}
.tagmodes button[aria-pressed="true"]{background:var(--hover);color:var(--ink)}
+.tagfilters{display:flex;gap:6px;flex-wrap:wrap;margin:0 0 18px}
+.tagfilters button{height:34px;padding:0 13px;border-radius:999px;border:1px solid var(--line-soft);
+ background:transparent;color:var(--muted);cursor:pointer;display:inline-flex;align-items:center;gap:7px}
+.tagfilters button::before,.alphatag::before{content:"";width:7px;height:7px;border-radius:50%;
+ background:var(--tag-color,var(--muted));flex:none}
+.tagfilters button[aria-pressed="true"]{color:var(--ink);border-color:color-mix(in srgb,var(--tag-color,var(--ink)) 45%,transparent);
+ background:color-mix(in srgb,var(--tag-color,var(--ink)) 12%,transparent)}
+.tagfilters .all::before{background:linear-gradient(135deg,#55A7FF,#D783FF)}
+.index-tags .tg,.alphatag{--tag-color:#7A91A8}
+.index-tags .tg.general,.alphatag.general,.tagfilters .general{--tag-color:#55A7FF}
+.index-tags .tg.artist,.alphatag.artist,.tagfilters .artist{--tag-color:#F1A454}
+.index-tags .tg.character,.alphatag.character,.tagfilters .character{--tag-color:#ED78AF}
+.index-tags .tg.copyright,.alphatag.copyright,.tagfilters .copyright{--tag-color:#A989F5}
+.index-tags .tg.meta,.alphatag.meta,.tagfilters .meta{--tag-color:#7F909E}
+.index .index-tags .tg{border-color:color-mix(in srgb,var(--tag-color) 32%,transparent);color:var(--ink-2);
+ background:color-mix(in srgb,var(--tag-color) 7%,transparent)}
+.index .index-tags .tg:hover{border-color:color-mix(in srgb,var(--tag-color) 62%,transparent);
+ background:color-mix(in srgb,var(--tag-color) 13%,transparent)}
.alphabet{display:grid;gap:22px}.alphagroup{border-top:1px solid var(--line-soft);padding-top:14px}
.alphagroup:first-child{border-top:0}.alphagroup h3{margin:0 0 10px;font-size:18px;color:var(--ink-2)}
.alphalist{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:5px 18px}
-.alphatag{display:flex;align-items:center;justify-content:space-between;gap:9px;border:0;background:transparent;
+.alphatag{display:flex;align-items:center;justify-content:flex-start;gap:9px;border:0;background:transparent;
color:var(--ink-2);padding:7px 8px;border-radius:6px;text-align:left;cursor:pointer;min-width:0}
-.alphatag:hover{background:var(--hover);color:var(--ink)}.alphatag span:first-child{overflow:hidden;text-overflow:ellipsis}
+.alphatag:hover{background:color-mix(in srgb,var(--tag-color) 9%,transparent);color:var(--ink)}.alphatag span:first-of-type{overflow:hidden;text-overflow:ellipsis;flex:1}
.alphatag .n{color:var(--muted);font-size:12px;flex:none}
.entityhero{display:grid;grid-template-columns:160px minmax(0,1fr);gap:24px;padding:10px 0 24px;
- border:0;background:transparent;margin-bottom:0;align-items:center}
+ border:0;background:transparent;margin-bottom:0;align-items:center;min-width:0;max-width:100%}
.entityportrait{width:160px;aspect-ratio:1;border-radius:50%;overflow:hidden;background:var(--overlay-5);
- display:grid;place-items:center;font-size:48px;color:var(--muted)}
+ display:grid;place-items:center;font-size:48px;color:var(--muted);max-width:100%}
.entityportrait.square{border-radius:18px}.entityportrait img,.entityportrait>span{grid-area:1/1}
.entityportrait img{width:100%;height:100%;object-fit:cover;display:block;z-index:1}
-.entityhero h2{font-size:27px;margin:0 0 5px}.entityhero .alias{color:var(--muted);margin-bottom:14px}
-.entitysummary{line-height:1.75;max-width:820px}.entitylinks{display:flex;flex-wrap:wrap;gap:7px;margin-top:15px}
-.entitylinks a,.entitylinks span{border:1px solid var(--line);border-radius:7px;padding:6px 10px;
- font-size:12px;text-decoration:none;color:var(--ink)}
-.entitylinks a:hover{border-color:var(--tungsten);color:var(--tungsten)}
+.entityhero>div:last-child{min-width:0;max-width:100%}.entityhero h2{font-size:30px;font-weight:400;
+ line-height:1.2;letter-spacing:0;margin:0 0 9px;overflow-wrap:anywhere}.entityhero .alias{color:var(--muted);
+ font-size:14px;line-height:1.45;margin-bottom:14px;overflow-wrap:anywhere}
+.entitysummary{font-size:15px;line-height:1.6;max-width:820px;color:var(--ink-2)}
+.entitylinks{display:flex;flex-wrap:wrap;gap:8px;margin-top:17px;max-width:100%}
+.entitylinks a,.entitylinks .private{min-width:0;max-width:100%;min-height:40px;border:1px solid var(--border-10);
+ border-radius:999px;padding:4px 12px 4px 4px;font-size:13px;text-decoration:none;color:var(--ink);
+ background:var(--overlay-5);display:inline-flex;align-items:center;gap:8px;overflow:hidden}
+.entitylinks a:hover{border-color:var(--border-15);background:var(--hover)}
.entitylinks .private{color:var(--muted);border-style:dashed}
+.entitylinkicon{width:32px;height:32px;border-radius:50%;background:var(--sunk);display:grid;place-items:center;
+ overflow:hidden;position:relative;flex:none}.entitylinkicon svg{width:16px;height:16px;stroke:currentColor;fill:none;
+ stroke-width:1.8}.entitylinkicon img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover;background:#fff}
+.entitylinklabel{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.entitylinkarrow{color:var(--muted);flex:none}
.entityterms{margin-top:13px;color:var(--muted);font-size:12px}.entityterms code{color:var(--ink-2);margin-right:8px}
-.entitymeta{display:grid;gap:22px;margin:0 0 28px}.entitymeta h3,.entitysection h3{font-size:13px;letter-spacing:.08em;color:var(--muted);margin:0 0 12px}
+.entitymeta{display:grid;gap:22px;margin:0 0 28px;min-width:0}.entitymeta section{min-width:0}.entitymeta h3,.entitysection h3{font-size:13px;letter-spacing:.08em;color:var(--muted);margin:0 0 12px}
.entitytags{display:flex;flex-wrap:wrap;gap:7px}.entitytags button{height:34px;padding:0 14px;border-radius:999px;
- border:1px solid var(--border-15);background:transparent;color:var(--ink-2);cursor:pointer}
+ border:1px solid var(--border-15);background:transparent;color:var(--ink-2);cursor:pointer;max-width:100%;
+ overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.entitytags button:hover{background:var(--overlay-5);color:var(--ink)}.entitytags button[aria-pressed="true"]{background:var(--ink-2);border-color:var(--ink-2);color:var(--ground)}.entitytags small{color:var(--muted);margin-left:4px}
.relatedpeople{display:flex;gap:14px;overflow-x:auto;padding-bottom:4px;scrollbar-width:none}
.relatedpeople::-webkit-scrollbar{display:none}.relatedperson{flex:0 0 78px;border:0;background:transparent;color:inherit;
@@ -238,7 +264,11 @@ button,input,textarea{font:inherit;color:inherit}
.relatedperson img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}.relatedperson .nm{display:block;
overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12px}.relatedperson small{color:var(--muted);font-size:10px}
.relatedperson:hover .ring{box-shadow:0 0 0 1px var(--border-15)}
-.entitysection h3{font-size:13px;letter-spacing:.08em;color:var(--muted);margin:0 0 12px}
+.entitysection{min-width:0;max-width:100%}.entitysection h3{font-size:13px;letter-spacing:.08em;color:var(--muted);margin:0 0 12px}
+.indexmore,.entitymore{display:flex;align-items:center;justify-content:center;margin:20px auto 0;min-width:124px;
+ min-height:40px;padding:8px 16px;border:1px solid var(--border-15);border-radius:999px;background:transparent;
+ color:var(--ink-2);cursor:pointer}.indexmore:hover,.entitymore:hover{background:var(--overlay-5);color:var(--ink)}
+.indexmore:disabled,.entitymore:disabled{opacity:.5;cursor:wait}
.entitylink{border:0;background:none;padding:0;color:var(--tungsten);cursor:pointer;text-decoration:none}
.entitylink:hover{text-decoration:underline}
@@ -615,7 +645,7 @@ body.drawer-open .edge{opacity:0;pointer-events:none} /* 展开时窄栏让位
#searchBtn{display:inline-flex!important}
/* 移动端不需要密度切换和筛选抽屉按钮挤在一起 */
#density{display:none}
- .entityhero{grid-template-columns:92px minmax(0,1fr);gap:14px;padding:13px}
+ .entityhero{grid-template-columns:92px minmax(0,1fr);gap:14px;padding:8px 0 18px}
.entityportrait{width:92px}.entityhero h2{font-size:20px}
.statshead{align-items:center}.stats h2{font-size:23px}.scards{grid-template-columns:minmax(0,1fr)}
.scard2{padding:16px}.kv .u{display:block;margin-left:0;margin-top:2px}
@@ -652,6 +682,7 @@ body.drawer-open .edge{opacity:0;pointer-events:none} /* 展开时窄栏让位
<symbol id="i-rotate-cw" viewBox="0 0 24 24"><path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/></symbol>
<symbol id="i-maximize" viewBox="0 0 24 24"><path d="M8 3H5a2 2 0 0 0-2 2v3"/><path d="M21 8V5a2 2 0 0 0-2-2h-3"/><path d="M3 16v3a2 2 0 0 0 2 2h3"/><path d="M16 21h3a2 2 0 0 0 2-2v-3"/></symbol>
<symbol id="i-chevron-left" viewBox="0 0 24 24"><path d="m15 18-6-6 6-6"/></symbol>
+ <symbol id="i-arrow-left" viewBox="0 0 24 24"><path d="m12 19-7-7 7-7"/><path d="M19 12H5"/></symbol>
<symbol id="i-heart" viewBox="0 0 24 24"><path d="M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5"/></symbol>
<symbol id="i-play" viewBox="0 0 24 24"><path d="M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"/></symbol>
<symbol id="i-clock" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></symbol>
@@ -721,12 +752,13 @@ const ENTITY_ROUTES={performer:'performers',studio:'studios',creator:'creators',
const ROUTE_ENTITIES={performers:'performer',studios:'studio',creators:'creator',series:'series'};
const entityPath=(kind,name)=>`/${ENTITY_ROUTES[kind]||kind}/${encodeURIComponent(name)}`;
const esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
+const faviconUrl=url=>{try{return new URL('/favicon.ico',url).href}catch{return ''}};
const foldName=s=>String(s??'').normalize('NFKC').trim().toLocaleLowerCase();
const fmtDur=s=>{if(!s)return'—';s=Math.round(s);const h=s/3600|0,m=(s%3600)/60|0,x=s%60;
return h?`${h}:${String(m).padStart(2,'0')}:${String(x).padStart(2,'0')}`:`${m}:${String(x).padStart(2,'0')}`};
const fmtSize=b=>b>=1099511627776?(b/1099511627776).toFixed(2)+' TB':b>=1073741824?(b/1073741824).toFixed(1)+' GB':(b/1048576|0)+' MB';
const LOC={local:'本地','115':'115',pikpak:'PikPak',online:'在线'};
-const DURATION_TAGS=new Set(['短片-2分内','中片-10分内','长片-30分内','超长片']);
+const DURATION_TAGS=new Set(['短片-2分内','中片-10分内','长片-30分内','超长片-30分上']);
/* 来源图标:品牌使用已缓存的官方资产;通用操作图标统一使用本地 Lucide 子集。 */
const SRCICON={
local:icon('hard-drive'),
@@ -913,10 +945,20 @@ function wireCards(root,onClick,onTag){
}
/* ── 顶部标签条 + 抽屉 ── */
+let barsRequestSeq=0,barsDataCache=null,barsDataAt=0,barsDataPromise=null;
+async function getBarsData(){
+ if(barsDataCache&&Date.now()-barsDataAt<30000)return barsDataCache;
+ if(!barsDataPromise)barsDataPromise=Promise.all([api('/api/facets'),api('/api/tops?n=30')])
+ .then(data=>{barsDataCache=data;barsDataAt=Date.now();return data})
+ .finally(()=>{barsDataPromise=null});
+ return barsDataPromise
+}
async function buildBars(){
+ const requestSeq=++barsRequestSeq;
// 两个聚合查询互不依赖。冷启动各需约 1 秒,串行会让手机首屏白等;
// 并行取回后再一次性绘制顶部与抽屉。
- const [facetData,tops]=await Promise.all([api('/api/facets'),api('/api/tops?n=30')]);
+ const [facetData,tops]=await getBarsData();
+ if(requestSeq!==barsRequestSeq)return;
facets=facetData; const st=facets.stats;
// 顶部三层:女优圆头像 / 厂牌 / 内容标签
@@ -1081,7 +1123,7 @@ async function openStats(push=true){
const card=(t,body)=>`<div class="scard2"><h3>${t}</h3>${body}</div>`;
const kv=(k,v,u)=>`<div class="kv"><span>${k}</span><b>${v}${u?`<span class="u">${u}</span>`:''}</b></div>`;
$('#stats').innerHTML=`
- <div class="statshead"><button class="backbtn" id="statsBack" title="返回浏览">${icon('chevron-left')}<span>返回</span></button>
+ <div class="statshead"><button class="backbtn" id="statsBack" title="返回浏览" aria-label="返回浏览">${icon('arrow-left')}</button>
<div><h2 class="disp">统计与管理</h2>
</div>
</div>
@@ -1132,85 +1174,141 @@ function closeStats(push=true){if(push)route('/');$('#stats').hidden=true;
$('#tiers').style.display='';$('#tagbar').style.display='';load(true)}
/* ── 全部艺人 / 创作者 / 标签索引页 ── */
-let tagIndexMode='alphabet';
+let tagIndexMode='alphabet',tagIndexCategory='all',indexRequestSeq=0;
+const TAG_CATEGORIES=[['all','全部'],['general','内容'],['artist','人物'],['character','角色'],['copyright','作品'],['meta','规格']];
async function openIndex(kind,q,push=true){
+ const requestSeq=++indexRequestSeq;
document.body.classList.remove('entity-open');
+ delete $('#index').dataset.entityKind;delete $('#index').dataset.entityName;
+ const people=kind==='creators'||kind==='performers';
+ const entityKind=kind==='performers'?'performer':'creator';
+ const indexLimit=people?120:180;
const indexQuery=new URLSearchParams();if(q)indexQuery.set('q',q);
- if(kind==='tags')indexQuery.set('view',tagIndexMode);
+ if(kind==='tags'){
+ indexQuery.set('view',tagIndexMode);
+ if(tagIndexCategory!=='all')indexQuery.set('category',tagIndexCategory)}
if(push)route('/'+kind+(indexQuery.size?'?'+indexQuery:''),!!q);
disposeStage(false);
- const d=await api('/api/index?kind='+kind+(q?'&q='+encodeURIComponent(q):''));
+ const indexApi=offset=>'/api/index?kind='+kind+'&limit='+indexLimit+'&offset='+offset+
+ (q?'&q='+encodeURIComponent(q):'')+
+ (kind==='tags'&&tagIndexCategory!=='all'?'&category='+encodeURIComponent(tagIndexCategory):'');
+ const d=await api(indexApi(0));
+ if(requestSeq!==indexRequestSeq)return;
$('#index').hidden=false; $('#grid').innerHTML=''; $('#count').textContent='';
$('#loadSentinel').hidden=true; $('#shortsSec').hidden=true;
- const people=kind==='creators'||kind==='performers';
- const entityKind=kind==='performers'?'performer':'creator';
- const title=kind==='performers'?'全部艺人':(kind==='creators'?'全部创作者':'全部标签');
- const tagGroups=()=>{
- const groups={};[...d.items].sort((a,b)=>a.k.localeCompare(b.k,'zh-CN',{numeric:true,sensitivity:'base'})).forEach(x=>{
+ const title=kind==='performers'?'艺人':(kind==='creators'?'创作者':'标签');
+ const tagItems=[...d.items];
+ const tagGroups=items=>{
+ const groups={};[...items].sort((a,b)=>a.k.localeCompare(b.k,'zh-CN',{numeric:true,sensitivity:'base'})).forEach(x=>{
const ch=x.k.normalize('NFKC').trim().charAt(0).toUpperCase();
const key=/[A-Z]/.test(ch)?ch:(/[0-9]/.test(ch)?'#':(/[\u3400-\u9fff]/.test(ch)?'中文':'其他'));
(groups[key]||(groups[key]=[])).push(x)});
return Object.entries(groups).sort(([a],[b])=>a.localeCompare(b,'zh-CN')).map(([letter,items])=>
`<section class="alphagroup"><h3>${letter}</h3><div class="alphalist">${items.map(x=>
- `<button class="alphatag" data-k="${esc(x.k)}"><span>${esc(x.k)}</span><span class="n">${x.n.toLocaleString()}</span></button>`).join('')}</div></section>`).join('')};
- const body = people
- ? `<div class="igrid">`+d.items.map(x=>`<button class="icell" data-k="${esc(x.k)}" data-kind="${entityKind}">
+ `<button class="alphatag ${x.cat||'general'}" data-k="${esc(x.k)}"><span>${esc(x.k)}</span><span class="n">${x.n.toLocaleString()}</span></button>`).join('')}</div></section>`).join('')};
+ const peopleHtml=items=>items.map(x=>`<button class="icell" data-k="${esc(x.k)}" data-kind="${entityKind}">
<span class="ring">${kind==='performers'
? `<img src="/entity-image?kind=performer&id=${x.entity_id}" alt="" loading="lazy" onerror="${x.rep?`this.onerror=null;this.src='/avatar?id=${x.rep}'`:`this.remove()`}">`
: (x.rep?`<img src="/avatar?id=${x.rep}" alt="" loading="lazy">`:`<span class="ini">${esc(x.k.slice(0,1))}</span>`)}</span>
- <span class="nm">${esc(x.k)}</span><span class="n">${x.n.toLocaleString()}</span></button>`).join('')+`</div>`
- : tagIndexMode==='alphabet'?`<div class="alphabet">${tagGroups()}</div>`:`<div class="tagwall">`+d.items.map(x=>`<button class="tg ${x.cat||'general'}" data-k="${esc(x.k)}"
+ <span class="nm">${esc(x.k)}</span><span class="n">${x.n.toLocaleString()}</span></button>`).join('');
+ const tagHtml=items=>tagIndexMode==='alphabet'?`<div class="alphabet">${tagGroups(items)}</div>`:`<div class="tagwall index-tags">`+items.map(x=>`<button class="tg ${x.cat||'general'}" data-k="${esc(x.k)}"
style="padding:5px 12px;font-size:13px">${esc(x.k)}
<span style="opacity:.6;font-size:11px">${x.n.toLocaleString()}</span></button>`).join('')+`</div>`;
- $('#index').innerHTML=`<div class="ihead"><button class="backbtn" id="iClose">${icon('chevron-left')}<span>返回</span></button>
+ const body=people?`<div class="igrid">${peopleHtml(d.items)}</div>`:tagHtml(tagItems);
+ const filters=kind==='tags'?`<div class="tagfilters" aria-label="标签类型">${TAG_CATEGORIES.map(([key,label])=>
+ `<button class="${key}" data-tag-category="${key}" aria-pressed="${tagIndexCategory===key}">${label}</button>`).join('')}</div>`:'';
+ $('#index').innerHTML=`<div class="ihead"><button class="backbtn" id="iClose" title="返回浏览" aria-label="返回浏览">${icon('arrow-left')}</button>
<h2 class="disp">${title}</h2>
- <span class="mono" style="color:var(--muted)">${d.items.length} 项</span>
+ <span class="mono" id="indexCount" style="color:var(--muted)">${tagItems.length}${d.has_more?'+':''} 项</span>
${kind==='tags'?`<div class="tagmodes"><button data-tag-view="cloud" aria-pressed="${tagIndexMode==='cloud'}">标签云</button><button data-tag-view="alphabet" aria-pressed="${tagIndexMode==='alphabet'}">字母表</button></div>`:''}
<div class="isearch"><input id="iq" placeholder="过滤…" value="${esc(q||'')}"></div>
- </div>${body}`;
+ </div>${filters}<div id="indexBody">${body}</div><button class="indexmore" id="indexMore" type="button" ${d.has_more?'':'hidden'}>载入更多</button>`;
$('#iClose').onclick=()=>{route('/');$('#index').hidden=true;load(true)};
let it2; $('#iq').oninput=e=>{clearTimeout(it2);it2=setTimeout(()=>openIndex(kind,e.target.value.trim(),true),300)};
$('#index').querySelectorAll('[data-tag-view]').forEach(b=>b.onclick=()=>{
tagIndexMode=b.dataset.tagView;openIndex('tags',$('#iq').value.trim(),true)});
- $('#index').querySelectorAll('[data-k]').forEach(b=>b.onclick=()=>{
+ $('#index').querySelectorAll('[data-tag-category]').forEach(b=>b.onclick=()=>{
+ tagIndexCategory=b.dataset.tagCategory;openIndex('tags',$('#iq').value.trim(),true)});
+ const wireIndexEntries=root=>root.querySelectorAll('[data-k]').forEach(b=>b.onclick=()=>{
if(people){openEntity(b.dataset.kind,b.dataset.k);return}
$('#index').hidden=true;state.tag=b.dataset.k;route('/?tag='+encodeURIComponent(state.tag));buildBars();load(true)});
+ wireIndexEntries($('#indexBody'));
+ let indexOffset=d.items.length;
+ $('#indexMore').onclick=async()=>{const more=$('#indexMore');more.disabled=true;
+ try{const next=await api(indexApi(indexOffset));if(requestSeq!==indexRequestSeq)return;
+ indexOffset+=next.items.length;d.has_more=next.has_more;
+ if(people){d.items.push(...next.items);const grid=$('#indexBody .igrid');
+ grid.insertAdjacentHTML('beforeend',peopleHtml(next.items));wireIndexEntries(grid)}
+ else{d.items.push(...next.items);tagItems.push(...next.items);$('#indexBody').innerHTML=tagHtml(tagItems);wireIndexEntries($('#indexBody'))}
+ $('#indexCount').textContent=indexOffset+(next.has_more?'+':'')+' 项';more.hidden=!next.has_more}
+ finally{if(requestSeq===indexRequestSeq)more.disabled=false}};
}
+const ENTITY_LABELS={performer:'女优',studio:'厂牌',creator:'创作者',series:'系列'};
+let entityRequestSeq=0;
+async function fetchEntityItems(kind,name,entityTag,offset=0){
+ const p=new URLSearchParams();p.set(kind,name);p.set('limit','48');p.set('offset',String(offset));p.set('sort','new');
+ if(offset)p.set('count','0');
+ if(entityTag)p.set('tag',entityTag);
+ const items=await api('/api/items?'+p);cache(items.items);return items
+}
+function renderEntityCollection(kind,name,items,entityTag,append=false){
+ const section=$('#index').querySelector('.entitysection');if(!section)return;
+ if(!append){section.innerHTML=`<h3></h3><div class="grid"></div><button class="entitymore" type="button">载入更多</button>`;
+ section.dataset.total=String(items.total||0);
+ section.querySelector('h3').textContent=`${ENTITY_LABELS[kind]||kind}的馆藏作品 · ${(items.total||0).toLocaleString()}${entityTag?' · '+entityTag:''}`}
+ const grid=section.querySelector('.grid');
+ grid.insertAdjacentHTML('beforeend',items.items.map(it=>cardHtml(it)).join(''));
+ wireCards(grid,undefined,tag=>updateEntityCollection(kind,name,tag===entityTag?'':tag,true));
+ const more=section.querySelector('.entitymore');
+ more.hidden=append?!items.has_more:grid.children.length>=Number(section.dataset.total||0);
+ more.onclick=async()=>{more.disabled=true;const seq=entityRequestSeq;
+ try{const next=await fetchEntityItems(kind,name,entityTag,grid.children.length);
+ if(seq===entityRequestSeq&&$('#index').dataset.entityKind===kind&&$('#index').dataset.entityName===name)
+ renderEntityCollection(kind,name,next,entityTag,true)}
+ finally{if(seq===entityRequestSeq)more.disabled=false}}
+}
+async function updateEntityCollection(kind,name,entityTag,push=true){
+ if(push)route(entityPath(kind,name)+(entityTag?'?tag='+encodeURIComponent(entityTag):''));
+ const seq=++entityRequestSeq;
+ const items=await fetchEntityItems(kind,name,entityTag);
+ if(seq!==entityRequestSeq)return;
+ $('#index').querySelectorAll('[data-entity-tag]').forEach(b=>
+ b.setAttribute('aria-pressed',String(b.dataset.entityTag===entityTag)));
+ renderEntityCollection(kind,name,items,entityTag)
+}
async function openEntity(kind,name,push=true,requestedTag){
const entityTag=requestedTag===undefined
? (push?'':new URLSearchParams(location.search).get('tag')||'')
: requestedTag;
if(push)route(entityPath(kind,name)+(entityTag?'?tag='+encodeURIComponent(entityTag):''));
disposeStage(false);
- const d=await api(`/api/entity?kind=${encodeURIComponent(kind)}&name=${encodeURIComponent(name)}`);
- if(d.error)return;
- const p=new URLSearchParams();p.set(kind,name);p.set('limit','120');p.set('sort','new');
- if(entityTag)p.set('tag',entityTag);
- const items=await api('/api/items?'+p);cache(items.items);
+ const seq=++entityRequestSeq;
+ const [d,items]=await Promise.all([
+ api(`/api/entity?kind=${encodeURIComponent(kind)}&name=${encodeURIComponent(name)}`),
+ fetchEntityItems(kind,name,entityTag)]);
+ if(d.error||seq!==entityRequestSeq)return;
document.body.classList.add('entity-open');
$('#index').hidden=false;$('#grid').innerHTML='';$('#count').textContent='';
$('#loadSentinel').hidden=true;$('#shortsSec').hidden=true;
- const labels={performer:'女优',studio:'厂牌',creator:'创作者',series:'系列'};
const image=d.id?(kind==='studio'
? `<img src="/logo?studio=${encodeURIComponent(d.canonical_name)}" alt="${esc(d.canonical_name)}"
onerror="if(!this.dataset.f){this.dataset.f='1';this.src='/entity-image?kind=studio&id=${d.id}'}else{this.remove()}">`
: `<img src="/entity-image?kind=${kind}&id=${d.id}" alt="${esc(d.canonical_name)}"
onerror="${d.representative_asset_id?`this.onerror=null;this.src='/avatar?id=${d.representative_asset_id}'`:`this.remove()`}">`):'';
const links=(d.links||[]).map(x=>x.clickable&&/^https?:\/\//i.test(x.url||'')
- ? `<a href="${esc(x.url)}" target="_blank" rel="noreferrer">${esc(x.label)} ↗</a>`
- : `<span class="private" title="私人馆藏来源记录,不直接打开下载页">来源 · ${esc(x.label||x.hostname||'已记录')}</span>`).join('');
+ ? `<a href="${esc(x.url)}" target="_blank" rel="noreferrer"><span class="entitylinkicon">${icon('globe')}<img class="entityfavicon" src="${esc(faviconUrl(x.url))}" data-studio="${kind==='studio'?esc(d.canonical_name):''}" alt=""></span><span class="entitylinklabel">${esc(x.label)}</span><span class="entitylinkarrow" aria-hidden="true">↗</span></a>`
+ : `<span class="private" title="私人馆藏来源记录,不直接打开下载页"><span class="entitylinkicon">${icon('globe')}</span><span class="entitylinklabel">来源 · ${esc(x.label||x.hostname||'已记录')}</span></span>`).join('');
const terms=(d.search_terms||[]).map(x=>`<code>${esc(x.term)}</code>`).join('');
const tags=(d.tags||[]).map(x=>`<button data-entity-tag="${esc(x.k)}" aria-pressed="${entityTag===x.k}">${esc(x.k)}<small>${x.n.toLocaleString()}</small></button>`).join('');
const related=(d.related_performers||[]).map(x=>`<button class="relatedperson" data-related-performer="${esc(x.k)}">
<span class="ring"><span>${esc(x.k.slice(0,1))}</span><img src="/entity-image?kind=performer&id=${x.id}" alt="" loading="lazy"
onerror="${x.rep?`this.onerror=null;this.src='/avatar?id=${x.rep}'`:`this.remove()`}"></span>
<span class="nm">${esc(x.k)}</span><small>${x.n.toLocaleString()} 部</small></button>`).join('');
- $('#index').innerHTML=`<div class="ihead"><button class="backbtn" id="iClose">${icon('chevron-left')}<span>返回</span></button>
- <span class="mono" style="color:var(--muted)">${labels[kind]||kind}资料页</span></div>
- <div class="entityhero"><div class="entityportrait ${kind==='performer'||kind==='creator'?'':'square'}">${image}<span>${esc(name.slice(0,1))}</span></div>
- <div><h2 class="disp">${esc(d.canonical_name)}</h2>
- <div class="alias mono">${(d.aliases||[]).length?'别名 · '+d.aliases.map(esc).join(' / '):'暂无别名'} · ${d.asset_count.toLocaleString()} 个视频</div>
+ $('#index').dataset.entityKind=kind;$('#index').dataset.entityName=name;
+ $('#index').innerHTML=`<div class="entityhero"><div class="entityportrait ${kind==='performer'||kind==='creator'?'':'square'}">${image}<span>${esc(name.slice(0,1))}</span></div>
+ <div><h2>${esc(d.canonical_name)}</h2>
+ <div class="alias">${(d.aliases||[]).length?'别名 · '+d.aliases.map(esc).join(' / '):'暂无别名'} · ${d.asset_count.toLocaleString()} 个视频</div>
${d.summary?`<div class="entitysummary">${esc(d.summary)}</div>`:''}
${links?`<div class="entitylinks">${links}</div>`:''}
${terms?`<div class="entityterms">馆藏检索词 · ${terms}</div>`:''}</div></div>
@@ -1218,15 +1316,16 @@ async function openEntity(kind,name,push=true,requestedTag){
${tags?`<section><h3>相关标签</h3><div class="entitytags">${tags}</div></section>`:''}
${related?`<section><h3>关联艺人</h3><div class="relatedpeople">${related}</div></section>`:''}
</div>`:''}
- <div class="entitysection"><h3>${labels[kind]||kind}的馆藏作品 · ${items.total.toLocaleString()}${entityTag?` · ${esc(entityTag)}`:''}</h3>
- <div class="grid">${items.items.map(it=>cardHtml(it)).join('')}</div></div>`;
- $('#iClose').onclick=()=>{route('/');document.body.classList.remove('entity-open');$('#index').hidden=true;load(true)};
+ <div class="entitysection"></div>`;
$('#index').querySelectorAll('[data-entity-tag]').forEach(b=>b.onclick=()=>{
const next=b.dataset.entityTag===entityTag?'':b.dataset.entityTag;
- openEntity(kind,name,true,next)});
+ updateEntityCollection(kind,name,next,true)});
+ $('#index').querySelectorAll('.entityfavicon').forEach(img=>img.addEventListener('error',()=>{
+ if(img.dataset.studio&&!img.dataset.fallback){img.dataset.fallback='1';img.src='/logo?studio='+encodeURIComponent(img.dataset.studio)}
+ else img.remove()}));
$('#index').querySelectorAll('[data-related-performer]').forEach(b=>b.onclick=()=>
openEntity('performer',b.dataset.relatedPerformer));
- wireCards($('#index'),undefined,tag=>openEntity(kind,name,true,tag===entityTag?'':tag));
+ renderEntityCollection(kind,name,items,entityTag);
window.scrollTo({top:0,behavior:'smooth'});
}
@@ -1307,29 +1406,43 @@ $('#drawer').addEventListener('mouseleave',()=>{
$('#scrim').onclick=()=>openDrawer(false);
/* ── 列表 ── */
+let adsBatch=null,loadRequestSeq=0,listLoading=false;
async function load(reset){
+ const requestSeq=reset?++loadRequestSeq:loadRequestSeq;
+ if(!reset&&listLoading)return;
+ if(!reset)listLoading=true;
+ try{
document.body.classList.remove('entity-open');
if(reset)offset=0;
$('#index').hidden=true; $('#stats').hidden=true; renderCombo();
if(state.state==='ads'){
- const d=await api('/api/ads?limit=200'); cache(d.items);
- $('#grid').innerHTML=d.items.map(it=>cardHtml(it)).join('');
- $('#count').innerHTML=`疑似广告 ${d.total} 个 · 标记后统一复核,不会直接删除`;
- $('#loadSentinel').hidden=true; $('#shortsSec').hidden=true; wireCards($('#grid')); return;
+ if(reset||!adsBatch){const nextAds=await api('/api/ads?limit=200');if(requestSeq!==loadRequestSeq)return;
+ adsBatch=nextAds;cache(adsBatch.items)}
+ const batch=adsBatch.items.slice(offset,offset+60);
+ const html=batch.map(it=>cardHtml(it)).join('');
+ if(reset)$('#grid').innerHTML=html;else $('#grid').insertAdjacentHTML('beforeend',html);
+ $('#count').innerHTML=`疑似广告 ${adsBatch.total} 个 · 当前载入 ${$('#grid').children.length} 个 · 标记后统一复核,不会直接删除`;
+ $('#loadSentinel').hidden=$('#grid').children.length>=adsBatch.items.length;
+ $('#shortsSec').hidden=true;wireCards($('#grid'));return;
}
+ adsBatch=null;
const p=new URLSearchParams(Object.entries(state).filter(([,v])=>v));
p.set('limit',60); p.set('offset',offset);
- const d=await api('/api/items?'+p); total=d.total; cache(d.items);
+ if(!reset)p.set('count','0');
+ const d=await api('/api/items?'+p);cache(d.items);
+ if(requestSeq!==loadRequestSeq)return;
+ if(reset)total=d.total;
const html=d.items.map(it=>cardHtml(it)).join('');
if(reset)$('#grid').innerHTML=html; else $('#grid').insertAdjacentHTML('beforeend',html);
renderCount();
$('#loadSentinel').hidden=$('#grid').children.length>=total;
wireCards($('#grid'));
paintSelection();
- if(reset)loadShorts();
+ if(reset)loadShorts(requestSeq);
+ }finally{if(!reset&&requestSeq===loadRequestSeq)listLoading=false}
}
const loadObserver=new IntersectionObserver(entries=>{
- if(entries.some(x=>x.isIntersecting)&&!$('#loadSentinel').hidden&&$('#stats').hidden&&$('#index').hidden){
+ if(entries.some(x=>x.isIntersecting)&&!listLoading&&!$('#loadSentinel').hidden&&$('#stats').hidden&&$('#index').hidden){
offset+=60;load(false)}
},{rootMargin:'320px'});
loadObserver.observe($('#loadSentinel'));
@@ -1342,11 +1455,12 @@ const runSearch=(useSuggestion=false)=>{let query=$('#q').value.trim();
let qt;$('#q').oninput=()=>{clearTimeout(qt);qt=setTimeout(runSearch,320)};
$('#q').onkeydown=e=>{if(e.key==='Enter'){e.preventDefault();clearTimeout(qt);runSearch(true);$('#q').blur()}};
-async function loadShorts(){
+async function loadShorts(requestSeq=loadRequestSeq){
if(state.orient==='竖屏'||state.state==='ads'){$('#shortsSec').hidden=true;return}
const p=new URLSearchParams(Object.entries(state).filter(([,v])=>v));
p.set('orient','竖屏');p.set('limit',18);p.set('offset',0);p.set('sort','new');
const d=await api('/api/items?'+p);
+ if(requestSeq!==loadRequestSeq)return;
if(!d.items.length){$('#shortsSec').hidden=true;return}
cache(d.items);
$('#shortsSec').hidden=false; $('#shortsN').textContent=d.total.toLocaleString()+' 个';
@@ -1723,7 +1837,10 @@ async function restoreRoute(){
if(entityKind&&parts.length>=2){await openEntity(entityKind,parts.slice(1).join('/'),false);return}
if(path==='/performers'||path==='/creators'||path==='/tags'){
const params=new URLSearchParams(location.search);
- if(path==='/tags')tagIndexMode=params.get('view')==='cloud'?'cloud':'alphabet';
+ if(path==='/tags'){
+ tagIndexMode=params.get('view')==='cloud'?'cloud':'alphabet';
+ const category=params.get('category')||'all';
+ tagIndexCategory=TAG_CATEGORIES.some(([key])=>key===category)?category:'all'}
await openIndex(path.slice(1),params.get('q')||'',false);return}
if(path==='/stats'){await openStats(false);return}
if(path==='/immerse'){await openTok(undefined,false);return}