Skip to content

armgit / peach

Public Imported from GitHub
0

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

fix follow media loading and action feedback

longmeidaof616994e5944
diff --git a/.claude/skills/peach-web-ui/SKILL.md b/.claude/skills/peach-web-ui/SKILL.md
index 0c30518f9..d059daca5 100644
--- a/.claude/skills/peach-web-ui/SKILL.md
+++ b/.claude/skills/peach-web-ui/SKILL.md
@@ -43,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。整页或大区块首次取数使用 Skeleton 预留最终结构。Spinner/Loading Dots 保留可见状态文字;Skeleton 只保留给辅助技术的状态名,不另画「正在读取」文案。三者都尊重 reduced motion。
+- Spinner 只反馈用户直接触发的动作,触发器统一调用 `setActionBusy()`:写入 `aria-busy=true` 与 `aria-disabled=true`、视觉变灰、拦截重复触发,同时保持可聚焦;请求等待期不得再用原生 `disabled`,它只留给缺输入、无权限等动作确实不可执行的状态。未知时长的后台抓取使用 Loading Dots。整页或大区块首次取数使用 Skeleton 预留最终结构。Spinner/Loading Dots 保留可见状态文字;Skeleton 只保留给辅助技术的状态名,不另画「正在读取」文案。三者都尊重 reduced motion。
+- 用户写操作只在服务端终态成功后调用共享 `actionReceipt()` 发一条过去时 Toast;可由安全逆操作完整恢复的状态提供 8 秒“撤销”,永久删除、凭据、保存到账本等不伪造撤销。仅打开面板/菜单/Dialog 不算操作完成,不发 Toast;失败除短 Toast 外仍在原位置保留原因与重试入口。
- 同一次页面进入只呈现一段等待态;深链启动与页面取数复用同一个 Skeleton,禁止 Spinner 再切换成 Loading Dots 或 Skeleton。
- Skeleton 只覆盖真正等待的内容区;静态标题、导航和能同步得到的筛选控件立即显示。骨架必须复用最终容器的宽度、列数与对齐方式:卡片网格横向铺满,居中面板仍居中,不得用一列通用占位替代不同页面结构。
- 关注来源标签先服从来源记录的类型:只有明确标为 `general` 的标签才能进入卡片、顶部筛选和在线标签页,`artist`/`character`/`copyright`/`metadata` 与未知类型不得靠词形猜成 `general`。通用词清理是第二道门槛,只处理已经确认的 `general`;详情可显示全部来源标签,并按真实类型着色。
diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md
index b53bbba13..246229948 100644
--- a/docs/HANDOFF.md
+++ b/docs/HANDOFF.md
@@ -76,7 +76,7 @@ Claude 的 `.claude/settings.json` 已配置 Stop、StopFailure、SessionEnd hoo
**Vercel Geist 控件(2026-08-28)**:官方 introduction 页实测普通操作使用 4/6px 圆角、图标操作为 32×32px,圆形留给 emoji 反馈等特殊语义。Peach 的普通操作和关闭按钮因此统一用 `--control-radius:6px`,菜单与 Modal 使用 `--floating-radius:12px`,状态标记使用 `--badge-radius:4px`;Tag 保持胶囊,媒体左右切换与头像保留圆形。全站字号、顶栏、搜索、播放列表、设置、管理、详情、关注与移动端共用这套语义 token;弹层自己的滚动容器必须使用 `overscroll-behavior:contain`,粘性标题栏要设置 `scroll-padding-top`,不能遮住键盘焦点。锁定版本、完整测量和有意差异见 `vercel-geist-controls-measured.md`。**Vercel Geist MiddleTruncate(2026-08-30)**:官方页 <https://vercel.com/geist/middle-truncate> 规定只对文件路径、URL、ID、SHA 等首尾都有信息的值做中间省略;单个 `…` 随容器宽度重算,复制和无障碍名称保留完整原文,外层不得再套 `text-overflow:ellipsis`。Peach 用原生 ES module 适配这套行为,不引入 React;资源标识必须显式使用 `data-middle-truncate`,标题、说明、人名和标签保留末尾省略;页面源门槛登记全部末尾省略选择器,任何新增截断都必须先分类。实时浏览器 DOM/CSS/JS 本轮未取得,通道错误与候选判断见 `vercel-geist-middle-truncate.md`。
**Vercel Tooltip/Collapse/Context Card/Projects/Analytics/Speed Insights 与 Geist Note/Progress/Switch/Fieldset/Scroller/Empty State(2026-08-30)**:登录态项目页确认搜索占剩余宽度、筛选为方形图标钮、主操作在右,菜单无展开动画且内部滚动;Analytics 与 Speed Insights 都使用「全局筛选或来源 Switch → 横向摘要指标带 → 主详情 → 同层 tablist 数据面板」层级,不把每个维度堆成独立 Bento。Peach 的统计页用真实库存、观看、覆盖和系统盘/资源盘/网盘使用空间复用该层级;口味页以浏览器记录/Peach 内部作为真实证据来源,不伪造体验分或时间图。Tooltip 固定在视口内,来源菜单不得套用 Collapse motion,作者别名才使用 Collapse;短元数据浮层最多一个主动作,Escape 关闭并交还焦点,瞬时成功回执用 Toast,错误恢复留在原位置;Note 只放字段/卡片/分区旁的持久上下文,页面问题用 Banner;Progress 必须有真实 value/max 和 ARIA,Switch 只用于 2–3 个互斥视图,布尔值用 Toggle;Fieldset 同组卡片固定同高,变化正文放单一 Scroller,Footer 保持固定动作区;Empty State 必须把图标、标题、说明和可选动作收在同一组件,且与上方工具条保持统一间距。完整 URL、资源 SHA、浏览器失败与恢复路径和 Peach 差异见 `vercel-geist-semantics-measured.md`、`vercel-geist-note-progress-switch-analytics.md` 与 `vercel-geist-fieldset-scroller-empty-state.md`;实现门槛见 `peach-web-ui`。
**Vercel Geist Table/Home(2026-08-30)**:同形可比较数据使用语义 `table`,数字列保持 tabular numerals;Peach 因此把系统盘、资源盘、115 与 PikPak 容量放进同一张使用空间表。内容标签是固定 Top 排行和直接筛选,不伪装成可排序数据表,桌面使用保持 DOM 排名顺序的双栏有序列表,手机回到单栏。Vercel Table 的交互 DOM 与计算样式本轮未取得,Home 只确认共享对齐和清晰分区;失败通道、已取得原则与有意差异见 `vercel-geist-table-ranking.md`。
-默认 Note、只读提示和 info 入口统一复用图片详情已有的本地 Lucide 圆圈 `i`,并显式使用 2px 描边与圆端点保证 `i` 的圆点可见,不复制未开放许可的 Geist 私有 SVG。**Vercel Command Menu/Search Input/Spinner/Loading Dots(2026-08-30)**:设置覆盖层使用锁定 Dialog CSS 的 350ms、`cubic-bezier(.4,0,.2,1)` 与 -40px 淡入轨迹,普通菜单仍无动画;Search Input 的搜索图标在查询期间原位换成 Spinner。用户直接触发的检查、加载、保存与应用使用 Spinner,后台抓取和扫描进度使用 Loading Dots;“没有更多历史内容”是中性、可关闭的 Note,不得登记为红色故障。证据哈希、未取得面与 Peach 差异见 `vercel-geist-command-search-loading.md`。**Vercel Notifications 中性说明 Note(2026-08-30)**:登录态截图确认底部补充说明使用带圆圈信息图标的整行中性表面,存在真实动作时链接紧跟正文;Peach 的口味归因和隐私说明复用 secondary `noteHtml`,没有真实动作时不伪造链接。实时 DOM/CSS 读取在 30 秒后超时,已取得边界、截图哈希和有意差异见 `vercel-notifications-note.md`。
+默认 Note、只读提示和 info 入口统一复用图片详情已有的本地 Lucide 圆圈 `i`,并显式使用 2px 描边与圆端点保证 `i` 的圆点可见,不复制未开放许可的 Geist 私有 SVG。**Vercel Command Menu/Search Input/Spinner/Loading Dots(2026-08-30,Button 于 2026-09-01 复核)**:设置覆盖层使用锁定 Dialog CSS 的 350ms、`cubic-bezier(.4,0,.2,1)` 与 -40px 淡入轨迹,普通菜单仍无动画;Search Input 的搜索图标在查询期间原位换成 Spinner。用户直接触发的检查、加载、保存、应用和分页抓取使用 Spinner,后台扫描进度使用 Loading Dots;等待按钮通过共享 busy 状态变灰并阻止重复触发,但不用原生 `disabled`,以保留焦点和 busy 播报。“没有更多历史内容”是中性、可关闭的 Note,不得登记为红色故障。证据哈希、未取得面与 Peach 差异见 `vercel-geist-command-search-loading.md`。**Vercel Notifications 中性说明 Note(2026-08-30)**:登录态截图确认底部补充说明使用带圆圈信息图标的整行中性表面,存在真实动作时链接紧跟正文;Peach 的口味归因和隐私说明复用 secondary `noteHtml`,没有真实动作时不伪造链接。实时 DOM/CSS 读取在 30 秒后超时,已取得边界、截图哈希和有意差异见 `vercel-notifications-note.md`。
**Beeg 资料页(2026-08-30)**:Reislin 与 SweetieFox 页面证据锁定的顺序是头像与名称、简介、外部链接、关联艺人轨道、标签轨道、内容;轨道不另加可见标题。Peach 的女优/厂牌资料页和关注页复用这个阅读顺序;资料页有照片时只显示一个 32×32px `PicsIcon`,放在标签左侧,选中代表照片视图,再点一次回到视频,不保留独立的「视频/照片」文字标签栏。合集详情继续使用普通详情的左媒体、右信息,下方另设 Mix/分卷/播放列表/多视频的横向切换带。锁定样式摘要、哈希、未取得面和主动差异见 `beeg-profile-layout.md`。**JAV 标题(2026-08-31)**:用户截图只锁定“粗体大写番号 + 作品标题、隐藏媒体扩展名”的显示语义;原页面 URL、DOM、字体和间距未取得。Peach 仅在 `is_jav` 项目的卡片、详情、沉浸和集合队列应用,不修改真实文件名,也不在账本只有番号时伪造官方标题。截图哈希与边界见 `jav-title-user-screenshot.md`。
YouTube Shorts 沉浸页使用用户截图记录 `docs/reference-snapshots/youtube-shorts-immersive-user-screenshot.md`:竖屏复用中央 9:16 舞台和外置动作列,横屏使用在整个视口视觉居中的 16:9 舞台并把动作列收进视频右侧;Peach 保留自己的反馈语义,不复制订阅或社交动作。沉浸视频每次加载都要带独立 `session`,切片、关闭、失败和页面离开时取消旧会话;只清浏览器的 `src` 不足以停止 CloudDrive 预读或 FFmpeg。普通播放器控制栏另使用用户截图、实际 YouTube `e937390a` 播放器 DOM/CSS/JS 和官方帮助记录 `docs/reference-snapshots/youtube-player-controls-user-screenshot.md`:控制栏为透明 59 px 两排结构;左侧播放是 40 px 圆钮,音量从 40 px 展开到 111 px且静音键固定在首个 40 px 内,音量外层用内缩 4 px 的白色 10% 伪元素同时覆盖图标和滑轨,2 px 滑轨固定在 40 px 高容器的 50%;音量 tooltip 必须位于进度层之上且不得被 volume bar 裁切。时间胶囊可切换已播/剩余。右侧画中画/设置/影院/全屏是 48×40 px 单钮共用一个 40 px 高、28 px 圆角深色胶囊。进度轨道按 200 ms 从约 4 px 放大到 6 px,12 px 圆点从隐藏放大到约 20 px;已播段、圆点和卡片观看进度统一使用 Peach 蓝。进度圆点自带的当前时刻 tooltip 必须隐藏,只保留指针位置的 `vjs-peach-seek-preview`。中央的 78 px 深色播放/暂停层只作用户手势后的 1 秒 bezel 反馈,初始不可见,waiting/seeking 时必须让位给按官方 DOM 与四组 keyframes 实现的 64 px loading,不能两层重叠;键盘仍按设置前后跳转,控制栏和中央层都不画 10 秒按钮。本地时刻预览复用九宫格接触表,在线视频只显示时刻。设置浮层按实测 274 px 宽、12 px 圆角、48 px 行高、56 px 图标列和 57 px 子菜单标题栏,只列真实能力;整行悬停覆盖图标、文字、值和箭头,40×24 px 开关的 20 px 圆点保留 2 px 边距。子菜单返回键保留 48 px 命中区和 32 px 箭头,内部悬停/按下圆形仅 40 px,不能越出 57 px 标题栏。环境模式、播放速度、画质、子层箭头和中央 bezel 必须使用已锁定 `e937390a` current modern 分支的原始 SVG path,不再按 Lucide 近似;子层 radio 勾选必须使用锁定版本的 24 px 填充 check path 放在左列、标签从 35 px 开始,不能复用全站描边勾或在选项右侧留下尾标。影院模式用按钮或 `T` 切换为大播放器,展开/收回使用不同图标和「影院模式/默认视图」提示;全屏播放器固定到四个视口边缘并使用 `100vw × 100vh`,普通视图用 `contain` 保全画面,全屏按用户明确要求用 `cover` 铺满视口并接受非等比例片源的边缘裁切。音量、画中画、设置项和全屏继续使用统一的本地 SVG;Peach 不复制没有实际能力的字幕、睡眠定时或自动播放按钮。
F95 masked 链接与 Gofile 文件列表的凭据边界见 `f95-masked-gofile-media`;Mix 只按已解析且
@@ -90,7 +90,7 @@ FANBOX 正文统一先经过 `peach.fanbox.normalize_fanbox_post`:数据模型
进入可切换媒体,压缩包等文件只保留为资源链接,重复 URL 按正文首次出现顺序去重。
Gofile token 是另一份本机可选凭据,只进 Gofile 请求头,不进 URL、证据、ledger 的公开投影
或浏览器 JSON。Gofile 当前把 contents API 限给 Premium;`error-notPremium` 要按套餐限制
-报告,不能误报成 token 无效。未取得文件列表时保留分享页,不得声称已经取得视频。
+报告,不能误报成 token 无效。未取得文件列表时保留分享页,不得声称已经取得视频。同一篇 FANBOX 可含多个 Gofile 文件夹:作品级仍为一个来源合集,媒体保留文件夹 id 与正文标签(如 `Mitsuru`/`Poll`)并在详情队列内分段,不能拆作品或压平混排。
## 批处理边界
diff --git a/docs/STATUS.md b/docs/STATUS.md
index e5226741a..1c792be8f 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -21,6 +21,7 @@ undefine
## 已核验能力
- 2026-09-01 JAV 详情身份区收齐到同一内容起点:115 来源图标、`厂牌` 标题、厂牌头像和名称不再逐层缩进;全站链接交互不再使用文字下划线,女优名以颜色、背景和描边反馈。文件名清洁仅在实际移除方括号域名后规整残留分隔符,避免把无关双连字符文件误纳入批次;最终计划 49 条全部完成,失败、源缺失、目标缺失和 ledger 行不一致均为 0。真实 ledger 已先后备份并应用 `0022`、`0023`,asset 75499、asset_tag 81196、entity 8178、asset_entity 145915 均未改变,`integrity_check=ok`、外键违规 0。最新主线 Windows 正式全量 1482 项通过、13 项按平台跳过;生产托盘与 80/443 子服务已用普通权限重启,项目 CA、SNI、主机名严格 HTTPS `/healthz` 返回 0.7.13、writer、非只读。内置浏览器实测桌面详情内容起点为 882 px;390×844 手机下来源、标题、头像和名称内容起点均为 35 px,横向溢出 0;女优链接计算样式为无下划线。
+- 2026-09-01 操作回执、关注媒体与 GoFile 归组已在隔离工作树完成:详情工具栏、关注卡片、稍后看、回收/垃圾处置、目录核对、播放列表、关注来源、凭据与批量操作统一复用终态 Toast;能安全反向写入的操作提供 8 秒撤销,等待按钮保持可聚焦但变灰且阻止重复提交。关注视频/图片详情复用同一媒体选择路径;显式图片/视频筛选即使为 0 项也保留切换控件。一个 FANBOX 作品仍是一个外层合集,多个 GoFile 链接只在合集内部按文件夹标签分段并保留各自媒体归属。F95 已保存会话的下次显式检查会重解析旧条目,不再被 304 短路。最新主线 Windows 正式全量 1496 项通过、13 项按平台跳过;生产切换待本分支集成后核验。本轮未触发真实关注检查,未写真实 ledger、候选或媒体。
- 2026-09-01 关注页加载与来源标签语义收口:静态标题立即显示,Skeleton 只覆盖慢内容并按最终横向网格/居中面板占位;Spinner 与 Loading Dots 不再串成第二段等待。Rule34.xxx 检查从来源帖子页记录 `general`/`artist`/`character`/`copyright`/`metadata`,`blender`、`3d`、`3d_model` 实测均为 `metadata`;卡片、顶部筛选和在线标签页只接收来源明确标为 `general` 且通过第二层通用词清理的标签,旧行未知类型不再猜测,详情仍显示全部标签并按类型着色。关注详情舞台在 `.followlist` 中跨满整行,管理作者标题去掉 `Collection` 容器后缀。最新主线组合后 Windows 正式全量 1421 项通过、13 项按平台跳过;生产托盘与 80/443 子服务已重启,项目 CA、SNI、主机名严格 HTTPS `/healthz` 返回 0.7.13、writer、非只读,本轮三个前端资源哈希与当时已合入源码一致。内置浏览器实测桌面舞台/列表均为 1166 px、视频 774×435,手机可用宽度 380 px 下舞台 348 px、视频 346×194,二者均为真实 `/follow-stream?id=2841` 且横向溢出 0;关注管理标题显示 `Billyhhyb`,导航相对内容区居中。旧 Rule34 行需下一次用户主动检查后才补齐来源类型;本轮未触发检查、未写真实 ledger、候选或磁盘媒体。
- 2026-08-31 “定位源文件”反馈已统一复用 Geist 语义:等待态只在触发按钮内显示 Spinner,以 `aria-busy` 阻止重复请求但不禁用按钮;成功在右下角短暂 Toast“已在资源管理器中显示”,只有失败原因留在内容流。Windows `catalog` 492 项通过;在当前 HTTPS 页面拦截 `/api/reveal`、替换为候选 `app.js` 后,1280×800 与 390×844 的请求等待期详情内容高度均保持 460.5625 px,页面总高度分别保持 1210 px 与 1415 px,状态行持续隐藏,26×26 按钮尺寸不变且 Spinner 可见。项目 CA 严格 HTTPS `/healthz` 返回 0.7.13、writer、非只读;本轮未调用真实定位接口、未写真实 ledger、未替换生产入口。
- 2026-08-31 JAV 官方封面规范化流程已写入项目技能并完成首轮全库正式执行:960 个非 FC2 JAV 番号中,824 张封面全部可解码,136 个仍缺失;缺失补抓新增 17 张,已有封面按像素面积升级 156 张,其中 Prestige 官方 API 133、DMM CDN 16、MGS 7。宽度不超过 800 的封面由 429 降至 274,宽度至少 1200 的由 305 增至 447;`ABW-232` 当前为 Prestige 官方 1024×690。流程先复用 Javinizer 原始证据,再量 DMM modern/legacy、Prestige、MGS 与历史精确 URL,按主机保持 1.5 秒限流;AVBase 遇 Cloudflare 即放弃且不绕过。正式 `metadata` 184 项通过,抓取批次退出码 0;封面与逐条来源日志已更新,批前日志备份为 `cover-fetch-log.pre-workflow-20260831.csv`。本轮不写 ledger、不改媒体文件,脚本与生成封面无需重启生产服务。
diff --git a/docs/reference-snapshots/vercel-geist-command-search-loading.md b/docs/reference-snapshots/vercel-geist-command-search-loading.md
index e28c2b7b4..05d1fef5a 100644
--- a/docs/reference-snapshots/vercel-geist-command-search-loading.md
+++ b/docs/reference-snapshots/vercel-geist-command-search-loading.md
@@ -1,6 +1,6 @@
# Vercel Geist Command Menu、Search Input、Spinner 与 Loading Dots
-取证日期:2026-08-30。
+首次取证日期:2026-08-30;Button 补充复核:2026-09-01。
## 锁定来源
@@ -8,6 +8,7 @@
- <https://vercel.com/geist/search-input> HTML SHA-256:`55F62A034450EB68A4D2A46726A0A9A8CF806570C2E31162C6C869F4B38C21A2`
- <https://vercel.com/geist/spinner> HTML SHA-256:`DD1B8A0742A6504D0E8852FAA61269C8720CB7C360B1B9FED6C9BF4C64772C60`
- <https://vercel.com/geist/loading-dots> HTML SHA-256:`CB5548EF02D135DFA26DF1A9881F3E57E79F3F846C4DE3F3A94FB4AC4CEB8983`
+- <https://vercel.com/geist/button> HTML SHA-256:`29941BBD7F091FD7AA397466F243F62A420918C884255D499EFC29878D56DF99`
- 官方 CSS `1zsi1fomvr48z.css`:`62B3416EB6D73D86FCF284B5A9FD05A69DCBB091E3D79B6725EC83F0990E6ECE`
- 官方 CSS `328y7_b581oob.css`:`3034E6739AE0E19814DF6E53BA7FEBEFE56CF986ED0F1C3534DF9AEE1F751B87`
- 官方 CSS `3ej-07gndl9ds.css`:`587B35B6741B202EE2A7ACAFB4D2A9C6EA2A2819DA55BCF218634FA91A5617EE`
@@ -19,6 +20,7 @@
- Command Menu 是全屏覆盖层。官方 Dialog 打开时使用 `350ms cubic-bezier(.4,0,.2,1)`,内容从 `translate3d(0,-40px,0); opacity:0` 到原位;关闭反向,背景同步淡入淡出。
- Search Input 前缀是搜索图标。Peach 在请求期间原位替换为 Spinner,输入框几何不变。
- Spinner 用于用户直接触发且等待结果的动作,例如按钮与分页;容器声明 `aria-busy=true`,Spinner 自身为 `role=status`。
+- Button 官方用 `loading` 表达请求中状态,明确要求触发器继续可聚焦并向辅助技术播报 busy;原生 `disabled` 只用于动作当前确实不可能执行的情况,而不是请求等待期。
- 官方 Spinner 由 10 根径向条组成,相隔 36°,持续 1000ms,延迟从 -900ms 到 0ms,透明度从 1 降至 .15。
- Loading Dots 用于仍在后台推进、总量未知的工作,不代替用户动作按钮的 Spinner。
- `prefers-reduced-motion: reduce` 下不得强行动画;状态文字与 ARIA 仍要保留。
@@ -27,6 +29,7 @@
- 设置面板复用 Dialog 轨迹;普通来源菜单仍按既有证据无动画,不能把 Command Menu 动画套给所有展开控件。
- 添加关注使用 Search Input 前缀;搜索时只把前缀替换成 Spinner,来源筛选保留“全部来源”可见文字。
-- 检查、加载、保存、应用等用户动作使用 Spinner;抓取更早内容和后台资源扫描说明使用 Loading Dots。
+- 检查、加载、保存、应用以及用户点下的“抓更早的一页”使用 Spinner;只有离开该按钮后仍在后台推进的资源扫描说明使用 Loading Dots。
+- 原生页面没有 Geist React 的 `loading` prop,因此 `setActionBusy()` 同时写入 `aria-busy=true` 与 `aria-disabled=true`,全局拦截重复点击并降低饱和度/不透明度;不用原生 `disabled`,焦点留在触发器上。
- Peach 是原生 ES module,不引入 Geist React 运行时;共享实现位于 `web/js/ui-components.js`。
- “没有更多历史内容”是成功的终止状态,使用中性可关闭 Note,不使用红色 error Note。
diff --git a/docs/reference-snapshots/vercel-geist-toast.md b/docs/reference-snapshots/vercel-geist-toast.md
index b86adc359..f3729c471 100644
--- a/docs/reference-snapshots/vercel-geist-toast.md
+++ b/docs/reference-snapshots/vercel-geist-toast.md
@@ -1,6 +1,6 @@
# Geist Toast 取证记录
-- 取证日期:2026-08-29
+- 取证日期:2026-09-01(复核)
- URL:<https://vercel.com/geist/toast>
- 取证方式:web reader 抓取页面正文(Geist 文档站是 React 渲染,视觉规格拿不到
可哈希的快照;这里记的是规范文字,要复核就重新抓一次)
@@ -21,6 +21,12 @@
- **Preservation**:默认自动消失;只有用户必须读到/必须操作时才常驻(preserve)。
- **Accessibility**:异步更新(toast、校验)需要 `aria-live="polite"`
(与 vercel-web-interface-guidelines 一致);toast 不自动抢焦点。
+- **Undo**:可逆操作使用过去时结果 + 单一 `Undo` 动作,保留 5–10 秒;Peach
+ 使用 8 秒和本地化的“撤销”。撤销本身必须等待真实写入成功,失败另报短 toast。
+- **Async flow**:一次用户动作只在终态发一条 toast,不用“开始/处理中/完成”
+ 连续三条 toast 复述同一个流程;等待只留在原触发器的 Spinner。
+- **Toggle**:持久化的 Toggle 在 `change` 后给成功 toast;只打开面板、菜单或
+ Dialog 尚未产生写入,不发伪成功回执。
- **Related**:需要用户立即处理时用 Banner / Note,而不是 toast。
## Peach 复用了什么
@@ -37,3 +43,6 @@
- toast 的量纲不取自本次抓取(正文没有视觉规格),沿用
`vercel-geist-controls-measured.md` 的实测值:8px 卡片圆角、发丝边、
比页面亮一档的表面、无重底色。
+- 详情、批量、关注管理和播放列表的写操作统一调用 `actionReceipt()`;适合逆向
+ 写回的反馈、标签、稍后看、版本需求、偏好和状态提供“撤销”,永久删除、凭据
+ 与保存到账本等不安全或不可逆操作只报终态,不伪造撤销。
diff --git a/docs/reference-sources.json b/docs/reference-sources.json
index 18a14b195..365b8a573 100644
--- a/docs/reference-sources.json
+++ b/docs/reference-sources.json
@@ -171,9 +171,9 @@
"name": "Vercel Geist Command Menu、Search Input、Spinner 与 Loading Dots",
"url": "https://vercel.com/geist/command-menu",
"snapshot": "docs/reference-snapshots/vercel-geist-command-search-loading.md",
- "checked_on": "2026-08-30",
- "sha256": "3be4d0f23965c2b0ef5865432d5db37f14f66f9e00dfa97801ec6074f0aab5d9",
- "role": "设置 Dialog 动效、搜索前缀、用户动作 Spinner、后台 Loading Dots 与无更多历史内容中性反馈的项目级依据。",
+ "checked_on": "2026-09-01",
+ "sha256": "03d09df900bc83c9d1c29d13b84dca77223f0f13c05f0f436011dd1543d8e2c9",
+ "role": "设置 Dialog 动效、搜索前缀、用户动作 Spinner、等待按钮可聚焦 busy 状态、后台 Loading Dots 与无更多历史内容中性反馈的项目级依据。",
"consumers": [
"web/js/ui-components.js",
"web/app.css",
diff --git a/src/peach/follow_gofile.py b/src/peach/follow_gofile.py
index eb76b0801..2d2e4f891 100644
--- a/src/peach/follow_gofile.py
+++ b/src/peach/follow_gofile.py
@@ -18,6 +18,7 @@ from __future__ import annotations
import json
import re
import urllib.parse
+from typing import Mapping
import httpx
@@ -30,6 +31,9 @@ from .http import HttpRequest, HttpResponse, HttpTransport
USER_AGENT = "Peach/0.2 (+local self-hosted follow reader)"
_FOLDER_PATH = re.compile(r"/d/([A-Za-z0-9_-]+)")
+_LABELED_FOLDER = re.compile(
+ r"gofile\s*\(([^)]+)\)\s*[-::]?\s*https://(?:[^/]+\.)?gofile\.io/d/"
+ r"([A-Za-z0-9_-]+)", re.IGNORECASE)
def folder_ids(links: list[str]) -> list[str]:
@@ -47,6 +51,12 @@ def folder_ids(links: list[str]) -> list[str]:
return list(dict.fromkeys(found))
+def folder_labels(text: str | None) -> dict[str, str]:
+ """Read optional human labels next to FANBOX Gofile links."""
+ return {folder: label.strip() for label, folder in _LABELED_FOLDER.findall(text or "")
+ if label.strip()}
+
+
class GofileExpander:
"""用用户自己的 API token 把 Gofile 文件夹展开成媒体条目。"""
@@ -61,7 +71,9 @@ class GofileExpander:
self.max_bytes = max_bytes
self.max_items = max_items
- def expand(self, links: list[str]) -> tuple[dict[str, object], ...]:
+ def expand(self, links: list[str], *,
+ labels: Mapping[str, str] | None = None,
+ ) -> tuple[dict[str, object], ...]:
folders = folder_ids(links)
if not folders or self.credential is None:
return ()
@@ -70,7 +82,8 @@ class GofileExpander:
seen: set[str] = set()
for folder in folders:
payload = self._contents(folder, token)
- self._collect(payload, items, seen)
+ self._collect(payload, items, seen, folder,
+ str((labels or {}).get(folder) or ""))
return tuple(items)
def _contents(self, folder: str, token: str) -> dict:
@@ -110,7 +123,8 @@ class GofileExpander:
raise FollowSourceError("Gofile 响应超出大小上限")
return response
- def _collect(self, payload: dict, items: list, seen: set) -> None:
+ def _collect(self, payload: dict, items: list, seen: set,
+ folder: str, label: str) -> None:
stack = [payload.get("data")]
while stack and len(items) < self.max_items:
node = stack.pop()
@@ -138,4 +152,6 @@ class GofileExpander:
"media_kind": kind,
"size": node.get("size"),
"resource_provider": "gofile",
+ "resource_group": f"gofile:{folder}",
+ "resource_group_label": label or f"Gofile · {folder}",
})
diff --git a/src/peach/follow_sources.py b/src/peach/follow_sources.py
index edeb75213..cee7e3d02 100644
--- a/src/peach/follow_sources.py
+++ b/src/peach/follow_sources.py
@@ -25,7 +25,7 @@ from .follow import (
DEFAULT_MAX_BYTES, FollowHistoryEnd, FollowSourceError, plain_text, stable_id,
)
from .follow_secrets import Credential, CredentialError
-from .follow_gofile import GofileExpander
+from .follow_gofile import GofileExpander, folder_labels
from .http import CurlCffiTransport, HttpRequest, HttpResponse, HttpTransport, HttpxTransport
@@ -467,7 +467,7 @@ class _BaseConnector:
self._check_status(response)
return self.parse_json(response)
- def _gofile_media(self, links: list[str]) -> tuple[dict[str, object], ...]:
+ def _gofile_media(self, links: list[str], *, labels=None) -> tuple[dict[str, object], ...]:
"""把帖子里的 Gofile 链接展开成媒体条目;实现见 `follow_gofile`。
留一个薄委托而不是让连接器直接构造展开器:调用点(f95zone / fanbox)不必知道
@@ -476,7 +476,7 @@ class _BaseConnector:
return GofileExpander(
self.transport, credential=self.gofile_credential,
timeout=self.timeout, max_bytes=self.max_bytes, max_items=self.max_items,
- ).expand(links)
+ ).expand(links, labels=labels)
class KemonoConnector(_BaseConnector):
@@ -1468,7 +1468,8 @@ class FanboxConnector(_BaseConnector):
probed += 1
links = detail["links"]
direct_media = detail["media_items"]
- gofile_media = self._gofile_media(links)
+ gofile_media = self._gofile_media(
+ links, labels=folder_labels(str(detail.get("summary") or "")))
media_items = tuple(direct_media) + gofile_media
candidates.append(FollowCandidate(
provider=self.provider,
diff --git a/src/peach/follow_store.py b/src/peach/follow_store.py
index 7b4ec02f9..b708c36db 100644
--- a/src/peach/follow_store.py
+++ b/src/peach/follow_store.py
@@ -158,6 +158,26 @@ class FollowStore:
"SELECT alias FROM entity_alias WHERE entity_id=?", (entity_id,))]
return tuple(dict.fromkeys(name for name in names if name))
+ def source_needs_media_reparse(self, source_id: int) -> bool:
+ """Whether saved credentials could unlock stale media metadata.
+
+ This is deliberately derived from candidate metadata rather than a new
+ truth field. A successful unconditional refresh replaces the metadata
+ and naturally clears the condition.
+ """
+ rows = self._connect().execute(
+ "SELECT metadata_json FROM follow_item WHERE source_id=?",
+ (source_id,),
+ ).fetchall()
+ for row in rows:
+ try:
+ metadata = json.loads(row[0] or "{}")
+ except (TypeError, json.JSONDecodeError):
+ continue
+ if isinstance(metadata, dict) and metadata.get("media_needs_credential"):
+ return True
+ return False
+
# ---- 抓取结果落地 ---------------------------------------------------
def record(self, source_id: int, fetch: SourceFetch, *,
diff --git a/src/peach/follow_stream.py b/src/peach/follow_stream.py
index 6e481f00f..3f80189b0 100644
--- a/src/peach/follow_stream.py
+++ b/src/peach/follow_stream.py
@@ -94,8 +94,6 @@ class FollowMediaResolver:
"""解析可播地址。`height` 指定清晰度,只有 rule34video 有多档可选;
要的那档不存在就退回默认(最高档),不报错——签名 URL 会过期,
为一次选档失败中断播放不值得。"""
- if item.metadata.get("media_needs_credential"):
- raise FollowMediaUnavailable("媒体需要来源登录会话")
media_items = item.metadata.get("media_items")
if (not isinstance(media_items, list) or not media_items) \
and item.provider == "f95zone":
@@ -126,8 +124,16 @@ class FollowMediaResolver:
if resource_provider == "f95zone":
if not _allowed_resource(url, ("attachments.f95zone.to",)):
raise FollowMediaUnavailable("F95 返回了不受信任的图片地址")
- return ResolvedFollowMedia(url, item.url)
+ loader = getattr(self, "_credential_loader", None)
+ credential = loader("f95zone") if loader else None
+ cookie = str(credential.values.get("cookie") or "") if credential else ""
+ if item.metadata.get("media_needs_credential") and not cookie:
+ raise FollowMediaUnavailable("F95 附件需要登录会话")
+ return ResolvedFollowMedia(
+ url, item.url, {"Cookie": cookie} if cookie else None)
raise FollowMediaUnavailable("媒体来源不受支持")
+ if item.metadata.get("media_needs_credential"):
+ raise FollowMediaUnavailable("媒体需要来源登录会话")
if item.provider != "rule34video":
# 归档站的存量行按旧规则拼过 URL(少 /data 前缀、主机也不对),
# 在这里修回可取的形式;`_allowed` 按后缀匹配,file./n1. 这些子域
diff --git a/src/peach/web_activity.py b/src/peach/web_activity.py
index 93981aa43..01fbae4ca 100644
--- a/src/peach/web_activity.py
+++ b/src/peach/web_activity.py
@@ -76,6 +76,10 @@ def w_feedback(contract: ActivityContract, body):
connection.execute(
"UPDATE asset SET o_count=COALESCE(o_count,0)+1 WHERE id=?", (aid,),
)
+ elif kind == "o-undo":
+ connection.execute(
+ "UPDATE asset SET o_count=MAX(COALESCE(o_count,0)-1,0) WHERE id=?", (aid,),
+ )
elif kind == "rate":
connection.execute(
"UPDATE asset SET rating=? WHERE id=?", (int(body.get("value", 0)), aid),
diff --git a/src/peach/web_follow.py b/src/peach/web_follow.py
index 7dcba2d68..51581fa24 100644
--- a/src/peach/web_follow.py
+++ b/src/peach/web_follow.py
@@ -198,6 +198,8 @@ def _media_items(item) -> list[dict]:
"thumb_url": thumb if thumb.startswith("https://") else None,
"size": media.get("size"),
"resource_provider": str(media.get("resource_provider") or ""),
+ "resource_group": str(media.get("resource_group") or "") or None,
+ "resource_group_label": str(media.get("resource_group_label") or "") or None,
})
return result
@@ -283,7 +285,7 @@ def _excluded_item(item) -> bool:
and not _f95_has_resource(item.media_url, item.metadata))
-def _item_payload(item) -> dict:
+def _item_payload(item, credential_providers: frozenset[str] = frozenset()) -> dict:
tags = _item_tags(item)
detail_tags = _item_all_tags(item)
media_kind = _media_kind(item)
@@ -295,6 +297,11 @@ def _item_payload(item) -> dict:
"\n".join(str(value) for value in recorded_links)
if isinstance(recorded_links, list) else ""
)
+ needs_credential = bool(item.metadata.get("media_needs_credential"))
+ credential_ready = not needs_credential or item.provider in credential_providers
+ playable = (media_kind in {"video", "image"}
+ and ((bool(media_items) and credential_ready)
+ or (bool(item.media_url) and not needs_credential)))
return {
"id": item.id,
"provider": item.provider,
@@ -318,15 +325,15 @@ def _item_payload(item) -> dict:
"variant_label": item.variant_label,
"status": item.status,
"asset_id": item.asset_id,
- "media_needs_credential": bool(item.metadata.get("media_needs_credential")),
+ "media_needs_credential": needs_credential,
"media_error": str(item.metadata.get("media_error") or "") or None,
"has_media": bool(item.media_url) or bool(media_items),
"media_kind": media_kind,
"media_type": _video_media_type(item.media_url)
if media_kind == "video" else None,
- "playable": (bool(item.media_url) or bool(media_items))
- and media_kind in {"video", "image"}
- and not bool(item.metadata.get("media_needs_credential")),
+ # 可直接读取的附件与仍需会话解析的外链可以同时存在。后者不能把
+ # 前者整体锁死;详情继续复用同一条 /follow-stream 媒体代理路径。
+ "playable": playable,
"media_items": media_items,
# 只投影连接器已验证过的文件页域名;原始媒体 URL 仍不进入 feed。
"resource_urls": safe_resource_urls,
@@ -336,12 +343,15 @@ def _item_payload(item) -> dict:
}
-def _group_payload(group: ReleaseGroup) -> dict:
+def _group_payload(group: ReleaseGroup,
+ credential_providers: frozenset[str] = frozenset()) -> dict:
return {
"release_key": group.release_key,
- "primary": _item_payload(group.primary),
- "variants": [_item_payload(item) for item in group.variants],
- "duplicates": [_item_payload(item) for item in group.duplicates],
+ "primary": _item_payload(group.primary, credential_providers),
+ "variants": [_item_payload(item, credential_providers)
+ for item in group.variants],
+ "duplicates": [_item_payload(item, credential_providers)
+ for item in group.duplicates],
"providers": list(group.providers),
"has_wip": group.has_wip,
"is_release": group.is_release,
@@ -733,6 +743,11 @@ def q_follow(contract, args) -> dict:
wanted_tags = tuple(value for value in
(part.strip() for part in str(args.get("tag") or "").split(","))
if value)
+ credential_store = _credential_store(contract)
+ credential_providers = frozenset(
+ provider for provider in CREDENTIAL_GUIDE
+ if credential_store.load(provider) is not None
+ )
with contract.database.read_connection() as connection:
store = _store(contract, connection)
source_rows = store.sources()
@@ -771,7 +786,8 @@ def q_follow(contract, args) -> dict:
page = [item for item in counted if not statuses or item.status in statuses]
has_more = len(page) > offset + limit
items = tuple(page[offset:offset + limit])
- groups = [_group_payload(group) for group in store.group(items)]
+ groups = [_group_payload(group, credential_providers)
+ for group in store.group(items)]
facets = _follow_facets(store, everything, by_source, alias_map)
# counts 与列表同源。以前它是一句全库 SQL,再逐条减掉被隐藏的 rule34video
# 和无资源的 f95zone——同一套排除规则维护了两份,而且它完全不看作者、来源和
@@ -944,9 +960,15 @@ def _run_follow_check(contract, body) -> dict:
credentials = _credential_store(contract)
results: list[dict] = []
with contract.database.read_connection() as connection:
- rows = [dict(row) for row in _store(contract, connection).sources(enabled_only=True)
+ store = _store(contract, connection)
+ rows = [dict(row) for row in store.sources(enabled_only=True)
if (source_id is None or row["id"] == source_id)
and (not older or row["provider"] in _BACKFILL_PROVIDERS)]
+ for row in rows:
+ row["force_media_reparse"] = (
+ not older and credentials.load(row["provider"]) is not None
+ and store.source_needs_media_reparse(row["id"])
+ )
for row in rows:
moment = datetime.now(timezone.utc)
provider, ref = row["provider"], row["ref"]
@@ -957,8 +979,15 @@ def _run_follow_check(contract, body) -> dict:
if gofile_credential is not None:
connector_kwargs["gofile_credential"] = gofile_credential
connector = build_connector(provider, **connector_kwargs)
- fetch = connector.fetch(ref, etag=row["etag"],
- last_modified=row["last_modified"], page=page)
+ # 凭据已经存在但旧候选仍标着 needs_credential 时,条件请求的 304
+ # 会让旧解析结果永久不变。显式检查应无条件重取一次,让凭据真正生效。
+ fetch = connector.fetch(
+ ref,
+ etag=None if row["force_media_reparse"] else row["etag"],
+ last_modified=(None if row["force_media_reparse"]
+ else row["last_modified"]),
+ page=page,
+ )
except FollowHistoryEnd:
with contract.database.write_transaction() as connection:
_store(contract, connection).record_history_end(row["id"], moment)
diff --git a/tests/test_follow_gofile.py b/tests/test_follow_gofile.py
index f8a5d96ee..89c58aa87 100644
--- a/tests/test_follow_gofile.py
+++ b/tests/test_follow_gofile.py
@@ -8,7 +8,7 @@ import json
import unittest
from peach.follow import FollowSourceError
-from peach.follow_gofile import GofileExpander, folder_ids
+from peach.follow_gofile import GofileExpander, folder_ids, folder_labels
from peach.follow_secrets import Credential, CredentialError
from peach.http import HttpResponse
@@ -47,6 +47,15 @@ class FolderIdTests(unittest.TestCase):
["OS2Qz9"],
)
+ def test_fanbox_copy_can_name_each_gofile_folder(self):
+ self.assertEqual(
+ folder_labels(
+ "gofile (Mitsuru) - https://gofile.io/d/DCkbZU "
+ "gofile (Poll) - https://gofile.io/d/bFRgRI"
+ ),
+ {"DCkbZU": "Mitsuru", "bFRgRI": "Poll"},
+ )
+
class CredentialIsolationTests(unittest.TestCase):
"""展开器自己发出的请求带什么。
@@ -96,9 +105,13 @@ class ApiErrorTests(unittest.TestCase):
{"status": "error-notPremium"}).encode("utf-8"))
def test_only_playable_files_survive(self):
- items = self._expand()
+ items = GofileExpander(
+ _transport(), credential=Credential("gofile", {"api_token": "t"}),
+ ).expand(["https://gofile.io/d/OS2Qz9"], labels={"OS2Qz9": "Poll"})
self.assertEqual([item["media_kind"] for item in items], ["video"])
self.assertEqual(items[0]["resource_provider"], "gofile")
+ self.assertEqual(items[0]["resource_group"], "gofile:OS2Qz9")
+ self.assertEqual(items[0]["resource_group_label"], "Poll")
self.assertEqual(items[0]["url"], "https://store1.gofile.io/download/one.mp4")
diff --git a/tests/test_follow_stream.py b/tests/test_follow_stream.py
index d0fc4fb84..3f57fb46c 100644
--- a/tests/test_follow_stream.py
+++ b/tests/test_follow_stream.py
@@ -77,6 +77,21 @@ class FollowMediaResolverTests(unittest.TestCase):
"https://attachments.f95zone.to/2026/08/one.jpg")
self.assertEqual(target.referer, item.url)
+ def test_f95_attachment_stays_available_while_other_links_need_a_session(self):
+ item = SimpleNamespace(
+ id=14, provider="f95zone", url="https://f95zone.to/threads/1/post-14",
+ media_url="https://f95zone.to/masked/gofile.io/1/locked",
+ metadata={"media_needs_credential": True, "attachments": [
+ "https://attachments.f95zone.to/2026/08/one.jpg",
+ ]},
+ )
+ resolver = FollowMediaResolver(lambda *_args: None).with_credential_loader(
+ lambda provider: Credential(provider, {"cookie": "xf_session=saved"}))
+ target = resolver.resolve(item, 0)
+ self.assertEqual(target.url,
+ "https://attachments.f95zone.to/2026/08/one.jpg")
+ self.assertEqual(target.headers, {"Cookie": "xf_session=saved"})
+
def test_gofile_media_keeps_the_token_in_the_proxy_header(self):
item = SimpleNamespace(
id=12, provider="fanbox", url="https://creator.fanbox.cc/posts/12",
diff --git a/tests/test_follow_web.py b/tests/test_follow_web.py
index cca8b5c9f..f7536dac4 100644
--- a/tests/test_follow_web.py
+++ b/tests/test_follow_web.py
@@ -248,12 +248,17 @@ class FollowContractTests(unittest.TestCase):
self.assertNotIn("media_url", item)
def test_legacy_f95_image_attachments_are_projected_without_a_ledger_write(self):
+ secrets = self.root / "secrets" / "follow"
+ secrets.mkdir(parents=True)
+ (secrets / "f95zone.json").write_text(
+ '{"cookie": "xf_session=saved"}', encoding="utf-8")
self._seed(candidates=(FollowCandidate(
provider="f95zone", external_id="21435167", title="Image set",
url="https://f95zone.to/threads/160190/post-21435167",
media_url="https://pixeldrain.com/l/verified",
thumb_url="https://attachments.f95zone.to/2026/08/one.jpg",
extra={"links": ["https://pixeldrain.com/l/verified"],
+ "media_needs_credential": True,
"attachments": [
"https://attachments.f95zone.to/2026/08/one.jpg",
"https://attachments.f95zone.to/2026/08/two.png",
@@ -264,8 +269,40 @@ class FollowContractTests(unittest.TestCase):
["image", "image"])
self.assertEqual(item["media_kind"], "image")
self.assertTrue(item["playable"])
+ self.assertTrue(item["media_needs_credential"])
self.assertTrue(all("url" not in media for media in item["media_items"]))
+ def test_saved_f95_session_forces_one_reparse_instead_of_accepting_304(self):
+ source_id = self._seed(candidates=(FollowCandidate(
+ provider="f95zone", external_id="21435168", title="Image set",
+ url="https://f95zone.to/threads/160190/post-21435168",
+ extra={"media_needs_credential": True},
+ ),), provider="f95zone", ref="160190", semantics="release")
+ secrets = self.root / "secrets" / "follow"
+ secrets.mkdir(parents=True)
+ (secrets / "f95zone.json").write_text(
+ '{"cookie": "xf_session=saved"}', encoding="utf-8")
+ with self.contract.database.write_transaction() as connection:
+ connection.execute(
+ "UPDATE follow_source SET etag='old',last_modified='yesterday' WHERE id=?",
+ (source_id,),
+ )
+ conditional = []
+
+ class _Recorder:
+ def fetch(self, ref, *, etag=None, last_modified=None, page=0):
+ conditional.append((etag, last_modified, page))
+ return SourceFetch(
+ provider="f95zone", ref=ref,
+ request_url="https://f95zone.to/threads/160190/latest",
+ semantics="release", candidates=(), raw_body=b"<html/>")
+
+ with mock.patch.object(web_follow, "build_connector", return_value=_Recorder()):
+ result = self._post("/api/follow/check", {"source": source_id})
+
+ self.assertTrue(result["results"][0]["ok"])
+ self.assertEqual(conditional, [(None, None, 0)])
+
def test_media_collections_expose_only_safe_display_fields_and_indices(self):
self._seed(candidates=(FollowCandidate(
provider="fanbox", external_id="12228983", title="Poll Results",
@@ -274,7 +311,9 @@ class FollowContractTests(unittest.TestCase):
{"id": "one", "name": "one.mp4", "media_kind": "video",
"url": "https://store1.gofile.io/download/one.mp4",
"thumb_url": "https://store1.gofile.io/one.jpg",
- "resource_provider": "gofile"},
+ "resource_provider": "gofile",
+ "resource_group": "gofile:OS2Qz9",
+ "resource_group_label": "Poll"},
{"id": "two", "name": "two.jpg", "media_kind": "image",
"url": "https://store1.gofile.io/download/two.jpg",
"resource_provider": "gofile"},
@@ -287,6 +326,8 @@ class FollowContractTests(unittest.TestCase):
["video", "image"])
self.assertEqual(item["media_items"][0]["name"], "one.mp4")
self.assertEqual(item["media_items"][0]["media_type"], "video/mp4")
+ self.assertEqual(item["media_items"][0]["resource_group"], "gofile:OS2Qz9")
+ self.assertEqual(item["media_items"][0]["resource_group_label"], "Poll")
self.assertIsNone(item["media_items"][1]["media_type"])
self.assertNotIn("url", item["media_items"][0])
self.assertNotIn("store1.gofile.io/download", json.dumps(item))
@@ -1701,6 +1742,13 @@ class FollowWebSourceTests(unittest.TestCase):
self.assertPageContains("route(followDetailReturnPath||'/follow')")
self.assertPageContains(".followitem a{text-decoration:none}")
+ def test_one_fanbox_collection_keeps_its_gofile_folder_sections(self):
+ self.assertPageContains("const followGroupedMediaOwner=group=>")
+ self.assertPageContains("(item.media_items||[]).some(media=>media.resource_group)")
+ self.assertPageContains("const key=media.resource_group||'ungrouped'")
+ self.assertPageContains('class="mixgrouplabel"')
+ self.assertPageContains('data-follow-media-owner="${item.id}"')
+
def test_follow_video_uses_the_shared_videojs_player_and_quality_control(self):
self.assertPageContains('class="video-js vjs-big-play-centered" controls playsinline preload="metadata"')
self.assertPageContains("if(followVideo){")
@@ -2064,7 +2112,8 @@ class FollowWebSourceTests(unittest.TestCase):
def test_credential_dependent_media_is_called_out(self):
self.assertPageContains("媒体链接需要 F95 登录会话解析")
- self.assertPageContains("已保存 F95 登录会话,等待下次检查重新解析资源")
+ self.assertPageContains("已显示可读取附件;F95 登录会话已保存")
+ self.assertPageContains("这条旧记录的受保护资源会在下次检查重新解析")
self.assertPageContains("followCredentialProviders=new Set")
self.assertPageContains("api('/api/follow/credentials').catch")
self.assertPageContains("个外部文件页;视频列表未取得")
@@ -2082,7 +2131,8 @@ class FollowWebSourceTests(unittest.TestCase):
self.assertPageContains("@keyframes geist-spinner-opacity")
self.assertPageContains("@keyframes geist-loading-dot")
self.assertPageContains("spinnerHtml('查找中')")
- self.assertPageContains("loadingDotsHtml('抓取中…')")
+ self.assertPageContains("spinnerHtml('抓取中')")
+ self.assertPageContains("setActionBusy(button);button.title='检查中…'")
self.assertPageContains("c.known?'已经关注':c.evidence")
self.assertPageLacks("已经在追")
@@ -2092,6 +2142,9 @@ class FollowWebSourceTests(unittest.TestCase):
def test_follow_cards_reuse_home_cards_hover_actions_and_mix_stacks(self):
self.assertPageContains("function followVideoItems(group)")
+ self.assertPageContains("function followCollectionItemsNewest(group)")
+ self.assertPageContains("Date.parse(b.published_at||'')")
+ self.assertPageContains("followCollectionItemsNewest(group).filter")
self.assertPageContains("item.playable&&item.media_kind==='video'")
self.assertPageContains('class="card followitem${isMix?\' collection\':\'\'}${imageView?\' imagecard\':\'\'}"')
self.assertPageContains("isMix?'mixstack '")
@@ -2119,6 +2172,9 @@ class FollowWebSourceTests(unittest.TestCase):
self.assertPageLacks('data-follow-media=')
self.assertPageContains("params.set('author',followAuthor)")
self.assertPageContains("route(followViewPath());renderFollow()")
+ self.assertPageContains("if(!counts.images&&followMediaView!=='images')return ''")
+ self.assertPageLacks("if(followMediaView==='images'&&!mediaCounts.images)followMediaView='videos'")
+ self.assertPageLacks("if(followMediaView==='videos'&&!mediaCounts.videos&&mediaCounts.images)followMediaView='images'")
self.assertPageContains("const preferredKind=followMediaView==='images'?'image':'video'")
watch = self.page.split("function renderFollow(){", 1)[1].split(
"function followBackfillState", 1)[0]
@@ -2142,7 +2198,7 @@ class FollowWebSourceTests(unittest.TestCase):
self.assertPageLacks("${icon('plus')}加载更多")
self.assertPageContains("${icon('history')}抓更早的一页")
self.assertPageContains("spinnerHtml('加载更多')")
- self.assertPageContains("loadingDotsHtml('抓取中…')")
+ self.assertPageContains("spinnerHtml('抓取中')")
def test_follow_management_list_has_routed_sorting(self):
self.assertPageContains('data-follow-sort aria-label="关注列表排序"')
diff --git a/tests/test_rm_web.py b/tests/test_rm_web.py
index 487cbe402..80a23ace8 100644
--- a/tests/test_rm_web.py
+++ b/tests/test_rm_web.py
@@ -486,6 +486,16 @@ class WebDataTests(unittest.TestCase):
)["feedback"])
self.assertEqual(self.row()["disposal"], "trash")
+ def test_orgasm_receipt_can_be_undone_without_crossing_zero(self):
+ added = rm_web.w_feedback(self.contract, {"id": 1, "kind": "o"})
+ self.assertEqual(added["o_count"], 1)
+ undone = rm_web.w_feedback(self.contract, {"id": 1, "kind": "o-undo"})
+ self.assertEqual(undone["o_count"], 0)
+ self.assertEqual(
+ rm_web.w_feedback(self.contract, {"id": 1, "kind": "o-undo"})["o_count"],
+ 0,
+ )
+
def test_flagged_means_positive_marks_not_disposal_or_negative_feedback(self):
rm_web.w_feedback(self.contract, {"id": 1, "kind": "dislike"})
rm_web.w_feedback(self.contract, {"id": 1, "kind": "dispose"})
diff --git a/tests/test_web_ui.py b/tests/test_web_ui.py
index 28e412e8e..208e71d3a 100644
--- a/tests/test_web_ui.py
+++ b/tests/test_web_ui.py
@@ -273,6 +273,18 @@ class WebUiSourceTests(unittest.TestCase):
def test_detail_feedback_toolbar_never_shrinks_into_a_line(self):
self.assertPageContains("width:max-content;overflow:hidden;flex:none")
+ def test_mutating_detail_actions_share_terminal_toasts_and_undo(self):
+ self.assertPageContains("const actionReceipt=(message,{undo=null,timeout=undo?8000:6000}={})")
+ self.assertPageContains("action:undo?{label:'撤销'")
+ self.assertPageContains("if(kind==='o')await postFeedback('o-undo')")
+ self.assertPageContains("actionReceipt(messages[kind],{undo:async()=>")
+ self.assertPageContains("actionReceipt(r.watch_later?'已加入稍后看':'已移出稍后看'")
+ self.assertPageContains("actionReceipt(r.better_version?'已标记寻找更好版本':'已取消寻找更好版本'")
+ self.assertPageContains("actionReceipt(`已删除标签「${tagLabel(tag)}」`,{undo:async()=>")
+ self.assertPageContains("actionReceipt(r.liked?'已保存喜欢偏好':'已取消喜欢'")
+ self.assertPageContains("if(later){e.stopPropagation();setActionBusy(later)")
+ self.assertPageContains("if(kind==='o')await post('o-undo')")
+
def test_detail_like_reason_is_an_icon_disclosure_without_idle_explanation(self):
self.assertPageContains('id="preferenceToggle" aria-label="喜爱理由"')
self.assertPageContains('id="preferencePanel" hidden')
@@ -280,9 +292,9 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains('placeholder="为什么喜欢?"')
self.assertPageContains('class="geist-button primary savepreference"')
self.assertPageContains('aria-label="提交喜爱理由"><span>提交</span></button>')
- self.assertPageContains("btn.setAttribute('aria-busy','true')")
+ self.assertPageContains("setActionBusy(btn)")
self.assertPageContains("spinnerHtml('正在提交喜爱理由')")
- self.assertPageContains("btn.removeAttribute('aria-busy');btn.innerHTML='<span>提交</span>'")
+ self.assertPageContains("setActionBusy(btn,false);btn.innerHTML='<span>提交</span>'")
self.assertPageContains('.geist-button.primary{border-color:var(--ink);background:var(--ink);color:var(--ground)}')
self.assertPageContains('.preference-foot>span{margin-right:auto')
self.assertPageLacks('aria-label="保存喜爱理由">${icon(\'check\')}</button>')
@@ -939,7 +951,8 @@ class WebUiSourceTests(unittest.TestCase):
def test_note_semantics_replace_empty_states_for_persistent_errors(self):
for name in ("emptyStateHtml", "loadingDotsHtml", "mediaViewButtonsHtml", "noteHtml", "progressHtml",
- "scrollerHtml", "skeletonHtml", "spinnerHtml", "wireScrollers"):
+ "scrollerHtml", "setActionBusy", "skeletonHtml", "spinnerHtml",
+ "wireBusyActions", "wireScrollers"):
self.assertPageContains(name)
self.assertPageContains("from './js/ui-components.js'")
self.assertPageContains("const NOTE_VARIANTS=new Set(['secondary','warning','error','success'])")
@@ -1213,10 +1226,10 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains(".count.manage-static{position:relative;top:auto;z-index:1}")
self.assertPageContains("if(!response.ok){")
self.assertPageContains("throw new Error(detail||`请求失败(${response.status})`)")
- self.assertPageContains("catch(error){alert(`操作失败:${error.message||'未知错误'}`)}")
+ self.assertPageContains("catch(error){actionFailure('批量操作',error)}")
self.assertPageContains("wireJunkCards($('#grid'));paintSelection();return")
- self.assertPageContains("toast(`操作失败:${esc(error.message||'未知错误')}`,{warn:true})")
- self.assertPageContains("b.dataset.kind==='dispose'&&r.disposal==='trash'&&state.state==='ads'")
+ self.assertPageContains("actionFailure('操作',error)")
+ self.assertPageContains("kind==='dispose'&&r.disposal==='trash'&&state.state==='ads'")
def test_junk_review_and_trash_render_every_physical_resource_type(self):
"""图片、网址快捷方式等不能复用视频播放器,但必须可预览、回收和还原。"""
@@ -1225,7 +1238,7 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains("String(it.name||'').toLowerCase().endsWith('.url')?'网址快捷方式'")
self.assertPageContains('src="/photo-thumb?id=${it.id}"')
self.assertPageContains('data-resource-operation="${action}"')
- self.assertPageContains("await api('/api/batch',{method:'POST',body:JSON.stringify({ids:[+card.dataset.id],operation})})")
+ self.assertPageContains("await api('/api/batch',{method:'POST',body:JSON.stringify({ids:[id],operation})})")
self.assertPageContains("if(it&&(!it.medium||it.medium==='video'))wireHover(el,it)")
self.assertPageContains("state.state==='trash'?d.items.map(resourceCardHtml).join('')")
self.assertPageContains("wireCards($('#grid'),state.state==='trash'?openResourceCard:undefined)")
@@ -1252,6 +1265,12 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains("wireJunkCards($('#grid'));paintSelection()")
self.assertPageContains("data-junk-batch=\"dismiss-junk\"")
self.assertPageContains("data-junk-batch=\"reconsider-junk\"")
+
+ def test_resource_and_source_mutations_use_terminal_toasts_with_safe_undo(self):
+ self.assertPageContains("actionReceipt(operation==='restore'?'已还原':'已移入回收站',{undo:async()=>")
+ self.assertPageContains("actionReceipt(`已添加 ${picked.length} 个关注来源`)")
+ self.assertPageContains("actionReceipt(saving?'已保存到账本':(labels[to]||'已更新关注状态')")
+ self.assertPageContains("actionReceipt(`已把 ${r.removed} 项移入回收站`,{undo:ids.length?async()=>")
self.assertPageContains("data-junk-batch=\"dispose\"")
self.assertPageContains(".batchbar:has([data-junk-batch]:not([hidden]))")
self.assertPageContains("#batchbar[hidden]{display:none}")
@@ -1656,6 +1675,25 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageLacks("detailpending")
self.assertPageLacks("showItemDetailLoading(origin,above)")
+ def test_loading_actions_are_inert_and_dimmed_without_losing_focus(self):
+ """用户触发的等待态统一走 Geist loading button,而不是各页自造半套状态。"""
+ self.assertPageContains("control.setAttribute('aria-busy','true')")
+ self.assertPageContains("control.setAttribute('aria-disabled','true')")
+ self.assertPageContains("control.removeAttribute('aria-disabled')")
+ self.assertPageContains("wireBusyActions(document)")
+ self.assertPageContains("event.stopImmediatePropagation()")
+ self.assertPageContains('button[aria-busy="true"],[role="button"][aria-busy="true"]{')
+ self.assertPageContains("cursor:wait!important;opacity:.55!important;filter:saturate(.35)")
+ self.assertNotRegex(
+ self.app_js,
+ r"disabled\s*=\s*true;[^\n]{0,100}(?:setAttribute\('aria-busy'|setActionBusy)",
+ "请求中的按钮必须保持可聚焦,不能再把 native disabled 和 busy 混用",
+ )
+ self.assertPageContains("setActionBusy(batch)")
+ self.assertPageContains("setActionBusy(scan,busy)")
+ self.assertPageContains("setActionBusy(addButton)")
+ self.assertPageContains("setActionBusy(btn)")
+
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)")
@@ -2664,12 +2702,12 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains("status.textContent='';toast('已在资源管理器中显示')")
self.assertPageContains("if(reveal)reveal.onclick=()=>revealSource(Number(reveal.dataset.reveal),status,{button:reveal})")
reveal_source = self.page.split("async function revealSource", 1)[1].split("async function syncMissing", 1)[0]
- self.assertIn("button.setAttribute('aria-busy','true')", reveal_source)
+ self.assertIn("setActionBusy(button)", reveal_source)
self.assertIn("status.textContent=''", reveal_source)
self.assertNotIn("status.textContent='正在定位…'", reveal_source,
"请求等待态必须留在按钮内,不能撑开详情内容流")
self.assertNotIn("button.disabled", reveal_source,
- "等待按钮应保持可聚焦,并由 aria-busy 阻止重复请求")
+ "等待按钮应保持可聚焦,并由共享 busy 状态阻止重复请求")
self.assertPageContains("api('/api/purge-missing',{method:'POST',body:JSON.stringify({id})})")
self.assertPageContains('data-reveal="${id}"')
self.assertPageContains('data-sync="${id}"')
diff --git a/web/app.css b/web/app.css
index 7cd59ed0a..bc59a122c 100644
--- a/web/app.css
+++ b/web/app.css
@@ -94,6 +94,11 @@ button,a,input,textarea,select,summary{touch-action:manipulation}
.geist-button:hover:not(:disabled){border-color:var(--ink-2);background:var(--hover)}
.geist-button:focus-visible{outline:2px solid var(--tungsten);outline-offset:2px}
.geist-button:disabled{cursor:default;opacity:.55}
+/* Vercel/Geist loading actions look unavailable and reject repeat activation,
+ but remain focusable; JS pairs this with aria-disabled instead of disabled. */
+button[aria-busy="true"],[role="button"][aria-busy="true"]{
+ cursor:wait!important;opacity:.55!important;filter:saturate(.35)
+}
.geist-button.primary{border-color:var(--ink);background:var(--ink);color:var(--ground)}
.geist-button.primary:hover:not(:disabled){border-color:color-mix(in srgb,var(--ink) 88%,var(--ground));
background:color-mix(in srgb,var(--ink) 88%,var(--ground))}
@@ -1417,6 +1422,10 @@ body.settings-open{overflow:hidden}
.toast .tclose:hover{background:var(--hover);color:var(--ink)}
.toast .tclose svg{width:13px;height:13px;stroke:currentColor;fill:none;stroke-width:2;stroke-linecap:round}
.toast.leaving{opacity:0;transform:translateY(4px);transition:opacity .15s ease,transform .15s ease}
+.mixgrouplabel{display:flex;align-items:center;gap:8px;margin:12px 10px 6px;color:var(--ink);
+ font-size:var(--fs-xs);font-weight:600}
+.mixgrouplabel:first-child{margin-top:4px}
+.mixgrouplabel span{color:var(--muted);font-variant-numeric:tabular-nums;font-weight:400}
/* ── 审查遮挡 ──
共享屏幕 / 录屏 / 截图时的全站内容遮蔽,设置项(#censorSetting)+ body.censor,
diff --git a/web/app.js b/web/app.js
index 2480482ff..8aeb8a92d 100644
--- a/web/app.js
+++ b/web/app.js
@@ -2,10 +2,11 @@ import {$, ENTITY_ROUTES, LOC, ROUTE_ENTITIES, ROUTE_STATES, SITE_FAVICONS, STAT
import { initMiddleTruncate } from './js/middle-truncate.js';
import {
emptyStateHtml, loadingDotsHtml, mediaViewButtonsHtml, noteHtml, progressHtml, scrollerHtml,
- skeletonHtml, spinnerHtml, wireScrollers,
+ setActionBusy, skeletonHtml, spinnerHtml, wireBusyActions, wireScrollers,
} from './js/ui-components.js';
initMiddleTruncate(document);
+wireBusyActions(document);
const pageSkeletonHtml=(label,{cards=false,className='',variant=''}={})=>
skeletonHtml(label,{variant:variant||(cards?'cards':'panel'),className});
@@ -283,6 +284,19 @@ const toast=(html,{timeout=6000,warn=false,action=null}={})=>{
return item;
};
+/* 所有可逆写操作共用同一种回执:只在请求真正完成后报过去时结果,撤销入口
+ 保留 8 秒。撤销本身也是一次真实写入,失败时另报一条短错误,不能把本地 UI
+ 偷偷改回去假装成功。不可逆或不适合撤销的操作仍用同一函数,但不传 undo。 */
+const actionReceipt=(message,{undo=null,timeout=undo?8000:6000}={})=>toast(esc(message),{
+ timeout,
+ action:undo?{label:'撤销',run:async()=>{
+ try{await undo();toast('已撤销')}
+ catch(error){toast(`撤销失败:${esc(error.message||'请重试')}`,{warn:true})}
+ }}:null,
+});
+const actionFailure=(message,error)=>toast(
+ `${esc(message)}失败:${esc(error?.message||'请重试')}`,{warn:true});
+
/* 随机排序每次进入首页都换种子;同一次访问继续复用该种子,保证筛选和分页
不会重复或漏项。「换一批」仍可在当前访问里主动生成下一批。 */
const newSeed=()=>String((Date.now()^(Math.random()*1e9|0))%99991);
@@ -875,8 +889,13 @@ $('#batchbar').querySelectorAll('[data-batch]').forEach(button=>button.onclick=a
try{const r=await api('/api/batch',{method:'POST',body:JSON.stringify({ids,operation})});
if(r.blocked&&r.blocked.length)alert(`已永久删除 ${r.purged} 个;${r.blocked.length} 个删不掉,仍留在回收站:\n`
+r.blocked.slice(0,5).map(x=>`${x.path}(${x.reason})`).join('\n'));
- setSelectMode(false,true);await reloadCurrentSurface()}
- catch(error){alert(`操作失败:${error.message||'未知错误'}`)}
+ setSelectMode(false,true);await reloadCurrentSurface();
+ const inverse=operation==='dispose'?'restore':operation==='restore'?'dispose':null;
+ actionReceipt(`已${labels[operation]} ${ids.length} 项`,{undo:inverse?async()=>{
+ await api('/api/batch',{method:'POST',body:JSON.stringify({ids,operation:inverse})});
+ await reloadCurrentSurface();
+ }:null})}
+ catch(error){actionFailure('批量操作',error)}
finally{button.disabled=false;paintSelection()}
});
$('#batchbar').querySelectorAll('[data-follow-batch]').forEach(button=>button.onclick=async()=>{
@@ -888,8 +907,8 @@ $('#batchbar').querySelectorAll('[data-follow-batch]').forEach(button=>button.on
const path=action==='save'?'/api/follow/save':'/api/follow/status';
const body=action==='save'?{items}:{items,to:action};
await api(path,{method:'POST',body:JSON.stringify(body)});
- setSelectMode(false,true);await openFollow(false);
- }catch(error){alert(`操作失败:${error.message||'未知错误'}`)}
+ setSelectMode(false,true);await openFollow(false);actionReceipt(`已${labels[action]} ${items.length} 项`);
+ }catch(error){actionFailure('批量操作',error)}
finally{button.disabled=false;paintSelection()}
});
$('#batchbar').querySelectorAll('[data-junk-batch]').forEach(button=>button.onclick=async()=>{
@@ -900,8 +919,13 @@ $('#batchbar').querySelectorAll('[data-junk-batch]').forEach(button=>button.oncl
try{
await api('/api/batch',{method:'POST',body:JSON.stringify({ids,operation})});
setSelectMode(false,true);adsBatch=null;await load(true);
- toast(`已批量${labels[operation]}:${ids.length} 项`);
- }catch(error){toast(`批量操作失败:${error.message||'未知错误'}`,{warn:true})}
+ const inverse=operation==='dispose'?'restore':operation==='dismiss-junk'?'reconsider-junk':
+ operation==='reconsider-junk'?'dismiss-junk':null;
+ actionReceipt(`已批量${labels[operation]}:${ids.length} 项`,{undo:inverse?async()=>{
+ await api('/api/batch',{method:'POST',body:JSON.stringify({ids,operation:inverse})});
+ await load(true);
+ }:null});
+ }catch(error){actionFailure('批量操作',error)}
finally{button.disabled=false;paintSelection()}
});
@@ -1183,16 +1207,16 @@ function wireJunkCards(root){
card.querySelectorAll('[data-junk-operation]').forEach(button=>button.onclick=async event=>{
event.preventDefault();event.stopPropagation();
const operation=button.dataset.junkOperation;
- button.disabled=true;button.setAttribute('aria-busy','true');
+ setActionBusy(button);
try{
await runJunkOperation(id,operation);
const disposed=operation==='dispose',reconsidered=operation==='reconsider-junk';
- toast(disposed?'已移入回收站':reconsidered?'已重新加入垃圾判断':'已标记为不是垃圾',{
- action:{label:'撤销',run:()=>runJunkOperation(id,disposed?'restore':reconsidered?'dismiss-junk':'reconsider-junk')},
+ actionReceipt(disposed?'已移入回收站':reconsidered?'已重新加入垃圾判断':'已标记为不是垃圾',{
+ undo:()=>runJunkOperation(id,disposed?'restore':reconsidered?'dismiss-junk':'reconsider-junk'),
});
}catch(error){
- toast(`操作失败:${esc(error.message||'未知错误')}`,{warn:true});
- button.disabled=false;button.removeAttribute('aria-busy');
+ actionFailure('操作',error);
+ setActionBusy(button,false);
}
});
});
@@ -1232,14 +1256,20 @@ function wireResourceCardActions(root){
event.preventDefault();event.stopPropagation();
const card=button.closest('[data-id]'),operation=button.dataset.resourceOperation;
if(!card)return;
- button.disabled=true;button.setAttribute('aria-busy','true');
+ setActionBusy(button);
button.innerHTML=`${spinnerHtml(operation==='restore'?'正在还原':'正在移入回收站')}<span>${operation==='restore'?'正在还原':'正在处理'}</span>`;
try{
- await api('/api/batch',{method:'POST',body:JSON.stringify({ids:[+card.dataset.id],operation})});
+ const id=+card.dataset.id;
+ await api('/api/batch',{method:'POST',body:JSON.stringify({ids:[id],operation})});
await load(true);
+ const inverse=operation==='restore'?'dispose':'restore';
+ actionReceipt(operation==='restore'?'已还原':'已移入回收站',{undo:async()=>{
+ await api('/api/batch',{method:'POST',body:JSON.stringify({ids:[id],operation:inverse})});
+ await load(true);
+ }});
}catch(error){
- alert(`操作失败:${error.message||'未知错误'}`);
- button.disabled=false;button.removeAttribute('aria-busy');
+ actionFailure('操作',error);
+ setActionBusy(button,false);
const label=operation==='restore'?'还原':'移入回收站';
button.innerHTML=`${icon(operation==='restore'?'rotate-ccw':'trash')}<span>${label}</span>`;
}
@@ -1315,9 +1345,15 @@ function wireCards(root,onClick,onTag){
if(v&&Number.isFinite(v.duration)){if(v._hop){clearInterval(v._hop);v._hop=null}
v.currentTime=Math.max(0,Math.min(v.duration,v.currentTime+(+seek.dataset.seek)))}return}
const later=e.target.closest('[data-later]');
- if(later){e.stopPropagation();api('/api/watch-later',{method:'POST',body:JSON.stringify({id:it.id})})
+ if(later){e.stopPropagation();setActionBusy(later);api('/api/watch-later',{method:'POST',body:JSON.stringify({id:it.id})})
.then(r=>{it.watch_later=r.watch_later;later.setAttribute('aria-pressed',r.watch_later);
- later.innerHTML=r.watch_later?icon('check'):icon('bookmark-plus')});return}
+ later.innerHTML=r.watch_later?icon('check'):icon('bookmark-plus');
+ actionReceipt(r.watch_later?'已加入稍后看':'已移出稍后看',{undo:async()=>{
+ const restored=await api('/api/watch-later',{method:'POST',body:JSON.stringify({id:it.id})});
+ it.watch_later=restored.watch_later;if(!later.isConnected)return;
+ later.setAttribute('aria-pressed',restored.watch_later);
+ later.innerHTML=restored.watch_later?icon('check'):icon('bookmark-plus');
+ }})}).catch(error=>actionFailure('更新稍后看',error)).finally(()=>setActionBusy(later,false));return}
if(selectMode||e.shiftKey||e.ctrlKey||e.metaKey){e.preventDefault();e.stopPropagation();toggleSelection(it.id,e.shiftKey);return}
if(e.target.closest('[data-open]')){e.stopPropagation();openCard(+el.dataset.id,el);return}
const ent=e.target.closest('[data-entity-kind]');
@@ -1561,8 +1597,8 @@ function renderCount(){
const batch=$('#batchAction');
if(batch)batch.onclick=async()=>{
if(batch.getAttribute('aria-busy')==='true')return;
- const old=batch.innerHTML;batch.setAttribute('aria-busy','true');batch.innerHTML=spinnerHtml('换一批');
- try{await refreshAll()}finally{batch.removeAttribute('aria-busy');batch.innerHTML=old}
+ const old=batch.innerHTML;setActionBusy(batch);batch.innerHTML=spinnerHtml('换一批');
+ try{await refreshAll()}finally{setActionBusy(batch,false);batch.innerHTML=old}
};
wireJavLayoutButtons($('#count'));
const emptyTrash=$('#emptyTrash');
@@ -1575,6 +1611,8 @@ function renderCount(){
否则用户看到条目还在会以为清空又没生效。 */
if(r.blocked&&r.blocked.length)alert(`已永久删除 ${r.purged} 个;${r.blocked.length} 个删不掉,仍留在回收站:\n`
+r.blocked.slice(0,5).map(x=>`${x.path}(${x.reason})`).join('\n'));
+ actionReceipt(`已永久删除 ${r.purged} 项`);
+ }catch(error){actionFailure('清空回收站',error);
}finally{await load(true)}
};
$('#count').querySelectorAll('[data-sort]').forEach(b=>b.onclick=()=>{
@@ -1776,7 +1814,7 @@ function resourceSyncMarkup(){
<div class="resourcesyncbox"><div class="resourcesyncbody"><h3>网盘与账本</h3>
<p>核对已挂载网盘与账本。网盘上已删除的条目先进入回收站;只清理没有在用的预览与播放缓存。</p></div>
<div class="resourcesyncfooter"><p>离线来源会整库跳过。候选 CSV、来源证据、女优头像和厂牌 Logo 不会删除。</p>
- <button class="resourceaction" type="button" id="resourceScan" aria-busy="false">${icon('refresh-cw')}<span>扫描差异</span></button></div></div>
+ <button class="resourceaction" type="button" id="resourceScan">${icon('refresh-cw')}<span>扫描差异</span></button></div></div>
<div id="resourceSyncResult" aria-live="polite"></div></section>`;
}
async function wireResourceSync(){
@@ -1784,7 +1822,7 @@ async function wireResourceSync(){
if(!scan||!result)return;
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));
+ setActionBusy(scan,busy);
scan.innerHTML=`${icon('refresh-cw')}<span>${busy?'扫描中':done?'重新扫描':'扫描差异'}</span>`;
};
const render=payload=>{
@@ -1802,13 +1840,13 @@ async function wireResourceSync(){
$('#resourceApply')?.addEventListener('click',async event=>{
const button=event.currentTarget;
if(!confirm(`把 ${payload.missing||0} 项移入回收站,并清理 ${cache.files||0} 个可重建缓存?`))return;
- button.disabled=true;button.setAttribute('aria-busy','true');
+ setActionBusy(button);
button.innerHTML=`${spinnerHtml('正在应用')}<span>正在重新核对并应用…</span>`;
try{
const applied=await api('/api/resource-sync/apply',{method:'POST',body:JSON.stringify({confirm:true,clean_cache:true,scan_id:payload.scan_id||''})});
result.innerHTML=`<p class="resourcesyncok">已把 ${applied.moved_to_trash.toLocaleString()} 项移入回收站,清理 ${applied.cache_removed.toLocaleString()} 个缓存,释放 ${fmtSize(applied.bytes_reclaimed||0)}。</p>`;
}catch(error){
- button.disabled=false;button.removeAttribute('aria-busy');
+ setActionBusy(button,false);
button.innerHTML=`${icon('refresh-cw')}<span>重试同步</span>`;
result.insertAdjacentHTML('beforeend',noteHtml(error.message,{variant:'error',label:'同步失败'}))}
});
@@ -1975,24 +2013,25 @@ function renderTaste(d){
root.querySelector('[data-taste-window]').onchange=e=>{tasteWindow=e.target.value;openTaste(false)};
root.querySelector('[data-taste-refresh]').onclick=async e=>{const button=e.currentTarget;
const oldButton=button.innerHTML;
- button.disabled=true;button.setAttribute('aria-busy','true');
+ setActionBusy(button);
button.innerHTML=`${spinnerHtml('正在读取')}<span>读取中…</span>`;
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;
- button.removeAttribute('aria-busy');button.innerHTML=oldButton}};
+ tasteCacheSet(tasteWindow,result.dashboard);renderTaste(result.dashboard);actionReceipt('已更新口味分析')}
+ catch(error){stateEl.textContent=error.message||'读取失败';setActionBusy(button,false);
+ button.innerHTML=oldButton}};
root.querySelector('[data-taste-import]').onclick=()=>file.click();
file.onchange=async()=>{const selected=file.files[0];if(!selected)return;stateEl.textContent=`正在导入 ${selected.name}…`;
try{const response=await fetch('/api/taste/import',{method:'POST',headers:{'Content-Type':'application/octet-stream','X-Peach-Filename':encodeURIComponent(selected.name)},body:selected});
const payload=await response.json().catch(()=>null);if(!response.ok)throw new Error(payload?.error||`导入失败(${response.status})`);
- tasteWindow='all';tasteCacheSet('all',payload.dashboard);renderTaste(payload.dashboard)}catch(error){stateEl.textContent=error.message||'导入失败'}};
+ tasteWindow='all';tasteCacheSet('all',payload.dashboard);renderTaste(payload.dashboard);actionReceipt('已导入口味数据')}
+ catch(error){stateEl.textContent=error.message||'导入失败';actionFailure('导入口味数据',error)}};
root.querySelectorAll('[data-taste-kind]').forEach(button=>button.onclick=()=>openTasteSignal(button.dataset.tasteKind,button.dataset.tasteName));
root.querySelectorAll('[data-taste-remove]').forEach(button=>button.onclick=async()=>{
if(!confirm('从口味分析中移除这个数据源?原始导出文件会保留。'))return;
button.disabled=true;stateEl.textContent='正在移除…';
try{const result=await api('/api/taste/source',{method:'POST',body:JSON.stringify({operation:'remove',source_key:button.dataset.tasteRemove,window:tasteWindow})});
- tasteCacheSet(tasteWindow,result.dashboard);renderTaste(result.dashboard)}
+ tasteCacheSet(tasteWindow,result.dashboard);renderTaste(result.dashboard);actionReceipt('已移除口味数据源')}
catch(error){stateEl.textContent=error.message||'移除失败';button.disabled=false}});
}
async function openTaste(push=true){
@@ -2038,7 +2077,7 @@ async function saveMixAsPlaylist(mix){
dialog.querySelector('form').onsubmit=async event=>{event.preventDefault();
const form=event.currentTarget,stateEl=form.querySelector('[data-playlist-state]');
try{const result=await api('/api/playlist',{method:'POST',body:JSON.stringify({action:'create',name:new FormData(form).get('name'),asset_ids:mix.items.map(item=>item.id),source_kind:'mix',source_seed_asset_id:mix.seedId})});
- dialog.close();await openPlaylist(result.playlist.id,result.playlist.current_asset_id,true)
+ dialog.close();actionReceipt('已保存为播放列表');await openPlaylist(result.playlist.id,result.playlist.current_asset_id,true)
}catch(error){stateEl.textContent=error.message||'保存失败'}
};
dialog.querySelector('input').select();
@@ -2050,7 +2089,7 @@ async function openAddToPlaylist(item){
<label>新播放列表<input name="name" maxlength="80" placeholder="输入名称" required></label><button type="submit">新建并加入</button><span data-playlist-state></span></form>
<div class="playlistpicklist">${rows||'<p class="empty">还没有播放列表</p>'}</div>`});
const finish=async body=>{const stateEl=dialog.querySelector('[data-playlist-state]');
- try{await api('/api/playlist',{method:'POST',body:JSON.stringify(body)});dialog.close()}
+ try{await api('/api/playlist',{method:'POST',body:JSON.stringify(body)});dialog.close();actionReceipt('已加入播放列表')}
catch(error){stateEl.textContent=error.message||'加入失败'}};
dialog.querySelector('form').onsubmit=event=>{event.preventDefault();finish({action:'create',name:new FormData(event.currentTarget).get('name'),asset_ids:[item.id]})};
dialog.querySelectorAll('[data-add-playlist]').forEach(button=>button.onclick=()=>finish({action:'add',id:+button.dataset.addPlaylist,asset_ids:[item.id]}));
@@ -2060,14 +2099,14 @@ async function movePlaylistItem(queue,index,delta,currentId){
const target=index+delta;if(target<0||target>=queue.items.length)return;
const ids=queue.items.map(item=>item.id);[ids[index],ids[target]]=[ids[target],ids[index]];
await api('/api/playlist',{method:'POST',body:JSON.stringify({action:'reorder',id:queue.playlistId,asset_ids:ids})});
- await openPlaylist(queue.playlistId,currentId,false);
+ await openPlaylist(queue.playlistId,currentId,false);actionReceipt('已调整播放顺序');
}
async function removePlaylistItem(queue,assetId,currentId){
if(queue?.kind!=='playlist'||!confirm('从播放列表移出这个视频?'))return;
const result=await api('/api/playlist',{method:'POST',body:JSON.stringify({action:'remove',id:queue.playlistId,asset_id:assetId})});
if(!result.playlist.items.length){await openPlaylists(true);return}
const next=result.playlist.items.some(item=>item.id===currentId)?currentId:result.playlist.current_asset_id;
- await openPlaylist(queue.playlistId,next,false);
+ await openPlaylist(queue.playlistId,next,false);actionReceipt('已移出播放列表');
}
async function openPlaylists(push=true){
releaseHoverPreviews();disposeStage(false);enterManagementSurface();
@@ -2084,15 +2123,17 @@ async function openPlaylists(push=true){
<div class="playlistactions"><button data-rename-playlist="${list.id}">保存名称</button><button data-open-playlist="${list.id}" ${resume?'':'disabled'}>继续播放</button><button class="danger" data-delete-playlist="${list.id}">删除</button></div></article>`}).join('');
$('#stats').innerHTML=`<section class="playlistpage"><header><div><h2>播放列表</h2><p>保存 Mix,按自己的顺序继续播放。</p></div><form class="playlistcreate" id="newPlaylist"><label>新播放列表<input name="name" maxlength="80" placeholder="输入名称" required></label><button type="submit">新建</button><span data-playlist-state></span></form></header><div class="playlistcards">${cards||emptyState('list-filter','还没有播放列表','保存 Mix 或新建列表后,会在这里按自己的顺序继续播放。')}</div></section>`;
$('#newPlaylist').onsubmit=async event=>{event.preventDefault();const form=event.currentTarget;
- try{await api('/api/playlist',{method:'POST',body:JSON.stringify({action:'create',name:new FormData(form).get('name'),asset_ids:[]})});await openPlaylists(false)}
+ try{await api('/api/playlist',{method:'POST',body:JSON.stringify({action:'create',name:new FormData(form).get('name'),asset_ids:[]})});await openPlaylists(false);actionReceipt('已新建播放列表')}
catch(error){form.querySelector('[data-playlist-state]').textContent=error.message||'新建失败'}};
$('#stats').querySelectorAll('[data-open-playlist]').forEach(button=>button.onclick=()=>{
const list=data.items.find(item=>item.id===+button.dataset.openPlaylist),resume=list?.current_asset_id||list?.preview_asset_id;
if(resume)openPlaylist(list.id,resume,true)});
$('#stats').querySelectorAll('[data-rename-playlist]').forEach(button=>button.onclick=async()=>{const card=button.closest('[data-playlist-card]'),input=card.querySelector('[data-playlist-name]');
- await api('/api/playlist',{method:'POST',body:JSON.stringify({action:'rename',id:+button.dataset.renamePlaylist,name:input.value})});await openPlaylists(false)});
+ try{await api('/api/playlist',{method:'POST',body:JSON.stringify({action:'rename',id:+button.dataset.renamePlaylist,name:input.value})});await openPlaylists(false);actionReceipt('已重命名播放列表')}
+ catch(error){actionFailure('重命名播放列表',error)}});
$('#stats').querySelectorAll('[data-delete-playlist]').forEach(button=>button.onclick=async()=>{if(!confirm('删除这个播放列表?视频本身不会删除。'))return;
- await api('/api/playlist',{method:'POST',body:JSON.stringify({action:'delete',id:+button.dataset.deletePlaylist})});await openPlaylists(false)});
+ try{await api('/api/playlist',{method:'POST',body:JSON.stringify({action:'delete',id:+button.dataset.deletePlaylist})});await openPlaylists(false);actionReceipt('已删除播放列表')}
+ catch(error){actionFailure('删除播放列表',error)}});
window.scrollTo({top:0,behavior:'smooth'});
}
@@ -2306,6 +2347,8 @@ async function openReview(push=true){
if(index>=0)rows.splice(index,1);
reviewData.counts[reviewCategory]=Math.max(0,(reviewData.counts[reviewCategory]||1)-1);
render();
+ actionReceipt(button.dataset.reviewStatus==='approved'?'已通过候选':
+ button.dataset.reviewStatus==='rejected'?'已拒绝候选':'已跳过候选');
return;
}
if(state)state.textContent=result.error||'服务端拒绝了这次判定';
@@ -2397,7 +2440,7 @@ async function loadMoreFollow(button){
if(!followData||followBusy)return;
followBusy=true;
const oldButton=button?.innerHTML;
- if(button){button.setAttribute('aria-busy','true');button.innerHTML=`${spinnerHtml('加载更多')}<span>加载中…</span>`}
+ if(button){setActionBusy(button);button.innerHTML=`${spinnerHtml('加载更多')}<span>加载中…</span>`}
try{
const next=await api(followPageUrl((followData.offset||0)+FOLLOW_PAGE));
followData={...next,
@@ -2405,7 +2448,7 @@ async function loadMoreFollow(button){
// counts 一直是全库口径,用新的那份即可;offset/has_more 跟着最新一页走。
sources:next.sources||followData.sources};
renderFollow();
- }finally{followBusy=false;if(button){button.removeAttribute('aria-busy');button.innerHTML=oldButton}}
+ }finally{followBusy=false;if(button){setActionBusy(button,false);button.innerHTML=oldButton}}
}
let followCredentialProviders=new Set();
/* 上一次检查的结果。检查完页面会整页重画,如果不把结果留在这里,用户看到的就只是
@@ -2461,10 +2504,20 @@ function followCollectionItems(group){
if(!item||seen.has(item.id))return false;seen.add(item.id);return true});
}
+function followCollectionItemsNewest(group){
+ return followCollectionItems(group).sort((a,b)=>{
+ const byTime=(Date.parse(b.published_at||'')||0)-(Date.parse(a.published_at||'')||0);
+ return byTime||(+b.id||0)-(+a.id||0);
+ });
+}
+
+const followGroupedMediaOwner=group=>followCollectionItems(group).find(item=>
+ (item.media_items||[]).some(media=>media.resource_group));
+
// F95 的「8 条动态」可能只有一个网盘页,也可能一条实际视频都没有。Mix 是播放
// 语义,只能由已解析、可在 Peach 内播放的视频触发,不能拿回复数或外链数冒充。
function followVideoItems(group){
- return followCollectionItems(group).filter(item=>
+ return followCollectionItemsNewest(group).filter(item=>
item.playable&&item.media_kind==='video');
}
@@ -2487,14 +2540,18 @@ const followMediaKinds=group=>{
};
const followItemForMedia=(group,view=followMediaView)=>{
const wanted=view==='images'?'image':'video';
- return followCollectionItems(group).find(item=>followItemMediaKinds(item).has(wanted))||group.primary;
+ return followCollectionItemsNewest(group).find(item=>followItemMediaKinds(item).has(wanted))||group.primary;
};
function followMediaNote(item){
if(item.media_error)return `媒体未取得:${item.media_error}`;
if(item.media_needs_credential)return followCredentialProviders.has(item.provider)
- ?'已保存 F95 登录会话,等待下次检查重新解析资源'
- :'媒体链接需要 F95 登录会话解析';
+ ?(item.playable
+ ?'已显示可读取附件;F95 登录会话已保存,受保护资源会在下次检查重新解析'
+ :'F95 登录会话已保存;这条旧记录的受保护资源会在下次检查重新解析')
+ :(item.playable
+ ?'已显示可读取附件;其他资源需要 F95 登录会话解析'
+ :'媒体链接需要 F95 登录会话解析');
if(item.has_media&&!item.playable&&item.media_kind==='external')return item.resource_urls?.length
?`已取得 ${item.resource_urls.length} 个外部文件页;视频列表未取得`
:'外部文件页未取得;视频列表未取得';
@@ -2529,6 +2586,8 @@ function followCollectionCopy(group,item,mark=''){
}
function followQueueHtml(group,itemId){
+ const groupedOwner=followGroupedMediaOwner(group);
+ if(groupedOwner)return followEmbeddedQueueHtml(groupedOwner,null);
const items=followVideoItems(group);
return `<aside class="mixqueue followqueue" data-queue-kind="collection"><div class="mixqueuehead"><div><h2>视频合集</h2><span>${esc(group.primary.title||'未命名合集')} · ${items.length} 个视频</span></div><div class="mixqueueactions">
<button data-follow-queue-close title="关闭" aria-label="关闭">${icon('x')}</button></div></div><div class="mixlist">${items.map(item=>{
@@ -2544,14 +2603,22 @@ function followQueueHtml(group,itemId){
function followEmbeddedQueueHtml(item,mediaIndex){
const items=item.media_items||[];
- return `<aside class="mixqueue followqueue" data-queue-kind="media"><div class="mixqueuehead"><div><h2>多媒体</h2><span>${esc(item.title||'未命名内容')} · ${items.length} 个媒体</span></div><div class="mixqueueactions">
- <button data-follow-queue-close title="关闭" aria-label="关闭">${icon('x')}</button></div></div><div class="mixlist">${items.map(media=>{
+ const groups=[];
+ items.forEach(media=>{
+ const key=media.resource_group||'ungrouped';
+ let group=groups.find(row=>row.key===key);
+ if(!group){group={key,label:media.resource_group_label||'',items:[]};groups.push(group)}
+ group.items.push(media);
+ });
+ const rows=groups.map(group=>`${group.label?`<h3 class="mixgrouplabel">${esc(group.label)} <span>${group.items.length}</span></h3>`:''}${group.items.map(media=>{
const thumb=media.thumb_url
?`<img src="${esc(media.thumb_url)}" alt="" loading="lazy" referrerpolicy="no-referrer" onerror="this.remove()">`
:`<span class="fnothumb">${sourceIcon(media.resource_provider||item.provider)}</span>`;
- return `<div class="mixrow"><button class="mixitem ${media.index===mediaIndex?'current':''}" data-follow-media-item="${media.index}" data-media-kind="${media.media_kind}" aria-current="${media.index===mediaIndex?'true':'false'}">
+ return `<div class="mixrow"><button class="mixitem ${media.index===mediaIndex?'current':''}" data-follow-media-owner="${item.id}" data-follow-media-item="${media.index}" data-media-kind="${media.media_kind}" aria-current="${media.index===mediaIndex?'true':'false'}">
<span class="mixitempic">${thumb}</span><span class="mixitemtext"><b data-middle-truncate>${esc(javDisplayName(media))}</b><span data-truncate-end>${media.media_kind==='image'?'图片':'视频'}</span></span></button></div>`;
- }).join('')}</div></aside>`;
+ }).join('')}`).join('');
+ return `<aside class="mixqueue followqueue" data-queue-kind="media"><div class="mixqueuehead"><div><h2>多媒体</h2><span>${esc(item.title||'未命名内容')} · ${items.length} 个媒体</span></div><div class="mixqueueactions">
+ <button data-follow-queue-close title="关闭" aria-label="关闭">${icon('x')}</button></div></div><div class="mixlist">${rows}</div></aside>`;
}
/* 重建条目索引。`merge` 时只往里加,不清空已有的。
@@ -2671,7 +2738,8 @@ async function openFollowDetail(id,push=true,mediaIndex=null,preserveReturn=fals
$('#stage').querySelectorAll('[data-follow-queue-item]').forEach(button=>button.onclick=()=>
openFollowDetail(+button.dataset.followQueueItem,true));
$('#stage').querySelectorAll('[data-follow-media-item]').forEach(button=>button.onclick=()=>
- openFollowDetail(item.id,false,+button.dataset.followMediaItem,true));
+ openFollowDetail(+(button.dataset.followMediaOwner||item.id),false,
+ +button.dataset.followMediaItem,true));
const switchImage=index=>openFollowDetail(item.id,false,+index,true);
$('#stage').querySelectorAll('[data-follow-image-item]').forEach(button=>button.onclick=()=>
switchImage(button.dataset.followImageItem));
@@ -2717,21 +2785,32 @@ async function openFollowDetail(id,push=true,mediaIndex=null,preserveReturn=fals
if(followTags.has(tag))followTags.delete(tag);else followTags.add(tag);
await closeDetail();
});
- const write=async(button,path,body,done)=>{
- const state=$('#stage').querySelector('.fstate');button.disabled=true;
- try{await api(path,{method:'POST',body:JSON.stringify(body)});done();state.textContent='已更新'}
- catch(error){button.disabled=false;state.textContent=error.message||'操作失败'}
+ const write=async(button,path,body,done,{message='已更新',undo=null}={})=>{
+ const state=$('#stage').querySelector('.fstate');setActionBusy(button);
+ try{await api(path,{method:'POST',body:JSON.stringify(body)});done();state.textContent='';
+ actionReceipt(message,{undo})}
+ catch(error){state.textContent=error.message||'操作失败';actionFailure('更新关注状态',error)}
+ finally{setActionBusy(button,false)}
};
$('#stage').querySelector('[data-follow-detail-save]')?.addEventListener('click',event=>{
const button=event.currentTarget;
write(button,'/api/follow/save',{item:item.id},()=>{
- item.status='saved';button.innerHTML=icon('check');button.title='已保存';button.setAttribute('aria-label','已保存')});
+ item.status='saved';button.innerHTML=icon('check');button.title='已保存';button.setAttribute('aria-label','已保存')},
+ {message:'已保存到账本'});
});
- $('#stage').querySelectorAll('[data-follow-detail-status]').forEach(button=>button.onclick=()=>
- write(button,'/api/follow/status',{item:item.id,to:button.dataset.followDetailStatus},()=>{
- item.status=button.dataset.followDetailStatus;
+ $('#stage').querySelectorAll('[data-follow-detail-status]').forEach(button=>button.onclick=()=>{
+ const before=item.status,to=button.dataset.followDetailStatus;
+ write(button,'/api/follow/status',{item:item.id,to},()=>{
+ item.status=to;
+ $('#stage').querySelectorAll('[data-follow-detail-status]').forEach(control=>
+ control.setAttribute('aria-pressed',String(control.dataset.followDetailStatus===item.status)))},
+ {message:to==='seen'?'已标记看过':'已更新关注状态',undo:before!=='saved'?async()=>{
+ await api('/api/follow/status',{method:'POST',body:JSON.stringify({item:item.id,to:before})});
+ item.status=before;
$('#stage').querySelectorAll('[data-follow-detail-status]').forEach(control=>
- control.setAttribute('aria-pressed',String(control.dataset.followDetailStatus===item.status)))}));
+ control.setAttribute('aria-pressed',String(control.dataset.followDetailStatus===before)));
+ }:null});
+ });
alignFollowImageControls();
// 滚到舞台本身,不是页面头部——就近展开的意义就在于视线不被拽走。
// 复用首页那套 sticky 偏移,标题不会被吸顶的筛选条盖住。
@@ -2774,11 +2853,13 @@ function followCard(group,authorSources=[]){
? `<img src="${esc(thumbUrl)}" alt="" loading="lazy" referrerpolicy="no-referrer" onerror="this.remove()">`
: `<span class="fnothumb">${esc(item.provider_label)}</span>`;
const videos=followMediaView==='videos'?followVideoItems(group):[],embedded=item.media_items||[];
- const isMix=embedded.length>1||videos.length>1;
- const mixCount=embedded.length>1?embedded.length:videos.length;
+ const groupedOwner=followMediaView==='videos'?followGroupedMediaOwner(group):null;
+ const groupedVideos=(groupedOwner?.media_items||[]).filter(media=>media.media_kind==='video');
+ const isMix=embedded.length>1||groupedVideos.length>1||videos.length>1;
+ const mixCount=embedded.length>1?embedded.length:(groupedVideos.length||videos.length);
const mixKind=embedded.length&&embedded.every(media=>media.media_kind==='image')?'图片'
:embedded.length&&embedded.some(media=>media.media_kind==='image')?'媒体':'视频';
- const mixTarget=embedded.length>1?item.id:videos[0]?.id;
+ const mixTarget=embedded.length>1?item.id:(videos[0]?.id||item.id);
const badges=followBadges(group);
const tags=followCardTags(item).slice(0,3).map(tag=>followTagChip(item,tag)).join('');
const open=`<button class="cardopenhit" data-follow-detail="${item.id}" aria-label="打开 ${esc(item.title)} 详情"></button>`;
@@ -2890,7 +2971,7 @@ function readFollowView(){
followMediaView=params.get('media')==='images'?'images':'videos';
}
function followMediaControl(counts){
- if(!counts.images)return '';
+ if(!counts.images&&followMediaView!=='images')return '';
return mediaViewButtonsHtml({active:followMediaView,videoCount:counts.videos,imageCount:counts.images});
}
function groupTagType(groups,tag){
@@ -2937,10 +3018,6 @@ function renderFollow(){
const mediaCounts={videos:0,images:0};
groups.forEach(group=>followMediaKinds(group).forEach(kind=>
mediaCounts[kind==='image'?'images':'videos']++));
- const requestedMediaView=followMediaView;
- if(followMediaView==='images'&&!mediaCounts.images)followMediaView='videos';
- if(followMediaView==='videos'&&!mediaCounts.videos&&mediaCounts.images)followMediaView='images';
- if(requestedMediaView!==followMediaView&&location.pathname==='/follow')route(followViewPath(),true);
const wantedKind=followMediaView==='images'?'image':'video';
const visible=groups.filter(group=>followMediaKinds(group).has(wantedKind));
const providerPills=[...providers].map(([key,label])=>
@@ -3029,8 +3106,8 @@ function wireFollowOlder(){
if(!button)return;
button.onclick=async()=>{
if(followBusy)return;
- followBusy=true;button.setAttribute('aria-busy','true');
- button.innerHTML=loadingDotsHtml('抓取中…');
+ followBusy=true;setActionBusy(button);
+ button.innerHTML=`${spinnerHtml('抓取中')}<span>抓取中…</span>`;
try{
followCheckReport=await api('/api/follow/check',
{method:'POST',body:JSON.stringify({older:true})});
@@ -3040,7 +3117,7 @@ function wireFollowOlder(){
followCheckReport={results:[{ok:false,error:error.message}]};
followCheckToast(followCheckReport);
await openFollow(false);
- }finally{followBusy=false;button.removeAttribute('aria-busy')}
+ }finally{followBusy=false;setActionBusy(button,false)}
};
}
@@ -3512,7 +3589,7 @@ function wireFollowManage(){
.map(line=>line.trim()).filter(Boolean);
if(!lines.length)return;
const byName=lines.some(line=>!line.includes('/'));
- form.dataset.busy='true';button.setAttribute('aria-busy','true');
+ form.dataset.busy='true';setActionBusy(button);
if(prefix)prefix.innerHTML=spinnerHtml('查找中');
// 索引下载的提醒只在真按名字查时出现;常驻成一句说明就是噪音。
state.textContent=byName?'查找中…(首次按名字查要下载创作者索引,可能几十秒)':'识别中…';
@@ -3522,7 +3599,7 @@ function wireFollowManage(){
state.textContent='';if(box){box.value='';box.style.height='auto'}
renderFollowPicks(result.results||[]);
}catch(error){state.textContent=error.message||'查找失败'}
- finally{form.dataset.busy='false';button.removeAttribute('aria-busy');
+ finally{form.dataset.busy='false';setActionBusy(button,false);
if(prefix)prefix.innerHTML=icon('search')}
};
root.querySelectorAll('[data-follow-remove]').forEach(button=>button.onclick=async()=>{
@@ -3531,23 +3608,27 @@ function wireFollowManage(){
try{
await api('/api/follow/source',{method:'POST',
body:JSON.stringify({action:'remove',id:+button.dataset.followRemove})});
- await openFollowManage(false);
- }catch(error){button.disabled=false;alert(error.message)}
+ await openFollowManage(false);actionReceipt('已取消关注来源');
+ }catch(error){button.disabled=false;actionFailure('取消关注来源',error)}
});
root.querySelectorAll('[data-follow-enabled]').forEach(control=>control.onchange=async()=>{
const enabled=control.checked;control.disabled=true;
try{
await api('/api/follow/source',{method:'POST',body:JSON.stringify(
{action:'enabled',id:Number(control.dataset.followEnabled),enabled})});
- await openFollowManage(false);
- }catch(error){control.checked=!enabled;control.disabled=false;alert(error.message)}
+ await openFollowManage(false);actionReceipt(enabled?'已启用关注来源':'已暂停关注来源',{undo:async()=>{
+ await api('/api/follow/source',{method:'POST',body:JSON.stringify(
+ {action:'enabled',id:Number(control.dataset.followEnabled),enabled:!enabled})});
+ await openFollowManage(false);
+ }});
+ }catch(error){control.checked=!enabled;control.disabled=false;actionFailure('更新关注来源',error)}
});
root.querySelectorAll('[data-follow-check]').forEach(button=>button.onclick=async()=>{
if(followBusy)return;
followBusy=true;const oldTitle=button.title;
const oldAria=button.getAttribute('aria-label');
const oldButton=button.innerHTML;
- button.setAttribute('aria-busy','true');button.title='检查中…';
+ setActionBusy(button);button.title='检查中…';
button.setAttribute('aria-label','检查中…');
button.innerHTML=`${spinnerHtml('检查中')}${button.matches('.frowicon')?'':'<span>检查中…</span>'}`;
try{
@@ -3569,7 +3650,7 @@ function wireFollowManage(){
if(box)box.outerHTML=note;
else $('#stats').querySelector('.fsec')?.insertAdjacentHTML('afterbegin',note);
}
- finally{followBusy=false;button.removeAttribute('aria-busy');button.innerHTML=oldButton;
+ finally{followBusy=false;setActionBusy(button,false);button.innerHTML=oldButton;
button.title=oldTitle;if(oldAria===null)button.removeAttribute('aria-label');
else button.setAttribute('aria-label',oldAria)}
});
@@ -3578,8 +3659,11 @@ function wireFollowManage(){
try{
await api('/api/follow/author-alias',{method:'POST',body:JSON.stringify(
{action:'add',canonical,alias})});
- await openFollowManage(false);
- }catch(error){button.disabled=false;alert(error.message)}
+ await openFollowManage(false);actionReceipt('已合并作者别名',{undo:async()=>{
+ await api('/api/follow/author-alias',{method:'POST',body:JSON.stringify({action:'remove',alias})});
+ await openFollowManage(false);
+ }});
+ }catch(error){button.disabled=false;actionFailure('合并作者别名',error)}
};
root.querySelectorAll('[data-follow-alias-add]').forEach(button=>button.onclick=()=>
saveAuthorAlias(button.dataset.canonical,button.dataset.alias,button));
@@ -3596,8 +3680,8 @@ function wireFollowManage(){
try{
await api('/api/follow/author-alias',{method:'POST',body:JSON.stringify(
{action:'remove',alias})});
- await openFollowManage(false);
- }catch(error){button.disabled=false;alert(error.message)}
+ await openFollowManage(false);actionReceipt('已移除作者别名');
+ }catch(error){button.disabled=false;actionFailure('移除作者别名',error)}
});
root.querySelectorAll('[data-follow-guess]').forEach(chip=>chip.onclick=()=>{
if(!form)return;
@@ -3618,7 +3702,7 @@ function wireFollowManage(){
await api('/api/follow/credential',{method:'POST',body:JSON.stringify(
{provider:form.dataset.credForm,values})});
// 值不回显:清掉输入框,重画之后只看得到字段名。
- form.reset();await openFollowManage(false);
+ form.reset();await openFollowManage(false);actionReceipt('已保存来源凭据');
}catch(error){state.textContent=error.message||'保存失败';button.disabled=false}
});
root.querySelectorAll('[data-cred-clear]').forEach(button=>button.onclick=async()=>{
@@ -3630,8 +3714,8 @@ function wireFollowManage(){
const done=await api('/api/follow/credential',{method:'POST',body:JSON.stringify(
{provider:button.dataset.credClear,values:{}})});
if(done.note)alert(done.note);
- await openFollowManage(false);
- }catch(error){button.disabled=false;alert(error.message)}
+ await openFollowManage(false);actionReceipt('已清除来源凭据');
+ }catch(error){button.disabled=false;actionFailure('清除来源凭据',error)}
});
root.querySelectorAll('[data-follow-bulk]').forEach(button=>button.onclick=async()=>{
const to=button.dataset.followBulk;
@@ -3644,8 +3728,8 @@ function wireFollowManage(){
for(const id of ids){
await api('/api/follow/status',{method:'POST',body:JSON.stringify({item:id,to})});
}
- await openFollowManage(false);
- }catch(error){button.disabled=false;alert(error.message)}
+ await openFollowManage(false);actionReceipt(`已批量标记 ${ids.length} 项`);
+ }catch(error){button.disabled=false;actionFailure('批量更新关注状态',error)}
});
root.querySelectorAll('[data-follow-view]').forEach(button=>
button.onclick=()=>openFollow());
@@ -3762,7 +3846,7 @@ function renderFollowPicks(results){
if(!picked.length)return;
const state=box.querySelector('[data-pick-state]');
if(addButton.getAttribute('aria-busy')==='true')return;
- addButton.setAttribute('aria-busy','true');
+ setActionBusy(addButton);
let done=0;const failures=[];
for(const input of picked){
state.innerHTML=`${spinnerHtml('添加中')}<span>添加中… ${++done}/${picked.length}</span>`;
@@ -3777,23 +3861,33 @@ function renderFollowPicks(results){
}
if(failures.length){
state.textContent=failures.join(';');
- addButton.removeAttribute('aria-busy');
+ setActionBusy(addButton,false);
return;
}
await openFollowManage(false);
+ actionReceipt(`已添加 ${picked.length} 个关注来源`);
};
}
async function followWrite(button,path,body){
const card=button.closest('.followitem'),state=card?.querySelector('.fstate');
- button.disabled=true;
+ const before=card?.dataset.status||'new';
+ setActionBusy(button);
try{
await api(path,{method:'POST',body:JSON.stringify(body)});
await openFollow(false);
+ const saving=path==='/api/follow/save',to=body.to;
+ const labels={new:'已恢复未看',seen:'已标记已看',ignored:'已忽略'};
+ actionReceipt(saving?'已保存到账本':(labels[to]||'已更新关注状态'),{undo:!saving&&before!=='saved'?async()=>{
+ await api('/api/follow/status',{method:'POST',body:JSON.stringify({item:body.item,to:before})});
+ await openFollow(false);
+ }:null});
}catch(e){
- button.disabled=false;
// 只读端(reader)写入必然 409,那是正常状态;照实显示比静默失败好。
- if(state)state.textContent=e.message;else alert(e.message);
+ if(state)state.textContent=e.message;
+ actionFailure(path==='/api/follow/save'?'保存到账本':'更新关注状态',e);
+ }finally{
+ setActionBusy(button,false);
}
}
function wireReviewAssets(root){
@@ -4150,14 +4244,14 @@ const sourceHint=message=>SOURCE_HINTS[message]||message;
async function revealSource(id,status,{button=null}={}){
if(button?.getAttribute('aria-busy')==='true')return;
const buttonHtml=button?.innerHTML,label=button?.textContent.trim();
- if(button){button.setAttribute('aria-busy','true');
+ if(button){setActionBusy(button);
button.innerHTML=`${spinnerHtml('正在定位')}${label?`<span>${esc(label)}</span>`:''}`}
status.textContent='';
try{
await api('/api/reveal',{method:'POST',body:JSON.stringify({id})});
status.textContent='';toast('已在资源管理器中显示');
}catch(e){status.textContent=sourceHint(e.message)}
- finally{if(button){button.removeAttribute('aria-busy');button.innerHTML=buttonHtml}}
+ finally{if(button){setActionBusy(button,false);button.innerHTML=buttonHtml}}
}
async function syncMissing(id,status,done){
@@ -4168,8 +4262,15 @@ async function syncMissing(id,status,done){
status.textContent=r.removed
? `已把 ${r.removed} 项移入回收站(核对 ${r.checked} 项)`
: `目录内 ${r.checked} 项都还在,无需改动`;
- if(r.removed&&done)done(r);
- }catch(e){status.textContent=sourceHint(e.message)}
+ if(r.removed){
+ const ids=(r.items||[]).map(item=>item.id);
+ if(done)done(r);
+ actionReceipt(`已把 ${r.removed} 项移入回收站`,{undo:ids.length?async()=>{
+ await api('/api/batch',{method:'POST',body:JSON.stringify({ids,operation:'restore'})});
+ if(done)done({removed:0,restored:ids.length});
+ }:null});
+ }else actionReceipt('目录核对完成,无需改动');
+ }catch(e){status.textContent=sourceHint(e.message);actionFailure('核对目录',e)}
}
/* 两个动作在照片详情里和作品标题旁复用;状态位置由各自表面决定。 */
@@ -5263,18 +5364,40 @@ async function openItem(id,push=true,queueContext=null,anchor=null){
const g=$('#gate');
const onlineGate=$('#onlineGate');
$('#addPlaylist').onclick=()=>openAddToPlaylist(it);
+ const paintDetailFeedback=result=>{
+ Object.assign(it,{feedback:result.feedback,disposal:result.disposal,o_count:result.o_count});
+ const stage=$('#stage');if(!stage)return;
+ stage.querySelector('.dislike')?.setAttribute('aria-pressed',result.feedback==='dislike');
+ stage.querySelector('.seen')?.setAttribute('aria-pressed',result.feedback==='seen');
+ stage.querySelector('.dispose')?.setAttribute('aria-pressed',result.disposal==='trash');
+ if($('#oCount'))$('#oCount').textContent=result.o_count||0;
+ };
+ const postFeedback=async kind=>{
+ const result=await api('/api/feedback',{method:'POST',body:JSON.stringify({id:it.id,kind})});
+ paintDetailFeedback(result);return result;
+ };
$('#stage').querySelectorAll('[data-kind]').forEach(b=>b.onclick=async()=>{
+ const kind=b.dataset.kind;
+ const before={feedback:it.feedback||null,disposal:it.disposal||null,o_count:it.o_count||0};
+ setActionBusy(b);
try{
- const r=await api('/api/feedback',{method:'POST',body:JSON.stringify({id:it.id,kind:b.dataset.kind})});
- Object.assign(it,{feedback:r.feedback,disposal:r.disposal,o_count:r.o_count});
- $('#stage').querySelector('.dislike').setAttribute('aria-pressed',r.feedback==='dislike');
- $('#stage').querySelector('.seen').setAttribute('aria-pressed',r.feedback==='seen');
- $('#stage').querySelector('.dispose').setAttribute('aria-pressed',r.disposal==='trash');
- $('#oCount').textContent=r.o_count||0;
- if(b.dataset.kind==='dispose'&&r.disposal==='trash'&&state.state==='ads'){
+ const r=await postFeedback(kind);
+ const messages={dislike:r.feedback==='dislike'?'已标记不合口味':'已取消不合口味',
+ seen:r.feedback==='seen'?'已标记看过':'已取消看过',
+ dispose:r.disposal==='trash'?'已移入回收站':'已移出回收站',o:'已记录一次高潮'};
+ actionReceipt(messages[kind],{undo:async()=>{
+ if(kind==='o')await postFeedback('o-undo');
+ else if(kind==='dispose')await postFeedback('dispose');
+ else{
+ if(r.feedback)await postFeedback(r.feedback);
+ if(before.feedback)await postFeedback(before.feedback);
+ }
+ if(state.state==='ads')await load(true);
+ }});
+ if(kind==='dispose'&&r.disposal==='trash'&&state.state==='ads'){
disposeStage(true);await load(true);
}
- }catch(error){alert(`操作失败:${error.message||'未知错误'}`)}
+ }catch(error){actionFailure('操作',error)}finally{setActionBusy(b,false)}
});
const renderDetailTags=()=>{
const wrap=$('#detailTags');if(!wrap)return;
@@ -5289,17 +5412,28 @@ async function openItem(id,push=true,queueContext=null,anchor=null){
commitContextFilter(filters=>{filters.tag=s.dataset.tag});
window.scrollTo({top:0,behavior:'smooth'})});
wrap.querySelectorAll('[data-remove-tag]').forEach(b=>b.onclick=async()=>{
- b.disabled=true;const tag=b.dataset.removeTag;
- const r=await api('/api/item-tag',{method:'POST',body:JSON.stringify({id:it.id,operation:'remove',tag})});
- if(r.ok){it.tags=(it.tags||[]).filter(x=>foldName(x.k)!==foldName(tag));renderDetailTags()}else b.disabled=false});
+ const tag=b.dataset.removeTag;setActionBusy(b);
+ try{const r=await api('/api/item-tag',{method:'POST',body:JSON.stringify({id:it.id,operation:'remove',tag})});
+ if(!r.ok)throw new Error('标签未删除');
+ const old=(it.tags||[]).find(x=>foldName(x.k)===foldName(tag))||{k:tag,cat:'general'};
+ it.tags=(it.tags||[]).filter(x=>foldName(x.k)!==foldName(tag));renderDetailTags();
+ actionReceipt(`已删除标签「${tagLabel(tag)}」`,{undo:async()=>{
+ await api('/api/item-tag',{method:'POST',body:JSON.stringify({id:it.id,operation:'add',tag})});
+ if(!(it.tags||[]).some(x=>foldName(x.k)===foldName(tag)))it.tags.push(old);
+ renderDetailTags();
+ }});
+ }catch(error){actionFailure('删除标签',error)}finally{setActionBusy(b,false)}});
const addTag=async tag=>{tag=tag.trim();if(!tag)return;
- const r=await api('/api/item-tag',{method:'POST',body:JSON.stringify({id:it.id,operation:'add',tag})});
+ try{const r=await api('/api/item-tag',{method:'POST',body:JSON.stringify({id:it.id,operation:'add',tag})});
if(r.ok){
if(!it.tags.some(x=>foldName(x.k)===foldName(tag)))it.tags.push({k:tag,cat:'general'});
try{const old=JSON.parse(localStorage.getItem('peach.recentTags')||'[]').filter(x=>foldName(x)!==foldName(tag));
localStorage.setItem('peach.recentTags',JSON.stringify([tag,...old].slice(0,12)))}catch(_e){}
- renderDetailTags()
- }
+ renderDetailTags();actionReceipt(`已添加标签「${tagLabel(tag)}」`,{undo:async()=>{
+ await api('/api/item-tag',{method:'POST',body:JSON.stringify({id:it.id,operation:'remove',tag})});
+ it.tags=(it.tags||[]).filter(x=>foldName(x.k)!==foldName(tag));renderDetailTags();
+ }})
+ }}catch(error){actionFailure('添加标签',error)}
};
const plus=$('#tagPlus'),picker=$('#tagPicker'),search=$('#tagPickSearch'),body=$('#tagPickBody');
let outsideHandler=null,activeIndex=-1;
@@ -5335,33 +5469,51 @@ async function openItem(id,push=true,queueContext=null,anchor=null){
renderDetailTags();
$('#stage').querySelectorAll('[data-entity-kind]').forEach(b=>b.onclick=()=>
openEntity(b.dataset.entityKind,b.dataset.entityName));
- $('#stageLater').onclick=async()=>{const r=await api('/api/watch-later',{method:'POST',
- body:JSON.stringify({id:it.id})});it.watch_later=r.watch_later;
- $('#stageLater').setAttribute('aria-pressed',r.watch_later);
- $('#stageLater').innerHTML=r.watch_later?icon('check'):icon('bookmark-plus')};
+ const paintLater=value=>{it.watch_later=value;const button=$('#stageLater');if(!button)return;
+ button.setAttribute('aria-pressed',value);button.innerHTML=value?icon('check'):icon('bookmark-plus')};
+ $('#stageLater').onclick=async()=>{const button=$('#stageLater');setActionBusy(button);
+ try{const r=await api('/api/watch-later',{method:'POST',body:JSON.stringify({id:it.id})});
+ paintLater(r.watch_later);actionReceipt(r.watch_later?'已加入稍后看':'已移出稍后看',{undo:async()=>{
+ const restored=await api('/api/watch-later',{method:'POST',body:JSON.stringify({id:it.id})});
+ paintLater(restored.watch_later);
+ }});
+ }catch(error){actionFailure('更新稍后看',error)}finally{setActionBusy(button,false)}};
$('#betterVersion').onclick=async()=>{const b=$('#betterVersion'),wanted=b.getAttribute('aria-pressed')!=='true';
- const r=await api('/api/quality-goal',{method:'POST',body:JSON.stringify({id:it.id,wanted})});
- it.better_version=r.better_version;it.better_version_reason=r.better_version_reason;
- b.setAttribute('aria-pressed',String(r.better_version));b.title=r.better_version?(r.better_version_reason||'已标记寻找更好版本'):'寻找高清、无水印或完整版'};
+ const before={wanted:!!it.better_version,reason:it.better_version_reason||''};setActionBusy(b);
+ const paintQuality=r=>{it.better_version=r.better_version;it.better_version_reason=r.better_version_reason;
+ if(!$('#betterVersion'))return;$('#betterVersion').setAttribute('aria-pressed',String(r.better_version));
+ $('#betterVersion').title=r.better_version?(r.better_version_reason||'已标记寻找更好版本'):'寻找高清、无水印或完整版'};
+ try{const r=await api('/api/quality-goal',{method:'POST',body:JSON.stringify({id:it.id,wanted})});paintQuality(r);
+ actionReceipt(r.better_version?'已标记寻找更好版本':'已取消寻找更好版本',{undo:async()=>{
+ const restored=await api('/api/quality-goal',{method:'POST',body:JSON.stringify({id:it.id,wanted:before.wanted,reason:before.reason})});paintQuality(restored);
+ }});
+ }catch(error){actionFailure('更新版本需求',error)}finally{setActionBusy(b,false)}};
const preferenceToggle=$('#preferenceToggle'),preferencePanel=$('#preferencePanel');
preferenceToggle.onclick=()=>{const open=preferencePanel.hidden;preferencePanel.hidden=!open;
preferenceToggle.setAttribute('aria-expanded',String(open));if(open)$('#likeReason').focus()};
- const savePreference=async()=>{
+ const savePreference=async(options={})=>{
const btn=$('#savePreference'),like=$('#likeBtn'),stateText=$('#preferenceState');
- btn.disabled=true;btn.setAttribute('aria-busy','true');
+ const before={liked:!!it.liked,reason:it.like_reason||''};
+ setActionBusy(btn);
btn.innerHTML=`${spinnerHtml('正在提交喜爱理由')}<span>提交中…</span>`;stateText.textContent='保存中…';
const reason=$('#likeReason').value;
- const liked=like.getAttribute('aria-pressed')==='true'||reason.trim().length>0;
+ const liked=options.liked??(like.getAttribute('aria-pressed')==='true'||reason.trim().length>0);
+ const paintPreference=r=>{it.liked=r.liked;it.like_reason=r.like_reason;
+ if(!$('#likeBtn'))return;$('#likeBtn').setAttribute('aria-pressed',r.liked);
+ $('#likeBtn').setAttribute('aria-label',r.liked?'取消喜欢':'喜欢');
+ $('#preferenceToggle').dataset.hasReason=String(!!r.like_reason);
+ $('#likeReason').value=r.like_reason||''};
try{const r=await api('/api/preference',{method:'POST',body:JSON.stringify({id:it.id,liked,reason})});
- it.liked=r.liked;it.like_reason=r.like_reason;
- like.setAttribute('aria-pressed',r.liked);like.setAttribute('aria-label',r.liked?'取消喜欢':'喜欢');
- preferenceToggle.dataset.hasReason=String(!!r.like_reason);
+ paintPreference(r);
stateText.textContent='已保存';setTimeout(()=>{if(stateText.textContent==='已保存')stateText.textContent=''},1400);
- }catch(e){stateText.textContent='保存失败 · 请重试'}finally{
- btn.disabled=false;btn.removeAttribute('aria-busy');btn.innerHTML='<span>提交</span>'}
+ actionReceipt(r.liked?'已保存喜欢偏好':'已取消喜欢',{undo:async()=>{
+ const restored=await api('/api/preference',{method:'POST',body:JSON.stringify({id:it.id,...before})});
+ paintPreference(restored);
+ }});
+ }catch(e){stateText.textContent='保存失败 · 请重试';actionFailure('保存喜欢偏好',e)}finally{
+ setActionBusy(btn,false);btn.innerHTML='<span>提交</span>'}
};
- $('#likeBtn').onclick=async()=>{const b=$('#likeBtn');
- b.setAttribute('aria-pressed',b.getAttribute('aria-pressed')!=='true');await savePreference()};
+ $('#likeBtn').onclick=()=>savePreference({liked:$('#likeBtn').getAttribute('aria-pressed')!=='true'});
$('#savePreference').onclick=savePreference;
const vv=$('#vid');
vv.addEventListener('play',()=>{if(!$('#stage').dataset.c){$('#stage').dataset.c='1';
@@ -5763,13 +5915,25 @@ $('#tok').addEventListener('touchcancel',()=>{
tokTouch=null;$('#tokBar').classList.remove('scrubbing');
},{passive:true});
[['#tokDislike','dislike'],['#tokSeen','seen'],['#tokO','o']].forEach(([s,kind])=>{
- $(s).onclick=async()=>{const it=tokList[tokIdx];
- const r=await api('/api/feedback',{method:'POST',body:JSON.stringify({id:it.id,kind})});
- $('#tokDislike').setAttribute('aria-pressed',r.feedback==='dislike');
- $('#tokSeen').setAttribute('aria-pressed',r.feedback==='seen');
- $('#tokSeenLabel').textContent=r.feedback==='seen'?'已看':'看过';
- $('#tokOn').textContent=r.o_count||0;
- if(kind==='dislike'&&r.feedback==='dislike')setTimeout(()=>tokNext(1),260)}});
+ $(s).onclick=async()=>{const it=tokList[tokIdx],button=$(s),before=it.feedback||null;
+ const paint=r=>{Object.assign(it,{feedback:r.feedback,o_count:r.o_count});
+ if(tokList[tokIdx]?.id!==it.id)return;
+ $('#tokDislike').setAttribute('aria-pressed',r.feedback==='dislike');
+ $('#tokSeen').setAttribute('aria-pressed',r.feedback==='seen');
+ $('#tokSeenLabel').textContent=r.feedback==='seen'?'已看':'看过';
+ $('#tokOn').textContent=r.o_count||0};
+ const post=async value=>{const r=await api('/api/feedback',{method:'POST',
+ body:JSON.stringify({id:it.id,kind:value})});paint(r);return r};
+ setActionBusy(button);
+ try{const r=await post(kind);
+ actionReceipt(kind==='o'?'已记录一次高潮':r.feedback===kind?
+ (kind==='seen'?'已标记看过':'已标记不合口味'):
+ (kind==='seen'?'已取消看过':'已取消不合口味'),{undo:async()=>{
+ if(kind==='o')await post('o-undo');
+ else{if(r.feedback)await post(r.feedback);if(before)await post(before)}
+ }});
+ if(kind==='dislike'&&r.feedback==='dislike')setTimeout(()=>tokNext(1),260)
+ }catch(error){actionFailure('更新反馈',error)}finally{setActionBusy(button,false)}}});
/* 当前该响应播放快捷键的 video:沉浸模式优先,其次详情播放器,都没开就返回 null。
直接操作原生元素而不是 Video.js 实例——沉浸模式没有 Video.js,而详情播放器读的
diff --git a/web/js/ui-components.js b/web/js/ui-components.js
index 72988c66f..0d15e67b5 100644
--- a/web/js/ui-components.js
+++ b/web/js/ui-components.js
@@ -28,6 +28,35 @@ export function spinnerHtml(label='加载中'){
return `<span class="geist-spinner" role="status" aria-label="${esc(label)}">${bars}</span>`;
}
+/**
+ * Geist loading action: visually unavailable and inert without using native
+ * `disabled`, so the trigger keeps keyboard focus while its request is running.
+ */
+export function setActionBusy(control,busy=true){
+ if(!control)return;
+ if(busy){
+ control.setAttribute('aria-busy','true');
+ control.setAttribute('aria-disabled','true');
+ }else{
+ control.removeAttribute('aria-busy');
+ control.removeAttribute('aria-disabled');
+ }
+}
+
+const busyActionRoots=new WeakSet();
+
+/** Block repeat pointer and keyboard activation for every shared busy action. */
+export function wireBusyActions(root=document){
+ if(busyActionRoots.has(root))return;
+ busyActionRoots.add(root);
+ root.addEventListener('click',event=>{
+ const control=event.target.closest?.('button[aria-busy="true"],[role="button"][aria-busy="true"]');
+ if(!control||!root.contains(control))return;
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ },true);
+}
+
/** Geist Loading Dots: indeterminate work continuing in the background. */
export function loadingDotsHtml(label='正在处理', {className=''}={}){
return `<span class="geist-loading${className?` ${esc(className)}`:''}" role="status">