Peach: Local-first video metadata scraper and media manager.
fix(web): stabilize follow discovery and loading
longmeidao9765609920ba
diff --git a/.claude/skills/peach-web-ui/SKILL.md b/.claude/skills/peach-web-ui/SKILL.mdindex 7ad4f3abe..ea6472d01 100644--- a/.claude/skills/peach-web-ui/SKILL.md+++ b/.claude/skills/peach-web-ui/SKILL.md@@ -5,7 +5,7 @@ description: 在新增、修改或复核 Peach 页面、控件、提示、错误# Peach Web UI 复用门槛-最后复核:2026-08-30+最后复核:2026-08-31## 开工顺序@@ -24,6 +24,7 @@ description: 在新增、修改或复核 Peach 页面、控件、提示、错误| 已知总量的进行状态 | Progress | 装饰性蓝条 || 用户触发动作等待结果 | Spinner | 旋转原操作图标、Loading Dots || 后台任务仍在推进 | Loading Dots | Spinner、假百分比 |+| 整页或大区块首次等待内容结构 | Skeleton | Spinner、Loading Dots || 2–3 个互斥视图 | Switch(radio) | Toggle || 布尔开关 | Toggle | Switch || 无布局高度变化的菜单 | Menu/Listbox,无动画 | Collapse 动画 |@@ -42,7 +43,8 @@ description: 在新增、修改或复核 Peach 页面、控件、提示、错误- Progress 必须有真实 `value/max`、可见单位与 `aria-valuemin/max/now`;分隔线放在完整指标(含进度条)之后。- Switch 必须共享 radio `name`、初始一个 `checked`、键盘可用;布尔状态继续使用 Toggle。- 菜单每项包含与入口相同的图标和文字,菜单内部滚动、`overscroll-behavior:contain`,不得把浏览器页面撑出滚动条。-- Spinner 只反馈用户直接触发的动作,触发器声明 `aria-busy` 且等待时保持可聚焦;未知时长的后台抓取使用 Loading Dots。两者都必须保留可读状态文字并尊重 reduced motion。+- Spinner 只反馈用户直接触发的动作,触发器声明 `aria-busy` 且等待时保持可聚焦;未知时长的后台抓取使用 Loading Dots。整页或大区块首次取数使用 Skeleton 预留最终结构。三者都必须保留可读状态文字并尊重 reduced motion。+- 同一次页面进入只呈现一段等待态;深链启动与页面取数复用同一个 Skeleton,禁止 Spinner 再切换成 Loading Dots 或 Skeleton。- 分页末尾、空页和“没有更多内容”是中性终止状态,用可关闭 Note;只有需要恢复或处理的故障才能进入红色 error Note。- 弹层标题栏与滚动正文分层:标题分隔线属于卡片全宽,滚动条只属于正文。- 没有直接证据不得新增动效;参考产品无动画的菜单保持无动画。diff --git a/src/peach/web_follow.py b/src/peach/web_follow.pyindex a42ff730a..95cf4eeea 100644--- a/src/peach/web_follow.py+++ b/src/peach/web_follow.py@@ -56,6 +56,29 @@ LOW_VALUE_FOLLOW_TAGS = frozenset({"no sound", "audio", "loop", "webm", "mp4",})+# 关注页的标签是「里面发生了什么」,不是人物计数、身体部位、画幅、年份、软件或+# 作品题材。原始 metadata 仍完整保留;这里只收窄卡片、详情、筛选条与在线标签页+# 共用的可见投影。Rule34.xxx 不提供 tag type,所以截图里这些漏项还需要形态判据。+NON_CONTENT_FOLLOW_TAG_TYPES = frozenset({+ "artist", "character", "copyright", "metadata",+})+_NON_CONTENT_FOLLOW_TAG_RE = re.compile(+ r"^(?:"+ r"(?:19|20)\d{2}|\d{1,2}:\d{1,2}|"+ r"\d+[_\s-]*(?:boy|girl|futa)s?|female|male|male/female|female_only|"+ r"(?:light[-_\s]?skinned[_\s-]?)?(?:female|male)|human|"+ r"(?:nude|naked)(?:[_\s-](?:female|male))?|"+ r"(?:(?:large|big|medium|small|bouncing)[_\s-])?"+ r"(?:breasts?|ass|pussy|penis|vagina|nipples?|areolae)|"+ r"(?:blonde|black|white|long|short)[_\s-](?:hair|female)|"+ r"(?:blue|green|brown)[_\s-]eyes|light[_\s-]skin|"+ r"(?:shorter|longer)[_\s-]than[_\s-]\d+[_\s-]seconds|short[_\s-]video|"+ r"beach|initial[_\s-]?a|square[_\s-]?enix|"+ r"final[_\s-]?fantasy(?:[_\s-].*)?|dead[_\s-]?or[_\s-]?alive(?:[_\s-].*)?"+ r")$", re.I,+)+_TOPICAL_FOLLOW_TAG_RE = re.compile(r"\([^)]+\)\s*$")+_IMAGE_MEDIA_RE = re.compile(r"\.(?:avif|gif|jpe?g|png|webp)(?:$|[?#])", re.I)_VIDEO_MEDIA_RE = re.compile(r"\.(?:m4v|mov|mp4|og[gv]|webm)(?:/)?(?:$|[?#])", re.I)_RULE34XXX_PREVIEW_RE = re.compile(@@ -87,10 +110,20 @@ def _item_tags(item) -> list[str]:values.extend(str(value).strip() for value in categories if str(value).strip())values = [html.unescape(value) for value in values]subject = html.unescape(str(item.metadata.get("tag") or "")).casefold()+ category_keys = {+ html.unescape(str(value)).casefold()+ for value in categories or []+ } if isinstance(categories, list) else set()+ recorded_types = item.metadata.get("tag_types")+ recorded_types = recorded_types if isinstance(recorded_types, dict) else {}seen, tags = set(), []for tag in values:key = tag.casefold()- if key == subject or key in seen or key in LOW_VALUE_FOLLOW_TAGS:+ tag_type = str(recorded_types.get(tag) or recorded_types.get(key) or "general").casefold()+ if (key == subject or key in seen or key in LOW_VALUE_FOLLOW_TAGS+ or key in category_keys or tag_type in NON_CONTENT_FOLLOW_TAG_TYPES+ or _NON_CONTENT_FOLLOW_TAG_RE.fullmatch(tag.strip())+ or _TOPICAL_FOLLOW_TAG_RE.search(tag)):continueseen.add(key)tags.append(tag)@@ -579,6 +612,7 @@ def _source_payload(row, aliases: dict[str, str] | None = None) -> dict:# 往回抓到哪一页了(0 起,0 = 只抓过第一页)。界面据此说清进度,# 否则用户点一次只看到列表变长一点,不知道自己走到第几页。"backfill_page": row["backfill_page"],+ "created_at": row["created_at"],"last_checked_at": row["last_checked_at"],"last_status": "not_modified" if history_exhausted else row["last_status"],"last_error": None if history_exhausted else row["last_error"],diff --git a/tests/test_follow_web.py b/tests/test_follow_web.pyindex 1c4d36c3f..d9c71be97 100644--- a/tests/test_follow_web.py+++ b/tests/test_follow_web.py@@ -419,22 +419,16 @@ class FollowContractTests(unittest.TestCase):self._seed()self.assertEqual(len(self._get(limit="nope")["groups"]), 1)- def test_cards_drop_generic_tags_but_filters_keep_them(self):- """卡片只留有身份的标签,general 那类内容描述不上卡片。-- footjob / standing sex / from behind 这种三个一排占满卡片底部,却几乎不用来- 找东西。筛选条里仍然保留——主动去筛和被动堆一排不是一回事。- """+ def test_all_follow_surfaces_share_the_content_tag_projection(self):+ """卡片、详情、筛选条与标签页不能各自保留一套噪声判定。"""page = (ROOT / "web" / "app.js").read_text(encoding="utf-8")- # 只留玩法:题材(copyright/artist)整类不上卡片- self.assertIn("if(followTagType(item,tag)!=='general')return false;", page)- # 站点把三种东西都塞进 general,所以还要按两条判据再筛- self.assertIn("FOLLOW_TAG_NOISE", page, "技术标记与计数要滤掉")- self.assertIn("FOLLOW_TAG_TOPICAL", page, "booru 的「角色 (作品)」写法要滤掉")+ self.assertIn("const followCardTags=item=>item.tags||[]", page)self.assertIn("const tags=followCardTags(item).slice(0,3)", page,"卡片必须走过滤后的标签")self.assertIn("data-follow-tag=\"${esc(key)}\"", page,- "筛选条仍要能按标签筛,包括被卡片滤掉的那些")+ "筛选条必须直接消费服务端投影")+ self.assertNotIn("FOLLOW_TAG_NOISE", page)+ self.assertNotIn("FOLLOW_TAG_TOPICAL", page)def test_generated_media_is_cached_for_a_month_not_a_day(self):"""按 id 取的生成物内容不会变,一天太短。@@ -1656,8 +1650,9 @@ class FollowWebSourceTests(unittest.TestCase):self.assertPageContains('class="tagbar followfilters"')self.assertPageContains('class="pill sourcepill" data-follow-provider=')self.assertPageLacks("内容标签目前由 ${")- self.assertPageContains("const rankedTags=[...tagCounts].sort((a,b)=>b[1]-a[1])")- self.assertPageContains("const topTagRows=rankedTags.slice(0,20)")+ self.assertPageContains("const randomizedAuthors=followRandomOrder([...authors],row=>row[0])")+ self.assertPageContains("const topTagRows=followRandomOrder([...tagCounts],row=>row[0]).slice(0,20)")+ self.assertPageContains("if(push)followDiscoverySeed=Math.floor(Math.random()*0xffffffff)")self.assertPageContains("topTagRows.push([tag,tagCounts.get(tag)])")def test_follow_tags_are_multi_select_and_use_rule34_property_colours(self):@@ -1707,9 +1702,16 @@ class FollowWebSourceTests(unittest.TestCase):# 第四个参数是来源自己给的清晰度表:rule34video 把每档写成独立 mp4 字段,# videojs 的 qualityLevels 只认 HLS/DASH 的自适应轨道,看不到它们。self.assertPageContains(- "function mountPlayerQualityControl(player,video,fallbackHeight=0,sourceQualities=null)")- self.assertPageContains("qualities:followQualities",- "关注详情要把查到的档位传给播放器")+ "function mountPlayerQualityControl(player,video,fallbackHeight=0,initialSourceQualities=null)")+ self.assertPageContains("const qualitiesPromise=api(`/follow-qualities?id=${encodeURIComponent(item.id)}`)")+ self.assertPageContains("qualitiesPromise",+ "关注详情要异步补上来源档位")+ detail = self.page.split("async function openFollowDetail", 1)[1].split(+ "function renderFollow", 1)[0]+ self.assertNotIn("await api(`/follow-qualities", detail,+ "清晰度回源不能挡住默认视频挂载")+ self.assertLess(detail.index("const followPlayer=mountDetailPlayer"),+ detail.index("wireFollowTelemetry"))self.assertPageContains('aria-label="播放器设置"')self.assertPageContains("data-player-quality-badge")self.assertPageContains("currentTimeDisplay:true,timeDivider:true")@@ -1858,17 +1860,28 @@ class FollowWebSourceTests(unittest.TestCase):def __init__(self, metadata):self.metadata = metadata- tags = web_follow._item_tags(- _Item({"tag": "lazyprocrastinator",- "tags": "lazyprocrastinator 1girls animated sound lazyprocrastinator"}))+ tags = web_follow._item_tags(_Item({+ "tag": "lazyprocrastinator",+ "tags": "lazyprocrastinator 1girls animated sound riding lazyprocrastinator",+ }))# 作者手柄本身不算标签:按作者筛已经有专门的筛选条,重复出现没有信息量。- self.assertEqual(tags, ["1girls"])+ self.assertEqual(tags, ["riding"])video_tags = web_follow._item_tags(_Item({"tags": ["deep throat", "3D", "3d_animation", "breast squeeze"],"categories": ["2D", "Final Fantasy"],}))- self.assertEqual(video_tags,- ["deep throat", "breast squeeze", "Final Fantasy"])+ self.assertEqual(video_tags, ["deep throat", "breast squeeze"])+ screenshot_tags = web_follow._item_tags(_Item({+ "tags": "beach dead_or_alive 16:9 2026 female 1boy 1girls breasts "+ "final_fantasy male ass pov blowjob",+ }))+ self.assertEqual(screenshot_tags, ["pov", "blowjob"])+ typed = web_follow._item_tags(_Item({+ "tags": ["artist name", "some character", "some series", "handjob"],+ "tag_types": {"artist name": "Artist", "some character": "character",+ "some series": "copyright", "handjob": "general"},+ }))+ self.assertEqual(typed, ["handjob"])self.assertEqual(web_follow._item_tags(_Item({})), [])self.assertEqual(web_follow._item_tags(_Item({"tags": " "})), [])# rule34.xxx 旧行存的是 HTML 转义形态;出口归一后与反转义的新写法@@ -2101,9 +2114,14 @@ class FollowWebSourceTests(unittest.TestCase):def test_follow_management_list_has_routed_sorting(self):self.assertPageContains('data-follow-sort aria-label="关注列表排序"')self.assertPageContains('<option value="checked"')+ self.assertPageContains('<option value="added"')self.assertPageContains('<option value="name"')self.assertPageContains('<option value="sources"')- self.assertPageContains("followManageSort=['checked','name','sources'].includes(requested)?requested:'checked'")+ self.assertPageContains("followManageSort=['checked','added','name','sources'].includes(requested)?requested:'checked'")+ self.assertPageContains("const added=group=>Math.max(...group.map(source=>Date.parse(source.created_at||'')||0))")+ self.assertPageContains("if(followManageSort==='added')return added(b)-added(a)")+ backend = (ROOT / "src" / "peach" / "web_follow.py").read_text(encoding="utf-8")+ self.assertIn('"created_at": row["created_at"]', backend)self.assertPageContains("return groups.sort((a,b)=>{")def test_mix_and_follow_queues_stay_below_media_with_details_on_the_right(self):diff --git a/tests/test_web_ui.py b/tests/test_web_ui.pyindex 47dfe0e3a..7fe123536 100644--- a/tests/test_web_ui.py+++ b/tests/test_web_ui.py@@ -794,7 +794,8 @@ class WebUiSourceTests(unittest.TestCase):def test_immerse_mode_has_loading_state_and_full_viewport_cover(self):self.assertPageContains('id="tokLoader"')- self.assertPageContains('class="tokspinner"')+ self.assertPageContains("$('#tokLoader').insertAdjacentHTML('afterbegin',spinnerHtml('媒体加载中'))")+ self.assertPageLacks('class="tokspinner"')self.assertPageContains("function setTokLoading(on,label='加载中…',it=null)")self.assertPageContains("function waitTokReady(video,timeout=15000)")self.assertPageContains("width:100%;height:100%;left:50%;transform:translateX(-50%);object-fit:cover")@@ -944,7 +945,7 @@ class WebUiSourceTests(unittest.TestCase):def test_note_semantics_replace_empty_states_for_persistent_errors(self):for name in ("emptyStateHtml", "loadingDotsHtml", "mediaViewButtonsHtml", "noteHtml", "progressHtml",- "scrollerHtml", "spinnerHtml", "wireScrollers"):+ "scrollerHtml", "skeletonHtml", "spinnerHtml", "wireScrollers"):self.assertPageContains(name)self.assertPageContains("from './js/ui-components.js'")self.assertPageContains("const NOTE_VARIANTS=new Set(['secondary','warning','error','success'])")@@ -978,6 +979,8 @@ class WebUiSourceTests(unittest.TestCase):self.assertIn("Switch 必须共享 radio `name`", rules)self.assertIn("Fieldset", rules)self.assertIn("Scroller", rules)+ self.assertIn("整页或大区块首次等待内容结构", rules)+ self.assertIn("同一次页面进入只呈现一段等待态", rules)self.assertIn("Empty State", rules)agents = (root / "AGENTS.md").read_text(encoding="utf-8")self.assertIn(".claude/skills/peach-web-ui/SKILL.md", agents)@@ -1621,13 +1624,24 @@ class WebUiSourceTests(unittest.TestCase):self.assertPageContains("stage.style.scrollMarginTop=`${itemDetailStickyOffset()+8}px`")self.assertPageContains("buildBars();\n scrollItemDetailIntoView();")- def test_catalog_loading_reuses_the_spinner_without_flashing_an_item_placeholder(self):+ def test_page_loading_uses_one_structural_skeleton_phase(self):self.assertPageContains("function renderCatalogLoading(label='正在读取作品')")- self.assertPageContains("count.innerHTML=`${spinnerHtml(label)}<span>载入中…</span>`")+ self.assertPageContains("$('#grid').innerHTML=pageSkeletonHtml(label,{cards:true,className:'catalog-skeleton'})")+ self.assertPageContains("function renderInitialSurfaceLoading()")+ self.assertPageContains("placeholder:`<div class=\"follow\">${pageSkeletonHtml('正在读取关注内容',{cards:true})}</div>`")+ self.assertPageContains("showManagementBody({placeholder:pageSkeletonHtml('正在读取统计')})")+ self.assertPageContains("showIndexLoading(people?'正在读取作者':'正在读取标签')")+ self.assertPageContains("$('#loadSentinel').innerHTML=loadingDotsHtml('继续载入中…')")+ self.assertPageContains("pageSkeletonHtml('正在读取推荐',{cards:true,className:'related-skeleton'})")+ self.assertPageLacks("count.innerHTML=`${spinnerHtml(label)}<span>载入中…</span>`")self.assertPageLacks("function showItemDetailLoading(anchor,above)")self.assertPageLacks("detailpending")self.assertPageLacks("showItemDetailLoading(origin,above)")+ def test_follow_separator_uses_the_same_border_token_as_tags(self):+ self.assertPageContains(".pill{flex:none;height:var(--filterItemH);padding:0 20px;border:1px solid var(--border-15)")+ self.assertPageContains(".followfilters .sep{flex:none;width:1px;height:24px;background:var(--border-15)")+def test_entity_profile_uses_logo_links_without_a_redundant_back_row(self):self.assertPageContains("const faviconUrl=url=>")self.assertPageContains('class="entitylinkicon"')diff --git a/web/app.css b/web/app.cssindex 7041575a0..25b1f3a2a 100644--- a/web/app.css+++ b/web/app.css@@ -467,10 +467,16 @@ body.photolight-open{overflow:hidden}.photozoom button:hover{background:rgba(255,255,255,.22)}.fcollapse{overflow:hidden;transition:height .2s ease-in-out}-/* Geist Skeleton:面板加载时先给形状,内容到了再替换。 */-.skeletonpanel{display:grid;gap:12px;padding:16px}+/* Geist Skeleton:整页/大区块等待内容结构时先占住稳定区域。 */+.skeletonpanel{min-height:240px;padding:16px}+.skeletonpanel>div{display:grid;gap:12px}.skeleton{display:block;height:18px;border-radius:6px;background:var(--hover);animation:skeleton-pulse 1.4s ease-in-out infinite}+.skeleton-cards>div{grid-template-columns:repeat(auto-fill,minmax(min(260px,100%),1fr));gap:14px}+.skeletoncard{display:grid;gap:10px;min-width:0}+.skeletoncard i,.skeletoncard b,.skeletoncard em{display:block;border-radius:6px;background:var(--hover);+ animation:skeleton-pulse 1.4s ease-in-out infinite}+.skeletoncard i{aspect-ratio:16/9}.skeletoncard b{width:72%;height:18px}.skeletoncard em{width:46%;height:14px}@keyframes skeleton-pulse{0%,100%{opacity:.55}50%{opacity:1}}/* 缩放滑杆:原生 accent-color 的轨道太粗,自绘成与时长双滑块同一套 4px 细轨。底色是视频上的白色,所以这一套固定用白色而不是主题色。 */@@ -1515,9 +1521,6 @@ body.drawer-open .edge{opacity:0;pointer-events:none} /* 展开时窄栏让位border-radius:24px;background:rgba(0,0,0,.58);color:#fff;backdrop-filter:blur(12px);pointer-events:none;font:var(--fs-xs)/1 "Cascadia Mono",monospace;white-space:nowrap}.tokloading[hidden]{display:none}-.tokspinner{width:17px;height:17px;border:2px solid rgba(255,255,255,.3);border-top-color:#fff;border-radius:50%;- animation:tok-spin .75s linear infinite}-@keyframes tok-spin{to{transform:rotate(360deg)}}.tokui{position:absolute;left:20px;bottom:20px;width:min(520px,calc(50% - 28.125vh - 36px));padding:0;color:#f1f1f1;pointer-events:none}.tok.tok-wide .tokui{width:min(500px,calc(36vw - 56px))}@@ -1741,7 +1744,7 @@ body.drawer-open .edge{opacity:0;pointer-events:none} /* 展开时窄栏让位padding:9px 0 8px;border-bottom-color:transparent;scrollbar-width:none;overscroll-behavior-inline:contain;touch-action:pan-x}.followfilters::-webkit-scrollbar{display:none}-.followfilters .sep{flex:none;width:1px;height:24px;background:var(--line-soft);margin:0 3px}+.followfilters .sep{flex:none;width:1px;height:24px;background:var(--border-15);margin:0 3px}.followfilters .pill .n{margin-left:5px;color:inherit}.followfilters .sourcepill{width:40px;padding:0}.followfilters .sourcepill .ficon{width:21px;height:21px;margin:0}diff --git a/web/app.js b/web/app.jsindex 28a6a445a..f0b97508e 100644--- a/web/app.js+++ b/web/app.js@@ -23,17 +23,41 @@ import {import { initMiddleTruncate } from './js/middle-truncate.js';import {emptyStateHtml, loadingDotsHtml, mediaViewButtonsHtml, noteHtml, progressHtml, scrollerHtml,- spinnerHtml, wireScrollers,+ skeletonHtml, spinnerHtml, wireScrollers,} from './js/ui-components.js';initMiddleTruncate(document);+const pageSkeletonHtml=(label,{cards=false,className=''}={})=>+ skeletonHtml(label,{variant:cards?'cards':'panel',className});+$('#loadSentinel').innerHTML=loadingDotsHtml('继续载入中…');+$('#tokLoader').insertAdjacentHTML('afterbegin',spinnerHtml('媒体加载中'));function renderCatalogLoading(label='正在读取作品'){const count=$('#count');count.setAttribute('aria-busy','true');- count.innerHTML=`${spinnerHtml(label)}<span>载入中…</span>`;+ count.textContent=label;+ $('#grid').innerHTML=pageSkeletonHtml(label,{cards:true,className:'catalog-skeleton'});}-renderCatalogLoading();+/* 深链启动前先占住目标表面。后续路由仍画同一种 Skeleton,因此不会先出现首页+ Spinner、再切成目标页 Loading Dots。 */+function renderInitialSurfaceLoading(){+ const path=decodeURIComponent(location.pathname);+ const management=new Set(['/stats','/taste','/review','/duplicates','/quality-goals',+ '/playlists','/resource-sync','/follow','/follow-manage']);+ if(management.has(path)||path.startsWith('/follow/item/')){+ const stats=$('#stats');stats.hidden=false;$('#grid').innerHTML='';+ stats.innerHTML=pageSkeletonHtml('正在读取页面',{cards:path.startsWith('/follow')});+ return;+ }+ if(path==='/performers'||path==='/creators'||path==='/tags'||+ /^\/(?:performers|creators|studios)\//.test(path)){+ $('#index').hidden=false;$('#grid').innerHTML='';+ $('#index').innerHTML=pageSkeletonHtml('正在读取页面',{cards:true});+ return;+ }+ renderCatalogLoading();+}+renderInitialSurfaceLoading();const JAV_MEDIA_SUFFIX=/\.(?:mp4|mkv|avi|wmv|mov|m4v|webm|ts|m2ts|mts|mpg|mpeg|flv|rm|rmvb|iso)$/i;const javDisplayName=(it,value=it?.name)=>{@@ -490,7 +514,7 @@ function mountPlayerAmbient(video){/* `sourceQualities` 是来源自己给的清晰度表([{height,label}],从高到低)。rule34video 把每档写成独立字段,videojs 的 qualityLevels 看不到它们——那套只认HLS/DASH 的自适应轨道,而这里是四个各自独立的 mp4。所以由调用方查好再传进来。 */-function mountPlayerQualityControl(player,video,fallbackHeight=0,sourceQualities=null){+function mountPlayerQualityControl(player,video,fallbackHeight=0,initialSourceQualities=null){const controlBar=player.getChild('controlBar')?.el();if(!controlBar||controlBar.querySelector('[data-player-quality]'))return;const root=document.createElement('div');@@ -503,6 +527,7 @@ function mountPlayerQualityControl(player,video,fallbackHeight=0,sourceQualitiesconst toggle=root.querySelector('button'),badge=root.querySelector('[data-player-quality-badge]');const menu=root.querySelector('.vjs-peach-settings-menu');const levels=typeof player.qualityLevels==='function'?player.qualityLevels():null;+ let sourceQualities=initialSourceQualities;let selected='auto';const resolution=(width,height)=>{const values=[Number(width),Number(height)].filter(value=>value>0);return values.length?Math.min(...values):0};const rows=()=>{@@ -579,6 +604,7 @@ function mountPlayerQualityControl(player,video,fallbackHeight=0,sourceQualitiesplayer.on('dispose',()=>document.removeEventListener('pointerdown',outside));qualityRows();mountPlayerTheaterControl(player,root);mountPlayerChromeLayout(player);+ return next=>{sourceQualities=next?.length?next:null;if(!menu.hidden)showMain();else qualityRows()};}function mountPlayerTheaterControl(player,settingsRoot){const controlBar=player.getChild('controlBar')?.el();if(!controlBar||controlBar.querySelector('[data-player-theater]'))return;@@ -771,7 +797,11 @@ function mountDetailPlayer(it,video,autoplay,options={}){});});detailPlayer.ready(()=>{- enforceDuration();mountPlayerQualityControl(detailPlayer,video,it.height,options.qualities);+ enforceDuration();+ const updateQualities=mountPlayerQualityControl(detailPlayer,video,it.height,options.qualities);+ options.qualitiesPromise?.then(next=>{+ if(detailPlayer===player&&!player.isDisposed())updateQualities?.(next)+ }).catch(()=>{});mountPlayerSeekPreview(detailPlayer,it,{thumbnail:!options.source});mountPlayerCenterControls(detailPlayer);if(statsButton)statsButton.hidden=false@@ -1602,6 +1632,11 @@ function showManagementBody({manage=true,placeholder=''}={}){else{$('#managebar').hidden=true;$('#manageTitle').hidden=true;buildEdge()}if(placeholder)$('#stats').innerHTML=placeholder;}+function showIndexLoading(label){+ $('#stats').hidden=true;$('#index').hidden=false;$('#grid').innerHTML='';+ $('#count').textContent='';$('#loadSentinel').hidden=true;$('#shortsSec').hidden=true;+ $('#index').innerHTML=pageSkeletonHtml(label,{cards:true});+}function enterManagementSurface(){// A catalog request started before browser Back must not repaint filters over// the management page after it resolves.@@ -1615,6 +1650,7 @@ async function openStats(push=true,focusResource=false){const surface=claimSurface('/stats');enterManagementSurface();disposeStage(false);+ showManagementBody({placeholder:pageSkeletonHtml('正在读取统计')});const d=await api('/api/stats');if(!surfaceCurrent(surface))return;showManagementBody();@@ -1733,7 +1769,7 @@ async function wireResourceSync(){const active=()=>location.pathname==='/stats'&&!$('#stats').hidden&&document.body.contains(result);const setBusy=(busy,done=false)=>{scan.disabled=busy;scan.setAttribute('aria-busy',String(busy));- scan.innerHTML=`${busy?spinnerHtml('扫描中'):icon('refresh-cw')}<span>${busy?'扫描中':done?'重新扫描':'扫描差异'}</span>`;+ scan.innerHTML=`${icon('refresh-cw')}<span>${busy?'扫描中':done?'重新扫描':'扫描差异'}</span>`;};const render=payload=>{const sources=payload.sources||[];@@ -1925,7 +1961,7 @@ function renderTaste(d){const oldButton=button.innerHTML;button.disabled=true;button.setAttribute('aria-busy','true');button.innerHTML=`${spinnerHtml('正在读取')}<span>读取中…</span>`;- stateEl.innerHTML=loadingDotsHtml('正在读取 Peach 所在主机的浏览器…');+ stateEl.textContent='';try{const result=await api('/api/taste/refresh',{method:'POST',body:JSON.stringify({window:tasteWindow})});tasteCacheSet(tasteWindow,result.dashboard);renderTaste(result.dashboard)}catch(error){stateEl.textContent=error.message||'读取失败';button.disabled=false;@@ -1953,11 +1989,7 @@ async function openTaste(push=true){const cachedEntry=tasteCache.get(tasteWindow),cached=cachedEntry?.dashboard;const cacheFresh=cached&&Date.now()-cachedEntry.at<TASTE_CACHE_FRESH_MS;if(cached)renderTaste(cached);- else $('#stats').innerHTML=`<div class="tastepage"><div class="skeletonpanel">- <span class="skeleton" style="width:38%"></span>- <span class="skeleton" style="width:100%"></span>- <span class="skeleton" style="width:100%"></span>- <span class="skeleton" style="width:72%"></span></div></div>`;+ else $('#stats').innerHTML=`<div class="tastepage">${pageSkeletonHtml('正在读取口味分析')}</div>`;if(!cacheFresh){const request=++tasteRequest;const requestedWindow=tasteWindow;@@ -2025,6 +2057,7 @@ async function openPlaylists(push=true){releaseHoverPreviews();disposeStage(false);enterManagementSurface();if(push)route('/playlists');const surface=claimSurface('/playlists');+ showManagementBody({manage:false,placeholder:pageSkeletonHtml('正在读取播放列表',{cards:true})});const data=await api('/api/playlists');if(!surfaceCurrent(surface))return;showManagementBody({manage:false});@@ -2059,7 +2092,7 @@ async function openDuplicates(push=true){releaseHoverPreviews();disposeStage(false);enterManagementSurface();if(push)route('/duplicates');const surface=claimSurface('/duplicates');- showManagementBody({placeholder:`<div class="review"><p class="empty">${loadingDotsHtml('正在比对')}</p></div>`});+ showManagementBody({placeholder:pageSkeletonHtml('正在比对重复内容',{cards:true})});const next=await api('/api/duplicates?limit=120');if(!surfaceCurrent(surface))return;dupData=next;@@ -2137,7 +2170,7 @@ async function openReview(push=true){releaseHoverPreviews();disposeStage(false);enterManagementSurface();if(push)route('/review');const surface=claimSurface('/review');- showManagementBody();+ showManagementBody({placeholder:pageSkeletonHtml('正在读取复核队列',{cards:true})});const runtime=await api('/healthz');if(!surfaceCurrent(surface))return;/* ADR-0018:确定的那部分先落库再取队列。reader 明知不能写就不要制造一次 409;@@ -2274,7 +2307,7 @@ async function openQualityGoals(push=true){releaseHoverPreviews();disposeStage(false);enterManagementSurface();if(push)route('/quality-goals');const surface=claimSurface('/quality-goals');- showManagementBody({placeholder:`<div class="review"><p class="empty">${loadingDotsHtml('正在读取')}</p></div>`});+ showManagementBody({placeholder:pageSkeletonHtml('正在读取高清版目标',{cards:true})});const next=await api('/api/quality-goals?limit=200');if(!surfaceCurrent(surface))return;qualityData=next;@@ -2299,6 +2332,14 @@ async function openQualityGoals(push=true){以及对内容做批量标记。联网只发生在管理页点「检查更新」的那一刻——看的那一页不联网。 */let followData=null,followRuntime=null,followFilter='new',followBusy=false,followManageSort='checked';+let followDiscoverySeed=Math.floor(Math.random()*0xffffffff);+const followDiscoveryRank=value=>{+ let hash=(2166136261^followDiscoverySeed)>>>0;+ for(const char of String(value)){hash^=char.codePointAt(0);hash=Math.imul(hash,16777619)>>>0}+ return hash;+};+const followRandomOrder=(rows,key)=>[...rows].sort((a,b)=>+ followDiscoveryRank(key(a))-followDiscoveryRank(key(b))||String(key(a)).localeCompare(String(key(b))));/* 来源筛选:fsrcProviders 记录见过的全部来源(默认全选),fsrcUnchecked 只记被取消勾选的——新来源自动进入「全选」。 */const fsrcProviders=new Set(),fsrcUnchecked=new Set();@@ -2379,37 +2420,9 @@ function followWhen(item){}const followTagType=(item,tag)=>item.tag_types&&item.tag_types[tag]||'general';-/* 卡片上只留「玩法」这一类:体位、动作、视角。-- 题材不留——`copyright`(Final Fantasy、Genshin Impact)和 `artist` 整类都是,- 看卡片时已经知道自己在看谁的什么作品了。-- 麻烦在于站点把三种东西都塞进了 `general`:真正的玩法(straight、male pov)、- 技术标记(animated、loop、blender、sound)、以及又一份题材(Final_Fantasy_VII、- InitialA)。所以只按标签类型过滤不够,还要按两条判据再筛一遍。 */-//: booru 的角色消歧写法 `角色 (作品)`。这类标签的 tag_types 常常也是 general,-//: 靠类型分不出来,但括号后缀是站点约定,认得出。-const FOLLOW_TAG_TOPICAL=/\([^)]+\)\s*$/;-//: 计数与技术标记:说的是「这条素材怎么做的」,不是「里面发生了什么」。-const FOLLOW_TAG_NOISE=/^(?:\d+\s*(?:boy|girl|futa)s?|solo|animated|loop|no\s*sound|sound|blender|3d|2d|cgi|hd|highres|absurdres|video|webm|mp4|vertical\s*video|horizontal\s*video)$/i;-//: 把 `Final_Fantasy_(series)` 与 copyright 里的 `Final Fantasy` 归一到同一个键,-//: 好把混进 general 的那份题材也认出来。-const followTagKey=tag=>String(tag).toLowerCase()- .replace(/\([^)]*\)/g,'').replace(/[_\s-]+/g,'').trim();-const followCardTags=item=>{- const tags=item.tags||[];- // 题材集合:非 general 的那些标签本身,用来反查混进 general 的同名项。- const topical=new Set(tags.filter(tag=>followTagType(item,tag)!=='general')- .map(followTagKey).filter(Boolean));- return tags.filter(tag=>{- if(followTagType(item,tag)!=='general')return false;- if(FOLLOW_TAG_NOISE.test(String(tag).trim()))return false;- if(FOLLOW_TAG_TOPICAL.test(String(tag)))return false;- const key=followTagKey(tag);- // 与某个题材同名,或本身就是题材的子条目(Final_Fantasy_VII ⊂ finalfantasy)- return !!key&&![...topical].some(t=>key===t||key.startsWith(t)||t.startsWith(key));- });-};+/* 卡片、详情、筛选条和在线标签页都只消费服务端的内容标签投影。过滤只维护一份,+ 原始来源标签仍完整留在 metadata。 */+const followCardTags=item=>item.tags||[];const followTagChip=(item,tag,kind='span')=>`<${kind} class="tg r34-${esc(followTagType(item,tag))}" data-follow-tag="${esc(tag)}">${esc(tagLabel(tag))}</${kind}>`;@@ -2666,17 +2679,14 @@ async function openFollowDetail(id,push=true,mediaIndex=null,preserveReturn=fals}const followVideo=$('#stage').querySelector('.followdetailmedia>video');if(followVideo){- /* 清晰度单独问一次:解析要抓来源详情页,列表一次几百条不可能逐条解析,- 所以只在用户真的展开某个条目时问。取不到就当只有原画,不挡播放。 */- let followQualities=null;- try{- const answer=await api(`/follow-qualities?id=${encodeURIComponent(item.id)}`);- followQualities=answer?.qualities?.length?answer.qualities:null;- }catch(_e){}+ /* 清晰度解析与默认片源并行。它需要回源抓详情,不能挡住播放器挂载;否则来源慢+ 一点,详情里就会先留下一个没有 src 的空视频框。 */+ const qualitiesPromise=api(`/follow-qualities?id=${encodeURIComponent(item.id)}`)+ .then(answer=>answer?.qualities?.length?answer.qualities:null).catch(()=>null);const followPlayer=mountDetailPlayer(item,followVideo,false,{source:{src,type:selectedMedia?.media_type||item.media_type||'video/mp4'},checkSourceStatus:false,- qualities:followQualities+ qualitiesPromise});const stopFollowAmbient=mountPlayerAmbient(followVideo);followPlayer?.one?.('dispose',stopFollowAmbient);@@ -2895,8 +2905,8 @@ function renderFollow(){const authors=new Map([...authorSources].filter(([key])=>activeAuthors.has(key)).map(([key,list])=>[key,{name:followAuthorName(list),sources:list,}]));- const rankedTags=[...tagCounts].sort((a,b)=>b[1]-a[1]);- const topTagRows=rankedTags.slice(0,20);+ const randomizedAuthors=followRandomOrder([...authors],row=>row[0]);+ const topTagRows=followRandomOrder([...tagCounts],row=>row[0]).slice(0,20);followTags.forEach(tag=>{if(tagCounts.has(tag)&&!topTagRows.some(([key])=>key===tag))topTagRows.push([tag,tagCounts.get(tag)]);@@ -2922,7 +2932,7 @@ function renderFollow(){$('#stats').innerHTML=`<div class="follow"><div class="followhead"><h2 class="disp pagetitle">关注</h2><button class="fbtn primary fcheck" data-follow-manage>${icon('settings')}管理关注</button></div>- ${authors.size?`<div class="tier followauthors" aria-label="按作者筛选">${[...authors].map(([key,author])=>+ ${authors.size?`<div class="tier followauthors" aria-label="按作者筛选">${randomizedAuthors.map(([key,author])=>`<button class="av" data-follow-author="${esc(key)}" aria-pressed="${key===followAuthor}"><span class="ring">${followAuthorAvatar(author.sources)}</span><span class="nm">${esc(author.name)}</span></button>`).join('')}</div>`:''}@@ -3021,11 +3031,12 @@ async function openFollow(push=true,renderForDetail=false){/* 从窄栏点进来(push)是「重新进入」,回到干净的 /follow;其余情况一律照 URL推导。筛选状态不再靠这里逐个手写重置——漏一个就会像 provider、tag、status以前那样一直按着,而它们还决定服务端取哪些条目,等于取错数据。 */+ if(push)followDiscoverySeed=Math.floor(Math.random()*0xffffffff);if(push)route('/follow');if(location.pathname==='/follow')readFollowView();const surface=claimSurface(renderForDetail?surfacePath():'/follow');showManagementBody({manage:false,- placeholder:`<div class="follow"><p class="empty">${loadingDotsHtml('正在读取')}</p></div>`});+ placeholder:`<div class="follow">${pageSkeletonHtml('正在读取关注内容',{cards:true})}</div>`});const [data,credentials]=await Promise.all([api(followPageUrl(0)),api('/api/follow/credentials').catch(()=>({providers:[]})),@@ -3057,9 +3068,11 @@ function followAuthorGroups(sources){const groups=order.map(key=>byKey.get(key));const name=group=>followAuthorName(group);const checked=group=>Math.max(...group.map(source=>Date.parse(source.last_checked_at||'')||0));+ const added=group=>Math.max(...group.map(source=>Date.parse(source.created_at||'')||0));return groups.sort((a,b)=>{if(followManageSort==='name')return name(a).localeCompare(name(b),'zh-CN',{numeric:true});if(followManageSort==='sources')return b.length-a.length||name(a).localeCompare(name(b),'zh-CN',{numeric:true});+ if(followManageSort==='added')return added(b)-added(a)||name(a).localeCompare(name(b),'zh-CN',{numeric:true});return checked(b)-checked(a)||name(a).localeCompare(name(b),'zh-CN',{numeric:true});});}@@ -3289,6 +3302,7 @@ function renderFollowManage(credentials){counts.new?` · <b>${counts.new}</b> 条未看`:''}</span><label class="fmanagesort"><span>排序</span><select data-follow-sort aria-label="关注列表排序"><option value="checked"${followManageSort==='checked'?' selected':''}>最近检查</option>+ <option value="added"${followManageSort==='added'?' selected':''}>添加时间</option><option value="name"${followManageSort==='name'?' selected':''}>作者名称</option><option value="sources"${followManageSort==='sources'?' selected':''}>来源数量</option></select></label>@@ -3334,10 +3348,10 @@ async function openFollowManage(push=true){if(push){followManageSort='checked';route('/follow-manage')}else if(location.pathname==='/follow-manage'){const requested=new URLSearchParams(location.search).get('sort');- followManageSort=['checked','name','sources'].includes(requested)?requested:'checked';+ followManageSort=['checked','added','name','sources'].includes(requested)?requested:'checked';}const surface=claimSurface('/follow-manage');- showManagementBody({placeholder:`<div class="follow"><p class="empty">${loadingDotsHtml('正在读取')}</p></div>`});+ showManagementBody({placeholder:`<div class="follow">${pageSkeletonHtml('正在读取关注管理',{cards:true})}</div>`});const [data,credentials,runtime]=await Promise.all([api('/api/follow?limit=1'),api('/api/follow/credentials'),api('/healthz')]);if(!surfaceCurrent(surface))return;@@ -3835,6 +3849,7 @@ async function openIndex(kind,q,push=true){// 写在前面等于自己加完自己删。document.body.classList.add('index-open');disposeStage(false);+ showIndexLoading(people?'正在读取作者':'正在读取标签');/* 在线标签走关注页那套统计,形状与 /api/index 一致,所以分页、搜索和「载入更多」这三处现成的机制换个地址就能用。 */const indexApi=offset=>onlineTags@@ -4318,6 +4333,8 @@ async function openEntity(kind,name,push=true,requestedTag){barsContext={type:'entity',kind,name,filters};showHomeSurfaces();disposeStage(false);+ document.body.classList.add('entity-open');+ showIndexLoading('正在读取资料');detailReturnBarsContext=null;entityJavLayout=false;const seq=++entityRequestSeq;@@ -5179,7 +5196,8 @@ async function openItem(id,push=true,queueContext=null,anchor=null){</div><button class="obtn" data-kind="o">${icon('sperm')}<span>记一次高潮</span><b class="mono" id="oCount">${it.o_count||0}</b></button></div></div></div>- ${queueContext?'':`<div class="next"><h3>接着看</h3><div class="nrow" id="nrow">载入中…</div></div>`}`;+ ${queueContext?'':`<div class="next"><h3>接着看</h3><div class="nrow" id="nrow">${+ pageSkeletonHtml('正在读取推荐',{cards:true,className:'related-skeleton'})}</div></div>`}`;$('#stage').classList.toggle('ambient-on',appSettings.ambientMode);$('#stage').classList.toggle('theater-mode',appSettings.theaterMode);diff --git a/web/index.html b/web/index.htmlindex 1b8fb8d69..4ad1acf3d 100644--- a/web/index.html+++ b/web/index.html@@ -124,14 +124,14 @@<h2 class="disp managetitle" id="manageTitle" hidden></h2><p class="pagelede mono" id="manageLede" hidden></p><section class="stats" id="stats" hidden></section>- <div class="count mono" id="count" role="status" aria-live="polite" aria-atomic="true">载入中…</div>+ <div class="count mono" id="count" role="status" aria-live="polite" aria-atomic="true"></div><div class="grid" id="grid"></div><section class="shorts" id="shortsSec" hidden><h2 class="disp">竖屏 <span class="mono" style="color:var(--muted);font-size:11px" id="shortsN"></span><button id="tokBtn"><svg viewBox="0 0 24 24" aria-hidden="true"><use href="#i-play"/></svg><span>进入沉浸模式</span></button></h2><div class="srow" id="srow"></div></section>- <div class="loadmore mono" id="loadSentinel" hidden>继续载入中…</div>+ <div class="loadmore mono" id="loadSentinel" hidden></div></main><div class="scrim" id="scrim"></div>@@ -152,7 +152,7 @@<div class="tokaction"><button id="tokO" title="记一次高潮" aria-label="记一次高潮"><svg viewBox="0 0 24 24"><use href="#i-heart"/></svg></button><span class="toklabel">高潮 <b id="tokOn">0</b></span></div></div></div>- <div class="tokloading" id="tokLoader" role="status" aria-live="polite" hidden><span class="tokspinner" aria-hidden="true"></span><span id="tokLoadingText">加载中…</span></div>+ <div class="tokloading" id="tokLoader" role="status" aria-live="polite" hidden><span id="tokLoadingText">加载中…</span></div><div class="tokhint mono">滚轮 / ↑↓ 切换 · Esc 退出 · 横竖屏混流</div><button class="tokclose" id="tokClose" title="关闭" aria-label="关闭"><svg viewBox="0 0 24 24"><use href="#i-x"/></svg></button><div class="tokbar" id="tokBar"><i id="tokProg"></i></div>diff --git a/web/js/ui-components.js b/web/js/ui-components.jsindex fb8f0f7ae..60076f8a5 100644--- a/web/js/ui-components.js+++ b/web/js/ui-components.js@@ -35,6 +35,20 @@ export function loadingDotsHtml(label='正在处理', {className=''}={}){<span>${esc(label)}</span></span>`;}+/** Geist Skeleton: reserve a large content region while its structure is loading. */+export function skeletonHtml(label='正在读取内容',{className='',variant='panel'}={}){+ const kind=new Set(['panel','cards']).has(variant)?variant:'panel';+ const body=kind==='cards'+ ?Array.from({length:6},()=>`<span class="skeletoncard"><i></i><b></b><em></em></span>`).join('')+ :`<span class="skeleton" style="width:38%"></span>+ <span class="skeleton" style="width:100%"></span>+ <span class="skeleton" style="width:100%"></span>+ <span class="skeleton" style="width:72%"></span>`;+ return `<div class="skeletonpanel skeleton-${kind}${className?` ${esc(className)}`:''}"+ role="status" aria-label="${esc(label)}"><span class="sr-only">${esc(label)}</span>+ <div aria-hidden="true">${body}</div></div>`;+}+/** Shared video/image view buttons for entity profiles and the follow feed. */export function mediaViewButtonsHtml({active='videos',videoValue='videos',imageValue='images',videoLabel='视频',imageLabel='图片',