// ==UserScript== // @name Steam 游戏库收藏分析 // @namespace steam-game-library-viewer // @author Github: SmallRob,SteamID: Healer007 // @version 2.48.0 // @description 给 Steam 商店页和个人主页加一个「游戏库分析」面板,一屏看清你的游戏资产。🏆 我的成就:同步你在 Steam 上的真实成就,按完成率、稀有度浏览每一款游戏,看得见哪款已完美通关、哪些是全球稀有成就、还差哪几个。🎮 游戏收藏:绝版游戏、锁区(你所在地区无法购买)、Epic / PS 限时免费、DLC 与捆绑包、年度佳作清单。💰 跨区比价:自动对比美 / 日 / 俄 / 土等多区售价,标出最便宜的国家。📊 统计图表:游玩时长、玩得最久的游戏、最近入库、年度曲库曲线。☁️ 云存档:查询各游戏的云存档状态。💗 愿望单:整理愿望单并识别家庭共享。全部数据只存在你自己的浏览器里,不上传任何服务器。完整更新日志见项目 README。 // @description:en Adds a "Game Library" panel to Steam's store and profile pages so you can see your whole game collection at a glance. 🏆 Achievements: syncs your real Steam achievements and lets you browse every game by completion rate and rarity — see which ones you've perfected, which contain globally rare achievements, and what's still missing. 🎮 Collection: delisted games, region-locked titles, Epic/PS giveaways, DLC and bundles, and Game of the Year picks. 💰 Price comparison: compares prices across US / JP / RU / TR regions and flags the cheapest country. 📊 Charts: playtime, most-played games, recent purchases, yearly library growth. ☁️ Cloud saves: check cloud-save status per game. 💗 Wishlist: tidy up your wishlist and spot family-shared titles. Everything stays in your own browser — nothing is uploaded. Full changelog in the project README. // @homepageURL https://github.com/SmallRob/steam-userscripts/blob/main/steam-game-library-viewer/README.md // @supportURL https://github.com/SmallRob/steam-userscripts/issues // @license MIT // @match https://store.steampowered.com/* // @match https://steamcommunity.com/id/*/home/ // @match https://steamcommunity.com/id/*/home // @match https://steamcommunity.com/profiles/*/home/ // @match https://steamcommunity.com/profiles/*/home // @connect api.steampowered.com // @connect store.steampowered.com // @connect steamcommunity.com // @connect cdn.akamai.steamstatic.com // @connect cdn.cloudflare.steamstatic.com // @connect shared.akamai.steamstatic.com // @connect shared.fastly.steamstatic.com // @connect fastly.jsdelivr.net // @connect gcore.jsdelivr.net // @connect jsdelivr.net // @connect cdn.jsdelivr.net // @connect leanisssharedstorage.blob.core.windows.net // @connect api.augmentedsteam.com // @connect open.er-api.com // @connect flagcdn.com // @connect api.isthereanydeal.com // @connect api.cheapshark.com // @connect steamcardexchange.net // @connect api.deepseek.com // @connect api.openai.com // @connect open.bigmodel.cn // @connect dashscope.aliyuncs.com // @connect api.moonshot.cn // @connect api.minimaxi.com // @connect ark.cn-beijing.volces.com // @connect playstation.com // @connect store.playstation.com // @connect bartervg.com // @connect raw.githubusercontent.com // @connect gamestatus.info // @connect steam-tracker.com // @connect api.xiaoheihe.cn // ============================================================================ // 依赖清单(速查版,完整说明见 docs/code-notes.md) // 本地真源 libs/ · 四方校验 node test-scripts/verify-remote-deps.js · 清单 test-scripts/remote-deps.config.json // A 基础层 core v2.0.6 / theme v2.1.4(theme 幂等,root.SGLVTheme 已存在则跳过)· scriptcat.org // B 浮窗层 ptw-framework v3.0.0 / ptw-tabs v3.1.2(framework 内嵌 token 副本)· scriptcat.org // C 宿主层 plugin-host v0.3.0 · jsdelivr 钉 commit(仅承担版本号暴露,与数据回流无关) // D 内联 shelf / cover-fallback v2.0.3 / game-collection v2.9.9(无远程发布版,见 INLINE 块) // E 数据 gameDb / delistedData / psplusData / humbleChoiceData · @resource @main 自动更新 // 纪律:一依赖一加载方式(@require 或内联,互斥);@require 钉具体版本;改库→发布→再改头部 // ============================================================================ // @require https://scriptcat.org/lib/7432/2.0.8/SGLV%20Core%20Library.js // @require https://scriptcat.org/lib/7493/2.1.4/%20SGLV%20Shared%20CSS%20(Library).js // @require https://scriptcat.org/lib/8427/3.0.0/SGLV%20PTW%20Framework.js // @require https://scriptcat.org/lib/8430/3.1.2/SGLV%20PTW%20Tab%20All.js // @require https://cdn.jsdelivr.net/gh/SmallRob/steam-namespace@50174b3/libs/sglv-plugin-host.lib.js // @resource gameDb https://fastly.jsdelivr.net/gh/SmallRob/steam-namespace@main/data/game-db-v1.2.json // @resource delistedData https://fastly.jsdelivr.net/gh/SmallRob/steam-namespace@main/data/steam_delisted_apps.json // @resource psplusData https://fastly.jsdelivr.net/gh/oXnMe/psplus-steam-overlay@main/data/psplus-games.json // @resource humbleChoiceData https://fastly.jsdelivr.net/gh/SmallFork/json@main/Humble_Choice.json // @grant GM_xmlhttpRequest // @grant GM_getValue // @grant GM_setValue // @grant GM_addStyle // @grant GM_getResourceText // @grant GM_listValues // @grant GM_notification // @grant unsafeWindow // @grant GM_info // @run-at document-idle // @tag Steam // @tag games // @icon data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Cdefs%3E%3ClinearGradient id='g' x1='0' y1='0' x2='1' y2='1'%3E%3Cstop offset='0' stop-color='%238b5cf6'/%3E%3Cstop offset='0.5' stop-color='%233b82f6'/%3E%3Cstop offset='1' stop-color='%2306b6d4'/%3E%3C/linearGradient%3E%3C/defs%3E%3Crect width='64' height='64' rx='14' fill='url(%23g)'/%3E%3Cg fill='%23fff'%3E%3Crect x='13' y='13' width='17' height='17' rx='3.5' opacity='.96'/%3E%3Crect x='34' y='13' width='17' height='17' rx='3.5' opacity='.78'/%3E%3Crect x='13' y='34' width='17' height='17' rx='3.5' opacity='.78'/%3E%3Crect x='34' y='34' width='17' height='17' rx='3.5' opacity='.96'/%3E%3C/g%3E%3Cpath d='M38 39 L47 44.5 L38 50 Z' fill='url(%23g)'/%3E%3C/svg%3E // ==/UserScript== // ==== SGLV-SHELF-INLINE-BEGIN (build-shelf-inline.js 自动生成,勿手改) ==== /** * 内联内容由 test-scripts/build-shelf-inline.js 生成 —— 请勿手改。 * 来源:libs/{sglv-libs-shelf.lib.js} * 改动请编辑库文件后重跑本脚本;verify-shelf-inline-sync.js 会拦截漏跑。 */ // ---------- sglv-libs-shelf.lib.js (1971 行) ---------- /* ===================================================================== * * SGLV 暂存箱库 (sglv-shelf) * * 定位:Steam 商店全域可达的「暂存箱」——把暂时不想买/想买但现在不买的 * 商品、愿望单项、外部链接与备忘统一暂存,随时查看与恢复。 * * 与 Steam-Cart-Enhanced.js(购物车增强)的关系 * --------------------------------------------------------------------- * 共享 localStorage['sce_cart_shelf_v1'],即「购物类」记录(kind = * app/bundle/package)双向互通:SCE 暂存的项在 SGLV 浮窗可见,SGLV 从 * 购物车暂存的项在 SCE 暂存架可见。用户未安装 SCE 时该 key 由本库独享, * 行为完全一致,无需任何配置。 * * 为什么 wishlist/note 不写进同一个 items 数组 * --------------------------------------------------------------------- * SCE 的 loadShelf() 过滤条件为 * it.id && (it.appid || it.bundleid || it.packageid || appids.length) * 且 saveShelf() 用过滤后的 shelf.items **整体重写** items 数组。 * 若把备忘录/外部链接塞进同一数组,用户一旦在购物车页使用 SCE 暂存, * 这些记录会被 SCE 静默丢弃(无 appid/bundleid/packageid)。 * 故采用双桶: * INTEROP_KEY = 'sce_cart_shelf_v1' 购物类,与 SCE 互通(有损风险 0) * EXTRA_KEY = 'sglv_shelf_extra_v1' 愿望单/备忘,本库独享 * 读取时合并为统一视图,写入时按 kind 路由,用户感知不到分桶。 * * 扩展字段安全性 * --------------------------------------------------------------------- * 顶层未知字段(如自定义 meta)会被 SCE 的 saveShelf 丢弃,故所有扩展 * 一律挂在「记录级」字段上——SCE 只改写它认识的字段,记录级扩展可无损 * 往返。写入互通桶时保留 days/tab 等 SCE 需要的顶层键(Object.assign 合并)。 * * 能力边界(诚实声明) * ------------------------------------------------------------------- * · 恢复(加购)走 AddItemsToCart/v1,全站可用,但**依赖当前登录账号**: * 记录写入时记 steamid,恢复前校验,不匹配直接拒绝(参考脚本无此保护, * 跨账号会静默加到错误账号的购物车)。 * · 暂存(移出购物车)**没有官方 API**,只能点 Steam 自己的「移除」按钮, * 因此仅在 /cart 页可用(与 SCE 同一约束)。其他页面按钮置灰并给跳转。 * · 愿望单不提供移除 API,故 wishlist 记录只做「打开/定位 + 记录管理」。 * · 折扣到期时间 endTs 仅当记录带有该字段时显示倒计时(由 SCE 写入); * 本库从购物车暂存时不主动拉折扣数据。 * * 桥接契约(宿主注入,见 init(ShelfHost)) * --------------------------------------------------------------------- * apiVersion: 1 * isZh: boolean * getSteamId(): string 当前账号 steamid64(可为空) * toast: { success, error, warning, info } * resolveName(appid): Promise 名称补全(可选,缺失时降级) * openUrl(url), isCartPage(): boolean (可选,缺失时降级) * * 暴露:window.SGLVShelf * ===================================================================== */ window.SGLVShelf = (function () { 'use strict'; const apiVersion = 1; // ==================== 常量 ==================== const CFG = { INTEROP_KEY: 'sce_cart_shelf_v1', // 与 Steam-Cart-Enhanced.js 共用 EXTRA_KEY: 'sglv_shelf_extra_v1', // 本库独享(wishlist / note) INTEROP_KINDS: ['app', 'bundle', 'package'], RESTORABLE: ['app', 'bundle', 'package'], CART_API: 'https://api.steampowered.com/IAccountCartService/GetCart/v1/', CART_ADD_API: 'https://api.steampowered.com/IAccountCartService/AddItemsToCart/v1/', ITEMS_API: 'https://api.steampowered.com/IStoreBrowseService/GetItems/v1/', SHELVE_STEP_MS: 700, RESTORE_STEP_MS: 250, CANDIDATE_STEP_MS: 200, MAX_ITEMS: 300, STALE_DAYS: 180, TICK_MS: 1000, }; const KIND_META = { app: { label: '单品', tag: 'cart' }, bundle: { label: '捆绑包', tag: 'cart' }, package: { label: '购买包', tag: 'cart' }, wishlist: { label: '愿望单', tag: 'wishlist' }, note: { label: '备忘', tag: 'note' }, }; const FILTER_META = [ { key: 'all', label: '全部' }, { key: 'cart', label: '购物' }, { key: 'wishlist', label: '愿望单' }, { key: 'note', label: '备忘' }, ]; // ==================== 宿主 ==================== let Host = null; let _hostReady = false; const _changeCbs = []; function zh(s, en) { return Host && Host.isZh === false ? en : s; } function toast(msg, type) { try { if (Host && Host.toast && typeof Host.toast[type] === 'function') Host.toast[type](msg); else if (typeof console !== 'undefined') console.log('[SGLVShelf]', type || 'info', msg); } catch (e) { /* ignore */ } } function debug() { if (typeof console === 'undefined') return; console.log.apply(console, ['[SGLVShelf]'].concat([].slice.call(arguments))); } // ==================== 基础工具 ==================== const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); const now = () => Date.now(); const num = (v) => { const n = Number(v); return isNaN(n) ? 0 : n; }; function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ( { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c] )); } function uid(prefix) { return (prefix || 'sh') + '_' + now().toString(36) + '_' + Math.random().toString(36).slice(2, 7); } function clamp(n, lo, hi) { return Math.max(lo, Math.min(hi, n)); } function absTime(ts) { if (!ts) return ''; try { const d = new Date(ts); const p = (x) => String(x).padStart(2, '0'); return d.getFullYear() + '-' + p(d.getMonth() + 1) + '-' + p(d.getDate()) + ' ' + p(d.getHours()) + ':' + p(d.getMinutes()); } catch (e) { return ''; } } /** 剩余时间文案;ts<=0 返回空串 */ function remainText(ts) { const t = num(ts); if (t <= 0) return ''; let s = Math.floor((t - now()) / 1000); if (s <= 0) return '已到期'; const d = Math.floor(s / 86400); s -= d * 86400; const h = Math.floor(s / 3600); s -= h * 3600; const m = Math.floor(s / 60); if (d > 0) return '剩 ' + d + ' 天 ' + h + ' 小时'; if (h > 0) return '剩 ' + h + ' 小时 ' + m + ' 分'; return '剩 ' + Math.max(1, m) + ' 分'; } /** 紧迫度:0 已过期/无,1 紧张(<24h),2 临近(<72h),3 宽松 */ function severity(ts) { const t = num(ts); if (t <= 0) return 0; const h = (t - now()) / 3600000; if (h <= 0) return 1; if (h < 24) return 1; if (h < 72) return 2; return 3; } function isVisible(el) { if (!el) return false; try { const cs = getComputedStyle(el); if (cs.display === 'none' || cs.visibility === 'hidden') return false; } catch (e) { /* ignore */ } try { if (el.getClientRects && document.body && document.body.getClientRects) { if (document.body.getClientRects().length && !el.getClientRects().length) return false; } } catch (e) { /* ignore */ } return true; } // ==================== 存储层 ==================== function lsGet(key) { try { return window.localStorage.getItem(key); } catch (e) { return null; } } function lsSet(key, val) { try { window.localStorage.setItem(key, val); return true; } catch (e) { return false; } } function readRaw(key) { const s = lsGet(key); if (!s) return null; try { const v = JSON.parse(s); return (v && typeof v === 'object') ? v : null; } catch (e) { return null; } } function isInteropKind(kind) { return CFG.INTEROP_KINDS.indexOf(kind) !== -1; } function bucketOf(kind) { return isInteropKind(kind) ? 'interop' : 'extra'; } /** * kind 推断的唯一权威入口(导入 / 归一化共用)。 * 顺序:显式合法 kind → 购买项 id → 未知 kind 按有无 appid 归一 → 有 url 判备忘 → 默认。 * 「先看 kind 再看 id」:kind='weird' + appid 应归一为 app,而 kind 缺失但带 bundleid * 才按 bundle 处理(与 SCE 的 legacy 推断兼容)。 */ function resolveKind(rec) { const r = rec || {}; const k = r.kind; if (k && KIND_META[k]) return k; if (r.bundleid) return 'bundle'; if (r.packageid) return 'package'; const hasApp = !!r.appid || (Array.isArray(r.appids) && r.appids.length); if (k) return hasApp ? 'app' : 'note'; if (r.url) return 'note'; return hasApp ? 'app' : 'note'; } function currentSteamId() { try { return (Host && typeof Host.getSteamId === 'function' && String(Host.getSteamId() || '')) || ''; } catch (e) { return ''; } } /** * 记录规范化。 * - 互通桶强制 kind ∈ app/bundle/package(与 SCE 的理解对齐) * - 缺失 kind 时按 bundleid/packageid 推断并打 legacy(与 SCE 2216-2230 同规则) * - 补齐 appids/names/displayName/count 等展示字段 * 不丢弃任何未知字段(往返无损) */ function normalizeRecord(rec, bucket) { const r = Object.assign({}, rec || {}); r.id = r.id || uid('sh'); if (!Array.isArray(r.appids)) r.appids = r.appids != null ? [r.appids] : []; r.appids = r.appids.map(num).filter((n) => n > 0); if (!r.names || typeof r.names !== 'object') r.names = {}; let kind = r.kind; if (!kind) { r.legacy = true; if (r.bundleid) kind = 'bundle'; else if (r.packageid) kind = 'package'; else kind = 'app'; if (r.appid == null && kind === 'app' && r.appids.length === 1) r.appid = r.appids[0]; } if (!KIND_META[kind]) kind = resolveKind(r); // 互通桶只允许购物类(SCE 不认其它 kind) if (bucket === 'interop' && !isInteropKind(kind)) kind = 'app'; r.kind = kind; // 三 id 字段互斥化(与 SCE 结构一致:冗余三字段,方便按类型直读) if (kind === 'bundle') { r.packageid = null; r.appid = null; } else if (kind === 'package') { r.bundleid = null; r.appid = null; } else { r.bundleid = null; r.packageid = null; } if (kind === 'bundle') r.bundleid = num(r.bundleid) || null; if (kind === 'package') r.packageid = num(r.packageid) || null; if ((kind === 'app' || kind === 'wishlist') && !r.appid && r.appids.length === 1) r.appid = r.appids[0]; if (kind === 'app' || kind === 'wishlist') r.appid = num(r.appid) || null; if (kind === 'note') { r.appid = null; r.bundleid = null; r.packageid = null; r.appids = []; } r.endTs = num(r.endTs); r.pct = num(r.pct); r.count = num(r.count) || r.appids.length || (kind === 'note' ? 1 : 0); r.removedAt = num(r.removedAt); r.addedAt = num(r.addedAt) || r.removedAt || 0; r.tags = Array.isArray(r.tags) ? r.tags.filter((x) => x != null && x !== '').slice(0, 12) : []; if (r.url == null) r.url = ''; if (r.note == null) r.note = ''; if (r.origin != 'sce') r.origin = 'sglv'; if (!r.source) r.source = bucket === 'interop' ? 'cart' : 'manual'; if (r.lastError === undefined) r.lastError = null; if (r.displayName == null) r.displayName = ''; // SCE 记录常只有 targetName 而 displayName 为空 —— 回填一份, // 使记录自描述(两个脚本都能直接读 displayName) if (!r.displayName && r.targetName) r.displayName = r.targetName; return r; } /** SCE 认可的记录形状(有 id 且至少一个可定位 id) */ function sceAcceptable(rec) { return !!(rec && rec.id && (rec.appid || rec.bundleid || rec.packageid || (Array.isArray(rec.appids) && rec.appids.length))); } function readBucket(bucket) { const key = bucket === 'interop' ? CFG.INTEROP_KEY : CFG.EXTRA_KEY; const raw = readRaw(key); const items = []; if (raw && Array.isArray(raw.items)) { raw.items.forEach((it) => { if (!it || typeof it !== 'object') return; if (bucket === 'interop' && !sceAcceptable(it)) return; items.push(normalizeRecord(it, bucket)); }); } return { raw: raw || {}, items: items }; } /** * 写桶。互通桶用 Object.assign 合并而非整体覆盖, * 保留 SCE 需要的顶层键(days/tab)与任何未来新增键。 */ function writeBucket(bucket, items) { const key = bucket === 'interop' ? CFG.INTEROP_KEY : CFG.EXTRA_KEY; const cur = readRaw(key) || {}; const payload = Object.assign({}, cur); payload.items = items; if (bucket === 'extra' && !payload.version) payload.version = 1; const ok = lsSet(key, JSON.stringify(payload)); if (!ok) toast(zh('暂存箱保存失败:浏览器存储不可用或已满', 'Shelf save failed: storage unavailable or full'), 'error'); return ok; } /** 统一视图:互通桶 + 独享桶 */ function allItems() { return readBucket('interop').items.concat(readBucket('extra').items); } function getItem(id) { const list = allItems(); for (let i = 0; i < list.length; i++) if (list[i].id === id) return list[i]; return null; } function countAll() { return allItems().length; } /** * 容量上限:**跨两桶的全局上限**。 * 淘汰顺序:先独享桶(备忘/愿望单,最不贵)→ 再互通桶(购物类,最贵)。 * 同桶内按 addedAt 升序(最旧先走)。 * 返回被淘汰条数。 */ function enforceCap() { const ex = readBucket('extra').items; const it = readBucket('interop').items; let over = ex.length + it.length - CFG.MAX_ITEMS; if (over <= 0) return 0; let dropped = 0; const drain = (arr) => { const order = arr.slice().sort((a, b) => (num(a.addedAt) || num(a.removedAt)) - (num(b.addedAt) || num(b.removedAt))); for (const r of order) { if (over <= 0) break; const i = arr.indexOf(r); if (i >= 0) { arr.splice(i, 1); over--; dropped++; } } }; drain(ex); if (over > 0) drain(it); if (dropped) { writeBucket('extra', ex); writeBucket('interop', it); } return dropped; } /** * 写入/更新一条记录(按 kind 路由桶)。 * opts.silent 内部批处理时静默(不逐条 toast、不逐条广播) */ function putItem(rec, opts) { const o = opts || {}; const inp = Object.assign({}, rec || {}); // 别名归一:允许调用方直接传 title/name(其他 SGLV 模块的常见用法) if (!inp.displayName && !inp.targetName) { const t = inp.title || inp.name; if (t) { inp.displayName = t; inp.targetName = t; } } // 时间戳补齐:无任何时间戳的记录(外部模块直接 putItem)盖章 now, // 否则 addedAt=0 会让「按加入时间排序」与陈旧清理全部失效 if (!num(inp.addedAt) && !num(inp.removedAt)) { inp.addedAt = now(); inp.removedAt = inp.addedAt; } const r = normalizeRecord(inp, bucketOf(inp.kind)); if (!sceAcceptable(r) && isInteropKind(r.kind)) { toast(zh('这条记录缺少可定位的商品 ID,未保存', 'Record lacks a resolvable id, skipped'), 'warning'); return null; } const bucket = bucketOf(r.kind); const cur = readBucket(bucket).items; const idx = cur.findIndex((x) => x.id === r.id); if (idx >= 0) cur[idx] = r; else cur.unshift(r); writeBucket(bucket, cur); const dropped = enforceCap(); if (dropped && !o.silent) { toast(zh('暂存箱已满(上限 ' + CFG.MAX_ITEMS + ' 条),已淘汰最旧的 ' + dropped + ' 条', 'Shelf full (' + CFG.MAX_ITEMS + '), pruned ' + dropped + ' oldest'), 'warning'); } if (!o.silent) emitChange(); return r; } function deleteItem(id, opts) { const o = opts || {}; const rec = getItem(id); if (!rec) return false; const bucket = bucketOf(rec.kind); const cur = readBucket(bucket).items.filter((x) => x.id !== id); writeBucket(bucket, cur); if (!o.silent) emitChange(); return true; } /** 清理长期未处理的记录(用户手动触发,绝不自动删) */ function pruneStale(days) { const limit = now() - (num(days) || CFG.STALE_DAYS) * 86400000; let n = 0; ['interop', 'extra'].forEach((b) => { const cur = readBucket(b).items; const keep = cur.filter((it) => (num(it.addedAt) || num(it.removedAt)) > limit); if (keep.length !== cur.length) { n += cur.length - keep.length; writeBucket(b, keep); } }); if (n) emitChange(); return n; } // ---- 偏好(存独享桶,SGLV 私有) ---- function getPrefs() { const raw = readRaw(CFG.EXTRA_KEY) || {}; const p = raw.prefs && typeof raw.prefs === 'object' ? raw.prefs : {}; return { filter: p.filter || 'all', sort: p.sort || 'end', compatOnly: !!p.compatOnly, }; } function setPrefs(patch) { const raw = readRaw(CFG.EXTRA_KEY) || {}; const next = Object.assign({}, raw.prefs || {}, patch || {}); const payload = Object.assign({}, raw); payload.prefs = next; if (!payload.version) payload.version = 1; lsSet(CFG.EXTRA_KEY, JSON.stringify(payload)); } // ---- 展示派生 ---- function displayName(rec) { if (!rec) return ''; if (rec.displayName) return rec.displayName; if (rec.targetName) return rec.targetName; if (rec.kind === 'note') return rec.url || zh('(未命名备忘)', '(untitled note)'); const n = rec.names && Object.keys(rec.names)[0]; if (n) return rec.names[n]; if (rec.appid) return 'App ' + rec.appid; if (rec.bundleid) return 'Bundle ' + rec.bundleid; if (rec.packageid) return 'Package ' + rec.packageid; return zh('(未命名)', '(untitled)'); } function linkOf(rec) { if (!rec) return ''; if (rec.kind === 'bundle' && rec.bundleid) return 'https://store.steampowered.com/bundle/' + rec.bundleid; if (rec.kind === 'package' && rec.packageid) return 'https://store.steampowered.com/sub/' + rec.packageid; if (rec.appid) return 'https://store.steampowered.com/app/' + rec.appid; if (rec.url) return rec.url; return ''; } /** 该记录是否属于其他账号(写入时账号 ≠ 当前账号) */ function foreignAccount(rec) { const mine = currentSteamId(); if (!mine || !rec || !rec.steamid) return false; return String(rec.steamid) !== mine; } function canRestore(rec) { return !!rec && CFG.RESTORABLE.indexOf(rec.kind) !== -1; } // ==================== 变更广播 ==================== function emitChange() { const n = countAll(); try { setBadge(n); } catch (e) { /* ignore */ } // 浮窗开着就同步重绘:删除/清空/导入/恢复都走 emitChange, // 否则弹窗确认后列表会停留在旧快照(UI 与数据不一致) if (isOpenFlag) { try { renderList(); } catch (e) { console.warn('[SGLVShelf] 重绘失败', e); } } _changeCbs.forEach((cb) => { try { cb(n); } catch (e) { console.warn('[SGLVShelf] onChange 回调异常', e); } }); } function onChange(cb) { if (typeof cb === 'function') _changeCbs.push(cb); } // ==================== Steam 接口层 ==================== function appConfigEl() { return document.querySelector('#application_config'); } function readJsonAttr(el, name) { if (!el) return null; try { return JSON.parse(el.getAttribute(name) || 'null'); } catch (e) { return null; } } function getAccessToken() { const uc = readJsonAttr(appConfigEl(), 'data-store_user_config'); return (uc && uc.webapi_token) || null; } function isLoggedIn() { const ui = readJsonAttr(appConfigEl(), 'data-userinfo'); return !!(ui && ui.logged_in); } function getContext() { const cfg = readJsonAttr(appConfigEl(), 'data-config') || {}; const lang = cfg.LANGUAGE || (window.g_Languages && window.g_Languages[0]) || 'schinese'; let cc = cfg.COUNTRY; if (!cc) { try { cc = new URLSearchParams(location.search).get('cc'); } catch (e) { /* ignore */ } } return { language: String(lang).toLowerCase(), country_code: String(cc || 'CN').toUpperCase(), steam_realm: 1 }; } function gmJson(url) { return new Promise((resolve, reject) => { if (typeof GM_xmlhttpRequest !== 'function') { fetch(url, { credentials: 'include' }).then((r) => r.json()).then(resolve).catch(reject); return; } GM_xmlhttpRequest({ method: 'GET', url: url, timeout: 15000, onload: (res) => { try { resolve(JSON.parse(res.responseText)); } catch (e) { reject(new Error('JSON 解析失败')); } }, onerror: () => reject(new Error('网络错误')), ontimeout: () => reject(new Error('请求超时')), }); }); } function gmFormPost(url, body) { return new Promise((resolve, reject) => { const headers = { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }; if (typeof GM_xmlhttpRequest !== 'function') { fetch(url, { method: 'POST', credentials: 'include', headers: headers, body: body }) .then((r) => r.json()).then(resolve).catch(reject); return; } GM_xmlhttpRequest({ method: 'POST', url: url, headers: headers, data: body, timeout: 20000, onload: (res) => { try { resolve(JSON.parse(res.responseText)); } catch (e) { reject(new Error('JSON 解析失败')); } }, onerror: () => reject(new Error('网络错误')), ontimeout: () => reject(new Error('请求超时')), }); }); } async function fetchLineItems(token) { const data = await gmJson(CFG.CART_API + '?access_token=' + encodeURIComponent(token)); const cart = data && data.response && data.response.cart; return ((cart && cart.line_items) || []).map((it) => ({ lineItemId: it.line_item_id != null ? it.line_item_id : null, type: it.type != null ? it.type : null, packageid: it.packageid ? Number(it.packageid) : null, bundleid: it.bundleid ? Number(it.bundleid) : null, })); } async function fetchStoreItems(ids) { if (!ids || !ids.length) return []; const payload = { ids: ids, context: getContext(), data_request: { include_basic_info: true, include_all_purchase_options: true }, }; const data = await gmJson(CFG.ITEMS_API + '?input_json=' + encodeURIComponent(JSON.stringify(payload))); return (data && data.response && data.response.store_items) || []; } function kindQuery(t) { return t.kind === 'bundle' ? { bundleid: t.id } : { packageid: t.id }; } function cartNavData(cc) { return { domain: 'store.steampowered.com', controller: 'default', method: 'default', submethod: '', feature: 'store_home', depth: 1, countrycode: cc, webkey: 0, is_client: false, curator_data: { clanid: null, listid: null }, is_likely_bot: false, is_utm: false, }; } function describeCartError(data) { const r = data && data.response; if (!r) return zh('接口没有返回内容,可能是网络或登录态问题', 'No response from API'); const e = r.error; if (e) { const bits = []; if (e.message) bits.push(String(e.message)); if (e.error_description && e.error_description !== e.message) bits.push(String(e.error_description)); if (e.eresult != null) bits.push('eresult ' + e.eresult); if (!bits.length) bits.push(JSON.stringify(e).slice(0, 200)); return bits.join(' / '); } return zh('Steam 没有把它加入购物车', 'Steam refused to add it'); } async function addOneToCart(token, cc, cand) { const item = { gift_info: null, flags: { is_gift: false, is_private: false } }; if (cand.kind === 'bundle') item.bundleid = cand.id; else item.packageid = cand.id; const payload = { user_country: cc, items: [item], navdata: cartNavData(cc) }; const data = await gmFormPost( CFG.CART_ADD_API + '?access_token=' + encodeURIComponent(token), 'input_json=' + encodeURIComponent(JSON.stringify(payload)) ); if (data && data.response && data.response.cart) return { ok: true, data: data }; return { ok: false, data: data, err: describeCartError(data) }; } function verifyRestored(data, cand) { const resp = (data && data.response) || {}; const lis = (resp.cart && resp.cart.line_items) || []; const ids = (resp.line_item_ids || []).map(String); const mine = ids.length ? lis.filter((li) => ids.indexOf(String(li.line_item_id)) !== -1) : []; const field = cand.kind === 'bundle' ? 'bundleid' : 'packageid'; if (mine.length > 1) return zh('Steam 一次加回了 ' + mine.length + ' 条(预期 1 条)', 'Steam added ' + mine.length + ' lines'); const pool = mine.length ? mine : lis; if (pool.some((li) => String(li[field] || '') === String(cand.id))) return ''; return zh('加回的购买项对不上(Steam 返回了别的项)', 'Restored item mismatch'); } async function bestOptionOfApp(appid) { try { const items = await fetchStoreItems([{ appid: Number(appid) }]); const si = items[0]; const opt = (si && si.best_purchase_option) || null; if (!opt) return null; if (opt.bundleid) return { kind: 'bundle', id: Number(opt.bundleid), name: si.name || '' }; if (opt.packageid) return { kind: 'package', id: Number(opt.packageid), name: si.name || '' }; } catch (e) { debug('bestOptionOfApp 失败', appid, e); } return null; } /** 旧记录(无购买项 id)按内容重新识别购买项 */ async function resolveTargetByContent(appids) { const idsWant = (appids || []).map(Number).filter((n) => n > 0); if (!idsWant.length) return null; try { const items = await fetchStoreItems(idsWant.map((a) => ({ appid: a }))); const cand = []; const seen = new Set(); const push = (kind, id) => { if (!kind || !id) return; const k = kind + ':' + id; if (seen.has(k)) return; seen.add(k); cand.push({ kind: kind, id: Number(id) }); }; items.forEach((si) => { (si.purchase_options || []).forEach((o) => { if (o.bundleid) push('bundle', o.bundleid); else if (o.packageid) push('package', o.packageid); }); const b = si.best_purchase_option; if (b) { if (b.bundleid) push('bundle', b.bundleid); else if (b.packageid) push('package', b.packageid); } }); if (!cand.length) return null; const detail = await fetchStoreItems(cand.map(kindQuery)); const byId = new Map(); detail.forEach((si) => { if (si && si.id != null) byId.set(String(si.id), si); }); let best = null; cand.forEach((c) => { const si = byId.get(String(c.id)); if (!si || !Array.isArray(si.included_appids)) return; const inc = si.included_appids.map(String); if (!idsWant.every((a) => inc.indexOf(String(a)) !== -1)) return; if (!best || inc.length < best.incLength) best = { kind: c.kind, id: c.id, name: si.name || '', incLength: inc.length, how: zh('按商品内容重新识别', 'resolved by content') }; }); return best; } catch (e) { debug('按内容解析购买项失败', e); return null; } } async function resolveRestorePlan(rec) { if (rec.legacy && rec.appids && rec.appids.length) { const byContent = await resolveTargetByContent(rec.appids); if (byContent) return [byContent]; } if (rec.kind === 'bundle' && rec.bundleid) return [{ kind: 'bundle', id: Number(rec.bundleid) }]; if (rec.kind === 'package' && rec.packageid) return [{ kind: 'package', id: Number(rec.packageid) }]; const appid = num(rec.appid || ((rec.appids && rec.appids.length === 1) ? rec.appids[0] : 0)); if (appid > 0 && rec.kind === 'app') { const one = await bestOptionOfApp(appid); if (one) return [one]; } return []; } function candidateLabel(c) { return c.kind === 'bundle' ? 'bundle ' + c.id : 'package ' + c.id; } // ==================== 恢复(加购) ==================== let busy = false; let busyText = ''; function isBusy() { return busy; } async function executeRestore(ids) { if (busy) { toast(zh('暂存箱正忙,稍后再试', 'Shelf is busy, try later'), 'warning'); return; } const targets = allItems().filter((it) => ids.indexOf(it.id) !== -1 && canRestore(it)); if (!targets.length) { toast(zh('选中的记录里没有可恢复到购物车的项', 'Nothing restorable selected'), 'warning'); return; } // 账号归属优先于登录态:「来自其他账号」比「未登录」更具体, // 若先判登录态会把它掩盖成一句误导性的登录提示 const blocked = targets.filter(foreignAccount); if (blocked.length === targets.length) { toast(zh('这些记录来自其他 Steam 账号,已阻止恢复', 'Records belong to another account — restore blocked'), 'error'); return; } if (!isLoggedIn() && !getAccessToken()) { toast(zh('未登录 Steam,请先登录后再恢复', 'Not logged in — log in first'), 'warning'); return; } const token = getAccessToken(); const cc = getContext().country_code; const added = []; const failed = []; const warns = []; busy = true; setBusy(zh('准备恢复 ' + targets.length + ' 项…', 'Preparing ' + targets.length + ' items…')); try { for (let i = 0; i < targets.length; i++) { const rec = targets[i]; if (foreignAccount(rec)) { failed.push({ name: displayName(rec), why: zh('来自其他 Steam 账号', 'from another account') }); continue; } setBusy(zh('正在恢复 ' + (i + 1) + '/' + targets.length + ':', 'Restoring ') + displayName(rec)); const plan = await resolveRestorePlan(rec); if (!plan.length) { rec.lastError = zh('记录里没有可用的购买项', 'no purchasable option'); putItem(rec, { silent: true }); failed.push({ name: displayName(rec), why: rec.lastError }); continue; } const errs = []; let ok = false; for (const cand of plan) { try { const r = await addOneToCart(token, cc, cand); if (r.ok) { const bad = verifyRestored(r.data, cand); rec.kind = cand.kind; rec.bundleid = cand.kind === 'bundle' ? cand.id : null; rec.packageid = cand.kind === 'package' ? cand.id : null; rec.appid = null; if (cand.name) rec.targetName = cand.name; rec.displayName = rec.targetName || displayName(rec); rec.legacy = false; rec.lastError = null; rec.restoredAt = now(); putItem(rec, { silent: true }); if (bad) warns.push({ name: displayName(rec), why: bad }); added.push(rec.id); ok = true; break; } errs.push(candidateLabel(cand) + ' → ' + r.err); } catch (e) { errs.push(candidateLabel(cand) + ' → ' + ((e && e.message) || zh('请求失败', 'request failed'))); } await sleep(CFG.CANDIDATE_STEP_MS); } if (!ok) { rec.lastError = errs.join(zh(';', '; ')) || zh('未知原因', 'unknown'); putItem(rec, { silent: true }); failed.push({ name: displayName(rec), why: rec.lastError }); } await sleep(CFG.RESTORE_STEP_MS); } } finally { busy = false; setBusy(''); emitChange(); } const parts = []; if (added.length) parts.push(zh('已恢复 ', 'Restored ') + added.length + ' ' + zh('项到购物车', 'items to cart')); if (failed.length) parts.push(zh('失败 ', 'Failed ') + failed.length + ' ' + zh('项', 'items')); if (warns.length) parts.push(zh('有 ', '') + warns.length + ' ' + zh('项 Steam 返回与预期不符', 'items returned unexpected cart content')); toast(parts.join(' · ') || zh('没有可恢复的项目', 'Nothing restored'), failed.length ? 'warning' : 'success'); if (failed.length || warns.length) { const rows = failed.concat(warns).map((f) => '
' + esc(f.name) + '' + esc(f.why) + '
').join(''); showModal({ title: zh('恢复结果', 'Restore result'), body: '
' + (parts.join(' · ') || '') + '
' + rows, buttons: [{ label: zh('知道了', 'OK'), primary: true }, { label: zh('刷新购物车', 'Refresh cart'), act: () => { location.href = 'https://store.steampowered.com/cart/'; } }], }); } return { added: added.length, failed: failed.length, warns: warns.length }; } // ==================== 购物车页:行内暂存 ==================== const CART_REMOVE_RE = /(remove|移除|删除|entfernen|supprimer|eliminar|rimuovi)/i; function cartRoot() { return document.querySelector('[data-featuretarget="react-root"]') || document.querySelector('.responsive_page_template_content') || document.body; } function collectAnchors(root) { const out = { apps: [], bundles: [], subs: [], all: [] }; const seen = new Set(); (root.querySelectorAll('a[href*="/app/"], a[href*="/bundle/"], a[href*="/sub/"]') || []).forEach((a) => { const href = a.getAttribute('href') || ''; const ma = href.match(/\/app\/(\d+)/); const mb = href.match(/\/bundle\/(\d+)/); const ms = href.match(/\/sub\/(\d+)/); if (ma && out.apps.indexOf(Number(ma[1])) === -1) out.apps.push(Number(ma[1])); if (mb && out.bundles.indexOf(Number(mb[1])) === -1) out.bundles.push(Number(mb[1])); if (ms && out.subs.indexOf(Number(ms[1])) === -1) out.subs.push(Number(ms[1])); const key = href; if (!seen.has(key)) { seen.add(key); out.all.push({ href: href, el: a }); } }); return out; } function nearestRowWith(el, root) { let n = el; for (let d = 0; n && d < 14; d++) { const anchors = collectAnchors(n); if (anchors.apps.length || anchors.bundles.length || anchors.subs.length) { if (n !== root && n.querySelector && n.querySelector('button, a')) return n; } n = n.parentElement; } return null; } function removeActionEl(rowEl) { let found = null; (rowEl.querySelectorAll('button, a') || []).forEach((el) => { if (found) return; const t = ((el.textContent || '') + ' ' + (el.getAttribute('aria-label') || '') + ' ' + (el.title || '')).trim(); if (t && CART_REMOVE_RE.test(t)) found = el; }); return found; } function rowKey(row) { return [row.appids.join('.'), row.bundleIds.join('.'), row.subIds.join('.')].join('|'); } function scanCartRows() { const root = cartRoot(); if (!root) return []; const rows = []; const seen = new Set(); collectAnchors(root).all.forEach((a) => { const rowEl = nearestRowWith(a.el, root); if (!rowEl) return; const key = rowEl.__sgshRowKey || (rowEl.__sgshRowKey = uid('row')); if (seen.has(key)) return; const an = collectAnchors(rowEl); if (!an.apps.length && !an.bundles.length && !an.subs.length) return; seen.add(key); rows.push({ rowEl: rowEl, key: key, appids: an.apps, bundleIds: an.bundles, subIds: an.subs, removeBtn: removeActionEl(rowEl), }); }); return rows; } /** 行内注入「暂存」按钮;检测到 SCE 已注入 .sce-shelve-btn 时跳过,避免双按钮 */ function injectCartButtons() { if (!onCartPage()) return 0; let n = 0; scanCartRows().forEach((row) => { if (row.rowEl.querySelector('.sgsh-shelve-btn') || row.rowEl.querySelector('.sce-shelve-btn')) return; const btn = document.createElement('button'); btn.className = 'sgsh-shelve-btn'; btn.type = 'button'; btn.textContent = zh('暂存', 'Stash'); btn.title = zh('加入暂存箱(会从购物车移除)', 'Move to shelf (removes from cart)'); btn.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); shelveOneRow(row); }); const act = removeActionEl(row.rowEl); if (act && act.parentElement) act.parentElement.insertBefore(btn, act); else row.rowEl.appendChild(btn); n++; }); return n; } function onCartPage() { try { return /^\/cart\/?(\?|$)/i.test(location.pathname); } catch (e) { return false; } } async function buildCartIndex() { const token = getAccessToken(); if (!token) return { entries: [], ok: false, error: zh('未登录 Steam,读不到登录令牌', 'Not logged in: no access token') }; let lineItems; try { lineItems = await fetchLineItems(token); } catch (e) { return { entries: [], ok: false, error: zh('读取购物车接口失败:', 'GetCart failed: ') + ((e && e.message) || e) }; } const targets = lineItems.map((li) => ( li.bundleid ? { kind: 'bundle', id: Number(li.bundleid) } : li.packageid ? { kind: 'package', id: Number(li.packageid) } : null )).filter(Boolean); let storeItems = []; if (targets.length) { try { storeItems = await fetchStoreItems(targets.map(kindQuery)); } catch (e) { debug('读取购买项内容失败', e); } } const byKey = new Map(); storeItems.forEach((si) => { if (!si || si.id == null) return; const t = targets.find((x) => String(x.id) === String(si.id)); const kind = (t && t.kind) || (si.item_type === 2 ? 'bundle' : 'package'); byKey.set(kind + ':' + si.id, si); }); return { ok: true, error: '', entries: lineItems.map((li, i) => { const t = targets[i]; if (!t) return null; const si = byKey.get(t.kind + ':' + t.id) || null; return { lineItemId: li.lineItemId, kind: t.kind, id: t.id, name: (si && si.name) || '', included: (si && Array.isArray(si.included_appids)) ? si.included_appids.map(String) : [], }; }).filter(Boolean), }; } function classifyRow(row, index) { const ents = ((index && index.entries) || []).filter((e) => e && e.kind); if (!ents.length) return null; const apps = (row.appids || []).map(String); if (apps.length) { const cover = ents.filter((e) => e.included.length && apps.every((a) => e.included.indexOf(a) !== -1)); if (cover.length) { const exact = cover.filter((e) => e.included.length === apps.length); const pool = exact.length ? exact : cover; pool.sort((a, b) => a.included.length - b.included.length); return { kind: pool[0].kind, id: pool[0].id, name: pool[0].name, lineItemId: pool[0].lineItemId, how: exact.length ? zh('内容与购物车里那一项一致', 'content matches cart line') : zh('内容都属于购物车里那一项', 'content belongs to cart line'), }; } } const links = []; (row.bundleIds || []).forEach((id) => links.push({ kind: 'bundle', id: num(id), how: '/bundle/' })); (row.subIds || []).forEach((id) => links.push({ kind: 'package', id: num(id), how: '/sub/' })); for (const l of links) { const hit = ents.find((e) => e.kind === l.kind && String(e.id) === String(l.id)); if (hit) return { kind: hit.kind, id: hit.id, name: hit.name, lineItemId: hit.lineItemId, how: l.how }; } return null; } function buildRecord(row, target) { const rec = normalizeRecord({ id: uid('sh'), kind: target.kind, bundleid: target.kind === 'bundle' ? target.id : null, packageid: target.kind === 'package' ? target.id : null, appid: null, targetName: target.name || '', targetHow: target.how || '', lineItemId: target.lineItemId != null ? target.lineItemId : null, appids: row.appids.slice(), names: {}, endTsMap: {}, endTs: 0, pct: 0, count: row.appids.length, removedAt: now(), addedAt: now(), source: 'cart', steamid: currentSteamId(), }, 'interop'); return rec; } /** 单行暂存(无确认弹窗,与 SCE 行内行为一致) */ async function shelveOneRow(row) { if (busy) { toast(zh('暂存箱正忙,稍后再试', 'Shelf is busy, try later'), 'warning'); return; } const index = await buildCartIndex(); if (!index.ok) { toast(index.error, 'error'); return; } let target = classifyRow(row, index); if (!target && row.appids.length === 1) { target = { kind: 'app', id: num(row.appids[0]), name: '', lineItemId: null, how: zh('单个商品,恢复时按商店当前购买项', 'single app; resolved at restore time') }; } if (!target) { showModal({ title: zh('无法暂存这一项', 'Cannot stash this line'), body: '
' + zh('这一行认不出对应的购买项(bundle/sub)。为避免暂存错东西,已中止。', 'Cannot resolve the purchase option for this line; aborted to avoid a wrong record.') + '
', buttons: [{ label: zh('知道了', 'OK'), primary: true }] }); return; } const rec = buildRecord(row, target); const ok = doShelveRows([{ row: row, rec: rec }]); if (ok) toast(zh('已暂存:', 'Stashed: ') + displayName(rec), 'success'); } /** 批量暂存(确认弹窗 → 执行) */ function shelveAllRows() { if (busy) { toast(zh('暂存箱正忙,稍后再试', 'Shelf is busy, try later'), 'warning'); return; } const rows = scanCartRows(); if (!rows.length) { toast(zh('购物车里没有可暂存的行', 'No cart rows found'), 'warning'); return; } showModal({ title: zh('暂存购物车', 'Stash whole cart'), body: '
' + zh('将把购物车里的 ', 'Moves ') + rows.length + ' ' + zh('项移出购物车并存入暂存箱:', 'lines out of the cart into the shelf:') + '
' + '
    ' + rows.map((r) => '
  • ' + esc((r.appids[0] ? 'App ' + r.appids[0] : (r.bundleIds[0] ? 'Bundle ' + r.bundleIds[0] : 'Package ' + (r.subIds[0] || '?')))) + '
  • ').join('') + '
' + '
' + zh('整包内只要有一项认不出购买项,该行会被跳过。', 'Lines whose purchase option cannot be resolved will be skipped.') + '
', buttons: [ { label: zh('取消', 'Cancel') }, { label: zh('确认暂存 ' + rows.length + ' 项', 'Stash ' + rows.length), primary: true, act: async () => { await doShelveRows(rows.map((r) => ({ row: r, rec: null }))); } }, ], }); } async function doShelveRows(items) { if (busy) return false; busy = true; let done = 0; let fail = 0; try { const index = await buildCartIndex(); if (!index.ok) { toast(index.error, 'error'); return false; } for (let i = 0; i < items.length; i++) { const it = items[i]; let rec = it.rec; if (!rec) { const t = classifyRow(it.row, index) || (it.row.appids.length === 1 ? { kind: 'app', id: num(it.row.appids[0]), name: '', lineItemId: null, how: zh('单个商品', 'single app') } : null); if (!t) { fail++; continue; } rec = buildRecord(it.row, t); } setBusy(zh('正在暂存 ' + (done + fail + 1) + '/' + items.length + ':', 'Stashing ') + displayName(rec)); let btn = it.row.removeBtn; if (!btn || !btn.isConnected) btn = removeActionEl(it.row.rowEl); if (!btn || !btn.isConnected) { const again = scanCartRows().find((r) => rowKey(r) === rowKey(it.row)); btn = again && (again.removeBtn || removeActionEl(again.rowEl)); } if (!btn || !btn.isConnected) { fail++; continue; } try { btn.click(); } catch (e) { fail++; continue; } putItem(rec, { silent: true }); done++; await sleep(CFG.SHELVE_STEP_MS); } } finally { busy = false; setBusy(''); emitChange(); } if (done) toast(zh('已暂存 ', 'Stashed ') + done + ' ' + zh('项', 'items'), 'success'); if (fail) toast(zh('有 ', '') + fail + ' ' + zh('项未暂存(找不到移除按钮或认不出购买项)', 'items not stashed (no remove button / unresolvable)'), 'warning'); if (done) setTimeout(() => { try { location.reload(); } catch (e) { /* ignore */ } }, 700); return done > 0; } // ==================== 公开:新增记录 ==================== async function resolveName(appid) { if (Host && typeof Host.resolveName === 'function') { try { const n = await Host.resolveName(appid); if (n) return n; } catch (e) { /* ignore */ } } try { const items = await fetchStoreItems([{ appid: num(appid) }]); if (items[0] && items[0].name) return items[0].name; } catch (e) { /* ignore */ } return ''; } /** 统一入口:{kind, appid/bundleid/packageid, url, title, note, tags, endTs, pct} */ async function addItem(input) { const inp = Object.assign({}, input || {}); let kind = inp.kind; if (!kind) { if (inp.url) kind = 'note'; else if (inp.bundleid) kind = 'bundle'; else if (inp.packageid) kind = 'package'; else kind = inp.appid ? 'app' : 'note'; } const rec = normalizeRecord({ id: inp.id || uid('sh'), kind: kind, appid: inp.appid != null ? num(inp.appid) : null, bundleid: inp.bundleid != null ? num(inp.bundleid) : null, packageid: inp.packageid != null ? num(inp.packageid) : null, appids: Array.isArray(inp.appids) ? inp.appids : (inp.appid ? [num(inp.appid)] : []), names: inp.names || {}, targetName: inp.title || inp.name || '', displayName: inp.title || inp.name || '', note: inp.note || '', url: inp.url || '', tags: inp.tags || [], endTs: num(inp.endTs), pct: num(inp.pct), price: num(inp.price), currency: inp.currency || '', source: inp.source || 'manual', steamid: currentSteamId(), addedAt: now(), removedAt: now(), }, bucketOf(kind)); if (isInteropKind(kind) && !rec.appid && !rec.bundleid && !rec.packageid) { toast(zh('缺少商品 ID,未保存', 'Missing product id'), 'warning'); return null; } // 名称补全(app/wishlist 且未命名) if (!rec.displayName && (kind === 'app' || kind === 'wishlist') && rec.appid) { rec.displayName = await resolveName(rec.appid); if (rec.displayName) rec.targetName = rec.displayName; } const saved = putItem(rec); if (saved) toast(zh('已加入暂存箱:', 'Added to shelf: ') + displayName(saved), 'success'); return saved; } function addWishlist(appid, name, note) { return addItem({ kind: 'wishlist', appid: appid, title: name, note: note, source: 'wishlist' }); } function addNote(url, title, note, tags) { return addItem({ kind: 'note', url: url, title: title, note: note, tags: tags, source: 'manual' }); } // ==================== 导入 / 导出 ==================== function buildExport(opts) { const o = opts || {}; let items = allItems(); if (o.compatOnly) items = items.filter((r) => isInteropKind(r.kind)); const interopRaw = readRaw(CFG.INTEROP_KEY) || {}; return { format: 'sglv-shelf', version: 2, exportedAt: now(), source: 'SGLV 暂存箱', compatOnly: !!o.compatOnly, counts: { cart: items.filter((r) => isInteropKind(r.kind)).length, wishlist: items.filter((r) => r.kind === 'wishlist').length, note: items.filter((r) => r.kind === 'note').length, }, days: typeof interopRaw.days === 'number' ? interopRaw.days : 3, items: items, }; } /** * 导入:兼容三种形态 * a) 本库导出体 {format:'sglv-shelf', items:[...]} * b) SCE 原样体 {items:[...], days, tab} * c) 裸数组 [...] * 返回 {added, updated, skipped} */ function parseImport(text) { let data = null; try { data = JSON.parse(String(text || '').trim()); } catch (e) { return { ok: false, error: zh('JSON 解析失败:', 'JSON parse failed: ') + (e.message || e) }; } let list = null; if (Array.isArray(data)) list = data; else if (data && Array.isArray(data.items)) list = data.items; if (!list) return { ok: false, error: zh('没有找到 items 数组', 'No items array found') }; let added = 0; let updated = 0; let skipped = 0; const interopNew = []; const extraNew = []; list.forEach((raw) => { if (!raw || typeof raw !== 'object') { skipped++; return; } const kind = resolveKind(raw); const bucket = bucketOf(kind); // 互通桶必须自带 id:SCE 读取时会丢弃无 id 的记录, // 放进去等于「导入成功但下次 SCE 保存时静默消失」 if (bucket === 'interop' && !raw.id) { skipped++; return; } const rec = normalizeRecord(raw, bucket); if (bucket === 'interop' && !sceAcceptable(raw)) { skipped++; return; } if (bucket === 'interop') interopNew.push(rec); else extraNew.push(rec); }); if (interopNew.length) { const cur = readBucket('interop').items; interopNew.forEach((rec) => { const idx = cur.findIndex((x) => sameTarget(x, rec)); if (idx >= 0) { cur[idx] = Object.assign({}, cur[idx], rec, { id: cur[idx].id }); updated++; } else { cur.unshift(rec); added++; } }); writeBucket('interop', cur); } if (extraNew.length) { const cur = readBucket('extra').items; extraNew.forEach((rec) => { const idx = cur.findIndex((x) => sameTarget(x, rec)); if (idx >= 0) { cur[idx] = Object.assign({}, cur[idx], rec, { id: cur[idx].id }); updated++; } else { cur.unshift(rec); added++; } }); writeBucket('extra', cur); } emitChange(); return { ok: true, added: added, updated: updated, skipped: skipped }; } /** 去重比较:同 kind 同 id 视为同一条(id 不同也不重复入库) */ function sameTarget(a, b) { if (!a || !b) return false; if (a.id && b.id && a.id === b.id) return true; if (a.kind !== b.kind) return false; if (a.kind === 'bundle') return !!a.bundleid && String(a.bundleid) === String(b.bundleid); if (a.kind === 'package') return !!a.packageid && String(a.packageid) === String(b.packageid); if (a.kind === 'note') return !!a.url && a.url === b.url; return !!a.appid && String(a.appid) === String(b.appid); } // ==================== UI:浮窗 ==================== let overlayEl = null; let panelEl = null; let modalEl = null; let modalOnClose = null; let tickTimer = null; let isOpenFlag = false; let uiState = { filter: 'all', sort: 'end', q: '', compatOnly: false }; /* ================================================================= * CSS —— steam-industrial token 体系 * 参考 steam-industrial-theme.css(oil-ui 方法论): * 高信息密度 · 小圆角(工业风) · 左侧色条强调 · 斑马纹列表 · 大写小标签 * 表面/文字用 Steam 原生 #171a21 色阶(dark/purple 主题下均稳定); * 强调色走 var(--sglv-accent),跟随主脚本主题切换(color-mix 派生阶)。 * ============================================================== */ const CSS = ` /* ---------- 0. Design Tokens(作用域:浮窗 / 弹窗 / 购物车行内按钮) ---------- */ .sgsh-panel,.sgsh-modal,.sgsh-shelve-btn{ /* 表面 */ --sgsh-bg:#171a21; --sgsh-bg-2:#1b2838; --sgsh-bg-3:#2a3040; --sgsh-bg-4:#333c4e; --sgsh-border:#3d4450; --sgsh-border-2:#2a3040; /* 文字 */ --sgsh-text:#c6d4df; --sgsh-text-2:#8f98a0; --sgsh-text-3:#5c6b7a; --sgsh-heading:#e5e9ed; /* 强调(跟随主题) */ --sgsh-accent:var(--sglv-accent,#66c0f4); --sgsh-accent-wash:color-mix(in srgb,var(--sgsh-accent) 8%,transparent); --sgsh-accent-soft:color-mix(in srgb,var(--sgsh-accent) 16%,transparent); --sgsh-accent-line:color-mix(in srgb,var(--sgsh-accent) 42%,transparent); /* 语义色 */ --sgsh-gold:#ffb74c; --sgsh-gold-text:#d4a853; --sgsh-red:#d94a4a; --sgsh-red-text:#e07070; --sgsh-red-wash:color-mix(in srgb,var(--sgsh-red) 14%,transparent); --sgsh-red-line:color-mix(in srgb,var(--sgsh-red) 42%,transparent); --sgsh-green:#7ba82a; --sgsh-sky:#7dd3fc; /* 刻度 */ --sgsh-r:3px; --sgsh-ease:150ms ease; } /* ---------- 1. 窗体 ---------- */ .sgsh-overlay { background: rgba(8,11,17,0.72) !important; } .sgsh-panel { width: 920px !important; height: 82vh !important; background: var(--sgsh-bg) !important; border: 1px solid var(--sgsh-border) !important; border-radius: 4px !important; box-shadow: 0 18px 60px rgba(0,0,0,.55) !important; } .sgsh-panel .sglv-header { background: var(--sgsh-bg-2) !important; border-bottom: 1px solid var(--sgsh-border); } /* ---------- 2. 头部 ---------- */ .sgsh-head { display:flex; align-items:center; gap:10px; } .sgsh-head-icon { width:24px; height:24px; display:flex; align-items:center; justify-content:center; background: var(--sgsh-accent-wash); border:1px solid var(--sgsh-accent-line); border-radius: var(--sgsh-r); color: var(--sgsh-accent); font-size:13px; } .sgsh-head-title { font-size:14px; font-weight:600; color:var(--sgsh-heading); letter-spacing:.3px; } .sgsh-count { min-width:22px; height:18px; padding:0 7px; border-radius:2px; font-size:11px; font-weight:700; display:inline-flex; align-items:center; justify-content:center; color:var(--sgsh-gold-text); background:rgba(255,183,76,.12); border:1px solid rgba(255,183,76,.35); font-variant-numeric:tabular-nums; } /* ---------- 3. 按钮(扁平 + 描边) ---------- */ .sgsh-btn { border:1px solid var(--sgsh-border-2); border-radius:var(--sgsh-r); padding:5px 11px; font-size:11px; font-weight:600; letter-spacing:.3px; cursor:pointer; background:var(--sgsh-bg-3); color:var(--sgsh-text); display:inline-flex; align-items:center; gap:5px; transition:color var(--sgsh-ease), background var(--sgsh-ease), border-color var(--sgsh-ease); } .sgsh-btn:hover { background:var(--sgsh-bg-4); color:var(--sgsh-heading); border-color:var(--sgsh-border); } .sgsh-btn.primary { background:var(--sgsh-accent-soft); border-color:var(--sgsh-accent-line); color:var(--sgsh-accent); } .sgsh-btn.primary:hover { background:color-mix(in srgb,var(--sgsh-accent) 26%,transparent); border-color:var(--sgsh-accent); } .sgsh-btn.danger { background:transparent; border-color:var(--sgsh-red-line); color:var(--sgsh-red-text); } .sgsh-btn.danger:hover { background:var(--sgsh-red-wash); color:#fff; } .sgsh-btn:disabled { opacity:.4; cursor:not-allowed; } /* ---------- 4. 工具栏(搜索 / 筛选 / 排序) ---------- */ .sgsh-toolbar { display:flex; align-items:center; gap:10px; padding:10px 14px; flex-shrink:0; border-bottom:1px solid var(--sgsh-border-2); background:var(--sgsh-bg); flex-wrap:wrap; } .sgsh-search { flex:1; min-width:160px; padding:6px 10px; border-radius:var(--sgsh-r); font-size:12px; background:var(--sgsh-bg-2); border:1px solid var(--sgsh-border-2); color:var(--sgsh-text); outline:none; transition:border-color var(--sgsh-ease), box-shadow var(--sgsh-ease); } .sgsh-search::placeholder { color:var(--sgsh-text-3); } .sgsh-search:focus { border-color:var(--sgsh-accent-line); box-shadow:0 0 0 1px var(--sgsh-accent-wash); } .sgsh-chips { display:flex; gap:4px; } .sgsh-chip { border:1px solid var(--sgsh-border-2); background:transparent; color:var(--sgsh-text-2); border-radius:var(--sgsh-r); padding:4px 11px; font-size:11px; font-weight:600; cursor:pointer; transition:color var(--sgsh-ease), background var(--sgsh-ease), border-color var(--sgsh-ease); } .sgsh-chip:hover { color:var(--sgsh-text); border-color:var(--sgsh-border); } .sgsh-chip.active { background:var(--sgsh-accent-soft); color:var(--sgsh-accent); border-color:var(--sgsh-accent-line); } .sgsh-sort { padding:6px 9px; border-radius:var(--sgsh-r); font-size:11px; background:var(--sgsh-bg-2); border:1px solid var(--sgsh-border-2); color:var(--sgsh-text); outline:none; cursor:pointer; transition:border-color var(--sgsh-ease); } .sgsh-sort:focus { border-color:var(--sgsh-accent-line); } /* ---------- 5. 摘要条 ---------- */ .sgsh-summary { padding:7px 14px; font-size:11px; color:var(--sgsh-text-2); border-bottom:1px solid var(--sgsh-border-2); display:flex; align-items:center; gap:12px; flex-shrink:0; font-variant-numeric:tabular-nums; } .sgsh-summary b { color:var(--sgsh-accent); } .sgsh-busy { color:var(--sgsh-gold-text); font-weight:600; } /* ---------- 6. 列表(斑马纹 + 左侧色条强调,替代卡片流) ---------- */ .sgsh-body { flex:1; overflow-y:auto; padding:8px 14px 12px; } .sgsh-body::-webkit-scrollbar { width:6px; } .sgsh-body::-webkit-scrollbar-track { background:transparent; } .sgsh-body::-webkit-scrollbar-thumb { background:var(--sgsh-border-2); border-radius:3px; } .sgsh-body::-webkit-scrollbar-thumb:hover { background:var(--sgsh-border); } .sgsh-row { display:flex; align-items:flex-start; gap:10px; padding:9px 12px 9px 9px; border-left:3px solid transparent; border-bottom:1px solid var(--sgsh-border-2); transition:background var(--sgsh-ease), border-color var(--sgsh-ease); } .sgsh-row:first-child { border-top:1px solid var(--sgsh-border-2); } .sgsh-row:nth-child(odd) { background:rgba(255,255,255,.02); } .sgsh-row:hover { background:var(--sgsh-accent-wash); border-left-color:var(--sgsh-accent); } .sgsh-row.is-foreign { border-left-color:var(--sgsh-red); } .sgsh-kindtag { flex-shrink:0; font-size:9px; font-weight:700; padding:2px 6px; border-radius:2px; letter-spacing:.8px; text-transform:uppercase; background:var(--sgsh-accent-wash); color:var(--sgsh-accent); border:1px solid var(--sgsh-accent-line); margin-top:1px; } .sgsh-kindtag.wishlist { background:rgba(125,211,252,.1); color:var(--sgsh-sky); border-color:rgba(125,211,252,.32); } .sgsh-kindtag.note { background:rgba(255,183,76,.1); color:var(--sgsh-gold-text); border-color:rgba(255,183,76,.32); } .sgsh-main { flex:1; min-width:0; } .sgsh-name { font-size:13px; font-weight:600; color:var(--sgsh-heading); overflow:hidden; text-overflow:ellipsis; white-space:nowrap; } .sgsh-meta { display:flex; flex-wrap:wrap; gap:8px; margin-top:3px; font-size:10.5px; color:var(--sgsh-text-2); font-variant-numeric:tabular-nums; } .sgsh-meta .sev1 { color:var(--sgsh-red-text); font-weight:600; } .sgsh-meta .sev2 { color:var(--sgsh-gold-text); font-weight:600; } .sgsh-meta .sev3 { color:var(--sgsh-green); } .sgsh-meta .sgsh-warn { color:var(--sgsh-gold-text); } .sgsh-note { margin-top:4px; font-size:11px; color:var(--sgsh-text-2); background:rgba(255,255,255,.03); border-left:2px solid var(--sgsh-accent-line); padding:4px 8px; border-radius:0 var(--sgsh-r) var(--sgsh-r) 0; word-break:break-all; } .sgsh-acts { display:flex; gap:4px; flex-shrink:0; } .sgsh-act { width:26px; height:26px; border-radius:var(--sgsh-r); border:1px solid var(--sgsh-border-2); background:transparent; color:var(--sgsh-text-2); cursor:pointer; font-size:12px; line-height:1; display:flex; align-items:center; justify-content:center; transition:color var(--sgsh-ease), background var(--sgsh-ease), border-color var(--sgsh-ease); } .sgsh-act:hover { background:var(--sgsh-accent-soft); color:var(--sgsh-accent); border-color:var(--sgsh-accent-line); } .sgsh-act.del:hover { background:var(--sgsh-red-wash); color:var(--sgsh-red-text); border-color:var(--sgsh-red-line); } .sgsh-act:disabled { opacity:.35; cursor:not-allowed; } .sgsh-empty { text-align:center; padding:50px 20px; color:var(--sgsh-text-3); font-size:12px; line-height:1.9; } .sgsh-foot { display:flex; align-items:center; gap:8px; padding:10px 14px; border-top:1px solid var(--sgsh-border); background:var(--sgsh-bg-2); flex-shrink:0; } .sgsh-foot .sp { flex:1; } /* ---------- 7. 购物车页行内暂存按钮 ---------- */ .sgsh-shelve-btn { margin:0 6px; padding:2px 9px; font-size:10px; font-weight:700; letter-spacing:.5px; cursor:pointer; border-radius:2px; border:1px solid var(--sgsh-accent-line); background:var(--sgsh-accent-wash); color:var(--sgsh-accent); transition:background var(--sgsh-ease), color var(--sgsh-ease), border-color var(--sgsh-ease); } .sgsh-shelve-btn:hover { background:var(--sgsh-accent-soft); border-color:var(--sgsh-accent); color:var(--sgsh-accent); } /* ---------- 8. 弹窗 ---------- */ .sgsh-modal-mask { position:fixed; inset:0; z-index:1000001; background:rgba(8,11,17,.7); display:flex; align-items:center; justify-content:center; } .sgsh-modal { width:520px; max-width:calc(100vw - 40px); max-height:82vh; display:flex; flex-direction:column; background:var(--sgsh-bg); border:1px solid var(--sgsh-border); border-radius:4px; box-shadow:0 18px 60px rgba(0,0,0,.6); overflow:hidden; } .sgsh-modal-head { padding:12px 16px; font-size:13px; font-weight:600; color:var(--sgsh-heading); background:var(--sgsh-bg-2); border-bottom:1px solid var(--sgsh-border); display:flex; align-items:center; letter-spacing:.3px; } .sgsh-modal-body { padding:14px 16px; overflow-y:auto; font-size:12px; color:var(--sgsh-text); line-height:1.7; } .sgsh-modal-foot { padding:11px 16px; border-top:1px solid var(--sgsh-border-2); display:flex; gap:8px; justify-content:flex-end; } .sgsh-m-lead { margin-bottom:9px; color:var(--sgsh-text); } .sgsh-m-lead b { color:var(--sgsh-accent); font-variant-numeric:tabular-nums; } .sgsh-m-warn { margin-top:9px; padding:7px 10px; border-radius:0 var(--sgsh-r) var(--sgsh-r) 0; font-size:11px; background:rgba(255,183,76,.07); border-left:2px solid var(--sgsh-gold); color:var(--sgsh-gold-text); line-height:1.5; } .sgsh-m-list { margin:6px 0 0; padding-left:18px; max-height:220px; overflow-y:auto; } .sgsh-m-line { display:flex; flex-direction:column; padding:5px 0; border-bottom:1px dashed var(--sgsh-border-2); } .sgsh-m-line span { color:var(--sgsh-text-2); font-size:11px; word-break:break-all; } /* ---------- 9. 表单 ---------- */ .sgsh-field { margin-bottom:11px; } .sgsh-field label { display:block; font-size:10px; color:var(--sgsh-text-2); margin-bottom:5px; font-weight:700; text-transform:uppercase; letter-spacing:.6px; } .sgsh-field input, .sgsh-field textarea, .sgsh-field select { width:100%; box-sizing:border-box; padding:7px 10px; border-radius:var(--sgsh-r); font-size:12px; background:var(--sgsh-bg-2); border:1px solid var(--sgsh-border-2); color:var(--sgsh-text); outline:none; font-family:inherit; transition:border-color var(--sgsh-ease); } .sgsh-field textarea { min-height:110px; resize:vertical; font-family:ui-monospace,Menlo,Consolas,monospace; font-size:11px; } .sgsh-field input:focus, .sgsh-field textarea:focus, .sgsh-field select:focus { border-color:var(--sgsh-accent-line); } .sgsh-field .hint { font-size:10.5px; color:var(--sgsh-text-3); margin-top:4px; } .sgsh-check { display:flex; align-items:center; gap:7px; font-size:11.5px; color:var(--sgsh-text-2); margin-bottom:10px; cursor:pointer; } .sgsh-check input { width:auto; } /* ---------- 10. 侧栏角标:红点,不展示条数(--sgsh-red 只定义在浮窗上,这里写死颜色) ---------- */ .sgsh-badge { position:absolute; top:2px; right:2px; width:7px; height:7px; min-width:0; padding:0; display:block; border-radius:50%; background:#e23b3b; box-shadow:0 0 0 1.5px rgba(15,18,24,.9); pointer-events:none; font-size:0; line-height:0; color:transparent; overflow:hidden; } `; function ensureCss() { if (document.getElementById('sgsh-css')) return; const st = document.createElement('style'); st.id = 'sgsh-css'; st.textContent = CSS; (document.head || document.documentElement).appendChild(st); } function ensureUI() { if (panelEl) return; ensureCss(); overlayEl = document.createElement('div'); overlayEl.className = 'sglv-overlay sgsh-overlay'; overlayEl.setAttribute('data-sglv-plugin-ui', '1'); overlayEl.addEventListener('click', closeShelf); document.body.appendChild(overlayEl); panelEl = document.createElement('div'); panelEl.className = 'sglv-panel sgsh-panel'; panelEl.setAttribute('data-sglv-plugin-ui', '1'); panelEl.innerHTML = `
📦
${zh('暂存箱', 'Shelf')}
0
`; document.body.appendChild(panelEl); panelEl.addEventListener('click', onPanelClick); panelEl.querySelector('#sgsh-q').addEventListener('input', (e) => { uiState.q = e.target.value; renderList(); }); panelEl.querySelector('#sgsh-sort').addEventListener('change', (e) => { uiState.sort = e.target.value; setPrefs({ sort: uiState.sort }); renderList(); }); document.addEventListener('keydown', onKeydown); window.addEventListener('storage', onStorage); renderChips(); } function onKeydown(e) { if (e.key === 'Escape') { if (modalEl) { closeModal(); return; } if (isOpenFlag) closeShelf(); } } /** 跨脚本热更新:SCE 改了互通桶 → 同步角标与列表 */ function onStorage(e) { if (!e || (e.key && e.key !== CFG.INTEROP_KEY && e.key !== CFG.EXTRA_KEY)) return; emitChange(); if (isOpenFlag) render(); } /** 有暂存则亮红点,不把条数写进角标 */ function setBadge(n) { try { const on = num(n) > 0; document.querySelectorAll('[data-sgsh-badge]').forEach((el) => { if (el.textContent) el.textContent = ''; el.style.display = on ? '' : 'none'; }); } catch (e) { /* ignore */ } } function renderChips() { const box = panelEl && panelEl.querySelector('#sgsh-chips'); if (!box) return; box.innerHTML = FILTER_META.map((f) => ( `` )).join(''); } function visibleItems() { let list = allItems(); if (uiState.filter !== 'all') { list = list.filter((r) => (KIND_META[r.kind] || {}).tag === uiState.filter); } const q = uiState.q.trim().toLowerCase(); if (q) { list = list.filter((r) => { const hay = [displayName(r), r.note, (r.tags || []).join(' '), r.appid, r.bundleid, r.packageid, r.url] .filter(Boolean).join(' ').toLowerCase(); return hay.indexOf(q) !== -1; }); } const sort = uiState.sort; list.sort((a, b) => { if (sort === 'name') return displayName(a).localeCompare(displayName(b)); if (sort === 'added') return (num(b.addedAt) || num(b.removedAt)) - (num(a.addedAt) || num(a.removedAt)); const ae = num(a.endTs) || Infinity; const be = num(b.endTs) || Infinity; if (ae !== be) return ae - be; return (num(a.addedAt) || num(a.removedAt)) - (num(b.addedAt) || num(b.removedAt)); }); return list; } function rowHtml(rec) { const name = displayName(rec); const km = KIND_META[rec.kind] || { label: rec.kind, tag: 'cart' }; const meta = []; if (rec.count > 1) meta.push(zh('含 ', 'incl. ') + rec.count + ' ' + zh('项', 'items')); if (rec.pct) meta.push('-' + rec.pct + '%'); if (num(rec.endTs)) { const s = severity(rec.endTs); meta.push('' + esc(absTime(rec.endTs)) + ' · ' + esc(remainText(rec.endTs)) + ''); } if (rec.price) meta.push((rec.currency || '') + ' ' + rec.price); meta.push(rec.source === 'cart' ? zh('来自购物车', 'from cart') : rec.source === 'wishlist' ? zh('来自愿望单', 'from wishlist') : zh('手动', 'manual')); if (foreignAccount(rec)) meta.push('' + zh('⚠ 其他账号写入', '⚠ other account') + ''); if (rec.lastError) meta.push('' + esc(rec.lastError) + ''); if ((rec.tags || []).length) meta.push('#' + rec.tags.map(esc).join(' #')); const acts = []; if (canRestore(rec)) acts.push(''); const url = linkOf(rec); if (url) acts.push(''); if (rec.url) acts.push(''); acts.push(''); acts.push(''); return `
${esc(km.label)}
${esc(name)}
${meta.join('·')}
${rec.note ? '
' + esc(rec.note) + '
' : ''}
${acts.join('')}
`; } function renderList() { const body = panelEl && panelEl.querySelector('#sgsh-body'); if (!body) return; const list = visibleItems(); const total = countAll(); const cnt = panelEl.querySelector('#sgsh-count'); if (cnt) cnt.textContent = String(total); const share = panelEl.querySelector('#sgsh-share'); if (share) { const nInterop = readBucket('interop').items.length; share.textContent = zh('与购物车增强互通 ', 'shared with cart script: ') + nInterop + ' · ' + zh('独享 ', 'private: ') + (total - nInterop); } const restoreable = list.filter(canRestore).length; const soonest = list.filter((r) => num(r.endTs)).sort((a, b) => a.endTs - b.endTs)[0]; const sum = panelEl.querySelector('#sgsh-summary'); if (sum) { sum.innerHTML = `${zh('共 ', 'Total ') + '' + list.length + '' + (list.length !== total ? zh('(全部 ' + total + ')', ' of ' + total) : '')}` + `${zh('可恢复 ', 'Restorable ') + '' + restoreable + ''}` + (soonest ? `${zh('最近到期 ', 'Next expiry ') + '' + esc(remainText(soonest.endTs)) + ''}` : '') + (busy ? `${esc(busyText)}` : ''); } const cartBtn = panelEl.querySelector('#sgsh-shelve-cart'); if (cartBtn) { cartBtn.style.display = onCartPage() ? '' : 'none'; cartBtn.disabled = busy; } const restoreAllBtn = panelEl.querySelector('[data-act="restore-all"]'); if (restoreAllBtn) restoreAllBtn.disabled = busy || restoreable === 0; if (!list.length) { body.innerHTML = `
📦
${total ? zh('没有符合当前筛选的记录', 'No record matches the filter') : zh('暂存箱是空的。
在购物车页点行内「暂存」、或用右上角「+ 新建」记录备忘与外部链接。', 'Shelf is empty.
Use the row-level “Stash” on /cart, or “+ New” to save notes and links.')}
`; return; } body.innerHTML = list.map(rowHtml).join(''); } function render() { renderList(); } function setBusy(text) { busyText = text || ''; if (isOpenFlag) renderList(); } function openShelf() { if (!_hostReady) { toast(zh('暂存箱模块未就绪', 'Shelf module not ready'), 'warning'); return; } ensureUI(); const p = getPrefs(); uiState.filter = p.filter; uiState.sort = p.sort; uiState.compatOnly = p.compatOnly; isOpenFlag = true; overlayEl.classList.add('sglv-show'); panelEl.classList.add('sglv-show'); const q = panelEl.querySelector('#sgsh-q'); if (q) q.value = uiState.q; const s = panelEl.querySelector('#sgsh-sort'); if (s) s.value = uiState.sort; renderChips(); renderList(); startTick(); injectCartButtons(); } function closeShelf() { if (!panelEl) return; isOpenFlag = false; stopTick(); closeModal(); overlayEl.classList.remove('sglv-show'); panelEl.classList.remove('sglv-show'); } function isOpen() { return isOpenFlag; } function toggleShelf() { if (isOpenFlag) closeShelf(); else openShelf(); } function startTick() { stopTick(); tickTimer = setInterval(() => { if (!isOpenFlag) { stopTick(); return; } const nodes = document.querySelectorAll('#sgsh-body [data-end]'); for (let i = 0; i < nodes.length; i++) { const el = nodes[i]; const ts = num(el.getAttribute('data-end')); const cls = 'sev' + severity(ts); if (el.className !== cls) el.className = cls; const txt = absTime(ts) + ' · ' + remainText(ts); if (el.textContent !== txt) el.textContent = txt; } }, CFG.TICK_MS); } function stopTick() { if (tickTimer) { clearInterval(tickTimer); tickTimer = null; } } // ==================== 弹窗 ==================== function showModal(opts) { const o = opts || {}; closeModal(); modalOnClose = o.onClose || null; const mask = document.createElement('div'); mask.className = 'sgsh-modal-mask'; mask.setAttribute('data-sglv-plugin-ui', '1'); const buttons = (o.buttons || [{ label: zh('关闭', 'Close'), primary: true }]).map((b, i) => ( `` )).join(''); mask.innerHTML = `
${esc(o.title || '')}
${o.body || ''}
${buttons}
`; mask.addEventListener('click', (e) => { if (e.target === mask && o.maskClose !== false) closeModal(); }); mask.querySelector('.sgsh-modal-foot').addEventListener('click', async (e) => { const b = e.target.closest('[data-mi]'); if (!b) return; const def = (o.buttons || [])[Number(b.getAttribute('data-mi'))]; if (def && typeof def.act === 'function') { b.disabled = true; try { await def.act(); } catch (err) { console.warn('[SGLVShelf] 弹窗动作失败', err); } b.disabled = false; } if (!def || def.keep !== true) closeModal(); }); document.body.appendChild(mask); modalEl = mask; return mask; } function closeModal() { if (!modalEl) return; modalEl.remove(); modalEl = null; const cb = modalOnClose; modalOnClose = null; if (cb) { try { cb(); } catch (e) { /* ignore */ } } } function showConfirm(title, lead, okLabel, act) { showModal({ title: title, body: '
' + lead + '
', buttons: [ { label: zh('取消', 'Cancel') }, { label: okLabel, primary: true, act: act }, ], }); } function copyText(txt) { try { if (navigator.clipboard && navigator.clipboard.writeText) { navigator.clipboard.writeText(txt); return true; } } catch (e) { /* ignore */ } try { const ta = document.createElement('textarea'); ta.value = txt; ta.style.position = 'fixed'; ta.style.opacity = '0'; document.body.appendChild(ta); ta.select(); document.execCommand('copy'); ta.remove(); return true; } catch (e) { return false; } } // ==================== 交互分发 ==================== function onPanelClick(e) { const chip = e.target.closest('[data-filter]'); if (chip) { uiState.filter = chip.getAttribute('data-filter'); setPrefs({ filter: uiState.filter }); renderChips(); renderList(); return; } const actBtn = e.target.closest('[data-act]'); if (!actBtn) return; const act = actBtn.getAttribute('data-act'); const rowEl = actBtn.closest('.sgsh-row'); const id = rowEl ? rowEl.getAttribute('data-id') : null; const rec = id ? getItem(id) : null; switch (act) { case 'close': closeShelf(); break; case 'add': showEditModal(null); break; case 'edit': if (rec) showEditModal(rec); break; case 'restore': if (rec) executeRestore([rec.id]); break; case 'restore-all': { const ids = visibleItems().filter(canRestore).map((r) => r.id); if (!ids.length) { toast(zh('没有可恢复的记录', 'Nothing to restore'), 'warning'); break; } showConfirm(zh('全部恢复', 'Restore all'), zh('将把 ', 'Restores ') + ids.length + ' ' + zh('项恢复到购物车。', 'items back into the cart.'), zh('确认恢复', 'Restore'), () => executeRestore(ids)); break; } case 'open': { const u = rec ? linkOf(rec) : ''; if (!u) break; if (Host && typeof Host.openUrl === 'function') { try { Host.openUrl(u); break; } catch (err) { /* fallthrough */ } } window.open(u, '_blank', 'noopener'); break; } case 'copy': if (rec && rec.url) toast(copyText(rec.url) ? zh('链接已复制', 'Link copied') : zh('复制失败', 'Copy failed'), copyText(rec.url) ? 'success' : 'error'); break; case 'del': if (rec) showConfirm(zh('删除这条暂存?', 'Delete this record?'), zh('将从暂存箱移除 ', 'Removes ') + esc(displayName(rec)) + '。', zh('删除', 'Delete'), () => { deleteItem(rec.id); toast(zh('已删除', 'Deleted'), 'success'); }); break; case 'clear': { const n = countAll(); if (!n) { toast(zh('暂存箱已经是空的', 'Shelf is already empty'), 'warning'); break; } showConfirm(zh('清空暂存箱', 'Clear shelf'), zh('将删除全部 ', 'Deletes all ') + n + ' ' + zh('条记录(含与购物车增强互通的)。此操作不可撤销,建议先导出。', 'records (including shared ones). This cannot be undone — export first.'), zh('确认清空', 'Clear all'), () => { writeBucket('interop', []); writeBucket('extra', []); emitChange(); toast(zh('暂存箱已清空', 'Shelf cleared'), 'success'); }); break; } case 'prune': { const n = pruneStale(CFG.STALE_DAYS); toast(n ? zh('已清理 ', 'Pruned ') + n + zh(' 条陈旧记录', ' stale records') : zh('没有超过 ' + CFG.STALE_DAYS + ' 天的记录', 'Nothing older than ' + CFG.STALE_DAYS + ' days'), n ? 'success' : 'info'); break; } case 'export': showExportModal(); break; case 'import': showImportModal(); break; case 'shelve-cart': shelveAllRows(); break; default: break; } } // ---- 新建 / 编辑 ---- function showEditModal(rec) { const isNew = !rec; const kind = rec ? rec.kind : 'note'; const kinds = ['note', 'app', 'wishlist', 'bundle', 'package']; const opt = (k) => ``; showModal({ title: isNew ? zh('新建暂存', 'New shelf entry') : zh('编辑暂存', 'Edit shelf entry'), body: `
${zh('单品/捆绑包/购买包会写入与「购物车增强」互通的存储;愿望单与备忘由本库独享。', 'app/bundle/package go to the bucket shared with the cart script; wishlist/note are private.')}
${zh('填了就会在列表里倒计时并按到期排序', 'Enables countdown and expiry sorting')}
`, buttons: [ { label: zh('取消', 'Cancel') }, { label: isNew ? zh('加入暂存箱', 'Add') : zh('保存', 'Save'), primary: true, keep: true, act: async () => { const g = (id) => { const el = document.getElementById(id); return el ? el.value.trim() : ''; }; const k = g('f-kind'); const payload = { kind: k, title: g('f-title'), appid: num(g('f-appid')) || null, bundleid: num(g('f-bundleid')) || null, packageid: num(g('f-packageid')) || null, url: g('f-url'), note: g('f-note'), tags: g('f-tags').split(/\s+/).filter(Boolean), endTs: num(g('f-endts')), source: k === 'wishlist' ? 'wishlist' : 'manual', }; if (k !== 'note' && !payload.appid && !payload.bundleid && !payload.packageid) { toast(zh('该类型必须填写对应 ID', 'This kind requires its id'), 'warning'); return; } if (rec) { const merged = Object.assign({}, rec, payload); putItem(merged); toast(zh('已保存', 'Saved'), 'success'); } else { await addItem(payload); } } }, ], onClose: () => { if (isOpenFlag) renderList(); }, }); } // ---- 导出 ---- function showExportModal() { const full = buildExport({ compatOnly: false }); const compat = buildExport({ compatOnly: true }); showModal({ title: zh('导出暂存箱', 'Export shelf'), body: `
${zh('共 ' + full.items.length + ' 条(购物类 ' + compat.items.length + ' 条)。Ctrl/⌘+C 或点复制。', full.items.length + ' records (' + compat.items.length + ' cart). Ctrl/⌘+C or use Copy.')}
`, buttons: [ { label: zh('取消', 'Cancel') }, { label: zh('复制', 'Copy'), act: () => { const ta = document.getElementById('f-json'); const txt = ta ? ta.value : ''; toast(copyText(txt) ? zh('已复制到剪贴板', 'Copied to clipboard') : zh('复制失败,请手动全选', 'Copy failed — select manually'), copyText(txt) ? 'success' : 'warning'); } }, ], }); const chk = document.getElementById('f-compat'); const ta = document.getElementById('f-json'); if (chk && ta) chk.addEventListener('change', () => { ta.value = JSON.stringify(chk.checked ? compat : full, null, 2); }); } // ---- 导入 ---- function showImportModal() { showModal({ title: zh('导入暂存箱', 'Import shelf'), body: `
${zh('粘贴 JSON。支持本库导出体、购物车增强的原样导出、以及裸数组。相同商品自动合并,不产生重复。', 'Paste JSON. Accepts this shelf export, the cart script raw export, or a bare array. Identical products merge instead of duplicating.')}
`, buttons: [ { label: zh('取消', 'Cancel') }, { label: zh('导入', 'Import'), primary: true, act: () => { const ta = document.getElementById('f-json'); const r = parseImport(ta ? ta.value : ''); if (!r.ok) { toast(r.error, 'error'); return; } toast(zh('导入完成:新增 ', 'Imported: ') + r.added + zh(' · 更新 ', ' · updated ') + r.updated + (r.skipped ? zh(' · 跳过 ', ' · skipped ') + r.skipped : ''), r.added || r.updated ? 'success' : 'info'); } }, ], onClose: () => { if (isOpenFlag) renderList(); }, }); } // ==================== 购物车页监听 ==================== let cartObserver = null; let cartDebounce = 0; function watchCartPage() { if (cartObserver) return; const boot = () => { if (cartObserver || !onCartPage()) return; injectCartButtons(); cartObserver = new MutationObserver((mutations) => { for (let i = 0; i < mutations.length; i++) { const t = mutations[i].target; if (t && typeof t.closest === 'function' && t.closest('#sgis-panel, .sglv-panel, .sglv-overlay, .sglv-menu-wrap, #familyAnalysisPanel, #swe-panel, #swe-fab, .swe-nav-entry, [data-sglv-plugin-ui], [data-fa-plugin-ui], [data-swe-plugin-ui]')) continue; clearTimeout(cartDebounce); cartDebounce = setTimeout(() => { if (onCartPage()) injectCartButtons(); }, 600); return; } }); cartObserver.observe(document.body, { childList: true, subtree: true }); }; boot(); // 单页应用路由(/cart 内部不会切页,但保险起见监听一次 popstate) window.addEventListener('popstate', () => setTimeout(boot, 300)); } function refreshCartButtons() { if (!onCartPage()) return; injectCartButtons(); if (isOpenFlag) renderList(); } // ==================== 对外 ==================== function init(host) { Host = host || null; if (!Host || Host.apiVersion !== apiVersion) { console.warn('[SGLVShelf] 握手失败:Host.apiVersion 与库版本不匹配'); _hostReady = false; return false; } _hostReady = true; try { // 样式必须此刻注入,不能等到 ensureUI():侧栏角标在浮窗首次打开前 // 就可能显示(init 的 emitChange 会点亮它),懒加载会让角标裸奔 ensureCss(); // 初始化即广播一次,让侧栏按钮拿到初始角标 emitChange(); watchCartPage(); } catch (e) { console.warn('[SGLVShelf] 初始化异常(数据层仍可用)', e); } debug('init ok · interop=%d extra=%d', readBucket('interop').items.length, readBucket('extra').items.length); return true; } return { init: init, apiVersion: apiVersion, // 浮窗 openShelf: openShelf, closeShelf: closeShelf, toggleShelf: toggleShelf, isOpen: isOpen, // 数据 getCount: countAll, allItems: allItems, getItem: getItem, addItem: addItem, addWishlist: addWishlist, addNote: addNote, deleteItem: deleteItem, putItem: putItem, executeRestore: executeRestore, pruneStale: pruneStale, buildExport: buildExport, parseImport: parseImport, onChange: onChange, setBadge: setBadge, // 购物车页 injectCartButtons: refreshCartButtons, onCartPage: onCartPage, shelveAllRows: shelveAllRows, // 测试/诊断用内部接口 _internals: { normalizeRecord: normalizeRecord, isInteropKind: isInteropKind, bucketOf: bucketOf, resolveKind: resolveKind, sceAcceptable: sceAcceptable, readBucket: readBucket, writeBucket: writeBucket, getPrefs: getPrefs, setPrefs: setPrefs, sameTarget: sameTarget, resolveRestorePlan: resolveRestorePlan, displayName: displayName, linkOf: linkOf, remainText: remainText, severity: severity, CFG: CFG, }, }; })(); // ==== SGLV-SHELF-INLINE-END ==== // ==== SGLV-COVER-FALLBACK-INLINE-BEGIN (inline-cover-fallback.js 自动生成,勿手改) ==== /** * 内联内容由 inline-cover-fallback.js 生成 —— 请勿手改。 * 来源:libs/sglv-libs-cover-fallback.lib.js * 改动请编辑库文件后重跑本脚本;verify-cover-fallback-inline-sync.js 会拦截漏跑。 * * v2.0.0 重写要点: * - 链首 cdn.cloudflare(老游戏命中率最高,替代 v1.x 的 shared.akamai schinese_2x) * - 链长 7-8 (从 20 砍掉一半多) * - schinese 变体放链尾(避免老游戏先吃 4-5 个 404) * - 拿掉 steamui.com 渠道(被 Cloudflare managed challenge 拦截,永久失效) * - JS 驱动的 chainLoad(img, ...) — 参考 steam-friend-manager 1.5.3 dashChainLoad * - addEventListener('error') 单一 listener,链耗尽异步走 Steam Store API * * v2.0.1: good URL 跨会话缓存补 6 个月 TTL(COVER_GOOD_TTL)—— * 验证可用的封面 URL 半年内不再重走整条链;游戏换封面后半年自动重新探测。 * * v2.0.2: 修复封面"越改越坏"根因—— * chainLoad 单一状态机(不再 onerror + addEventListener 双推进); * skipUrl 跳过刚失败的 src;成功后 recordGood 落缓存;锁可复位; * getCoverUrl 先查 lang 键再回落无 lang 键。 * * v2.0.3: 缓存复用 / 渐进式失效—— * 过期条目不再批量删除(旧 URL 继续当初始 src,命中即刷新 ts,404 才走链); * LRU 500 → 2000;负缓存真正接上(网络失败 10min / 确认无资产 24h); * 只剪除 data:/blob: 垃圾条目。 */ // ---------- sglv-libs-cover-fallback.lib.js (610 行) ---------- /* * SGLV Cover Fallback Library v2.0.3 * * v2.0.3 缓存策略(渐进式失效 / 增量刷新 / 最大化复用旧缓存): * - 过期条目不再批量删除:旧 URL 继续作为初始 src 使用,命中即 recordGood 刷新 ts(零成本续期), * 404 只让这一条走回退链 —— 杜绝"半年后整库同时过期 → 全量重爬" * - PERSISTED_MAX 500 → 2000:大库不再频繁淘汰仍在使用的 good URL * - 负缓存真正接上(此前 _coverNeg 定义了但无人使用):API 网络失败 10min 重试、 * 确认无资产 24h 重试,避免每次渲染都打 appdetails * - loadPersisted 只剪除 data:/blob: 垃圾条目,http(s) 条目一律保留 * * v2.0.2 修复(封面"越改越坏"根因): * - chainLoad 不再混用 img.onerror + addEventListener('error')(同一次失败双推进, * 一次 error 跳过 2 个 URL 直冲 placeholder);改为单一状态机 * - 支持 skipUrl:跳过调用方刚失败的 src(旧实现重设同一 URL → 立刻再失败) * - 加载成功一律 recordGood() 写缓存(旧实现要求 onLoaded,宿主全都没传 → 缓存恒空) * - recordGood 只接受 http(s),data:/blob: 占位图绝不入缓存 * - 成功/放弃时复位 _sglvChainLoading(旧实现一次性锁永不复位,视图切换后彻底失效) * - getCoverUrl 先查 lang 键再回落无 lang 键(旧实现写入无 lang、读取只有 lang → 中文界面永不命中) * * v2.0.0 重写(性能与覆盖率重设计): * - 链首 cdn.cloudflare.steamstatic.com(Steam 老游戏命中率最高,2018 前所有发售游戏都覆盖) * - 链长度从 20 砍到 7-8(去掉冗余的 4 CDN × schinese 变体置顶;实测 schinese 变体在老游戏几乎全 404) * - schinese 变体放链尾部(仅在所有基础 URL 失败后才尝试,节省 4-5 个 404) * - 新增 chainLoad(img, appid, kind, opts) — JS 驱动链式加载(参考 steam-friend-manager 1.5.3 dashChainLoad) * img 创建时无 src(避免浏览器主动加载链首 404),addEventListener('error') 单一 listener, * 链耗尽后异步走 Steam Store API(不阻塞当前链) * - 移除 v1.x 的 steamui.com 渠道(被 Cloudflare managed challenge 拦截,受限网络下 _steamuiCfBlockedUntil * 永久触发,getSteamuiAssets 永远返回 null,整个 hash URL 直通渠道失效——回退到传统 CDN 链 + API 兜底) * - 保留 good URL 缓存 + GM 持久化(LRU 500)+ 负缓存(双 TTL:确认无资产 24h / 网络抖动快速自愈) * - 兼容 v1.x API:getCoverUrl(appid, kind, lang) / resolveCover(appid, kind, lang) / * bindErrorHandler(rootEl, onFailed) / loadImageWithFallback(img, onFailed) * * 设计目标:从 sglv-libs-core 抽出"封面降级 + 多 CDN 探测"基础设施, * 供所有 SGLV 系列脚本 @require 共享,避免每个脚本都重写一遍: * - cdn.cloudflare 链(老游戏最稳)→ store_item_assets 链(新游戏)→ header.jpg 兜底 * - 跨视图/跨会话的 good URL 缓存(按 kind 隔离) * - appdetails API 兜底(kind 感知:capsule 优先 capsule_image, 其余 header_image) * - SVG placeholder * * 使用方式: * 1) 宿主 @require 此 lib * 2) img 标签加 data-sglv-cover="1" + data-appid="123" + data-kind="capsule"(kind 默认 capsule) * 3) 初始 src 推荐用 SGLVCoverFallback.getCoverUrl(appId, kind) 同步取(命中缓存或链首) * 4) 在根容器上调用 SGLVCoverFallback.bindErrorHandler(rootEl) * 5) 错误时自动走 chainLoad(JS 接管,加 addEventListener('error') 单一 listener) * 6) 成功时自动写缓存(同会话 + 跨会话 GM) * 7) 链耗尽后异步走 Steam Store API(不阻塞当前链) * * 桥接契约(测试/宿主需要注入): * window.__sglvCoverMockGmXhr = function(method, url, opts, cb) 可选,默认走 GM_xmlhttpRequest * * API: * version: '2.0.0' * apiVersion: 3 * SVG_PLACEHOLDER: data:image/svg+xml 兜底图 * CHAIN: 默认 CDN fallback 链(横图 7:3,向后兼容) * KINDS: 支持的图片类型列表 * LANG_VARIANTS: 各 kind 的语言变体文件名模板(链尾部,老游戏通常 miss) * getCoverUrl(appId, kind?, lang?): 获取初始 URL(good 缓存→链首) * resolveCover(appId, kind?, lang?): Promise 版(同步 good 缓存→链首;异步仅在 Steam API 调用时使用) * chainLoad(img, appid, kind?, opts?): JS 驱动的链式加载(主要入口 — 推荐) * bindErrorHandler(rootEl, onFailed?): 在 rootEl 上绑定 error/load 委托(全局只调一次) * loadImageWithFallback(img, onFailed?): 兼容 v1.x 手动触发单图降级 * getSteamuiAssets: (v1.x 兼容, v2.0 返回 null, 避免误调) * getSteamuiGoodUrl: (v1.x 兼容, v2.0 返回 '') * * 宿主需 @grant GM_xmlhttpRequest, GM_getValue, GM_setValue。 */ (function (root) { 'use strict'; // ==================== 常量 ==================== const VERSION = '2.0.3'; const API_VERSION = 3; // CDN 前缀(按"老游戏命中率"排序,链首=命中率最高) // v2.0.0: cdn.cloudflare 排第一 — Steam 老游戏(2018 前)基本都在这 // shared.akamai store_item_assets 排第二 — 新游戏(2018+ / 哈希子目录) // cdn.akamai 排第三 — 部分老 CDN 资源 // shared.fastly store_item_assets 排第四 — 备用哈希子目录 const CDN_CF = 'https://cdn.cloudflare.steamstatic.com/steam/apps/'; const CDN_SHARED_AK = 'https://shared.akamai.steamstatic.com/store_item_assets/steam/apps/'; const CDN_AK = 'https://cdn.akamai.steamstatic.com/steam/apps/'; const CDN_SHARED_FASTLY = 'https://shared.fastly.steamstatic.com/store_item_assets/steam/apps/'; // kind → 基础文件列表(无语言变体;变体放链尾部,避免老游戏先吃 4-5 个 404) const POSTER_FILES = ['library_600x900_2x.jpg', 'library_600x900.jpg']; const CAPSULE_FILES = ['capsule_467x181.jpg', 'capsule_231x87.jpg']; const HEADER_FILES = ['header.jpg']; const HERO_FILES = ['library_hero_2x.jpg', 'library_hero.jpg']; const LOGO_FILES = ['logo_2x.png', 'logo.png']; const LIB_HEADER_FILES = ['library_header_2x.jpg', 'library_header.jpg']; // 语言变体文件名模板(仅在基础链全部失败时追加,避免老游戏先吃 schinese 404) // 实测 Steam CDN 路径直接支持语言后缀: capsule_467x181_schinese.jpg / logo_schinese.png 等 // 但 2018 前发售的老游戏几乎都没这些变体 → 放链尾节省 4-5 个 404 const LANG_VARIANTS = { poster: ['library_600x900_{v}_2x.jpg', 'library_600x900_{v}.jpg'], capsule: ['capsule_467x181_{v}.jpg', 'capsule_231x87_{v}.jpg'], header: ['header_{v}.jpg'], hero: ['library_hero_{v}_2x.jpg', 'library_hero_{v}.jpg'], logo: ['logo_{v}_2x.png', 'logo_{v}.png'], library_header: ['library_header_{v}_2x.jpg', 'library_header_{v}.jpg'], }; const KINDS = ['poster', 'capsule', 'header', 'hero', 'logo', 'library_header']; // SVG placeholder(URL 编码内嵌) const SVG_PLACEHOLDER = "data:image/svg+xml;utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 184 69'%3E%3Crect fill='%231a1f3a' width='184' height='69'/%3E%3Ctext x='50%25' y='50%25' text-anchor='middle' dy='.3em' fill='%2364748b' font-family='system-ui' font-size='10'%3ENo Image%3C/text%3E%3C/svg%3E"; // ==================== 内存缓存(同会话跨视图共享) ==================== // 缓存键按 kind(+lang) 隔离 → "kind:appid" / "kind:appid@lang" const _goodMap = new Map(); function goodKey(kind, appId, lang) { const k = kind || 'capsule'; return lang ? k + ':' + appId + '@' + lang : k + ':' + appId; } // ==================== 持久化缓存(跨会话,GM_setValue) ==================== // 与 v1.x 兼容: 键名 'sglv_cover_url_v2', LRU 2000 // v2.0.3: 500 → 2000 —— 大库(1000+ 游戏)下 500 条会频繁淘汰仍在使用的条目, // 被淘汰的条目下次渲染要从链首重爬(最坏 10 次 404)。2000 条约 240KB,远低于 GM 配额。 const PERSISTED_KEY = 'sglv_cover_url_v2'; const PERSISTED_MAX = 2000; // 新鲜期(诊断/迁移用,不再用于批量删除) // v2.0.3: 过期条目**不再删除** —— 渐进式失效: // 旧 URL 继续作为初始 src 使用,命中则 recordGood 刷新 ts(零成本续期); // 404 则只让这一条走回退链。避免"半年后整库同时过期 → 全量重爬"。 // 容量由 PERSISTED_MAX 的 LRU(按最近成功使用时间)控制。 const COVER_GOOD_TTL = 6 * 30 * 24 * 3600 * 1000; // 180 天(仅 v1 迁移门槛) let _persisted = null; function loadPersisted() { if (_persisted !== null) return _persisted; _persisted = {}; try { const raw = GM_getValue(PERSISTED_KEY); if (raw && typeof raw === 'object') _persisted = raw; } catch (e) { /* ignore */ } // 只剪除确定无效的条目(非 http(s) 的 data:/blob: 占位残留)。 // 过期条目保留:它大概率仍然可用,作为初始 src 再试一次比"重新爬整条链"便宜得多。 let pruned = false; for (const key in _persisted) { const ent = _persisted[key]; if (!ent || !isHttpUrl(ent.url)) { delete _persisted[key]; pruned = true; continue; } _goodMap.set(key, ent.url); } if (pruned) { try { GM_setValue(PERSISTED_KEY, _persisted); } catch (e) { /* ignore */ } } // v1.x 兼容: 迁移 v1 旧格式 (appid 直接作键) try { const now = Date.now(); const oldRaw = GM_getValue('sglv_cover_url_v1'); if (oldRaw && typeof oldRaw === 'object') { for (const id in oldRaw) { const ent = oldRaw[id]; if (ent && isHttpUrl(ent.url) && !_persisted['capsule:' + id] && (now - (ent.ts || 0)) <= COVER_GOOD_TTL) { _persisted['capsule:' + id] = { url: ent.url, ts: ent.ts || now }; _goodMap.set('capsule:' + id, ent.url); } } } } catch (e) { /* ignore */ } return _persisted; } let _writeTimer = null; let _writeDirty = false; // 同一 URL 的 ts 刷新落盘节流:ts 只服务 LRU 排序,不需要秒级精度。 // 每次 load 都整表序列化(2000 条约 220KB)会在滚动时造成明显卡顿。 const PERSIST_TOUCH_TTL = 60 * 60 * 1000; // 1h function setPersisted(cacheKey, url) { if (!cacheKey || !url) return; const container = loadPersisted(); const ent = container[cacheKey]; const now = Date.now(); if (ent && ent.url === url && (now - (ent.ts || 0)) < PERSIST_TOUCH_TTL) return; container[cacheKey] = { url, ts: now }; const keys = Object.keys(container); if (keys.length > PERSISTED_MAX) { // LRU: 删最旧的 keys.sort((a, b) => (container[a].ts || 0) - (container[b].ts || 0)); while (keys.length > PERSISTED_MAX) delete container[keys.shift()]; } _writeDirty = true; if (_writeTimer) return; _writeTimer = setTimeout(() => { _writeTimer = null; if (!_writeDirty) return; _writeDirty = false; try { GM_setValue(PERSISTED_KEY, container); } catch (e) { /* 配额/序列化失败静默 */ } }, 50); } function flushPersisted() { if (_writeTimer) { clearTimeout(_writeTimer); _writeTimer = null; } if (_writeDirty && _persisted) { _writeDirty = false; try { GM_setValue(PERSISTED_KEY, _persisted); } catch (e) { /* ignore */ } } } function clearPersisted() { _persisted = {}; _goodMap.clear(); try { GM_setValue(PERSISTED_KEY, {}); } catch (e) { /* ignore */ } try { GM_setValue('sglv_cover_url_v1', {}); } catch (e) { /* ignore */ } } // ==================== 负缓存(API 调用失败避免重试风暴) ==================== // 双 TTL: 确认无资产(API 成功但 data 空)24h;网络/限频失败 10min 快速自愈 // 收敛策略:同一 appid+kind 最多每 10min / 24h 打一次 API, // 网络抖动很快恢复,确认无资产也不会每次渲染都重试 —— 渐进式刷新。 const COVER_NEG_TTL = 24 * 60 * 60 * 1000; const COVER_NETFAIL_TTL = 10 * 60 * 1000; const COVER_NEG_MAX = 800; const _coverNeg = new Map(); // 'kind:appid' → { t, n } (n=1 网络失败,n=0 确认无资产) function _negHit(rec) { if (!rec) return false; const now = Date.now(); return (now - rec.t) < (rec.n ? COVER_NETFAIL_TTL : COVER_NEG_TTL); } function _negKey(k, appId) { return k + ':' + appId; } function _negMark(k, appId, netFail) { const key = _negKey(k, appId); _coverNeg.delete(key); _coverNeg.set(key, { t: Date.now(), n: netFail ? 1 : 0 }); if (_coverNeg.size > COVER_NEG_MAX) { const it = _coverNeg.keys(); while (_coverNeg.size > COVER_NEG_MAX) { const kk = it.next(); if (kk.done) break; _coverNeg.delete(kk.value); } } } // ==================== 链构建 ==================== // v2.0.0: 链首 cdn.cloudflare(老游戏命中率最高),基础文件, schinese 变体放链尾 function buildFiles(kind, lang) { const k = (kind && KINDS.indexOf(kind) >= 0) ? kind : 'capsule'; let base; if (k === 'poster') base = POSTER_FILES; else if (k === 'capsule') base = CAPSULE_FILES; else if (k === 'header') base = HEADER_FILES; else if (k === 'hero') base = HERO_FILES; else if (k === 'logo') base = LOGO_FILES; else base = LIB_HEADER_FILES; const files = base.slice(); // schinese 变体放链尾 — 老游戏(2018 前)基本没这些,放链首是 4-5 个浪费的 404 if (lang) { const tpl = LANG_VARIANTS[k]; if (tpl) for (const t of tpl) files.push(t.replace('{v}', lang)); } return files; } // 链构造: cdn.cloudflare(1) → store_item_assets(2,3,4) → header.jpg 兜底 // 总数 7-8 URL(从 v1.x 的 20 砍掉一半多) function buildFullChain(appId, kind, lang) { const id = String(appId); const files = buildFiles(kind, lang); const full = []; for (const f of files) { // 1. cdn.cloudflare 链首(老游戏最稳) full.push(CDN_CF + id + '/' + f); // 2. shared.akamai store_item_assets(新游戏哈希子目录) full.push(CDN_SHARED_AK + id + '/' + f); // 3. cdn.akamai(部分老 CDN 资源) full.push(CDN_AK + id + '/' + f); // 4. shared.fastly store_item_assets(备用) full.push(CDN_SHARED_FASTLY + id + '/' + f); } // header.jpg 兜底(几乎所有游戏都有,放链尾) if (kind !== 'header' && kind !== 'library_header') { full.push(CDN_CF + id + '/header.jpg'); full.push(CDN_SHARED_AK + id + '/header.jpg'); } return full; } // ==================== 链去重 ==================== // 同一 URL 不重复探测(steamui hash URL 可能跟基础链重复) function _dedupeChain(chain) { if (!Array.isArray(chain)) return chain; const seen = new Set(); const out = []; for (const u of chain) { if (u && !seen.has(u)) { seen.add(u); out.push(u); } } return out; } // ==================== good URL 写入(统一入口) ==================== // v2.0.2: 宿主一直调用 recordGood() 但 v2.0.0 没有导出该 API — // 结果 whole 会话内没有任何 URL 被写进 good 缓存,getCoverUrl 永远只返回链首, // 每张封面每次渲染都要从链首重新试错(这也是"越改越慢/越改越坏"的根源之一)。 function isHttpUrl(u) { return typeof u === 'string' && /^https?:\/\//i.test(u); } // 取 img 当前 src(容错: 测试/桩对象可能没有 getAttribute) function _imgSrc(img) { try { if (img && typeof img.getAttribute === 'function') return img.getAttribute('src') || ''; return (img && img.src) || ''; } catch (e) { return ''; } } // 记录"已验证可加载"的 URL:同会话 Map + 跨会话 GM 持久化 // 只接受 http(s) —— data:/blob: 占位图绝不入缓存 // 统一写无 lang 键(lang 只是读取顺序偏好,写两份会浪费 LRU 配额; // getCoverUrl 会先查 lang 键再回落无 lang 键) function recordGood(appId, url, kind, lang) { if (!appId || !isHttpUrl(url)) return false; const k = (kind && KINDS.indexOf(kind) >= 0) ? kind : 'capsule'; const id = String(appId); _goodMap.set(goodKey(k, id, ''), url); setPersisted(goodKey(k, id, ''), url); if (lang) _goodMap.set(goodKey(k, id, lang), url); // 仅内存别名,不额外占持久化配额 return true; } // ==================== getCoverUrl / resolveCover (兼容 v1.x API) ==================== function getCoverUrl(appId, kind, lang) { if (!appId) return ''; const k = kind || 'capsule'; loadPersisted(); // 1) 同步 good 缓存(同会话 + 跨会话) // v2.0.2: 先查带 lang 的键,再回落到无 lang 键 —— 写入统一走无 lang 键, // 旧实现只查 lang 键导致中文界面下跨会话缓存永远命中不了 const cached = _goodMap.get(goodKey(k, appId, lang)) || _goodMap.get(goodKey(k, appId, '')); if (isHttpUrl(cached)) return cached; // 2) 没缓存 → 链首(基础文件,无 schinese 变体 — 优先快速命中老游戏) const chain = buildFullChain(appId, k, ''); return chain[0] || ''; } // v1.x 兼容: Promise 版封面解析 // v2.0: 同步 good 缓存命中后直接 resolve;未命中走链首(异步 Steam API 仅在显式调用时执行) function resolveCover(appId, kind, lang) { if (!appId) return Promise.resolve(SVG_PLACEHOLDER); const u = getCoverUrl(appId, kind, lang); return Promise.resolve(u || SVG_PLACEHOLDER); } // ==================== Steam Store API 兜底 ==================== // kind 感知: capsule 优先 capsule_image, poster/header/hero/logo/library_header 优先 header_image function fetchFromAPI(appId, kind) { return new Promise((resolve) => { const k = kind || 'capsule'; const apiUrl = `https://store.steampowered.com/api/appdetails?appids=${appId}&filters=basic`; const gmxhr = root.__sglvCoverMockGmXhr || (typeof GM_xmlhttpRequest !== 'undefined' ? GM_xmlhttpRequest : null); let settled = false; // v2.0.3: 区分「网络失败」(10min 后可重试) 与「确认无资产」(24h) —— // 两者都写负缓存,避免每次渲染都重打 API(重试风暴),又不会永久拉黑。 const finish = (url, netFail) => { if (settled) return; settled = true; if (isHttpUrl(url)) _coverNeg.delete(_negKey(k, appId)); else _negMark(k, appId, !!netFail); resolve(url || ''); }; const pick = (d) => (k === 'capsule') ? (d.capsule_image || d.header_image || '') : (d.header_image || d.capsule_image || ''); if (gmxhr) { gmxhr({ method: 'GET', url: apiUrl, timeout: 8000, onload: (r) => { try { const j = JSON.parse(_safeText(r)); const d = j[appId]; if (d && d.success && d.data) finish(pick(d.data), false); else finish('', false); // API 正常返回但无该游戏资产 → 24h 内不重试 } catch (e) { finish('', true); } }, onerror: () => finish('', true), ontimeout: () => finish('', true), }); } else if (typeof fetch !== 'undefined') { fetch(apiUrl).then(r => r.json()).then(j => { const d = j[appId]; if (d && d.success && d.data) finish(pick(d.data), false); else finish('', false); }).catch(() => finish('', true)); } else { finish('', true); } }); } function _safeText(r) { try { if (!r) return ''; if (typeof r.responseText === 'string') return r.responseText; if (typeof r.response === 'string') return r.response; return ''; } catch (e) { return ''; } } // ==================== chainLoad: JS 驱动的链式加载(v2.0.2 重写)==================== // v2.0.2 修复的关键缺陷: // ① 旧实现同时挂 img.onerror 与 addEventListener('error') —— 同一次失败两套 // handler 各推进一次链(tryFinal 被调两次),一次 error 跳过 2 个 URL, // 直接从链首冲到 placeholder。现在只用一对 addEventListener,单一状态机。 // ② 旧实现忽略调用方当前 src —— bindErrorHandler 明明算了 cur 却没用, // chain[0] 往往就是刚 404 的那个 URL,重设同一 URL 立刻再次失败。 // 现在支持 opts.skipUrl,并且 step() 内部也跳过 curSrc。 // ③ 旧实现只有调用方传 onLoaded 才写 good 缓存,而宿主全部没传 — // 缓存永远是空的。现在加载成功即内部 recordGood()。 // ④ 旧实现的 _sglvChainLoading 一次性锁从不复位 —— 同一 img 节点再次赋值 // src(视图切换复用节点)后 error 全被忽略,永远停在坏图上。现在成功/放弃时复位。 // ⑤ 旧实现链耗尽后还会再试一遍 header.jpg 两连(finalChain),而 buildFullChain // 已经带了 header 兜底 —— 重复请求。现在去重后统一由 chain 覆盖。 // - img 创建时可无 src(不触发浏览器主动加载) // - 链耗尽后异步走 Steam API(不阻塞当前链) // - 失败/超时/API 空: 通知 onGiveUp(宿主替换占位)或设 SVG placeholder function chainLoad(img, appid, kind, opts) { if (!img || !appid) return; const k = (kind && KINDS.indexOf(kind) >= 0) ? kind : 'capsule'; const o = opts || {}; const lang = o.lang || root.__sglvCoverLang || ''; // 1) 同步 good 缓存命中 — 放链首(成功概率最高,避免链首 404) // 只接受 http(s):占位图/脏缓存一律忽略,继续走真实 CDN 链 loadPersisted(); const goodRaw = _goodMap.get(goodKey(k, appid, lang)) || _goodMap.get(goodKey(k, appid, '')); const good = isHttpUrl(goodRaw) ? goodRaw : ''; // 2) 完整链(已含 header.jpg 兜底) const chain = _dedupeChain((good ? [good] : []).concat(buildFullChain(appid, k, lang))); // 3) 从"当前已失败的 src"之后继续,不重复请求同一个 404 const curSrc = (o.skipUrl != null) ? String(o.skipUrl) : _imgSrc(img); let i = 0; const pos = chain.indexOf(curSrc); if (pos >= 0 && pos + 1 < chain.length) i = pos + 1; let done = false; let apiStarted = false; function detach() { img.removeEventListener('error', onError); img.removeEventListener('load', onLoad); img._sglvChainLoading = 0; // 释放一次性锁,允许后续重新接管 } function succeed() { if (done) return; done = true; detach(); const u = img.currentSrc || img.src || ''; recordGood(appid, u, k, lang); if (o.onLoaded) { try { o.onLoaded(u); } catch (e) { /* ignore */ } } } function fail() { if (done) return; done = true; detach(); if (o.onGiveUp) { try { o.onGiveUp(); } catch (e) { /* ignore */ } } // 宿主已替换节点时不再改 src(onGiveUp 内部 replaceChild) if (!o.noPlaceholder && img.isConnected && img.parentElement) img.src = SVG_PLACEHOLDER; } function step() { if (done) return; while (i < chain.length) { const u = chain[i++]; if (!u || u === curSrc) continue; // 刚失败的 URL 不再请求 img.src = u; return; } // 4) 链耗尽 → Steam API 兜底(仅一次) if (!apiStarted) { apiStarted = true; // v2.0.3: 负缓存命中则跳过 API —— 同一 appid+kind 在 TTL 内最多打一次, // 既不会每次渲染都重试(重试风暴),也会在 TTL 后自动恢复(渐进式刷新) if (_negHit(_coverNeg.get(_negKey(k, appid)))) { fail(); return; } Promise.resolve(fetchFromAPI(appid, k)).then(function (url) { if (done) return; if (isHttpUrl(url) && chain.indexOf(url) < 0) { img.src = url; return; } fail(); }, fail); return; } fail(); } function onError() { if (!done) step(); } function onLoad() { if (done) return; // naturalWidth <= 1 视为占位/空图,不写缓存也不算成功 if (!img.naturalWidth || img.naturalWidth < 2) return; succeed(); } img.addEventListener('load', onLoad); img.addEventListener('error', onError); step(); } // ==================== bindErrorHandler (兼容 v1.x API) ==================== // 在 rootEl 上绑定 error/load 委托 — 任何 data-sglv-cover="1" 的 img 出错时自动走 chainLoad // 全局只调一次(bindErrorHandler 内部守卫) function bindErrorHandler(rootEl, onFailed) { if (!rootEl || rootEl.dataset.sglvCoverHandlerBound) return; rootEl.dataset.sglvCoverHandlerBound = '1'; rootEl.addEventListener('error', (e) => { const t = e.target; if (!t || t.tagName !== 'IMG') return; if (t.dataset && t.dataset.sglvCover !== '1') return; if (t._sglvChainLoading) return; const appid = t.dataset.appid; if (!appid) return; t._sglvChainLoading = 1; const kind = t.dataset.kind || 'capsule'; // 记录当前失败 src,从 chain 中跳过(避免对同一个 404 重复发请求) const cur = _imgSrc(t); chainLoad(t, appid, kind, { skipUrl: cur, onGiveUp: () => { if (onFailed) try { onFailed(t); } catch (e) {} }, }); }, true); // capture: 捕获内嵌 img 的 error } // ==================== loadImageWithFallback (兼容 v1.x API) ==================== function loadImageWithFallback(img, onFailed) { if (!img) return; const appid = img.dataset && img.dataset.appid; if (!appid) return; const kind = (img.dataset && img.dataset.kind) || 'capsule'; if (img._sglvChainLoading) return; img._sglvChainLoading = 1; chainLoad(img, appid, kind, { skipUrl: _imgSrc(img), onGiveUp: () => { if (onFailed) try { onFailed(img); } catch (e) {} }, }); } // ==================== v1.x 兼容: steamui 接口(全部返回空)==================== // v2.0 移除 steamui.com 渠道(被 CF managed challenge 拦截,失效) // 保留接口名(返回 null/'')避免宿主调用炸 function getSteamuiAssets(appId, opts) { return Promise.resolve(null); } function getSteamuiGoodUrl(appId, kind, lang) { return ''; } function _resetSteamuiState() { /* no-op */ } // ==================== 公开 API ==================== const api = { // 元信息 version: VERSION, apiVersion: API_VERSION, // 常量 SVG_PLACEHOLDER, CHAIN: ['capsule_231x87.jpg', 'capsule_184x69.jpg', 'capsule_467x181.jpg', 'header.jpg'], KINDS, LANG_VARIANTS, // 链构建 buildFiles, buildFullChain, _dedupeChain, // 同步获取 URL getCoverUrl, resolveCover, // JS 驱动链式加载(主要入口) chainLoad, // 委托绑定 bindErrorHandler, loadImageWithFallback, // 缓存管理 recordGood, // v2.0.2: 宿主成功回调统一写 good 缓存(仅接受 http(s)) flushPersisted, clearPersisted, // v1.x 兼容(steamui 渠道已移除,接口保留) getSteamuiAssets, getSteamuiGoodUrl, _resetSteamuiState, // 内部 API(供宿主 monky-patch / 调试) _goodMap, loadPersisted, setPersisted, isHttpUrl, _safeText, fetchFromAPI, }; root.SGLVCoverFallback = api; if (typeof unsafeWindow !== 'undefined' && unsafeWindow !== root) { try { unsafeWindow.SGLVCoverFallback = api; } catch (e) { /* ignore */ } } return api; })(typeof window !== 'undefined' ? window : globalThis); // ==== SGLV-COVER-FALLBACK-INLINE-END ==== // ==== SGLV-GAME-COLLECTION-INLINE-BEGIN (inline-game-collection.js 自动生成,勿手改) ==== /** * 内联内容由 inline-game-collection.js 生成 —— 请勿手改。 * 来源:libs/sglv-libs-game-collection.lib.js * 改动请编辑库文件后重跑本脚本;verify-game-collection-inline-sync.js 会拦截漏跑。 * * v2.1.0 关键改进: * - seriesCoverImg / seriesCapsuleImg 重写为 data-属性 + 单一 onerror 委托 * (img 创建时无 src,失败时由 _sglvChainFallback → chainLoad JS 接管) * - 3 级下拉面包菜单 (分类 › 供应商 › 系列) 替代 sidebar 列表选择器 * - _bcRenderDetail 统一 4 个 detail 渲染函数 * - 30+ 条 CSS 渐变/圆角/hover 动效 */ // ---------- sglv-libs-game-collection.lib.js (11155 行) ---------- /* * SGLV Game Collection Library v2.1.0 * * ── 版本沿革 ────────────────────────────────────────────── * v2.9.9(PS 会免:独占占位画居中 + 名称显示优化): * ① 占位画居中——蓝色 PS 底纹改绝对定位铺满图片盒 + flex 双向居中,PS Logo 收敛到与卡片 * 协调的尺寸,Logo+名称组稳定落在正中(此前 height:100% 在 aspect-ratio 盒内 + 过大 Logo * 让内容观感偏移、不居中)。 * ② 名称显示——底纹名称降为居中两行省略的小字说明;并给底纹名称挂 data-sglv-psstore, * 让它与卡片正文一样被异步替换成 PS Store 官方名(此前只有正文被替换,底纹残留 * URL slug 拆词产生的 garbled 名,两处不一致)。 * ③ 泛化名守卫——PS Store 页 og:title 整页就是平台名(区域限售回落首页)时解析出 * "PlayStation" 之类泛化词,此前会回填成卡片名;现视为抓取失败保留原名。 * * v2.9.8(年度大作:顶部穿透修复 + TGA 年度游戏殿堂): * ① 顶部内容穿透修复——年度大作滚动区 padding-top:2px 与 sticky 分组标题栏(top:0)组合, * 使吸附后的标题栏停在滚动口顶 +2px,这 2px 缝隙没有栏体遮挡,滚过的彩色封面从中透出。 * 改为滚动区 padding-top:0 + 首元素 margin-top:2px(margin 随内容一起滚走, * 静止时顶部留白不变,吸附时标题栏与滚动口严丝合缝,杜绝穿透)。 * ② TGA 年度游戏殿堂(参考 steam-friend-manager 1.6.2)——年份时间轴最左新增金色「年度游戏」 * 节点,点击进入殿堂:2014–2025 历届 GOTY 冠军竖版海报墙(年份徽标 + 皇冠数=当年获奖次数 + * 在库标记,非 Steam 平台独占用平台配色占位画);点击任一冠军打开「年度游戏 · {year}」提名弹窗 * (左获奖者竖版海报 + 右提名横版网格,Steam 卡点击开商店页,ESC/遮罩/关闭按钮退出)。 * 数据源 SmallFork/json TGA_winners.json(fastly→cdn→raw 三级回退 + IDB 永久缓存 + 24h 后台刷新)。 * ③ 年度大作卡片交叉标记——命中 TGA 年度游戏冠军的卡片加金色 👑 年度游戏 chip,点击直接开该年提名弹窗。 * * v2.9.7(收藏模块:非 Steam 游戏补真实封面): * ① PS 会免 tab 里没有 steamAppId 的 PS 独占条目(实测数据源 1595 条中 293 条) * 此前只有一块蓝色 PS Logo 占位画、没有任何封面——本版给它们补上 PS Store 真实主视觉。 * 做法参考 steam-friend-manager 1.6.2 的非 Steam 卡(sfd-tga-excl-art + sfd-tga-excl-img): * 平台占位画垫底,商店主视觉图绝对定位盖在其上;图加载失败自动移除图,保住占位画。 * ② 封面来源:PS Store 页面内嵌的 schema.org JSON-LD(script#mfe-jsonld-tags → Product.image), * 实测为 1024×1024 方图,CDN image.api.playstation.com 可直链热链(无需 Referer、无需鉴权)。 * 主区域(zh-hans-hk)缺图时自动换 en-us 再试一次(部分地区未发行/限售会缺 SSR 数据)。 * ③ 抓取层重构:fetchPsStoreName 升级为 fetchPsStoreMeta —— 同一次请求同时产出中文名与封面图 * (此前中文名独立抓页,改后二者共用一页,零额外请求);缓存 key 升到 sglvPsStoreMetaCache_v2 * (中文名 + 封面),v1 旧 key 自动迁移,无需清缓存。 * ④ 抓取限流:PS Store 单页 300KB+,加并发闸门(4 路)+ 同 URL 请求去重;缓存整表落盘改 3s 节流 * (单页 49 张卡原本会放大成 49 次整表序列化写入)。 * ⑤ 三个视图统一补封面:卡片(2:3 海报)/ 封面(460×215 横版)/ 列表(92×43 图标); * 方图焦点上移(object-position: center 20%)保住方图上方的游戏 LOGO 区。 * * v2.9.6(年度大作筛选/边距 + KPI 光斑 + Humble 平铺): * ① 年度大作年份时间轴从"滚动定位"改为"真筛选"——点击年份节点只渲染该年份分块 * (gotyState.yearFilter,再点同一年份或「全部」取消);active 由筛选态决定, * 不再被平滑滚动中途漂移;当前筛选下 0 条的年份节点灰显禁用,杜绝"点了没反应"。 * ② 年度大作列表边距收紧——工具栏行/时间轴行留白、年份块(14px)+分组(12px)叠加空隙、 * 分组 header padding 全部压缩;renderGotyScroll 重渲染后回到顶部,消除顶部空白观感。 * ③ KPI 卡片光斑弱化——主脚本 CSS_KPI 的 ::before(全卡渐变 hover:opacity 1)与共享 CSS 库 * 的 ::before(40x40 圆形 blur 8px)层叠成"左上角一团高斯模糊光斑"遮住标签/图标; * sgc-panel 内覆盖为全卡轻渐变(hover 0.5)+数值去发光+选中仅 accent 描边+hover 阴影收敛。 * ④ Humble 月包顶部缩略图全量平铺——去掉"最多 5 个 + +N 折叠块",8 款游戏直接平铺 * (44px 缩略 + flex-wrap 自动换行),右侧空白不再浪费、无需展开即可看全。 * * v2.9.5(DLC 封面绑定修复 + 状态斜切带移除): * ① DLC 分组视图(renderDlcGrouped)从未调用 bindRestrictedCoverLoaders → * wrapper 永远停在 sglv-img-loading(灰色空块)。改为 appendDlcCardsChunked * 每批 append 后统一绑定(幂等),扁平/分组/任意调用方都覆盖。 * ② 移除受限卡片封面右下角的琥珀/绿色状态斜切带(.sglv-own-flag)—— * 7 列紧凑卡片里贴着封面底边,看起来就是"一块黄色背景";拥有态已由徽章表达。 * * v2.9.4(卡片墙竖版化): * ① 系列分类 / PS 会免 / Epic 赠送的默认卡片视图改为竖版海报(2:3)+ 每行 7 列紧凑网格 * ② unifiedCover 新增 preferVertical:poster 走竖版优先链(library_600x900_2x → * library_600x900 → header 兜底),其余 tab 保持原横向链;binder 通过 * data-cover-prefer-vertical 选择同一条链,避免初始 src 与回退链错位 * ③ 竖版图 object-fit:cover 铺满;横版兜底(markLoaded 打 .sglv-img-wide)走 contain letterbox * ④ 三个视图 pageSize 48 → 49(7×7 整排,不留半排) * * v2.9.3(缓存复用 / 渐进式失效 / 增量刷新): * ① 横版封面统一归一到 header 槽位(markLoaded / API 兜底按 URL 形态写,而不是按容器 kind)—— * 受限/PS/Epic/GOTY/主面板共享同一份横版 good URL,不再各探一次 * ② coverGoodUrl 横版类补 header/capsule 交叉读取;restrictedCoverImg 不再把竖版海报塞进横版容器 * ③ API 兜底负缓存 10min(成功结果本会话有效)—— 失败不再永久拉黑,也不会每次渲染重打接口 * ④ GOTY 持久缓存:先读原始值恢复"已被 180 天容器 TTL 清掉"的旧表,容器 TTL 改 10 年, * 条目失效交给"用一次自愈 + LRU 淘汰",避免整表同时过期后全量重爬 * ⑤ markLoaded 同步写宿主共享缓存(Host.recordPosterGood):收藏视图验证过的封面主面板直接复用 * * v2.1.0(从 sglv-libs-core 剥离 + 收藏模块 UI/封面改造): * ① 从 sglv-libs-core IIFE 剥离为独立 lib, 与 sglv-libs-cover-fallback 同步 * ② seriesCoverImg / seriesCapsuleImg 重写为 data-属性 + 单一 onerror 委托 * (img 创建时无 src, 失败时由 _sglvChainFallback → chainLoad JS 接管, * 取代 v1.x 的 20 URL inline string 链; 链长 7-8 砍掉一半多) * * v2.0.0(大版本,配合主脚本 v2.20.0 架构重构): * ① 恢复独立库形态——v2.11.44-hotfix 起收藏模块被内联进主脚本(受限网络下 * 外部 @require 静默失败导致功能全不可用),内联期主脚本侧演进了两个补丁 * (v2.11.49 捆绑包骨架屏 / v2.11.50 Humble Choice 月包分析 Tab)。 * 本版将 1.9.47 + 两个补丁合并收编为独立库正式版本,主脚本 2.20.0 起 * 恢复 @require 外部加载,主脚本仅保留收藏基本界面(菜单/按钮/桥接/降级)。 * ② 代码本体与主脚本 2.11.51 内联块逐字节一致(除本头部),行为零回归。 * ③ apiVersion 保持 1,CollectionHost 桥接契约不变。 * * ── 历史版本(1.9.x,收编自主脚本内联期/原独立库) ────────── * v1.9.50: Humble Choice 月包分析 Tab(数据源 @resource humbleChoiceData, * KPI + 搜索 + 拥有筛选 + 分页网格;借鉴 steam-friend-manager 1.5.2) * v1.9.49: 捆绑包 Tab 骨架屏(数据异步构建中先出骨架,避免闪"暂无进包数据"空态) * v1.9.47: 全面修复绝版游戏/年度大作/锁区/PS/Epic/DLC/捆绑包翻页失效 + 绝版数据兜底链—— * ① 9 处 Host.renderPagination 调用补传第 8 参数 onJump(delisted/psplus/epic/blocked/goty/dlc×2/bundle, * 主脚本 renderPagination 内部所有按钮(首页/上页/下页/末页/跳页)统一走 goPage()→onJump 唯一触发路径, * 缺失 onJump → 翻页按钮全部静默失效 → 用户看到"只能加载第一页/不能翻页"); * ② 绝版数据兜底链:@resource 同步预热失败(Tampermonkey 大文件 3.5MB 偶发静默失败)→ 异步拉远程源三级回退 * (fastly.jsdelivr → cdn.jsdelivr → raw.githubusercontent) + 24h TTL 缓存跨会话秒开 + 6h 后台节流 * 静默刷新;首次进入 tab 显示加载骨架(避免误判为"无数据"),远程源回调内触发 renderDelistedGamesList() 重渲染; * ③ 工具栏新增"从远程源重新加载"按钮(force 走全链路,30s 兜底还原 spinner 防止失败场景卡死); * ④ delistedState.pageSize 50→48 与其他 tab 保持一致; * ⑤ getFilteredDelistedApps 缓存键加入 ownedIds 集合指纹(前 8 个 appid djb2 哈希 + size), * 同数量不同游戏的 owned 集合变化时 subFilter=owned/missing 筛选结果精确失效(此前仅按 size 粗粒度失效, * 新购买/退款的绝版游戏不展示/错误展示) * v1.9.46: 主题层适配(配合主脚本 v2.11.40 典雅紫/经典蓝双主题)——JS 模板中 6 处内联紫色 * (系列徽章/锁区手动徽章/DLC 提示文字/DLC KPI 边与图标/dlcBadgeStyle 常量)改用 * var(--sglv-accent 及派生 token) 并带紫色 fallback,主题切换时随主脚本主题层 :root 即时变色; * 面板 CSS 类级紫色由主脚本主题层 Part E(html[data-sglv-theme="blue"] 前缀高特异性覆盖)处理,本库 CSS 零改动 * v1.9.44: 封面交叉缓存(按页面需求方向取缓存,杜绝样式格式不匹配的缓存地址直用)—— * ① coverGoodUrl 方向严格读取:所有缓存层(宿主会话 good 缓存 / steamui 精确 URL)均以 * _sgcvUrlMatchesKind 校验方向(poster=竖版 library_600x900 族,capsule/header=横版), * 方向不匹配的条目不再直接返回——poster 缓存曾被横版兜底 URL 污染(v1.9.42 起 API 兜底 * 与链尾 header 加载成功即写入 poster 缓存),竖版视图直用导致裁切错位、参差不齐 * ② 竖版缺失标记 + 横版替代交叉缓存:coverVerticalMissing(poster 缓存横版条目 = * 此前 poster 链已耗尽至横版兜底的会话级结论)+ coverHorizontalFallbackUrl * (仅返回 poster 标记条目——capsule/header 缓存存在 ≠ 竖版资产缺失, * 未确认缺失时交叉读取会跳过竖版链探测直接加载错位横图), * 四个 poster 函数(series/blocked/psplus/epic)标记命中时横版替代直用并 letterbox 显示, * 免去每次渲染重爬整条竖版链;竖版未确认缺失时绝不使用横版(保证竖版优先语义) * ③ 竞速兜底方向门控:_sgcvCoverRace 对 API URL 方向校验,poster kind 拒绝横版劫持 * (API filters=basic 恒返回横版 header_image,劫持会压制链上更深处的竖版资产, * 并把横版写入 poster 缓存造成"有竖版资产的游戏显示横版"的会话级污染) * ④ _sgcvPosterOnloadAttr 统一 poster onload(宽图检测 letterbox + good 记录), * blocked/psplus/epic 海报函数补齐 v1.9.43 只加在 seriesCoverImg 的宽图检测 * v1.9.43: 系列封面方向门控 + API 兜底竞速(修复"竖屏封面显示横板封面、横板封面长时间无法加载")—— * ① 根因 A(竖版显示横图):数据源 poster 字段(steam_vediogame_selected.json)实测 340/340 * 全为横版 header URL(并非 v1.9.30 文档假设的竖版 library_600x900_2x),v1.9.30 起 * seriesCoverImg 将其直接作为竖版 kind 初始 src → 2:3 竖版卡片 object-fit:cover 裁切变形, * 且压制了已有竖版资产游戏正常显示。修复:poster 字段方向门控(_sgcvIsVerticalUrl 判定 * library_600x900 族)——竖版 kind 仅接受竖版 URL,横版 kind 仅接受横版 URL; * 竖版 kind 无可用 poster 时走竖版语言变体链(library_600x900_2x 置顶) * ② 根因 B(横版封面黑屏 ~22s):新游戏(未上市/新上架)商店资产仅存在于 * store_item_assets hash 路径,无 hash 传统链(hero 16 + capsule 20 = 36 URL)全部 404, * 串行爬取约 22s 后才触发 appdetails API 兜底。修复:_sgcvCoverRace 竞速兜底—— * 首个 onerror 即后台拉起 Host.fetchCoverApiUrl(宿主三级缓存 + 并发去重),CDN 链 * 继续走,API 先返回且图片尚未加载成功时直接劫持 src(失败场景 ~22s → ~2s) * ③ seriesCapsuleImg 横版 poster 复用:hero 链首未命中后第 2 跳即命中 poster 预验证 * header URL(460x215 与封面视图容器 aspect-ratio 460/215 完全一致) * ④ 竖版无资产 letterbox:poster kind onload 宽图检测(naturalWidth>naturalHeight 追加 * sglv-img-wide 类)→ object-fit:contain + 渐变底,API 兜底返回的横版 header 完整显示不裁切 * ⑤ 竞速兜底同步接入 blocked/psplus/epic 六个封面函数(老游戏无 library 资产场景同样提速) * v1.9.42: 封面高清增强(竖版 2x 默认 + 横版 hero 高清 2x,参考 sglv-cover-fallback.lib.js v1.2.0)—— * ① 横版 capsule 链增强:coverChainLang 对 capsule kind 头部插入 hero 高清增强链 * (library_hero_2x 3840x1240 → library_hero 1920x620 → 原 capsule_467x181 链 → header 兜底), * hero 高清 2x 成为默认横版封面;_heroPrefixChain 去除 hero 链尾 header(保持 capsule 资产 * 优先级高于 header),_dedupeChain 去重;对 8 个封面函数 + GOTY + 系列封面视图全量生效 * ② 新增 heroEnhancedChain(appid):cover-fallback 可用时复用其 hero 链(含中文语言变体 * library_hero_schinese_2x 置顶);不可用时手工构建同序 4CDN 链,可选依赖缺失不降级 * ③ coverGoodUrl:capsule kind 优先 steamui hero 精确 hash URL(image2x 优先), * 其次宿主 good 缓存,最后本 kind steamui URL * ④ 竖版 poster 链保持 2x 置顶断言(library_600x900_2x 高清竖版为默认:cover-fallback 链 / * Host 链 / 数据源 poster 字段三方一致),新增独立测试 sglv-game-collection.lib.test.js 回归 * v1.9.41: 封面链语言变体增强(配合 sglv-cover-fallback.lib.js v1.2.0)—— * ① 新增模块级 coverChainLang(appid, kind) / coverGoodUrl(appid, kind) 辅助: * SGLVCoverFallback 可用时走其完整链(steamui 精确 hash URL 优先 + * 中文界面下语言变体封面 library_600x900_schinese 等置顶 + 4CDN 交叉回退), * 不可用时原样回退 Host.coverChainUrls(向后兼容,行为与 v1.9.40 一致) * ② v2.8.0 起全部封面函数(seriesCoverImg / seriesCapsuleImg / psplusPosterImg / * psplusCapsuleImg / epicPosterImg / epicCapsuleImg / dlcPosterImg / dlcCapsuleImg) * 已统一改走 unifiedCover + bindRestrictedCoverLoaders——good 缓存查询改为同步读取, * 回退链由 addEventListener 驱动(不再依赖跨上下文 inline onerror), * CDN 链换用语言变体链;内联 onerror 链构建逻辑不变 * ③ gotyCoverImgTag / _bindGotyCoverDelegation 同步换链(GOTY good 缓存保持独立) * ④ 可选依赖、零破坏:cover-fallback 未加载或 kind 不受支持时自动降级原 Host 链 * v1.9.40: 系列分类工具栏更新时间提示移除—— * ① 移除常驻状态文本 #sglv-pub-status("更新: 日期"),该文本为不换行 flex 项, * 会压缩供应商/系列切换按钮(flex:1)导致按钮变形 * ② 刷新结果摘要改为悬浮提示 .sglv-pub-refresh-toast:绝对定位于模式切换条下方, * 不参与 flex 布局,3 秒后自动消失,保留刷新反馈但零布局影响 * ③ 移除 pubState.supplierFetchedAt/seriesFetchedAt 及相关赋值(配合宿主 v2.9.113) * v1.9.39: 系列详情工具栏布局重构—— * ① 修复工具栏操作选项超出面板宽度导致横向滚动条的问题:改用 flex-wrap 布局, * 控件按逻辑分组(完成度 / 拥有筛选 / 排序 / 视图),窄面板自动换行 * ② 拥有状态筛选从下拉菜单改为"已拥有"/"未拥有"两个切换标签按钮, * 未选中任何标签表示查询全部;点击已激活按钮可取消筛选回到全部 * v1.9.38: PS会免刷新无数据根因修复 + 移除手动刷新按钮—— * ① 修复刷新后数据消失:_mergeByAppid 按 appid 合并,但 PS会免条目字段为 * recordId/steamAppId(无 appid),非空状态合并时全部条目被丢弃为空数组, * 且空数组写回永久缓存导致后续加载也空白。上游为全量快照(psplus-data-sync.js * 每日全量镜像),改为远程快照整体替换 state 与缓存,不再增量合并 * ② 移除工具栏刷新按钮(数据变更频率低,无需手动更新),保留 6h 后台节流静默刷新 * ③ 删除 force 刷新相关代码:loadPsplusGames force 分支、_refreshPsplusFromRemote * force 参数/spinner/状态文本、psplusState.refreshResult/showResultUntil、 * #sglv-ps-refresh spinner CSS;renderPsplusRefreshStatus 简化为仅显示更新时间 * v1.9.37: PS会免降级数据源—— * ① 新增 PSPLUS_BACKUP_URLS 三级 CDN 回退链(SmallRob/steam-namespace 镜像, * 由 js_script/psplus-data-sync.js 每日同步自主源 oXnMe/psplus-steam-overlay) * ② _refreshPsplusFromRemote 改为主源 + 降级源多级回退(_tryNextUrl 模式): * 主源失败(网络错误/超时/非2xx/格式无效)时依次尝试 3 个镜像源, * 全部失败才报错并尝试缓存恢复(参照 EPIC_GITHUB_URLS _tryNextGithubSource 写法) * v1.9.35: 系列分类筛选与封面视图优化—— * ① 移除点击进度条筛选逻辑,改为筛选下拉菜单(全部/已拥有/未拥有,默认全部), * 进度条保留为纯视觉收集完成度指示器(不可点击) * v1.9.34: 系列详情工具栏布局重构——工具栏操作选项超出面板宽度导致横向滚动条, * 改用 flex-wrap 布局,控件按逻辑分组(完成度 / 拥有筛选 / 排序 / 视图),窄面板自动换行 * v1.9.30: 系列封面竖版化(数据源 poster 字段作为竖版 kind 初始 src) */ window.SGLVCollection = (function () { /** * HTML 转义助手(v2.42.2 新增)。 * 背景:供应商名 / 系列名来自**远程可改写**的 game-db JSON * (@resource steam-namespace@main/data/game-db-v1.2.json), * 之前直接拼进 innerHTML —— 远程数据一旦被投毒,即可在 Steam 页面上执行任意脚本。 * 本库此前**完全没有**转义助手(其它模块各自有 escHtml,这里补齐)。 */ function sgcEsc(v) { return String(v == null ? '' : v).replace(/[&<>"']/g, (c) => ( { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c] )); } 'use strict'; // ---- 桥接宿主(由 init(ctx) 注入) ---- let Host = null; const apiVersion = 1; // ---- SGLVCore 依赖(sglv-core.lib.js 提供的零业务基础设施;缺失时所有调用走 noop 兜底) ---- // v1.9.1: DLC 渐进式加载复用 makeThrottledProgress / concurrentPool,避免每批数据都触发主线程渲染风暴 const _C = (typeof unsafeWindow !== 'undefined' && unsafeWindow.SGLVCore) || window.SGLVCore || null; const _throttled = _C && typeof _C.makeThrottledProgress === 'function' ? _C.makeThrottledProgress : null; const _StageProgress = _C && _C.StageProgress ? _C.StageProgress : null; // ---- v1.9.41: 封面链语言变体增强(sglv-cover-fallback.lib.js v1.2.0 可选依赖)---- // ---- v1.9.42: 竖版 2x 默认 + 横版 hero 高清 2x 增强 ---- // 惰性解析:cover-fallback 与本库的加载顺序不作假设,每次调用时取 function _coverFb() { try { return (typeof unsafeWindow !== 'undefined' && unsafeWindow.SGLVCoverFallback) || window.SGLVCoverFallback || null; } catch (e) { return null; } } // 中文界面请求语言变体封面(library_600x900_schinese 等),其余界面用默认资产 function coverLang() { return (Host && Host.isZh) ? 'schinese' : null; } // v2.0.0: 4 CDN 前缀(顺序与 sglv-cover-fallback.lib.js v2.0.0 一致:cdn.cloudflare 链首, // 老游戏最稳;新游戏哈希子目录走 store_item_assets/akamai/fastly 兜底) // v1.9.42 用 shared.akamai 优先,新游戏走哈希子目录命中,但老游戏 4-5 次 404 浪费 const _COVER_CDNS = [ 'https://cdn.cloudflare.steamstatic.com/steam/apps/', 'https://shared.akamai.steamstatic.com/store_item_assets/steam/apps/', 'https://cdn.akamai.steamstatic.com/steam/apps/', 'https://shared.fastly.steamstatic.com/store_item_assets/steam/apps/', ]; // v1.9.42: 横版 hero 高清 2x 增强链(library_hero_2x 3840x1240 → library_hero 1920x620) // cover-fallback 可用 → 复用其 hero 链(中文语言变体 library_hero_schinese_2x 置顶 + 2x 先于非 2x + 4CDN + header 兜底); // 不可用 → 手工构建同序链,保证可选依赖缺失时横版增强不降级 function heroEnhancedChain(appid) { try { const fb = _coverFb(); if (fb && typeof fb.buildFullChain === 'function' && Array.isArray(fb.KINDS) && fb.KINDS.indexOf('hero') >= 0) { const chain = fb.buildFullChain(appid, 'hero', coverLang()); if (Array.isArray(chain) && chain.length) return chain; } } catch (e) { /* fallthrough */ } const lang = coverLang(); const files = []; if (lang) files.push('library_hero_' + lang + '_2x.jpg', 'library_hero_' + lang + '.jpg'); files.push('library_hero_2x.jpg', 'library_hero.jpg'); const out = []; for (const f of files) for (const cdn of _COVER_CDNS) out.push(cdn + appid + '/' + f); return out; } // v1.9.42: 链去重(保留首次出现顺序) function _dedupeChain(chain) { const seen = new Set(); const out = []; for (const u of chain) if (!seen.has(u)) { seen.add(u); out.push(u); } return out; } // v1.9.42: hero 前缀链去除尾部 header 兜底(header 统一留在整链末尾, // 保证 capsule_467x181 等横版资产的优先级高于 header) function _heroPrefixChain(appid) { return heroEnhancedChain(appid).filter(u => u.slice(-11) !== '/header.jpg'); } // 封面完整回退链:cover-fallback 链(steamui 精确 URL 语境 + 语言变体置顶 + 4CDN) // → 降级 Host.coverChainUrls(v1.9.40 原行为) // v1.9.42: ① poster 竖版链保持 2x 置顶(library_600x900_2x 高清竖版为默认: // cover-fallback 链 / Host 链均保证 2x 先于 1x,数据源 poster 字段同为 2x URL) // ② capsule 横版链增强:头部插入 hero 高清 2x 增强链(library_hero_2x 为默认横版封面), // 原 capsule_467x181 链降级为 hero 缺失时的回退 function coverChainLang(appid, kind) { try { const fb = _coverFb(); if (fb && typeof fb.buildFullChain === 'function' && Array.isArray(fb.KINDS) && fb.KINDS.indexOf(kind) >= 0) { let chain = fb.buildFullChain(appid, kind, coverLang()); if (kind === 'capsule') chain = _heroPrefixChain(appid).concat(chain); if (Array.isArray(chain) && chain.length) return _dedupeChain(chain); } } catch (e) { /* fallthrough */ } const host = Host.coverChainUrls(appid, kind); return kind === 'capsule' ? _dedupeChain(_heroPrefixChain(appid).concat(host)) : host; } // good 缓存:v1.9.42 起 capsule 横版优先 steamui hero 精确 hash URL(image2x 优先,即 hero 高清 2x), // 其次宿主会话级缓存,最后 cover-fallback 的本 kind steamui 精确 hash URL(同步缓存命中) // v1.9.44: 交叉缓存方向门控——所有读取均校验 URL 方向与 kind 匹配(poster=竖版,其余=横版), // 方向不匹配的缓存条目(poster 缓存被横版兜底写入、capsule 缓存混入竖版)不再直接返回, // 防止竖版视图直用横版缓存地址导致裁切错位(或反向);横版替代走 coverHorizontalFallbackUrl function _sgcvUrlMatchesKind(u, kind) { if (typeof u !== 'string' || !u) return false; const v = _sgcvIsVerticalUrl(u); return (kind === 'poster') ? v : !v; } function coverGoodUrl(appid, kind) { if (kind === 'capsule') { try { const fb = _coverFb(); if (fb && typeof fb.getSteamuiGoodUrl === 'function') { const heroUrl = fb.getSteamuiGoodUrl(appid, 'hero', coverLang()); if (heroUrl && _sgcvUrlMatchesKind(heroUrl, kind)) return heroUrl; } } catch (e) { /* fallthrough */ } } const good = Host.getPosterGood(appid, kind); if (good && _sgcvUrlMatchesKind(good, kind)) return good; // v2.9.3: 横版视图共享 header 槽位 —— 受限/PS/Epic/GOTY/主面板验证过的横版 URL // 统一归一到 header(markLoaded / API 兜底也是这么写的),这里补上交叉读取, // 避免同一张 header.jpg 在每个视图各探一次整链 if (kind !== 'poster') { const alts = (kind === 'header') ? ['capsule'] : ['header', 'capsule']; for (const ak of alts) { let u = ''; try { u = Host.getPosterGood(appid, ak) || ''; } catch (e) { /* ignore */ } if (u && _sgcvUrlMatchesKind(u, kind)) return u; } } try { const fb = _coverFb(); if (fb && typeof fb.getSteamuiGoodUrl === 'function') { const u = fb.getSteamuiGoodUrl(appid, kind, coverLang()) || ''; if (u && _sgcvUrlMatchesKind(u, kind)) return u; } } catch (e) { /* fallthrough */ } // v2.0.0: 不再 fb.getCoverUrl 兜底(会污染"已验证好 URL"语义,且对 capsule kind // 返回 capsule_467x181.jpg 而非 hero 链首,让 seriesCapsuleImg 错失 hero 增强) // 调用方应自己取 coverChainLang(appid, kind)[0] 作为初始 src return ''; } // v1.9.44: 竖版缺失判定——poster 缓存存在横版条目 = 此前 poster 链已耗尽至横版兜底 // (poster 链竖版优先,poster 上下文加载出横版 ⇒ 竖版资产确认缺失的会话级标记) function coverVerticalMissing(appid) { try { const p = Host.getPosterGood(appid, 'poster'); return !!(p && !_sgcvIsVerticalUrl(p)); } catch (e) { return false; } } // v1.9.44: 横版替代交叉缓存——仅竖版确认缺失(poster 缓存横版标记条目)时返回该标记条目 // (链尾 header 兜底,2.14:1 最贴竖版容器 letterbox),未确认缺失时一律为空: // capsule/header 缓存存在 ≠ 竖版资产缺失(横竖是各自独立文件),未确认即交叉读取 // 会令竖版视图跳过竖版链探测、直接加载错位横图 function coverHorizontalFallbackUrl(appid) { try { const p = Host.getPosterGood(appid, 'poster'); return (p && !_sgcvIsVerticalUrl(p)) ? p : ''; } catch (e) { return ''; } } // ---- v1.9.43: 封面方向门控 + API 兜底竞速 ---- // 竖版资产判定:library_600x900 族(含语言/2x 变体);header/capsule/hero/page_bg 均为横版。 // 数据源 poster 字段实测全为横版 header URL,v1.9.30-1.9.42 将其当作竖版初始 src // 导致 2:3 竖版卡片显示横图裁切变形 function _sgcvIsVerticalUrl(u) { return typeof u === 'string' && u.indexOf('library_600x900') >= 0; } // API 兜底竞速:首个 onerror 即后台拉起 appdetails(Host.fetchCoverApiUrl 三级缓存 + // 并发去重),CDN 链继续串行走;API 先返回且图片尚未加载成功时直接劫持 src。 // 新游戏(资产仅存在于 hash 路径、无 hash 链全 404)从 ~36 次串行 404(约 22s) // 缩短到 ~2-3 次请求;老游戏链首即命中,竞速不触发任何请求 function _sgcvCoverRaceImpl(img, appid, kind) { if (!img || img._sgcvRace) return; img._sgcvRace = 1; try { if (!Host || typeof Host.fetchCoverApiUrl !== 'function') return; Host.fetchCoverApiUrl(appid, kind).then(function (url) { if (!url || !img.isConnected || img.src === url) return; // v1.9.44: 方向门控——API URL 与 kind 方向不匹配时不劫持。 // poster kind 的 API 兜底(filters=basic)恒为横版 header_image:劫持会压制 // 链上更深处仍可能命中的竖版资产,并把横版写入 poster 缓存造成 // "有竖版资产的游戏显示横版"的会话级污染;横版兜底由链尾 header + _sglvPosterFallback 承担 if (!_sgcvUrlMatchesKind(url, kind)) return; // CDN 链已加载成功(onload 已加 sglv-img-loaded 类)则不干预 if (img.classList.contains('sglv-img-loaded') || (img.complete && img.naturalWidth > 0)) return; // API URL 失败 → 占位(先替换 onerror,防止链式 handler 死循环) img.onerror = function () { img.onerror = null; _sgcvToPlaceholder(img); }; img.src = url; }).catch(function () { /* API 失败:CDN 链继续走,不干预 */ }); } catch (e) { /* Host 契约缺失:降级为纯链行走 */ } } // 竞速 URL 加载失败的占位(与宿主 _posterImgToPlaceholder 同款,仅替换 img 节点保留徽章浮层) function _sgcvToPlaceholder(img) { if (!img || !img.parentElement) return; const holder = document.createElement('div'); holder.className = img.className; holder.style.cssText = 'display:flex;align-items:center;justify-content:center;color:#5a6a7a;font-size:11px'; holder.textContent = (Host && Host.isZh) ? '无图片' : 'No Image'; img.parentElement.replaceChild(holder, img); } // 挂载到页面上下文(内联 onerror 属性在页面上下文执行,与宿主 _sglvPosterFallback 同机制) try { const _sgcvPageWin = (typeof unsafeWindow !== 'undefined') ? unsafeWindow : window; _sgcvPageWin._sgcvCoverRace = _sgcvCoverRaceImpl; } catch (e) { /* ignore */ } // v1.9.44: poster kind 通用 onload 属性——宽图检测(横版兜底/替代 letterbox 显示)+ good 记录 function _sgcvPosterOnloadAttr(appid) { return 'this.classList.add(\'sglv-img-loaded\');' + 'if(this.naturalWidth>this.naturalHeight)this.classList.add(\'sglv-img-wide\');' + '_sglvRecordPosterGood(\'' + appid + '\',this.src,\'poster\');'; } // v1.9.44: 竖版缺失标记快速路径 HTML——竖版确认缺失后横版替代直用(交叉缓存), // 免去每次渲染重爬整条竖版链(8 个 CDN 404 + header 兜底) function _sgcvHorizontalFallbackImgHtml(appid, name, cls, fbFn) { const url = coverHorizontalFallbackUrl(appid); if (!url) return ''; return '' + name +
            ''; } // v2.9.22: sgc-panel 紧凑 CSS(仿主面板 v2.9.22 页头风格 + 品牌图标 + 拖动 + 骨架占位) const SGC_PANEL_CSS = ` /* === 紧凑 header:去除"游戏收藏"标题,保留左侧 Steam 图标 + 中间 tab-bar + 右侧关闭 === */ .sgc-panel > .sglv-header { padding: 8px 14px !important; gap: 12px; cursor: move; /* header 作为拖动手柄 */ user-select: none; background: linear-gradient(135deg, rgba(27, 40, 56, 0.95) 0%, rgba(42, 71, 94, 0.95) 100%) !important; border-bottom: 1px solid rgba(102, 192, 244, 0.18) !important; } .sgc-panel > .sglv-header h2 { display: none !important; } .sgc-panel > .sglv-header > .sglv-tab-bar { display: flex; align-items: center; gap: 2px; flex: 1; min-width: 0; overflow-x: auto; scrollbar-width: none; } .sgc-panel > .sglv-header > .sglv-tab-bar::-webkit-scrollbar { display: none; } /* === 保留最左侧 Steam 图标作为品牌标识 === */ .sglv-header-brand { width: 24px; height: 24px; border-radius: 6px; flex-shrink: 0; display: inline-flex; align-items: center; justify-content: center; background: linear-gradient(135deg, rgba(102, 192, 244, 0.18), rgba(139, 92, 246, 0.18)); border: 1px solid rgba(102, 192, 244, 0.25); color: #66c0f4; box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.06); transition: transform 0.2s, box-shadow 0.2s; } .sglv-header-brand:hover { transform: rotate(-8deg) scale(1.05); box-shadow: 0 2px 8px rgba(102, 192, 244, 0.35), inset 0 1px 0 rgba(255, 255, 255, 0.1); } .sglv-header-brand img { width: 14px; height: 14px; display: block; border-radius: 2px; } /* === tab 按钮紧凑化(覆盖 shared css 的 flex:1 + 大 padding) === */ .sgc-panel .sglv-tab { flex: 0 0 auto !important; padding: 5px 12px !important; font-size: 12.5px !important; font-weight: 600 !important; border-radius: 8px !important; border: 1px solid transparent !important; background: transparent !important; color: #94a3b8 !important; white-space: nowrap !important; gap: 5px !important; transition: background 0.15s, color 0.15s, border-color 0.15s, transform 0.15s !important; } .sgc-panel .sglv-tab:hover { color: #e2e8f0 !important; background: rgba(255, 255, 255, 0.06) !important; } .sgc-panel .sglv-tab.active { color: #fff !important; background: rgba(102, 192, 244, 0.22) !important; border-color: rgba(102, 192, 244, 0.4) !important; box-shadow: 0 0 0 1px rgba(102, 192, 244, 0.15) inset, 0 1px 4px rgba(102, 192, 244, 0.18) !important; } .sgc-panel .sglv-tab svg { width: 14px; height: 14px; flex-shrink: 0; } /* === 隐藏原 .sglv-tabs 单独行(兼容老代码,防止双重显示) === */ .sgc-panel .sglv-tabs { display: none !important; } /* === 关闭按钮位置 === */ .sgc-panel > .sglv-header > .sglv-header-actions { gap: 6px; flex-shrink: 0; margin-left: auto; } /* === v2.9.22: Epic免费标签 → 封面右下角(card + cover 两种视图) === */ .sglv-card-img-wrap > .sglv-epic-free-badge, .sglv-wl-cover-img-wrap > .sglv-epic-free-badge { position: absolute !important; bottom: 6px !important; right: 6px !important; top: auto !important; left: auto !important; margin-top: 0 !important; background: #ff69b4 !important; color: #fff !important; padding: 2px 6px !important; border-radius: 3px !important; font-size: 10px !important; font-weight: 700 !important; z-index: 2 !important; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.35) !important; backdrop-filter: blur(4px) !important; -webkit-backdrop-filter: blur(4px) !important; } /* === v2.9.22: GotY"年度大作"标签 → 封面右下角(card + cover)== 风格与 Epic免费一致 === */ .sglv-card-img-wrap > .sglv-goty-goty-badge, .sglv-wl-cover-img-wrap > .sglv-goty-goty-badge { position: absolute !important; bottom: 6px !important; right: 6px !important; top: auto !important; left: auto !important; margin-top: 0 !important; background: linear-gradient(135deg, #f59e0b, #ef4444) !important; color: #fff !important; padding: 2px 6px !important; border-radius: 3px !important; font-size: 10px !important; font-weight: 700 !important; z-index: 2 !important; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.35) !important; backdrop-filter: blur(4px) !important; -webkit-backdrop-filter: blur(4px) !important; } /* === v2.9.22: cover 视图下方信息行统一间距(Epic / Delisted / GotY 一致) === */ .sglv-wl-cover-body .sglv-epic-owned-row, .sglv-wl-cover-body .sglv-blocked-owned-row, .sglv-wl-cover-body .sglv-goty-owned-row { margin-top: 2px; gap: 4px; } /* === v2.9.22: 供应商列表视图封面列 === */ .sglv-pub-list-col.cover { padding-right: 8px; } .sglv-pub-list-cover { width: 80px; height: 36px; object-fit: cover; border-radius: 4px; display: block; background: rgba(255, 255, 255, 0.05); } /* === v1.9.16: 供应商/系列游戏 genres 类型标签(可选字段,无 genres 时不渲染) === */ .sglv-pub-genre-tags { display: inline-flex; gap: 3px; margin-left: 6px; vertical-align: 1px; flex-wrap: wrap; } .sglv-pub-genre-tag { font-size: 10px; line-height: 1; padding: 2px 5px; border-radius: 3px; background: rgba(102, 192, 244, 0.12); color: #9ecfea; white-space: nowrap; } .sglv-card-genre-row { display: flex; gap: 3px; flex-wrap: wrap; margin-top: 3px; } /* === v2.9.22: GotY 状态行紧凑布局(owned badge + 🕐 发售日期同行) === */ .sglv-goty-status-row { display: flex !important; align-items: center !important; gap: 6px !important; flex-wrap: wrap !important; margin-top: 4px !important; min-height: 18px !important; } .sglv-goty-status-row .sglv-card-badge { display: inline-flex !important; align-items: center !important; font-size: 10px !important; padding: 2px 7px !important; margin-top: 0 !important; flex-shrink: 0 !important; } .sglv-goty-date { display: inline-flex !important; align-items: center !important; gap: 3px !important; font-size: 10px !important; color: var(--sglv-text-secondary, #94a3b8) !important; font-variant-numeric: tabular-nums !important; margin-left: auto !important; white-space: nowrap !important; } /* v1.0.4: 发售倒计时徽章(参考 friend-manager sfd-stress-featured-countdown) 三态:future(将发售,亮橙)/ today(今日,amber 强调+外发光)/ past(已发售,暗灰) */ .sglv-goty-countdown { display: inline-flex !important; align-items: center !important; gap: 2px !important; margin-left: 4px !important; padding: 1px 6px !important; border-radius: 8px !important; font-size: 9.5px !important; line-height: 1.2 !important; font-variant-numeric: tabular-nums !important; transition: all .18s var(--sglv-transition, ease) !important; } .sglv-goty-countdown-days { font-weight: 800 !important; font-size: 11px !important; letter-spacing: -.3px !important; } .sglv-goty-countdown-lbl { opacity: .85 !important; font-weight: 500 !important; } .sglv-goty-countdown--future { background: linear-gradient(135deg, rgba(245, 158, 11, 0.18), rgba(255, 159, 67, 0.10)) !important; border: 1px solid rgba(245, 158, 11, 0.4) !important; color: #f59e0b !important; box-shadow: 0 0 6px rgba(245, 158, 11, 0.18) !important; } .sglv-goty-countdown--future .sglv-goty-countdown-days { color: #fbbf24 !important; } .sglv-goty-countdown--today { background: linear-gradient(135deg, rgba(34, 197, 94, 0.22), rgba(74, 222, 128, 0.14)) !important; border: 1px solid rgba(34, 197, 94, 0.5) !important; color: #22c55e !important; box-shadow: 0 0 8px rgba(34, 197, 94, 0.3) !important; animation: sglv-goty-today-pulse 1.8s ease-in-out infinite !important; } .sglv-goty-countdown--today .sglv-goty-countdown-days { color: #4ade80 !important; } @keyframes sglv-goty-today-pulse { 0%, 100% { box-shadow: 0 0 8px rgba(34, 197, 94, 0.3); } 50% { box-shadow: 0 0 14px rgba(34, 197, 94, 0.55); } } .sglv-goty-countdown--past { background: rgba(148, 163, 184, 0.08) !important; border: 1px solid rgba(148, 163, 184, 0.18) !important; color: var(--sglv-text-muted, #64748b) !important; } .sglv-goty-countdown--past .sglv-goty-countdown-days { color: var(--sglv-text-muted, #64748b) !important; } .sglv-goty-date .sglv-goty-clock { width: 11px !important; height: 11px !important; display: inline-flex !important; align-items: center !important; justify-content: center !important; opacity: 0.6 !important; flex-shrink: 0 !important; } .sglv-goty-date .sglv-goty-clock svg { width: 11px !important; height: 11px !important; } /* list 视图中的 goty-date 样式(不要 right-push,跟其他 meta 元素 inline) */ .sglv-list-meta .sglv-goty-date { margin-left: 0 !important; gap: 3px !important; } /* === v2.x: GotY 时光机 —— 年份时间轴 + 分组 + 焦点卡 + 网格(参考 steam-friend-manager sfd-stress-*)=== */ /* v2.x: GotY 顶部紧凑 —— KPI 卡片覆盖(只影响 goty,不污染其他 tab 共享的 .sglv-trend-kpi-card) */ #sglv-goty-kpi .sglv-trend-kpi-row { gap: 6px !important; margin: 4px 0 2px !important; } #sglv-goty-kpi .sglv-trend-kpi-card { padding: 6px 10px !important; min-width: 0 !important; } #sglv-goty-kpi .sglv-trend-kpi-header { margin-bottom: 2px !important; gap: 4px !important; } #sglv-goty-kpi .sglv-trend-kpi-value { font-size: 18px !important; line-height: 1.1 !important; } #sglv-goty-kpi .sglv-trend-kpi-label { font-size: 11px !important; } #sglv-goty-kpi .sglv-trend-kpi-sub { font-size: 10px !important; margin-top: 1px !important; } #sglv-goty-kpi .sglv-trend-kpi-icon { font-size: 13px !important; } /* 年份时间轴:渐变主线 + 发光年份节点,点击切换年份(显示/隐藏对应年份块) */ .sglv-goty-timeline { position: relative; display: flex; align-items: flex-start; padding: 6px 20px 2px; margin: 0 6px 4px; flex: none; gap: 0; justify-content: flex-start; overflow-x: auto; overflow-y: hidden; scrollbar-width: thin; } .sglv-goty-timeline::-webkit-scrollbar { height: 4px; } .sglv-goty-timeline::-webkit-scrollbar-thumb { background: rgba(102, 192, 244, 0.2); border-radius: 2px; } .sglv-goty-tl-line { position: absolute; top: 10px; left: 20px; right: 20px; height: 2px; background: linear-gradient(90deg, transparent, #06cfbe 12%, #66c0f4 50%, #a78bfa 88%, transparent); opacity: 0.7; pointer-events: none; } .sglv-goty-tl-node { position: relative; display: flex; flex-direction: column; align-items: center; gap: 2px; background: none; border: none; cursor: pointer; padding: 0 6px; font-family: inherit; color: inherit; flex-shrink: 0; } .sglv-goty-tl-node:hover .sglv-goty-tl-dot { transform: scale(1.4); border-color: #66c0f4; box-shadow: 0 0 12px rgba(102, 192, 244, 0.8); } .sglv-goty-tl-node.sglv-goty-tl-active .sglv-goty-tl-dot { background: #66c0f4; border-color: #66c0f4; box-shadow: 0 0 14px rgba(102, 192, 244, 0.95), 0 0 4px rgba(255, 255, 255, 0.6); } .sglv-goty-tl-dot { width: 7px; height: 7px; border-radius: 50%; background: #0f172a; border: 2px solid rgba(102, 192, 244, 0.55); transition: all 0.2s; box-shadow: 0 0 6px rgba(102, 192, 244, 0.35); } .sglv-goty-tl-year { font-size: 10px; font-weight: 700; color: #64748b; letter-spacing: 0.5px; transition: color 0.2s, text-shadow 0.2s; white-space: nowrap; } .sglv-goty-tl-node:hover .sglv-goty-tl-year { color: #9fd0f5; } .sglv-goty-tl-node.sglv-goty-tl-active .sglv-goty-tl-year { color: #66c0f4; text-shadow: 0 0 10px rgba(102, 192, 244, 0.7); } .sglv-goty-tl-count { font-size: 8px; color: #94a3b8; font-weight: 600; line-height: 1; } .sglv-goty-tl-node.sglv-goty-tl-active .sglv-goty-tl-count { color: #66c0f4; } /* 年份分块容器(可滚动) */ .sglv-goty-scroll { flex: 1; overflow-y: auto; overflow-x: hidden; min-height: 0; padding-right: 2px; } .sglv-goty-year-block { margin-bottom: 14px; } /* 分组(未发售 / 已发售)sticky header */ .sglv-goty-group { margin-bottom: 12px; } .sglv-goty-group-header { display: flex; align-items: center; gap: 10px; padding: 8px 12px; background: #1a2233; border-radius: 8px; margin-bottom: 8px; position: sticky; top: 0; z-index: 10; border: 1px solid rgba(102, 192, 244, 0.12); cursor: pointer; user-select: none; transition: background 0.15s; } .sglv-goty-group-header:hover { background: #1e2940; } .sglv-goty-group-caret { width: 0; height: 0; border-left: 5px solid currentColor; border-top: 4px solid transparent; border-bottom: 4px solid transparent; color: #94a3b8; transition: transform 0.2s; flex-shrink: 0; } .sglv-goty-group-header.sglv-goty-group-collapsed .sglv-goty-group-caret { transform: rotate(-90deg); } .sglv-goty-group-title { font-size: 14px; font-weight: 700; color: #f8fafc; flex-shrink: 0; } .sglv-goty-group-count { font-size: 12px; color: #94a3b8; flex-shrink: 0; } .sglv-goty-group-bar { flex: 1; height: 8px; background: #0f172a; border-radius: 4px; overflow: hidden; min-width: 60px; } .sglv-goty-group-bar-fill { height: 100%; background: linear-gradient(90deg, #4caf50, #66c0f4); transition: width 0.3s ease; } .sglv-goty-group-pct { font-size: 12px; font-weight: 600; color: #94a3b8; flex-shrink: 0; min-width: 40px; text-align: right; } .sglv-goty-group-body { display: block; } .sglv-goty-group-header.sglv-goty-group-collapsed + .sglv-goty-group-body { display: none; } /* 焦点大卡(未发售分组前 1-2 个,宽海报贴边) */ .sglv-goty-featured-wrap { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 10px; } .sglv-goty-featured { display: flex; align-items: center; gap: 0; border-radius: 10px; overflow: hidden; background: linear-gradient(135deg, rgba(245, 158, 11, 0.08), rgba(255, 159, 67, 0.04)); border: 1px solid rgba(245, 158, 11, 0.3); cursor: pointer; transition: transform 0.15s, border-color 0.2s, box-shadow 0.2s; padding: 0 10px 0 0; } .sglv-goty-featured:hover { transform: translateY(-2px); border-color: rgba(245, 158, 11, 0.55); box-shadow: 0 6px 18px rgba(0, 0, 0, 0.35); } .sglv-goty-featured.owned { border-color: rgba(76, 175, 80, 0.4); background: linear-gradient(135deg, rgba(76, 175, 80, 0.08), rgba(102, 187, 106, 0.04)); } .sglv-goty-featured-poster { width: 190px; aspect-ratio: 460/215; object-fit: cover; display: block; flex-shrink: 0; border-radius: 0; } .sglv-goty-featured-info { min-width: 0; display: flex; flex-direction: column; gap: 4px; padding: 10px 14px 10px 12px; flex: 1; } .sglv-goty-featured-badge { display: inline-block; align-self: flex-start; font-size: 11px; font-weight: 700; color: #f59e0b; background: rgba(245, 158, 11, 0.15); border: 1px solid rgba(245, 158, 11, 0.3); padding: 1px 8px; border-radius: 4px; line-height: 1.4; } .sglv-goty-featured.owned .sglv-goty-featured-badge { color: #66bb6a; background: rgba(102, 187, 106, 0.2); border-color: rgba(102, 187, 106, 0.4); } .sglv-goty-featured-name { font-size: 15px; font-weight: 700; color: #f8fafc; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; line-height: 1.3; } .sglv-goty-featured-date { font-size: 12px; color: #94a3b8; } .sglv-goty-featured-countdown { display: flex; flex-direction: column; align-items: center; justify-content: center; flex-shrink: 0; padding: 0 4px; min-width: 64px; } .sglv-goty-featured-days { font-size: 26px; font-weight: 800; color: #ff9f43; line-height: 1; } .sglv-goty-featured.owned .sglv-goty-featured-days { color: #66bb6a; } .sglv-goty-featured-days-lbl { font-size: 10px; color: #f59e0b; margin-top: 3px; white-space: nowrap; text-transform: uppercase; letter-spacing: 0.5px; } .sglv-goty-featured.owned .sglv-goty-featured-days-lbl { color: #66bb6a; } /* 网格 5 列(共用 card / cover / list 三种视图) */ .sglv-goty-grid { display: grid; grid-template-columns: repeat(6, 1fr); gap: 6px; } @media (max-width: 1100px) { .sglv-goty-grid { grid-template-columns: repeat(5, 1fr); } } @media (max-width: 800px) { .sglv-goty-grid { grid-template-columns: repeat(4, 1fr); } } .sglv-goty-card { display: flex; flex-direction: column; border-radius: 9px; background: rgba(15, 23, 42, 0.5); border: 1px solid rgba(102, 192, 244, 0.18); overflow: hidden; cursor: pointer; transition: border-color 0.2s, transform 0.15s, opacity 0.2s, box-shadow 0.2s; } .sglv-goty-card:hover { border-color: rgba(102, 192, 244, 0.55); transform: translateY(-2px); box-shadow: 0 6px 18px rgba(0, 0, 0, 0.35); } .sglv-goty-card-img { width: 100%; aspect-ratio: 2/3; object-fit: cover; display: block; background: #0f172a; } .sglv-goty-card-img-wrap { position: relative; } .sglv-goty-card-body { padding: 4px 6px 5px; display: flex; flex-direction: column; gap: 2px; } .sglv-goty-card-name { font-size: 11px; font-weight: 600; color: #f1f5f9; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; line-height: 1.25; } .sglv-goty-card-meta { display: flex; align-items: center; gap: 4px; font-size: 10px; color: #94a3b8; line-height: 1.2; } .sglv-goty-card-owned { display: inline-flex; align-items: center; gap: 2px; font-size: 9px; font-weight: 700; color: #66bb6a; background: rgba(102, 187, 106, 0.18); border: 1px solid rgba(102, 187, 106, 0.35); padding: 1px 5px; border-radius: 3px; line-height: 1.3; } .sglv-goty-card-not-owned { display: inline-flex; align-items: center; font-size: 9px; font-weight: 600; color: #94a3b8; background: rgba(148, 163, 184, 0.1); border: 1px solid rgba(148, 163, 184, 0.18); padding: 1px 5px; border-radius: 3px; line-height: 1.3; } .sglv-goty-card-countdown { font-size: 9.5px; font-weight: 700; line-height: 1.3; } .sglv-goty-card-countdown.future { color: #f59e0b; } .sglv-goty-card-countdown.today { color: #66c0f4; } .sglv-goty-card-countdown.past { color: #64748b; } /* list 视图(行项) */ .sglv-goty-list-view { display: flex; flex-direction: column; gap: 4px; } .sglv-goty-list-item { display: flex; align-items: center; gap: 10px; padding: 6px 8px; border-radius: 6px; background: rgba(15, 23, 42, 0.4); border: 1px solid rgba(102, 192, 244, 0.12); cursor: pointer; transition: background 0.15s, border-color 0.15s; } .sglv-goty-list-item:hover { background: rgba(15, 23, 42, 0.7); border-color: rgba(102, 192, 244, 0.35); } .sglv-goty-list-icon { width: 60px; height: 30px; object-fit: cover; border-radius: 4px; flex-shrink: 0; } .sglv-goty-list-info { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; } .sglv-goty-list-name { font-size: 13px; font-weight: 600; color: #f1f5f9; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .sglv-goty-list-meta { display: flex; align-items: center; gap: 6px; font-size: 11px; color: #94a3b8; } /* 工具条 + 顶部 chip 行(回归一行 chip 风格,与 sglv 主色一致) */ .sglv-goty-toolbar-row { display: flex; align-items: center; gap: 6px; padding: 4px 8px 6px; flex-wrap: wrap; } .sglv-goty-toolbar-row .sglv-search { flex: 1; min-width: 120px; } .sglv-goty-empty { text-align: center; padding: 40px 16px; color: #94a3b8; font-size: 13px; } /* === v2.9.22: PS会免封面视图 — tier-badge 绝对定位到 cover 视图封面右上角 === */ /* shared CSS 的 .sglv-card-img-wrap .sglv-ps-tier-badge 定位只对 card 视图生效; cover 视图用 .sglv-wl-cover-img-wrap,需要独立覆盖。 */ .sglv-wl-cover-img-wrap > .sglv-ps-tier-badge { position: absolute !important; top: 6px !important; right: 6px !important; z-index: 2 !important; backdrop-filter: blur(4px) !important; -webkit-backdrop-filter: blur(4px) !important; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.35) !important; } /* === v2.9.22: PS会免 cover 视图 — 信息行紧凑到 3 行内 === */ /* 状态徽章 + 在库徽章合并到同一行(左右排列),月份/版本单独一行 */ .sglv-wl-cover-body .sglv-ps-status-row { display: flex !important; align-items: center !important; gap: 5px !important; flex-wrap: wrap !important; margin-top: 2px !important; } .sglv-wl-cover-body .sglv-ps-status-row .sglv-card-badge { display: inline-flex !important; align-items: center !important; font-size: 10px !important; padding: 2px 7px !important; margin-top: 0 !important; } /* 月份 + 版本 meta 行紧凑 */ .sglv-wl-cover-body .sglv-ps-meta-row { display: flex !important; align-items: center !important; gap: 6px !important; flex-wrap: wrap !important; font-size: 10px !important; color: var(--sglv-text-secondary) !important; } .sglv-wl-cover-body .sglv-ps-meta-row .sglv-ps-month-item { display: inline-flex !important; align-items: center !important; gap: 3px !important; } .sglv-wl-cover-body .sglv-ps-meta-row .sglv-ps-month-item .sglv-ps-clock { width: 11px !important; height: 11px !important; display: inline-flex !important; align-items: center !important; opacity: 0.65 !important; } .sglv-wl-cover-body .sglv-ps-meta-row .sglv-ps-month-item .sglv-ps-clock svg { width: 11px !important; height: 11px !important; } .sglv-wl-cover-body .sglv-ps-meta-row .sglv-ps-versions { display: inline-flex !important; gap: 3px !important; } .sglv-wl-cover-body .sglv-ps-meta-row .sglv-ps-versions span { font-size: 9px !important; padding: 1px 4px !important; border-radius: 3px !important; background: rgba(255, 255, 255, 0.08) !important; border: 1px solid rgba(255, 255, 255, 0.15) !important; } /* === v2.9.22: 年度大作 chip 强化 — 默认全部展开,active 更明显 === */ .sgc-panel .sglv-goty-year-bar { padding: 8px 12px !important; gap: 6px !important; background: linear-gradient(180deg, rgba(139, 92, 246, 0.08), transparent) !important; border-bottom: 1px solid rgba(139, 92, 246, 0.18) !important; } .sgc-panel .sglv-goty-year-chip { padding: 4px 12px !important; font-size: 12px !important; } .sgc-panel .sglv-goty-year-chip.active { background: linear-gradient(135deg, rgba(139, 92, 246, 0.4), rgba(59, 130, 246, 0.25)) !important; color: #fff !important; border-color: rgba(139, 92, 246, 0.6) !important; box-shadow: 0 0 12px rgba(139, 92, 246, 0.35) !important; } /* === v2.9.22: PS / Epic 占位封面 logo 尺寸(适配新版 viewBox 122.88x95.18 和 100x100) === */ .sglv-ps-cover-placeholder .sglv-ps-logo { width: 72px !important; height: 56px !important; opacity: 0.85 !important; color: #fff !important; flex-shrink: 0 !important; filter: drop-shadow(0 2px 6px rgba(0, 0, 0, 0.35)); } .sglv-ps-cover-placeholder .sglv-ps-logo svg { width: 100% !important; height: 100% !important; display: block; } /* v2.9.9: PS 独占占位画居中 + 名称显示优化 —— ① 占位画改绝对定位铺满图片盒(aspect-ratio 盒内 height:100% 的解析差异不再影响它), flex 双向居中,PS Logo + 名称组稳定落在正中;z-index:0 让真实封面(z-index:1)仍能盖住它。 ② 名称降为居中、两行省略的小字说明(不再是挤占视觉中心的三行大字),与正文异步官方名同源。 */ .sgc-panel .sglv-card-img-wrap > .sglv-ps-cover-placeholder, .sgc-panel .sglv-wl-cover-img-wrap > .sglv-ps-cover-placeholder { position: absolute !important; inset: 0 !important; z-index: 0 !important; justify-content: center !important; align-items: center !important; gap: 6px !important; padding: 10px !important; } .sgc-panel .sglv-ps-cover-placeholder .sglv-ps-cover-name { max-width: 88% !important; font-size: 10px !important; font-weight: 600 !important; line-height: 1.3 !important; letter-spacing: 0.2px !important; -webkit-line-clamp: 2 !important; opacity: 0.92 !important; } /* Epic 占位容器:覆盖 PS 的蓝色渐变,改为深色盾形风格 */ .sglv-epic-cover-placeholder { background: linear-gradient(135deg, #0d0d0d 0%, #1f1f1f 55%, #2a2a2a 100%) !important; box-shadow: inset 0 0 30px rgba(0, 0, 0, 0.5) !important; } .sglv-epic-cover-placeholder .sglv-epic-logo { width: 96px !important; height: 96px !important; opacity: 1 !important; flex-shrink: 0 !important; filter: drop-shadow(0 4px 12px rgba(0, 0, 0, 0.6)); } .sglv-epic-cover-placeholder .sglv-epic-logo svg { width: 100% !important; height: 100% !important; display: block; } /* === v2.9.7: PS 独占(非 Steam 游戏)真实封面层 === 参考 steam-friend-manager 1.6.2 的 .sfd-tga-excl-img:平台占位画垫底, 商店主视觉绝对定位盖在其上;图片加载失败由 JS 直接移除 img,保住占位画。 */ .sglv-ps-excl-cover { position: absolute !important; inset: 0; z-index: 1; width: 100% !important; height: 100% !important; object-fit: cover; /* 主视觉为 1024×1024 方图:2:3 海报位裁上下、460/215 横版裁左右, 焦点上移(center 20%)保住方图上方的游戏 LOGO 区 */ object-position: center 20%; opacity: 0; transition: opacity .18s ease; } .sglv-ps-excl-cover.sglv-ps-excl-cover-loaded { opacity: 1 !important; } /* 列表视图图标位:包一层 relative 容器,封面图绝对定位盖住 PS 图标 */ .sglv-ps-excl-iconwrap { position: relative !important; overflow: hidden !important; } /* === 加载中骨架:body 为空或仅含简单文字时显示 spinner === */ @keyframes sgc-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } .sgc-body-loading { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%; min-height: 320px; padding: 40px 20px; gap: 14px; color: #94a3b8; font-size: 13px; text-align: center; } .sgc-body-loading .sgc-bl-spinner { width: 36px; height: 36px; border: 3px solid rgba(102, 192, 244, 0.15); border-top-color: #66c0f4; border-radius: 50%; animation: sgc-spin 0.9s linear infinite; } .sgc-body-loading .sgc-bl-title { font-size: 15px; font-weight: 600; color: #cbd5e1; } .sgc-body-loading .sgc-bl-tip { font-size: 12px; color: #64748b; line-height: 1.6; max-width: 380px; } /* body 完全为空时(首次打开/切 tab 瞬间)显示 fallback 提示 */ .sgc-panel .sglv-body:empty::before { content: "加载中…"; display: flex; align-items: center; justify-content: center; height: 200px; color: #94a3b8; font-size: 13px; } /* === v1.9.1: DLC 收藏标签页骨架(KPI shimmer + 卡片占位 + 阶段进度条) === */ @keyframes sglv-skel-shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } } .sglv-skel-line { background: linear-gradient(90deg, rgba(102,192,244,0.06) 0%, rgba(102,192,244,0.20) 50%, rgba(102,192,244,0.06) 100%); background-size: 200% 100%; animation: sglv-skel-shimmer 1.4s ease-in-out infinite; border-radius: 4px; height: 14px; margin: 6px 0; } .sglv-skel-line.lg { height: 22px; width: 55%; } .sglv-skel-line.md { height: 14px; width: 40%; } .sglv-skel-line.sm { height: 10px; width: 28%; } .sglv-trend-kpi-card.skeleton { pointer-events: none; opacity: 0.55; } .sglv-trend-kpi-card.skeleton .sglv-skel-line { margin: 8px 0; } .sglv-skel-card { background: rgba(255,255,255,0.04) !important; border: 1px solid rgba(255,255,255,0.06) !important; position: relative; overflow: hidden; } .sglv-skel-card::after { content: ""; position: absolute; inset: 0; background: linear-gradient(90deg, transparent 0%, rgba(102,192,244,0.10) 50%, transparent 100%); background-size: 200% 100%; animation: sglv-skel-shimmer 1.4s ease-in-out infinite; pointer-events: none; } .sglv-skel-card .sglv-card-img-wrap, .sglv-skel-card .sglv-card-body { visibility: hidden; } .sglv-skel-stage { margin: 14px 18px; display: flex; flex-direction: column; gap: 8px; } .sglv-skel-stage-bar { height: 4px; background: rgba(102,192,244,0.12); border-radius: 2px; overflow: hidden; } .sglv-skel-stage-fill { height: 100%; background: linear-gradient(90deg, #66c0f4, #a78bfa); border-radius: 2px; transition: width 0.4s ease; } .sglv-skel-stage-text { font-size: 12px; color: #94a3b8; display: flex; align-items: center; gap: 8px; } .sglv-skel-stage-text::before { content: ""; width: 12px; height: 12px; border: 2px solid rgba(102,192,244,0.25); border-top-color: #66c0f4; border-radius: 50%; animation: sgc-spin 0.9s linear infinite; flex-shrink: 0; } .sglv-skel-grid { padding: 0 12px 12px; } /* === v1.9.4: DLC 加载等待动画(参考 steam-friend-manager spinner 风格) === */ .sglv-dlc-loading { display:flex; flex-direction:column; align-items:center; justify-content:center; padding:48px 20px; gap:14px; color:#94a3b8; min-height:280px; } .sglv-dlc-loading .sglv-dlc-spin { width:32px; height:32px; animation:sgc-spin 1s linear infinite; color:#a78bfa; } .sglv-dlc-loading-text { font-size:13px; font-weight:600; color:#cbd5e1; } .sglv-dlc-loading-sub { font-size:11px; color:#64748b; } .sglv-dlc-loading-bar { width:220px; height:3px; background:rgba(102,192,244,0.12); border-radius:2px; overflow:hidden; } .sglv-dlc-loading-bar-fill { height:100%; background:linear-gradient(90deg,#66c0f4,#a78bfa); border-radius:2px; transition:width 0.4s ease; } /* === v1.9.4: DLC 工具栏分隔符 + 已拥有筛选 === */ .sglv-toolbar-sep { width:1px; height:24px; background:rgba(148,163,184,0.2); flex-shrink:0; margin:0 2px; } .sglv-dlc-own-filter { display:flex; gap:2px; flex-shrink:0; } .sglv-dlc-own-filter .sglv-btn { padding:4px 10px; font-size:11.5px; } /* === v1.9.35: 系列详情工具栏——flex-wrap 防溢出 + 拥有状态切换标签 === */ .sglv-pub-detail-toolbar { display: flex; align-items: center; flex-wrap: wrap; gap: 8px 12px; margin-bottom: 8px; font-size: 13px; color: #8a9ba8; } .sglv-pub-completion { flex-shrink: 0; } .sglv-pub-own-filter { display: flex; gap: 2px; flex-shrink: 0; } .sglv-pub-own-filter .sglv-btn { padding: 3px 10px; font-size: 11.5px; } .sglv-pub-sort-group { display: flex; align-items: center; gap: 4px; flex-shrink: 0; } .sglv-pub-detail-toolbar .sglv-view-toggle { margin-left: auto; gap: 4px !important; } /* === v1.9.1: DLC 收藏标签页 KPI 紧凑布局(5 列一行, 缩 padding/font, 避免换行) === */ /* shared-css 默认 .sglv-trend-kpi-row 是 4 列,5 个 KPI 必然换行 → 用 id 选择器精准覆盖 */ #sglv-dlc-kpi .sglv-trend-kpi-row { grid-template-columns: repeat(5, 1fr); gap: 6px; margin-bottom: 8px; } #sglv-dlc-kpi .sglv-trend-kpi-card { padding: 5px 8px 4px; min-width: 0; } #sglv-dlc-kpi .sglv-trend-kpi-header { gap: 3px; margin-bottom: 1px; } #sglv-dlc-kpi .sglv-trend-kpi-icon { width: 16px; height: 16px; border-radius: 4px; } #sglv-dlc-kpi .sglv-trend-kpi-icon svg { width: 10px; height: 10px; } #sglv-dlc-kpi .sglv-trend-kpi-label { font-size: 10px; line-height: 1.2; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } #sglv-dlc-kpi .sglv-trend-kpi-value { font-size: 17px; line-height: 1.15; white-space: nowrap; } #sglv-dlc-kpi .sglv-trend-kpi-sub { font-size: 9px; line-height: 1.3; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } /* === v1.9.1: DLC groupMode=true 时,视图切换按钮置灰不可点 === */ /* 分组视图天然是 card 布局,viewMode 概念对它无意义 → 视觉禁用 + pointer-events none */ .sgc-panel .sglv-view-toggle.sglv-view-disabled { opacity: 0.35; pointer-events: none; filter: grayscale(0.6); } .sgc-panel .sglv-view-toggle.sglv-view-disabled .sglv-btn.active { /* 即使 active 也不应被强调,保持整体灰态 */ box-shadow: none; } /* === v1.8.2: 供应商/系列模式切换条(系列分类标签页侧边栏顶部) === */ .sgc-panel .sglv-pub-mode-switch { display: flex; gap: 4px; padding: 8px 10px; border-bottom: 1px solid rgba(255,255,255,0.06); position: sticky; top: 0; background: rgba(20,30,42,0.96); backdrop-filter: blur(4px); z-index: 2; } .sgc-panel .sglv-pub-mode-btn { flex: 1; padding: 5px 10px; font-size: 12px; font-weight: 600; border-radius: 6px; border: 1px solid rgba(255,255,255,0.08); background: rgba(255,255,255,0.03); color: #94a3b8; cursor: pointer; transition: background 0.15s, color 0.15s, border-color 0.15s; } .sgc-panel .sglv-pub-mode-btn:hover { color: #e2e8f0; background: rgba(255,255,255,0.07); } .sgc-panel .sglv-pub-mode-btn.active { color: #fff; background: rgba(102,192,244,0.22); border-color: rgba(102,192,244,0.4); box-shadow: 0 0 0 1px rgba(102,192,244,0.15) inset; } /* v2.9.90: 系列刷新按钮——不占 flex:1,固定宽度 */ .sgc-panel .sglv-pub-mode-btn.sglv-pub-series-refresh { flex: 0 0 auto; padding: 5px 8px; color: #94a3b8; } .sgc-panel .sglv-pub-mode-btn.sglv-pub-series-refresh:hover { color: #66c0f4; } .sgc-panel .sglv-pub-mode-btn.sglv-pub-series-refresh svg { width: 14px; height: 14px; } .sgc-panel .sglv-pub-mode-btn.sglv-pub-series-refresh.sglv-spin svg { animation: sgc-spin 0.8s linear infinite; } /* v1.9.47-fix: 绝版游戏刷新按钮 spinner 动画 */ #sglv-delisted-refresh.sglv-spin svg { animation: sgc-spin 0.8s linear infinite; } /* v1.9.40: 刷新结果悬浮提示——绝对定位不参与工具栏 flex 布局,任何内容都不会压缩切换按钮 */ .sgc-panel .sglv-pub-refresh-toast { position: absolute; top: calc(100% + 4px); right: 10px; z-index: 3; display: inline-flex; align-items: center; gap: 8px; padding: 4px 10px; font-size: 11px; color: #cbd5e1; background: rgba(15,23,35,0.96); border: 1px solid rgba(255,255,255,0.1); border-radius: 6px; box-shadow: 0 4px 12px rgba(0,0,0,0.35); pointer-events: none; white-space: nowrap; } .sglv-pub-status-ok { color: #4caf50; font-weight: 600; } .sglv-pub-status-dim { color: #8f9bb3; } .sglv-pub-status-err { color: #ef5350; font-weight: 600; } /* v2.9.90: 锁区游戏刷新按钮 spinner 动画 */ #sglv-blocked-refresh.sglv-spin svg { animation: sgc-spin 0.8s linear infinite; } .sglv-ps-status { font-size: 11px; color: #8f9bb3; white-space: nowrap; margin-left: 4px; display: inline-flex; align-items: center; gap: 6px; } /* v2.9.91: 锁区游戏工具栏状态文本(更新时间 / 加载进度) */ .sglv-blocked-status { font-size: 11px; color: #8f9bb3; white-space: nowrap; margin-left: 4px; display: inline-flex; align-items: center; } .sglv-blocked-status.loading { color: #66c0f4; } /* === v1.8.2: 系列模式扁平列表项(无二级分类) === */ .sgc-panel .sglv-series-flat-item { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 7px 12px; font-size: 12.5px; color: #cbd5e1; cursor: pointer; border-left: 2px solid transparent; transition: background 0.15s, border-color 0.15s; } .sgc-panel .sglv-series-flat-item:hover { background: rgba(255,255,255,0.05); } .sgc-panel .sglv-series-flat-item.active { background: rgba(102,192,244,0.12); border-left-color: #66c0f4; color: #fff; } .sgc-panel .sglv-series-flat-item .sglv-series-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .sgc-panel .sglv-series-empty-hint { padding: 20px 12px; font-size: 12px; color: #8a9ba8; text-align: center; } /* v2.0.0: sidebar 模式提示 */ .sglv-pub-sidebar-hint { padding: 12px 14px; margin-top: 8px; font-size: 11.5px; color: #8a9ba8; text-align: center; background: rgba(102, 192, 244, 0.05); border: 1px dashed rgba(102, 192, 244, 0.2); border-radius: 6px; line-height: 1.5; } /* === v1.9.0: DLC 收藏标签页样式 === */ .sglv-dlc-group { border: 1px solid rgba(102, 192, 244, 0.12); border-radius: 8px; margin-bottom: 8px; overflow: hidden; background: rgba(255, 255, 255, 0.02); } .sglv-dlc-group.collapsed .sglv-dlc-card-row { display: none; } .sglv-dlc-group-head { display: flex !important; align-items: center !important; gap: 8px !important; padding: 8px 12px !important; cursor: pointer !important; background: rgba(102, 192, 244, 0.06) !important; transition: background 0.15s !important; } .sglv-dlc-group-head:hover { background: rgba(102, 192, 244, 0.12) !important; } .sglv-dlc-arrow { font-size: 12px; color: #94a3b8; transition: transform 0.15s; flex-shrink: 0; } .sglv-dlc-pname { font-weight: 600; font-size: 13px; color: #e2e8f0; flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .sglv-dlc-meta { font-size: 11px; color: #94a3b8; flex-shrink: 0; } .sglv-dlc-pct { font-weight: 700; font-size: 13px; color: #66c0f4; font-variant-numeric: tabular-nums; flex-shrink: 0; } /* === v1.9.3: DLC 父游戏 group 展开后,DLC 卡片用横版 4 列 grid(替代原 8 列竖图) === */ .sglv-dlc-card-row { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; padding: 8px 12px 12px; } .sglv-dlc-card-row .sglv-dlc-group-cover { width: 100% !important; } @media (max-width: 1280px) { .sglv-dlc-card-row { grid-template-columns: repeat(3, 1fr) !important; } } @media (max-width: 900px) { .sglv-dlc-card-row { grid-template-columns: repeat(2, 1fr) !important; } } @media (max-width: 600px) { .sglv-dlc-card-row { grid-template-columns: 1fr !important; } } .sglv-dlc-type-badge-music { background: rgba(34, 165, 247, 0.15); color: #22a5f7; border: 1px solid rgba(34, 165, 247, 0.25); padding: 1px 5px; border-radius: 3px; font-size: 9px; font-weight: 700; } .sglv-dlc-type-badge-dlc { background: rgba(139, 92, 246, 0.15); color: #a78bfa; border: 1px solid rgba(139, 92, 246, 0.25); padding: 1px 5px; border-radius: 3px; font-size: 9px; font-weight: 700; } .sglv-dlc-group-toggle { display: flex; gap: 2px; background: rgba(255, 255, 255, 0.06); border-radius: 8px; padding: 2px; } .sglv-dlc-group-toggle .sglv-btn { padding: 4px 10px; font-size: 12px; font-weight: 600; border-radius: 6px; } /* === v1.9.14: 捆绑包标签页专用样式 === */ /* === v1.9.24: 锁区游戏 SVG 锁图案封面占位符 === */ .sglv-blocked-cover-placeholder { width: 100%; height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; background: linear-gradient(135deg, #1a1a2e 0%, #16213e 40%, #0f3460 100%); position: relative; overflow: hidden; } .sglv-blocked-cover-placeholder::before { content: ''; position: absolute; inset: 0; background: radial-gradient(ellipse at 50% 35%, rgba(239,68,68,0.12) 0%, transparent 60%); } .sglv-blocked-cover-placeholder::after { content: ''; position: absolute; inset: 0; background: repeating-linear-gradient(45deg, transparent 0, transparent 12px, rgba(239,68,68,0.03) 12px, rgba(239,68,68,0.03) 24px); pointer-events: none; } .sglv-blocked-cover-placeholder .sglv-blocked-lock-svg { width: 48px; height: 48px; filter: drop-shadow(0 2px 8px rgba(239,68,68,0.4)); z-index: 1; flex-shrink: 0; } .sglv-blocked-cover-placeholder .sglv-blocked-cover-name { margin-top: 8px; padding: 0 8px; font-size: 11px; font-weight: 600; color: rgba(248,113,113,0.8); text-align: center; line-height: 1.3; max-width: 90%; overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; z-index: 1; } /* 横版封面视图(cover)适配 */ .sglv-wl-cover-img-wrap .sglv-blocked-cover-placeholder { background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%); } .sglv-wl-cover-img-wrap .sglv-blocked-cover-placeholder .sglv-blocked-lock-svg { width: 40px; height: 40px; } .sglv-wl-cover-img-wrap .sglv-blocked-cover-placeholder .sglv-blocked-cover-name { font-size: 10px; } /* 列表视图小图标 */ .sglv-list-icon.sglv-blocked-list-icon { width: 45px; height: 21px; display: flex; align-items: center; justify-content: center; background: linear-gradient(135deg, #1a1a2e, #0f3460); border: 1px solid rgba(239,68,68,0.2); border-radius: 3px; } .sglv-blocked-list-icon svg { width: 14px !important; height: 14px !important; } /* === v1.9.24: KPI 卡片炫彩增强 === */ .sgc-panel .sglv-trend-kpi-card { background: linear-gradient(135deg, rgba(255,255,255,0.04) 0%, rgba(255,255,255,0.01) 100%) !important; border-width: 1px !important; position: relative; overflow: hidden; transition: transform 0.25s, box-shadow 0.25s, border-color 0.25s !important; } .sgc-panel .sglv-trend-kpi-card::after { content: ''; position: absolute; top: 0; left: -100%; width: 100%; height: 100%; background: linear-gradient(90deg, transparent, rgba(255,255,255,0.06), transparent); transition: left 0.6s; pointer-events: none; } .sgc-panel .sglv-trend-kpi-card:hover::after { left: 100%; } .sgc-panel .sglv-trend-kpi-card:hover { transform: translateY(-2px) !important; box-shadow: 0 4px 20px rgba(0,0,0,0.3) !important; } .sgc-panel .sglv-trend-kpi-card.active { box-shadow: 0 0 0 1px var(--sglv-accent) inset, 0 4px 16px rgba(102,192,244,0.2) !important; } /* 锁区 KPI 红色卡片增强 */ .sgc-panel .sglv-trend-kpi-card[style*="ef4444"] { background: linear-gradient(135deg, rgba(239,68,68,0.08) 0%, rgba(239,68,68,0.02) 100%) !important; } .sgc-panel .sglv-trend-kpi-card[style*="ef4444"]:hover { box-shadow: 0 4px 20px rgba(239,68,68,0.25) !important; border-color: rgba(239,68,68,0.5) !important; } /* 橙色卡片增强 */ .sgc-panel .sglv-trend-kpi-card[style*="ff9800"] { background: linear-gradient(135deg, rgba(255,152,0,0.08) 0%, rgba(255,152,0,0.02) 100%) !important; } .sgc-panel .sglv-trend-kpi-card[style*="ff9800"]:hover { box-shadow: 0 4px 20px rgba(255,152,0,0.25) !important; border-color: rgba(255,152,0,0.5) !important; } /* 绿色(mine)卡片增强 */ .sgc-panel .sglv-trend-kpi-card.mine { background: linear-gradient(135deg, rgba(34,197,94,0.08) 0%, rgba(34,197,94,0.02) 100%) !important; } .sgc-panel .sglv-trend-kpi-card.mine:hover { box-shadow: 0 4px 20px rgba(34,197,94,0.25) !important; border-color: rgba(34,197,94,0.5) !important; } /* KPI 数值炫彩文字 */ .sgc-panel .sglv-trend-kpi-card .sglv-trend-kpi-value { text-shadow: 0 0 12px currentColor; filter: brightness(1.1); } /* === v1.9.24: 收集进度条炫彩 + 减细 === */ /* 系列分类筛选进度条减细(原 12px → 7px) */ .sgc-panel .sglv-progress-filter { height: 7px !important; border-radius: 4px !important; } .sgc-panel .sglv-progress-filter .sglv-progress-fill { background: linear-gradient(90deg, #4caf50, #22d3ee, #66c0f4) !important; box-shadow: 0 0 6px rgba(34,211,238,0.3) !important; } .sgc-panel .sglv-progress-filter .sglv-progress-fill.active { background: linear-gradient(90deg, #22c55e, #34d399, #22d3ee) !important; box-shadow: 0 0 8px rgba(34,211,238,0.5) !important; } /* 供应商/系列概览进度条也减细并炫彩 */ .sgc-panel .sglv-pub-card .sglv-progress, .sgc-panel .sglv-series-card .sglv-progress { height: 4px !important; margin: 4px 0 2px !important; } .sgc-panel .sglv-pub-card .sglv-progress-fill, .sgc-panel .sglv-series-card .sglv-progress-fill { background: linear-gradient(90deg, #4caf50, #22d3ee) !important; } /* 概览大进度条炫彩 */ .sgc-panel .sglv-stat-row + .sglv-progress { height: 8px !important; border-radius: 4px !important; } .sgc-panel .sglv-stat-row + .sglv-progress .sglv-progress-fill { background: linear-gradient(90deg, #4caf50, #22d3ee, #66c0f4, #a78bfa) !important; box-shadow: 0 0 8px rgba(102,192,244,0.3) !important; } /* === v1.9.33: 图片加载占位背景 + 焦点可见性 === */ /* 图片容器加载背景——封面图加载前显示柔和渐变占位 */ .sgc-panel .sglv-card-img-wrap, .sgc-panel .sglv-wl-cover-img-wrap { background: linear-gradient(135deg, rgba(255,255,255,0.03) 0%, rgba(255,255,255,0.06) 50%, rgba(255,255,255,0.02) 100%); } /* 图片加载完成淡入动画 */ .sgc-panel .sglv-card-img, .sgc-panel .sglv-wl-cover-img { opacity: 0; transition: opacity 0.3s ease; } .sgc-panel .sglv-card-img.sglv-img-loaded, .sgc-panel .sglv-wl-cover-img.sglv-img-loaded { opacity: 1; } /* v1.9.43: 竖版容器内横图 letterbox——无竖版资产的游戏(API 兜底返回横版 header) onload 检测 naturalWidth>naturalHeight 后追加 sglv-img-wide 类,object-fit:contain 完整显示 + 渐变底,替代 object-fit:cover 的居中裁切变形 */ .sgc-panel .sglv-card-img.sglv-img-wide { object-fit: contain !important; background: linear-gradient(160deg, rgba(22, 32, 45, 0.88) 0%, rgba(27, 40, 56, 0.88) 100%); } /* 焦点可见性——所有交互元素 focus-visible */ .sgc-panel .sglv-btn:focus-visible, .sgc-panel .sglv-view-btn:focus-visible, .sgc-panel .sglv-sort-select:focus-visible, .sgc-panel .sglv-search:focus-visible, .sgc-panel .sglv-metric-card:focus-visible { outline: 2px solid var(--sglv-accent, #66c0f4); outline-offset: 2px; } /* select 暗色模式原生样式修复 */ .sgc-panel .sglv-sort-select { background-color: rgba(62, 68, 84, 0.8); color: #c7d5e0; border: 1px solid rgba(255,255,255,0.1); } /* === v1.9.34: 系列横版封面视图增强效果 === */ /* 封面卡片 hover 光晕 + 缩放 */ .sgc-panel .sglv-pub-cover-card { transition: transform 0.28s ease, box-shadow 0.28s ease, border-color 0.28s ease !important; } .sgc-panel .sglv-pub-cover-card:hover { transform: translateY(-3px) !important; box-shadow: 0 6px 24px rgba(0,0,0,0.4), 0 0 0 1px rgba(102,192,244,0.15) !important; border-color: rgba(102,192,244,0.35) !important; } /* 已拥有游戏封面卡片——绿色边框微光 */ .sgc-panel .sglv-pub-cover-card.sglv-pub-cover-owned { border-color: rgba(76,175,80,0.2) !important; } .sgc-panel .sglv-pub-cover-card.sglv-pub-cover-owned:hover { border-color: rgba(76,175,80,0.5) !important; box-shadow: 0 6px 24px rgba(0,0,0,0.4), 0 0 12px rgba(76,175,80,0.15) !important; } /* 封面图片 hover 缩放 */ .sgc-panel .sglv-pub-cover-card .sglv-wl-cover-img { transition: opacity 0.3s ease, transform 0.35s ease !important; } .sgc-panel .sglv-pub-cover-card:hover .sglv-wl-cover-img { transform: scale(1.04) !important; } /* 封面底部渐变遮罩——提升文字可读性 */ .sgc-panel .sglv-pub-cover-overlay { position: absolute !important; bottom: 0 !important; left: 0 !important; right: 0 !important; height: 50% !important; background: linear-gradient(to top, rgba(0,0,0,0.55) 0%, transparent 100%) !important; pointer-events: none !important; z-index: 1 !important; } /* 拥有状态徽章——封面右上角毛玻璃 */ .sgc-panel .sglv-pub-cover-badge { position: absolute !important; top: 6px !important; right: 6px !important; z-index: 2 !important; margin-top: 0 !important; backdrop-filter: blur(6px) !important; -webkit-backdrop-filter: blur(6px) !important; box-shadow: 0 1px 4px rgba(0,0,0,0.35) !important; } /* === v1.9.33: prefers-reduced-motion 无障碍降级 === */ @media (prefers-reduced-motion: reduce) { .sgc-panel *, .sgc-panel *::before, .sgc-panel *::after { animation-duration: 0.01ms !important; animation-iteration-count: 1 !important; transition-duration: 0.01ms !important; scroll-behavior: auto !important; } .sgc-panel .sglv-card-img, .sgc-panel .sglv-wl-cover-img { opacity: 1 !important; transition: none !important; } } /* === v2.6.0: 受限游戏板组件样式已迁至下方 v2.6.0 区块(HERO + 卡片重构), 旧的一排等宽 KPI 小卡样式已随版本收敛一并移除。 === */ /* === v2.8.0: 捆绑包「内容墙」重构 === 设计思路反转:捆绑包的价值在于"包里有什么",主游戏封面是干扰项。 卡片 = 顶部主游戏标题条(上下文)+ 3 列 DLC 封面墙(主体)。 每张 DLC 有独立 appid,可直接取真实 header.jpg —— 旧版 24px 社区图标读不出美术细节。 */ .sglv-bundle-wall { display: grid !important; grid-template-columns: repeat(auto-fill, minmax(232px, 1fr)) !important; gap: 12px !important; } .sglv-bundle-card { position: relative; display: flex; flex-direction: column; border-radius: 10px; overflow: hidden; border: 1px solid rgba(255, 255, 255, 0.055); background: linear-gradient(180deg, rgba(255, 255, 255, 0.035) 0%, rgba(255, 255, 255, 0.015) 100%); box-shadow: 0 1px 2px rgba(0, 0, 0, 0.22); transition: transform 0.18s cubic-bezier(0.22, 1, 0.36, 1), border-color 0.18s ease, box-shadow 0.18s ease; } .sglv-bundle-card:hover { transform: translateY(-3px); border-color: rgba(102, 192, 244, 0.36); box-shadow: 0 10px 26px -8px rgba(0, 0, 0, 0.6), 0 0 0 1px rgba(102, 192, 244, 0.1); } /* ---- 顶部标题条:主游戏退为上下文 ---- */ .sglv-bundle-head { padding: 8px 10px 7px; border-bottom: 1px solid rgba(255, 255, 255, 0.045); background: rgba(255, 255, 255, 0.018); position: relative; } .sglv-bundle-title-row { display: flex; align-items: baseline; gap: 6px; cursor: pointer; min-width: 0; } .sglv-bundle-title-row:hover .sglv-bundle-title { color: #eef5fb !important; } .sglv-bundle-title { font-size: 12px; font-weight: 700; color: #dce8f4; line-height: 1.3; letter-spacing: 0.01em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; flex: 1 1 auto; min-width: 0; transition: color 0.15s; } .sglv-bundle-appid { font-size: 9px; color: rgba(148, 163, 184, 0.5); font-variant-numeric: tabular-nums; flex-shrink: 0; } .sglv-bundle-meta { display: flex; align-items: center; gap: 6px; margin-top: 3px; font-size: 9.5px; color: #8296ab; font-variant-numeric: tabular-nums; } .sglv-bundle-stat { display: inline-flex; align-items: center; gap: 3px; } .sglv-bundle-stat-ico { font-size: 9px; opacity: 0.8; } .sglv-bundle-sep { width: 1px; height: 9px; background: rgba(255, 255, 255, 0.12); } /* 已拥有的主游戏:标题条左侧一条绿色标记 */ .sglv-bundle-head.is-owned::before { content: ''; position: absolute; left: 0; top: 7px; bottom: 7px; width: 2.5px; border-radius: 0 2px 2px 0; background: linear-gradient(180deg, #34d399, #22c55e); box-shadow: 0 0 7px rgba(52, 211, 153, 0.5); } /* ---- DLC 封面墙:3 列 ---- */ .sglv-bundle-tiles { display: grid; grid-template-columns: repeat(3, 1fr); gap: 3px; padding: 6px; } .sglv-bundle-tiles-single { grid-template-columns: 1fr; } .sglv-bundle-tile { position: relative; aspect-ratio: 16 / 10; border-radius: 5px; overflow: hidden; cursor: pointer; background: rgba(255, 255, 255, 0.04); border: 1px solid rgba(255, 255, 255, 0.05); transition: transform 0.16s cubic-bezier(0.22, 1, 0.36, 1), border-color 0.16s ease, box-shadow 0.16s ease, z-index 0s; } .sglv-bundle-tile:hover { transform: scale(1.07); border-color: rgba(102, 192, 244, 0.6); box-shadow: 0 6px 16px -4px rgba(0, 0, 0, 0.7), 0 0 0 1px rgba(102, 192, 244, 0.25); z-index: 3; } /* 搜索命中的 DLC:琥珀色描边 */ .sglv-bundle-tile.is-hit { border-color: rgba(251, 191, 36, 0.75); box-shadow: 0 0 0 1px rgba(251, 191, 36, 0.3), 0 0 12px -2px rgba(251, 191, 36, 0.35); } /* 已拥有 DLC:左上角小绿点 */ .sglv-bundle-tile.is-owned::after { content: ''; position: absolute; top: 4px; left: 4px; width: 6px; height: 6px; border-radius: 50%; background: #34d399; box-shadow: 0 0 0 1.5px rgba(10, 18, 28, 0.85), 0 0 7px rgba(52, 211, 153, 0.75); z-index: 4; pointer-events: none; } /* tile 内的封面:填满 + letterbox */ .sglv-bundle-tile .sglv-img-wrapper { position: absolute; inset: 0; } .sglv-bundle-tile .sglv-img-wrapper > .sglv-card-img { object-fit: cover !important; } /* 进包次数角标 */ .sglv-bundle-tile-num { position: absolute; right: 3px; bottom: 3px; z-index: 4; min-width: 15px; padding: 0 3px; border-radius: 3px; background: rgba(8, 14, 22, 0.82); border: 1px solid rgba(245, 158, 11, 0.4); color: #fbbf24; font-size: 8.5px; font-weight: 700; line-height: 13px; text-align: center; font-variant-numeric: tabular-nums; backdrop-filter: blur(3px); -webkit-backdrop-filter: blur(3px); pointer-events: none; } .sglv-bundle-tile-badge { position: absolute; left: 4px; bottom: 4px; z-index: 4; padding: 1px 5px; border-radius: 3px; background: rgba(8, 14, 22, 0.8); border: 1px solid rgba(52, 211, 153, 0.4); color: #34d399; font-size: 8.5px; font-weight: 700; line-height: 14px; backdrop-filter: blur(3px); -webkit-backdrop-filter: blur(3px); pointer-events: none; } /* ---- 展开按钮:ghost 风格,不用白底黑字 ---- */ .sglv-bundle-expand { display: flex; align-items: center; justify-content: center; gap: 5px; width: calc(100% - 12px); margin: 0 6px 6px; padding: 4px 0; border-radius: 5px; background: rgba(102, 192, 244, 0.07); border: 1px solid rgba(102, 192, 244, 0.18); color: #8fc9e8; font-size: 9.5px; font-weight: 600; cursor: pointer; transition: background 0.15s, border-color 0.15s, color 0.15s; } .sglv-bundle-expand:hover { background: rgba(102, 192, 244, 0.14); border-color: rgba(102, 192, 244, 0.38); color: #b6e0f5; } .sglv-bundle-expand.is-open { background: rgba(255, 255, 255, 0.035); border-color: rgba(255, 255, 255, 0.1); color: #8296ab; } .sglv-bundle-expand-caret { font-size: 8px; opacity: 0.8; transition: transform 0.2s ease; display: inline-block; } .sglv-bundle-expand.is-open .sglv-bundle-expand-caret { transform: rotate(180deg); } /* 折叠区展开时不额外加间距 */ .sglv-bundle-tiles-rest { padding-top: 0; } /* === v2.9.0: 年度大片「大海报」视图 === 此前 cover 视图复用 card 视图的 .sglv-goty-grid + renderGotyGridCard, 渲染结果完全一致 → 点击「大海报」按钮后视觉零变化(用户报"切换没效果")。 这里给出独立的横向宽海报布局:封面铺满 + 底部渐变 + 标题信息叠加。 */ .sglv-goty-cover-grid { display: grid !important; grid-template-columns: repeat(auto-fill, minmax(272px, 1fr)) !important; gap: 12px !important; padding: 10px 0; } .sglv-goty-cover-card { position: relative; border-radius: 10px; overflow: hidden; cursor: pointer; border: 1px solid rgba(255, 255, 255, 0.06); box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3); transition: transform 0.2s cubic-bezier(0.22, 1, 0.36, 1), border-color 0.2s ease, box-shadow 0.2s ease; } .sglv-goty-cover-card:hover { transform: translateY(-4px) scale(1.008); border-color: rgba(102, 192, 244, 0.45); box-shadow: 0 14px 32px -10px rgba(0, 0, 0, 0.72), 0 0 0 1px rgba(102, 192, 244, 0.12); } .sglv-goty-cover-img-wrap { position: relative; aspect-ratio: 460 / 215 !important; /* header.jpg 原生比例 */ overflow: hidden; background: linear-gradient(145deg, rgba(102,192,244,0.06), rgba(139,92,246,0.06)); } .sglv-goty-cover-img-wrap .sglv-img-wrapper { position: absolute; inset: 0; } /* 大海报视图:横图铺满,不留黑边 */ .sglv-goty-cover-img-wrap .sglv-img-wrapper > .sglv-goty-cover-img { object-fit: cover !important; opacity: 0; transition: opacity 0.3s ease; } .sglv-goty-cover-img-wrap .sglv-img-wrapper.sglv-img-loaded > .sglv-goty-cover-img { opacity: 1; } /* 大图上不显示转圈 spinner */ .sglv-goty-cover-img-wrap .sglv-img-wrapper.sglv-img-loading::after { display: none !important; } /* 底部渐变 + 信息叠加 */ .sglv-goty-cover-grad { position: absolute; left: 0; right: 0; bottom: 0; height: 68%; background: linear-gradient(to top, rgba(8, 13, 20, 0.94) 0%, rgba(8, 13, 20, 0.72) 38%, rgba(8, 13, 20, 0.22) 72%, transparent 100%); pointer-events: none; z-index: 2; } .sglv-goty-cover-overlay { position: absolute; left: 0; right: 0; bottom: 0; padding: 12px 14px 11px; z-index: 3; display: flex; flex-direction: column; gap: 3px; pointer-events: none; } .sglv-goty-cover-title { font-size: 14px; font-weight: 700; color: #f2f7fb; line-height: 1.25; letter-spacing: 0.01em; text-shadow: 0 1px 6px rgba(0, 0, 0, 0.85); display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; } .sglv-goty-cover-meta { display: flex; align-items: center; gap: 8px; font-size: 10px; font-weight: 600; } .sglv-goty-cover-owned { color: #34d399; text-shadow: 0 1px 4px rgba(0,0,0,0.8); } .sglv-goty-cover-not-owned { color: #94a3b8; text-shadow: 0 1px 4px rgba(0,0,0,0.8); } .sglv-goty-cover-countdown { padding: 1px 6px; border-radius: 3px; background: rgba(245, 158, 11, 0.16); border: 1px solid rgba(245, 158, 11, 0.32); color: #fbbf24; font-size: 9px; backdrop-filter: blur(3px); -webkit-backdrop-filter: blur(3px); } .sglv-goty-cover-countdown.today { background: rgba(239, 68, 68, 0.18); border-color: rgba(239, 68, 68, 0.4); color: #fca5a5; } .sglv-goty-cover-countdown.past { background: rgba(100, 116, 139, 0.18); border-color: rgba(100, 116, 139, 0.35); color: #94a3b8; } /* 已拥有:左上角绿点 + 细绿边 */ .sglv-goty-cover-card.is-owned { border-color: rgba(52, 211, 153, 0.32); } .sglv-goty-cover-card.is-owned::after { content: ''; position: absolute; top: 9px; left: 9px; width: 7px; height: 7px; border-radius: 50%; background: #34d399; box-shadow: 0 0 0 2px rgba(8, 13, 20, 0.85), 0 0 9px rgba(52, 211, 153, 0.8); z-index: 4; } /* === v2.8.0: 工具栏整合筛选 + 分页到一行 === */ /* 分页器移入 toolbar 后,用弹性占位把左侧控件与右侧分页推到两端。 core 已有 .sglv-toolbar .sglv-pagination { margin-left: auto }, 这里补 spacer 作为双保险,并让窄浮窗下分页可换行而不撑破工具栏。 */ .sglv-toolbar-spacer { flex: 1 1 auto; min-width: 8px; height: 1px; } .sglv-toolbar .sglv-pagination { margin-left: auto !important; flex-shrink: 0 !important; } .sglv-toolbar .sglv-toolbar-spacer + .sglv-pagination { margin-left: 0 !important; /* spacer 已占位,去掉 auto 避免双重间隙 */ } /* 状态文本(锁区「更新: 2026-08-10」)与分页之间留出间距 */ .sglv-blocked-status { flex-shrink: 0 !important; } /* === v2.8.0: 大海报视图(Epic / PS会免 / 系列 / GOTY / DLC)封面容器适配 === 这五处原本用裸 直接放进 .sglv-wl-cover-img-wrap, 现在改为 .sglv-img-wrapper 三态结构,需要补容器规则: ① wrapper 撑满父容器(绝对定位),避免图片高度塌陷; ② letterbox 改为 cover —— 大海报视图就是给横图"放大展示"的,contain 会留大片黑边; ③ 骨架/兜底层沿用受限游戏板那套三态样式,无需额外定义。 */ .sglv-wl-cover-img-wrap { position: relative; overflow: hidden; background: rgba(255, 255, 255, 0.04); } .sglv-wl-cover-img-wrap .sglv-img-wrapper { position: absolute; inset: 0; width: 100%; height: 100%; } /* 大海报视图:横图铺满(cover),这是该视图存在的意义 */ .sglv-wl-cover-img-wrap .sglv-img-wrapper > .sglv-wl-cover-img { object-fit: cover !important; opacity: 0; transition: opacity 0.25s ease; } .sglv-wl-cover-img-wrap .sglv-img-wrapper.sglv-img-loaded > .sglv-wl-cover-img { opacity: 1; } /* 该视图中不显示进度 spinner(大图上转圈很扎眼),只保留淡骨架 */ .sglv-wl-cover-img-wrap .sglv-img-wrapper.sglv-img-loading::after { display: none !important; } .sglv-wl-cover-img-wrap .sglv-img-wrapper.sglv-img-loading::before { opacity: 0.5; } /* GOTY 网格卡片内的封面同理 */ .sglv-goty-grid .sglv-img-wrapper { position: relative; width: 100%; height: 100%; } .sglv-goty-grid .sglv-img-wrapper > .sglv-card-img { object-fit: cover !important; } /* 系列分类的 header 视图 */ .sglv-pub-list-cover { object-fit: cover !important; } /* === v2.7.0: HERO 质感打磨 === */ .sglv-hero { position: relative; overflow: hidden; background: radial-gradient(120% 140% at 8% -20%, rgba(102, 192, 244, 0.13) 0%, transparent 55%), linear-gradient(135deg, rgba(28, 42, 60, 0.78) 0%, rgba(18, 28, 42, 0.9) 100%); border-color: rgba(102, 192, 244, 0.2); box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.06), 0 4px 18px -8px rgba(0, 0, 0, 0.5); } /* 右上角极淡网格纹理,呼应 Steam 的"库"隐喻 */ .sglv-hero::after { content: ''; position: absolute; top: 0; right: 0; width: 180px; height: 100%; background-image: linear-gradient(rgba(255, 255, 255, 0.022) 1px, transparent 1px), linear-gradient(90deg, rgba(255, 255, 255, 0.022) 1px, transparent 1px); background-size: 14px 14px; mask-image: linear-gradient(to left, #000, transparent); -webkit-mask-image: linear-gradient(to left, #000, transparent); pointer-events: none; } .sglv-hero-left, .sglv-hero-right { position: relative; z-index: 1; } .sglv-hero-num { font-size: 38px !important; font-weight: 800 !important; letter-spacing: -0.03em; line-height: 1; font-variant-numeric: tabular-nums; background: linear-gradient(180deg, #ffffff 20%, #a8c8e0 100%); -webkit-background-clip: text; background-clip: text; -webkit-text-fill-color: transparent; text-shadow: none; } .sglv-hero-progress { height: 6px !important; border-radius: 4px; background: rgba(255, 255, 255, 0.07); box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.3); overflow: hidden; } .sglv-hero-progress-fill { height: 100%; border-radius: 4px; background: linear-gradient(90deg, #22c55e, #4ade80 55%, #66c0f4); box-shadow: 0 0 10px rgba(74, 222, 128, 0.4); } .sglv-hero-scope { padding: 6px 8px; border-radius: 7px; background: rgba(255, 255, 255, 0.04); border: 1px solid rgba(255, 255, 255, 0.065); transition: background 0.16s, border-color 0.16s, transform 0.14s; } .sglv-hero-scope:hover { background: rgba(255, 255, 255, 0.085); transform: translateY(-1px); } .sglv-hero-scope.active { background: linear-gradient(180deg, rgba(102, 192, 244, 0.22), rgba(102, 192, 244, 0.12)); border-color: rgba(102, 192, 244, 0.55); box-shadow: 0 0 0 1px rgba(102, 192, 244, 0.18), 0 3px 10px -4px rgba(102, 192, 244, 0.4); } .sglv-hero-scope-val { font-size: 15px !important; font-weight: 700; font-variant-numeric: tabular-nums; letter-spacing: -0.01em; } .sglv-hero-type { padding: 3.5px 7px; border-radius: 5px; transition: background 0.15s, transform 0.12s; } .sglv-hero-type:hover { background: rgba(255, 255, 255, 0.055); transform: translateX(2px); } .sglv-hero-type.active { background: rgba(102, 192, 244, 0.14); box-shadow: inset 2px 0 0 #66c0f4; } .sglv-hero-type-track { height: 6px !important; border-radius: 4px; background: rgba(255, 255, 255, 0.055); box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.25); } .sglv-hero-type-fill { height: 100%; border-radius: 4px; box-shadow: 0 0 8px currentColor; } .sglv-hero-type-count { font-size: 11px !important; font-weight: 700; } .sglv-hero-type-pct { font-size: 9.5px !important; } /* === v2.9.2: 三态封面 wrapper 基础规则(补齐缺失的 base)=== 此前工程里只有 ::before/::after 的 override,没有基础定义: - .sglv-img-fallback-layer 是普通 block → 永远跟在图片下方占位; - .sglv-img-broken 无法隐藏图片; - loading 骨架/spinner 没有 content/position,override 全部失效。 这里补齐 loading / loaded / broken 三态的最小闭环。 */ .sglv-img-wrapper { position: relative; display: block; overflow: hidden; } .sglv-img-wrapper > img { display: block; max-width: 100%; } /* 卡片容器内:wrapper 撑满固定比例容器,img 由 core 的 .sglv-card-img(width/height 100% !important)决定尺寸, object-fit:contain 负责 letterbox(横图不硬裁主体) */ .sglv-card-img-wrap > .sglv-img-wrapper { position: absolute; inset: 0; } .sglv-card-img-wrap > .sglv-img-wrapper > img { width: 100%; height: 100%; } .sglv-img-fallback-layer { position: absolute; inset: 0; display: none; flex-direction: column; align-items: center; justify-content: center; z-index: 2; pointer-events: none; } .sglv-img-wrapper.sglv-img-broken > img { visibility: hidden; } .sglv-img-wrapper.sglv-img-broken > .sglv-img-fallback-layer { display: flex; } .sglv-img-wrapper.sglv-img-loading::before { content: ''; position: absolute; inset: 0; z-index: 1; background: linear-gradient(100deg, rgba(255,255,255,0.015) 0%, rgba(255,255,255,0.06) 45%, rgba(255,255,255,0.015) 100%); background-size: 220% 100%; animation: sglv-img-shimmer 1.4s ease-in-out infinite; } .sglv-img-wrapper.sglv-img-loading::after { content: ''; position: absolute; top: 50%; left: 50%; z-index: 2; width: 20px; height: 20px; margin: -10px 0 0 -10px; border-radius: 50%; border: 1.5px solid rgba(102, 192, 244, 0.18); border-top-color: rgba(102, 192, 244, 0.7); animation: sglv-img-spin 0.9s linear infinite; } @keyframes sglv-img-shimmer { 0% { background-position: 120% 0; } 100% { background-position: -120% 0; } } @keyframes sglv-img-spin { to { transform: rotate(360deg); } } /* === v2.7.0: broken 占位精致化 —— 去掉粗笨大图标,改为细线图标 + 短标签 === */ .sglv-img-fallback-layer { gap: 7px !important; background: repeating-linear-gradient(45deg, rgba(255, 255, 255, 0.012) 0 6px, transparent 6px 12px), linear-gradient(160deg, rgba(30, 42, 58, 0.9), rgba(18, 26, 38, 0.95)); } .sglv-img-broken-icon { width: 26px !important; height: 26px !important; background: rgba(148, 163, 184, 0.1) !important; border: 1px solid rgba(148, 163, 184, 0.16) !important; color: rgba(148, 163, 184, 0.55) !important; } .sglv-img-broken-icon svg { width: 13px !important; height: 13px !important; } .sglv-img-broken-label { font-size: 9px !important; letter-spacing: 0.04em; opacity: 0.5; font-weight: 500; } .sglv-img-broken-blocked .sglv-img-broken-icon, .sglv-img-wrapper.sglv-img-broken.sglv-img-broken-blocked .sglv-img-broken-icon { background: rgba(239, 68, 68, 0.1) !important; border-color: rgba(239, 68, 68, 0.2) !important; color: rgba(239, 68, 68, 0.55) !important; } /* 骨架:更细腻的扫描线 */ .sglv-img-wrapper.sglv-img-loading::before { background: linear-gradient(100deg, rgba(255,255,255,0.015) 0%, rgba(255,255,255,0.06) 45%, rgba(255,255,255,0.015) 100%); background-size: 220% 100%; } .sglv-img-wrapper.sglv-img-loading::after { width: 20px; height: 20px; margin: -10px 0 0 -10px; border-width: 1.5px; border-color: rgba(102, 192, 244, 0.18); border-top-color: rgba(102, 192, 244, 0.7); } /* === v2.7.0: 质感打磨 —— 层级、材质、微交互 === */ /* 卡片:更克制的边框 + 悬停抬升 + 顶部高光 */ .sglv-card-grid .sglv-game-card { border: 1px solid rgba(255, 255, 255, 0.055) !important; border-radius: 9px !important; background: linear-gradient(180deg, rgba(255, 255, 255, 0.038) 0%, rgba(255, 255, 255, 0.018) 100%) !important; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.22); transition: transform 0.18s cubic-bezier(0.22, 1, 0.36, 1), border-color 0.18s ease, box-shadow 0.18s ease, background 0.18s ease !important; } .sglv-card-grid .sglv-game-card:hover { transform: translateY(-3px) !important; border-color: rgba(102, 192, 244, 0.38) !important; background: linear-gradient(180deg, rgba(102, 192, 244, 0.075) 0%, rgba(255, 255, 255, 0.022) 100%) !important; box-shadow: 0 8px 22px -6px rgba(0, 0, 0, 0.55), 0 0 0 1px rgba(102, 192, 244, 0.12); } /* 顶部 1px 高光,模拟受光边缘 */ .sglv-card-grid .sglv-game-card::before { content: ''; position: absolute; top: 0; left: 8px; right: 8px; height: 1px; background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.16), transparent); pointer-events: none; z-index: 7; opacity: 0.75; } .sglv-card-grid .sglv-game-card { position: relative !important; } /* 封面区:更深的底 + 底部渐隐,让横图与卡片体衔接自然 */ .sglv-card-grid .sglv-game-card .sglv-card-img-wrap { position: relative; overflow: hidden; border-bottom: 1px solid rgba(255, 255, 255, 0.045); } .sglv-card-grid .sglv-game-card .sglv-card-img-wrap::after { content: ''; position: absolute; left: 0; right: 0; bottom: 0; height: 26px; background: linear-gradient(to top, rgba(18, 26, 38, 0.55), transparent); pointer-events: none; z-index: 5; } /* 游戏名:两行截断(部分长名),hover 显示全名 */ .sglv-card-grid .sglv-game-card .sglv-card-name { font-size: 11px !important; font-weight: 600 !important; line-height: 1.32 !important; color: #d5e2ee !important; letter-spacing: 0.01em; display: -webkit-box !important; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; min-height: 29px; /* 两行高度,保证同行卡片正文对齐 */ margin-bottom: 2px; } .sglv-card-grid .sglv-game-card:hover .sglv-card-name { color: #eef5fb !important; } .sglv-card-grid .sglv-game-card .sglv-card-id-inline { font-size: 9px !important; opacity: 0.5; font-variant-numeric: tabular-nums; } /* 两栏 meta:细分隔线 + 更克制的排版 */ .sglv-card-meta2 { display: flex !important; align-items: center; justify-content: space-between; gap: 6px; margin-top: 2px; padding-top: 4px; border-top: 1px solid rgba(255, 255, 255, 0.04); min-width: 0; } .sglv-meta-col-left, .sglv-meta-col-right { display: flex; align-items: center; gap: 4px; min-width: 0; } .sglv-meta-col-left { flex: 1 1 auto; overflow: hidden; } .sglv-meta-col-right { flex: 0 0 auto; } /* 分类徽章:更精致 —— 半透明底 + 左侧色点 */ .sglv-type-badge { display: inline-flex !important; align-items: center; font-size: 9px !important; font-weight: 600 !important; padding: 1.5px 5px 1.5px 4px !important; border-radius: 4px !important; border: 1px solid transparent !important; line-height: 1.45; white-space: nowrap; flex-shrink: 0; letter-spacing: 0.01em; } /* 拥有态文字:纯文字,无背景无边框 */ .sglv-own-text { font-size: 9px !important; font-weight: 600 !important; line-height: 1.45; white-space: nowrap; flex-shrink: 0; letter-spacing: 0.01em; } .sglv-own-text.owned { color: #34d399 !important; } .sglv-own-text.missing { color: #fbbf24 !important; } /* 右栏数值:小图标 + tabular 对齐 */ .sglv-meta-col-right .sglv-meta-item { display: inline-flex !important; align-items: center; gap: 2.5px; font-size: 9px !important; color: rgba(148, 163, 184, 0.85) !important; white-space: nowrap; line-height: 1.45; font-variant-numeric: tabular-nums; } .sglv-meta-col-right .sglv-meta-item svg { width: 9px !important; height: 9px !important; opacity: 0.55; flex-shrink: 0; } .sglv-meta-col-right .sglv-m-playtime { color: #66c0f4 !important; font-weight: 700 !important; } /* 状态斜切带:更利落 */ .sglv-own-flag { position: absolute !important; bottom: 0; right: 0; z-index: 8; pointer-events: none; clip-path: polygon(16px 0, 100% 0, 100% 100%, 0 100%); border-top-left-radius: 2px; transition: opacity 0.18s ease; } .sglv-own-flag.missing { width: 54px; height: 4px; background: linear-gradient(90deg, rgba(245, 158, 11, 0.4), #f59e0b 70%); } .sglv-own-flag.owned { width: 30px; height: 3px; clip-path: polygon(12px 0, 100% 0, 100% 100%, 0 100%); background: linear-gradient(90deg, rgba(52, 211, 153, 0.4), #34d399 70%); } .sglv-card-grid .sglv-game-card:hover .sglv-own-flag { opacity: 0.85; } /* 网格间距略增,给抬升留呼吸 */ .sglv-card-grid { gap: 12px !important; } /* === v2.6.0: 受限游戏板 HERO —— 铺满宽度的仪表盘 === */ .sglv-hero { display: flex !important; align-items: stretch; gap: 14px; width: 100%; padding: 12px 14px 13px; margin-bottom: 10px; border-radius: 10px; border: 1px solid rgba(102, 192, 244, 0.16); background: linear-gradient(135deg, rgba(27, 40, 56, 0.72) 0%, rgba(20, 32, 48, 0.86) 100%); box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.04); } /* 左区:主数字 —— flex: 0 0 auto 保证数字不被压缩,宽度随内容自适应 */ .sglv-hero-left { flex: 0 0 auto; min-width: 148px; display: flex; flex-direction: column; } .sglv-hero-title { font-size: 10px; font-weight: 600; letter-spacing: 0.08em; color: #7e93ab; text-transform: uppercase; } .sglv-hero-num { font-size: 34px; font-weight: 800; line-height: 1.05; letter-spacing: -0.02em; color: #e8f1fa; margin: 3px 0 7px; text-shadow: 0 0 22px rgba(102, 192, 244, 0.28); } .sglv-hero-progress { width: 100%; height: 4px; border-radius: 3px; background: rgba(255, 255, 255, 0.08); overflow: hidden; } .sglv-hero-progress-fill { height: 100%; border-radius: 3px; background: linear-gradient(90deg, #34d399, #66c0f4); transition: width 0.4s ease; } .sglv-hero-progress-cap { font-size: 9px; color: #6f8399; margin-top: 4px; letter-spacing: 0.02em; } /* scope 卡:紧凑双联,取代原 KPI 行里的"在库/未拥有"两张卡 */ .sglv-hero-scope-row { display: flex; gap: 6px; margin-top: 9px; } .sglv-hero-scope { flex: 1; min-width: 62px; padding: 5px 7px; border-radius: 6px; background: rgba(255, 255, 255, 0.045); border: 1px solid rgba(255, 255, 255, 0.07); cursor: pointer; transition: background 0.15s, border-color 0.15s, transform 0.12s; } .sglv-hero-scope:hover { background: rgba(255, 255, 255, 0.09); transform: translateY(-1px); } .sglv-hero-scope.active { background: rgba(102, 192, 244, 0.17); border-color: rgba(102, 192, 244, 0.5); } .sglv-hero-scope-val { display: block; font-size: 14px; font-weight: 700; line-height: 1.2; color: #dbe7f3; } .sglv-hero-scope-label { display: block; font-size: 9px; color: #8296ab; margin-top: 1px; } /* 右区:类型占比列表 —— flex:1 吃掉全部剩余宽度,这是"铺满浮窗"的关键 */ .sglv-hero-right { flex: 1 1 auto; min-width: 0; display: flex; flex-direction: column; gap: 3px; padding-left: 14px; border-left: 1px solid rgba(255, 255, 255, 0.07); } .sglv-hero-right-head { font-size: 9px; font-weight: 600; letter-spacing: 0.08em; color: #6f8399; text-transform: uppercase; margin-bottom: 2px; } .sglv-hero-type { display: flex !important; align-items: center; gap: 7px; padding: 3px 6px; border-radius: 5px; cursor: pointer; transition: background 0.15s; } .sglv-hero-type:hover { background: rgba(255, 255, 255, 0.05); } .sglv-hero-type.active { background: rgba(102, 192, 244, 0.14); } .sglv-hero-type-dot { width: 7px; height: 7px; border-radius: 2px; flex-shrink: 0; } .sglv-hero-type-name { font-size: 10px; color: #b9c9d9; width: 56px; flex-shrink: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .sglv-hero-type-track { flex: 1 1 auto; min-width: 20px; height: 5px; border-radius: 3px; background: rgba(255, 255, 255, 0.06); overflow: hidden; } .sglv-hero-type-fill { display: block; height: 100%; border-radius: 3px; opacity: 0.85; transition: width 0.35s ease; } .sglv-hero-type-count { font-size: 10px; font-weight: 700; color: #dbe7f3; width: 46px; text-align: right; flex-shrink: 0; font-variant-numeric: tabular-nums; } .sglv-hero-type-pct { font-size: 9px; color: #7e93ab; width: 30px; text-align: right; flex-shrink: 0; font-variant-numeric: tabular-nums; } .sglv-hero-empty { font-size: 10px; color: #6f8399; padding: 8px 0; } /* 窄浮窗:右区换行到下方,仍保持铺满 */ @media (max-width: 720px) { .sglv-hero { flex-direction: column; gap: 10px; } .sglv-hero-left { min-width: 0; } .sglv-hero-right { padding-left: 0; padding-top: 10px; border-left: none; border-top: 1px solid rgba(255,255,255,0.07); } } /* === v2.6.0: 受限游戏卡片重构 —— letterbox 封面 + 状态斜切带 + 两栏 meta === */ /* 封面容器:横向图 letterbox(居中不裁剪),高度略降给信息区腾空间 */ .sglv-card-grid .sglv-game-card .sglv-card-img-wrap { aspect-ratio: 16 / 11 !important; /* 从 2:3 改为接近 header.jpg 的 460:215 比例 */ background: linear-gradient(145deg, rgba(102,192,244,0.05), rgba(139,92,246,0.05)) !important; } .sglv-img-wrapper > .sglv-card-img { object-fit: contain !important; /* 关键:横向图在容器内完整显示,不再硬裁主体 */ object-position: center; } /* === v2.9.4: 竖版海报卡片墙(系列分类 / PS 会免 / Epic 赠送) === 数据源里竖版 library_600x900 覆盖率更高,卡片默认改用 2:3 海报; 拿不到竖版时链尾回退 header.jpg,img 会被 markLoaded 标上 .sglv-img-wide → 下面单独走 contain letterbox,视觉上不裁切、不变形。 */ .sgc-panel .sglv-card-grid.sglv-card-grid-7 { grid-template-columns: repeat(7, minmax(0, 1fr)) !important; gap: 8px !important; } .sgc-panel .sglv-card-grid .sglv-game-card.sglv-poster-card .sglv-card-img-wrap { aspect-ratio: 2 / 3 !important; background: linear-gradient(160deg, rgba(22, 32, 45, 0.85) 0%, rgba(27, 40, 56, 0.85) 100%) !important; } /* 竖版:铺满容器(2:3 容器 + 2:3 图 → 零留白) */ .sgc-panel .sglv-poster-card .sglv-img-wrapper > .sglv-card-img:not(.sglv-img-wide) { object-fit: cover !important; object-position: center top; } /* 横版兜底:完整显示,上下留渐变底(不硬裁主体) */ .sgc-panel .sglv-poster-card .sglv-img-wrapper > .sglv-card-img.sglv-img-wide { object-fit: contain !important; object-position: center; } .sgc-panel .sglv-poster-card .sglv-card-body { padding: 5px 7px 6px !important; } .sgc-panel .sglv-poster-card .sglv-card-name { min-height: 27px !important; } .sgc-panel .sglv-poster-card .sglv-card-id-inline, .sgc-panel .sglv-poster-card .sglv-card-id { font-size: 9px !important; opacity: 0.55; } /* 7 列下卡片内边距/徽章同步收紧 */ .sgc-panel .sglv-poster-card .sglv-card-badge { font-size: 9px !important; padding: 1px 5px !important; } .sgc-panel .sglv-poster-card .sglv-info-row { gap: 4px !important; flex-wrap: wrap; } /* 状态斜切带(signature)—— 封���右下角的一道纯色斜带,无文字。 取代原先信息区里的实心「未拥有」色块,节省一整行高度。 未拥有 = 琥珀(醒目,提示"这个你还没有");已拥有 = 绿(细一些,次要) */ .sglv-own-flag { position: absolute !important; bottom: 0; right: 0; width: 62px; height: 5px; z-index: 6; pointer-events: none; clip-path: polygon(18px 0, 100% 0, 100% 100%, 0 100%); border-top-left-radius: 3px; } .sglv-own-flag.missing { background: linear-gradient(90deg, rgba(245,158,11,0.55), #f59e0b); box-shadow: 0 0 8px rgba(245,158,11,0.45); } .sglv-own-flag.owned { width: 34px; height: 4px; clip-path: polygon(14px 0, 100% 0, 100% 100%, 0 100%); background: linear-gradient(90deg, rgba(52,211,153,0.5), #34d399); } /* 两栏 meta:左 = 分类徽章 + 拥有态;右 = 数值/日期 */ .sglv-card-meta2 { display: flex !important; align-items: center; justify-content: space-between; gap: 6px; margin-top: 3px; min-width: 0; } .sglv-meta-col-left, .sglv-meta-col-right { display: flex; align-items: center; gap: 5px; min-width: 0; } .sglv-meta-col-left { flex: 0 1 auto; overflow: hidden; } .sglv-meta-col-right { flex: 0 0 auto; justify-content: flex-end; } .sglv-type-badge { display: inline-flex !important; align-items: center; font-size: 9px !important; padding: 1px 5px !important; border-radius: 3px !important; border: 1px solid transparent; font-weight: 700; line-height: 1.5; white-space: nowrap; flex-shrink: 0; } /* 拥有态文字:与分类徽章同字号同风格,只是无边框 —— 不再是实心色块 */ .sglv-own-text { font-size: 9px !important; font-weight: 600; line-height: 1.5; white-space: nowrap; flex-shrink: 0; } .sglv-own-text.owned { color: #34d399 !important; } .sglv-own-text.missing { color: #fbbf24 !important; } /* 右栏 meta 项:图标 + 文本,超长省略 */ .sglv-meta-col-right .sglv-meta-item { display: inline-flex !important; align-items: center; gap: 2px; font-size: 9px !important; color: var(--sglv-text-secondary) !important; white-space: nowrap; line-height: 1.5; } .sglv-meta-col-right .sglv-meta-item svg { width: 9px !important; height: 9px !important; opacity: 0.65; flex-shrink: 0; } .sglv-meta-col-right .sglv-m-playtime { color: #66c0f4 !important; font-weight: 700; } /* 卡片正文:两栏后高度收紧 */ .sglv-card-grid .sglv-game-card .sglv-card-body { padding: 5px 7px 6px !important; } .sglv-card-grid .sglv-game-card .sglv-card-name { font-size: 11px !important; line-height: 1.35; margin-bottom: 1px; } /* 列表视图的两栏 meta 同样生效 */ .sglv-list-item .sglv-card-meta2 { margin-top: 2px; } .sglv-list-item .sglv-meta-col-right .sglv-meta-item { font-size: 10px !important; } /* 搜索高亮:改为左标记 + 底色,避免整块抢眼 */ .sglv-highlight { background: rgba(251, 191, 36, 0.16) !important; color: #fbbf24 !important; border-radius: 2px; padding: 0 2px; font-weight: 700; box-shadow: inset 2px 0 0 rgba(251, 191, 36, 0.8); } /* === Humble 专项 v2.4.0: 月卡 + 缩略 + 展开行 === */ .sglv-humble-month-card { padding: 12px 14px; background: rgba(255, 255, 255, 0.03); border: 1px solid rgba(255, 255, 255, 0.06); border-radius: 8px; margin-bottom: 10px; } .sglv-humble-month-head { display: flex; align-items: baseline; gap: 8px; flex-wrap: wrap; } .sglv-humble-month-title { font-size: 13px; font-weight: 700; color: #e2e8f0; } .sglv-humble-month-count { font-size: 11px; color: #94a3b8; } .sglv-humble-month-owned { margin-left: auto; font-size: 11px; font-weight: 700; color: #4caf50; } .sglv-humble-month-owned:empty, .sglv-humble-month-owned[data-zero="1"] { color: #8f98a0; } /* 月卡顶部 3-5 个游戏缩略 */ .sglv-humble-game-thumbs { display: flex; gap: 6px; margin: 8px 0 0 0; flex-wrap: wrap; } .sglv-humble-game-thumb { position: relative; width: 48px; height: 48px; border-radius: 4px; overflow: hidden; background: rgba(255, 255, 255, 0.05); border: 1px solid rgba(255, 255, 255, 0.08); flex-shrink: 0; } .sglv-humble-game-thumb img { width: 100%; height: 100%; object-fit: cover; display: block; } .sglv-humble-game-thumb.no-img { background: linear-gradient(135deg, rgba(102, 192, 244, 0.08), rgba(139, 92, 246, 0.08)); } .sglv-humble-game-thumb.owned { border-color: rgba(76, 175, 80, 0.5); box-shadow: 0 0 0 1px rgba(76, 175, 80, 0.2); } .sglv-humble-game-thumb-mark { position: absolute; top: 1px; right: 1px; width: 14px; height: 14px; background: #4caf50; color: #fff; font-size: 10px; font-weight: 700; border-radius: 50%; display: flex; align-items: center; justify-content: center; line-height: 1; } .sglv-humble-game-thumb-more { width: 48px; height: 48px; border-radius: 4px; background: rgba(255, 255, 255, 0.04); border: 1px dashed rgba(255, 255, 255, 0.15); display: flex; align-items: center; justify-content: center; font-size: 11px; font-weight: 600; color: #94a3b8; flex-shrink: 0; } /* 展开行 */ .sglv-humble-month-details { margin-top: 8px; } .sglv-humble-month-summary { cursor: pointer; font-size: 11px; color: #66c0f4; user-select: none; padding: 2px 0; } .sglv-humble-month-rows { margin-top: 6px; display: flex; flex-direction: column; gap: 2px; } .sglv-humble-row { display: flex; align-items: center; gap: 8px; padding: 4px 6px; border-radius: 4px; font-size: 12px; color: #cbd5e1; transition: background 0.15s; } .sglv-humble-row:hover { background: rgba(102, 192, 244, 0.08); } .sglv-humble-row.owned { color: #4caf50; } .sglv-humble-row-icon { width: 24px !important; height: 24px !important; flex-shrink: 0; border-radius: 3px; object-fit: cover; background: rgba(255, 255, 255, 0.05); } .sglv-humble-row-owned, .sglv-humble-row-missing { flex: none; width: 16px; text-align: center; font-weight: 700; } .sglv-humble-row-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .sglv-humble-row-pub { flex: none; font-size: 10px; color: #8f98a0; } .sglv-humble-row-link { flex: none; font-size: 10px; color: #66c0f4; text-decoration: none; } .sglv-humble-row-link:hover { text-decoration: underline; } /* ==================== v2.9.6: 年度大作 列表边距收紧 ==================== */ /* 工具栏上下留白过大(搜索框行与内容区之间出现明显空隙),整体收紧 */ .sgc-panel .sglv-goty-toolbar-row { padding: 2px 8px 4px !important; gap: 5px !important; } /* 滚动区顶部 + 年份块/分组之间的间距收紧(年份块 14px + 分组 12px 叠加出 26px 空隙) */ /* v2.9.8: padding-top 归零——原 2px padding 与 sticky 分组标题栏(top:0)组合,吸附后标题栏停在 滚动口顶 +2px,该 2px 缝隙无栏体遮挡 → 滚过的封面从中透出(顶部穿透)。静止留白改用首元素 margin-top(随内容滚走,不影响吸附),吸附时标题栏与滚动口严丝合缝。 */ .sgc-panel .sglv-goty-scroll { padding-top: 0; } .sgc-panel .sglv-goty-scroll > :first-child { margin-top: 2px; } .sgc-panel .sglv-goty-year-block { margin-bottom: 8px; } .sgc-panel .sglv-goty-group { margin-bottom: 6px; } .sgc-panel .sglv-goty-group-header { margin-bottom: 6px; padding: 6px 10px; } /* 时间轴行自身留白收紧 */ .sgc-panel .sglv-goty-timeline { padding: 4px 14px 2px; margin: 0 2px 2px; } /* 空年份节点(disabled):灰显 + 禁用 hover 发光,消除"点了没反应" */ .sgc-panel .sglv-goty-tl-node[disabled] { cursor: not-allowed; opacity: 0.35; } .sgc-panel .sglv-goty-tl-node[disabled] .sglv-goty-tl-dot { box-shadow: none; } .sgc-panel .sglv-goty-tl-node[disabled]:hover .sglv-goty-tl-dot { transform: none; border-color: rgba(102,192,244,0.55); box-shadow: none; } .sgc-panel .sglv-goty-tl-node[disabled]:hover .sglv-goty-tl-year { color: #64748b; } /* ==================== v2.9.6: KPI 卡片光斑弱化(修复选中/hover 强光斑遮挡文字) ==================== */ /* 根因:主脚本 CSS_KPI 把 .sglv-trend-kpi-card::before 重定义为"全卡渐变 opacity:0/hover:1", 但共享 CSS 库的 ::before 还留着 width:40px/height:40px/border-radius:50%/filter:blur(8px) —— 两者层叠后变成"左上角一团 40x40 圆形高斯模糊光斑",hover/选中时完全遮住标签与图标。 */ .sgc-panel .sglv-trend-kpi-card::before { top: -1px !important; right: -1px !important; bottom: -1px !important; left: -1px !important; width: auto !important; height: auto !important; border-radius: inherit !important; filter: none !important; background: linear-gradient(135deg, rgba(102,192,244,0.10), transparent 52%) !important; opacity: 0; } .sgc-panel .sglv-trend-kpi-card:hover::before { opacity: 0.5; } /* 数值发光(text-shadow 12px currentColor + brightness 滤镜)弱化,避免数字糊成一团 */ .sgc-panel .sglv-trend-kpi-card .sglv-trend-kpi-value { text-shadow: none !important; filter: none !important; } /* 选中态:只保留 accent 描边(去掉 16px 外发光),选中状态用边框表达更清晰 */ .sgc-panel .sglv-trend-kpi-card.active { box-shadow: 0 0 0 1px rgba(102,192,244,0.55) inset !important; } /* hover 抬升 + 多重外发光(含 22px 蓝光晕)收敛为轻阴影 */ .sgc-panel .sglv-trend-kpi-card:hover, .sgc-panel .sglv-trend-kpi-card.clickable:hover { transform: translateY(-1px) !important; box-shadow: 0 3px 10px rgba(0,0,0,0.35) !important; } /* ==================== v2.9.6: Humble 月包缩略图平铺 ==================== */ /* 缩略图不再截断 5 个 + "+N",全量平铺(flex-wrap 自动换行),右侧空白不再浪费 */ .sgc-panel .sglv-humble-game-thumbs { gap: 5px; } .sgc-panel .sglv-humble-game-thumb, .sgc-panel .sglv-humble-game-thumb-more { width: 44px; height: 44px; } /* ==================== v2.9.8: TGA 年度游戏殿堂 ==================== */ /* 金色「年度游戏」时间轴节点(置于年份节点之前) */ .sgc-panel .sglv-goty-tl-node.sglv-goty-tl-goty { padding-right: 12px; margin-right: 4px; } .sgc-panel .sglv-goty-tl-node.sglv-goty-tl-goty::after { content: ''; position: absolute; top: 2px; bottom: 2px; right: 0; width: 1px; background: linear-gradient(180deg, transparent, rgba(245,158,11,0.4), transparent); } .sgc-panel .sglv-goty-tl-node.sglv-goty-tl-goty .sglv-goty-tl-dot { width: 9px; height: 9px; border-color: rgba(245,158,11,0.7); background: radial-gradient(circle, #fde68a 0%, #f59e0b 70%); box-shadow: 0 0 8px rgba(245,158,11,0.6); } .sgc-panel .sglv-goty-tl-node.sglv-goty-tl-goty .sglv-goty-tl-year { color: #fbbf24; } .sgc-panel .sglv-goty-tl-node.sglv-goty-tl-goty:hover .sglv-goty-tl-dot { transform: scale(1.35); border-color: #fde68a; box-shadow: 0 0 14px rgba(245,158,11,0.9); } .sgc-panel .sglv-goty-tl-node.sglv-goty-tl-goty.sglv-goty-tl-active .sglv-goty-tl-dot { background: #fde68a; border-color: #fde68a; box-shadow: 0 0 16px rgba(245,158,11,1), 0 0 5px rgba(255,255,255,0.7); } .sgc-panel .sglv-goty-tl-node.sglv-goty-tl-goty.sglv-goty-tl-active .sglv-goty-tl-year { color: #fde68a; text-shadow: 0 0 10px rgba(245,158,11,0.8); } /* 殿堂 hero 标题条 */ .sglv-tga-hall { padding: 2px 2px 8px; } .sglv-tga-hero { display: flex; align-items: center; gap: 10px; padding: 10px 14px; margin-bottom: 10px; border-radius: 10px; background: linear-gradient(135deg, rgba(245,158,11,0.16), rgba(15,23,42,0.4) 55%); border: 1px solid rgba(245,158,11,0.35); } .sglv-tga-hero-icon { display: inline-flex; color: #fbbf24; flex-shrink: 0; } .sglv-tga-hero-icon svg { width: 26px; height: 26px; } .sglv-tga-hero-txt { min-width: 0; } .sglv-tga-hero-title { font-size: 16px; font-weight: 800; color: #fde68a; letter-spacing: 0.5px; line-height: 1.2; } .sglv-tga-hero-sub { font-size: 10px; font-weight: 700; color: rgba(251,191,36,0.7); letter-spacing: 1.5px; } .sglv-tga-hero-count { margin-left: auto; flex-shrink: 0; font-size: 12px; font-weight: 700; color: #fbbf24; white-space: nowrap; } /* 殿堂冠军墙 */ .sglv-tga-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(104px, 1fr)); gap: 8px; } .sglv-tga-cell { position: relative; display: flex; flex-direction: column; border-radius: 9px; overflow: hidden; cursor: pointer; background: rgba(15,23,42,0.5); border: 1px solid rgba(245,158,11,0.22); transition: transform 0.15s, border-color 0.2s, box-shadow 0.2s; } .sglv-tga-cell:hover { transform: translateY(-3px); border-color: rgba(245,158,11,0.75); box-shadow: 0 8px 22px rgba(0,0,0,0.45), 0 0 14px rgba(245,158,11,0.25); } .sglv-tga-cell.not-owned { opacity: 0.72; } .sglv-tga-cell.not-owned:hover { opacity: 1; } .sglv-tga-poster { position: relative; width: 100%; aspect-ratio: 2/3; background: #0f172a; overflow: hidden; } .sglv-tga-poster-img { width: 100%; height: 100%; object-fit: cover; display: block; } .sglv-tga-year-badge { position: absolute; top: 5px; left: 5px; z-index: 3; padding: 1px 7px; border-radius: 10px; font-size: 11px; font-weight: 800; color: #1a1206; letter-spacing: 0.5px; background: linear-gradient(135deg, #fde68a, #f59e0b); box-shadow: 0 1px 5px rgba(0,0,0,0.5); } .sglv-tga-crown { position: absolute; top: 4px; right: 5px; z-index: 3; display: flex; align-items: center; gap: 1px; color: #fbbf24; filter: drop-shadow(0 1px 3px rgba(0,0,0,0.7)); font-size: 10px; font-weight: 800; } .sglv-tga-crown svg { width: 15px; height: 15px; } .sglv-tga-crown.multi svg { width: 13px; height: 13px; } .sglv-tga-cell-info { padding: 5px 7px 6px; display: flex; flex-direction: column; gap: 3px; } .sglv-tga-cell-name { font-size: 11.5px; font-weight: 700; color: #f1f5f9; line-height: 1.25; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .sglv-tga-tag { display: inline-flex; align-items: center; gap: 2px; align-self: flex-start; font-size: 9px; font-weight: 700; padding: 1px 5px; border-radius: 3px; line-height: 1.4; color: #94a3b8; background: rgba(148,163,184,0.12); border: 1px solid rgba(148,163,184,0.2); } .sglv-tga-tag.owned { color: #66bb6a; background: rgba(102,187,106,0.18); border-color: rgba(102,187,106,0.35); } .sglv-tga-excl-type { display: inline-flex; align-items: center; align-self: flex-start; font-size: 9px; font-weight: 700; padding: 1px 5px; border-radius: 3px; line-height: 1.4; border: 1px solid currentColor; background: rgba(255,255,255,0.05); max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } /* 非 Steam 平台占位画(平台主色 SVG + 平台名 + 提示;有商店图则叠加) */ .sglv-tga-excl-art { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 4px; padding: 6px; text-align: center; background: radial-gradient(circle at 50% 35%, rgba(255,255,255,0.08), rgba(15,23,42,0.85)); } .sglv-tga-excl-art svg { width: 34px; height: 34px; opacity: 0.9; } .sglv-tga-excl-name { font-size: 10px; font-weight: 700; color: currentColor; line-height: 1.2; } .sglv-tga-excl-hint { font-size: 9px; color: rgba(148,163,184,0.75); } .sglv-tga-excl-img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; z-index: 2; } /* 年度大作卡片上的金色 👑 年度游戏 chip */ .sglv-goty-tga-chip { display: inline-flex; align-items: center; gap: 2px; cursor: pointer; font-size: 9px; font-weight: 800; padding: 1px 5px; border-radius: 3px; line-height: 1.4; color: #1a1206; background: linear-gradient(135deg, #fde68a, #f59e0b); border: 1px solid rgba(245,158,11,0.6); white-space: nowrap; } .sglv-goty-tga-chip:hover { filter: brightness(1.12); box-shadow: 0 0 8px rgba(245,158,11,0.6); } /* 提名弹窗 */ .sglv-tga-modal { position: fixed; inset: 0; z-index: 2147483000; display: flex; align-items: center; justify-content: center; background: rgba(4,8,16,0.72); backdrop-filter: blur(3px); -webkit-backdrop-filter: blur(3px); padding: 20px; } .sglv-tga-modal-win { display: flex; flex-direction: column; width: 100%; max-width: 720px; max-height: 86vh; background: #141d2e; border: 1px solid rgba(245,158,11,0.4); border-radius: 12px; box-shadow: 0 20px 60px rgba(0,0,0,0.6), 0 0 30px rgba(245,158,11,0.12); overflow: hidden; } .sglv-tga-modal-head { display: flex; align-items: center; gap: 8px; padding: 12px 16px; flex-shrink: 0; background: linear-gradient(135deg, rgba(245,158,11,0.18), rgba(20,29,46,0.2)); border-bottom: 1px solid rgba(245,158,11,0.25); } .sglv-tga-modal-trophy { display: inline-flex; color: #fbbf24; } .sglv-tga-modal-trophy svg { width: 20px; height: 20px; } .sglv-tga-modal-title { font-size: 15px; font-weight: 800; color: #fde68a; white-space: nowrap; } .sglv-tga-modal-sub { font-size: 11px; font-weight: 600; color: rgba(251,191,36,0.8); white-space: nowrap; } .sglv-tga-modal-close { margin-left: auto; display: inline-flex; cursor: pointer; color: #94a3b8; padding: 2px; border-radius: 4px; transition: color 0.15s, background 0.15s; } .sglv-tga-modal-close:hover { color: #f8fafc; background: rgba(255,255,255,0.1); } .sglv-tga-modal-close svg { width: 18px; height: 18px; } .sglv-tga-modal-body { display: flex; gap: 14px; padding: 14px 16px; overflow-y: auto; } .sglv-tga-noms-side { flex-shrink: 0; width: 168px; display: flex; flex-direction: column; gap: 6px; } .sglv-tga-noms-side-top { display: flex; align-items: center; gap: 6px; } .sglv-tga-side-year { font-size: 13px; font-weight: 800; color: #fde68a; } .sglv-tga-side-cat { font-size: 10px; font-weight: 700; color: rgba(251,191,36,0.75); } .sglv-tga-winner-poster { position: relative; width: 100%; aspect-ratio: 2/3; border-radius: 8px; overflow: hidden; background: #0f172a; border: 2px solid rgba(245,158,11,0.65); box-shadow: 0 4px 16px rgba(0,0,0,0.4); cursor: pointer; } .sglv-tga-winner-poster.excl { cursor: default; } .sglv-tga-winner-img { width: 100%; height: 100%; object-fit: cover; display: block; } .sglv-tga-noms-side-name { font-size: 13px; font-weight: 700; color: #f1f5f9; line-height: 1.3; } .sglv-tga-noms-side-own { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; } .sglv-tga-winner-badge { display: inline-flex; align-items: center; font-size: 10px; font-weight: 800; padding: 2px 8px; border-radius: 4px; color: #1a1206; background: linear-gradient(135deg, #fde68a, #f59e0b); } .sglv-tga-noms-grid { flex: 1; min-width: 0; display: grid; grid-template-columns: 1fr 1fr; gap: 10px; align-content: start; } .sglv-tga-nom-card { display: flex; flex-direction: column; gap: 4px; padding: 6px; border-radius: 8px; cursor: pointer; background: rgba(15,23,42,0.5); border: 1px solid rgba(102,192,244,0.18); transition: border-color 0.2s, transform 0.15s; } .sglv-tga-nom-card:hover { border-color: rgba(102,192,244,0.55); transform: translateY(-2px); } .sglv-tga-nom-card.excl { cursor: default; } .sglv-tga-nom-card.excl:hover { transform: none; border-color: rgba(102,192,244,0.18); } .sglv-tga-nom-img-wrap { position: relative; width: 100%; aspect-ratio: 467/181; border-radius: 5px; overflow: hidden; background: #0f172a; } .sglv-tga-nom-img { width: 100%; height: 100%; object-fit: cover; display: block; } .sglv-tga-nom-name { font-size: 11.5px; font-weight: 600; color: #f1f5f9; line-height: 1.25; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .sglv-tga-noms-empty { flex: 1; display: flex; align-items: center; justify-content: center; color: #64748b; font-size: 13px; min-height: 120px; } @media (max-width: 620px) { .sglv-tga-modal-body { flex-direction: column; } .sglv-tga-noms-side { width: 100%; flex-direction: row; align-items: flex-end; gap: 12px; } .sglv-tga-winner-poster { width: 120px; } } `; // ==================== v2.8.0: 统一封面渲染(按 kind) ==================== // 背景:Epic / PS会免 / 系列分类 / 年度大作 / DLC 五个 tab 的「大海报视图」全部加载失败, // 但它们的「网格视图」和「列表视图」正常 —— 说明问题不在数据、不在网络, // 而在这几个 tab 特有的渲染路径。 // // 排查出的三个叠加原因: // ① 一次性锁不可复位:_sgcvChainFallbackImpl 首次进入时置 img._sglvChainLoading = 1 且永不复位。 // 同一 appid 在视图间切换(网格→大海报→网格)时,第二次 onerror 直接被锁死, // chainLoad 永不执行 → 永远停在坏 src 上。用户「切到大海报视图」恰好触发这个路径。 // ② kind 缓存污染:网格视图写入的是竖版 good URL(recordPosterGood(appid, url, 'poster')), // 大海报视图按 'capsule' 读缓存时被 _sgcvUrlMatchesKind 判为方向不符而丢弃, // 于是既拿不到缓存、又被迫走链首的 library_hero(对非新游戏命中率低)。 // ③ 跨上下文 inline onerror:这五处都依赖挂在 unsafeWindow 上的 // _sglvChainFallback / _sglvRecordPosterGood 才能回退,一旦某次注入失败或被覆盖, // onerror 就是个 undefined 函数,图片静默停在坏 src 上(无任何可见错误)。 // // 统一方案:全部改走 v2.7.0 的 bindRestrictedCoverLoaders(addEventListener + 闭包链索引, // 无跨上下文依赖、无一次性锁、每次渲染重新绑定),按 kind 给出不同的 URL 链与容器类。 // ==================================================================== /** 按 kind 返回统一封面链(横向优先,命中率高) * - 'poster' → 卡片视图用,横图 letterbox * - 'capsule' → 大海报视图用,横向大图铺满 * - 'hero' → 系列/供应商视图用,超宽横图 */ function unifiedCoverChain(appid, kind, preferVertical) { const id = String(appid); const cdn = [ 'https://cdn.cloudflare.steamstatic.com/steam/apps/' + id, 'https://shared.akamai.steamstatic.com/store_item_assets/steam/apps/' + id, 'https://cdn.akamai.steamstatic.com/steam/apps/' + id, 'https://shared.fastly.steamstatic.com/store_item_assets/steam/apps/' + id, ]; if (kind === 'poster' && preferVertical) { // v2.9.4: 竖版优先链(与主脚本 coverChainUrls('poster') 保持一致)—— // library_600x900_2x → library_600x900 → header 兜底 // 拿不到竖版时自动落到 header.jpg(横版 letterbox),逻辑不变 const files = ['library_600x900_2x.jpg', 'library_600x900.jpg', 'header.jpg']; const out = []; for (const f of files) for (let i = 0; i < cdn.length; i++) out.push(cdn[i] + '/' + f); return out; } if (kind === 'hero') { // hero:优先 library_hero(系列视图专属,超宽比例) return [ cdn[0] + '/library_hero.jpg', cdn[1] + '/library_hero.jpg', cdn[2] + '/library_hero.jpg', cdn[3] + '/library_hero.jpg', cdn[0] + '/header.jpg', cdn[1] + '/header.jpg', cdn[2] + '/header.jpg', cdn[3] + '/header.jpg', cdn[0] + '/capsule_467x181.jpg', cdn[1] + '/capsule_467x181.jpg', ]; } // poster / capsule:统一横向链(header 命中率最高,capsule_467x181 兜底) return [ cdn[0] + '/header.jpg', cdn[1] + '/header.jpg', cdn[2] + '/header.jpg', cdn[3] + '/header.jpg', cdn[0] + '/capsule_467x181.jpg', cdn[1] + '/capsule_467x181.jpg', cdn[0] + '/capsule_231x87.jpg', cdn[1] + '/capsule_231x87.jpg', ]; } /** * 统一封面组件(替代 epicCapsuleImg / psplusCapsuleImg / seriesCapsuleImg / gotyCoverImg / dlcPosterImg) * @param {number|string} appid * @param {string} name * @param {'poster'|'capsule'|'hero'} kind * @param {Object} [opts] * @param {string} [opts.imgCls] - img 类名(默认按 kind 推断) * @param {boolean} [opts.isBlocked] - 锁区红色锁占位 * @returns {string} HTML */ function unifiedCover(appid, name, kind, opts) { const o = opts || {}; const k = kind || 'poster'; if (!appid) { // 无 appid(PS 独占游戏)—— 显示占位容器,不生成坏 img return '
' + Host.wlEscape(name || (Host.isZh ? '无封面' : 'No Cover')) + '
'; } const imgCls = o.imgCls || (k === 'poster' ? 'sglv-card-img' : 'sglv-wl-cover-img'); const safeName = Host.wlEscape(name || ''); const brokenCls = 'sglv-img-broken' + (o.isBlocked ? ' sglv-img-broken-blocked' : ''); // v2.9.4: preferVertical —— 竖版海报卡片墙(系列/PS/Epic) const preferVertical = !!o.preferVertical; const chain = unifiedCoverChain(appid, k, preferVertical); // 已有 good 缓存则优先用(跨视图共享): // ① v2.9.3: coverGoodUrl —— 方向门控 + 横版 header/capsule 交叉槽位, // 同一张图不再由主面板/收藏/PS/Epic 各探一次 // ② v2.9.2: cover-fallback 的跨会话缓存 let first = ''; try { first = coverGoodUrl(String(appid), k) || ''; } catch (e) { /* ignore */ } // 竖版槽位里的横版条目 = 上次已确认该游戏无竖版资产(链耗尽标记): // 直接拿来 letterbox,省掉每次重新吃 8 个 404 if (!first && k === 'poster') { try { first = coverHorizontalFallbackUrl(String(appid)) || ''; } catch (e) { /* ignore */ } } try { const fb = _coverFb(); if (!first && fb && typeof fb.getCoverUrl === 'function') { first = fb.getCoverUrl(String(appid), k, coverLang()) || ''; } } catch (e) { /* ignore */ } first = first || chain[0]; // v2.9.2: wrapper 必须带 data-cover-appid —— bindRestrictedCoverLoaders 用 // `.sglv-img-wrapper[data-cover-appid]` 选择;此前只写 data-appid, // 选择器一个都匹配不到 → 从不绑定 → sglv-img-loading 永不摘除 // → .sglv-wl-cover-img-wrap 下 opacity:0,大海报视图全是空白。 return '
' + '' + safeName + '' + '
' + _restrictedBrokenInner(name, o.isBlocked) + '
' + '
'; } // v1.9.24: 锁区游戏 SVG 锁图案——用于标签页图标和 KPI 卡片图标 // 全新样式:渐变锁体 + 弧形锁扣 + 钥匙孔,带红色警示色调 const BLOCKED_LOCK_ICON_SVG = '' + '' + '' + '' + '' + ''; // v1.9.24: 锁区游戏 SVG 锁图案——最终兜底占位符 // 使用递增序号生成唯一 gradient ID 避免多实例冲突 let _blockedCoverSeq = 0; function blockedCoverSvg() { const sid = '_blk' + (_blockedCoverSeq++); return '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + ''; } // v1.9.24: 锁区游戏封面兜底 DOM(CDN + API 全部失败时展示) function blockedPlaceholderDom(name) { const holder = document.createElement('div'); holder.className = 'sglv-blocked-cover-placeholder'; holder.innerHTML = blockedCoverSvg() + '
' + Host.wlEscape(name || '') + '
'; return holder; } // v1.9.24: 锁区游戏封面全局回退——Steam CDN 全部失败时先用 Store API 取真实封面 URL, // API URL 仍加载失败时替换为 SVG 锁占位符(参照 _sglvPsCoverFallback 逻辑) // v1.9.29: 传递 kind 参数,使 API 兜底按图片类型选择最佳 URL unsafeWindow._sglvBlockedCoverFallback = function(img, appid, kind) { if (!img || !img.parentElement) return; Host.fetchCoverApiUrl(appid, kind).then(url => { if (url) { img.onerror = function() { img.onerror = null; img.parentElement.replaceChild(blockedPlaceholderDom(img.alt), img); }; img.src = url; return; } img.parentElement.replaceChild(blockedPlaceholderDom(img.alt), img); }); }; // v1.9.24: 锁区游戏列表视图图标回退——CDN 图标失败时替换为锁图标占位 div unsafeWindow._sglvBlockedListIconFallback = function(img) { if (!img || !img.parentElement) return; const holder = document.createElement('div'); holder.className = 'sglv-list-icon sglv-blocked-list-icon'; holder.innerHTML = ''; img.parentElement.replaceChild(holder, img); }; // v1.9.24: 锁区游戏竖版封面——Steam 多 CDN 回退链 + Store API + SVG 锁兜底 // v2.0.0: 统一 onerror 委托 _sglvChainFallback(失败时由 chainLoad JS 接管整链 + API 兜底) // 锁占位 SVG 由 _sglvChainFallbackImpl → onGiveUp(若 chainLoad 完全失败) → 后续由 blocked 专用回调接管 // v2.9.22: sgc-panel 拖动(参考 steam-friend-manager 1.2.5 makeDraggable) // 用 !important 覆盖 shared CSS 中 sglv-panel 的 top/left/transform 定位 function makeSgcDraggable(el, handle) { if (!el || !handle) return; let isDragging = false, startX = 0, startY = 0, startLeft = 0, startTop = 0; const onDown = (e) => { const t = e.target; if (t.closest('button, input, select, textarea, label, a')) return; isDragging = true; startX = e.clientX; startY = e.clientY; const rect = el.getBoundingClientRect(); startLeft = rect.left; startTop = rect.top; el.style.cursor = 'grabbing'; e.preventDefault(); }; const onMove = (e) => { if (!isDragging) return; el.style.setProperty('left', (startLeft + e.clientX - startX) + 'px', 'important'); el.style.setProperty('top', (startTop + e.clientY - startY) + 'px', 'important'); el.style.setProperty('right', 'auto', 'important'); el.style.setProperty('bottom', 'auto', 'important'); el.style.setProperty('transform', 'none', 'important'); }; const onUp = () => { if (!isDragging) return; isDragging = false; el.style.cursor = ''; }; handle.addEventListener('mousedown', onDown); document.addEventListener('mousemove', onMove); document.addEventListener('mouseup', onUp); } function init(ctx) { if (!ctx || typeof ctx !== 'object') { console.warn('[SGLVCollection] init: invalid ctx'); return false; } if (ctx.apiVersion !== apiVersion) { console.warn('[SGLVCollection] Host apiVersion mismatch: expected', apiVersion, 'got', ctx.apiVersion); // 尝试用宿主的 showToast 提示(可能不可用) try { if (ctx.showToast) { const zh = ctx.isZh; ctx.showToast(zh ? '收藏模块版本不兼容,请更新主脚本或收藏模块' : 'Collection module version mismatch, please update host script or collection module'); } } catch (e) { /* ignore */ } return false; } Host = ctx; // v1.9.47-fix: 同步预热绝版游戏远程源 TTL 缓存(避免开 tab 才发起请求,首屏秒开) try { _warmDelistedRemoteCache(); } catch (e) { /* 忽略 */ } return true; } // ==================== 游戏收藏模块 ==================== // v1.9.5: 永久缓存层——绕过宿主 TTL 缓存 // v1.9.6: 从 GM_getValue/GM_setValue 迁移到 SGLVCore.IDB // 原因:GM_setValue 在多数环境有 5MB 限制,大收藏数据(数千条 + 元数据)可能撑爆 // IDB 容量无限制,且与主脚本 PCC 持久化层同源,统一管理 // 旧 key 'sglv_perm_xxx' 兼容:首次读取时尝试从旧 GM key 迁移,迁移后清旧 key const PERM_CACHE_PREFIX = 'sglv_idb_perm_'; const PERM_CACHE_GM_PREFIX = 'sglv_perm_'; // v1.9.5 旧 key,用于一次性迁移 const _C_IDB = _C && _C.IDB; function _permCacheGet(key) { // 1) 优先从 IDB 读 if (_C_IDB) { try { const v = _C_IDB.get(PERM_CACHE_PREFIX + key, null); if (v != null) return v; } catch (e) { /* IDB 读失败,降级到旧 GM */ } } // 2) 旧 GM 兜底(一次性迁移)— 读旧 key 并迁移到 IDB try { const raw = GM_getValue(PERM_CACHE_GM_PREFIX + key, ''); if (!raw) return null; const parsed = JSON.parse(raw); // 立即迁移到 IDB if (_C_IDB && parsed != null) { try { _C_IDB.set(PERM_CACHE_PREFIX + key, parsed); } catch (e) { /* ignore */ } // 迁移成功后清旧 key(可选,这里保留以防 IDB 写入失败) // 不主动清,让 IDB 读优先 + 下次读时也会再次尝试迁移 } return parsed; } catch { return null; } } function _permCacheSet(key, data) { if (_C_IDB) { try { _C_IDB.set(PERM_CACHE_PREFIX + key, data); return; } catch (e) { /* IDB 失败,降级 */ } } // 降级到旧 GM try { GM_setValue(PERM_CACHE_GM_PREFIX + key, JSON.stringify(data)); } catch (e) { /* ignore quota */ } } // v1.9.5: 按 appid 增量合并——新数据覆盖同 appid 条目,旧数据中独有的条目保留 function _mergeByAppid(oldItems, newItems) { if (!Array.isArray(oldItems) || oldItems.length === 0) return newItems || []; if (!Array.isArray(newItems) || newItems.length === 0) return oldItems; const map = new Map(); oldItems.forEach(g => { if (g && g.appid) map.set(g.appid, g); }); newItems.forEach(g => { if (g && g.appid) map.set(g.appid, g); }); return Array.from(map.values()); } // v1.9.5: appid 数组增量合并(去重) function _mergeAppidArray(oldIds, newIds) { const set = new Set(oldIds || []); (newIds || []).forEach(id => set.add(id)); return Array.from(set); } // v1.9.5: 后台刷新节流检查——intervalMs 内已刷新过则跳过 function _shouldThrottle(lastTs, intervalMs) { return lastTs > 0 && (Date.now() - lastTs) < intervalMs; } // v1.9.5: debounce 工具函数——避免搜索框每次按键触发完整重渲染 function _debounce(fn, delay = 200) { let timer = null; const debounced = function(...args) { if (timer) clearTimeout(timer); timer = setTimeout(() => { fn.apply(this, args); timer = null; }, delay); }; return debounced; } // v1.9.5: 缓存 Intl.Collator 实例,避免每次过滤都重新构造 const _nameCollator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }); let _collectionActiveTab = 'publisher'; // v1.0.4: 默认标签改为"供应商/系列"(与新 tab 顺序一致) let _collectionBodyInitialized = false; // v2.9.22: 跟踪 body 是否已首次渲染——避免首次打开闪一帧骨架 let collectionOverlayEl = null; let collectionPanelEl = null; // ---------- 模块本地状态(v2.6.4 起不再挂主 state,库化后天然隔离) ---------- // v1.8.2: mode = 'publisher' | 'series' — 供应商/系列双模式切换(系列数据独立展示不合并) // v2.9.92: 新增 supplierResult/seriesResult 跟踪各自刷新结果(updated/nochange/error) // v1.9.40: 移除 supplierFetchedAt/seriesFetchedAt——更新时间文本不再常驻工具栏(曾压缩切换按钮致变形), // 刷新结果改为悬浮提示(不参与 flex 布局) const pubState = { mode: 'publisher', expandedPublishers: new Set(), selectedPublisher: null, selectedSeries: null, viewMode: 'card', filter: 'all', dataLoading: false, refreshStage: '', supplierResult: '', seriesResult: '', showResultUntil: 0, // v1.9.31: 系列详情排序——sortField: order|date|name|appid,sortDir: asc|desc sortField: 'order', sortDir: 'asc' }; // v1.9.19: 系列详情分页状态(供应商/系列详情共用)——pageSize 与其他 tab 保持一致(48) // pageCache: { key: 页码 } 记忆每个系列的浏览页码,切换回已浏览分类时恢复进度 // v2.9.4: 系列分类卡片墙改 7 列 → 每页 49(7×7)刚好铺满,不留半排 const pubDetailState = { page: 1, pageSize: 49, cacheKey: null, pageCache: new Map() }; const delistedState = { search: '', typeFilter: 'all', subFilter: 'all', page: 1, pageSize: 48, viewMode: 'card', // v1.9.32: 绝版游戏排序——appidDesc|appidAsc|dateDesc|dateAsc // v1.9.47-fix: pageSize 50→48——与其他 tab(psplus/epic/blocked/goty/dlc/bundle)保持一致 sort: 'appidDesc' }; const psplusState = { games: [], loaded: false, loading: false, search: '', tierFilter: 'all', statusFilter: 'all', sort: 'dateDesc', page: 1, pageSize: 49, viewMode: 'card', updatedAt: '', loadError: null }; // v2.7.9: Epic 赠送模块状态(数据仅为 Steam appid 数组,名称异步加载) const epicState = { appids: [], loaded: false, loading: false, search: '', ownFilter: 'all', sort: 'appidDesc', page: 1, pageSize: 49, viewMode: 'card', updatedAt: '', loadError: null, source: '' }; // v2.9.7: 年度大作模块状态(数据含 name/date/appid,名称无需异步加载) // v2.x: "GotY 时光机"——年份时间轴 + 分组(未发售/已发售)+ 焦点卡 + 网格 5 列 // 移除 year 单选字段(改用 expandedYears Set 默认全部展开),移除 page/pageSize(网格 5 列滚动) // v2.9.6: 新增 yearFilter —— 年份时间轴节点点击后"真筛选"(null=全部年份); // 旧实现只是 scrollIntoView 滚动定位,平滑滚动中途 active 会漂移到中间年份, // 且停在年份块之间的 margin 空隙上,表现为"点击不生效/位置不准/顶部留白"。 // v2.9.8: 新增 tgaView —— 时间轴金色「年度游戏」节点开启后,滚动区改渲染 TGA 历届 GOTY 殿堂 // (与年份筛选互斥:进入殿堂清 yearFilter,选年份则退出殿堂)。 const gotyState = { games: [], loaded: false, loading: false, availableYears: [], expandedYears: null, search: '', ownFilter: 'all', yearFilter: null, tgaView: false, sort: 'dateDesc', viewMode: 'card', updatedAt: '', loadError: null, source: '', lastFetchAt: 0 }; // v1.9.0: DLC 收藏模块状态——三级渐进加载(Barter.vg DLC DB → Steam 全库存 type → DLC 子类型) // v1.9.1: 加 stage / level*Done 字段——支持 L1∥L2 并行 + 中间阶段增量 rebuild(不阻塞 UI 进程) // v1.9.2: 加 dlcTypeCache 字段——本地 IDB 永久缓存 DLC 子类型映射(只增不减),实现真正增量 const dlcState = { dlcs: [], parentTotalMap: {}, loaded: false, loading: false, loadError: null, search: '', typeFilter: 'all', sort: 'parentAsc', page: 1, pageSize: 48, viewMode: 'card', groupMode: true, expandedParents: new Set(), ownFilter: 'all', // v1.9.4: 全部/已拥有 筛选 stage: 0, // 0=未开始 1=Barter.vg 2=appType 3=DLC 子类型 level1Done: false, // Barter.vg DLC DB 完成 level2Done: false, // Steam 全库存 appType 完成 rebuildQueued: false, // 防抖:同一帧多次 scheduleRebuild 合并 // v1.9.2: 本地 IDB 永久缓存,key=appId,value=type('dlc'/'music'/'video'...) // 加载时用此缓存立即填充 buildDlcList,只 enrich 缓存里没有的 DLC(真正的"只增不减"增量) dlcTypeCache: {}, dlcTypeCacheLoaded: false, // IDB 异步加载完成后置 true idbLoadPromise: null, // 第一次 IDB.loadAll 的 promise(避免重复) // v1.9.3: 后台静默刷新节流(避免短时间内重复 enrich) lastBgRefreshAt: 0, // v1.9.8: 后台 DLC 子类型增量获取中(不阻塞 UI 渲染) dlcTypeEnriching: false, // v1.9.8: 缓存 filteredDlc 结果(filters/search/sort 未变时跳过重算) _filteredCache: null, _filteredCacheKey: null, }; // v1.9.2: IDB 缓存 schema 版本号(用于 cache invalidation 升级) // v1.9.3: 版本号稳定为 1——业务 key(dlc_subtype_map)+ 内容 schema 都没变,lib 升级不应清缓存 const _DLC_CACHE_VERSION = { dlc_subtype: 1 }; // v1.9.14: 捆绑包标签页状态——复用 DLC 进包数据(Host.getBundleCount + Host.getDlcsByParentMap) const bundleState = { data: [], // [{appid,name,isOwned,totalBundle,dlcCount,dlcs:[{appid,name,bundleCount,isOwned,playtime}]}] loaded: false, loading: false, // v2.5.0: Bundle 数据库加载中 loadError: false, // v2.5.0: Bundle 数据库加载失败 search: '', sort: 'bundleDesc', page: 1, pageSize: 48, }; const _DLC_TYPE_CACHE_IDB_KEY = 'dlc_subtype_map'; // v1.9.3: 后台静默刷新节流——6h(与 cloud-save 同步,避免短时间内重复跑 L1+L2+L3) const _DLC_BG_REFRESH_INTERVAL = 6 * 3600 * 1000; // v1.9.1: DLC 三级加载阶段文案(loading 骨架中央显示当前阶段) const DLC_STAGES = [ null, // 0 占位 { pct: 15, zh: '加载 Barter.vg DLC 数据库…', en: 'Loading Barter.vg DLC DB…' }, { pct: 55, zh: '补全 Steam 全库存应用类型…', en: 'Enriching Steam app types…' }, { pct: 85, zh: '获取 DLC 子类型(音乐/视频…)…', en: 'Fetching DLC subtypes…' }, ]; // ==================== v2.2.0: 受限游戏板通用组件 ==================== // 仿 steam-friend-manager buildDelistedBoardData + makeDelistedCardsRow 风格, // 抽象出"受限游戏板(绝版/锁区/将来可能的 wishlist 锁区 等)"通用数据层 + UI 组件, // 替代每个 tab 各自维护一套内联模板字符串。 // // 用法: // const board = makeRestrictedBoardData(myGames, restrictedList, { typeKey, typeLabelMap }); // const heroHtml = makeRestrictedHero({ total, ownedCount, scopeBase, typeKeys, ... }); // const cardHtml = makeRestrictedCard({ appid, name, isOwned, typeLabel, ... }); // const listHtml = makeRestrictedListItem({ appid, name, isOwned, ... }); // ============================================================ /** 构建受限游戏板数据:来源游戏 ∩ 受限数据库 * @param {Array} sourceEntries - 来源游戏 [{appid, name, ...}] * @param {Array} restrictedList - 受限数据库 [{appid, name, type, changed, ...}] * @param {Object} [opts] * @param {Function} [opts.typeKey] - 标准化 type 字段(默认直接取 a.type) * @returns {{owned: Array, missing: Array, allApps: Array, total: number}} */ function makeRestrictedBoardData(sourceEntries, restrictedList, opts) { const o = opts || {}; const typeKeyFn = o.typeKey || ((a) => a.type || 'default'); const ownedIds = new Set(); const ownedEntryMap = new Map(); (sourceEntries || []).forEach(s => { if (s && s.appid != null) { const id = Number(s.appid); ownedIds.add(id); ownedEntryMap.set(id, s); } }); const owned = []; const missing = []; const allApps = []; (restrictedList || []).forEach(app => { if (!app || app.appid == null) return; const appid = Number(app.appid); if (!appid) return; const entry = { appid, name: app.name || ('App ' + appid), type: typeKeyFn(app) || 'default', changed: app.changed || app.delistedAt || '', _meta: app // 保留原始数据,调用方可读取附加字段(achievements / owners 等) }; allApps.push(entry); if (ownedIds.has(appid)) { owned.push(Object.assign({ sourceEntry: ownedEntryMap.get(appid) }, entry)); } else { missing.push(entry); } }); return { owned, missing, allApps, total: restrictedList ? restrictedList.length : 0 }; } /** KPI 卡片行:总数 / 已拥有 / 未拥有 + 类型筛选 * @param {Object} opts * @param {number} opts.total * @param {number} opts.ownedCount * @param {number} opts.missingCount * @param {Array} opts.scopeBase - 范围筛选基础列表('all' / 'owned' / 'missing' 切换) * @param {string} opts.scope - 'all' | 'owned' | 'missing' * @param {string} opts.typeFilter - 'all' | * @param {string[]} opts.labels - [总数, 拥有, 未拥有] 三档文案 * @param {string[]} [opts.typeKeys] - 类型 key 列表(决定渲染几个类型卡) * @param {Object} [opts.typeColors] - { typeKey → 颜色 } * @param {Object} [opts.typeLabels] - { typeKey → 标签 } * @param {string} opts.tabId - 用于事件委托的 data-attr 前缀 */ /** * 受限游戏板 HERO —— v2.6.0 重设计 * * 旧设计的问题(截图实证):一行 7 张等宽小卡横排,每个数字都是同一视觉权重, * 浮窗再宽也铺不满 → 大片留白;而真正有决策价值的"哪类占多数"完全看不出来。 * * 新设计:左大右小的仪表盘结构,天然铺满任意宽度。 * 左区 主数字(锁区总数)+ 拥有率细进度条 + 两个 scope 卡(在库/未拥有) * 右区 类型占比条形列表,每行 = 分类色块 + 名称 + 占比条 + 数量 + 百分比 * 交互:scope 卡切换拥有态筛选;类型行点击切换类型筛选(再次点击同一行回到全部)。 * * @param {Object} opts 含 total / ownedCount / scopeBase / scope / typeFilter / typeKeys / typeColors / typeLabels / tabId / title */ function makeRestrictedHero(opts) { const o = opts || {}; const tabId = o.tabId || 'sgr'; const scope = o.scope || 'all'; const typeFilter = o.typeFilter || 'all'; const typeKeys = o.typeKeys || []; const typeColors = o.typeColors || {}; const typeLabels = o.typeLabels || {}; const total = o.total || 0; const ownedCount = o.ownedCount || 0; const scopeBase = o.scopeBase || []; const title = o.title || (Host.isZh ? '受限总数' : 'Total'); // 类型计数(基于当前 scope 收窄后的列表)+ 占比 const typeStats = typeKeys.map(function (key) { const count = scopeBase.filter(function (g) { return g.type === key; }).length; return { key: key, count: count, color: typeColors[key] || '#94a3b8', label: typeLabels[key] || key }; }).filter(function (t) { return t.count > 0; }); const statSum = typeStats.reduce(function (s, t) { return s + t.count; }, 0) || 1; const ownedPct = total > 0 ? Math.round(ownedCount / total * 100) : 0; // 左区:scope 卡(在库 / 未拥有)—— 主数字已表达"全部",这里不再重复一个"全部"卡 const scopeCards = '
' + '
' + '' + ownedCount.toLocaleString() + '' + '' + (Host.isZh ? '在库' : 'Owned') + '' + '
' + '
' + '' + (total - ownedCount).toLocaleString() + '' + '' + (Host.isZh ? '未拥有' : 'Missing') + '' + '
' + '
'; // 右区:类型占比条形列表 const typeRows = typeStats.map(function (t) { const pct = Math.round(t.count / statSum * 100); const active = typeFilter === t.key; return '
' + '' + '' + Host.wlEscape(t.label) + '' + '' + '' + t.count.toLocaleString() + '' + '' + pct + '%' + '
'; }).join(''); return '
' + '
' + '
' + Host.wlEscape(title) + '
' + '
' + total.toLocaleString() + '
' + '
' + '
' + '
' + '
' + (Host.isZh ? '已收集' : 'Collected') + ' ' + ownedPct + '%
' + scopeCards + '
' + '
' + '
' + (Host.isZh ? '分类占比' : 'By category') + '
' + (typeRows || '
' + (Host.isZh ? '无分类数据' : 'No category data') + '
') + '
' + '
'; } // v2.6.0: 筛选区统一由 makeRestrictedHero 渲染(HERO 仪表盘), // 此处不再保留旧的一排等宽 KPI 小卡实现。 /** 受限游戏卡片(卡片视图)— 封面 + 名称 + 类型徽章 + 拥有徽章 + meta 项 * @param {Object} opts * @param {number} opts.appid * @param {string} opts.name * @param {boolean} opts.isOwned * @param {string} [opts.typeLabel] - 顶部类型徽章文本 * @param {string} [opts.typeKey] - 用于 class="sglv-type-" 着色 * @param {string} [opts.typeColor] - 徽章主色(默认 #f44336 红色系) * @param {Array} [opts.metaItems] - 附加 meta 项(每个是 HTML 片段) * @param {string} [opts.clickUrl] - 自定义跳转 URL * @param {string} [opts.coverHtml] - 自定义封面 HTML(默认 restrictedCoverImg) * @returns {string} HTML */ // v2.5.0: 徽章配色工具——typeColor 是实色(如 #fb923c),直接拿来做 background 会得到 // 与文字同色的实心方块(截图里的橙色/紫色块,文字完全不可见)。 // 这里把实色转成低透明度背景 + 实色文字 + 实色描边,保证文字始终可读。 function _badgeColors(hex) { const c = hex || '#f44336'; const m = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(c); if (!m) return { bg: 'rgba(244,67,54,0.15)', fg: '#f44336', border: 'rgba(244,67,54,0.28)' }; const r = parseInt(m[1], 16), g = parseInt(m[2], 16), b = parseInt(m[3], 16); return { bg: 'rgba(' + r + ',' + g + ',' + b + ',0.14)', fg: '#' + m[1] + m[2] + m[3], border: 'rgba(' + r + ',' + g + ',' + b + ',0.32)' }; } // v2.6.0: 状态斜切带(signature element)——取代原先的「未拥有/已拥有」实心标签块。 // 旧方案的问题:彩色实心底 + 同色文字,视觉上就是一个读不出内容的色块(截图里的紫色方块), // 而且每张卡都挂一个色块,卡片信息区被挤成两行。 // 新方案:把状态做成封���右下角的一道斜切色带(纯色无文字),状态文字移入下方 meta 栏, // 卡片因此省下一整行,信息区得以压缩成两栏。 // 未拥有 → 琥珀色带(#f59e0b),提示"这个你还没有" // 已拥有 → 绿色细带(#34d399),细一些表示次要 function _stateRibbon(isOwned) { // v2.9.5: 移除封面右下角的琥珀色/绿色斜切带 —— // 7 列紧凑卡片里它贴着封面底边,视觉上就是"一块黄色背景", // 而卡片下方已有「购买已禁用/未拥有/已拥有」徽章表达同一信息。 // 保留函数 + CSS(.sglv-own-flag)以便随时回滚。 void isOwned; return ''; } /** * 受限游戏卡片 —— v2.6.0 重构版式 * 封面(横向图 letterbox + 右下角状态斜切带) * 名称行(游戏名 + appid) * 两栏 meta:左 = 分类徽章 + 拥有态文字;右 = 日期 / 数值类信息 */ function makeRestrictedCard(opts) { const o = opts || {}; const appid = Number(o.appid); const name = o.name || ('App ' + appid); const isOwned = !!o.isOwned; const clickUrl = o.clickUrl || ('https://store.steampowered.com/app/' + appid); const coverHtml = o.coverHtml != null ? o.coverHtml : restrictedCoverImg(appid, name, 'poster', { isBlocked: !!o.isBlocked }); // 两栏布局:left = 分类徽章 + 拥有态;right = 日期 / 统计 const metaLeft = []; if (o.typeLabel && o.typeKey) { const bc = _badgeColors(o.typeColor); metaLeft.push('' + Host.wlEscape(o.typeLabel) + ''); } if (o.showOwnText !== false) { metaLeft.push('' + (isOwned ? '✓ ' + Host.wlEscape(Host.T.owned || '已拥有') : Host.wlEscape(Host.T.missing || '未拥有')) + ''); } const metaRight = (o.metaItems || []).filter(Boolean); const twoCol = '
' + '
' + metaLeft.join('') + '
' + '
' + metaRight.join('') + '
' + '
'; return '
' + '
' + coverHtml + _stateRibbon(isOwned) + '
' + '
' + '
' + '' + Host.wlEscape(name) + '' + '' + appid + '' + '
' + twoCol + '
' + '
'; } function makeRestrictedListItem(opts) { const o = opts || {}; const appid = Number(o.appid); const name = o.name || ('App ' + appid); const isOwned = !!o.isOwned; const clickUrl = o.clickUrl || ('https://store.steampowered.com/app/' + appid); const iconUrl = o.iconUrl || (typeof Host.getGameIconUrl === 'function' ? Host.getGameIconUrl(appid, '') : ''); // v2.6.0: 列表视图同步去掉实心拥有态块 —— 左列 = 分类徽章 + 拥有态文字,右列 = 日期/统计 const bc = _badgeColors(o.typeColor); const left = []; if (o.typeLabel && o.typeKey) { left.push('' + Host.wlEscape(o.typeLabel) + ''); } left.push('' + (isOwned ? '✓ ' + Host.wlEscape(Host.T.owned || '已拥有') : Host.wlEscape(Host.T.missing || '未拥有')) + ''); const right = (o.metaItems || []).filter(Boolean); return '
' + '' + Host.wlEscape(name) + '' + '
' + '
' + '' + Host.wlEscape(name) + '' + '' + appid + '' + '
' + '
' + '
' + left.join('') + '
' + '
' + right.join('') + '
' + '
' + '
' + '
'; } // ==================== v2.4.0: 收藏标签页壳(统一工具栏 + KPI + 网格 + 翻页) ==================== // 抽象 4 个 tab 共用的"容器 + 工具栏 + KPI + 内容 + 翻页"四段式结构, // 各 tab 通过回调定制工具栏内容(搜索/排序/视图切换/刷新按钮) // ================================================================ /** * 创建收藏标签页外壳 * @param {Object} opts * @param {HTMLElement} opts.parent - 父元素(body) * @param {string} opts.tabId - 唯一 ID 前缀(用于元素 ID) * @param {string} [opts.wrapCls] - wrap 容器 class(默认 'sglv-collection-tab') * @param {string} [opts.kpiHtml] - KPI 区域 HTML(可选) * @param {string} [opts.toolbarHtml] - 工具栏 HTML(可选) * @param {string} [opts.filterBarHtml] - 筛选栏 HTML(可选) * @returns {{ wrap: HTMLElement, kpi: HTMLElement|null, toolbar: HTMLElement, content: HTMLElement, pagination: HTMLElement }} */ function createCollectionTabShell(opts) { const o = opts || {}; const parent = o.parent; if (!parent) throw new Error('createCollectionTabShell: parent required'); const tabId = o.tabId || 'sgr'; const wrapCls = o.wrapCls || 'sglv-collection-tab'; const wrap = document.createElement('div'); wrap.className = wrapCls; wrap.dataset.tab = tabId; let kpi = null; if (o.kpiHtml) { kpi = document.createElement('div'); kpi.id = tabId + '-kpi'; kpi.innerHTML = o.kpiHtml; wrap.appendChild(kpi); } const toolbar = document.createElement('div'); toolbar.className = 'sglv-toolbar'; toolbar.innerHTML = o.toolbarHtml || ''; if (toolbar.children.length > 0) wrap.appendChild(toolbar); if (o.filterBarHtml) { const filterBar = document.createElement('div'); filterBar.className = 'sglv-filter-bar'; filterBar.innerHTML = o.filterBarHtml; wrap.appendChild(filterBar); } const content = document.createElement('div'); content.className = 'sglv-content'; content.id = tabId + '-content'; wrap.appendChild(content); const pagination = document.createElement('div'); pagination.className = 'sglv-pagination'; pagination.id = tabId + '-pagination'; wrap.appendChild(pagination); parent.appendChild(wrap); return { wrap: wrap, kpi: kpi, toolbar: toolbar, content: content, pagination: pagination }; } // ==================== v2.4.0: 多源数据加载器(MultiSourceLoader) ==================== // 抽象"缓存命中 → 后台静默刷新 → 多源回退 → 负缓存"通用组件 // 锁区/绝版/捆绑包等数据加载均可接入 // ================================================================ // ---- MultiSourceLoader 底层工具:统一委托 SGLVCore(_C) ---- // 修复:本组件初版直接使用裸标识符 nsKey / negCacheGet / negCacheSet / // negCacheClear / gmFetch,但这几个名字在本 lib 内从未定义(预期来自 SGLVCore)。 // 运行时抛 ReferenceError 的后果: // · gmFetch —— 同步抛出落在 Promise executor 内 → load() 永远 reject, // 串行多源回退全部走不通 → 锁区/绝版/捆绑包标签页永远拿不到远程数据; // · negCache* —— 被 try/catch 吞掉 → 负缓存从未生效 → 源挂掉时反复重试风暴。 const _mslNsKey = (k) => (_C && typeof _C.nsKey === 'function') ? _C.nsKey(k) : ('sglv_' + k); const _mslNegGet = (k, ttl) => { try { return (_C && _C.negCache) ? _C.negCache.get(k, ttl) : null; } catch (e) { return null; } }; const _mslNegSet = (k, err) => { try { if (_C && _C.negCache) _C.negCache.set(k, err); } catch (e) { /* ignore */ } }; const _mslNegClear = (k) => { try { if (_C && _C.negCache) _C.negCache.clear(k); } catch (e) { /* ignore */ } }; const _mslFetch = (url) => (_C && typeof _C.gmFetchText === 'function') ? _C.gmFetchText(url) : fetch(url).then((r) => { if (!r.ok) throw new Error('HTTP ' + r.status); return r.text(); }); /** * 创建多源加载器实例 * @param {Object} cfg * @param {string} cfg.key - 缓存 key(同时作为 nsKey 前缀) * @param {string[]} cfg.sources - URL 列表(按顺序回退) * @param {Function} cfg.parse - 解析函数 (text) => { apps, source, fetchedAt } * @param {number} [cfg.ttl] - TTL 毫秒(默认 6h) * @param {number} [cfg.negCacheTtl] - 负缓存 TTL 毫秒(默认 30min) * @param {Function} [cfg.onUpdate] - 数据更新回调 (result) => void * @returns {Object} loader instance { load(force), getCache(), clearCache() } */ function createMultiSourceLoader(cfg) { const c = cfg || {}; const key = c.key; if (!key) throw new Error('createMultiSourceLoader: key required'); const sources = Array.isArray(c.sources) ? c.sources.slice() : []; const parse = c.parse || function (t) { return JSON.parse(t); }; const ttl = c.ttl || (6 * 3600 * 1000); const negTtl = c.negCacheTtl || (30 * 60 * 1000); const onUpdate = c.onUpdate || function () {}; let _memCache = null; let _loading = false; let _lastBgRefresh = 0; let _pendingForce = false; const _permKey = 'msl_' + key; // 永久缓存读写(基于 SGLVCore.IDB) function _permGet() { try { if (_C_IDB) return _C_IDB.get(PERM_CACHE_PREFIX + _permKey, null); } catch (e) { /* ignore */ } return null; } function _permSet(v) { try { if (_C_IDB) _C_IDB.set(PERM_CACHE_PREFIX + _permKey, v); } catch (e) { /* ignore */ } _memCache = v; } // 负缓存(防止短时间内重复打挂掉的源) function _negGet() { return _mslNegGet(_mslNsKey('msl_neg_' + key), negTtl); } function _negSet(msg) { _mslNegSet(_mslNsKey('msl_neg_' + key), msg || ''); } function _negClear() { _mslNegClear(_mslNsKey('msl_neg_' + key)); } function _backgroundRefresh(force) { if (_loading) { if (force) _pendingForce = true; return; } _loading = true; const restore = () => { _loading = false; if (_pendingForce) { _pendingForce = false; setTimeout(() => load(true), 0); } }; // 串行回退多源 const trySources = async (idx) => { if (idx >= sources.length) { _loading = false; if (!force) _negSet('all sources failed'); throw new Error('MultiSourceLoader[' + key + ']: all sources failed'); } try { const text = await _mslFetch(sources[idx]); const parsed = parse(text); _permSet({ data: parsed, source: 'remote', fetchedAt: Date.now() }); _negClear(); _lastBgRefresh = Date.now(); onUpdate({ data: parsed, source: 'remote', fetchedAt: _lastBgRefresh }); _loading = false; return parsed; } catch (e) { console.warn('[MSL ' + key + '] source ' + idx + ' failed:', e.message); return trySources(idx + 1); } }; trySources(0).catch(e => { _loading = false; if (!force) _negSet(e.message); }); } function load(force) { if (!force) { if (_memCache) return Promise.resolve({ data: _memCache.data, source: _memCache.source || 'memory', fetchedAt: _memCache.fetchedAt || 0, fromCache: true }); const perm = _permGet(); if (perm && perm.data) { _memCache = perm; // 后台静默刷新节流 if (Date.now() - _lastBgRefresh > ttl) _backgroundRefresh(false); return Promise.resolve({ data: perm.data, source: perm.source || 'permCache', fetchedAt: perm.fetchedAt || 0, fromCache: true }); } if (_negGet()) return Promise.resolve({ data: null, source: 'negCache', fetchedAt: 0, fromCache: true }); } return new Promise((resolve, reject) => { if (_loading) { _pendingForce = !!force; return; } _loading = true; const trySources = (idx) => { if (idx >= sources.length) { _loading = false; if (!force) _negSet('all sources failed'); return reject(new Error('all sources failed')); } _mslFetch(sources[idx]).then(text => { const parsed = parse(text); _permSet({ data: parsed, source: 'remote', fetchedAt: Date.now() }); _negClear(); _lastBgRefresh = Date.now(); _loading = false; onUpdate({ data: parsed, source: 'remote', fetchedAt: _lastBgRefresh }); resolve({ data: parsed, source: 'remote', fetchedAt: _lastBgRefresh, fromCache: false }); }).catch(e => { console.warn('[MSL ' + key + '] source ' + idx + ' failed:', e.message); trySources(idx + 1); }); }; trySources(0); }); } return { load: load, getCache: function () { return _memCache || _permGet(); }, clearCache: function () { _memCache = null; try { if (_C_IDB) _C_IDB.set(PERM_CACHE_PREFIX + _permKey, null); } catch (e) {} _negClear(); }, invalidate: function () { _memCache = null; } }; } // ==================== v2.6.0: 受限游戏封面加载器(重写) ==================== // 参考 steam-friend-manager-1.5.3.js 的 dashLoadPosterImg + steam-activity-modern.user.js // 的 coverChainUrls / fetchCapsuleFromAPI,重写要点: // // ① 【关键修复】链首改为横向 header.jpg 而非竖版 library_600x900。 // 旧链把 library_600x900 放链首且竖版变体有 8 个 URL。绝版 / 锁区收录的绝大多数是 // 2015 年前的老游戏,Steam 早已不再为其生成竖版 library_600x900 —— 这 8 个 URL 必然 // 逐个 404,串行等待把首屏拖到数秒后才落到 header.jpg,表现为"封面加载失败"。 // header.jpg 是 Steam 对所有已发售游戏的通用横图,命中率接近 100%,应当放链首。 // ② 链长从 12 收敛到 6(4 CDN × header/capsule 各一),配合 ① 大幅缩短失败路径。 // ③ 新增 appdetails API 兜底(filters=basic 同时返回 capsule_image 与 header_image), // 这是老游戏和非英语区游戏唯一可靠的取图途径(old API 由 steam-activity 验证有效)。 // ④ 成功 URL 统一写跨会话缓存(recordGood),下次直接链首命中,省掉全部探测请求。 // ⑤ 容器改为 letterbox:横向图在竖版容器内居中显示(上下留白), // 不再用 object-fit:cover 硬裁 —— 旧游戏横图被裁成竖版时主体常被切掉。 // ================================================================ // 通用"无封面"占位(Steam 图标) const RESTRICTED_BROKEN_ICON_SVG = ''; // 锁区"被锁"占位(红色锁) const RESTRICTED_BLOCKED_ICON_SVG = ''; /** 受限游戏封面短链(横向优先)。 * chain[0] = cdn.cloudflare header.jpg(命中率最高) * chain[1] = shared.akamai store_item_assets header.jpg * chain[2] = cdn.akamai header.jpg * chain[3] = shared.fastly store_item_assets header.jpg * chain[4] = shared.akamai store_item_assets capsule_467x181.jpg(更新游戏的大横幅) * chain[5] = cdn.cloudflare capsule_467x181.jpg * 全部失败 → appdetails API 兜底(见 restrictedCoverImg 的 onerror) */ function restrictedCoverChain(appid) { const id = String(appid); return [ `https://cdn.cloudflare.steamstatic.com/steam/apps/${id}/header.jpg`, `https://shared.akamai.steamstatic.com/store_item_assets/steam/apps/${id}/header.jpg`, `https://cdn.akamai.steamstatic.com/steam/apps/${id}/header.jpg`, `https://shared.fastly.steamstatic.com/store_item_assets/steam/apps/${id}/header.jpg`, `https://shared.akamai.steamstatic.com/store_item_assets/steam/apps/${id}/capsule_467x181.jpg`, `https://cdn.cloudflare.steamstatic.com/steam/apps/${id}/capsule_467x181.jpg`, ]; } // appdetails API 兜底结果缓存(同 appid 只发一次请求,多张卡共享) // v2.9.3: 成功结果本会话长期有效;失败结果只缓存 10 分钟(渐进式重试), // 避免一次网络抖动把该 appid 在整个会话里永久拉黑 const _coverApiCache = new Map(); // appid → { url, ts } const _coverApiPending = new Set(); const COVER_API_NEG_TTL = 10 * 60 * 1000; const COVER_API_CACHE_MAX = 1200; function _coverApiCached(id) { const e = _coverApiCache.get(id); if (!e) return undefined; if (!e.url && (Date.now() - e.ts) > COVER_API_NEG_TTL) { _coverApiCache.delete(id); return undefined; } return e.url; } function _coverApiStore(id, url) { _coverApiCache.delete(id); _coverApiCache.set(id, { url: url || '', ts: Date.now() }); if (_coverApiCache.size > COVER_API_CACHE_MAX) { const it = _coverApiCache.keys(); while (_coverApiCache.size > COVER_API_CACHE_MAX) { const n = it.next(); if (n.done) break; _coverApiCache.delete(n.value); } } } /** appdetails?filters=basic 兜底取图 —— 老游戏/非英语区游戏唯一可靠途径。 * 参考 steam-activity-modern.user.js 的 fetchCapsuleFromAPI(含 in-flight 去重)。 */ function fetchCoverFromApi(appid) { const id = String(appid); const cachedNow = _coverApiCached(id); if (cachedNow !== undefined) return Promise.resolve(cachedNow); if (_coverApiPending.has(id)) return Promise.resolve(''); // 并发中不再重复打接口 _coverApiPending.add(id); const apiUrl = `https://store.steampowered.com/api/appdetails?appids=${id}&filters=basic`; const finish = (url) => { _coverApiStore(id, url); _coverApiPending.delete(id); if (url) { // v2.9.3: appdetails 的 capsule_image/header_image 都是横版,归 header 槽位; // 写成 poster 会让"竖版缺失"标记被误触(主线竖版链还没跑过)。 // 真正的归槽以 markLoaded 按实际加载 URL 形态写入为准。 try { const fb = _coverFb(); if (fb && typeof fb.recordGood === 'function') fb.recordGood(id, url, 'header'); } catch (e) { /* ignore */ } } return url || ''; }; return new Promise((resolve) => { const doReq = (typeof GM_xmlhttpRequest !== 'undefined') ? GM_xmlhttpRequest : null; const onFail = () => resolve(finish('')); if (doReq) { let settled = false; const timer = setTimeout(onFail, 8000); doReq({ method: 'GET', url: apiUrl, timeout: 8000, onload: (resp) => { if (settled) return; settled = true; clearTimeout(timer); let url = ''; try { const json = JSON.parse(resp.responseText); const d = json && json[id]; if (d && d.success && d.data) url = d.data.capsule_image || d.data.header_image || ''; } catch (e) { url = ''; } resolve(finish(url)); }, onerror: () => { if (!settled) { settled = true; clearTimeout(timer); onFail(); } }, ontimeout: () => { if (!settled) { settled = true; clearTimeout(timer); onFail(); } }, }); } else { fetch(apiUrl).then(r => r.json()).then(json => { const d = json && json[id]; const url = (d && d.success && d.data) ? (d.data.capsule_image || d.data.header_image || '') : ''; resolve(finish(url)); }).catch(() => resolve(finish(''))); } }); } /** * 三态封面渲染后的同步校正补丁。 * 背景:受限游戏列表一次性 innerHTML 写入上千张卡,浏览器对命中 HTTP 缓存的图 * 可能在 DOM 解析阶段就完成解码 —— 此时 inline onload 事件的监听器尚未挂上, * 导致 wrapper 永远停在 sglv-img-loading(opacity:0 → 封面全白)。 */ // v2.7.0: 已并入 bindRestrictedCoverLoaders(链式回退 + API 兜底 + 缓存命中补状态), // 保留同名薄封装,避免 3 个渲染函数里的调用点需要同步改名。 function syncRestrictedCoverStates(root) { bindRestrictedCoverLoaders(root); } /** * 受限游戏三态封面加载器(绝版 / 锁区 / 捆绑包 共用)—— v2.7.0 重写 * * v2.6.0 的实现把回退链塞进 inline onerror,用 `.replace(/\d+/, ci)` 拼下一个 URL。 * 这是错的:appid 本身含数字,replace 会把 appid 替换成链索引, * 实测 chain[5].replace(/\d+/, 1) → `.../apps/1/header.jpg`, * 于是整条链全是 404,永远走不到 API 兜底 —— 表现为"所有封面全挂"。 * * v2.7.0 改为「渲染时只输出干净标记 + 渲染后统一绑定事件」: * - HTML 里只有 ,没有任何拼接的 JS; * - bindRestrictedCoverLoaders() 渲染后扫一遍,用 addEventListener 绑定链式回退; * 链数组在闭包里,索引直接取自 dataset,不会有字符串替换的坑; * - 链穷尽 → fetchCoverFromApi() 兜底 → 仍失败才 broken。 */ function restrictedCoverImg(appid, name, kind, opts) { const o = opts || {}; const isBlocked = !!o.isBlocked; const safeName = Host.wlEscape(name || ''); const brokenCls = 'sglv-img-broken' + (isBlocked ? ' sglv-img-broken-blocked' : ''); // 1) 跨会话缓存命中 —— 命中即链首,后续全部跳过 // v2.9.3: 受限封面是横版容器,只读横版槽位: // 竖版缺失标记(poster 槽位里的横版 URL)→ header → capsule → 本会话 API 结果 // 旧实现直接读 poster 槽位,可能把竖版海报塞进 16:9 容器 let url = ''; try { url = coverHorizontalFallbackUrl(String(appid)) || ''; } catch (e) { /* ignore */ } if (!url) { try { url = coverGoodUrl(String(appid), 'header') || ''; } catch (e) { /* ignore */ } } if (!url) { try { url = coverGoodUrl(String(appid), 'capsule') || ''; } catch (e) { /* ignore */ } } if (!url) { try { const fb = _coverFb(); if (fb && typeof fb.getCoverUrl === 'function') { url = fb.getCoverUrl(String(appid), 'header', Host.isZh ? 'schinese' : '') || ''; } } catch (e) { /* ignore */ } } if (!url) { const cachedApi = _coverApiCached(String(appid)); if (cachedApi) url = cachedApi; } const chain = restrictedCoverChain(appid); const firstUrl = url || chain[0]; if (!firstUrl) { return '
' + _restrictedBrokenInner(name, isBlocked) + '
'; } // 2) 干净的 HTML:只带 data 标记,回退逻辑交给 bindRestrictedCoverLoaders // v2.9.2: 必须带 data-cover-appid(见 unifiedCover 同名注释) return '
' + '' + safeName + '' + '
' + _restrictedBrokenInner(name, isBlocked) + '
' + '
'; } /** * 渲染后绑定封面回退链(v2.7.0 核心) * 每个 wrapper 只绑定一次(用 __bound 标记),内部维护链索引, * 链穷尽后走一次 appdetails API 兜底。 */ function bindRestrictedCoverLoaders(root) { const scope = root || document; // v2.9.2: 选择器同时接受 data-cover-appid / data-appid —— // 旧选择器只认 wrapper 上的 data-cover-appid,而 unifiedCover / restrictedCoverImg // 生成的 wrapper 只有 data-appid,一个都匹配不到 → 从不绑定事件 // → sglv-img-loading 永不摘除(大海报视图 opacity:0 全空白) // → 图片 404 后也没有任何回退链。 scope.querySelectorAll('.sglv-img-wrapper[data-appid]:not([data-bound]), .sglv-img-wrapper[data-cover-appid]:not([data-bound])').forEach(function (wrapper) { const img = wrapper.querySelector('img'); if (!img) return; wrapper.setAttribute('data-bound', '1'); const appid = img.getAttribute('data-cover-appid') || wrapper.getAttribute('data-cover-appid') || wrapper.getAttribute('data-appid'); if (!appid) return; const isBlocked = wrapper.getAttribute('data-cover-blocked') === '1'; const brokenCls = 'sglv-img-broken' + (isBlocked ? ' sglv-img-broken-blocked' : ''); const name = img.getAttribute('alt') || ''; const kind = wrapper.getAttribute('data-cover-kind') || 'poster'; const preferVertical = wrapper.getAttribute('data-cover-prefer-vertical') === '1'; // hero(大海报视图)走独立长链;竖版卡片墙走竖版优先链(链尾同样是 header 兜底); // 其余(受限封面/锁区/捆绑包)统一横向链 let chain; if (kind === 'hero') chain = unifiedCoverChain(appid, 'hero'); else if (kind === 'poster' && preferVertical) chain = unifiedCoverChain(appid, 'poster', true); else chain = restrictedCoverChain(appid); // 初始 src 可能是跨会话 good 缓存(不在 chain 里): // 命中 chain → 从下一条继续;未命中 → 从链首开始尝试 let ci = chain.indexOf(img.getAttribute('src') || ''); let apiTried = false; img.setAttribute('data-cover-appid', appid); const markLoaded = () => { wrapper.classList.remove('sglv-img-loading'); wrapper.classList.add('sglv-img-loaded'); // v2.9.2: 图片本身也要挂 sglv-img-loaded —— // `.sgc-panel .sglv-card-img { opacity: 0 }` 的显示态是 // `.sglv-card-img.sglv-img-loaded`(img 级),旧 inline onload 会加。 // 改用事件委托后没人加 → 卡片/列表视图封面全员 opacity:0 不可见。 if (img.classList) { img.classList.add('sglv-img-loaded'); if (img.naturalWidth > img.naturalHeight) img.classList.add('sglv-img-wide'); } // v2.9.3: 按图片实际形态归槽(竖版 → poster,横版 → header), // 而不是按容器 kind —— 受限/大海报容器加载的常是 header.jpg, // 写成 capsule 会污染对应槽位;归一到 header 则各视图共享。 // 例外:竖版容器最终加载了横图 = "竖版资产缺失"标记,仍需写 poster 槽位, // 否则 coverVerticalMissing 永远为假,竖版视图每次都要重吃 8 个 404。 try { const src = img.src || ''; if (src && src.indexOf('data:') !== 0) { const vertical = _sgcvIsVerticalUrl(src); const slots = vertical ? ['poster'] : ['header']; if (!vertical && kind === 'poster') slots.push('poster'); // 缺失标记 const fb = _coverFb(); for (const slot of slots) { if (fb && typeof fb.recordGood === 'function') fb.recordGood(appid, src, slot); // 同步写入宿主共享缓存(跨面板复用:收藏 → 主面板) if (Host && typeof Host.recordPosterGood === 'function') Host.recordPosterGood(appid, src, slot); } } } catch (e) { /* ignore */ } }; const markBroken = () => { wrapper.classList.remove('sglv-img-loading'); wrapper.classList.add(brokenCls); const layer = wrapper.querySelector('.sglv-img-fallback-layer'); if (layer) layer.innerHTML = _restrictedBrokenInner(name, isBlocked); }; // 推进到链上第一个"不是当前失败 URL"的候选 const advance = () => { const cur = img.getAttribute('src') || ''; for (ci++; ci < chain.length; ci++) { const u = chain[ci]; if (u && u !== cur) { img.src = u; return true; } } return false; }; const onError = () => { if (advance()) return; if (!apiTried) { apiTried = true; fetchCoverFromApi(appid).then(url => { if (url) { img.src = url; return; } markBroken(); }).catch(() => markBroken()); return; } markBroken(); }; img.addEventListener('load', () => { // naturalWidth<=1 视为占位/空图(同步校正时也会走到这里) if (!img.naturalWidth || img.naturalWidth < 2) return; markLoaded(); }); img.addEventListener('error', onError); // load/error 早于绑定(HTTP 缓存命中 / 首图在 DOM 解析阶段就 404) // → 立即补状态,否则 wrapper 会永远停在 sglv-img-loading if (img.complete) { if (img.naturalWidth > 1) markLoaded(); else if (img.getAttribute('src')) onError(); } }); } // broken 态内容(同时用作 wrapper 内的兜底层,loaded 态下被 CSS 隐藏) function _restrictedBrokenInner(name, isBlocked) { return '
' + (isBlocked ? RESTRICTED_BLOCKED_ICON_SVG : RESTRICTED_BROKEN_ICON_SVG) + '
' + '
' + Host.wlEscape(isBlocked ? (Host.isZh ? '锁区游戏' : 'Region Locked') : (Host.isZh ? '无封面' : 'No Cover')) + (name ? '
' + Host.wlEscape(name) : '') + '
'; } // ==================== 供应商分类标签页 ==================== // v1.9.19: 统计缓存——数据安装期注入后低频更新,按 GAME_DB 引用缓存计算结果; // @resource 更新后 getGameDb() 返回新引用 → Map key 变化自动失效(Map 最多保留 2 代引用,防内存泄漏) const _pubStatsCache = new Map(); // dbRef → { sig, inner: Map(pubName → { total, owned }) } const _seriesStatsCache = new Map(); // dbRef → { sig, inner: Map(pubName + '\u0000' + seriesName → { total, owned }) } function _getStatsCacheForDb(map) { const db = Host.getGameDb(); if (!db) return null; // v1.9.19-fix: sig = 拥有集合规模 + 家庭共享开关——面板打开期间重新同步家庭库 // (sglv:games-updated)时 db 引用不变但拥有集合变化,需整代失效; // sig 随每代缓存独立存放(不共用全局表),避免两个缓存重建时序互相干扰 const sig = (Host.getOwnedGames ? Host.getOwnedGames().length : -1) + '|' + !!Host.getShowFamilyShared(); let entry = map.get(db); if (entry && entry.sig !== sig) entry = null; // sig 变化 → 整代失效 if (!entry) { entry = { sig, inner: new Map() }; map.set(db, entry); if (map.size > 2) map.delete(map.keys().next().value); } return entry.inner; } function computePublisherStats(pubName) { const db = Host.getGameDb(); const pub = db?.[pubName]; if (!pub) return { total: 0, owned: 0 }; const inner = _getStatsCacheForDb(_pubStatsCache); if (inner) { const hit = inner.get(pubName); if (hit) return hit; } let total = 0, owned = 0; const activeOwnedIds = Host.getActiveOwnedAppIds(); for (const series of Object.values(pub)) { total += series.length; for (const g of series) if (activeOwnedIds.has(g.id)) owned++; } const res = { total, owned }; if (inner) inner.set(pubName, res); return res; } function computeSeriesStats(pubName, seriesName) { const db = Host.getGameDb(); const series = db?.[pubName]?.[seriesName]; if (!series) return { total: 0, owned: 0 }; const inner = _getStatsCacheForDb(_seriesStatsCache); const key = pubName + '\u0000' + seriesName; if (inner) { const hit = inner.get(key); if (hit) return hit; } let owned = 0; const activeOwnedIds = Host.getActiveOwnedAppIds(); for (const g of series) if (activeOwnedIds.has(g.id)) owned++; const res = { total: series.length, owned }; if (inner) inner.set(key, res); return res; } // v1.9.16: genres 类型标签 HTML(game-db-v1.2.json 可选字段;旧数据无 genres 时返回空串,安全降级) function genreTagsHtml(g, max = 3) { if (!Array.isArray(g.genres) || !g.genres.length) return ''; const tags = g.genres.slice(0, max).map(t => `${Host.wlEscape(t)}`).join(''); const more = g.genres.length > max ? `+${g.genres.length - max}` : ''; return tags + more; } // 统一计算游戏拥有状态徽章信息(供供应商分类列表/卡片视图复用) function getGameBadgeInfo(g, ownedAppIds) { const isOwned = ownedAppIds.has(g.id); if (!isOwned) return { isOwned: false, badgeClass: 'missing', badgeText: Host.T.missing, tooltip: '' }; const gameObj = Host.getOwnedGames().find(og => og.appid === g.id); if (gameObj && !Host.isGameOwnedByMe(gameObj)) { return { isOwned: true, badgeClass: 'shared', badgeText: Host.isZh ? '共享' : 'Shared', tooltip: `title="共享自: ${Host.getGameOwnerNames(gameObj)}"` }; } return { isOwned: true, badgeClass: 'owned', badgeText: '✓ ' + Host.T.owned, tooltip: '' }; } function renderPublisherTab(parent) { const body = document.createElement('div'); body.className = 'sglv-pub-layout'; // 左侧边栏(v1.8.2: 顶部含供应商/系列模式切换) const sidebar = document.createElement('div'); sidebar.className = 'sglv-pub-sidebar'; sidebar.id = 'sglv-pub-sidebar'; body.appendChild(sidebar); // 右侧内容 const main = document.createElement('div'); main.className = 'sglv-pub-main'; main.id = 'sglv-pub-main'; body.appendChild(main); parent.appendChild(body); renderPubSidebar(); if (pubState.mode === 'series') { // v1.8.2: 系列模式——默认展开第一个系列 ensureSeriesSelected(); if (pubState.selectedSeries) renderSeriesModeDetail(pubState.selectedSeries); else renderSeriesModeEmpty(); } else { // v1.9.19: 供应商模式——默认展开首个供应商并选中其首个系列,按需渲染(不再默认停留 Overview) ensurePublisherSelected(); if (pubState.selectedSeries) { renderPubSeriesDetail(pubState.selectedPublisher, pubState.selectedSeries); } else if (pubState.selectedPublisher) { renderPubPublisherDetail(pubState.selectedPublisher); } else { renderPubOverview(); // GAME_DB 为空时保持总览(空态) } } } /** v1.9.19: 确保供应商模式下有选中项:未选中/选中项已不存在时默认展开第一个供应商并选中其第一个系列(参照 ensureSeriesSelected) */ function ensurePublisherSelected() { const db = Host.getGameDb() || {}; const pubNames = Object.keys(db); if (!pubNames.length) { pubState.selectedPublisher = null; pubState.selectedSeries = null; return; } if (!pubState.selectedPublisher || !db[pubState.selectedPublisher]) { pubState.selectedPublisher = pubNames[0]; pubState.selectedSeries = null; } pubState.expandedPublishers.add(pubState.selectedPublisher); if (!pubState.selectedSeries || !db[pubState.selectedPublisher][pubState.selectedSeries]) { const seriesNames = Object.keys(db[pubState.selectedPublisher]); pubState.selectedSeries = seriesNames.length ? seriesNames[0] : null; } } // ---- v1.8.2: 系列数据访问(宿主未提供 getSeriesDb 时安全降级) ---- function getSeriesDb() { return (typeof Host.getSeriesDb === 'function' && Host.getSeriesDb()) || {}; } function computeSeriesModeStats(seriesName) { const games = getSeriesDb()[seriesName] || []; let owned = 0; const activeOwnedIds = Host.getActiveOwnedAppIds(); for (const g of games) if (activeOwnedIds.has(g.id)) owned++; return { total: games.length, owned }; } /** 确保系列模式下有选中项:未选中/选中项已不存在时默认展开第一个系列 */ function ensureSeriesSelected() { const db = getSeriesDb(); const names = Object.keys(db); if (!names.length) { pubState.selectedSeries = null; return; } if (!pubState.selectedSeries || !db[pubState.selectedSeries]) { pubState.selectedSeries = names[0]; } } /** v1.8.2: 供应商/系列模式切换条 */ function renderPubModeSwitch() { const wrap = document.createElement('div'); wrap.className = 'sglv-pub-mode-switch'; const modes = [ { key: 'publisher', label: Host.isZh ? '供应商' : 'Publisher' }, { key: 'series', label: Host.isZh ? '系列' : 'Series' }, ]; for (const m of modes) { const btn = document.createElement('button'); btn.className = 'sglv-pub-mode-btn' + (pubState.mode === m.key ? ' active' : ''); btn.textContent = m.label; btn.addEventListener('click', () => { if (pubState.mode === m.key) return; pubState.mode = m.key; pubState.filter = 'all'; renderPubSidebar(); if (m.key === 'series') { ensureSeriesSelected(); if (pubState.selectedSeries) renderSeriesModeDetail(pubState.selectedSeries); else renderSeriesModeEmpty(); } else { // v1.9.19: 切回供应商模式——同样默认进入首个供应商的首个系列(选中项有效则保留) ensurePublisherSelected(); if (pubState.selectedSeries) { renderPubSeriesDetail(pubState.selectedPublisher, pubState.selectedSeries); } else if (pubState.selectedPublisher) { renderPubPublisherDetail(pubState.selectedPublisher); } else { renderPubOverview(); } } }); wrap.appendChild(btn); } // v2.9.91: 两种模式均显示刷新按钮——同时刷新供应商+系列数据 const hasRefresh = typeof Host.loadSeriesData === 'function' || typeof Host.loadSupplierData === 'function'; if (hasRefresh) { const refreshBtn = document.createElement('button'); refreshBtn.className = 'sglv-pub-mode-btn sglv-pub-series-refresh'; refreshBtn.id = 'sglv-pub-refresh'; refreshBtn.title = Host.isZh ? '刷新供应商和系列数据' : 'Refresh supplier & series data'; refreshBtn.innerHTML = Host.ICONS.refresh; // 修复:原调用 loadAllCollectionData(true),但该函数在模块 4 抽离后已无定义 // (悬空引用 → 点刷新即抛 ReferenceError)。按上方守卫条件直接调用宿主加载器, // 数据到位后由 sglv:series-data-loaded / sglv:supplier-data-loaded 事件触发重绘。 refreshBtn.addEventListener('click', () => { if (typeof Host.loadSeriesData === 'function') Host.loadSeriesData(true); if (typeof Host.loadSupplierData === 'function') Host.loadSupplierData(true); }); wrap.appendChild(refreshBtn); // v1.9.40: 不再常驻状态文本(更新时间曾压缩切换按钮致变形)——刷新结果由悬浮提示显示 } return wrap; } /** 刷新供应商/系列标签页内容(不重建整个面板,避免骨架闪烁) * 修复:sglv:series-data-loaded / sglv:supplier-data-loaded 事件回调引用了本函数, * 但该函数从未定义 → 事件触发时抛 ReferenceError,远程数据更新后界面不刷新。 * 逻辑与 renderPubModeSwitch 的模式切换分支保持一致。 */ function refreshPublisherTabContent() { renderPubSidebar(); if (pubState.mode === 'series') { ensureSeriesSelected(); if (pubState.selectedSeries) renderSeriesModeDetail(pubState.selectedSeries); else renderSeriesModeEmpty(); } else { ensurePublisherSelected(); if (pubState.selectedSeries) renderPubSeriesDetail(pubState.selectedPublisher, pubState.selectedSeries); else if (pubState.selectedPublisher) renderPubPublisherDetail(pubState.selectedPublisher); else renderPubOverview(); } } function renderPubOverview() { const main = document.getElementById('sglv-pub-main'); if (!main) return; let totalAll = 0, ownedAll = 0; for (const pubName of Object.keys(Host.getGameDb())) { const s = computePublisherStats(pubName); totalAll += s.total; ownedAll += s.owned; } const pctAll = totalAll > 0 ? Math.round(ownedAll / totalAll * 100) : 0; const showFamilyShared = Host.getShowFamilyShared(); const activeTotalGames = showFamilyShared ? Host.getOwnedGames().length : Host.getOwnedGames().filter(g => Host.isGameOwnedByMe(g)).length; let html = `
${Host.ICONS.library}${Host.T.totalGames}
${activeTotalGames}
${Host.T.kpiOfTotal}
${Host.ICONS.heart}${Host.T.ownedInDb}
${ownedAll}
${Host.T.kpiRate} ${pctAll}%
${Host.ICONS.shield}${Host.T.missingInDb}
${totalAll - ownedAll}
${Host.T.kpiRate} ${100 - pctAll}%
${Host.ICONS.barChart}${Host.T.ownership}
${pctAll}%
${Host.T.kpiCollectionProgress}
`; for (const [pubName] of Object.entries(Host.getGameDb())) { const pStats = computePublisherStats(pubName); const pct = pStats.total > 0 ? Math.round(pStats.owned / pStats.total * 100) : 0; html += `
${sgcEsc(pubName)} ${pStats.owned}/${pStats.total} (${pct}%)
`; } main.innerHTML = html; main.querySelectorAll('.sglv-pub-card').forEach(card => { card.addEventListener('click', () => { const pubName = card.dataset.pub; pubState.expandedPublishers.add(pubName); pubState.selectedPublisher = pubName; pubState.selectedSeries = null; renderPubSidebar(); renderPubPublisherDetail(pubName); }); }); } // v1.8.2: 系列模式侧边栏——扁平系列列表(无供应商二级分类) function renderSeriesSidebarList(sidebar) { const db = getSeriesDb(); const names = Object.keys(db); // v1.9.37: 移除'系列数据加载中…'提示,数据未就绪时直接返回(避免界面变形) if (!names.length) return; for (const seriesName of names) { const sStats = computeSeriesModeStats(seriesName); const completionPct = sStats.total > 0 ? Math.round(sStats.owned / sStats.total * 100) : 0; const item = document.createElement('div'); item.className = 'sglv-series-flat-item' + (pubState.selectedSeries === seriesName ? ' active' : ''); item.innerHTML = '' + seriesName + '' + '' + sStats.owned + '/' + sStats.total + ''; item.addEventListener('click', () => { pubState.selectedSeries = seriesName; renderPubSidebar(); renderSeriesModeDetail(seriesName); }); sidebar.appendChild(item); } } function renderPubSidebar() { const sidebar = document.getElementById('sglv-pub-sidebar'); if (!sidebar) return; sidebar.innerHTML = ''; // v1.8.2: 顶部模式切换(供应商 / 系列) sidebar.appendChild(renderPubModeSwitch()); // v1.8.2: 系列模式——扁平系列列表,无二级分类 if (pubState.mode === 'series') { renderSeriesSidebarList(sidebar); return; } for (const [pubName, pubData] of Object.entries(Host.getGameDb())) { const pStats = computePublisherStats(pubName); const isExpanded = pubState.expandedPublishers.has(pubName); const pubEl = document.createElement('div'); pubEl.className = 'sglv-pub-item'; const header = document.createElement('div'); header.className = `sglv-pub-header${pubState.selectedPublisher === pubName && !pubState.selectedSeries ? ' active' : ''}`; header.innerHTML = ` ${sgcEsc(pubName)} ${pStats.owned}/${pStats.total} `; header.addEventListener('click', () => { if (pubState.expandedPublishers.has(pubName)) pubState.expandedPublishers.delete(pubName); else pubState.expandedPublishers.add(pubName); pubState.selectedPublisher = pubName; pubState.selectedSeries = null; renderPubSidebar(); renderPubPublisherDetail(pubName); }); pubEl.appendChild(header); const seriesList = document.createElement('div'); seriesList.className = `sglv-series-list${isExpanded ? ' expanded' : ''}`; for (const [seriesName, games] of Object.entries(pubData)) { const sStats = computeSeriesStats(pubName, seriesName); const completionPct = sStats.total > 0 ? Math.round(sStats.owned / sStats.total * 100) : 0; const isSelected = pubState.selectedPublisher === pubName && pubState.selectedSeries === seriesName; const seriesHeader = document.createElement('div'); seriesHeader.className = `sglv-series-header${isSelected ? ' active' : ''}`; seriesHeader.innerHTML = ` ${sgcEsc(seriesName)} ${sStats.owned}/${sStats.total} `; seriesHeader.addEventListener('click', e => { e.stopPropagation(); pubState.selectedPublisher = pubName; pubState.selectedSeries = seriesName; renderPubSidebar(); renderPubSeriesDetail(pubName, seriesName); }); seriesList.appendChild(seriesHeader); } pubEl.appendChild(seriesList); sidebar.appendChild(pubEl); } } // v2.0.0: 选 pub 后显示该 pub 下所有系列的合并游戏列表 // 用户可通过面包菜单二级下拉进一步选具体 series function renderPubPublisherDetail(pubName) { const main = document.getElementById('sglv-pub-main'); if (!main) return; const pStats = computePublisherStats(pubName); const pct = pStats.total > 0 ? Math.round(pStats.owned / pStats.total * 100) : 0; let html = `
${sgcEsc(pubName)}
${Host.ICONS.library}${Host.isZh ? '游戏总数' : 'Total'}
${pStats.total}
${Host.ICONS.heart}${Host.T.owned}
${pStats.owned}
${Host.ICONS.shield}${Host.T.missing}
${pStats.total - pStats.owned}
${Host.ICONS.barChart}${Host.T.ownership}
${pct}%
`; for (const [seriesName] of Object.entries(Host.getGameDb()[pubName] || {})) { const sStats = computeSeriesStats(pubName, seriesName); const sPct = sStats.total > 0 ? Math.round(sStats.owned / sStats.total * 100) : 0; html += `
${sgcEsc(seriesName)} ${sStats.owned}/${sStats.total} (${sPct}%)
`; } main.innerHTML = html; main.querySelectorAll('.sglv-series-card').forEach(card => { card.addEventListener('click', () => { const p = card.dataset.pub, s = card.dataset.series; pubState.selectedPublisher = p; pubState.selectedSeries = s; pubState.expandedPublishers.add(p); renderPubSidebar(); renderPubSeriesDetail(p, s); }); }); } function renderPubSeriesDetail(pubName, seriesName) { const games = Host.getGameDb()[pubName]?.[seriesName] || []; const breadcrumbHtml = `
${sgcEsc(pubName)} › ${sgcEsc(seriesName)}
`; renderSeriesDetailCommon(breadcrumbHtml, games, () => renderPubSeriesDetail(pubName, seriesName), 'pub:' + pubName + '\u0000' + seriesName); } // v2.0.0: 系列模式 — 面包菜单 + 完成度 + 网格 function renderSeriesModeDetail(seriesName) { const games = getSeriesDb()[seriesName] || []; const breadcrumbHtml = `
${Host.isZh ? '系列' : 'Series'} ${sgcEsc(seriesName)}
`; renderSeriesDetailCommon(breadcrumbHtml, games, () => renderSeriesModeDetail(seriesName), 'series:' + seriesName); } function renderSeriesModeEmpty() { const main = document.getElementById('sglv-pub-main'); if (!main) return; main.innerHTML = ''; } /** * v1.9.31: 系列游戏排序辅助——日期解析为可排序字符串 * 支持所有数据源日期格式(兼容 game_series.json 中文格式 + vediogame_filtered.json ISO 格式): * "YYYY年M月D日" / "YYYY年M月" / "YYYY年"(中文格式,game_series.json) * "YYYY-MM-DD" / "YYYY-MM-__" / "YYYY-MM" / "YYYY"(ISO 格式,vediogame_filtered.json) * "Q[1-4] YYYY"(季度格式) * "待定" / "TBD" / "" → 返回空串(排序时排到末尾) * @param {string} dateStr - 日期字符串 * @returns {string} 可排序字符串(如 "20260901"),无效/未知日期返回 '' */ function seriesDateToSortable(dateStr) { if (!dateStr) return ''; var s = String(dateStr).trim(); if (!s || s === '待定' || s === 'TBD' || s === 'tbd') return ''; // 中文完整日期: "2026年01月30日" / "2026 年7月8日" var m = s.match(/(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日/); if (m) return m[1] + m[2].padStart(2, '0') + m[3].padStart(2, '0'); // 中文年月: "2028年3月" var m2 = s.match(/(\d{4})\s*年\s*(\d{1,2})\s*月/); if (m2) return m2[1] + m2[2].padStart(2, '0') + '99'; // 中文年份: "2026年" var m3 = s.match(/^(\d{4})\s*年/); if (m3) return m3[1] + '1299'; // ISO 完整日期: "2026-09-01" var m4 = /^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(s); if (m4) return m4[1] + m4[2].padStart(2, '0') + m4[3].padStart(2, '0'); // ISO 部分日期(日未知): "2026-01-__" var m5 = /^(\d{4})-(\d{1,2})-__$/.exec(s); if (m5) return m5[1] + m5[2].padStart(2, '0') + '99'; // ISO 年月: "2026-08" var m6 = /^(\d{4})-(\d{1,2})$/.exec(s); if (m6) return m6[1] + m6[2].padStart(2, '0') + '99'; // 纯年份: "2026" var m7 = /^(\d{4})$/.exec(s); if (m7) return m7[1] + '1299'; // 季度格式: "Q4 2026" → 该季度末月 var m8 = /^Q([1-4])\s+(\d{4})$/i.exec(s); if (m8) { var qMon = String(parseInt(m8[1]) * 3).padStart(2, '0'); return m8[2] + qMon + '99'; } return ''; } /** * v1.9.31: 系列游戏排序——按 sortField + sortDir 排序,未知/空日期始终排到末尾 * @param {Array} games - 游戏列表 [{id, name, date, order, poster?}] * @param {string} sortField - 'order'|'date'|'name'|'appid' * @param {string} sortDir - 'asc'|'desc' * @returns {Array} 排序后的新数组(不修改原数组) */ function sortSeriesGames(games, sortField, sortDir) { var sorted = games.slice(); var desc = sortDir === 'desc'; try { sorted.sort(function (a, b) { var r; switch (sortField) { case 'name': r = _nameCollator.compare(a.name || '~', b.name || '~'); return desc ? -r : r; case 'appid': r = (a.id || 0) - (b.id || 0); return desc ? -r : r; case 'date': // 未知/空日期始终排到末尾,与 sortDir 无关 var sa = seriesDateToSortable(a.date); var sb = seriesDateToSortable(b.date); if (!sa && !sb) return 0; if (!sa) return 1; // a 未知 → 排后面 if (!sb) return -1; // b 未知 → 排后面 return desc ? sb.localeCompare(sa) : sa.localeCompare(sb); case 'order': default: r = (a.order || 0) - (b.order || 0); return desc ? -r : r; } }); } catch (e) { console.warn('[SGLV-Series] sortSeriesGames 排序失败,降级为原始顺序:', e); } return sorted; } /** * v1.9.30: 系列封面图生成——优先使用数据源 poster 字段(预验证URL,避免CDN试错), * 失败后走三级 CDN 降级链 + API 兜底。向后兼容:poster 为空时走原 Host 逻辑。 * @param {Object} g - 游戏条目 {id, name, poster?} * @param {string} kind - 图片类型 'poster'|'header' * @param {string} cls - img class * @returns {string} img 标签 HTML */ // v2.0.0 (cover-fallback v2.0): 重写为 data-属性 + 单一 onerror 委托 // 之前: inline 链式 onerror 串 7-20 URL, 浏览器主动加载链首 (常 404), HTML attribute 冗长 // 现在: img 创建时 src = SGLVCoverFallback.getCoverUrl() (链首 cdn.cloudflare,老游戏命中), // 失败时委托 _sglvChainFallback → SGLVCoverFallback.chainLoad (JS 接管, addEventListener 单 listener) // 链长度: 7-8 (从 20 砍掉一半多), schinese 变体放链尾 (避免老游戏先吃 4-5 个 404) // v2.0.0 (cover-fallback v2.0): 重写为 data-属性 + 单一 onerror 委托 // 之前: inline 链式 onerror 串 7-20 URL, 浏览器主动加载链首 (常 404), HTML attribute 冗长 // 现在: img 创建时 src = SGLVCoverFallback.getCoverUrl() (链首 cdn.cloudflare, 老游戏命中), // 失败时委托 _sglvChainFallback → SGLVCoverFallback.chainLoad (JS 接管, addEventListener 单 listener) // 链长度: 7-8 (从 20 砍掉一半多), schinese 变体放链尾 (避免老游戏先吃 4-5 个 404) // v2.8.0: 统一走 unifiedCover(addEventListener 绑定,无跨上下文 inline onerror、无一次性锁)。 // kind 'header' 归一到 'hero' 链(系列视图专属的超宽横图链)。 function seriesCoverImg(g, kind, cls, opts) { const k = (kind === 'header') ? 'hero' : (kind || 'poster'); return unifiedCover(g.id, g.name || '', k, Object.assign({ imgCls: cls || 'sglv-card-img' }, opts || {})); } function seriesCapsuleImg(g) { return unifiedCover(g.id, g.name || '', 'capsule', { imgCls: 'sglv-wl-cover-img' }); } function _sgcvChainFallbackImpl(img) { if (!img || !img.dataset || !img.dataset.appid) return; var appid = img.dataset.appid; var kind = img.dataset.kind || 'capsule'; if (img._sglvChainLoading) return; img._sglvChainLoading = 1; try { var fb = _coverFb(); if (fb && typeof fb.chainLoad === 'function') { fb.chainLoad(img, String(appid), kind, { onGiveUp: function () { if (img && img.parentElement) { var ph = document.createElement('div'); ph.className = (img.className || '') + ' sglv-cover-broken'; ph.textContent = (Host && Host.isZh) ? '无封面' : 'No Cover'; img.parentElement.replaceChild(ph, img); } }, }); } else { if (img.parentElement) { var ph = document.createElement('div'); ph.className = (img.className || '') + ' sglv-cover-broken'; ph.textContent = (Host && Host.isZh) ? '无封面' : 'No Cover'; img.parentElement.replaceChild(ph, img); } } } catch (e) { /* 静默降级 */ } } try { var _sgcvPageWin = (typeof unsafeWindow !== 'undefined') ? unsafeWindow : window; _sgcvPageWin._sglvChainFallback = _sgcvChainFallbackImpl; } catch (e) { /* ignore */ } // 挂载到页面上下文(内联 onerror 属性在页面上下文执行) try { var _sgcvPageWin = (typeof unsafeWindow !== 'undefined') ? unsafeWindow : window; _sgcvPageWin._sglvChainFallback = _sgcvChainFallbackImpl; } catch (e) { /* ignore */ } // v2.0.0: 删掉旧版 seriesCapsuleImg(2838 旧实现)——已统一到 _sglvChainFallback 单委托 // 旧版 inline 链式 onerror 串 7-20 URL + 竞速兜底,与新 design 重复,会让 2838 旧版覆盖 // 上面的 2767 新版,导致单委托 _sglvChainFallback 永远不会生效 /** * 系列/供应商游戏列表公共渲染(KPI + 进度筛选 + 卡片/列表视图) * @param {string} breadcrumbHtml - 顶部面包屑 HTML * @param {Array} games - [{id, name, date}] * @param {function} rerender - 重渲染回调 * @param {string} cacheKey - v1.9.19: 分类标识(含 filter),用于分页进度记忆/恢复 */ function renderSeriesDetailCommon(breadcrumbHtml, games, rerender, cacheKey) { const main = document.getElementById('sglv-pub-main'); if (!main) return; cacheKey = cacheKey ? cacheKey + '\u0000' + pubState.filter + '\u0000' + pubState.sortField + '\u0000' + pubState.sortDir : null; // v1.9.19: 切换分类时保存旧页码、恢复新分类页码(filter/viewMode 变化仍走 rerender,页码由 cacheKey 区分) if (pubDetailState.cacheKey !== cacheKey) { if (pubDetailState.cacheKey) pubDetailState.pageCache.set(pubDetailState.cacheKey, pubDetailState.page); pubDetailState.page = (cacheKey && pubDetailState.pageCache.get(cacheKey)) || 1; pubDetailState.cacheKey = cacheKey; } const ownedAppIds = Host.getActiveOwnedAppIds(); let ownedCount = 0; for (const g of games) if (ownedAppIds.has(g.id)) ownedCount++; const sStats = { total: games.length, owned: ownedCount }; const pct = sStats.total > 0 ? Math.round(sStats.owned / sStats.total * 100) : 0; const viewMode = pubState.viewMode; // v1.9.34: 'card' | 'cover' | 'list' let html = breadcrumbHtml + `
${Host.isZh ? '收集完成度' : 'Completion'}: ${pct}% (${sStats.owned}/${sStats.total})
${viewMode === 'list' ? '
' : viewMode === 'cover' ? '
' : '
'} `; // 按拥有状态筛选游戏 let displayGames = games; if (pubState.filter === 'owned') { displayGames = games.filter(g => ownedAppIds.has(g.id)); } else if (pubState.filter === 'unowned') { displayGames = games.filter(g => !ownedAppIds.has(g.id)); } // v1.9.31: 排序——按 sortField + sortDir 排序,未知/空日期排末尾 displayGames = sortSeriesGames(displayGames, pubState.sortField, pubState.sortDir); // v1.9.19: 分页——只渲染当前页的游戏卡片/封面(页大小与其他 tab 一致) const { pageItems, totalPages, page: _clampedPage } = Host.paginate(displayGames, pubDetailState.page, pubDetailState.pageSize); pubDetailState.page = _clampedPage; if (displayGames.length === 0) { html += `
${pubState.filter === 'owned' ? (Host.isZh ? '该系列没有已拥有的游戏' : 'No owned games in this series') : pubState.filter === 'unowned' ? (Host.isZh ? '该系列没有未拥有的游戏' : 'All games in this series are owned') : (Host.isZh ? '该分类暂无游戏' : 'No games in this category')}
`; } else if (viewMode === 'list') { // 列表视图:表头(含封面列) html += `
${Host.isZh ? '封面' : 'Cover'} ${Host.isZh ? '状态' : 'Status'} ${Host.isZh ? '游戏名称' : 'Game Name'} AppID
`; for (const g of pageItems) { const { badgeClass, badgeText, tooltip } = getGameBadgeInfo(g, ownedAppIds); // v1.9.30: 封面优先使用数据源 poster 字段(预验证URL),失败走 CDN 降级链 + API 兜底 const coverImg = seriesCoverImg(g, 'header', 'sglv-pub-list-cover'); html += ` ${coverImg} ${badgeText} ${g.name}${(() => { const tags = genreTagsHtml(g); return tags ? `${tags}` : ''; })()} ${g.id} `; } } else if (viewMode === 'cover') { // v1.9.34: 横版封面视图(capsule 大图) for (const g of pageItems) { const { isOwned, badgeClass, badgeText, tooltip } = getGameBadgeInfo(g, ownedAppIds); html += `
${seriesCapsuleImg(g)}
${badgeText}
${g.name}${g.id}
${(() => { const tags = genreTagsHtml(g); return tags ? `
${tags}
` : ''; })()}
`; } } else { // 卡片视图 for (const g of pageItems) { const { isOwned, badgeClass, badgeText, tooltip } = getGameBadgeInfo(g, ownedAppIds); html += `
${seriesCoverImg(g, 'poster', 'sglv-card-img', { preferVertical: true })}
${g.name}
AppID: ${g.id}
${(() => { const tags = genreTagsHtml(g); return tags ? `
${tags}
` : ''; })()} ${badgeText}
`; } } html += '
'; // v1.9.19: 分页导航(与其他 tab 同一套 Host.renderPagination) html += `
`; main.innerHTML = html; // v2.8.0: 统一封面链绑定(系列视图的三种卡片都走 unifiedCover) bindRestrictedCoverLoaders(main); // v2.3.33:异步加载游戏中文名 main.querySelectorAll('[data-sglv-appid]').forEach(el => { Host.loadGameZhName(el, el.getAttribute('data-sglv-appid'), el.textContent); }); // 统一事件绑定 // v1.9.35: 已拥有/未拥有 切换标签——点击已激活的标签则取消(回到全部) const ownOwnedBtn = main.querySelector('#sglv-pub-own-owned'); const ownUnownedBtn = main.querySelector('#sglv-pub-own-unowned'); if (ownOwnedBtn) ownOwnedBtn.addEventListener('click', () => { pubState.filter = pubState.filter === 'owned' ? 'all' : 'owned'; pubDetailState.page = 1; rerender(); }); if (ownUnownedBtn) ownUnownedBtn.addEventListener('click', () => { pubState.filter = pubState.filter === 'unowned' ? 'all' : 'unowned'; pubDetailState.page = 1; rerender(); }); // v1.9.31: 排序事件——字段切换 + 方向切换 const sortFieldSelect = main.querySelector('#sglv-pub-sort-field'); if (sortFieldSelect) sortFieldSelect.addEventListener('change', (e) => { pubState.sortField = e.target.value; pubDetailState.page = 1; rerender(); }); const sortDirBtn = main.querySelector('#sglv-pub-sort-dir'); if (sortDirBtn) sortDirBtn.addEventListener('click', (e) => { e.stopPropagation(); pubState.sortDir = pubState.sortDir === 'asc' ? 'desc' : 'asc'; pubDetailState.page = 1; rerender(); }); // v1.9.31: data-view 属性区分视图按钮与排序方向按钮 main.querySelectorAll('.sglv-view-btn[data-view]').forEach(btn => { btn.addEventListener('click', (e) => { e.stopPropagation(); pubState.viewMode = btn.dataset.view; rerender(); }); }); // v1.9.19: 分页事件(onJump 驱动首/上/下/末页与跳页输入) Host.renderPagination(document.getElementById('sglv-pub-series-pagination'), 'sglv-pub-series', pubDetailState.page, totalPages, displayGames.length, () => { pubDetailState.page--; rerender(); }, () => { pubDetailState.page++; rerender(); }, (p) => { pubDetailState.page = p; rerender(); }); } // ==================== 绝版游戏标签页 ==================== // v1.9.47-fix: 绝版游戏数据兜底链—— // ① Host.getDelistedDb() 同步取(来自主脚本 @resource delistedData;3.5MB 大文件,Tampermonkey // 偶发静默加载失败 + 解析慢导致"暂无绝版游戏数据"), // ② 若 ① 为空 → 异步拉远程源三级回退(fastly.jsdelivr → cdn.jsdelivr → raw.githubusercontent), // ③ 写回 Host.cacheSet('delistedDbRemote', ...) 供后续会话秒开(6h 节流后台刷新)。 // 选 _refreshDelistedFromRemote 而非替换 Host.getDelistedDb(闭包不可改),改为缓存到 // _delistedRemoteCache,并让 getDelistedApps() 优先取它,保留 @resource 作为快速通道。 const _DELISTED_REMOTE_SOURCES = [ 'https://fastly.jsdelivr.net/gh/SmallRob/steam-namespace@main/data/steam_delisted_apps.json', 'https://cdn.jsdelivr.net/gh/SmallRob/steam-namespace@main/data/steam_delisted_apps.json', 'https://raw.githubusercontent.com/SmallRob/steam-namespace/main/data/steam_delisted_apps.json' ]; let _delistedRemoteCache = null; // 远程源完整 JSON {version, source, fetchedAt, totalCount, data} let _delistedRemoteLoading = false; // 防止并发请求 let _delistedRemoteLoaded = false; // 远程已成功加载过(避免每次开 tab 重新拉) const _DELISTED_REMOTE_BG_INTERVAL = 6 * 3600 * 1000; // 6h 后台节流 let _delistedLastBgRefreshAt = 0; let _delistedForceRemote = false; // 工具栏刷新按钮触发(force 走全链路) function _normalizeDelistedRaw(raw) { if (!raw || typeof raw !== 'object') return []; let rawApps = []; if (Array.isArray(raw.data)) rawApps = raw.data; else if (raw.delisted && Array.isArray(raw.delisted.apps)) rawApps = raw.delisted.apps; return rawApps.map(app => ({ appid: app.appId || app.appid, name: app.name, type: app.delistType || app.type || 'Delisted', changed: app.delistedAt || app.changed, owners: app.ownerPercentage != null ? app.ownerPercentage + '%' : (app.owners || '-'), achievements: app.achievementCount || app.achievements, keyshopPrice: app.keyshopPrice, source: app.source })); } // 解析远程响应文本,校验为合法绝版 JSON(data 数组 / totalCount > 0) function _parseDelistedResponseText(txt) { try { const obj = JSON.parse(txt); if (!obj || typeof obj !== 'object') return null; const okData = Array.isArray(obj.data) && obj.data.length > 0; const okLegacy = obj.delisted && Array.isArray(obj.delisted.apps) && obj.delisted.apps.length > 0; if (!okData && !okLegacy) return null; return obj; } catch (e) { return null; } } function _refreshDelistedFromRemote(force) { if (typeof GM_xmlhttpRequest !== 'function') return; if (_delistedRemoteLoading) return; _delistedRemoteLoading = true; function _tryNext(idx) { if (idx >= _DELISTED_REMOTE_SOURCES.length) { _delistedRemoteLoading = false; return; } GM_xmlhttpRequest({ method: 'GET', url: _DELISTED_REMOTE_SOURCES[idx], timeout: 20000, onload(r) { try { const txt = _safeRespText(r); const obj = _parseDelistedResponseText(txt); if (obj) { _delistedRemoteCache = obj; _delistedRemoteLoaded = true; _delistedLastBgRefreshAt = Date.now(); // 写 TTL 缓存(24h),后续会话秒开 try { Host.cacheSet('delistedDbRemote', obj, 24 * 3600 * 1000); } catch (e) { /* 忽略 */ } _delistedRemoteLoading = false; // 触发 UI 重渲染(若当前已开 delisted tab) // v1.9.47-fix: 数据到达时,若 wrap 还是"加载骨架占位"状态(无 toolbar/KPI), // 清空 body 重建 tab 一次性同步 KPI/分类汇总/工具栏(否则仅刷新列表内容)。 if (_collectionActiveTab === 'delisted' && collectionPanelEl && collectionPanelEl.classList.contains('sglv-show')) { const body = collectionPanelEl.querySelector('#sgc-body'); if (body) { const wrap = body.querySelector('.sglv-delisted-wrap'); const hasFullUi = wrap && wrap.querySelector('#sglv-delisted-pagination'); if (hasFullUi) { renderDelistedGamesList(); } else { // 清空 body 重建,避免旧 wrap 与新 wrap 重复 body.innerHTML = ''; renderDelistedTab(body); } } } return; } } catch (e) { /* fallthrough */ } _tryNext(idx + 1); }, onerror() { _tryNext(idx + 1); }, ontimeout() { _tryNext(idx + 1); } }); } _tryNext(0); } // 启动时尝试从 TTL 缓存预热远程源(避免开 tab 才发起请求) function _warmDelistedRemoteCache() { try { const cached = Host.cacheGet('delistedDbRemote'); if (cached && typeof cached === 'object') { if ((Array.isArray(cached.data) && cached.data.length > 0) || (cached.delisted && Array.isArray(cached.delisted.apps) && cached.delisted.apps.length > 0)) { _delistedRemoteCache = cached; _delistedRemoteLoaded = true; } } } catch (e) { /* 忽略 */ } } function getDelistedApps() { // ① 优先 _delistedRemoteCache(已通过远程源/TTL 缓存预热),正常情况 @resource 加载也走这条分支 if (_delistedRemoteCache) return _normalizeDelistedRaw(_delistedRemoteCache); // ② @resource 数据(主脚本 GM_getResourceText('delistedData') 同步返回) const DELISTED_DB = Host.getDelistedDb(); if (DELISTED_DB && ((Array.isArray(DELISTED_DB.data) && DELISTED_DB.data.length > 0) || (DELISTED_DB.delisted && Array.isArray(DELISTED_DB.delisted.apps) && DELISTED_DB.delisted.apps.length > 0))) { return _normalizeDelistedRaw(DELISTED_DB); } // ③ 远程源未触发过 → 触发(force 模式跳过 @resource 兜底走全链路) if (!_delistedRemoteLoaded && !_delistedRemoteLoading) { _refreshDelistedFromRemote(_delistedForceRemote); } return []; } // 工具栏"刷新"按钮触发的强制刷新入口 function forceRefreshDelistedFromRemote() { _delistedForceRemote = true; _delistedRemoteLoaded = false; // 强制重走源 _delistedRemoteCache = null; _delistedRemoteLoading = false; _refreshDelistedFromRemote(true); } // v2.2.0: 绝版类型 → 颜色映射(KPI 行 + 卡片徽章共用) const DELISTED_TYPE_COLORS = { 'delisted': '#f44336', // 已下架 'purchase_disabled': '#fb923c', // 购买禁用 'f2p_unavailable': '#a78bfa', // F2P 不可用 'retail_only': '#60a5fa', // 仅零售 'test_app': '#94a3b8' // 测试应用 }; const DELISTED_TYPE_KEYS = ['delisted', 'purchase_disabled', 'f2p_unavailable', 'retail_only', 'test_app']; function getTypeKey(type) { if (!type) return 'delisted'; // 已经是小写下划线格式,直接返回 if (type.includes('_')) return type; // 大写格式 -> 小写下划线格式 const map = { 'Delisted': 'delisted', 'Purchase disabled': 'purchase_disabled', 'F2P (unavailable)': 'f2p_unavailable', 'Retail only': 'retail_only', 'Test app': 'test_app', }; return map[type] || 'delisted'; } function getTypeLabel(type) { if (!type) return Host.T.typeDelisted; const map = { 'Delisted': Host.T.typeDelisted, 'delisted': Host.T.typeDelisted, 'Purchase disabled': Host.T.typePurchaseDisabled, 'purchase_disabled': Host.T.typePurchaseDisabled, 'F2P (unavailable)': Host.T.typeF2P, 'f2p_unavailable': Host.T.typeF2P, 'Retail only': Host.T.typeRetailOnly, 'retail_only': Host.T.typeRetailOnly, 'Test app': Host.T.typeTestApp, 'test_app': Host.T.typeTestApp, }; return map[type] || type; } function getFilteredDelistedApps() { const allApps = getDelistedApps(); // v2.3.14: 使用 getActiveOwnedAppIds() 替代 ownedAppIds, // 以尊重"显示家庭共享"开关:关闭时仅匹配自己拥有的游戏,不匹配家庭组共享游戏 const ownedIds = Host.getActiveOwnedAppIds(); // v1.9.47-fix: 缓存键加入 ownedIds 集合指纹—— // 此前仅用 ownedIds.size(拥有游戏数量)做粗粒度失效,同数量但不同游戏的 owned 集合变化会导致 // subFilter=owned/missing 筛选结果过时(新购买的不展示,已退款的仍展示)。 // 用前 8 个 appid 的 djb2 哈希 + 数量作指纹,既能精确失效又避免 ownedIds 全量入键(缓存键爆炸)。 let _ownedSig = 0; if (ownedIds && ownedIds.size) { const sample = Array.from(ownedIds).slice(0, 8); let h = ownedIds.size * 2654435761; for (const n of sample) { h = ((h << 5) + h + Number(n) | 0) >>> 0; } _ownedSig = h.toString(36); } const cacheK = Host.cacheKey('delisted-filter', allApps.length, delistedState.subFilter, delistedState.typeFilter, delistedState.search, delistedState.sort, ownedIds.size, _ownedSig); return Host.getCached(cacheK, () => { let apps = allApps; // 子分类筛选:全部 / 已拥有 / 未拥有 if (delistedState.subFilter === 'owned') { apps = apps.filter(a => ownedIds.has(Number(appidFix(a.appid))) || ownedIds.has(String(a.appid))); } else if (delistedState.subFilter === 'missing') { apps = apps.filter(a => !ownedIds.has(Number(appidFix(a.appid))) && !ownedIds.has(String(a.appid))); } // Type filter if (delistedState.typeFilter !== 'all') { apps = apps.filter(a => getTypeKey(a.type) === delistedState.typeFilter); } // Search filter if (delistedState.search) { const q = delistedState.search.toLowerCase(); apps = apps.filter(a => (a.name || '').toLowerCase().includes(q) || String(a.appid).includes(q) ); } // v1.9.32: 排序——按 appid 或下架时间(delistedAt/changed),空日期排末尾 apps = apps.slice().sort((a, b) => { let r = 0; switch (delistedState.sort) { case 'appidAsc': r = (a.appid || 0) - (b.appid || 0); break; case 'dateDesc': { const sa = seriesDateToSortable(a.changed), sb = seriesDateToSortable(b.changed); if (!sa && !sb) { r = 0; break; } if (!sa) return 1; if (!sb) return -1; r = sb.localeCompare(sa); break; } case 'dateAsc': { const sa = seriesDateToSortable(a.changed), sb = seriesDateToSortable(b.changed); if (!sa && !sb) { r = 0; break; } if (!sa) return 1; if (!sb) return -1; r = sa.localeCompare(sb); break; } case 'appidDesc': default: r = (b.appid || 0) - (a.appid || 0); } return r || ((a.appid || 0) - (b.appid || 0)); }); return apps; }); } function appidFix(v) { const n = Number(v); return isNaN(n) ? v : n; } function getOwnedGameInfo(appid) { // v2.3.14: 关闭"显示家庭共享"时,仅在自己拥有的游戏中查找,避免命中家庭组共享游戏 const showFamilyShared = Host.getShowFamilyShared(); const pool = showFamilyShared ? Host.getOwnedGames() : Host.getOwnedGames().filter(g => Host.isGameOwnedByMe(g)); return pool.find(g => g.appid === appidFix(appid)) || null; } function renderDelistedGamesList() { const content = document.getElementById('sglv-delisted-content'); if (!content) return; const apps = getFilteredDelistedApps(); // v2.4.0: 复用 paginate 纯函数统一分页计算 const { pageItems: pageApps, totalPages, page: _clampedPage } = Host.paginate(apps, delistedState.page, delistedState.pageSize); delistedState.page = _clampedPage; // v2.3.14: 使用 getActiveOwnedAppIds() 尊重"显示家庭共享"开关 const ownedIds = Host.getActiveOwnedAppIds(); // v2.2.0: 抽出受限游戏板通用组件(绝版 / 锁区 / 将来可能扩展共用一套) // 卡片元数据构造:owners / changed / achievements / lastPlayed / playtime const ownersSvg = ''; const dateSvg = ''; const clockSvg = ''; if (delistedState.viewMode === 'card') { content.innerHTML = '
' + pageApps.map(function (app) { const appid = appidFix(app.appid); const isOwned = ownedIds.has(Number(appid)) || ownedIds.has(String(appid)); const typeKey = getTypeKey(app.type); const ownedInfo = isOwned ? getOwnedGameInfo(appid) : null; const playtimeH = ownedInfo && ownedInfo.playtime > 0 ? (ownedInfo.playtime / 60).toFixed(1) + 'h' : ''; const lastPlayed = ownedInfo && ownedInfo.lastPlayed ? Host.formatLastPlayedShort(ownedInfo.lastPlayed) : ''; // v2.6.0 关键修复:此前这里传的是 coverHtml = Host.posterImg(...), // 导致绝版 tab 完全绕开了新写的 restrictedCoverImg(横向优先短链 + API 兜底), // 仍在走旧的长链(8 个 library_600x900 竖版 URL)——绝版收录的都是老游戏, // 这 8 个竖版图必然全 404,这就是"绝版封面加载失败"的直接原因。 // 现在删掉 coverHtml 覆盖,让 makeRestrictedCard 走默认的 restrictedCoverImg。 // 游玩时长从封面 overlay 移入右栏 meta(overlay 会与新的状态斜切带抢右下角位置)。 const metaItems = []; if (playtimeH) metaItems.push('' + clockSvg + Host.wlEscape(playtimeH) + ''); if (app.owners) metaItems.push('' + ownersSvg + Host.wlEscape(app.owners) + ''); if (app.changed) metaItems.push('' + dateSvg + Host.wlEscape(app.changed) + ''); return makeRestrictedCard({ appid: appid, name: app.name, isOwned: isOwned, typeLabel: getTypeLabel(app.type), typeKey: typeKey, typeColor: DELISTED_TYPE_COLORS[typeKey] || '#f44336', metaItems: metaItems }); }).join('') + '
'; } else { content.innerHTML = '
' + pageApps.map(function (app) { const appid = appidFix(app.appid); const isOwned = ownedIds.has(Number(appid)) || ownedIds.has(String(appid)); const typeKey = getTypeKey(app.type); const ownedInfo = isOwned ? getOwnedGameInfo(appid) : null; const playtimeH = ownedInfo && ownedInfo.playtime > 0 ? (ownedInfo.playtime / 60).toFixed(1) + 'h' : ''; const lastPlayed = ownedInfo && ownedInfo.lastPlayed ? Host.formatLastPlayedShort(ownedInfo.lastPlayed) : ''; // v2.6.0: 列表视图右栏保留 3 项(拥有率 / 下架 / 最后游玩),比卡片多一项是因为横向空间充裕 const metaItems = []; if (app.owners) metaItems.push('' + ownersSvg + Host.wlEscape(app.owners) + ''); if (app.changed) metaItems.push('' + dateSvg + Host.wlEscape(app.changed) + ''); if (lastPlayed) metaItems.push('' + clockSvg + Host.wlEscape(lastPlayed) + ''); if (playtimeH) metaItems.push('' + Host.wlEscape(playtimeH) + ''); return makeRestrictedListItem({ appid: appid, name: app.name, isOwned: isOwned, typeLabel: getTypeLabel(app.type), typeKey: typeKey, typeColor: DELISTED_TYPE_COLORS[typeKey] || '#f44336', metaItems: metaItems }); }).join('') + '
'; } // v2.3.33:异步加载游戏中文名 content.querySelectorAll('[data-sglv-appid]').forEach(el => { Host.loadGameZhName(el, el.getAttribute('data-sglv-appid'), el.textContent); }); // v2.5.0: 补齐缓存命中图的 loaded 态(onload 早于监听器挂载时不会触发) syncRestrictedCoverStates(content); // v1.9.47-fix: 主脚本 renderPagination 所有按钮(首页/上页/下页/末页/跳页)统一走 onJump, // 缺失第 8 参数 → 翻页按钮全部失效("只能加载第一页")。补传 onJump。 Host.renderPagination(document.getElementById('sglv-delisted-pagination'), 'sglv-delisted', delistedState.page, totalPages, apps.length, () => { delistedState.page--; renderDelistedGamesList(); }, () => { delistedState.page++; renderDelistedGamesList(); }, (p) => { delistedState.page = p; renderDelistedGamesList(); }); } // v1.9.47-fix: 加载骨架占位——构建完整工具栏 + 工具栏事件绑定(刷新按钮), // 内容区域只放加载骨架条。数据到达时由 _refreshDelistedFromRemote 回调触发 // renderDelistedGamesList() 仅更新 #sglv-delisted-content,工具栏/状态保留。 // 这样既保证用户看到工具栏(可点刷新),又不会因数据未到而无法操作。 function _renderDelistedLoadingScaffold(wrap) { // 工具栏(只放搜索框 + 视图按钮 + 刷新按钮,无数据时类型/排序/子筛选无意义,留空避免误操作) const toolbar = document.createElement('div'); toolbar.className = 'sglv-toolbar sglv-delisted-toolbar'; toolbar.innerHTML = `
`; wrap.appendChild(toolbar); // 内容区(加载骨架) const content = document.createElement('div'); content.className = 'sglv-content'; content.id = 'sglv-delisted-content'; const loadingText = _delistedRemoteLoading ? (Host.isZh ? '正在加载绝版游戏数据…' : 'Loading delisted game data…') : (Host.isZh ? '暂无绝版游戏数据' : 'No delisted game data available'); content.innerHTML = '
' + loadingText + '
'; wrap.appendChild(content); // 刷新按钮事件(复用正常路径的事件签名,只是数据为空时点击依然可走 force 全链路) const refreshBtn = toolbar.querySelector('#sglv-delisted-refresh'); if (refreshBtn) { refreshBtn.addEventListener('click', () => { if (refreshBtn.classList.contains('sglv-spin')) return; refreshBtn.classList.add('sglv-spin'); const restore = () => refreshBtn.classList.remove('sglv-spin'); forceRefreshDelistedFromRemote(); setTimeout(restore, 30000); const poll = setInterval(() => { if (!_delistedRemoteLoading) { clearInterval(poll); restore(); } }, 200); }); } } // v2.5.0: 重渲染绝版 KPI 卡片行——筛选态(scope / type)变化后需要刷新 active 态与各类型可见计数。 // scope 变化会改变每个类型卡显示的计数(scopeBase 随 scope 收窄),所以必须整体重算而非切 class。 function renderDelistedTabKpi(kpiEl) { if (!kpiEl) return; const apps = getDelistedApps(); if (!apps.length) { kpiEl.innerHTML = ''; return; } const ownedIds = Host.getActiveOwnedAppIds(); const isOwnedId = (id) => ownedIds.has(Number(id)) || ownedIds.has(String(id)); const totalDelisted = apps.length; let ownedDelisted = 0; apps.forEach(app => { if (isOwnedId(app.appid)) ownedDelisted++; }); const scope = (delistedState.subFilter === 'owned') ? 'owned' : (delistedState.subFilter === 'missing') ? 'missing' : 'all'; const scopeBase = (scope === 'owned') ? apps.filter(a => isOwnedId(a.appid)) : (scope === 'missing') ? apps.filter(a => !isOwnedId(a.appid)) : apps; const typeLabels = { 'delisted': Host.T.typeDelisted, 'purchase_disabled': Host.T.typePurchaseDisabled, 'f2p_unavailable': Host.T.typeF2P, 'retail_only': Host.T.typeRetailOnly, 'test_app': Host.T.typeTestApp }; // v2.6.0: KPI 小卡行 → HERO 仪表盘(与锁区同款,铺满浮窗宽度 + 分类占比可视化) kpiEl.innerHTML = makeRestrictedHero({ total: totalDelisted, ownedCount: ownedDelisted, scopeBase: scopeBase.map(function (a) { return { type: getTypeKey(a.type) }; }), scope: scope, typeFilter: delistedState.typeFilter, title: Host.T.delistedTotal, typeKeys: DELISTED_TYPE_KEYS, typeColors: DELISTED_TYPE_COLORS, typeLabels: typeLabels, tabId: 'delisted' }); } function renderDelistedTab(parent) { const wrap = document.createElement('div'); wrap.className = 'sglv-delisted-wrap'; // v1.9.47-fix: 首次进入触发远程源兜底预热(@resource 加载失败/同步阻塞时仍能加载) if (!_delistedRemoteLoaded && !_delistedRemoteLoading) { _warmDelistedRemoteCache(); // 先尝试 TTL 缓存(秒开) if (!_delistedRemoteCache) _refreshDelistedFromRemote(false); // 无缓存 → 远程源 } // v1.9.47-fix: 后台静默刷新节流(6h) else if (_delistedRemoteLoaded && !_delistedRemoteLoading && (Date.now() - _delistedLastBgRefreshAt) > _DELISTED_REMOTE_BG_INTERVAL) { _refreshDelistedFromRemote(false); } const apps = getDelistedApps(); if (apps.length === 0) { // v1.9.47-fix: 构建完整工具栏(可点刷新) + 加载骨架占位。 // 数据到达时 _refreshDelistedFromRemote 回调 → renderDelistedGamesList() // 仅更新 #sglv-delisted-content,工具栏/状态保留(避免重新打开 tab 闪烁)。 parent.appendChild(wrap); _renderDelistedLoadingScaffold(wrap); return; } // v2.3.14: 使用 getActiveOwnedAppIds() 尊重"显示家庭共享"开关, // 关闭家庭共享时 KPI 与分类统计均仅计自己拥有的绝版游戏 const ownedIds = Host.getActiveOwnedAppIds(); const totalDelisted = apps.length; let ownedDelisted = 0; apps.forEach(app => { if (ownedIds.has(Number(app.appid)) || ownedIds.has(String(app.appid))) ownedDelisted++; }); const missingDelisted = totalDelisted - ownedDelisted; // v2.5.0 收敛:原布局有 5 层筛选 UI(KPI 行 / 类型徽章汇总栏 / 独立进度条 / // 工具栏类型按钮组 / 工具栏拥有状态按钮组),后三层与前两层表达同一组维度,视觉噪音极大。 // 改为 2 层:① KPI 卡片行(3 scope + 5 类型,全部可点即筛选)② 工具栏(搜索 / 排序 / 视图 / 刷新)。 // 拥有率进度条的信息不再单独占一行。 const kpiSection = document.createElement('div'); kpiSection.id = 'sglv-delisted-kpi'; wrap.appendChild(kpiSection); renderDelistedTabKpi(kpiSection); // Toolbar(v2.5.0: 移除类型/拥有状态按钮组——已由 KPI 卡片承担;此处只留搜索 / 排序 / 视图 / 刷新) // v2.8.0: 分页器并入工具栏右侧同一行(此前独立成行,多占一整行垂直空间) const toolbar = document.createElement('div'); toolbar.className = 'sglv-toolbar sglv-delisted-toolbar'; toolbar.innerHTML = ` `; wrap.appendChild(toolbar); // Content area const content = document.createElement('div'); content.className = 'sglv-content'; content.id = 'sglv-delisted-content'; wrap.appendChild(content); parent.appendChild(wrap); // Event bindings // v2.5.0: 筛选职责已收敛到 KPI 卡片行 —— 用事件委托替代原先分散在 // 「分类汇总徽章 / 工具栏类型按钮 / 工具栏拥有状态按钮」三处的监听。 // - data-delisted-scope="all|owned|missing" → subFilter // - data-delisted-type="" → typeFilter(再次点击同一类型回到「全部」) const scopeToSub = { all: 'all', owned: 'owned', missing: 'missing' }; kpiSection.addEventListener('click', e => { // v2.6.0: 点击 HERO 左侧主数字区 → 一键清空 type + sub 两个筛选维度 if (!e.target.closest('[data-delisted-scope],[data-delisted-type]') && e.target.closest('.sglv-hero-left')) { if (delistedState.subFilter !== 'all' || delistedState.typeFilter !== 'all') { delistedState.subFilter = 'all'; delistedState.typeFilter = 'all'; delistedState.page = 1; renderDelistedTabKpi(kpiSection); renderDelistedGamesList(); } return; } const scopeCard = e.target.closest('[data-delisted-scope]'); if (scopeCard) { delistedState.subFilter = scopeToSub[scopeCard.dataset.delistedScope] || 'all'; delistedState.page = 1; renderDelistedTabKpi(kpiSection); renderDelistedGamesList(); return; } const typeCard = e.target.closest('[data-delisted-type]'); if (typeCard) { const t = typeCard.dataset.delistedType; delistedState.typeFilter = (delistedState.typeFilter === t) ? 'all' : t; delistedState.page = 1; renderDelistedTabKpi(kpiSection); renderDelistedGamesList(); } }); toolbar.querySelector('#sglv-delisted-search').addEventListener('input', _debounce((e) => { delistedState.search = e.target.value; delistedState.page = 1; renderDelistedGamesList(); }, 200)); // v1.9.32: 排序下拉事件 toolbar.querySelector('#sglv-delisted-sort').addEventListener('change', (e) => { delistedState.sort = e.target.value; delistedState.page = 1; renderDelistedGamesList(); }); toolbar.querySelector('#sglv-delisted-card').addEventListener('click', () => { delistedState.viewMode = 'card'; toolbar.querySelector('#sglv-delisted-card').classList.add('active'); toolbar.querySelector('#sglv-delisted-list').classList.remove('active'); renderDelistedGamesList(); }); toolbar.querySelector('#sglv-delisted-list').addEventListener('click', () => { delistedState.viewMode = 'list'; toolbar.querySelector('#sglv-delisted-list').classList.add('active'); toolbar.querySelector('#sglv-delisted-card').classList.remove('active'); renderDelistedGamesList(); }); // v1.9.47-fix: 远程源手动刷新(@resource 加载失败时可点此走三级回退) const refreshBtn = toolbar.querySelector('#sglv-delisted-refresh'); if (refreshBtn) { refreshBtn.addEventListener('click', () => { if (refreshBtn.classList.contains('sglv-spin')) return; refreshBtn.classList.add('sglv-spin'); const restore = () => refreshBtn.classList.remove('sglv-spin'); const prevLoading = _delistedRemoteLoading; forceRefreshDelistedFromRemote(); // 监听 30s 后兜底还原(防止失败场景按钮卡在 spinning 状态) setTimeout(restore, 30000); // 轮询直到 loading=false 再还原 const poll = setInterval(() => { if (!_delistedRemoteLoading) { clearInterval(poll); restore(); } }, 200); }); } renderDelistedGamesList(); } // v1.9.27: 安全读取 GM_xmlhttpRequest 响应文本 // 浏览器扩展(如 inspector.js) hook XMLHttpRequest.prototype.send 并修改 responseType 为 arraybuffer, // 导致 r.responseText 抛 InvalidStateError。此函数先尝试 responseText,失败后尝试 response(ArrayBuffer→TextDecoder) function _safeRespText(r) { try { if (r.responseText) return r.responseText; } catch (e) { /* responseType 被外部修改为 arraybuffer */ } try { if (typeof r.response === 'string') return r.response; if (r.response instanceof ArrayBuffer) return new TextDecoder().decode(new Uint8Array(r.response)); } catch (e2) { /* ignore */ } return ''; } // ==================== PS 会免标签页 (v2.6.0) ==================== // 远程数据源:psplus-games.json(由 oXnMe/psplus-steam-overlay 维护) // 数据结构:{ updatedAt, count, games: [{ recordId, steamAppId, tier, month, monthSort, statusName, statusDisplay, statusDate, versions, psstore, color }] } // tier: 1=Essential(必备) 2=Extra(升级) 3=Premium(高级) // statusName: 在库/领取中/截止领取/已出库/即将出库 const PSPLUS_DATA_URL = 'https://fastly.jsdelivr.net/gh/oXnMe/psplus-steam-overlay@main/data/psplus-games.json'; // v1.9.37: 降级数据源——由 js_script/psplus-data-sync.js 每日同步镜像到 SmallRob/steam-namespace 仓库 // 主源(oXnMe)不可用时依次尝试三级 CDN 回退链(参照 EPIC_GITHUB_URLS 写法) const PSPLUS_BACKUP_URLS = [ 'https://fastly.jsdelivr.net/gh/SmallRob/steam-namespace@main/data/psplus-games.json', 'https://cdn.jsdelivr.net/gh/SmallRob/steam-namespace@main/data/psplus-games.json', 'https://raw.githubusercontent.com/SmallRob/steam-namespace/main/data/psplus-games.json' ]; // PS Logo SVG(白色,用于占位封面) // v2.9.22: 真实 PlayStation 标识(官方蓝紫色 P + S 经典组合,参考 PS 官方 logo SVG) const PS_LOGO_SVG = ''; // 从 PS Store URL 提取游戏名称(slug → Title Case)——v2.6.2 增强支持 playstation.com games slug 与 store.playstation.com product ID function psExtractName(psstore) { if (!psstore) return ''; // 1. playstation.com /games/{slug} 形式 const m = psstore.match(/\/games\/([^\/\?]+)/); if (m) { return m[1].split('-').filter(Boolean).map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' '); } // 2. store.playstation.com /product/{id}_{name} 形式——name 在 ID 之后可能含字母+数字 // 例如 UP1642-CUSA04798_00-SLUS211960000001 → SLUS211960000001 // JP0106-PPSA34548_00-GITAROOMAN000000 → GITAROOMAN000000 const p = psstore.match(/\/product\/[A-Z0-9\-]+_00-([A-Za-z0-9]+)/); if (p) { // ID 经常是大写字母+数字混合,去掉前 1-2 字母前缀尝试拆分:SLUS21196 → SLUS-21196;GITAROOMAN → GITAROO MAN const raw = p[1]; // 尝试按"大写+小写"分词(AstroBot → Astro Bot) const spaced = raw.replace(/([a-z])([A-Z])/g, '$1 $2'); // 尝试按"数字+字母"分词(SLUS21196 → SLUS 21196) const spaced2 = spaced.replace(/([A-Z]+)(\d)/g, '$1 $2').replace(/(\d)([A-Z])/g, '$1 $2'); // 尝试按纯连续大写字母拆:GITAROOMAN → GITAROO MAN (按 4+ 字母) let result = spaced2.replace(/([A-Z]{4,})/g, m => m.replace(/([A-Z]{2})([A-Z]+)/, '$1 $2').trim()); // 收尾:把数字与字母之间加空格 result = result.replace(/([A-Za-z])(\d)/g, '$1 $2').replace(/(\d)([A-Za-z])/g, '$1 $2'); return result.split(/\s+/).filter(Boolean).map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' '); } return ''; } // v2.6.2: PS 独占异步抓取 psstore 页面获取中文名(基于 product ID 解析 ) // v2.9.7: 升级为「PS Store 元数据」抓取——同一次请求同时解析中文名与真实封面主视觉。 // 背景:收藏模块里唯一的非 Steam 游戏是「PS 会免」里无 steamAppId 的 PS 独占条目 // (实测数据源 1595 条中 293 条无 steamAppId),此前只有一块蓝色 PS Logo 占位画,没有封面。 // 做法参考 steam-friend-manager 1.6.2 的非 Steam 卡(sfd-tga-excl-art + sfd-tga-excl-img): // 平台占位画垫底,商店主视觉图覆盖其上;图加载失败自动移除图,保住占位画。 // 主视觉来源:PS Store 页面内嵌的 schema.org JSON-LD(script#mfe-jsonld-tags → Product.image), // 实测为 1024×1024 方图,CDN image.api.playstation.com 可直链热链(无需 Referer)。 // 输入 psstore URL;输出 Promise<{name, cover}>,空字符串表示获取失败 const _psStoreMetaPending = new Map(); const _PS_STORE_NAME_TTL = 6 * 3600 * 1000; // 6h,与 PS 会免数据 TTL 对齐 const _PS_STORE_NAME_NEG_TTL = 30 * 60 * 1000; // 失败 30 分钟内不再请求 const _PS_STORE_COVER_TTL = 30 * 24 * 3600 * 1000; // 封面主视觉 30 天(静态资源,几乎不变) const _PS_STORE_COVER_NEG_TTL = 6 * 3600 * 1000; // 封面抓取失败 6h 后再试 const SGLV_PS_NAME_KEY = 'sglvPsStoreNameCache_v1'; // v1 旧 key(仅中文名,用于一次性迁移) const SGLV_PS_META_KEY = 'sglvPsStoreMetaCache_v2'; // v2 新 key(中文名 + 封面图) const _PS_META_MAX_CONCURRENCY = 4; // PS Store 页面 300KB+,限并发避免打满带宽 const _PS_STORE_PRIMARY_LOCALE = 'zh-hans-hk'; // 主区域(数据源多为该区域) const _PS_STORE_ALT_LOCALE = 'en-us'; // 兜底区域(主区域缺图时再试一次) // 内存镜像 —— 避免每次读缓存都 GM_getValue + JSON.parse(单页 49 张卡会放大成 49 次解析) let _psMetaCacheMap = null; let _psMetaFlushTimer = null; let _psMetaDirty = false; function sglvPsStoreMetaCacheLoad() { if (_psMetaCacheMap) return _psMetaCacheMap; let map = {}; try { map = JSON.parse(GM_getValue(SGLV_PS_META_KEY, '{}') || '{}') || {}; } catch (e) { map = {}; } if (!map || typeof map !== 'object') map = {}; // 迁移 v1(仅中文名)——封面字段留空,等首次抓取补齐 try { const old = JSON.parse(GM_getValue(SGLV_PS_NAME_KEY, '{}') || '{}') || {}; Object.keys(old).forEach(u => { if (map[u]) return; const o = old[u]; if (!o) return; map[u] = { name: o.name || '', nameTs: o.ts || 0 }; }); } catch (e) { /* 忽略迁移失败 */ } _psMetaCacheMap = map; return map; } // 落盘节流——一页 49 张卡会连续写 49 次,整表 JSON 序列化放大成几十 MB 写入 function sglvPsStoreMetaCacheSave() { _psMetaDirty = true; if (_psMetaFlushTimer) return; _psMetaFlushTimer = setTimeout(() => { _psMetaFlushTimer = null; if (!_psMetaDirty) return; _psMetaDirty = false; try { GM_setValue(SGLV_PS_META_KEY, JSON.stringify(_psMetaCacheMap || {})); } catch (e) { /* 忽略失败 */ } }, 3000); } // 旧接口(仅中文名)保留,内部并入元数据抓取 function sglvPsStoreNameCacheLoad() { return sglvPsStoreMetaCacheLoad(); } function sglvPsStoreNameCacheSave() { sglvPsStoreMetaCacheSave(); } // 区域化 URL——数据源里 psstore 多数是 zh-hant-hk,统一到主区域再抓 // 只替换「语言-地区」段(如 zh-hans-hk / en-us),不动 www.playstation.com/games/{slug} 这类无区域段 URL function psStoreLocaleUrl(url, locale) { if (!url) return ''; if (!/playstation\.com/.test(url)) return url; if (!locale) return url; if (url.indexOf('/' + locale + '/') >= 0) return url; return url.replace(/(playstation\.com)\/[a-z]{2}(?:-[a-z]{2,4}){0,2}\//, '$1/' + locale + '/'); } // PS Store 页面 → 官方名(og:title → <title> → twitter:title,与 v2.6.2 既有口径一致) function parsePsStoreName(html) { let name = ''; try { if (!html) return ''; let m = html.match(/<meta\s+(?:[^>]*?)property=["']og:title["']\s+(?:[^>]*?)content=["']([^"']+)/i); if (!m) m = html.match(/<title[^>]*>([^<]+)<\/title>/i); if (!m) m = html.match(/<meta\s+(?:[^>]*?)name=["']twitter:title["']\s+(?:[^>]*?)content=["']([^"']+)/i); if (m) { name = m[1] .replace(/\s*\|\s*PlayStation.*$/i, '') .replace(/\s*-\s*PlayStation.*$/i, '') .replace(/\s*·\s*PlayStation.*$/i, '') .replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'") .trim(); } } catch (e) { /* 忽略失败 */ } // v2.9.9: og:title 可能整页就是平台/商店名(区域限售页回落到首页), // 此时解析出的"name"是 "PlayStation" 之类泛化词,回填会把卡片名改成平台名 —— 视为抓取失败。 if (/^(playstation(\s+(store|official\s+site))?|ps\s*store|games?)$/i.test(name)) return ''; return name; } // PS Store 页面 → 真实封面主视觉(只认 image.api.playstation.com 主视觉域) function isPsCoverUrl(u) { return typeof u === 'string' && /^https:\/\/image\.api\.playstation\.com\/vulcan\//.test(u); } function parsePsStoreCover(html) { if (!html) return ''; try { // ① schema.org JSON-LD(PS Store SSR 直出 Product.image) const m = html.match(/<script[^>]+id=["']mfe-jsonld-tags["'][^>]*>([\s\S]*?)<\/script>/i); if (m) { try { const o = JSON.parse(m[1]); const img = o && typeof o.image === 'string' ? o.image : ''; if (isPsCoverUrl(img)) return img; } catch (e) { /* JSON 解析失败走兜底 */ } } // ② 兜底——页面里第一张非评分图标的主视觉 const all = html.match(/https:\/\/image\.api\.playstation\.com\/vulcan\/[^"'\\\s]+?\.(?:jpg|jpeg|png)/gi); if (all) { for (let i = 0; i < all.length; i++) if (isPsCoverUrl(all[i])) return all[i]; } } catch (e) { /* 忽略失败 */ } return ''; } // 页面抓取(GM_xmlhttpRequest 包装) function psStoreRequest(url) { return new Promise(resolve => { if (typeof GM_xmlhttpRequest !== 'function') { resolve(''); return; } GM_xmlhttpRequest({ method: 'GET', url: url, timeout: 15000, onload(resp) { let html = ''; try { html = _safeRespText(resp); } catch (e) { html = ''; } resolve(html || ''); }, onerror() { resolve(''); }, ontimeout() { resolve(''); } }); }); } // 并发闸门——PS Store 页面体积大,限制同时在飞的请求数 let _psMetaQueue = []; let _psMetaActive = 0; function psMetaEnqueue(task) { return new Promise(resolve => { _psMetaQueue.push({ task, resolve }); psMetaPump(); }); } function psMetaPump() { while (_psMetaActive < _PS_META_MAX_CONCURRENCY && _psMetaQueue.length) { const job = _psMetaQueue.shift(); _psMetaActive++; const release = () => { _psMetaActive--; psMetaPump(); }; Promise.resolve().then(job.task) .then(meta => job.resolve(meta || { name: '', cover: '' }), () => job.resolve({ name: '', cover: '' })) .then(release, release); } } // 读缓存里的封面 URL(同步,供渲染时直接贴 src,避免"先空后闪") function psStoreCoverCacheGet(url) { if (!url) return ''; try { const e = sglvPsStoreMetaCacheLoad()[url]; if (!e || !e.cover || !e.coverTs) return ''; if (Date.now() - e.coverTs > _PS_STORE_COVER_TTL) return ''; return e.cover; } catch (e) { return ''; } } // 抓取 + 缓存:一次请求同时产出中文名与封面主视觉 async function fetchPsStoreMetaNow(psstoreUrl) { const cache = sglvPsStoreMetaCacheLoad(); const entry = cache[psstoreUrl] || {}; const now = Date.now(); const nameFresh = !!(entry.name && entry.nameTs && (now - entry.nameTs) < _PS_STORE_NAME_TTL); const coverFresh = !!(entry.cover && entry.coverTs && (now - entry.coverTs) < _PS_STORE_COVER_TTL); const coverFailed = !!(entry.coverFailTs && (now - entry.coverFailTs) < _PS_STORE_COVER_NEG_TTL); // 缓存全命中 → 不发请求 if ((!Host.isZh || nameFresh) && (coverFresh || coverFailed)) { return { name: entry.name || '', cover: entry.cover || '' }; } const primaryUrl = psStoreLocaleUrl(psstoreUrl, _PS_STORE_PRIMARY_LOCALE); const html = await psStoreRequest(primaryUrl); let name = nameFresh ? (entry.name || '') : parsePsStoreName(html); let cover = coverFresh ? (entry.cover || '') : parsePsStoreCover(html); // 主区域没 SSR 出主视觉(部分地区未发行/限售)→ 换美区再试一次 if (!cover && !coverFresh && !coverFailed) { const altUrl = psStoreLocaleUrl(psstoreUrl, _PS_STORE_ALT_LOCALE); if (altUrl && altUrl !== primaryUrl) { const altHtml = await psStoreRequest(altUrl); if (altHtml) { cover = parsePsStoreCover(altHtml); if (!name && !nameFresh) name = parsePsStoreName(altHtml); } } } const next = Object.assign({}, entry); if (name && name !== entry.name) { next.name = name; next.nameTs = now; } if (cover) { next.cover = cover; next.coverTs = now; delete next.coverFailTs; } else if (!coverFresh) { next.coverFailTs = now; } cache[psstoreUrl] = next; sglvPsStoreMetaCacheSave(); return { name: name || '', cover: cover || '' }; } // 对外入口:同 URL 并发去重 + 并发闸门 function fetchPsStoreMeta(psstoreUrl) { if (!psstoreUrl) return Promise.resolve({ name: '', cover: '' }); if (_psStoreMetaPending.has(psstoreUrl)) return _psStoreMetaPending.get(psstoreUrl); const p = psMetaEnqueue(() => fetchPsStoreMetaNow(psstoreUrl)).then(meta => { _psStoreMetaPending.delete(psstoreUrl); return meta; }, () => { _psStoreMetaPending.delete(psstoreUrl); return { name: '', cover: '' }; }); _psStoreMetaPending.set(psstoreUrl, p); return p; } // v2.6.2 旧接口:只取中文名(中文环境才有意义) function fetchPsStoreName(psstoreUrl) { if (!Host.isZh) return Promise.resolve(''); if (!psstoreUrl) return Promise.resolve(''); const cache = sglvPsStoreMetaCacheLoad(); const cached = cache[psstoreUrl]; if (cached) { if (cached.name && Date.now() - (cached.nameTs || 0) < _PS_STORE_NAME_TTL) return Promise.resolve(cached.name); if (!cached.name && Date.now() - (cached.nameTs || 0) < _PS_STORE_NAME_NEG_TTL) return Promise.resolve(''); } return fetchPsStoreMeta(psstoreUrl).then(meta => meta.name || ''); } // PS 会免占位封面 DOM(蓝色渐变 + 真实 PS 标识 + 名称),供运行时回退统一调用 function psPlaceholderDom(name) { const holder = document.createElement('div'); holder.className = 'sglv-ps-cover-placeholder'; holder.innerHTML = '<div class="sglv-ps-logo">' + PS_LOGO_SVG + '</div><div class="sglv-ps-cover-name">' + Host.wlEscape(name || 'PS Exclusive') + '</div>'; return holder; } // PS 会免封面图全局回退:Steam CDN 全部失败时先用 Store API 取真实封面 URL, // API URL 仍加载失败时替换为蓝色 PS 占位(v1.1.1:修复 API URL 二次失败无兜底导致破图) // v1.9.29: 传递 kind 参数,使 API 兜底按图片类型选择最佳 URL unsafeWindow._sglvPsCoverFallback = function(img, appid, kind) { if (!img || !img.parentElement) return; Host.fetchCoverApiUrl(appid, kind).then(url => { if (url) { img.onerror = function() { img.onerror = null; img.parentElement.replaceChild(psPlaceholderDom(img.alt), img); }; img.src = url; return; } img.parentElement.replaceChild(psPlaceholderDom(img.alt), img); }); }; // PS 会免列表视图图标回退:CDN 图标失败时替换为 PS 蓝色占位 div // (保持 92x43 尺寸,避免旧版 this.style.display='none' 导致整行左对齐错位) unsafeWindow._sglvPsListIconFallback = function(img) { if (!img || !img.parentElement) return; const holder = document.createElement('div'); holder.className = 'sglv-list-icon'; holder.style.cssText = 'display:flex;align-items:center;justify-content:center;background:linear-gradient(135deg,#003791,#0070D1);color:#fff;border-radius:4px;padding:4px'; holder.innerHTML = Host.ICONS.playstation; img.parentElement.replaceChild(holder, img); }; // PS 会免封面 —— v2.8.0 统一走 unifiedCover。 // 原实现是本项目最严重的封面反模式:每次渲染都用循环拼出 12 层嵌套的 // `this.src='...';this.onerror=function(){...}` 字符串再塞进 inline onerror, // 还叠加 _sgcvCoverRace 竞速 + 跨上下文 _sglvPsCoverFallback 兜底。 // 后果:① HTML 体积暴涨 ② 内联属性里的多层闭包极易被 CSP/扩展拦截 // ③ 跨视图切换撞上一次性锁后永久失效(用户反馈的"大海报视图无封面")。 // v2.9.7: 无 appid 的 PS 独占游戏不再只有占位画——占位画下垫一层真实封面主视觉 // (data-sglv-ps-cover 由 bindPsExclusiveCovers 异步补 src)。 function psplusPosterImg(appid, name, psstore) { if (!appid) return _psExclusivePlaceholder(name, psstore); // v2.9.4: 卡片墙默认竖版海报(竖版优先链,拿不到自动回退横版 header) return unifiedCover(appid, name, 'poster', { preferVertical: true }); } function psplusCapsuleImg(appid, name, psstore) { if (!appid) return _psExclusivePlaceholder(name, psstore); return unifiedCover(appid, name, 'capsule', { imgCls: 'sglv-wl-cover-img' }); } // PS 独占占位画 + 真实封面图层 // 占位画(蓝色 PS Logo + 名称)垫底,封面图绝对定位覆盖其上; // 封面抓不到/加载失败 → 图被移除,占位画原样保留(与 friend-manager 非 Steam 卡同构)。 function _psExclusivePlaceholder(name, psstore) { const cover = psstore ? '<img class="sglv-ps-excl-cover" data-sglv-ps-cover="' + Host.wlEscape(psstore) + '" alt="" loading="lazy" decoding="async" referrerpolicy="no-referrer">' : ''; return '<div class="sglv-ps-cover-placeholder"><div class="sglv-ps-logo">' + PS_LOGO_SVG + '</div><div class="sglv-ps-cover-name"' + (psstore ? ' data-sglv-psstore="' + Host.wlEscape(psstore) + '"' : '') + '>' + Host.wlEscape(name || 'PS Exclusive') + '</div></div>' + cover; } // PS 独占封面绑定:给占位画上的 img 补真实主视觉 // ① 缓存命中 → 同步贴 src(无闪烁) // ② 未命中 → 异步抓 PS Store 页(与中文名共用同一次请求),拿到后补 src // ③ 加载失败/无图 → 直接移除 img,占位画不受影响 function bindPsExclusiveCovers(root) { if (!root || typeof root.querySelectorAll !== 'function') return; const imgs = root.querySelectorAll('img[data-sglv-ps-cover]'); if (!imgs.length) return; Array.prototype.forEach.call(imgs, img => { const url = img.getAttribute('data-sglv-ps-cover'); if (!url) { img.remove(); return; } if (img.getAttribute('data-sglv-ps-bound') === '1') return; img.setAttribute('data-sglv-ps-bound', '1'); img.addEventListener('load', () => img.classList.add('sglv-ps-excl-cover-loaded'), { once: true }); img.addEventListener('error', () => img.remove(), { once: true }); const cached = psStoreCoverCacheGet(url); if (cached) { img.src = cached; return; } fetchPsStoreMeta(url).then(meta => { if (!meta || !meta.cover) { img.remove(); return; } if (!img.isConnected) return; img.src = meta.cover; }); }); } function psTierLabel(tier) { if (tier === 1) return Host.T.psTierEssential; if (tier === 2) return Host.T.psTierExtra; if (tier === 3) return Host.T.psTierPremium; return '?'; } function psTierClass(tier) { if (tier === 1) return 'tier-essential'; if (tier === 2) return 'tier-extra'; if (tier === 3) return 'tier-premium'; return ''; } // 状态颜色映射 function psStatusColor(statusName) { if (statusName === '在库') return '#4caf50'; if (statusName === '领取中') return '#2196f3'; if (statusName === '截止领取' || statusName === '已出库') return '#ff9800'; if (statusName === '即将出库') return '#ff5722'; return '#888'; } // 获取游戏显示名称——v2.6.2 优先用 psstore 提取的英文名作为初始显示,中文名异步替换 // 有 steamAppId:先用 psExtractName 提取英文名(如果有 psstore),再异步 fetchGameZhName 替换为中文名 // 无 steamAppId (PS 独占):用 psExtractName 提取英文名,再异步 fetchPsStoreName 抓页面拿中文名 function psGameName(g) { const fromPs = psExtractName(g.psstore); if (fromPs) return fromPs; if (g.steamAppId) return Host.isZh ? `App ${g.steamAppId}` : `App ${g.steamAppId}`; return Host.isZh ? 'PS 独占' : 'PS Exclusive'; } // 数据加载(@resource 兜底 + 远程 JSON 异步更新 + 永久缓存) // v1.9.5: 缓存永不过期——优先读永久缓存秒开,后台静默全量刷新(6h 节流) // v2.7.1: @require 库中 GM_xmlhttpRequest 可能因 Tampermonkey 沙箱隔离而静默挂起, // 改为优先用 @resource(GM_getResourceText)同步兜底,后台异步更新缓存。 const _PSPLUS_BG_INTERVAL = 6 * 3600 * 1000; // v1.9.5: 后台刷新 6h 节流 let _psplusLastBgRefreshAt = 0; // v1.9.24: 简单字符串哈希(djb2 变体),用于检测远程数据是否变化 function _psplusDataHash(str) { let hash = 5381; const len = str.length; // 采样哈希:前500字符 + 后500字符 + 长度,避免对超大 JSON 全量遍历 const sample = str.slice(0, 500) + str.slice(Math.max(0, len - 500)) + len; for (let i = 0; i < sample.length; i++) { hash = ((hash << 5) + hash) + sample.charCodeAt(i); hash = hash & hash; } return String(hash); } async function loadPsplusGames() { // v1.9.38: 移除 force 刷新路径(刷新按钮已移除),保留缓存/资源秒开 + 后台静默刷新 if (psplusState.loading) return; // v1.9.5: 优先读永久缓存(永不过期) const cached = _permCacheGet('psplusGames'); if (cached && Array.isArray(cached.games) && cached.games.length > 0) { psplusState.games = cached.games; psplusState.updatedAt = cached.updatedAt || ''; psplusState.loaded = true; renderPsplusSections(); // 后台静默刷新(6h 节流) if (_shouldThrottle(_psplusLastBgRefreshAt, _PSPLUS_BG_INTERVAL)) return; _refreshPsplusFromRemote(false); return; } // 2) 永久缓存无 → 用 @resource 同步兜底(GM_getResourceText,零网络依赖) let resourceData = null; try { const raw = Host.getResourceText ? Host.getResourceText('psplusData') : null; if (raw) { const parsed = JSON.parse(raw); if (parsed && Array.isArray(parsed.games) && parsed.games.length > 0) { resourceData = parsed; } } } catch (e) { /* resource 解析失败,忽略 */ } if (resourceData) { psplusState.games = resourceData.games; psplusState.updatedAt = resourceData.updatedAt || ''; psplusState.loaded = true; psplusState.loading = false; // v1.9.26: 写入永久缓存(含 dataHash) _permCacheSet('psplusGames', { games: resourceData.games, updatedAt: resourceData.updatedAt, dataHash: _psplusDataHash(JSON.stringify(resourceData)) }); renderPsplusSections(); // 后台异步更新(获取最新全量快照) _refreshPsplusFromRemote(false); return; } // 3) @resource 也不可用 → 回退到 GM_xmlhttpRequest 异步加载 _refreshPsplusFromRemote(true); } // 内部:后台异步从远程 JSON 更新 PS会免数据 // v1.9.5: 远程数据到达后全量替换(上游为每日全量快照) // v1.9.26: 增加 _psplusDataHash 哈希对比——远程数据未变化则跳过更新/缓存写入 // v1.9.38: 移除 force 刷新(刷新按钮/spinner/状态文本已删除) // showLoading=true 时显示 loading 状态(用于无缓存的首次加载) function _refreshPsplusFromRemote(showLoading) { if (typeof GM_xmlhttpRequest !== 'function') return; // 沙箱中不可用则跳过 // v1.9.38: 无手动刷新入口,loading 中直接返回避免并发请求 if (psplusState.loading) return; // v1.9.26: 获取缓存中的数据哈希,用于远程数据变化检测 const cached = _permCacheGet('psplusGames'); const cachedHash = (cached && cached.dataHash) || ''; if (showLoading) { psplusState.loading = true; psplusState.loadError = null; renderPsplusGamesList(); } // v1.9.27: loading 安全超时——30s 后强制清除 loading(防止浏览器扩展阻断回调导致永久卡死) let _psplusLoadingTimer = null; if (showLoading) { _psplusLoadingTimer = setTimeout(() => { if (psplusState.loading) { psplusState.loading = false; // 尝试从永久缓存恢复数据 const cacheFallback = _permCacheGet('psplusGames'); if (cacheFallback && Array.isArray(cacheFallback.games) && cacheFallback.games.length > 0) { psplusState.games = cacheFallback.games; psplusState.updatedAt = cacheFallback.updatedAt || ''; psplusState.loaded = true; psplusState.loadError = null; } else { psplusState.loadError = 'Timeout (loading safety)'; } renderPsplusGamesList(); } }, 30000); } // v1.9.27: 统一清理 loading 超时定时器 const _clearLoadingTimer = () => { if (_psplusLoadingTimer) { clearTimeout(_psplusLoadingTimer); _psplusLoadingTimer = null; } }; // v1.9.27: 错误时尝试从永久缓存恢复数据(避免刷新失败导致数据全部丢失) const _restoreCacheOnError = () => { if (psplusState.games.length === 0) { const cacheFallback = _permCacheGet('psplusGames'); if (cacheFallback && Array.isArray(cacheFallback.games) && cacheFallback.games.length > 0) { psplusState.games = cacheFallback.games; psplusState.updatedAt = cacheFallback.updatedAt || ''; psplusState.loaded = true; psplusState.loadError = null; return true; } } return false; }; // v1.9.37: 主源 + 降级数据源多级回退——主源(oXnMe)失败时依次尝试 SmallRob/steam-namespace 镜像 const _psplusAllUrls = [PSPLUS_DATA_URL].concat(PSPLUS_BACKUP_URLS); function _tryNextUrl(idx) { if (idx >= _psplusAllUrls.length) { // 所有源均失败 → 尝试从缓存恢复数据 _clearLoadingTimer(); if (showLoading) { psplusState.loading = false; if (_restoreCacheOnError()) { renderPsplusSections(); } else { psplusState.loadError = 'All sources failed'; renderPsplusGamesList(); } } return; } GM_xmlhttpRequest({ method: 'GET', url: _psplusAllUrls[idx], timeout: 20000, onload(r) { try { // v1.9.27: 使用 _safeRespText 防止浏览器扩展 hook XHR 导致 responseText 抛 InvalidStateError const rawText = _safeRespText(r); // v1.9.37: 非 2xx 响应 → 尝试下一个源 if (r.status < 200 || r.status >= 300 || !rawText) { _tryNextUrl(idx + 1); return; } // v1.9.26: 计算远程数据哈希,与缓存哈希对比 const remoteHash = _psplusDataHash(rawText); // v1.9.26: 哈希对比——远程数据未变化则跳过更新,保留现有缓存和状态 if (cachedHash && remoteHash === cachedHash) { _clearLoadingTimer(); psplusState.loading = false; _psplusLastBgRefreshAt = Date.now(); return; } const parsed = JSON.parse(rawText); if (parsed && Array.isArray(parsed.games) && parsed.games.length > 0) { _clearLoadingTimer(); // v1.9.38: 上游为全量快照,直接整体替换 state(修复 _mergeByAppid 按 appid // 合并、但 PS会免条目无 appid 字段导致非空状态合并后数据被清空的根因) psplusState.games = parsed.games; psplusState.updatedAt = parsed.updatedAt || ''; psplusState.loaded = true; psplusState.loading = false; _psplusLastBgRefreshAt = Date.now(); // v1.9.26: 写入永久缓存(含 dataHash) _permCacheSet('psplusGames', { games: psplusState.games, updatedAt: psplusState.updatedAt, dataHash: remoteHash }); renderPsplusSections(); return; } // 格式无效 → 尝试下一个源 _tryNextUrl(idx + 1); } catch (e) { // 解析异常 → 尝试下一个源 _tryNextUrl(idx + 1); } }, onerror() { _tryNextUrl(idx + 1); }, ontimeout() { _tryNextUrl(idx + 1); }, }); } _tryNextUrl(0); } // 筛选 + 排序 function getFilteredPsplus() { const q = psplusState.search.toLowerCase().trim(); const ownedIds = Host.getActiveOwnedAppIds(); const isPsOwned = g => g.steamAppId && (ownedIds.has(Number(g.steamAppId)) || ownedIds.has(String(g.steamAppId))); let games = psplusState.games.filter(g => { if (q) { const name = psExtractName(g.psstore).toLowerCase(); const appid = String(g.steamAppId || ''); if (!name.includes(q) && !appid.includes(q) && !(g.month || '').includes(q)) return false; } if (psplusState.tierFilter !== 'all') { // v1.6.0: catalog 档位匹配 tier 2(升级) + 3(高级) if (psplusState.tierFilter === 'catalog') { if (g.tier !== 2 && g.tier !== 3) return false; } else if (String(g.tier) !== psplusState.tierFilter) return false; } if (psplusState.statusFilter !== 'all') { if (psplusState.statusFilter === 'expired') { if (g.statusName !== '截止领取' && g.statusName !== '已出库') return false; } else if (psplusState.statusFilter === 'steamOwned') { // v2.7.9: 直接筛选 Steam 家庭共享库已有的匹配游戏 if (!isPsOwned(g)) return false; } else if (g.statusName !== psplusState.statusFilter) return false; } return true; }); const tierOrder = { 1: 1, 2: 2, 3: 3 }; games.sort((a, b) => { switch (psplusState.sort) { case 'dateAsc': return (a.monthSort || '').localeCompare(b.monthSort || ''); case 'tierAsc': return (tierOrder[a.tier] || 9) - (tierOrder[b.tier] || 9) || (b.monthSort || '').localeCompare(a.monthSort || ''); case 'tierDesc': return (tierOrder[b.tier] || 9) - (tierOrder[a.tier] || 9) || (b.monthSort || '').localeCompare(a.monthSort || ''); case 'nameAsc': return _nameCollator.compare(psExtractName(a.psstore) || '~', psExtractName(b.psstore) || '~'); case 'dateDesc': default: return (b.monthSort || '').localeCompare(a.monthSort || ''); } }); return games; } // ----- 渲染 ----- function renderPsplusTab(parent) { const wrap = document.createElement('div'); wrap.className = 'sglv-psplus-wrap'; // KPI 区域 const kpi = document.createElement('div'); kpi.id = 'sglv-psplus-kpi'; wrap.appendChild(kpi); // 工具栏(v2.6.1:紧凑两行——第1行 搜索+排序+视图;第2行 筛选按钮+分页) const toolbar = document.createElement('div'); toolbar.className = 'sglv-toolbar'; const sortOptions = [ { key: 'dateDesc', label: Host.T.psSortDateDesc }, { key: 'dateAsc', label: Host.T.psSortDateAsc }, { key: 'tierAsc', label: Host.T.psSortTierAsc }, { key: 'tierDesc', label: Host.T.psSortTierDesc }, { key: 'nameAsc', label: Host.T.psSortNameAsc }, ]; toolbar.innerHTML = ` <input class="sglv-search" aria-label="搜索" id="sglv-psplus-search" placeholder="${Host.T.psSearch}" value="${Host.wlEscape(psplusState.search)}"> <select class="sglv-sort-select" aria-label="排序方式" id="sglv-psplus-sort"> ${sortOptions.map(o => `<option value="${o.key}"${psplusState.sort === o.key ? ' selected' : ''}>${o.label}</option>`).join('')} </select> <div class="sglv-view-toggle"> <button class="sglv-btn sglv-btn-secondary sglv-btn-icon${psplusState.viewMode === 'card' ? ' active' : ''}" id="sglv-ps-card" title="${Host.T.cardView}">${Host.ICONS.grid}</button> <button class="sglv-btn sglv-btn-secondary sglv-btn-icon${psplusState.viewMode === 'cover' ? ' active' : ''}" id="sglv-ps-cover" title="${Host.T.coverView}">${Host.ICONS.cover}</button> <button class="sglv-btn sglv-btn-secondary sglv-btn-icon${psplusState.viewMode === 'list' ? ' active' : ''}" id="sglv-ps-list" title="${Host.T.listView}">${Host.ICONS.list}</button> </div> <span class="sglv-ps-status" id="sglv-ps-status"></span> `; wrap.appendChild(toolbar); // 筛选栏(档位 + 状态)——分页也放这一行(v2.6.1 紧凑操作栏) const filterBar = document.createElement('div'); filterBar.className = 'sglv-filter-bar'; const tierBtns = [ { key: 'all', label: Host.T.all }, { key: '1', label: Host.T.psTierEssential }, { key: '2', label: Host.T.psTierExtra }, { key: '3', label: Host.T.psTierPremium }, ]; const statusBtns = [ { key: 'all', label: Host.T.psStatusAll }, { key: '在库', label: Host.T.psStatusIn }, { key: '领取中', label: Host.T.psStatusActive }, { key: 'expired', label: Host.T.psStatusExpired }, { key: '即将出库', label: Host.T.psStatusLeaving }, { key: 'steamOwned', label: Host.T.steamInLib }, ]; filterBar.innerHTML = ` <div class="sglv-filter-bar-group"> ${tierBtns.map(b => `<button class="sglv-btn sglv-btn-secondary sglv-ps-tier-btn${psplusState.tierFilter === b.key ? ' active' : ''}" data-tier="${b.key}">${b.label}</button>`).join('')} </div> <span class="sglv-filter-sep"></span> <div class="sglv-filter-bar-group"> ${statusBtns.map(b => `<button class="sglv-btn sglv-btn-secondary sglv-ps-status-btn${psplusState.statusFilter === b.key ? ' active' : ''}" data-status="${b.key}">${b.label}</button>`).join('')} </div> <div class="sglv-pagination sglv-pagination-inline" id="sglv-psplus-pagination"></div> `; wrap.appendChild(filterBar); // 游戏列表容器 const content = document.createElement('div'); content.className = 'sglv-content'; content.id = 'sglv-psplus-content'; wrap.appendChild(content); parent.appendChild(wrap); // 事件绑定 toolbar.querySelector('#sglv-psplus-search').addEventListener('input', _debounce((e) => { psplusState.search = e.target.value; psplusState.page = 1; renderPsplusGamesList(); }, 200)); toolbar.querySelector('#sglv-psplus-sort').addEventListener('change', (e) => { psplusState.sort = e.target.value; psplusState.page = 1; renderPsplusGamesList(); }); const setPsViewMode = (mode) => { psplusState.viewMode = mode; ['card', 'cover', 'list'].forEach(m => { toolbar.querySelector('#sglv-ps-' + m)?.classList.toggle('active', m === mode); }); renderPsplusGamesList(); }; toolbar.querySelector('#sglv-ps-card').addEventListener('click', () => setPsViewMode('card')); toolbar.querySelector('#sglv-ps-cover').addEventListener('click', () => setPsViewMode('cover')); toolbar.querySelector('#sglv-ps-list').addEventListener('click', () => setPsViewMode('list')); filterBar.querySelectorAll('.sglv-ps-tier-btn').forEach(btn => { btn.addEventListener('click', () => { psplusState.tierFilter = btn.dataset.tier; psplusState.page = 1; filterBar.querySelectorAll('.sglv-ps-tier-btn').forEach(b => b.classList.remove('active')); btn.classList.add('active'); renderPsplusKpi(); // v1.6.0: 同步 KPI active 高亮 renderPsplusGamesList(); }); }); filterBar.querySelectorAll('.sglv-ps-status-btn').forEach(btn => { btn.addEventListener('click', () => { psplusState.statusFilter = btn.dataset.status; psplusState.page = 1; filterBar.querySelectorAll('.sglv-ps-status-btn').forEach(b => b.classList.remove('active')); btn.classList.add('active'); renderPsplusKpi(); // v1.6.0: 同步 KPI active 高亮 renderPsplusGamesList(); }); }); // v1.6.0: 筛选改为点击 KPI 卡片切换(再次点击同一卡片回到「全部」),与年度大作/Epic赠送标签页一致 kpi.addEventListener('click', e => { const card = e.target.closest('[data-psplus-filter]'); if (!card) return; const f = card.dataset.psplusFilter; const activeKpi = getPsplusActiveKpi(); if (activeKpi === f) { // 再次点击同一卡片 → 回到「全部」 psplusState.tierFilter = 'all'; psplusState.statusFilter = 'all'; } else { switch (f) { case 'all': psplusState.tierFilter = 'all'; psplusState.statusFilter = 'all'; break; case 'essential': psplusState.tierFilter = '1'; psplusState.statusFilter = 'all'; break; case 'catalog': psplusState.tierFilter = 'catalog'; psplusState.statusFilter = 'all'; break; case 'steamOwned': psplusState.tierFilter = 'all'; psplusState.statusFilter = 'steamOwned'; break; } } psplusState.page = 1; syncPsplusFilterBtns(filterBar); // 同步筛选栏按钮 active 状态 renderPsplusKpi(); // 刷新 KPI active 高亮 renderPsplusGamesList(); }); if (!psplusState.loaded && !psplusState.loading) { loadPsplusGames(); } else { renderPsplusSections(); } } function renderPsplusSections() { if (_collectionActiveTab !== 'psplus' || !document.getElementById('sglv-psplus-content')) return; renderPsplusKpi(); renderPsplusGamesList(); renderPsplusRefreshStatus(); } /** v1.9.38: 渲染 PS会免工具栏状态文本(仅显示更新时间,手动刷新已移除) */ function renderPsplusRefreshStatus() { const el = document.getElementById('sglv-ps-status'); if (!el) return; const zh = Host.isZh; const date = psplusState.updatedAt ? psplusState.updatedAt.slice(0, 10) : ''; el.textContent = date ? (zh ? '更新: ' : 'Updated: ') + date : ''; el.className = 'sglv-ps-status'; } // v1.6.0: 根据 tierFilter + statusFilter 推断当前激活的 KPI 卡片 function getPsplusActiveKpi() { if (psplusState.tierFilter === 'all' && psplusState.statusFilter === 'all') return 'all'; if (psplusState.tierFilter === '1' && psplusState.statusFilter === 'all') return 'essential'; if (psplusState.tierFilter === 'catalog' && psplusState.statusFilter === 'all') return 'catalog'; if (psplusState.tierFilter === 'all' && psplusState.statusFilter === 'steamOwned') return 'steamOwned'; return ''; // 自定义组合,无 KPI 高亮 } // v1.6.0: KPI 点击后同步筛选栏按钮 active 状态 function syncPsplusFilterBtns(filterBar) { filterBar.querySelectorAll('.sglv-ps-tier-btn').forEach(b => { b.classList.toggle('active', b.dataset.tier === psplusState.tierFilter); }); filterBar.querySelectorAll('.sglv-ps-status-btn').forEach(b => { b.classList.toggle('active', b.dataset.status === psplusState.statusFilter); }); } function renderPsplusKpi() { const el = document.getElementById('sglv-psplus-kpi'); if (!el) return; if (!psplusState.loaded) { el.innerHTML = ''; return; } const games = psplusState.games; const total = games.length; const essential = games.filter(g => g.tier === 1).length; const catalog = games.filter(g => g.tier === 2 || g.tier === 3).length; const steamLinked = games.filter(g => g.steamAppId).length; const ownedIds = Host.getActiveOwnedAppIds(); const steamOwned = games.filter(g => g.steamAppId && (ownedIds.has(Number(g.steamAppId)) || ownedIds.has(String(g.steamAppId)))).length; const updatedStr = psplusState.updatedAt ? (Host.isZh ? '更新于 ' : 'Updated ') + psplusState.updatedAt.slice(0, 10) : ''; const activeKpi = getPsplusActiveKpi(); const tipAll = Host.isZh ? '点击筛选:全部' : 'Click to filter: All'; const tipEssential = Host.isZh ? '点击筛选:必备档' : 'Click to filter: Essential'; const tipCatalog = Host.isZh ? '点击筛选:升级/高级档' : 'Click to filter: Extra/Premium'; const tipSteam = Host.isZh ? '点击筛选:Steam 已拥有' : 'Click to filter: Owned on Steam'; el.innerHTML = ` <div class="sglv-trend-kpi-row"> <div class="sglv-trend-kpi-card blue clickable${activeKpi === 'all' ? ' active' : ''}" data-psplus-filter="all" title="${tipAll}"> <div class="sglv-trend-kpi-header"><span class="sglv-trend-kpi-icon">${Host.ICONS.playstation}</span><span class="sglv-trend-kpi-label">${Host.T.psKpiTotal}</span></div> <div class="sglv-trend-kpi-value">${total.toLocaleString()}</div> <div class="sglv-trend-kpi-sub">${updatedStr}</div> </div> <div class="sglv-trend-kpi-card clickable${activeKpi === 'essential' ? ' active' : ''}" style="border-left:3px solid #FFCD3C" data-psplus-filter="essential" title="${tipEssential}"> <div class="sglv-trend-kpi-header"><span class="sglv-trend-kpi-icon" style="color:#FFCD3C">${Host.ICONS.gift}</span><span class="sglv-trend-kpi-label">${Host.T.psKpiMonthly}</span></div> <div class="sglv-trend-kpi-value">${essential.toLocaleString()}</div> <div class="sglv-trend-kpi-sub">${Host.T.psTierEssential}</div> </div> <div class="sglv-trend-kpi-card clickable${activeKpi === 'catalog' ? ' active' : ''}" style="border-left:3px solid #2196f3" data-psplus-filter="catalog" title="${tipCatalog}"> <div class="sglv-trend-kpi-header"><span class="sglv-trend-kpi-icon" style="color:#2196f3">${Host.ICONS.library}</span><span class="sglv-trend-kpi-label">${Host.T.psKpiCatalog}</span></div> <div class="sglv-trend-kpi-value">${catalog.toLocaleString()}</div> <div class="sglv-trend-kpi-sub">${Host.T.psTierExtra} / ${Host.T.psTierPremium}</div> </div> <div class="sglv-trend-kpi-card mine clickable${activeKpi === 'steamOwned' ? ' active' : ''}" data-psplus-filter="steamOwned" title="${tipSteam}"> <div class="sglv-trend-kpi-header"><span class="sglv-trend-kpi-icon">${Host.ICONS.heart}</span><span class="sglv-trend-kpi-label">${Host.T.psKpiSteamOwned}</span></div> <div class="sglv-trend-kpi-value">${steamOwned.toLocaleString()}</div> <div class="sglv-trend-kpi-sub">${Host.T.psKpiSteamTotal.replace('{n}', steamLinked)}</div> </div> </div> `; } function renderPsplusGamesList() { const content = document.getElementById('sglv-psplus-content'); if (!content) return; const clearPagination = () => { const p = document.getElementById('sglv-psplus-pagination'); if (p) p.innerHTML = ''; }; if (psplusState.loading) { content.innerHTML = '<div class="sglv-progress" style="margin:16px 0"><div class="sglv-progress-fill" style="width:45%"></div></div><div class="sglv-empty">' + Host.T.psLoading + '</div>'; clearPagination(); return; } if (psplusState.loadError) { content.innerHTML = '<div class="sglv-empty">' + Host.T.psLoadError + '</div>'; clearPagination(); return; } if (!psplusState.loaded || psplusState.games.length === 0) { content.innerHTML = '<div class="sglv-empty">' + Host.T.psLoading + '</div>'; clearPagination(); return; } const games = getFilteredPsplus(); if (games.length === 0) { content.innerHTML = '<div class="sglv-empty">' + (Host.isZh ? '无匹配结果' : 'No matching results') + '</div>'; clearPagination(); return; } const { pageItems, totalPages, page: _clampedPage } = Host.paginate(games, psplusState.page, psplusState.pageSize); psplusState.page = _clampedPage; const ownedIds = Host.getActiveOwnedAppIds(); const isOwned = g => g.steamAppId && (ownedIds.has(Number(g.steamAppId)) || ownedIds.has(String(g.steamAppId))); const tierBadgeHtml = g => '<span class="sglv-ps-tier-badge ' + psTierClass(g.tier) + '">' + psTierLabel(g.tier) + '</span>'; const statusBadgeHtml = g => '<span class="sglv-card-badge" style="background:' + psStatusColor(g.statusName) + ';color:#fff;font-size:10px;margin-top:0;padding:2px 6px;border-radius:3px">' + Host.wlEscape(g.statusDisplay || g.statusName) + '</span>'; const versionsHtml = g => (g.versions || []).map(v => '<span style="font-size:10px;padding:1px 4px;border-radius:2px;background:rgba(255,255,255,0.1);border:1px solid rgba(255,255,255,0.2)">' + v + '</span>').join(' '); const ownershipBadgeHtml = g => isOwned(g) ? '<span class="sglv-card-badge owned" style="margin-top:0">✓ ' + Host.T.steamInLib + '</span>' : ''; // 卡片视图 if (psplusState.viewMode === 'card') { content.innerHTML = '<div class="sglv-card-grid sglv-card-grid-7">' + pageItems.map(g => { const appid = Number(g.steamAppId) || 0; const name = psGameName(g); const clickUrl = appid ? 'https://store.steampowered.com/app/' + appid : (g.psstore || '#'); // v2.6.2: 名称 span 加 data-sglv-psstore 以便异步替换 PS 独占中文名 const nameSpan = appid ? '<span data-sglv-appid="' + appid + '" data-sglv-psstore="' + Host.wlEscape(g.psstore || '') + '">' + Host.wlEscape(name) + '</span><span class="sglv-card-id-inline">' + appid + '</span>' : '<span data-sglv-psstore="' + Host.wlEscape(g.psstore || '') + '">' + Host.wlEscape(name) + '</span>'; return '<div class="sglv-game-card sglv-poster-card" data-appid="' + (appid || g.recordId) + '" onclick="window.open(\'' + clickUrl + '\',\'_blank\')">' + '<div class="sglv-card-img-wrap">' + tierBadgeHtml(g) + psplusPosterImg(appid, name, g.psstore) + '</div>' + '<div class="sglv-card-body">' + '<div class="sglv-card-name" title="' + Host.wlEscape(name) + '">' + nameSpan + '</div>' + '<div class="sglv-info-row sglv-wl-price-row">' + statusBadgeHtml(g) + ownershipBadgeHtml(g) + '</div>' + '<div class="sglv-info-row sglv-ps-meta-row"><span class="sglv-meta-item sglv-ps-month-item"><span class="sglv-ps-clock">' + Host.ICONS.clock + '</span><span>' + Host.wlEscape(g.month || '') + '</span></span><span class="sglv-ps-versions">' + versionsHtml(g) + '</span></div>' + '</div>' + '</div>'; }).join('') + '</div>'; } else if (psplusState.viewMode === 'cover') { // 封面视图(横板大图) // v2.9.22: 信息行紧凑到 3 行:标题 / [状态+在库] / [月份+版本] content.innerHTML = '<div class="sglv-wl-cover-grid">' + pageItems.map(g => { const appid = Number(g.steamAppId) || 0; const name = psGameName(g); const clickUrl = appid ? 'https://store.steampowered.com/app/' + appid : (g.psstore || '#'); const nameSpan = appid ? '<span data-sglv-appid="' + appid + '" data-sglv-psstore="' + Host.wlEscape(g.psstore || '') + '">' + Host.wlEscape(name) + '</span><span class="sglv-card-id-inline">' + appid + '</span>' : '<span data-sglv-psstore="' + Host.wlEscape(g.psstore || '') + '">' + Host.wlEscape(name) + '</span>'; return '<div class="sglv-wl-cover-card" data-appid="' + (appid || g.recordId) + '" onclick="window.open(\'' + clickUrl + '\',\'_blank\')">' + '<div class="sglv-wl-cover-img-wrap">' + tierBadgeHtml(g) + (appid ? unifiedCover(appid, name, 'capsule') : psplusCapsuleImg(0, name, g.psstore)) + '</div>' + '<div class="sglv-wl-cover-body">' + '<div class="sglv-card-name" title="' + Host.wlEscape(name) + '">' + nameSpan + '</div>' + '<div class="sglv-info-row sglv-wl-price-row sglv-ps-status-row">' + statusBadgeHtml(g) + ownershipBadgeHtml(g) + '</div>' + '<div class="sglv-info-row sglv-ps-meta-row"><span class="sglv-meta-item sglv-ps-month-item"><span class="sglv-ps-clock">' + Host.ICONS.clock + '</span><span>' + Host.wlEscape(g.month || '') + '</span></span><span class="sglv-ps-versions">' + versionsHtml(g) + '</span></div>' + '</div>' + '</div>'; }).join('') + '</div>'; } else { // 列表视图 content.innerHTML = '<div class="sglv-list-view">' + pageItems.map(g => { const appid = Number(g.steamAppId) || 0; const name = psGameName(g); const clickUrl = appid ? 'https://store.steampowered.com/app/' + appid : (g.psstore || '#'); const iconHtml = appid ? '<img class="sglv-list-icon" src="' + Host.getGameIconUrl(appid, '') + '" alt="' + Host.wlEscape(name) + '" loading="lazy" decoding="async" onerror="_sglvPsListIconFallback(this)">' // v2.9.7: PS 独占——PS 图标垫底 + 真实封面图覆盖其上(失败自动移除图) : '<div class="sglv-list-icon sglv-ps-excl-iconwrap" style="display:flex;align-items:center;justify-content:center;background:linear-gradient(135deg,#003791,#0070D1);color:#fff;border-radius:4px;padding:4px">' + Host.ICONS.playstation + (g.psstore ? '<img class="sglv-ps-excl-cover" data-sglv-ps-cover="' + Host.wlEscape(g.psstore) + '" alt="" loading="lazy" decoding="async" referrerpolicy="no-referrer">' : '') + '</div>'; const nameSpan = appid ? '<span data-sglv-appid="' + appid + '" data-sglv-psstore="' + Host.wlEscape(g.psstore || '') + '">' + Host.wlEscape(name) + '</span><span class="sglv-card-id-inline">' + appid + '</span>' : '<span data-sglv-psstore="' + Host.wlEscape(g.psstore || '') + '">' + Host.wlEscape(name) + '</span>'; return '<div class="sglv-list-item" data-appid="' + (appid || g.recordId) + '" onclick="window.open(\'' + clickUrl + '\',\'_blank\')">' + iconHtml + '<div class="sglv-list-info">' + '<div class="sglv-list-name">' + nameSpan + '</div>' + '<div class="sglv-list-meta">' + tierBadgeHtml(g) + statusBadgeHtml(g) + ownershipBadgeHtml(g) + '<span style="font-size:11px;color:var(--sglv-text-secondary)">' + Host.wlEscape(g.month || '') + '</span><span style="display:flex;gap:2px">' + versionsHtml(g) + '</span></div>' + '</div>' + '</div>'; }).join('') + '</div>'; } // v1.9.47-fix: 补 onJump——PS会免翻页 5 个按钮全部走 onJump(参见主脚本 renderPagination) const pagination = document.getElementById('sglv-psplus-pagination'); if (pagination) { Host.renderPagination(pagination, 'sglv-psplus', psplusState.page, totalPages, games.length, () => { psplusState.page--; renderPsplusGamesList(); }, () => { psplusState.page++; renderPsplusGamesList(); }, (p) => { psplusState.page = p; renderPsplusGamesList(); }); } // v2.6.2: 异步加载中文名——同时支持 steam appid 路径与 PS 独占 psstore 路径 content.querySelectorAll('[data-sglv-appid]').forEach(el => { Host.loadGameZhName(el, el.getAttribute('data-sglv-appid'), el.textContent); }); // v2.6.2: PS 独占(无 steamAppId)——异步抓 psstore 页面替换为中文名 // v2.9.7: 改走 fetchPsStoreMeta —— 与封面主视觉共用同一次请求(不再二次抓页) content.querySelectorAll('[data-sglv-psstore]').forEach(el => { const psUrl = el.getAttribute('data-sglv-psstore'); if (!psUrl) return; // 已经有 appid 的由 loadGameZhName 处理,这里跳过 if (el.hasAttribute('data-sglv-appid')) return; const original = el.textContent; fetchPsStoreMeta(psUrl).then(meta => { // 英文环境沿用既有命名(psExtractName 的 slug 标题化),不做替换 if (!Host.isZh) return; const zhName = meta && meta.name; if (zhName && zhName !== original) { el.textContent = zhName; el.title = `${zhName} (${original})`; } }); }); // v2.8.0: 统一封面链绑定(addEventListener,无跨上下文 inline onerror) bindRestrictedCoverLoaders(content); // v2.9.7: PS 独占(非 Steam 游戏)真实封面绑定——占位画上叠商店主视觉 bindPsExclusiveCovers(content); } // ==================== Epic 赠送标签页 (v1.1.0) ==================== // 数据来源:GitHub 自建数据源 epic_freebies.json(epic-freebies-weekly-sync.js 周同步生产,jsdelivr 三级回退)。 // v1.9.19: 已移除 keylol 抓取兜底(帖子需登录阅读权限,无法获取)。 // 与 "E宝的爱标识助手" 脚本共享 GM 存储 key 'epic_freebie_ids',可互相补充。 // 数据仅为 Steam appid 集合(无名称/日期/档位),名称经 Steam 中文名异步加载。 // 多级兜底:① IDB 永久缓存 → ② GM 存储 epic_freebie_ids + 内置名单 → ③ 远程抓取(GitHub 数据源三级回退)→ ④ 手动 JSON 导入。 // 拥有判定:getActiveOwnedAppIds()(尊重家庭组开关),匹配当前 Steam 用户家庭共享游戏库。 // v1.9.17: GitHub 自建数据源三级回退链(参照年度大作 GOTY_DATA_SOURCES 写法)—— // 优先 jsdelivr(国内稳定),raw.githubusercontent 兜底;v1.9.19 起全部失败即视为刷新失败。 const EPIC_GITHUB_URLS = [ 'https://fastly.jsdelivr.net/gh/SmallRob/steam-namespace@main/data/epic_freebies.json', // ① fastly 节点(优先) 'https://cdn.jsdelivr.net/gh/SmallRob/steam-namespace@main/data/epic_freebies.json', // ② jsdelivr 主节点 'https://raw.githubusercontent.com/SmallRob/steam-namespace/main/data/epic_freebies.json' // ③ raw 兜底 ]; const EPIC_GM_KEY = 'epic_freebie_ids'; // 与 E宝的爱标识助手 共享 // 内置兜底名单(取自 E宝的爱标识助手 MANUAL_FREEBIE_IDS) const EPIC_MANUAL_IDS = ['690640','1564220','822094','750920','391220','203160','362960','346940','234650','300550','49520','261640']; // v2.9.22: Epic Games 盾形标识(深色盾形 + 白色 EPIC/GAMES 文字,参考 Epic 官方 logo) const EPIC_LOGO_SVG = '<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"><path d="M8 18 L8 52 C8 70 26 86 50 94 C74 86 92 70 92 52 L92 18 Z" fill="#1a1a1a" stroke="#3a3a3a" stroke-width="1.2"/><text x="50" y="47" text-anchor="middle" font-family="Arial Black, Helvetica, sans-serif" font-size="20" font-weight="900" fill="#fff" letter-spacing="0.5">EPIC</text><text x="50" y="65" text-anchor="middle" font-family="Arial, Helvetica, sans-serif" font-size="11" font-weight="700" fill="#fff" letter-spacing="1.2">GAMES</text></svg>'; // 名称缓存(会话级,供搜索/排序使用;中文复用宿主持久化缓存;英文复用宿主 fetchGameEnName // (filters=basic + 会话缓存,与橱窗别名/SGIS 别名路径共享,v2.45.1 收编 _epicFetchEnName) const _epicNameCache = new Map(); const _epicNamePending = new Map(); function epicLoadName(appid) { const id = Number(appid); if (!id) return Promise.resolve(''); if (_epicNameCache.has(id)) return Promise.resolve(_epicNameCache.get(id)); if (_epicNamePending.has(id)) return _epicNamePending.get(id); // 默认中文名:中文环境优先复用宿主持久化中文名缓存(含 30 天 TTL + 负缓存); // 中文名获取失败(游戏无中文名 / 请求失败)→ 回退英文名,确保至少展示一种语言名称。 const p = (async () => { if (Host.isZh && typeof Host.fetchGameZhName === 'function') { const zh = await Host.fetchGameZhName(id); if (zh) { _epicNameCache.set(id, zh); _epicNamePending.delete(id); return zh; } } // 英文名走宿主桥(老宿主无此导出时降级为空名 → 显示 'App xxx' 占位) const en = (Host && typeof Host.fetchGameEnName === 'function') ? await Host.fetchGameEnName(id) : ''; _epicNameCache.set(id, en || ''); _epicNamePending.delete(id); return en || ''; })(); _epicNamePending.set(id, p); return p; } function epicDisplayName(appid) { const cached = _epicNameCache.get(Number(appid)); if (cached) return cached; return 'App ' + appid; } function epicSourceLabel(source) { if (source === 'github') return Host.T.epicSourceGithub || (Host.isZh ? 'GitHub 数据源' : 'GitHub'); if (source === 'keylol') return Host.T.epicSourceKeylol; if (source === 'local') return Host.T.epicSourceLocal; if (source === 'import') return Host.T.epicSourceImport; return Host.T.epicSourceManual; } // Epic 占位封面(HTML 字符串,用于无 appid 时初始渲染)——深色盾形 + EPIC 标识 + 名称 function epicPlaceholder(name) { return '<div class="sglv-ps-cover-placeholder sglv-epic-cover-placeholder" style="background:linear-gradient(135deg,#0d0d0d,#1f1f1f)"><div class="sglv-epic-logo">' + EPIC_LOGO_SVG + '</div><div class="sglv-ps-cover-name">' + Host.wlEscape(name || 'Epic') + '</div></div>'; } // Epic 占位封面 DOM(深色渐变 + 真实 Epic 盾形标识 + 名称),供运行时回退统一调用 function epicPlaceholderDom(name) { const holder = document.createElement('div'); holder.className = 'sglv-ps-cover-placeholder sglv-epic-cover-placeholder'; holder.style.background = 'linear-gradient(135deg,#0d0d0d,#1f1f1f)'; holder.innerHTML = '<div class="sglv-epic-logo">' + EPIC_LOGO_SVG + '</div><div class="sglv-ps-cover-name">' + Host.wlEscape(name || 'Epic') + '</div>'; return holder; } // Epic 封面全局回退:Steam CDN 全部失败时先用 Store API 取真实封面 URL, // API URL 仍加载失败时替换为深色 Epic 占位(v1.1.1:修复 API URL 二次失败无兜底导致破图) // v1.9.29: 传递 kind 参数,使 API 兜底按图片类型选择最佳 URL unsafeWindow._sglvEpicCoverFallback = function(img, appid, kind) { if (!img || !img.parentElement) return; Host.fetchCoverApiUrl(appid, kind).then(url => { if (url) { img.onerror = function() { img.onerror = null; img.parentElement.replaceChild(epicPlaceholderDom(img.alt), img); }; img.src = url; return; } img.parentElement.replaceChild(epicPlaceholderDom(img.alt), img); }); }; // 竖版封面(卡片视图) // v1.9.29: ① 传递 kind 给 _sglvEpicCoverFallback ② onerror 链跳过 chain[0] // v1.9.41: good/链走 coverGoodUrl/coverChainLang function epicPosterImg(appid, name) { // v2.8.0: 统一封面(原实现走 coverGoodUrl + inline _sglvChainFallback, // 跨视图切换时会撞上 _sglvChainLoading 一次性锁导致永久失效) // v2.9.4: 卡片墙默认竖版海报(竖版优先链,拿不到自动回退横版 header) return unifiedCover(appid, name, 'poster', { preferVertical: true }); } // 徽章 function epicFreeBadgeHtml() { return '<span class="sglv-card-badge sglv-epic-free-badge">' + Host.T.epicBadgeFree + '</span>'; } function epicOwnedBadgeHtml(owned) { return owned ? '<span class="sglv-card-badge owned" style="margin-top:0">✓ ' + Host.T.steamInLib + '</span>' : '<span class="sglv-card-badge" style="background:rgba(255,255,255,0.12);color:#8f98a0;margin-top:0;padding:2px 6px;border-radius:3px;font-size:10px">' + Host.T.epicBadgeNotOwned + '</span>'; } // 合并多个来源 → 去重数字数组 function mergeEpicIds(...sources) { const set = new Set(); for (const src of sources) { if (!Array.isArray(src)) continue; for (const id of src) { const n = Number(id); if (n > 0) set.add(n); } } return Array.from(set); } // 加载 Epic 赠送数据(多级兜底) // v1.9.5: 缓存永不过期——优先读永久缓存秒开,后台增量合并刷新(6h 节流) const _EPIC_BG_INTERVAL = 6 * 3600 * 1000; let _epicLastBgRefreshAt = 0; function loadEpicGames(force = false) { // v1.9.27: force 时重置可能卡死的 loading 标志 if (epicState.loading) { if (!force) return; epicState.loading = false; } // v1.9.5: 优先读永久缓存(永不过期) if (!force) { const cached = _permCacheGet('epicFreeGames'); if (cached && Array.isArray(cached.appids) && cached.appids.length > 0) { epicState.appids = cached.appids; epicState.updatedAt = cached.updatedAt || ''; epicState.source = cached.source || ''; epicState.loaded = true; renderEpicSections(); // 后台增量刷新(6h 节流) if (_shouldThrottle(_epicLastBgRefreshAt, _EPIC_BG_INTERVAL)) return; _refreshEpicFromRemote(false, false); return; } } // 2) GM 存储 + 内置名单(即时兜底) let gmIds = []; try { gmIds = GM_getValue(EPIC_GM_KEY, []) || []; } catch (e) { gmIds = []; } const merged = mergeEpicIds(gmIds, EPIC_MANUAL_IDS); if (merged.length > 0) { epicState.appids = merged; epicState.updatedAt = ''; epicState.source = gmIds.length > 0 ? 'local' : 'manual'; epicState.loaded = true; // v1.9.5: 写入永久缓存 _permCacheSet('epicFreeGames', { appids: merged, updatedAt: '', source: epicState.source }); if (!force) renderEpicSections(); } // 3) 远程抓取(GitHub 数据源三级回退;force 时显示 loading,失败回退到本地数据) _refreshEpicFromRemote(force, force); } // 远程抓取失败时的统一处理(有本地数据则保留并提示,无数据则显示错误) function _epicFailLoading(msg) { epicState.loading = false; if (epicState.appids.length === 0) { epicState.loadError = msg; } else { epicState.loadError = null; Host.showToast(Host.isZh ? '更新失败,已使用本地数据' : 'Update failed, using local data'); } renderEpicGamesList(); } // 内部:远程刷新 Epic 数据(v1.9.17 改造,v1.9.19 移除 keylol 兜底)—— // 仅走 GitHub 数据源三级回退链(fastly.jsdelivr → cdn.jsdelivr → raw.githubusercontent, // 参照年度大作 _refreshGotyFromRemote)。每个请求均带 timeout, // onerror/ontimeout 一律降级到下一个 URL,绝不挂起 // (参照 v2.7.1 沙箱挂起历史教训:任何分支都必须走到 settle)。 function _refreshEpicFromRemote(force, showLoading) { if (typeof GM_xmlhttpRequest !== 'function') { if (showLoading) _epicFailLoading('noXhr'); return; } // v1.9.27: force 时重置可能卡死的 loading 标志 if (epicState.loading) { if (!force) return; epicState.loading = false; } if (showLoading) { epicState.loading = true; epicState.loadError = null; renderEpicGamesList(); } // 兼容两种 JSON 格式:数组 appid 列表 / 对象 { _meta?, updatedAt?, appids: number[], games?: [...] } function _extractEpicAppids(data) { if (Array.isArray(data)) return data; if (data && typeof data === 'object') { if (Array.isArray(data.appids)) return data.appids; if (Array.isArray(data.games)) return data.games.map(g => (g && g.appid)).filter(Boolean); } return null; } // 成功响应公共逻辑:提取 appid → mergeEpicIds 增量合并(只增不减)→ 写缓存 → 渲染 function _processEpicJson(data) { const incoming = mergeEpicIds(_extractEpicAppids(data)); if (incoming.length === 0) return false; let gmIds = []; try { gmIds = GM_getValue(EPIC_GM_KEY, []) || []; } catch (e) { /* 忽略失败,不影响主流程 */ } // v1.9.18: 并入当前缓存历史(只增不减),远程数据变小也不丢本地历史 appid const merged = mergeEpicIds(incoming, epicState.appids, gmIds, EPIC_MANUAL_IDS); epicState.appids = merged; epicState.updatedAt = (data && typeof data === 'object' && data.updatedAt) ? String(data.updatedAt).slice(0, 10) : new Date().toISOString().slice(0, 10); epicState.source = 'github'; epicState.loaded = true; epicState.loading = false; epicState.loadError = null; _epicLastBgRefreshAt = Date.now(); // v1.9.5: 记录后台刷新时间戳 try { GM_setValue(EPIC_GM_KEY, incoming); } catch (e) { /* 忽略失败,不影响主流程 */ } // v1.9.5: 写入永久缓存(永不过期)+ TTL 缓存(兼容) _permCacheSet('epicFreeGames', { appids: merged, updatedAt: epicState.updatedAt, source: 'github' }); try { Host.cacheSet('epicFreeGames', { appids: merged, updatedAt: epicState.updatedAt, source: 'github' }, Host.cacheTTL.epic); } catch (e) { /* 忽略失败 */ } renderEpicSections(); return true; } // 依次尝试 EPIC_GITHUB_URLS,任一成功即停止;全部失败 → 视为刷新失败(保留本地缓存数据) function _tryNextGithubSource(idx) { if (idx >= EPIC_GITHUB_URLS.length) { // v1.9.19: keylol 兜底已移除(帖子需登录阅读权限)——force 刷新提示失败并用本地数据,后台刷新静默 if (showLoading) _epicFailLoading('network'); return; } GM_xmlhttpRequest({ method: 'GET', url: EPIC_GITHUB_URLS[idx], timeout: 15000, onload(r) { try { if (r.status !== 404 && _safeRespText(r)) { if (_processEpicJson(JSON.parse(_safeRespText(r)))) return; // 成功,停止 } } catch (e) { /* 解析异常,交给下一个源 */ } _tryNextGithubSource(idx + 1); // 失败,尝试下一个源 }, onerror() { _tryNextGithubSource(idx + 1); }, ontimeout() { _tryNextGithubSource(idx + 1); }, }); } _tryNextGithubSource(0); } // 手动 JSON 导入(兜底:远程抓取失败时) function importEpicJson() { const raw = prompt(Host.T.epicImportPrompt, ''); if (!raw || !raw.trim()) return; try { const data = JSON.parse(raw); let ids = []; if (Array.isArray(data)) ids = data; else if (Array.isArray(data.appids)) ids = data.appids; else if (Array.isArray(data.games)) ids = data.games.map(g => g.appid || g.steamAppId || g.id).filter(Boolean); const incoming = mergeEpicIds(ids); if (incoming.length === 0) { Host.showToast(Host.T.epicImportNoData); return; } let gmIds = []; try { gmIds = GM_getValue(EPIC_GM_KEY, []) || []; } catch (e) { /* 忽略失败,不影响主流程 */ } const merged = mergeEpicIds(incoming, gmIds, EPIC_MANUAL_IDS); try { GM_setValue(EPIC_GM_KEY, incoming); } catch (e) { /* 忽略失败,不影响主流程 */ } try { Host.cacheSet('epicFreeGames', { appids: merged, updatedAt: new Date().toISOString().slice(0, 10), source: 'import' }, Host.cacheTTL.epic); } catch (e) { /* 忽略失败,不影响主流程 */ } epicState.appids = merged; epicState.updatedAt = new Date().toISOString().slice(0, 10); epicState.source = 'import'; epicState.loaded = true; epicState.loading = false; epicState.loadError = null; epicState.page = 1; Host.showToast(Host.T.epicImportOk.replace('{n}', merged.length)); renderEpicSections(); } catch (e) { Host.showToast(Host.T.epicImportFail + e.message); } } // v1.9.18: 一键导出全量 JSON(含缓存历史)——epic_freebies.json 兼容格式, // 可经 js_script/epic-freebies-weekly-sync.js --import 回流 GitHub 数据源维护全量名单 function exportEpicJson() { const ids = mergeEpicIds(epicState.appids).sort((a, b) => a - b); if (ids.length === 0) { Host.showToast(Host.T.epicExportEmpty || (Host.isZh ? '没有可导出的 Epic 赠送数据' : 'No Epic data to export')); return; } const payload = { _meta: { source: 'sglv-epic-export', version: 1 }, updatedAt: new Date().toISOString(), appids: ids }; const text = JSON.stringify(payload, null, 2); const filename = 'epic_freebies_export_' + new Date().toISOString().slice(0, 10) + '.json'; try { const blob = new Blob([text], { type: 'application/json' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = filename; document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(url), 5000); Host.showToast((Host.T.epicExportOk || (Host.isZh ? '已导出 {n} 款 Epic 赠送游戏' : 'Exported {n} Epic free games')).replace('{n}', String(ids.length))); } catch (e) { // 兜底:Blob 下载不可用时弹窗展示 JSON 供手工复制保存 prompt(Host.T.epicExportFail || (Host.isZh ? '自动下载失败,请手工复制以下 JSON:' : 'Auto download failed. Copy JSON below:'), text); } } // 筛选 + 排序 function getFilteredEpic() { const q = epicState.search.toLowerCase().trim(); const ownedIds = Host.getActiveOwnedAppIds(); const isOwned = n => ownedIds.has(n) || ownedIds.has(String(n)); let list = epicState.appids.map(Number).filter(n => n > 0); if (q) { list = list.filter(n => { if (String(n).includes(q)) return true; const name = (_epicNameCache.get(n) || '').toLowerCase(); return name.includes(q); }); } if (epicState.ownFilter === 'owned') list = list.filter(isOwned); else if (epicState.ownFilter === 'notOwned') list = list.filter(n => !isOwned(n)); list.sort((a, b) => { switch (epicState.sort) { case 'appidAsc': return a - b; case 'nameAsc': return _nameCollator.compare(_epicNameCache.get(a) || '~', _epicNameCache.get(b) || '~') || (a - b); case 'appidDesc': default: return b - a; } }); return list; } // ----- 渲染 ----- function renderEpicTab(parent) { const wrap = document.createElement('div'); wrap.className = 'sglv-psplus-wrap'; // KPI 区域 const kpi = document.createElement('div'); kpi.id = 'sglv-epic-kpi'; wrap.appendChild(kpi); // 工具栏:搜索 + 排序 + 视图 + 导入 + 刷新 const toolbar = document.createElement('div'); toolbar.className = 'sglv-toolbar'; const sortOptions = [ { key: 'appidDesc', label: Host.T.epicSortAppidDesc }, { key: 'appidAsc', label: Host.T.epicSortAppidAsc }, { key: 'nameAsc', label: Host.T.epicSortNameAsc }, ]; toolbar.innerHTML = ` <input class="sglv-search" aria-label="搜索" id="sglv-epic-search" placeholder="${Host.T.epicSearch}" value="${Host.wlEscape(epicState.search)}"> <select class="sglv-sort-select" aria-label="排序方式" id="sglv-epic-sort"> ${sortOptions.map(o => `<option value="${o.key}"${epicState.sort === o.key ? ' selected' : ''}>${o.label}</option>`).join('')} </select> <div class="sglv-view-toggle"> <button class="sglv-btn sglv-btn-secondary sglv-btn-icon${epicState.viewMode === 'card' ? ' active' : ''}" id="sglv-epic-card" title="${Host.T.cardView}">${Host.ICONS.grid}</button> <button class="sglv-btn sglv-btn-secondary sglv-btn-icon${epicState.viewMode === 'cover' ? ' active' : ''}" id="sglv-epic-cover" title="${Host.T.coverView}">${Host.ICONS.cover}</button> <button class="sglv-btn sglv-btn-secondary sglv-btn-icon${epicState.viewMode === 'list' ? ' active' : ''}" id="sglv-epic-list" title="${Host.T.listView}">${Host.ICONS.list}</button> </div> <button class="sglv-btn sglv-btn-secondary sglv-btn-icon" id="sglv-epic-import" title="${Host.T.epicImportTip}">${Host.ICONS.tag}</button> <button class="sglv-btn sglv-btn-secondary sglv-btn-icon" id="sglv-epic-export" title="${Host.T.epicExportTip || (Host.isZh ? '一键导出 Epic 赠送数据 JSON(含本地缓存历史全量)' : 'Export Epic free games JSON (incl. local history)')}">${Host.ICONS.download || '<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>'}</button> <button class="sglv-btn sglv-btn-secondary sglv-btn-icon" id="sglv-epic-refresh" title="${Host.T.epicRefreshTip}">${Host.ICONS.refresh}</button> <div class="sglv-pagination" id="sglv-epic-pagination"></div> `; wrap.appendChild(toolbar); // 游戏列表容器 const content = document.createElement('div'); content.className = 'sglv-content'; content.id = 'sglv-epic-content'; wrap.appendChild(content); parent.appendChild(wrap); // 事件绑定 toolbar.querySelector('#sglv-epic-search').addEventListener('input', _debounce((e) => { epicState.search = e.target.value; epicState.page = 1; renderEpicGamesList(); }, 200)); toolbar.querySelector('#sglv-epic-sort').addEventListener('change', (e) => { epicState.sort = e.target.value; epicState.page = 1; renderEpicGamesList(); }); const setEpicViewMode = (mode) => { epicState.viewMode = mode; ['card', 'cover', 'list'].forEach(m => { toolbar.querySelector('#sglv-epic-' + m)?.classList.toggle('active', m === mode); }); renderEpicGamesList(); }; toolbar.querySelector('#sglv-epic-card').addEventListener('click', () => setEpicViewMode('card')); toolbar.querySelector('#sglv-epic-cover').addEventListener('click', () => setEpicViewMode('cover')); toolbar.querySelector('#sglv-epic-list').addEventListener('click', () => setEpicViewMode('list')); toolbar.querySelector('#sglv-epic-import').addEventListener('click', () => importEpicJson()); toolbar.querySelector('#sglv-epic-export').addEventListener('click', () => exportEpicJson()); toolbar.querySelector('#sglv-epic-refresh').addEventListener('click', () => loadEpicGames(true)); // v1.5.0: 筛选改为点击 KPI 卡片切换(再次点击同一卡片回到「全部」),与年度大作标签页一致 kpi.addEventListener('click', e => { const card = e.target.closest('[data-epic-filter]'); if (!card) return; const f = card.dataset.epicFilter; epicState.ownFilter = epicState.ownFilter === f ? 'all' : f; epicState.page = 1; renderEpicKpi(); // 刷新 KPI active 高亮 renderEpicGamesList(); }); if (!epicState.loaded && !epicState.loading) { loadEpicGames(); } else { renderEpicSections(); } } function renderEpicSections() { if (_collectionActiveTab !== 'epic' || !document.getElementById('sglv-epic-content')) return; renderEpicKpi(); renderEpicGamesList(); } function renderEpicKpi() { const el = document.getElementById('sglv-epic-kpi'); if (!el) return; if (!epicState.loaded) { el.innerHTML = ''; return; } const total = epicState.appids.length; const ownedIds = Host.getActiveOwnedAppIds(); const isOwned = n => ownedIds.has(n) || ownedIds.has(String(n)); const owned = epicState.appids.filter(n => isOwned(Number(n))).length; const notOwned = total - owned; const srcLabel = epicSourceLabel(epicState.source); const updatedStr = epicState.updatedAt ? (Host.isZh ? '更新于 ' : 'Updated ') + epicState.updatedAt + ' · ' + srcLabel : (Host.isZh ? '来源:' : 'Source: ') + srcLabel; el.innerHTML = ` <div class="sglv-trend-kpi-row"> <div class="sglv-trend-kpi-card blue clickable${epicState.ownFilter === 'all' ? ' active' : ''}" data-epic-filter="all" title="${Host.isZh ? '点击筛选:全部' : 'Click to filter: All'}"> <div class="sglv-trend-kpi-header"><span class="sglv-trend-kpi-icon">${Host.ICONS.epic}</span><span class="sglv-trend-kpi-label">${Host.T.epicKpiTotal}</span></div> <div class="sglv-trend-kpi-value">${total.toLocaleString()}</div> <div class="sglv-trend-kpi-sub">${updatedStr}</div> </div> <div class="sglv-trend-kpi-card mine clickable${epicState.ownFilter === 'owned' ? ' active' : ''}" data-epic-filter="owned" title="${Host.isZh ? '点击筛选:steam在库' : 'Click to filter: In Library'}"> <div class="sglv-trend-kpi-header"><span class="sglv-trend-kpi-icon">${Host.ICONS.heart}</span><span class="sglv-trend-kpi-label">${Host.T.epicKpiOwned}</span></div> <div class="sglv-trend-kpi-value">${owned.toLocaleString()}</div> <div class="sglv-trend-kpi-sub">${Host.T.epicKpiOwnedSub}</div> </div> <div class="sglv-trend-kpi-card clickable${epicState.ownFilter === 'notOwned' ? ' active' : ''}" style="border-left:3px solid #ff9800" data-epic-filter="notOwned" title="${Host.isZh ? '点击筛选:未拥有' : 'Click to filter: Not Owned'}"> <div class="sglv-trend-kpi-header"><span class="sglv-trend-kpi-icon" style="color:#ff9800">${Host.ICONS.tag}</span><span class="sglv-trend-kpi-label">${Host.T.epicKpiNotOwned}</span></div> <div class="sglv-trend-kpi-value">${notOwned.toLocaleString()}</div> <div class="sglv-trend-kpi-sub">${Host.isZh ? '可在 Epic 领取' : 'Claimable on Epic'}</div> </div> </div> `; } function renderEpicGamesList() { const content = document.getElementById('sglv-epic-content'); if (!content) return; const clearPagination = () => { const p = document.getElementById('sglv-epic-pagination'); if (p) p.innerHTML = ''; }; if (epicState.loading) { content.innerHTML = '<div class="sglv-progress" style="margin:16px 0"><div class="sglv-progress-fill" style="width:45%"></div></div><div class="sglv-empty">' + Host.T.epicLoading + '</div>'; clearPagination(); return; } if (epicState.loadError) { content.innerHTML = '<div class="sglv-empty">' + Host.T.epicLoadError + '</div>'; clearPagination(); return; } if (!epicState.loaded || epicState.appids.length === 0) { content.innerHTML = '<div class="sglv-empty">' + Host.T.epicNoData + '</div>'; clearPagination(); return; } const list = getFilteredEpic(); if (list.length === 0) { content.innerHTML = '<div class="sglv-empty">' + (Host.isZh ? '无匹配结果' : 'No matching results') + '</div>'; clearPagination(); return; } const { pageItems, totalPages, page: _clampedPage } = Host.paginate(list, epicState.page, epicState.pageSize); epicState.page = _clampedPage; const ownedIds = Host.getActiveOwnedAppIds(); const isOwned = n => ownedIds.has(n) || ownedIds.has(String(n)); const freeBadge = epicFreeBadgeHtml(); // 卡片视图 if (epicState.viewMode === 'card') { content.innerHTML = '<div class="sglv-card-grid sglv-card-grid-7">' + pageItems.map(appid => { const name = epicDisplayName(appid); const clickUrl = 'https://store.steampowered.com/app/' + appid; const nameSpan = '<span data-sglv-epic-appid="' + appid + '">' + Host.wlEscape(name) + '</span><span class="sglv-card-id-inline">' + appid + '</span>'; return '<div class="sglv-game-card sglv-poster-card" data-appid="' + appid + '" onclick="window.open(\'' + clickUrl + '\',\'_blank\')">' + '<div class="sglv-card-img-wrap">' + freeBadge + epicPosterImg(appid, name) + '</div>' + '<div class="sglv-card-body">' + '<div class="sglv-card-name" title="' + Host.wlEscape(name) + '">' + nameSpan + '</div>' + '<div class="sglv-info-row sglv-wl-price-row">' + epicOwnedBadgeHtml(isOwned(appid)) + '</div>' + '</div>' + '</div>'; }).join('') + '</div>'; } else if (epicState.viewMode === 'cover') { // 封面视图(横板大图) // v2.9.22: 标签统一规则——封面上不放任何徽章(freeBadge 在右下角,owned badge 在标题下方) content.innerHTML = '<div class="sglv-wl-cover-grid">' + pageItems.map(appid => { const name = epicDisplayName(appid); const clickUrl = 'https://store.steampowered.com/app/' + appid; const nameSpan = '<span data-sglv-epic-appid="' + appid + '">' + Host.wlEscape(name) + '</span><span class="sglv-card-id-inline">' + appid + '</span>'; return '<div class="sglv-wl-cover-card" data-appid="' + appid + '" onclick="window.open(\'' + clickUrl + '\',\'_blank\')">' + '<div class="sglv-wl-cover-img-wrap">' + freeBadge + unifiedCover(appid, name, 'capsule') + '</div>' + '<div class="sglv-wl-cover-body">' + '<div class="sglv-card-name" title="' + Host.wlEscape(name) + '">' + nameSpan + '</div>' + '<div class="sglv-info-row sglv-wl-price-row sglv-epic-owned-row">' + epicOwnedBadgeHtml(isOwned(appid)) + '</div>' + '</div>' + '</div>'; }).join('') + '</div>'; } else { // 列表视图 content.innerHTML = '<div class="sglv-list-view">' + pageItems.map(appid => { const name = epicDisplayName(appid); const clickUrl = 'https://store.steampowered.com/app/' + appid; const iconHtml = '<img class="sglv-list-icon" src="' + Host.getGameIconUrl(appid, '') + '" alt="' + Host.wlEscape(name) + '" loading="lazy" decoding="async" onerror="this.style.display=\'none\'">'; const nameSpan = '<span data-sglv-epic-appid="' + appid + '">' + Host.wlEscape(name) + '</span><span class="sglv-card-id-inline">' + appid + '</span>'; return '<div class="sglv-list-item" data-appid="' + appid + '" onclick="window.open(\'' + clickUrl + '\',\'_blank\')">' + iconHtml + '<div class="sglv-list-info">' + '<div class="sglv-list-name">' + nameSpan + '</div>' + '<div class="sglv-list-meta">' + freeBadge + epicOwnedBadgeHtml(isOwned(appid)) + '</div>' + '</div>' + '</div>'; }).join('') + '</div>'; } // 分页 // v1.9.47-fix: 补 onJump——Epic 翻页 5 个按钮全部走 onJump(参见主脚本 renderPagination) const pagination = document.getElementById('sglv-epic-pagination'); if (pagination) { Host.renderPagination(pagination, 'sglv-epic', epicState.page, totalPages, list.length, () => { epicState.page--; renderEpicGamesList(); }, () => { epicState.page++; renderEpicGamesList(); }, (p) => { epicState.page = p; renderEpicGamesList(); }); } // 异步加载中文名 + 写入本地缓存供搜索/排序 content.querySelectorAll('[data-sglv-epic-appid]').forEach(el => { const appid = el.getAttribute('data-sglv-epic-appid'); const original = el.textContent; epicLoadName(appid).then(name => { if (name && name !== original) { el.textContent = name; el.title = name + ' (' + original + ')'; // v2.7.9: 清除占位符内联样式,允许 CSS class 生效(项目约定) el.style.color = ''; el.style.fontStyle = ''; el.style.fontWeight = ''; } }); }); // v2.8.0: 统一封面链绑定(addEventListener,无跨上下文 inline onerror) bindRestrictedCoverLoaders(content); } // ==================== 锁区游戏标签页 (v2.9.12) ==================== // 数据源: GitHub 静态源优先(fastly.jsdelivr.net/gh/SmallRob/steam-namespace steam_blocked_apps.json) // → steam-tracker.com API (Banned + Purchase disabled) → HTML (Regional variant) + 手动导入 // 宿主桥接: Host.loadBlockedApps(force), Host.getBlockedApps(), Host.isBlockedLoaded(), // Host.parseManualBlockedJson(text), Host.getBlockedSource() const blockedState = { apps: [], loaded: false, loading: false, search: '', ownFilter: 'all', catFilter: 'all', sort: 'appidDesc', page: 1, pageSize: 48, viewMode: 'card', source: '', loadError: null, fetchedAt: '', // v2.9.90: 远程数据集更新时间 pendingForce: false, // v2.9.90: loading中时排队的force刷新请求 // v2.9.91: 好评500分类单独加载(独立于主锁区数据,确保 categoryId=500 条目始终可用) topRatedApps: [], topRatedLoaded: false, topRatedLoading: false, topRatedFetchedAt: '', refreshStage: '', // v2.9.91: 刷新进度文本 }; function blockedCatBadgeHtml(catId) { if (catId === 20) return '<span class="sglv-badge" style="background:rgba(239,68,68,0.15);color:#f87171;border:1px solid rgba(239,68,68,0.25)">' + Host.T.blockedBadgeBanned + '</span>'; if (catId === 3) return '<span class="sglv-badge" style="background:rgba(245,158,11,0.15);color:#fbbf24;border:1px solid rgba(245,158,11,0.25)">' + Host.T.blockedBadgePurchase + '</span>'; if (catId === 10) return '<span class="sglv-badge" style="background:rgba(59,130,246,0.15);color:#60a5fa;border:1px solid rgba(59,130,246,0.25)">' + Host.T.blockedBadgeRegional + '</span>'; if (catId === 0) return '<span class="sglv-badge" style="background:var(--sglv-accent-bg, rgba(168,85,247,0.15));color:var(--sglv-accent-light, #c084fc);border:1px solid var(--sglv-accent-border, rgba(168,85,247,0.25))">' + Host.T.blockedBadgeManual + '</span>'; // v1.9.15: 好评500 分类(人工整理锁区游戏,categoryId=500) if (catId === 500) return '<span class="sglv-badge" style="background:rgba(16,185,129,0.15);color:#34d399;border:1px solid rgba(16,185,129,0.25)">' + (Host.isZh ? '好评500' : 'Positive 500+') + '</span>'; return ''; } function blockedOwnedBadgeHtml(owned) { if (owned) return '<span class="sglv-badge" style="background:rgba(75,181,79,0.15);color:#4bb54f;border:1px solid rgba(75,181,79,0.25)">' + Host.T.blockedBadgeOwned + '</span>'; return ''; } // v2.9.91: 好评500分类数据远程URL(与主脚本 BLOCKED_STATIC_URL 同源,独立加载确保 categoryId=500 条目可用) const BLOCKED_TOP_RATED_URL = 'https://fastly.jsdelivr.net/gh/SmallRob/steam-namespace@main/data/steam_blocked_apps.json'; const BLOCKED_TOP_RATED_FALLBACK_URL = 'https://raw.githubusercontent.com/SmallRob/steam-namespace/refs/heads/main/data/steam_blocked_apps.json'; /** * v2.9.91: 单独加载好评500分类数据 * 直接从远程 JSON 筛选 categoryId=500 条目,独立于主锁区数据缓存 * @param {boolean} force - 强制刷新(忽略永久缓存) * @returns {Promise<Array>} 好评500条目数组 */ function _fetchTopRatedFromRemote() { return new Promise((resolve, reject) => { if (typeof GM_xmlhttpRequest !== 'function') { reject(new Error('GM_xmlhttpRequest unavailable')); return; } const tryFetch = (url, isFallback) => { GM_xmlhttpRequest({ method: 'GET', url, headers: { 'Accept': 'application/json' }, timeout: 15000, onload(r) { if (r.status < 200 || r.status >= 300) { if (!isFallback) { tryFetch(BLOCKED_TOP_RATED_FALLBACK_URL, true); return; } reject(new Error(`HTTP ${r.status}`)); return; } try { const data = JSON.parse(_safeRespText(r)); const apps = Array.isArray(data) ? data : (Array.isArray(data.data) ? data.data : []); const topRated = apps .filter(a => a.categoryId === 500 || a.category_id === 500) .map(a => ({ appid: Number(a.appid) || 0, name: (a.name || '').trim(), category: a.category || '好评500', categoryId: 500, type: a.type || 'game', source: 'static', changedAt: a.changedAt || a.changed_at || '', positiveRating: a.positiveRating || 0, reviews: a.reviews || 0, cheapestRegion: a.cheapestRegion || '', })); const fetchedAt = (!Array.isArray(data) && data.fetchedAt) ? data.fetchedAt : ''; resolve({ apps: topRated, fetchedAt }); } catch (e) { if (!isFallback) { tryFetch(BLOCKED_TOP_RATED_FALLBACK_URL, true); return; } reject(new Error('JSON parse fail')); } }, onerror: () => { if (!isFallback) { tryFetch(BLOCKED_TOP_RATED_FALLBACK_URL, true); return; } reject(new Error('Network error')); }, ontimeout: () => { if (!isFallback) { tryFetch(BLOCKED_TOP_RATED_FALLBACK_URL, true); return; } reject(new Error('Timeout')); }, }); }; tryFetch(BLOCKED_TOP_RATED_URL, false); }); } /** * v2.9.91: 加载好评500分类数据(含永久缓存 + 后台静默刷新) * @param {boolean} force - 强制刷新 */ function loadTopRatedApps(force) { if (blockedState.topRatedLoading) return Promise.resolve(); // 非强制时优先从永久缓存秒开 if (!force) { const permCached = _permCacheGet('blockedTopRated'); if (permCached && Array.isArray(permCached.apps) && permCached.apps.length > 0) { blockedState.topRatedApps = permCached.apps; blockedState.topRatedFetchedAt = permCached.fetchedAt || ''; blockedState.topRatedLoaded = true; // 后台静默刷新 _fetchTopRatedFromRemote().then(result => { if (result.fetchedAt && result.fetchedAt !== blockedState.topRatedFetchedAt) { blockedState.topRatedApps = result.apps; blockedState.topRatedFetchedAt = result.fetchedAt; _permCacheSet('blockedTopRated', { apps: result.apps, fetchedAt: result.fetchedAt }); if (_collectionActiveTab === 'blocked') renderBlockedSections(); } }).catch(() => {}); return Promise.resolve(); } } blockedState.topRatedLoading = true; return _fetchTopRatedFromRemote().then(result => { blockedState.topRatedApps = result.apps || []; blockedState.topRatedFetchedAt = result.fetchedAt || ''; blockedState.topRatedLoaded = true; blockedState.topRatedLoading = false; _permCacheSet('blockedTopRated', { apps: blockedState.topRatedApps, fetchedAt: blockedState.topRatedFetchedAt }); }).catch(() => { blockedState.topRatedLoading = false; }); } /** * v2.9.91: 将好评500条目合并到主锁区列表(按 appid 去重,已有条目不覆盖) * @returns {Array} 合并后的完整锁区列表 */ function getMergedBlockedApps() { if (!blockedState.topRatedApps || blockedState.topRatedApps.length === 0) { return blockedState.apps; } const existing = new Set(blockedState.apps.map(a => a.appid)); const additions = blockedState.topRatedApps.filter(a => !existing.has(a.appid)); return blockedState.apps.concat(additions); } function loadBlockedGames(force) { // v2.9.90: loading中时,force请求排队(pendingForce),避免静默丢弃用户刷新操作 // v1.9.27: force 时直接重置可能卡死的 loading 标志(浏览器扩展阻断回调时 loading 可能永久卡 true) if (blockedState.loading) { if (force) { blockedState.loading = false; blockedState.pendingForce = false; } else { return; } } blockedState.loading = true; blockedState.loadError = null; blockedState.refreshStage = Host.isZh ? '正在加载锁区数据…' : 'Loading blocked data…'; // v2.9.90: 刷新按钮 spinner 反馈 const refreshBtn = document.getElementById('sglv-blocked-refresh'); if (refreshBtn) refreshBtn.classList.add('sglv-spin'); renderBlockedSections(); renderBlockedToolbarStatus(); if (typeof Host.loadBlockedApps !== 'function') { blockedState.loading = false; blockedState.loadError = 'Host loadBlockedApps unavailable'; blockedState.refreshStage = ''; if (refreshBtn) refreshBtn.classList.remove('sglv-spin'); renderBlockedSections(); renderBlockedToolbarStatus(); return; } // v2.9.91: 同时加载好评500分类数据(force 时同步强制刷新) loadTopRatedApps(force); Host.loadBlockedApps(force, (stage, text) => { // v2.9.91: 进度回调更新工具栏状态 blockedState.refreshStage = text || ''; renderBlockedToolbarStatus(); }).then(result => { blockedState.apps = result.apps || []; blockedState.source = result.source || 'api'; // v2.9.90: 存储 fetchedAt 用于显示数据更新时间 blockedState.fetchedAt = result.fetchedAt || ''; blockedState.loaded = true; blockedState.loading = false; blockedState.page = 1; blockedState.refreshStage = ''; // v1.9.5: 写入永久缓存(永不过期)+ v2.9.90: 含 fetchedAt _permCacheSet('blockedApps', { apps: blockedState.apps, source: blockedState.source, fetchedAt: blockedState.fetchedAt }); if (refreshBtn) refreshBtn.classList.remove('sglv-spin'); renderBlockedSections(); renderBlockedToolbarStatus(); // v2.9.90: 若有排队的 force 请求,立即执行 if (blockedState.pendingForce) { blockedState.pendingForce = false; loadBlockedGames(true); } }).catch(e => { blockedState.loading = false; blockedState.loadError = e.message || 'Load failed'; blockedState.refreshStage = ''; if (refreshBtn) refreshBtn.classList.remove('sglv-spin'); renderBlockedSections(); renderBlockedToolbarStatus(); // v2.9.90: 若有排队的 force 请求,立即执行 if (blockedState.pendingForce) { blockedState.pendingForce = false; loadBlockedGames(true); } }); } function importBlockedJson() { const text = prompt(Host.T.blockedImportPrompt); if (!text || !text.trim()) return; try { const apps = Host.parseManualBlockedJson(text); if (!apps.length) { Host.showToast(Host.T.blockedImportNoData); return; } // 合并到现有数据(手动导入的不覆盖已有条目) const existing = new Map(blockedState.apps.map(a => [a.appid, a])); apps.forEach(a => { if (!existing.has(a.appid)) existing.set(a.appid, a); }); blockedState.apps = Array.from(existing.values()); blockedState.loaded = true; blockedState.source = 'import'; blockedState.page = 1; // v1.9.5: 写入永久缓存(永不过期)+ TTL 缓存(兼容主脚本加载路径) // v2.9.90: 含 fetchedAt(手动导入无远程时间戳,置空) _permCacheSet('blockedApps', { apps: blockedState.apps, source: 'import', fetchedAt: '' }); try { Host.cacheSet('blockedApps', { apps: blockedState.apps, source: 'import', fetchedAt: '' }, Host.cacheTTL.blockedApps); } catch (e) { /* 忽略失败 */ } Host.showToast(Host.T.blockedImportOk.replace('{n}', apps.length)); renderBlockedSections(); } catch (e) { Host.showToast(Host.T.blockedImportFail + e.message); } } function getFilteredBlocked() { const q = blockedState.search.toLowerCase().trim(); const ownedIds = Host.getActiveOwnedAppIds(); const isOwned = n => ownedIds.has(n) || ownedIds.has(String(n)); // v2.9.91: 使用合并后的锁区列表(含好评500单独加载的条目) let list = getMergedBlockedApps().filter(a => a.appid > 0); if (q) { list = list.filter(a => { if (String(a.appid).includes(q)) return true; return (a.name || '').toLowerCase().includes(q); }); } if (blockedState.ownFilter === 'owned') list = list.filter(a => isOwned(a.appid)); else if (blockedState.ownFilter === 'notOwned') list = list.filter(a => !isOwned(a.appid)); if (blockedState.catFilter !== 'all') { const catMap = { banned: 20, purchase: 3, regional: 10, manual: 0, topRated: 500 }; const targetId = catMap[blockedState.catFilter]; list = list.filter(a => a.categoryId === targetId); } // v1.9.5: 使用缓存的 _nameCollator,避免每次渲染重新构造 list.sort((a, b) => { let r = 0; switch (blockedState.sort) { case 'appidAsc': r = a.appid - b.appid; break; case 'nameAsc': r = _nameCollator.compare(a.name || '~', b.name || '~') || (a.appid - b.appid); break; case 'dateDesc': r = (b.changedAt || '').localeCompare(a.changedAt || ''); break; case 'dateAsc': r = (a.changedAt || '').localeCompare(b.changedAt || ''); break; case 'appidDesc': default: r = b.appid - a.appid; } return r || (a.appid - b.appid); }); return list; } function renderBlockedTab(parent) { const wrap = document.createElement('div'); wrap.className = 'sglv-psplus-wrap'; const kpi = document.createElement('div'); kpi.id = 'sglv-blocked-kpi'; wrap.appendChild(kpi); const toolbar = document.createElement('div'); toolbar.className = 'sglv-toolbar'; const sortOptions = [ { key: 'appidDesc', label: Host.T.blockedSortAppidDesc }, { key: 'appidAsc', label: Host.T.blockedSortAppidAsc }, { key: 'nameAsc', label: Host.T.blockedSortNameAsc }, { key: 'dateDesc', label: Host.T.blockedSortDateDesc }, { key: 'dateAsc', label: Host.T.blockedSortDateAsc }, ]; toolbar.innerHTML = ` <input class="sglv-search" aria-label="搜索" id="sglv-blocked-search" placeholder="${Host.T.blockedSearch}" value="${Host.wlEscape(blockedState.search)}"> <select class="sglv-sort-select" aria-label="排序方式" id="sglv-blocked-sort"> ${sortOptions.map(o => `<option value="${o.key}"${blockedState.sort === o.key ? ' selected' : ''}>${o.label}</option>`).join('')} </select> <div class="sglv-view-toggle"> <button class="sglv-btn sglv-btn-secondary sglv-btn-icon${blockedState.viewMode === 'card' || blockedState.viewMode === 'cover' ? ' active' : ''}" id="sglv-blocked-card" title="${Host.T.cardView}">${Host.ICONS.grid}</button> <button class="sglv-btn sglv-btn-secondary sglv-btn-icon${blockedState.viewMode === 'list' ? ' active' : ''}" id="sglv-blocked-list" title="${Host.T.listView}">${Host.ICONS.list}</button> </div> <button class="sglv-btn sglv-btn-secondary sglv-btn-icon" id="sglv-blocked-import" title="${Host.T.blockedImportTip}">${Host.ICONS.tag}</button> <button class="sglv-btn sglv-btn-secondary sglv-btn-icon" id="sglv-blocked-refresh" title="${Host.T.blockedRefreshTip}">${Host.ICONS.refresh}</button> <span class="sglv-blocked-status" id="sglv-blocked-status"></span> <div class="sglv-toolbar-spacer"></div> <div class="sglv-pagination sglv-pagination-inline" id="sglv-blocked-pagination"></div> `; wrap.appendChild(toolbar); // v2.5.0: 移除独立筛选栏——own/cat 筛选统一由 KPI 卡片行承担(3 scope + 4 类型), // 原筛选栏与 KPI 行表达同一组维度,双排并存造成界面逻辑混乱。 // v2.8.0: 分页器也并入工具栏右侧,工具栏独占一行即可完成「搜索+排序+视图+分页」全部操作。 const content = document.createElement('div'); content.className = 'sglv-content'; content.id = 'sglv-blocked-content'; wrap.appendChild(content); parent.appendChild(wrap); toolbar.querySelector('#sglv-blocked-search').addEventListener('input', _debounce((e) => { blockedState.search = e.target.value; blockedState.page = 1; renderBlockedGamesList(); }, 200)); toolbar.querySelector('#sglv-blocked-sort').addEventListener('change', (e) => { blockedState.sort = e.target.value; blockedState.page = 1; renderBlockedGamesList(); }); const setBlockedViewMode = (mode) => { blockedState.viewMode = mode; ['card', 'list'].forEach(m => { toolbar.querySelector('#sglv-blocked-' + m)?.classList.toggle('active', m === mode || (m === 'card' && blockedState.viewMode === 'cover')); }); renderBlockedGamesList(); }; toolbar.querySelector('#sglv-blocked-card').addEventListener('click', () => setBlockedViewMode('card')); toolbar.querySelector('#sglv-blocked-list').addEventListener('click', () => setBlockedViewMode('list')); toolbar.querySelector('#sglv-blocked-import').addEventListener('click', () => importBlockedJson()); toolbar.querySelector('#sglv-blocked-refresh').addEventListener('click', () => loadBlockedGames(true)); // v2.6.0: HERO 承担全部筛选职责(事件委托) // - data-blocked-scope="owned|missing" → ownFilter(再点同一卡回到「全部」) // - data-blocked-type="banned|purchase_disabled|regional|top_rated" → catFilter(同样 toggle 回「all」) // - 点击 HERO 左侧主数字区 → 一键清空两个维度(替代原先两个「全部」按钮的"重置"语义) kpi.addEventListener('click', e => { if (!e.target.closest('[data-blocked-scope],[data-blocked-type]') && e.target.closest('.sglv-hero-left')) { if (blockedState.ownFilter !== 'all' || blockedState.catFilter !== 'all') { blockedState.ownFilter = 'all'; blockedState.catFilter = 'all'; blockedState.page = 1; renderBlockedKpi(); renderBlockedGamesList(); } return; } const scopeCard = e.target.closest('[data-blocked-scope]'); if (scopeCard) { const f = scopeCard.dataset.blockedScope; blockedState.ownFilter = (blockedState.ownFilter === f && f !== 'all') ? 'all' : f; blockedState.page = 1; renderBlockedKpi(); renderBlockedGamesList(); return; } const typeCard = e.target.closest('[data-blocked-type]'); if (typeCard) { const t = typeCard.dataset.blockedType; // typeKey(banned/purchase_disabled/regional/top_rated) → catFilter(banned/purchase/regional/topRated) const toCat = { banned: 'banned', purchase_disabled: 'purchase', regional: 'regional', top_rated: 'topRated' }; const cat = toCat[t]; if (!cat) return; blockedState.catFilter = (blockedState.catFilter === cat) ? 'all' : cat; blockedState.page = 1; renderBlockedKpi(); renderBlockedGamesList(); } }); if (!blockedState.loaded && !blockedState.loading) { // 优先从宿主缓存读取 if (Host.isBlockedLoaded && Host.isBlockedLoaded() && Host.getBlockedApps) { blockedState.apps = Host.getBlockedApps(); blockedState.source = Host.getBlockedSource ? Host.getBlockedSource() : 'api'; // v2.9.90: 读取宿主的 fetchedAt if (Host.getBlockedFetchedAt) blockedState.fetchedAt = Host.getBlockedFetchedAt(); blockedState.loaded = true; renderBlockedSections(); } else { // v1.9.5: 宿主缓存无数据 → 尝试永久缓存秒开,后台静默刷新 const permCached = _permCacheGet('blockedApps'); if (permCached && Array.isArray(permCached.apps) && permCached.apps.length > 0) { blockedState.apps = permCached.apps; blockedState.source = permCached.source || 'api'; // v2.9.90: 读取 permCache 中的 fetchedAt blockedState.fetchedAt = permCached.fetchedAt || ''; blockedState.loaded = true; renderBlockedSections(); loadBlockedGames(false); // 后台静默刷新 } else { loadBlockedGames(false); } } } else { renderBlockedSections(); } // v2.9.91: 单独加载好评500分类数据(独立于主锁区数据缓存,确保 categoryId=500 条目始终可用) if (!blockedState.topRatedLoaded && !blockedState.topRatedLoading) { loadTopRatedApps(false).then(() => { if (_collectionActiveTab === 'blocked') renderBlockedSections(); }); } } function renderBlockedSections() { if (_collectionActiveTab !== 'blocked' || !document.getElementById('sglv-blocked-content')) return; renderBlockedKpi(); renderBlockedToolbarStatus(); renderBlockedGamesList(); } // v2.9.91: 渲染工具栏刷新按钮右侧的状态文本(更新时间 / 加载进度) function renderBlockedToolbarStatus() { const el = document.getElementById('sglv-blocked-status'); if (!el) return; if (blockedState.refreshStage) { // 加载中:显示进度文本 + spinner el.innerHTML = `<svg style="width:11px;height:11px;animation:sgc-spin 0.8s linear infinite;vertical-align:middle;margin-right:4px" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>${Host.wlEscape(blockedState.refreshStage)}`; el.className = 'sglv-blocked-status loading'; } else if (blockedState.fetchedAt) { // 空闲:显示数据更新时间 const date = blockedState.fetchedAt.slice(0, 10); el.textContent = (Host.isZh ? '更新: ' : 'Updated: ') + date; el.className = 'sglv-blocked-status'; } else { el.textContent = ''; el.className = 'sglv-blocked-status'; } } // v2.5.0: 锁区筛选栏已移除——筛选职责统一收敛到 KPI 卡片行(3 scope 卡 + 4 类型卡), // 避免"顶部 KPI 行 + 下方筛选栏"两处重复表达同一组筛选维度。 // 保留 syncBlockedFilterBtns 仅为兼容旧调用点(空实现,不再有筛选栏可同步)。 function syncBlockedFilterBtns() { /* v2.5.0: 筛选栏已移除,KPI 卡片自带 active 态 */ } function renderBlockedKpi() { const el = document.getElementById('sglv-blocked-kpi'); if (!el) return; if (!blockedState.loaded) { el.innerHTML = ''; return; } // v2.9.91: 使用合并后的锁区列表(含好评500单独加载的条目) const mergedApps = getMergedBlockedApps(); const total = mergedApps.length; const ownedIds = Host.getActiveOwnedAppIds(); const isOwned = n => ownedIds.has(n) || ownedIds.has(String(n)); const owned = mergedApps.filter(a => isOwned(a.appid)).length; // v2.2.0: 用通用受限游戏板 KPI 行组件(scope 卡 + 类型卡合并展示) const typeColors = { banned: '#ef4444', purchase_disabled: '#fb923c', regional: '#a78bfa', top_rated: '#fbbf24' }; const typeLabels = {}; BLOCKED_TYPE_KEYS.forEach(k => { const info = Object.values(BLOCKED_TYPE_INFO).find(v => v.key === k); typeLabels[k] = Host.isZh ? info.label.zh : info.label.en; }); // v2.5.0: 筛选统一收敛到 KPI 卡片行——scope 由 ownFilter 映射,type 由 catFilter 反向映射。 // catFilter 的历史值(banned/purchase/regional/manual/topRated)与 typeKey(banned/purchase_disabled/regional/top_rated)命名不一致, // 这里做双向映射,保证 KPI 卡 active 态与实际筛选一致。manual 无对应类型卡 → 视为未选中任何类型。 const scope = blockedState.ownFilter === 'notOwned' ? 'missing' : blockedState.ownFilter; const catToType = { banned: 'banned', purchase: 'purchase_disabled', regional: 'regional', topRated: 'top_rated' }; const typeFilter = catToType[blockedState.catFilter] || 'all'; const scopeBase = (scope === 'owned') ? mergedApps.filter(a => isOwned(a.appid)) : (scope === 'missing') ? mergedApps.filter(a => !isOwned(a.appid)) : mergedApps; // v2.6.0: KPI 小卡行 → HERO 仪表盘(大数字 + 类型占比条,铺满浮窗宽度) // 顺带解决旧版"两个全部":主数字即"全部",scope 卡只有「在库/未拥有」,类型行点击即筛选。 el.innerHTML = makeRestrictedHero({ total: total, ownedCount: owned, scopeBase: scopeBase.map(function (a) { return { type: _blockedTypeKey(a) }; }), scope: scope, typeFilter: typeFilter, title: Host.T.blockedKpiTotal, typeKeys: BLOCKED_TYPE_KEYS, typeColors: typeColors, typeLabels: typeLabels, tabId: 'blocked' }); } // v2.2.0: 锁区类型标准化——categoryId → typeKey + 颜色映射 // 真实 categoryId:20=下架 / 3=停售 / 10=锁区 / 500=好评500 const BLOCKED_TYPE_INFO = { 20: { key: 'banned', color: '#ef4444', label: { zh: '下架', en: 'Banned' } }, 3: { key: 'purchase_disabled', color: '#fb923c', label: { zh: '停售', en: 'Purchase disabled' } }, 10: { key: 'regional', color: '#a78bfa', label: { zh: '锁区', en: 'Regional' } }, 500: { key: 'top_rated', color: '#fbbf24', label: { zh: '好评500', en: 'Positive 500+' } } }; const BLOCKED_TYPE_KEYS = ['banned', 'purchase_disabled', 'regional', 'top_rated']; function _blockedCategoryInfo(app) { const cid = Number(app.categoryId || 0); return BLOCKED_TYPE_INFO[cid] || { key: 'unknown', color: '#94a3b8', label: { zh: '其他', en: 'Other' } }; } function _blockedTypeLabel(app) { const info = _blockedCategoryInfo(app); return Host.isZh ? info.label.zh : info.label.en; } function _blockedTypeKey(app) { return _blockedCategoryInfo(app).key; } function _blockedTypeColor(app) { return _blockedCategoryInfo(app).color; } function renderBlockedGamesList() { const content = document.getElementById('sglv-blocked-content'); if (!content) return; const clearPagination = () => { const p = document.getElementById('sglv-blocked-pagination'); if (p) p.innerHTML = ''; }; if (blockedState.loading) { // v2.9.91: 显示刷新进度文本(若有) const stageText = blockedState.refreshStage || Host.T.blockedLoading; content.innerHTML = '<div class="sglv-progress" style="margin:16px 0"><div class="sglv-progress-fill" style="width:45%"></div></div><div class="sglv-empty">' + Host.wlEscape(stageText) + '</div>'; clearPagination(); return; } if (blockedState.loadError) { content.innerHTML = '<div class="sglv-empty">' + Host.T.blockedLoadError + '</div>'; clearPagination(); return; } if (!blockedState.loaded || blockedState.apps.length === 0) { content.innerHTML = '<div class="sglv-empty">' + Host.T.blockedNoData + '</div>'; clearPagination(); return; } const list = getFilteredBlocked(); if (list.length === 0) { content.innerHTML = '<div class="sglv-empty">' + (Host.isZh ? '无匹配结果' : 'No matching results') + '</div>'; clearPagination(); return; } const { pageItems, totalPages, page: _clampedPage } = Host.paginate(list, blockedState.page, blockedState.pageSize); blockedState.page = _clampedPage; const ownedIds = Host.getActiveOwnedAppIds(); const isOwned = n => ownedIds.has(n) || ownedIds.has(String(n)); // v2.2.0: 移除 cover viewMode,统一为 card / list 两视图(与绝版对齐) if (blockedState.viewMode === 'list') { content.innerHTML = '<div class="sglv-list-view">' + pageItems.map(function (a) { const name = a.name || ('App ' + a.appid); const owned = isOwned(a.appid); const metaItems = []; if (a.changedAt) metaItems.push('<span style="color:#8f98a0">' + Host.T.blockedChangedAt + ': ' + Host.wlEscape(a.changedAt) + '</span>'); return makeRestrictedListItem({ appid: a.appid, name: name, isOwned: owned, typeLabel: _blockedTypeLabel(a), typeKey: _blockedTypeKey(a), typeColor: _blockedTypeColor(a), metaItems: metaItems, clickUrl: 'https://store.steampowered.com/app/' + a.appid }); }).join('') + '</div>'; } else { content.innerHTML = '<div class="sglv-card-grid">' + pageItems.map(function (a) { const name = a.name || ('App ' + a.appid); const owned = isOwned(a.appid); const metaItems = []; if (a.changedAt) metaItems.push('<span class="sglv-meta-item">' + Host.T.blockedChangedAt + ': ' + Host.wlEscape(a.changedAt) + '</span>'); return makeRestrictedCard({ appid: a.appid, name: name, isOwned: owned, isBlocked: true, typeLabel: _blockedTypeLabel(a), typeKey: _blockedTypeKey(a), typeColor: _blockedTypeColor(a), metaItems: metaItems, clickUrl: 'https://store.steampowered.com/app/' + a.appid }); }).join('') + '</div>'; } // v2.5.0: 补齐缓存命中图的 loaded 态 + 异步加载中文名 syncRestrictedCoverStates(content); content.querySelectorAll('[data-sglv-appid]').forEach(el => { Host.loadGameZhName(el, el.getAttribute('data-sglv-appid'), el.textContent); }); const pagination = document.getElementById('sglv-blocked-pagination'); if (pagination) { // v1.9.47-fix: 补 onJump——锁区翻页 5 个按钮全部走 onJump(参见主脚本 renderPagination) Host.renderPagination(pagination, 'sglv-blocked', blockedState.page, totalPages, list.length, () => { blockedState.page--; renderBlockedGamesList(); }, () => { blockedState.page++; renderBlockedGamesList(); }, (p) => { blockedState.page = p; renderBlockedGamesList(); }); } } // ==================== 年度大作标签页 (v2.9.7, v1.7.x 按年数据源) ==================== // v1.8.1: 数据源改用 jsdelivr CDN 优先(国内稳定),raw.githubusercontent 兜底。 // raw.githubusercontent.com 在国内经常连接超时/被墙,导致年度大作加载失败。 // jsdelivr CDN 对 GitHub 仓库有镜像缓存,国内访问稳定且速度快。 // 采用三级回退链:fastly.jsdelivr → cdn.jsdelivr → raw.githubusercontent // 缓存延长至 6 天,刷新节流延长至 24h(数据基本不变,偶尔新增待发售游戏)。 // v1.7.1: GitHub repo 实际只存了一个 2026.json 全量文件(含 2020-2026 所有年度), // 按年探测 2024/2025.json 都会 404 导致大量数据被静默丢弃。 // 改为"单文件全量拉 2026.json + 从 date 字段动态提取 availableYears"。 // JSON 格式:[{ name: "游戏名", date: "2026年01月30日", appid: 2362060 }, ...] // v1.7.0: 增加按年度筛选——availableYears 从数据里动态提取(去重 + 倒序) // 默认展示全部年度 + 按时间降序(dateDesc) const GOTY_YEAR_MIN = 2020; // 数据里允许的最小年份(用于过滤异常数据) const GOTY_DATA_FILE = '2026.json'; // 全量文件名(repo 实际只这一个) // v1.8.1: CDN 回退链——优先 jsdelivr(国内稳定),raw.githubusercontent 兜底 const GOTY_DATA_SOURCES = [ 'https://fastly.jsdelivr.net/gh/SmallRob/steam-namespace@main/data/' + GOTY_DATA_FILE, // ① fastly 节点(优先) 'https://cdn.jsdelivr.net/gh/SmallRob/steam-namespace@main/data/' + GOTY_DATA_FILE, // ② jsdelivr 主节点 'https://raw.githubusercontent.com/SmallRob/steam-namespace/refs/heads/main/data/' + GOTY_DATA_FILE, // ③ raw 兜底 ]; function _gotyCurrentYear() { return new Date().getFullYear(); } // "2026年01月30日" / "2026 年7月8日" → "20260130"(可排序字符串) function gotyDateToSortable(dateStr) { if (!dateStr) return '99999999'; const m = String(dateStr).match(/(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日/); if (!m) return '99999999'; return m[1] + m[2].padStart(2, '0') + m[3].padStart(2, '0'); } // 从可排序字符串中提取年份("20260130" → 2026) function gotyDateYear(sortable) { if (!sortable || sortable === '99999999') return null; return parseInt(sortable.slice(0, 4), 10); } // v2.9.22: "2026年01月30日" → "2026-01-30"(完整年月日,紧凑显示用) function gotyDateFull(dateStr) { const s = gotyDateToSortable(dateStr); if (s === '99999999') return dateStr || ''; return s.slice(0, 4) + '-' + s.slice(4, 6) + '-' + s.slice(6, 8); } // v1.0.4: 发售日期 → Date 对象(无效返回 null,区别于空字符串) // 参考 friend-manager 精品游戏 sfd-stress-featured-countdown (steam-friend-manager.user.js:11489) function gotyDateToDate(dateStr) { const s = gotyDateToSortable(dateStr); if (s === '99999999') return null; const y = +s.slice(0, 4), m = +s.slice(4, 6) - 1, d = +s.slice(6, 8); if (!y || m < 0 || d < 1) return null; const dt = new Date(y, m, d); return isNaN(dt.getTime()) ? null : dt; } // v1.0.4: 发售倒计时 HTML // 状态机:未发售(亮橙)/ 今日发售(amber 强调)/ 已发售(暗灰)/ 发售日期待定(null) // 参考 steam-friend-manager sfd-stress-featured-countdown / sfd-stress-featured-days function gotyCountdownHtml(dateStr) { const releaseDate = gotyDateToDate(dateStr); if (!releaseDate) return ''; const now = new Date(); // 抹掉当天时分秒,按"自然日"差计算(与 friend-manager parseStressDate 一致) const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()); const relStart = new Date(releaseDate.getFullYear(), releaseDate.getMonth(), releaseDate.getDate()); const daysLeft = Math.round((relStart - todayStart) / 86400000); if (daysLeft > 0) { return '<span class="sglv-goty-countdown sglv-goty-countdown--future" title="' + (Host.isZh ? '距离发售还有 ' : 'Releases in ') + daysLeft + (Host.isZh ? ' 天' : ' days') + '">' + '<span class="sglv-goty-countdown-days">' + daysLeft + '</span>' + '<span class="sglv-goty-countdown-lbl">' + (Host.isZh ? '天后发售' : 'days left') + '</span>' + '</span>'; } if (daysLeft === 0) { return '<span class="sglv-goty-countdown sglv-goty-countdown--today" title="' + (Host.isZh ? '今日发售' : 'Releases today') + '">' + '<span class="sglv-goty-countdown-days">★</span>' + '<span class="sglv-goty-countdown-lbl">' + (Host.isZh ? '今日发售' : 'today') + '</span>' + '</span>'; } // 已发售:仅显示"X 天前发售"作历史时间感(不强调) const ago = -daysLeft; return '<span class="sglv-goty-countdown sglv-goty-countdown--past" title="' + (Host.isZh ? '已发售 ' : 'Released ') + ago + (Host.isZh ? ' 天' : ' days ago') + '">' + '<span class="sglv-goty-countdown-days">' + ago + '</span>' + '<span class="sglv-goty-countdown-lbl">' + (Host.isZh ? '天前发售' : 'days ago') + '</span>' + '</span>'; } // ==================== v1.4.0: 年度大作封面获取优化 ==================== // 参考 Steam-Wishlist-Sidebar v1.2.0(SWE)的「持久化 good URL 缓存 + 多 CDN 回退 + // appdetails API 兜底」模式。年度大作多为新发售/未发售的 2026 游戏,部分胶囊图在单一 // CDN 上尚未就绪,需多 CDN 回退 + API 兜底才能稳定获取;首次会话解析成功的 URL 持久化 // 到 GM 存储(跨会话 LRU),后续会话直接命中最终 URL,跳过整条回退链,减少封面请求与闪烁。 const GOTY_COVER_CACHE_KEY = 'sglv_goty_cover_good_v1'; const GOTY_COVER_MAX = 600; // LRU 容量上限 // v2.9.3: 不再按条目 ts 判断是否有效,也不用 180 天容器 TTL(旧实现到期后 // cacheGet 会整表丢弃 → 所有 GOTY 封面同时重爬)。 // 容器 TTL 拉长到 10 年,失效交给"用一次自愈(404 → 回退链)+ LRU 600 淘汰"。 const GOTY_COVER_CONTAINER_TTL = 10 * 365 * 24 * 3600 * 1000; // 10 年(容器不过期) const _gotyCoverGood = new Map(); // `${kind}:${appid}` → 已验证可用 URL(内存) const _gotyCoverNext = new WeakMap(); // img → 下一个待尝试的 chain 索引 const _gotyCoverApiTried = new WeakMap();// img → 是否已尝试 API 兜底 let _gotyCoverPersisted = null; // null=未加载, {key:{url,ts}} let _gotyCoverWriteTimer = null; let _gotyCoverDirty = false; const _GOTY_PLACEHOLDER = "data:image/svg+xml;utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 200 300'%3E%3Crect fill='%231a1f3a' width='200' height='300'/%3E%3Ctext x='50%25' y='50%25' text-anchor='middle' dy='.3em' fill='%2364748b' font-family='system-ui' font-size='16'%3E🎮%3C/text%3E%3C/svg%3E"; function _gotyCoverLoadPersisted() { if (_gotyCoverPersisted !== null) return; _gotyCoverPersisted = {}; let data = null; // v2.9.3: 直接读原始值(不经 cacheGet 的 expires 检查)—— // 旧版本写的是 180 天容器 TTL,过期后 cacheGet 会整表清空; // 这里把内容完好的旧表恢复出来,并马上用 10 年 TTL 重写。 try { if (typeof GM_getValue === 'function') { const s = GM_getValue('sglv_cache_' + GOTY_COVER_CACHE_KEY, ''); if (s) { const obj = JSON.parse(s); if (obj && obj.data && typeof obj.data === 'object') data = obj.data; } } } catch (e) { /* ignore */ } if (!data) { try { const raw = Host.cacheGet(GOTY_COVER_CACHE_KEY); if (raw && typeof raw === 'object') data = raw; } catch (e) { /* ignore */ } } if (!data) return; let n = 0; for (const k in data) { const ent = data[k]; // 只收 http(s)(历史版本可能写入过 data: 占位图) if (ent && typeof ent.url === 'string' && /^https?:\/\//i.test(ent.url)) { _gotyCoverPersisted[k] = ent; _gotyCoverGood.set(k, ent.url); n++; } } if (n) { // 立刻用长 TTL 重写,避免下一次读取又被整表过期 try { Host.cacheSet(GOTY_COVER_CACHE_KEY, _gotyCoverPersisted, GOTY_COVER_CONTAINER_TTL); } catch (e) { /* ignore */ } } } function _gotyCoverRecordGood(appid, url, kind) { if (!appid || !url) return; // v2.9.2: 占位 data URI 绝不入持久缓存(否则下次渲染直接以占位图当封面) if (!/^https?:\/\//i.test(url)) return; const key = `${kind || 'poster'}:${appid}`; if (_gotyCoverGood.get(key) === url) return; // 已记录,跳过 _gotyCoverGood.set(key, url); _gotyCoverLoadPersisted(); _gotyCoverPersisted[key] = { url, ts: Date.now() }; // LRU 淘汰 const keys = Object.keys(_gotyCoverPersisted); if (keys.length > GOTY_COVER_MAX) { keys.sort((a, b) => (_gotyCoverPersisted[a].ts || 0) - (_gotyCoverPersisted[b].ts || 0)); while (keys.length > GOTY_COVER_MAX) delete _gotyCoverPersisted[keys.shift()]; } _gotyCoverDirty = true; // 节流落盘(80ms),避免高频 load 事件触发 GM 写入风暴 if (_gotyCoverWriteTimer) return; _gotyCoverWriteTimer = setTimeout(() => { _gotyCoverWriteTimer = null; if (!_gotyCoverDirty) return; _gotyCoverDirty = false; try { Host.cacheSet(GOTY_COVER_CACHE_KEY, _gotyCoverPersisted, GOTY_COVER_CONTAINER_TTL); } catch (e) { /* ignore */ } }, 80); } function _gotyCoverGetGood(appid, kind) { _gotyCoverLoadPersisted(); const v = _gotyCoverGood.get(`${kind || 'poster'}:${appid}`) || ''; // v2.9.2: 历史版本可能把 data: 占位图写进过缓存 —— 读到也当没有 return /^https?:\/\//i.test(v) ? v : ''; } // 生成年度大作封面 <img>(无内联 onerror,回退由 _bindGotyCoverDelegation 委托处理) // kind: 'poster'(竖版卡片) | 'capsule'(横版封面) | 'header'(列表图标) // v1.9.41: 链走 coverChainLang(语言变体链;good 缓存仍用 GOTY 专用持久缓存) function gotyCoverImgTag(appid, name, kind, cls) { const good = _gotyCoverGetGood(appid, kind) || coverGoodUrl(appid, kind); const chain = coverChainLang(appid, kind); const firstUrl = good || chain[0]; return `<img class="${cls}" data-goty-img="${kind}" data-appid="${appid}" src="${firstUrl}" alt="${Host.wlEscape(name)}" loading="lazy" decoding="async" referrerpolicy="no-referrer">`; } function gotyBadgeHtml() { return '<span class="sglv-card-badge sglv-goty-goty-badge">' + Host.T.gotyBadgeGoty + '</span>'; } function gotyOwnedBadgeHtml(owned) { return owned ? '<span class="sglv-card-badge owned" style="margin-top:0">✓ ' + Host.T.steamInLib + '</span>' : '<span class="sglv-card-badge" style="background:rgba(255,255,255,0.12);color:#8f98a0;margin-top:0;padding:2px 6px;border-radius:3px;font-size:10px">' + Host.T.gotyBadgeNotOwned + '</span>'; } // v2.9.8: 命中 TGA 年度游戏冠军的年度大作卡片 → 金色 👑 chip(点击开该年提名弹窗) function gotyTgaChipHtml(appid) { const info = _tgaState.index && _tgaState.index.byAppid[Number(appid)]; if (!info) return ''; return '<span class="sglv-goty-tga-chip" data-tga-chip="' + info.year + '" title="' + (Host.isZh ? 'TGA 年度游戏冠军 · ' + info.year + '(点击查看提名)' : 'TGA Game of the Year ' + info.year + ' (click for nominees)') + '">👑 ' + (Host.isZh ? '年度游戏' : 'GOTY') + '</span>'; } function _gotyCoverPlaceholder(img) { img.removeAttribute('data-goty-img'); // 占位图不再触发回退 img.src = _GOTY_PLACEHOLDER; } // 在年度大作内容容器上绑定图片回退委托(img 的 error/load 不冒泡,用捕获阶段) function _bindGotyCoverDelegation(contentEl) { if (!contentEl || contentEl.dataset.gotyCoverBound === '1') return; contentEl.dataset.gotyCoverBound = '1'; contentEl.addEventListener('error', (e) => { const img = e.target; if (!img || img.tagName !== 'IMG' || !img.dataset.gotyImg) return; const appid = img.dataset.appid; const kind = img.dataset.gotyImg; const chain = coverChainLang(appid, kind); let next = _gotyCoverNext.get(img); if (next === undefined) next = 0; // 跳过与当前已失败 src 相同的 chain 条目,避免重复请求 const curSrc = img.getAttribute('src'); while (next < chain.length && chain[next] === curSrc) next++; if (next < chain.length) { _gotyCoverNext.set(img, next + 1); img.src = chain[next]; return; } // 回退链耗尽 → appdetails API 兜底(仅尝试一次),成功会触发 load → 记录 good URL // v1.9.29: 传递 kind 参数,使 API 兜底按图片类型选择最佳 URL if (!_gotyCoverApiTried.get(img)) { _gotyCoverApiTried.set(img, true); Host.fetchCoverApiUrl(appid, kind).then(url => { if (url) img.src = url; else _gotyCoverPlaceholder(img); }).catch(() => _gotyCoverPlaceholder(img)); } else { _gotyCoverPlaceholder(img); } }, true); contentEl.addEventListener('load', (e) => { const img = e.target; if (!img || img.tagName !== 'IMG' || !img.dataset.gotyImg) return; if (img.naturalWidth && img.naturalWidth > 1) { _gotyCoverRecordGood(img.dataset.appid, img.getAttribute('src'), img.dataset.gotyImg); } }, true); } // v1.9.5: 缓存永不过期——优先读永久缓存秒开,后台增量合并刷新(24h 节流) const _GOTY_BG_INTERVAL = 24 * 3600 * 1000; // 年度大作数据变化慢,24h 节流足够 let _gotyLastBgRefreshAt = 0; function loadGotyGames(force) { // v1.9.27: force 时重置可能卡死的 loading 标志 if (gotyState.loading) { if (!force) return; gotyState.loading = false; } if (!force) { // v1.9.5: 优先读永久缓存(永不过期) const cached = _permCacheGet('gotyGames_v2'); if (cached && Array.isArray(cached.games) && cached.games.length > 0) { gotyState.games = cached.games; gotyState.updatedAt = cached.updatedAt || ''; gotyState.source = cached.source || Host.T.gotySourceCache; gotyState.availableYears = Array.isArray(cached.availableYears) ? cached.availableYears : []; gotyState.lastFetchAt = cached.lastFetchAt || 0; gotyState.loaded = true; renderGotySections(); // v1.9.5: 后台增量刷新(24h 节流) if (_shouldThrottle(_gotyLastBgRefreshAt, _GOTY_BG_INTERVAL)) return; _refreshGotyFromRemote(false, false); return; } } // v1.9.47-fix: 无缓存首次进入 → showLoading=true 展示 loading 骨架,避免 // "打开 GOTY tab → 远程源未返回时看到"暂无数据" → 数据到达后突然刷出" 的闪烁/误判。 _refreshGotyFromRemote(force, true); } function _gotyFailLoading(msg) { gotyState.loading = false; if (gotyState.games.length === 0) { gotyState.loadError = msg; } else { gotyState.loadError = null; Host.showToast(Host.isZh ? '更新失败,已使用本地数据' : 'Update failed, using local data'); } renderGotySections(); } // v1.8.1: 远程获取——CDN 三级回退链(fastly.jsdelivr → cdn.jsdelivr → raw.githubusercontent) // 依次尝试每个数据源,任一成功即停止;全部失败才报错。 // raw.githubusercontent.com 在国内经常超时/被墙,jsdelivr CDN 更稳定。 // v1.7.1: 单文件全量拉取 2026.json(包含 2020-currentYear 所有年度) // 从每个 game 的 date 字段动态提取 availableYears(去重 + 倒序) function _refreshGotyFromRemote(force, showLoading) { if (typeof GM_xmlhttpRequest !== 'function') { if (showLoading) _gotyFailLoading('noXhr'); return; } // v1.9.27: force 时重置可能卡死的 loading 标志 if (gotyState.loading) { if (!force) return; gotyState.loading = false; } if (showLoading) { gotyState.loading = true; gotyState.loadError = null; renderGotySections(); } const targetYear = gotyState.year; // 用户已选年度(null = 全部) // v1.8.1: 处理成功响应的公共逻辑(解析 + 过滤 + 去重 + 缓存 + 渲染) function _processGotyResponse(r) { const _gotyTxt = _safeRespText(r); if (r.status === 404 || !_gotyTxt) return false; // 交给下一个源 const data = JSON.parse(_gotyTxt); if (!Array.isArray(data) || data.length === 0) return false; // 解析 + 过滤无效数据 const games = data .filter(g => g && g.appid && Number(g.appid) > 0) .map(g => { const sortable = gotyDateToSortable(g.date || ''); return { appid: Number(g.appid), name: g.name || ('App ' + g.appid), date: g.date || '', year: gotyDateYear(sortable) }; }) .filter(g => g.year && g.year >= GOTY_YEAR_MIN && g.year <= _gotyCurrentYear() + 2); if (games.length === 0) return false; // v1.9.5: 增量合并去重(按 appid)——使用统一工具函数 gotyState.games = _mergeByAppid(gotyState.games, games); // 从所有 games 的 date 字段动态提取 availableYears(去重 + 倒序) const yearSet = new Set(); gotyState.games.forEach(g => { if (g.year) yearSet.add(g.year); }); gotyState.availableYears = Array.from(yearSet).sort((a, b) => b - a); // v1.9.24: 默认展开全部年度供用户筛选(null = 全部),仅在用户已选年度不在列表时回退到全部 if (targetYear && !gotyState.availableYears.includes(targetYear)) { gotyState.year = null; } gotyState.updatedAt = new Date().toISOString().slice(0, 10); gotyState.source = Host.T.gotySourceGithub; gotyState.loaded = true; gotyState.loadError = null; gotyState.loading = false; gotyState.lastFetchAt = Date.now(); _gotyLastBgRefreshAt = Date.now(); // v1.9.5: 记录后台刷新时间戳 // v1.9.5: 写入永久缓存(永不过期) _permCacheSet('gotyGames_v2', { games: gotyState.games, availableYears: gotyState.availableYears, updatedAt: gotyState.updatedAt, source: gotyState.source, lastFetchAt: gotyState.lastFetchAt }); renderGotySections(); return true; } // v1.8.1: 依次尝试 GOTY_DATA_SOURCES 中的每个数据源 function _tryNextSource(idx) { if (idx >= GOTY_DATA_SOURCES.length) { // 所有数据源都失败 gotyState.loading = false; if (gotyState.games.length === 0) _gotyFailLoading('networkError'); return; } GM_xmlhttpRequest({ method: 'GET', url: GOTY_DATA_SOURCES[idx], timeout: 15000, onload(r) { try { if (_processGotyResponse(r)) return; // 成功,停止 } catch (e) { /* 解析异常,交给下一个源 */ } _tryNextSource(idx + 1); // 失败,尝试下一个源 }, onerror() { _tryNextSource(idx + 1); }, ontimeout() { _tryNextSource(idx + 1); }, }); } _tryNextSource(0); } // v2.x: "GotY 时光机" — 按游戏发售日期拆为"未发售 / 已发售"两组; // 搜索 + 拥有筛选 + 排序在整个游戏集上过滤,年份时间轴按显示/隐藏年份块 function getGotyByYearAndSearch() { const q = (gotyState.search || '').toLowerCase().trim(); const ownedIds = Host.getActiveOwnedAppIds(); const isOwned = n => ownedIds.has(n) || ownedIds.has(String(n)); let list = gotyState.games.filter(g => g.appid > 0); if (q) { list = list.filter(g => String(g.appid).includes(q) || (g.name || '').toLowerCase().includes(q)); } if (gotyState.ownFilter === 'owned') list = list.filter(g => isOwned(g.appid)); else if (gotyState.ownFilter === 'notOwned') list = list.filter(g => !isOwned(g.appid)); // 默认 sort='dateDesc' —— 最新在前 list.sort((a, b) => { const da = gotyDateToSortable(a.date); const db = gotyDateToSortable(b.date); switch (gotyState.sort) { case 'dateDesc': return db.localeCompare(da) || (b.appid - a.appid); case 'dateAsc': return da.localeCompare(db) || (a.appid - b.appid); case 'nameAsc': return _nameCollator.compare(a.name || '~', b.name || '~') || da.localeCompare(db); case 'appidAsc': return a.appid - b.appid; default: return db.localeCompare(da) || (b.appid - a.appid); } }); // 按 year 分组(已排序,空 year 跳过) const byYear = {}; for (const g of list) { if (!g.year) continue; if (!byYear[g.year]) byYear[g.year] = []; byYear[g.year].push(g); } return byYear; } // v2.x: GotY 焦点大卡(未发售分组前 2 个,宽海报贴边 + 倒计时大数字) // 参考 steam-friend-manager 1.5.3 sfd-stress-featured-* (steam-friend-manager-1.5.3.js:11448) function renderGotyFeaturedCard(g) { const appid = g.appid; const ownedIds = Host.getActiveOwnedAppIds(); const isOwned = ownedIds.has(appid) || ownedIds.has(String(appid)); const releaseDate = gotyDateToDate(g.date); const now = new Date(); let daysLeft = null; let state = 'future'; if (releaseDate) { const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()); const relStart = new Date(releaseDate.getFullYear(), releaseDate.getMonth(), releaseDate.getDate()); const diff = Math.round((relStart - todayStart) / 86400000); if (diff > 0) { daysLeft = diff; state = 'future'; } else if (diff === 0) { daysLeft = 0; state = 'today'; } else { daysLeft = diff; state = 'past'; } } const cls = 'sglv-goty-featured' + (isOwned ? ' owned' : ''); const badgeText = isOwned ? (state === 'past' ? (Host.isZh ? '已拥有' : 'Owned') : (Host.isZh ? '已预购' : 'Wishlisted')) : (state === 'future' ? (Host.isZh ? '即将发售' : 'Upcoming') : (state === 'today' ? (Host.isZh ? '今日发售' : 'Today') : (Host.isZh ? '未拥有' : 'Not Owned'))); const daysText = daysLeft == null ? '—' : (state === 'past' ? '−' + Math.abs(daysLeft) : String(daysLeft)); const daysLbl = daysLeft == null ? (Host.isZh ? '待定' : 'TBD') : (state === 'future' ? (Host.isZh ? '天后' : 'd') : (state === 'today' ? (Host.isZh ? '今天' : 'today') : (Host.isZh ? '天前' : 'd ago'))); const clickUrl = 'https://store.steampowered.com/app/' + appid; const posterHtml = gotyCoverImgTag(appid, g.name, 'capsule', 'sglv-goty-featured-poster'); return '<div class="' + cls + '" data-appid="' + appid + '" onclick="window.open(\'' + clickUrl + '\',\'_blank\')">' + posterHtml + '<div class="sglv-goty-featured-info">' + '<span class="sglv-goty-featured-badge">' + badgeText + '</span>' + '<div class="sglv-goty-featured-name" title="' + Host.wlEscape(g.name) + '">' + Host.wlEscape(g.name) + '</div>' + '<div class="sglv-goty-featured-date">' + Host.wlEscape(gotyDateFull(g.date)) + '</div>' + '</div>' + '<div class="sglv-goty-featured-countdown">' + '<div class="sglv-goty-featured-days">' + daysText + '</div>' + '<div class="sglv-goty-featured-days-lbl">' + daysLbl + '</div>' + '</div>' + '</div>'; } // v2.x: GotY 网格卡片(card 视图: 竖版海报 + 名称 + 拥有 + 倒计时) /** 年度大片「大海报」卡片 —— v2.9.0 * 此前 cover 视图与 card 视图共用 renderGotyGridCard + .sglv-goty-grid, * 渲染结果完全一致 → 用户点「大海报」按钮视觉零变化,表现为"切换没效果"。 * 这里给 cover 视图独立的渲染路径:横向宽海报(.sglv-goty-cover-card), * 封面用 unifiedCover 的 capsule 链铺满,标题与元信息叠在封面下半部分。 */ function renderGotyCoverCard(g) { const appid = g.appid; const ownedIds = Host.getActiveOwnedAppIds(); const isOwned = ownedIds.has(appid) || ownedIds.has(String(appid)); const releaseDate = gotyDateToDate(g.date); const now = new Date(); let countdownHtml = ''; let countdownCls = ''; if (releaseDate) { const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()); const relStart = new Date(releaseDate.getFullYear(), releaseDate.getMonth(), releaseDate.getDate()); const diff = Math.round((relStart - todayStart) / 86400000); if (diff > 0) { countdownHtml = '<span class="sglv-goty-cover-countdown">' + (Host.isZh ? '还有 ' + diff + ' 天' : diff + 'd') + '</span>'; countdownCls = ' future'; } else if (diff === 0) { countdownHtml = '<span class="sglv-goty-cover-countdown">' + (Host.isZh ? '今日发售' : 'Today') + '</span>'; countdownCls = ' today'; } else if (diff > -60) { countdownHtml = '<span class="sglv-goty-cover-countdown">' + (Host.isZh ? Math.abs(diff) + ' 天前' : Math.abs(diff) + 'd ago') + '</span>'; countdownCls = ' past'; } } const clickUrl = 'https://store.steampowered.com/app/' + appid; return '<div class="sglv-goty-cover-card' + (isOwned ? ' is-owned' : '') + '" data-appid="' + appid + '"' + ' onclick="window.open(\'' + clickUrl + '\',\'_blank\')" title="' + Host.wlEscape(g.name) + '">' + '<div class="sglv-goty-cover-img-wrap">' + unifiedCover(appid, g.name, 'capsule', { imgCls: 'sglv-goty-cover-img' }) + '<div class="sglv-goty-cover-grad"></div>' + '<div class="sglv-goty-cover-overlay">' + '<div class="sglv-goty-cover-title">' + Host.wlEscape(g.name) + '</div>' + '<div class="sglv-goty-cover-meta">' + (isOwned ? '<span class="sglv-goty-cover-owned">\u2713 ' + (Host.isZh ? '在库' : 'Owned') + '</span>' : '<span class="sglv-goty-cover-not-owned">' + (Host.isZh ? '未拥有' : 'Not Owned') + '</span>') + countdownHtml + gotyTgaChipHtml(appid) + '</div>' + '</div>' + '</div>' + '</div>'; } function renderGotyGridCard(g) { const appid = g.appid; const ownedIds = Host.getActiveOwnedAppIds(); const isOwned = ownedIds.has(appid) || ownedIds.has(String(appid)); const releaseDate = gotyDateToDate(g.date); const now = new Date(); let countdownHtml = ''; if (releaseDate) { const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()); const relStart = new Date(releaseDate.getFullYear(), releaseDate.getMonth(), releaseDate.getDate()); const diff = Math.round((relStart - todayStart) / 86400000); if (diff > 0) countdownHtml = '<span class="sglv-goty-card-countdown future">还有 ' + diff + ' 天</span>'; else if (diff === 0) countdownHtml = '<span class="sglv-goty-card-countdown today">今日发售</span>'; else if (diff > -60) countdownHtml = '<span class="sglv-goty-card-countdown past">' + Math.abs(diff) + ' 天前</span>'; } const ownedHtml = isOwned ? '<span class="sglv-goty-card-owned">✓ ' + (Host.isZh ? '在库' : 'Owned') + '</span>' : '<span class="sglv-goty-card-not-owned">' + (Host.isZh ? '未拥有' : 'Not Owned') + '</span>'; const clickUrl = 'https://store.steampowered.com/app/' + appid; return '<div class="sglv-goty-card" data-appid="' + appid + '" onclick="window.open(\'' + clickUrl + '\',\'_blank\')" title="' + Host.wlEscape(g.name) + '">' + '<div class="sglv-goty-card-img-wrap">' + gotyCoverImgTag(appid, g.name, 'poster', 'sglv-goty-card-img') + gotyBadgeHtml() + '</div>' + '<div class="sglv-goty-card-body">' + '<div class="sglv-goty-card-name">' + Host.wlEscape(g.name) + '</div>' + '<div class="sglv-goty-card-meta">' + ownedHtml + countdownHtml + gotyTgaChipHtml(appid) + '</div>' + '</div>' + '</div>'; } // v2.x: GotY 列表行项 function renderGotyListItem(g) { const appid = g.appid; const ownedIds = Host.getActiveOwnedAppIds(); const isOwned = ownedIds.has(appid) || ownedIds.has(String(appid)); const ownedHtml = gotyOwnedBadgeHtml(isOwned); const dateHtml = g.date ? '<span class="sglv-goty-date"><span class="sglv-goty-clock">' + Host.ICONS.clock + '</span>' + Host.wlEscape(gotyDateFull(g.date)) + gotyCountdownHtml(g.date) + '</span>' : ''; const clickUrl = 'https://store.steampowered.com/app/' + appid; return '<div class="sglv-goty-list-item" data-appid="' + appid + '" onclick="window.open(\'' + clickUrl + '\',\'_blank\')">' + gotyCoverImgTag(appid, g.name, 'header', 'sglv-goty-list-icon') + '<div class="sglv-goty-list-info">' + '<div class="sglv-goty-list-name">' + Host.wlEscape(g.name) + ' <span class="sglv-card-id-inline">' + appid + '</span></div>' + '<div class="sglv-goty-list-meta">' + gotyBadgeHtml() + ' ' + ownedHtml + ' ' + dateHtml + ' ' + gotyTgaChipHtml(appid) + '</div>' + '</div>' + '</div>'; } // v2.x: 单个分组(未发售 / 已发售)HTML // sticky header(可点击折叠) + 焦点卡(0-2 个, 仅未发售组有) + 网格 5 列 function renderGotyGroup(year, title, groupGames, isUnreleased) { const ownedIds = Host.getActiveOwnedAppIds(); const isOwned = n => ownedIds.has(n) || ownedIds.has(String(n)); const ownedCount = groupGames.filter(g => isOwned(g.appid)).length; const total = groupGames.length; const pct = total > 0 ? Math.round(ownedCount / total * 100) : 0; const groupKey = year + ':' + (isUnreleased ? 'unreleased' : 'released'); const collapsed = gotyState.expandedYears && gotyState.expandedYears.has('collapsed:' + groupKey); const headerCls = 'sglv-goty-group-header' + (collapsed ? ' sglv-goty-group-collapsed' : ''); const bodyCls = 'sglv-goty-group-body'; let body = ''; // 焦点卡: 仅未发售组 + >=1 款时,前 2 个 if (isUnreleased && groupGames.length >= 1) { const featured = groupGames.slice(0, 2); const rest = groupGames.slice(2); body += '<div class="sglv-goty-featured-wrap">' + featured.map(renderGotyFeaturedCard).join('') + '</div>'; if (rest.length > 0) { body += (gotyState.viewMode === 'cover') ? '<div class="sglv-goty-cover-grid">' + rest.map(renderGotyCoverCard).join('') + '</div>' : '<div class="sglv-goty-grid">' + rest.map(renderGotyGridCard).join('') + '</div>'; } } else if (gotyState.viewMode === 'cover') { // v2.9.0: cover 视图改为独立的横向宽海报卡(此前与 card 视图渲染完全一致,切换无视觉变化) body += '<div class="sglv-goty-cover-grid">' + groupGames.map(renderGotyCoverCard).join('') + '</div>'; } else if (gotyState.viewMode === 'list') { body += '<div class="sglv-goty-list-view">' + groupGames.map(renderGotyListItem).join('') + '</div>'; } else { body += '<div class="sglv-goty-grid">' + groupGames.map(renderGotyGridCard).join('') + '</div>'; } const titleHtml = (isUnreleased ? '🕐 ' : '✓ ') + title; return '<div class="sglv-goty-group" data-group-key="' + groupKey + '">' + '<div class="' + headerCls + '" data-toggle-group="' + groupKey + '">' + '<span class="sglv-goty-group-caret"></span>' + '<span class="sglv-goty-group-title">' + titleHtml + '</span>' + '<span class="sglv-goty-group-count">' + ownedCount + ' / ' + total + (Host.isZh ? ' 已拥有' : ' owned') + '</span>' + '<div class="sglv-goty-group-bar"><div class="sglv-goty-group-bar-fill" style="width:' + pct + '%"></div></div>' + '<span class="sglv-goty-group-pct">' + pct + '%</span>' + '</div>' + '<div class="' + bodyCls + '">' + body + '</div>' + '</div>'; } // v2.x: 单个年份分块(包含"未发售" + "已发售"两个子分组) // 按当前日期切分; 时间轴节点 active = 当前 visible 年份 function renderGotyYearBlock(year, games) { const now = new Date(); const nowYear = now.getFullYear(); const nowMonth = now.getMonth(); const nowDay = now.getDate(); // 按"未发售" / "已发售"切分 const unreleased = []; const released = []; games.forEach(g => { const d = gotyDateToDate(g.date); if (!d) { // 无日期: 视作已发售(展示) released.push(g); return; } const isFuture = d.getFullYear() > nowYear || (d.getFullYear() === nowYear && (d.getMonth() > nowMonth || (d.getMonth() === nowMonth && d.getDate() > nowDay))); if (isFuture) unreleased.push(g); else released.push(g); }); // 未发售组: 按日期升序(最近的发售在前) unreleased.sort((a, b) => gotyDateToSortable(a.date).localeCompare(gotyDateToSortable(b.date))); // 已发售组: 按日期降序 released.sort((a, b) => gotyDateToSortable(b.date).localeCompare(gotyDateToSortable(a.date))); const unreleasedTitle = (Host.isZh ? '即将发售' : 'Upcoming'); const releasedTitle = (Host.isZh ? '已发售' : 'Released'); let html = '<div class="sglv-goty-year-block" data-year="' + year + '">'; if (unreleased.length > 0) html += renderGotyGroup(year, year + ' · ' + unreleasedTitle, unreleased, true); if (released.length > 0) html += renderGotyGroup(year, year + ' · ' + releasedTitle, released, false); html += '</div>'; return html; } // v2.x: GotY 标签页(主入口) function renderGotyTab(parent) { const wrap = document.createElement('div'); wrap.className = 'sglv-psplus-wrap sglv-goty-wrap'; wrap.style.cssText = 'display:flex;flex-direction:column;height:100%;min-height:0;'; const kpi = document.createElement('div'); kpi.id = 'sglv-goty-kpi'; wrap.appendChild(kpi); // 年份时间轴(横向滚动) const timeline = document.createElement('div'); timeline.id = 'sglv-goty-timeline'; timeline.className = 'sglv-goty-timeline'; wrap.appendChild(timeline); // 工具条(搜索 + 排序 + 视图 + 刷新) const toolbar = document.createElement('div'); toolbar.className = 'sglv-goty-toolbar-row'; const sortOptions = [ { key: 'dateDesc', label: Host.T.gotySortDateDesc }, { key: 'dateAsc', label: Host.T.gotySortDateAsc }, { key: 'nameAsc', label: Host.T.gotySortNameAsc }, { key: 'appidAsc', label: Host.T.gotySortAppidAsc }, ]; toolbar.innerHTML = '<input class="sglv-search" aria-label="搜索" id="sglv-goty-search" placeholder="' + Host.T.gotySearch + '" value="' + Host.wlEscape(gotyState.search) + '">' + '<select class="sglv-sort-select" aria-label="排序方式" id="sglv-goty-sort">' + sortOptions.map(o => '<option value="' + o.key + '"' + (gotyState.sort === o.key ? ' selected' : '') + '>' + o.label + '</option>').join('') + '</select>' + '<div class="sglv-view-toggle">' + '<button class="sglv-btn sglv-btn-secondary sglv-btn-icon' + (gotyState.viewMode === 'card' ? ' active' : '') + '" id="sglv-goty-card" title="' + Host.T.cardView + '">' + Host.ICONS.grid + '</button>' + '<button class="sglv-btn sglv-btn-secondary sglv-btn-icon' + (gotyState.viewMode === 'cover' ? ' active' : '') + '" id="sglv-goty-cover" title="' + Host.T.coverView + '">' + Host.ICONS.cover + '</button>' + '<button class="sglv-btn sglv-btn-secondary sglv-btn-icon' + (gotyState.viewMode === 'list' ? ' active' : '') + '" id="sglv-goty-list" title="' + Host.T.listView + '">' + Host.ICONS.list + '</button>' + '</div>' + '<button class="sglv-btn sglv-btn-secondary sglv-btn-icon" id="sglv-goty-refresh" title="' + Host.T.gotyRefreshTip + '">' + Host.ICONS.refresh + '</button>'; wrap.appendChild(toolbar); // 滚动区(年份分块) const scroll = document.createElement('div'); scroll.id = 'sglv-goty-scroll'; scroll.className = 'sglv-goty-scroll'; wrap.appendChild(scroll); parent.appendChild(wrap); // ---- 事件 ---- toolbar.querySelector('#sglv-goty-search').addEventListener('input', _debounce(e => { gotyState.search = e.target.value; renderGotySections(); }, 200)); toolbar.querySelector('#sglv-goty-sort').addEventListener('change', e => { gotyState.sort = e.target.value; renderGotySections(); }); const setView = m => { gotyState.viewMode = m; ['card', 'cover', 'list'].forEach(x => toolbar.querySelector('#sglv-goty-' + x)?.classList.toggle('active', x === m)); renderGotySections(); }; toolbar.querySelector('#sglv-goty-card').addEventListener('click', () => setView('card')); toolbar.querySelector('#sglv-goty-cover').addEventListener('click', () => setView('cover')); toolbar.querySelector('#sglv-goty-list').addEventListener('click', () => setView('list')); // v2.9.8: 刷新同时强拉 TGA 冠军数据(殿堂 + 👑 chip) toolbar.querySelector('#sglv-goty-refresh').addEventListener('click', () => { loadGotyGames(true); loadTgaWinners(true); }); // KPI 卡片点击切换拥有筛选 kpi.addEventListener('click', e => { const card = e.target.closest('[data-goty-filter]'); if (!card) return; const f = card.dataset.gotyFilter; gotyState.ownFilter = gotyState.ownFilter === f ? 'all' : f; renderGotyKpi(); renderGotySections(); }); // v2.9.6: 时间轴节点点击 = 切换年份筛选(真筛选,不再滚动定位) // 点击年份 → 只显示该年份分块;再次点击同一年份或点「全部」→ 回到全部。 // (disabled 节点为原生 button,不会派发 click,无需额外判断) timeline.addEventListener('click', e => { const node = e.target.closest('.sglv-goty-tl-node'); if (!node) return; // v2.9.8: 金色「年度游戏」节点 → 切换 TGA 殿堂视图(与年份筛选互斥) if (node.dataset.tgaView) { gotyState.tgaView = !gotyState.tgaView; if (gotyState.tgaView) gotyState.yearFilter = null; renderGotySections(); return; } gotyState.tgaView = false; const year = node.dataset.year; const y = (year === 'all' || year == null) ? null : parseInt(year, 10); gotyState.yearFilter = (gotyState.yearFilter === y) ? null : y; renderGotySections(); }); // 分组折叠切换 + v2.9.8 TGA 殿堂冠军卡点击 → 开该年提名弹窗 scroll.addEventListener('click', e => { const cell = e.target.closest('[data-tga-cell]'); if (cell) { const yr = parseInt(cell.dataset.tgaCell, 10); if (yr) openTgaNomsModal(yr); return; } const header = e.target.closest('[data-toggle-group]'); if (!header) return; const key = header.dataset.toggleGroup; const fullKey = 'collapsed:' + key; if (!gotyState.expandedYears) gotyState.expandedYears = new Set(); if (gotyState.expandedYears.has(fullKey)) { gotyState.expandedYears.delete(fullKey); } else { gotyState.expandedYears.add(fullKey); } // 只重渲染该分组 const groupEl = header.parentElement; const year = groupEl.dataset.groupKey.split(':')[0]; const gamesArr = getGotyByYearAndSearch()[+year] || []; const now = new Date(); const nowY = now.getFullYear(), nowM = now.getMonth(), nowD = now.getDate(); const isUnr = key.endsWith(':unreleased'); const filtered = isUnr ? gamesArr.filter(g => { const d = gotyDateToDate(g.date); if (!d) return false; return d.getFullYear() > nowY || (d.getFullYear() === nowY && (d.getMonth() > nowM || (d.getMonth() === nowM && d.getDate() > nowD))); }) : gamesArr.filter(g => { const d = gotyDateToDate(g.date); if (!d) return true; return !(d.getFullYear() > nowY || (d.getFullYear() === nowY && (d.getMonth() > nowM || (d.getMonth() === nowM && d.getDate() > nowD)))); }); // 简单做法: 整个 scroll 重渲染(分组小,开销可接受) renderGotySections(); }); // 滚动监听: 时间轴 active 跟随(v2.9.6: 年份筛选锁定时不跟随,active 由筛选态决定) scroll.addEventListener('scroll', () => { if (gotyState.yearFilter != null || gotyState.tgaView) return; const blocks = scroll.querySelectorAll('.sglv-goty-year-block'); let current = null; blocks.forEach(b => { const r = b.getBoundingClientRect(); const scrollTop = scroll.getBoundingClientRect().top; if (r.top - scrollTop <= 80) current = b.dataset.year; }); timeline.querySelectorAll('.sglv-goty-tl-node').forEach(n => { n.classList.toggle('sglv-goty-tl-active', n.dataset.year === String(current || 'all')); }); }); // v2.9.8: 年度大作卡片上的金色 👑 年度游戏 chip —— capture 阶段拦截点击开提名弹窗, // stopPropagation 阻止冒泡到卡片自身的 inline onclick(开商店页) scroll.addEventListener('click', e => { const chip = e.target.closest('[data-tga-chip]'); if (!chip) return; e.preventDefault(); e.stopPropagation(); const yr = parseInt(chip.dataset.tgaChip, 10); if (yr) openTgaNomsModal(yr); }, true); // 首次进入:加载数据 or 已加载则直接渲染 // v2.9.0: 绑定已移入 renderGotyScroll() —— 年度大片的视图切换/排序/年份筛选 // 都走 renderGotySections → renderGotyScroll 重渲染内容, // 绑定放在 renderGotyTab 里会早于内容生成执行(等于绑定空容器), // 导致「切视图后新卡片封面不加载」。 if (!gotyState.loaded && !gotyState.loading) { loadGotyGames(); } else { renderGotySections(); } // v2.9.8: 预载 TGA 冠军索引(缓存命中同步重渲染补 👑 chip;未命中后台拉取,供殿堂视图) loadTgaWinners(); } // v2.x: 重建时间轴 + scroll 区 function renderGotySections() { if (_collectionActiveTab !== 'goty' || !document.getElementById('sglv-goty-scroll')) return; renderGotyKpi(); renderGotyTimeline(); renderGotyScroll(); // v2.9.0: 内容渲染完成后再绑定封面链(每次重渲染都要重新绑定新生成的 wrapper) bindRestrictedCoverLoaders(document.getElementById('sglv-goty-scroll')); } // v2.x: 顶部 3 KPI(全部 / 已拥有 / 未拥有,clickable 切换 ownFilter) function renderGotyKpi() { const el = document.getElementById('sglv-goty-kpi'); if (!el) return; if (!gotyState.loaded) { el.innerHTML = ''; return; } const ownedIds = Host.getActiveOwnedAppIds(); const isOwned = n => ownedIds.has(n) || ownedIds.has(String(n)); const total = gotyState.games.length; const owned = gotyState.games.filter(g => isOwned(g.appid)).length; const notOwned = total - owned; const srcLabel = gotyState.source || Host.T.gotySourceGithub; const updatedStr = gotyState.updatedAt ? (Host.isZh ? '更新于 ' : 'Updated ') + gotyState.updatedAt + ' · ' + srcLabel : (Host.isZh ? '来源:' : 'Source: ') + srcLabel; el.innerHTML = '<div class="sglv-trend-kpi-row">' + '<div class="sglv-trend-kpi-card blue clickable' + (gotyState.ownFilter === 'all' ? ' active' : '') + '" data-goty-filter="all" title="' + (Host.isZh ? '点击筛选:全部' : 'Click to filter: All') + '">' + '<div class="sglv-trend-kpi-header"><span class="sglv-trend-kpi-icon">' + Host.ICONS.trophy + '</span><span class="sglv-trend-kpi-label">' + Host.T.gotyKpiTotal + '</span></div>' + '<div class="sglv-trend-kpi-value">' + total.toLocaleString() + '</div>' + '<div class="sglv-trend-kpi-sub">' + updatedStr + '</div>' + '</div>' + '<div class="sglv-trend-kpi-card mine clickable' + (gotyState.ownFilter === 'owned' ? ' active' : '') + '" data-goty-filter="owned" title="' + (Host.isZh ? '点击筛选:steam在库' : 'Click to filter: In Library') + '">' + '<div class="sglv-trend-kpi-header"><span class="sglv-trend-kpi-icon">' + Host.ICONS.heart + '</span><span class="sglv-trend-kpi-label">' + Host.T.gotyKpiOwned + '</span></div>' + '<div class="sglv-trend-kpi-value">' + owned.toLocaleString() + '</div>' + '<div class="sglv-trend-kpi-sub">' + Host.T.gotyKpiOwnedSub + '</div>' + '</div>' + '<div class="sglv-trend-kpi-card clickable' + (gotyState.ownFilter === 'notOwned' ? ' active' : '') + '" style="border-left:3px solid #ff9800" data-goty-filter="notOwned" title="' + (Host.isZh ? '点击筛选:未拥有' : 'Click to filter: Not Owned') + '">' + '<div class="sglv-trend-kpi-header"><span class="sglv-goty-trend-kpi-icon" style="color:#ff9800">' + Host.ICONS.tag + '</span><span class="sglv-trend-kpi-label">' + Host.T.gotyKpiNotOwned + '</span></div>' + '<div class="sglv-trend-kpi-value">' + notOwned.toLocaleString() + '</div>' + '<div class="sglv-trend-kpi-sub">' + (Host.isZh ? '可在 Steam 购买' : 'Available on Steam') + '</div>' + '</div>' + '</div>'; } // v2.x: 年份时间轴(渐变主线 + 发光年份节点,首节点 "全部") function renderGotyTimeline() { const el = document.getElementById('sglv-goty-timeline'); if (!el) return; if (!gotyState.loaded) { el.innerHTML = ''; return; } // 收集各年游戏数(在当前 search/filter/sort 之后) const byYear = getGotyByYearAndSearch(); const yearStats = (gotyState.availableYears || []).slice().sort((a, b) => b - a).map(y => ({ year: y, count: (byYear[y] || []).length, })); // 总数(全部) const totalCount = Object.values(byYear).reduce((s, arr) => s + arr.length, 0); // v2.9.6: active 由 yearFilter 决定(不再依赖滚动位置)——「全部」仅在未筛选时点亮 // v2.9.8: 殿堂视图(tgaView)开启时「全部」不点亮,改点亮金色「年度游戏」节点 const isAllActive = !gotyState.tgaView && gotyState.yearFilter == null && !gotyState.search && gotyState.ownFilter === 'all'; let html = '<div class="sglv-goty-tl-line"></div>' + '<button type="button" class="sglv-goty-tl-node sglv-goty-tl-goty' + (gotyState.tgaView ? ' sglv-goty-tl-active' : '') + '" data-tga-view="1" title="' + (Host.isZh ? 'TGA 年度游戏殿堂(历届冠军)' : 'TGA Game of the Year Hall') + '">' + '<span class="sglv-goty-tl-dot"></span>' + '<span class="sglv-goty-tl-year">' + (Host.isZh ? '年度游戏' : 'GOTY') + '</span>' + '<span class="sglv-goty-tl-count">' + (Host.isZh ? '殿堂' : 'Hall') + '</span>' + '</button>' + '<button type="button" class="sglv-goty-tl-node' + (isAllActive ? ' sglv-goty-tl-active' : '') + '" data-year="all" title="' + (Host.isZh ? '全部年度' : 'All Years') + '">' + '<span class="sglv-goty-tl-dot"></span>' + '<span class="sglv-goty-tl-year">' + (Host.isZh ? '全部' : 'All') + '</span>' + '<span class="sglv-goty-tl-count">' + totalCount + '</span>' + '</button>'; yearStats.forEach(s => { // v2.9.6: 当前搜索/筛选下该年 0 条 → 禁用点击(灰显,避免"点了没反应") const empty = s.count === 0; const active = gotyState.yearFilter === s.year; const title = empty ? (Host.isZh ? '该年度暂无匹配游戏' : 'No matching games in ' + s.year) : (Host.isZh ? (active ? '取消筛选,显示全部年度' : '只看 ' + s.year + ' 年游戏') : (active ? 'Clear year filter' : 'Show only ' + s.year + ' games')); html += '<button type="button" class="sglv-goty-tl-node' + (active ? ' sglv-goty-tl-active' : '') + '"' + (empty ? ' disabled' : ' data-year="' + s.year + '"') + ' title="' + title + '">' + '<span class="sglv-goty-tl-dot"></span>' + '<span class="sglv-goty-tl-year">' + s.year + '</span>' + '<span class="sglv-goty-tl-count">' + s.count + '</span>' + '</button>'; }); el.innerHTML = html; } // v2.x: scroll 区(所有年份分块) function renderGotyScroll() { const el = document.getElementById('sglv-goty-scroll'); if (!el) return; // v2.9.8: TGA 年度游戏殿堂视图(时间轴金色节点开启时优先渲染,覆盖常规年份分块) if (gotyState.tgaView) { renderTgaHall(el); return; } if (gotyState.loading) { el.innerHTML = '<div class="sglv-progress" style="margin:16px 0"><div class="sglv-progress-fill" style="width:45%"></div></div><div class="sglv-goty-empty">' + Host.T.gotyLoading + '</div>'; return; } if (gotyState.loadError && gotyState.games.length === 0) { el.innerHTML = '<div class="sglv-goty-empty">' + Host.T.gotyLoadError + '</div>'; return; } if (!gotyState.loaded || gotyState.games.length === 0) { el.innerHTML = '<div class="sglv-goty-empty">' + Host.T.gotyNoData + '</div>'; return; } const byYear = getGotyByYearAndSearch(); let yearKeys = Object.keys(byYear).map(Number).filter(y => byYear[y].length > 0).sort((a, b) => b - a); // v2.9.6: 年份筛选 —— 时间轴选中某年时只渲染该年份分块 if (gotyState.yearFilter != null) yearKeys = yearKeys.filter(y => y === gotyState.yearFilter); if (yearKeys.length === 0) { el.innerHTML = '<div class="sglv-goty-empty">' + (gotyState.yearFilter != null ? (Host.isZh ? '该年度暂无匹配游戏' : 'No matching games in this year') : (Host.isZh ? '无匹配结果' : 'No matching results')) + '</div>'; return; } _bindGotyCoverDelegation(el); let html = ''; yearKeys.forEach(y => { html += renderGotyYearBlock(y, byYear[y]); }); el.innerHTML = html; // v2.9.6: 重渲染后回到顶部(避免残留上次滚动位置造成"顶部空白"观感) el.scrollTop = 0; } // ==================== v2.9.8: TGA 年度游戏殿堂(参考 steam-friend-manager 1.6.2)==================== // 数据源 SmallFork/json TGA_winners.json: // { _meta:{categories:{goty:'年度游戏',…}}, years:[{year, games:[{awards, appid, name, url?, nominees:[{appid,name,url?}]}]}] } // appid=number → Steam 游戏;appid=string → 非 Steam 平台独占("任天堂独占"/"PlayStation 独占"/…) // awards==='goty' 标记当年年度游戏冠军;同名游戏同年多条获奖记录 → 皇冠数=当年获奖次数 const TGA_WINNERS_SOURCES = [ 'https://fastly.jsdelivr.net/gh/SmallFork/json@main/TGA_winners.json', // ① fastly(优先,国内稳定) 'https://cdn.jsdelivr.net/gh/SmallFork/json@main/TGA_winners.json', // ② jsdelivr 主节点 'https://raw.githubusercontent.com/SmallFork/json/main/TGA_winners.json',// ③ raw 兜底 ]; const _TGA_BG_INTERVAL = 24 * 3600 * 1000; // TGA 历史数据几乎不变,24h 后台刷新足够 let _tgaLastBgRefreshAt = 0; const _tgaState = { data: null, index: null, loaded: false, loading: false, loadError: null, updatedAt: '', source: '', lastFetchAt: 0 }; // 非 Steam 平台占位画配置(appid 字符串即平台名;平台主色 + 内联 SVG 图标,取自 friend-manager) const TGA_PLATFORMS = { '任天堂独占': { color: '#ff6b6b', icon: '<rect x="2.5" y="3.5" width="8" height="17" rx="4"/><rect x="13.5" y="3.5" width="8" height="17" rx="4"/><circle cx="6.5" cy="8.5" r="1.5"/><circle cx="17.5" cy="16" r="1.5"/>' }, 'PlayStation 独占': { color: '#5b9cf8', icon: '<path d="M7.5 4.8l3.2 5.4H4.3z"/><circle cx="16.5" cy="7.5" r="2.5"/><path d="M5.2 14l4.6 4.6M9.8 14l-4.6 4.6"/><rect x="14.4" y="14.2" width="4.4" height="4.4" rx=".7"/>' }, 'Xbox/微软商店': { color: '#4ade80', icon: '<circle cx="12" cy="12" r="8.2"/><path d="M6.6 6.4c3 2.6 7.8 7.4 10.8 11M17.4 6.4c-3 2.6-7.8 7.4-10.8 11"/>' }, '暴雪战网': { color: '#38bdf8', icon: '<path d="M12 3.2a8.8 8.8 0 1 0 8.8 8.8"/><path d="M12 6.6a5.4 5.4 0 1 1-5.4 5.4"/><path d="M12 10a2 2 0 1 0 2 2"/>' }, 'Epic 独占': { color: '#cbd5e1', icon: '<path d="M12 3l7.5 2.6v6.2c0 4.6-3.5 7.6-7.5 8.7-4-1.1-7.5-4.1-7.5-8.7V5.6z"/><path d="M9.4 8.6h5.2M9.4 12h4.2M9.4 15.4h5.2"/>' }, '手机游戏': { color: '#34d399', icon: '<rect x="7" y="2.6" width="10" height="18.8" rx="2.4"/><path d="M10.5 5.6h3"/>' }, 'VR 独占': { color: '#a78bfa', icon: '<path d="M3.2 8.4a2.6 2.6 0 0 1 2.6-2.6h12.4a2.6 2.6 0 0 1 2.6 2.6v4.2a2.6 2.6 0 0 1-2.6 2.6h-2.6L12 18.4l-3.6-3.2H5.8a2.6 2.6 0 0 1-2.6-2.6z"/>' }, }; const TGA_PLATFORM_FALLBACK = { color: '#66c0f4', icon: '<rect x="2.4" y="7" width="19.2" height="9.4" rx="2.4"/><path d="M7 9.6v4.2M4.9 11.7h4.2"/><circle cx="16.6" cy="10.6" r="1"/><circle cx="18.6" cy="12.8" r="1"/>' }; const TGA_CROWN_SVG = '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M2.8 7l4.7 3.4L12 4.5l4.5 5.9L21.2 7l-1.5 9.5a1.6 1.6 0 0 1-1.6 1.4H5.9a1.6 1.6 0 0 1-1.6-1.4z"/><rect x="5.2" y="19.3" width="13.6" height="1.8" rx="0.9"/></svg>'; // 纯函数:TGA 原始数据 → 冠军索引(无副作用,供单测) // byYear[year] = { year, winner, count(当年获奖次数), nominees[] };byAppid[steamAppid] = { year, count } // years = 有 GOTY 冠军的年份倒序;cats = 奖项 key→中文名映射 function tgaBuildWinnerIndex(data) { const idx = { byYear: {}, byAppid: {}, years: [], cats: (data && data._meta && data._meta.categories) || {} }; const years = (data && Array.isArray(data.years)) ? data.years : []; years.forEach(y => { if (!y || y.year == null || !Array.isArray(y.games)) return; const yr = Number(y.year); if (!yr) return; const winner = y.games.find(g => g && g.awards === 'goty'); if (!winner) return; const count = Math.max(1, y.games.filter(g => g && g.name === winner.name).length); idx.byYear[yr] = { year: yr, winner: winner, count: count, nominees: Array.isArray(winner.nominees) ? winner.nominees : [] }; idx.years.push(yr); if (typeof winner.appid === 'number') idx.byAppid[winner.appid] = { year: yr, count: count }; }); idx.years.sort((a, b) => b - a); return idx; } function tgaOwned(appid) { try { const ids = Host.getActiveOwnedAppIds(); return !!(ids && (ids.has(appid) || ids.has(String(appid)))); } catch (e) { return false; } } function tgaPlatform(type) { return TGA_PLATFORMS[String(type)] || TGA_PLATFORM_FALLBACK; } function tgaOpenStore(appid) { try { window.open('https://store.steampowered.com/app/' + appid, '_blank'); } catch (e) { /* ignore */ } } function tgaOwnedChipHtml(owned) { return owned ? '<span class="sglv-tga-tag owned">✓ ' + (Host.isZh ? '在库' : 'Owned') + '</span>' : '<span class="sglv-tga-tag">' + (Host.isZh ? '未拥有' : 'Not owned') + '</span>'; } function tgaExclTypeHtml(type) { return '<span class="sglv-tga-excl-type" style="color:' + tgaPlatform(type).color + '">' + Host.wlEscape(String(type)) + '</span>'; } // 非 Steam 平台占位画(vertical=true 竖版省略平台名);有商店图(game.url)则叠加海报层(失败自动移除) function tgaExclArtHtml(game, vertical) { const type = String(game.appid); const p = tgaPlatform(type); let html = '<div class="sglv-tga-excl-art" style="color:' + p.color + '">' + '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">' + p.icon + '</svg>' + (vertical ? '' : '<div class="sglv-tga-excl-name">' + Host.wlEscape(type) + '</div>') + '<div class="sglv-tga-excl-hint">' + (Host.isZh ? '封面待补充' : 'No cover yet') + '</div>' + '</div>'; if (game.url) html += '<img class="sglv-tga-excl-img" src="' + Host.wlEscape(game.url) + '" loading="lazy" decoding="async" alt="" referrerpolicy="no-referrer">'; return html; } function tgaBindExclImgs(root) { if (!root || !root.querySelectorAll) return; root.querySelectorAll('.sglv-tga-excl-img').forEach(img => img.addEventListener('error', () => img.remove(), { once: true })); } // 皇冠(数量=当年获奖次数,最多显示 3 顶,超出以 ×N 标注) function tgaCrownHtml(count) { const n = Math.max(1, count || 1); const shown = TGA_CROWN_SVG.repeat(Math.min(3, n)); return '<div class="sglv-tga-crown' + (n > 1 ? ' multi' : '') + '" title="' + (Host.isZh ? '当年获 ' + n + ' 项奖' : n + ' awards that year') + '">' + shown + (n > 3 ? '<span>×' + n + '</span>' : '') + '</div>'; } // 殿堂单卡:竖版海报 + 金色年份徽标 + 皇冠 + 名称 + 在库/平台标记(点击开该年提名弹窗) function tgaHallCellHtml(info) { const w = info.winner, year = info.year; const isSteam = typeof w.appid === 'number'; const owned = isSteam ? tgaOwned(w.appid) : false; const cls = 'sglv-tga-cell' + (isSteam ? (owned ? ' owned' : ' not-owned') : ' excl'); const poster = '<div class="sglv-tga-poster">' + (isSteam ? gotyCoverImgTag(w.appid, w.name, 'poster', 'sglv-tga-poster-img') : tgaExclArtHtml(w, true)) + '</div>'; const ownChip = isSteam ? tgaOwnedChipHtml(owned) : tgaExclTypeHtml(w.appid); return '<div class="' + cls + '" data-tga-cell="' + year + '" title="' + Host.wlEscape(w.name) + ' · ' + year + '">' + poster + '<div class="sglv-tga-year-badge">' + year + '</div>' + tgaCrownHtml(info.count) + '<div class="sglv-tga-cell-info"><div class="sglv-tga-cell-name">' + Host.wlEscape(w.name) + '</div>' + ownChip + '</div>' + '</div>'; } // 殿堂视图(hero + 历届冠军墙);数据未就绪时触发加载并显示占位 function renderTgaHall(el) { const loadingHtml = '<div class="sglv-progress" style="margin:16px 0"><div class="sglv-progress-fill" style="width:45%"></div></div><div class="sglv-goty-empty">' + (Host.isZh ? '正在获取 TGA 年度游戏数据…' : 'Loading TGA data…') + '</div>'; if (_tgaState.loading) { el.innerHTML = loadingHtml; return; } if (!_tgaState.loaded || !_tgaState.index || !_tgaState.index.years.length) { if (_tgaState.loadError) { el.innerHTML = '<div class="sglv-goty-empty">' + (Host.isZh ? 'TGA 数据获取失败,请点击右上角刷新重试' : 'Failed to load TGA data, click refresh to retry') + '</div>'; return; } el.innerHTML = loadingHtml; loadTgaWinners(); return; } const idx = _tgaState.index; _bindGotyCoverDelegation(el); const cells = idx.years.map(y => tgaHallCellHtml(idx.byYear[y])).join(''); const newest = idx.years[0], oldest = idx.years[idx.years.length - 1]; el.innerHTML = '<div class="sglv-tga-hall">' + '<div class="sglv-tga-hero">' + '<span class="sglv-tga-hero-icon">' + Host.ICONS.trophy + '</span>' + '<div class="sglv-tga-hero-txt"><div class="sglv-tga-hero-title">' + (Host.isZh ? '年度游戏殿堂' : 'Game of the Year Hall') + '</div>' + '<div class="sglv-tga-hero-sub">TGA · GAME OF THE YEAR</div></div>' + '<span class="sglv-tga-hero-count">' + oldest + '–' + newest + ' · ' + idx.years.length + (Host.isZh ? ' 届冠军' : ' champions') + '</span>' + '</div>' + '<div class="sglv-tga-grid">' + cells + '</div>' + '</div>'; tgaBindExclImgs(el); el.scrollTop = 0; } // ---- 提名弹窗(单例):左获奖者竖版海报 + 右提名横版网格;ESC/遮罩/关闭按钮退出 ---- let _tgaNomsModal = null, _tgaNomsEsc = null; function closeTgaNomsModal() { if (_tgaNomsEsc) { document.removeEventListener('keydown', _tgaNomsEsc, true); _tgaNomsEsc = null; } if (_tgaNomsModal) { _tgaNomsModal.remove(); _tgaNomsModal = null; } } function openTgaNomsModal(year) { const idx = _tgaState.index; const info = idx && idx.byYear[year]; if (!info) return; closeTgaNomsModal(); const w = info.winner; const catLabel = (idx.cats && idx.cats.goty) || (Host.isZh ? '年度游戏' : 'Game of the Year'); const noms = info.nominees.filter(n => n && n.name !== w.name); const isSteam = typeof w.appid === 'number'; const owned = isSteam ? tgaOwned(w.appid) : false; // 左栏:获奖者竖版海报(Steam 可点开商店;非 Steam 占位画)+ 名称 + 获奖徽章 + 在库/平台标记 const winPoster = isSteam ? '<div class="sglv-tga-winner-poster" data-tga-store="' + w.appid + '">' + gotyCoverImgTag(w.appid, w.name, 'poster', 'sglv-tga-winner-img') + '</div>' : '<div class="sglv-tga-winner-poster excl">' + tgaExclArtHtml(w, true) + '</div>'; const winOwn = isSteam ? tgaOwnedChipHtml(owned) : tgaExclTypeHtml(w.appid); // 右栏:提名横版网格(不含获奖者本人) let gridHtml = ''; noms.forEach(n => { const nSteam = typeof n.appid === 'number'; if (nSteam) { const nOwned = tgaOwned(n.appid); gridHtml += '<div class="sglv-tga-nom-card' + (nOwned ? ' owned' : '') + '" data-tga-store="' + n.appid + '" title="' + Host.wlEscape(n.name) + '">' + '<div class="sglv-tga-nom-img-wrap">' + gotyCoverImgTag(n.appid, n.name, 'capsule', 'sglv-tga-nom-img') + '</div>' + '<div class="sglv-tga-nom-name">' + Host.wlEscape(n.name) + '</div>' + (nOwned ? tgaOwnedChipHtml(true) : '') + '</div>'; } else { gridHtml += '<div class="sglv-tga-nom-card excl" title="' + Host.wlEscape(n.name) + '">' + '<div class="sglv-tga-nom-img-wrap">' + tgaExclArtHtml(n, false) + '</div>' + '<div class="sglv-tga-nom-name">' + Host.wlEscape(n.name) + '</div>' + tgaExclTypeHtml(n.appid) + '</div>'; } }); const html = '<div class="sglv-tga-modal-win">' + '<div class="sglv-tga-modal-head">' + '<span class="sglv-tga-modal-trophy">' + Host.ICONS.trophy + '</span>' + '<span class="sglv-tga-modal-title">' + Host.wlEscape(catLabel) + ' · ' + year + '</span>' + '<span class="sglv-tga-modal-sub">' + (Host.isZh ? '获奖 1 · 提名 ' + noms.length + ' 款' : 'Winner 1 · ' + noms.length + ' nominees') + '</span>' + '<span class="sglv-tga-modal-close" title="' + (Host.isZh ? '关闭' : 'Close') + '">' + Host.ICONS.close + '</span>' + '</div>' + '<div class="sglv-tga-modal-body">' + '<div class="sglv-tga-noms-side">' + '<div class="sglv-tga-noms-side-top"><span class="sglv-tga-side-year">' + year + '</span><span class="sglv-tga-side-cat">' + Host.wlEscape(catLabel) + '</span></div>' + winPoster + '<div class="sglv-tga-noms-side-name">' + Host.wlEscape(w.name) + '</div>' + '<div class="sglv-tga-noms-side-own"><span class="sglv-tga-winner-badge">' + (Host.isZh ? '获奖' : 'Winner') + '</span>' + winOwn + '</div>' + '</div>' + (gridHtml ? '<div class="sglv-tga-noms-grid">' + gridHtml + '</div>' : '<div class="sglv-tga-noms-empty">' + (Host.isZh ? '暂无提名数据' : 'No nominees') + '</div>') + '</div>' + '</div>'; const modal = document.createElement('div'); modal.className = 'sglv-tga-modal'; modal.innerHTML = html; modal.addEventListener('click', ev => { if (ev.target === modal || ev.target.closest('.sglv-tga-modal-close')) { closeTgaNomsModal(); return; } const storeEl = ev.target.closest('[data-tga-store]'); if (storeEl) tgaOpenStore(storeEl.dataset.tgaStore); }); _tgaNomsEsc = ev => { if (ev.key === 'Escape') closeTgaNomsModal(); }; document.addEventListener('keydown', _tgaNomsEsc, true); document.body.appendChild(modal); _tgaNomsModal = modal; _bindGotyCoverDelegation(modal); tgaBindExclImgs(modal); } // ---- 数据加载:IDB 永久缓存优先秒开 + 24h 后台刷新(镜像 loadGotyGames)---- function _tgaFailLoading(msg) { _tgaState.loading = false; if (!_tgaState.loaded) _tgaState.loadError = msg; if (gotyState.tgaView) renderGotySections(); } function loadTgaWinners(force) { if (_tgaState.loading) { if (!force) return; _tgaState.loading = false; } if (!force) { const cached = _permCacheGet('tgaWinners_v1'); if (cached && cached.data && Array.isArray(cached.data.years) && cached.data.years.length) { _tgaState.data = cached.data; _tgaState.index = tgaBuildWinnerIndex(cached.data); _tgaState.updatedAt = cached.updatedAt || ''; _tgaState.source = cached.source || (Host.isZh ? '本地缓存' : 'local cache'); _tgaState.lastFetchAt = cached.lastFetchAt || 0; _tgaState.loaded = true; _tgaState.loadError = null; // 缓存命中后重渲染:殿堂视图 或 常规视图(补上 👑 年度游戏 chip) if (gotyState.tgaView || gotyState.loaded) renderGotySections(); if (_shouldThrottle(_tgaLastBgRefreshAt, _TGA_BG_INTERVAL)) return; _refreshTgaFromRemote(false, false); return; } } _refreshTgaFromRemote(force, true); } function _refreshTgaFromRemote(force, showLoading) { if (typeof GM_xmlhttpRequest !== 'function') { if (showLoading) _tgaFailLoading('noXhr'); return; } if (_tgaState.loading) { if (!force) return; _tgaState.loading = false; } if (showLoading) { _tgaState.loading = true; _tgaState.loadError = null; if (gotyState.tgaView) renderGotySections(); } function _processTga(r) { const txt = _safeRespText(r); if (r.status === 404 || !txt) return false; const data = JSON.parse(txt); if (!data || !Array.isArray(data.years) || !data.years.length) return false; _tgaState.data = data; _tgaState.index = tgaBuildWinnerIndex(data); _tgaState.updatedAt = new Date().toISOString().slice(0, 10); _tgaState.source = 'TGA · GitHub'; _tgaState.loaded = true; _tgaState.loadError = null; _tgaState.loading = false; _tgaState.lastFetchAt = Date.now(); _tgaLastBgRefreshAt = Date.now(); _permCacheSet('tgaWinners_v1', { data: data, updatedAt: _tgaState.updatedAt, source: _tgaState.source, lastFetchAt: _tgaState.lastFetchAt }); if (gotyState.tgaView || gotyState.loaded) renderGotySections(); return true; } function _tryNextTga(i) { if (i >= TGA_WINNERS_SOURCES.length) { _tgaState.loading = false; if (!_tgaState.loaded) _tgaFailLoading('networkError'); else if (gotyState.tgaView) renderGotySections(); return; } GM_xmlhttpRequest({ method: 'GET', url: TGA_WINNERS_SOURCES[i], timeout: 15000, onload(r) { try { if (_processTga(r)) return; } catch (e) { /* 解析异常,交给下一个源 */ } _tryNextTga(i + 1); }, onerror() { _tryNextTga(i + 1); }, ontimeout() { _tryNextTga(i + 1); }, }); } _tryNextTga(0); } // ==================== DLC 收藏标签页 (v1.9.0) ==================== // 数据源: Host.isDlc (双源: Barter.vg DLC DB + Steam type=1/6) // Host.getDlcParent (DLC→父游戏 appID, 仅 Barter.vg 提供) // Host.getDlcType (DLC 子类型: music/dlc/video, 需 enrichDlcTypes) // Host.getBundleCount (进包次数) // 加载时序: loadDlcDatabase → enrichOwnedAppTypes → enrichDlcTypes (三级渐进) // 宿主桥接: Host.isDlc, Host.isDlcDbReady, Host.loadDlcDatabase, // Host.enrichOwnedAppTypes, Host.enrichDlcTypes, Host.getDlcType, // Host.getBundleCount, Host.getDlcParent, Host.getParentDlcTotalMap function dlcTypeBadgeHtml(type) { if (type === 'music') return '<span class="sglv-dlc-type-badge-music">' + Host.T.dlcBadgeMusic + '</span>'; return '<span class="sglv-dlc-type-badge-dlc">DLC</span>'; } function dlcBundleBadgeHtml(count) { if (!count || count <= 0) return ''; return '<span class="sglv-badge" style="background:rgba(245,158,11,0.15);color:#fbbf24;border:1px solid rgba(245,158,11,0.25);font-size:9px;padding:1px 5px;border-radius:3px;font-weight:700">📦' + count + '</span>'; } function dlcPlayedBadgeHtml(playtime) { if (!playtime || playtime <= 0) return ''; return '<span class="sglv-badge" style="background:rgba(75,181,79,0.15);color:#4bb54f;border:1px solid rgba(75,181,79,0.25);font-size:9px;padding:1px 5px;border-radius:3px;font-weight:700">' + Math.round(playtime / 60) + 'h</span>'; } // v1.9.4: 已拥有/未拥有 徽章 function dlcOwnedBadgeHtml(isOwned) { if (isOwned) return '<span class="sglv-badge" style="background:rgba(102,192,244,0.15);color:#66c0f4;border:1px solid rgba(102,192,244,0.25);font-size:9px;padding:1px 5px;border-radius:3px;font-weight:700">' + (Host.isZh ? '已拥有' : 'Owned') + '</span>'; return '<span class="sglv-badge" style="background:rgba(148,163,184,0.1);color:#64748b;border:1px solid rgba(148,163,184,0.15);font-size:9px;padding:1px 5px;border-radius:3px;font-weight:600">' + (Host.isZh ? '未拥有' : 'Not Owned') + '</span>'; } function dlcPosterImg(appid, name) { return unifiedCover(appid, name, 'poster'); } function dlcCapsuleImg(appid, name) { // v2.8.0: 统一封面(Host.capsuleImg 走旧 inline onerror 链,跨视图切换时会锁死) return unifiedCover(appid, name, 'capsule', { imgCls: 'sglv-wl-cover-img' }); } function dlcLookupParentName(parentApp) { if (!parentApp) return null; const found = Host.getOwnedGames().find(g => g.appid === parentApp || String(g.appid) === String(parentApp)); return found ? found.name : null; } // ==================== v1.9.2: DLC 子类型 IDB 永久缓存(只增不减) ==================== // 首次 enrichDlcTypes 后,所有已 enrich 的 DLC 写入 IDB。 // 下次加载:从 IDB 同步预热 dlcTypeCache,只 enrich 缓存里没有的 DLC("只增不减"增量)。 // 即使主脚本 GM 缓存丢失(用户清理脚本存储),本缓存仍能秒返已知子类型。 async function _ensureDlcTypeCacheLoaded() { if (dlcState.dlcTypeCacheLoaded) return dlcState.dlcTypeCache; if (dlcState.idbLoadPromise) return dlcState.idbLoadPromise; dlcState.idbLoadPromise = (async () => { if (!_C || !_C.IDB || typeof _C.IDB.loadAll !== 'function') { console.log('[SGLV-DLC] SGLVCore.IDB 不可用,跳过 IDB 缓存(fallback to in-memory only)'); dlcState.dlcTypeCacheLoaded = true; return dlcState.dlcTypeCache; } try { await _C.IDB.loadAll(); // 缓存版本号管理:ensureCacheVersions 升级时自动失效旧版本 if (typeof _C.ensureCacheVersions === 'function') { _C.ensureCacheVersions(_DLC_CACHE_VERSION); } const raw = _C.IDB.get(_DLC_TYPE_CACHE_IDB_KEY, null); if (raw && typeof raw === 'object' && !Array.isArray(raw)) { dlcState.dlcTypeCache = raw; console.log(`[SGLV-DLC] IDB dlcTypeCache 命中: ${Object.keys(raw).length} 个 DLC 子类型已缓存`); } else { console.log('[SGLV-DLC] IDB dlcTypeCache 空,首次使用'); } } catch (e) { console.warn('[SGLV-DLC] IDB 加载失败,使用空缓存:', e); } dlcState.dlcTypeCacheLoaded = true; return dlcState.dlcTypeCache; })(); return dlcState.idbLoadPromise; } // 持久化到 IDB(异步写,内存立即可见) function _persistDlcTypeCache() { if (!_C || !_C.IDB) return; try { _C.IDB.set(_DLC_TYPE_CACHE_IDB_KEY, dlcState.dlcTypeCache); } catch (e) { /* quota */ } } // 构建已拥有 DLC 列表(v1.9.4: 全量加载所有已知 DLC,匹配 isOwned) // v1.9.2: 同步版本保留,供"快速终态 rebuild"用;大库存场景请用 buildDlcListAsync function buildDlcList() { const t0 = performance.now(); const showFamilyShared = Host.getShowFamilyShared(); const pool = showFamilyShared ? Host.getOwnedGames() : Host.getOwnedGames().filter(g => Host.isGameOwnedByMe(g)); const ownedMap = {}; pool.forEach(g => { ownedMap[String(g.appid)] = g; }); // v1.9.11: 预构建 parentAppId → name 映射(O(1)查找),替代 dlcLookupParentName 的 O(n) 线性扫描 const parentNameMap = {}; Host.getOwnedGames().forEach(g => { if (g && g.appid) parentNameMap[String(g.appid)] = g.name; }); const dlcsByParent = (typeof Host.getDlcsByParentMap === 'function') ? Host.getDlcsByParentMap() : {}; const allDlcAppIds = new Set(); for (const dlcIds of Object.values(dlcsByParent)) { for (const id of dlcIds) allDlcAppIds.add(id); } for (const g of pool) { if (Host.isDlc(g.appid)) allDlcAppIds.add(g.appid); } console.log(`[SGLV-DLC] buildDlcList — 库存池 ${pool.length} 款 (familyShared=${showFamilyShared}), 全量 DLC ${allDlcAppIds.size} 个, isDlcDbReady=${Host.isDlcDbReady()}`); dlcState.dlcs = Array.from(allDlcAppIds).map(appid => { const owned = ownedMap[String(appid)]; const parentApp = Host.getDlcParent(appid); const type = (dlcState.dlcTypeCache && dlcState.dlcTypeCache[appid]) || Host.getDlcType(appid) || 'dlc'; return { appid, name: owned ? owned.name : ('DLC ' + appid), playtime: owned ? (owned.playtime || 0) : 0, parentApp: parentApp, parentName: parentApp ? (parentNameMap[String(parentApp)] || null) : null, type: type, bundleCount: Host.getBundleCount(appid), isOwned: !!owned, }; }); const withParent = dlcState.dlcs.filter(d => d.parentApp).length; const withType = dlcState.dlcs.filter(d => d.type !== 'dlc').length; const withBundle = dlcState.dlcs.filter(d => d.bundleCount > 0).length; console.log(`[SGLV-DLC] buildDlcList — 完成: ${dlcState.dlcs.length} 个 DLC, 父游戏=${withParent}, 子类型=${withType}, 进包=${withBundle}, 耗时 ${Math.round(performance.now() - t0)}ms`); } // v1.9.2: buildDlcList 的 async 分片版本——每 300 个 yield 一次(setTimeout 0 让出主线程) // 大库存(2k+)场景避免单次同步 200-500ms 卡顿;每个 chunk 后用 setTimeout 让浏览器处理用户输入 // v1.9.4: 全量加载——遍历所有已拥有父游戏的全部 DLC(含未拥有),匹配 isOwned async function buildDlcListAsync() { const t0 = performance.now(); const showFamilyShared = Host.getShowFamilyShared(); const allOwned = Host.getOwnedGames(); const pool = showFamilyShared ? allOwned : allOwned.filter(g => Host.isGameOwnedByMe(g)); // v1.9.4: 构建 appid → ownedGame 映射,用于匹配已拥有 DLC 和父游戏名称 const ownedMap = {}; pool.forEach(g => { ownedMap[String(g.appid)] = g; }); // v1.9.11: 预构建 parentAppId → name 映射(O(1)查找),替代 dlcLookupParentName 的 O(n) 线性扫描 // 71371 DLC × 10891 games 线性扫描 = ~7.8亿次比较,导致 buildDlcListAsync 永远无法完成 const parentNameMap = {}; allOwned.forEach(g => { if (g && g.appid) parentNameMap[String(g.appid)] = g.name; }); // v1.9.4: 获取父游戏→DLC列表 反向映射(Host.getDlcsByParentMap) const dlcsByParent = (typeof Host.getDlcsByParentMap === 'function') ? Host.getDlcsByParentMap() : {}; const parentKeys = Object.keys(dlcsByParent); // 收集所有需要处理的 DLC appid(全量 = 所有已知 DLC) const allDlcAppIds = new Set(); // 从父游戏反向映射收集 for (const dlcIds of Object.values(dlcsByParent)) { for (const id of dlcIds) allDlcAppIds.add(id); } // 同时保留原有逻辑:已拥有且 isDlc 的也加入(可能有些 DLC 不在 Barter.vg 数据库) for (const g of pool) { if (Host.isDlc(g.appid)) allDlcAppIds.add(g.appid); } const dlcCandidates = Array.from(allDlcAppIds); console.log(`[SGLV-DLC] buildDlcListAsync — 库存池 ${pool.length} 款, 父游戏 ${parentKeys.length} 个, 全量 DLC ${dlcCandidates.length} 个 (含未拥有)`); const out = []; const CHUNK = 300; for (let i = 0; i < dlcCandidates.length; i += CHUNK) { const slice = dlcCandidates.slice(i, i + CHUNK); slice.forEach(appid => { const owned = ownedMap[String(appid)]; const parentApp = Host.getDlcParent(appid); let type = (dlcState.dlcTypeCache && dlcState.dlcTypeCache[appid]) || Host.getDlcType(appid) || 'dlc'; out.push({ appid, name: owned ? owned.name : ('DLC ' + appid), playtime: owned ? (owned.playtime || 0) : 0, parentApp, parentName: parentApp ? (parentNameMap[String(parentApp)] || null) : null, type, bundleCount: Host.getBundleCount(appid), isOwned: !!owned, }); }); // 每片后让出主线程——浏览器可处理 UI 事件(点击、滚动等) if (i + CHUNK < dlcCandidates.length) { await new Promise(r => setTimeout(r, 0)); } } dlcState.dlcs = out; // v1.9.8: 清除过滤缓存(dlcs 内容已变,需重算 filtered/sorted 结果) dlcState._filteredCache = null; dlcState._filteredCacheKey = null; const withParent = out.filter(d => d.parentApp).length; const withType = out.filter(d => d.type !== 'dlc').length; const withBundle = out.filter(d => d.bundleCount > 0).length; console.log(`[SGLV-DLC] buildDlcListAsync — 完成: ${out.length} 个 DLC, 父游戏=${withParent}, 子类型=${withType}, 进包=${withBundle}, 耗时 ${Math.round(performance.now() - t0)}ms`); } // 三级渐进加载: Barter.vg DLC DB → Steam 全库存 type → DLC 子类型 // v1.9.1: L1 + L2 并行启动,任一完成立即 schedule buildDlcList + render(不阻塞 UI 进程) // v1.9.2: 四阶段加载——阶段 0 同步预热(IDB + 主脚本闭包),秒出;无缓存才走阶段 1+2+3 冷启 // L3 真正"只增不减"增量:只 enrich dlcTypeCache 里没有的 DLC // v1.9.8: 渐进式渲染——L1+L2 完成后立即 loaded=true 渲染数据,L3 后台异步获取子类型 // DLC 数据只增不减,缓存永久有效,支持增量更新;修复加载完成但一直显示加载中的问题 async function loadDlcData(force) { if (dlcState.loading) { // v1.9.27: force 时重置可能卡死的 loading 标志 if (!force) { console.log('[SGLV-DLC] loadDlcData — 已在加载中, 跳过'); return; } console.log('[SGLV-DLC] loadDlcData — force 重置卡死的 loading 标志'); dlcState.loading = false; } if (dlcState.loaded && !force) { console.log('[SGLV-DLC] loadDlcData — 已加载且非强制, 直接渲染'); renderDlcSections(); return; } const t0 = performance.now(); console.log(`[SGLV-DLC] loadDlcData — 开始加载 (force=${!!force}, dlcState.loaded=${dlcState.loaded})`); dlcState.loading = true; dlcState.loadError = null; dlcState.stage = 0; dlcState.level1Done = false; dlcState.level2Done = false; dlcState.rebuildQueued = false; // ==================== 阶段 0: 同步预热(关键!) ==================== // 1) IDB 永久缓存 → 立即填 dlcTypeCache(只增不减,即使主脚本 GM 缓存丢失也能秒返) // 2) Host.loadDlcDatabaseFromCacheSync → 同步填主脚本 dlcDbData / appTypeMap 闭包 // 3) buildDlcListAsync → 立即 build(分片,非阻塞) // 4) 如果拿到数据(dlcState.dlcs.length > 0),直接 loaded=true → 秒出 UI // 5) 后台异步跑 L1+L2(刷新可能新增的 DLC)+ L3 增量 enrich try { await _ensureDlcTypeCacheLoaded(); if (typeof Host.loadDlcDatabaseFromCacheSync === 'function') { try { Host.loadDlcDatabaseFromCacheSync(); } catch (e) { /* noop */ } } await buildDlcListAsync(); if (dlcState.dlcs.length > 0) { dlcState.loaded = true; dlcState.loading = false; dlcState.stage = 0; try { dlcState.parentTotalMap = Host.getParentDlcTotalMap() || {}; } catch (e) { dlcState.parentTotalMap = {}; } renderDlcSections(); console.log(`[SGLV-DLC] 阶段 0 缓存命中,立即出 ${dlcState.dlcs.length} 个 DLC,耗时 ${Math.round(performance.now() - t0)}ms`); // 后台异步刷新(不阻塞,fire-and-forget) _backgroundDlcRefresh(); return; } console.log('[SGLV-DLC] 阶段 0 无缓存(dlcs=0),降级到阶段 1+2+3 冷启'); } catch (e) { console.warn('[SGLV-DLC] 阶段 0 预热失败,降级到冷启:', e); } // ==================== 阶段 1+2: 冷启(无缓存场景) ==================== dlcState.stage = 1; renderDlcSections(); if (_StageProgress && typeof _StageProgress.ensure === 'function') { try { _StageProgress.ensure(); _StageProgress.setStage(1, 3, 'DLC'); } catch (e) { /* noop */ } } // ---- 工具:scheduleRebuild ---- const scheduleRebuild = (reason) => { if (dlcState.rebuildQueued) return; dlcState.rebuildQueued = true; setTimeout(() => { dlcState.rebuildQueued = false; if (_collectionActiveTab !== 'dlc') return; (async () => { try { const t = performance.now(); await buildDlcListAsync(); renderDlcSections(); console.log(`[SGLV-DLC] scheduleRebuild(${reason}) — dlcs=${dlcState.dlcs.length}, 渲染耗时 ${Math.round(performance.now() - t)}ms`); } catch (e) { console.warn('[SGLV-DLC] scheduleRebuild failed:', e); } })(); }, 0); }; try { // ==================== Level 1 ∥ Level 2 并行 ==================== const p1 = (async () => { const t1 = performance.now(); try { await Host.loadDlcDatabase(); dlcState.level1Done = true; console.log(`[SGLV-DLC] [Level 1/3] Barter.vg 就绪, 耗时 ${Math.round(performance.now() - t1)}ms`); scheduleRebuild('L1-done'); } catch (e) { console.warn('[SGLV-DLC] [Level 1/3] 失败:', e); } })(); const p2 = (async () => { const t2 = performance.now(); try { await Host.enrichOwnedAppTypes(); dlcState.level2Done = true; dlcState.stage = 2; if (_StageProgress) try { _StageProgress.setStage(2, 3, 'appType'); } catch (e) {} console.log(`[SGLV-DLC] [Level 2/3] appType 就绪, 耗时 ${Math.round(performance.now() - t2)}ms`); scheduleRebuild('L2-done'); } catch (e) { console.warn('[SGLV-DLC] [Level 2/3] 失败:', e); } })(); await Promise.all([p1, p2]); // v1.9.8: L1+L2 完成后立即 build + 渐进式渲染(loaded=true),L3 后台异步 dlcState.stage = 2; await buildDlcListAsync(); try { dlcState.parentTotalMap = Host.getParentDlcTotalMap() || {}; } catch (e) { dlcState.parentTotalMap = {}; } // v1.9.8: 关键改变 — L1+L2 完成后立即标记 loaded=true,用户可以看到 DLC 列表 // L3 (DLC 子类型) 在后台异步获取,不阻塞 UI dlcState.loaded = true; dlcState.loading = false; dlcState.page = 1; dlcState.stage = 0; if (_StageProgress) try { _StageProgress.hide(); } catch (e) {} renderDlcSections(); console.log(`[SGLV-DLC] L1+L2 完成, 渐进式渲染 ${dlcState.dlcs.length} 个 DLC, 耗时 ${Math.round(performance.now() - t0)}ms`); // v1.9.8: L3 后台异步获取 DLC 子类型(fire-and-forget,不阻塞 UI) _backgroundDlcTypeEnrich(); } catch (e) { dlcState.loadError = e.message || 'Load failed'; console.warn(`[SGLV-DLC] loadDlcData — 加载失败: ${e.message}, 已耗时 ${Math.round(performance.now() - t0)}ms`, e); dlcState.loading = false; if (_StageProgress) try { _StageProgress.hide(); } catch (e) {} renderDlcSections(); } } // v1.9.8: 后台 DLC 子类型增量获取 — L1+L2 完成后 fire-and-forget // 从 dlcTypeCache 中筛选未获取类型的 DLC,调用 Host.enrichDlcTypes 增量获取 // 获取完成后 rebuild + re-render,更新 KPI 和卡片类型显示 // DLC 数据只增不减,dlcTypeCache 永久缓存(IDB),支持增量更新 async function _backgroundDlcTypeEnrich() { if (dlcState.dlcTypeEnriching) { console.log('[SGLV-DLC] [bg L3] 已在获取中, 跳过'); return; } const dlcIds = dlcState.dlcs.map(d => d.appid); if (dlcIds.length === 0) return; // 增量:只获取 dlcTypeCache 中没有的 DLC const dlcIdsToEnrich = dlcIds.filter(id => !dlcState.dlcTypeCache[id]); if (dlcIdsToEnrich.length === 0) { console.log(`[SGLV-DLC] [bg L3] 跳过: 全部 ${dlcIds.length} 个 DLC 已在本地 IDB 缓存中`); return; } dlcState.dlcTypeEnriching = true; const t3 = performance.now(); console.log(`[SGLV-DLC] [bg L3] 增量 enrich ${dlcIdsToEnrich.length}/${dlcIds.length} 个 DLC(命中 ${dlcIds.length - dlcIdsToEnrich.length})`); try { // v2.9.68: 使用 onProgress 回调实现渐进式 re-render let renderTimer = null; await Host.enrichDlcTypes(dlcIdsToEnrich, { onProgress: (done, total) => { // 节流渲染:每 1.5s 最多刷新一次 UI if (!renderTimer) { renderTimer = setTimeout(() => { renderTimer = null; if (_collectionActiveTab !== 'dlc') return; (async () => { try { // 从主脚本拉取已获取的类型,合并到 dlcTypeCache let newCount = 0; for (const id of dlcIdsToEnrich) { const t = Host.getDlcType(id); if (t && !dlcState.dlcTypeCache[id]) { dlcState.dlcTypeCache[id] = t; newCount++; } } if (newCount > 0) { _persistDlcTypeCache(); // 清除过滤缓存,让新类型生效 dlcState._filteredCache = null; dlcState._filteredCacheKey = null; await buildDlcListAsync(); renderDlcSections(); } } catch (e) { /* noop */ } })(); }, 1500); } } }); // 最终:拉取所有类型,rebuild + re-render let newCount = 0; for (const id of dlcIdsToEnrich) { const t = Host.getDlcType(id); if (t && !dlcState.dlcTypeCache[id]) { dlcState.dlcTypeCache[id] = t; newCount++; } } if (newCount > 0) { _persistDlcTypeCache(); dlcState._filteredCache = null; dlcState._filteredCacheKey = null; await buildDlcListAsync(); } try { dlcState.parentTotalMap = Host.getParentDlcTotalMap() || {}; } catch (e) {} if (_collectionActiveTab === 'dlc') renderDlcSections(); console.log(`[SGLV-DLC] [bg L3] 增量完成: 新增 ${newCount} 个 type, 累计 ${Object.keys(dlcState.dlcTypeCache).length} 个, 耗时 ${Math.round(performance.now() - t3)}ms`); } catch (e) { console.warn('[SGLV-DLC] [bg L3] 失败:', e); } finally { dlcState.dlcTypeEnriching = false; } } // v1.9.2: 后台异步刷新——阶段 0 缓存命中后,fire-and-forget 跑 L1+L2 + L3 增量 // v1.9.3: 节流(6h)——避免短时间内重复刷新 // 目标:在不阻塞 UI 的前提下,让 dlcTypeCache 持续累计(只增不减,后续秒返) async function _backgroundDlcRefresh() { // v1.9.3: 节流——6h 内已刷过则跳过(多次打开 DLC tab 不会重复跑) if (Date.now() - (dlcState.lastBgRefreshAt || 0) < _DLC_BG_REFRESH_INTERVAL) { console.log(`[SGLV-DLC] 后台刷新跳过(节流): 上次 ${new Date(dlcState.lastBgRefreshAt).toLocaleString()}`); return; } dlcState.lastBgRefreshAt = Date.now(); const tb = performance.now(); try { // L1 ∥ L2 并行(主脚本缓存命中时秒返,否则走网络) const p1 = Host.loadDlcDatabase() .then(() => { dlcState.level1Done = true; }) .catch(e => console.warn('[SGLV-DLC] [bg L1] 失败:', e)); const p2 = Host.enrichOwnedAppTypes() .then(() => { dlcState.level2Done = true; }) .catch(e => console.warn('[SGLV-DLC] [bg L2] 失败:', e)); await Promise.all([p1, p2]); console.log(`[SGLV-DLC] [bg] L1+L2 完成, 耗时 ${Math.round(performance.now() - tb)}ms`); // 重建(可能新增 DLC) await buildDlcListAsync(); dlcState._filteredCache = null; dlcState._filteredCacheKey = null; if (_collectionActiveTab === 'dlc') renderDlcSections(); // v1.9.8: L3 增量 enrich 委托给 _backgroundDlcTypeEnrich(复用渐进式渲染逻辑) await _backgroundDlcTypeEnrich(); console.log(`[SGLV-DLC] 后台刷新完成, 总耗时 ${Math.round(performance.now() - tb)}ms`); } catch (e) { console.warn('[SGLV-DLC] 后台刷新失败:', e); } } // 筛选 + 排序后的扁平 DLC 列表 // v1.9.8: 缓存结果——当 dlcs/search/typeFilter/ownFilter/sort 未变时跳过重算,减少点击卡顿 function getFilteredDlc() { const cacheKey = `${dlcState.dlcs.length}|${dlcState.search}|${dlcState.typeFilter}|${dlcState.ownFilter}|${dlcState.sort}`; if (dlcState._filteredCacheKey === cacheKey && dlcState._filteredCache) { return dlcState._filteredCache; } const q = dlcState.search.toLowerCase().trim(); let list = dlcState.dlcs.slice(); if (q) { list = list.filter(d => { if (String(d.appid).includes(q)) return true; if ((d.name || '').toLowerCase().includes(q)) return true; if (d.parentName && d.parentName.toLowerCase().includes(q)) return true; return false; }); } if (dlcState.typeFilter === 'dlc') list = list.filter(d => d.type === 'dlc'); else if (dlcState.typeFilter === 'music') list = list.filter(d => d.type === 'music'); else if (dlcState.typeFilter === 'bundled') list = list.filter(d => d.bundleCount > 0); else if (dlcState.typeFilter === 'played') list = list.filter(d => d.playtime > 0); // v1.9.4: 已拥有筛选 if (dlcState.ownFilter === 'owned') list = list.filter(d => d.isOwned); // v1.9.5: 使用缓存的 _nameCollator,避免每次渲染重新构造 // v1.9.13: 激进防御——sort 出错时降级为 appid 排序,绝不抛异常中断渲染 try { list.sort((a, b) => { let r = 0; switch (dlcState.sort) { case 'appidAsc': r = a.appid - b.appid; break; case 'appidDesc': r = b.appid - a.appid; break; case 'nameAsc': r = _nameCollator.compare(a.name || '~', b.name || '~') || (a.appid - b.appid); break; case 'typeAsc': r = (a.type || 'z').localeCompare(b.type || 'z') || (a.appid - b.appid); break; case 'parentAsc': default: r = _nameCollator.compare(a.parentName || a.parentApp || '~', b.parentName || b.parentApp || '~') || (a.appid - b.appid); } return r || (a.appid - b.appid); }); } catch (sortErr) { console.warn('[SGLV-DLC] getFilteredDlc sort 失败,降级 appid 排序:', sortErr); list.sort((a, b) => a.appid - b.appid); } // v1.9.8: 缓存结果 dlcState._filteredCache = list; dlcState._filteredCacheKey = cacheKey; return list; } // 按父游戏分组(用于分组视图) function getGroupedDlc(filtered) { const groups = {}; const noParent = []; filtered.forEach(d => { if (d.parentApp) { const key = String(d.parentApp); if (!groups[key]) groups[key] = { parentApp: d.parentApp, parentName: d.parentName, dlcs: [] }; groups[key].dlcs.push(d); } else { noParent.push(d); } }); let groupList = Object.values(groups); // v1.9.5: 使用缓存的 _nameCollator // v1.9.13: 激进防御——sort 出错时降级为不排序 try { groupList.sort((a, b) => _nameCollator.compare(a.parentName || String(a.parentApp), b.parentName || String(b.parentApp))); } catch (sortErr) { console.warn('[SGLV-DLC] getGroupedDlc sort 失败,跳过排序:', sortErr); } if (noParent.length > 0) { groupList.push({ parentApp: null, parentName: Host.T.dlcUnknownParent, dlcs: noParent }); } // 计算完成度(v1.9.4: ownedDlc 只统计已拥有,totalDlc 为全部已知 DLC) groupList.forEach(g => { g.totalDlc = g.dlcs.length; g.ownedDlc = g.dlcs.filter(d => d.isOwned).length; g.pct = g.totalDlc > 0 ? Math.round(g.ownedDlc / g.totalDlc * 100) : 100; }); return groupList; } function renderDlcTab(parent) { const wrap = document.createElement('div'); wrap.className = 'sglv-psplus-wrap'; const kpi = document.createElement('div'); kpi.id = 'sglv-dlc-kpi'; wrap.appendChild(kpi); const toolbar = document.createElement('div'); toolbar.className = 'sglv-toolbar'; const sortOptions = [ { key: 'parentAsc', label: Host.T.dlcSortParent }, { key: 'appidDesc', label: Host.T.dlcSortAppidDesc }, { key: 'appidAsc', label: Host.T.dlcSortAppidAsc }, { key: 'nameAsc', label: Host.T.dlcSortNameAsc }, { key: 'typeAsc', label: Host.T.dlcSortType }, ]; // v1.9.1: groupMode=true 时视图按钮置灰(分组视图天然是 card 布局,viewMode 概念对它无意义) const viewToggleDisabledCls = dlcState.groupMode ? ' sglv-view-disabled' : ''; toolbar.innerHTML = ` <input class="sglv-search" aria-label="搜索" id="sglv-dlc-search" placeholder="${Host.T.dlcSearch}" value="${Host.wlEscape(dlcState.search)}"> <select class="sglv-sort-select" aria-label="排序方式" id="sglv-dlc-sort"> ${sortOptions.map(o => `<option value="${o.key}"${dlcState.sort === o.key ? ' selected' : ''}>${o.label}</option>`).join('')} </select> <div class="sglv-view-toggle${viewToggleDisabledCls}"> <button class="sglv-btn sglv-btn-secondary sglv-btn-icon${dlcState.viewMode === 'card' ? ' active' : ''}" id="sglv-dlc-card" title="${Host.T.cardView}">${Host.ICONS.grid}</button> <button class="sglv-btn sglv-btn-secondary sglv-btn-icon${dlcState.viewMode === 'cover' ? ' active' : ''}" id="sglv-dlc-cover" title="${Host.T.coverView}">${Host.ICONS.cover}</button> <button class="sglv-btn sglv-btn-secondary sglv-btn-icon${dlcState.viewMode === 'list' ? ' active' : ''}" id="sglv-dlc-list" title="${Host.T.listView}">${Host.ICONS.list}</button> </div> <div class="sglv-toolbar-sep"></div> <div class="sglv-dlc-own-filter"> <button class="sglv-btn sglv-btn-secondary${dlcState.ownFilter === 'all' ? ' active' : ''}" id="sglv-dlc-own-all">${Host.isZh ? '全部' : 'All'}</button> <button class="sglv-btn sglv-btn-secondary${dlcState.ownFilter === 'owned' ? ' active' : ''}" id="sglv-dlc-own-owned">${Host.isZh ? '已拥有' : 'Owned'}</button> </div> <div class="sglv-dlc-group-toggle"> <button class="sglv-btn sglv-btn-secondary${dlcState.groupMode ? ' active' : ''}" id="sglv-dlc-grouped">${Host.T.dlcGroupByParent}</button> <button class="sglv-btn sglv-btn-secondary${!dlcState.groupMode ? ' active' : ''}" id="sglv-dlc-flat">${Host.T.dlcFlatList}</button> </div> <div class="sglv-pagination" id="sglv-dlc-pagination"></div> `; wrap.appendChild(toolbar); const content = document.createElement('div'); content.className = 'sglv-content'; content.id = 'sglv-dlc-content'; wrap.appendChild(content); parent.appendChild(wrap); // 事件绑定 toolbar.querySelector('#sglv-dlc-search').addEventListener('input', _debounce((e) => { dlcState.search = e.target.value; dlcState.page = 1; renderDlcGamesList(); }, 200)); toolbar.querySelector('#sglv-dlc-sort').addEventListener('change', (e) => { dlcState.sort = e.target.value; dlcState.page = 1; renderDlcGamesList(); }); const setDlcViewMode = (mode) => { // v1.9.1: groupMode=true 时视图按钮被禁用,直接返回(双保险,防止 pointer-events bypass) if (dlcState.groupMode) return; dlcState.viewMode = mode; ['card', 'cover', 'list'].forEach(m => { toolbar.querySelector('#sglv-dlc-' + m)?.classList.toggle('active', m === mode); }); renderDlcGamesList(); }; toolbar.querySelector('#sglv-dlc-card').addEventListener('click', () => setDlcViewMode('card')); toolbar.querySelector('#sglv-dlc-cover').addEventListener('click', () => setDlcViewMode('cover')); toolbar.querySelector('#sglv-dlc-list').addEventListener('click', () => setDlcViewMode('list')); // v1.9.4: 已拥有筛选切换 const setDlcOwnFilter = (filter) => { dlcState.ownFilter = filter; dlcState.page = 1; toolbar.querySelector('#sglv-dlc-own-all')?.classList.toggle('active', filter === 'all'); toolbar.querySelector('#sglv-dlc-own-owned')?.classList.toggle('active', filter === 'owned'); renderDlcGamesList(); }; toolbar.querySelector('#sglv-dlc-own-all').addEventListener('click', () => setDlcOwnFilter('all')); toolbar.querySelector('#sglv-dlc-own-owned').addEventListener('click', () => setDlcOwnFilter('owned')); // v1.9.1: 统一 grouped/flat 切换逻辑,同步视图按钮置灰状态 const applyDlcGroupMode = (grouped) => { dlcState.groupMode = grouped; dlcState.page = 1; toolbar.querySelector('#sglv-dlc-grouped').classList.toggle('active', grouped); toolbar.querySelector('#sglv-dlc-flat').classList.toggle('active', !grouped); toolbar.querySelector('.sglv-view-toggle')?.classList.toggle('sglv-view-disabled', grouped); renderDlcGamesList(); }; toolbar.querySelector('#sglv-dlc-grouped').addEventListener('click', () => applyDlcGroupMode(true)); toolbar.querySelector('#sglv-dlc-flat').addEventListener('click', () => applyDlcGroupMode(false)); // KPI 卡片点击筛选 kpi.addEventListener('click', e => { const card = e.target.closest('[data-dlc-filter]'); if (!card) return; const f = card.dataset.dlcFilter; dlcState.typeFilter = dlcState.typeFilter === f ? 'all' : f; dlcState.page = 1; renderDlcKpi(); renderDlcGamesList(); }); // v1.9.3: 用户点击 tab 立即进入——先无条件渲染骨架(KPI + content 都是 skeleton) // 后台 loadDlcData 完成后再 renderDlcSections() 替换为真实数据 // 这样无论冷启/热数据都能"秒进" renderDlcSections(); if (!dlcState.loaded && !dlcState.loading) { // fire-and-forget:后台加载,不阻塞 UI loadDlcData(); } } function renderDlcSections() { if (_collectionActiveTab !== 'dlc' || !document.getElementById('sglv-dlc-content')) return; // v1.9.13: 激进防御——任何渲染异常都不应中断 loadDlcData 流程 try { renderDlcKpi(); renderDlcGamesList(); } catch (e) { console.warn('[SGLV-DLC] renderDlcSections 渲染异常(已降级):', e); const content = document.getElementById('sglv-dlc-content'); if (content && !content.innerHTML.trim()) { content.innerHTML = '<div class="sglv-empty">' + (Host.isZh ? 'DLC 渲染异常,数据已加载,请尝试切换排序或刷新页面' : 'DLC render error, data loaded. Try switching sort or refresh') + '</div>'; } } } // v1.9.1: 阶段进度条 + DLC 卡片骨架 HTML 工厂 // 用于 loading 状态:KPI 区 5 个 shimmer 卡 + content 区阶段条 + 12 个 card 占位 // 数据稳定(loaded=true)前不展示真实 KPI 数字,避免数字跳变 // v1.9.4: spinner 加载等待动画(参考 steam-friend-manager 的 spinner 风格) // v2.9.67: 修复 wlEscape 三元表达式 bug(两分支都调用了 Host.wlEscape) function renderDlcLoadingHtml() { const stage = DLC_STAGES[dlcState.stage] || { pct: 30, zh: '加载中…', en: 'Loading…' }; const pct = stage.pct; const text = Host && Host.isZh ? stage.zh : stage.en; const safeText = Host && Host.wlEscape ? Host.wlEscape(text) : text; const spinSvg = '<svg class="sglv-dlc-spin" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>'; return `<div class="sglv-dlc-loading"> ${spinSvg} <div class="sglv-dlc-loading-text">${safeText}</div> <div class="sglv-dlc-loading-bar"><div class="sglv-dlc-loading-bar-fill" style="width:${pct}%"></div></div> <div class="sglv-dlc-loading-sub">${Host && Host.isZh ? '正在加载所有已知 DLC 数据…' : 'Loading all known DLC data…'}</div> </div>`; } function renderDlcKpiSkeletonHtml() { const skel = '<div class="sglv-skel-line lg"></div><div class="sglv-skel-line md"></div><div class="sglv-skel-line sm"></div>'; const cards = Array.from({ length: 5 }, () => `<div class="sglv-trend-kpi-card skeleton">${skel}</div>`).join(''); return `<div class="sglv-trend-kpi-row">${cards}</div>`; } function renderDlcKpi() { const el = document.getElementById('sglv-dlc-kpi'); if (!el) return; // v1.9.1: 加载中 / 未加载完成统一显示骨架(数字会跳变,体验差) if (dlcState.loading || !dlcState.loaded) { el.innerHTML = renderDlcKpiSkeletonHtml(); return; } const total = dlcState.dlcs.length; const owned = dlcState.dlcs.filter(d => d.isOwned).length; const regular = dlcState.dlcs.filter(d => d.type === 'dlc').length; const music = dlcState.dlcs.filter(d => d.type === 'music').length; const bundled = dlcState.dlcs.filter(d => d.bundleCount > 0).length; const played = dlcState.dlcs.filter(d => d.playtime > 0).length; const parentCount = new Set(dlcState.dlcs.filter(d => d.parentApp).map(d => String(d.parentApp))).size; const noParent = dlcState.dlcs.filter(d => !d.parentApp).length; // v1.9.8: 后台子类型获取中时,在 KPI 区底部显示进度提示 const enrichHint = dlcState.dlcTypeEnriching ? `<div style="text-align:center;padding:4px 0 2px;font-size:11px;color:var(--sglv-accent, #a78bfa);display:flex;align-items:center;justify-content:center;gap:6px"> <svg style="width:12px;height:12px;animation:sgc-spin 1s linear infinite" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg> ${Host.isZh ? '后台获取 DLC 子类型中…' : 'Fetching DLC subtypes in background…'} </div>` : ''; const ownPct = total > 0 ? Math.round(owned / total * 100) : 0; const subText = Host.T.dlcKpiSub.replace('{n}', parentCount) + (noParent > 0 ? ' · ' + Host.T.dlcKpiNoParent + ' ' + noParent : ''); el.innerHTML = ` <div class="sglv-trend-kpi-row"> <div class="sglv-trend-kpi-card blue clickable${dlcState.typeFilter === 'all' ? ' active' : ''}" data-dlc-filter="all" title="${Host.isZh ? '点击筛选:全部' : 'Click to filter: All'}"> <div class="sglv-trend-kpi-header"><span class="sglv-trend-kpi-icon">${Host.ICONS.puzzle}</span><span class="sglv-trend-kpi-label">${Host.T.dlcKpiTotal}</span></div> <div class="sglv-trend-kpi-value">${total.toLocaleString()}</div> <div class="sglv-trend-kpi-sub">${subText}</div> <div class="sglv-trend-kpi-sub" style="color:#4bb54f;font-weight:600">${Host.isZh ? '已拥有 ' + owned.toLocaleString() + ' (' + ownPct + '%)' : 'Owned ' + owned.toLocaleString() + ' (' + ownPct + '%)'}</div> </div> <div class="sglv-trend-kpi-card clickable${dlcState.typeFilter === 'dlc' ? ' active' : ''}" style="border-left:3px solid var(--sglv-accent-deep, #8b5cf6)" data-dlc-filter="dlc" title="${Host.isZh ? '点击筛选:常规 DLC' : 'Click to filter: Regular DLC'}"> <div class="sglv-trend-kpi-header"><span class="sglv-trend-kpi-icon" style="color:var(--sglv-accent, #a78bfa)">${Host.ICONS.package}</span><span class="sglv-trend-kpi-label">${Host.T.dlcKpiRegular}</span></div> <div class="sglv-trend-kpi-value">${regular.toLocaleString()}</div> <div class="sglv-trend-kpi-sub">type=1</div> </div> <div class="sglv-trend-kpi-card clickable${dlcState.typeFilter === 'music' ? ' active' : ''}" style="border-left:3px solid #22a5f7" data-dlc-filter="music" title="${Host.isZh ? '点击筛选:音乐包' : 'Click to filter: Music'}"> <div class="sglv-trend-kpi-header"><span class="sglv-trend-kpi-icon" style="color:#22a5f7">${Host.ICONS.tag}</span><span class="sglv-trend-kpi-label">${Host.T.dlcKpiMusic}</span></div> <div class="sglv-trend-kpi-value">${music.toLocaleString()}</div> <div class="sglv-trend-kpi-sub">type=6</div> </div> <div class="sglv-trend-kpi-card clickable${dlcState.typeFilter === 'bundled' ? ' active' : ''}" style="border-left:3px solid #f59e0b" data-dlc-filter="bundled" title="${Host.isZh ? '点击筛选:进包 DLC' : 'Click to filter: Bundled'}"> <div class="sglv-trend-kpi-header"><span class="sglv-trend-kpi-icon" style="color:#f59e0b">${Host.ICONS.package}</span><span class="sglv-trend-kpi-label">${Host.T.dlcKpiBundled}</span></div> <div class="sglv-trend-kpi-value">${bundled.toLocaleString()}</div> <div class="sglv-trend-kpi-sub">${Host.isZh ? '含 Bundle' : 'In Bundles'}</div> </div> <div class="sglv-trend-kpi-card clickable${dlcState.typeFilter === 'played' ? ' active' : ''}" style="border-left:3px solid #4bb54f" data-dlc-filter="played" title="${Host.isZh ? '点击筛选:已游玩' : 'Click to filter: Played'}"> <div class="sglv-trend-kpi-header"><span class="sglv-trend-kpi-icon" style="color:#4bb54f">${Host.ICONS.trend}</span><span class="sglv-trend-kpi-label">${Host.T.dlcKpiPlayed}</span></div> <div class="sglv-trend-kpi-value">${played.toLocaleString()}</div> <div class="sglv-trend-kpi-sub">playtime>0</div> </div> </div> ${enrichHint} `; } // v1.9.1: 大网格 rAF 分片 append,避免一次性 innerHTML 写入上千卡片卡顿 // 用 DocumentFragment 多次 append,rAF 让出浏览器绘制 const _DLC_RENDER_CHUNK = 24; // 每片卡片数 const _DLC_RENDER_RAF_THRESHOLD = 30; // 超过此数才走分片(少量直接 innerHTML 更快) function appendDlcCardsChunked(grid, htmls, done) { if (!grid || !htmls || htmls.length === 0) { if (done) done(); return; } if (htmls.length <= _DLC_RENDER_RAF_THRESHOLD || typeof requestAnimationFrame !== 'function') { grid.innerHTML = htmls.join(''); // v2.9.5: DLC 分组视图从不绑定封面回退 → wrapper 永远停在 sglv-img-loading(灰块) bindRestrictedCoverLoaders(grid); if (done) done(); return; } let i = 0; const total = htmls.length; const step = () => { const frag = document.createDocumentFragment(); const t0 = performance.now(); const end = Math.min(i + _DLC_RENDER_CHUNK, total); for (; i < end; i++) { const tpl = document.createElement('template'); tpl.innerHTML = htmls[i].trim(); const node = tpl.content.firstChild; if (node) frag.appendChild(node); } grid.appendChild(frag); // v2.9.5: 每批 append 后就绑定新卡片(幂等,只处理未绑定的 wrapper)—— // DLC 分组视图(renderDlcGrouped)此前完全没有调用 binder, // 封面 404 后无回退链,wrapper 永远停在 loading 灰块。 bindRestrictedCoverLoaders(grid); if (i < total) { // 切片之间让出主线程:rAF 等同 16ms,若耗时 > 12ms 也强制让出 if (performance.now() - t0 > 12) { setTimeout(step, 0); } else { requestAnimationFrame(step); } } else { if (done) done(); } }; step(); } function renderDlcGamesList() { const content = document.getElementById('sglv-dlc-content'); if (!content) return; const clearPagination = () => { const p = document.getElementById('sglv-dlc-pagination'); if (p) p.innerHTML = ''; }; // v1.9.4: loading 阶段显示 spinner 加载动画(参考 steam-friend-manager 风格) // v2.9.67: 尚未加载(!loaded && !loading)时也显示加载动画,避免首次进入空白 if (dlcState.loading || (!dlcState.loaded && !dlcState.loadError)) { content.innerHTML = renderDlcLoadingHtml(); clearPagination(); return; } if (dlcState.loadError) { content.innerHTML = '<div class="sglv-empty">' + Host.T.dlcLoadError + '</div>'; clearPagination(); return; } if (!dlcState.loaded || dlcState.dlcs.length === 0) { content.innerHTML = '<div class="sglv-empty">' + Host.T.dlcNoData + '</div>'; clearPagination(); return; } // v1.9.13: 激进防御——getFilteredDlc 出错时降级为未排序原始列表,绝不白屏 let list; try { list = getFilteredDlc(); } catch (e) { console.warn('[SGLV-DLC] getFilteredDlc 异常,降级未排序列表:', e); list = dlcState.dlcs.slice(); } if (list.length === 0) { content.innerHTML = '<div class="sglv-empty">' + (Host.isZh ? '无匹配结果' : 'No matching results') + '</div>'; clearPagination(); return; } // 分组视图 if (dlcState.groupMode) { let groups; try { groups = getGroupedDlc(list); } catch (e) { console.warn('[SGLV-DLC] getGroupedDlc 异常,降级扁平视图:', e); dlcState.groupMode = false; groups = null; } if (groups) { const { pageItems, totalPages, page: _clampedPage } = Host.paginate(groups, dlcState.page, dlcState.pageSize); dlcState.page = _clampedPage; renderDlcGrouped(content, pageItems); const pagination = document.getElementById('sglv-dlc-pagination'); if (pagination) { // v1.9.47-fix: 补 onJump——DLC 翻页 5 个按钮全部走 onJump Host.renderPagination(pagination, 'sglv-dlc', dlcState.page, totalPages, groups.length, () => { dlcState.page--; renderDlcGamesList(); }, () => { dlcState.page++; renderDlcGamesList(); }, (p) => { dlcState.page = p; renderDlcGamesList(); }); } return; } } // 扁平视图 const { pageItems, totalPages, page: _clampedPage } = Host.paginate(list, dlcState.page, dlcState.pageSize); dlcState.page = _clampedPage; // v1.9.1: 先建空 grid 容器,再 rAF 分片 append(避免上千卡片 innerHTML 解析卡顿) let gridClass = 'sglv-card-grid'; let cardHtmls; if (dlcState.viewMode === 'card') { gridClass = 'sglv-card-grid'; cardHtmls = pageItems.map(d => { const clickUrl = 'https://store.steampowered.com/app/' + d.appid; const badges = dlcOwnedBadgeHtml(d.isOwned) + dlcTypeBadgeHtml(d.type) + dlcBundleBadgeHtml(d.bundleCount) + dlcPlayedBadgeHtml(d.playtime); const dimCls = d.isOwned ? '' : ' sglv-dlc-not-owned'; return '<div class="sglv-game-card' + dimCls + '" data-appid="' + d.appid + '" onclick="window.open(\'' + clickUrl + '\',\'_blank\')">' + '<div class="sglv-card-img-wrap">' + dlcPosterImg(d.appid, d.name) + '</div>' + '<div class="sglv-card-body">' + '<div class="sglv-card-name" title="' + Host.wlEscape(d.name) + '">' + Host.wlEscape(d.name) + '</div>' + '<div class="sglv-card-id">AppID: ' + d.appid + '</div>' + '<div class="sglv-badge-row">' + badges + '</div>' + (d.parentName ? '<div class="sglv-card-id" style="margin-top:2px">' + Host.wlEscape(d.parentName) + '</div>' : '') + '</div>' + '</div>'; }); } else if (dlcState.viewMode === 'cover') { gridClass = 'sglv-wl-cover-grid'; cardHtmls = pageItems.map(d => { const clickUrl = 'https://store.steampowered.com/app/' + d.appid; const badges = dlcOwnedBadgeHtml(d.isOwned) + dlcTypeBadgeHtml(d.type) + dlcBundleBadgeHtml(d.bundleCount) + dlcPlayedBadgeHtml(d.playtime); const dimCls = d.isOwned ? '' : ' sglv-dlc-not-owned'; return '<div class="sglv-wl-cover-card' + dimCls + '" data-appid="' + d.appid + '" onclick="window.open(\'' + clickUrl + '\',\'_blank\')">' + '<div class="sglv-wl-cover-img-wrap">' + dlcCapsuleImg(d.appid, d.name) + '</div>' + '<div class="sglv-wl-cover-body">' + '<div class="sglv-card-name" title="' + Host.wlEscape(d.name) + '">' + Host.wlEscape(d.name) + ' <span class="sglv-card-id-inline">' + d.appid + '</span></div>' + '<div class="sglv-info-row sglv-wl-price-row">' + badges + '</div>' + '</div>' + '</div>'; }); } else { gridClass = 'sglv-list-view'; cardHtmls = pageItems.map(d => { const clickUrl = 'https://store.steampowered.com/app/' + d.appid; const iconHtml = '<img class="sglv-list-icon" src="' + Host.getGameIconUrl(d.appid, '') + '" alt="' + Host.wlEscape(d.name) + '" loading="lazy" decoding="async" onerror="this.style.display=\'none\'">'; const badges = dlcOwnedBadgeHtml(d.isOwned) + dlcTypeBadgeHtml(d.type) + dlcBundleBadgeHtml(d.bundleCount) + dlcPlayedBadgeHtml(d.playtime); const dimCls = d.isOwned ? '' : ' sglv-dlc-not-owned'; return '<div class="sglv-list-item' + dimCls + '" data-appid="' + d.appid + '" onclick="window.open(\'' + clickUrl + '\',\'_blank\')">' + iconHtml + '<div class="sglv-list-info">' + '<div class="sglv-list-name">' + Host.wlEscape(d.name) + ' <span class="sglv-card-id-inline">' + d.appid + '</span></div>' + '<div class="sglv-list-meta">' + badges + (d.parentName ? ' · ' + Host.wlEscape(d.parentName) : '') + '</div>' + '</div>' + '</div>'; }); } content.innerHTML = `<div class="${gridClass}" id="sglv-dlc-grid"></div>`; const grid = document.getElementById('sglv-dlc-grid'); appendDlcCardsChunked(grid, cardHtmls); const pagination = document.getElementById('sglv-dlc-pagination'); if (pagination) { // v1.9.47-fix: 补 onJump——DLC 翻页 5 个按钮全部走 onJump Host.renderPagination(pagination, 'sglv-dlc', dlcState.page, totalPages, list.length, () => { dlcState.page--; renderDlcGamesList(); }, () => { dlcState.page++; renderDlcGamesList(); }, (p) => { dlcState.page = p; renderDlcGamesList(); }); } // v2.8.0: 统一封面链绑定(addEventListener,无跨上下文 inline onerror) bindRestrictedCoverLoaders(content); } // 分组视图渲染:父游戏折叠头 + DLC 卡片子网格 // v1.9.1: group 头一次性 innerHTML 写入(数量小),展开的 group 内卡片用 rAF 分片 append // 解决"几百个父游戏全展开 → 几千卡片 innerHTML 解析"卡死 function renderDlcGrouped(content, groups) { // 1. 先构造所有 group 的外层骨架(头 + 空 card-row 占位),用 data-group-idx 关联 const groupHtmls = groups.map((g, gi) => { const expanded = dlcState.expandedParents.has(String(g.parentApp)); const arrow = expanded ? '▼' : '▶'; return '<div class="sglv-dlc-group' + (expanded ? '' : ' collapsed') + '" data-group-idx="' + gi + '">' + '<div class="sglv-dlc-group-head" data-parent="' + (g.parentApp || 'null') + '">' + '<span class="sglv-dlc-arrow">' + arrow + '</span>' + '<span class="sglv-dlc-pname" title="' + Host.wlEscape(g.parentName || String(g.parentApp)) + '">' + Host.wlEscape(g.parentName || String(g.parentApp)) + '</span>' + '<span class="sglv-dlc-meta">' + g.ownedDlc + '/' + g.totalDlc + ' DLC</span>' + '<span class="sglv-dlc-pct">' + g.pct + '%</span>' + '</div>' + (expanded ? '<div class="sglv-dlc-card-row"></div>' : '') + '</div>'; }); content.innerHTML = groupHtmls.join(''); // 2. 绑定折叠/展开 content.querySelectorAll('.sglv-dlc-group-head').forEach(head => { head.addEventListener('click', () => { const p = head.dataset.parent; if (dlcState.expandedParents.has(p)) dlcState.expandedParents.delete(p); else dlcState.expandedParents.add(p); renderDlcGamesList(); }); }); // 3. 展开的 group:把 DLC 卡片 HTML 准备好,分片 append 到对应 card-row // 各 group 独立分片,互不阻塞(DOM 解析局部化) // v1.9.3: 横版封面布局,每行 4 列(替代原 8 列窄图) groups.forEach((g, gi) => { if (!dlcState.expandedParents.has(String(g.parentApp))) return; if (!g.dlcs || g.dlcs.length === 0) return; const cardHtmls = g.dlcs.map(d => { const clickUrl = 'https://store.steampowered.com/app/' + d.appid; const badges = dlcTypeBadgeHtml(d.type) + dlcBundleBadgeHtml(d.bundleCount) + dlcPlayedBadgeHtml(d.playtime); return '<div class="sglv-wl-cover-card sglv-dlc-group-cover" data-appid="' + d.appid + '" onclick="window.open(\'' + clickUrl + '\',\'_blank\')">' + '<div class="sglv-wl-cover-img-wrap">' + dlcCapsuleImg(d.appid, d.name) + '</div>' + '<div class="sglv-wl-cover-body">' + '<div class="sglv-card-name" title="' + Host.wlEscape(d.name) + '">' + Host.wlEscape(d.name) + ' <span class="sglv-card-id-inline">' + d.appid + '</span></div>' + '<div class="sglv-info-row sglv-wl-price-row">' + badges + '</div>' + '</div>' + '</div>'; }); const row = content.querySelector('.sglv-dlc-group[data-group-idx="' + gi + '"] .sglv-dlc-card-row'); if (row) appendDlcCardsChunked(row, cardHtmls); }); } // ==================== 捆绑包标签页 (v1.9.14) ==================== // 数据源: Host.getBundleCount(appid) — DLC 进包次数 (Barter.vg) // Host.getDlcParent(appid) — DLC→父游戏 appID // Host.getDlcsByParentMap() — 父游戏→DLC列表 反向映射 // 展示: 已拥有游戏中,包含进包 DLC 的父游戏列表,以及直接进包的游戏 // 构建捆绑包数据: 扫描所有已拥有父游戏的 DLC, 找出进包 DLC, 按父游戏分组 // ==================== 捆绑包标签页 ==================== // v2.5.0 关键修复:捆绑包数据源(Barter.vg bundle 数据库)原先**只能被动消费**—— // buildBundleData() 直接调 Host.getBundleCount(),而它在 bundleDbData 为 null 时恒返回 0。 // 原先只有「我的库存」tab 才会触发 loadBundleDatabase(),于是用户直接点捆绑包 tab // (不先进库存 tab)时:dlcsByParent 空 + bundleCount 全 0 → KPI 全 0 + 「暂无进包数据」。 // 修复:renderBundleTab 进入时主动 await Host.loadBundleDatabase(), // 并区分 loading / loadError / loaded 三态分别给出进度条、失败提示+重试按钮、真实空态。 const BUNDLE_LOAD_STAGES = { zh: { start: '正在加载进包数据…', fail: '进包数据加载失败', retry: '重试', notReady: '进包数据源未就绪,请点击重试' }, en: { start: 'Loading bundle data…', fail: 'Failed to load bundle data', retry: 'Retry', notReady: 'Bundle data source not ready, click retry' } }; const _bundleLang = () => (Host.isZh ? BUNDLE_LOAD_STAGES.zh : BUNDLE_LOAD_STAGES.en); /** 确保 Bundle 数据库就绪——已就绪直接返回 true;否则主动触发宿主加载并等待完成。 */ function ensureBundleDbReady() { // 已就绪 if (typeof Host.isBundleDbReady === 'function' ? Host.isBundleDbReady() : true) return Promise.resolve(true); // 宿主未暴露主动加载能力 → 降级:只能等「我的库存」tab 预热 if (typeof Host.loadBundleDatabase !== 'function') return Promise.resolve(false); bundleState.loading = true; bundleState.loadError = false; return Promise.resolve() .then(() => Host.loadBundleDatabase()) .then(() => { const ok = (typeof Host.isBundleDbReady === 'function') ? Host.isBundleDbReady() : true; bundleState.loading = false; bundleState.loadError = !ok; return ok; }) .catch(e => { console.warn('[SGLV-Bundle] loadBundleDatabase 失败:', e); bundleState.loading = false; bundleState.loadError = true; return false; }); } /** 强制重新加载 Bundle 数据库(重试按钮)——先清缓存再拉,避免负缓存 30min 内直接跳过。 */ function reloadBundleDb() { bundleState.loading = true; bundleState.loadError = false; bundleState.loaded = false; renderBundleKpi(); renderBundleList(); if (typeof Host.loadBundleDatabase !== 'function') { bundleState.loading = false; bundleState.loadError = true; renderBundleKpi(); renderBundleList(); return; } Promise.resolve().then(() => Host.loadBundleDatabase()).then(() => { bundleState.loading = false; const ok = (typeof Host.isBundleDbReady === 'function') ? Host.isBundleDbReady() : true; bundleState.loadError = !ok; if (ok) buildBundleData(); renderBundleKpi(); renderBundleList(); }).catch(e => { console.warn('[SGLV-Bundle] reloadBundleDb 失败:', e); bundleState.loading = false; bundleState.loadError = true; renderBundleKpi(); renderBundleList(); }); } function buildBundleData() { const t0 = performance.now(); const allOwned = Host.getOwnedGames() || []; const showFamilyShared = Host.getShowFamilyShared(); const pool = showFamilyShared ? allOwned : allOwned.filter(g => Host.isGameOwnedByMe(g)); // 构建 appid → game 映射 (O(1) 查找游戏名称/拥有状态) const gameMap = {}; pool.forEach(g => { if (g && g.appid) gameMap[String(g.appid)] = g; }); // 全量 owned 用于查父游戏名称 (即使父游戏不在当前 pool) allOwned.forEach(g => { if (g && g.appid && !gameMap[String(g.appid)]) gameMap[String(g.appid)] = g; }); const hasBundleCount = typeof Host.getBundleCount === 'function'; const dlcsByParent = (typeof Host.getDlcsByParentMap === 'function') ? Host.getDlcsByParentMap() : {}; const parentBundleMap = {}; // parentAppid → bundle item // 1. 遍历父游戏→DLC列表, 找出进包 DLC for (const [parentApp, dlcIds] of Object.entries(dlcsByParent)) { if (!Array.isArray(dlcIds)) continue; let totalBundle = 0; const bundledDlcs = []; for (const dlcId of dlcIds) { const bc = hasBundleCount ? Host.getBundleCount(dlcId) : 0; if (bc > 0) { totalBundle += bc; const dlcGame = gameMap[String(dlcId)]; bundledDlcs.push({ appid: dlcId, // v2.8.0: 未在库存里找到名字时不再回退成"DLC <id>"这种占位文案—— // 卡片上直接显示 appid + 无封面骨架,比"DLC 347150"更干净。 name: dlcGame ? dlcGame.name : '', bundleCount: bc, isOwned: !!dlcGame, playtime: dlcGame ? (dlcGame.playtime || 0) : 0, }); } } if (totalBundle > 0) { const parentGame = gameMap[String(parentApp)]; parentBundleMap[parentApp] = { appid: Number(parentApp), name: parentGame ? parentGame.name : ('App ' + parentApp), isOwned: !!parentGame && pool.some(g => String(g.appid) === String(parentApp)), totalBundle: totalBundle, dlcCount: bundledDlcs.length, dlcs: bundledDlcs, }; } } // 2. 检查已拥有游戏本身是否也进包 (getBundleCount 对主游戏可能也有效) for (const g of pool) { if (!g || !g.appid) continue; const bc = hasBundleCount ? Host.getBundleCount(g.appid) : 0; if (bc <= 0) continue; const key = String(g.appid); if (!parentBundleMap[key]) { // 主游戏直接进包, 且没有子 DLC 进包 parentBundleMap[key] = { appid: g.appid, name: g.name, isOwned: true, totalBundle: bc, dlcCount: 0, dlcs: [], }; } else { // 主游戏既自身进包, 子 DLC 也进包——把本体作为第一条 DLC 记录 parentBundleMap[key].totalBundle += bc; parentBundleMap[key].dlcs.unshift({ appid: g.appid, name: g.name + ' ' + (Host.isZh ? '(本体)' : '(Base)'), bundleCount: bc, isOwned: true, playtime: g.playtime || 0, }); parentBundleMap[key].dlcCount++; } } // 按累计进包数降序作为默认排序 bundleState.data = Object.values(parentBundleMap).sort((a, b) => b.totalBundle - a.totalBundle); bundleState.loaded = true; console.log(`[SGLV-Bundle] buildBundleData — ${bundleState.data.length} 个含进包游戏, 总进包 DLC ${bundleState.data.reduce((s, g) => s + g.dlcCount, 0)} 个, 耗时 ${Math.round(performance.now() - t0)}ms`); } // 过滤+排序 function getFilteredBundle() { let list = bundleState.data.slice(); // 搜索过滤 (游戏名 / appid / DLC名) if (bundleState.search) { const q = bundleState.search.toLowerCase(); list = list.filter(item => String(item.name).toLowerCase().includes(q) || String(item.appid).includes(q) || item.dlcs.some(d => String(d.name).toLowerCase().includes(q)) ); } // 排序 const sort = bundleState.sort; try { list.sort((a, b) => { if (sort === 'bundleDesc') return b.totalBundle - a.totalBundle || b.dlcCount - a.dlcCount; if (sort === 'bundleAsc') return a.totalBundle - b.totalBundle || a.dlcCount - b.dlcCount; if (sort === 'nameAsc') return _nameCollator.compare(a.name, b.name); if (sort === 'appidDesc') return b.appid - a.appid; if (sort === 'appidAsc') return a.appid - b.appid; return 0; }); } catch (e) { // 降级: 按 appid 排序 list.sort((a, b) => b.appid - a.appid); } return list; } // 渲染 KPI 卡片 function renderBundleKpi() { const el = document.getElementById('sglv-bundle-kpi'); if (!el) return; // v2.5.0: 加载中 / 失败态不再复用 DLC 的 KPI 骨架(原骨架与捆绑包字段无关,且失败时显示骨架误导用户) if (bundleState.loading) { el.innerHTML = ''; return; } if (bundleState.loadError) { el.innerHTML = ''; return; } if (!bundleState.loaded) { el.innerHTML = renderDlcKpiSkeletonHtml(); return; } const data = bundleState.data; const totalGames = data.length; const totalDlcs = data.reduce((s, g) => s + g.dlcCount, 0); const totalBundles = data.reduce((s, g) => s + g.totalBundle, 0); const ownedGames = data.filter(g => g.isOwned).length; const ownPct = totalGames > 0 ? Math.round(ownedGames / totalGames * 100) : 0; // v2.8.0: KPI 小卡 → HERO 仪表盘(与锁区/绝版同款,铺满浮窗宽度) // 捆绑包没有"分类"维度,右区改放两个规模指标(进包 DLC / 累计进包次数)的占比条。 const stats = [ { key: 'dlcs', label: Host.isZh ? '进包 DLC' : 'Bundled DLCs', count: totalDlcs, color: '#a78bfa' }, { key: 'times', label: Host.isZh ? '累计进包' : 'Bundle entries', count: totalBundles, color: '#f59e0b' }, ].filter(t => t.count > 0); const statSum = stats.reduce((s, t) => s + t.count, 0) || 1; el.innerHTML = '<div class="sglv-hero">' + '<div class="sglv-hero-left">' + '<div class="sglv-hero-title">' + (Host.isZh ? '含进包游戏' : 'Games w/ Bundles') + '</div>' + '<div class="sglv-hero-num">' + totalGames.toLocaleString() + '</div>' + '<div class="sglv-hero-progress"><div class="sglv-hero-progress-fill" style="width:' + ownPct + '%"></div></div>' + '<div class="sglv-hero-progress-cap">' + (Host.isZh ? '已拥有' : 'Owned') + ' ' + ownPct + '%</div>' + '<div class="sglv-hero-scope-row">' + '<div class="sglv-hero-scope' + (ownPct === 100 ? ' active' : '') + '">' + '<span class="sglv-hero-scope-val">' + ownedGames.toLocaleString() + '</span>' + '<span class="sglv-hero-scope-label">' + (Host.isZh ? '已拥有' : 'Owned') + '</span>' + '</div>' + '<div class="sglv-hero-scope' + (ownPct < 100 ? ' active' : '') + '">' + '<span class="sglv-hero-scope-val">' + (totalGames - ownedGames).toLocaleString() + '</span>' + '<span class="sglv-hero-scope-label">' + (Host.isZh ? '家庭共享' : 'Family') + '</span>' + '</div>' + '</div>' + '</div>' + '<div class="sglv-hero-right">' + '<div class="sglv-hero-right-head">' + (Host.isZh ? '进包规模' : 'Bundle scale') + '</div>' + stats.map(function (t) { const pct = Math.round(t.count / statSum * 100); return '<div class="sglv-hero-type">' + '<span class="sglv-hero-type-dot" style="background:' + t.color + '"></span>' + '<span class="sglv-hero-type-name">' + Host.wlEscape(t.label) + '</span>' + '<span class="sglv-hero-type-track"><span class="sglv-hero-type-fill" style="width:' + pct + '%;background:' + t.color + '"></span></span>' + '<span class="sglv-hero-type-count">' + t.count.toLocaleString() + '</span>' + '<span class="sglv-hero-type-pct">' + pct + '%</span>' + '</div>'; }).join('') + '</div>' + '</div>'; } // 渲染游戏列表 (卡片视图) function renderBundleList() { const content = document.getElementById('sglv-bundle-content'); if (!content) return; const clearPagination = () => { const p = document.getElementById('sglv-bundle-pagination'); if (p) p.innerHTML = ''; }; // v2.5.0: 三态判断顺序调整为 加载中 → 失败 → DLC 未就绪 → 构建中骨架 → 空态 → 列表。 // 原先「DLC 未就绪」在前且没有 loading 态,导致加载中直接闪「暂无进包数据」。 if (bundleState.loading) { content.innerHTML = '<div class="sglv-bundle-state">' + '<div class="sglv-progress" style="margin:0 0 10px"><div class="sglv-progress-fill sglv-progress-indeterminate"></div></div>' + '<div class="sglv-empty">' + Host.wlEscape(_bundleLang().start) + '</div>' + '</div>'; clearPagination(); return; } if (bundleState.loadError) { content.innerHTML = '<div class="sglv-bundle-state">' + '<div class="sglv-empty sglv-empty-error">' + Host.wlEscape(_bundleLang().fail) + '</div>' + '<div class="sglv-bundle-state-actions">' + '<button class="sglv-btn sglv-btn-secondary" id="sglv-bundle-retry">' + Host.wlEscape(_bundleLang().retry) + '</button>' + '</div>' + '</div>'; clearPagination(); const retry = content.querySelector('#sglv-bundle-retry'); if (retry) retry.addEventListener('click', () => reloadBundleDb()); return; } // 检查 DLC 数据库是否可用(进包数据依赖 Barter.vg DLC 反向映射) if (typeof Host.isDlcDbReady === 'function' && !Host.isDlcDbReady()) { content.innerHTML = '<div class="sglv-bundle-state">' + '<div class="sglv-empty">' + (Host.isZh ? 'DLC 数据库尚未加载,请先打开「DLC 收藏」标签页加载数据后返回。' : 'DLC database not loaded. Please open the "DLC" tab first to load data, then come back.') + '</div></div>'; clearPagination(); return; } if (!bundleState.loaded) { // 数据异步构建中——骨架占位(避免闪"暂无进包数据"空态) const skelCards = Array.from({ length: 12 }, () => '<div class="sglv-skel-game-card"><div class="sglv-skel-cover"></div><div class="sglv-skel-bar sglv-skel-card-name"></div><div class="sglv-skel-bar sglv-skel-card-meta"></div></div>' ).join(''); content.innerHTML = '<div class="sglv-skel-grid">' + skelCards + '</div>'; clearPagination(); return; } if (bundleState.data.length === 0) { content.innerHTML = '<div class="sglv-bundle-state">' + '<div class="sglv-empty">' + (Host.isZh ? '暂无进包数据' : 'No bundle data available') + '</div>' + '<div class="sglv-bundle-state-actions">' + '<button class="sglv-btn sglv-btn-secondary" id="sglv-bundle-retry">' + Host.wlEscape(_bundleLang().retry) + '</button>' + '</div></div>'; clearPagination(); const retry = content.querySelector('#sglv-bundle-retry'); if (retry) retry.addEventListener('click', () => reloadBundleDb()); return; } const list = getFilteredBundle(); if (list.length === 0) { content.innerHTML = '<div class="sglv-empty">' + (Host.isZh ? '无匹配结果' : 'No matching results') + '</div>'; clearPagination(); return; } const { pageItems, totalPages, page: _clampedPage } = Host.paginate(list, bundleState.page, bundleState.pageSize); bundleState.page = _clampedPage; const bundleBadgeStyle = 'background:rgba(245,158,11,0.15);color:#fbbf24;border:1px solid rgba(245,158,11,0.25);font-size:10px;padding:2px 6px;border-radius:3px;font-weight:700'; const dlcBadgeStyle = 'background:var(--sglv-accent-bg, rgba(167,139,250,0.15));color:var(--sglv-accent, #a78bfa);border:1px solid var(--sglv-accent-border, rgba(167,139,250,0.25));font-size:10px;padding:2px 6px;border-radius:3px;font-weight:700'; content.innerHTML = '<div class="sglv-bundle-wall">' + pageItems.map(item => { const q = (bundleState.search || '').toLowerCase(); const parentName = item.name || ('App ' + item.appid); const parentNameCls = q && parentName.toLowerCase().includes(q) ? ' sglv-highlight' : ''; const restId = 'sglv-bundle-rest-' + item.appid; // ---- 顶部标题条:主游戏退为上下文(左侧色条表示已拥有) ---- const head = '<div class="sglv-bundle-head' + (item.isOwned ? ' is-owned' : '') + '">' + '<div class="sglv-bundle-title-row" onclick="event.stopPropagation();window.open(\'https://store.steampowered.com/app/' + item.appid + '\',\'_blank\')" title="' + Host.wlEscape(parentName) + '">' + '<span class="sglv-bundle-title' + parentNameCls + '">' + Host.wlEscape(parentName) + '</span>' + '<span class="sglv-bundle-appid">' + item.appid + '</span>' + '</div>' + '<div class="sglv-bundle-meta">' + '<span class="sglv-bundle-stat"><span class="sglv-bundle-stat-ico">📦</span>' + item.totalBundle + (Host.isZh ? ' 进包' : ' bundles') + '</span>' + (item.dlcCount > 0 ? '<span class="sglv-bundle-sep"></span><span class="sglv-bundle-stat">' + item.dlcCount + ' DLC</span>' : '') + '</div>' + '</div>'; // ---- 主体:DLC 封面墙(3 列) ---- // 每个 DLC 有独立 appid,可直接走 restrictedCoverImg 拿真实封面; // 旧版用 24px 社区图标,DLC 的美术资源基本读不出来。 const renderTile = (d) => { const dlcUrl = 'https://store.steampowered.com/app/' + d.appid; const label = d.name || ('DLC ' + d.appid); const hitCls = q && d.name && d.name.toLowerCase().includes(q) ? ' is-hit' : ''; return '<div class="sglv-bundle-tile' + hitCls + (d.isOwned ? ' is-owned' : '') + '"' + ' onclick="event.stopPropagation();window.open(\'' + dlcUrl + '\',\'_blank\')"' + ' title="' + Host.wlEscape(label) + '\n📦 ' + d.bundleCount + (Host.isZh ? ' 进包' : ' bundles') + ' · ' + d.appid + '">' + restrictedCoverImg(d.appid, d.name, 'poster') + '<span class="sglv-bundle-tile-num">' + d.bundleCount + '</span>' + '</div>'; }; let wallHtml = ''; if (item.dlcs.length > 0) { const PREVIEW = 6; // 2 行 × 3 列 const preview = item.dlcs.slice(0, PREVIEW); const rest = item.dlcs.slice(PREVIEW); wallHtml = '<div class="sglv-bundle-tiles">' + preview.map(renderTile).join('') + '</div>' + (rest.length > 0 ? '<div class="sglv-bundle-tiles sglv-bundle-tiles-rest" id="' + restId + '" hidden>' + rest.map(renderTile).join('') + '</div>' + '<button class="sglv-bundle-expand" data-target="' + restId + '" data-count="' + rest.length + '">' + '<span class="sglv-bundle-expand-txt">' + (Host.isZh ? '展开其余 ' + rest.length + ' 个' : 'Show ' + rest.length + ' more') + '</span>' + '<span class="sglv-bundle-expand-caret">▾</span>' + '</button>' : ''); } else { // 主游戏本体直接进包、无子 DLC —— 用主游戏封面占位,保持卡片视觉完整 wallHtml = '<div class="sglv-bundle-tiles sglv-bundle-tiles-single">' + '<div class="sglv-bundle-tile is-owned" onclick="event.stopPropagation();window.open(\'https://store.steampowered.com/app/' + item.appid + '\',\'_blank\')" title="' + Host.wlEscape(parentName) + '">' + restrictedCoverImg(item.appid, parentName, 'poster') + '<span class="sglv-bundle-tile-badge">' + (Host.isZh ? '本体进包' : 'Base') + '</span>' + '</div></div>'; } return '<div class="sglv-bundle-card">' + head + wallHtml + '</div>'; }).join('') + '</div>'; // v2.8.0: DLC 墙折叠展开(事件委托,避免上千个监听器) content.querySelectorAll('.sglv-bundle-expand').forEach(btn => { btn.addEventListener('click', e => { e.stopPropagation(); const box = document.getElementById(btn.dataset.target); if (!box) return; const show = box.hasAttribute('hidden'); if (show) box.removeAttribute('hidden'); else box.setAttribute('hidden', ''); const n = box.querySelectorAll('.sglv-bundle-tile').length; btn.querySelector('.sglv-bundle-expand-txt').textContent = show ? (Host.isZh ? '收起' : 'Show less') : (Host.isZh ? '展开其余 ' + n + ' 个' : 'Show ' + n + ' more'); btn.querySelector('.sglv-bundle-expand-caret').textContent = show ? '▴' : '▾'; btn.classList.toggle('is-open', show); }); }); bindRestrictedCoverLoaders(content); // 分页 // v1.9.47-fix: 补 onJump——捆绑包翻页 5 个按钮全部走 onJump(参见主脚本 renderPagination) const pagination = document.getElementById('sglv-bundle-pagination'); if (pagination) { Host.renderPagination(pagination, 'sglv-bundle', bundleState.page, totalPages, list.length, () => { bundleState.page--; renderBundleList(); }, () => { bundleState.page++; renderBundleList(); }, (p) => { bundleState.page = p; renderBundleList(); }); } } // 捆绑包标签页主渲染入口 function renderBundleTab(parent) { const wrap = document.createElement('div'); wrap.className = 'sglv-psplus-wrap'; // KPI 区域 const kpi = document.createElement('div'); kpi.id = 'sglv-bundle-kpi'; wrap.appendChild(kpi); // 工具栏: 搜索 + 排序 const toolbar = document.createElement('div'); toolbar.className = 'sglv-toolbar'; const sortOptions = [ { key: 'bundleDesc', label: Host.isZh ? '进包数↓' : 'Bundles↓' }, { key: 'bundleAsc', label: Host.isZh ? '进包数↑' : 'Bundles↑' }, { key: 'nameAsc', label: Host.isZh ? '名称 A-Z' : 'Name A-Z' }, { key: 'appidDesc', label: Host.isZh ? 'AppID↓' : 'AppID↓' }, { key: 'appidAsc', label: Host.isZh ? 'AppID↑' : 'AppID↑' }, ]; toolbar.innerHTML = ` <input class="sglv-search" aria-label="搜索" id="sglv-bundle-search" placeholder="${Host.isZh ? '搜索游戏 / DLC…' : 'Search game / DLC…'}" value="${Host.wlEscape(bundleState.search)}"> <select class="sglv-sort-select" aria-label="排序方式" id="sglv-bundle-sort"> ${sortOptions.map(o => `<option value="${o.key}"${bundleState.sort === o.key ? ' selected' : ''}>${o.label}</option>`).join('')} </select> <div class="sglv-pagination" id="sglv-bundle-pagination"></div> `; wrap.appendChild(toolbar); // 游戏列表容器 const content = document.createElement('div'); content.className = 'sglv-content'; content.id = 'sglv-bundle-content'; wrap.appendChild(content); parent.appendChild(wrap); // 事件绑定 toolbar.querySelector('#sglv-bundle-search').addEventListener('input', _debounce((e) => { bundleState.search = e.target.value; bundleState.page = 1; renderBundleList(); }, 200)); toolbar.querySelector('#sglv-bundle-sort').addEventListener('change', (e) => { bundleState.sort = e.target.value; bundleState.page = 1; renderBundleList(); }); // v2.5.0: 数据异步加载链路—— // ① 先同步渲染 loading 态(进度条),不闪空态; // ② 主动确保 Bundle 数据库就绪(原先只在「我的库存」tab 触发,直接点捆绑包必然空); // ③ 同步读一次缓存,命中则立即出列表(秒开路径); // ④ 让出主线程后构建派生数据(buildBundleData 遍历库存×DLC 进包映射,是长任务)。 // 容器已随 tab 切换被移出文档时跳过本次构建。 renderBundleKpi(); renderBundleList(); ensureBundleDbReady().then(() => { // Bundle 数据库就绪后,DLC 反向映射也可能尚未就绪 → 触发一次 DLC 加载再重建 const dlcPromise = (typeof Host.isDlcDbReady === 'function' && !Host.isDlcDbReady() && typeof Host.loadDlcDatabase === 'function') ? Promise.resolve().then(() => Host.loadDlcDatabase()).catch(() => null) : Promise.resolve(); return dlcPromise.then(() => { if (!document.getElementById('sglv-bundle-kpi')) return; // 容器已卸载 buildBundleData(); renderBundleKpi(); renderBundleList(); }); }); } // ==================== 收藏浮窗管理(v2.7.0) ==================== function ensureCollectionPanel() { if (collectionPanelEl) return; collectionOverlayEl = document.createElement('div'); collectionOverlayEl.className = 'sglv-overlay sgc-overlay'; collectionOverlayEl.addEventListener('click', closeCollection); document.body.appendChild(collectionOverlayEl); collectionPanelEl = document.createElement('div'); collectionPanelEl.className = 'sglv-panel sgc-panel'; // v2.9.22: 重排页头——保留最左侧 Steam 图标作为品牌标识,6 个 tab 移入 header 内部(仿主面板 v2.9.22 紧凑风格) collectionPanelEl.innerHTML = ` <div class="sglv-header"> <div class="sglv-header-brand" title="${Host.isZh ? '游戏收藏' : 'Game Collection'}"><img src="https://steamcommunity.com/favicon.ico" alt="Steam" onerror="this.replaceWith(document.createTextNode('🎮'))"></div> <div class="sglv-tab-bar"> <button class="sglv-tab sglv-tab-btn active" data-tab="publisher">${Host.ICONS.grid}<span>${Host.T.tabPublisher}</span></button> <button class="sglv-tab sglv-tab-btn" data-tab="goty">${Host.ICONS.trophy}<span>${Host.T.tabGoty}</span></button> <button class="sglv-tab sglv-tab-btn" data-tab="delisted">${Host.ICONS.shield}<span>${Host.T.tabDelisted}</span></button> <button class="sglv-tab sglv-tab-btn" data-tab="blocked">${BLOCKED_LOCK_ICON_SVG}<span>${Host.T.tabBlocked}</span></button> <button class="sglv-tab sglv-tab-btn" data-tab="psplus">${Host.ICONS.playstation}<span>${Host.T.tabPsplus}</span></button> <button class="sglv-tab sglv-tab-btn" data-tab="epic">${Host.ICONS.epic}<span>${Host.T.tabEpic}</span></button> <button class="sglv-tab sglv-tab-btn" data-tab="dlc">${Host.ICONS.puzzle}<span>${Host.T.tabDlc}</span></button> <button class="sglv-tab sglv-tab-btn" data-tab="bundle">${Host.ICONS.package}<span>${Host.isZh ? '捆绑包' : 'Bundles'}</span></button> <button class="sglv-tab sglv-tab-btn" data-tab="humble">${Host.ICONS.gift}<span>${Host.T.tabHumble}</span></button> </div> <div class="sglv-header-actions"> <button class="sglv-header-btn sglv-home-btn" title="${Host.isZh ? '返回游戏库' : 'Back to Library'}">${Host.ICONS.home || '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg>'}</button> <button class="sglv-header-btn sglv-close-btn" title="✕">${Host.ICONS.close}</button> </div> </div> <div class="sglv-body" id="sgc-body"></div> `; document.body.appendChild(collectionPanelEl); collectionPanelEl.querySelector('.sglv-close-btn').addEventListener('click', closeCollection); // v1.8.0: home 按钮 → 关闭收藏浮窗并返回游戏库浮窗 collectionPanelEl.querySelector('.sglv-home-btn').addEventListener('click', () => { closeCollection(); document.dispatchEvent(new CustomEvent('sglv:open-library')); }); collectionPanelEl.querySelectorAll('.sglv-tab').forEach(tab => { tab.addEventListener('click', () => { _collectionActiveTab = tab.dataset.tab; collectionPanelEl.querySelectorAll('.sglv-tab').forEach(t => t.classList.remove('active')); tab.classList.add('active'); renderCollectionBody(); }); }); // v1.8.0: 系列分类数据异步加载完成后,若当前正在展示系列分类标签页则自动刷新 // v1.9.40: 移除 seriesFetchedAt 更新(更新时间文本已移除) // v1.9.37: 不再调用 renderCollectionBody(会闪骨架),改为直接刷新侧边栏+详情 document.addEventListener('sglv:series-data-loaded', () => { if (_collectionActiveTab === 'publisher' && collectionPanelEl && collectionPanelEl.classList.contains('sglv-show')) { refreshPublisherTabContent(); } }); // v2.9.91: 供应商数据远程更新事件——运行时检查发现远程版本有更新时自动刷新 // v1.9.37: 同上,改为直接刷新侧边栏+详情 document.addEventListener('sglv:supplier-data-loaded', () => { if (_collectionActiveTab === 'publisher' && collectionPanelEl && collectionPanelEl.classList.contains('sglv-show')) { refreshPublisherTabContent(); } }); // v2.9.90: 锁区数据远程更新事件——后台时间戳检查发现新版本或强制刷新后, // 自动更新收藏浮窗的 blockedState 并重新渲染(解决主面板刷新后收藏浮窗仍显示旧数据的问题) document.addEventListener('sglv:blocked-data-updated', (e) => { const detail = e.detail || {}; if (Array.isArray(detail.apps) && detail.apps.length > 0) { blockedState.apps = detail.apps; blockedState.source = detail.source || 'static'; blockedState.fetchedAt = detail.fetchedAt || ''; blockedState.loaded = true; // 同步写入永久缓存 _permCacheSet('blockedApps', { apps: blockedState.apps, source: blockedState.source, fetchedAt: blockedState.fetchedAt }); // v2.9.91: 同时刷新好评500分类数据(确保与主数据同步) loadTopRatedApps(true).finally(() => { if (_collectionActiveTab === 'blocked' && collectionPanelEl && collectionPanelEl.classList.contains('sglv-show')) { renderBlockedSections(); } }); // 若收藏浮窗打开且当前在锁区标签页,重新渲染 if (_collectionActiveTab === 'blocked' && collectionPanelEl && collectionPanelEl.classList.contains('sglv-show')) { renderBlockedSections(); } } }); // v2.9.22: 注入 sgc-panel 紧凑 CSS(仿主面板 v2.9.22:紧凑 header、tab 按钮圆角化、品牌图标、拖动 cursor、加载骨架) if (typeof GM_addStyle === 'function' && !collectionPanelEl._sgcStyled) { GM_addStyle(SGC_PANEL_CSS); collectionPanelEl._sgcStyled = true; } // v2.9.22: 绑定拖动(仅一次) if (!collectionPanelEl._sgcDraggable) { makeSgcDraggable(collectionPanelEl, collectionPanelEl.querySelector('.sglv-header')); collectionPanelEl._sgcDraggable = true; } // v2.7.0: 监听主脚本库存更新事件,收藏浮窗打开时自动刷新 document.addEventListener('sglv:games-updated', () => { if (collectionPanelEl && collectionPanelEl.classList.contains('sglv-show')) { renderCollectionBody(); } }); } // ==================== v2.11.50: Humble Choice 月包分析(借鉴 steam-friend-manager 1.5.2) ==================== // 数据源:@resource humbleChoiceData(SmallFork JSON,{months:[{choice,month,year,games:[{name,appid,date,publisher}]}]})。 // 性能:月份解析一次缓存;游戏列表放 <details> 内惰性展开(不渲染海报,纯文本行); // 分页 12 月/页;搜索/筛选走内存过滤 + 局部重渲。 const humbleState = { search: '', filter: 'all', page: 1, pageSize: 12 }; let _humbleMonthsCache = null; const HUMBLE_MON_ZH = { January: 1, February: 2, March: 3, April: 4, May: 5, June: 6, July: 7, August: 8, September: 9, October: 10, November: 11, December: 12 }; function humbleLoadMonths() { if (_humbleMonthsCache !== null) return _humbleMonthsCache; const raw = (typeof Host.getResourceText === 'function') ? Host.getResourceText('humbleChoiceData') : null; if (!raw) { _humbleMonthsCache = []; return _humbleMonthsCache; } try { const json = JSON.parse(raw); _humbleMonthsCache = Array.isArray(json.months) ? json.months : []; } catch (e) { console.warn('[SGLV-Humble] 数据解析失败:', e); _humbleMonthsCache = []; } return _humbleMonthsCache; } function renderHumbleTab(parent) { const wrap = document.createElement('div'); wrap.className = 'sglv-psplus-wrap'; parent.appendChild(wrap); const months = humbleLoadMonths(); if (!months.length) { wrap.innerHTML = `<div class="sglv-empty">${Host.T.humbleNoData}</div>`; return; } const ownedIds = Host.getActiveOwnedAppIds(); const isOwned = id => ownedIds.has(Number(id)) || ownedIds.has(String(id)); // 预计算每月统计与展示标签(一次遍历) months.forEach(m => { const games = Array.isArray(m.games) ? m.games : []; m._games = games; m._owned = games.filter(g => isOwned(g.appid)).length; const zh = HUMBLE_MON_ZH[m.month] || ''; m._label = Host.isZh ? `#${m.choice} ${m.year}年${zh}月` : `#${m.choice} ${m.month} ${m.year}`; }); wrap.innerHTML = ` <div id="sglv-humble-kpi"></div> <div class="sglv-toolbar"> <input class="sglv-search" aria-label="搜索" id="sglv-humble-search" placeholder="${Host.T.humbleSearch}" value="${Host.wlEscape(humbleState.search)}"> <div class="sglv-filter-bar" style="margin:0"> ${['all', 'owned', 'unowned'].map(f => `<button class="sglv-btn sglv-btn-secondary${humbleState.filter === f ? ' active' : ''}" data-humble-filter="${f}">${Host.T['humbleFilter' + f[0].toUpperCase() + f.slice(1)]}</button>`).join('')} </div> <button class="sglv-btn sglv-btn-secondary" id="sglv-humble-expand-all" title="${Host.isZh ? '全部展开' : 'Expand all'}">${Host.isZh ? '展开' : 'Expand'}</button> <button class="sglv-btn sglv-btn-secondary" id="sglv-humble-collapse-all" title="${Host.isZh ? '全部收起' : 'Collapse all'}">${Host.isZh ? '收起' : 'Collapse'}</button> <div class="sglv-pagination" id="sglv-humble-pagination"></div> </div> <div class="sglv-content" id="sglv-humble-content"></div> `; const kpiEl = wrap.querySelector('#sglv-humble-kpi'); const contentEl = wrap.querySelector('#sglv-humble-content'); const pagiEl = wrap.querySelector('#sglv-humble-pagination'); const totalGames = months.reduce((s, m) => s + m._games.length, 0); const totalOwned = months.reduce((s, m) => s + m._owned, 0); const ownedPct = totalGames > 0 ? Math.round(totalOwned / totalGames * 100) : 0; const unowned = totalGames - totalOwned; // v2.4.0: 填充 KPI sub 文本(之前 "游戏数" 和 "未拥有" sub 为空) kpiEl.innerHTML = ` <div class="sglv-trend-kpi-row"> <div class="sglv-trend-kpi-card blue"> <div class="sglv-trend-kpi-header"><span class="sglv-trend-kpi-icon">${Host.ICONS.gift}</span><span class="sglv-trend-kpi-label">${Host.T.humbleKpiMonths}</span></div> <div class="sglv-trend-kpi-value">${months.length}</div> <div class="sglv-trend-kpi-sub">Choice #1 ~ #${months[months.length - 1].choice}</div> </div> <div class="sglv-trend-kpi-card" style="border-left:3px solid #a78bfa"> <div class="sglv-trend-kpi-header"><span class="sglv-trend-kpi-icon" style="color:#a78bfa">${Host.ICONS.package}</span><span class="sglv-trend-kpi-label">${Host.T.humbleKpiGames}</span></div> <div class="sglv-trend-kpi-value">${totalGames.toLocaleString()}</div> <div class="sglv-trend-kpi-sub">${Host.isZh ? '历年总数' : 'Total all years'}</div> </div> <div class="sglv-trend-kpi-card" style="border-left:3px solid #4bb54f"> <div class="sglv-trend-kpi-header"><span class="sglv-trend-kpi-icon" style="color:#4bb54f;font-weight:700">✓</span><span class="sglv-trend-kpi-label">${Host.T.humbleKpiOwned}</span></div> <div class="sglv-trend-kpi-value">${totalOwned.toLocaleString()}</div> <div class="sglv-trend-kpi-sub" style="color:#4bb54f;font-weight:600">${ownedPct}%</div> </div> <div class="sglv-trend-kpi-card" style="border-left:3px solid #f59e0b"> <div class="sglv-trend-kpi-header"><span class="sglv-trend-kpi-icon" style="color:#f59e0b">${Host.ICONS.clock}</span><span class="sglv-trend-kpi-label">${Host.T.humbleKpiUnowned}</span></div> <div class="sglv-trend-kpi-value">${unowned.toLocaleString()}</div> <div class="sglv-trend-kpi-sub">${Host.isZh ? '待探索 ' + (totalGames ? Math.round(unowned / totalGames * 100) : 0) + '%' : 'To explore ' + (totalGames ? Math.round(unowned / totalGames * 100) : 0) + '%'}</div> </div> </div>`; const q = () => (humbleState.search || '').toLowerCase(); // v2.4.0: 月卡顶部展示 3-5 个游戏缩略 + 搜索高亮 + <details> 行升级(加封面 + 拥有徽章) const monthCardHtml = m => { const games = m._games; const pct = games.length ? Math.round(m._owned / games.length * 100) : 0; const titleCls = q() && m._label.toLowerCase().includes(q()) ? ' sglv-highlight' : ''; // v2.9.6: 顶部游戏缩略 —— 全量平铺(去掉"最多 5 个 + "+N" 截断", // 月包 8 款远没占满卡片宽度,右侧大片空白却让用户多点一次展开才看得全) const gameThumbsHtml = games.length > 0 ? '<div class="sglv-humble-game-thumbs">' + games.map(g => { const owned = isOwned(g.appid); const thumbCls = owned ? 'sglv-humble-game-thumb owned' : 'sglv-humble-game-thumb'; return '<div class="' + thumbCls + '" title="' + Host.wlEscape(g.name || '') + '">' + '<img src="' + Host.getGameIconUrl(g.appid, '') + '" alt="" loading="lazy" onerror="this.parentElement.classList.add(\'no-img\')">' + (owned ? '<span class="sglv-humble-game-thumb-mark">✓</span>' : '') + '</div>'; }).join('') + '</div>' : ''; // 展开行:每行加 24x24 封面 + 拥有徽章 + 搜索高亮 const rows = games.map(g => { const owned = isOwned(g.appid); const nameCls = q() && (g.name || '').toLowerCase().includes(q()) ? ' sglv-highlight' : ''; const icon = '<img class="sglv-humble-row-icon" src="' + Host.getGameIconUrl(g.appid, '') + '" alt="" loading="lazy" onerror="this.style.display=\'none\'">'; const ownedMark = owned ? '<span class="sglv-humble-row-owned">✓</span>' : '<span class="sglv-humble-row-missing">·</span>'; return '<div class="sglv-humble-row' + (owned ? ' owned' : '') + '">' + icon + ownedMark + '<span class="sglv-humble-row-name' + nameCls + '" title="' + Host.wlEscape(g.name || '') + '">' + Host.wlEscape(g.name || '') + '</span>' + (g.publisher ? '<span class="sglv-humble-row-pub">' + Host.wlEscape(g.publisher) + '</span>' : '') + (g.appid ? '<a class="sglv-humble-row-link" href="https://store.steampowered.com/app/' + g.appid + '" target="_blank" rel="noopener" onclick="event.stopPropagation()">' + g.appid + '</a>' : '') + '</div>'; }).join(''); return '<div class="sglv-humble-month-card">' + '<div class="sglv-humble-month-head">' + '<span class="sglv-humble-month-title' + titleCls + '">' + Host.wlEscape(m._label) + '</span>' + '<span class="sglv-humble-month-count">' + games.length + ' games</span>' + '<span class="sglv-humble-month-owned">' + Host.T.humbleOwnedIn + ' ' + m._owned + '/' + games.length + ' (' + pct + '%)</span>' + '</div>' + gameThumbsHtml + '<details class="sglv-humble-month-details">' + '<summary class="sglv-humble-month-summary">' + (Host.isZh ? '展开游戏列表' : 'Show games') + '</summary>' + '<div class="sglv-humble-month-rows">' + rows + '</div>' + '</details>' + '</div>'; }; const filteredMonths = () => { const qStr = q(); return months.filter(m => { if (humbleState.filter === 'owned' && m._owned === 0) return false; if (humbleState.filter === 'unowned' && m._owned > 0) return false; if (!qStr) return true; if (m._label.toLowerCase().includes(qStr)) return true; return m._games.some(g => (g.name || '').toLowerCase().includes(qStr) || (g.publisher || '').toLowerCase().includes(qStr) || String(g.appid) === qStr); }); }; const renderList = () => { const list = filteredMonths().sort((a, b) => b.choice - a.choice); const pg = Host.paginate(list, humbleState.page, humbleState.pageSize); humbleState.page = pg.page; contentEl.innerHTML = pg.pageItems.map(monthCardHtml).join(''); if (typeof Host.renderPagination === 'function') { Host.renderPagination(pagiEl, 'sglv-humble', pg.page, pg.totalPages, list.length, () => { humbleState.page--; renderList(); }, () => { humbleState.page++; renderList(); }, p => { humbleState.page = p; renderList(); }); } }; renderList(); // 搜索(防抖 200ms,复用 lib 内 _debounce) wrap.querySelector('#sglv-humble-search').addEventListener('input', _debounce(e => { humbleState.search = e.target.value; humbleState.page = 1; renderList(); }, 200)); // 拥有状态筛选 wrap.querySelectorAll('[data-humble-filter]').forEach(btn => { btn.addEventListener('click', () => { humbleState.filter = btn.dataset.humbleFilter; humbleState.page = 1; wrap.querySelectorAll('[data-humble-filter]').forEach(b => b.classList.remove('active')); btn.classList.add('active'); renderList(); }); }); // v2.4.0: 批量展开/收起 wrap.querySelector('#sglv-humble-expand-all').addEventListener('click', () => { contentEl.querySelectorAll('details.sglv-humble-month-details').forEach(d => { d.open = true; }); }); wrap.querySelector('#sglv-humble-collapse-all').addEventListener('click', () => { contentEl.querySelectorAll('details.sglv-humble-month-details').forEach(d => { d.open = false; }); }); } function renderCollectionBody() { const body = collectionPanelEl?.querySelector('#sgc-body'); if (!body) return; // v1.9.37: 移除切 tab 骨架屏,直接渲染内容(避免界面变形/闪烁) body.innerHTML = ''; if (_collectionActiveTab === 'delisted') renderDelistedTab(body); else if (_collectionActiveTab === 'blocked') renderBlockedTab(body); else if (_collectionActiveTab === 'goty') renderGotyTab(body); else if (_collectionActiveTab === 'publisher') renderPublisherTab(body); else if (_collectionActiveTab === 'psplus') renderPsplusTab(body); else if (_collectionActiveTab === 'epic') renderEpicTab(body); else if (_collectionActiveTab === 'dlc') renderDlcTab(body); else if (_collectionActiveTab === 'bundle') renderBundleTab(body); else if (_collectionActiveTab === 'humble') renderHumbleTab(body); _collectionBodyInitialized = true; } function openCollection() { ensureCollectionPanel(); collectionOverlayEl.classList.add('sglv-show'); collectionPanelEl.classList.add('sglv-show'); // v2.11.49: 打开性能优化——先同步显示面板+骨架占位,把当前 tab 的重构建 // (DOM 批量插入 + 数据遍历)推迟到下一帧,避免长任务阻塞打开动画造成卡顿 const body = collectionPanelEl && collectionPanelEl.querySelector('#sgc-body'); if (body && !body.childElementCount) { const skelLines = '<div class="sglv-skel-line lg"></div><div class="sglv-skel-line md"></div><div class="sglv-skel-line sm"></div>'; const kpiCards = Array.from({ length: 5 }, () => `<div class="sglv-trend-kpi-card skeleton">${skelLines}</div>`).join(''); const cards = Array.from({ length: 8 }, () => '<div class="sglv-skel-game-card"><div class="sglv-skel-cover"></div><div class="sglv-skel-bar sglv-skel-card-name"></div><div class="sglv-skel-bar sglv-skel-card-meta"></div></div>' ).join(''); body.innerHTML = `<div style="padding:16px 18px"><div class="sglv-trend-kpi-row">${kpiCards}</div><div class="sglv-skel-grid">${cards}</div></div>`; } requestAnimationFrame(() => requestAnimationFrame(renderCollectionBody)); } function closeCollection() { closeTgaNomsModal(); // v2.9.8: 关闭收藏面板时清理遗留的 TGA 提名弹窗 if (collectionOverlayEl) collectionOverlayEl.classList.remove('sglv-show'); if (collectionPanelEl) collectionPanelEl.classList.remove('sglv-show'); } function toggleCollection() { if (collectionPanelEl && collectionPanelEl.classList.contains('sglv-show')) closeCollection(); else openCollection(); } return { init, apiVersion, openCollection, closeCollection, toggleCollection, renderPublisherTab, renderDelistedTab, renderPsplusTab, renderEpicTab, renderBlockedTab, renderGotyTab, renderDlcTab, renderBundleTab, renderHumbleTab, // v2.6.0: 供封面 <img> 的 inline onerror 调用(appdetails API 兜底取图)。 // 必须在 window 上可见 —— inline handler 运行在页面上下文,只能通过 window.SGLVCollection 访问。 _fetchCoverFromApi: fetchCoverFromApi, restrictedCoverChain: restrictedCoverChain }; })(); // ==== SGLV-GAME-COLLECTION-INLINE-END ==== (function () { 'use strict'; if (window.self !== window.top) return; const _v = typeof GM_info !== 'undefined' ? GM_info.script.version : 'unknown'; try { var __PH = (typeof unsafeWindow !== 'undefined' && unsafeWindow.__PLUGIN_HOST__) || (typeof window !== 'undefined' && window.__PLUGIN_HOST__); if (__PH && typeof __PH.registerPlugin === 'function') { __PH.registerPlugin({ id: 'sglv', name: 'Steam 游戏库展示', family: 'core' }); } } catch (e) { } const sglvToast = { _el: null, _timer: null, _show(msg, type) { if (!this._el) { this._el = document.createElement('div'); this._el.id = 'sglv-toast'; this._el.setAttribute('data-sglv-plugin-ui', '1'); document.body.appendChild(this._el); } this._el.textContent = msg; this._el.className = 'sglv-toast' + (type ? ' sglv-toast-' + type : ''); requestAnimationFrame(() => this._el.classList.add('sglv-toast-show')); if (this._timer) clearTimeout(this._timer); this._timer = setTimeout(() => this._el.classList.remove('sglv-toast-show'), 2500); }, success(msg) { this._show(msg, 'success'); }, error(msg) { this._show(msg, 'error'); }, warning(msg) { this._show(msg, 'warning'); }, info(msg) { this._show(msg, 'info'); } }; function escHtml(s) { return String(s == null ? '' : s) .replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>') .replace(/"/g, '"') .replace(/'/g, '''); } function sglvCurrencySymbol(code) { try { const lib = (typeof unsafeWindow !== 'undefined' && unsafeWindow.SGLVCurrency) || window.SGLVCurrency; if (lib && lib.apiVersion === 1) return lib.symbolOf(code); } catch (e) { console.debug('[SGLV] SGLVCurrency.symbolOf 异常,降级内置 map', e); } const map = { 'CNY': '¥', 'USD': '$', 'EUR': '€', 'GBP': '£', 'JPY': '¥', 'KRW': '₩', 'INR': '₹', 'RUB': '₽', 'BRL': 'R$', 'TRY': '₺', 'AUD': 'A$', 'CAD': 'C$', 'HKD': 'HK$', 'TWD': 'NT$', 'SGD': 'S$', 'THB': '฿', 'MYR': 'RM', 'PHP': '₱', 'IDR': 'Rp', 'VND': '₫', 'MXN': 'Mex$', 'ARS': 'ARS$', 'CLP': 'CLP$', 'COP': 'COL$', 'PEN': 'S/', 'ZAR': 'R', 'UAH': '₴', 'PLN': 'zł', 'NOK': 'kr', 'CHF': 'CHF ', 'NZD': 'NZ$', 'SAR': 'SR', 'AED': 'AED ', 'ILS': '₪', 'KZT': '₸', 'QAR': 'QR', 'KWD': 'KD', 'CRC': '₡', 'UYU': '$U' }; return map[String(code || '').toUpperCase()] || '¥'; } let C = (typeof unsafeWindow !== 'undefined' && unsafeWindow.SGLVCore) || (typeof window !== 'undefined' ? window.SGLVCore : null) || null; if (!C) { console.error('[SGLV] 致命: SGLVCore 基础库未加载 (@require sglv-core.lib.js 拉取失败或被网络拦截)。脚本本次不初始化 — 请检查脚本管理器外部依赖/网络(可访问 update.greasyfork.org)后刷新重试。'); return; } const sglvNotifyNetFail = (C && typeof C.notifyNetFail === 'function') ? C.notifyNetFail.bind(C) : (label, err) => { try { console.warn('[SGLV] 数据获取失败(系统通知未接入):', label, (err && err.message) || err); } catch (e2) {} }; const CUR = (typeof unsafeWindow !== 'undefined' && unsafeWindow.SGLVCurrency) || window.SGLVCurrency; const hasSglvCurrency = !!(CUR && CUR.apiVersion === 1); if (!hasSglvCurrency) console.warn('[SGLV] SGLVCurrency 未加载或版本不匹配,货币增强功能降级为内置实现'); const nsKey = C.nsKey; const APIKEY_CONSENT_GM_KEY = nsKey('apikey_consent_v1'); let _apiKeyConsentState = ''; let _pendingFetchAfterKey = false; function _readApiKeyConsent() { if (!_apiKeyConsentState) { try { _apiKeyConsentState = GM_getValue(APIKEY_CONSENT_GM_KEY, '') || ''; } catch (e) { _apiKeyConsentState = ''; } } return _apiKeyConsentState; } function _writeApiKeyConsent(v) { _apiKeyConsentState = v; try { GM_setValue(APIKEY_CONSENT_GM_KEY, v); } catch (e) { } } function _initApiKeyConsent() { if (_readApiKeyConsent()) return; let legacy = false; try { if (typeof GM_listValues === 'function') { const keys = GM_listValues() || []; legacy = keys.some(k => typeof k === 'string' && k.indexOf('sglv') === 0); } } catch (e) { } _writeApiKeyConsent(legacy ? 'legacy' : 'pending'); console.log('[SGLV] API Key 同意门初始化:', _apiKeyConsentState); } _initApiKeyConsent(); function _hasApiKeyConsent() { const s = _readApiKeyConsent(); return s === 'agreed' || s === 'legacy'; } function _openApiKeyConsent() { return new Promise((resolve) => { const old = document.getElementById('sglv-apikey-consent'); if (old) { try { old.remove(); } catch (e) { } } const whyZh = [ 'Steam 官方 Web API 要求每个调用方携带一枚属于自己的 Key。没有 Key 就拿不到完整库存、游玩时长、家庭组归属与成就数据,只能退化到不完整的页面抓取。', 'Key 由 Steam 官方免费发放:<b>steamcommunity.com/dev/apikey</b> → 填一个域名 → 注册,即刻拿到。' ]; const whyEn = [ 'Steam\'s official Web API requires every caller to carry its own key. Without one you only get incomplete page scraping — no full inventory, playtime, family attribution or achievements.', 'The key is free from Steam: <b>steamcommunity.com/dev/apikey</b> → enter a domain → register.' ]; const riskZh = [ 'Key 只保存在你本机的浏览器脚本存储里(GM 存储),不上传、不跨设备同步。', 'Key 只会发往 Steam 官方接口 <b>api.steampowered.com</b>。本插件没有服务端,不做任何数据回流,也不会发往任何第三方。', '这枚 Key 的权限是「读取公开资料」(库存 / 时长 / 成就 / 公开档案),拿不到密码、邮箱、付款信息,也动不了你的库存资产。', '想撤销随时去 <b>steamcommunity.com/dev/apikey</b> 重置,重置后本插件立即失效。', '填 Key 是可选的:不填也能继续用,只是部分数据缺失。' ]; const riskEn = [ 'The key is stored only in your own browser (GM storage) — never uploaded, never synced across devices.', 'It is sent only to Steam\'s official endpoint <b>api.steampowered.com</b>. This script has no server, performs no data backhaul, and never talks to third parties.', 'Its scope is reading public profile data (library / playtime / achievements / public profile). It cannot read your password, email or payment details, and cannot touch your inventory.', 'Revoke it any time at <b>steamcommunity.com/dev/apikey</b> — this script stops working immediately.', 'Configuring a key is optional: you can keep using the script without it, with some data missing.' ]; const listZh = isZh, listEn = !isZh; const why = listZh ? whyZh : whyEn; const risk = listZh ? riskZh : riskEn; const ov = document.createElement('div'); ov.id = 'sglv-apikey-consent'; ov.className = 'sglv-apikey-consent'; ov.setAttribute('data-sglv-plugin-ui', '1'); ov.innerHTML = ` <div class="sglv-apikey-consent-card" role="dialog" aria-modal="true"> <div class="sglv-apikey-consent-head"> <span class="sglv-apikey-consent-title">🔐 ${isZh ? '配置 Steam API Key 前的说明' : 'Before you configure a Steam API Key'}</span> <button class="sglv-apikey-consent-close" title="✕" type="button">✕</button> </div> <div class="sglv-apikey-consent-body"> <div class="sglv-apikey-consent-sec"> <div class="sglv-apikey-consent-sec-title">${isZh ? '为什么需要' : 'Why it is needed'}</div> ${why.map(t => `<p class="sglv-apikey-consent-p">${t}</p>`).join('')} </div> <div class="sglv-apikey-consent-sec"> <div class="sglv-apikey-consent-sec-title">${isZh ? '风险与边界' : 'Risks & boundaries'}</div> <ul class="sglv-apikey-consent-ul"> ${risk.map(t => `<li>${t}</li>`).join('')} </ul> </div> <label class="sglv-apikey-consent-check"> <input type="checkbox" id="sglv-apikey-consent-check"> <span>${isZh ? '我已阅读并理解上述用途与风险,自行配置 API Key' : 'I have read and understood the above purpose and risks, and I choose to configure the key myself'}</span> </label> </div> <div class="sglv-apikey-consent-actions"> <button class="sglv-apikey-consent-btn ghost" id="sglv-apikey-consent-no" type="button">${isZh ? '不同意,不配置' : 'Decline'}</button> <button class="sglv-apikey-consent-btn primary" id="sglv-apikey-consent-yes" type="button" disabled>${isZh ? '同意并前往设置' : 'Agree & open settings'}</button> </div> </div>`; document.body.appendChild(ov); const chk = ov.querySelector('#sglv-apikey-consent-check'); const yes = ov.querySelector('#sglv-apikey-consent-yes'); const no = ov.querySelector('#sglv-apikey-consent-no'); const close = ov.querySelector('.sglv-apikey-consent-close'); let done = false; function finish(ok) { if (done) return; done = true; try { ov.remove(); } catch (e) { } try { document.removeEventListener('keydown', onKey); } catch (e) { } resolve(ok); } function onKey(e) { if (e.key === 'Escape') finish(false); } document.addEventListener('keydown', onKey); chk.addEventListener('change', () => { yes.disabled = !chk.checked; }); yes.addEventListener('click', () => { if (!chk.checked) return; _writeApiKeyConsent('agreed'); finish(true); }); no.addEventListener('click', () => finish(false)); close.addEventListener('click', () => finish(false)); ov.addEventListener('click', (e) => { if (e.target === ov) finish(false); }); }); } function _openApiKeySettings() { const openSettings = SGLV_API.openGlobalSettings; if (typeof openSettings === 'function') openSettings(); else showToast(isZh ? '设置页暂不可用,请刷新页面重试' : 'Settings unavailable — please reload'); setTimeout(() => { const el = document.getElementById('sglv-gs-apikey'); if (el) { try { el.scrollIntoView({ block: 'center' }); el.focus(); } catch (e) { } } }, 80); } async function _requireApiKeyConsent(opts) { opts = opts || {}; if (storage.getApiKey()) return true; const state = _readApiKeyConsent(); if (state === 'legacy' || state === 'agreed') return true; const ok = await _openApiKeyConsent(); if (!ok) { showToast(isZh ? '未同意配置 API Key,已停止加载数据' : 'Consent declined — data loading stopped'); return false; } _pendingFetchAfterKey = !!opts.thenFetch; _openApiKeySettings(); return false; } const BUNDLE_DB_CACHE_KEY_V2 = nsKey('bundle_db_cache_v2'); const sglvIDB = C.IDB; const CACHE_VERSION = { bundle_db: 2, dlc_db: 1, app_types: 1, cover_good_url: 1, game_name: 1, blocked_apps: 1, }; function ensureCacheVersions() { return C.ensureCacheVersions(CACHE_VERSION); } const negCacheGet = C.negCache.get.bind(C.negCache); const negCacheSet = C.negCache.set.bind(C.negCache); const negCacheClear = C.negCache.clear.bind(C.negCache); const StageProgress = C.StageProgress; const concurrentPool = C.concurrentPool; const sglvGmFetchRetry = C.gmFetchJson; const sglvGmFetchTextRetry = C.gmFetchText; function spinSvg(size = 34, cls = '') { if (cls) { return `<svg class="${cls}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>`; } return `<svg viewBox="0 0 24 24" width="${size}" height="${size}" fill="none" stroke="#a78bfa" stroke-width="2" style="animation:sglv-spin 1s linear infinite;"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>`; } function stageBarsHtml(total, active, wrapId = '') { const bars = Array.from({ length: total }, (_, i) => `<div class="sgis-load-stage-bar ${i + 1 < active ? 'done' : i + 1 === active ? 'active' : ''}"></div>` ).join(''); return `<div class="sgis-load-stages"${wrapId ? ` id="${wrapId}"` : ''}>${bars}</div>`; } function createLoadingHtml(text, size = 34, opts = null) { const svg = (!opts || opts.spin !== 'none') ? spinSvg(size, opts ? (opts.svgCls || '') : '') : ''; const textEl = opts && opts.textCls ? `<div class="${opts.textCls}">${text}</div>` : `<span style="font-size:13px;">${text}</span>`; let inner = svg + textEl; if (opts && opts.stages) { const active = opts.activeStage != null ? opts.activeStage : opts.stages.length; inner += stageBarsHtml(opts.stages.length, active, opts.stagesId || ''); } if (opts && opts.progress) { const p = opts.progress; const raw = p.pct != null ? p.pct : (p.total > 0 ? Math.round(p.current / p.total * 100) : 0); const pct = Math.max(0, Math.min(100, raw)); inner += `<div class="sglv-wl-loading-bar"><div class="sglv-wl-loading-bar-fill" style="width:${pct}%"></div></div>`; } if (opts && opts.sub != null) inner += `<div class="sglv-wl-loading-sub">${opts.sub}</div>`; if (opts && opts.cls) return `<div class="${opts.cls}">${inner}</div>`; return `<div style="display:flex;flex-direction:column;align-items:center;justify-content:center;padding:50px 20px;gap:12px;color:#8a9ba8;">${inner}</div>`; } const GAME_DB = (function() { try { const raw = JSON.parse(GM_getResourceText('gameDb') || '{}'); const { _meta, ...db } = raw; return db; } catch(e) { console.warn('[SGLV] GAME_DB 加载失败:', e); return {}; } })(); let _sglvDelistedDbCache = null; function _getDelistedDb() { if (_sglvDelistedDbCache !== null) return _sglvDelistedDbCache; try { _sglvDelistedDbCache = JSON.parse(GM_getResourceText('delistedData') || '{}'); } catch (e) { console.warn('[SGLV] DELISTED_DB 加载失败:', e); _sglvDelistedDbCache = {}; } return _sglvDelistedDbCache; } const SERIES_DATA_URL = 'https://fastly.jsdelivr.net/gh/SmallRob/steam-namespace@main/data/game_series.json'; const VEDIO_SERIES_DATA_URL = 'https://fastly.jsdelivr.net/gh/SmallRob/steam-namespace@main/data/steam_vediogame_selected.json'; const SERIES_DATA_URL_RAW = 'https://raw.githubusercontent.com/SmallRob/steam-namespace/main/data/game_series.json'; const VEDIO_SERIES_DATA_URL_RAW = 'https://raw.githubusercontent.com/SmallRob/steam-namespace/main/data/steam_vediogame_selected.json'; let seriesDb = {}; let _lastSeriesRaw = null; const GAME_DB_REMOTE_URL = 'https://fastly.jsdelivr.net/gh/SmallRob/steam-namespace@main/data/game-db-v1.2.json'; const GAME_DB_REMOTE_URL_RAW = 'https://raw.githubusercontent.com/SmallRob/steam-namespace/main/data/game-db-v1.2.json'; let supplierDbOverride = null; let supplierFetchedAt = ''; function groupSeriesData(seriesData) { const grouped = {}; const pushGame = (seriesName, item) => { const id = Number(item.appid) || 0; if (!id) return; if (!grouped[seriesName]) grouped[seriesName] = []; if (grouped[seriesName].some(g => g.id === id)) return; grouped[seriesName].push({ id, name: item.name || '', date: item.date || '', order: Number(item['序号'] || item.order) || 0, poster: item.poster || '', }); }; if (Array.isArray(seriesData)) { for (const item of seriesData) { const seriesName = String(item['系列'] || item.series || '').trim() || '未分类'; pushGame(seriesName, item); } } else if (seriesData && typeof seriesData === 'object') { for (const [seriesName, games] of Object.entries(seriesData)) { const name = String(seriesName).trim(); if (!name || !Array.isArray(games)) continue; for (const item of games) pushGame(name, item); } } for (const games of Object.values(grouped)) { games.sort((a, b) => (a.order || Infinity) - (b.order || Infinity)); } return grouped; } function mergeVedioSeriesData(mainData, vedioData) { if (!Array.isArray(vedioData) || !vedioData.length) return mainData; if (Array.isArray(mainData)) { return mainData.concat(vedioData.map(item => Object.assign({}, item, { 系列: '互动影游' }))); } if (mainData && typeof mainData === 'object') { const out = Object.assign({}, mainData); out['互动影游'] = vedioData; return out; } return { '互动影游': vedioData }; } function _sigHash(str) { let h = 5381; for (let i = 0; i < str.length; i++) h = ((h << 5) + h + str.charCodeAt(i)) | 0; return (h >>> 0).toString(36); } function _computeSeriesSignature(data) { if (Array.isArray(data)) { const ids = data.map(i => String(i && (i.appid != null ? i.appid : i.name) || '')).sort(); return `arr:${data.length}:${_sigHash(ids.join(','))}`; } else if (data && typeof data === 'object') { const keys = Object.keys(data).sort(); const parts = keys.map(k => { const arr = Array.isArray(data[k]) ? data[k] : []; const ids = arr.map(i => String(i && (i.appid != null ? i.appid : i.name) || '')).sort(); return `${k}(${arr.length}):${_sigHash(ids.join(','))}`; }); let totalGames = 0; for (const k of keys) if (Array.isArray(data[k])) totalGames += data[k].length; return `obj:${keys.length}:${totalGames}:${_sigHash(parts.join('|'))}`; } return 'empty'; } function _gmGetJsonRaw(url, timeout = 15000) { return sglvGmFetchRetry(url, { timeout, retries: 0, headers: { 'Accept': 'application/json' } }); } async function _fetchCollectionJson(cdnUrl, rawUrl, force) { const bust = force ? `?_sglv=${Date.now()}` : ''; try { return await sglvGmFetchRetry(cdnUrl + bust, { timeout: 15000 }); } catch (e) { return await _gmGetJsonRaw(rawUrl + bust, 15000); } } async function loadSeriesData(force = false, onProgress) { const report = (text) => { if (typeof onProgress === 'function') onProgress(text); }; if (!force) { const cached = cacheGet('seriesData'); if (cached) { const cachedDb = groupSeriesData(cached); if (Object.keys(cachedDb).length > 0) { seriesDb = cachedDb; _lastSeriesRaw = cached; document.dispatchEvent(new CustomEvent('sglv:series-data-loaded')); } } } try { report(isZh ? '正在加载系列数据…' : 'Fetching series data…'); const [mainRes, vedioRes] = await Promise.allSettled([ _fetchCollectionJson(SERIES_DATA_URL, SERIES_DATA_URL_RAW, force), _fetchCollectionJson(VEDIO_SERIES_DATA_URL, VEDIO_SERIES_DATA_URL_RAW, force), ]); let mainData = mainRes.status === 'fulfilled' ? mainRes.value : null; let vedioData = vedioRes.status === 'fulfilled' ? vedioRes.value : null; if (!mainData && !vedioData) { const err = (mainRes.status === 'rejected' ? mainRes.reason : vedioRes.reason); throw (err instanceof Error ? err : new Error('All series sources failed')); } if (mainRes.status === 'rejected') { console.warn('[SGLV] 系列分类主数据源加载失败:', mainRes.reason && mainRes.reason.message); const cachedMain = cacheGet('seriesData') || _lastSeriesRaw; if (cachedMain) mainData = cachedMain; else if (vedioData) mainData = {}; } if (vedioRes.status === 'rejected') { console.warn('[SGLV] 互动影游数据加载失败:', vedioRes.reason && vedioRes.reason.message); const cachedRaw = cacheGet('seriesData') || _lastSeriesRaw; if (cachedRaw && !Array.isArray(cachedRaw) && Array.isArray(cachedRaw['互动影游'])) { vedioData = cachedRaw['互动影游']; } } const data = mergeVedioSeriesData(mainData, vedioData); const freshDb = groupSeriesData(data); if (Object.keys(freshDb).length > 0) { _lastSeriesRaw = data; const newSig = _computeSeriesSignature(data); const cachedRaw = cacheGet('seriesData'); const oldSig = cachedRaw ? _computeSeriesSignature(cachedRaw) : ''; if (newSig !== oldSig) { cacheSet('seriesData', data, CACHE_TTL.seriesData); seriesDb = freshDb; document.dispatchEvent(new CustomEvent('sglv:series-data-loaded')); let totalGames = 0; for (const games of Object.values(freshDb)) totalGames += games.length; console.log(`[SGLV] 系列分类数据${force ? '强制' : ''}加载成功: ${totalGames} 条,共 ${Object.keys(freshDb).length} 个系列 (签名: ${newSig})`); return { status: 'updated', msg: isZh ? `系列: ${Object.keys(freshDb).length} 项已更新` : `Series: ${Object.keys(freshDb).length} items updated` }; } else { cacheSet('seriesData', data, CACHE_TTL.seriesData); console.log('[SGLV] 系列分类数据远程无变化,跳过更新'); return { status: 'nochange', msg: isZh ? '系列: 已是最新' : 'Series: up to date' }; } } return { status: 'nochange', msg: isZh ? '系列: 数据为空' : 'Series: empty' }; } catch (e) { console.warn('[SGLV] 系列分类数据加载失败:', e.message); sglvNotifyNetFail(isZh ? '收藏分类数据' : 'Collection data', e); return { status: 'error', msg: isZh ? `系列: ${e.message}` : `Series: ${e.message}` }; } } async function loadSupplierData(force = false, onProgress) { const report = (text) => { if (typeof onProgress === 'function') onProgress(text); }; if (!force) { const cached = cacheGet('supplierData'); if (cached && cached.db) { const cachedSig = _computeSupplierSignature(cached.raw || {}); const currentSig = _computeSupplierSignature(GAME_DB); if (cachedSig !== currentSig) { supplierDbOverride = cached.db; supplierFetchedAt = cached.fetchedAt || ''; document.dispatchEvent(new CustomEvent('sglv:supplier-data-loaded')); } } } try { report(isZh ? '正在加载供应商数据…' : 'Fetching supplier data…'); const data = await _fetchCollectionJson(GAME_DB_REMOTE_URL, GAME_DB_REMOTE_URL_RAW, force); const { _meta, ...db } = data; const newSig = _computeSupplierSignature(data); const oldSig = _computeSupplierSignature(GAME_DB); if (force || newSig !== oldSig) { supplierDbOverride = db; supplierFetchedAt = new Date().toISOString().slice(0, 10); cacheSet('supplierData', { db, raw: data, fetchedAt: supplierFetchedAt }, CACHE_TTL.seriesData); document.dispatchEvent(new CustomEvent('sglv:supplier-data-loaded')); const totalGames = Object.values(db).reduce((s, v) => { try { return s + Object.values(v).reduce((ss, arr) => ss + (Array.isArray(arr) ? arr.length : 0), 0); } catch { return s; } }, 0); console.log(`[SGLV] 供应商数据${force ? '强制' : ''}加载成功: ${Object.keys(db).length} 个供应商, ${totalGames} 个游戏 (签名: ${newSig})`); return { status: 'updated', msg: isZh ? `供应商: ${Object.keys(db).length} 项已更新` : `Supplier: ${Object.keys(db).length} items updated` }; } else { console.log('[SGLV] 供应商数据远程无变化,跳过更新'); return { status: 'nochange', msg: isZh ? '供应商: 已是最新' : 'Supplier: up to date' }; } } catch (e) { console.warn('[SGLV] 供应商数据加载失败:', e.message); sglvNotifyNetFail(isZh ? '供应商分类数据' : 'Supplier data', e); return { status: 'error', msg: isZh ? `供应商: ${e.message}` : `Supplier: ${e.message}` }; } } function _computeSupplierSignature(data) { if (!data || typeof data !== 'object') return 'empty'; const keys = Object.keys(data).filter(k => k !== '_meta'); let totalGames = 0; for (const k of keys) { if (typeof data[k] === 'object' && data[k] !== null) { for (const sk of Object.keys(data[k])) { if (Array.isArray(data[k][sk])) totalGames += data[k][sk].length; } } } return `pub:${keys.length}:${totalGames}`; } const _S = 'viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"'; const ICONS = { game: `<svg ${_S}><rect x="2" y="6" width="20" height="12" rx="2"/><path d="M12 12h.01"/><path d="M17 10h.01"/><path d="M17 14h.01"/><path d="M7 12h4"/><path d="M9 10v4"/></svg>`, grid: `<svg ${_S}><rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="14" y="3" width="7" height="7" rx="1.5"/><rect x="3" y="14" width="7" height="7" rx="1.5"/><rect x="14" y="14" width="7" height="7" rx="1.5"/></svg>`, list: `<svg ${_S}><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/></svg>`, close: `<svg ${_S}><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>`, settings: `<svg ${_S}><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>`, refresh: `<svg ${_S}><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>`, package: `<svg ${_S}><path d="M16.5 9.4L12 12 3.5 7.4"/><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><path d="M3.27 6.96L12 12.01l8.73-5.05"/><path d="M12 22.08V12"/></svg>`, trend: `<svg ${_S}><polyline points="23 6 13.5 15.5 8.5 10.5 1 18"/><polyline points="17 6 23 6 23 12"/></svg>`, download: `<svg ${_S}><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>`, barChart: `<svg ${_S}><line x1="12" y1="20" x2="12" y2="10"/><line x1="18" y1="20" x2="18" y2="4"/><line x1="6" y1="20" x2="6" y2="16"/></svg>`, shield: `<svg ${_S}><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>`, clock: `<svg ${_S}><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg>`, share: `<svg ${_S}><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/></svg>`, familyShare: `<svg ${_S}><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>`, heart: `<svg ${_S}><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>`, dollar: `<svg ${_S}><line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>`, tag: `<svg ${_S}><path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"/><line x1="7" y1="7" x2="7.01" y2="7"/></svg>`, gift: `<svg ${_S}><polyline points="20 12 20 22 4 22 4 12"/><rect x="2" y="7" width="20" height="5"/><line x1="12" y1="22" x2="12" y2="7"/><path d="M12 7H7.5a2.5 2.5 0 0 1 0-5C11 2 12 7 12 7z"/><path d="M12 7h4.5a2.5 2.5 0 0 0 0-5C13 2 12 7 12 7z"/></svg>`, library: `<svg ${_S}><path d="M16 6V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v2"/><rect x="2" y="6" width="20" height="12" rx="2"/><path d="M2 10h20"/></svg>`, calendar: `<svg ${_S}><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>`, rocket: `<svg ${_S}><path d="M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"/><path d="M12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.27 9.65-7 13-1.04.5-2 1-3 1z"/><path d="M9 12H4s.55-3.03 2-4c1.62-1.1 5-.5 5-.5"/><path d="M12 15v5s3.03-.55 4-2c1.1-1.62.5-5 .5-5"/></svg>`, cover: `<svg ${_S}><rect x="2" y="5" width="20" height="14" rx="2"/><circle cx="7.5" cy="10" r="1.5"/><polyline points="22 15 16 9 6 19"/></svg>`, playstation: `<svg viewBox="0 0 122.88 95.18" xmlns="http://www.w3.org/2000/svg" fill="#0070D1"><path d="M2.49,69.39c-4.61,3.07-3.07,8.9,6.75,11.67c10.13,3.38,21.18,4.3,31.93,2.46c0.61,0,1.23-0.31,1.54-0.31V72.76l-10.44,3.38c-3.99,1.23-7.98,1.54-11.97,0.61c-3.07-0.92-2.46-2.76,1.23-4.3l21.18-7.37V53.73L13.23,63.86C9.55,65.09,5.86,66.93,2.49,69.39L2.49,69.39z M73.71,23.33v29.78c12.59,6.14,22.41,0,22.41-15.96c0-16.27-5.83-23.64-22.72-29.47C64.5,4.6,55.29,1.84,46.08,0v88.73l21.49,6.45V20.57c0-3.38,0-5.83,2.46-4.91C73.41,16.58,73.71,19.96,73.71,23.33L73.71,23.33z M113.63,62.32c-8.9-3.07-18.42-4.3-27.63-3.38c-4.91,0.31-9.52,1.54-13.82,3.07l-0.92,0.31V74.3l19.96-7.37c3.99-1.23,7.98-1.54,11.97-0.61c3.07,0.92,2.46,2.76-1.23,4.3l-30.7,11.36v11.67l42.37-15.66c3.07-1.23,5.83-2.76,8.29-5.22C124.07,69.69,123.15,65.39,113.63,62.32L113.63,62.32z"/></svg>`, epic: `<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"><path d="M8 18 L8 52 C8 70 26 86 50 94 C74 86 92 70 92 52 L92 18 Z" fill="#1a1a1a" stroke="#3a3a3a" stroke-width="1.2"/><text x="50" y="47" text-anchor="middle" font-family="Arial Black, Helvetica, sans-serif" font-size="20" font-weight="900" fill="#fff" letter-spacing="0.5">EPIC</text><text x="50" y="65" text-anchor="middle" font-family="Arial, Helvetica, sans-serif" font-size="11" font-weight="700" fill="#fff" letter-spacing="1.2">GAMES</text></svg>`, card: `<svg ${_S}><rect x="3" y="6" width="18" height="13" rx="2"/><line x1="3" y1="11" x2="21" y2="11"/></svg>`, trophy: `<svg ${_S}><path d="M6 9H4.5a2.5 2.5 0 0 1 0-5H6"/><path d="M18 9h1.5a2.5 2.5 0 0 0 0-5H18"/><path d="M4 22h16"/><path d="M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22"/><path d="M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22"/><path d="M18 2H6v7a6 6 0 0 0 12 0V2Z"/></svg>`, profileLimited: `<svg ${_S}><circle cx="12" cy="8" r="4"/><path d="M4 21v-2a8 8 0 0 1 14-5.3"/><path d="M18 14l3 5.5h-6z" fill="currentColor" fill-opacity="0.3"/><path d="M18 16.5v2" stroke-width="2"/></svg>`, achievement: `<svg ${_S}><path d="M6 9H4.5a2.5 2.5 0 0 1 0-5H6"/><path d="M18 9h1.5a2.5 2.5 0 0 0 0-5H18"/><path d="M4 22h16"/><path d="M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22"/><path d="M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22"/><path d="M18 2H6v7a6 6 0 0 0 12 0V2Z"/></svg>`, cloud: `<svg ${_S}><path d="M18 10h-1.26A8 8 0 1 0 9 20h9a5 5 0 0 0 0-10z"/><polyline points="12 13 12 21"/><polyline points="8 17 12 21 16 17"/></svg>`, puzzle: `<svg ${_S}><path d="M19.439 7.85c-.049.318.14.547.457.615a1.5 1.5 0 1 1-1.29 2.73c-.317-.117-.6-.005-.74.293a1.5 1.5 0 1 1-2.73-1.29c.117-.317.005-.6-.293-.74a1.5 1.5 0 1 1 1.29-2.73c.318.117.6.005.74-.293a1.5 1.5 0 1 1 2.73 1.29c-.117.317-.005.6.293.74z"/><path d="M2 6a4 4 0 0 1 4-4h12a4 4 0 0 1 4 4v12a4 4 0 0 1-4 4H6a4 4 0 0 1-4-4z" opacity="0.3"/></svg>`, search: `<svg ${_S}><circle cx="11" cy="11" r="7"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>`, palette: `<svg ${_S}><path d="M12 22a10 10 0 1 1 10-10c0 1.66-1.34 3-3 3h-1.6a1.4 1.4 0 0 0-1 2.39c.36.36.6.86.6 1.41A2.2 2.2 0 0 1 12 22z"/><circle cx="7.5" cy="11.5" r="1" fill="#a78bfa"/><circle cx="10.5" cy="7.5" r="1" fill="#22d3ee"/><circle cx="15" cy="7.5" r="1" fill="#f472b6"/><circle cx="17" cy="11.5" r="1" fill="#fbbf24"/></svg>`, external: `<svg ${_S}><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>`, showcase: `<svg ${_S}><path d="M3 9l1-5h16l1 5"/><path d="M4 9v11a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1V9"/><line x1="9" y1="21" x2="9" y2="9"/><line x1="15" y1="21" x2="15" y2="9"/><line x1="3" y1="9" x2="21" y2="9"/></svg>`, edit: `<svg ${_S}><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>`, medal: `<svg ${_S}><circle cx="12" cy="9" r="6" fill="currentColor" fill-opacity="0.15"/><circle cx="12" cy="9" r="6"/><circle cx="12" cy="9" r="2" fill="currentColor"/><path d="M8.5 14L7 21l5-2.5L17 21l-1.5-7"/></svg>`, }; const CSS_STYLES = (typeof window.SGLVSharedCSS === 'string' && window.SGLVSharedCSS) || ''; GM_addStyle(CSS_STYLES); const CSS_ACHIEVEMENT =` /* ====== 主布局:左右分栏 ====== */ .sglv-ach-layout { display: flex; height: 100%; min-height: 400px; background: linear-gradient(180deg, #0d1117 0%, #161b22 100%); border-radius: 8px; overflow: hidden; } /* ====== 左侧边栏 ====== */ .sglv-ach-sidebar { width: 240px; flex-shrink: 0; display: flex; flex-direction: column; background: linear-gradient(180deg, rgba(22,27,34,0.95) 0%, rgba(13,17,23,0.95) 100%); border-right: 1px solid rgba(48,54,61,0.6); overflow-y: auto; } .sglv-ach-sidebar-header { display: flex; align-items: center; gap: 8px; padding: 16px 16px 12px; border-bottom: 1px solid rgba(48,54,61,0.4); } .sglv-ach-sidebar-title { font-size: 15px; font-weight: 700; color: #e6edf3; display: flex; align-items: center; gap: 6px; } .sglv-ach-sidebar-title svg { width: 20px; height: 20px; } /*用户信息区 — 参考设计渐变背景+径向光晕 */ .sglv-ach-user-card { padding: 20px 16px; display: flex; flex-direction: column; align-items: center; gap: 6px; border-bottom: 1px solid rgba(48,54,61,0.4); background: linear-gradient(160deg, rgba(99,102,241,0.08), rgba(168,85,247,0.04)); position: relative; overflow: hidden; } .sglv-ach-user-card::after { content: ''; position: absolute; inset: -50%; background: radial-gradient(circle, rgba(168,85,247,0.12), transparent 60%); pointer-events: none; } .sglv-ach-user-avatar { width: 64px; height: 64px; border-radius: 50%; background: linear-gradient(135deg, #fde047, #d97706); display: flex; align-items: center; justify-content: center; flex-shrink: 0; position: relative; box-shadow: 0 8px 24px rgba(251,191,36,0.35); z-index: 1; } .sglv-ach-user-avatar svg { width: 32px; height: 32px; } .sglv-ach-user-level { position: absolute; bottom: -4px; right: -4px; background: #1c2128; border: 2px solid #fde047; border-radius: 10px; padding: 0 5px; font-size: 10px; font-weight: 700; color: #fde047; line-height: 1.4; } .sglv-ach-user-name { font-size: 14px; font-weight: 700; color: #e6edf3; position: relative; z-index: 1; } .sglv-ach-user-pts { font-size: 11px; color: #8b949e; position: relative; z-index: 1; } .sglv-ach-user-pts strong { color: #fbbf24; font-weight: 700; } /*分类导航 — 参考设计图标背景+激活渐变 */ .sglv-ach-nav { padding: 8px 0; flex: 1; } .sglv-ach-nav-label { font-size: 10px; font-weight: 700; color: #6e7681; text-transform: uppercase; letter-spacing: 0.05em; padding: 8px 16px 4px; } .sglv-ach-nav-item { display: flex; align-items: center; gap: 10px; padding: 8px 12px; margin: 0 8px; cursor: pointer; transition: all 0.15s; border-radius: 10px; } .sglv-ach-nav-item:hover { background: rgba(99,102,241,0.08); } .sglv-ach-nav-item.active { background: linear-gradient(90deg, rgba(99,102,241,0.2), transparent); color: #fff; } .sglv-ach-nav-item-icon { width: 28px; height: 28px; border-radius: 8px; overflow: hidden; flex-shrink: 0; background: rgba(99,102,241,0.12); display: flex; align-items: center; justify-content: center; } .sglv-ach-nav-item-icon svg { width: 18px; height: 18px; } .sglv-ach-nav-item-name { font-size: 12px; font-weight: 600; color: #c9d1d9; flex: 1; } .sglv-ach-nav-item.active .sglv-ach-nav-item-name { color: #fff; font-weight: 700; } .sglv-ach-nav-item-badge { font-size: 10px; font-weight: 700; padding: 2px 8px; border-radius: 6px; flex-shrink: 0; background: rgba(99,102,241,0.15); color: #c7d2fe; } .sglv-ach-nav-item.active .sglv-ach-nav-item-badge { background: #6366f1; color: #fff; } .sglv-ach-nav-item-badge.complete { background: rgba(63,185,80,0.15); color: #3fb950; } .sglv-ach-nav-item-badge.partial { background: rgba(56,139,253,0.15); color: #58a6ff; } .sglv-ach-nav-item-badge.none { background: rgba(255,255,255,0.06); color: #6e7681; } /*侧边栏最近解锁 — 参考设计mini-icon渐变 */ .sglv-ach-sidebar-recent { padding: 8px 0 12px; border-top: 1px solid rgba(48,54,61,0.4); } .sglv-ach-sidebar-recent-label { font-size: 10px; font-weight: 700; color: #6e7681; text-transform: uppercase; letter-spacing: 0.05em; padding: 8px 16px 4px; } .sglv-ach-sidebar-recent-item { display: flex; align-items: center; gap: 10px; padding: 6px 16px; transition: background 0.15s; cursor: pointer; border-radius: 8px; margin: 0 8px; } .sglv-ach-sidebar-recent-item:hover { background: rgba(99,102,241,0.06); } .sglv-ach-sidebar-recent-icon { width: 32px; height: 32px; border-radius: 8px; overflow: hidden; flex-shrink: 0; background: linear-gradient(135deg, #6366f1, #a78bfa); display: flex; align-items: center; justify-content: center; } .sglv-ach-sidebar-recent-icon svg { width: 20px; height: 20px; } .sglv-ach-sidebar-recent-info { flex: 1; min-width: 0; } .sglv-ach-sidebar-recent-name { font-size: 11px; font-weight: 600; color: #d2a8ff; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .sglv-ach-sidebar-recent-time { font-size: 9px; color: #6e7681; margin-top: 1px; } .sglv-ach-sidebar-recent-empty { font-size: 11px; color: #6e7681; padding: 8px 16px; opacity: 0.6; } /* ====== 右侧主内容区 ====== */ .sglv-ach-main { flex: 1; display: flex; flex-direction: column; overflow: hidden; } /*统计概览区 — 参考设计玻璃态容器 */ .sglv-ach-header { display: flex; align-items: center; gap: 20px; padding: 20px 24px; background: linear-gradient(135deg, rgba(30,41,59,0.6), rgba(15,23,42,0.6)); backdrop-filter: blur(20px); border-bottom: 1px solid rgba(99,102,241,0.12); flex-shrink: 0; } .sglv-ach-ring-wrap { position: relative; width: 88px; height: 88px; flex-shrink: 0; } .sglv-ach-ring-svg { width: 100%; height: 100%; transform: rotate(-90deg); } .sglv-ach-ring-bg { fill: none; stroke: rgba(99,102,241,0.12); stroke-width: 6; } .sglv-ach-ring-fill { fill: none; stroke: url(#ach-ring-grad); stroke-width: 6; stroke-linecap: round; transition: stroke-dashoffset 0.8s cubic-bezier(0.4,0,0.2,1); } .sglv-ach-ring-text { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; } .sglv-ach-ring-val { font-size: 22px; font-weight: 800; background: linear-gradient(135deg, #22d3ee, #a78bfa, #fbbf24); -webkit-background-clip: text; background-clip: text; -webkit-text-fill-color: transparent; line-height: 1; } .sglv-ach-ring-label { font-size: 8px; color: #64748b; margin-top: 2px; letter-spacing: 0.02em; white-space: nowrap; } /* === 成就 KPI 卡片复用 sglv-playtime-kpi-card 统一风格 === */ .sglv-ach-kpi-row { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; flex: 1; min-width: 0; } /* ====== v2.44.0:Hero 总览(真实口径) + 游戏成就矩阵 + 自定义徽章架 ====== */ .sglv-ach-header-v2 { flex-direction: column; align-items: stretch; gap: 12px; padding: 16px 24px 14px; } .sglv-ach-hero-top { display: flex; align-items: center; gap: 20px; } .sglv-ach-kpi-row-6 { grid-template-columns: repeat(6, minmax(0, 1fr)); } .sglv-ach-hero-strip { display: flex; align-items: center; gap: 22px; flex-wrap: wrap; padding-top: 10px; border-top: 1px solid rgba(48,54,61,0.45); } .sglv-ach-hero-item { display: flex; align-items: baseline; gap: 7px; font-size: 11px; min-width: 0; } .sglv-ach-hero-item .lbl { color: #6e7681; font-weight: 600; white-space: nowrap; } .sglv-ach-hero-item .val { color: #e6edf3; font-weight: 700; font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 280px; } .sglv-ach-nav-item-icon { color: #a5b4fc; } .sglv-ach-sidebar-recent-dot { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; margin: 0 4px; } /* 子视图切换(游戏成就 / 聚合分析) */ .sglv-ach-subview { display: none; } .sglv-ach-subview.active { display: block; } /* 游戏成就矩阵 —— v2.44.0 新增的主视图 */ .sglv-ach-matrix { display: flex; flex-direction: column; gap: 6px; } /* 空态卡片 —— 空态必须读成「下一步做什么」,不能只给一行淡灰小字 */ .sglv-ach-empty-card { padding: 24px 20px; border-radius: 14px; background: rgba(13,17,23,0.5); border: 1px dashed rgba(74,85,104,0.7); text-align: center; } .sglv-ach-empty-title { font-size: 13.5px; font-weight: 700; color: #c9d1d9; margin-bottom: 6px; } .sglv-ach-empty-hint { font-size: 11.5px; color: #8b949e; line-height: 1.7; } .sglv-ach-empty-cta { margin-top: 14px; padding: 8px 20px; border-radius: 10px; border: 1px solid rgba(34,211,238,0.42); background: rgba(34,211,238,0.12); color: #67e8f9; font-size: 12px; font-weight: 700; cursor: pointer; transition: all 0.15s; font-family: inherit; } .sglv-ach-empty-cta:hover { background: rgba(34,211,238,0.22); border-color: rgba(34,211,238,0.65); } .sglv-ach-matrix-row { display: flex; align-items: center; gap: 12px; padding: 9px 12px; border-radius: 10px; background: rgba(13,17,23,0.45); border: 1px solid rgba(48,54,61,0.45); transition: background 0.15s, border-color 0.15s; cursor: pointer; } .sglv-ach-matrix-row:hover { background: rgba(34,211,238,0.07); border-color: rgba(34,211,238,0.32); } .sglv-ach-matrix-row:focus-visible { outline: 2px solid rgba(34,211,238,0.6); outline-offset: 1px; } /* v2.44.2:矩阵工具栏(借鉴游戏收藏模块的「完成度 / 排序 / 视图」工具栏) */ .sglv-ach-mx { display: flex; flex-direction: column; gap: 10px; } .sglv-ach-mx-toolbar { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; } .sglv-ach-mx-group { display: flex; align-items: center; gap: 3px; padding: 3px; border-radius: 9px; background: rgba(13,17,23,0.5); border: 1px solid rgba(48,54,61,0.6); } .sglv-ach-mx-seg { padding: 5px 11px; border-radius: 7px; border: none; background: transparent; color: #8b949e; font-size: 11.5px; font-weight: 700; cursor: pointer; transition: all 0.15s; font-family: inherit; white-space: nowrap; } .sglv-ach-mx-seg:hover { color: #e6edf3; background: rgba(99,102,241,0.12); } .sglv-ach-mx-seg.active { color: #fff; background: linear-gradient(135deg, rgba(34,211,238,0.2), rgba(99,102,241,0.18)); box-shadow: inset 0 1px 0 rgba(255,255,255,0.06); } .sglv-ach-mx-search { flex: 1; min-width: 130px; max-width: 260px; padding: 6px 12px; border-radius: 9px; border: 1px solid rgba(48,54,61,0.7); background: rgba(13,17,23,0.55); color: #e6edf3; font-size: 12px; outline: none; font-family: inherit; } .sglv-ach-mx-search:focus { border-color: rgba(34,211,238,0.5); } .sglv-ach-mx-search::placeholder { color: #6e7681; } .sglv-ach-mx-meta { font-size: 11px; color: #6e7681; } /* 列表行:游戏封面缩略图(capsule 231x87 比例) */ .sglv-ach-matrix-ico { width: 92px; height: 34px; flex-shrink: 0; border-radius: 6px; overflow: hidden; background: rgba(13,17,23,0.6); } .sglv-ach-matrix-ico img { width: 100%; height: 100%; object-fit: cover; display: block; } /* 卡片视图 */ .sglv-ach-mx-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 12px; } .sglv-ach-mx-card { display: flex; flex-direction: column; gap: 6px; padding: 8px; border-radius: 12px; background: rgba(13,17,23,0.5); border: 1px solid rgba(48,54,61,0.5); cursor: pointer; transition: background 0.15s, border-color 0.15s; } .sglv-ach-mx-card:hover { background: rgba(34,211,238,0.06); border-color: rgba(34,211,238,0.3); } .sglv-ach-mx-card:focus-visible { outline: 2px solid rgba(34,211,238,0.6); outline-offset: 1px; } .sglv-ach-mx-card-cover { width: 100%; aspect-ratio: 2 / 3; border-radius: 8px; overflow: hidden; background: rgba(13,17,23,0.7); } .sglv-ach-mx-card-cover img { width: 100%; height: 100%; object-fit: cover; display: block; } .sglv-ach-mx-card-name { font-size: 12px; font-weight: 600; color: #e6edf3; line-height: 1.35; max-height: 33px; overflow: hidden; } .sglv-ach-mx-card-bar { height: 4px; border-radius: 3px; background: rgba(48,54,61,0.7); overflow: hidden; } .sglv-ach-mx-card-bar i { display: block; height: 100%; background: linear-gradient(90deg, #22d3ee, #6366f1); border-radius: 3px; } .sglv-ach-mx-card-meta { font-size: 10px; color: #8b949e; } .sglv-ach-mx-card .sglv-ach-matrix-tags { justify-content: flex-start; margin-top: 2px; } .sglv-ach-matrix-ring { position: relative; width: 38px; height: 38px; flex-shrink: 0; } .sglv-ach-matrix-ring svg { width: 100%; height: 100%; transform: rotate(-90deg); } .sglv-ach-matrix-ring .bg { fill: none; stroke: rgba(99,102,241,0.15); stroke-width: 3; } .sglv-ach-matrix-ring .fill { fill: none; stroke: url(#ach-ring-grad) #22d3ee; stroke-width: 3; stroke-linecap: round; } .sglv-ach-matrix-ring-t { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; font-size: 10px; font-weight: 700; color: #e6edf3; } .sglv-ach-matrix-info { flex: 1; min-width: 0; } .sglv-ach-matrix-name { font-size: 13px; font-weight: 600; color: #e6edf3; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .sglv-ach-matrix-meta { font-size: 11px; color: #8b949e; margin-top: 2px; } .sglv-ach-matrix-tags { display: flex; align-items: center; gap: 6px; flex-shrink: 0; flex-wrap: wrap; justify-content: flex-end; } .sglv-ach-matrix-tag { font-size: 9px; font-weight: 700; padding: 2px 7px; border-radius: 5px; letter-spacing: 0.04em; white-space: nowrap; } .sglv-ach-matrix-tag.perfect { background: rgba(63,185,80,0.16); color: #3fb950; } .sglv-ach-matrix-tag.rare { background: rgba(168,85,247,0.16); color: #c084fc; } .sglv-ach-matrix-tag.done { background: rgba(251,191,36,0.14); color: #fbbf24; } .sglv-ach-matrix-tag.muted { background: rgba(110,118,129,0.18); color: #8b949e; } /* 自定义成就徽章架(弱化后的位置:页面底部、可折叠) */ .sglv-ach-shelf { flex-shrink: 0; border-top: 1px solid rgba(48,54,61,0.5); background: rgba(13,17,23,0.5); } .sglv-ach-shelf-head { display: flex; align-items: center; gap: 10px; width: 100%; padding: 10px 24px; background: none; border: none; cursor: pointer; text-align: left; color: #8b949e; font-family: inherit; } .sglv-ach-shelf-head:hover { background: rgba(99,102,241,0.06); } .sglv-ach-shelf-title { font-size: 12px; font-weight: 700; color: #c9d1d9; } .sglv-ach-shelf-summary { font-size: 11px; color: #6e7681; flex: 1; } .sglv-ach-shelf-caret { font-size: 11px; color: #8b949e; } .sglv-ach-shelf-body { padding: 0 24px 14px; display: none; } .sglv-ach-shelf.open .sglv-ach-shelf-body { display: block; } .sglv-ach-shelf-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(104px, 1fr)); gap: 8px; } .sglv-ach-badge { display: flex; flex-direction: column; align-items: center; gap: 4px; padding: 8px 6px; border-radius: 10px; background: rgba(13,17,23,0.5); border: 1px solid rgba(48,54,61,0.4); opacity: 0.5; } .sglv-ach-badge.on { opacity: 1; border-color: rgba(99,102,241,0.35); } .sglv-ach-badge-icon { width: 40px; height: 40px; } .sglv-ach-badge-icon svg { width: 100%; height: 100%; } .sglv-ach-badge-name { font-size: 10px; color: #c9d1d9; text-align: center; line-height: 1.3; max-height: 26px; overflow: hidden; } .sglv-ach-badge-bar { width: 100%; height: 3px; border-radius: 2px; background: rgba(48,54,61,0.7); overflow: hidden; } .sglv-ach-badge-bar i { display: block; height: 100%; background: linear-gradient(90deg, #22d3ee, #6366f1); border-radius: 2px; } .sglv-ach-shelf-foot { display: flex; align-items: center; gap: 12px; margin-top: 10px; font-size: 10px; color: #6e7681; } .sglv-ach-shelf-foot span { flex: 1; } @media (max-width: 900px) { .sglv-ach-kpi-row-6 { grid-template-columns: repeat(3, minmax(0, 1fr)); } } @media (max-width: 720px) { .sglv-ach-header-v2 { padding: 12px 14px 10px; } .sglv-ach-hero-top { flex-direction: column; align-items: stretch; gap: 12px; } .sglv-ach-shelf-head, .sglv-ach-shelf-body { padding-left: 14px; padding-right: 14px; } } .sglv-ach-reset-btn { padding: 8px 16px; border-radius: 10px; border: 1px solid rgba(239,68,68,0.3); background: rgba(239,68,68,0.08); color: #fca5a5; cursor: pointer; font-size: 12px; transition: all 0.2s; flex-shrink: 0; } .sglv-ach-reset-btn:hover { background: rgba(239,68,68,0.18); border-color: rgba(239,68,68,0.5); } /*Steam 平台成就/徽章数横幅 */ .sglv-ach-steam-banner { display: flex; align-items: center; gap: 12px; padding: 10px 16px; margin-bottom: 10px; background: linear-gradient(135deg, rgba(34,211,238,0.08), rgba(251,191,36,0.06), rgba(139,92,246,0.04)); border: 1px solid rgba(34,211,238,0.15); border-radius: 12px; position: relative; overflow: hidden; } .sglv-ach-steam-banner::after { content: ''; position: absolute; top: -20px; right: -20px; width: 80px; height: 80px; background: radial-gradient(circle, rgba(251,191,36,0.12), transparent 60%); pointer-events: none; } .sglv-ach-steam-banner-icon { width: 36px; height: 36px; border-radius: 10px; flex-shrink: 0; display: flex; align-items: center; justify-content: center; background: linear-gradient(135deg, rgba(251,191,36,0.2), rgba(34,211,238,0.12)); box-shadow: inset 0 0 0 1px rgba(255,255,255,0.06); } .sglv-ach-steam-banner-icon svg { width: 18px; height: 18px; color: #fbbf24; } .sglv-ach-steam-banner-info { flex: 1; } .sglv-ach-steam-banner-label { font-size: 11px; color: #8b949e; font-weight: 600; } .sglv-ach-steam-banner-val { font-size: 24px; font-weight: 800; line-height: 1.1; background: linear-gradient(135deg, #22d3ee, #fbbf24); -webkit-background-clip: text; background-clip: text; -webkit-text-fill-color: transparent; font-variant-numeric: tabular-nums; } .sglv-ach-steam-banner-note { font-size: 10px; color: #6e7681; flex-shrink: 0; } /*成就内容区 — 参考设计容器圆角 */ .sglv-ach-content { flex: 1; padding: 16px 24px; overflow-y: auto; } .sglv-ach-content-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 14px; } .sglv-ach-content-title { font-size: 15px; font-weight: 700; color: #e6edf3; } .sglv-ach-content-count { font-size: 11px; color: #22d3ee; background: rgba(34,211,238,0.1); padding: 3px 10px; border-radius: 8px; font-weight: 600; } .sglv-ach-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 12px; } /* ====== 主视图切换:Steam 成就 / 自定义成就 ====== */ .sglv-ach-switch { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; padding: 12px 24px 0; flex-shrink: 0; } .sglv-ach-switch-btn { display: inline-flex; align-items: center; gap: 7px; padding: 7px 14px; border-radius: 10px; border: 1px solid rgba(48,54,61,0.8); background: rgba(13,17,23,0.55); color: #8b949e; font-size: 12px; font-weight: 700; cursor: pointer; transition: all 0.16s; } .sglv-ach-switch-btn:hover { color: #e6edf3; border-color: rgba(99,102,241,0.4); } .sglv-ach-switch-btn.active { color: #e6edf3; background: linear-gradient(135deg, rgba(34,211,238,0.16), rgba(99,102,241,0.14)); border-color: rgba(34,211,238,0.5); box-shadow: inset 0 1px 0 rgba(255,255,255,0.06); } .sglv-ach-switch-btn b { font-size: 10px; font-weight: 700; padding: 1px 6px; border-radius: 6px; background: rgba(148,163,184,0.16); color: #94a3b8; } .sglv-ach-switch-btn.active b { background: rgba(34,211,238,0.24); color: #a5f3fc; } /* 两个视图各自独立滚动:切标签不重建 DOM,也不丢滚动位置 */ .sglv-ach-tracks { flex: 1; min-height: 0; display: flex; flex-direction: column; } .sglv-ach-track { flex: 1; min-height: 0; overflow-y: auto; display: none; } .sglv-ach-track.active { display: block; } .sglv-ach-track-steam { padding: 14px 24px 16px; } .sglv-ach-track-custom > .sglv-ach-content { flex: none; height: auto; overflow: visible; } .sglv-ach-track::-webkit-scrollbar { width: 8px; } .sglv-ach-track::-webkit-scrollbar-thumb { background: rgba(99,102,241,0.32); border-radius: 4px; } @media (max-width: 720px) { .sglv-ach-switch { padding: 10px 14px 0; } .sglv-ach-track-steam { padding: 12px 14px 14px; } } /* ===== ACH-DEEP-CSS:BEGIN ===== 真实成就(S1 数据层 + S2/S3/S4/S5 深度面板) 这段 CSS 会被 test-scripts/build-preview.js 原样抽到本地预览页,改样式只改这里 ===== */ .sglv-ach-real { margin-bottom: 16px; padding: 14px 18px; border-radius: 14px; background: linear-gradient(135deg, rgba(15,23,42,0.72), rgba(30,41,59,0.42)); border: 1px solid rgba(34,211,238,0.18); } .sglv-ach-real-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 12px; } .sglv-ach-real-title { font-size: 14px; font-weight: 700; color: #e6edf3; display: flex; align-items: center; gap: 8px; } .sglv-ach-real-tag { font-size: 9px; font-weight: 700; padding: 2px 6px; border-radius: 5px; background: rgba(34,211,238,0.15); color: #22d3ee; letter-spacing: 0.05em; } .sglv-ach-real-sub { font-size: 11px; color: #8b949e; text-align: right; } .sglv-ach-real-kpis { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; } .sglv-ach-real-kpi { padding: 9px 12px; border-radius: 10px; background: rgba(13,17,23,0.55); border: 1px solid rgba(48,54,61,0.5); min-width: 0; } .sglv-ach-real-kpi-v { font-size: 19px; font-weight: 700; color: #e6edf3; line-height: 1.2; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .sglv-ach-real-kpi-l { font-size: 10px; color: #8b949e; margin-top: 3px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .sglv-ach-real-kpi.gold .sglv-ach-real-kpi-v { color: #fbbf24; } .sglv-ach-real-kpi.cyan .sglv-ach-real-kpi-v { color: #22d3ee; } .sglv-ach-real-kpi.violet .sglv-ach-real-kpi-v { color: #a78bfa; } .sglv-ach-real-bar { height: 6px; border-radius: 4px; background: rgba(48,54,61,0.6); overflow: hidden; margin-top: 12px; } .sglv-ach-real-bar > div { height: 100%; background: linear-gradient(90deg, #22d3ee, #6366f1); border-radius: 4px; transition: width 0.3s; } .sglv-ach-real-foot { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-top: 10px; flex-wrap: wrap; } .sglv-ach-real-hint { font-size: 10px; color: #6e7681; line-height: 1.5; min-width: 0; } .sglv-ach-real-actions { display: flex; align-items: center; gap: 8px; flex-shrink: 0; } .sglv-ach-real-btn { padding: 6px 14px; border-radius: 8px; border: 1px solid rgba(34,211,238,0.35); background: rgba(34,211,238,0.12); color: #67e8f9; font-size: 11px; font-weight: 700; cursor: pointer; transition: all 0.15s; flex-shrink: 0; white-space: nowrap; } .sglv-ach-real-btn:hover:not(:disabled) { background: rgba(34,211,238,0.22); border-color: rgba(34,211,238,0.55); } .sglv-ach-real-btn:disabled { opacity: 0.45; cursor: default; } .sglv-ach-real-btn.ghost { border-color: rgba(148,163,184,0.28); background: rgba(148,163,184,0.08); color: #94a3b8; } .sglv-ach-real-btn.ghost:hover:not(:disabled) { background: rgba(148,163,184,0.16); border-color: rgba(148,163,184,0.45); color: #cbd5e1; } .sglv-ach-real-hint.sglv-ach-real-loading { color: #22d3ee; animation: sglv-ach-pulse 2s ease-in-out infinite; } @keyframes sglv-ach-pulse { 0%,100% { opacity:1; } 50% { opacity:0.6; } } .sglv-ach-deep { margin-bottom: 16px; padding: 14px 18px 16px; border-radius: 14px; background: linear-gradient(135deg, rgba(15,23,42,0.62), rgba(30,41,59,0.34)); border: 1px solid rgba(99,102,241,0.16); } .sglv-ach-deep-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; margin-bottom: 12px; } .sglv-ach-deep-tabs { display: flex; gap: 6px; flex-wrap: wrap; } .sglv-ach-deep-tab { display: inline-flex; align-items: center; gap: 6px; padding: 6px 12px; border-radius: 9px; border: 1px solid rgba(48,54,61,0.8); background: rgba(13,17,23,0.5); color: #8b949e; font-size: 11.5px; font-weight: 600; cursor: pointer; transition: all 0.15s; } .sglv-ach-deep-tab:hover { color: #e6edf3; border-color: rgba(99,102,241,0.4); } .sglv-ach-deep-tab.active { color: #e6edf3; background: rgba(99,102,241,0.16); border-color: rgba(129,140,248,0.55); box-shadow: inset 0 1px 0 rgba(255,255,255,0.06); } .sglv-ach-deep-tab b { font-size: 10px; font-weight: 700; padding: 1px 6px; border-radius: 6px; background: rgba(148,163,184,0.16); color: #94a3b8; } .sglv-ach-deep-tab.active b { background: rgba(129,140,248,0.28); color: #c7d2fe; } .sglv-ach-deep-hunter { display: flex; align-items: baseline; gap: 8px; padding: 5px 12px; border-radius: 9px; background: linear-gradient(135deg, rgba(251,191,36,0.14), rgba(244,63,94,0.1)); border: 1px solid rgba(251,191,36,0.32); } .sglv-ach-deep-hunter-l { font-size: 10px; color: #d6bc8a; letter-spacing: 0.04em; } .sglv-ach-deep-hunter-v { font-size: 17px; font-weight: 800; color: #fbbf24; line-height: 1; } .sglv-ach-deep-body { min-height: 60px; } .sglv-ach-sec { display: flex; align-items: center; gap: 8px; margin: 0 0 8px; font-size: 11px; font-weight: 700; color: #8b949e; letter-spacing: 0.03em; } .sglv-ach-sec b { font-size: 10px; padding: 1px 6px; border-radius: 6px; background: rgba(148,163,184,0.14); color: #94a3b8; font-weight: 700; } .sglv-ach-sec + .sglv-ach-wall, .sglv-ach-sec + .sglv-ach-list { margin-bottom: 14px; } .sglv-ach-empty { padding: 18px 4px; font-size: 11.5px; color: #6e7681; line-height: 1.7; } .sglv-ach-wall { display: grid; grid-template-columns: repeat(auto-fill, minmax(206px, 1fr)); gap: 9px; } .sglv-ach-wall-card { position: relative; text-align: left; padding: 11px 13px 12px; border-radius: 11px; border: 1px solid rgba(48,54,61,0.7); background: linear-gradient(135deg, rgba(13,17,23,0.72), rgba(30,41,59,0.3)); cursor: pointer; transition: all 0.16s; overflow: hidden; font-family: inherit; color: inherit; } .sglv-ach-wall-card::before { content: ''; position: absolute; inset: 0 auto 0 0; width: 3px; background: var(--tw, #6366f1); opacity: 0.85; } .sglv-ach-wall-card:hover { transform: translateY(-2px); border-color: rgba(129,140,248,0.5); box-shadow: 0 10px 26px rgba(0,0,0,0.36); } .sglv-ach-wall-top { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-bottom: 5px; } .sglv-ach-wall-name { flex: 1; min-width: 0; font-size: 12.5px; font-weight: 700; color: #e6edf3; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .sglv-ach-game-ico { width: 48px; height: 22px; object-fit: cover; object-position: center; border-radius: 4px; flex-shrink: 0; display: block; background: rgba(255,255,255,0.06); } .sglv-ach-wall-card .sglv-ach-game-ico { width: 36px; height: 36px; border-radius: 6px; } .sglv-ach-wall-badge { flex-shrink: 0; font-size: 9px; font-weight: 800; padding: 2px 6px; border-radius: 5px; color: var(--tw, #6366f1); background: color-mix(in srgb, var(--tw, #6366f1) 16%, transparent); border: 1px solid color-mix(in srgb, var(--tw, #6366f1) 38%, transparent); letter-spacing: 0.04em; } .sglv-ach-wall-sub { font-size: 10px; color: #8b949e; } .sglv-ach-wall-ach { margin-top: 5px; font-size: 10.5px; color: #6e7681; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .sglv-ach-buckets { display: grid; gap: 6px; margin-bottom: 14px; } .sglv-ach-bucket { display: grid; grid-template-columns: 44px 1fr 74px; align-items: center; gap: 10px; font-size: 10.5px; } .sglv-ach-bucket-l { color: var(--bc, #94a3b8); font-weight: 700; } .sglv-ach-bucket-bar { height: 8px; border-radius: 5px; background: rgba(48,54,61,0.55); overflow: hidden; position: relative; } .sglv-ach-bucket-bar > i { position: absolute; inset: 0 auto 0 0; min-width: 2px; background: color-mix(in srgb, var(--bc, #94a3b8) 70%, transparent); border-radius: 5px; } .sglv-ach-bucket-c { color: #8b949e; text-align: right; font-variant-numeric: tabular-nums; } .sglv-ach-bucket-c b { color: #e6edf3; } .sglv-ach-list { display: grid; gap: 4px; } .sglv-ach-row { display: grid; grid-template-columns: 8px 48px 1fr auto; align-items: center; gap: 10px; width: 100%; padding: 7px 10px; border-radius: 8px; border: 1px solid transparent; background: rgba(13,17,23,0.42); cursor: pointer; text-align: left; font-family: inherit; color: inherit; transition: all 0.13s; } .sglv-ach-row:hover { background: rgba(30,41,59,0.66); border-color: rgba(99,102,241,0.32); } .sglv-ach-row-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--dc, #94a3b8); box-shadow: 0 0 7px color-mix(in srgb, var(--dc, #94a3b8) 55%, transparent); } .sglv-ach-row-main { min-width: 0; } .sglv-ach-row-t { display: block; font-size: 11.5px; color: #d8e0e8; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .sglv-ach-row-s { display: block; font-size: 10px; color: #6e7681; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-top: 1px; } .sglv-ach-row-p { font-size: 11.5px; font-weight: 700; color: var(--dc, #94a3b8); font-variant-numeric: tabular-nums; white-space: nowrap; } .sglv-ach-row-p small { font-size: 9px; font-weight: 600; color: #6e7681; margin-left: 2px; } .sglv-ach-modal { position: fixed; inset: 0; z-index: 2147483000; display: flex; align-items: center; justify-content: center; padding: 24px; } .sglv-ach-modal-mask { position: absolute; inset: 0; background: rgba(2,6,14,0.74); backdrop-filter: blur(4px); } .sglv-ach-modal-panel { position: relative; width: min(680px, 100%); max-height: min(78vh, 720px); display: flex; flex-direction: column; border-radius: 16px; background: linear-gradient(160deg, rgba(17,24,39,0.98), rgba(11,15,25,0.99)); border: 1px solid rgba(99,102,241,0.28); box-shadow: 0 24px 70px rgba(0,0,0,0.6); overflow: hidden; animation: sglv-ach-modal-in 0.16s ease-out; } @keyframes sglv-ach-modal-in { from { opacity: 0; transform: translateY(10px) scale(0.985); } to { opacity: 1; transform: none; } } .sglv-ach-modal-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 14px; padding: 16px 18px 13px; border-bottom: 1px solid rgba(48,54,61,0.6); } .sglv-ach-modal-title { display: flex; align-items: center; gap: 8px; font-size: 15px; font-weight: 800; color: #e6edf3; margin-bottom: 4px; } .sglv-ach-modal-title .sglv-ach-game-ico { width: 64px; height: 30px; } .sglv-ach-modal-sub { font-size: 11px; color: #8b949e; } .sglv-ach-modal-sub b { color: #22d3ee; font-weight: 700; } .sglv-ach-modal-close { flex-shrink: 0; width: 26px; height: 26px; border-radius: 8px; border: 1px solid rgba(48,54,61,0.8); background: rgba(13,17,23,0.6); color: #8b949e; font-size: 15px; line-height: 1; cursor: pointer; transition: all 0.14s; } .sglv-ach-modal-close:hover { color: #e6edf3; border-color: rgba(239,68,68,0.45); background: rgba(239,68,68,0.12); } .sglv-ach-modal-body { padding: 10px 14px 16px; overflow-y: auto; overscroll-behavior: contain; } .sglv-ach-modal-body::-webkit-scrollbar { width: 8px; } .sglv-ach-modal-body::-webkit-scrollbar-thumb { background: rgba(99,102,241,0.32); border-radius: 4px; } .sglv-ach-mrow { display: grid; grid-template-columns: 8px 1fr auto; align-items: center; gap: 10px; padding: 8px 10px; border-radius: 8px; } .sglv-ach-mrow:nth-child(odd) { background: rgba(30,41,59,0.3); } .sglv-ach-mrow.off .sglv-ach-row-t { color: #6e7681; } .sglv-ach-mrow.off .sglv-ach-row-dot { opacity: 0.42; } .sglv-ach-mrow-p { font-size: 11px; font-weight: 700; color: var(--dc, #94a3b8); font-variant-numeric: tabular-nums; white-space: nowrap; } .sglv-ach-mrow-p small { font-size: 9px; color: #6e7681; font-weight: 600; margin-left: 3px; } @media (max-width: 720px) { .sglv-ach-real-kpis { grid-template-columns: repeat(2, 1fr); } .sglv-ach-deep-head { align-items: flex-start; } .sglv-ach-bucket { grid-template-columns: 38px 1fr 64px; } .sglv-ach-modal { padding: 12px; } } /* ===== ACH-DEEP-CSS:END ===== */ /*成就卡片 — 参考设计稀有度左边框+hover提升+图标光泽 */ .sglv-ach-card { display: flex; align-items: flex-start; gap: 14px; padding: 16px 18px; border-radius: 14px; background: linear-gradient(135deg, rgba(15,23,42,0.6), rgba(30,41,59,0.4)); border: 1px solid rgba(99,102,241,0.1); transition: all 0.25s; position: relative; overflow: hidden; } .sglv-ach-card::before { content: ''; position: absolute; left: 0; top: 0; bottom: 0; width: 4px; background: var(--ach-rarity, #6366f1); opacity: 0.8; } .sglv-ach-card:hover { transform: translateY(-2px); border-color: rgba(99,102,241,0.3); box-shadow: 0 8px 24px rgba(0,0,0,0.3); } .sglv-ach-card.unlocked { --ach-rarity: #22c55e; border-color: rgba(34,197,94,0.15); background: linear-gradient(135deg, rgba(34,197,94,0.05), rgba(13,17,23,0.4)); } .sglv-ach-card.unlocked.rare { --ach-rarity: #22d3ee; } .sglv-ach-card.unlocked.epic { --ach-rarity: #a78bfa; } .sglv-ach-card.unlocked.legendary { --ach-rarity: #fbbf24; } .sglv-ach-card.locked { --ach-rarity: #6366f1; opacity: 0.6; } .sglv-ach-card.locked.rare { --ach-rarity: #22d3ee; } .sglv-ach-card.locked.epic { --ach-rarity: #a78bfa; } .sglv-ach-card.locked.legendary { --ach-rarity: #fbbf24; } /*图标 — 参考设计渐变背景+内阴影+光泽叠加 */ .sglv-ach-card-icon { width: 52px; height: 52px; border-radius: 14px; display: flex; align-items: center; justify-content: center; flex-shrink: 0; overflow: hidden; position: relative; background: linear-gradient(135deg, rgba(99,102,241,0.15), rgba(139,92,246,0.08)); box-shadow: inset 0 1px 0 rgba(255,255,255,0.1), inset 0 -1px 0 rgba(0,0,0,0.2); } .sglv-ach-card-icon::after { content: ''; position: absolute; inset: 0; border-radius: 14px; background: linear-gradient(135deg, rgba(255,255,255,0.12) 0%, transparent 40%); pointer-events: none; } .sglv-ach-card-icon svg { width: 100%; height: 100%; display: block; } .sglv-ach-card.unlocked .sglv-ach-card-icon { box-shadow: inset 0 1px 0 rgba(255,255,255,0.15), inset 0 -1px 0 rgba(0,0,0,0.2), 0 4px 12px rgba(99,102,241,0.25); } .sglv-ach-card.locked .sglv-ach-card-icon { filter: grayscale(70%) brightness(0.5); } .sglv-ach-card-rarity { position: absolute; top: -2px; right: -2px; width: 14px; height: 14px; border-radius: 50%; border: 1.5px solid #0d1117; z-index: 2; } .sglv-ach-card-rarity.common { background: #8b949e; } .sglv-ach-card-rarity.rare { background: #22d3ee; } .sglv-ach-card-rarity.epic { background: #a78bfa; } .sglv-ach-card-rarity.legendary { background: #fbbf24; } .sglv-ach-card-body { flex: 1; min-width: 0; } .sglv-ach-card-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-bottom: 4px; } .sglv-ach-card-name { font-size: 14px; font-weight: 700; color: #e6edf3; display: flex; align-items: center; gap: 6px; } .sglv-ach-card.unlocked .sglv-ach-card-name { color: #4ade80; } /*NEW 标签 */ .sglv-ach-card-new-tag { font-size: 9px; background: #22c55e; color: #fff; padding: 1px 6px; border-radius: 4px; font-weight: 700; line-height: 1.4; } /*点数徽章 — 参考设计渐变背景 */ .sglv-ach-card-pts { font-size: 11px; font-weight: 700; padding: 4px 10px; border-radius: 8px; flex-shrink: 0; white-space: nowrap; background: linear-gradient(135deg, rgba(251,191,36,0.15), rgba(245,158,11,0.1)); border: 1px solid rgba(251,191,36,0.3); color: #fbbf24; } .sglv-ach-card.unlocked .sglv-ach-card-pts { background: rgba(34,197,94,0.1); border-color: rgba(34,197,94,0.3); color: #4ade80; } .sglv-ach-card-desc { font-size: 11px; color: #94a3b8; line-height: 1.4; margin-bottom: 8px; } /*进度条 — 参考设计微光动画 */ .sglv-ach-card-progress-wrap { display: flex; align-items: center; gap: 8px; } .sglv-ach-card-progress { flex: 1; height: 6px; background: rgba(34,211,238,0.08); border-radius: 3px; overflow: hidden; position: relative; } .sglv-ach-card-progress-fill { height: 100%; border-radius: 3px; transition: width 0.6s cubic-bezier(0.4,0,0.2,1); position: relative; } .sglv-ach-card.unlocked .sglv-ach-card-progress-fill { background: linear-gradient(90deg, #22d3ee, #34d399, #fbbf24); box-shadow: 0 0 8px rgba(34,211,238,0.4); } .sglv-ach-card.locked .sglv-ach-card-progress-fill { background: linear-gradient(90deg, #38bdf8, #a78bfa, #f59e0b); box-shadow: 0 0 8px rgba(56,189,248,0.25); } .sglv-ach-card-progress-fill::after { content: ''; position: absolute; inset: 0; background: linear-gradient(90deg, transparent, rgba(255,255,255,0.3), transparent); animation: sglv-ach-shimmer 2.5s infinite; } @keyframes sglv-ach-shimmer { 0% { transform: translateX(-100%); } 100% { transform: translateX(100%); } } .sglv-ach-card-progress-val { font-size: 10px; color: #64748b; white-space: nowrap; font-variant-numeric: tabular-nums; } .sglv-ach-card.unlocked .sglv-ach-card-progress-val { color: #22d3ee; font-weight: 600; } .sglv-ach-card-unlock-time { font-size: 9px; color: #6e7681; margin-top: 4px; } .sglv-ach-footer { font-size: 10px; color: #6e7681; text-align: center; padding: 10px 0; margin-top: 8px; border-top: 1px solid rgba(48,54,61,0.3); }`; const CSS_SHOWCASE =` /* ====== 展柜主布局 ====== */ .sglv-sc-wrap { display: flex; flex-direction: column; height: 100%; min-height: 400px; background: linear-gradient(180deg, #0d1117 0%, #161b22 100%); border-radius: 8px; overflow: hidden; } .sglv-sc-scroll { flex: 1; overflow-y: auto; padding: 20px; } /* ====== 英雄区(玩家档案横幅 — 紧凑版 v2) ====== */ .sglv-sc-hero { position: relative; display: flex; align-items: center; gap: 12px; padding: 10px 14px; border-radius: 10px; margin-bottom: 14px; overflow: hidden; background: linear-gradient(135deg, rgba(99,102,241,0.10) 0%, rgba(168,85,247,0.06) 50%, rgba(6,182,212,0.04) 100%); border: 1px solid rgba(99,102,241,0.15); } .sglv-sc-hero::before { content: ''; position: absolute; inset: 0; background: radial-gradient(ellipse at top right, rgba(168,85,247,0.10), transparent 60%); pointer-events: none; } .sglv-sc-avatar-wrap { position: relative; flex-shrink: 0; z-index: 1; } .sglv-sc-avatar { width: 44px; height: 44px; border-radius: 50%; object-fit: cover; border: 2px solid rgba(255,255,255,0.12); box-shadow: 0 1px 8px rgba(0,0,0,0.35), 0 0 0 1px rgba(168,85,247,0.25); background: linear-gradient(135deg, #1a1a2e, #16213e); } .sglv-sc-avatar-placeholder { width: 44px; height: 44px; border-radius: 50%; display: flex; align-items: center; justify-content: center; background: linear-gradient(135deg, #6366f1, #8b5cf6); color: #fff; font-size: 18px; font-weight: 700; border: 2px solid rgba(255,255,255,0.12); box-shadow: 0 1px 8px rgba(0,0,0,0.35); } .sglv-sc-level-badge { display: inline-flex; align-items: center; padding: 1px 7px; border-radius: 8px; background: linear-gradient(135deg, #f59e0b, #d97706); color: #fff; font-size: 10px; font-weight: 800; border: 1px solid rgba(245,158,11,0.4); box-shadow: 0 1px 4px rgba(245,158,11,0.25); font-variant-numeric: tabular-nums; line-height: 1.3; white-space: nowrap; flex-shrink: 0; } .sglv-sc-hero-info { flex: 1; min-width: 0; z-index: 1; } .sglv-sc-hero-name-row { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; } .sglv-sc-hero-name { font-size: 15px; font-weight: 800; color: #f1f5f9; line-height: 1.2; text-shadow: 0 1px 3px rgba(0,0,0,0.4); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 200px; } .sglv-sc-hero-country { font-size: 10px; color: #94a3b8; display: inline-flex; align-items: center; gap: 3px; padding: 1px 6px; border-radius: 8px; background: rgba(148,163,184,0.08); border: 1px solid rgba(148,163,184,0.1); white-space: nowrap; } .sglv-sc-hero-country img { width: 14px; height: 10px; border-radius: 1px; } .sglv-sc-hero-stats { display: flex; gap: 0; margin-top: 8px; flex-wrap: wrap; } .sglv-sc-hero-stat { display: flex; align-items: center; gap: 6px; padding: 0 14px; border-right: 1px solid rgba(148,163,184,0.10); } .sglv-sc-hero-stat:first-child { padding-left: 0; } .sglv-sc-hero-stat:last-child { border-right: none; } .sglv-sc-hero-stat svg { width: 14px; height: 14px; color: #818cf8; flex-shrink: 0; } .sglv-sc-hero-stat-val { font-size: 14px; font-weight: 700; color: #e2e8f0; font-variant-numeric: tabular-nums; line-height: 1; } .sglv-sc-hero-stat-label { font-size: 10px; color: #64748b; line-height: 1; margin-top: 2px; } /* ====== 双栏布局 ====== */ .sglv-sc-cols { display: flex; gap: 20px; align-items: flex-start; } .sglv-sc-left { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 20px; } .sglv-sc-right { width: 340px; flex-shrink: 0; } /* ====== 区块卡片通用 ====== */ .sglv-sc-card { background: rgba(22,27,34,0.6); border: 1px solid rgba(48,54,61,0.5); border-radius: 10px; overflow: hidden; backdrop-filter: blur(8px); } .sglv-sc-card-header { display: flex; align-items: center; gap: 8px; padding: 14px 16px 10px; border-bottom: 1px solid rgba(48,54,61,0.3); } .sglv-sc-card-header svg { width: 18px; height: 18px; color: #a78bfa; flex-shrink: 0; } .sglv-sc-card-title { font-size: 14px; font-weight: 700; color: #e6edf3; } .sglv-sc-card-body { padding: 14px 16px; } /* ====== 游戏封面网格(4×2 竖版) ====== */ .sglv-sc-cover-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; } .sglv-sc-cover-item { position: relative; aspect-ratio: 2/3; border-radius: 8px; overflow: hidden; background: #1a1a2e; cursor: pointer; border: 1px solid rgba(255,255,255,0.06); transition: border-color 0.2s, box-shadow 0.2s; } .sglv-sc-cover-item:hover { border-color: rgba(168,85,247,0.5); box-shadow: 0 4px 16px rgba(168,85,247,0.2); } .sglv-sc-cover-item img { width: 100%; height: 100%; object-fit: cover; display: block; } .sglv-sc-cover-overlay { position: absolute; inset: 0; display: flex; flex-direction: column; justify-content: flex-end; padding: 8px; background: linear-gradient(0deg, rgba(0,0,0,0.85) 0%, rgba(0,0,0,0.2) 50%, transparent 100%); opacity: 0; transition: opacity 0.2s; } .sglv-sc-cover-item:hover .sglv-sc-cover-overlay { opacity: 1; } .sglv-sc-cover-name { font-size: 11px; font-weight: 600; color: #f1f5f9; line-height: 1.3; overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; } .sglv-sc-cover-hours { font-size: 10px; color: #a5b4fc; margin-top: 2px; font-variant-numeric: tabular-nums; } .sglv-sc-cover-placeholder { display: flex; align-items: center; justify-content: center; width: 100%; height: 100%; color: #475569; font-size: 11px; } /*骨架屏样式 — shimmer 动画占位块 */ .sglv-sc-sk-block { background: linear-gradient(90deg, rgba(99,102,241,0.06) 25%, rgba(99,102,241,0.15) 37%, rgba(99,102,241,0.06) 63%); background-size: 400% 100%; animation: sglv-sc-shimmer 1.4s ease infinite; } @keyframes sglv-sc-shimmer { 0% { background-position: 100% 50%; } 100% { background-position: 0% 50%; } } .sglv-sc-skeleton-wrap .sglv-sc-playtime-item, .sglv-sc-skeleton-wrap .sglv-sc-ach-item { background: transparent; border-left: none; } /* ====== 编辑按钮 ====== */ .sglv-sc-edit-btn { display: inline-flex; align-items: center; gap: 5px; padding: 5px 12px; border-radius: 6px; font-size: 12px; font-weight: 600; background: rgba(99,102,241,0.15); border: 1px solid rgba(99,102,241,0.3); color: #a5b4fc; cursor: pointer; transition: background 0.15s, border-color 0.15s; margin-left: auto; } .sglv-sc-edit-btn:hover { background: rgba(99,102,241,0.25); border-color: rgba(99,102,241,0.5); } .sglv-sc-edit-btn svg { width: 14px; height: 14px; } /* ====== 最近游玩时长列表 ====== */ .sglv-sc-playtime-list { display: flex; flex-direction: column; gap: 8px; } .sglv-sc-playtime-item { display: flex; align-items: center; gap: 10px; padding: 8px 10px; border-radius: 8px; background: rgba(13,17,23,0.5); transition: background 0.15s; } .sglv-sc-playtime-item:hover { background: rgba(99,102,241,0.08); } .sglv-sc-playtime-icon { width: 32px; height: 32px; border-radius: 6px; object-fit: cover; flex-shrink: 0; background: #1a1a2e; } .sglv-sc-playtime-icon-ph { width: 32px; height: 32px; border-radius: 6px; display: flex; align-items: center; justify-content: center; background: #1a1a2e; color: #475569; font-size: 10px; flex-shrink: 0; } .sglv-sc-playtime-info { flex: 1; min-width: 0; } .sglv-sc-playtime-name { font-size: 12px; font-weight: 600; color: #cbd5e1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .sglv-sc-playtime-meta { font-size: 10px; margin-top: 2px; display: flex; align-items: center; gap: 0; } .sglv-sc-playtime-bar { height: 4px; background: rgba(99,102,241,0.1); border-radius: 2px; margin-top: 4px; overflow: hidden; } .sglv-sc-playtime-bar-fill { height: 100%; border-radius: 2px; background: linear-gradient(90deg, #6366f1, #a855f7); transition: width 0.6s ease; } .sglv-sc-playtime-empty { text-align: center; padding: 24px; color: #64748b; font-size: 12px; } /* ====== 最近解锁成就列表 ====== */ .sglv-sc-ach-list { display: flex; flex-direction: column; gap: 8px; } .sglv-sc-ach-item { display: flex; align-items: center; gap: 10px; padding: 10px; border-radius: 8px; background: rgba(13,17,23,0.5); border-left: 3px solid transparent; transition: background 0.15s, border-color 0.15s; } .sglv-sc-ach-item:hover { background: rgba(99,102,241,0.08); } .sglv-sc-ach-item.rarity-common { border-left-color: #64748b; } .sglv-sc-ach-item.rarity-rare { border-left-color: #58a6ff; } .sglv-sc-ach-item.rarity-epic { border-left-color: #a855f7; } .sglv-sc-ach-item.rarity-legendary { border-left-color: #fbbf24; } .sglv-sc-ach-icon { width: 36px; height: 36px; border-radius: 8px; display: flex; align-items: center; justify-content: center; flex-shrink: 0; background: rgba(99,102,241,0.1); } .sglv-sc-ach-icon svg { width: 22px; height: 22px; } .sglv-sc-ach-info { flex: 1; min-width: 0; } .sglv-sc-ach-name { font-size: 12px; font-weight: 600; color: #e2e8f0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .sglv-sc-ach-meta { font-size: 10px; color: #64748b; margin-top: 2px; display: flex; align-items: center; gap: 6px; } .sglv-sc-ach-pts { font-size: 11px; font-weight: 700; color: #fbbf24; flex-shrink: 0; font-variant-numeric: tabular-nums; } .sglv-sc-ach-empty { text-align: center; padding: 24px; color: #64748b; font-size: 12px; } /* ====== 玩家画像标签 ====== */ .sglv-sc-tags { display: flex; flex-wrap: wrap; gap: 8px; padding: 14px 16px; } .sglv-sc-tag { display: inline-flex; align-items: center; gap: 4px; padding: 5px 12px; border-radius: 16px; font-size: 11px; font-weight: 600; border: 1px solid rgba(255,255,255,0.08); } .sglv-sc-tag-collector { background: rgba(139,92,246,0.12); border-color: rgba(139,92,246,0.3); color: #c4b5fd; } .sglv-sc-tag-playtime { background: rgba(6,182,212,0.12); border-color: rgba(6,182,212,0.3); color: #67e8f9; } .sglv-sc-tag-mastery { background: rgba(16,185,129,0.12); border-color: rgba(16,185,129,0.3); color: #6ee7b7; } .sglv-sc-tag-diversity { background: rgba(249,115,22,0.12); border-color: rgba(249,115,22,0.3); color: #fdba74; } .sglv-sc-tag-loyalty { background: rgba(244,114,182,0.12); border-color: rgba(244,114,182,0.3); color: #f9a8d4; } .sglv-sc-tag-special { background: rgba(251,191,36,0.12); border-color: rgba(251,191,36,0.3); color: #fcd34d; } /* ====== 封面选择器弹窗(内嵌于游戏库浮窗内,不遮挡浮窗本身) ====== */ .sglv-panel .sglv-sc-picker-overlay { position: absolute; inset: 0; z-index: 1000002; background: rgba(0,0,0,0.65); backdrop-filter: blur(4px); display: flex; align-items: center; justify-content: center; border-radius: inherit; animation: sglv-sc-fade-in 0.2s ease; } .sglv-sc-picker { width: 720px; max-width: calc(100% - 40px); max-height: calc(100% - 40px); background: #161b22; border: 1px solid rgba(48,54,61,0.6); border-radius: 12px; display: flex; flex-direction: column; overflow: hidden; box-shadow: 0 20px 60px rgba(0,0,0,0.6); } .sglv-sc-picker-header { display: flex; align-items: center; gap: 10px; padding: 16px 20px; border-bottom: 1px solid rgba(48,54,61,0.4); } .sglv-sc-picker-title { font-size: 15px; font-weight: 700; color: #e6edf3; flex: 1; } .sglv-sc-picker-search { width: 200px; padding: 6px 10px; border-radius: 6px; border: 1px solid rgba(48,54,61,0.6); background: #0d1117; color: #e2e8f0; font-size: 12px; outline: none; } .sglv-sc-picker-search:focus { border-color: rgba(99,102,241,0.5); } .sglv-sc-picker-close { width: 28px; height: 28px; border-radius: 6px; border: none; background: rgba(255,255,255,0.06); color: #94a3b8; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 16px; } .sglv-sc-picker-close:hover { background: rgba(255,255,255,0.12); color: #f1f5f9; } .sglv-sc-picker-body { flex: 1; overflow-y: auto; padding: 16px 20px; overscroll-behavior: contain; } .sglv-sc-picker-grid { display: grid; grid-template-columns: repeat(6, 1fr); gap: 10px; } .sglv-sc-picker-item { position: relative; aspect-ratio: 2/3; border-radius: 6px; overflow: hidden; cursor: pointer; border: 2px solid transparent; transition: border-color 0.15s, transform 0.15s; } .sglv-sc-picker-item:hover { transform: scale(1.03); } .sglv-sc-picker-item.selected { border-color: #22c55e; } .sglv-sc-picker-item img { width: 100%; height: 100%; object-fit: cover; } .sglv-sc-picker-item-name { position: absolute; bottom: 0; left: 0; right: 0; padding: 4px 6px; font-size: 9px; color: #fff; background: linear-gradient(0deg, rgba(0,0,0,0.85), transparent); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .sglv-sc-picker-check { position: absolute; top: 4px; right: 4px; width: 20px; height: 20px; border-radius: 50%; background: #22c55e; color: #fff; display: none; align-items: center; justify-content: center; font-size: 12px; font-weight: 700; } .sglv-sc-picker-item.selected .sglv-sc-picker-check { display: flex; } .sglv-sc-picker-footer { display: flex; align-items: center; gap: 12px; padding: 12px 20px; border-top: 1px solid rgba(48,54,61,0.4); } .sglv-sc-picker-count { font-size: 12px; color: #94a3b8; } .sglv-sc-picker-count strong { color: #22c55e; } .sglv-sc-picker-save { padding: 7px 18px; border-radius: 6px; border: none; background: linear-gradient(135deg, #6366f1, #8b5cf6); color: #fff; font-size: 13px; font-weight: 600; cursor: pointer; margin-left: auto; transition: opacity 0.15s; } .sglv-sc-picker-save:hover { opacity: 0.9; } .sglv-sc-picker-save:disabled { opacity: 0.4; cursor: not-allowed; } /* ====== 英雄区徽章展示区 ====== */ .sglv-sc-hero-divider { width: 1px; height: 44px; background: rgba(148,163,184,0.12); flex-shrink: 0; z-index: 1; } .sglv-sc-hero-badges { display: flex; gap: 8px; align-items: center; flex-shrink: 0; z-index: 1; } .sglv-sc-hero-badge { width: 48px; height: 48px; border-radius: 8px; background: rgba(255,255,255,0.04); border: 1.5px solid rgba(139,92,246,0.3); display: flex; align-items: center; justify-content: center; cursor: pointer; transition: border-color 0.16s, transform 0.16s, box-shadow 0.16s; position: relative; overflow: visible; } .sglv-sc-hero-badge:hover { border-color: rgba(139,92,246,0.6); transform: translateY(-2px); box-shadow: 0 4px 12px rgba(139,92,246,0.2); } .sglv-sc-hero-badge img { width: 36px; height: 36px; object-fit: contain; border-radius: 4px; } .sglv-sc-hero-badge-fallback { display: flex; align-items: center; justify-content: center; width: 100%; height: 100%; color: #818cf8; } .sglv-sc-hero-badge-fallback svg { width: 22px; height: 22px; } .sglv-sc-hero-badge-lvl { position: absolute; bottom: -5px; right: -5px; font-size: 9px; font-weight: 700; color: #fff; background: linear-gradient(135deg, #8b5cf6, #6366f1); border-radius: 4px; padding: 0 4px; line-height: 14px; box-shadow: 0 1px 3px rgba(0,0,0,0.3); white-space: nowrap; } .sglv-sc-hero-badge-foil-tag { position: absolute; top: -5px; left: -5px; font-size: 8px; font-weight: 700; color: #1a1a2e; background: linear-gradient(135deg, #fbbf24, #f59e0b); border-radius: 3px; padding: 0 3px; line-height: 12px; white-space: nowrap; } .sglv-sc-hero-badge-empty { width: 48px; height: 48px; border-radius: 8px; border: 1.5px dashed rgba(148,163,184,0.2); display: flex; align-items: center; justify-content: center; color: rgba(148,163,184,0.4); font-size: 20px; cursor: pointer; transition: border-color 0.16s, color 0.16s; } .sglv-sc-hero-badge-empty:hover { border-color: rgba(139,92,246,0.4); color: rgba(139,92,246,0.6); } .sglv-sc-hero-badge-edit { width: 28px; height: 28px; border-radius: 6px; background: rgba(139,92,246,0.15); border: 1px solid rgba(139,92,246,0.25); color: #a78bfa; cursor: pointer; flex-shrink: 0; display: flex; align-items: center; justify-content: center; transition: background 0.16s, border-color 0.16s; } .sglv-sc-hero-badge-edit:hover { background: rgba(139,92,246,0.25); border-color: rgba(139,92,246,0.5); } .sglv-sc-hero-badge-edit svg { width: 14px; height: 14px; } /* ====== 徽章选择器弹窗 ====== */ .sglv-sc-badge-picker { max-width: 680px; } .sglv-sc-badge-tabs { display: flex; gap: 6px; padding: 10px 20px; border-bottom: 1px solid rgba(48,54,61,0.3); flex-wrap: wrap; } .sglv-sc-badge-tab { padding: 5px 12px; border-radius: 6px; border: 1px solid rgba(48,54,61,0.5); background: transparent; color: #94a3b8; font-size: 12px; font-weight: 600; cursor: pointer; transition: all 0.16s; white-space: nowrap; } .sglv-sc-badge-tab:hover { background: rgba(255,255,255,0.04); color: #c4b5fd; } .sglv-sc-badge-tab.active { background: rgba(139,92,246,0.15); border-color: rgba(139,92,246,0.4); color: #c4b5fd; } .sglv-sc-badge-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; } .sglv-sc-badge-pick-item { position: relative; border-radius: 8px; overflow: hidden; background: rgba(22,27,34,0.6); border: 1.5px solid rgba(48,54,61,0.5); cursor: pointer; transition: border-color 0.16s, transform 0.16s; display: flex; flex-direction: column; gap: 6px; padding: 8px; } .sglv-sc-badge-pick-item:hover { border-color: rgba(139,92,246,0.4); transform: scale(1.02); } .sglv-sc-badge-pick-item.selected { border-color: #22c55e; } .sglv-sc-badge-pick-icon { width: 100%; height: 64px; display: flex; align-items: center; justify-content: center; background: rgba(13,17,23,0.4); border-radius: 6px; overflow: hidden; } .sglv-sc-badge-pick-icon img { max-width: 56px; max-height: 56px; object-fit: contain; } .sglv-sc-badge-pick-icon.no-icon { } .sglv-sc-badge-pick-noicon { font-size: 24px; opacity: 0.5; } .sglv-sc-badge-pick-info { flex: 1; min-width: 0; } .sglv-sc-badge-pick-name { font-size: 11px; font-weight: 600; color: #e2e8f0; line-height: 1.3; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .sglv-sc-badge-pick-meta { display: flex; gap: 4px; flex-wrap: wrap; margin-top: 3px; } .sglv-sc-badge-pick-meta span { font-size: 9px; padding: 0 4px; border-radius: 3px; line-height: 14px; } .sglv-sc-badge-foil { background: rgba(245,158,11,0.15); color: #fbbf24; } .sglv-sc-badge-lvl { background: rgba(139,92,246,0.15); color: #c4b5fd; } .sglv-sc-badge-pick-xp { background: rgba(34,197,94,0.1); color: #86efac; } .sglv-sc-badge-pick-item .sglv-sc-picker-check { top: 4px; right: 4px; } @keyframes sglv-sc-fade-in { from { opacity: 0; } to { opacity: 1; } } /* ====== 加载/空状态 ====== */ .sglv-sc-loading { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%; gap: 12px; color: #8a9ba8; } .sglv-sc-loading svg { animation: sglv-spin 1s linear infinite; } @media (prefers-reduced-motion: reduce) { .sglv-sc-cover-overlay, .sglv-sc-cover-item, .sglv-sc-playtime-item, .sglv-sc-ach-item, .sglv-sc-picker-item, .sglv-sc-hero-badge, .sglv-sc-hero-badge-empty, .sglv-sc-badge-pick-item { transition: none !important; } .sglv-panel .sglv-sc-picker-overlay { animation: none !important; } .sglv-sc-loading svg { animation: none !important; } }`; const CSS_CLOUDSAVE =` /* ====== 云存档主布局 ====== */ .sglv-cs-wrap { display: flex; gap: 0; height: 100%; min-height: 400px; } .sglv-cs-side { width: 540px; flex-shrink: 0; border-right: 1px solid rgba(255,255,255,0.06); padding: 14px; overflow-y: auto; } .sglv-cs-list-wrap { flex: 1; display: flex; flex-direction: column; overflow: hidden; } /* ====== 状态视图(加载/错误/空) ====== */ .sglv-cs-state-box { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%; gap: 12px; padding: 40px; text-align: center; width: 100%; } .sglv-cs-state-icon { font-size: 36px; } .sglv-cs-state-msg { font-size: 14px; color: var(--sglv-text-1, #e2e8f0); max-width: 360px; line-height: 1.5; } .sglv-cs-state-tip { font-size: 11px; color: var(--sglv-text-2, #94a3b8); } .sglv-cs-action-btn { padding: 8px 20px; border-radius: 8px; border: 1px solid rgba(139,92,246,0.4); background: rgba(139,92,246,0.12); color: #c4b5fd; cursor: pointer; font-size: 13px; transition: all 0.2s; } .sglv-cs-action-btn:hover { background: rgba(139,92,246,0.25); border-color: rgba(139,92,246,0.6); } /* ====== KPI 卡片(炫彩边框 + 色彩变体) ====== */ /* === 云存档 KPI 卡片复用 sglv-playtime-kpi-card 统一风格(4 列均分) === */ .sglv-cs-kpi-row { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; margin-bottom: 18px; } @media (max-width: 1100px) { .sglv-cs-kpi-row { grid-template-columns: repeat(2, 1fr) !important; } } /* ====== 仪表盘区块 ====== */ .sglv-cs-section { margin-bottom: 16px; } .sglv-cs-section-title { font-size: 12px; font-weight: 600; color: var(--sglv-text-1, #e2e8f0); margin-bottom: 8px; } /* ====== TOP 10 ====== */ .sglv-cs-top10 { display: flex; flex-direction: column; gap: 6px; } .sglv-cs-top10-item { display: flex; align-items: center; gap: 6px; font-size: 11px; } .sglv-cs-top10-rank { width: 16px; text-align: center; font-weight: 700; color: var(--sglv-text-2, #94a3b8); flex-shrink: 0; } .sglv-cs-top10-name { flex-shrink: 0; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--sglv-text-1, #e2e8f0); width: 140px; } .sglv-cs-top10-bar-track { flex: 1; height: 8px; background: rgba(255,255,255,0.05); border-radius: 4px; overflow: hidden; min-width: 30px; } .sglv-cs-top10-bar { height: 100%; background: linear-gradient(90deg, #8b5cf6, #6366f1); border-radius: 4px; transition: width 0.4s ease; } .sglv-cs-top10-size { flex-shrink: 0; color: var(--sglv-text-2, #94a3b8); font-size: 10px; min-width: 44px; text-align: right; } /* ====== 分布图 ====== */ /*大小分布 + 文件数分布 并排两栏 */ .sglv-cs-dist-pair { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 16px; } .sglv-cs-dist-card { background: rgba(255,255,255,0.02); border: 1px solid rgba(255,255,255,0.05); border-radius: 8px; padding: 10px 8px 8px; } .sglv-cs-dist-card .sglv-cs-section-title { font-size: 11px; margin-bottom: 6px; text-align: center; } .sglv-cs-dist { display: flex; align-items: flex-end; gap: 8px; height: 130px; } .sglv-cs-dist-col { flex: 1; display: flex; flex-direction: column; align-items: center; height: 100%; justify-content: flex-end; min-width: 0; } .sglv-cs-dist-bar-track { width: 100%; flex: 1; display: flex; align-items: flex-end; justify-content: center; min-height: 2px; } .sglv-cs-dist-bar { width: 50%; max-width: 32px; background: linear-gradient(180deg, #8b5cf6, #6366f1); border-radius: 3px 3px 0 0; min-height: 2px; transition: height 0.4s ease; } .sglv-cs-dist-bar-2 { background: linear-gradient(180deg, #3b82f6, #06b6d4); } .sglv-cs-dist-val { font-size: 10px; font-weight: 600; color: var(--sglv-text-1, #e2e8f0); margin-top: 3px; } .sglv-cs-dist-label { font-size: 9px; color: var(--sglv-text-2, #94a3b8); text-align: center; margin-top: 1px; } /* ====== Diff 徽章 ====== */ .sglv-cs-diff-box { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 12px; } .sglv-cs-diff-badge { font-size: 10px; padding: 3px 8px; border-radius: 6px; font-weight: 600; } .sglv-cs-diff-badge.new { background: rgba(34,197,94,0.15); color: #4ade80; border: 1px solid rgba(34,197,94,0.3); } .sglv-cs-diff-badge.changed { background: rgba(251,191,36,0.15); color: #fbbf24; border: 1px solid rgba(251,191,36,0.3); } .sglv-cs-diff-badge.removed { background: rgba(239,68,68,0.15); color: #f87171; border: 1px solid rgba(239,68,68,0.3); } /* ====== 底部 ====== */ .sglv-cs-footer { display: flex; align-items: center; gap: 8px; margin-top: auto; padding-top: 12px; border-top: 1px solid rgba(255,255,255,0.04); flex-wrap: wrap; } .sglv-cs-source-badge { font-size: 10px; padding: 2px 8px; border-radius: 6px; background: rgba(139,92,246,0.12); color: #c4b5fd; border: 1px solid rgba(139,92,246,0.2); } .sglv-cs-updated { font-size: 10px; color: var(--sglv-text-2, #94a3b8); } .sglv-cs-refresh-btn { margin-left: auto; background: none; border: none; color: var(--sglv-text-2, #94a3b8); cursor: pointer; padding: 4px; border-radius: 6px; display: flex; align-items: center; transition: all 0.2s; } .sglv-cs-refresh-btn:hover { color: #c4b5fd; background: rgba(139,92,246,0.12); } .sglv-cs-refresh-btn svg { width: 14px; height: 14px; } /* ====== 工具栏 ====== */ .sglv-cs-toolbar { display: flex; gap: 8px; padding: 10px 12px; border-bottom: 1px solid rgba(255,255,255,0.06); flex-shrink: 0; } .sglv-cs-search { flex: 1; background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.08); border-radius: 8px; padding: 6px 12px; color: var(--sglv-text-1, #e2e8f0); font-size: 12px; outline: none; transition: border-color 0.2s; } .sglv-cs-search:focus { border-color: rgba(139,92,246,0.5); } .sglv-cs-search::placeholder { color: var(--sglv-text-2, #94a3b8); } .sglv-cs-sort { background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.08); border-radius: 8px; padding: 6px 8px; color: var(--sglv-text-1, #e2e8f0); font-size: 12px; outline: none; cursor: pointer; } /* ====== 列表头 ====== */ .sglv-cs-list-header { display: flex; align-items: center; justify-content: space-between; padding: 8px 12px; font-size: 12px; font-weight: 600; color: var(--sglv-text-1, #e2e8f0); flex-shrink: 0; } .sglv-cs-list-count { font-size: 11px; color: var(--sglv-text-2, #94a3b8); background: rgba(255,255,255,0.05); padding: 2px 8px; border-radius: 6px; } /* ====== 游戏列表 ====== */ .sglv-cs-game-list { flex: 1; overflow-y: auto; padding: 0 12px 12px; } .sglv-cs-game-row { display: flex; align-items: center; gap: 10px; padding: 8px 10px; border-radius: 8px; transition: background 0.15s; margin-bottom: 4px; } .sglv-cs-game-row:hover { background: rgba(255,255,255,0.04); } .sglv-cs-game-cover { width: 46px; height: 22px; border-radius: 4px; object-fit: cover; flex-shrink: 0; background: rgba(255,255,255,0.04); } /*通用 cover failed 样式(sglv-cover-fallback.lib.js 添加) */ .sglv-cs-cover-failed, .sglv-cover-failed { object-fit: contain !important; padding: 4px; opacity: 0.6; } .sglv-cs-game-cover-fallback { width: 46px; height: 22px; border-radius: 4px; flex-shrink: 0; display: flex; align-items: center; justify-content: center; background: linear-gradient(135deg, rgba(59,130,246,0.12), rgba(139,92,246,0.08)); font-size: 9px; color: var(--sglv-text-2, #94a3b8); } .sglv-cs-game-info { display: flex; flex-direction: column; gap: 2px; min-width: 0; flex: 1; } .sglv-cs-game-name { font-size: 12px; color: var(--sglv-text-1, #e2e8f0); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .sglv-cs-game-appid { font-size: 10px; color: var(--sglv-text-2, #94a3b8); } .sglv-cs-game-stats { display: flex; align-items: center; gap: 8px; flex-shrink: 0; } .sglv-cs-game-files { font-size: 11px; color: var(--sglv-text-2, #94a3b8); } .sglv-cs-game-size { font-size: 11px; color: var(--sglv-text-1, #e2e8f0); font-weight: 600; min-width: 60px; text-align: right; } .sglv-cs-game-dl { font-size: 10px; color: #66c0f4; text-decoration: none; flex-shrink: 0; opacity: 0.7; transition: opacity 0.15s; } .sglv-cs-game-dl:hover { opacity: 1; text-decoration: underline; } .sglv-cs-status-badge { font-size: 9px; padding: 2px 6px; border-radius: 4px; font-weight: 700; } .sglv-cs-status-badge.new { background: rgba(34,197,94,0.15); color: #4ade80; } .sglv-cs-status-badge.changed { background: rgba(251,191,36,0.15); color: #fbbf24; } .sglv-cs-list-empty { text-align: center; padding: 40px 20px; font-size: 13px; color: var(--sglv-text-2, #94a3b8); }`; const CSS_STAGE =` #sglv-stage-progress { padding: 8px 16px; background: linear-gradient(180deg, rgba(167,139,250,0.08), transparent); border-bottom: 1px solid rgba(167,139,250,0.15); display: block; } #sglv-stage-progress .sglv-stage-progress-row { display: flex; align-items: center; gap: 12px; } #sglv-stage-progress .sglv-stage-progress-bar { flex: 1; height: 6px; background: rgba(255,255,255,0.06); border-radius: 3px; overflow: hidden; position: relative; } #sglv-stage-progress .sglv-stage-progress-fill { height: 100%; background: linear-gradient(90deg, #a78bfa 0%, #38bdf8 100%); width: 0%; transition: width 0.25s ease-out; border-radius: 3px; } #sglv-stage-progress .sglv-stage-progress-text { flex-shrink: 0; font-size: 12px; color: #94a3b8; min-width: 200px; text-align: right; font-variant-numeric: tabular-nums; }`; const CSS_HEADER =` /* === 紧凑页头:删除 h2 标题占用空间,padding 收紧 === */ .sglv-panel > .sglv-header { padding: 8px 14px !important; gap: 12px; cursor: move; /* 整个 header 作为拖动手柄 */ user-select: none; } .sglv-panel > .sglv-header h2 { display: none !important; } /* === 保留最左侧 Steam 图标作为品牌标识(去掉"游戏库"文字) === */ .sglv-header-brand { width: 24px; height: 24px; border-radius: 6px; flex-shrink: 0; display: inline-flex; align-items: center; justify-content: center; background: linear-gradient(135deg, rgba(102, 192, 244, 0.18), rgba(139, 92, 246, 0.18)); border: 1px solid rgba(102, 192, 244, 0.25); color: #66c0f4; box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.06); transition: transform 0.2s, box-shadow 0.2s; } .sglv-header-brand:hover { transform: rotate(-8deg) scale(1.05); box-shadow: 0 2px 8px rgba(102, 192, 244, 0.35), inset 0 1px 0 rgba(255, 255, 255, 0.1); } .sglv-header-brand img { width: 14px; height: 14px; display: block; border-radius: 2px; } .sglv-header-brand svg { width: 14px; height: 14px; } .sglv-panel > .sglv-header > .sglv-tab-bar { display: flex; align-items: center; gap: 2px; flex: 1; min-width: 0; overflow: visible; position: relative; } /* === tab 按钮紧凑化(等宽等距布局,flex:1 使各标签宽度一致) === */ /*紧凑——padding 4px 5px,font-size 11.5px,为右侧全局搜索框腾出空间 */ .sglv-panel .sglv-tab { flex: 1 1 0 !important; padding: 4px 5px !important; font-size: 11.5px !important; font-weight: 600 !important; border-radius: 6px !important; border: 1px solid transparent !important; background: transparent !important; color: #94a3b8 !important; white-space: nowrap !important; justify-content: center !important; gap: 4px !important; min-width: 0 !important; overflow: hidden !important; text-overflow: ellipsis !important; transition: background 0.15s, color 0.15s, border-color 0.15s, transform 0.15s !important; height: 26px !important; } .sglv-panel .sglv-tab:hover { color: #e2e8f0 !important; background: rgba(255, 255, 255, 0.06) !important; } .sglv-panel .sglv-tab.active { color: #fff !important; background: rgba(102, 192, 244, 0.22) !important; border-color: rgba(102, 192, 244, 0.4) !important; box-shadow: 0 0 0 1px rgba(102, 192, 244, 0.15) inset, 0 1px 4px rgba(102, 192, 244, 0.18) !important; } .sglv-panel .sglv-tab svg { width: 12px; height: 12px; flex-shrink: 0; } .sglv-panel .sglv-tab span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; } /* === 头部 action 按钮 hover 反馈 + 状态点 === */ .sglv-panel > .sglv-header > .sglv-header-actions { gap: 6px; flex-shrink: 0; margin-left: auto; } .sglv-panel .sglv-header-btn { width: 30px !important; height: 30px !important; } /* === ★v2.36.0 导出下拉菜单(合并原 CSV/JSON 两个 header 按钮) === */ .sglv-export-menu { position: fixed; z-index: 1000012; min-width: 176px; padding: 6px; background: var(--sglv-panel-bg, rgba(23,26,33,0.98)); border: 1px solid var(--sglv-border, rgba(255,255,255,0.1)); border-radius: 10px; box-shadow: 0 12px 36px rgba(0,0,0,0.55); display: none; opacity: 0; transform: translateY(-4px); transition: opacity .15s ease, transform .15s ease; } .sglv-export-menu.show { display: block; opacity: 1; transform: translateY(0); } .sglv-export-menu button { display: flex; align-items: center; gap: 9px; width: 100%; padding: 8px 10px; border: none; background: transparent; color: var(--sglv-text, #c7d5e0); font-size: 12.5px; border-radius: 7px; cursor: pointer; text-align: left; font-family: inherit; } .sglv-export-menu button:hover { background: rgba(102,192,244,0.12); color: #fff; } .sglv-export-menu .fmt-badge { flex-shrink: 0; min-width: 38px; text-align: center; padding: 2px 6px; border-radius: 6px; font-size: 10px; font-weight: 700; letter-spacing: .04em; } .sglv-export-menu .fmt-badge.csv { background: rgba(52,211,153,0.14); color: #34d399; } .sglv-export-menu .fmt-badge.json { background: rgba(102,192,244,0.14); color: #66c0f4; } /* === 头部开关紧凑(家庭组) === */ .sglv-panel .sglv-switch-container { display: inline-flex; align-items: center; gap: 6px; font-size: 11.5px; color: #94a3b8; user-select: none; cursor: pointer; height: 30px; padding: 0 4px 0 6px; border-radius: 6px; transition: background 0.15s, color 0.15s; } .sglv-panel .sglv-switch-container:hover { background: rgba(255, 255, 255, 0.05); color: #e2e8f0; } /* === 头部渐变微调,让 tab active 高光更明显 === */ .sglv-panel > .sglv-header { background: linear-gradient(135deg, rgba(27, 40, 56, 0.95) 0%, rgba(42, 71, 94, 0.95) 100%) !important; border-bottom: 1px solid rgba(102, 192, 244, 0.18) !important; } /* === tab 菜单紧凑化(保留),并接入全局搜索框 + 下拉结果浮层 === */ /* 全局搜索框:紧贴 wishlist tab 右侧,flex:0 0 auto 不抢占 tab 等宽空间 */ /*审查:移除 flex-grow:1(与 flex:0 0 auto 冲突,会抢 tab 空间导致布局错乱) */ .sglv-panel .sglv-global-search { flex: 0 0 200px !important; position: relative !important; display: flex !important; align-items: center !important; gap: 4px !important; height: 26px !important; padding: 0 6px 0 8px !important; margin-left: 6px !important; background: rgba(255, 255, 255, 0.06) !important; border: 1px solid rgba(255, 255, 255, 0.1) !important; border-radius: 6px !important; color: #c7d5e0 !important; transition: border-color 0.15s, background 0.15s, box-shadow 0.15s, width 0.15s !important; min-width: 120px !important; max-width: 240px !important; } .sglv-panel .sglv-global-search:hover { background: rgba(255, 255, 255, 0.09) !important; } .sglv-panel .sglv-global-search:focus-within { border-color: rgba(102, 192, 244, 0.55) !important; background: rgba(255, 255, 255, 0.1) !important; box-shadow: 0 0 0 1px rgba(102, 192, 244, 0.25) !important; } .sglv-panel .sglv-global-search-icon { display: inline-flex !important; align-items: center !important; color: #8a9ba8 !important; flex-shrink: 0 !important; } .sglv-panel .sglv-global-search-icon svg { width: 12px !important; height: 12px !important; } .sglv-panel .sglv-global-search input { flex: 1 1 auto !important; min-width: 0 !important; border: none !important; background: transparent !important; color: #fff !important; font-size: 11.5px !important; line-height: 1 !important; outline: none !important; padding: 0 !important; height: 100% !important; } .sglv-panel .sglv-global-search input::placeholder { color: #6b7c8c !important; font-size: 11px !important; } .sglv-panel .sglv-global-search-clear { flex: 0 0 auto !important; display: none !important; align-items: center !important; justify-content: center !important; width: 16px !important; height: 16px !important; padding: 0 !important; border: none !important; border-radius: 4px !important; background: rgba(255, 255, 255, 0.1) !important; color: #c7d5e0 !important; cursor: pointer !important; transition: background 0.15s, color 0.15s !important; } .sglv-panel .sglv-global-search-clear:hover { background: rgba(255, 255, 255, 0.2) !important; color: #fff !important; } .sglv-panel .sglv-global-search-clear svg { width: 9px !important; height: 9px !important; } .sglv-panel .sglv-global-search.has-text .sglv-global-search-clear { display: inline-flex !important; } /*搜索结果浮层 — 右对齐搜索框,动画显隐,动态 max-height 防溢出面板 */ .sglv-panel .sglv-global-search-pop { position: absolute !important; top: calc(100% + 6px) !important; right: 0 !important; left: auto !important; min-width: 300px !important; max-width: 400px !important; max-height: calc(80vh - 80px) !important; overflow-y: auto !important; background: rgba(15, 23, 42, 0.98) !important; border: 1px solid rgba(102, 192, 244, 0.35) !important; border-radius: 10px !important; box-shadow: 0 12px 32px rgba(0, 0, 0, 0.7), 0 0 0 1px rgba(0, 0, 0, 0.3) !important; z-index: 1000001 !important; padding: 4px 0 !important; backdrop-filter: blur(12px) !important; display: block !important; opacity: 0; transform: translateY(-6px) scale(0.98); visibility: hidden; transition: opacity 0.16s ease, transform 0.16s ease, visibility 0s linear 0.16s; transform-origin: top right; } .sglv-panel .sglv-global-search-pop::-webkit-scrollbar { width: 6px; } .sglv-panel .sglv-global-search-pop::-webkit-scrollbar-thumb { background: rgba(255, 255, 255, 0.15); border-radius: 3px; } .sglv-panel .sglv-global-search-pop.show { opacity: 1; transform: translateY(0) scale(1); visibility: visible; transition: opacity 0.16s ease, transform 0.16s ease, visibility 0s; } .sglv-panel .sglv-gs-header { padding: 8px 12px 5px !important; font-size: 10px !important; font-weight: 700 !important; color: #6e7681 !important; text-transform: uppercase !important; letter-spacing: 0.05em !important; display: flex !important; align-items: center !important; justify-content: space-between !important; border-bottom: 1px solid rgba(255, 255, 255, 0.04) !important; } .sglv-panel .sglv-gs-header-count { background: rgba(102, 192, 244, 0.12) !important; color: #66c0f4 !important; font-weight: 700 !important; text-transform: none !important; letter-spacing: 0 !important; padding: 1px 7px !important; border-radius: 10px !important; font-size: 10px !important; } .sglv-panel .sglv-gs-item { display: flex !important; align-items: center !important; gap: 10px !important; padding: 7px 12px !important; cursor: pointer !important; color: #c7d5e0 !important; font-size: 12px !important; transition: background 0.12s, color 0.12s !important; border-left: 2px solid transparent !important; } .sglv-panel .sglv-gs-item:hover, .sglv-panel .sglv-gs-item.focus { background: rgba(102, 192, 244, 0.12) !important; color: #fff !important; border-left-color: rgba(102, 192, 244, 0.6) !important; } .sglv-panel .sglv-gs-item-thumb { width: 48px !important; height: 18px !important; flex-shrink: 0 !important; background: rgba(255, 255, 255, 0.04) !important; border-radius: 3px !important; overflow: hidden !important; display: flex !important; align-items: center !important; justify-content: center !important; transition: transform 0.15s ease !important; } .sglv-panel .sglv-gs-item:hover .sglv-gs-item-thumb, .sglv-panel .sglv-gs-item.focus .sglv-gs-item-thumb { transform: scale(1.08) !important; } .sglv-panel .sglv-gs-item-thumb img { width: 100% !important; height: 100% !important; object-fit: cover !important; } .sglv-panel .sglv-gs-item-body { flex: 1 1 auto !important; min-width: 0 !important; } .sglv-panel .sglv-gs-item-name { font-size: 12px !important; font-weight: 600 !important; color: #e2e8f0 !important; white-space: nowrap !important; overflow: hidden !important; text-overflow: ellipsis !important; } .sglv-panel .sglv-gs-item.focus .sglv-gs-item-name { color: #fff !important; } .sglv-panel .sglv-gs-item-name mark { background: rgba(102, 192, 244, 0.35) !important; color: #fff !important; padding: 0 1px !important; border-radius: 2px !important; } .sglv-panel .sglv-gs-item-sub { font-size: 10px !important; color: #8a9ba8 !important; white-space: nowrap !important; overflow: hidden !important; text-overflow: ellipsis !important; margin-top: 1px !important; } /*右侧徽章+图标容器,统一收紧间距 */ .sglv-panel .sglv-gs-item-right { display: flex !important; align-items: center !important; gap: 4px !important; flex-shrink: 0 !important; } .sglv-panel .sglv-gs-item-type { flex-shrink: 0 !important; font-size: 9px !important; font-weight: 700 !important; padding: 1px 5px !important; border-radius: 3px !important; text-transform: uppercase !important; letter-spacing: 0.04em !important; } .sglv-panel .sglv-gs-item-type.owned { background: rgba(63, 185, 80, 0.15) !important; color: #3fb950 !important; } .sglv-panel .sglv-gs-item-type.wishlist { background: rgba(245, 158, 11, 0.15) !important; color: #f59e0b !important; } .sglv-panel .sglv-gs-item-type.store { background: rgba(102, 192, 244, 0.15) !important; color: #66c0f4 !important; } /*精准匹配(AppID直接命中)行高亮 */ .sglv-panel .sglv-gs-item-exact { border-left: 3px solid #4ade80 !important; background: rgba(74, 222, 128, 0.04) !important; } .sglv-panel .sglv-gs-item-exact:hover, .sglv-panel .sglv-gs-item-exact.focus { background: rgba(74, 222, 128, 0.08) !important; } /*家庭共享次级徽章(紫色,小尺寸,紧贴主 type 徽章右侧) */ .sglv-panel .sglv-gs-item-shared { display: inline-flex !important; align-items: center !important; padding: 1px 6px !important; margin-left: 0 !important; font-size: 10px !important; font-weight: 600 !important; border-radius: 3px !important; background: rgba(139, 92, 246, 0.18) !important; color: #c4b5fd !important; border: 1px solid rgba(139, 92, 246, 0.35) !important; cursor: help !important; } .sglv-panel .sglv-gs-item-ext { display: inline-flex !important; align-items: center !important; color: #6e7681 !important; } .sglv-panel .sglv-gs-item-ext svg { width: 10px !important; height: 10px !important; } .sglv-panel .sglv-gs-empty { padding: 20px 12px !important; text-align: center !important; color: #6e7681 !important; font-size: 11px !important; display: flex !important; flex-direction: column !important; align-items: center !important; gap: 8px !important; } .sglv-panel .sglv-gs-empty-icon { opacity: 0.4 !important; } .sglv-panel .sglv-gs-empty-icon svg { width: 28px !important; height: 28px !important; } .sglv-panel .sglv-gs-footer { padding: 6px 12px !important; border-top: 1px solid rgba(255, 255, 255, 0.05) !important; font-size: 10px !important; color: #6e7681 !important; display: flex !important; align-items: center !important; gap: 10px !important; background: rgba(15, 23, 42, 0.5) !important; } .sglv-panel .sglv-gs-footer-hint { display: flex !important; align-items: center !important; gap: 3px !important; } .sglv-panel .sglv-gs-footer kbd { background: rgba(255, 255, 255, 0.08) !important; border: 1px solid rgba(255, 255, 255, 0.12) !important; border-radius: 3px !important; padding: 0 4px !important; font-size: 9px !important; font-family: monospace !important; color: #c7d5e0 !important; } /* === 游戏详情浮窗(点击搜索结果后弹出) === */ .sglv-panel .sglv-detail-overlay { position: absolute; inset: 0; background: rgba(0,0,0,0.5); z-index: 1000002; border-radius: inherit; opacity: 0; visibility: hidden; transition: opacity 0.16s ease, visibility 0s linear 0.16s; } .sglv-panel .sglv-detail-overlay.show { opacity: 1; visibility: visible; transition: opacity 0.16s ease, visibility 0s; } .sglv-panel .sglv-detail-pop { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -48%) scale(0.96); width: calc(100% - 48px); max-width: 560px; max-height: calc(85vh - 60px); background: linear-gradient(160deg, rgba(23,33,45,0.99), rgba(15,23,42,0.99)); border: 1px solid rgba(102,192,244,0.25); border-radius: 14px; box-shadow: 0 20px 60px rgba(0,0,0,0.6), 0 0 0 1px rgba(0,0,0,0.3); z-index: 1000003; overflow: hidden; display: flex; flex-direction: column; opacity: 0; visibility: hidden; transition: opacity 0.2s ease, transform 0.2s ease, visibility 0s linear 0.2s; } .sglv-panel .sglv-detail-pop.show { opacity: 1; visibility: visible; transform: translate(-50%, -50%) scale(1); transition: opacity 0.2s ease, transform 0.2s ease, visibility 0s; } .sglv-detail-close { position: absolute; top: 10px; right: 10px; z-index: 5; width: 30px; height: 30px; border-radius: 50%; border: none; background: rgba(0,0,0,0.4); color: #c7d5e0; cursor: pointer; display: flex; align-items: center; justify-content: center; transition: background 0.16s, color 0.16s; } .sglv-detail-close:hover { background: rgba(244,67,54,0.5); color: #fff; } .sglv-detail-close svg { width: 16px; height: 16px; } .sglv-detail-scroll { overflow-y: auto; overflow-x: hidden; } .sglv-detail-scroll::-webkit-scrollbar { width: 6px; } .sglv-detail-scroll::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.15); border-radius: 3px; } .sglv-detail-hero { position: relative; width: 100%; aspect-ratio: 231/87; overflow: hidden; background: #1a2332; } .sglv-detail-hero img { width: 100%; height: 100%; object-fit: cover; display: block; } .sglv-detail-hero::after { content:''; position:absolute; inset:0; background: linear-gradient(180deg, transparent 40%, rgba(15,23,42,0.95)); } .sglv-detail-body { padding: 0 18px 18px; } .sglv-detail-name { font-size: 18px; font-weight: 700; color: #e2e8f0; margin: -20px 0 4px; position: relative; z-index: 1; text-shadow: 0 2px 8px rgba(0,0,0,0.8); } .sglv-detail-desc { font-size: 12px; color: #8b949e; line-height: 1.6; margin: 10px 0; } .sglv-detail-meta { display: grid; grid-template-columns: auto 1fr; gap: 4px 12px; font-size: 11px; margin: 10px 0; } .sglv-detail-meta dt { color: #6e7681; font-weight: 600; } .sglv-detail-meta dd { color: #c7d5e0; margin: 0; } .sglv-detail-tags { display: flex; flex-wrap: wrap; gap: 4px; margin: 10px 0; } .sglv-detail-tag { font-size: 10px; padding: 2px 8px; border-radius: 4px; background: rgba(102,192,244,0.1); color: #66c0f4; border: 1px solid rgba(102,192,244,0.15); } .sglv-detail-price { display: flex; align-items: center; gap: 8px; margin: 10px 0; } .sglv-detail-price-val { font-size: 16px; font-weight: 700; color: #4ade80; } .sglv-detail-price-discount { font-size: 12px; color: #fbbf24; } .sglv-detail-price-free { font-size: 16px; font-weight: 700; color: #4ade80; } .sglv-detail-shots { display: flex; gap: 6px; overflow-x: auto; margin: 10px 0; padding-bottom: 4px; } .sglv-detail-shots::-webkit-scrollbar { height: 4px; } .sglv-detail-shots::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.15); border-radius: 2px; } .sglv-detail-shot { flex-shrink: 0; width: 200px; height: 113px; border-radius: 6px; overflow: hidden; background: #1a2332; } .sglv-detail-shot img { width: 100%; height: 100%; object-fit: cover; display: block; } .sglv-detail-actions { display: flex; gap: 8px; margin-top: 14px; padding-top: 14px; border-top: 1px solid rgba(255,255,255,0.06); } .sglv-detail-btn { display: inline-flex; align-items: center; gap: 5px; padding: 8px 16px; border-radius: 8px; font-size: 12px; font-weight: 600; cursor: pointer; border: none; transition: all 0.16s; text-decoration: none; } .sglv-detail-btn-primary { background: linear-gradient(135deg, #66c0f4, #1a9fff); color: #fff; } .sglv-detail-btn-primary:hover { filter: brightness(1.1); } .sglv-detail-btn-secondary { background: rgba(255,255,255,0.08); color: #c7d5e0; } .sglv-detail-btn-secondary:hover { background: rgba(255,255,255,0.14); } .sglv-detail-btn-ai { background: linear-gradient(135deg, #6366f1, #8b5cf6); color: #fff; } .sglv-detail-btn-ai:hover { filter: brightness(1.15); } .sglv-detail-btn svg { width: 14px; height: 14px; } .sglv-detail-loading { display: flex; flex-direction: column; align-items: center; justify-content: center; min-height: 200px; gap: 12px; color: #6e7681; font-size: 12px; } .sglv-detail-error { display: flex; flex-direction: column; align-items: center; justify-content: center; min-height: 200px; gap: 8px; color: #f87171; font-size: 12px; } .sglv-detail-metacritic { display: inline-flex; align-items: center; gap: 4px; font-size: 11px; padding: 2px 8px; border-radius: 4px; font-weight: 700; } /* === body 首屏骨架占位(避免空数据时出现完全空白) === */ .sglv-body-loading { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%; min-height: 320px; padding: 40px 20px; gap: 16px; color: #94a3b8; font-size: 13px; text-align: center; } .sglv-body-loading .sglv-bl-title { font-size: 15px; font-weight: 600; color: #cbd5e1; } .sglv-body-loading .sglv-bl-tip { font-size: 12px; color: #64748b; line-height: 1.6; max-width: 420px; } .sglv-body-loading .sglv-bl-spinner { width: 36px; height: 36px; border: 3px solid rgba(102, 192, 244, 0.15); border-top-color: #66c0f4; border-radius: 50%; animation: sglv-spin 0.9s linear infinite; } .sglv-body-loading .sglv-bl-actions { display: flex; gap: 8px; margin-top: 4px; } .sglv-body-loading .sglv-bl-btn { padding: 6px 14px; font-size: 12px; font-weight: 600; border-radius: 6px; border: 1px solid rgba(102, 192, 244, 0.3); background: rgba(102, 192, 244, 0.1); color: #66c0f4; cursor: pointer; transition: background 0.15s, border-color 0.15s; } .sglv-body-loading .sglv-bl-btn:hover { background: rgba(102, 192, 244, 0.2); border-color: rgba(102, 192, 244, 0.5); } .sglv-body-loading .sglv-bl-btn.primary { background: linear-gradient(135deg, rgba(139, 92, 246, 0.25), rgba(102, 192, 244, 0.2)); border-color: rgba(139, 92, 246, 0.4); color: #c4b5fd; } .sglv-body-loading .sglv-bl-btn.primary:hover { background: linear-gradient(135deg, rgba(139, 92, 246, 0.35), rgba(102, 192, 244, 0.3)); } /* === 统计仪表布局——热力图行改自适应内容高度(不再撑满 wrap),6月增量SVG加高减少留白 === */ /*sglv-body 需 min-height:0 确保 flex 子项正确滚动(移动端关键修复) */ .sglv-body { min-height: 0 !important; } /* wrap: flex:1 填满 sglv-body 可用高度,内部 flex column 纵向排列各区块 */ .sglv-playtime-wrap { display: flex !important; flex-direction: column !important; flex: 1 1 0 !important; min-height: 0 !important; gap: 10px !important; overflow-y: auto !important; padding: 12px !important; } /*图表行(甜甜圈+趋势) 使用内容高度,不再 flex-grow 撑满 wrap 剩余空间。 低分屏下 flex-grow:1 会吞掉热力图行的可用高度,导致下方热力图/增量图被挤压变形。 改为 flex:0 0 auto 后,各行按内容自然排列,wrap 的 overflow-y:auto 负责纵向滚动。 */ .sglv-playtime-row { flex: 0 0 auto !important; min-height: 0 !important; } /*图表列最小高度,确保甜甜圈/趋势图有足够渲染空间 */ .sglv-playtime-col { min-height: 220px !important; } /*雷达行紧凑:雷达卡内容居中、右侧统计面板均匀分布填满高度,消除底部空白失衡 */ .sglv-radar-card { justify-content: center; } .sglv-radar-stats { justify-content: space-between; } /*图表行(甜甜圈+趋势)适度紧凑:限制列高与甜甜圈尺寸,下方热力图/增量区更快进入视野。 注意只限 svg 高度——覆写宽度会让 CDN 库的 viewBox SVG 宽度塌缩消失 */ .sglv-playtime-row { max-height: 320px !important; } .sglv-playtime-col { max-height: 320px !important; overflow: hidden !important; } .sglv-playtime-col > #sglv-pt-donut { flex: 1 1 auto; min-height: 0; overflow: hidden; display: flex; flex-direction: column; justify-content: center; } .sglv-playtime-col > #sglv-pt-donut svg { max-height: 190px !important; } .sglv-playtime-col > #sglv-pt-donut .sglv-donut-chart { flex-shrink: 1; min-height: 0; } /*热力图行 grid 7:3——改成自适应内容高度 + 最小高度,不再撑满 wrap 剩余高度,避免盖住上方 KPI/图表区 */ /*overflow 从 hidden 改为 visible,允许内容自然溢出由 wrap 的 overflow-y:auto 滚动,而非裁剪变形 */ .sglv-heatmap-acquire-row { display: grid !important; grid-template-columns: 7fr 3fr !important; align-items: stretch !important; min-height: 320px !important; flex: 0 0 auto !important; gap: 10px !important; overflow: visible !important; } .sglv-heatmap-acquire-row .sglv-heatmap-section, .sglv-heatmap-acquire-row .sglv-heatmap-mini-section { flex: none !important; min-width: 0 !important; max-width: none !important; min-height: 280px !important; display: flex !important; flex-direction: column !important; overflow: visible !important; } /*热力图 block 撑满 section 高度 */ .sglv-heatmap-acquire-row .sglv-heatmap-block, .sglv-heatmap-acquire-row .sglv-heatmap-mini-skeleton, .sglv-heatmap-acquire-row .sglv-hm-mini-inner { flex: 1 1 0 !important; min-height: 0 !important; } /*增量柱图——SVG 用 auto 高度而非 100%,避免容器被压缩时 SVG 跟着变形 */ .sglv-heatmap-acquire-row .sglv-hm-mini-chart { flex: 1 1 auto !important; min-height: 120px !important; } .sglv-heatmap-acquire-row .sglv-hm-mini-chart svg { height: auto !important; max-height: 100% !important; } /*热力图 SVG 保持原始尺寸,由 scroll 容器水平滚动展示完整内容 */ .sglv-heatmap-block svg { max-width: 100% !important; height: auto !important; } .sglv-heatmap-scroll svg { max-width: none !important; height: auto !important; display: block !important; } .sglv-heatmap-acquire-row .sglv-heatmap-scroll { overflow-x: auto !important; } /*热力图 section 紧凑 padding + scroll 容器居中(SVG 内容垂直居中) */ .sglv-heatmap-acquire-row .sglv-heatmap-section { padding: 10px 12px 8px !important; } .sglv-heatmap-acquire-row .sglv-heatmap-mini-section { padding: 10px 12px 8px !important; } .sglv-heatmap-section > #sglv-pt-heatmap { flex: 1 1 0 !important; min-height: 0 !important; display: flex !important; flex-direction: column !important; justify-content: flex-start !important; } /*热力图 scroll 紧凑 padding-bottom */ .sglv-heatmap-scroll { padding-bottom: 2px !important; } /*heatmap-body 擑满 block 剩余高度,scroll 区域可滚动 + 居中 SVG */ .sglv-heatmap-acquire-row .sglv-heatmap-body { flex: 1 1 0 !important; min-height: 0 !important; display: flex !important; flex-direction: column !important; } .sglv-heatmap-acquire-row .sglv-heatmap-body .sglv-heatmap-scroll { flex: 1 1 0 !important; min-height: 0 !important; display: flex !important; flex-direction: column !important; justify-content: center !important; } .sglv-heatmap-acquire-row .sglv-heatmap-body .sglv-heatmap-scroll > svg { flex: 0 0 auto !important; align-self: flex-start !important; } /* 趋势图折线等比缩放(meet)后居中 */ .sglv-pt-trend-chart { align-items: center !important; } /*增量柱图底部统计栏样式 */ .sglv-hm-mini-summary { display: flex; flex-wrap: wrap; gap: 8px; padding: 6px 4px 0; flex-shrink: 0; } .sglv-hm-mini-stat { font-size: 10px; color: var(--sglv-text-secondary); white-space: nowrap; } .sglv-hm-mini-stat b { font-size: 13px; font-weight: 800; color: #e0e0e0; } /* 移动端热力图行恢复上下排列 */ @media (max-width: 900px) { .sglv-heatmap-acquire-row { grid-template-columns: 1fr !important; } } /* === 移动端统计仪表适配——KPI 卡片防换行 + 热力图高度收缩 === */ /* KPI 卡片内部文字截断,防止窄屏换行变形 */ .sglv-playtime-kpi-value { white-space: nowrap !important; overflow: hidden !important; text-overflow: ellipsis !important; } .sglv-playtime-kpi-sub { white-space: nowrap !important; overflow: hidden !important; text-overflow: ellipsis !important; } .sglv-playtime-kpi-label { white-space: nowrap !important; overflow: hidden !important; text-overflow: ellipsis !important; } @media (max-width: 768px) { /* KPI 卡片:2 列布局时进一步紧凑化 */ .sglv-playtime-kpi-row { gap: 5px !important; } .sglv-playtime-kpi-row .sglv-playtime-kpi-card { padding: 5px 8px 4px !important; } .sglv-playtime-kpi-row .sglv-playtime-kpi-value { font-size: 15px !important; } .sglv-playtime-kpi-row .sglv-playtime-kpi-label { font-size: 9px !important; } .sglv-playtime-kpi-row .sglv-playtime-kpi-sub { font-size: 8px !important; } .sglv-playtime-kpi-row .sglv-playtime-kpi-icon { width: 14px !important; height: 14px !important; } .sglv-playtime-kpi-row .sglv-playtime-kpi-icon svg { width: 9px !important; height: 9px !important; } .sglv-playtime-kpi-row .sglv-playtime-kpi-unit { font-size: 10px !important; } /*热力图行降低最小高度,但仍保持足够渲染空间,由 wrap 滚动而非压缩 */ .sglv-heatmap-acquire-row { min-height: 260px !important; } .sglv-heatmap-acquire-row .sglv-heatmap-section, .sglv-heatmap-acquire-row .sglv-heatmap-mini-section { padding: 8px 10px 6px !important; min-height: 220px !important; } /* 图表行(甜甜圈+趋势) 单列堆叠时限制高度,避免无限增高 */ .sglv-playtime-row { flex: 0 0 auto !important; } .sglv-playtime-col { min-height: 200px !important; max-height: 280px !important; } .sglv-playtime-col > #sglv-pt-donut { min-height: 160px !important; } .sglv-pt-trend-chart { min-height: 160px !important; } } @media (max-width: 480px) { /* 超窄屏:KPI 保持 2 列但进一步缩小 */ .sglv-playtime-kpi-row { gap: 4px !important; } .sglv-playtime-kpi-row .sglv-playtime-kpi-card { padding: 4px 6px 3px !important; } .sglv-playtime-kpi-row .sglv-playtime-kpi-value { font-size: 14px !important; } .sglv-playtime-kpi-row .sglv-playtime-kpi-label { font-size: 8px !important; } .sglv-playtime-kpi-row .sglv-playtime-kpi-sub { font-size: 7px !important; } /*热力图行降低高度但保持最小渲染空间 */ .sglv-heatmap-acquire-row { min-height: 220px !important; } .sglv-heatmap-acquire-row .sglv-heatmap-section, .sglv-heatmap-acquire-row .sglv-heatmap-mini-section { min-height: 180px !important; } /* 图表列限制高度 */ .sglv-playtime-col { min-height: 180px !important; max-height: 240px !important; } /* wrap 内边距收紧 */ .sglv-playtime-wrap { padding: 8px !important; gap: 8px !important; } } /* === 分页导航——简化单行布局,首页|上页|下页|末页 + 跳页输入 === */ .sglv-tl-pagination, .sglv-pagination, .sglv-pt-pagination { display: flex !important; align-items: center !important; justify-content: center !important; flex-wrap: nowrap !important; gap: 4px !important; padding: 8px 0 2px !important; overflow: hidden !important; } /* 箭头/文本按钮 */ .sglv-page-arrow { min-width: 24px; height: 24px; padding: 0 2px; border: 1px solid rgba(255,255,255,0.1); border-radius: 5px; background: rgba(255,255,255,0.04); color: #c7d5e0; font-size: 13px; line-height: 1; cursor: pointer; transition: var(--sglv-transition); text-align: center; flex-shrink: 0; } .sglv-page-arrow:hover:not(:disabled) { background: rgba(102,192,244,0.15); border-color: rgba(102,192,244,0.4); color: #fff; } .sglv-page-arrow:disabled { opacity: 0.3; cursor: not-allowed; } /* 中文文本按钮——加宽适配文字 */ .sglv-page-text-btn { min-width: auto !important; padding: 0 8px !important; font-size: 11px !important; white-space: nowrap !important; } /* 页码按钮组(已废弃,隐藏) */ .sglv-page-btns { display: none !important; } .sglv-page-btn { display: none !important; } .sglv-page-ellipsis { display: none !important; } /* 跳页输入框——紧凑,回车跳转 */ .sglv-page-jump-input { width: 38px; height: 24px; padding: 0 2px; text-align: center; background: rgba(255,255,255,0.08); border: 1px solid rgba(255,255,255,0.1); border-radius: 4px; color: #fff; font-size: 11px; outline: none; flex-shrink: 0; -moz-appearance: textfield; } .sglv-page-jump-input::-webkit-inner-spin-button, .sglv-page-jump-input::-webkit-outer-spin-button { -webkit-appearance: none; margin: 0; } .sglv-page-jump-input:focus { border-color: rgba(102,192,244,0.5); } /* 页码信息——极简 */ .sglv-page-info { font-size: 10px !important; color: var(--sglv-text-secondary) !important; white-space: nowrap !important; flex-shrink: 0 !important; } /* 工具栏内嵌分页——更紧凑,隐藏箭头和跳页 */ .sglv-pagination-inline .sglv-page-arrow { min-width: 20px; height: 20px; font-size: 11px; } .sglv-pagination-inline .sglv-page-btn { min-width: 20px; height: 20px; font-size: 10px; } .sglv-pagination-inline .sglv-page-jump-input { display: none; } .sglv-pagination-inline .sglv-page-info { display: none; } /* === 统计仪表 KPI 卡片 6 列 1 行紧凑布局 + 扁平化(参考设计图) === */ .sglv-playtime-kpi-row { grid-template-columns: repeat(6, 1fr) !important; gap: 6px !important; } @media (max-width: 1280px) { .sglv-playtime-kpi-row { grid-template-columns: repeat(3, 1fr) !important; } } @media (max-width: 700px) { .sglv-playtime-kpi-row { grid-template-columns: repeat(2, 1fr) !important; } } /* 6 列 1 行时各元素字号紧凑 */ .sglv-playtime-kpi-row .sglv-playtime-kpi-value { font-size: 17px !important; } .sglv-playtime-kpi-row .sglv-playtime-kpi-label { font-size: 10px !important; } .sglv-playtime-kpi-row .sglv-playtime-kpi-sub { font-size: 9px !important; } .sglv-playtime-kpi-row .sglv-playtime-kpi-icon { width: 16px !important; height: 16px !important; } .sglv-playtime-kpi-row .sglv-playtime-kpi-icon svg { width: 10px !important; height: 10px !important; } .sglv-playtime-kpi-row .sglv-playtime-kpi-unit { font-size: 11px !important; } /*KPI 卡片扁平化——弱化边框,靠左侧色条 + 背景色区分,参考设计图 */ .sglv-playtime-kpi-card { border-width: 1px !important; border-left-width: 3px !important; } /* === 游玩率/完成度 KPI 卡片颜色变体(cyan/rose)+ % 单位字号 === */ .sglv-playtime-kpi-card.cyan { border-color: rgba(34, 211, 238, 0.35); } .sglv-playtime-kpi-card.cyan::before { background: #22d3ee; } .sglv-playtime-kpi-card.cyan .sglv-playtime-kpi-value { color: #22d3ee; } .sglv-playtime-kpi-card.cyan .sglv-playtime-kpi-icon { background: rgba(34, 211, 238, 0.15); color: #22d3ee; } .sglv-playtime-kpi-card.rose { border-color: rgba(244, 63, 94, 0.35); } .sglv-playtime-kpi-card.rose::before { background: #f43f5e; } .sglv-playtime-kpi-card.rose .sglv-playtime-kpi-value { color: #fb7185; } .sglv-playtime-kpi-card.rose .sglv-playtime-kpi-icon { background: rgba(244, 63, 94, 0.15); color: #fb7185; } .sglv-playtime-kpi-card.gold { border-color: rgba(251, 191, 36, 0.3); } .sglv-playtime-kpi-card.gold::before { background: #fbbf24; } .sglv-playtime-kpi-card.gold .sglv-playtime-kpi-value { color: #fbbf24; } .sglv-playtime-kpi-card.gold .sglv-playtime-kpi-icon { background: rgba(251, 191, 36, 0.12); color: #fbbf24; } .sglv-playtime-kpi-unit { font-size: 13px; font-weight: 700; opacity: 0.85; margin-left: 2px; } /* === 入库趋势页 KPI 紧凑布局(4 卡放左半侧顶部)+ 时间线撑到顶部 === */ .sglv-trend-kpi-row-compact { gap: 6px !important; margin-bottom: 8px !important; } .sglv-trend-kpi-row-compact .sglv-trend-kpi-card { padding: 7px 10px !important; } .sglv-trend-kpi-row-compact .sglv-trend-kpi-value { font-size: 17px !important; } .sglv-trend-kpi-row-compact .sglv-trend-kpi-label { font-size: 10px !important; } .sglv-trend-kpi-row-compact .sglv-trend-kpi-sub { font-size: 9px !important; } .sglv-trend-kpi-row-compact .sglv-trend-kpi-icon { width: 16px !important; height: 16px !important; } .sglv-trend-kpi-row-compact .sglv-trend-kpi-icon svg { width: 10px !important; height: 10px !important; } /* 时间线顶到页面顶部:rightCol 整体高度撑满 */ .sglv-trend-split-right { align-self: stretch; } /* === KPI 两行布局 + 新色彩变体 === */ .sglv-trend-kpi-wrap { display: flex; flex-direction: column; gap: 6px; margin-bottom: 8px; flex-shrink: 0; } .sglv-trend-kpi-wrap .sglv-trend-kpi-row { margin-bottom: 0 !important; } .sglv-trend-kpi-card.green { border-color: rgba(52,211,153,0.3); } .sglv-trend-kpi-card.green::before { background: #34d399; } .sglv-trend-kpi-card.green .sglv-trend-kpi-value { color: #34d399; } .sglv-trend-kpi-card.green .sglv-trend-kpi-icon { background: rgba(52,211,153,0.15); color: #34d399; } .sglv-trend-kpi-card.orange { border-color: rgba(245,158,11,0.3); } .sglv-trend-kpi-card.orange::before { background: #f59e0b; } .sglv-trend-kpi-card.orange .sglv-trend-kpi-value { color: #f59e0b; } .sglv-trend-kpi-card.orange .sglv-trend-kpi-icon { background: rgba(245,158,11,0.15); color: #f59e0b; } .sglv-trend-kpi-card.cyan { border-color: rgba(6,182,212,0.3); } .sglv-trend-kpi-card.cyan::before { background: #06b6d4; } .sglv-trend-kpi-card.cyan .sglv-trend-kpi-value { color: #22d3ee; } .sglv-trend-kpi-card.cyan .sglv-trend-kpi-icon { background: rgba(6,182,212,0.15); color: #22d3ee; } .sglv-trend-kpi-card.purple { border-color: rgba(167,139,250,0.3); } .sglv-trend-kpi-card.purple::before { background: #a78bfa; } .sglv-trend-kpi-card.purple .sglv-trend-kpi-value { color: #a78bfa; } .sglv-trend-kpi-card.purple .sglv-trend-kpi-icon { background: rgba(167,139,250,0.15); color: #a78bfa; } .sglv-trend-kpi-unit { font-size: 10px; font-weight: 600; opacity: 0.7; margin-left: 2px; } /* === 右侧标签切换 === */ .sglv-trend-right-tabs { display: flex; gap: 2px; margin-bottom: 10px; flex-shrink: 0; border-bottom: 1px solid rgba(148,163,184,0.12); } .sglv-trend-right-tab { display: inline-flex; align-items: center; gap: 5px; padding: 6px 12px; font-size: 12px; font-weight: 600; color: #8a9ba8; background: transparent; border: none; border-bottom: 2px solid transparent; cursor: pointer; transition: color 0.15s, border-color 0.15s; white-space: nowrap; } .sglv-trend-right-tab svg { width: 14px; height: 14px; } .sglv-trend-right-tab:hover { color: #cbd5e1; } .sglv-trend-right-tab.active { color: var(--sglv-accent, #66c0f4); border-bottom-color: var(--sglv-accent, #66c0f4); } .sglv-trend-right-content { flex: 1; display: flex; flex-direction: column; min-height: 0; overflow: hidden; } /* === 频率分析图表 === */ .sglv-freq-scroll { flex: 1; overflow-y: auto; min-height: 0; padding-right: 2px; } .sglv-freq-scroll::-webkit-scrollbar { width: 5px; } .sglv-freq-scroll::-webkit-scrollbar-thumb { background: rgba(148,163,184,0.2); border-radius: 3px; } .sglv-freq-summary-row { display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px; margin-bottom: 14px; } .sglv-freq-summary-card { display: flex; flex-direction: column; align-items: center; gap: 2px; padding: 8px 6px; background: rgba(255,255,255,0.03); border: 1px solid rgba(148,163,184,0.1); border-radius: 8px; text-align: center; } .sglv-freq-summary-label { font-size: 9px; color: #64748b; font-weight: 600; } .sglv-freq-summary-value { font-size: 16px; font-weight: 700; color: #e2e8f0; } .sglv-freq-summary-sub { font-size: 9px; color: #475569; } .sglv-freq-chart-section { margin-bottom: 14px; } .sglv-freq-chart-title { font-size: 11px; font-weight: 700; color: #94a3b8; margin-bottom: 6px; } .sglv-freq-chart svg rect { transition: opacity 0.15s; } .sglv-freq-chart svg rect[data-v] { cursor: pointer; } .sglv-freq-chart-labels { display: flex; font-size: 9px; color: #475569; margin-top: 3px; } .sglv-freq-chart-labels span { flex: 1; text-align: center; } .sglv-freq-chart-labels-hr span { font-size: 8px; } /* === 游玩数据页——家庭成员对比紧凑到右半侧底部,Top 20 撑到更高视野 === */ .sglv-playtime-split-right { gap: 0; } /* 家庭对比放右半侧后紧凑显示:限制高度 + 内部滚动 */ .sglv-playtime-split-right > .sglv-family-compare-section { flex-shrink: 0; margin: 10px 0 0; padding: 10px 12px; max-height: 200px; background: rgba(255, 255, 255, 0.02); border: 1px solid rgba(255, 255, 255, 0.06); border-radius: 8px; display: flex; flex-direction: column; overflow: hidden; } .sglv-playtime-split-right > .sglv-family-compare-section .sglv-playtime-section-title { margin-bottom: 6px; font-size: 12px; } .sglv-playtime-split-right > .sglv-family-compare-section .sglv-family-compare-container { margin-top: 0; max-height: 140px; overflow-y: auto; } /*游戏橱窗 KPI 扁平化——与统计仪表/入库趋势页一致,左侧色条+紧凑 padding */ .sglv-stats-dashboard .sglv-stat-dash-card { padding: 6px 10px 5px !important; border-left-width: 3px !important; } @keyframes sglv-skel-pulse { 0%, 100% { opacity: 0.55; } 50% { opacity: 0.9; } } @keyframes sglv-skel-shimmer-x { 0% { background-position: -200% 0; } 100% { background-position: 200% 0; } } .sglv-heatmap-skeleton svg rect { animation: sglv-skel-pulse 1.6s ease-in-out infinite; } .sglv-heatmap-skeleton svg rect:nth-child(odd) { animation-delay: 0.15s; } .sglv-heatmap-skeleton svg rect:nth-child(3n) { animation-delay: 0.3s; } .sglv-heatmap-mini-skeleton rect { animation: sglv-skel-pulse 1.4s ease-in-out infinite; } .sglv-heatmap-mini-skeleton rect:nth-child(odd) { animation-delay: 0.2s; } .sglv-family-bar-skel .sglv-family-bar-track { background: rgba(255, 255, 255, 0.04) !important; } .sglv-family-bar-skel .sglv-family-bar-name, .sglv-family-bar-skel .sglv-family-bar-hours { background: linear-gradient(90deg, rgba(255, 255, 255, 0.04) 0%, rgba(255, 255, 255, 0.1) 50%, rgba(255, 255, 255, 0.04) 100%) !important; background-size: 200% 100%; animation: sglv-skel-shimmer-x 1.6s linear infinite; } .sglv-family-bar-skel:nth-child(2) .sglv-family-bar-name, .sglv-family-bar-skel:nth-child(2) .sglv-family-bar-hours { animation-delay: 0.15s; } .sglv-family-bar-skel:nth-child(3) .sglv-family-bar-name, .sglv-family-bar-skel:nth-child(3) .sglv-family-bar-hours { animation-delay: 0.3s; } .sglv-family-bar-skel:nth-child(4) .sglv-family-bar-name, .sglv-family-bar-skel:nth-child(4) .sglv-family-bar-hours { animation-delay: 0.45s; }`; const CSS_SGIS_ENHANCE =` /* === tab 容器:增加底部高光 + tab 之间分隔感 === */ .sgis-tabs { position: relative; } .sgis-tabs::after { content: ""; position: absolute; left: 12px; right: 12px; bottom: -1px; height: 1px; background: linear-gradient(90deg, transparent, rgba(139, 92, 246, 0.35), transparent); pointer-events: none; } /* === tab 本身:图标上浮 + 文字微微缩放 === */ .sgis-tab .sgis-svg { transition: transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1); } .sgis-tab:hover .sgis-svg { transform: translateY(-1px) scale(1.08); } .sgis-tab.active .sgis-svg { transform: translateY(-0.5px) scale(1.12); filter: drop-shadow(0 1px 4px rgba(139, 92, 246, 0.45)); } .sgis-tab span { transition: font-weight 0.2s, letter-spacing 0.2s; } .sgis-tab.active span { font-weight: 700; letter-spacing: 0.3px; } /* 连点标签时只是在等最后一次点击落定,鼠标给出反馈,点击仍然有效 */ .sgis-tabs.is-arming .sgis-tab { cursor: progress; } /* === 标题图标:更精致渐变 + 内阴影 === */ .sgis-title-icon { background: linear-gradient(135deg, #8b5cf6 0%, #6366f1 45%, #3b82f6 100%) !important; box-shadow: 0 4px 12px rgba(139, 92, 246, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.25), inset 0 -1px 0 rgba(0, 0, 0, 0.2) !important; } .sgis-title-icon::after { background: linear-gradient(180deg, rgba(255, 255, 255, 0.18) 0%, transparent 45%) !important; } /* === 右上角 action 按钮:加 active 反馈 === */ .sgis-icon-btn:active { transform: translateY(0) scale(0.94) !important; } .sgis-icon-btn.sgis-spin svg { animation: sgis-spin 0.8s linear infinite, sgis-pulse 1.4s ease-in-out infinite; } @keyframes sgis-pulse { 0%, 100% { box-shadow: 0 2px 8px rgba(139, 92, 246, 0.25); } 50% { box-shadow: 0 2px 14px rgba(139, 92, 246, 0.6); } } /* === SGIS 整体滚动条更精致 === */ .sgis-body::-webkit-scrollbar-thumb { background: linear-gradient(180deg, rgba(139, 92, 246, 0.45), rgba(59, 130, 246, 0.45)) !important; } .sgis-pane { min-width: 0; } .sgis-pane.is-active { animation: sgis-pane-in .18s ease; } @keyframes sgis-pane-in { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: none; } } .sgis-tab-pending { min-height: 160px; } .sgis-social-friend { content-visibility: auto; contain-intrinsic-size: auto 64px; } /* === SGIS 状态指示器(用于加载/错误/空状态) === */ .sgis-state-icon { width: 48px; height: 48px; border-radius: 14px; background: linear-gradient(135deg, rgba(139, 92, 246, 0.15), rgba(59, 130, 246, 0.08)); border: 1px solid rgba(139, 92, 246, 0.2); display: inline-flex; align-items: center; justify-content: center; margin-bottom: 10px; color: #a78bfa; box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.06); } .sgis-state-icon svg { width: 22px; height: 22px; } /* === 错误状态用红 === */ .sgis-state.error .sgis-state-icon { background: linear-gradient(135deg, rgba(244, 63, 94, 0.15), rgba(244, 63, 94, 0.05)); border-color: rgba(244, 63, 94, 0.3); color: #f87171; } /* === 徽章标签页英雄区(顶部总览) === */ .sgis-badge-hero { position: relative; background: linear-gradient(135deg, rgba(139, 92, 246, 0.18) 0%, rgba(59, 130, 246, 0.1) 50%, var(--sgis-bg-2) 100%); border: 1px solid rgba(139, 92, 246, 0.3); border-radius: 12px; padding: 14px 14px 12px; margin-bottom: 10px; overflow: hidden; box-shadow: 0 4px 16px rgba(139, 92, 246, 0.08), inset 0 1px 0 rgba(255, 255, 255, 0.05); } .sgis-badge-hero::before { content: ""; position: absolute; top: -40px; right: -30px; width: 140px; height: 140px; background: radial-gradient(circle, rgba(139, 92, 246, 0.25) 0%, transparent 65%); pointer-events: none; } .sgis-badge-hero::after { content: ""; position: absolute; bottom: -30px; left: -20px; width: 100px; height: 100px; background: radial-gradient(circle, rgba(6, 182, 212, 0.15) 0%, transparent 60%); pointer-events: none; } .sgis-badge-hero > * { position: relative; z-index: 1; } .sgis-badge-hero-stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px; margin-bottom: 10px; } .sgis-badge-hero-stat { text-align: center; padding: 6px 4px; background: rgba(255, 255, 255, 0.04); border-radius: 7px; border: 1px solid rgba(255, 255, 255, 0.05); } .sgis-badge-hero-stat.highlight { background: linear-gradient(135deg, rgba(16, 185, 129, 0.15), rgba(20, 184, 166, 0.08)); border-color: rgba(16, 185, 129, 0.3); } .sgis-badge-hero-stat-val { font-size: 18px; font-weight: 800; color: #fff; line-height: 1.1; font-variant-numeric: tabular-nums; letter-spacing: -0.5px; } .sgis-badge-hero-stat.highlight .sgis-badge-hero-stat-val { color: #34d399; } .sgis-badge-hero-stat-lbl { font-size: 9px; color: var(--sgis-text-2); margin-top: 2px; font-weight: 600; } .sgis-badge-hero-stat.highlight .sgis-badge-hero-stat-lbl { color: #6ee7b7; } .sgis-badge-hero-progress { margin-bottom: 12px; } .sgis-badge-hero-progress-label { display: flex; justify-content: space-between; font-size: 10px; color: var(--sgis-text-2); margin-bottom: 4px; font-weight: 600; } .sgis-badge-hero-progress-label span:last-child { color: #c4b5fd; } .sgis-badge-hero-progress-bar { height: 6px; background: rgba(255, 255, 255, 0.06); border-radius: 3px; overflow: hidden; box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.3); } .sgis-badge-hero-progress-fill { height: 100%; background: linear-gradient(90deg, #10b981 0%, #34d399 100%); border-radius: 3px; transition: width 0.5s; box-shadow: 0 0 6px rgba(16, 185, 129, 0.4); } .sgis-badge-hero-levels { padding-top: 10px; border-top: 1px dashed rgba(255, 255, 255, 0.08); } .sgis-badge-hero-levels-label { font-size: 10px; color: var(--sgis-text-2); margin-bottom: 6px; font-weight: 600; } .sgis-badge-hero-levels-bars { display: flex; align-items: flex-end; justify-content: space-around; gap: 4px; height: 50px; } .sgis-badge-hero-level-cell { flex: 1; display: flex; flex-direction: column; align-items: center; gap: 2px; min-width: 0; } .sgis-badge-hero-level-bar { width: 100%; min-height: 3px; max-width: 24px; background: linear-gradient(180deg, #8b5cf6 0%, #6366f1 100%); border-radius: 3px 3px 0 0; flex: 1; align-self: flex-end; display: flex; align-items: flex-start; justify-content: center; padding-top: 2px; box-shadow: 0 0 6px rgba(139, 92, 246, 0.3); transition: height 0.4s; } .sgis-badge-hero-level-count { font-size: 9px; color: #fff; font-weight: 700; font-variant-numeric: tabular-nums; } .sgis-badge-hero-level-num { font-size: 9px; color: var(--sgis-text-2); font-weight: 600; } /* === 章节标题 meta(右侧次要信息) === */ .sgis-section-title-meta { font-size: 10px; color: var(--sgis-text-2); font-weight: 500; text-transform: none; letter-spacing: 0; margin-left: auto; } /* === 洞察页成就引导入口(替代旧折叠列表) === */ .sgis-insight-ach-entry { display: flex; align-items: center; gap: 12px; padding: 12px 14px; background: linear-gradient(135deg, rgba(251, 191, 36, 0.08), rgba(245, 158, 11, 0.04)); border: 1px solid rgba(251, 191, 36, 0.18); border-radius: 10px; transition: all 0.25s ease; margin-top: 2px; } .sgis-insight-ach-entry:hover { background: linear-gradient(135deg, rgba(251, 191, 36, 0.14), rgba(245, 158, 11, 0.08)); border-color: rgba(251, 191, 36, 0.35); transform: translateY(-1px); box-shadow: 0 4px 12px rgba(251, 191, 36, 0.12); } .sgis-insight-ach-entry > svg { width: 36px; height: 36px; flex-shrink: 0; filter: drop-shadow(0 2px 4px rgba(251, 191, 36, 0.25)); } .sgis-insight-ach-entry-info { flex: 1; min-width: 0; } .sgis-insight-ach-entry-title { font-size: 12px; font-weight: 700; color: #fef3c7; margin-bottom: 2px; line-height: 1.3; } .sgis-insight-ach-entry-sub { font-size: 10px; color: var(--sgis-text-2); line-height: 1.4; } .sgis-insight-ach-entry-btn { flex-shrink: 0; padding: 5px 10px; background: linear-gradient(135deg, #fbbf24, #f59e0b); color: #1c0a01; border: none; border-radius: 6px; font-size: 10px; font-weight: 700; cursor: pointer; transition: all 0.2s ease; white-space: nowrap; } .sgis-insight-ach-entry-btn:hover { background: linear-gradient(135deg, #fcd34d, #fbbf24); transform: translateY(-1px); box-shadow: 0 2px 6px rgba(251, 191, 36, 0.4); } .sgis-insight-ach-entry-btn:active { transform: translateY(0); } /* === 徽章 group 头增强(加进度条 + 已合成数) === */ .sgis-badge-group-head { gap: 10px; padding: 9px 12px; } .sgis-badge-group-head:hover { background: linear-gradient(135deg, rgba(139, 92, 246, 0.05), rgba(59, 130, 246, 0.02)); } .sgis-badge-group-progress { width: 100%; margin-top: 6px; height: 3px; background: rgba(255, 255, 255, 0.05); border-radius: 2px; overflow: hidden; } .sgis-badge-group-progress-fill { height: 100%; background: linear-gradient(90deg, #10b981, #34d399); border-radius: 2px; } .sgis-badge-group-stats { flex-direction: column; align-items: flex-end; gap: 3px; } .sgis-badge-group-stat-val { font-size: 11px; font-weight: 700; color: #c4b5fd; } .sgis-badge-group-stat-lbl { font-size: 9px; color: var(--sgis-text-3); margin-left: 4px; } /* === 徽章 footer 折叠说明 === */ .sgis-badge-footer-details { margin-top: 14px; padding: 8px 10px; background: rgba(255, 255, 255, 0.02); border: 1px solid rgba(255, 255, 255, 0.05); border-radius: 7px; font-size: 10px; color: var(--sgis-text-2); } .sgis-badge-footer-details summary { cursor: pointer; font-weight: 600; user-select: none; list-style: none; display: flex; align-items: center; gap: 5px; } .sgis-badge-footer-details summary::-webkit-details-marker { display: none; } .sgis-badge-footer-details summary::before { content: "▸"; display: inline-block; transition: transform 0.2s; font-size: 9px; color: var(--sgis-text-3); } .sgis-badge-footer-details[open] summary::before { transform: rotate(90deg); } .sgis-badge-footer-content { padding-top: 8px; line-height: 1.6; } .sgis-badge-footer-formula { margin-bottom: 4px; } .sgis-badge-footer-formula b { color: #c4b5fd; } .sgis-badge-footer-breakdown { font-size: 9px; color: var(--sgis-text-3); } .sgis-badge-footer-meta { font-size: 9px; color: var(--sgis-text-3); margin-top: 2px; } /* === 价值卡片单列布局(共享库默认 flex 单列,在窄侧边栏里 2 列挤压变形) === v2.9.18 尝试 2 列 grid + minmax(0,1fr) + 三层 min-width:0 链式压制,但实际渲染出单卡仍被竖向挤压 (游戏名截断为 S..、Lv./50/XP 竖排)—— 在 300px 宽的 SGIS 侧边栏里 2 列宽度仍不够放下 56px img + 38px score + 名字 + market。 v2.9.21 退回单列布局,删掉所有过紧的子项压缩样式,卡片按 flex 自然撑开,信息完整可读。 历史: 共享库 sglv-shared-css.lib.js:1467 的 .sgis-value-cards { display:flex; flex-direction:column; gap:6px; } 直接可用。 这里只追加 !important 防止共享库默认被覆盖即可,不再做 2 列。 */ .sgis-value-cards { display: flex !important; flex-direction: column !important; gap: 6px !important; width: 100% !important; max-width: 100% !important; box-sizing: border-box; } /* 单元本身保持原样,不压制 min-width,让 flex 子项(img 56 + score 38 + market 文本)自然撑开 */ /* === 愿望单首次加载骨架屏(避免页面紧缩) === */ @keyframes sglv-skel-shimmer { 0% { background-position: -200% 0; } 100% { background-position: 200% 0; } } .sglv-skel-bar { background: linear-gradient(90deg, rgba(255, 255, 255, 0.04) 0%, rgba(139, 92, 246, 0.12) 50%, rgba(255, 255, 255, 0.04) 100%); background-size: 200% 100%; animation: sglv-skel-shimmer 1.6s linear infinite; border-radius: 4px; } .sglv-wl-kpi { display: grid; grid-template-columns: repeat(2, 1fr); gap: 6px; margin-bottom: 10px; } .sglv-wl-kpi-cell { position: relative; background: linear-gradient(135deg, rgba(139, 92, 246, 0.08), rgba(59, 130, 246, 0.04)), var(--sglv-surface-1, rgba(255, 255, 255, 0.025)); border: 1px solid rgba(139, 92, 246, 0.18); border-radius: 8px; padding: 10px 8px; text-align: center; display: flex; flex-direction: column; align-items: center; gap: 6px; box-shadow: var(--sglv-shadow-sm, 0 2px 8px rgba(0, 0, 0, 0.35)), inset 0 1px 0 rgba(139, 92, 246, 0.12); transition: transform 0.18s var(--sglv-ease, ease), box-shadow 0.18s var(--sglv-ease, ease), border-color 0.18s var(--sglv-ease, ease); overflow: hidden; } .sglv-wl-kpi-cell::before { content: ''; position: absolute; inset: -1px; border-radius: 8px; pointer-events: none; background: linear-gradient(135deg, rgba(139, 92, 246, 0.35), transparent 60%); opacity: 0; transition: opacity 0.18s var(--sglv-ease, ease); } .sglv-wl-kpi-cell:hover { transform: translateY(-2px); border-color: rgba(139, 92, 246, 0.4); box-shadow: var(--sglv-shadow-md, 0 6px 20px rgba(0, 0, 0, 0.45)), 0 0 0 1px rgba(139, 92, 246, 0.25), 0 0 22px rgba(139, 92, 246, 0.2), inset 0 1px 0 rgba(139, 92, 246, 0.18); } .sglv-wl-kpi-cell:hover::before { opacity: 1; } .sglv-wl-kpi-cell > * { position: relative; z-index: 1; } .sglv-skel-num { width: 50%; height: 18px; } .sglv-skel-lbl { width: 70%; height: 9px; } .sglv-skel-section-title { width: 40%; height: 12px; margin-bottom: 8px; } .sglv-skel-row { width: 100%; height: 10px; margin-bottom: 6px; opacity: 0.85; } .sglv-skel-row-short { width: 60%; opacity: 0.6; } .sglv-skel-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 8px; padding: 4px 0; } .sglv-skel-game-card { background: rgba(255, 255, 255, 0.025); border: 1px solid rgba(255, 255, 255, 0.05); border-radius: 8px; padding: 8px; display: flex; flex-direction: column; gap: 8px; } .sglv-skel-cover { width: 100%; aspect-ratio: 184 / 69; background: linear-gradient(90deg, rgba(139, 92, 246, 0.08) 0%, rgba(139, 92, 246, 0.18) 50%, rgba(139, 92, 246, 0.08) 100%); background-size: 200% 100%; animation: sglv-skel-shimmer 1.6s linear infinite; border-radius: 4px; } .sglv-skel-card-name { width: 80%; height: 11px; } .sglv-skel-card-meta { width: 50%; height: 9px; } .sglv-wl-skel-tip { display: flex; align-items: center; justify-content: center; gap: 8px; padding: 18px 12px; margin-top: 12px; color: var(--sglv-text-secondary, #94a3b8); font-size: 12px; font-weight: 500; } .sglv-wl-skel-tip .sglv-spinner { width: 16px; height: 16px; border-width: 2px; } /* === 愿望单加载等待动画(参考 DLC spinner 风格) === */ .sglv-wl-loading { display:flex; flex-direction:column; align-items:center; justify-content:center; padding:48px 20px; gap:14px; color:#94a3b8; min-height:280px; } .sglv-wl-loading .sglv-wl-spin { width:32px; height:32px; animation:sglv-spin 1s linear infinite; color:#a78bfa; } .sglv-wl-loading-text { font-size:13px; font-weight:600; color:#cbd5e1; } .sglv-wl-loading-sub { font-size:11px; color:#64748b; } .sglv-wl-loading-bar { width:220px; height:3px; background:rgba(102,192,244,0.12); border-radius:2px; overflow:hidden; } .sglv-wl-loading-bar-fill { height:100%; background:linear-gradient(90deg,#66c0f4,#a78bfa); border-radius:2px; transition:width 0.4s ease; }`; const CSS_TOAST =` @keyframes sglv-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } .sglv-toast { position: fixed; bottom: 50px; left: 50%; transform: translateX(-50%) translateY(20px); background: rgba(15,23,42,0.95); color: #fff; border: 1px solid rgba(167,139,250,0.5); padding: 10px 24px; border-radius: 20px; font-size: 13px; font-weight: 500; box-shadow: 0 4px 16px rgba(0,0,0,0.3); z-index: 999999; opacity: 0; pointer-events: none; transition: opacity 0.3s, transform 0.3s; } .sglv-toast.sglv-toast-show { opacity: 1; transform: translateX(-50%) translateY(0); } .sglv-toast.sglv-toast-success { border-color: #2ed573; } .sglv-toast.sglv-toast-error { border-color: #ff6b6b; } .sglv-toast.sglv-toast-warning { border-color: #f59e0b; } .sglv-toast.sglv-toast-info { border-color: #54a0ff; }`; const CSS_APIKEY_CONSENT =` @keyframes sglv-consent-in { from { opacity: 0; transform: translateY(12px) scale(0.98); } to { opacity: 1; transform: translateY(0) scale(1); } } .sglv-apikey-consent { position: fixed; inset: 0; z-index: 10000050; background: rgba(2,6,23,0.72); backdrop-filter: blur(3px); display: flex; align-items: center; justify-content: center; padding: 20px; box-sizing: border-box; } .sglv-apikey-consent-card { width: min(560px, 100%); max-height: 86vh; display: flex; flex-direction: column; background: linear-gradient(160deg, rgba(30,41,59,0.99), rgba(15,23,42,0.99)); border: 1px solid rgba(167,139,250,0.4); border-radius: 14px; box-shadow: 0 24px 64px rgba(0,0,0,0.6); color: #e2e8f0; font-size: 13px; line-height: 1.7; animation: sglv-consent-in 0.22s ease-out; } .sglv-apikey-consent-head { display: flex; align-items: center; gap: 10px; padding: 16px 18px 12px; border-bottom: 1px solid rgba(148,163,184,0.16); } .sglv-apikey-consent-title { flex: 1; font-size: 15px; font-weight: 700; color: #fff; } .sglv-apikey-consent-close { background: none; border: none; color: #94a3b8; cursor: pointer; font-size: 15px; line-height: 1; padding: 4px 8px; border-radius: 6px; } .sglv-apikey-consent-close:hover { color: #fff; background: rgba(148,163,184,0.15); } .sglv-apikey-consent-body { padding: 16px 18px; overflow-y: auto; } .sglv-apikey-consent-sec + .sglv-apikey-consent-sec { margin-top: 16px; } .sglv-apikey-consent-sec-title { font-size: 12px; font-weight: 700; color: #a78bfa; margin-bottom: 8px; letter-spacing: 0.04em; } .sglv-apikey-consent-p { margin: 0 0 8px; color: #cbd5e1; font-size: 12.5px; } .sglv-apikey-consent-p b, .sglv-apikey-consent-ul b { color: #e9d5ff; } .sglv-apikey-consent-ul { margin: 0; padding-left: 18px; color: #cbd5e1; font-size: 12.5px; } .sglv-apikey-consent-ul li { margin-bottom: 6px; } .sglv-apikey-consent-check { display: flex; align-items: flex-start; gap: 9px; margin-top: 16px; padding: 11px 13px; border: 1px solid rgba(167,139,250,0.32); border-radius: 10px; background: rgba(167,139,250,0.07); cursor: pointer; font-size: 12.5px; color: #e2e8f0; } .sglv-apikey-consent-check:hover { border-color: rgba(167,139,250,0.55); } .sglv-apikey-consent-check input { margin-top: 3px; accent-color: #a78bfa; flex: none; cursor: pointer; } .sglv-apikey-consent-actions { display: flex; gap: 10px; padding: 14px 18px 18px; border-top: 1px solid rgba(148,163,184,0.16); } .sglv-apikey-consent-btn { flex: 1; padding: 10px 0; border-radius: 9px; font-size: 13px; font-weight: 600; cursor: pointer; border: 1px solid transparent; transition: filter 0.15s, opacity 0.15s; } .sglv-apikey-consent-btn.primary { background: linear-gradient(90deg, #8b5cf6, #3b82f6); color: #fff; } .sglv-apikey-consent-btn.ghost { background: transparent; border-color: rgba(148,163,184,0.3); color: #cbd5e1; } .sglv-apikey-consent-btn:hover:not(:disabled) { filter: brightness(1.15); } .sglv-apikey-consent-btn:disabled { opacity: 0.42; cursor: not-allowed; } .sglv-set-locked { padding: 12px 14px; border: 1px dashed rgba(167,139,250,0.4); border-radius: 10px; background: rgba(167,139,250,0.06); } .sglv-set-locked-title { font-size: 13px; font-weight: 700; color: #e9d5ff; margin-bottom: 6px; } .sglv-set-locked-desc { font-size: 12px; color: #94a3b8; line-height: 1.65; margin-bottom: 10px; } .sglv-set-locked-btn { padding: 7px 16px; border-radius: 8px; font-size: 12px; font-weight: 600; cursor: pointer; border: 1px solid transparent; background: linear-gradient(90deg, #8b5cf6, #3b82f6); color: #fff; } .sglv-set-locked-btn:hover { filter: brightness(1.15); }`; const CSS_SETTINGS =` .sglv-panel .sglv-settings-btn.sglv-active { background: rgba(102,192,244,0.2) !important; color: #66c0f4 !important; box-shadow: inset 0 0 0 1px rgba(102,192,244,0.5); border-radius: 6px; } .sglv-set-wrap { display: flex; flex-direction: column; height: 100%; min-height: 0; } .sglv-set-topbar { display: flex; align-items: center; gap: 12px; padding: 14px 18px 10px; flex: none; border-bottom: 1px solid rgba(148,163,184,0.12); } .sglv-set-back { display: inline-flex; align-items: center; gap: 6px; background: rgba(148,163,184,0.1); border: 1px solid rgba(148,163,184,0.2); color: #cbd5e1; font-size: 12px; font-weight: 600; padding: 6px 12px; border-radius: 8px; cursor: pointer; transition: background 0.15s, color 0.15s; } .sglv-set-back:hover { background: rgba(148,163,184,0.22); color: #fff; } .sglv-set-title { display: flex; align-items: center; gap: 8px; font-size: 15px; font-weight: 700; color: #fff; } .sglv-set-title svg { width: 16px; height: 16px; color: #66c0f4; } .sglv-set-grid { flex: 1; min-height: 0; overflow-y: auto; display: grid; grid-template-columns: repeat(auto-fit, minmax(340px, 1fr)); gap: 14px; padding: 16px 18px; align-content: start; } .sglv-set-card { background: rgba(15,23,42,0.55); border: 1px solid rgba(148,163,184,0.14); border-radius: 12px; padding: 16px; transition: border-color 0.15s; } .sglv-set-card:hover { border-color: rgba(102,192,244,0.35); } .sglv-set-card.wide { grid-column: 1 / -1; } .sglv-set-card-title { display: flex; align-items: center; gap: 8px; font-size: 13px; font-weight: 700; color: #e2e8f0; margin-bottom: 8px; } .sglv-set-chip { display: inline-flex; width: 26px; height: 26px; align-items: center; justify-content: center; border-radius: 8px; flex: none; } .sglv-set-chip svg { width: 14px; height: 14px; } .sglv-set-chip.blue { background: rgba(102,192,244,0.15); color: #66c0f4; } .sglv-set-chip.purple { background: rgba(167,139,250,0.15); color: #a78bfa; } .sglv-set-chip.amber { background: rgba(245,158,11,0.15); color: #f59e0b; } .sglv-set-desc { font-size: 12px; color: #94a3b8; line-height: 1.7; margin-bottom: 12px; } .sglv-set-desc a { color: #66c0f4; text-decoration: none; } .sglv-set-desc a:hover { text-decoration: underline; } .sglv-set-field { margin-bottom: 12px; } .sglv-set-field:last-child { margin-bottom: 0; } .sglv-set-field > label { display: block; font-size: 12px; font-weight: 600; color: #cbd5e1; margin-bottom: 6px; } .sglv-set-input { width: 100%; box-sizing: border-box; background: rgba(2,6,23,0.6); border: 1px solid rgba(148,163,184,0.22); border-radius: 8px; padding: 9px 12px; color: #e2e8f0; font-size: 13px; transition: border-color 0.15s, box-shadow 0.15s; } .sglv-set-input::placeholder { color: #475569; } .sglv-set-input:focus { outline: none; border-color: #66c0f4; box-shadow: 0 0 0 3px rgba(102,192,244,0.15); } .sglv-set-hint { font-size: 11px; color: #64748b; margin-top: 4px; line-height: 1.5; } .sglv-set-mode-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 10px; } .sglv-set-mode-item { display: flex; gap: 10px; align-items: flex-start; padding: 10px 12px; border: 1px solid rgba(148,163,184,0.16); border-radius: 10px; cursor: pointer; transition: border-color 0.15s, background 0.15s; } .sglv-set-mode-item:hover { border-color: rgba(167,139,250,0.4); background: rgba(167,139,250,0.06); } .sglv-set-mode-item input { margin-top: 3px; accent-color: #a78bfa; cursor: pointer; } .sglv-set-mode-item input:checked ~ .sglv-set-mode-info .sglv-set-mode-name { color: #a78bfa; } .sglv-set-mode-name { font-size: 12.5px; font-weight: 700; color: #e2e8f0; } .sglv-set-mode-desc { font-size: 11.5px; color: #94a3b8; margin-top: 2px; line-height: 1.5; } /*设置页面开关样式 */ .sglv-set-chip.green { background: rgba(75,181,79,0.15); color: #4bb54f; } .sglv-set-toggle-row { display: flex !important; align-items: center; justify-content: space-between; font-size: 12.5px; font-weight: 600; color: #cbd5e1; cursor: pointer; user-select: none; } .sglv-set-switch { position: relative; display: inline-block; width: 36px; height: 20px; flex: none; } .sglv-set-switch input { opacity: 0; width: 0; height: 0; } .sglv-set-slider { position: absolute; cursor: pointer; inset: 0; background-color: rgba(255,255,255,0.1); transition: .2s; border-radius: 20px; border: 1px solid rgba(255,255,255,0.05); } .sglv-set-slider:before { position: absolute; content: ""; height: 14px; width: 14px; left: 2px; bottom: 2px; background-color: #8a9ba8; transition: .2s; border-radius: 50%; } .sglv-set-switch input:checked + .sglv-set-slider { background-color: rgba(75,181,79,0.2); border-color: rgba(75,181,79,0.4); } .sglv-set-switch input:checked + .sglv-set-slider:before { transform: translateX(16px); background-color: #4bb54f; } /*外观主题选择卡(sglv-set-theme-swatch 为主题预览色板,颜色刻意固定不随主题切换——生成器跳过) */ .sglv-set-theme-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; } .sglv-set-theme-opt { position: relative; display: flex; flex-direction: column; gap: 8px; padding: 10px; border: 1px solid rgba(148,163,184,0.16); border-radius: 10px; cursor: pointer; transition: border-color 0.15s, background 0.15s, box-shadow 0.15s; } .sglv-set-theme-opt:hover { border-color: rgba(167,139,250,0.4); } .sglv-set-theme-opt input { position: absolute; opacity: 0; width: 0; height: 0; } .sglv-set-theme-swatch { height: 34px; border-radius: 8px; border: 1px solid rgba(255,255,255,0.08); } .sglv-set-theme-swatch.purple { background: linear-gradient(135deg, #171a21 0%, #4c1d95 55%, #a78bfa 100%); } .sglv-set-theme-swatch.blue { background: linear-gradient(135deg, #171a21 0%, #2a475e 55%, #66c0f4 100%); } .sglv-set-theme-name { display: flex; align-items: center; justify-content: space-between; font-size: 12.5px; font-weight: 700; color: #e2e8f0; } .sglv-set-theme-name .sglv-set-theme-check { color: #4bb54f; font-size: 12px; opacity: 0; } .sglv-set-theme-opt.selected { border-color: rgba(167,139,250,0.55); background: rgba(167,139,250,0.07); box-shadow: 0 0 0 1px rgba(167,139,250,0.25); } .sglv-set-theme-opt.selected .sglv-set-theme-check { opacity: 1; } .sglv-set-theme-desc { font-size: 11px; color: #94a3b8; line-height: 1.5; } .sglv-set-savebar { display: flex; align-items: center; gap: 12px; padding: 12px 18px; flex: none; border-top: 1px solid rgba(148,163,184,0.12); background: rgba(2,6,23,0.35); } .sglv-set-save-btn { display: inline-flex; align-items: center; gap: 6px; background: linear-gradient(90deg, #8b5cf6, #3b82f6); color: #fff; border: none; border-radius: 8px; padding: 9px 22px; font-size: 13px; font-weight: 700; cursor: pointer; transition: filter 0.15s, transform 0.1s; } .sglv-set-save-btn:hover { filter: brightness(1.15); } .sglv-set-save-btn:active { transform: scale(0.97); } .sglv-set-status { font-size: 12px; color: #2ed573; font-weight: 600; }`; const CSS_KPI =` .sglv-stat-dash-card.orange { border-color: rgba(245, 158, 11, 0.3); background: rgba(245, 158, 11, 0.08); } .sglv-stat-dash-card.orange .sglv-stat-dash-icon { color: #f59e0b; } .sglv-stat-dash-card.orange .sglv-stat-dash-value { color: #f59e0b; } .sglv-stat-dash-card.teal { border-color: rgba(20, 184, 166, 0.3); background: rgba(20, 184, 166, 0.08); } .sglv-stat-dash-card.teal .sglv-stat-dash-icon { color: #14b8a6; } .sglv-stat-dash-card.teal .sglv-stat-dash-value { color: #14b8a6; } .sglv-stat-dash-card.pink { border-color: rgba(236, 72, 153, 0.3); background: rgba(236, 72, 153, 0.08); } .sglv-stat-dash-card.pink .sglv-stat-dash-icon { color: #ec4899; } .sglv-stat-dash-card.pink .sglv-stat-dash-value { color: #ec4899; } .sglv-bundle-badge { display: inline-block; margin-left: 4px; padding: 1px 5px; font-size: 10px; font-weight: 600; border-radius: 3px; background: #f59e0b; color: #fff; vertical-align: middle; cursor: help; } /*游戏橱窗 KPI 改为 grid 7 列扁平布局,与统计仪表/趋势页一致 */ .sglv-stats-dashboard { display: grid !important; grid-template-columns: repeat(7, 1fr) !important; gap: 6px !important; } @media (max-width: 1280px) { .sglv-stats-dashboard { grid-template-columns: repeat(4, 1fr) !important; } } @media (max-width: 768px) { .sglv-stats-dashboard { grid-template-columns: repeat(3, 1fr) !important; } } @media (max-width: 480px) { .sglv-stats-dashboard { grid-template-columns: repeat(2, 1fr) !important; } } .sglv-stats-dashboard .sglv-stat-dash-card { min-width: 0; cursor: pointer; transition: transform 0.15s, box-shadow 0.15s, border-color 0.15s; } .sglv-stats-dashboard .sglv-stat-dash-card:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.3); } .sglv-stats-dashboard .sglv-stat-dash-card.active { box-shadow: 0 0 0 2px rgba(102,192,244,0.4); border-left-width: 4px !important; } .sglv-stats-dashboard .sglv-stat-dash-card.amber { cursor: default; } .sglv-stats-dashboard .sglv-stat-dash-card.amber:hover { transform: none; box-shadow: none; } /* v1.0.3: sglv-stat-dash-card / sglv-trend-kpi-card / sglv-wl-kpi-cell 共享炫彩效果 — 渐变背景 + shadow-sm 基线 + 抬升 -2px + accent-glow 外发光 */ .sglv-stat-dash-card, .sglv-trend-kpi-card { position: relative; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,.35), inset 0 1px 0 rgba(255,255,255,.04); } .sglv-stat-dash-card::before, .sglv-trend-kpi-card::before { content: ''; position: absolute; inset: -1px; pointer-events: none; background: linear-gradient(135deg, rgba(102,192,244,.32), transparent 60%); opacity: 0; transition: opacity .18s ease; } .sglv-stat-dash-card:hover::before, .sglv-trend-kpi-card:hover::before { opacity: 1; } .sglv-stat-dash-card:hover, .sglv-trend-kpi-card:hover { box-shadow: 0 6px 20px rgba(0,0,0,.45), 0 0 0 1px rgba(102,192,244,.25), 0 0 22px rgba(102,192,244,.18), inset 0 1px 0 rgba(255,255,255,.06); border-color: rgba(102,192,244,.45) !important; } .sglv-stat-dash-value, .sglv-trend-kpi-value { text-shadow: 0 0 14px rgba(102,192,244,.25); } .sglv-stat-dash-card > *, .sglv-trend-kpi-card > * { position: relative; z-index: 1; }`; const CSS_SUBSTATUS =` .sgis-sub-status { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 8px; } .sgis-sub-badge { display: inline-flex; align-items: center; gap: 4px; padding: 3px 8px; font-size: 11px; font-weight: 600; border-radius: 4px; } /*年度大作 KPI 卡片可点击筛选样式 */ .sglv-trend-kpi-card.clickable { cursor: pointer; transition: transform 0.15s, box-shadow 0.15s, border-color 0.15s; } .sglv-trend-kpi-card.clickable:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.3); } .sglv-trend-kpi-card.active { border-width: 2px; box-shadow: 0 0 0 2px rgba(102,192,244,0.4); }`; const CSS_COVER =` /* ====== 横版封面视图(3列,467/181 胶囊横幅) ====== */ .sglv-cover-grid { display: grid !important; grid-template-columns: repeat(3, 1fr) !important; gap: 12px !important; } @media (max-width: 1100px) { .sglv-cover-grid { grid-template-columns: repeat(2, 1fr) !important; } } @media (max-width: 700px) { .sglv-cover-grid { grid-template-columns: 1fr !important; } } .sglv-cover-card { background: linear-gradient(135deg, rgba(255,255,255,0.06) 0%, rgba(255,255,255,0.02) 100%) !important; border: 1px solid rgba(102,192,244,0.1) !important; border-radius: 10px !important; overflow: hidden !important; transition: transform 0.2s, box-shadow 0.2s, border-color 0.2s !important; cursor: pointer !important; display: flex !important; flex-direction: column !important; } .sglv-cover-card:hover { border-color: rgba(102,192,244,0.35) !important; transform: translateY(-3px) !important; box-shadow: 0 6px 20px rgba(102,192,244,0.12), 0 2px 8px rgba(0,0,0,0.3) !important; } .sglv-cover-img-wrap { position: relative !important; width: 100% !important; aspect-ratio: 467/181 !important; overflow: hidden !important; background: rgba(255,255,255,0.05) !important; flex-shrink: 0 !important; } .sglv-cover-img { width: 100% !important; height: 100% !important; object-fit: cover !important; display: block !important; transition: transform 0.3s !important; } .sglv-cover-card:hover .sglv-cover-img { transform: scale(1.04) !important; } .sglv-cover-gradient { position: absolute !important; bottom: 0 !important; left: 0 !important; right: 0 !important; height: 45% !important; background: linear-gradient(to top, rgba(13,18,35,0.85) 0%, transparent 100%) !important; pointer-events: none !important; z-index: 1 !important; } .sglv-cover-badges { position: absolute !important; top: 6px !important; left: 6px !important; display: flex !important; gap: 4px !important; z-index: 2 !important; } .sglv-cover-badge { display: inline-flex !important; align-items: center !important; gap: 3px !important; font-size: 10px !important; font-weight: 700 !important; padding: 2px 7px !important; border-radius: 4px !important; backdrop-filter: blur(6px) !important; -webkit-backdrop-filter: blur(6px) !important; background: rgba(0,0,0,0.55) !important; color: #c4b5fd !important; line-height: 1.3 !important; } .sglv-cover-badge svg { width: 10px !important; height: 10px !important; opacity: 0.85 !important; } .sglv-cover-badge.shared { background: rgba(139,92,246,0.55) !important; color: #ddd6fe !important; } .sglv-cover-badge.bundle { background: rgba(255,152,0,0.55) !important; color: #ffd591 !important; } .sglv-cover-playtime { position: absolute !important; bottom: 6px !important; right: 6px !important; display: inline-flex !important; align-items: center !important; gap: 3px !important; font-size: 11px !important; font-weight: 700 !important; padding: 2px 8px !important; border-radius: 4px !important; background: rgba(0,0,0,0.65) !important; color: #66c0f4 !important; backdrop-filter: blur(6px) !important; -webkit-backdrop-filter: blur(6px) !important; z-index: 2 !important; line-height: 1.3 !important; } .sglv-cover-playtime svg { width: 10px !important; height: 10px !important; opacity: 0.85 !important; } .sglv-cover-body { padding: 8px 10px 9px !important; display: flex !important; flex-direction: column !important; gap: 3px !important; } .sglv-cover-name { font-size: 13px !important; font-weight: 600 !important; color: #e0e0e0 !important; overflow: hidden !important; text-overflow: ellipsis !important; white-space: nowrap !important; } .sglv-cover-meta { display: flex; align-items: center; gap: 5px; flex-wrap: wrap; } .sglv-cover-id { font-size: 10px !important; color: var(--sglv-text-secondary) !important; font-variant-numeric: tabular-nums !important; } /* ====== 卡片视图增强 ====== */ .sglv-game-card { border-radius: 10px !important; } .sglv-game-card:hover { box-shadow: 0 6px 20px rgba(102,192,244,0.1), 0 2px 8px rgba(0,0,0,0.3) !important; } .sglv-card-img { transition: transform 0.3s !important; } .sglv-game-card:hover .sglv-card-img { transform: scale(1.05) !important; } /* ====== 工具栏排版优化 ====== */ .sglv-toolbar { gap: 8px !important; }`; const CSS_PRICE =` /* === 9区完整价格对比表 === */ .sgis-price-tbl { display:flex; flex-direction:column; gap:1px; } .sgis-price-tbl-header { display:grid; grid-template-columns: 1.6fr 0.9fr 1fr 0.6fr 0.9fr; gap:2px; padding:4px 6px; font-size:9px; color:var(--sgis-text-2); text-transform:uppercase; letter-spacing:0.3px; border-bottom:1px solid rgba(255,255,255,0.06); } .sgis-price-tbl-row { display:grid; grid-template-columns: 1.6fr 0.9fr 1fr 0.6fr 0.9fr; gap:2px; padding:5px 6px; font-size:11px; align-items:center; border-radius:4px; transition:background 0.15s; } .sgis-price-tbl-row:hover { background:rgba(255,255,255,0.04); } .sgis-price-tbl-row-lowest { background:rgba(75,181,79,0.12) !important; border-left:3px solid #4bb54f; } .sgis-price-tbl-row-highest { background:rgba(230,57,70,0.10) !important; border-left:3px solid #e63946; } .sgis-price-tbl-row.user-region { box-shadow: inset 0 0 0 1px rgba(167,139,250,0.3); } .sgis-price-tbl-cell { display:flex; align-items:center; gap:3px; overflow:hidden; } .sgis-price-tbl-region { gap:4px; } .sgis-price-tbl-initial { color:var(--sgis-text-2); font-size:10px; } .sgis-price-tbl-price { font-weight:600; } .sgis-price-tbl-cny { font-weight:700; color:#66c0f4; } .sgis-price-tbl-badge-low { font-size:8px; background:#4bb54f; color:#fff; padding:1px 4px; border-radius:3px; margin-left:2px; } .sgis-price-tbl-badge-high { font-size:8px; background:#e63946; color:#fff; padding:1px 4px; border-radius:3px; margin-left:2px; } /* === 国旗完整显示 — flagcdn w40 各国旗帜宽高比不一(US/GB/KZ/CO 为 2:1 宽旗, BR 为 10:7 等),共享库 .sgis-price-flag 固定 30×20(3:2)+cover 会把宽旗左右裁掉约 1/4; 此处以更高优先级覆盖为 contain,旗帜图案完整呈现,比例空隙由行背景自然过渡 === */ .sgis-price-tbl .sgis-price-flag { object-fit: contain; } .sgis-price-featured-img { object-fit: contain; } /* === 比价目标货币切换(多地区低价排行页头) === */ .sgis-price-cur-switch { margin-left:auto; display:inline-flex; align-items:center; gap:4px; flex-shrink:0; text-transform:none; letter-spacing:0; } .sgis-price-cur-switch-label { font-size:9px; color:var(--sgis-text-2); font-weight:500; } .sgis-price-cur-select { font-size:10px; font-weight:600; color:#66c0f4; font-family:inherit; background:rgba(102,192,244,0.08); border:1px solid rgba(102,192,244,0.25); border-radius:6px; padding:2px 4px; cursor:pointer; outline:none; max-width:132px; text-transform:none; letter-spacing:0; transition:border-color 0.15s, background 0.15s; } .sgis-price-cur-select:hover { border-color:rgba(102,192,244,0.5); background:rgba(102,192,244,0.14); } .sgis-price-cur-select:focus { border-color:rgba(102,192,244,0.6); } .sgis-price-cur-select option { background:#1b2838; color:#fff; } .sgis-price-cur-fallback { font-size:9px; color:#c0a050; margin:-4px 0 6px; line-height:1.4; } /* === 评测标签页 === */ /* === 评测摘要(Steam 风格大字 + 渐变进度条) === */ .sgis-review-summary { display:flex; flex-direction:column; gap:10px; padding:10px 12px; background:rgba(255,255,255,0.02); border:1px solid rgba(255,255,255,0.05); border-radius:8px; } .sgis-review-summary-head { display:flex; align-items:center; gap:12px; } .sgis-review-score { display:flex; align-items:center; gap:12px; flex:1; min-width:0; } .sgis-review-score-icon { font-size:30px; line-height:1; flex-shrink:0; filter:drop-shadow(0 1px 2px rgba(0,0,0,0.3)); } .sgis-review-score-meta { display:flex; flex-direction:column; gap:2px; min-width:0; flex:1; } .sgis-review-score-text { font-size:14px; font-weight:700; line-height:1.2; } .sgis-review-score-desc { font-size:10px; color:var(--sgis-text-2); line-height:1.3; } .sgis-review-pct-big { font-size:24px; font-weight:800; font-variant-numeric:tabular-nums; line-height:1; flex-shrink:0; letter-spacing:-0.5px; } .sgis-review-pct-big.pos { color:#4bb54f; } .sgis-review-pct-big.mix { color:#a78bfa; } .sgis-review-pct-big.neg { color:#e63946; } .sgis-review-bar { display:flex; height:8px; border-radius:4px; overflow:hidden; background:rgba(230,57,70,0.3); box-shadow:inset 0 1px 2px rgba(0,0,0,0.3); } .sgis-review-bar-positive { background:linear-gradient(90deg,#4bb54f 0%,#66c0f4 100%); height:100%; transition:width 0.5s cubic-bezier(0.4,0,0.2,1); box-shadow:0 0 6px rgba(75,181,79,0.4); } .sgis-review-bar-positive.mix { background:linear-gradient(90deg,#a78bfa 0%,#54a0ff 100%); box-shadow:0 0 6px rgba(167,139,250,0.4); } .sgis-review-bar-positive.neg { background:linear-gradient(90deg,#e63946 0%,#ff6b6b 100%); box-shadow:0 0 6px rgba(230,57,70,0.4); } .sgis-review-counts { display:flex; justify-content:space-between; font-size:10px; font-weight:600; } .sgis-review-counts .pos { color:#4bb54f; } .sgis-review-counts .neg { color:#e63946; } .sgis-review-trend { display:flex; gap:10px; font-size:10px; flex-wrap:wrap; padding:6px 8px; background:rgba(255,255,255,0.02); border-radius:6px; } .sgis-review-trend-item { display:flex; flex-direction:column; gap:2px; flex:1; min-width:80px; } .sgis-review-trend-label { color:var(--sgis-text-2); font-size:9px; } .sgis-review-trend-val { font-weight:600; font-variant-numeric:tabular-nums; } .sgis-review-filters { display:flex; flex-wrap:wrap; gap:4px; padding:6px 0; border-top:1px solid rgba(255,255,255,0.06); border-bottom:1px solid rgba(255,255,255,0.06); } .sgis-review-filter-group { display:flex; align-items:center; gap:2px; } .sgis-review-filter-label { font-size:9px; color:var(--sgis-text-2); margin-right:2px; } .sgis-review-filter-btn { font-size:10px; padding:2px 7px; border-radius:10px; border:1px solid rgba(255,255,255,0.1); background:transparent; color:var(--sgis-text-2); cursor:pointer; transition:all 0.15s; } .sgis-review-filter-btn:hover { background:rgba(255,255,255,0.06); } .sgis-review-filter-btn.active { background:rgba(102,192,244,0.2); color:#66c0f4; border-color:rgba(102,192,244,0.4); } .sgis-review-list { display:flex; flex-direction:column; gap:8px; padding:4px 0; } /*评测项卡片化——左右色条标识好评/差评 */ .sgis-review-item { position:relative; padding:10px 10px 8px 12px; border-radius:8px; background:rgba(255,255,255,0.025); border:1px solid rgba(255,255,255,0.05); transition:all 0.2s ease; overflow:hidden; } .sgis-review-item::before { content:""; position:absolute; left:0; top:0; bottom:0; width:3px; background:linear-gradient(180deg,transparent,rgba(75,181,79,0.5),transparent); opacity:0; transition:opacity 0.2s; } .sgis-review-item.is-positive::before { background:linear-gradient(180deg,transparent,#4bb54f,transparent); opacity:0.7; } .sgis-review-item.is-negative::before { background:linear-gradient(180deg,transparent,#e63946,transparent); opacity:0.7; } .sgis-review-item:hover { background:rgba(255,255,255,0.045); border-color:rgba(139,92,246,0.15); transform:translateY(-1px); box-shadow:0 2px 8px rgba(0,0,0,0.15); } .sgis-review-item.is-positive:hover { border-color:rgba(75,181,79,0.25); } .sgis-review-item.is-negative:hover { border-color:rgba(230,57,70,0.25); } .sgis-review-item-header { display:flex; align-items:center; gap:8px; margin-bottom:6px; } .sgis-review-avatar { width:32px; height:32px; min-width:32px; border-radius:50%; background:rgba(255,255,255,0.08); display:flex; align-items:center; justify-content:center; object-fit:cover; flex-shrink:0; border:1px solid rgba(255,255,255,0.06); } .sgis-review-avatar-link { display:inline-flex; line-height:0; flex-shrink:0; border-radius:50%; transition:transform 0.2s; } .sgis-review-avatar-link:hover { transform:scale(1.08); } .sgis-review-avatar-fallback { background:linear-gradient(135deg,rgba(139,92,246,0.4),rgba(59,130,246,0.3)); color:#fff; font-weight:700; font-size:13px; letter-spacing:0.5px; text-transform:uppercase; } .sgis-review-author-wrap { display:flex; flex-direction:column; gap:1px; min-width:0; flex:1; } .sgis-review-author { font-size:12px; font-weight:600; color:#66c0f4; text-decoration:none; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; transition:color 0.15s; } a.sgis-review-author:hover { color:#93c5fd; } .sgis-review-date { font-size:10px; color:var(--sgis-text-3); font-weight:400; } .sgis-review-rec { font-size:10px; padding:2px 7px; border-radius:4px; font-weight:700; flex-shrink:0; } .sgis-review-rec-yes { background:rgba(75,181,79,0.18); color:#4bb54f; border:1px solid rgba(75,181,79,0.3); } .sgis-review-rec-no { background:rgba(230,57,70,0.18); color:#f87171; border:1px solid rgba(230,57,70,0.3); } .sgis-review-meta { font-size:10px; color:var(--sgis-text-2); display:flex; gap:8px; flex-wrap:wrap; margin:6px 0 4px; } .sgis-review-meta-item { padding:1px 6px; background:rgba(255,255,255,0.04); border-radius:3px; } /*计数摘要条——图标 + 数字 + 已筛选徽章 */ .sgis-review-count-summary { display:flex; align-items:center; gap:6px; margin-top:8px; padding:5px 8px; font-size:10px; color:var(--sgis-text-2); background:rgba(139,92,246,0.06); border:1px solid rgba(139,92,246,0.12); border-radius:5px; } .sgis-review-count-summary b { color:#c4b5fd; font-weight:700; } .sgis-review-count-icon { width:12px; height:12px; color:#a78bfa; flex-shrink:0; } .sgis-review-count-icon svg { width:12px; height:12px; } .sgis-review-count-filtered { margin-left:auto; font-size:9px; font-weight:700; padding:1px 6px; background:rgba(167,139,250,0.2); color:#a78bfa; border:1px solid rgba(167,139,250,0.3); border-radius:8px; } .sgis-review-text { font-size:12px; line-height:1.6; color:var(--sgis-text); margin-top:4px; display:-webkit-box; -webkit-line-clamp:3; -webkit-box-orient:vertical; overflow:hidden; cursor:pointer; transition:all 0.15s; padding:4px 0; word-break:break-word; } .sgis-review-text:hover { color:#f8fafc; } .sgis-review-text.expanded { -webkit-line-clamp:unset; overflow:visible; } /*评测项操作行(展开/复制)——紧凑胶囊按钮 */ .sgis-review-actions { display:flex; align-items:center; gap:6px; margin-top:6px; } .sgis-review-action-btn { display:inline-flex; align-items:center; gap:4px; padding:2px 8px; font-size:10px; font-weight:600; background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.08); color:var(--sgis-text-2); border-radius:10px; cursor:pointer; transition:all 0.15s; } .sgis-review-action-btn:hover { background:rgba(139,92,246,0.15); border-color:rgba(139,92,246,0.3); color:#c4b5fd; } .sgis-review-action-btn svg { width:11px; height:11px; transition:transform 0.25s; } .sgis-review-expand-btn.is-expanded svg { transform:rotate(180deg); } .sgis-review-action-btn.copied { background:rgba(75,181,79,0.2); border-color:rgba(75,181,79,0.4); color:#4bb54f; } .sgis-review-votes { font-size:10px; color:var(--sgis-text-3); margin-top:6px; display:flex; gap:10px; padding-top:6px; border-top:1px dashed rgba(255,255,255,0.06); } /*评测空状态——精致状态点 + 文字 */ .sgis-review-empty { text-align:center; padding:30px 16px; font-size:12px; color:var(--sgis-text-2); display:flex; flex-direction:column; align-items:center; gap:6px; } .sgis-review-empty-icon { width:42px; height:42px; border-radius:12px; background:linear-gradient(135deg,rgba(139,92,246,0.12),rgba(59,130,246,0.06)); border:1px solid rgba(139,92,246,0.18); display:flex; align-items:center; justify-content:center; color:var(--sgis-text-2); margin-bottom:4px; } .sgis-review-empty-icon svg { width:20px; height:20px; } /* === 跨区送礼推荐 === */ .sgis-gift-card { padding:10px; border-radius:8px; background:linear-gradient(135deg, rgba(167,139,250,0.12), rgba(102,192,244,0.08)); border:1px solid rgba(167,139,250,0.2); margin-top:8px; } .sgis-gift-title { font-size:12px; font-weight:700; margin-bottom:6px; display:flex; align-items:center; gap:4px; } .sgis-gift-scheme { font-size:14px; font-weight:700; color:#66c0f4; margin:4px 0; } .sgis-gift-save { font-size:20px; font-weight:800; color:#4bb54f; } .sgis-gift-pct { font-size:11px; color:#4bb54f; font-weight:600; } .sgis-gift-prices { display:flex; gap:12px; margin:6px 0; font-size:10px; } .sgis-gift-price-item { display:flex; flex-direction:column; } .sgis-gift-price-label { color:var(--sgis-text-2); } .sgis-gift-price-val { font-weight:600; } .sgis-gift-warn { font-size:9px; color:#e6a839; margin-top:6px; padding:4px 6px; background:rgba(230,168,57,0.08); border-radius:4px; } .sgis-gift-rule { font-size:9px; color:var(--sgis-text-2); margin-top:4px; } .sgis-gift-alt { font-size:10px; color:var(--sgis-text-2); margin-top:6px; padding-top:6px; border-top:1px dashed rgba(255,255,255,0.06); } /* === SVG 价格走势图 === */ .sgis-price-chart-wrap { margin-top:8px; border-radius:8px; background:rgba(255,255,255,0.02); padding:8px 6px 4px; border:1px solid rgba(255,255,255,0.05); } .sgis-price-chart-header { display:flex; align-items:center; justify-content:space-between; margin-bottom:4px; } .sgis-price-chart-title { font-size:10px; color:var(--sgis-text-2); font-weight:500; } .sgis-chart-range-group { display:flex; gap:2px; } .sgis-chart-range-btn { font-size:9px; padding:1px 6px; border-radius:8px; border:1px solid rgba(255,255,255,0.08); background:transparent; color:var(--sgis-text-2); cursor:pointer; transition:all 0.15s; } .sgis-chart-range-btn:hover { background:rgba(255,255,255,0.06); } .sgis-chart-range-btn.active { background:rgba(102,192,244,0.2); color:#66c0f4; border-color:rgba(102,192,244,0.4); } /* === DRM 警告徽章 === */ .sgis-drm-badge { display:inline-flex; align-items:center; gap:3px; font-size:10px; font-weight:600; padding:2px 8px; border-radius:4px; background:rgba(239,68,68,0.15); color:#f87171; border:1px solid rgba(239,68,68,0.25); } .sgis-drm-badge.warn { background:rgba(245,158,11,0.15); color:#fbbf24; border-color:rgba(245,158,11,0.25); } /* === 中文语音标记 === */ .sgis-audio-badge { display:inline-flex; align-items:center; gap:3px; font-size:10px; font-weight:600; padding:2px 8px; border-radius:4px; background:rgba(75,181,79,0.15); color:#4bb54f; border:1px solid rgba(75,181,79,0.25); } /* === 资料受限/Steam正在了解 状态徽章 (参考 steam-restricted-game-realtime-userscript) === */ .sgis-profile-badge { display:inline-flex; align-items:center; gap:3px; font-size:10px; font-weight:600; padding:2px 8px; border-radius:4px; border:1px solid rgba(255,255,255,0.12); background:rgba(255,255,255,0.06); color:var(--sgis-text); } .sgis-profile-badge svg { width:12px; height:12px; flex-shrink:0; } .sgis-profile-badge.restricted { background:rgba(239,68,68,0.15); color:#f87171; border-color:rgba(239,68,68,0.25); } .sgis-profile-badge.learning { background:rgba(245,158,11,0.15); color:#fbbf24; border-color:rgba(245,158,11,0.25); } .sgis-profile-badge.normal { background:rgba(34,197,94,0.12); color:#22c55e; border-color:rgba(34,197,94,0.2); } .sgis-profile-badge.loading { background:rgba(255,255,255,0.04); color:var(--sgis-text-2); border-color:rgba(255,255,255,0.08); } /* === gamestatus.info 破解状态徽章 === */ .sgis-crack-badge { display:inline-flex; align-items:center; gap:3px; font-size:10px; font-weight:600; padding:2px 8px; border-radius:4px; border:1px solid rgba(255,255,255,0.12); background:rgba(255,255,255,0.06); color:var(--sgis-text); } .sgis-crack-badge svg { width:12px; height:12px; flex-shrink:0; } .sgis-crack-badge.cracked { background:rgba(34,197,94,0.15); color:#22c55e; border-color:rgba(34,197,94,0.25); } .sgis-crack-badge.not-cracked { background:rgba(239,68,68,0.15); color:#f87171; border-color:rgba(239,68,68,0.25); } .sgis-crack-badge.bypass { background:rgba(245,158,11,0.15); color:#fbbf24; border-color:rgba(245,158,11,0.25); } .sgis-crack-badge.release-today { background:rgba(59,130,246,0.15); color:#60a5fa; border-color:rgba(59,130,246,0.25); } .sgis-crack-badge.aaa { background:rgba(168,85,247,0.15); color:#c084fc; border-color:rgba(168,85,247,0.25); } .sgis-crack-protection { display:inline-flex; align-items:center; font-size:9px; font-weight:500; padding:1px 6px; border-radius:3px; background:rgba(255,255,255,0.05); color:var(--sgis-text-2); border:1px solid rgba(255,255,255,0.08); } .sgis-crack-group { display:inline-flex; align-items:center; gap:4px; font-size:9px; font-weight:500; padding:1px 6px; border-radius:3px; background:rgba(20,184,166,0.12); color:#2dd4bf; border:1px solid rgba(20,184,166,0.2); } .sgis-crack-group .sgis-crack-group-key { opacity:0.65; font-weight:400; } .sgis-crack-group .sgis-crack-group-val { font-weight:600; } .sgis-crack-date { font-size:9px; color:var(--sgis-text-2); } .sgis-crack-score { display:inline-flex; align-items:center; gap:2px; font-size:9px; font-weight:600; padding:1px 6px; border-radius:3px; background:rgba(250,204,21,0.12); color:#facc15; border:1px solid rgba(250,204,21,0.2); } .sgis-crack-score svg { width:10px; height:10px; } .sgis-crack-hardware { margin-top:6px; padding:6px 8px; border-radius:6px; background:rgba(255,255,255,0.03); border:1px solid rgba(255,255,255,0.06); } .sgis-crack-hardware-title { font-size:10px; font-weight:600; color:var(--sgis-text-2); margin-bottom:4px; } .sgis-crack-hw-row { display:flex; gap:6px; font-size:10px; line-height:1.5; } .sgis-crack-hw-key { color:var(--sgis-text-2); min-width:32px; font-weight:500; } .sgis-crack-hw-val { color:var(--sgis-text); flex:1; word-break:break-word; } /* === 评测搜索(flex 布局,按钮不再溢出) === */ .sgis-review-search-wrap { display:flex; align-items:center; gap:6px; margin-bottom:6px; } .sgis-review-search-input { flex:1; min-width:0; width:auto; box-sizing:border-box; font-size:11px; padding:5px 9px; border-radius:6px; border:1px solid rgba(255,255,255,0.1); background:rgba(255,255,255,0.03); color:var(--sgis-text); transition:border-color 0.15s; } .sgis-review-search-input:focus { outline:none; border-color:rgba(102,192,244,0.4); } .sgis-review-search-input::placeholder { color:var(--sgis-text-2); font-size:10px; } .sgis-review-regex-toggle { flex-shrink:0; font-size:10px; padding:4px 8px; border-radius:6px; border:1px solid rgba(255,255,255,0.1); background:rgba(255,255,255,0.03); color:var(--sgis-text-2); cursor:pointer; transition:all 0.15s; font-family:monospace; font-weight:600; letter-spacing:0.5px; } .sgis-review-regex-toggle:hover { background:rgba(167,139,250,0.1); border-color:rgba(167,139,250,0.3); } .sgis-review-regex-toggle.active { background:rgba(167,139,250,0.2); color:#a78bfa; border-color:rgba(167,139,250,0.4); box-shadow:0 0 0 1px rgba(167,139,250,0.2); } .sgis-review-search-clear { flex-shrink:0; width:22px; height:22px; padding:0; border-radius:50%; border:1px solid rgba(255,255,255,0.1); background:rgba(255,255,255,0.03); color:var(--sgis-text-2); cursor:pointer; transition:all 0.15s; display:flex; align-items:center; justify-content:center; font-size:13px; line-height:1; } .sgis-review-search-clear:hover { background:rgba(230,57,70,0.15); color:#e63946; border-color:rgba(230,57,70,0.4); }`; const CSS_LOAD =` /* === 加载容器(替代裸 spinner,给用户结构感) === */ .sgis-load-block { display:flex; flex-direction:column; align-items:stretch; justify-content:flex-start; padding:18px 16px 14px; gap:10px; } .sgis-load-head { display:flex; align-items:center; gap:8px; font-size:12px; color:var(--sgis-text); } .sgis-load-head .sgis-spinner { width:18px; height:18px; margin:0; flex-shrink:0; } .sgis-load-stage { flex:1; font-weight:600; letter-spacing:0.2px; } .sgis-load-pct { font-size:11px; color:var(--sgis-text-2); font-variant-numeric:tabular-nums; flex-shrink:0; } /* === 主进度条(带渐变 + 流光) === */ .sgis-load-bar { position:relative; height:6px; background:rgba(255,255,255,0.05); border-radius:3px; overflow:hidden; box-shadow:inset 0 1px 2px rgba(0,0,0,0.3); } .sgis-load-bar-fill { position:absolute; left:0; top:0; bottom:0; width:0%; border-radius:3px; background:linear-gradient(90deg,#06b6d4,#3b82f6,#8b5cf6); transition:width 0.35s cubic-bezier(0.4,0,0.2,1); box-shadow:0 0 10px rgba(59,130,246,0.5); } .sgis-load-bar-fill::after { content:""; position:absolute; inset:0; background:linear-gradient(90deg,transparent,rgba(255,255,255,0.45),transparent); animation:sgis-load-shimmer 1.4s linear infinite; } @keyframes sgis-load-shimmer { 0%{transform:translateX(-100%)} 100%{transform:translateX(100%)} } /* === 阶段指示条(4 段小条,阶段切换时高亮) === */ .sgis-load-stages { display:flex; gap:3px; } .sgis-load-stage-bar { flex:1; height:3px; border-radius:2px; background:rgba(255,255,255,0.06); transition:all 0.3s; } .sgis-load-stage-bar.active { background:linear-gradient(90deg,#06b6d4,#3b82f6); box-shadow:0 0 6px rgba(59,130,246,0.6); } .sgis-load-stage-bar.done { background:rgba(16,185,129,0.55); } /* === 骨架屏:与真实游戏行 1:1 布局,避免加载完成后跳变 === */ .sgis-skel-list { display:flex; flex-direction:column; gap:6px; margin-top:4px; } .sgis-skel-row { display:flex; align-items:center; gap:10px; padding:8px 10px; background:rgba(255,255,255,0.02); border:1px solid rgba(255,255,255,0.04); border-radius:8px; } .sgis-skel-icon { width:32px; height:32px; border-radius:4px; flex-shrink:0; background:linear-gradient(90deg,rgba(139,92,246,0.08),rgba(139,92,246,0.18),rgba(139,92,246,0.08)); background-size:200% 100%; animation:sgis-skel-shimmer 1.4s linear infinite; } .sgis-skel-lines { flex:1; min-width:0; display:flex; flex-direction:column; gap:6px; } .sgis-skel-line { height:8px; border-radius:3px; background:linear-gradient(90deg,rgba(255,255,255,0.04),rgba(255,255,255,0.10),rgba(255,255,255,0.04)); background-size:200% 100%; animation:sgis-skel-shimmer 1.4s linear infinite; } .sgis-skel-line.l1 { width:55%; } .sgis-skel-line.l2 { width:30%; height:7px; opacity:0.6; } .sgis-skel-row:nth-child(odd) .sgis-skel-icon, .sgis-skel-row:nth-child(odd) .sgis-skel-line { animation-delay:0s; } .sgis-skel-row:nth-child(even) .sgis-skel-icon, .sgis-skel-row:nth-child(even) .sgis-skel-line { animation-delay:0.2s; } .sgis-skel-row:nth-child(3n) .sgis-skel-icon, .sgis-skel-row:nth-child(3n) .sgis-skel-line { animation-delay:0.4s; } @keyframes sgis-skel-shimmer { 0%{background-position:200% 0} 100%{background-position:-200% 0} } /* === 加载中已完成计数(用户能看到 "已处理 X / 约 Y" 真实进度) === */ .sgis-load-counter { font-size:10px; color:var(--sgis-text-2); text-align:center; font-variant-numeric:tabular-nums; margin-top:2px; }`; const CSS_ALIAS =` /* === v2.11.48: 游戏别名行 (Steam EN + 小黑盒中文别名,异步填充) === */ .sgis-alias-row { display: flex; flex-wrap: wrap; gap: 4px 6px; align-items: center; margin-top: 4px; min-height: 0; line-height: 1; } .sgis-alias-row:empty { display: none; } .sgis-alias-pill { display: inline-flex; align-items: center; gap: 4px; font-size: 10.5px; line-height: 1.4; padding: 2px 7px; border-radius: 4px; background: rgba(255, 255, 255, 0.05); border: 1px solid rgba(255, 255, 255, 0.1); max-width: 100%; } .sgis-alias-pill .sgis-alias-source { font-size: 9px; font-weight: 500; opacity: 0.6; letter-spacing: 0.2px; } .sgis-alias-pill .sgis-alias-value { font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 200px; } .sgis-alias-en { border-color: rgba(147, 197, 253, 0.25); background: rgba(96, 165, 250, 0.08); }`; const CSS_THEME_PURPLE =` /* ====== 1. 全局 CSS 变量覆盖 → 紫色主调 ====== */ :root { --sglv-accent: #a78bfa !important; --sglv-accent-light: #c4b5fd !important; --sglv-accent-deep: #8b5cf6 !important; --sglv-accent-glow: rgba(139, 92, 246, 0.4) !important; --sglv-accent-bg: rgba(139, 92, 246, 0.12) !important; --sglv-accent-border: rgba(139, 92, 246, 0.3) !important; } /* ====== 2. 面板头部 → 紫色调 ====== */ .sglv-panel > .sglv-header { background: linear-gradient(135deg, rgba(27, 40, 56, 0.95) 0%, rgba(42, 71, 94, 0.95) 100%) !important; border-bottom: 1px solid rgba(139, 92, 246, 0.2) !important; } .sglv-header-brand { background: linear-gradient(135deg, rgba(139, 92, 246, 0.18), rgba(99, 102, 241, 0.12)) !important; border: 1px solid rgba(139, 92, 246, 0.25) !important; color: #a78bfa !important; } .sglv-header-brand:hover { box-shadow: 0 2px 8px rgba(139, 92, 246, 0.35), inset 0 1px 0 rgba(255, 255, 255, 0.1) !important; } /* ====== 3. Tab 激活态 → 紫色 ====== */ .sglv-panel .sglv-tab.active { color: #fff !important; background: rgba(139, 92, 246, 0.18) !important; border-color: rgba(139, 92, 246, 0.4) !important; box-shadow: 0 0 0 1px rgba(139, 92, 246, 0.15) inset, 0 1px 4px rgba(139, 92, 246, 0.2) !important; } .sglv-panel .sglv-tab:hover { background: rgba(139, 92, 246, 0.08) !important; } /* ====== 4. 全局搜索框聚焦 → 紫色 ====== */ .sglv-panel .sglv-global-search:focus-within { border-color: rgba(139, 92, 246, 0.55) !important; box-shadow: 0 0 0 1px rgba(139, 92, 246, 0.25) !important; } /* ====== 5. KPI 卡片 — 恢复紫色变体 ====== */ /* amber 变体保持金色(原版设计) */ .sglv-playtime-kpi-card.amber { border-color: rgba(245, 158, 11, 0.35) !important; } .sglv-playtime-kpi-card.amber::before { background: #f59e0b !important; } .sglv-playtime-kpi-card.amber .sglv-playtime-kpi-value { color: #fbbf24 !important; } .sglv-playtime-kpi-card.amber .sglv-playtime-kpi-icon { background: rgba(245, 158, 11, 0.15) !important; color: #fbbf24 !important; } /* purple 变体 → 恢复紫色 */ .sglv-playtime-kpi-card.purple { border-color: rgba(139, 92, 246, 0.35) !important; } .sglv-playtime-kpi-card.purple::before { background: #8b5cf6 !important; } .sglv-playtime-kpi-card.purple .sglv-playtime-kpi-value { color: #c4b5fd !important; } .sglv-playtime-kpi-card.purple .sglv-playtime-kpi-icon { background: rgba(139, 92, 246, 0.15) !important; color: #c4b5fd !important; } /* blue/cyan/green/rose 语义色保持不变 */ /* ====== 6. 统计仪表 — 区块标题 → 紫色 ====== */ .sglv-playtime-section-title { color: #a78bfa !important; border-bottom: 1px solid rgba(139, 92, 246, 0.12) !important; } .sglv-playtime-section-title svg { color: #a78bfa !important; } /* ====== 7. 趋势筛选按钮 → 紫色激活 ====== */ .sglv-trend-btn.active { background: rgba(139, 92, 246, 0.18) !important; color: #c4b5fd !important; border-color: rgba(139, 92, 246, 0.3) !important; } .sglv-trend-btn:hover { background: rgba(139, 92, 246, 0.1) !important; } /* ====== 8. 进度条 → 青蓝紫渐变 ====== */ #sglv-stage-progress .sglv-stage-progress-fill { background: linear-gradient(90deg, #06b6d4 0%, #3b82f6 50%, #8b5cf6 100%) !important; } #sglv-stage-progress { background: linear-gradient(180deg, rgba(139, 92, 246, 0.06), transparent) !important; border-bottom: 1px solid rgba(139, 92, 246, 0.12) !important; } /* ====== 9. 仪表盘 — 新增雷达图区块 ====== */ .sglv-radar-row { display: grid; grid-template-columns: 280px 1fr; gap: 10px; flex: 0 0 auto; min-height: 0; } @media (max-width: 900px) { .sglv-radar-row { grid-template-columns: 1fr; } } .sglv-radar-card { background: linear-gradient(135deg, rgba(34, 211, 238, 0.05), rgba(139, 92, 246, 0.04), rgba(244, 114, 182, 0.04), rgba(13, 17, 23, 0.4)); border: 1px solid rgba(139, 92, 246, 0.12); border-radius: 10px; padding: 12px; display: flex; flex-direction: column; align-items: center; gap: 8px; } .sglv-radar-card-title { font-size: 12px; font-weight: 700; background: linear-gradient(90deg, #22d3ee, #34d399, #a78bfa, #f472b6, #f59e0b); -webkit-background-clip: text; background-clip: text; -webkit-text-fill-color: transparent; display: flex; align-items: center; gap: 6px; align-self: flex-start; } .sglv-radar-card-title svg { width: 14px; height: 14px; color: #a78bfa; } .sglv-radar-svg { width: 220px; height: 220px; } .sglv-radar-svg .radar-grid { fill: none; stroke: rgba(255, 255, 255, 0.08); stroke-width: 1; } .sglv-radar-svg .radar-axis { stroke-width: 1; } .sglv-radar-svg .radar-area { stroke-width: 2; stroke-linejoin: round; transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1); } .sglv-radar-svg .radar-point { stroke: #0d1117; stroke-width: 2; transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1); } .sglv-radar-svg .radar-label { font-size: 10px; font-weight: 700; text-anchor: middle; } .sglv-radar-svg .radar-value { font-size: 11px; font-weight: 800; text-anchor: middle; } /* 雷达图右侧统计面板 */ .sglv-radar-stats { display: flex; flex-direction: column; gap: 6px; padding: 12px; background: rgba(13, 17, 23, 0.4); border: 1px solid rgba(255, 255, 255, 0.05); border-radius: 10px; } .sglv-radar-stat-item { display: flex; align-items: center; gap: 8px; padding: 6px 8px; border-radius: 8px; background: rgba(255, 255, 255, 0.02); border: 1px solid rgba(255, 255, 255, 0.04); transition: background 0.15s; } .sglv-radar-stat-item:hover { background: rgba(255, 255, 255, 0.05); } .sglv-radar-stat-icon { width: 28px; height: 28px; border-radius: 8px; flex-shrink: 0; display: flex; align-items: center; justify-content: center; } .sglv-radar-stat-icon svg { width: 14px; height: 14px; } .sglv-radar-stat-info { flex: 1; min-width: 0; } .sglv-radar-stat-label { font-size: 10px; color: #8b949e; font-weight: 600; } .sglv-radar-stat-bar { height: 4px; background: rgba(255, 255, 255, 0.06); border-radius: 2px; overflow: hidden; margin-top: 3px; } .sglv-radar-stat-bar-fill { height: 100%; border-radius: 2px; transition: width 0.6s cubic-bezier(0.4, 0, 0.2, 1); } .sglv-radar-stat-val { font-size: 14px; font-weight: 700; font-variant-numeric: tabular-nums; flex-shrink: 0; } /* ====== 10. 仪表盘 KPI 行增强 — hover 微光 ====== */ .sglv-playtime-kpi-card { position: relative; transition: transform 0.15s, box-shadow 0.15s, border-color 0.15s; } .sglv-playtime-kpi-card:hover { transform: translateY(-1px); box-shadow: 0 3px 10px rgba(0, 0, 0, 0.2); } .sglv-playtime-kpi-card.amber:hover { box-shadow: 0 3px 10px rgba(245, 158, 11, 0.15); } /* v1.0.3: playtime-kpi 卡片炫彩升级——叠加 accent 渐变背景 + shadow-sm 基线 + hover 抬升 + 外发光 */ .sglv-playtime-kpi-card { overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,.35), inset 0 1px 0 rgba(255,255,255,.04); } .sglv-playtime-kpi-card::before { content: ''; position: absolute; inset: -1px; pointer-events: none; background: linear-gradient(135deg, rgba(102,192,244,.3), transparent 60%); opacity: 0; transition: opacity .18s ease; } .sglv-playtime-kpi-card:hover::before { opacity: 1; } .sglv-playtime-kpi-card:hover { box-shadow: 0 6px 20px rgba(0,0,0,.45), 0 0 0 1px rgba(102,192,244,.25), 0 0 22px rgba(102,192,244,.18), inset 0 1px 0 rgba(255,255,255,.06); } .sglv-playtime-kpi-value { text-shadow: 0 0 14px rgba(102,192,244,.25); } .sglv-playtime-kpi-card > * { position: relative; z-index: 1; } /* ====== 11. 仪表盘 KPI 行 — 7 列 grid (含雷达图入口) ====== */ .sglv-stats-dashboard { display: grid !important; grid-template-columns: repeat(7, 1fr) !important; gap: 6px !important; } /* ====== 12. 甜甜圈图中心文字 → 紫色 ====== */ .sglv-pt-donut-center-val { fill: #a78bfa !important; } .sglv-pt-donut-center-label { fill: #8b949e !important; } /* ====== 13. 热力图标题 → 紫色 ====== */ .sglv-heatmap-section .sglv-playtime-section-title { color: #a78bfa !important; } .sglv-hm-mini-title { color: #a78bfa !important; } /* ====== 14. 成就页 — 环形进度图背景 → 紫色 ====== */ .sglv-ach-ring-bg { stroke: rgba(139, 92, 246, 0.1) !important; } /* 注意: gradient 定义在 SVG defs 中,需在 JS 中修改 stop colors */ /* ====== 15. 成就页 — 侧边栏用户卡片紫色调 ====== */ .sglv-ach-user-card { background: linear-gradient(160deg, rgba(139, 92, 246, 0.1), rgba(99, 102, 241, 0.04)) !important; } .sglv-ach-user-card::after { background: radial-gradient(circle, rgba(139, 92, 246, 0.12), transparent 60%) !important; } .sglv-ach-user-avatar { background: linear-gradient(135deg, #8b5cf6, #6366f1) !important; box-shadow: 0 8px 24px rgba(139, 92, 246, 0.35) !important; } .sglv-ach-user-level { border: 2px solid #a78bfa !important; color: #c4b5fd !important; } .sglv-ach-user-pts strong { color: #c4b5fd !important; } /* ====== 16. 成就页 — 分类导航紫色激活 ====== */ .sglv-ach-nav-item:hover { background: rgba(139, 92, 246, 0.08) !important; } .sglv-ach-nav-item.active { background: linear-gradient(90deg, rgba(139, 92, 246, 0.2), transparent) !important; } .sglv-ach-nav-item-icon { background: rgba(139, 92, 246, 0.12) !important; } .sglv-ach-nav-item.active .sglv-ach-nav-item-icon { background: rgba(139, 92, 246, 0.2) !important; } .sglv-ach-nav-item-badge { background: rgba(139, 92, 246, 0.15) !important; color: #c4b5fd !important; } .sglv-ach-nav-item.active .sglv-ach-nav-item-badge { background: #8b5cf6 !important; color: #0d1117 !important; } /* ====== 17. 成就页 — 侧边栏最近解锁紫色调 ====== */ .sglv-ach-sidebar-recent-icon { background: linear-gradient(135deg, #8b5cf6, #6366f1) !important; } .sglv-ach-sidebar-recent-item:hover { background: rgba(139, 92, 246, 0.06) !important; } .sglv-ach-sidebar-recent-name { color: #e2e8f0 !important; } /* ====== 18. 成就页 — 统计概览区紫色调 ====== */ .sglv-ach-header { background: linear-gradient(135deg, rgba(30, 41, 59, 0.6), rgba(15, 23, 42, 0.6)) !important; border-bottom: 1px solid rgba(139, 92, 246, 0.12) !important; gap: 14px !important; padding: 16px 20px !important; } /*环形进度数值使用炫彩渐变,不强制紫色 */ /* ====== 19. 成就页 — 成就卡片紫色调 ====== */ .sglv-ach-card { background: linear-gradient(135deg, rgba(13, 17, 23, 0.6), rgba(30, 41, 59, 0.4)) !important; border: 1px solid rgba(139, 92, 246, 0.08) !important; } .sglv-ach-card:hover { border-color: rgba(139, 92, 246, 0.3) !important; box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3) !important; } .sglv-ach-card.unlocked { background: linear-gradient(135deg, rgba(139, 92, 246, 0.05), rgba(13, 17, 23, 0.4)) !important; border-color: rgba(139, 92, 246, 0.15) !important; } .sglv-ach-card.unlocked .sglv-ach-card-name { color: #c4b5fd !important; } .sglv-ach-card.unlocked .sglv-ach-card-pts { background: linear-gradient(135deg, rgba(139, 92, 246, 0.15), rgba(99, 102, 241, 0.1)) !important; border-color: rgba(139, 92, 246, 0.3) !important; color: #c4b5fd !important; } .sglv-ach-card.unlocked .sglv-ach-card-progress-fill { background: linear-gradient(90deg, #22d3ee, #34d399, #fbbf24) !important; box-shadow: 0 0 8px rgba(34, 211, 238, 0.4) !important; } .sglv-ach-card.locked .sglv-ach-card-progress-fill { background: linear-gradient(90deg, #38bdf8, #a78bfa, #f59e0b) !important; box-shadow: 0 0 8px rgba(56, 189, 248, 0.25) !important; } .sglv-ach-card-icon { background: linear-gradient(135deg, rgba(139, 92, 246, 0.15), rgba(99, 102, 241, 0.08)) !important; } /* 稀有度色保持不变(legendary 已是金色, common/rare/epic 语义色保留) */ .sglv-ach-card.unlocked .sglv-ach-card-icon { box-shadow: inset 0 1px 0 rgba(255,255,255,0.15), inset 0 -1px 0 rgba(0,0,0,0.2), 0 4px 12px rgba(139, 92, 246, 0.2) !important; } /* ====== 20. 成就页 — 内容标题紫色调 ====== */ .sglv-ach-content-title { color: #a78bfa !important; } .sglv-ach-content-count { background: rgba(139, 92, 246, 0.1) !important; color: #c4b5fd !important; } .sglv-ach-reset-btn { border: 1px solid rgba(239, 68, 68, 0.3) !important; background: rgba(239, 68, 68, 0.08) !important; } /* ====== 21. 个人展柜 — 英雄区紫青色调(恢复原版色彩平衡) ====== */ .sglv-sc-hero { background: linear-gradient(135deg, rgba(99,102,241,0.10) 0%, rgba(168,85,247,0.06) 50%, rgba(6,182,212,0.04) 100%) !important; border: 1px solid rgba(99,102,241,0.15) !important; } .sglv-sc-hero::before { background: radial-gradient(ellipse at top right, rgba(168,85,247,0.10), transparent 60%) !important; } .sglv-sc-avatar { border: 2px solid rgba(255, 255, 255, 0.12) !important; box-shadow: 0 1px 8px rgba(0, 0, 0, 0.35), 0 0 0 1px rgba(168, 85, 247, 0.25) !important; } .sglv-sc-avatar-placeholder { background: linear-gradient(135deg, #6366f1, #8b5cf6) !important; } /* 用户名保持白色,不加金色 */ .sglv-sc-hero-name { color: #f1f5f9 !important; } /* 国家标签保持中性灰 */ .sglv-sc-hero-country { background: rgba(148, 163, 184, 0.08) !important; color: #94a3b8 !important; border: 1px solid rgba(148, 163, 184, 0.1) !important; } /* Hero 统计图标 → 恢复靛蓝色 */ .sglv-sc-hero-stat svg { color: #818cf8 !important; } /* Hero 统计数值 → 恢复浅色 */ .sglv-sc-hero-stat-val { color: #e2e8f0 !important; } /* ====== 22. 展柜卡片标题 → 恢复紫色 ====== */ .sglv-sc-card-header svg { color: #a78bfa !important; } .sglv-sc-card-title { color: #e6edf3 !important; } /* ====== 23. 展柜封面网格 → 恢复紫色 hover ====== */ .sglv-sc-cover-item { border: 1px solid rgba(255, 255, 255, 0.06) !important; } .sglv-sc-cover-item:hover { border-color: rgba(168, 85, 247, 0.5) !important; box-shadow: 0 4px 16px rgba(168, 85, 247, 0.2) !important; } /* ====== 24. 展柜最近游玩 → 恢复靛蓝紫色 ====== */ .sglv-sc-playtime-item:hover { background: rgba(99, 102, 241, 0.06) !important; } .sglv-sc-playtime-bar { background: rgba(99, 102, 241, 0.1) !important; } .sglv-sc-playtime-bar-fill { background: linear-gradient(90deg, #6366f1, #a855f7) !important; } /* ====== 25. 展柜标签徽章 → 移除金色覆盖,恢复原版多彩 ====== */ /* 原版已有: collector(紫), playtime(青), mastery(绿), diversity(橙), loyalty(粉), special(金) */ /* ====== 27. Toast 通知 → 紫色 ====== */ #sglv-toast.sglv-toast-success { border-left-color: #8b5cf6 !important; } #sglv-toast.sglv-toast-info { border-left-color: #66c0f4 !important; } /* ====== 28. 页码按钮 → 紫色 hover ====== */ .sglv-page-arrow:hover:not(:disabled) { background: rgba(139, 92, 246, 0.15) !important; border-color: rgba(139, 92, 246, 0.4) !important; } /* ====== 29. 仪表盘图表行卡片容器 → 紫色微边 ====== */ .sglv-playtime-col { background: rgba(13, 17, 23, 0.3); border: 1px solid rgba(139, 92, 246, 0.06); border-radius: 10px; padding: 10px; } .sglv-heatmap-section, .sglv-heatmap-mini-section { background: rgba(13, 17, 23, 0.3) !important; border: 1px solid rgba(139, 92, 246, 0.06) !important; border-radius: 10px !important; } /* ====== 30. SGIS 侧边栏标签 → 恢复紫色激活态 ====== */ .sgis-tab.active .sgis-svg { filter: drop-shadow(0 1px 4px rgba(139, 92, 246, 0.45)) !important; } .sgis-tab.active { border-bottom-color: #8b5cf6 !important; } .sgis-tabs::after { background: linear-gradient(90deg, transparent, rgba(139, 92, 246, 0.35), transparent) !important; } /* ====== 31. SGIS 标题图标 → 恢复紫蓝渐变 ====== */ .sgis-title-icon { background: linear-gradient(135deg, #8b5cf6 0%, #6366f1 50%, #3b82f6 100%) !important; box-shadow: 0 4px 12px rgba(139, 92, 246, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.25), inset 0 -1px 0 rgba(0, 0, 0, 0.2) !important; } .sgis-fab { background: linear-gradient(135deg, #8b5cf6, #6366f1) !important; box-shadow: 0 4px 12px rgba(139, 92, 246, 0.4) !important; } /* ====== 32. 加载进度条 → 恢复青蓝紫渐变 ====== */ .sgis-load-bar-fill { background: linear-gradient(90deg, #06b6d4, #3b82f6, #8b5cf6) !important; box-shadow: 0 0 10px rgba(59, 130, 246, 0.5) !important; } .sgis-load-stage-bar.active { background: linear-gradient(90deg, #06b6d4, #3b82f6) !important; box-shadow: 0 0 6px rgba(59, 130, 246, 0.6) !important; } .sgis-skel-icon { background: linear-gradient(90deg, rgba(139, 92, 246, 0.08), rgba(139, 92, 246, 0.18), rgba(139, 92, 246, 0.08)) !important; background-size: 200% 100% !important; } /* ====== 34. 云存档 KPI 卡片 → 紫色调 ====== */ .sglv-cs-source-badge { background: rgba(139, 92, 246, 0.12) !important; color: #c4b5fd !important; border: 1px solid rgba(139, 92, 246, 0.2) !important; } .sglv-cs-refresh-btn:hover { color: #a78bfa !important; background: rgba(139, 92, 246, 0.12) !important; } .sglv-cs-top10-bar { background: linear-gradient(90deg, #6366f1, #a855f7) !important; } /* ====== 35. 集合工具栏刷新按钮 → 紫色 hover ====== */ .sglv-col-refresh-btn:hover { color: #a78bfa !important; background: rgba(139, 92, 246, 0.1) !important; } /* ====== 36. 移动端适配 ====== */ @media (max-width: 768px) { .sglv-radar-row { grid-template-columns: 1fr; } .sglv-radar-svg { width: 180px; height: 180px; } } @media (max-width: 480px) { .sglv-radar-svg { width: 160px; height: 160px; } .sglv-radar-card { padding: 8px; } } /* ====== SGIS Hero — 紫青平衡 + 紧凑布局 + 保留背景图 ====== */ /* 主卡片:恢复紫色渐变基调,紧凑 padding 保留 */ .sgis-profile-main-card { background: linear-gradient(160deg, #1a1633 0%, #16142b 40%, #0f0d20 100%) !important; box-shadow: 0 8px 32px rgba(0, 0, 0, 0.45), 0 0 0 1px rgba(139, 92, 246, 0.15) !important; padding: 14px 14px 12px !important; border-radius: 16px !important; } /* 右上角径向光晕 → 紫色 */ .sgis-profile-main-card::before { background: radial-gradient(circle, rgba(139, 92, 246, 0.4) 0%, transparent 60%) !important; } /* 底部高光线 → 紫色 */ .sgis-profile-main-card::after { background: linear-gradient(90deg, transparent 0%, rgba(139, 92, 246, 0.6) 50%, transparent 100%) !important; } /* 背景装饰图 → 恢复原始 game-library.png + 紫色滤镜 + mask */ .sgis-profile-main-card-bg { background: url('https://leanisssharedstorage.blob.core.windows.net/copilot/asdm-files/game-library.png') no-repeat center center !important; background-size: contain !important; opacity: 0.18 !important; filter: saturate(1.2) drop-shadow(0 0 20px rgba(139, 92, 246, 0.25)) !important; mask-image: linear-gradient(90deg, rgba(0,0,0,0) 0%, rgba(0,0,0,1) 40%, rgba(0,0,0,1) 100%) !important; -webkit-mask-image: linear-gradient(90deg, rgba(0,0,0,0) 0%, rgba(0,0,0,1) 40%, rgba(0,0,0,1) 100%) !important; } /* Hero 头部行 → 紧凑(保留) */ .sgis-profile-head { gap: 12px !important; margin-bottom: 12px !important; } /* 头像 → 64px + 青色边框(原版色调) */ .sgis-profile-avatar { width: 64px !important; height: 64px !important; border-radius: 18px !important; border: 2px solid rgba(102, 192, 244, 0.5) !important; box-shadow: 0 6px 20px rgba(0, 0, 0, 0.4), 0 0 0 3px rgba(102, 192, 244, 0.08) !important; } /* 在线状态徽章 → 恢复紫蓝渐变 */ .sgis-profile-avatar-badge { background: linear-gradient(135deg, #8b5cf6 0%, #6366f1 50%, #3b82f6 100%) !important; box-shadow: 0 4px 12px rgba(139, 92, 246, 0.5), 0 0 0 2px #16142b !important; } /* 等级徽章 → 保持金色(原版即为金色,作为 premium accent) */ .sgis-profile-level-badge { background: linear-gradient(135deg, #f59e0b 0%, #f97316 100%) !important; box-shadow: 0 2px 6px rgba(249, 115, 22, 0.4) !important; } /* 用户名 → 白色,不加金色 text-shadow */ .sgis-profile-name { text-shadow: none !important; } /* SteamID → 恢复灰蓝色 */ .sgis-profile-steamid { color: rgba(148, 163, 184, 0.9) !important; } /* 验证徽章 → 恢复紫蓝渐变 */ .sgis-profile-verified { background: linear-gradient(135deg, #8b5cf6, #3b82f6) !important; box-shadow: 0 2px 6px rgba(139, 92, 246, 0.4) !important; } /* 好友数进度环 → 恢复绿色 */ .sgis-friend-gauge-text b { color: #10b981 !important; } .sgis-friend-gauge:hover { background: rgba(255, 255, 255, 0.05) !important; } /* ====== 38. SGIS KPI 统计卡片 — 恢复多彩语义色 ====== */ /* 默认状态:恢复中性背景,移除大面积金色 */ .sgis-profile-stat { background: linear-gradient(160deg, rgba(255, 255, 255, 0.04) 0%, rgba(255, 255, 255, 0.01) 100%) !important; border: 1px solid rgba(255, 255, 255, 0.06) !important; border-radius: 12px !important; transition: all 0.2s ease !important; } /* 顶部高光线 → 恢复 currentColor 语义色 */ .sgis-profile-stat::after { opacity: 0.35 !important; } /* hover → 紫色光晕 + 上浮 */ .sgis-profile-stat:hover { border-color: rgba(139, 92, 246, 0.3) !important; background: linear-gradient(160deg, rgba(139, 92, 246, 0.08) 0%, rgba(59, 130, 246, 0.03) 100%) !important; box-shadow: 0 6px 16px rgba(0, 0, 0, 0.3) !important; transform: translateY(-2px) !important; } /* 默认图标背景 → 恢复紫蓝渐变 */ .sgis-profile-stat-icon { background: linear-gradient(135deg, rgba(139, 92, 246, 0.2), rgba(59, 130, 246, 0.08)) !important; box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.04) !important; } .sgis-profile-stat-icon svg { color: #c4b5fd !important; } /* t-blue / t-purple / t-cyan / t-green / t-rose → 全部恢复原版语义色 */ .sgis-profile-stat-icon.t-blue { background: linear-gradient(135deg, rgba(59, 130, 246, 0.22), rgba(37, 99, 235, 0.08)) !important; box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.04) !important; } .sgis-profile-stat-icon.t-blue svg { color: #93c5fd !important; } .sgis-profile-stat-icon.t-purple { background: linear-gradient(135deg, rgba(168, 85, 247, 0.22), rgba(139, 92, 246, 0.08)) !important; box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.04) !important; } .sgis-profile-stat-icon.t-purple svg { color: #c4b5fd !important; } .sgis-profile-stat-val.t-purple { color: #c4b5fd !important; } /* KPI 值文字 → 移除金色光泽 */ .sgis-profile-stat-val { text-shadow: none !important; } /* 5列模式 KPI 紧凑(保留布局优化) */ .sgis-profile-stats.cols-5 { gap: 6px !important; } .sgis-profile-stats.cols-5 .sgis-profile-stat { padding: 10px 4px 8px !important; border-radius: 10px !important; } /* ====== 39. SGIS 区块标题 — 恢复紫色 ====== */ .sgis-section-title { color: #a78bfa !important; border-bottom: 1px solid rgba(139, 92, 246, 0.08) !important; } .sgis-section-title svg { color: #a78bfa !important; } /* ====== 40. SGIS 战绩/游戏人生 双大卡 — 恢复紫蓝色调 ====== */ .sgis-feature-card { background: linear-gradient(160deg, rgba(139, 92, 246, 0.12) 0%, rgba(59, 130, 246, 0.04) 50%, rgba(15, 17, 35, 0.6) 100%) !important; border: 1px solid rgba(139, 92, 246, 0.2) !important; transition: all 0.25s ease !important; } .sgis-feature-card::before { background: radial-gradient(circle, rgba(139, 92, 246, 0.2) 0%, transparent 60%) !important; } .sgis-feature-card::after { background: linear-gradient(90deg, transparent 0%, rgba(139, 92, 246, 0.5) 50%, transparent 100%) !important; } .sgis-feature-card:hover { border-color: rgba(139, 92, 246, 0.4) !important; box-shadow: 0 8px 20px rgba(139, 92, 246, 0.2) !important; transform: translateY(-2px) !important; } /* alt 变体 → 恢复靛蓝色 */ .sgis-feature-card.alt { background: linear-gradient(160deg, rgba(99, 102, 241, 0.12) 0%, rgba(59, 130, 246, 0.04) 50%, rgba(15, 17, 35, 0.6) 100%) !important; border-color: rgba(99, 102, 241, 0.2) !important; } .sgis-feature-card.alt::before { background: radial-gradient(circle, rgba(99, 102, 241, 0.2) 0%, transparent 60%) !important; } .sgis-feature-card.alt::after { background: linear-gradient(90deg, transparent 0%, rgba(99, 102, 241, 0.5) 50%, transparent 100%) !important; } /* 特征卡片图标 → 恢复紫蓝色 */ .sgis-feature-icon { background: linear-gradient(135deg, rgba(139, 92, 246, 0.22), rgba(59, 130, 246, 0.12)) !important; box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.04), 0 2px 6px rgba(139, 92, 246, 0.15) !important; } .sgis-feature-icon svg { color: #c4b5fd !important; } .sgis-feature-card.alt .sgis-feature-icon { background: linear-gradient(135deg, rgba(99, 102, 241, 0.22), rgba(59, 130, 246, 0.12)) !important; box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.04), 0 2px 6px rgba(99, 102, 241, 0.15) !important; } .sgis-feature-card.alt .sgis-feature-icon svg { color: #a5b4fc !important; } /* hover 箭头 → 紫色 */ .sgis-feature-card:hover .sgis-feature-arrow { color: #c4b5fd !important; } /* 特征卡片数值 → 恢复紫色 */ .sgis-feature-stat-val.t-purple { color: #c4b5fd !important; } /* ====== 40b. SGIS 双大卡紧凑优化 — 3列统计行 + 压缩高度 ====== */ .sis-feature-grid, .sgis-feature-grid { gap: 8px !important; margin-bottom: 8px !important; } .sgis-feature-card { padding: 10px 10px 8px !important; } .sgis-feature-head { gap: 8px !important; margin-bottom: 8px !important; } .sgis-feature-icon { width: 30px !important; height: 30px !important; border-radius: 8px !important; } .sgis-feature-icon svg { width: 15px !important; height: 15px !important; } .sgis-feature-title { font-size: 13px !important; } .sgis-feature-sub { font-size: 9px !important; margin-top: 1px !important; } .sgis-feature-arrow { width: 14px !important; height: 14px !important; } /* 3列统计行 — 战绩总览 */ .sgis-feature-stats-3 { grid-template-columns: repeat(3, 1fr) !important; gap: 4px !important; } .sgis-feature-stats-3 .sgis-feature-stat { padding: 5px 4px !important; } .sgis-feature-stats-3 .sgis-feature-stat-lbl { font-size: 8px !important; margin-bottom: 1px !important; } .sgis-feature-stats-3 .sgis-feature-stat-val { font-size: 13px !important; } /* 游戏人生卡片紧凑 */ .sgis-feature-card.alt .sgis-feature-stats { gap: 4px !important; } .sgis-feature-card.alt .sgis-feature-stat { padding: 5px 4px !important; } .sgis-feature-card.alt .sgis-feature-stat-lbl { font-size: 8px !important; margin-bottom: 1px !important; } .sgis-feature-card.alt .sgis-feature-stat-val { font-size: 13px !important; } .sgis-feature-extra { margin-top: 6px !important; padding: 5px 8px !important; font-size: 9px !important; } .sgis-feature-extra svg { width: 11px !important; height: 11px !important; } /* ====== 41. SGIS XP 卡片 — 保持金色进度条(原版设计),恢复中性背景 ====== */ .sgis-xp-card { border: 1px solid rgba(255, 255, 255, 0.06) !important; background: linear-gradient(160deg, rgba(255, 255, 255, 0.035) 0%, rgba(15, 17, 35, 0.5) 100%) !important; } /* XP 进度条和图标保持原版金色系,不做覆盖 */ /* XP 等级 next → 恢复紫色 */ .sgis-xp-levels .next { color: #c4b5fd !important; } /* XP 累计数值 → 恢复紫色 */ .sgis-xp-total b { color: #c4b5fd !important; } /* ====== 42. SGIS 社交标题 ====== */ .sgis-section-title.sgis-social-title { border-bottom-color: rgba(139, 92, 246, 0.08) !important; } /* ====== 43. SGIS copy 按钮 hover ====== */ .sgis-copy-btn:hover { background: rgba(255, 255, 255, 0.1) !important; color: #fff !important; }`; const CSS_THEME_BLUE =` /* ===================================================================== *经典蓝主题层 —— scripts/gen-sglv-theme-blue.js 自动生成,勿手改(重跑再生) * Part A: 典雅紫主题层(CSS_THEME_PURPLE)色值镜像映射 —— 覆盖面板/侧边栏全部可见表面 * Part B: 主脚本 CSS 常量原生紫色规则 → 蓝色瘦身覆盖(仅换色声明 + !important) * Part C: 共享样式库(sglv-shared-css)原生紫色规则 → 蓝色瘦身覆盖 * Part D: 侧边栏手工精调(靛蓝暗基底→Steam 深蓝/标题栏柔化,自动映射盲区) * Part E: 收藏库(sglv-game-collection)面板 CSS 紫色覆盖(html[data-sglv-theme] 前缀, * 特异性压过其懒注入且带 220 处 !important 的 <style>,顺序无关) * 映射: #a78bfa→#66c0f4 #c4b5fd→#a3d5f7 #8b5cf6→#1a9fff #a855f7→#3b82f6 * #6366f1→#2563eb #818cf8→#60a5fa + 深紫背景系;语义色(金/绿/红/玫/青)保持 * 例外: .sglv-set-theme-swatch 主题预览色板固定不随主题切换 * ===================================================================== */ /* ########## Part A: 紫色主题层镜像(共 663 行) ########## */ /* ====== 1. 全局 CSS 变量覆盖 → 紫色主调 ====== */ :root { --sglv-accent: #66c0f4 !important; --sglv-accent-light: #a3d5f7 !important; --sglv-accent-deep: #1a9fff !important; --sglv-accent-glow: rgba(102, 192, 244, 0.4) !important; --sglv-accent-bg: rgba(102, 192, 244, 0.12) !important; --sglv-accent-border: rgba(102, 192, 244, 0.3) !important; } /* ====== 2. 面板头部 → 紫色调 ====== */ .sglv-panel > .sglv-header { background: linear-gradient(135deg, rgba(27, 40, 56, 0.95) 0%, rgba(42, 71, 94, 0.95) 100%) !important; border-bottom: 1px solid rgba(26,159,255, 0.2) !important; } .sglv-header-brand { background: linear-gradient(135deg, rgba(26,159,255, 0.18), rgba(37,99,235, 0.12)) !important; border: 1px solid rgba(26,159,255, 0.25) !important; color: #66c0f4 !important; } .sglv-header-brand:hover { box-shadow: 0 2px 8px rgba(26,159,255, 0.35), inset 0 1px 0 rgba(255, 255, 255, 0.1) !important; } /* ====== 3. Tab 激活态 → 紫色 ====== */ .sglv-panel .sglv-tab.active { color: #fff !important; background: rgba(26,159,255, 0.18) !important; border-color: rgba(26,159,255, 0.4) !important; box-shadow: 0 0 0 1px rgba(26,159,255, 0.15) inset, 0 1px 4px rgba(26,159,255, 0.2) !important; } .sglv-panel .sglv-tab:hover { background: rgba(26,159,255, 0.08) !important; } /* ====== 4. 全局搜索框聚焦 → 紫色 ====== */ .sglv-panel .sglv-global-search:focus-within { border-color: rgba(26,159,255, 0.55) !important; box-shadow: 0 0 0 1px rgba(26,159,255, 0.25) !important; } /* ====== 5. KPI 卡片 — 恢复紫色变体 ====== */ /* amber 变体保持金色(原版设计) */ .sglv-playtime-kpi-card.amber { border-color: rgba(245, 158, 11, 0.35) !important; } .sglv-playtime-kpi-card.amber::before { background: #f59e0b !important; } .sglv-playtime-kpi-card.amber .sglv-playtime-kpi-value { color: #fbbf24 !important; } .sglv-playtime-kpi-card.amber .sglv-playtime-kpi-icon { background: rgba(245, 158, 11, 0.15) !important; color: #fbbf24 !important; } /* purple 变体 → 恢复紫色 */ .sglv-playtime-kpi-card.purple { border-color: rgba(26,159,255, 0.35) !important; } .sglv-playtime-kpi-card.purple::before { background: #1a9fff !important; } .sglv-playtime-kpi-card.purple .sglv-playtime-kpi-value { color: #a3d5f7 !important; } .sglv-playtime-kpi-card.purple .sglv-playtime-kpi-icon { background: rgba(26,159,255, 0.15) !important; color: #a3d5f7 !important; } /* blue/cyan/green/rose 语义色保持不变 */ /* ====== 6. 统计仪表 — 区块标题 → 紫色 ====== */ .sglv-playtime-section-title { color: #66c0f4 !important; border-bottom: 1px solid rgba(26,159,255, 0.12) !important; } .sglv-playtime-section-title svg { color: #66c0f4 !important; } /* ====== 7. 趋势筛选按钮 → 紫色激活 ====== */ .sglv-trend-btn.active { background: rgba(26,159,255, 0.18) !important; color: #a3d5f7 !important; border-color: rgba(26,159,255, 0.3) !important; } .sglv-trend-btn:hover { background: rgba(26,159,255, 0.1) !important; } /* ====== 8. 进度条 → 青蓝紫渐变 ====== */ #sglv-stage-progress .sglv-stage-progress-fill { background: linear-gradient(90deg, #06b6d4 0%, #3b82f6 50%, #1a9fff 100%) !important; } #sglv-stage-progress { background: linear-gradient(180deg, rgba(26,159,255, 0.06), transparent) !important; border-bottom: 1px solid rgba(26,159,255, 0.12) !important; } /* ====== 9. 仪表盘 — 新增雷达图区块 ====== */ .sglv-radar-row { display: grid; grid-template-columns: 280px 1fr; gap: 10px; flex: 0 0 auto; min-height: 0; } @media (max-width: 900px) { .sglv-radar-row { grid-template-columns: 1fr; } } .sglv-radar-card { background: linear-gradient(135deg, rgba(34, 211, 238, 0.05), rgba(26,159,255, 0.04), rgba(244, 114, 182, 0.04), rgba(13, 17, 23, 0.4)); border: 1px solid rgba(26,159,255, 0.12); border-radius: 10px; padding: 12px; display: flex; flex-direction: column; align-items: center; gap: 8px; } .sglv-radar-card-title { font-size: 12px; font-weight: 700; background: linear-gradient(90deg, #22d3ee, #34d399, #66c0f4, #f472b6, #f59e0b); -webkit-background-clip: text; background-clip: text; -webkit-text-fill-color: transparent; display: flex; align-items: center; gap: 6px; align-self: flex-start; } .sglv-radar-card-title svg { width: 14px; height: 14px; color: #66c0f4; } .sglv-radar-svg { width: 220px; height: 220px; } .sglv-radar-svg .radar-grid { fill: none; stroke: rgba(255, 255, 255, 0.08); stroke-width: 1; } .sglv-radar-svg .radar-axis { stroke-width: 1; } .sglv-radar-svg .radar-area { stroke-width: 2; stroke-linejoin: round; transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1); } .sglv-radar-svg .radar-point { stroke: #0d1117; stroke-width: 2; transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1); } .sglv-radar-svg .radar-label { font-size: 10px; font-weight: 700; text-anchor: middle; } .sglv-radar-svg .radar-value { font-size: 11px; font-weight: 800; text-anchor: middle; } /* 雷达图右侧统计面板 */ .sglv-radar-stats { display: flex; flex-direction: column; gap: 6px; padding: 12px; background: rgba(13, 17, 23, 0.4); border: 1px solid rgba(255, 255, 255, 0.05); border-radius: 10px; } .sglv-radar-stat-item { display: flex; align-items: center; gap: 8px; padding: 6px 8px; border-radius: 8px; background: rgba(255, 255, 255, 0.02); border: 1px solid rgba(255, 255, 255, 0.04); transition: background 0.15s; } .sglv-radar-stat-item:hover { background: rgba(255, 255, 255, 0.05); } .sglv-radar-stat-icon { width: 28px; height: 28px; border-radius: 8px; flex-shrink: 0; display: flex; align-items: center; justify-content: center; } .sglv-radar-stat-icon svg { width: 14px; height: 14px; } .sglv-radar-stat-info { flex: 1; min-width: 0; } .sglv-radar-stat-label { font-size: 10px; color: #8b949e; font-weight: 600; } .sglv-radar-stat-bar { height: 4px; background: rgba(255, 255, 255, 0.06); border-radius: 2px; overflow: hidden; margin-top: 3px; } .sglv-radar-stat-bar-fill { height: 100%; border-radius: 2px; transition: width 0.6s cubic-bezier(0.4, 0, 0.2, 1); } .sglv-radar-stat-val { font-size: 14px; font-weight: 700; font-variant-numeric: tabular-nums; flex-shrink: 0; } /* ====== 10. 仪表盘 KPI 行增强 — hover 微光 ====== */ .sglv-playtime-kpi-card { position: relative; transition: transform 0.15s, box-shadow 0.15s, border-color 0.15s; } .sglv-playtime-kpi-card:hover { transform: translateY(-1px); box-shadow: 0 3px 10px rgba(0, 0, 0, 0.2); } .sglv-playtime-kpi-card.amber:hover { box-shadow: 0 3px 10px rgba(245, 158, 11, 0.15); } /* v1.0.3: playtime-kpi 卡片炫彩升级——叠加 accent 渐变背景 + shadow-sm 基线 + hover 抬升 + 外发光 */ .sglv-playtime-kpi-card { overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,.35), inset 0 1px 0 rgba(255,255,255,.04); } .sglv-playtime-kpi-card::before { content: ''; position: absolute; inset: -1px; pointer-events: none; background: linear-gradient(135deg, rgba(102,192,244,.3), transparent 60%); opacity: 0; transition: opacity .18s ease; } .sglv-playtime-kpi-card:hover::before { opacity: 1; } .sglv-playtime-kpi-card:hover { box-shadow: 0 6px 20px rgba(0,0,0,.45), 0 0 0 1px rgba(102,192,244,.25), 0 0 22px rgba(102,192,244,.18), inset 0 1px 0 rgba(255,255,255,.06); } .sglv-playtime-kpi-value { text-shadow: 0 0 14px rgba(102,192,244,.25); } .sglv-playtime-kpi-card > * { position: relative; z-index: 1; } /* ====== 11. 仪表盘 KPI 行 — 7 列 grid (含雷达图入口) ====== */ .sglv-stats-dashboard { display: grid !important; grid-template-columns: repeat(7, 1fr) !important; gap: 6px !important; } /* ====== 12. 甜甜圈图中心文字 → 紫色 ====== */ .sglv-pt-donut-center-val { fill: #66c0f4 !important; } .sglv-pt-donut-center-label { fill: #8b949e !important; } /* ====== 13. 热力图标题 → 紫色 ====== */ .sglv-heatmap-section .sglv-playtime-section-title { color: #66c0f4 !important; } .sglv-hm-mini-title { color: #66c0f4 !important; } /* ====== 14. 成就页 — 环形进度图背景 → 紫色 ====== */ .sglv-ach-ring-bg { stroke: rgba(26,159,255, 0.1) !important; } /* 注意: gradient 定义在 SVG defs 中,需在 JS 中修改 stop colors */ /* ====== 15. 成就页 — 侧边栏用户卡片紫色调 ====== */ .sglv-ach-user-card { background: linear-gradient(160deg, rgba(26,159,255, 0.1), rgba(37,99,235, 0.04)) !important; } .sglv-ach-user-card::after { background: radial-gradient(circle, rgba(26,159,255, 0.12), transparent 60%) !important; } .sglv-ach-user-avatar { background: linear-gradient(135deg, #1a9fff, #2563eb) !important; box-shadow: 0 8px 24px rgba(26,159,255, 0.35) !important; } .sglv-ach-user-level { border: 2px solid #66c0f4 !important; color: #a3d5f7 !important; } .sglv-ach-user-pts strong { color: #a3d5f7 !important; } /* ====== 16. 成就页 — 分类导航紫色激活 ====== */ .sglv-ach-nav-item:hover { background: rgba(26,159,255, 0.08) !important; } .sglv-ach-nav-item.active { background: linear-gradient(90deg, rgba(26,159,255, 0.2), transparent) !important; } .sglv-ach-nav-item-icon { background: rgba(26,159,255, 0.12) !important; } .sglv-ach-nav-item.active .sglv-ach-nav-item-icon { background: rgba(26,159,255, 0.2) !important; } .sglv-ach-nav-item-badge { background: rgba(26,159,255, 0.15) !important; color: #a3d5f7 !important; } .sglv-ach-nav-item.active .sglv-ach-nav-item-badge { background: #1a9fff !important; color: #0d1117 !important; } /* ====== 17. 成就页 — 侧边栏最近解锁紫色调 ====== */ .sglv-ach-sidebar-recent-icon { background: linear-gradient(135deg, #1a9fff, #2563eb) !important; } .sglv-ach-sidebar-recent-item:hover { background: rgba(26,159,255, 0.06) !important; } .sglv-ach-sidebar-recent-name { color: #e2e8f0 !important; } /* ====== 18. 成就页 — 统计概览区紫色调 ====== */ .sglv-ach-header { background: linear-gradient(135deg, rgba(30, 41, 59, 0.6), rgba(15, 23, 42, 0.6)) !important; border-bottom: 1px solid rgba(26,159,255, 0.12) !important; gap: 14px !important; padding: 16px 20px !important; } /*环形进度数值使用炫彩渐变,不强制紫色 */ /* ====== 19. 成就页 — 成就卡片紫色调 ====== */ .sglv-ach-card { background: linear-gradient(135deg, rgba(13, 17, 23, 0.6), rgba(30, 41, 59, 0.4)) !important; border: 1px solid rgba(26,159,255, 0.08) !important; } .sglv-ach-card:hover { border-color: rgba(26,159,255, 0.3) !important; box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3) !important; } .sglv-ach-card.unlocked { background: linear-gradient(135deg, rgba(26,159,255, 0.05), rgba(13, 17, 23, 0.4)) !important; border-color: rgba(26,159,255, 0.15) !important; } .sglv-ach-card.unlocked .sglv-ach-card-name { color: #a3d5f7 !important; } .sglv-ach-card.unlocked .sglv-ach-card-pts { background: linear-gradient(135deg, rgba(26,159,255, 0.15), rgba(37,99,235, 0.1)) !important; border-color: rgba(26,159,255, 0.3) !important; color: #a3d5f7 !important; } .sglv-ach-card.unlocked .sglv-ach-card-progress-fill { background: linear-gradient(90deg, #22d3ee, #34d399, #fbbf24) !important; box-shadow: 0 0 8px rgba(34, 211, 238, 0.4) !important; } .sglv-ach-card.locked .sglv-ach-card-progress-fill { background: linear-gradient(90deg, #38bdf8, #66c0f4, #f59e0b) !important; box-shadow: 0 0 8px rgba(56, 189, 248, 0.25) !important; } .sglv-ach-card-icon { background: linear-gradient(135deg, rgba(26,159,255, 0.15), rgba(37,99,235, 0.08)) !important; } /* 稀有度色保持不变(legendary 已是金色, common/rare/epic 语义色保留) */ .sglv-ach-card.unlocked .sglv-ach-card-icon { box-shadow: inset 0 1px 0 rgba(255,255,255,0.15), inset 0 -1px 0 rgba(0,0,0,0.2), 0 4px 12px rgba(26,159,255, 0.2) !important; } /* ====== 20. 成就页 — 内容标题紫色调 ====== */ .sglv-ach-content-title { color: #66c0f4 !important; } .sglv-ach-content-count { background: rgba(26,159,255, 0.1) !important; color: #a3d5f7 !important; } .sglv-ach-reset-btn { border: 1px solid rgba(239, 68, 68, 0.3) !important; background: rgba(239, 68, 68, 0.08) !important; } /* ====== 21. 个人展柜 — 英雄区紫青色调(恢复原版色彩平衡) ====== */ .sglv-sc-hero { background: linear-gradient(135deg, rgba(37,99,235, 0.10) 0%, rgba(59,130,246, 0.06) 50%, rgba(6,182,212,0.04) 100%) !important; border: 1px solid rgba(37,99,235, 0.15) !important; } .sglv-sc-hero::before { background: radial-gradient(ellipse at top right, rgba(59,130,246, 0.10), transparent 60%) !important; } .sglv-sc-avatar { border: 2px solid rgba(255, 255, 255, 0.12) !important; box-shadow: 0 1px 8px rgba(0, 0, 0, 0.35), 0 0 0 1px rgba(59,130,246, 0.25) !important; } .sglv-sc-avatar-placeholder { background: linear-gradient(135deg, #2563eb, #1a9fff) !important; } /* 用户名保持白色,不加金色 */ .sglv-sc-hero-name { color: #f1f5f9 !important; } /* 国家标签保持中性灰 */ .sglv-sc-hero-country { background: rgba(148, 163, 184, 0.08) !important; color: #94a3b8 !important; border: 1px solid rgba(148, 163, 184, 0.1) !important; } /* Hero 统计图标 → 恢复靛蓝色 */ .sglv-sc-hero-stat svg { color: #60a5fa !important; } /* Hero 统计数值 → 恢复浅色 */ .sglv-sc-hero-stat-val { color: #e2e8f0 !important; } /* ====== 22. 展柜卡片标题 → 恢复紫色 ====== */ .sglv-sc-card-header svg { color: #66c0f4 !important; } .sglv-sc-card-title { color: #e6edf3 !important; } /* ====== 23. 展柜封面网格 → 恢复紫色 hover ====== */ .sglv-sc-cover-item { border: 1px solid rgba(255, 255, 255, 0.06) !important; } .sglv-sc-cover-item:hover { border-color: rgba(59,130,246, 0.5) !important; box-shadow: 0 4px 16px rgba(59,130,246, 0.2) !important; } /* ====== 24. 展柜最近游玩 → 恢复靛蓝紫色 ====== */ .sglv-sc-playtime-item:hover { background: rgba(37,99,235, 0.06) !important; } .sglv-sc-playtime-bar { background: rgba(37,99,235, 0.1) !important; } .sglv-sc-playtime-bar-fill { background: linear-gradient(90deg, #2563eb, #3b82f6) !important; } /* ====== 25. 展柜标签徽章 → 移除金色覆盖,恢复原版多彩 ====== */ /* 原版已有: collector(紫), playtime(青), mastery(绿), diversity(橙), loyalty(粉), special(金) */ /* ====== 27. Toast 通知 → 紫色 ====== */ #sglv-toast.sglv-toast-success { border-left-color: #1a9fff !important; } #sglv-toast.sglv-toast-info { border-left-color: #66c0f4 !important; } /* ====== 28. 页码按钮 → 紫色 hover ====== */ .sglv-page-arrow:hover:not(:disabled) { background: rgba(26,159,255, 0.15) !important; border-color: rgba(26,159,255, 0.4) !important; } /* ====== 29. 仪表盘图表行卡片容器 → 紫色微边 ====== */ .sglv-playtime-col { background: rgba(13, 17, 23, 0.3); border: 1px solid rgba(26,159,255, 0.06); border-radius: 10px; padding: 10px; } .sglv-heatmap-section, .sglv-heatmap-mini-section { background: rgba(13, 17, 23, 0.3) !important; border: 1px solid rgba(26,159,255, 0.06) !important; border-radius: 10px !important; } /* ====== 30. SGIS 侧边栏标签 → 恢复紫色激活态 ====== */ .sgis-tab.active .sgis-svg { filter: drop-shadow(0 1px 4px rgba(26,159,255, 0.45)) !important; } .sgis-tab.active { border-bottom-color: #1a9fff !important; } .sgis-tabs::after { background: linear-gradient(90deg, transparent, rgba(26,159,255, 0.35), transparent) !important; } /* ====== 31. SGIS 标题图标 → 恢复紫蓝渐变 ====== */ .sgis-title-icon { background: linear-gradient(135deg, #1a9fff 0%, #2563eb 50%, #3b82f6 100%) !important; box-shadow: 0 4px 12px rgba(26,159,255, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.25), inset 0 -1px 0 rgba(0, 0, 0, 0.2) !important; } .sgis-fab { background: linear-gradient(135deg, #1a9fff, #2563eb) !important; box-shadow: 0 4px 12px rgba(26,159,255, 0.4) !important; } /* ====== 32. 加载进度条 → 恢复青蓝紫渐变 ====== */ .sgis-load-bar-fill { background: linear-gradient(90deg, #06b6d4, #3b82f6, #1a9fff) !important; box-shadow: 0 0 10px rgba(59, 130, 246, 0.5) !important; } .sgis-load-stage-bar.active { background: linear-gradient(90deg, #06b6d4, #3b82f6) !important; box-shadow: 0 0 6px rgba(59, 130, 246, 0.6) !important; } .sgis-skel-icon { background: linear-gradient(90deg, rgba(26,159,255, 0.08), rgba(26,159,255, 0.18), rgba(26,159,255, 0.08)) !important; background-size: 200% 100% !important; } /* ====== 34. 云存档 KPI 卡片 → 紫色调 ====== */ .sglv-cs-source-badge { background: rgba(26,159,255, 0.12) !important; color: #a3d5f7 !important; border: 1px solid rgba(26,159,255, 0.2) !important; } .sglv-cs-refresh-btn:hover { color: #66c0f4 !important; background: rgba(26,159,255, 0.12) !important; } .sglv-cs-top10-bar { background: linear-gradient(90deg, #2563eb, #3b82f6) !important; } /* ====== 35. 集合工具栏刷新按钮 → 紫色 hover ====== */ .sglv-col-refresh-btn:hover { color: #66c0f4 !important; background: rgba(26,159,255, 0.1) !important; } /* ====== 36. 移动端适配 ====== */ @media (max-width: 768px) { .sglv-radar-row { grid-template-columns: 1fr; } .sglv-radar-svg { width: 180px; height: 180px; } } @media (max-width: 480px) { .sglv-radar-svg { width: 160px; height: 160px; } .sglv-radar-card { padding: 8px; } } /* ====== SGIS Hero — 紫青平衡 + 紧凑布局 + 保留背景图 ====== */ /* 主卡片:恢复紫色渐变基调,紧凑 padding 保留 */ .sgis-profile-main-card { background: linear-gradient(160deg, #16202d 0%, #121a25 40%, #0d131c 100%) !important; box-shadow: 0 8px 32px rgba(0, 0, 0, 0.45), 0 0 0 1px rgba(26,159,255, 0.15) !important; padding: 14px 14px 12px !important; border-radius: 16px !important; } /* 右上角径向光晕 → 紫色 */ .sgis-profile-main-card::before { background: radial-gradient(circle, rgba(26,159,255, 0.4) 0%, transparent 60%) !important; } /* 底部高光线 → 紫色 */ .sgis-profile-main-card::after { background: linear-gradient(90deg, transparent 0%, rgba(26,159,255, 0.6) 50%, transparent 100%) !important; } /* 背景装饰图 → 恢复原始 game-library.png + 紫色滤镜 + mask */ .sgis-profile-main-card-bg { background: url('https://leanisssharedstorage.blob.core.windows.net/copilot/asdm-files/game-library.png') no-repeat center center !important; background-size: contain !important; opacity: 0.18 !important; filter: saturate(1.2) drop-shadow(0 0 20px rgba(26,159,255, 0.25)) !important; mask-image: linear-gradient(90deg, rgba(0,0,0,0) 0%, rgba(0,0,0,1) 40%, rgba(0,0,0,1) 100%) !important; -webkit-mask-image: linear-gradient(90deg, rgba(0,0,0,0) 0%, rgba(0,0,0,1) 40%, rgba(0,0,0,1) 100%) !important; } /* Hero 头部行 → 紧凑(保留) */ .sgis-profile-head { gap: 12px !important; margin-bottom: 12px !important; } /* 头像 → 64px + 青色边框(原版色调) */ .sgis-profile-avatar { width: 64px !important; height: 64px !important; border-radius: 18px !important; border: 2px solid rgba(102, 192, 244, 0.5) !important; box-shadow: 0 6px 20px rgba(0, 0, 0, 0.4), 0 0 0 3px rgba(102, 192, 244, 0.08) !important; } /* 在线状态徽章 → 恢复紫蓝渐变 */ .sgis-profile-avatar-badge { background: linear-gradient(135deg, #1a9fff 0%, #2563eb 50%, #3b82f6 100%) !important; box-shadow: 0 4px 12px rgba(26,159,255, 0.5), 0 0 0 2px #121a25 !important; } /* 等级徽章 → 保持金色(原版即为金色,作为 premium accent) */ .sgis-profile-level-badge { background: linear-gradient(135deg, #f59e0b 0%, #f97316 100%) !important; box-shadow: 0 2px 6px rgba(249, 115, 22, 0.4) !important; } /* 用户名 → 白色,不加金色 text-shadow */ .sgis-profile-name { text-shadow: none !important; } /* SteamID → 恢复灰蓝色 */ .sgis-profile-steamid { color: rgba(148, 163, 184, 0.9) !important; } /* 验证徽章 → 恢复紫蓝渐变 */ .sgis-profile-verified { background: linear-gradient(135deg, #1a9fff, #3b82f6) !important; box-shadow: 0 2px 6px rgba(26,159,255, 0.4) !important; } /* 好友数进度环 → 恢复绿色 */ .sgis-friend-gauge-text b { color: #10b981 !important; } .sgis-friend-gauge:hover { background: rgba(255, 255, 255, 0.05) !important; } /* ====== 38. SGIS KPI 统计卡片 — 恢复多彩语义色 ====== */ /* 默认状态:恢复中性背景,移除大面积金色 */ .sgis-profile-stat { background: linear-gradient(160deg, rgba(255, 255, 255, 0.04) 0%, rgba(255, 255, 255, 0.01) 100%) !important; border: 1px solid rgba(255, 255, 255, 0.06) !important; border-radius: 12px !important; transition: all 0.2s ease !important; } /* 顶部高光线 → 恢复 currentColor 语义色 */ .sgis-profile-stat::after { opacity: 0.35 !important; } /* hover → 紫色光晕 + 上浮 */ .sgis-profile-stat:hover { border-color: rgba(26,159,255, 0.3) !important; background: linear-gradient(160deg, rgba(26,159,255, 0.08) 0%, rgba(59, 130, 246, 0.03) 100%) !important; box-shadow: 0 6px 16px rgba(0, 0, 0, 0.3) !important; transform: translateY(-2px) !important; } /* 默认图标背景 → 恢复紫蓝渐变 */ .sgis-profile-stat-icon { background: linear-gradient(135deg, rgba(26,159,255, 0.2), rgba(59, 130, 246, 0.08)) !important; box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.04) !important; } .sgis-profile-stat-icon svg { color: #a3d5f7 !important; } /* t-blue / t-purple / t-cyan / t-green / t-rose → 全部恢复原版语义色 */ .sgis-profile-stat-icon.t-blue { background: linear-gradient(135deg, rgba(59, 130, 246, 0.22), rgba(37, 99, 235, 0.08)) !important; box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.04) !important; } .sgis-profile-stat-icon.t-blue svg { color: #93c5fd !important; } .sgis-profile-stat-icon.t-purple { background: linear-gradient(135deg, rgba(59,130,246, 0.22), rgba(26,159,255, 0.08)) !important; box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.04) !important; } .sgis-profile-stat-icon.t-purple svg { color: #a3d5f7 !important; } .sgis-profile-stat-val.t-purple { color: #a3d5f7 !important; } /* KPI 值文字 → 移除金色光泽 */ .sgis-profile-stat-val { text-shadow: none !important; } /* 5列模式 KPI 紧凑(保留布局优化) */ .sgis-profile-stats.cols-5 { gap: 6px !important; } .sgis-profile-stats.cols-5 .sgis-profile-stat { padding: 10px 4px 8px !important; border-radius: 10px !important; } /* ====== 39. SGIS 区块标题 — 恢复紫色 ====== */ .sgis-section-title { color: #66c0f4 !important; border-bottom: 1px solid rgba(26,159,255, 0.08) !important; } .sgis-section-title svg { color: #66c0f4 !important; } /* ====== 40. SGIS 战绩/游戏人生 双大卡 — 恢复紫蓝色调 ====== */ .sgis-feature-card { background: linear-gradient(160deg, rgba(26,159,255, 0.12) 0%, rgba(59, 130, 246, 0.04) 50%, rgba(15, 17, 35, 0.6) 100%) !important; border: 1px solid rgba(26,159,255, 0.2) !important; transition: all 0.25s ease !important; } .sgis-feature-card::before { background: radial-gradient(circle, rgba(26,159,255, 0.2) 0%, transparent 60%) !important; } .sgis-feature-card::after { background: linear-gradient(90deg, transparent 0%, rgba(26,159,255, 0.5) 50%, transparent 100%) !important; } .sgis-feature-card:hover { border-color: rgba(26,159,255, 0.4) !important; box-shadow: 0 8px 20px rgba(26,159,255, 0.2) !important; transform: translateY(-2px) !important; } /* alt 变体 → 恢复靛蓝色 */ .sgis-feature-card.alt { background: linear-gradient(160deg, rgba(37,99,235, 0.12) 0%, rgba(59, 130, 246, 0.04) 50%, rgba(15, 17, 35, 0.6) 100%) !important; border-color: rgba(37,99,235, 0.2) !important; } .sgis-feature-card.alt::before { background: radial-gradient(circle, rgba(37,99,235, 0.2) 0%, transparent 60%) !important; } .sgis-feature-card.alt::after { background: linear-gradient(90deg, transparent 0%, rgba(37,99,235, 0.5) 50%, transparent 100%) !important; } /* 特征卡片图标 → 恢复紫蓝色 */ .sgis-feature-icon { background: linear-gradient(135deg, rgba(26,159,255, 0.22), rgba(59, 130, 246, 0.12)) !important; box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.04), 0 2px 6px rgba(26,159,255, 0.15) !important; } .sgis-feature-icon svg { color: #a3d5f7 !important; } .sgis-feature-card.alt .sgis-feature-icon { background: linear-gradient(135deg, rgba(37,99,235, 0.22), rgba(59, 130, 246, 0.12)) !important; box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.04), 0 2px 6px rgba(37,99,235, 0.15) !important; } .sgis-feature-card.alt .sgis-feature-icon svg { color: #93c5fd !important; } /* hover 箭头 → 紫色 */ .sgis-feature-card:hover .sgis-feature-arrow { color: #a3d5f7 !important; } /* 特征卡片数值 → 恢复紫色 */ .sgis-feature-stat-val.t-purple { color: #a3d5f7 !important; } /* ====== 40b. SGIS 双大卡紧凑优化 — 3列统计行 + 压缩高度 ====== */ .sis-feature-grid, .sgis-feature-grid { gap: 8px !important; margin-bottom: 8px !important; } .sgis-feature-card { padding: 10px 10px 8px !important; } .sgis-feature-head { gap: 8px !important; margin-bottom: 8px !important; } .sgis-feature-icon { width: 30px !important; height: 30px !important; border-radius: 8px !important; } .sgis-feature-icon svg { width: 15px !important; height: 15px !important; } .sgis-feature-title { font-size: 13px !important; } .sgis-feature-sub { font-size: 9px !important; margin-top: 1px !important; } .sgis-feature-arrow { width: 14px !important; height: 14px !important; } /* 3列统计行 — 战绩总览 */ .sgis-feature-stats-3 { grid-template-columns: repeat(3, 1fr) !important; gap: 4px !important; } .sgis-feature-stats-3 .sgis-feature-stat { padding: 5px 4px !important; } .sgis-feature-stats-3 .sgis-feature-stat-lbl { font-size: 8px !important; margin-bottom: 1px !important; } .sgis-feature-stats-3 .sgis-feature-stat-val { font-size: 13px !important; } /* 游戏人生卡片紧凑 */ .sgis-feature-card.alt .sgis-feature-stats { gap: 4px !important; } .sgis-feature-card.alt .sgis-feature-stat { padding: 5px 4px !important; } .sgis-feature-card.alt .sgis-feature-stat-lbl { font-size: 8px !important; margin-bottom: 1px !important; } .sgis-feature-card.alt .sgis-feature-stat-val { font-size: 13px !important; } .sgis-feature-extra { margin-top: 6px !important; padding: 5px 8px !important; font-size: 9px !important; } .sgis-feature-extra svg { width: 11px !important; height: 11px !important; } /* ====== 41. SGIS XP 卡片 — 保持金色进度条(原版设计),恢复中性背景 ====== */ .sgis-xp-card { border: 1px solid rgba(255, 255, 255, 0.06) !important; background: linear-gradient(160deg, rgba(255, 255, 255, 0.035) 0%, rgba(15, 17, 35, 0.5) 100%) !important; } /* XP 进度条和图标保持原版金色系,不做覆盖 */ /* XP 等级 next → 恢复紫色 */ .sgis-xp-levels .next { color: #a3d5f7 !important; } /* XP 累计数值 → 恢复紫色 */ .sgis-xp-total b { color: #a3d5f7 !important; } /* ====== 42. SGIS 社交标题 ====== */ .sgis-section-title.sgis-social-title { border-bottom-color: rgba(26,159,255, 0.08) !important; } /* ====== 43. SGIS copy 按钮 hover ====== */ .sgis-copy-btn:hover { background: rgba(255, 255, 255, 0.1) !important; color: #fff !important; } /* ########## Part B: 主脚本 CSS 常量原生紫色覆盖(120 条) ########## */ .sglv-ach-user-card { background: linear-gradient(160deg, rgba(37,99,235, 0.08), rgba(59,130,246, 0.04)) !important; } .sglv-ach-user-card::after { background: radial-gradient(circle, rgba(59,130,246, 0.12), transparent 60%) !important; } .sglv-ach-nav-item:hover { background: rgba(37,99,235, 0.08) !important; } .sglv-ach-nav-item.active { background: linear-gradient(90deg, rgba(37,99,235, 0.2), transparent) !important; } .sglv-ach-nav-item-icon { background: rgba(37,99,235, 0.12) !important; } .sglv-ach-nav-item-badge { background: rgba(37,99,235, 0.15) !important; color: #dbeafe !important; } .sglv-ach-nav-item.active .sglv-ach-nav-item-badge { background: #2563eb !important; } .sglv-ach-sidebar-recent-item:hover { background: rgba(37,99,235, 0.06) !important; } .sglv-ach-sidebar-recent-icon { background: linear-gradient(135deg, #2563eb, #66c0f4) !important; } .sglv-ach-header { border-bottom: 1px solid rgba(37,99,235, 0.12) !important; } .sglv-ach-ring-bg { stroke: rgba(37,99,235, 0.12) !important; } .sglv-ach-ring-val { background: linear-gradient(135deg, #22d3ee, #66c0f4, #fbbf24) !important; -webkit-background-clip: text !important; background-clip: text !important; } .sglv-ach-steam-banner { background: linear-gradient(135deg, rgba(34,211,238,0.08), rgba(251,191,36,0.06), rgba(26,159,255, 0.04)) !important; } .sglv-ach-card { border: 1px solid rgba(37,99,235, 0.1) !important; } .sglv-ach-card::before { background: var(--ach-rarity, #2563eb) !important; } .sglv-ach-card:hover { border-color: rgba(37,99,235, 0.3) !important; } .sglv-ach-card.unlocked.epic { --ach-rarity: #66c0f4 !important; } .sglv-ach-card.locked { --ach-rarity: #2563eb !important; } .sglv-ach-card.locked.epic { --ach-rarity: #66c0f4 !important; } .sglv-ach-card-icon { background: linear-gradient(135deg, rgba(37,99,235, 0.15), rgba(26,159,255, 0.08)) !important; } .sglv-ach-card.unlocked .sglv-ach-card-icon { box-shadow: inset 0 1px 0 rgba(255,255,255,0.15), inset 0 -1px 0 rgba(0,0,0,0.2), 0 4px 12px rgba(37,99,235, 0.25) !important; } .sglv-ach-card-rarity.epic { background: #66c0f4 !important; } .sglv-ach-card.locked .sglv-ach-card-progress-fill { background: linear-gradient(90deg, #38bdf8, #66c0f4, #f59e0b) !important; } .sglv-sc-hero { background: linear-gradient(135deg, rgba(37,99,235, 0.10) 0%, rgba(59,130,246, 0.06) 50%, rgba(6,182,212,0.04) 100%) !important; border: 1px solid rgba(37,99,235, 0.15) !important; } .sglv-sc-hero::before { background: radial-gradient(ellipse at top right, rgba(59,130,246, 0.10), transparent 60%) !important; } .sglv-sc-avatar { box-shadow: 0 1px 8px rgba(0,0,0,0.35), 0 0 0 1px rgba(59,130,246, 0.25) !important; } .sglv-sc-avatar-placeholder { background: linear-gradient(135deg, #2563eb, #1a9fff) !important; } .sglv-sc-hero-stat svg { color: #60a5fa !important; } .sglv-sc-card-header svg { color: #66c0f4 !important; } .sglv-sc-cover-item:hover { border-color: rgba(59,130,246, 0.5) !important; box-shadow: 0 4px 16px rgba(59,130,246, 0.2) !important; } .sglv-sc-cover-hours { color: #93c5fd !important; } .sglv-sc-sk-block { background: linear-gradient(90deg, rgba(37,99,235, 0.06) 25%, rgba(37,99,235, 0.15) 37%, rgba(37,99,235, 0.06) 63%) !important; } .sglv-sc-edit-btn { background: rgba(37,99,235, 0.15) !important; border: 1px solid rgba(37,99,235, 0.3) !important; color: #93c5fd !important; } .sglv-sc-edit-btn:hover { background: rgba(37,99,235, 0.25) !important; border-color: rgba(37,99,235, 0.5) !important; } .sglv-sc-playtime-item:hover { background: rgba(37,99,235, 0.08) !important; } .sglv-sc-playtime-bar { background: rgba(37,99,235, 0.1) !important; } .sglv-sc-playtime-bar-fill { background: linear-gradient(90deg, #2563eb, #3b82f6) !important; } .sglv-sc-ach-item:hover { background: rgba(37,99,235, 0.08) !important; } .sglv-sc-ach-item.rarity-epic { border-left-color: #3b82f6 !important; } .sglv-sc-ach-icon { background: rgba(37,99,235, 0.1) !important; } .sglv-sc-tag-collector { background: rgba(26,159,255, 0.12) !important; border-color: rgba(26,159,255, 0.3) !important; color: #a3d5f7 !important; } .sglv-sc-picker-search:focus { border-color: rgba(37,99,235, 0.5) !important; } .sglv-sc-picker-save { background: linear-gradient(135deg, #2563eb, #1a9fff) !important; } .sglv-sc-hero-badge { border: 1.5px solid rgba(26,159,255, 0.3) !important; } .sglv-sc-hero-badge:hover { border-color: rgba(26,159,255, 0.6) !important; box-shadow: 0 4px 12px rgba(26,159,255, 0.2) !important; } .sglv-sc-hero-badge-fallback { color: #60a5fa !important; } .sglv-sc-hero-badge-lvl { background: linear-gradient(135deg, #1a9fff, #2563eb) !important; } .sglv-sc-hero-badge-empty:hover { border-color: rgba(26,159,255, 0.4) !important; color: rgba(26,159,255, 0.6) !important; } .sglv-sc-hero-badge-edit { background: rgba(26,159,255, 0.15) !important; border: 1px solid rgba(26,159,255, 0.25) !important; color: #66c0f4 !important; } .sglv-sc-hero-badge-edit:hover { background: rgba(26,159,255, 0.25) !important; border-color: rgba(26,159,255, 0.5) !important; } .sglv-sc-badge-tab:hover { color: #a3d5f7 !important; } .sglv-sc-badge-tab.active { background: rgba(26,159,255, 0.15) !important; border-color: rgba(26,159,255, 0.4) !important; color: #a3d5f7 !important; } .sglv-sc-badge-pick-item:hover { border-color: rgba(26,159,255, 0.4) !important; } .sglv-sc-badge-lvl { background: rgba(26,159,255, 0.15) !important; color: #a3d5f7 !important; } .sglv-cs-action-btn { border: 1px solid rgba(26,159,255, 0.4) !important; background: rgba(26,159,255, 0.12) !important; color: #a3d5f7 !important; } .sglv-cs-action-btn:hover { background: rgba(26,159,255, 0.25) !important; border-color: rgba(26,159,255, 0.6) !important; } .sglv-cs-top10-bar { background: linear-gradient(90deg, #1a9fff, #2563eb) !important; } .sglv-cs-dist-bar { background: linear-gradient(180deg, #1a9fff, #2563eb) !important; } .sglv-cs-source-badge { background: rgba(26,159,255, 0.12) !important; color: #a3d5f7 !important; border: 1px solid rgba(26,159,255, 0.2) !important; } .sglv-cs-refresh-btn:hover { color: #a3d5f7 !important; background: rgba(26,159,255, 0.12) !important; } .sglv-cs-search:focus { border-color: rgba(26,159,255, 0.5) !important; } .sglv-cs-game-cover-fallback { background: linear-gradient(135deg, rgba(59,130,246,0.12), rgba(26,159,255, 0.08)) !important; } #sglv-stage-progress { background: linear-gradient(180deg, rgba(102,192,244, 0.08), transparent) !important; border-bottom: 1px solid rgba(102,192,244, 0.15) !important; } #sglv-stage-progress .sglv-stage-progress-fill { background: linear-gradient(90deg, #66c0f4 0%, #38bdf8 100%) !important; } .sglv-header-brand { background: linear-gradient(135deg, rgba(102, 192, 244, 0.18), rgba(26,159,255, 0.18)) !important; } .sglv-panel .sglv-gs-item-shared { background: rgba(26,159,255, 0.18) !important; color: #a3d5f7 !important; border: 1px solid rgba(26,159,255, 0.35) !important; } .sglv-detail-btn-ai { background: linear-gradient(135deg, #2563eb, #1a9fff) !important; } .sglv-body-loading .sglv-bl-btn.primary { background: linear-gradient(135deg, rgba(26,159,255, 0.25), rgba(102, 192, 244, 0.2)) !important; border-color: rgba(26,159,255, 0.4) !important; color: #a3d5f7 !important; } .sglv-body-loading .sglv-bl-btn.primary:hover { background: linear-gradient(135deg, rgba(26,159,255, 0.35), rgba(102, 192, 244, 0.3)) !important; } .sglv-trend-kpi-card.purple { border-color: rgba(102,192,244, 0.3) !important; } .sglv-trend-kpi-card.purple::before { background: #66c0f4 !important; } .sglv-trend-kpi-card.purple .sglv-trend-kpi-value { color: #66c0f4 !important; } .sglv-trend-kpi-card.purple .sglv-trend-kpi-icon { background: rgba(102,192,244, 0.15) !important; color: #66c0f4 !important; } .sgis-tabs::after { background: linear-gradient(90deg, transparent, rgba(26,159,255, 0.35), transparent) !important; } .sgis-tab.active .sgis-svg { filter: drop-shadow(0 1px 4px rgba(26,159,255, 0.45)) !important; } .sgis-title-icon { background: linear-gradient(135deg, #1a9fff 0%, #2563eb 45%, #3b82f6 100%) !important; box-shadow: 0 4px 12px rgba(26,159,255, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.25), inset 0 -1px 0 rgba(0, 0, 0, 0.2) !important; } .sgis-body::-webkit-scrollbar-thumb { background: linear-gradient(180deg, rgba(26,159,255, 0.45), rgba(59, 130, 246, 0.45)) !important; } .sgis-state-icon { background: linear-gradient(135deg, rgba(26,159,255, 0.15), rgba(59, 130, 246, 0.08)) !important; border: 1px solid rgba(26,159,255, 0.2) !important; color: #66c0f4 !important; } .sgis-badge-hero { background: linear-gradient(135deg, rgba(26,159,255, 0.18) 0%, rgba(59, 130, 246, 0.1) 50%, var(--sgis-bg-2) 100%) !important; border: 1px solid rgba(26,159,255, 0.3) !important; box-shadow: 0 4px 16px rgba(26,159,255, 0.08), inset 0 1px 0 rgba(255, 255, 255, 0.05) !important; } .sgis-badge-hero::before { background: radial-gradient(circle, rgba(26,159,255, 0.25) 0%, transparent 65%) !important; } .sgis-badge-hero-progress-label span:last-child { color: #a3d5f7 !important; } .sgis-badge-hero-level-bar { background: linear-gradient(180deg, #1a9fff 0%, #2563eb 100%) !important; box-shadow: 0 0 6px rgba(26,159,255, 0.3) !important; } .sgis-badge-group-head:hover { background: linear-gradient(135deg, rgba(26,159,255, 0.05), rgba(59, 130, 246, 0.02)) !important; } .sgis-badge-group-stat-val { color: #a3d5f7 !important; } .sgis-badge-footer-formula b { color: #a3d5f7 !important; } .sglv-skel-bar { background: linear-gradient(90deg, rgba(255, 255, 255, 0.04) 0%, rgba(26,159,255, 0.12) 50%, rgba(255, 255, 255, 0.04) 100%) !important; } .sglv-wl-kpi-cell { background: linear-gradient(135deg, rgba(26,159,255, 0.06), rgba(59, 130, 246, 0.03)) !important; border: 1px solid rgba(26,159,255, 0.15) !important; } .sglv-skel-cover { background: linear-gradient(90deg, rgba(26,159,255, 0.08) 0%, rgba(26,159,255, 0.18) 50%, rgba(26,159,255, 0.08) 100%) !important; } .sglv-wl-loading .sglv-wl-spin { color:#66c0f4 !important; } .sglv-wl-loading-bar-fill { background:linear-gradient(90deg,#66c0f4,#66c0f4) !important; } .sglv-toast { border: 1px solid rgba(102,192,244, 0.5) !important; } .sglv-set-chip.purple { background: rgba(102,192,244, 0.15) !important; color: #66c0f4 !important; } .sglv-set-mode-item:hover { border-color: rgba(102,192,244, 0.4) !important; background: rgba(102,192,244, 0.06) !important; } .sglv-set-mode-item input { accent-color: #66c0f4 !important; } .sglv-set-mode-item input:checked ~ .sglv-set-mode-info .sglv-set-mode-name { color: #66c0f4 !important; } .sglv-set-theme-opt:hover { border-color: rgba(102,192,244, 0.4) !important; } .sglv-set-theme-opt.selected { border-color: rgba(102,192,244, 0.55) !important; background: rgba(102,192,244, 0.07) !important; box-shadow: 0 0 0 1px rgba(102,192,244, 0.25) !important; } .sglv-set-save-btn { background: linear-gradient(90deg, #1a9fff, #3b82f6) !important; } .sglv-cover-badge { color: #a3d5f7 !important; } .sglv-cover-badge.shared { background: rgba(26,159,255, 0.55) !important; color: #d3ecfd !important; } .sgis-price-tbl-row.user-region { box-shadow: inset 0 0 0 1px rgba(102,192,244, 0.3) !important; } .sgis-review-pct-big.mix { color:#66c0f4 !important; } .sgis-review-bar-positive.mix { background:linear-gradient(90deg,#66c0f4 0%,#54a0ff 100%) !important; box-shadow:0 0 6px rgba(102,192,244, 0.4) !important; } .sgis-review-item:hover { border-color:rgba(26,159,255, 0.15) !important; } .sgis-review-avatar-fallback { background:linear-gradient(135deg,rgba(26,159,255, 0.4),rgba(59,130,246,0.3)) !important; } .sgis-review-count-summary { background:rgba(26,159,255, 0.06) !important; border:1px solid rgba(26,159,255, 0.12) !important; } .sgis-review-count-summary b { color:#a3d5f7 !important; } .sgis-review-count-icon { color:#66c0f4 !important; } .sgis-review-count-filtered { background:rgba(102,192,244, 0.2) !important; color:#66c0f4 !important; border:1px solid rgba(102,192,244, 0.3) !important; } .sgis-review-action-btn:hover { background:rgba(26,159,255, 0.15) !important; border-color:rgba(26,159,255, 0.3) !important; color:#a3d5f7 !important; } .sgis-review-empty-icon { background:linear-gradient(135deg,rgba(26,159,255, 0.12),rgba(59,130,246,0.06)) !important; border:1px solid rgba(26,159,255, 0.18) !important; } .sgis-gift-card { background:linear-gradient(135deg, rgba(102,192,244, 0.12), rgba(102,192,244,0.08)) !important; border:1px solid rgba(102,192,244, 0.2) !important; } .sgis-crack-badge.aaa { background:rgba(59,130,246, 0.15) !important; color:#60a5fa !important; border-color:rgba(59,130,246, 0.25) !important; } .sgis-review-regex-toggle:hover { background:rgba(102,192,244, 0.1) !important; border-color:rgba(102,192,244, 0.3) !important; } .sgis-review-regex-toggle.active { background:rgba(102,192,244, 0.2) !important; color:#66c0f4 !important; border-color:rgba(102,192,244, 0.4) !important; box-shadow:0 0 0 1px rgba(102,192,244, 0.2) !important; } .sgis-load-bar-fill { background:linear-gradient(90deg,#06b6d4,#3b82f6,#1a9fff) !important; } .sgis-skel-icon { background:linear-gradient(90deg,rgba(26,159,255, 0.08),rgba(26,159,255, 0.18),rgba(26,159,255, 0.08)) !important; } /* ########## Part C: 共享样式库原生紫色覆盖(163 条) ########## */ .sglv-stat-card.purple, .sglv-stat-dash-card.purple, .sglv-playtime-kpi-card.purple { border-color: rgba(26,159,255, 0.35) !important; } .sglv-stat-card.purple::before, .sglv-stat-dash-card.purple::before, .sglv-playtime-kpi-card.purple::before { background: #66c0f4 !important; } .sglv-card-badge.shared { background: rgba(26,159,255, 0.2) !important; color: #66c0f4 !important; } .sglv-ps-tier-badge.tier-premium { background:rgba(102,192,244, 0.95) !important; } .sglv-ps-card.sglv-ps-exclusive:hover { border-color:rgba(102,192,244, 0.4) !important; } .sglv-wl-kpi-card.kpi-free::before { background: #2563eb !important; } .sglv-wl-kpi-card.kpi-year::before { background: #3b82f6 !important; } .sglv-wl-kpi-card.kpi-free .sglv-wl-kpi-icon { background: rgba(37,99,235, 0.15) !important; color: #2563eb !important; } .sglv-wl-kpi-card.kpi-year .sglv-wl-kpi-icon { background: rgba(59,130,246, 0.15) !important; color: #3b82f6 !important; } .sglv-wl-year-bar { background: linear-gradient(180deg, rgba(37,99,235, 0.85), rgba(37,99,235, 0.35)) !important; } .sglv-list-badge.shared { background: rgba(26,159,255, 0.2) !important; color: #66c0f4 !important; } .sglv-stat-card.purple .sglv-stat-icon { background: rgba(26,159,255, 0.15) !important; color: #66c0f4 !important; } .sglv-stat-dash-card.purple .sglv-stat-dash-value { color: #66c0f4 !important; } .sglv-stat-dash-card.purple .sglv-stat-dash-icon { background: rgba(26,159,255, 0.15) !important; color: #66c0f4 !important; } .sglv-trend-kpi-card.total { border-color: rgba(96,165,250, 0.35) !important; } .sglv-trend-kpi-card.total .sglv-trend-kpi-value { color: #60a5fa !important; } .sglv-trend-kpi-card.total::before { background: #60a5fa !important; } .sglv-trend-kpi-card.total .sglv-trend-kpi-icon { background: rgba(96,165,250, 0.15) !important; color: #60a5fa !important; } .sglv-playtime-kpi-card.purple .sglv-playtime-kpi-value { color: #66c0f4 !important; } .sglv-playtime-kpi-card.purple .sglv-playtime-kpi-icon { background: rgba(26,159,255, 0.15) !important; color: #66c0f4 !important; } :root { --sgis-border: rgba(26,159,255, 0.18) !important; --sgis-purple: #1a9fff !important; --sgis-purple-2: #66c0f4 !important; --sgis-purple-text: #a3d5f7 !important; --sgis-shadow: 0 16px 60px rgba(0, 0, 0, 0.55), 0 0 0 1px rgba(26,159,255, 0.08) !important; --sgis-glow-purple: 0 0 24px rgba(26,159,255, 0.18) !important; } #sgis-fab { background: linear-gradient(135deg, #1a9fff 0%, #3b82f6 50%, #06b6d4 100%) !important; box-shadow: -4px 0 18px rgba(26,159,255, 0.4), inset 0 0 0 1px rgba(255, 255, 255, 0.15) !important; } #sgis-fab:hover { box-shadow: -6px 0 24px rgba(26,159,255, 0.55), inset 0 0 0 1px rgba(255, 255, 255, 0.2) !important; } #sgis-panel { border-left: 1px solid rgba(26,159,255, 0.22) !important; } #sgis-panel::before { background: linear-gradient(90deg, transparent 0%, rgba(26,159,255, 0.5) 50%, transparent 100%) !important; } .sgis-header { background: linear-gradient(135deg, rgba(26,159,255, 0.22) 0%, rgba(59, 130, 246, 0.12) 50%, var(--sgis-bg-2) 100%) !important; border-bottom: 1px solid rgba(26,159,255, 0.2) !important; } .sgis-header::before { background: radial-gradient(circle, rgba(26,159,255, 0.22) 0%, transparent 65%) !important; } .sgis-header-decoration { background: linear-gradient(90deg, transparent 0%, rgba(26,159,255, 0.4) 50%, transparent 100%) !important; } .sgis-title-text { background: linear-gradient(135deg, #fff 0%, #a3d5f7 100%) !important; -webkit-background-clip: text !important; background-clip: text !important; } .sgis-title-icon { background: linear-gradient(135deg, #1a9fff 0%, #2563eb 50%, #3b82f6 100%) !important; box-shadow: 0 4px 12px rgba(26,159,255, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.2) !important; } .sgis-icon-btn:hover { background: rgba(26,159,255, 0.18) !important; border-color: rgba(26,159,255, 0.3) !important; box-shadow: 0 2px 8px rgba(26,159,255, 0.25) !important; } .sgis-tabs { border-bottom: 1px solid rgba(26,159,255, 0.12) !important; } .sgis-tab::before { background: linear-gradient(135deg, rgba(26,159,255, 0.3), rgba(59, 130, 246, 0.2)) !important; } .sgis-tab:hover { color: #a3d5f7 !important; } .sgis-tab.active { box-shadow: 0 2px 8px rgba(26,159,255, 0.25), inset 0 0 0 1px rgba(26,159,255, 0.5) !important; } .sgis-body { scrollbar-color: rgba(26,159,255, 0.4) transparent !important; } .sgis-body::-webkit-scrollbar-thumb { background: linear-gradient(180deg, rgba(26,159,255, 0.4), rgba(59, 130, 246, 0.4)) !important; } .sgis-body::-webkit-scrollbar-thumb:hover { background: linear-gradient(180deg, rgba(26,159,255, 0.6), rgba(59, 130, 246, 0.6)) !important; } .sgis-retry-btn { border: 1px solid rgba(26,159,255, 0.4) !important; background: linear-gradient(135deg, rgba(26,159,255, 0.15), rgba(59, 130, 246, 0.1)) !important; color: #a3d5f7 !important; } .sgis-retry-btn:hover { background: linear-gradient(135deg, rgba(26,159,255, 0.3), rgba(59, 130, 246, 0.2)) !important; box-shadow: 0 4px 12px rgba(26,159,255, 0.25) !important; } .sgis-spinner { border: 3px solid rgba(26,159,255, 0.15) !important; border-top-color: #1a9fff !important; box-shadow: 0 0 16px rgba(26,159,255, 0.3) !important; } .sgis-hero { background: linear-gradient(135deg, rgba(102, 192, 244, 0.15) 0%, rgba(26,159,255, 0.1) 50%, var(--sgis-bg-2) 100%) !important; } .sgis-hero::after { background: radial-gradient(circle, rgba(26,159,255, 0.15) 0%, transparent 60%) !important; } .sgis-section:hover { border-color: rgba(26,159,255, 0.12) !important; } .sgis-section-title { color: #66c0f4 !important; border-bottom: 1px solid rgba(26,159,255, 0.08) !important; } .sgis-section-title svg { color: #66c0f4 !important; } .sgis-row { border-bottom: 1px dashed rgba(26,159,255, 0.08) !important; } .sgis-tag { background: linear-gradient(135deg, rgba(26,159,255, 0.12), rgba(59, 130, 246, 0.06)) !important; color: #a3d5f7 !important; border: 1px solid rgba(26,159,255, 0.18) !important; } .sgis-tag:hover { background: linear-gradient(135deg, rgba(26,159,255, 0.22), rgba(59, 130, 246, 0.12)) !important; border-color: rgba(26,159,255, 0.35) !important; } .sgis-link { background: linear-gradient(135deg, rgba(26,159,255, 0.1), rgba(59, 130, 246, 0.06)) !important; color: #a3d5f7 !important; border: 1px solid rgba(26,159,255, 0.2) !important; } .sgis-link:hover { background: linear-gradient(135deg, rgba(26,159,255, 0.2), rgba(59, 130, 246, 0.12)) !important; border-color: rgba(26,159,255, 0.4) !important; } .sgis-taste-tag.theme { background: rgba(26,159,255, 0.12) !important; color: #a3d5f7 !important; border-color: rgba(26,159,255, 0.22) !important; } .sgis-owned-hero.shared { background: linear-gradient(135deg, rgba(26,159,255, 0.18) 0%, rgba(37,99,235, 0.08) 50%, var(--sgis-bg-2) 100%) !important; border-color: rgba(26,159,255, 0.35) !important; } .sgis-owned-hero.shared::after { background: radial-gradient(circle, rgba(26,159,255, 0.2) 0%, transparent 65%) !important; } .sgis-owned-hero.shared .sgis-owned-icon { background: linear-gradient(135deg, #1a9fff, #2563eb) !important; box-shadow: 0 2px 6px rgba(26,159,255, 0.4) !important; } .sgis-btn { background: linear-gradient(135deg, rgba(26,159,255, 0.18), rgba(59, 130, 246, 0.1)) !important; border: 1px solid rgba(26,159,255, 0.3) !important; color: #a3d5f7 !important; } .sgis-btn:hover { background: linear-gradient(135deg, rgba(26,159,255, 0.3), rgba(59, 130, 246, 0.18)) !important; border-color: rgba(26,159,255, 0.45) !important; box-shadow: 0 4px 10px rgba(26,159,255, 0.2) !important; } .sgis-stat-box:hover { border-color: rgba(26,159,255, 0.3) !important; background: linear-gradient(135deg, rgba(26,159,255, 0.08), rgba(59, 130, 246, 0.04)) !important; } .sgis-owner-item.sharer { border-color: rgba(26,159,255, 0.35) !important; background: rgba(26,159,255, 0.08) !important; } .sgis-owner-tag.sharer { background: rgba(26,159,255, 0.25) !important; } .sgis-card-toggle button.active { background: linear-gradient(135deg, rgba(26,159,255, 0.3), rgba(59, 130, 246, 0.2)) !important; box-shadow: inset 0 0 0 1px rgba(26,159,255, 0.4) !important; } .sgis-card-item:hover { background: rgba(26,159,255, 0.12) !important; border-color: rgba(26,159,255, 0.3) !important; box-shadow: 0 4px 12px rgba(26,159,255, 0.15) !important; } .sgis-card-icon-fallback { background: linear-gradient(135deg, rgba(26,159,255, 0.15), rgba(59, 130, 246, 0.08)) !important; } .sgis-card-badge { background: rgba(26,159,255, 0.2) !important; } .sgis-family-share-row.sharing { background: rgba(26,159,255, 0.12) !important; border: 1px solid rgba(26,159,255, 0.3) !important; color: #66c0f4 !important; } .sgis-family-share-row.sharing .sgis-family-share-icon { background: rgba(26,159,255, 0.3) !important; } .sgis-predict-btn { border: 1px solid rgba(26,159,255, 0.4) !important; background: linear-gradient(135deg, rgba(26,159,255, 0.18), rgba(59, 130, 246, 0.1)) !important; color: #a3d5f7 !important; } .sgis-predict-btn:hover { background: linear-gradient(135deg, rgba(26,159,255, 0.3), rgba(59, 130, 246, 0.18)) !important; box-shadow: 0 4px 14px rgba(26,159,255, 0.3) !important; } .sgis-profile-main-card { background: linear-gradient(160deg, #16202d 0%, #121a25 40%, #0d131c 100%) !important; box-shadow: 0 10px 40px rgba(0, 0, 0, 0.45), 0 0 0 1px rgba(26,159,255, 0.15) !important; } .sgis-profile-main-card::before { background: radial-gradient(circle, rgba(26,159,255, 0.4) 0%, transparent 60%) !important; } .sgis-profile-main-card::after { background: linear-gradient(90deg, transparent 0%, rgba(26,159,255, 0.6) 50%, transparent 100%) !important; } .sgis-profile-main-card-bg { filter: saturate(1.2) drop-shadow(0 0 20px rgba(26,159,255, 0.25)) !important; } .sgis-profile-avatar-badge { background: linear-gradient(135deg, #1a9fff 0%, #2563eb 50%, #3b82f6 100%) !important; box-shadow: 0 4px 12px rgba(26,159,255, 0.5), 0 0 0 3px #121a25 !important; } .sgis-profile-verified { background: linear-gradient(135deg, #1a9fff, #3b82f6) !important; box-shadow: 0 2px 6px rgba(26,159,255, 0.4) !important; } .sgis-profile-stat:hover { border-color: rgba(26,159,255, 0.3) !important; background: linear-gradient(160deg, rgba(26,159,255, 0.08) 0%, rgba(59, 130, 246, 0.03) 100%) !important; } .sgis-profile-stat-icon { background: linear-gradient(135deg, rgba(26,159,255, 0.2), rgba(59, 130, 246, 0.08)) !important; } .sgis-profile-stat-icon svg { color: #a3d5f7 !important; } .sgis-profile-stat-icon.t-purple { background: linear-gradient(135deg, rgba(59,130,246, 0.22), rgba(26,159,255, 0.08)) !important; } .sgis-profile-stat-icon.t-purple svg { color: #a3d5f7 !important; } .sgis-profile-stat-val.t-purple { color: #a3d5f7 !important; } .sgis-xp-levels .next { color: #a3d5f7 !important; } .sgis-xp-total b { color: #a3d5f7 !important; } .sgis-feature-card { background: linear-gradient(160deg, rgba(26,159,255, 0.12) 0%, rgba(59, 130, 246, 0.04) 50%, rgba(15, 17, 35, 0.6) 100%) !important; border: 1px solid rgba(26,159,255, 0.2) !important; } .sgis-feature-card::before { background: radial-gradient(circle, rgba(26,159,255, 0.2) 0%, transparent 60%) !important; } .sgis-feature-card::after { background: linear-gradient(90deg, transparent 0%, rgba(26,159,255, 0.5) 50%, transparent 100%) !important; } .sgis-feature-card:hover { border-color: rgba(26,159,255, 0.4) !important; box-shadow: 0 8px 20px rgba(26,159,255, 0.2) !important; } .sgis-feature-card.alt { background: linear-gradient(160deg, rgba(37,99,235, 0.12) 0%, rgba(59, 130, 246, 0.04) 50%, rgba(15, 17, 35, 0.6) 100%) !important; border-color: rgba(37,99,235, 0.2) !important; } .sgis-feature-card.alt::before { background: radial-gradient(circle, rgba(37,99,235, 0.2) 0%, transparent 60%) !important; } .sgis-feature-card.alt::after { background: linear-gradient(90deg, transparent 0%, rgba(37,99,235, 0.5) 50%, transparent 100%) !important; } .sgis-feature-icon { background: linear-gradient(135deg, rgba(26,159,255, 0.22), rgba(37,99,235, 0.12)) !important; box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.04), 0 2px 6px rgba(26,159,255, 0.15) !important; } .sgis-feature-card.alt .sgis-feature-icon { background: linear-gradient(135deg, rgba(37,99,235, 0.22), rgba(59, 130, 246, 0.12)) !important; box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.04), 0 2px 6px rgba(37,99,235, 0.15) !important; } .sgis-feature-icon svg { color: #a3d5f7 !important; } .sgis-feature-card.alt .sgis-feature-icon svg { color: #93c5fd !important; } .sgis-feature-card:hover .sgis-feature-arrow { color: #a3d5f7 !important; } .sgis-feature-stat-val.t-purple { color: #a3d5f7 !important; } .sgis-activity-type.news { background: rgba(102,192,244, 0.2) !important; } .sgis-badge-icon { background: linear-gradient(135deg, rgba(26,159,255, 0.12), rgba(59, 130, 246, 0.06)) !important; } .sgis-badge-card:hover .sgis-badge-icon { background: linear-gradient(135deg, rgba(26,159,255, 0.2), rgba(59, 130, 246, 0.1)) !important; } .sgis-badge-icon svg { color: #a3d5f7 !important; } .sgis-user-ach.unlocked .sgis-user-ach-icon { background: linear-gradient(135deg, rgba(26,159,255, 0.12), rgba(59,130,246,0.08)) !important; box-shadow: 0 0 12px rgba(26,159,255, 0.2) !important; } .sgis-persona-section { background: linear-gradient(135deg, rgba(26,159,255, 0.12) 0%, rgba(59, 130, 246, 0.06) 50%, var(--sgis-bg-2) 100%) !important; border: 1px solid rgba(26,159,255, 0.22) !important; box-shadow: 0 2px 8px rgba(26,159,255, 0.08) !important; } .sgis-persona-section::before { background: radial-gradient(circle, rgba(26,159,255, 0.2) 0%, transparent 60%) !important; } .sgis-persona-title { color: #a3d5f7 !important; } .sgis-persona-title svg { color: #a3d5f7 !important; } .sgis-persona-type { background: linear-gradient(135deg, rgba(26,159,255, 0.25), rgba(37,99,235, 0.15)) !important; color: #a3d5f7 !important; border: 1px solid rgba(26,159,255, 0.3) !important; } .sgis-persona-trait { background: linear-gradient(135deg, rgba(26,159,255, 0.18), rgba(37,99,235, 0.08)) !important; color: #a3d5f7 !important; border: 1px solid rgba(26,159,255, 0.2) !important; } .sgis-insight-kpi.purple { border-color: rgba(26,159,255, 0.3) !important; border-left-color: #1a9fff !important; } .sgis-insight-kpi.purple::before { background: #1a9fff !important; } .sgis-insight-kpi.purple:hover { border-color: rgba(26,159,255, 0.5) !important; } .sgis-insight-persona { border: 1px solid rgba(26,159,255, 0.25) !important; } .sgis-insight-persona-head { background: linear-gradient(135deg, rgba(26,159,255, 0.35), rgba(59, 130, 246, 0.18)) !important; } .sgis-insight-persona-rarity { background: linear-gradient(135deg, rgba(26,159,255, 0.4), rgba(37,99,235, 0.25)) !important; color: #d3ecfd !important; border: 1px solid rgba(26,159,255, 0.4) !important; } .sgis-insight-persona-trait { background: linear-gradient(135deg, rgba(26,159,255, 0.18), rgba(59,130,246,0.08)) !important; color: #a3d5f7 !important; border: 1px solid rgba(26,159,255, 0.22) !important; } .sgis-insight-persona-trait:hover { background: linear-gradient(135deg, rgba(26,159,255, 0.3), rgba(59,130,246,0.15)) !important; border-color: rgba(26,159,255, 0.4) !important; } .sgis-insight-metric:hover { border-color: rgba(26,159,255, 0.2) !important; } .sgis-insight-dim:hover { border-color: rgba(26,159,255, 0.3) !important; } .sgis-insight-ai { border: 1px solid rgba(26,159,255, 0.22) !important; } .sgis-insight-ai-head { background: linear-gradient(135deg, rgba(26,159,255, 0.18), rgba(59, 130, 246, 0.08)) !important; border-bottom: 1px solid rgba(26,159,255, 0.15) !important; } .sgis-insight-ai-icon { background: linear-gradient(135deg, rgba(26,159,255, 0.35), rgba(37,99,235, 0.2)) !important; } .sgis-insight-ai-icon svg { color: #a3d5f7 !important; } .sgis-insight-ai-btn { background: linear-gradient(135deg, rgba(26,159,255, 0.45), rgba(59, 130, 246, 0.3)) !important; border: 1px solid rgba(26,159,255, 0.4) !important; } .sgis-insight-ai-btn:hover { background: linear-gradient(135deg, rgba(26,159,255, 0.6), rgba(59, 130, 246, 0.45)) !important; box-shadow: 0 3px 10px rgba(26,159,255, 0.25) !important; } .sgis-insight-ai-oneliner { background: linear-gradient(135deg, rgba(26,159,255, 0.15), rgba(59, 130, 246, 0.08)) !important; border: 1px solid rgba(26,159,255, 0.2) !important; } .sgis-insight-ai-oneliner svg { color: #a3d5f7 !important; } .sgis-insight-ach-toggle:hover { color: #a3d5f7 !important; } .sgis-social-friend:hover { border-color: rgba(26,159,255, 0.25) !important; background: linear-gradient(135deg, rgba(26,159,255, 0.06) 0%, rgba(59,130,246,0.03) 100%) !important; } .sgis-social-friend-days { background: rgba(26,159,255, 0.12) !important; color: #a3d5f7 !important; border: 1px solid rgba(26,159,255, 0.18) !important; } .sgis-social-group-head { color: #66c0f4 !important; border-bottom: 1px solid rgba(26,159,255, 0.1) !important; } .sgis-social-group-head .count { background: rgba(26,159,255, 0.15) !important; color: #a3d5f7 !important; } .sgis-gc-fill { background: linear-gradient(90deg, #38bdf8, #60a5fa) !important; } .sgis-news-item { background: linear-gradient(135deg, rgba(255, 255, 255, 0.025), rgba(26,159,255, 0.015)) !important; } .sgis-news-item:hover { background: linear-gradient(135deg, rgba(26,159,255, 0.08), rgba(59, 130, 246, 0.04)) !important; border-color: rgba(26,159,255, 0.25) !important; box-shadow: 0 2px 8px rgba(26,159,255, 0.1) !important; } .sgis-news-feed { background: linear-gradient(135deg, rgba(26,159,255, 0.18), rgba(59, 130, 246, 0.1)) !important; color: #a3d5f7 !important; border: 1px solid rgba(26,159,255, 0.18) !important; } .sgis-card-item.sgis-card-with-bg:hover::after { background: linear-gradient(90deg, rgba(15, 17, 35, 0.85) 0%, rgba(26,159,255, 0.3) 50%, rgba(59, 130, 246, 0.2) 100%) !important; } .sgis-scroll-area { scrollbar-color: rgba(26,159,255, 0.4) transparent !important; } .sgis-scroll-area::-webkit-scrollbar-thumb { background: linear-gradient(180deg, rgba(26,159,255, 0.4), rgba(59, 130, 246, 0.4)) !important; } .sgis-badge-group { background: linear-gradient(160deg, rgba(255, 255, 255, 0.025) 0%, rgba(26,159,255, 0.02) 100%) !important; } .sgis-badge-group:hover { border-color: rgba(26,159,255, 0.18) !important; } .sgis-badge-group-head::after { background: linear-gradient(90deg, transparent, rgba(26,159,255, 0.15), transparent) !important; } .sgis-badge-group-icon { background: linear-gradient(135deg, rgba(26,159,255, 0.18), rgba(59, 130, 246, 0.08)) !important; } .sgis-badge-group-icon svg { color: #a3d5f7 !important; } .sgis-badge-group-stat { color: #a3d5f7 !important; background: rgba(26,159,255, 0.12) !important; } .sgis-badge-group-expanded .sgis-badge-group-arrow { color: #a3d5f7 !important; } .sgis-badge-row:hover { background: rgba(26,159,255, 0.08) !important; border-color: rgba(26,159,255, 0.2) !important; } .sgis-badge-row-icon { background: linear-gradient(135deg, rgba(26,159,255, 0.15), rgba(59, 130, 246, 0.06)) !important; } .sgis-badge-row-icon svg { color: #a3d5f7 !important; } .sgis-badge-row-lv { color: #66c0f4 !important; } .sgis-badge-row-rar.r3 { background: rgba(26,159,255, 0.2) !important; color: #a3d5f7 !important; } .sgis-badge-row-link { background: rgba(26,159,255, 0.12) !important; color: #a3d5f7 !important; } .sgis-badge-row-link:hover { background: rgba(26,159,255, 0.25) !important; } .sgis-dist-label { color: #a3d5f7 !important; } .sgis-dist-bar-fill { background: linear-gradient(90deg, #1a9fff, #3b82f6) !important; box-shadow: 0 0 6px rgba(26,159,255, 0.3) !important; } .sgis-value-card { background: linear-gradient(160deg, rgba(255, 255, 255, 0.04) 0%, rgba(26,159,255, 0.025) 100%) !important; } .sgis-value-card:hover { background: linear-gradient(160deg, rgba(26,159,255, 0.1) 0%, rgba(59, 130, 246, 0.04) 100%) !important; border-color: rgba(26,159,255, 0.3) !important; } .sgis-value-card-market { color: #a3d5f7 !important; } .sgis-badge-row-icon-wrap { background: radial-gradient(circle at 50% 35%, rgba(26,159,255, 0.12), transparent 65%), linear-gradient(135deg, rgba(15, 23, 42, 0.6) 0%, rgba(30, 41, 59, 0.5) 100%) !important; } .sgis-badge-tip { border: 1px solid rgba(26,159,255, 0.35) !important; box-shadow: 0 8px 24px rgba(0, 0, 0, 0.5), 0 0 0 1px rgba(26,159,255, 0.1) !important; } .sgis-badge-tip-head { border-bottom: 1px solid rgba(26,159,255, 0.15) !important; } .sgis-badge-tip-bd-bar > div { background: linear-gradient(90deg, #1a9fff, #3b82f6) !important; } .sgis-tagrec-tab:hover { background: rgba(26,159,255, 0.1) !important; } .sgis-tagrec-tab.active { background: rgba(26,159,255, 0.2) !important; color: #a3d5f7 !important; border-color: rgba(26,159,255, 0.4) !important; } .sglv-goty-year-chip:hover { background: rgba(26,159,255, 0.12) !important; border-color: rgba(26,159,255, 0.3) !important; } .sglv-goty-year-chip.active { background: linear-gradient(135deg, rgba(26,159,255, 0.25), rgba(59, 130, 246, 0.15)) !important; color: #a3d5f7 !important; border-color: rgba(26,159,255, 0.5) !important; box-shadow: 0 0 8px rgba(26,159,255, 0.2) !important; } /* ########## Part E: 收藏库面板 CSS 紫色覆盖(8 条,attr 前缀顺序无关) ########## */ html[data-sglv-theme="blue"] .sglv-header-brand { background: linear-gradient(135deg, rgba(102, 192, 244, 0.18), rgba(26,159,255, 0.18)) !important; } html[data-sglv-theme="blue"] .sgc-panel .sglv-goty-year-bar { background: linear-gradient(180deg, rgba(26,159,255, 0.08), transparent) !important; border-bottom: 1px solid rgba(26,159,255, 0.18) !important; } html[data-sglv-theme="blue"] .sgc-panel .sglv-goty-year-chip.active { background: linear-gradient(135deg, rgba(26,159,255, 0.4), rgba(59, 130, 246, 0.25)) !important; border-color: rgba(26,159,255, 0.6) !important; box-shadow: 0 0 12px rgba(26,159,255, 0.35) !important; } html[data-sglv-theme="blue"] .sglv-skel-stage-fill { background: linear-gradient(90deg, #66c0f4, #66c0f4) !important; } html[data-sglv-theme="blue"] .sglv-dlc-loading .sglv-dlc-spin { color:#66c0f4 !important; } html[data-sglv-theme="blue"] .sglv-dlc-loading-bar-fill { background:linear-gradient(90deg,#66c0f4,#66c0f4) !important; } html[data-sglv-theme="blue"] .sglv-dlc-type-badge-dlc { background: rgba(26,159,255, 0.15) !important; color: #66c0f4 !important; border: 1px solid rgba(26,159,255, 0.25) !important; } html[data-sglv-theme="blue"] .sgc-panel .sglv-stat-row + .sglv-progress .sglv-progress-fill { background: linear-gradient(90deg, #4caf50, #22d3ee, #66c0f4, #66c0f4) !important; } /* ########## Part D: 手工精调(侧边栏靛蓝暗基底→Steam 深蓝 + 标题栏柔化 + 收藏库渐变保深度) ########## */ :root { --sgis-bg: linear-gradient(180deg, rgba(23, 26, 33, 0.98) 0%, rgba(13, 19, 30, 0.99) 100%) !important; --sgis-bg-solid: #10151d !important; --sgis-bg-2: rgba(19, 25, 36, 0.85) !important; --sgis-bg-3: rgba(24, 32, 48, 0.7) !important; } .sgis-tabs { background: linear-gradient(180deg, rgba(23, 26, 33, 0.7) 0%, rgba(13, 19, 30, 0.85) 100%) !important; } .sgis-header { background: linear-gradient(135deg, rgba(102, 192, 244, 0.12) 0%, rgba(59, 130, 246, 0.07) 50%, var(--sgis-bg-2) 100%) !important; border-bottom: 1px solid rgba(102, 192, 244, 0.18) !important; } .sgis-header::before { background: radial-gradient(circle, rgba(102, 192, 244, 0.12) 0%, transparent 65%) !important; } .sgis-header-decoration { background: linear-gradient(90deg, transparent 0%, rgba(102, 192, 244, 0.3) 50%, transparent 100%) !important; } #sgis-panel { border-left: 1px solid rgba(102, 192, 244, 0.2) !important; } #sgis-panel::before { background: linear-gradient(90deg, transparent 0%, rgba(102, 192, 244, 0.35) 50%, transparent 100%) !important; } html[data-sglv-theme="blue"] .sglv-skel-stage-fill { background: linear-gradient(90deg, #1a9fff, #66c0f4) !important; } html[data-sglv-theme="blue"] .sglv-dlc-loading-bar-fill { background: linear-gradient(90deg, #1a9fff, #66c0f4) !important; } html[data-sglv-theme="blue"] .sgc-panel .sglv-stat-row + .sglv-progress .sglv-progress-fill { background: linear-gradient(90deg, #4caf50, #22d3ee, #1a9fff, #66c0f4) !important; } /* ---- D5. 成就页 → 经典蓝统一视觉 ---- * 痛点: 页面原为 GitHub 暗底+多彩语义第三风格,蓝色铬件下绿色稀有度条/彩虹进度条/金青横幅 * 混杂扎眼。收敛策略: 页面底转 Steam 深蓝;稀有度只保留角标圆点与低饱和左条(信息不丢); * 进度/徽章/NEW/横幅/环形数值统一蓝系;已解锁名称与计数文字换柔和浅蓝(降刺眼度)。 */ .sglv-ach-layout, .sglv-sc-wrap { background: linear-gradient(180deg, #141c28 0%, #0e141d 100%) !important; } .sglv-ach-sidebar { background: linear-gradient(180deg, rgba(18, 25, 36, 0.95) 0%, rgba(12, 17, 25, 0.95) 100%) !important; border-right-color: rgba(102, 192, 244, 0.08) !important; } .sglv-ach-sidebar-header { border-bottom-color: rgba(102, 192, 244, 0.08) !important; } .sglv-ach-user-card { border-bottom-color: rgba(102, 192, 244, 0.06) !important; } .sglv-ach-card { background: linear-gradient(135deg, rgba(16, 24, 36, 0.6), rgba(24, 34, 50, 0.4)) !important; border-color: rgba(102, 192, 244, 0.08) !important; } .sglv-ach-card:hover { border-color: rgba(102, 192, 244, 0.3) !important; } .sglv-ach-card::before { opacity: 0.45 !important; } .sglv-ach-card.unlocked { border-color: rgba(102, 192, 244, 0.18) !important; background: linear-gradient(135deg, rgba(102, 192, 244, 0.05), rgba(13, 17, 23, 0.4)) !important; } .sglv-ach-card.unlocked .sglv-ach-card-name { color: #d9e8f7 !important; } .sglv-ach-card.unlocked .sglv-ach-card-pts { background: rgba(102, 192, 244, 0.1) !important; border-color: rgba(102, 192, 244, 0.25) !important; color: #a9d4f5 !important; } .sglv-ach-card-new-tag { background: #1a9fff !important; } .sglv-ach-card-progress { background: rgba(102, 192, 244, 0.08) !important; } .sglv-ach-card.unlocked .sglv-ach-card-progress-fill { background: linear-gradient(90deg, #1a9fff, #66c0f4) !important; box-shadow: 0 0 8px rgba(102, 192, 244, 0.3) !important; } .sglv-ach-card.locked .sglv-ach-card-progress-fill { background: linear-gradient(90deg, #4c6b87, #66c0f4) !important; box-shadow: none !important; } .sglv-ach-card.unlocked .sglv-ach-card-progress-val { color: #7fb8e0 !important; } .sglv-ach-content-count { background: rgba(102, 192, 244, 0.1) !important; color: #a9d4f5 !important; } .sglv-ach-ring-bg { stroke: rgba(102, 192, 244, 0.1) !important; } .sglv-ach-ring-val { background: linear-gradient(135deg, #1a9fff, #a3d5f7) !important; -webkit-background-clip: text !important; background-clip: text !important; } .sglv-ach-steam-banner { background: linear-gradient(135deg, rgba(102, 192, 244, 0.08), rgba(26, 159, 255, 0.04)) !important; border-color: rgba(102, 192, 244, 0.15) !important; } .sglv-ach-steam-banner::after { background: radial-gradient(circle, rgba(102, 192, 244, 0.1), transparent 60%) !important; } .sglv-ach-steam-banner-icon { background: linear-gradient(135deg, rgba(102, 192, 244, 0.18), rgba(26, 159, 255, 0.1)) !important; } .sglv-ach-steam-banner-icon svg { color: #66c0f4 !important; } .sglv-ach-steam-banner-val { background: linear-gradient(135deg, #66c0f4, #22d3ee) !important; -webkit-background-clip: text !important; background-clip: text !important; } .sglv-ach-user-pts strong { color: #a9d4f5 !important; } `; const CSS_LIST_FIX = ` /* ====== 列表视图固定 2 列等宽(愿望单等所有 list 视图共用) ====== */ .sglv-list-view { grid-template-columns: repeat(2, minmax(0, 1fr)) !important; width: 100% !important; max-width: 100% !important; } .sglv-list-view > .sglv-list-item { min-width: 0 !important; max-width: 100% !important; overflow: hidden !important; } .sglv-list-view .sglv-list-info { min-width: 0 !important; max-width: 100% !important; overflow: hidden !important; } .sglv-list-view .sglv-list-meta { min-width: 0 !important; max-width: 100% !important; overflow: hidden !important; } /* ====== v2.31.6 长列表渲染治理:游戏库屏外条目降级渲染 ====== 背景:一页 48 项(横版 24 项),每项含封面图 + 标题 + 徽章, 切视图/筛选/排序/翻页都会整块重建 DOM,屏外条目白白参与布局与绘制。 实测(Chromium,48 张卡片):布局 17.5ms → 1.1ms,绝对节省 16.4ms(超过一帧预算)。 写法要点: - 用 auto(不用 hidden):hidden 会让条目不可被 Ctrl+F 搜到; - contain-intrinsic-size 的 auto 前缀让浏览器自己记住上次真实高度, 因此无需 JS 测高——也就没有"重复测量导致高度越改越小"的老问题, 面板 resize 导致列宽变化时浏览器也会自动重新学习; - 作用域限定 .sglv-content(游戏库主滚动容器), 不影响愿望单/系列/云存档等共用 renderGameView 工厂的其他页面; - 刻意不加 contain:条目内含 position:absolute 的浮层(徽章/时长角标/斜切带), 加了会被 paint containment 裁剪。 */ .sglv-content .sglv-game-card { content-visibility: auto; contain-intrinsic-size: auto var(--sglv-h, 200px); } .sglv-content .sglv-cover-card { content-visibility: auto; contain-intrinsic-size: auto var(--sglv-h, 190px); } .sglv-content .sglv-list-item { content-visibility: auto; contain-intrinsic-size: auto var(--sglv-h, 62px); } `; const CSS_MENU = ` /* ====== 导航栏二级菜单——点击接管 + fixed 停靠 ====== */ /*子菜单竖排 + 自带底板(不再依赖共享库)。根因: .sglv-submenu-item{display:block} 只存在于 @require 外部库 sglv-shared-css, 该库加载失败时 CSS_STYLES 为空串(见 v2.7.1 注释), 两个 <a> 退回 inline 默认值 → 「游戏收藏 / 游戏数据」横排成一行, 且 ▾ 开关因 Steam .menuitem{float:left} 换行堆到「游戏库」上方。此处在主脚本内以 !important 兜底: ① menuWrap 改 inline-flex + 子元素 float:none —— 游戏库与 ▾ 恒在同一行; ② 子菜单项强制 display:block + width:100% —— 恒为竖排, 任何加载顺序都不横排; ③ 子菜单自带 min-width/底板/圆角/阴影 —— 共享库缺失时也不会"裸奔"贴到页面上。 停靠坐标仍由 JS 按 fab.getBoundingClientRect() 写入 --sglv-sub-*(见 dockSubmenu)。 */ .sglv-menu-wrap { display: inline-flex !important; align-items: center !important; vertical-align: middle !important; } .sglv-menu-wrap > .sglv-fab { float: none !important; } /*完美复刻 Steam 原生 supernav 下拉(对照 雅俊杰汐→主页/讨论/创意工坊/市场/实况直播) 面板: rgba(58,79,96,.95) = Steam supernav dropdown token / 无圆角无描边 / 轻投影; 菜单项: 14px 常规字重 + #c7d5e0 + 行高 30px + 左右 16px 内边距(与 Steam 实测留白一致); 悬停: rgba(255,255,255,.12) 浅色高亮 = Steam 原生 hover, 不是蓝底也不是白色块; 父项「游戏库」展开时**不做**激活底色 —— Steam 展开父项不变色, 此前误加的 rgba(255,255,255,.12) 父项底 + .is-active 纯白块是"看起来不一样"的主因, 均已移除。 选中态(is-active)改为白字 + 600 字重 + 极浅底, 与 Steam 视觉体系不冲突。 */ .sglv-submenu { display: none !important; box-sizing: border-box !important; width: max-content !important; min-width: 120px !important; max-width: 260px !important; padding: 4px 0 !important; background: rgba(58, 79, 96, 0.95) !important; border: none !important; border-radius: 0 !important; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4) !important; overflow: hidden !important; z-index: 9999 !important; } .sglv-submenu-item { display: block !important; float: none !important; width: 100% !important; box-sizing: border-box !important; height: 30px !important; line-height: 30px !important; padding: 0 16px !important; font-size: 14px !important; font-weight: 400 !important; color: #c7d5e0 !important; background: transparent !important; white-space: nowrap !important; text-decoration: none !important; } .sglv-submenu-item:hover { background: rgba(255, 255, 255, 0.12) !important; color: #ffffff !important; } .sglv-submenu-item.is-active { background: rgba(255, 255, 255, 0.06) !important; color: #ffffff !important; font-weight: 600 !important; } .sglv-menu-wrap.sglv-open .sglv-submenu { display: block !important; } .sglv-menu-wrap.sglv-open:hover .sglv-submenu { display: block !important; } .sglv-menu-wrap:hover .sglv-submenu { display: none !important; } .sglv-submenu.sglv-submenu-docked { position: fixed !important; top: var(--sglv-sub-top, 100%) !important; left: var(--sglv-sub-left, 0) !important; overflow: visible !important; } /* 热区桥:向上盖住按钮与菜单之间的缝。overflow:hidden 会把这段裁掉,停靠态必须改回 visible。 */ .sglv-submenu.sglv-submenu-docked::before { content: '' !important; position: absolute !important; left: 0 !important; right: 0 !important; top: -10px !important; height: 10px !important; display: block !important; background: transparent !important; } .sglv-menu-wrap.sglv-menu-fixed { position: fixed !important; top: 14px !important; right: 160px !important; z-index: 99999 !important; display: inline-flex !important; } /* React 商店头(愿望单等页没有 .supernav_container):入口插在「客服」同一条 flex 行里, 外观由运行时复制的头部链接 class 决定。这里只取消浮动定位,避免再钉到右上角。 */ .sglv-menu-wrap.sglv-menu-in-header { position: relative !important; top: auto !important; right: auto !important; margin: 0 !important; flex: 0 0 auto !important; float: none !important; z-index: 2 !important; align-items: stretch !important; align-self: stretch !important; } .sglv-menu-wrap.sglv-menu-in-header > .sglv-fab { height: 100% !important; box-sizing: border-box !important; } `; const CSS_PLAYDATA = ` /* ====== 游玩数据页(排行 + 洞察) ====== */ .sglv-pt-hero-kpi { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 10px; flex-shrink: 0; } /* HERO KPI 卡宽松化:Top20 可内部滚动后不再极限压缩——恢复呼吸感 padding/字号 */ .sglv-pt-hero-kpi .sglv-playtime-kpi-card { padding: 8px 12px 6px; } .sglv-pt-hero-kpi .sglv-playtime-kpi-value { font-size: 20px; } .sglv-pt-hero-kpi .sglv-playtime-kpi-label { font-size: 11.5px; } .sglv-pt-hero-kpi .sglv-playtime-kpi-sub { font-size: 10px; } .sglv-pt-panel { background: var(--sglv-section-bg, rgba(255,255,255,0.02)); border: 1px solid var(--sglv-border, rgba(255,255,255,0.08)); border-radius: var(--sglv-radius, 10px); padding: 14px 16px; min-width: 0; } .sglv-pt-panel-body { display: flex; flex-direction: column; gap: 8px; min-width: 0; } /* v2.32.0 起总览瘦身为「HERO + Top20」直排结构(.sglv-pt-main-row 双栏已废弃), 时长集中度/活跃度分层迁入「游玩分析」Tab——旧双栏选择器一并清除 */ .sglv-pt-conc-summary { display: flex; flex-wrap: wrap; gap: 6px; } .sglv-pt-conc-chip { font-size: 11.5px; padding: 3px 10px; border-radius: 999px; background: rgba(102,192,244,0.1); border: 1px solid rgba(102,192,244,0.22); color: #c7d5e0; } .sglv-pt-conc-chip b { color: var(--sglv-accent, #66c0f4); font-weight: 700; } .sglv-pt-conc-note { font-size: 11.5px; color: var(--sglv-text-secondary, #8a9ba8); line-height: 1.5; } .sglv-pt-conc-chart { width: 100%; height: 160px; display: flex; align-items: center; } .sglv-pt-conc-chart .sglv-trend-svg { height: auto !important; max-height: 160px; width: 100% !important; } .sglv-pt-layer-row { cursor: pointer; border-radius: 4px; padding: 2px 6px; transition: background .15s; } .sglv-pt-layer-row:hover { background: rgba(102,192,244,0.08); } /* 活跃度分层面板隐藏"点击任一分层查看该层排行"提示行(远端 PTW 库尚未更新, 主脚本 CSS 兜底,避免面板体溢出容器) */ #sglv-pt-act-body > .sglv-pt-conc-note { display: none !important; } .sglv-pt-dust { margin-top: 8px; padding-top: 10px; border-top: 1px dashed rgba(255,255,255,0.08); display: flex; align-items: center; gap: 8px; flex-wrap: wrap; font-size: 11.5px; color: var(--sglv-text-secondary, #8a9ba8); } .sglv-pt-dust b { color: #fbbf24; } .sglv-pt-dust-btn { border: 1px solid rgba(251,191,36,0.35); background: rgba(251,191,36,0.1); color: #fbbf24; border-radius: 4px; font-size: 11.5px; padding: 2px 9px; cursor: pointer; } .sglv-pt-dust-btn:hover { background: rgba(251,191,36,0.2); } /*Top20 单列长列表——列表自身滚动后放开压缩:行高 ~34px, icon 28px / padding 6-10px / gap 10px / rank 24×24,呼吸感优先于"一屏看完" */ .sglv-pt-top-grid { display: grid; grid-template-columns: minmax(0, 1fr); gap: 4px; } .sglv-pt-top-grid .sglv-pt-top-item { margin-bottom: 0; min-width: 0; padding: 6px 10px; gap: 10px; } .sglv-pt-top-col .sglv-pt-icon { width: 28px; height: 28px; border-radius: 4px; } .sglv-pt-top-col .sglv-pt-rank { width: 24px; height: 24px; font-size: 11px; border-radius: 5px; } .sglv-pt-top-col .sglv-pt-name { font-size: 13px; line-height: 1.3; } .sglv-pt-top-col .sglv-pt-meta { font-size: 11px; line-height: 1.3; margin-top: 2px; } .sglv-pt-top-col .sglv-pt-info { display: flex; flex-direction: column; gap: 0; justify-content: center; } .sglv-pt-top-col .sglv-pt-hours { min-width: 48px; font-size: 12.5px; } .sglv-pt-top-col .sglv-pt-bar-wrap { height: 5px; } /* Top20 段标题:14px 字号 + 10px 下间距 */ .sglv-pt-top-col > .sglv-playtime-section-title { font-size: 14px; margin-bottom: 10px; } /* panel 内 section title(集中度/活跃度分层):14px 字号 + 10px 下间距 */ .sglv-pt-panel > .sglv-playtime-section-title { font-size: 14px; margin-bottom: 10px; } /* 活跃度分层行:行距/轨道放宽,与面板留白节奏一致(游玩分析 Tab) */ .sglv-dist-bar-row { margin-bottom: 6px; gap: 10px; } .sglv-dist-bar-track { height: 16px; } .sglv-dist-bar-label { width: 72px; font-size: 11.5px; } .sglv-dist-bar-value { width: 84px; font-size: 11.5px; } .sglv-ptwin-open { display: inline-flex; align-items: center; gap: 4px; padding: 3px 10px; border-radius: 6px; border: 1px solid rgba(102,192,244,0.3); background: rgba(102,192,244,0.1); color: var(--sglv-accent, #66c0f4); font-size: 11px; font-weight: 600; cursor: pointer; transition: var(--sglv-transition); } .sglv-ptwin-open:hover { background: rgba(102,192,244,0.2); } .sglv-ptwin-open svg { width: 12px; height: 12px; } /* 主区布局:HERO 固定 → Top20 卡片占满剩余高度 → 列表自身纵向滚动(sglv-pt-tab 仅游玩数据页,勿波及统计仪表页) */ .sglv-body > .sglv-pt-tab { overflow: hidden !important; padding: 12px 14px !important; gap: 12px !important; } .sglv-body > .sglv-pt-tab > .sglv-playtime-wrap { flex: 1 1 0 !important; min-height: 0 !important; overflow: hidden !important; gap: 12px !important; } /* v2.33.1 修复:v2.32.0 重构后总览 DOM 变为 .sglv-pt-overview 直排(HERO + Top20), 旧 .sglv-pt-main-row 双栏选择器失配 → 面板退化 block、#sglv-pt-top-list 无高度约束, 溢出被内层 overflow:hidden 裁掉且无滚动条。改为直接锚定 .sglv-pt-overview 新结构: 面板 flex column 撑满剩余高度,滚动交还列表自身;不锚定 .sglv-body, 全屏浮窗 overview Tab 同构 DOM 同规则受益 */ .sglv-pt-overview > .sglv-pt-top-col { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; } .sglv-pt-top-col > .sglv-playtime-section-title { flex-shrink: 0; } .sglv-pt-top-col > #sglv-pt-top-list { flex: 1 1 auto; min-height: 140px; max-height: none; overflow-y: auto; overflow-x: hidden; overscroll-behavior: contain; scrollbar-gutter: stable; scrollbar-width: thin; scrollbar-color: rgba(255,255,255,0.14) transparent; } .sglv-pt-top-col > #sglv-pt-top-list::-webkit-scrollbar { width: 6px; } .sglv-pt-top-col > #sglv-pt-top-list::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.14); border-radius: 3px; } .sglv-pt-top-col > #sglv-pt-top-list::-webkit-scrollbar-thumb:hover { background: rgba(255,255,255,0.24); } /* 列表不足一屏(游戏 <20 款)时行块顶部对齐,不随 flex 拉伸出空隙 */ .sglv-pt-top-grid { align-content: start; } /* ≤900px:单列流式,恢复整页滚动 */ @media (max-width: 900px) { .sglv-body > .sglv-pt-tab, .sglv-body > .sglv-pt-tab > .sglv-playtime-wrap { overflow-y: auto !important; } .sglv-pt-overview > .sglv-pt-top-col { flex: 0 0 auto; } .sglv-pt-top-col > #sglv-pt-top-list { overflow-y: visible; min-height: 0; } } /* ====== 全部游戏排行遗留壳样式 ====== .sglv-ptwin-overlay/.sglv-ptwin/.sglv-ptwin-head/tabs/body/pane 系列已废弃(排行已改走 SGLVPTW 框架浮窗), 仍在使用的:.sglv-ptwin-open(Top20 卡片头「全部游戏排行」按钮)、 .sglv-pt-all-loading / .sglv-pt-all-hint(月历/排行 Tab 加载态)。 */ .sglv-pt-all-loading { padding: 24px 0; text-align: center; font-size: 12px; color: var(--sglv-text-secondary, #8a9ba8); } .sglv-pt-all-hint { margin: 0 0 8px; font-size: 11px; line-height: 1.5; color: #fbbf24; } /* ====== 全部游戏排行过滤 chips(隐藏从未游玩/隐藏家庭共享/正倒序切换) ====== */ .sglv-pt-filter-chip { border: 1px solid rgba(255,255,255,0.12); background: rgba(255,255,255,0.04); color: #8a9ba8; border-radius: 999px; font-size: 11px; padding: 3px 10px; cursor: pointer; white-space: nowrap; } .sglv-pt-filter-chip:hover { color: #fff; } .sglv-pt-filter-chip.active { color: var(--sglv-accent, #66c0f4); border-color: rgba(102,192,244,0.35); background: rgba(102,192,244,0.1); } /* ====== 全部游戏列表行首游戏图标 ====== */ /* 紧凑 22px(共享库 .sglv-pt-icon 为 Top20 的 40px;本列表行密 padding 6px/字号 12px, 40px 会把行高从 ~29px 撑到 ~52px,密集排行可读性下降)。固定尺寸 + flex-shrink:0 保证图标懒加载过程零布局抖动;object-fit:cover 兼容竖版/横版资产裁切一致。 */ .sglv-pt-all-icon { width: 22px; height: 22px; border-radius: 3px; flex-shrink: 0; object-fit: cover; background: rgba(255,255,255,0.05); } /* ====== 家庭成员对比(对比条 + 可展开 Top20) ====== */ .sglv-fam-list { margin-top: 8px; } .sglv-fam-item { background: rgba(255,255,255,0.025); border: 1px solid var(--sglv-border, rgba(255,255,255,0.08)); border-radius: 8px; margin-bottom: 8px; overflow: hidden; } .sglv-fam-item.is-me { border-color: rgba(102,192,244,0.28); background: rgba(102,192,244,0.05); } .sglv-fam-head { display: flex; align-items: center; gap: 8px; padding: 8px 10px; cursor: pointer; } .sglv-fam-head:hover { background: rgba(255,255,255,0.04); } .sglv-fam-rank { width: 22px; height: 22px; flex: 0 0 22px; border-radius: 5px; display: flex; align-items: center; justify-content: center; font-size: 11px; font-weight: 700; background: rgba(255,255,255,0.06); color: #94a3b8; } .sglv-fam-item.is-me .sglv-fam-rank { background: rgba(102,192,244,0.2); color: #66c0f4; } .sglv-fam-name { flex: 1; min-width: 0; font-size: 13px; font-weight: 600; color: #e0e0e0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .sglv-fam-item.is-me .sglv-fam-name { color: #66c0f4; } .sglv-fam-hours { flex: 0 0 auto; font-size: 13px; font-weight: 700; color: #fbbf24; white-space: nowrap; } .sglv-fam-chev { flex: 0 0 auto; font-size: 11px; color: #8a9ba8; transition: transform .2s ease; } .sglv-fam-item.open .sglv-fam-chev { transform: rotate(180deg); } .sglv-fam-track { height: 5px; margin: 0 10px 8px; background: rgba(255,255,255,0.06); border-radius: 3px; overflow: hidden; } .sglv-fam-fill { display: block; height: 100%; border-radius: 3px; background: linear-gradient(90deg, #4caf50, #2e7d32); transition: width .4s ease; min-width: 2px; } .sglv-fam-item.is-me .sglv-fam-fill { background: linear-gradient(90deg, #66c0f4, #4a9eda); } .sglv-fam-games { display: none; padding: 6px 10px 10px; border-top: 1px dashed rgba(255,255,255,0.08); } .sglv-fam-item.open .sglv-fam-games { display: block; } .sglv-fam-game { display: flex; align-items: center; gap: 8px; padding: 3px 0; } .sglv-fam-game-rank { flex: 0 0 20px; font-size: 10px; color: #64748b; text-align: right; } /*家庭对比 Top20 行首游戏图标——16px 紧凑尺寸(行高由 12px 名称行 ~17px 决定, 16px 图标不撑高行;固定尺寸 + flex-shrink:0 保证懒加载零布局抖动) */ .sglv-fam-game-icon { width: 16px; height: 16px; border-radius: 3px; flex-shrink: 0; object-fit: cover; background: rgba(255,255,255,0.05); } .sglv-fam-game-name { flex: 1; min-width: 0; font-size: 12px; color: #c7d5e0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .sglv-fam-game-bar { flex: 0 0 90px; height: 4px; border-radius: 2px; background: rgba(255,255,255,0.06); overflow: hidden; } .sglv-fam-game-bar > i { display: block; height: 100%; border-radius: 2px; background: linear-gradient(90deg, #66c0f4, #4caf50); } .sglv-fam-game-hours { flex: 0 0 58px; text-align: right; font-size: 11px; font-weight: 600; color: #fbbf24; } .sglv-fam-empty { padding: 8px 2px; font-size: 11px; color: var(--sglv-text-secondary, #8a9ba8); } .sglv-fam-refresh { flex: 0 0 auto; width: 24px; height: 24px; border-radius: 5px; border: 1px solid rgba(102,192,244,0.3); background: rgba(102,192,244,0.1); color: var(--sglv-accent, #66c0f4); cursor: pointer; display: flex; align-items: center; justify-content: center; padding: 0; } .sglv-fam-refresh:hover { background: rgba(102,192,244,0.2); } .sglv-fam-refresh svg { width: 12px; height: 12px; } @media (max-width: 1100px) { .sglv-pt-hero-kpi { grid-template-columns: repeat(3, minmax(0, 1fr)); } } @media (max-width: 600px) { .sglv-pt-hero-kpi { grid-template-columns: repeat(2, minmax(0, 1fr)); } } /* ====== 全部游戏浮窗 · 入库月历 Tab ====== */ /* v2.22.6 布局最终形态:**选择器固定 + 详情自带滚动条**(用户明确要求两条): pane(不滚) = toolbar(固定) + grid(固定·完整 12 月卡) + timeline(唯一滚动区) —— 走过的弯路与各自的失效点: ① grid 收缩 + timeline min-height → timeline 保底生效后,flex 剩余收缩压力 全部转嫁 grid,选择器被压到 ~140px(用户截图:日期行被切半、7-12 月整行消失); ② grid 固定 + timeline{flex:1 1 0} 吃剩余 → 选择器完整,但 800px 视口下 timeline 只剩 4px,详情几乎不可见; ③ 滚动上移到 pane → 选择器/详情都正常,但**滚动条跑到了整个 Tab 区域的最右缘** (贴着窗口边框),用户反馈「滚动条消失、无法滚动查看」—— 技术上可滚,但滚动入口视觉上不可见 = 等于没有。 现方案:滚动条还给详情区(.sglv-ptcal-timeline overflow-y:auto), grid 固定不压缩,空间冲突由「矮视口紧凑月历」化解(见下方 @media)。*/ .sglv-ptcal-pane { flex: 1; min-height: 0; display: flex; flex-direction: column; gap: 10px; overflow-y: auto; overscroll-behavior: contain; } .sglv-ptcal-toolbar { display: flex; align-items: center; gap: 10px 8px; flex-wrap: wrap; flex: 0 0 auto; } .sglv-ptcal-yearnav { display: flex; align-items: center; gap: 4px; flex-shrink: 0; } .sglv-ptcal-yearnav-btn { width: 24px; height: 24px; border: 1px solid rgba(102,192,244,0.3); background: rgba(102,192,244,0.1); color: var(--sglv-accent, #66c0f4); border-radius: 5px; cursor: pointer; font-size: 10px; display: flex; align-items: center; justify-content: center; padding: 0; } .sglv-ptcal-yearnav-btn:hover { background: rgba(102,192,244,0.2); } .sglv-ptcal-yearnav-btn:disabled { opacity: 0.35; cursor: default; } .sglv-ptcal-year-label { min-width: 52px; text-align: center; font-size: 15px; font-weight: 700; color: #fff; } /* 年份胶囊:单行横向滚动,但宽度有下限保护。 v2.22.6修正:原写 min-width:0,flex 收缩时容器被压到 ~145px, 13 个胶囊(flex:0 0 auto 不可压)反而把内容挤成「一排小点」; 下限 min(200px,45%) 保证至少放得下 4 个胶囊,多出的年份走横向滚动。 上限 min(52%,460px) 取代旧硬编码 46%(46% 在 1080px 窗口只有 ~500px, 叠加右侧 summary 后必然溢出被裁)。*/ .sglv-ptcal-year-chips { display: flex; gap: 4px; flex-wrap: nowrap; flex: 0 1 auto; min-width: min(200px, 45%); max-width: min(52%, 460px); overflow-x: auto; overscroll-behavior-x: contain; scrollbar-width: thin; padding-bottom: 1px; } .sglv-ptcal-year-chip { flex: 0 0 auto; border: 1px solid rgba(255,255,255,0.12); background: rgba(255,255,255,0.04); color: #8a9ba8; border-radius: 999px; font-size: 11px; padding: 2px 10px; cursor: pointer; } .sglv-ptcal-year-chip:hover { color: #fff; } .sglv-ptcal-year-chip.active { color: var(--sglv-accent, #66c0f4); border-color: rgba(102,192,244,0.35); background: rgba(102,192,244,0.1); } /*「今年」胶囊——当前年即使在筛选集内无数据(如吃灰榜入库超 1 年)也固定占位, 绿点标识自然年"此刻",与入库数量绿色阶同语义但仅为标记点 */ .sglv-ptcal-year-chip.now::after { content: ''; display: inline-block; width: 5px; height: 5px; border-radius: 50%; background: #39d353; margin-left: 5px; vertical-align: 1px; } .sglv-ptcal-year-chip.now.active::after { box-shadow: 0 0 5px rgba(57,211,83,0.9); } /* 统计区:允许整块换行到下一行,不再与年份胶囊抢同一行导致右侧被裁 */ .sglv-ptcal-summary { display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 6px; margin-left: auto; min-width: 0; } .sglv-ptcal-chip { font-size: 11px; padding: 2px 9px; border-radius: 999px; background: rgba(102,192,244,0.08); border: 1px solid rgba(102,192,244,0.2); color: #c7d5e0; white-space: nowrap; } .sglv-ptcal-chip b { color: var(--sglv-accent, #66c0f4); font-weight: 700; } .sglv-ptcal-chip.peak b { color: #fbbf24; } /*「仅个人游戏」过滤 chip(复用 ptcal-chip 底样, active 高亮 accent) */ .sglv-ptcal-chip.tgl { cursor: pointer; } .sglv-ptcal-chip.tgl:hover { color: #fff; } .sglv-ptcal-chip.tgl.active { color: var(--sglv-accent, #66c0f4); border-color: rgba(102,192,244,0.45); background: rgba(102,192,244,0.16); } .sglv-ptcal-legend { display: inline-flex; align-items: center; gap: 3px; font-size: 10px; color: #8a9ba8; flex-shrink: 0; } .sglv-ptcal-legend .swatch { width: 10px; height: 10px; border-radius: 2px; display: inline-block; } /*6+6 月历组合(每行 6 个月 × 2 行, 替代原 8+4)—— 卡片宽度封顶 240px 确保宽度适中(全屏下不过度拉伸、日格保持可点尺寸), space-between 均匀分配余白; <1200px 退化 4 列, <760px 退化 2 列(小屏卡片可用性优先) v2.22.6:flex:0 0 auto —— 12 个月卡**永不收缩、永不内部滚动**, 月历选择区整体固定在顶部,时间线只能从它下方开始。 */ .sglv-ptcal-grid { display: grid; grid-template-columns: repeat(6, minmax(0, 240px)); justify-content: space-between; gap: 10px 8px; flex: 0 0 auto; } @media (max-width: 1400px) { .sglv-ptcal-grid { grid-template-columns: repeat(6, minmax(0, 1fr)); } } /* v2.22.6:4 列断点 1200→1000px。1200px 以下就退 4 列时,12 张月卡排成 3 行(~680px), 在「窄而高」的窗口(如 1280×1000)里会把详情压到百来像素;收到 1000px 后 1100~1200px 的常见宽度保持 6 列 2 行,详情可视区明显更充裕。 */ @media (max-width: 1000px) { .sglv-ptcal-grid { grid-template-columns: repeat(4, minmax(0, 1fr)); } } @media (max-width: 760px) { .sglv-ptcal-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } } .sglv-ptcal-month { background: rgba(255,255,255,0.025); border: 1px solid var(--sglv-border, rgba(255,255,255,0.08)); border-radius: 8px; padding: 8px 8px 6px; min-width: 0; } .sglv-ptcal-month-head { display: flex; align-items: baseline; justify-content: space-between; gap: 6px; margin-bottom: 5px; } .sglv-ptcal-month-name { font-size: 12px; font-weight: 700; color: #c7d5e0; } .sglv-ptcal-month-count { font-size: 10px; color: #8a9ba8; } .sglv-ptcal-month-count b { color: var(--sglv-accent, #66c0f4); } .sglv-ptcal-week, .sglv-ptcal-days { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); gap: 2px; } .sglv-ptcal-wd { font-size: 9px; color: #64748b; text-align: center; padding-bottom: 1px; } .sglv-ptcal-day { aspect-ratio: 1; border-radius: 3px; display: flex; align-items: center; justify-content: center; font-size: 9px; line-height: 1; color: #8a9ba8; background: rgba(255,255,255,0.03); min-width: 0; } .sglv-ptcal-day.empty { background: transparent; } .sglv-ptcal-day.future { background: rgba(255,255,255,0.012); color: #3d4a5a; } .sglv-ptcal-day.has { cursor: pointer; color: #fff; font-weight: 600; } .sglv-ptcal-day.has:hover { outline: 1px solid var(--sglv-accent, #66c0f4); } .sglv-ptcal-day.sel { outline: 2px solid var(--sglv-accent, #66c0f4); } .sglv-ptcal-day.lv1 { background: #0e4429; } .sglv-ptcal-day.lv2 { background: #006832; } .sglv-ptcal-day.lv3 { background: #26a641; } .sglv-ptcal-day.lv4 { background: #39d353; color: #062b13; } /*当月入库时间线(常驻展示,倒序:月末 → 月初) —— 选中态背景色与该日在月历中的「入库数量色阶」同色(lv1~lv4), --ptcal-c 为该级实色(描边/左侧色条),--ptcal-c-soft 为同色低透明背景。 */ /*tl-body 不设 max-height——滚动由 .sglv-ptcal-timeline 容器承担 (v2.20.1 曾由外层 pane 统一滚动, 现日历区固定后时间线独立滚动), 分组不再被截断。 */ /* 时间线 = **详情区自己的滚动容器**(滚动条就在详情区内,用户可直接看到并悬停滚动)。 min-height:140px 是「详情绝不被压成几像素」的硬保证:极窄而高的窗口 (如 1080×1000 命中 max-width:1200px 的 4 列断行,月历变3 行 ~680px) 也不会把详情挤没 —— 此时由 pane 滚动承载,超出部分仍可达。 scrollbar-gutter:stable 让滚动条常驻占位,避免内容随滚动条出现/消失抖动。 */ .sglv-ptcal-timeline { flex: 1 1 auto; min-height: 140px; overflow-y: auto; overscroll-behavior: contain; border-top: 1px dashed var(--sglv-border-subtle, rgba(102,192,244,.13)); padding: 0 2px 4px 0; scrollbar-gutter: stable; } /* 矮视口紧凑月历(视口高 ≤900px):12 张标准月卡(~450px) + 详情可视区无法在 800px 视口的 ~598px pane 内共存。这里把月卡切紧凑档(卡宽 240→170px、 内距/日格间距收紧),两行总高降到 ~390px,释放的高度全部给详情区, 实现「选择器完整 + 详情可滚动」同时成立;日格仍有 ~22px,鼠标点击可用。 */ @media (max-height: 900px) { .sglv-ptcal-grid { grid-template-columns: repeat(6, minmax(0, 170px)); gap: 8px 6px; } .sglv-ptcal-month { padding: 6px 6px 4px; } .sglv-ptcal-month-head { margin-bottom: 3px; } .sglv-ptcal-week, .sglv-ptcal-days { gap: 1px; } .sglv-ptcal-day { font-size: 8.5px; border-radius: 2px; } .sglv-ptcal-wd { font-size: 8px; padding-bottom: 0; } .sglv-ptcal-group-games { grid-template-columns: repeat(auto-fill, minmax(170px, 1fr)); } } /*分组头吸顶——时间线滚动时「当月入库时间线」标题钉在详情区顶部 (自带底色遮住滚过的内容, 底部投影提示分层) v2.22.6: 底色改走 token(原为硬编码 #16202d,浅色主题下是一块深色补丁) */ .sglv-ptcal-tl-head { position: sticky; top: 0; z-index: 1; display: flex; align-items: baseline; gap: 8px; flex-wrap: wrap; padding: 6px 0 8px; margin-bottom: 0; background: var(--sglv-surface-deep, #16202d); box-shadow: 0 10px 12px -10px rgba(0,0,0,0.65); } .sglv-ptcal-tl-title { font-size: 12px; font-weight: 700; color: #fff; display: inline-flex; align-items: center; gap: 6px; } .sglv-ptcal-tl-title svg { width: 13px; height: 13px; color: var(--sglv-accent, #66c0f4); } .sglv-ptcal-tl-month { font-variant-numeric: tabular-nums; color: var(--sglv-accent, #66c0f4); } .sglv-ptcal-tl-hint { font-size: 11px; color: var(--sglv-text-secondary, #8a9ba8); line-height: 1.5; } .sglv-ptcal-tl-body { display: flex; flex-direction: column; gap: 6px; } .sglv-ptcal-group { border: 1px solid rgba(255,255,255,0.06); border-left: 3px solid transparent; border-radius: 8px; background: rgba(255,255,255,0.02); padding: 6px 8px; transition: var(--sglv-transition); } .sglv-ptcal-group.lv1 { --ptcal-c: #0e4429; --ptcal-c-soft: rgba(14,68,41,0.55); } .sglv-ptcal-group.lv2 { --ptcal-c: #006832; --ptcal-c-soft: rgba(0,104,50,0.52); } .sglv-ptcal-group.lv3 { --ptcal-c: #26a641; --ptcal-c-soft: rgba(38,166,65,0.34); } .sglv-ptcal-group.lv4 { --ptcal-c: #39d353; --ptcal-c-soft: rgba(57,211,83,0.28); } .sglv-ptcal-group.sel { background: var(--ptcal-c-soft); border-color: var(--ptcal-c); box-shadow: 0 0 0 1px var(--ptcal-c); } .sglv-ptcal-group-head { display: flex; align-items: center; gap: 7px; cursor: pointer; } .sglv-ptcal-group-date { font-size: 12px; font-weight: 700; color: var(--ptcal-c, #fff); font-variant-numeric: tabular-nums; } .sglv-ptcal-group.lv4 .sglv-ptcal-group-date { color: #6ee87a; } .sglv-ptcal-group-wd { font-size: 10px; color: #64748b; } .sglv-ptcal-group-count { font-size: 10px; font-weight: 700; color: var(--ptcal-c, #c7d5e0); border: 1px solid var(--ptcal-c, rgba(255,255,255,0.2)); background: var(--ptcal-c-soft, rgba(255,255,255,0.06)); border-radius: 999px; padding: 0 8px; margin-left: auto; } .sglv-ptcal-group.lv4 .sglv-ptcal-group-count { color: #eafff0; } /*游戏条目轨道 200px→190px:单条可用宽度从 ~150px 提到 ~180px, 「永远消失的幻想乡 ~The Story of...」这类长名不再被压到只剩三四个字。 */ .sglv-ptcal-group-games { display: grid; grid-template-columns: repeat(auto-fill, minmax(190px, 1fr)); gap: 2px 10px; margin-top: 5px; } .sglv-ptcal-detail-item { display: flex; align-items: center; gap: 7px; padding: 3px 6px; border-radius: 5px; font-size: 12px; color: #c7d5e0; cursor: pointer; min-width: 0; } .sglv-ptcal-detail-item:hover { background: rgba(102,192,244,0.14); color: #fff; } .sglv-ptcal-detail-item img { width: 16px; height: 16px; border-radius: 3px; flex-shrink: 0; } .sglv-ptcal-detail-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .sglv-ptcal-detail-hours { flex-shrink: 0; font-size: 10px; font-weight: 600; color: #fbbf24; font-variant-numeric: tabular-nums; } .sglv-ptcal-detail-empty { font-size: 11px; color: var(--sglv-text-secondary, #8a9ba8); padding: 4px 0; } @media (max-width: 900px) { .sglv-ptcal-summary { margin-left: 0; } } `; const CSS_INLINE = [ CSS_ACHIEVEMENT, CSS_SHOWCASE, CSS_CLOUDSAVE, CSS_STAGE, CSS_HEADER, CSS_SGIS_ENHANCE, CSS_TOAST, CSS_APIKEY_CONSENT, CSS_SETTINGS, CSS_KPI, CSS_SUBSTATUS, CSS_COVER, CSS_PRICE, CSS_LOAD, CSS_ALIAS, CSS_PLAYDATA, CSS_LIST_FIX, CSS_MENU ].join(''); GM_addStyle(CSS_INLINE); const SGLV_THEMES = { purple: { id: 'purple', zh: '典雅紫', en: 'Elegant Purple', css: () => CSS_THEME_PURPLE }, blue: { id: 'blue', zh: '经典蓝', en: 'Classic Blue', css: () => CSS_THEME_BLUE }, }; const DEFAULT_SGLV_THEME = 'purple'; function getThemeId() { try { const v = storage.getUiTheme(); return SGLV_THEMES[v] ? v : DEFAULT_SGLV_THEME; } catch (e) { return DEFAULT_SGLV_THEME; } } function applySglvTheme(id) { const theme = SGLV_THEMES[id] || SGLV_THEMES[DEFAULT_SGLV_THEME]; document.documentElement.setAttribute('data-sglv-theme', theme.id); let el = document.getElementById('sglv-theme-style'); if (!el) { el = document.createElement('style'); el.id = 'sglv-theme-style'; } el.textContent = theme.css(); document.head.appendChild(el); window.dispatchEvent(new CustomEvent('sglv-theme-changed', { detail: { themeId: theme.id } })); return theme.id; } const isZh = (navigator.language || '').toLowerCase().startsWith('zh'); const T = { title: isZh ? '游戏库' : 'Game Library', tabOwned: isZh ? '游戏橱窗' : 'Game Showcase', tabShowcase: isZh ? '个人展柜' : 'Showcase', tabPublisher: isZh ? '系列分类' : 'By Series', tabTrend: isZh ? '入库趋势' : 'Acquisition Trends', trendChartTitle: isZh ? '入库趋势图' : 'Trend Chart', trendTimelineTitle: isZh ? '入库时间线' : 'Acquisition Timeline', trendTimelineTotal: isZh ? '入库总数' : 'Total', trendFreqTitle: isZh ? '入库频率分析' : 'Acquisition Frequency', trendTabTimeline: isZh ? '入库时间线' : 'Timeline', trendTabFrequency: isZh ? '频率分析' : 'Frequency', trendKpiThisYear: isZh ? '今年入库' : 'This Year', trendKpiAvgYear: isZh ? '年均入库' : 'Avg / Year', trendKpiPeakYear: isZh ? '峰值年份' : 'Peak Year', trendKpiRecent30: isZh ? '近30天' : 'Last 30 Days', trendKpiRecent90: isZh ? '近90天' : 'Last 90 Days', trendKpiActiveDays: isZh ? '活跃天数' : 'Active Days', trendKpiWeeklyAvg: isZh ? '周均入库' : 'Weekly Avg', trendKpiGames: isZh ? '款' : 'games', trendFreqByMonth: isZh ? '月度入库频率' : 'Monthly Frequency', trendFreqByWeekday: isZh ? '星期分布' : 'Weekday Distribution', trendFreqByHour: isZh ? '时段分布' : 'Hourly Distribution', trendFreqSummary: isZh ? '频率摘要' : 'Frequency Summary', trendFreqPeakMonth: isZh ? '最活跃月份' : 'Peak Month', trendFreqPeakWeekday: isZh ? '最活跃星期' : 'Peak Weekday', trendFreqPeakHour: isZh ? '最活跃时段' : 'Peak Hour', trendFreqStreak: isZh ? '最长连续天数' : 'Longest Streak', trendFreqDays: isZh ? '天' : 'days', trendFreqWeekdayLong: isZh ? '周日,周一,周二,周三,周四,周五,周六' : 'Sun,Mon,Tue,Wed,Thu,Fri,Sat', trendFreqHrLabel: isZh ? '时' : 'h', tabSettings: isZh ? '设置' : 'Settings', searchPlaceholder: isZh ? '搜索游戏名称...' : 'Search game name...', noData: isZh ? '暂无游戏数据,请点击右上角刷新按钮' : 'No game data. Click the refresh button at the top right.', noApiKey: isZh ? '请先登录 Steam 商店,或在设置中配置 API Key' : 'Login to Steam Store or configure API Key in Settings.', apiKeyLabel: 'Steam Web API Key', steamIdLabel: isZh ? 'SteamID64(留空自动检测)' : 'SteamID64 (auto-detect if empty)', save: isZh ? '保存设置' : 'Save', saved: isZh ? '已保存' : 'Saved', totalGames: isZh ? '总游戏数' : 'Total Games', ownedInDb: isZh ? '数据库已拥有' : 'Owned in DB', missingInDb: isZh ? '数据库未拥有' : 'Missing in DB', ownership: isZh ? '拥有率' : 'Ownership', page: isZh ? '页' : 'Page', prev: isZh ? '上一页' : 'Prev', next: isZh ? '下一页' : 'Next', first: isZh ? '首页' : 'First', last: isZh ? '末页' : 'Last', jumpTo: isZh ? '跳至' : 'Go to', pageOf: isZh ? '共' : 'of', owned: isZh ? '已拥有' : 'Owned', missing: isZh ? '未拥有' : 'Missing', all: isZh ? '全部' : 'All', cardView: isZh ? '卡片' : 'Card', coverView: isZh ? '横版封面' : 'Wide Cover', listView: isZh ? '列表' : 'List', fetchSuccess: isZh ? '获取成功,共 {n} 款游戏' : 'Fetched {n} games', fetchFail: isZh ? '获取失败' : 'Fetch failed', apiKeyHelp: isZh ? '脚本会自动从 Steam 商店页面获取登录凭证(access_token),无需配置 API Key 即可使用。如需获取更多数据(如游戏时长),可配置 <b>API Key</b>:打开 <a href="https://steamcommunity.com/dev/apikey" target="_blank">steamcommunity.com/dev/apikey</a> → 填写域名 → 注册即可。' : 'The script auto-detects login credentials from the Steam store page. API Key is optional for extra data (playtime). Get a free <b>API Key</b>: Visit <a href="https://steamcommunity.com/dev/apikey" target="_blank">steamcommunity.com/dev/apikey</a> → Enter domain → Register.', tabDelisted: isZh ? '绝版游戏' : 'Delisted Games', delistedTotal: isZh ? '绝版总数' : 'Total Delisted', delistedOwned: isZh ? '已拥有绝版' : 'Owned Delisted', delistedMissing: isZh ? '未拥有绝版' : 'Missing Delisted', delistedOwnership: isZh ? '绝版拥有率' : 'Delisted Ownership', delistedSearch: isZh ? '搜索绝版游戏...' : 'Search delisted games...', typeAll: isZh ? '全部类型' : 'All Types', typeDelisted: isZh ? '已下架' : 'Delisted', typePurchaseDisabled: isZh ? '购买已禁用' : 'Purchase Disabled', typeF2P: isZh ? 'F2P不可用' : 'F2P Unavailable', typeRetailOnly: isZh ? '仅零售' : 'Retail Only', typeTestApp: isZh ? '测试应用' : 'Test App', delistedOwners: isZh ? '拥有占比' : 'Owner %', delistedDate: isZh ? '下架时间' : 'Delisted Date', delistedAchievements: isZh ? '成就数' : 'Achievements', delistedKeyshops: isZh ? 'Keyshop价格' : 'Keyshop Price', tabPlaytime: isZh ? '统计仪表' : 'Stats', tabPlaydata: isZh ? '游玩数据' : 'Play Data', tabAchievements: isZh ? '我的成就' : 'Achievements', achCategoryCollector: isZh ? '收藏成就' : 'Collection', achCategoryPlaytime: isZh ? '时长成就' : 'Playtime', achCategoryMastery: isZh ? '专精成就' : 'Mastery', achCategoryDiversity: isZh ? '多元成就' : 'Diversity', achCategoryLoyalty: isZh ? '忠诚成就' : 'Loyalty', achCategorySpecial: isZh ? '特殊成就' : 'Special', achUnlocked: isZh ? '已解锁' : 'Unlocked', achLocked: isZh ? '未解锁' : 'Locked', achProgress: isZh ? '进度' : 'Progress', achNoData: isZh ? '暂无成就数据,请先获取游戏库' : 'No achievement data. Please fetch your library first.', achSummary: isZh ? '成就总览' : 'Achievement Summary', achSummaryDesc: isZh ? '已解锁' : 'Unlocked', achPoints: isZh ? '成就点数' : 'Points', achRarityCommon: isZh ? '普通' : 'Common', achRarityRare: isZh ? '稀有' : 'Rare', achRarityEpic: isZh ? '史诗' : 'Epic', achRarityLegendary: isZh ? '传奇' : 'Legendary', achRecentUnlocks: isZh ? '最近解锁' : 'Recent Unlocks', achTotalPoints: isZh ? '总成就点数' : 'Total Points', achCompletionRate: isZh ? '完成率' : 'Completion', achUnlockedAt: isZh ? '解锁于' : 'Unlocked at', achNoUnlocks: isZh ? '暂无已解锁成就' : 'No achievements unlocked yet', achResetConfirm: isZh ? '确定要重置所有成就解锁记录吗?此操作不可撤销。' : 'Reset all achievement unlock records? This cannot be undone.', achResetBtn: isZh ? '重置记录' : 'Reset', achAllCats: isZh ? '全部' : 'All', globalSearchPh: isZh ? '搜索游戏(中文/拼音/英文)' : 'Search games (CN/Pinyin/EN)', gsHeader: isZh ? '搜索结果' : 'Search Results', gsEmpty: isZh ? '未匹配到游戏,试试中文/拼音首字母/英文子串' : 'No matches. Try CN/pinyin/English substring', gsMinLen: isZh ? '至少输入 1 个字符' : 'Type at least 1 character', gsTypeOwned: isZh ? '已拥有' : 'Owned', gsTypeWishlist: isZh ? '愿望单' : 'Wishlist', gsTypeStore: isZh ? '商店' : 'Store', gsType: isZh ? '类型' : 'Type', gsFooterHint: isZh ? '↑↓ 选择 · Enter 跳转 · Esc 关闭' : '↑↓ Navigate · Enter Open · Esc Close', gsOpenStore: isZh ? '在 Steam 商店打开' : 'Open in Steam Store', gsJumpToOwned: isZh ? '跳转到游戏库' : 'Jump to Library', gsJumpToWishlist: isZh ? '跳转到愿望单' : 'Jump to Wishlist', dpLoading: isZh ? '正在获取游戏详情…' : 'Loading game details…', dpError: isZh ? '获取详情失败' : 'Failed to load details', dpRetry: isZh ? '重试' : 'Retry', dpDeveloper: isZh ? '开发商' : 'Developer', dpPublisher: isZh ? '发行商' : 'Publisher', dpRelease: isZh ? '发行日期' : 'Release Date', dpPlatforms: isZh ? '平台' : 'Platforms', dpGenres: isZh ? '类型' : 'Genres', dpCategories: isZh ? '特色' : 'Features', dpPrice: isZh ? '价格' : 'Price', dpFree: isZh ? '免费' : 'Free', dpScreenshots: isZh ? '截图' : 'Screenshots', dpStorePage: isZh ? '商店页' : 'Store Page', dpJumpLib: isZh ? '跳转到游戏库' : 'Jump to Library', dpJumpWl: isZh ? '跳转到愿望单' : 'Jump to Wishlist', ptTotalHours: isZh ? '总游玩时长' : 'Total Hours', ptAvgHours: isZh ? '平均时长' : 'Avg Hours', ptPlayedCount: isZh ? '已游玩' : 'Played', ptUnplayedCount: isZh ? '从未游玩' : 'Unplayed', ptPlayRate: isZh ? '游玩率' : 'Play Rate', ptCompletion: isZh ? '完成度' : 'Completion', ptDistTitle: isZh ? '时长分布' : 'Playtime Distribution', ptTopTitle: isZh ? '游玩时长 Top 20' : 'Top 20 by Playtime', ptAllTitle: isZh ? '全部游戏(按时长排序)' : 'All Games (by Playtime)', ptSearchPlaceholder: isZh ? '搜索游戏名称...' : 'Search game name...', ptHeroRecent: isZh ? '近2周时长' : '2-Week Hours', ptHeroRecentSub: isZh ? '需配置 API Key' : 'API key required', ptHeroLongest: isZh ? '最长单游' : 'Longest Game', ptHeroMedian: isZh ? '中位数' : 'Median', ptHeroMedianSub: isZh ? '已游玩 {n} 款的中位' : 'median of {n} played', ptHeroMedianNone: isZh ? '从未游玩' : 'never played', ptConcTitle: isZh ? '时长集中度' : 'Playtime Concentration', ptConcTop: isZh ? '前 {n} 款占全部游玩时长的 {p}%' : 'Top {n} games account for {p}% of total playtime', ptConcHalf: isZh ? ',前 {n} 款即吃掉一半时长' : ', top {n} reach 50%', ptActTitle: isZh ? '活跃度分层(按最近游玩)' : 'Activity Layers (by Last Played)', ptActHint: isZh ? '点击任一分层查看该层排行' : 'Click a layer to open its ranking', ptDustScanning: isZh ? '正在统计吃灰游戏…' : 'Scanning idle games…', ptDustView: isZh ? '查看吃灰榜' : 'View idle list', ptDustText: isZh ? '入库超 1 年却从未启动' : 'Owned over a year, never launched', ptPlayTabLabel: isZh ? '游玩分析' : 'Play Analysis', ptPlayDistTitle: isZh ? '时长分档分布' : 'Playtime Distribution', ptPlayDistModeCount: isZh ? '按游戏数' : 'By count', ptPlayDistModeHours: isZh ? '按时长' : 'By hours', ptPlayInsightTitle: isZh ? '玩家画像(5 维)' : 'Player Profile (5 dims)', ptPlayInsightSub: isZh ? '本地规则推断,非 AI 评分' : 'Local rule-based, not AI scoring', ptPlayRecentTitle: isZh ? '最近两周游玩' : 'Last 2 Weeks', ptPlayRecentEmpty: isZh ? '最近两周没有游玩记录' : 'No play in the last 2 weeks', ptPlayRecentNeedKey: isZh ? '需要 Steam Web API Key 才能读取近两周时长' : 'Steam Web API Key required for 2-week playtime', ptPlaySciTitle: isZh ? '剧情完成度(SCI)' : 'Story Completion (SCI)', ptPlaySciSub: isZh ? '累计时长 ÷ 剧情基准时长,衡量你玩到了主线的多少' : 'Total playtime / story baseline', ptPlaySciNoData: isZh ? '暂无剧情时长数据(未接入 HLTB 索引)' : 'No story-length data (HLTB index not loaded)', ptPlaySciSample: isZh ? '基于 {n} 款有剧情数据的游戏' : 'Based on {n} games with story data', ptPlayRadarEmpty: isZh ? '洞察数据不可用' : 'Insight data unavailable', ptPlayTitle: isZh ? '游玩分析' : 'Play Analysis', ptLibTabLabel: isZh ? '库分析' : 'Library Analysis', ptLibEraTitle: isZh ? '发行年代分布' : 'Release Era Distribution', ptLibEraScope: isZh ? 'Steam 可用部分' : 'Steam-available subset', ptLibEraRef: isZh ? 'HLTB 全量参考' : 'HLTB full population', ptLibEraBias: isZh ? '样本偏差 {n}pt —— 主机独占游戏未计入,实际年代更早' : 'Sample bias {n}pt — console-exclusive titles excluded', ptLibGenTitle: isZh ? '类型分布' : 'Genre Distribution', ptLibSilTitle: isZh ? '沉默库存' : 'Silent Stock', ptLibSilDesc: isZh ? '已入库但从未启动 · 按剧情时长从短到长(最容易救回)· 前 10 款' : 'Never launched · shortest story first · top 10', ptPotTabLabel: isZh ? '潜力清单' : 'Potentials', ptPotFastTitle: isZh ? '最快通关' : 'Fastest to Finish', ptPotTasteTitle: isZh ? '口味最对' : 'Best Taste Match', ptPotSilentTitle: isZh ? '沉默库存' : 'Silent Stock', ptPotEmpty: isZh ? '暂无匹配结果(口味画像或标签数据不足)' : 'No matches (insufficient taste/tag data)', ptPotEstHours: isZh ? '预计 {h} 小时' : '~{h}h est.', ptAllOpenBtn: isZh ? '全部游戏排行' : 'All Games', ptAllOpenTip: isZh ? '打开全部游戏时长排行(全屏浮窗)' : 'Open full playtime ranking (fullscreen)', ptWinTabAll: isZh ? '全部游戏' : 'All Games', ptWinTabFamily: isZh ? '家庭对比' : 'Family Compare', ptWinTabCalendar: isZh ? '入库月历' : 'Entry Calendar', ptCalLoading: isZh ? '正在获取入库时间…' : 'Loading acquisition times…', ptCalNoData: isZh ? '未获取到入库时间数据' : 'No acquisition data available', ptCalNoDataHint: isZh ? '入库月历依赖家庭组共享库/个人许可页的入库时间,请先登录 Steam 后重试' : 'The calendar needs acquisition times from the family library / licenses page. Sign in to Steam and retry.', ptCalYearTotal: isZh ? '本年入库' : 'Acquired this year', ptCalPeakMonth: isZh ? '最猛月份' : 'Peak month', ptCalPeakDay: isZh ? '单日峰值' : 'Peak day', ptCalMonthsCovered: isZh ? '覆盖月份' : 'Months covered', ptCalUnit: isZh ? '款' : 'games', ptCalThisYear: isZh ? '今年' : 'This year', ptCalNoDataThisYear: isZh ? '当前筛选集在今年暂无入库记录' : 'No entries this year in the current filter', ptMenuGameData: isZh ? '游戏数据' : 'Game Data', ptMenuOpenPanel: isZh ? '打开游戏库面板' : 'Open Library Panel', ptMenuOpenPanelTip: isZh ? '打开中央游戏库面板(橱窗 / 时长 / 洞察 / 愿望单等)' : 'Open the central library panel', ptMenuGameDataTip: isZh ? '全部游戏排行 / 家庭对比 / 入库月历(全屏浮窗)' : 'All games ranking / Family compare / Entry calendar (fullscreen)', ptMenuDataEmpty: isZh ? '游戏库数据尚未加载,请先打开面板等待数据加载' : 'Library data not loaded yet — open the panel and wait', ptCalTimeline: isZh ? '当月入库时间线' : 'This Month Timeline', ptCalTimelineHint: isZh ? '按时间倒序(月末 → 月初)· 点击日历中的色块日期可高亮当天记录' : 'Reverse-chronological (month-end → month-start) · click a colored day to highlight its records', ptCalTimelineEmpty: isZh ? '本月暂无入库记录' : 'No entries this month', ptCalTimelineEmptyHint: isZh ? '点击月历中有色块的日期,即可查看并高亮当天记录' : 'Click a colored day in the calendar to view and highlight its records', ptCalOpenStore: isZh ? '在 Steam 商店打开' : 'Open in Steam Store', ptCalPrevYear: isZh ? '上一年' : 'Previous year', ptCalNextYear: isZh ? '下一年' : 'Next year', ptCalFuture: isZh ? '未到时间' : 'Not yet', ptSortPlaytime: isZh ? '时长降序' : 'Playtime', ptSortRecent: isZh ? '最近游玩' : 'Last Played', ptSortAcquired: isZh ? '入库时间' : 'Acquired', ptSortName: isZh ? '名称' : 'Name', ptSortAcquiredLoading: isZh ? '正在获取入库时间…' : 'Loading acquisition times…', ptFilterUnplayed: isZh ? '隐藏从未游玩' : 'Hide unplayed', ptFilterShared: isZh ? '隐藏家庭共享' : 'Hide family shared', ptSortAsc: isZh ? '↑ 正序' : '↑ Asc', ptSortDesc: isZh ? '↓ 倒序' : '↓ Desc', ptCalPersonalOnly: isZh ? '仅个人游戏' : 'Personal only', ptCalPersonalOnlyTip: isZh ? '月历与时间线仅统计本人拥有的游戏(排除家庭共享入库)' : 'Count only games owned by me (exclude family-shared entries)', ptCalPersonalEmpty: isZh ? '该筛选集内个人游戏暂无入库记录' : 'No personal-only entries in this filter', ptZeroPtHint: isZh ? '该列表内游戏均为 0 时长,时长列无法区分先后——按入库时间/最近游玩倒序兜底排列' : 'All games here have 0 playtime; fallback order (acquired / last played) is applied.', ptSortAcquiredEmpty: isZh ? '未获取到入库时间,已回退时长排序' : 'No acquisition data — fell back to playtime sorting', ptWeeklyUpdated: isZh ? '游玩时长已按周增量更新({n} 款变化)' : 'Playtime updated weekly ({n} changed)', ptFamRefreshTip: isZh ? '刷新家庭成员数据(默认按周缓存)' : 'Refresh family data (weekly cache)', ptFamTop20: isZh ? 'Top 20 游玩时长' : 'Top 20 Playtime', ptFamNoGames: isZh ? '暂无游玩时长数据' : 'No playtime data', ptFamPrivate: isZh ? '获取失败,该成员资料可能为私密' : 'Failed — profile may be private', ptRange0: isZh ? '从未游玩' : 'Never Played', ptRange1: isZh ? '0-1 小时' : '0-1 hours', ptRange2: isZh ? '1-10 小时' : '1-10 hours', ptRange3: isZh ? '10-50 小时' : '10-50 hours', ptRange4: isZh ? '50-100 小时' : '50-100 hours', ptRange5: isZh ? '100-500 小时' : '100-500 hours', ptRange6: isZh ? '500+ 小时' : '500+ hours', ptHours: isZh ? '小时' : 'hours', ptLastPlayed: isZh ? '最近游玩' : 'Last Played', ptNever: isZh ? '从未' : 'Never', ptNoData: isZh ? '暂无游玩时长数据,请先获取游戏库' : 'No playtime data. Fetch library first.', ptDays: isZh ? '天前' : 'days ago', ptFamilyCompare: isZh ? '家庭成员游玩时长对比' : 'Family Playtime Comparison', ptFetchingFamily: isZh ? '正在获取家庭成员数据…' : 'Fetching family data…', ptNoFamily: isZh ? '未加入家庭组或未配置 API Key' : 'No family group or API Key', ptNoApiKey: isZh ? '请先在设置中配置 API Key' : 'Configure API Key in settings first', ptNoToken: isZh ? '请先点击面板刷新按钮获取家庭组信息' : 'Click refresh to fetch family info first', ptRetryBtn: isZh ? '重试' : 'Retry', ptLibHeatmap: isZh ? '入库热力图' : 'Library Heatmap', ptHeatmapNoData: isZh ? '暂无入库时间数据' : 'No acquisition time data', ptHeatmapLoading: isZh ? '加载中…' : 'Loading…', ptPending: isZh ? '待加入' : 'Pending', ptHeatmapTotal: isZh ? '总' : 'Total', ptHeatmapPeak: isZh ? '峰值' : 'Peak', ptHeatmapAvg: isZh ? '日均' : 'Avg/day', ptHeatmapLess: isZh ? '少' : 'Less', ptHeatmapMore: isZh ? '多' : 'More', ptHeatmapAcquired: isZh ? '款入库' : 'acquired', ptHeatmapAll: isZh ? '全部' : 'All', ptHeatmapMini6m: isZh ? '近6月入库增量' : '6-Month Acquisitions', refreshBtnTitle: isZh ? '通过 API Key 刷新游戏库与时长' : 'Refresh library & playtime via API Key', refreshSuccess: isZh ? '游戏库与时长已刷新' : 'Library & playtime refreshed', categoryAll: isZh ? '全部' : 'All', categoryPlayed: isZh ? '已游玩' : 'Played', categoryUnplayed: isZh ? '未游玩' : 'Unplayed', categoryShared: isZh ? '共享' : 'Shared', categoryOwned: isZh ? '仅自己' : 'Owned Only', categoryBundled: isZh ? '进过包' : 'Bundled', categoryCards: isZh ? '有卡牌' : 'Has Cards', statsBundled: isZh ? '进包游戏' : 'Bundled Games', statsCards: isZh ? '有卡游戏' : 'Card Games', kpiInBundles: isZh ? '曾出现在 bundle 中' : 'appeared in bundles', kpiHasCards: isZh ? '含集换式卡牌' : 'has trading cards', sortBundleDesc: isZh ? '进包次数 多→少' : 'Bundle count ↓', bundleBadgeTip: isZh ? '曾出现在' : 'Appeared in', bundleBadgeUnit: isZh ? '个 bundle 中' : ' bundles', categoryDlcOnly: isZh ? '仅 DLC' : 'DLC Only', statsDlcTotal: isZh ? 'DLC 总数' : 'DLC Total', kpiDlcMusic: isZh ? '音乐' : 'Music', kpiDlcBundled: isZh ? '进包' : 'Bundled', sortLabel: isZh ? '排序方式' : 'Sort by', sortAppidAsc: isZh ? 'AppID 小→大' : 'AppID ↑', sortAppidDesc: isZh ? 'AppID 大→小' : 'AppID ↓', sortNameAsc: isZh ? '名称 A→Z' : 'Name A–Z', sortAcquiredDesc: isZh ? '入库 新→旧' : 'Newest first', sortAcquiredAsc: isZh ? '入库 旧→新' : 'Oldest first', sortPlaytimeDesc: isZh ? '时长 多→少' : 'Most played', sortLastPlayedDesc: isZh ? '最近游玩' : 'Recently played', statsTotalGames: isZh ? '总游戏数' : 'Total Games', statsTotalHours: isZh ? '总时长 (h)' : 'Total Hours', statsPlayed: isZh ? '已游玩' : 'Played', statsUnplayed: isZh ? '未游玩' : 'Unplayed', statsShared: isZh ? '共享游戏' : 'Shared Games', kpiAvgHours: isZh ? '均' : 'Avg', kpiPerGame: isZh ? '/款' : '/game', kpiRate: isZh ? '占比' : 'Rate', kpiOfTotal: isZh ? '占总数' : 'of total', kpiPlayRateSub: isZh ? '已启动 ÷ 全部' : 'started ÷ total', kpiCompletionSub: isZh ? '深度游玩 ≥10h' : 'deep play ≥10h', kpiFromFamily: isZh ? '来自家庭组' : 'from family', kpiHours: isZh ? '小时' : 'hours', kpiMyCollection: isZh ? '我的收藏' : 'My Collection', kpiDedupMerge: isZh ? '合并去重' : 'Deduplicated', kpiFamilyMembers: isZh ? '位家庭成员' : 'family members', kpiYearSpan: isZh ? '年跨度' : 'year span', kpiDelisted: isZh ? '款绝版' : 'delisted', kpiCollected: isZh ? '已收藏' : 'collected', kpiToCollect: isZh ? '待收藏' : 'to collect', kpiCollectionProgress: isZh ? '收藏进度' : 'Collection Progress', delistedSubAll: isZh ? '全部绝版' : 'All Delisted', delistedSubOwned: isZh ? '已拥有' : 'Owned', delistedSubMissing: isZh ? '未拥有' : 'Missing', ptSourceApi: isZh ? 'API' : 'API', ptSourceScrape: isZh ? '页面抓取' : 'Scraped', ptTrendTitle: isZh ? '时长趋势' : 'Playtime Trend', ptTrendMonth: isZh ? '月' : 'Month', ptTrendQuarter: isZh ? '季' : 'Quarter', ptTrendYear: isZh ? '年' : 'Year', aiSettingsTitle: isZh ? 'AI 模型配置' : 'AI Model Settings', aiApiUrlLabel: isZh ? 'AI API 地址' : 'AI API URL', aiApiKeyLabel: isZh ? 'AI API Key' : 'AI API Key', aiModelLabel: isZh ? '模型名称' : 'Model Name', aiApiUrlHelp: isZh ? '默认为 DeepSeek 官方 API 地址,也可填入其他兼容 OpenAI 格式的 API 地址' : 'Default is DeepSeek official API URL. Also supports OpenAI-compatible API endpoints.', aiModelHelp: isZh ? '默认为 deepseek-v4-pro,可修改为其他模型名称' : 'Default is deepseek-v4-pro. Can be changed to other model names.', aiNotConfigured: isZh ? '未配置 AI API Key,请在设置中配置' : 'AI API Key not configured. Set it in Settings.', aiTranslating: isZh ? 'AI 翻译总结中…' : 'AI translating & summarizing…', aiTranslateFail: isZh ? 'AI 翻译失败' : 'AI translation failed', aiToggleOriginal: isZh ? '原文' : 'Original', aiToggleSummary: isZh ? 'AI翻译总结' : 'AI Summary', aiSharedHint: isZh ? '检测到 Steam AI Agent 插件,AI 配置已自动共享' : 'Steam AI Agent detected, AI config is shared automatically', ptNoActivity: isZh ? '近期无游玩活动' : 'No recent activity', globalSettings: isZh ? '全局设置' : 'Global Settings', themeSection: isZh ? '外观主题' : 'Appearance', themeDesc: isZh ? '选择界面配色主题,保存后立即生效(无需刷新页面)。' : 'Pick the UI color theme. Applies instantly on save (no reload needed).', themePurpleDesc: isZh ? '紫青炫彩主调 · 默认' : 'Violet accent · default', themeBlueDesc: isZh ? 'Steam 经典蓝主调' : 'Steam classic blue accent', settingsBack: isZh ? '返回游戏库' : 'Back to Library', steamApiSection: isZh ? 'Steam API 配置' : 'Steam API Settings', itadSection: isZh ? 'ITAD 价格增强' : 'ITAD Price Enhancement', itadApiKeyLabel: 'ITAD API Key', itadDesc: isZh ? '配置 ITAD (IsThereAnyDeal) API 密钥后,价格页面将增强为<b style="color:#a7d54f">15+ 区域比价</b>、<b style="color:#a7d54f">多商店价格对比</b>(GOG/Fanatical/Humble 等)、<b style="color:#a7d54f">活跃 Bundle</b> 展示及<b style="color:#a7d54f">历史最低价</b>徽章。未配置时自动回退到基础模式。' : 'With an ITAD API key, the price tab enhances to <b style="color:#a7d54f">15+ region comparison</b>, <b style="color:#a7d54f">multi-store pricing</b> (GOG/Fanatical/Humble), <b style="color:#a7d54f">active bundles</b>, and <b style="color:#a7d54f">historical low</b> badges. Falls back to basic mode if not configured.', itadKeyPlaceholder: '32位十六进制密钥 (如 a9d468...14b725)', itadTestConn: isZh ? '测试连接' : 'Test Connection', itadTesting: isZh ? '测试中…' : 'Testing…', itadConnSuccess: isZh ? '连接成功' : 'Connected', itadConnFail: isZh ? '连接失败' : 'Failed', itadConnNoKey: isZh ? '未配置' : 'Not configured', itadHelpTitle: isZh ? '密钥申请方法' : 'How to get a key', itadHelpSteps: isZh ? '① 访问 <a href="https://isthereanydeal.com" target="_blank" style="color:#66c0f4">isthereanydeal.com</a> → 注册账号并<b>验证邮箱</b>(影响速率限额)<br>② 进入 <a href="https://isthereanydeal.com/apps" target="_blank" style="color:#66c0f4">isthereanydeal.com/apps</a> → 点击 <b>Register App</b><br>③ 填写应用名称(不可与他人重复)→ <b>Submit</b><br>④ 在 <b>API Keys</b> 区域复制 32 位密钥 → 粘贴到上方输入框<br>⑤ 点击「测试连接」验证 → 保存设置即可生效<br><span style="color:#555">限额:每 5 分钟 1000 次请求 · 可商用但需标注 ITAD 来源</span>' : '① Visit <a href="https://isthereanydeal.com" target="_blank" style="color:#66c0f4">isthereanydeal.com</a> → Register & <b>verify email</b> (affects rate limit)<br>② Go to <a href="https://isthereanydeal.com/apps" target="_blank" style="color:#66c0f4">isthereanydeal.com/apps</a> → Click <b>Register App</b><br>③ Enter app name (must be unique) → <b>Submit</b><br>④ Copy the 32-char key from <b>API Keys</b> → Paste above<br>⑤ Click "Test Connection" → Save Settings<br><span style="color:#555">Limit: 1000 requests / 5 min · Commercial use OK with ITAD attribution</span>', aiPredictSection: isZh ? 'AI 价格预测配置' : 'AI Price Prediction Settings', aiPredictModes: isZh ? '预测模式' : 'Prediction Modes', aiPredictModesHelp: isZh ? '选择一种或多种预测模式,AI将基于所选模式进行分析' : 'Select one or more prediction modes for AI analysis', aiPredictModeSeasonal: isZh ? '季节性折扣预测' : 'Seasonal Discount', aiPredictModeSeasonalDesc: isZh ? '基于Steam促销活动节点(夏促/秋促/冬促/春促)预测折扣时机' : 'Predict based on Steam sale events (Summer/Autumn/Winter/Spring)', aiPredictModeTrend: isZh ? '价格趋势预测' : 'Price Trend', aiPredictModeTrendDesc: isZh ? '基于历史折扣间隔和幅度趋势预测下次折扣' : 'Predict next discount based on historical intervals and depth trends', aiPredictModeLowest: isZh ? '史低突破预测' : 'Historical Low', aiPredictModeLowestDesc: isZh ? '预测达到或突破历史最低价的可能性与时机' : 'Predict probability and timing of reaching or breaking historical low', aiPredictModeReview: isZh ? '评价动量预测' : 'Review Momentum', aiPredictModeReviewDesc: isZh ? '结合游戏口碑变化趋势评估折扣力度' : 'Assess discount depth based on review momentum changes', aiPredictModeSimilar: isZh ? '相似历史预测' : 'Similar History', aiPredictModeSimilarDesc: isZh ? '匹配相似价格历史片段预测折扣模式' : 'Match similar price history patterns to predict discounts', aiPredictBtn: isZh ? 'AI预测' : 'AI Predict', aiPredicting: isZh ? 'AI预测分析中…' : 'AI predicting…', aiPredictFail: isZh ? 'AI预测失败' : 'AI prediction failed', aiPredictNoData: isZh ? '需要先获取历史价格数据' : 'Need price history data first', aiPredictNoKey: isZh ? '未配置AI API Key,请在设置中配置' : 'AI API Key not configured. Set it in Settings.', aiPredictResult: isZh ? 'AI价格预测分析' : 'AI Price Prediction', aiPredictConfidence: isZh ? '把握度' : 'Confidence', aiPredictDays: isZh ? '天后' : 'days later', aiPredictBestTime: isZh ? '最佳入手时机' : 'Best Time to Buy', aiPredictSaleEvent: isZh ? '促销节点' : 'Sale Event', aiPredictRecommendation: isZh ? '购买建议' : 'Recommendation', tabWishlist: isZh ? '愿望单' : 'Wishlist', wlTotal: isZh ? '愿望单总数' : 'Wishlist Total', wlTotalValue: isZh ? '愿望单总价值' : 'Total Value', wlDiscounted: isZh ? '打折中' : 'On Sale', wlInLibrary: isZh ? '已在库' : 'In Library', wlAvgDiscount: isZh ? '平均折扣' : 'Avg Discount', wlSearch: isZh ? '搜索愿望单游戏...' : 'Search wishlist...', wlNoData: isZh ? '暂无愿望单数据' : 'No wishlist data', wlFetching: isZh ? '正在获取愿望单数据…' : 'Fetching wishlist…', wlFetchFail: isZh ? '愿望单获取失败,请点击右上角刷新按钮重试' : 'Wishlist fetch failed, click refresh to retry', wlFetchSuccess: isZh ? '愿望单获取成功,共 {n} 款' : 'Fetched {n} wishlist items', wlLoadStage1: isZh ? '正在抓取愿望单页面…' : 'Fetching wishlist page…', wlLoadStage2: isZh ? '正在补全商店数据…' : 'Enriching store data…', wlLoadStage3: isZh ? '正在补全游戏详情…' : 'Enriching game details…', wlLoadSub: isZh ? '正在从 Steam 获取愿望单数据,请稍候' : 'Loading wishlist data from Steam, please wait', wlRefreshTip: isZh ? '重新获取愿望单' : 'Refetch wishlist', wlCurveTip: isZh ? '价格历史与史低预测' : 'Price history & low prediction', wlCurveTitle: isZh ? '打折曲线' : 'Price Curve', wlCurveLoading: isZh ? '正在获取历史价格…' : 'Fetching price history…', wlCurveNoData: isZh ? '暂无历史价格数据(可在设置配置 ITAD API Key 获得完整数据)' : 'No price history (configure ITAD API key in settings for full data)', wlCurveLowest: isZh ? '史低' : 'Lowest', wlCurveNow: isZh ? '现价' : 'Now', wlPredictTitle: isZh ? '下次新史低预测' : 'Next Historical Low Prediction', wlPredictDue: isZh ? '已到预测窗口,随时可能' : 'Due now', wlPredictStalled: isZh ? '节奏停滞或已达底线' : 'Stalled / floor reached', wlPredictIn: isZh ? '约' : 'in', wlPredictDays: isZh ? '天' : 'd', wlPredictLast: isZh ? '上次史低' : 'Last low', wlPredictGap: isZh ? '史低间隔' : 'Low interval', wlPredictNextCut: isZh ? '预计折扣' : 'Predicted cut', wlConfHigh: isZh ? '可信度高' : 'High confidence', wlConfMid: isZh ? '可信度中' : 'Medium confidence', wlConfLow: isZh ? '可信度低' : 'Low confidence', wlCurveSource: isZh ? '数据源' : 'Source', wlFilterDiscount: isZh ? '打折中' : 'On Sale', wlFilterInLibrary: isZh ? '已在库' : 'In Library', wlFilterFree: isZh ? '免费' : 'Free', wlFilterComingSoon: isZh ? '即将发售' : 'Coming Soon', wlComingSoon: isZh ? '即将发售' : 'Coming Soon', wlKpiComingSoon: isZh ? '即将发售' : 'Coming Soon', wlTypeDist: isZh ? '类型分布' : 'Type Distribution', wlUpcoming: isZh ? '待上市游戏' : 'Upcoming Games', wlUpcoming30d: isZh ? '30天内' : '<30d', wlUpcoming90d: isZh ? '90天内' : '<90d', wlUpcomingFar: isZh ? '更远' : 'Far', wlUpcomingNoDate: isZh ? '未定日期' : 'No Date', wlDiscountDist: isZh ? '折扣分布' : 'Discount Distribution', wlTopDiscount: isZh ? 'TOP 折扣' : 'TOP Discounts', wlFree: isZh ? '免费' : 'Free', wlNoPrice: isZh ? '暂无价格' : 'N/A', wlTypeGame: isZh ? '游戏' : 'Games', wlTypeDlc: 'DLC', wlTypeSoftware: isZh ? '软件' : 'Software', wlTypeOther: isZh ? '其他' : 'Other', wlDiscOff: isZh ? '无折扣' : 'No Discount', wlDateAdded: isZh ? '添加于' : 'Added', wlTopTags: isZh ? '热门标签 TOP 15' : 'Top 15 Tags', wlTimeline: isZh ? '添加时间线' : 'Added Timeline', wlPriceDist: isZh ? '价格区间分布' : 'Price Range Distribution', wlAddedByYear: isZh ? '按年添加趋势' : 'Added by Year', wlKpiTotalValue: isZh ? '总价值' : 'Total Value', wlKpiOnSale: isZh ? '打折中' : 'On Sale', wlMultiCurHint: isZh ? '部分条目币种无汇率,已按可折算部分统计' : 'Some currencies lack rates; partial total shown', wlKpiFree: isZh ? '免费游戏' : 'Free Games', wlKpiInLib: isZh ? '已入库' : 'In Library', wlEarliest: isZh ? '最早于' : 'Earliest', wlAvgPrice: isZh ? '均价' : 'Avg', wlMedian: isZh ? '中位' : 'Median', wlRate: isZh ? '占比' : 'Rate', wlAvgDisc: isZh ? '均折' : 'Avg', wlMaxDisc: isZh ? '最高' : 'Max', wlPurchaseRate: isZh ? '购入率' : 'Purchase Rate', wlPriceFree: isZh ? '免费' : 'Free', wlPriceLt50: '<50', wlPrice50_100: '50-100', wlPrice100_200: '100-200', wlPrice200_500: '200-500', wlPriceGte500: '500+', wlUncatEmpty: isZh ? '无分类 {n} 款' : '{n} uncategorized', wlRankTip: isZh ? '愿望单排序位次(可在 Steam 愿望单页面拖拽调整)' : 'Wishlist rank (drag to reorder on your Steam wishlist page)', wlCatStats: isZh ? '我的类别统计' : 'Category Stats', wlCatStatsCats: isZh ? '共 {n} 个类别' : '{n} categories', wlCatStatsNoCat: isZh ? '未分类' : 'Uncategorized', wlCatStatsClick: isZh ? '点击筛选此类别' : 'Click to filter by category', wlCatStatsActive: isZh ? '类别: ' : 'Category: ', wlFamilyShared: isZh ? '家庭共享' : 'Family Shared', wlDisc0: isZh ? '无折扣' : 'None', wlDisc1_25: '1-25%', wlDisc26_50: '26-50%', wlDisc51_75: '51-75%', wlDisc76plus: '76%+', tabPsplus: isZh ? 'PS 会免' : 'PS Plus', tabHumble: isZh ? 'Humble月包' : 'Humble Choice', humbleSearch: isZh ? '搜索游戏 / 发行商…' : 'Search game / publisher…', humbleKpiMonths: isZh ? '月包数' : 'Months', humbleKpiGames: isZh ? '游戏总数' : 'Total Games', humbleKpiOwned: isZh ? '已拥有' : 'Owned', humbleKpiUnowned: isZh ? '未拥有' : 'Not Owned', humbleMonthLabel: isZh ? '第' : 'Choice #', humbleOwnedIn: isZh ? '已收' : 'Owned', humbleFilterAll: isZh ? '全部' : 'All', humbleFilterOwned: isZh ? '已拥有' : 'Owned', humbleFilterUnowned: isZh ? '未拥有' : 'Not Owned', humbleNoData: isZh ? '月包数据加载失败(@resource 不可用)' : 'Failed to load bundle data (@resource unavailable)', psSearch: isZh ? '搜索游戏名称 / AppID...' : 'Search name / AppID...', psSortDateDesc: isZh ? '日期 ↓(新到旧)' : 'Date ↓ (new to old)', psSortDateAsc: isZh ? '日期 ↑(旧到新)' : 'Date ↑ (old to new)', psSortTierAsc: isZh ? '档位 ↑(必备→高级)' : 'Tier ↑ (Essential→Premium)', psSortTierDesc: isZh ? '档位 ↓(高级→必备)' : 'Tier ↓ (Premium→Essential)', psSortNameAsc: isZh ? '名称 A→Z' : 'Name A→Z', psRefreshTip: isZh ? '重新获取 PS 会免数据' : 'Reload PS Plus data', psTierEssential: isZh ? '必备' : 'Essential', psTierExtra: isZh ? '升级' : 'Extra', psTierPremium: isZh ? '高级' : 'Premium', psStatusAll: isZh ? '全部状态' : 'All Status', psStatusIn: isZh ? '在库' : 'In Library', psStatusActive: isZh ? '领取中' : 'Claimable', psStatusExpired: isZh ? '已截止/出库' : 'Expired/Out', psStatusLeaving: isZh ? '即将出库' : 'Leaving Soon', psKpiTotal: isZh ? '会免总数' : 'Total Titles', psKpiMonthly: isZh ? '每月可领' : 'Monthly', psKpiCatalog: isZh ? '游戏目录' : 'Catalog', psKpiSteamOwned: isZh ? 'Steam 已拥有' : 'Owned on Steam', psKpiSteamTotal: isZh ? '共 {n} 款有 Steam 版' : '{n} on Steam', psUpdated: isZh ? '更新于' : 'Updated', psLoading: isZh ? '正在获取 PS 会免数据...' : 'Loading PS Plus data...', psLoadError: isZh ? 'PS 会免数据获取失败,请稍后点击刷新重试' : 'Failed to load PS Plus data. Click refresh to retry.', steamInLib: isZh ? 'steam在库' : 'Steam Owned', tabEpic: isZh ? 'Epic赠送' : 'Epic Free', epicSearch: isZh ? '搜索名称 / AppID...' : 'Search name / AppID...', epicSortAppidDesc: isZh ? 'AppID ↓(大→小)' : 'AppID ↓ (high to low)', epicSortAppidAsc: isZh ? 'AppID ↑(小→大)' : 'AppID ↑ (low to high)', epicSortNameAsc: isZh ? '名称 A→Z' : 'Name A→Z', epicRefreshTip: isZh ? '从 GitHub 数据源更新 Epic 赠送名单' : 'Refresh Epic free list from GitHub data source', epicImportTip: isZh ? '手动导入 Epic 赠送数据 JSON' : 'Import Epic free games JSON', epicExportTip: isZh ? '一键导出 Epic 赠送数据 JSON(含本地缓存历史全量)' : 'Export Epic free games JSON (incl. local history)', epicExportOk: isZh ? '已导出 {n} 款 Epic 赠送游戏' : 'Exported {n} Epic free games', epicExportEmpty: isZh ? '没有可导出的 Epic 赠送数据' : 'No Epic data to export', epicExportFail: isZh ? '自动下载失败,请手工复制以下 JSON:' : 'Auto download failed. Copy JSON below:', epicKpiTotal: isZh ? 'Epic赠送总数' : 'Epic Free Titles', epicKpiOwned: isZh ? 'steam在库' : 'Steam Owned', epicKpiNotOwned: isZh ? '未拥有' : 'Not Owned', epicKpiOwnedSub: isZh ? '已在 Steam 家庭共享库' : 'In Steam family library', epicLoading: isZh ? '正在获取 Epic 赠送数据...' : 'Loading Epic free data...', epicLoadError: isZh ? 'Epic 数据获取失败,可点击导入按钮手动导入 JSON,或用「一键导出/导入」在设备间同步' : 'Failed to load Epic data. Try manual JSON import.', epicNoData: isZh ? '暂无 Epic 赠送数据,请点击刷新或导入' : 'No Epic data. Click refresh or import.', epicImportPrompt: isZh ? '请粘贴 Epic 赠送数据 JSON:\n支持 [appid,...] / {"appids":[...]} / {"games":[{"appid":...}]}\n(与「E宝的爱标识助手」共享存储,自动合并)' : 'Paste Epic free games JSON:\n[appid,...] / {"appids":[...]} / {"games":[{"appid":...}]}', epicImportOk: isZh ? '导入成功,共 {n} 款' : 'Imported {n} games', epicImportNoData: isZh ? '未识别到有效 appid' : 'No valid appid found', epicImportFail: isZh ? 'JSON 解析失败:' : 'JSON parse failed: ', epicBadgeFree: isZh ? 'Epic免费' : 'Epic Free', epicBadgeNotOwned: isZh ? '未拥有' : 'Not Owned', epicSourceKeylol: isZh ? '其乐论坛' : 'keylol', epicSourceLocal: isZh ? '本地缓存' : 'Local', epicSourceManual: isZh ? '内置名单' : 'Built-in', epicSourceImport: isZh ? '手动导入' : 'Imported', tabGoty: isZh ? '年度大作' : 'GotY', gotySearch: isZh ? '搜索游戏名称 / AppID...' : 'Search name / AppID...', gotySortDateAsc: isZh ? '发售日 ↑(早→晚)' : 'Date ↑ (early to late)', gotySortDateDesc: isZh ? '发售日 ↓(晚→早)' : 'Date ↓ (late to early)', gotySortNameAsc: isZh ? '名称 A→Z' : 'Name A→Z', gotySortAppidAsc: isZh ? 'AppID ↑(小→大)' : 'AppID ↑ (low to high)', gotyRefreshTip: isZh ? '重新获取年度大作数据' : 'Reload GotY data', gotyFilterAll: isZh ? '全部' : 'All', gotyFilterOwned: isZh ? 'steam在库' : 'Steam Owned', gotyFilterNotOwned: isZh ? '未拥有' : 'Not Owned', gotyKpiTotal: isZh ? '年度大作总数' : 'GotY Total', gotyKpiOwned: isZh ? 'steam在库' : 'Steam Owned', gotyKpiNotOwned: isZh ? '未拥有' : 'Not Owned', gotyKpiOwnedSub: isZh ? '已在 Steam 家庭共享库' : 'In Steam family library', gotyLoading: isZh ? '正在获取年度大作数据...' : 'Loading GotY data...', gotyLoadError: isZh ? '年度大作数据获取失败,请点击刷新重试' : 'Failed to load GotY data. Click refresh to retry.', gotyNoData: isZh ? '暂无年度大作数据' : 'No GotY data', gotyBadgeGoty: isZh ? '年度大作' : 'GotY', gotyBadgeNotOwned: isZh ? '未拥有' : 'Not Owned', gotyReleaseDate: isZh ? '发售' : 'Release', gotySourceGithub: isZh ? 'GitHub' : 'GitHub', gotySourceCache: isZh ? '本地缓存' : 'Local', gotyFilterAllYears: isZh ? '全部年度' : 'All Years', tabBlocked: isZh ? '锁区游戏' : 'Region Blocked', blockedSearch: isZh ? '搜索名称 / AppID...' : 'Search name / AppID...', blockedSortAppidDesc: isZh ? 'AppID ↓(大→小)' : 'AppID ↓ (high to low)', blockedSortAppidAsc: isZh ? 'AppID ↑(小→大)' : 'AppID ↑ (low to high)', blockedSortNameAsc: isZh ? '名称 A→Z' : 'Name A→Z', blockedSortDateDesc: isZh ? '变更日期 ↓(新→旧)' : 'Changed ↓ (new to old)', blockedSortDateAsc: isZh ? '变更日期 ↑(旧→新)' : 'Changed ↑ (old to new)', blockedRefreshTip: isZh ? '重新获取锁区游戏数据' : 'Reload blocked data', blockedImportTip: isZh ? '手动导入锁区游戏 JSON' : 'Import blocked games JSON', blockedFilterAll: isZh ? '全部' : 'All', blockedFilterOwned: isZh ? 'steam在库' : 'Steam Owned', blockedFilterNotOwned: isZh ? '未拥有' : 'Not Owned', blockedKpiTotal: isZh ? '锁区总数' : 'Blocked Total', blockedKpiOwned: isZh ? 'steam在库' : 'Steam Owned', blockedKpiNotOwned: isZh ? '未拥有' : 'Not Owned', blockedKpiSubBanned: isZh ? 'Banned N · Purchase M · Regional K' : 'Banned N · Purchase M · Regional K', blockedLoading: isZh ? '正在获取锁区游戏数据...' : 'Loading blocked data...', blockedLoadError: isZh ? '锁区数据获取失败,可点击导入按钮手动导入,或稍后点击刷新重试' : 'Failed to load blocked data. Try import or retry later.', blockedNoData: isZh ? '暂无锁区游戏数据,请点击刷新或导入' : 'No blocked data. Click refresh or import.', blockedImportPrompt: isZh ? '请粘贴锁区游戏数据 JSON:\n支持 [{appid,name,...}] 数组格式\n或 srbb_blocked_apps 格式 {"appid":{"name":"...","at":...}}' : 'Paste blocked games JSON:\n[{appid,name,...}] array\nor srbb format {"appid":{"name":"...","at":...}}', blockedImportOk: isZh ? '导入成功,共 {n} 款' : 'Imported {n} games', blockedImportNoData: isZh ? '未识别到有效 appid' : 'No valid appid found', blockedImportFail: isZh ? 'JSON 解析失败:' : 'JSON parse failed: ', blockedBadgeOwned: isZh ? '在库' : 'Owned', blockedBadgeBanned: isZh ? '封禁' : 'Banned', blockedBadgePurchase: isZh ? '购买禁用' : 'Purchase Disabled', blockedBadgeRegional: isZh ? '区域变体' : 'Regional Variant', blockedBadgeManual: isZh ? '手动' : 'Manual', blockedChangedAt: isZh ? '变更' : 'Changed', tabCloudSave: isZh ? '云存档' : 'Cloud Saves', csTotalGames: isZh ? '云存档游戏' : 'Cloud Games', csTotalSize: isZh ? '总占用' : 'Total Size', csTotalFiles: isZh ? '文件总数' : 'Total Files', csAvgSize: isZh ? '平均大小' : 'Avg Size', csLargestSave: isZh ? '最大存档' : 'Largest Save', csTopSizes: isZh ? 'TOP 10 存档大小' : 'TOP 10 Save Sizes', csSizeDist: isZh ? '大小分布' : 'Size Distribution', csFileDist: isZh ? '文件数分布' : 'File Count Distribution', csGameList: isZh ? '游戏列表' : 'Game List', csSearch: isZh ? '搜索游戏名称...' : 'Search game name...', csSortSizeDesc: isZh ? '大小 ↓(大→小)' : 'Size ↓ (large to small)', csSortSizeAsc: isZh ? '大小 ↑(小→大)' : 'Size ↑ (small to large)', csSortFilesDesc: isZh ? '文件数 ↓' : 'Files ↓', csSortNameAsc: isZh ? '名称 A→Z' : 'Name A→Z', csRefreshTip: isZh ? '重新获取云存档数据及文件数' : 'Reload cloud save data & file counts', csFetching: isZh ? '正在获取云存档数据…' : 'Fetching cloud saves…', csFetchFail: isZh ? '云存档数据获取失败,请点击刷新重试' : 'Cloud save fetch failed. Click refresh to retry.', csFetchSuccess: isZh ? '获取成功,共 {n} 款游戏' : 'Fetched {n} games', csNoData: isZh ? '暂无云存档数据,请点击刷新获取' : 'No cloud save data. Click refresh to fetch.', csBadgeNew: isZh ? '新增' : 'NEW', csBadgeChanged: isZh ? '变化' : 'CHANGED', csBadgeRemoved: isZh ? '移除' : 'REMOVED', csUpdated: isZh ? '存档更新' : 'Saves updated', csFileCountUpdated: isZh ? '文件数更新' : 'File count updated', csFiles: isZh ? '文件' : 'files', csSizeLt1: '<1MB', csSize1_10: '1-10MB', csSize10_50: '10-50MB', csSize50_100: '50-100MB', csSize100plus: '100MB+', csFilesLt3: '<3', csFiles3_5: '3-5', csFiles5_10: '5-10', csFiles10plus: '10+', csLoginRequired: isZh ? '需要 Steam 登录态,请在 store.steampowered.com 登录后重试' : 'Steam login required. Please login on store.steampowered.com.', csSourceWeb: isZh ? '网页抓取' : 'Web scrape', csSourceCache: isZh ? '本地缓存' : 'Local cache', csBgRefreshing: isZh ? '后台更新中…' : 'Background updating…', csBgRefreshDone: isZh ? '后台更新完成,新增 {n} 款' : 'Background update done, +{n}', tabDlc: isZh ? 'DLC收藏' : 'DLC Collection', dlcKpiTotal: isZh ? 'DLC 总数' : 'DLC Total', dlcKpiRegular: isZh ? '常规 DLC' : 'Regular DLC', dlcKpiMusic: isZh ? '音乐包' : 'Music Packs', dlcKpiBundled: isZh ? '进包 DLC' : 'Bundled DLC', dlcKpiPlayed: isZh ? '已游玩' : 'Played', dlcKpiSub: isZh ? '覆盖 {n} 款游戏' : 'Across {n} games', dlcKpiNoParent: isZh ? '未关联父游戏' : 'No parent', dlcSearch: isZh ? '搜索 DLC 或父游戏...' : 'Search DLC or parent...', dlcSortParent: isZh ? '按父游戏' : 'By Parent', dlcSortAppidDesc: isZh ? 'AppID ↓(大→小)' : 'AppID ↓ (high to low)', dlcSortAppidAsc: isZh ? 'AppID ↑(小→大)' : 'AppID ↑ (low to high)', dlcSortNameAsc: isZh ? '名称 A→Z' : 'Name A→Z', dlcSortType: isZh ? '按类型' : 'By Type', dlcFilterAll: isZh ? '全部' : 'All', dlcFilterDlc: isZh ? '常规' : 'Regular', dlcFilterMusic: isZh ? '音乐' : 'Music', dlcFilterBundled: isZh ? '进包' : 'Bundled', dlcFilterPlayed: isZh ? '已游玩' : 'Played', dlcGroupByParent: isZh ? '按父游戏' : 'By Parent', dlcFlatList: isZh ? '扁平' : 'Flat', dlcLoading: isZh ? '正在加载 DLC 数据库...' : 'Loading DLC database...', dlcLoadError: isZh ? 'DLC 数据加载失败,请稍后重试' : 'DLC data load failed. Please retry later.', dlcNoData: isZh ? '暂无 DLC,请先加载游戏库' : 'No DLC found. Load your library first.', dlcBadgeMusic: isZh ? '音乐' : 'Music', dlcBadgeBundle: isZh ? '包' : 'Bundle', dlcBadgePlayed: isZh ? '已玩' : 'Played', dlcComplete: isZh ? '收集完成度' : 'Completion', dlcUnknownParent: isZh ? '未知父游戏' : 'Unknown Parent', }; const state = { activeTab: 'owned', viewMode: 'card', ownedFilter: 'all', ownedSort: 'appidAsc', ownedGames: [], ownedAppIds: new Set(), isLoading: false, showSettings: false, searchQuery: '', page: 1, pageSize: 48, wishlistGames: [], wishlistLoaded: false, wishlistLoading: false, wishlistLoadStage: 0, wishlistLoadProgress: 0, wishlistSearch: '', wishlistFilter: 'all', wishlistPage: 1, wishlistPageSize: 48, wishlistViewMode: 'card', wishlistCategoryNames: {}, wishlistCategoryFilter: null, achMainTab: '', achSelectedCat: 'all', achDeepTab: 'perfect', achSteamView: 'games', achNavView: 'all', achShelfOpen: false, achShelfTouched: false, achMatrixPage: 1, achMatrixPageSize: 50, achMatrixSort: 'rate', achMatrixView: 'list', achMatrixQuery: '', blockedApps: [], blockedLoaded: false, blockedLoading: false, blockedError: null, blockedSource: null, cloudSaveGames: [], cloudSaveLoaded: false, cloudSaveLoading: false, cloudSaveError: null, cloudSaveSource: null, cloudSaveLastUpdate: 0, cloudSaveSearch: '', cloudSaveSort: 'sizeDesc', cloudSaveDiff: null, cloudSaveBgRefresh: false, cloudSaveBgRefreshAt: 0, cloudSaveFileCountEnriching: false, cloudSaveFileCountAt: 0, showcaseProfile: null, showcaseProfileLoading: false, showcaseProfileAt: 0, showcaseConfig: null, showcaseConfigLoaded: false, showcasePickerOpen: false, showcaseBadgeIcons: null, showcaseBadgeIconsLoading: false, showcaseBadgeIconsAt: 0, showcaseBadges: null, showcasePreheating: false, showcasePreheated: false, showcaseRenderToken: 0, }; const BOOL_ATTRS = new Set(['disabled', 'checked', 'selected', 'readonly', 'required', 'hidden', 'multiple', 'autofocus', 'open']); function h(tag, props = {}, children = []) { const el = document.createElement(tag); for (const [k, v] of Object.entries(props)) { if (v == null) continue; if (k === 'style' && typeof v === 'object') { for (const [sk, sv] of Object.entries(v)) { if (sk.startsWith('--')) el.style.setProperty(sk, sv); else { el.style[sk] = sv; } } } else if (k === 'dataset') { Object.assign(el.dataset, v); } else if (k.startsWith('on') && typeof v === 'function') { el.addEventListener(k.slice(2).toLowerCase(), v); } else if (k === 'text') { el.textContent = v; } else if (k === 'html') { el.innerHTML = v; } else if (BOOL_ATTRS.has(k)) { v ? el.setAttribute(k, '') : el.removeAttribute(k); } else { el.setAttribute(k, v); } } for (const c of children) { if (c == null || c === false) continue; el.appendChild(typeof c === 'string' ? document.createTextNode(c) : c); } return el; } function parseStored(key, fallback) { const str = GM_getValue(key, ''); if (!str) return fallback; try { return JSON.parse(str); } catch (e) { return fallback; } } function $(selector, parent = document) { return parent.querySelector(selector); } function debounce(fn, delay = 200) { let timer = null; const debounced = function(...args) { if (timer) clearTimeout(timer); timer = setTimeout(() => { fn.apply(this, args); timer = null; }, delay); }; debounced.cancel = () => { if (timer) { clearTimeout(timer); timer = null; } }; return debounced; } const _nameCollator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }); const KPI_TONE_CLASS = { dash: 'sglv-stat-dash', trend: 'sglv-trend-kpi', playtime: 'sglv-playtime-kpi', wl: 'sglv-wl-kpi', sgis: 'sgis-insight-kpi', }; function kpiCards(items, opts = {}) { const prefix = KPI_TONE_CLASS[opts.tone]; if (!prefix) throw new TypeError(`kpiCards: 未知 tone "${opts.tone}"(可用: ${Object.keys(KPI_TONE_CLASS).join('/')})`); return (items || []).map(it => { const icon = it.icon || ''; const label = escHtml(it.label); const value = escHtml(it.value); const unit = (it.unit != null && it.unit !== '') ? `<span class="${prefix}-unit">${escHtml(it.unit)}</span>` : ''; const suffixHtml = it.suffixHtml || ''; const subHtml = (it.sub != null && it.sub !== '') ? `<div class="${prefix}-sub">${escHtml(it.sub)}${it.subSuffixHtml || ''}</div>` : ''; const colorCls = it.color || ''; if (opts.tone === 'wl') { return `<div class="${prefix}-card ${colorCls}"><div class="${prefix}-icon">${icon}</div><div class="${prefix}-value">${value}${unit}${suffixHtml}</div><div class="${prefix}-label">${label}</div>${subHtml}</div>`; } if (opts.tone === 'sgis') { return `<div class="${prefix} ${colorCls}"><div class="${prefix}-head"><div class="${prefix}-icon" style="background:${it.grad || ''}">${icon}</div><div class="${prefix}-label">${label}</div></div><div class="${prefix}-val">${value}${unit}${suffixHtml}</div>${subHtml}</div>`; } if (opts.tone === 'dash') { return `<div class="${prefix}-card ${colorCls}${it.active ? ' active' : ''}"${it.dataFilter ? ` data-filter="${it.dataFilter}"` : ''}><div class="${prefix}-header"><span class="${prefix}-icon">${icon}</span><span class="${prefix}-label">${label}</span></div><div class="${prefix}-value">${value}${unit}${suffixHtml}</div>${subHtml}</div>`; } return `<div class="${prefix}-card ${colorCls}"><div class="${prefix}-header"><span class="${prefix}-icon">${icon}</span><span class="${prefix}-label">${label}</span></div><div class="${prefix}-value">${value}${unit}${suffixHtml}</div>${subHtml}</div>`; }).join(''); } function emptyHtml(text, opts = {}) { const style = opts.style ? ` style="${opts.style}"` : ''; return `<div class="sglv-empty"${style}>${escHtml(text)}</div>`; } const SKELETONS = { showcase: () => { const sk = (w, h, r) => `<div class="sglv-sc-sk-block" style="width:${w};height:${h};border-radius:${r || '6px'};"></div>`; return ` <div class="sglv-sc-wrap sglv-sc-skeleton-wrap"> <div class="sglv-sc-scroll"> <div class="sglv-sc-hero"> <div class="sglv-sc-avatar-wrap">${sk('44px', '44px', '50%')}</div> <div class="sglv-sc-hero-info"> <div class="sglv-sc-hero-name-row">${sk('140px', '18px')}</div> <div class="sglv-sc-hero-stats"> <div class="sglv-sc-hero-stat">${sk('60px', '32px')}</div> <div class="sglv-sc-hero-stat">${sk('60px', '32px')}</div> <div class="sglv-sc-hero-stat">${sk('60px', '32px')}</div> </div> </div> </div> <div class="sglv-sc-cols"> <div class="sglv-sc-left"> <div class="sglv-sc-card"> <div class="sglv-sc-card-header">${sk('120px', '16px')}</div> <div class="sglv-sc-card-body"><div class="sglv-sc-cover-grid"> ${Array(8).fill(sk('100%', '170px', '8px')).join('')} </div></div> </div> <div class="sglv-sc-card"> <div class="sglv-sc-card-header">${sk('120px', '16px')}</div> <div class="sglv-sc-card-body"> ${Array(4).fill(`<div class="sglv-sc-playtime-item">${sk('32px', '32px', '50%')}<div class="sglv-sc-playtime-info">${sk('100%', '14px')}${sk('70%', '12px')}</div></div>`).join('')} </div> </div> </div> <div class="sglv-sc-right"> <div class="sglv-sc-card" style="margin-bottom:20px;"> <div class="sglv-sc-card-header">${sk('120px', '16px')}</div> <div class="sglv-sc-card-body"> ${Array(4).fill(`<div class="sglv-sc-ach-item">${sk('32px', '32px', '50%')}<div class="sglv-sc-ach-info">${sk('100%', '14px')}${sk('60%', '12px')}</div></div>`).join('')} </div> </div> <div class="sglv-sc-card"> <div class="sglv-sc-card-header">${sk('80px', '16px')}</div> <div class="sglv-sc-tags">${sk('70px', '24px', '12px')}${sk('70px', '24px', '12px')}</div> </div> </div> </div> </div> </div>`; }, heatmap: () => { const cellSize = 12, cellGap = 3, cellStep = cellSize + cellGap; const labelW = 26, monthH = 16; const monthNames = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']; const dayNames = ['', '一', '', '三', '', '五', '']; const totalWeeks = 53; const baseColor = '#21262d'; const topH = monthH; const svgW = labelW + totalWeeks * cellStep + 8; const svgH = topH + 7 * cellStep + 8; const monthParts = monthNames.map((n, i) => { const w = Math.floor(i * totalWeeks / 12); return `<text x="${labelW + w * cellStep}" y="${topH - 5}" fill="#475569" font-size="10">${n}</text>`; }).join(''); const dayParts = dayNames.map((n, i) => n ? `<text x="0" y="${topH + i * cellStep + 10}" fill="#475569" font-size="10">${n}</text>` : '').join(''); const cellParts = []; for (let w = 0; w < totalWeeks; w++) { for (let d = 0; d < 7; d++) { const x = labelW + w * cellStep, y = topH + d * cellStep; cellParts.push(`<rect x="${x}" y="${y}" width="${cellSize}" height="${cellSize}" rx="2" fill="${baseColor}"/>`); } } const legendSwatches = ['#161b22', '#0e4429', '#006832', '#26a641', '#39d353'] .map(c => `<span class="swatch" style="background:${c};opacity:0.6"></span>`).join(''); const skeleton = `<svg width="${svgW}" height="${svgH}" viewBox="0 0 ${svgW} ${svgH}" style="display:block;max-width:100%;height:auto;">${monthParts}${dayParts}${cellParts.join('')}</svg> <div class="sglv-heatmap-summary" style="opacity:0.5"> <span class="sglv-heatmap-legend"><span>${T.ptHeatmapLess}</span>${legendSwatches}<span>${T.ptHeatmapMore}</span></span> <span>${T.ptHeatmapTotal}: <b>—</b></span> <span>${T.ptHeatmapPeak}: <b>—</b></span> <span>${T.ptHeatmapAvg}: <b>—</b></span> <span>${isZh ? '加载中…' : 'Loading…'}</span> </div>`; return `<div class="sglv-heatmap-block sglv-heatmap-skeleton">${skeleton}</div>`; }, monthly: () => { const now = new Date(); const months = []; for (let i = 5; i >= 0; i--) { const d = new Date(now.getFullYear(), now.getMonth() - i, 1); months.push({ y: d.getFullYear(), m: d.getMonth(), key: `${String(d.getMonth() + 1).padStart(2, '0')}.${String(d.getFullYear()).slice(-2)}` }); } const W = 280, H = 200, lw = 32, topPad = 20, botPad = 24; const plotW = W - lw - 2, plotH = H - topPad - botPad; const step = plotW / 6, barW = Math.min(26, step * 0.6); let parts = ''; const gridVals = [0, 1]; for (const v of gridVals) { const y = topPad + plotH - (v / 1) * plotH; parts += `<line x1="${lw}" y1="${y}" x2="${W - 2}" y2="${y}" stroke="rgba(255,255,255,0.04)" stroke-width="1" stroke-dasharray="3,3"/>`; parts += `<text x="${lw - 4}" y="${y + 3}" fill="#475569" font-size="9" text-anchor="end">${v}</text>`; } months.forEach((mo, i) => { const cx = lw + step * i + step / 2; const bx = cx - barW / 2, by = topPad + plotH - 2; parts += `<rect x="${bx.toFixed(1)}" y="${by.toFixed(1)}" width="${barW}" height="2" rx="3" fill="#334155" opacity="0.25"/>`; const lbl = String(mo.y).slice(2) + '.' + String(mo.m + 1).padStart(2, '0'); parts += `<text x="${cx}" y="${H - 4}" fill="#475569" font-size="9" text-anchor="middle">${lbl}</text>`; }); const svg = `<svg viewBox="0 0 ${W} ${H}" preserveAspectRatio="xMidYMid meet" style="display:block;width:100%;height:100%;">${parts}</svg>`; const summaryHtml = `<div class="sglv-hm-mini-summary" style="opacity:0.5"> <span class="sglv-hm-mini-stat"><b>—</b> ${isZh ? '总计' : 'total'}</span> <span class="sglv-hm-mini-stat">${isZh ? '加载中…' : 'Loading…'}</span> </div>`; return `<div class="sglv-hm-mini-inner"> <div class="sglv-hm-mini-title">${T.ptHeatmapMini6m}</div> <div class="sglv-hm-mini-chart">${svg}</div> ${summaryHtml} </div>`; }, family: (rows = 4) => { const widths = [72, 55, 38, 22]; const rowHtml = []; for (let i = 0; i < rows; i++) { const w = widths[i] || 18; rowHtml.push( `<div class="sglv-family-bar-row sglv-family-bar-skel">` + `<span class="sglv-family-bar-name" style="background:linear-gradient(90deg,rgba(255,255,255,0.06),rgba(255,255,255,0.02));border-radius:3px;width:60px;height:12px;display:inline-block"></span>` + `<div class="sglv-family-bar-track"><div class="sglv-family-bar-fill" style="width:${w}%;background:linear-gradient(90deg,rgba(255,255,255,0.12),rgba(255,255,255,0.06))"></div></div>` + `<span class="sglv-family-bar-hours" style="background:linear-gradient(90deg,rgba(255,255,255,0.06),rgba(255,255,255,0.02));border-radius:3px;width:48px;height:12px;display:inline-block"></span>` + `</div>` ); } return rowHtml.join(''); }, wishlist: (wrap) => { const kpiEl = wrap.querySelector('#sglv-wishlist-kpi'); if (kpiEl && !kpiEl.innerHTML) { kpiEl.className = 'sglv-wl-kpi'; kpiEl.innerHTML = Array.from({ length: 4 }, () => `<div class="sglv-wl-kpi-cell"> <div class="sglv-skel-bar sglv-skel-num"></div> <div class="sglv-skel-bar sglv-skel-lbl"></div> </div>` ).join(''); } const sectionIds = ['sglv-wl-upcoming', 'sglv-wl-catstats', 'sglv-wl-tags', 'sglv-wl-year-trend', 'sglv-wl-price-dist', 'sglv-wl-disc-dist', 'sglv-wl-timeline']; sectionIds.forEach(id => { const el = wrap.querySelector('#' + id); if (!el || el.innerHTML) return; el.innerHTML = `<div class="sglv-skel-bar sglv-skel-section-title"></div> <div class="sglv-skel-bar sglv-skel-row"></div> <div class="sglv-skel-bar sglv-skel-row"></div> <div class="sglv-skel-bar sglv-skel-row sglv-skel-row-short"></div>`; }); const content = wrap.querySelector('#sglv-wishlist-content'); if (content && !content.innerHTML) { content.innerHTML = `<div class="sglv-skel-grid">${Array.from({ length: 12 }, () => `<div class="sglv-skel-game-card"> <div class="sglv-skel-cover"></div> <div class="sglv-skel-bar sglv-skel-card-name"></div> <div class="sglv-skel-bar sglv-skel-card-meta"></div> </div>` ).join('')}</div> ${wishlistLoadingHtml()}`; } }, sgis: (rows = 8) => Array.from({ length: Math.max(0, rows) }, () => `<div class="sgis-skel-row"> <div class="sgis-skel-icon"></div> <div class="sgis-skel-lines"> <div class="sgis-skel-line l1"></div> <div class="sgis-skel-line l2"></div> </div> </div>` ).join(''), }; function createSkeleton(kind, arg) { const build = SKELETONS[kind]; if (!build) throw new TypeError(`createSkeleton: 未知 kind "${kind}"(可用: ${Object.keys(SKELETONS).join('/')})`); return build(arg); } const HBAR_NS = { family: { row: 'sglv-family-bar-row', name: 'sglv-family-bar-name', track: 'sglv-family-bar-track', fill: 'sglv-family-bar-fill', val: 'sglv-family-bar-hours' }, wl: { row: 'sglv-wl-bar-row', name: 'sglv-wl-bar-name', track: 'sglv-wl-bar-track', fill: 'sglv-wl-bar-fill', val: 'sglv-wl-bar-val' }, taste: { row: 'sgis-taste-bar-row', name: 'sgis-taste-bar-label', track: 'sgis-taste-bar-track', fill: 'sgis-taste-bar-fill', val: 'sgis-taste-bar-val' }, cs10: { name: 'sglv-cs-top10-name', track: 'sglv-cs-top10-bar-track', fill: 'sglv-cs-top10-bar', val: 'sglv-cs-top10-size' }, sc: { track: 'sglv-sc-playtime-bar', fill: 'sglv-sc-playtime-bar-fill' }, pt: { track: 'sglv-pt-bar-wrap', fill: 'sglv-pt-bar-fill' }, ptAll: { track: 'sglv-pt-all-bar', fill: 'sglv-pt-all-bar-fill' }, wlBare: { track: 'sglv-wl-bar-track', fill: 'sglv-wl-bar-fill' }, ach: { track: 'sgis-ach-bar', fill: 'sgis-ach-bar-fill' }, xp: { track: 'sgis-xp-bar', fill: 'sgis-xp-bar-fill' }, radar: { track: 'sglv-radar-stat-bar', fill: 'sglv-radar-stat-bar-fill' }, }; function hbarRow({ cls, name, nameTitle, pct, color, val, rowClass, nameTag = 'span', valTag = 'span' }) { const NS = HBAR_NS[cls]; if (!NS) return ''; const nameHtml = name != null ? `<${nameTag} class="${NS.name}"${nameTitle != null ? ` title="${nameTitle}"` : ''}>${name}</${nameTag}>` : ''; const valHtml = val != null ? `<${valTag} class="${NS.val}">${val}</${valTag}>` : ''; const fill = pct != null && pct !== '' ? `<div class="${NS.fill}" style="width:${pct}%${color ? `;background:${color}` : ''}"></div>` : ''; const track = `<div class="${NS.track}">${fill}</div>`; return NS.row ? `<div class="${NS.row}${rowClass ? ' ' + rowClass : ''}">${nameHtml}${track}${valHtml}</div>` : nameHtml + track + valHtml; } function renderGameView(items, opts = {}) { const { viewMode, imgHtml, bodyHtml, trailingHtml = () => '', itemAttrs = () => '', wrapAttrs = '', gridCls = 'sglv-card-grid', cardCls = 'sglv-game-card', bodyCls = 'sglv-card-body', bareImg = false, itemPrefixHtml = () => '', listItemCls = 'sglv-list-item', listInfoCls = 'sglv-list-info', rowsOnly = false, } = opts; if (viewMode === 'card') { return `<div class="${gridCls}"${wrapAttrs}>${items.map(g => ` ${itemPrefixHtml(g)}<div class="${cardCls}"${itemAttrs(g)}> ${bareImg ? imgHtml(g) : `<div class="sglv-card-img-wrap">${imgHtml(g)}</div>`} <div class="${bodyCls}">${bodyHtml(g)}</div> </div>`).join('')}</div>`; } const rows = items.map(g => ` <div class="${listItemCls}"${itemAttrs(g)}> ${imgHtml(g)} <div class="${listInfoCls}">${bodyHtml(g)}</div> ${trailingHtml(g)} </div>`).join(''); return rowsOnly ? rows : `<div class="sglv-list-view"${wrapAttrs}>${rows}</div>`; } function listToolbarHtml(cfg = {}) { const { search = null, sort = null, views = null, extraHtml = '', } = cfg; let html = ''; if (search) { html += `<input type="text" class="${search.cls || 'sglv-search'}"${search.id ? ` id="${search.id}"` : ''} placeholder="${search.placeholder}"${search.value != null ? ` value="${search.value}"` : ''}${search.style ? ` style="${search.style}"` : ''}>`; } if (sort) { html += `<select class="${sort.cls || 'sglv-sort-select'}"${sort.id ? ` id="${sort.id}"` : ''}${sort.title ? ` title="${sort.title}"` : ''}>${sort.options.map(o => `<option value="${o.value}"${sort.value === o.value ? ' selected' : ''}>${o.label}</option>`).join('')}</select>`; } if (views) { html += `<div class="sglv-view-toggle">${views.modes.map(m => `<button class="sglv-btn sglv-btn-secondary sglv-btn-icon${views.value === m.mode ? ' active' : ''}"${views.idPrefix ? ` id="${views.idPrefix}${m.mode}"` : ''}${views.useDataView ? ` data-view="${m.mode}"` : ''} title="${m.title}">${m.icon}</button>` ).join('')}</div>`; } return html + extraHtml; } function buildListToolbar(cfg = {}) { const { cls = 'sglv-toolbar', search = null, sort = null, views = null, onChange = null } = cfg; const el = document.createElement('div'); el.className = cls; el.innerHTML = listToolbarHtml(cfg); if (onChange) { if (search) { const input = search.id ? el.querySelector(`#${search.id}`) : el.querySelector(`input.${search.cls || 'sglv-search'}`); if (input) input.addEventListener('input', debounce(e => onChange({ type: 'input', value: e.target.value }), 200)); } if (sort) { const sel = sort.id ? el.querySelector(`#${sort.id}`) : el.querySelector(`select.${sort.cls || 'sglv-sort-select'}`); if (sel) sel.addEventListener('change', e => onChange({ type: 'sort', value: e.target.value })); } if (views) { const btns = views.idPrefix ? views.modes.map(m => el.querySelector(`#${views.idPrefix}${m.mode}`)).filter(Boolean) : [...el.querySelectorAll('[data-view]')]; btns.forEach(btn => { btn.addEventListener('click', () => { const mode = views.idPrefix ? btn.id.slice(views.idPrefix.length) : btn.dataset.view; btns.forEach(b => b.classList.toggle('active', b === btn)); onChange({ type: 'view', value: mode }); }); }); } } return el; } function pickerModalHtml(cfg = {}) { const { modalCls = 'sglv-sc-picker', idBase, title, searchPlaceholder, searchAria = '', extraHtml = '', gridCls, afterGridHtml = '', countInit, maxSelect, saveText, } = cfg; return ` <div class="${modalCls}"> <div class="sglv-sc-picker-header"> <span class="sglv-sc-picker-title">${title}</span> <input type="text" class="sglv-sc-picker-search" id="${idBase}-search" placeholder="${searchPlaceholder}" autocomplete="off" spellcheck="false"${searchAria ? ` aria-label="${searchAria}"` : ''}> <button class="sglv-sc-picker-close" id="${idBase}-close" aria-label="${isZh ? '关闭' : 'Close'}">✕</button> </div> ${extraHtml} <div class="sglv-sc-picker-body"> <div class="${gridCls}" id="${idBase}-grid"></div> ${afterGridHtml} </div> <div class="sglv-sc-picker-footer"> <span class="sglv-sc-picker-count" id="${idBase}-count"><strong>${countInit}</strong> / ${maxSelect}</span> <button class="sglv-sc-picker-save" id="${idBase}-save">${saveText}</button> </div> </div> `; } function openPickerModal(cfg = {}) { const { overlayId, idBase, maxSelect, currentSelected = [], getItems, itemKey, renderItem, itemSelector, keyFromItem, onGridRendered = null, bindExtra = null, canSave = size => size > 0, buildResult, maxWarningText, savedToastText, onSave, } = cfg; const existing = document.getElementById(overlayId); if (existing) existing.remove(); const mountTarget = (SGLV_API.getPanelEl && SGLV_API.getPanelEl()) || document.body; const selected = new Set(currentSelected); const overlay = document.createElement('div'); overlay.className = 'sglv-sc-picker-overlay'; overlay.id = overlayId; overlay.innerHTML = pickerModalHtml(cfg); mountTarget.appendChild(overlay); const grid = overlay.querySelector(`#${idBase}-grid`); const searchInput = overlay.querySelector(`#${idBase}-search`); const countEl = overlay.querySelector(`#${idBase}-count`); const saveBtn = overlay.querySelector(`#${idBase}-save`); function updateCount() { countEl.innerHTML = `<strong>${selected.size}</strong> / ${maxSelect}`; saveBtn.disabled = !canSave(selected.size); } function renderGrid() { const items = getItems(searchInput.value); grid.innerHTML = items.map(it => renderItem(it, selected.has(itemKey(it)))).join(''); grid.querySelectorAll(itemSelector).forEach(item => { item.addEventListener('click', () => { const key = keyFromItem(item); if (selected.has(key)) { selected.delete(key); item.classList.remove('selected'); } else { if (selected.size >= maxSelect) { sglvToast.warning(maxWarningText); return; } selected.add(key); item.classList.add('selected'); } updateCount(); }); }); if (onGridRendered) onGridRendered(grid, renderGrid); } renderGrid(); updateCount(); const debouncedSearch = debounce(() => renderGrid(), 200); searchInput.addEventListener('input', (e) => debouncedSearch(e.target.value)); if (bindExtra) bindExtra(overlay, renderGrid); function close() { overlay.remove(); document.removeEventListener('keydown', escHandler); } overlay.querySelector(`#${idBase}-close`).addEventListener('click', close); overlay.addEventListener('click', (e) => { if (e.target === overlay) close(); }); saveBtn.addEventListener('click', () => { const result = buildResult(selected); close(); if (onSave) onSave(result); sglvToast.success(savedToastText); }); const escHandler = (e) => { if (e.key === 'Escape') close(); }; document.addEventListener('keydown', escHandler); setTimeout(() => searchInput.focus(), 100); } function getWishlistLoadStage() { const stages = [ { pct: 15, text: T.wlLoadStage1 }, { pct: 45, text: T.wlLoadStage2 }, { pct: 75, text: T.wlLoadStage3 }, ]; const stage = stages[state.wishlistLoadStage - 1] || { pct: 10, text: T.wlFetching }; const pct = state.wishlistLoadProgress > 0 ? state.wishlistLoadProgress : stage.pct; return { text: stage.text, pct }; } function wishlistLoadingHtml() { const s = getWishlistLoadStage(); return createLoadingHtml(s.text, 32, { cls: 'sglv-wl-loading', svgCls: 'sglv-wl-spin', textCls: 'sglv-wl-loading-text', progress: { pct: s.pct }, sub: T.wlLoadSub, }); } function switchToTab(tabName) { if (!tabName) return; state.activeTab = tabName; state.showSettings = false; const _panel = SGLV_API.getPanelEl && SGLV_API.getPanelEl(); if (_panel) { _panel.querySelectorAll('.sglv-tab').forEach(t => t.classList.remove('active')); const tabBtn = _panel.querySelector(`.sglv-tab[data-tab="${tabName}"]`); if (tabBtn) tabBtn.classList.add('active'); } if (SGLV_API.renderBody) SGLV_API.renderBody(); } function _getPinyinLib() { return (typeof window !== 'undefined' && window.SGLVPinyin) || (typeof unsafeWindow !== 'undefined' && unsafeWindow.SGLVPinyin) || null; } const _searchIndex = []; const _searchIndexByAppid = new Map(); let _searchIndexBuilt = false; const _PUNCT_STRIP_RE = /[\s\-_::·、,,.\/\\()()\[\]【】''""]/g; const _PUNCT_TEST_RE = /[\s\-_::·、,,.\/\\()()\[\]【】''""]/; function _extractGameDbEntries() { try { let db = null; try { const txt = GM_getResourceText('gameDb'); if (txt) db = JSON.parse(txt); } catch (e) { } if (!db) return []; const entries = []; for (const publisher of Object.keys(db)) { if (publisher === '_meta') continue; const seriesMap = db[publisher]; if (!seriesMap || typeof seriesMap !== 'object') continue; for (const series of Object.keys(seriesMap)) { const items = seriesMap[series]; if (!Array.isArray(items)) continue; for (const it of items) { if (it && it.id && it.name) { entries.push({ appid: Number(it.id), name: it.name }); } } } } return entries; } catch (e) { return []; } } function buildSearchIndex() { _searchIndex.length = 0; _searchIndexByAppid.clear(); const ownedSet = new Set(); if (Array.isArray(state.ownedGames)) { for (const g of state.ownedGames) { if (!g || !g.appid) continue; const appid = Number(g.appid); if (ownedSet.has(appid)) continue; ownedSet.add(appid); _searchIndexByAppid.set(appid, { appid, name: g.name || '', type: 'owned', owned: true, wishlist: false, store: false, _gameObj: g, }); } } if (Array.isArray(state.wishlistGames)) { for (const g of state.wishlistGames) { if (!g || !g.appid) continue; const appid = Number(g.appid); if (ownedSet.has(appid)) { const ex = _searchIndexByAppid.get(appid); if (ex) { ex.wishlist = true; ex.type = 'owned'; } continue; } if (_searchIndexByAppid.has(appid)) continue; _searchIndexByAppid.set(appid, { appid, name: g.name || '', type: 'wishlist', owned: false, wishlist: true, store: false, }); } } const dbEntries = _extractGameDbEntries(); for (const e of dbEntries) { if (_searchIndexByAppid.has(e.appid)) { _searchIndexByAppid.get(e.appid).store = true; continue; } _searchIndexByAppid.set(e.appid, { appid: e.appid, name: e.name, type: 'store', owned: false, wishlist: false, store: true, }); } for (const entry of _searchIndexByAppid.values()) { entry._scoreBias = entry.owned ? 30 : entry.wishlist ? 20 : 0; _searchIndex.push(entry); } _searchIndexBuilt = true; console.log(`[Steam 游戏库展示] 全局搜索索引已构建: ${_searchIndex.length} 条 (owned=${ownedSet.size}, wishlist=${(state.wishlistGames||[]).length}, store=${dbEntries.length})`); } // v2.47.2: 搜索用名 = 原始名 + 中文别名。索引里的 name 来自 Steam API 英文名, // 中文名只异步补 DOM(sglvGameNameCache)从不回写索引 → 搜"人中之龙"零结果。 // 把两者拼成 searchName 一起交给拼音库,英文/中文/拼音首字母三路都能命中。 function _sglvBuildSearchName(name, nameZh) { return (nameZh && nameZh !== name) ? (name + ' ' + nameZh) : name; } // 每次搜索前用最新中文名缓存刷新索引(缓存异步填充,建索引时多半还没加载) function _sglvRefreshSearchNames() { let cache = null; try { cache = sglvGameNameCacheLoad(); } catch (e) { } if (!cache) return; for (const e of _searchIndex) { const c = cache[String(e.appid)]; const zh = (c && c.name) || ''; if (e._nameZh !== zh) { e._nameZh = zh; e.searchName = _sglvBuildSearchName(e.name, zh); } } } function searchGames(query, limit = 30) { if (!_searchIndexBuilt) buildSearchIndex(); _sglvRefreshSearchNames(); injectSGLVAppDetailHost(); const lib = _getPinyinLib(); if (!lib) { console.warn('[Steam 游戏库展示] 拼音库未加载,搜索不可用'); return []; } return lib.searchByPinyin(query, _searchIndex, { limit, getName: e => e.searchName || e.name, }); } function highlightMatch(name, query, nameZh) { // 中文 query 命中中文别名 → 高亮中文名,避免展示英文名却找不到高亮点 if (nameZh && query) { const qCn = String(query).trim(); const idxZh = nameZh.toLowerCase().indexOf(qCn.toLowerCase()); if (idxZh >= 0) { return escHtml(nameZh.slice(0, idxZh)) + '<mark>' + escHtml(nameZh.slice(idxZh, idxZh + qCn.length)) + '</mark>' + escHtml(nameZh.slice(idxZh + qCn.length)); } } if (!name || !query) return escHtml(name || ''); const escaped = escHtml(name); const q = String(query).trim(); if (!q) return escaped; const lowerName = name.toLowerCase(); const lowerQ = q.toLowerCase(); const idx = lowerName.indexOf(lowerQ); if (idx >= 0) { const before = escHtml(name.slice(0, idx)); const hit = escHtml(name.slice(idx, idx + q.length)); const after = escHtml(name.slice(idx + q.length)); return before + '<mark>' + hit + '</mark>' + after; } const nameNoSpace = lowerName.replace(_PUNCT_STRIP_RE, ''); const qNoSpace = lowerQ.replace(_PUNCT_STRIP_RE, ''); const idx2 = nameNoSpace.indexOf(qNoSpace); if (idx2 >= 0) { let count = 0, startOrig = -1, endOrig = -1; for (let i = 0; i < name.length; i++) { const c = name[i].toLowerCase(); if (!_PUNCT_TEST_RE.test(c)) { if (count === idx2) startOrig = i; if (count === idx2 + qNoSpace.length - 1) { endOrig = i + 1; break; } count++; } } if (startOrig >= 0 && endOrig > startOrig) { return escHtml(name.slice(0, startOrig)) + '<mark>' + escHtml(name.slice(startOrig, endOrig)) + '</mark>' + escHtml(name.slice(endOrig)); } } const lib = _getPinyinLib(); if (lib && typeof lib.toPinyinAbbr === 'function') { const pinyinAbbr = lib.toPinyinAbbr(name).toLowerCase(); const idx3 = pinyinAbbr.indexOf(lowerQ); if (idx3 >= 0) { return escHtml(name.slice(0, idx3)) + '<mark>' + escHtml(name.slice(idx3, idx3 + q.length)) + '</mark>' + escHtml(name.slice(idx3 + q.length)); } const abbrNoSpace = pinyinAbbr.replace(_PUNCT_STRIP_RE, ''); const idx4 = abbrNoSpace.indexOf(qNoSpace); if (idx4 >= 0) { let count2 = 0, startOrig2 = -1, endOrig2 = -1; for (let i = 0; i < pinyinAbbr.length; i++) { const c = pinyinAbbr[i]; if (!_PUNCT_TEST_RE.test(c)) { if (count2 === idx4) startOrig2 = i; if (count2 === idx4 + qNoSpace.length - 1) { endOrig2 = i + 1; break; } count2++; } } if (startOrig2 >= 0 && endOrig2 > startOrig2) { return escHtml(name.slice(0, startOrig2)) + '<mark>' + escHtml(name.slice(startOrig2, endOrig2)) + '</mark>' + escHtml(name.slice(endOrig2)); } } } return escaped; } let _gsFocusIdx = -1; let _gsLastResults = []; let _gsLastQuery = ''; let _gsInputEl = null; let _gsPopEl = null; let _gsSearchWrap = null; let _gsClearBtn = null; function markSearchIndexDirty() { _searchIndexBuilt = false; } function _gsShowPop(show) { if (!_gsPopEl) return; _gsPopEl.classList.toggle('show', show); } function closeSearchPop() { _gsShowPop(false); _gsFocusIdx = -1; } let _gsStoreSearchToken = 0; function _gsIsWordChar(ch) { return /[\p{L}\p{N}_]/u.test(ch); } function _gsShrinkStoreQuery(q) { const s = String(q || '').trim(); if (!s) return ''; let end = s.length; while (end > 0 && !_gsIsWordChar(s[end - 1])) end--; const stripped = s.slice(0, end).trimEnd(); if (stripped !== s) return stripped; const m = stripped.match(/^(.*)\s+\S+$/); if (!m) return ''; return m[1].trimEnd(); } const _GS_STORE_PROHIBITED_RE = /\bdemo\b|\bprologue\b|试玩|体验版|序章/i; function _gsStoreIsProhibited(name) { return _GS_STORE_PROHIBITED_RE.test(String(name || '')); } function _gsDemoteStoreItems(items, query) { if (_gsStoreIsProhibited(query)) return items; const clean = [], demoted = []; for (const it of items) (_gsStoreIsProhibited(it.name) ? demoted : clean).push(it); return clean.concat(demoted); } function _gsStoreLocale() { let cfg = null; try { const el = document.querySelector('#application_config'); cfg = JSON.parse((el && el.getAttribute('data-config')) || 'null'); } catch (e) { cfg = null; } return { lang: (cfg && cfg.LANGUAGE) ? String(cfg.LANGUAGE).toLowerCase() : (isZh ? 'schinese' : 'english'), cc: (cfg && cfg.COUNTRY) ? String(cfg.COUNTRY).toLowerCase() : 'cn', }; } async function searchSteamStore(query) { const token = ++_gsStoreSearchToken; try { const loc = _gsStoreLocale(); let q = String(query || '').trim(); let items = []; let shrinks = 0; while (q) { const url = `https://store.steampowered.com/api/storesearch/?term=${encodeURIComponent(q)}&l=${loc.lang}&cc=${loc.cc}&max_results=15`; const data = await sglvGmFetchRetry(url, { timeout: 5000, retries: 0 }); if (token !== _gsStoreSearchToken) return []; if (!data || !Array.isArray(data.items)) return []; if (data.items.length) { items = data.items; break; } if (shrinks >= 2) break; const next = _gsShrinkStoreQuery(q); if (!next || next === q) break; q = next; shrinks++; } return _gsDemoteStoreItems(items, query).map(item => ({ appid: Number(item.id), name: item.name || '', type: 'store', owned: false, wishlist: false, store: true, _storeResult: true, _storeImg: item.tiny_image || '', _storePrice: item.prices ? { final: (Number(item.prices.final) || 0) / 100, initial: (Number(item.prices.initial) || 0) / 100, discount: Number(item.prices.discount_percentage) || 0, currency: item.prices.currency || '', } : null, _storeReview: item.review_desc || '', })); } catch (e) { return []; } } function mergeSearchResults(localResults, storeResults) { if (!storeResults || storeResults.length === 0) return localResults; const localAppids = new Set(localResults.map(r => r.appid)); const merged = [...localResults]; for (const sr of storeResults) { if (!sr.appid || localAppids.has(sr.appid)) continue; if (_searchIndexByAppid.has(sr.appid)) { const existing = _searchIndexByAppid.get(sr.appid); if (existing.owned || existing.wishlist) continue; } merged.push(sr); localAppids.add(sr.appid); if (merged.length >= 30) break; } return merged; } function detectAppidExactMatch(query) { const num = Number(query); if (!Number.isInteger(num) || num <= 0) return null; if (_searchIndexByAppid.has(num)) { const entry = _searchIndexByAppid.get(num); return { ...entry, _exactMatch: true }; } return { appid: num, name: `App ${num}`, type: 'store', owned: false, wishlist: false, store: true, _exactMatch: true }; } function buildSearchItem(entry, idx, q) { const owned = !!entry.owned, wishlist = !!entry.wishlist, store = !!entry.store; let typeKey, typeText; if (owned) { typeKey = 'owned'; typeText = T.gsTypeOwned; } else if (wishlist) { typeKey = 'wishlist'; typeText = T.gsTypeWishlist; } else { typeKey = 'store'; typeText = T.gsTypeStore; } const badges = []; if (owned && wishlist) badges.push(`<span class="sglv-gs-item-type wishlist" style="opacity:.6">${escHtml(T.gsTypeWishlist)}</span>`); if (owned && store) badges.push(`<span class="sglv-gs-item-type store" style="opacity:.6">${escHtml(T.gsTypeStore)}</span>`); if (entry._exactMatch) badges.push(`<span class="sglv-gs-item-type" style="background:rgba(74,222,128,0.15);color:#4ade80;border:1px solid rgba(74,222,128,0.25)">${isZh ? '精准匹配' : 'Exact'}</span>`); let ownershipBadge = ''; try { if (unsafeWindow.SGLVAppDetail && entry._gameObj) { const b = unsafeWindow.SGLVAppDetail.getOwnershipBadge(entry.appid, entry._gameObj); if (b && b.kind === 'shared') { const tip = b.tip ? escHtml(b.tip) : (isZh ? '家庭库中共享' : 'Family shared'); const lbl = isZh ? '共享' : 'Shared'; ownershipBadge = `<span class="sglv-gs-item-shared" title="${tip}">${lbl}</span>`; } } } catch (e) { } const subText = owned ? T.gsJumpToOwned : wishlist ? T.gsJumpToWishlist : T.gsOpenStore; const htmlName = highlightMatch(entry.name, q, entry._nameZh); const capSrc = entry._storeImg || (SGLV_API.getGameIconUrl ? SGLV_API.getGameIconUrl(entry.appid, '') : ''); const extIcon = (!owned && !wishlist) ? `<span class="sglv-gs-item-ext">${ICONS.external}</span>` : ''; let storeInfoHtml = ''; if (entry._storeResult && entry._storePrice && entry._storePrice.final > 0) { const sp = entry._storePrice; const sym = sglvCurrencySymbol(sp.currency); const priceStr = `${sym}${sp.final.toFixed(2)}`; const discountStr = sp.discount > 0 ? `<span style="color:#4ade80;font-weight:700">-${sp.discount}%</span>` : ''; const origStr = sp.discount > 0 && sp.initial > sp.final ? `<span style="text-decoration:line-through;color:var(--sgis-text-2);font-size:9px">${sym}${sp.initial.toFixed(2)}</span>` : ''; storeInfoHtml = ` · ${discountStr} ${priceStr} ${origStr}`; } else if (entry._storeResult && entry._storeReview) { storeInfoHtml = ` · ${escHtml(entry._storeReview)}`; } return `<div class="sglv-gs-item${entry._exactMatch ? ' sglv-gs-item-exact' : ''}" data-idx="${idx}" data-appid="${entry.appid}" data-type="${typeKey}"> <div class="sglv-gs-item-thumb">${capSrc ? `<img src="${capSrc}" alt="" loading="lazy" onerror="this.onerror=null;_sglvIconFallback(this,'${entry.appid}','')">` : ''}</div> <div class="sglv-gs-item-body"> <div class="sglv-gs-item-name">${htmlName}</div> <div class="sglv-gs-item-sub">${escHtml(subText)} · AppID ${entry.appid}${storeInfoHtml}</div> </div> <div class="sglv-gs-item-right"> <span class="sglv-gs-item-type ${typeKey}">${escHtml(typeText)}</span> ${ownershipBadge} ${badges.join('')} ${extIcon} </div> </div>`; } function gsFooterHtml() { return isZh ? `<div class="sglv-gs-footer"> <span class="sglv-gs-footer-hint"><kbd>↑</kbd><kbd>↓</kbd> 选择</span> <span class="sglv-gs-footer-hint"><kbd>Enter</kbd> 跳转</span> <span class="sglv-gs-footer-hint"><kbd>Esc</kbd> 关闭</span> </div>` : `<div class="sglv-gs-footer"> <span class="sglv-gs-footer-hint"><kbd>↑</kbd><kbd>↓</kbd> Navigate</span> <span class="sglv-gs-footer-hint"><kbd>Enter</kbd> Open</span> <span class="sglv-gs-footer-hint"><kbd>Esc</kbd> Close</span> </div>`; } function renderGsResults(q, results) { const header = `<div class="sglv-gs-header"><span>${escHtml(T.gsHeader)}</span><span class="sglv-gs-header-count">${results.length}</span></div>`; const items = results.map((entry, idx) => buildSearchItem(entry, idx, q)).join(''); _gsPopEl.innerHTML = header + items + gsFooterHtml(); _gsShowPop(true); _gsPopEl.querySelectorAll('.sglv-gs-item').forEach(itemEl => { const idx = Number(itemEl.dataset.idx); itemEl.addEventListener('mouseenter', () => { _gsFocusIdx = idx; _gsUpdateFocusClass(); }); itemEl.addEventListener('click', (ev) => { ev.preventDefault(); ev.stopPropagation(); const target = _gsLastResults[idx]; if (target) _gsJumpToGame(target); }); }); } function renderSearchResults(query) { if (!_gsPopEl) return; const q = String(query || '').trim(); if (!q) { _gsLastQuery = ''; _gsShowPop(false); _gsLastResults = []; return; } const results = searchGames(q, 30); _gsLastQuery = q; _gsFocusIdx = -1; const exactMatch = detectAppidExactMatch(q); if (exactMatch) { const idx = results.findIndex(r => r.appid === exactMatch.appid); if (idx >= 0) { results[idx]._exactMatch = true; results.unshift(results.splice(idx, 1)[0]); } else { results.unshift(exactMatch); } } _gsLastResults = results; if (results.length === 0) { _gsPopEl.innerHTML = `<div class="sglv-gs-empty"> <div class="sglv-gs-empty-icon">${ICONS.search}</div> <span>${escHtml(T.gsEmpty)}</span> </div>`; _gsShowPop(true); } else { renderGsResults(q, results); } if (results.length < 8 && !exactMatch) { searchSteamStore(q).then(storeResults => { if (storeResults.length === 0) return; if (_gsLastQuery !== q) return; const merged = mergeSearchResults(_gsLastResults, storeResults); if (merged.length === _gsLastResults.length) return; _gsLastResults = merged; _gsFocusIdx = -1; renderSearchResults_merged(q, merged); }).catch(() => {}); } } function renderSearchResults_merged(query, results) { if (!_gsPopEl || results.length === 0) return; renderGsResults(query, results); } function _gsUpdateFocusClass() { if (!_gsPopEl) return; const items = _gsPopEl.querySelectorAll('.sglv-gs-item'); items.forEach((el, i) => { if (i === _gsFocusIdx) el.classList.add('focus'); else el.classList.remove('focus'); }); if (_gsFocusIdx >= 0 && items[_gsFocusIdx]) { items[_gsFocusIdx].scrollIntoView({ block: 'nearest', behavior: 'smooth' }); } } let _detailEscHandler = null; let _detailToken = 0; function closeDetailPopup() { _detailToken++; const overlay = document.getElementById('sglv-detail-overlay'); const pop = document.getElementById('sglv-detail-pop'); if (overlay) overlay.classList.remove('show'); if (pop) { pop.classList.remove('show'); pop.innerHTML = ''; } if (_detailEscHandler) { document.removeEventListener('keydown', _detailEscHandler); _detailEscHandler = null; } } function _bindDetailClose(pop) { const overlay = document.getElementById('sglv-detail-overlay'); const closeBtn = pop.querySelector('#sglv-detail-close-btn'); if (closeBtn) closeBtn.addEventListener('click', closeDetailPopup); if (overlay) overlay.onclick = closeDetailPopup; if (_detailEscHandler) document.removeEventListener('keydown', _detailEscHandler); _detailEscHandler = (e) => { if (e.key === 'Escape') closeDetailPopup(); }; document.addEventListener('keydown', _detailEscHandler); } function showGameDetailPopup(appid, entry) { const overlay = document.getElementById('sglv-detail-overlay'); const pop = document.getElementById('sglv-detail-pop'); if (!overlay || !pop) { console.warn('[SGLV] 详情浮窗容器未找到'); return; } injectSGLVAppDetailHost(); const token = ++_detailToken; pop.innerHTML = `<button class="sglv-detail-close" id="sglv-detail-close-btn">${ICONS.close}</button> <div class="sglv-detail-scroll"><div class="sglv-detail-loading"> ${spinSvg(34)} <span>${escHtml(T.dpLoading)}</span> </div></div>`; overlay.classList.add('show'); pop.classList.add('show'); _bindDetailClose(pop); _loadAndRenderDetail(appid, entry, pop, token); } async function _loadAndRenderDetail(appid, entry, pop, token) { const A = (typeof unsafeWindow !== 'undefined' && unsafeWindow.SGLVAppDetail) || (typeof window !== 'undefined' && window.SGLVAppDetail); if (!A || typeof A.loadDetail !== 'function') { if (token !== _detailToken) return; _renderDetailError(pop, appid, entry, 'SGLVAppDetail 库未加载'); return; } try { const d = await A.loadDetail(appid, { useCache: true }); if (token !== _detailToken) return; if (!d) { _renderDetailError(pop, appid, entry, 'API 无数据返回'); return; } _renderDetailContent(pop, appid, entry, d, token); } catch (e) { if (token !== _detailToken) return; _renderDetailError(pop, appid, entry, e.message || String(e)); } } function _renderDetailError(pop, appid, entry, msg) { pop.innerHTML = `<button class="sglv-detail-close" id="sglv-detail-close-btn">${ICONS.close}</button> <div class="sglv-detail-scroll"><div class="sglv-detail-error"> <span>${escHtml(T.dpError)}</span> <span style="font-size:10px;color:#6e7681">${escHtml(msg)}</span> <button class="sglv-detail-btn sglv-detail-btn-secondary" id="sglv-detail-retry">${escHtml(T.dpRetry)}</button> </div></div>`; _bindDetailClose(pop); const retry = pop.querySelector('#sglv-detail-retry'); if (retry) retry.addEventListener('click', () => showGameDetailPopup(appid, entry)); } async function _fillProfileStatusBadge(pop, appid, token) { const statusEl = pop.querySelector('#sglv-detail-profile-status'); if (!statusEl) return; const _renderBadge = (info) => { if (!info || info.status === 'normal') return; const title = info.status === 'restricted' ? 'Profile Features Limited:该游戏的卡片、成就、游玩时长等资料不会显示在 Steam 个人资料页' : 'Steam 正在了解该游戏,部分资料功能可能暂时受限'; statusEl.innerHTML = `<span class="sgis-profile-badge ${escHtml(info.status)}" title="${escHtml(title)}">${ICONS.profileLimited} ${escHtml(info.label)}</span>`; }; const cached = cacheGet('profileFeatures_' + appid); if (cached) { _renderBadge(cached); return; } try { const url = `https://store.steampowered.com/app/${appid}/?l=english&cc=us`; const html = await sglvGmFetchTextRetry(url, { timeout: 15000, headers: { 'Accept': 'text/html', 'Accept-Language': 'en-US,en;q=0.9', 'Cookie': 'mature_content=1; birthtime=441734400; lastagecheckage=1-January-1900; Steam_Language=english', }, }); if (token !== _detailToken) return; const doc = new DOMParser().parseFromString(html, 'text/html'); const learningEl = doc.querySelector('.game_area_details_specs_ctn.learning_about'); let result; if (!learningEl) { result = { status: 'normal', label: '资料正常', source: 'fetch' }; } else { const labelEl = learningEl.querySelector('.label'); const labelText = (labelEl ? labelEl.textContent : '') || learningEl.textContent || ''; if (/Profile\s+Features\s+Limited/i.test(labelText)) { result = { status: 'restricted', label: '资料受限', source: 'fetch' }; } else { result = { status: 'learning', label: 'Steam正在了解', source: 'fetch' }; } } cacheSet('profileFeatures_' + appid, result, CACHE_TTL.profileFeatures); if (token !== _detailToken) return; _renderBadge(result); } catch (e) { sglvNotifyNetFail('资料受限徽章检测', e); } } function _renderDetailContent(pop, appid, entry, d, token) { const platforms = []; if (d.platforms) { if (d.platforms.win) platforms.push('Windows'); if (d.platforms.mac) platforms.push('macOS'); if (d.platforms.linux) platforms.push('SteamOS+Linux'); } let priceHtml = ''; if (d.isFree) { priceHtml = `<span class="sglv-detail-price-free">${escHtml(T.dpFree)}</span>`; } else { const gi = (entry && entry._gameObj) ? entry._gameObj : null; if (gi && Number(gi.finalPrice) > 0) { const sym = SGLV_API.detectWlPriceSymbol ? SGLV_API.detectWlPriceSymbol() : '¥'; priceHtml = `<span class="sglv-detail-price-val">${sym}${escHtml(String(gi.finalPrice))}</span>`; if (gi.discountPct > 0) priceHtml += `<span class="sglv-detail-price-discount">-${escHtml(String(gi.discountPct))}%</span>`; } else if (d.cnPrice) { const curSym = sglvCurrencySymbol(d.cnPrice.currency); priceHtml = `<span class="sglv-detail-price-val">${curSym}${escHtml(String(d.cnPrice.price))}</span>`; if (d.cnPrice.discount > 0) priceHtml += `<span class="sglv-detail-price-discount">-${escHtml(String(d.cnPrice.discount))}%</span>`; } } let metaHtml = ''; if (d.metacritic && d.metacritic.score) { const s = d.metacritic.score; const c = s >= 75 ? '#4ade80' : s >= 50 ? '#fbbf24' : '#f87171'; metaHtml = `<a class="sglv-detail-metacritic" href="${escHtml(d.metacritic.url || '#')}" target="_blank" rel="noopener" style="background:${c}22;color:${c};border:1px solid ${c}55">Metacritic ${escHtml(String(s))}</a>`; } let reviewHtml = ''; if (d.reviews && d.reviews.summary) { reviewHtml = `<div style="font-size:11px;color:#8b949e;margin:6px 0">${escHtml(d.reviews.summary)}${d.reviews.count ? ` (${escHtml(d.reviews.count)})` : ''}</div>`; } const genresHtml = (d.genres && d.genres.length) ? `<div class="sglv-detail-tags">${d.genres.map(g => `<span class="sglv-detail-tag">${escHtml(g)}</span>`).join('')}</div>` : ''; const shotsHtml = (d.screenshots && d.screenshots.length) ? `<div class="sglv-detail-shots">${d.screenshots.slice(0, 6).map(s => `<div class="sglv-detail-shot"><img src="${escHtml(s.thumbnail || s.full)}" alt="" loading="lazy" onerror="this.parentElement.style.display='none'"></div>` ).join('')}</div>` : ''; const storeUrl = `https://store.steampowered.com/app/${appid}`; let actionsHtml = `<a class="sglv-detail-btn sglv-detail-btn-primary" href="${storeUrl}" target="_blank" rel="noopener">${escHtml(T.dpStorePage)}</a>`; if (entry && entry.owned) { actionsHtml += `<button class="sglv-detail-btn sglv-detail-btn-secondary" id="sglv-detail-jump-lib">${escHtml(T.dpJumpLib)}</button>`; } else if (entry && entry.wishlist) { actionsHtml += `<button class="sglv-detail-btn sglv-detail-btn-secondary" id="sglv-detail-jump-wl">${escHtml(T.dpJumpWl)}</button>`; } const _saAgent = (typeof unsafeWindow !== 'undefined' && unsafeWindow.SteamAgent) || window.SteamAgent; if (_saAgent && typeof _saAgent.isInstalled === 'function' && _saAgent.isInstalled()) { actionsHtml += `<button class="sglv-detail-btn sglv-detail-btn-ai" id="sglv-detail-ask-ai">🤖 问 AI</button>`; } pop.innerHTML = `<button class="sglv-detail-close" id="sglv-detail-close-btn">${ICONS.close}</button> <div class="sglv-detail-scroll"> ${d.cover ? `<div class="sglv-detail-hero"><img src="${escHtml(d.cover)}" alt="" onerror="this.parentElement.style.display='none'"></div>` : ''} <div class="sglv-detail-body"> <div class="sglv-detail-name">${escHtml(d.name || (entry && entry.name) || '')}</div> <div style="display:flex;align-items:center;flex-wrap:wrap;gap:6px;margin-top:4px">${metaHtml}<span id="sglv-detail-profile-status"></span></div> ${reviewHtml} ${d.shortDesc ? `<div class="sglv-detail-desc">${escHtml(d.shortDesc)}</div>` : ''} <dl class="sglv-detail-meta"> ${d.developers && d.developers.length ? `<dt>${escHtml(T.dpDeveloper)}</dt><dd>${escHtml(d.developers.join(', '))}</dd>` : ''} ${d.publishers && d.publishers.length ? `<dt>${escHtml(T.dpPublisher)}</dt><dd>${escHtml(d.publishers.join(', '))}</dd>` : ''} ${d.releaseDate ? `<dt>${escHtml(T.dpRelease)}</dt><dd>${escHtml(d.releaseDate)}</dd>` : ''} ${platforms.length ? `<dt>${escHtml(T.dpPlatforms)}</dt><dd>${escHtml(platforms.join(', '))}</dd>` : ''} ${priceHtml ? `<dt>${escHtml(T.dpPrice)}</dt><dd>${priceHtml}</dd>` : ''} </dl> ${genresHtml} ${shotsHtml} <div class="sglv-detail-actions">${actionsHtml}</div> </div> </div>`; _bindDetailClose(pop); const jumpLib = pop.querySelector('#sglv-detail-jump-lib'); if (jumpLib) jumpLib.addEventListener('click', () => { closeDetailPopup(); if (state.activeTab !== 'owned') switchToTab('owned'); else if (SGLV_API.renderBody) SGLV_API.renderBody(); requestAnimationFrame(() => _gsScrollToAppid(entry.appid, '#sglv-body')); showToast(`🎮 ${entry.name}`); }); const jumpWl = pop.querySelector('#sglv-detail-jump-wl'); if (jumpWl) jumpWl.addEventListener('click', () => { closeDetailPopup(); if (state.activeTab !== 'wishlist') switchToTab('wishlist'); else if (SGLV_API.renderBody) SGLV_API.renderBody(); requestAnimationFrame(() => _gsScrollToAppid(entry.appid, '#sglv-body')); showToast(`💖 ${entry.name}`); }); const askAi = pop.querySelector('#sglv-detail-ask-ai'); if (askAi) askAi.addEventListener('click', () => { const sa = (typeof unsafeWindow !== 'undefined' && unsafeWindow.SteamAgent) || window.SteamAgent; if (!sa || !sa.open) return; const gameName = d.name || (entry && entry.name) || ''; const prompt = `请帮我分析 Steam 游戏「${gameName}」(AppID: ${appid}),包括:\n1. 游戏评价和口碑\n2. 当前价格是否值得入手\n3. 类型和玩法特点\n4. 适合什么样的玩家`; closeDetailPopup(); sa.open({ message: prompt }); }); _fillProfileStatusBadge(pop, appid, token); } function _gsJumpToGame(entry) { if (!entry) return; closeSearchPop(); if (_gsInputEl) { _gsInputEl.value = ''; _gsInputEl.dispatchEvent(new Event('input')); } showGameDetailPopup(entry.appid, entry); } function _gsScrollToAppid(appid, containerSel = '#sglv-body') { try { const container = document.querySelector(containerSel); if (!container) return false; const selectors = [ `.sglv-cover-name[data-sglv-appid="${appid}"]`, `.sglv-card-name[data-sglv-appid="${appid}"]`, `.sglv-list-name[data-sglv-appid="${appid}"]`, `.sglv-game-card[data-appid="${appid}"]`, `.sglv-wl-cover-card[data-appid="${appid}"]`, `.sglv-list-item[data-appid="${appid}"]`, `[data-sglv-appid="${appid}"]`, `[data-appid="${appid}"]`, ]; for (const sel of selectors) { const el = container.querySelector(sel); if (el) { el.scrollIntoView({ behavior: 'smooth', block: 'center' }); const card = el.closest('.sglv-game-card, .sglv-wl-cover-card, .sglv-list-item, .sglv-cover-card, .sglv-cover-item, .sglv-card-grid > div, .sglv-list-view > div') || el; if (card && card.style) { const orig = card.style.boxShadow; card.style.boxShadow = '0 0 0 3px rgba(102, 192, 244, 0.8), 0 0 24px rgba(102, 192, 244, 0.6)'; card.style.transition = 'box-shadow 0.3s ease'; setTimeout(() => { card.style.boxShadow = orig; }, 2400); } return true; } } showToast(isZh ? '该游戏在当前视图未显示(可能受分页或搜索过滤影响)' : 'Game not visible (pagination/search filter?)'); return false; } catch (e) { console.warn('[SGLV] 搜索跳转滚动失败:', e); return false; } } const _gsDebouncedRender = debounce((q) => renderSearchResults(q), 150); function bindGlobalSearchEvents() { const _panel = SGLV_API.getPanelEl && SGLV_API.getPanelEl(); _gsInputEl = _panel?.querySelector('#sglv-global-search-input'); _gsPopEl = _panel?.querySelector('#sglv-global-search-pop'); _gsSearchWrap = _panel?.querySelector('#sglv-global-search'); _gsClearBtn = _panel?.querySelector('#sglv-global-search-clear'); if (!_gsInputEl || !_gsPopEl) return; const onInput = () => { const v = _gsInputEl.value; if (v) _gsSearchWrap.classList.add('has-text'); else _gsSearchWrap.classList.remove('has-text'); if (!v.trim()) { _gsShowPop(false); _gsLastResults = []; _gsFocusIdx = -1; return; } _gsDebouncedRender(v); }; _gsInputEl.addEventListener('input', onInput); addDisposer(() => _gsInputEl.removeEventListener('input', onInput)); const onFocus = () => { if (_gsInputEl.value.trim() && _gsLastResults.length) _gsShowPop(true); }; _gsInputEl.addEventListener('focus', onFocus); addDisposer(() => _gsInputEl.removeEventListener('focus', onFocus)); const onKeydown = (e) => { const key = e.key; if (key === 'ArrowDown') { e.preventDefault(); if (!_gsLastResults.length) return; _gsShowPop(true); _gsFocusIdx = (_gsFocusIdx + 1) % _gsLastResults.length; _gsUpdateFocusClass(); } else if (key === 'ArrowUp') { e.preventDefault(); if (!_gsLastResults.length) return; _gsShowPop(true); _gsFocusIdx = _gsFocusIdx <= 0 ? _gsLastResults.length - 1 : _gsFocusIdx - 1; _gsUpdateFocusClass(); } else if (key === 'Enter') { e.preventDefault(); if (_gsFocusIdx >= 0 && _gsLastResults[_gsFocusIdx]) { _gsJumpToGame(_gsLastResults[_gsFocusIdx]); } else if (_gsLastResults.length > 0) { _gsJumpToGame(_gsLastResults[0]); } } else if (key === 'Escape') { e.preventDefault(); if (_gsPopEl.classList.contains('show')) { closeSearchPop(); } else { _gsInputEl.value = ''; _gsInputEl.dispatchEvent(new Event('input')); _gsInputEl.blur(); } } }; _gsInputEl.addEventListener('keydown', onKeydown); addDisposer(() => _gsInputEl.removeEventListener('keydown', onKeydown)); if (_gsClearBtn) { const onClear = (e) => { e.preventDefault(); e.stopPropagation(); _gsInputEl.value = ''; _gsInputEl.dispatchEvent(new Event('input')); _gsInputEl.focus(); }; _gsClearBtn.addEventListener('click', onClear); addDisposer(() => _gsClearBtn.removeEventListener('click', onClear)); } const onDocClick = (e) => { if (!_gsSearchWrap) return; if (_gsSearchWrap.contains(e.target)) return; closeSearchPop(); }; document.addEventListener('mousedown', onDocClick, true); addDisposer(() => document.removeEventListener('mousedown', onDocClick, true)); const onTabClick = (e) => { if (e.target.closest('.sglv-tab')) closeSearchPop(); }; _panel?.addEventListener('click', onTabClick); addDisposer(() => _panel?.removeEventListener('click', onTabClick)); } unsafeWindow.SGLVSearch = { search: searchGames, build: buildSearchIndex, dirty: markSearchIndexDirty, jump: (appid) => { if (!_searchIndexBuilt) buildSearchIndex(); const entry = _searchIndexByAppid.get(Number(appid)); if (entry) { _gsJumpToGame(entry); return true; } return false; }, }; let _hostApiInjected = false; function injectSGLVAppDetailHost() { if (_hostApiInjected) return; try { const A = (typeof unsafeWindow !== 'undefined' && unsafeWindow.SGLVAppDetail) || (typeof window !== 'undefined' && window.SGLVAppDetail); if (!A || typeof A.setHostApi !== 'function') return; A.setHostApi({ getOwnedGames: () => state.ownedGames, isGameOwnedByMe: (g) => isGameOwnedByMe(g), getGameOwnerNames: (g) => getGameOwnerNames(g), getActiveSteamId: () => getActiveSteamId(), }); _hostApiInjected = true; } catch (e) { } } function paginate(items, page, size) { const totalPages = Math.max(1, Math.ceil(items.length / size)); const clampedPage = Math.min(Math.max(1, page), totalPages); const start = (clampedPage - 1) * size; return { pageItems: items.slice(start, start + size), totalPages, page: clampedPage }; } function sglvSmartPool(tasks, concurrency, opts = {}) { const MAX_RETRY = opts.maxRetry != null ? opts.maxRetry : 2; const cap = Math.max(1, Math.min(concurrency, tasks.length)); const results = new Array(tasks.length); let nextIndex = 0; let inFlight = 0; let activeConcurrency = cap; const isRateLimited = (e) => { const m = (e && e.message) ? String(e.message) : String(e || ''); return m.includes('429') || m.toLowerCase().includes('rate'); }; async function runTask(index) { for (let retry = 0; retry <= MAX_RETRY; retry++) { try { results[index] = await tasks[index](); return; } catch (e) { if (retry === MAX_RETRY) return; const rate = isRateLimited(e); await new Promise(r => setTimeout(r, (retry === 0 ? 1000 : 2000) + (rate ? 1000 : 0))); if (rate) activeConcurrency = Math.max(1, Math.floor(activeConcurrency * 0.7)); } } } async function worker() { while (nextIndex < tasks.length) { while (inFlight >= activeConcurrency) await new Promise(r => setTimeout(r, 100)); if (nextIndex >= tasks.length) break; const idx = nextIndex++; inFlight++; try { await runTask(idx); } finally { inFlight--; } } } const workers = []; for (let i = 0; i < cap; i++) workers.push(worker()); return Promise.all(workers).then(() => results); } const disposers = []; function addDisposer(fn) { if (typeof fn === 'function') disposers.push(fn); } function runDisposers() { while (disposers.length) { try { (disposers.pop())(); } catch (e) {} } } const _posterGoodUrl = new Map(); const SGLV_COVER_BK_KEY = 'sglv_bk_cover_map'; const SGLV_COVER_BK_MAX = 2 * 1024 * 1024; let _coverBkTimer = null; let _coverBkLoaded = false; function _coverBkRestore() { if (_coverBkLoaded) return; _coverBkLoaded = true; try { const s = GM_getValue(SGLV_COVER_BK_KEY, null); if (s) { const obj = JSON.parse(s); let n = 0; Object.keys(obj).forEach(k => { const u = obj[k]; if (typeof u === 'string' && /^https?:\/\//i.test(u) && !_posterGoodUrl.has(k)) { _posterGoodUrl.set(k, u); n++; } }); if (n) console.log(`[SGLV] 封面 URL 持久缓存已恢复 ${n} 条`); } } catch (e) { } } function _coverBkFlush() { if (_coverBkTimer) { clearTimeout(_coverBkTimer); _coverBkTimer = null; } try { let obj = {}; _posterGoodUrl.forEach((url, k) => { obj[k] = url; }); let s = JSON.stringify(obj); if (s.length > SGLV_COVER_BK_MAX) { obj = {}; const entries = Array.from(_posterGoodUrl.entries()); entries.slice(-8000).forEach(([k, u]) => { obj[k] = u; }); s = JSON.stringify(obj); } if (s.length <= SGLV_COVER_BK_MAX) GM_setValue(SGLV_COVER_BK_KEY, s); } catch (e) { } } function _coverBkSchedule() { if (_coverBkTimer) return; _coverBkTimer = setTimeout(() => { _coverBkTimer = null; _coverBkFlush(); }, 2000); } try { window.addEventListener('beforeunload', _coverBkFlush); } catch (e) { } function recordPosterGood(appid, url, kind) { if (!appid || !url) return; if (!/^https?:\/\//i.test(url)) return; _coverBkRestore(); const key = `${kind || 'poster'}:${appid}`; if (_posterGoodUrl.get(key) === url) return; _posterGoodUrl.set(key, url); _coverBkSchedule(); } function getPosterGood(appid, kind) { _coverBkRestore(); const u = _posterGoodUrl.get(`${kind || 'poster'}:${appid}`); return (u && /^https?:\/\//i.test(u)) ? u : ''; } unsafeWindow._sglvRecordPosterGood = function(appid, url, kind) { recordPosterGood(appid, url, kind); try { if (url && /^https?:\/\//i.test(url) && url.indexOf('library_600x900') < 0) { recordPosterGood(appid, url, 'header'); } } catch (e) { } }; function _getSharedAiConfig() { try { const sa = (typeof unsafeWindow !== 'undefined' && unsafeWindow.SteamAgent) || window.SteamAgent; if (sa && typeof sa.getActiveModel === 'function') { const m = sa.getActiveModel(); if (m && m.apiKey) return { apiKey: m.apiKey, apiUrl: m.apiUrl, model: m.model }; } } catch {} try { const raw = GM_getValue('sa_model_configs', null); const models = typeof raw === 'string' ? JSON.parse(raw) : raw; if (Array.isArray(models) && models.length > 0) { const activeId = GM_getValue('sa_active_model', ''); const m = models.find(x => x.id === activeId) || models[0]; if (m && m.apiKey) return { apiKey: m.apiKey, apiUrl: m.apiUrl, model: m.model }; } } catch {} try { const agentKey = GM_getValue('sa_ai_api_key', ''); if (agentKey) return { apiKey: agentKey, apiUrl: GM_getValue('sa_ai_api_url', '') || 'https://api.deepseek.com/v1/chat/completions', model: GM_getValue('sa_ai_api_model', '') || 'deepseek-v4-pro', }; } catch {} return null; } const storage = { getApiKey: () => GM_getValue(nsKey('api_key'), ''), setApiKey: v => GM_setValue(nsKey('api_key'), v), getSteamId: () => GM_getValue(nsKey('steamid'), ''), setSteamId: v => GM_setValue(nsKey('steamid'), v), getShowFamilyShared: () => GM_getValue(nsKey('show_family_shared'), true), setShowFamilyShared: v => GM_setValue(nsKey('show_family_shared'), v), getApiKeyConsent: () => _readApiKeyConsent(), setApiKeyConsent: v => _writeApiKeyConsent(v), getOwnedSort: () => GM_getValue(nsKey('owned_sort'), 'appidAsc'), setOwnedSort: v => GM_setValue(nsKey('owned_sort'), v), getUiTheme: () => GM_getValue(nsKey('ui_theme'), 'purple'), setUiTheme: v => GM_setValue(nsKey('ui_theme'), v), getPriceTargetCurrency: () => GM_getValue(nsKey('price_target_currency'), 'CNY'), setPriceTargetCurrency: v => GM_setValue(nsKey('price_target_currency'), v), getAiApiUrl: () => _getSharedAiConfig()?.apiUrl || GM_getValue(nsKey('ai_api_url'), 'https://api.deepseek.com/v1/chat/completions'), setAiApiUrl: v => GM_setValue(nsKey('ai_api_url'), v), getAiApiKey: () => _getSharedAiConfig()?.apiKey || GM_getValue(nsKey('ai_api_key'), ''), setAiApiKey: v => GM_setValue(nsKey('ai_api_key'), v), getAiModel: () => _getSharedAiConfig()?.model || GM_getValue(nsKey('ai_model'), 'deepseek-v4-pro'), setAiModel: v => GM_setValue(nsKey('ai_model'), v), getItadApiKey: () => GM_getValue(nsKey('itad_api_key'), ''), setItadApiKey: v => GM_setValue(nsKey('itad_api_key'), v), getPredictModes: () => { const arr = parseStored(nsKey('predict_modes'), ['seasonal', 'trend', 'lowest']); return Array.isArray(arr) && arr.length ? arr : ['seasonal', 'trend', 'lowest']; }, setPredictModes: v => GM_setValue(nsKey('predict_modes'), JSON.stringify(v)), getCachedGames: () => { const k = nsKey('cached_games'); const v = sglvIDB.get(k, undefined); return v !== undefined ? v : parseStored(k, parseStored('sglv_cached_games', [])); }, setCachedGames: v => sglvIDB.set(nsKey('cached_games'), v), getFamilyInfo: () => { const k = nsKey('family_info'); const v = sglvIDB.get(k, undefined); return v !== undefined ? v : parseStored(k, parseStored('sglv_family_info', {})); }, setFamilyInfo: v => sglvIDB.set(nsKey('family_info'), v), getCloudSaveData: () => { const k = nsKey('cloud_save_data'); const v = sglvIDB.get(k, undefined); return v !== undefined ? v : parseStored(k, null); }, setCloudSaveData: v => sglvIDB.set(nsKey('cloud_save_data'), v), }; try { applySglvTheme(getThemeId()); } catch (e) { console.warn('[SGLV] 主题应用失败,回退默认主题:', e); try { applySglvTheme(DEFAULT_SGLV_THEME); } catch (e2) {} } function migrateLegacyGmKeysToIDB() { const legacyKeys = [ ['sglv_cached_games', nsKey('cached_games')], ['sglv_family_info', nsKey('family_info')], ]; for (const [oldKey, newKey] of legacyKeys) { try { if (sglvIDB.has(newKey)) continue; const raw = GM_getValue(oldKey, null); if (raw == null) continue; const v = typeof raw === 'string' ? JSON.parse(raw) : raw; if (v != null && (Array.isArray(v) ? v.length : Object.keys(v).length)) { sglvIDB.set(newKey, v); console.log(`[SGLV] 迁移 ${oldKey} → IDB:${newKey} (${Array.isArray(v) ? v.length : Object.keys(v).length} 项)`); } } catch (e) { console.warn(`[SGLV] 迁移 ${oldKey} 失败:`, e); } } } const CACHE_TTL = { overview: 24 * 3600 * 1000, prices: 2 * 3600 * 1000, historyPrices: 6 * 3600 * 1000, achievements: 1 * 3600 * 1000, globalAchievements: 12 * 3600 * 1000, news: 30 * 60 * 1000, familyShare: 6 * 3600 * 1000, appDetailsExtra: 24 * 3600 * 1000, friendsList: 6 * 3600 * 1000, friendsVac: 24 * 3600 * 1000, friendsLevels: 7 * 24 * 3600 * 1000, psplus: 6 * 3600 * 1000, epic: 12 * 3600 * 1000, goty: 6 * 24 * 3600 * 1000, reviews: 1 * 3600 * 1000, giftRec: 2 * 3600 * 1000, gameStatus: 6 * 3600 * 1000, profileFeatures: 24 * 3600 * 1000, blockedApps: 24 * 3600 * 1000, seriesData: 6 * 30 * 24 * 3600 * 1000, wishlist: 3 * 24 * 3600 * 1000, cloudSave: 2 * 24 * 3600 * 1000, gameAlias: 30 * 24 * 3600 * 1000, gameAliasMiss: 6 * 3600 * 1000, }; const CLOUDSAVE_BG_REFRESH_INTERVAL = 6 * 3600 * 1000; const CLOUDSAVE_FILECOUNT_INTERVAL = 5 * 24 * 3600 * 1000; function cacheGet(key) { try { const raw = GM_getValue('sglv_cache_' + key, ''); if (!raw) return null; const obj = JSON.parse(raw); if (obj.expires && Date.now() > obj.expires) { GM_setValue('sglv_cache_' + key, ''); return null; } return obj.data; } catch { return null; } } function cachePeek(key) { try { const raw = GM_getValue('sglv_cache_' + key, ''); if (!raw) return null; const obj = JSON.parse(raw); if (obj.data == null) return null; return { data: obj.data, fresh: !(obj.expires && Date.now() > obj.expires) }; } catch { return null; } } function cacheSet(key, data, ttl) { try { GM_setValue('sglv_cache_' + key, JSON.stringify({ data, expires: Date.now() + ttl })); } catch { } } function cacheDelete(key) { try { GM_setValue('sglv_cache_' + key, ''); } catch { } } function cacheClear(prefix) { try { const keys = GM_listValues ? GM_listValues() : []; for (const k of keys) { if (k.startsWith('sglv_cache_' + (prefix || ''))) { GM_setValue(k, ''); } } } catch { } } const AI_PROMPT_URL = 'https://cdn.jsdelivr.net/gh/SmallRob/steam-namespace@main/prompts/ai-prompt-template.json'; const AI_PRICE_PREDICT_PROMPT_URL = 'https://cdn.jsdelivr.net/gh/SmallRob/steam-namespace@main/prompts/ai-price-predict-template.json'; const AI_INSIGHT_PROMPT_URL = 'https://cdn.jsdelivr.net/gh/SmallRob/steam-namespace@main/prompts/ai-insight-template.json'; const FALLBACK_PREDICT_PROMPT = `# 角色\n你是一位精通Steam平台价格分析和游戏行业趋势的数据科学家。基于游戏的历史折扣数据和Steam促销活动节点,使用多种预测模型对游戏价格走势进行预测分析。\n\n# 任务\n根据输入的游戏价格历史数据、折扣记录和发行信息,使用用户选定的预测模式进行分析,输出结构化的预测结果。\n\n## 预测模式说明\n用户已启用以下预测模式:\n{PREDICT_MODES}\n\n### seasonal(季节性折扣预测)\n基于Steam官方促销活动日历(夏促6-7月/秋促11月底/冬促12月底/春促3月)预测下一次折扣时机。\n\n### trend(价格趋势预测)\n基于历史折扣的间隔周期和幅度趋势,预测下次折扣的可能百分比和价格。\n\n### lowest(史低突破预测)\n预测游戏达到或突破历史最低价的可能性和时机。\n\n### review(评价动量预测)\n结合游戏口碑变化趋势评估未来折扣力度。\n\n### similar(相似历史预测)\n匹配游戏价格历史中的相似片段预测折扣模式。\n\n# 输出格式\n严格按以下JSON格式输出,不要输出任何其他文字。\n\n{"models":[{"mode":"seasonal","mode_name":"模式名称","prediction":"预测摘要","discount_percent":50,"predicted_price":134.00,"currency":"CNY","days_until":46,"target_date":"2026-08-27","confidence":92,"sale_event":"秋季特卖","detail":"详细分析","indicators":{}}],"best_buy":{"recommendation":"购买建议","best_time":"最佳时间","best_price":134.00,"wait_days":46,"urgency":"medium"}}\n\n# 输入数据\n- 游戏名称:{GAME_NAME}\n- 应用ID:{APP_ID}\n- 发行日期:{RELEASE_DATE}\n- 当前日期:{CURRENT_DATE}\n- 当前价格:{CURRENT_PRICE} {CURRENCY}\n- 原价:{ORIGINAL_PRICE} {CURRENCY}\n\n## 历史折扣记录:\n{DISCOUNT_RECORDS}\n\n## 完整价格历史:\n{PRICE_HISTORY}\n\n# 注意事项\n- 基于数据客观分析,不要编造数据。\n- confidence反映数据支撑程度:样本充足且规律明显时高分,不足时低分。\n- best_buy应综合所有模式给出最优建议。\n- 输出必须是合法JSON。`; const PREDICT_MODES = [ { key: 'seasonal', name: T.aiPredictModeSeasonal, desc: T.aiPredictModeSeasonalDesc }, { key: 'trend', name: T.aiPredictModeTrend, desc: T.aiPredictModeTrendDesc }, { key: 'lowest', name: T.aiPredictModeLowest, desc: T.aiPredictModeLowestDesc }, { key: 'review', name: T.aiPredictModeReview, desc: T.aiPredictModeReviewDesc }, { key: 'similar', name: T.aiPredictModeSimilar, desc: T.aiPredictModeSimilarDesc }, ]; const _promptCache = new Map(); function loadPromptTemplate(url, fallback = null) { if (_promptCache.has(url)) return Promise.resolve(_promptCache.get(url)); return sglvGmFetchRetry(url, { timeout: 15000, retries: 0 }).then(data => { if (data.prompt && data.prompt.trim()) { _promptCache.set(url, data.prompt.trim()); return _promptCache.get(url); } if (fallback) { _promptCache.set(url, fallback); return fallback; } throw new Error(isZh ? '提示词模板内容为空' : 'Prompt template is empty'); }).catch(e => { if (fallback) { _promptCache.set(url, fallback); return fallback; } throw e; }); } const FALLBACK_TRANSLATE_PROMPT = `# 角色\n你是一位精通游戏行业的翻译与内容分析专家。对Steam游戏动态新闻进行智能翻译与归纳总结。\n\n# 任务\n对输入的游戏动态新闻列表,逐条执行:\n1. 非中文内容翻译为简体中文,中文保留原文。游戏专有名词保留英文后接括号中文释义。\n2. 提炼核心信息,1-3句话总结,不超过100字。\n3. 严格按JSON格式输出。\n\n# 输出格式\n{"items":[{"title":"标题翻译或原文","summary":"1-3句话总结","is_translated":true}]}\n\n# 输入数据\n- 游戏名称:{GAME_NAME}\n- 应用ID:{APP_ID}\n\n新闻列表:\n{NEWS_DATA}\n\n# 注意事项\n- items数组长度必须与输入新闻条数一致。\n- 输出必须是合法JSON。`; const getAiPromptTemplate = () => loadPromptTemplate(AI_PROMPT_URL, FALLBACK_TRANSLATE_PROMPT); const getPredictPromptTemplate = () => loadPromptTemplate(AI_PRICE_PREDICT_PROMPT_URL, FALLBACK_PREDICT_PROMPT); const FALLBACK_INSIGHT_PROMPT = `# 角色\n你是一位游戏行为分析专家和 Steam 库存评论家, 以犀利幽默的风格点评玩家的游戏库。\n\n# 任务\n基于玩家的 Steam 游戏数据和个人口味画像, 从六个维度生成深度分析报告。语言要犀利但不恶意, 数据支撑, 避免空话套话。\n\n# 输入数据\n- 玩家昵称: {PERSONA_NAME}\n- Steam 等级: {STEAM_LEVEL}\n- 游戏总数: {GAME_COUNT}\n- 总时长: {TOTAL_HOURS} 小时\n- 已启动游戏: {PLAYED_COUNT} ({PLAYED_PERCENT}%)\n- 未启动游戏: {UNPLAYED_COUNT} (吃灰率 {DUST_RATE}%)\n- 超 100h 游戏: {OVER_100H_COUNT} 款\n- 超 500h 游戏: {OVER_500H_COUNT} 款\n- 深度游玩(≥10h): {LONG_GAMES_COUNT} 款\n- 平均时长: {AVG_HOURS}h/款\n- 玩家类型: {PERSONA_TYPE} ({PERSONA_RARITY})\n- 玩家特征: {TRAITS}\n- 口味标签: {TASTE_TAGS}\n- 愿望单热门标签: {WISHLIST_TAGS}\n- 维度评分: {DIM_SCORES}\n- 维度详情:\n{DIM_DETAILS}\n- 游玩最多 Top10: {TOP_GAMES}\n- 最近游玩: {RECENT_GAMES}\n- 吃灰游戏示例: {DUST_EXAMPLES}\n\n# 输出格式\n严格按以下 JSON 格式输出, 不要输出任何其他文字。\n{\n "oneLiner": "一句话犀利总结, 30字以内, 直击要害",\n "sections": [\n {"title": "库存概况", "content": "2-4句, 评价游戏数量、规模、收藏习惯"},\n {"title": "游玩习惯", "content": "2-4句, 分析时长投入、深度游玩、吃灰情况"},\n {"title": "偏好画像", "content": "2-4句, 从 Top10 游戏和口味标签推断品味偏好、游戏类型倾向"},\n {"title": "亮点槽点", "content": "2-4句, 先肯定亮点再点出槽点, 犀利但建设性"},\n {"title": "购买建议", "content": "2-4句, 基于现状给出未来购买/游玩的具体建议"},\n {"title": "犀利毒舌", "content": "2-3句, 最犀利最毒舌的终极点评, 可使用比喻和讽刺但不人身攻击, 直击玩家最核心的矛盾"}\n ]\n}`; const getInsightPromptTemplate = () => loadPromptTemplate(AI_INSIGHT_PROMPT_URL, FALLBACK_INSIGHT_PROMPT); function callAiApi(prompt, { temperature = 0.3, timeout = 60000, maxTokens = 4096, returnMeta = false } = {}) { const apiKey = storage.getAiApiKey(); if (!apiKey) return Promise.reject(new Error(T.aiNotConfigured)); const apiUrl = storage.getAiApiUrl(); return sglvGmFetchRetry(apiUrl, { method: 'POST', timeout, headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` }, data: JSON.stringify({ model: storage.getAiModel(), messages: [{ role: 'user', content: prompt }], temperature, max_tokens: maxTokens }), onHttpError(status, text) { let errDetail = ''; try { const errData = JSON.parse(text || ''); errDetail = errData?.error?.message || errData?.message || errData?.error || ''; } catch { errDetail = (text || '').slice(0, 200); } return `AI API HTTP ${status}${errDetail ? ': ' + errDetail : ''}`; }, }).then(respData => { const choice = respData?.choices?.[0] || {}; const content = choice.message?.content || ''; const finishReason = choice.finish_reason || ''; if (!content) { console.error('[SGIS] AI 返回为空, finishReason:', finishReason, '| respData:', JSON.stringify(respData).slice(0, 500)); throw new Error('AI 返回为空 (finishReason: ' + finishReason + ')'); } if (returnMeta) { return { content, finishReason, truncated: finishReason === 'length' }; } return content; }).catch(e => { console.error('[SGIS] callAiApi error:', e.message, '| url:', apiUrl, '| model:', storage.getAiModel()); throw e; }); } function repairTruncatedJson(str) { let s = str; let inStr = false, esc = false; const stk = []; let lastSafeBoundary = -1; for (let i = 0; i < s.length; i++) { const c = s[i]; if (esc) { esc = false; continue; } if (c === '\\') { esc = true; continue; } if (c === '"') { inStr = !inStr; continue; } if (inStr) continue; if (c === '{' || c === '[') stk.push(c); else if (c === '}' || c === ']') { if (stk.length) { stk.pop(); if (stk.length > 0 && stk[stk.length - 1] === '[') { lastSafeBoundary = i + 1; } } } } if (inStr) s += '"'; s = s.replace(/[\s]+$/, ''); if (s.length > 0) { const lastCh = s[s.length - 1]; if (lastCh !== '}' && lastCh !== ']' && lastCh !== ',') { if (lastSafeBoundary >= 0) { s = s.slice(0, lastSafeBoundary); } } } s = s.replace(/,\s*$/, ''); inStr = false; esc = false; const finalStk = []; for (let i = 0; i < s.length; i++) { const c = s[i]; if (esc) { esc = false; continue; } if (c === '\\') { esc = true; continue; } if (c === '"') { inStr = !inStr; continue; } if (inStr) continue; if (c === '{' || c === '[') finalStk.push(c); else if (c === '}' || c === ']') { if (finalStk.length) finalStk.pop(); } } while (finalStk.length > 0) { const open = finalStk.pop(); s += (open === '{' ? '}' : ']'); } return s; } function safeParseAiJson(content, expectKey) { if (!content || typeof content !== 'string') throw new Error('AI 返回内容为空'); let cleaned = content.replace(/<think>[\s\S]*?<\/think>/gi, '').trim(); cleaned = cleaned.replace(/^```(?:json)?\s*/i, '').replace(/```\s*$/i, '').trim(); const openChar = expectKey && expectKey.startsWith('[') ? '[' : '{'; const closeChar = openChar === '{' ? '}' : ']'; const firstIdx = cleaned.indexOf(openChar); if (firstIdx === -1) throw new Error('AI 返回中找不到 JSON 起始符'); const fullContent = cleaned.slice(firstIdx); let depth = 0, inString = false, escape = false, endIdx = -1; for (let i = firstIdx; i < cleaned.length; i++) { const ch = cleaned[i]; if (escape) { escape = false; continue; } if (ch === '\\') { escape = true; continue; } if (ch === '"') { inString = !inString; continue; } if (inString) continue; if (ch === openChar) depth++; else if (ch === closeChar) { depth--; if (depth === 0) { endIdx = i + 1; break; } } } if (endIdx === -1) { try { const repaired = repairTruncatedJson(fullContent); const result = JSON.parse(repaired); if (result && typeof result === 'object') { result._truncated = true; } return result; } catch (eRepair) { const m = cleaned.match(/\{[\s\S]*\}/); if (m) endIdx = m.index + m[0].length; else throw new Error('AI 返回中找不到 JSON 闭合符 (疑似响应被截断)'); } } let jsonStr = cleaned.slice(firstIdx, endIdx); jsonStr = jsonStr.replace(/[\s,]+$/, ''); jsonStr = jsonStr.replace(/^\s*\/\/.*$/gm, ''); jsonStr = jsonStr.replace(/\/\*[\s\S]*?\*\//g, ''); const quoteCount = (jsonStr.match(/"/g) || []).length; if (quoteCount % 2 !== 0) { jsonStr = jsonStr.replace(/"([^"]*)$/, '$1'); } jsonStr = jsonStr.replace(/,(\s*[}\]])/g, '$1'); jsonStr = jsonStr.replace(/'([a-zA-Z_]\w*)'(\s*:)/g, '"$1"$2'); try { return JSON.parse(jsonStr); } catch (e1) { try { const fixed = jsonStr.replace(/[\u0000-\u001F\u007F]/g, (m) => { if (m === '\n' || m === '\r' || m === '\t') return m; return ''; }); return JSON.parse(fixed); } catch (e2) { try { const repaired = repairTruncatedJson(fullContent); const result = JSON.parse(repaired); if (result && typeof result === 'object') { result._truncated = true; } return result; } catch (e3) { throw new Error('AI 返回 JSON 解析失败: ' + e1.message.slice(0, 80) + ' (位置 ' + jsonStr.length + ', 截断修复亦失败)'); } } } } async function callAiTranslateSummary(newsItems, gameName, appId) { let prompt = await getAiPromptTemplate(); const cappedNews = newsItems.slice(0, 15); const newsData = cappedNews.map((n, i) => `[${i + 1}] 标题: ${n.title || '(无标题)'}\n内容: ${n.contents || '(无内容)'}` ).join('\n\n'); prompt = prompt.replace(/\{GAME_NAME\}/g, gameName || '未知游戏') .replace(/\{APP_ID\}/g, appId || '') .replace(/\{NEWS_DATA\}/g, newsData); const { content, finishReason, truncated } = await callAiApi(prompt, { temperature: 0.3, timeout: 60000, maxTokens: 8192, returnMeta: true }); const parsed = safeParseAiJson(content, '{'); const items = parsed.items || []; const wasTruncated = truncated || parsed._truncated === true || items.length < cappedNews.length; if (wasTruncated && items.length > 0) { items.forEach(it => { it._truncated = true; }); } return items; } async function callAiPricePredict(historyData, gameName, appId, currentPrice, originalPrice) { console.log('[SGIS] AI价格预测开始, gameName:', gameName, 'appId:', appId); let prompt = await getPredictPromptTemplate(); console.log('[SGIS] 提示词模板加载完成, length:', prompt.length); const enabledModes = storage.getPredictModes(); const modesText = enabledModes.map(m => { const mode = PREDICT_MODES.find(p => p.key === m); return mode ? `- ${mode.key}(${mode.name}):${mode.desc}` : ''; }).filter(Boolean).join('\n'); const _safeNum = (v) => { const n = Number(v); return isNaN(n) ? 0 : n; }; const discounts = historyData.discounts || []; const discountRecords = discounts.map(d => { const dateStr = d.date ? new Date(d.date).toLocaleDateString('zh-CN') : '—'; const daysStr = d.daysFromRelease != null ? `距发行${d.daysFromRelease}天` : ''; return `- ${dateStr} | -${d.cut}% | ${d.currency}${_safeNum(d.price).toFixed(2)} | 原价${d.currency}${_safeNum(d.regular).toFixed(2)} | ${daysStr}`; }).join('\n') || '无折扣记录'; const history = historyData.history || []; const priceHistory = history.map(h => { const dateStr = h.date ? new Date(h.date).toLocaleDateString('zh-CN') : '—'; return `- ${dateStr} | ${h.cut > 0 ? '-' + h.cut + '%' : '原价'} | ${h.currency}${_safeNum(h.price).toFixed(2)} | 原价${h.currency}${_safeNum(h.regular).toFixed(2)}`; }).join('\n') || '无价格历史'; const currentDate = new Date().toISOString().split('T')[0]; const currency = (history[0] || discounts[0] || {}).currency || 'CNY'; prompt = prompt.replace(/\{PREDICT_MODES\}/g, modesText) .replace(/\{GAME_NAME\}/g, gameName || historyData.gameTitle || '未知游戏') .replace(/\{APP_ID\}/g, appId || '') .replace(/\{RELEASE_DATE\}/g, historyData.releaseDate || '未知') .replace(/\{CURRENT_DATE\}/g, currentDate) .replace(/\{CURRENT_PRICE\}/g, String(currentPrice || '—')) .replace(/\{ORIGINAL_PRICE\}/g, String(originalPrice || '—')) .replace(/\{CURRENCY\}/g, currency) .replace(/\{DISCOUNT_RECORDS\}/g, discountRecords) .replace(/\{PRICE_HISTORY\}/g, priceHistory); console.log('[SGIS] AI API 调用中, model:', storage.getAiModel(), 'url:', storage.getAiApiUrl()); const content = await callAiApi(prompt, { temperature: 0.4, timeout: 90000, maxTokens: 8192 }); console.log('[SGIS] AI API 返回, content length:', content.length); const result = safeParseAiJson(content, '{'); console.log('[SGIS] AI 价格预测解析完成, models:', (result.models || []).length); return result; } const SGLV_GAME_NAME_KEY = 'sglv_game_name_cache'; const SGLV_NAME_CACHE_TTL = 30 * 864e5; let _sglvGameNameCache = null; const _sglvGameNamePending = new Map(); const SAA_BRIDGE_KEY = '__saa_bridge_sglv__'; const SAA_BRIDGE_NAMES_MAX_CHARS = 1.2 * 1024 * 1024; let _saaBridgeTimer = null; function scheduleSaaBridge() { if (_saaBridgeTimer) return; _saaBridgeTimer = setTimeout(() => { _saaBridgeTimer = null; try { writeSaaBridge(); } catch (e) { } }, 2000); } function writeSaaBridge() { try { const bridge = { v: 1, updatedAt: Date.now(), rates: null, names: null, namesSkipped: null }; try { const rates = GM_getValue('sgis-rates', null); const ts = Number(GM_getValue('sgis-rates-ts', 0)) || 0; if (rates && typeof rates === 'object') bridge.rates = { ts, map: rates }; } catch (e) { } try { const raw = GM_getValue(SGLV_GAME_NAME_KEY, null); if (raw && typeof raw === 'object') { const names = {}; for (const k in raw) { const v = raw[k]; names[k] = (v && typeof v === 'object') ? (v.name || '') : v; } const nKeys = Object.keys(names).length; if (nKeys) { let approx = 0; try { approx = JSON.stringify(names).length; } catch (e) { approx = Infinity; } if (approx <= SAA_BRIDGE_NAMES_MAX_CHARS) bridge.names = names; else bridge.namesSkipped = 'quota'; } } } catch (e) { bridge.namesSkipped = 'quota'; } const full = JSON.stringify(bridge); if (sglvLocalSet(SAA_BRIDGE_KEY, full)) return; if (bridge.names) { bridge.names = null; bridge.namesSkipped = 'quota'; sglvLocalSet(SAA_BRIDGE_KEY, JSON.stringify(bridge)); } } catch (e) { } } try { scheduleSaaBridge(); } catch (e) {} function sglvGameNameCacheLoad() { if (_sglvGameNameCache !== null) return _sglvGameNameCache; _sglvGameNameCache = {}; try { const raw = GM_getValue(SGLV_GAME_NAME_KEY); if (raw && typeof raw === 'object') _sglvGameNameCache = raw; } catch (e) { console.warn('[SGLV] 游戏名称缓存读取失败:', e); } return _sglvGameNameCache; } function sglvGameNameCacheSave() { try { GM_setValue(SGLV_GAME_NAME_KEY, _sglvGameNameCache || {}); } catch (e) { console.warn('[SGLV] 游戏名称缓存写入失败:', e); } try { scheduleSaaBridge(); } catch (e) {} } const SGLV_NAME_NEG_TTL = 30 * 60 * 1000; function fetchGameZhName(appid) { if (!isZh) return Promise.resolve(''); const id = String(appid); const cache = sglvGameNameCacheLoad(); const cached = cache[id]; if (cached && cached.name && Date.now() - (cached.ts || 0) < SGLV_NAME_CACHE_TTL) { return Promise.resolve(cached.name); } if (cached && !cached.name && Date.now() - (cached.ts || 0) < SGLV_NAME_NEG_TTL) { return Promise.resolve(''); } if (_sglvGameNamePending.has(id)) return _sglvGameNamePending.get(id); const p = new Promise(resolve => { const settle = (name) => { cache[id] = { name, ts: Date.now() }; try { sglvGameNameCacheSave(); } catch (e) { console.warn('[SGLV] 游戏名称缓存保存失败:', id, e); } _sglvGameNamePending.delete(id); resolve(name); }; sglvGmFetchRetry(`https://store.steampowered.com/api/appdetails?appids=${id}&filters=basic&l=schinese`, { timeout: 10000, retries: 1 }) .then(json => { let name = ''; try { const d = json && json[id]; if (d && d.success && d.data && d.data.name) name = d.data.name; } catch (e) { console.warn('[SGLV] 中文名解析失败:', id, e); } settle(name); }) .catch(() => settle('')); }); _sglvGameNamePending.set(id, p); return p; } function loadGameZhName(el, appid, originalName) { if (!el || !appid) return; fetchGameZhName(appid).then(zhName => { if (zhName && zhName !== originalName) { el.textContent = zhName; el.title = `${zhName} (${originalName})`; } }); } const _sglvEnNameCache = new Map(); const _sglvEnNamePending = new Map(); function fetchGameEnName(appid) { const id = String(appid); if (_sglvEnNameCache.has(id)) return Promise.resolve(_sglvEnNameCache.get(id)); if (_sglvEnNamePending.has(id)) return _sglvEnNamePending.get(id); const p = new Promise(resolve => { sglvGmFetchRetry(`https://store.steampowered.com/api/appdetails?appids=${id}&filters=basic&l=english`, { timeout: 10000, retries: 1 }) .then(json => { let name = ''; try { const d = json && json[id]; if (d && d.success && d.data && d.data.name) name = d.data.name; } catch (e) { console.warn('[SGLV] 英文名解析失败:', id, e); } if (name) _sglvEnNameCache.set(id, name); _sglvEnNamePending.delete(id); resolve(name); }) .catch(() => { _sglvEnNamePending.delete(id); resolve(''); }); }); _sglvEnNamePending.set(id, p); return p; } const _APP_PLACEHOLDER_RE = /^App\s+\d+$/i; function loadGameNameAlias(el, appid, originalName) { if (!el || !appid || !originalName) return; const isPlaceholder = _APP_PLACEHOLDER_RE.test(originalName.trim()); fetchGameZhName(appid).then(zhName => { if (zhName && zhName !== originalName) { el.textContent = zhName; el.title = `${zhName} (${originalName})`; if (!isPlaceholder) { _appendGrayAlias(el, originalName); } return; } if (!isPlaceholder) return; fetchGameEnName(appid).then(enName => { if (enName && enName !== originalName) { el.textContent = enName; el.title = enName; } }); }); } function _appendGrayAlias(el, alias) { if (el.querySelector('.sglv-name-alias')) return; const span = document.createElement('span'); span.className = 'sglv-name-alias'; span.textContent = alias; el.appendChild(span); } function applyGameAliases(container, opts = {}) { if (!container || typeof container.querySelectorAll !== 'function') return; const sel = opts.scope ? `${opts.scope} [data-sglv-appid]` : '[data-sglv-appid]'; container.querySelectorAll(sel).forEach(el => { if (el.getAttribute('data-sglv-alias-done')) return; el.setAttribute('data-sglv-alias-done', '1'); const appid = el.getAttribute('data-sglv-appid'); if (opts.aliasFor && typeof el.matches === 'function' && el.matches(opts.aliasFor)) { loadGameNameAlias(el, appid, el.textContent); } else { loadGameZhName(el, appid, el.textContent); } }); } let _activeSteamId = null; function getActiveSteamId() { if (_activeSteamId) return _activeSteamId; _activeSteamId = storage.getSteamId() || detectSteamId(); return _activeSteamId; } function isGameOwnedByMe(g) { const steamId = getActiveSteamId(); if (!g.owners || g.owners.length === 0) return true; if (!steamId) return true; return g.owners.includes(steamId); } function getGameOwnerNames(g) { if (!g.owners || g.owners.length === 0) return ''; const familyInfo = storage.getFamilyInfo(); const nameMap = familyInfo?.steamIdtoName || {}; return g.owners.map(sid => nameMap[sid] || 'ID:' + sid.slice(-4)).join(', '); } function sglvLocalSet(key, val) { try { window.localStorage.setItem(key, val); return true; } catch (e) { return false; } } let _cachedStatFiltered = null; let _cachedStatFilteredSig = ''; function getStatFilteredGames() { const allGames = (state.ownedGames && state.ownedGames.length) ? state.ownedGames : storage.getCachedGames(); const _isDlc = SGLV_API.isDlc; const dlcReady = (SGLV_API.isDlcDbReady && SGLV_API.isDlcDbReady()) ? '1' : '0'; const sig = `${allGames.length}|${dlcReady}`; if (_cachedStatFiltered && _cachedStatFilteredSig === sig) return _cachedStatFiltered; const result = allGames.filter(g => isGameOwnedByMe(g) && !(_isDlc && _isDlc(g.appid))); _cachedStatFiltered = result; _cachedStatFilteredSig = sig; return result; } let _cachedDlcCount = null; let _cachedDlcCountKey = ''; function getOwnedDlcCount() { const allGames = (state.ownedGames && state.ownedGames.length) ? state.ownedGames : storage.getCachedGames(); const _isDlc = SGLV_API.isDlc; const dlcReady = (SGLV_API.isDlcDbReady && SGLV_API.isDlcDbReady()) ? '1' : '0'; const key = `${allGames.length}|${dlcReady}`; if (_cachedDlcCount !== null && _cachedDlcCountKey === key) return _cachedDlcCount; if (!_isDlc || dlcReady === '0') { _cachedDlcCount = 0; _cachedDlcCountKey = key; return 0; } _cachedDlcCount = allGames.filter(g => isGameOwnedByMe(g) && _isDlc(g.appid)).length; _cachedDlcCountKey = key; return _cachedDlcCount; } let _cachedActiveOwnedAppIds = null; let _cachedActiveOwnedAppIdsKey = ''; function getActiveOwnedAppIds() { const showFamilyShared = storage.getShowFamilyShared(); const cacheKey = `${state.ownedGames.length}|${showFamilyShared}`; if (_cachedActiveOwnedAppIds && _cachedActiveOwnedAppIdsKey === cacheKey) { return _cachedActiveOwnedAppIds; } const appIds = new Set(); state.ownedGames.forEach(g => { if (showFamilyShared || isGameOwnedByMe(g)) { appIds.add(g.appid); } }); _cachedActiveOwnedAppIds = appIds; _cachedActiveOwnedAppIdsKey = cacheKey; return appIds; } function invalidateActiveOwnedAppIdsCache() { _cachedActiveOwnedAppIds = null; _cachedActiveOwnedAppIdsKey = ''; } let _cachedWebApiToken = null; function getAccessTokenSync() { try { const appConfig = document.getElementById('application_config'); if (appConfig) { const storeConfig = JSON.parse(appConfig.getAttribute('data-store_user_config') || '{}'); if (storeConfig.webapi_token) return storeConfig.webapi_token; } } catch (e) { } try { const m = document.documentElement.innerHTML.match(/"webapi_token"\s*:\s*"([^"]+)"/); if (m && m[1]) return m[1]; } catch (e) { } return null; } function fetchWebApiTokenFromStore() { if (_cachedWebApiToken) return Promise.resolve(_cachedWebApiToken); return sglvGmFetchTextRetry('https://store.steampowered.com/', { timeout: 10000 }).then(html => { try { const m1 = html.match(/id="application_config"[^>]*data-store_user_config="([^"]*)"/); if (m1 && m1[1]) { const decoded = m1[1].replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>'); const config = JSON.parse(decoded); if (config.webapi_token) { _cachedWebApiToken = config.webapi_token; return config.webapi_token; } } const m2 = html.match(/"webapi_token"\s*:\s*"([^"]+)"/); if (m2 && m2[1]) { _cachedWebApiToken = m2[1]; return m2[1]; } } catch (e) { } return null; }).catch(() => null); } async function getAccessToken() { const syncToken = getAccessTokenSync(); if (syncToken) return syncToken; const storeToken = await fetchWebApiTokenFromStore(); if (storeToken) return storeToken; return storage.getApiKey() || null; } function detectSteamId() { try { if (unsafeWindow.g_steamID) return unsafeWindow.g_steamID; } catch { } try { const appConfig = document.getElementById('application_config'); if (appConfig) { const userInfo = JSON.parse(appConfig.getAttribute('data-userinfo') || '{}'); if (userInfo.steamid) return String(userInfo.steamid); } } catch (e) { } const m = document.documentElement.innerHTML.match(/g_steamID\s*=\s*"(\d{17})"/); return m ? m[1] : ''; } function showToast(msg) { sglvToast.info(msg); } function copyTextToClipboard(text) { try { if (navigator.clipboard && navigator.clipboard.writeText) { navigator.clipboard.writeText(text).catch(() => fallbackCopyText(text)); return; } } catch { } fallbackCopyText(text); } function fallbackCopyText(text) { try { const ta = document.createElement('textarea'); ta.value = text; ta.style.cssText = 'position:fixed;top:-9999px;left:-9999px;opacity:0'; document.body.appendChild(ta); ta.select(); document.execCommand('copy'); document.body.removeChild(ta); } catch { } } let _dynamicStoreOwnedAppIds = null; async function fetchDynamicStoreOwnedAppIds() { if (_dynamicStoreOwnedAppIds) return _dynamicStoreOwnedAppIds; try { const data = await sglvGmFetchRetry('https://store.steampowered.com/dynamicstore/userdata/', { timeout: 15000 }); const ownedApps = data?.rgOwnedApps; if (Array.isArray(ownedApps)) { _dynamicStoreOwnedAppIds = new Set(ownedApps.map(Number).filter(n => Number.isFinite(n) && n > 0)); console.log(`[SGLV] dynamicstore/userdata 获取 ${_dynamicStoreOwnedAppIds.size} 个 owned appids`); } } catch (e) { console.warn('[SGLV] dynamicstore/userdata 获取失败:', e); sglvNotifyNetFail('DynamicStore 拥有游戏列表获取', e); } return _dynamicStoreOwnedAppIds; } function getDynamicStoreAppIds(kind) { try { const win = (typeof unsafeWindow !== 'undefined') ? unsafeWindow : window; let raw = null; if (kind === 'wishlist') raw = win.GDynamicStore?.s_rgWishlist || win.g_rgWishlist; else if (kind === 'owned') raw = win.GDynamicStore?.s_rgOwnedApps; if (!raw) return new Set(); const arr = Array.isArray(raw) ? raw : Object.keys(raw); return new Set(arr.map(Number).filter(n => Number.isFinite(n) && n > 0)); } catch { return new Set(); } } const SGLV_API = {}; (function () { function requestSteamAPI(url) { return sglvGmFetchTextRetry(url, { timeout: 30000 }).then(text => { if (text.startsWith('<') || text.startsWith('<!DOCTYPE')) { throw new Error('Steam API 返回 HTML 而非 JSON(可能未登录或 API Key 失效)'); } return JSON.parse(text); }); } function parsePlaytimeTextToMinutes(text) { if (!text) return 0; const t = text.trim(); const m1 = t.match(/([\d.]+)\s*hrs?/i); if (m1) return Math.round(parseFloat(m1[1]) * 60); const m2 = t.match(/([\d.]+)\s*小时/); if (m2) { const h = parseFloat(m2[1]); const minM = t.match(/(\d+)\s*分钟/); const min = minM ? parseInt(minM[1], 10) : 0; return Math.round(h * 60 + min); } const m3 = t.match(/(\d+)\s*minutes?/i); if (m3) return parseInt(m3[1], 10); return 0; } function parseLastPlayedToTs(text) { if (!text) return 0; const t = text.trim(); if (!/last|最后|上次|play|今天|昨天|前天|\d{4}年|days?|hours?/i.test(t)) return 0; const now = Math.floor(Date.now() / 1000); if (/今天|just now|几分钟前|a few minutes ago/i.test(t)) return now; if (/昨天|yesterday/i.test(t)) return now - 86400; if (/前天/i.test(t)) return now - 2 * 86400; const dayM = t.match(/(\d+)\s*天前|(\d+)\s*days?\s*ago/i); if (dayM) return now - parseInt(dayM[1] || dayM[2], 10) * 86400; return now; } async function fetchGamesPage(steamId, tab = 'all') { if (!steamId) return { games: [], total: 0 }; const url = `https://steamcommunity.com/profiles/${steamId}/games/?tab=${tab}`; try { const text = await sglvGmFetchTextRetry(url, { timeout: 20000 }); const doc = new DOMParser().parseFromString(text, 'text/html'); const rows = doc.querySelectorAll('.gameListRow'); const games = []; rows.forEach(row => { const appid = parseInt(row.id?.replace('game_', '') || row.dataset?.appid || '0', 10); if (!appid) return; const name = row.querySelector('.gameListRowItemName, .gameListRowItem h2, .gameListRowItem .gameListRowItemName')?.textContent?.trim() || row.querySelector('a[href*="/app/"]')?.textContent?.trim() || ''; const logoImg = row.querySelector('img.gameListLogo, img[src*="capsule"], img[src*="header"]'); const logoSrc = logoImg?.getAttribute('src') || ''; const playtimeEl = row.querySelector('.gameListRowItem .gameListRowItemHours, .hours_played, .gameListRowItem .gameListRowItemTime, .gameListRowItem .gameListRowItemStat'); const playtimeText = playtimeEl?.textContent?.trim() || ''; const playtime = parsePlaytimeTextToMinutes(playtimeText); const lastPlayedText = row.querySelector('.gameListRowItem .gameListRowItemLastPlayed, .last_played, .gameListRowItem .gameListRowItemTime')?.textContent?.trim() || ''; const lastPlayed = parseLastPlayedToTs(lastPlayedText); games.push({ appid, name: name || `App ${appid}`, playtime_forever: playtime, playtime_2weeks: 0, rtime_last_played: lastPlayed, img_icon_url: '', logoSrc }); }); const totalEl = doc.querySelector('.gameListRowItem .gameListRowItemCount, .gameListRow .gameListRowItem .gameListRowItemCount'); const totalText = totalEl?.textContent || ''; const totalMatch = totalText.match(/(\d+)/); const total = totalMatch ? parseInt(totalMatch[1], 10) : games.length; return { games, total }; } catch (e) { console.warn('[SGLV] games 页抓取失败:', e); return { games: [], total: 0 }; } } const _computedCache = new Map(); const _PCC_CACHE = C.PersistentComputeCache || null; const _COMPUTE_CACHE_SCHEMA_VER = 1; let _pccHydrated = false; function cacheKey(...parts) { return parts.map(p => JSON.stringify(p)).join('|'); } function getCached(key, computeFn) { if (_computedCache.has(key)) return _computedCache.get(key); const v = computeFn(); _computedCache.set(key, v); if (_PCC_CACHE) { try { _PCC_CACHE.set(key, _COMPUTE_CACHE_SCHEMA_VER, key, v); } catch (e) { } } return v; } function hydrateComputedCache() { if (_pccHydrated) return 0; if (!_PCC_CACHE) { _pccHydrated = true; return 0; } try { const pccMem = _PCC_CACHE._mem || {}; let count = 0; for (const k of Object.keys(pccMem)) { if (!_computedCache.has(k)) { const entry = pccMem[k]; if (entry && entry.value !== undefined && entry._ver === _COMPUTE_CACHE_SCHEMA_VER) { _computedCache.set(k, entry.value); count++; } } } _pccHydrated = true; if (count > 0) console.log(`[SGLV-Compute] PCC IDB 预热 ${count} 条已缓存计算结果到 _computedCache`); return count; } catch (e) { console.warn('[SGLV-Compute] PCC hydrate 失败:', e); _pccHydrated = true; return 0; } } function clearComputedCache() { console.log('[SGLV-Compute] clearComputedCache 被调用 — 失效所有计算缓存'); _computedCache.clear(); if (_PCC_CACHE) { try { _PCC_CACHE.clear(); } catch (e) { } } _pccHydrated = true; _cachedActiveOwnedAppIds = null; _cachedActiveOwnedAppIdsKey = ''; _cachedDlcCount = null; _cachedDlcCountKey = ''; _cachedStatFiltered = null; _cachedStatFilteredSig = ''; if (SGLV_API.invalidateAppTypeCache) SGLV_API.invalidateAppTypeCache(); const hadDlcTypeMap = !!dlcTypeMap; dlcTypeMap = null; _dlcsByParentCache = null; console.log(`[SGLV-Compute] clearComputedCache 完成 — dlcTypeMap ${hadDlcTypeMap ? '已失效 (之前有数据)' : '本就为空'},appTypeCache 已失效,DLC 数量缓存已失效,statFiltered 已失效,dlcsByParent 已失效`); } function getBizCached(key, schemaVer, inputSig, computeFn) { if (!_PCC_CACHE) return computeFn(); const meta = _PCC_CACHE.getSyncWithMeta(key); if (meta && meta._ver === schemaVer && meta._sig === inputSig) { return meta.value; } const v = computeFn(); try { _PCC_CACHE.set(key, schemaVer, inputSig, v); } catch (e) { } return v; } function getGameDBMeta(appid) { for (const [pubName, pubData] of Object.entries(GAME_DB)) { for (const [seriesName, games] of Object.entries(pubData)) { if (games.some(g => g.id === appid)) { return { publisher: pubName, series: seriesName }; } } } return { publisher: '', series: '' }; } function communityIconChainUrls(appid, iconHash) { const cf = 'https://cdn.cloudflare.steamstatic.com'; const ak = 'https://cdn.akamai.steamstatic.com'; const shAk = 'https://shared.akamai.steamstatic.com'; const shF = 'https://shared.fastly.steamstatic.com'; const urls = []; if (iconHash) { urls.push(`${shF}/community_assets/images/apps/${appid}/${iconHash}.jpg`); urls.push(`${shAk}/community_assets/images/apps/${appid}/${iconHash}.jpg`); urls.push(`${cf}/steamcommunity/public/images/apps/${appid}/${iconHash}.jpg`); urls.push(`${ak}/steamcommunity/public/images/apps/${appid}/${iconHash}.jpg`); } urls.push(`${cf}/steam/apps/${appid}/capsule_sm_120.jpg`); urls.push(`${ak}/steam/apps/${appid}/capsule_sm_120.jpg`); urls.push(`${shAk}/store_item_assets/steam/apps/${appid}/capsule_sm_120.jpg`); urls.push(`${shF}/store_item_assets/steam/apps/${appid}/capsule_sm_120.jpg`); return urls; } function getGameIconUrl(appid, iconHash) { const good = getPosterGood(appid, 'icon'); if (good) return good; if (iconHash) return `https://shared.fastly.steamstatic.com/community_assets/images/apps/${appid}/${iconHash}.jpg`; return `https://cdn.cloudflare.steamstatic.com/steam/apps/${appid}/capsule_sm_120.jpg`; } function sglvIconFallback(img, appid, iconHash) { if (!img || !appid) return; const cur = img.getAttribute('src') || ''; const good = getPosterGood(appid, 'icon'); if (good && good !== cur) { img.onerror = function () { img.onerror = null; sglvIconFallback(img, appid, iconHash); }; img.onload = function () { img.onload = null; }; img.src = good; return; } const chain = communityIconChainUrls(appid, iconHash); let start = chain.indexOf(cur) + 1; const tryNext = (i) => { if (i >= chain.length) { img.onerror = function () { img.onerror = null; img.style.display = 'none'; }; img.src = `https://cdn.cloudflare.steamstatic.com/steam/apps/${appid}/header.jpg`; return; } img.onerror = function () { img.onerror = null; tryNext(i + 1); }; img.onload = function () { recordPosterGood(appid, img.src, 'icon'); img.onload = null; }; img.src = chain[i]; }; tryNext(start); } unsafeWindow._sglvIconFallback = sglvIconFallback; function coverChainUrls(appid, kind) { const cf = `https://cdn.cloudflare.steamstatic.com/steam/apps/${appid}`; const ak = `https://cdn.akamai.steamstatic.com/steam/apps/${appid}`; const sh = `https://shared.akamai.steamstatic.com/store_item_assets/steam/apps/${appid}`; const sf = `https://shared.fastly.steamstatic.com/store_item_assets/steam/apps/${appid}`; if (kind === 'poster') { return [ `${cf}/library_600x900_2x.jpg`, `${cf}/library_600x900.jpg`, `${ak}/library_600x900_2x.jpg`, `${ak}/library_600x900.jpg`, `${sh}/library_600x900_2x.jpg`, `${sh}/library_600x900.jpg`, `${sf}/library_600x900_2x.jpg`, `${sf}/library_600x900.jpg`, `${cf}/header.jpg`, `${ak}/header.jpg`, `${sh}/header.jpg`, `${sf}/header.jpg`, ]; } if (kind === 'capsule') { return [ `${cf}/capsule_467x181.jpg`, `${cf}/capsule_231x87.jpg`, `${cf}/header.jpg`, `${ak}/capsule_231x87.jpg`, `${ak}/header.jpg`, `${sh}/capsule_184x69.jpg`, `${sh}/header.jpg`, `${sf}/capsule_184x69.jpg`, `${sf}/header.jpg`, ]; } return [`${cf}/header.jpg`, `${ak}/header.jpg`, `${sh}/header.jpg`, `${sf}/header.jpg`]; } const _posterApiCache = new Map(); const _posterApiPending = new Map(); const _posterApiNeg = new Map(); const POSTER_API_NEG_TTL = 10 * 60 * 1000; const POSTER_API_NEG_MAX = 600; function _markPosterApiNeg(cacheKey) { _posterApiNeg.delete(cacheKey); _posterApiNeg.set(cacheKey, Date.now()); if (_posterApiNeg.size > POSTER_API_NEG_MAX) { const it = _posterApiNeg.keys(); while (_posterApiNeg.size > POSTER_API_NEG_MAX) { const n = it.next(); if (n.done) break; _posterApiNeg.delete(n.value); } } } function _posterApiNegHit(cacheKey) { const t = _posterApiNeg.get(cacheKey); if (!t) return false; if ((Date.now() - t) < POSTER_API_NEG_TTL) return true; _posterApiNeg.delete(cacheKey); return false; } function _posterImgToPlaceholder(img) { if (!img || !img.parentElement) return; const holder = document.createElement('div'); holder.className = img.className; holder.style.cssText = 'display:flex;align-items:center;justify-content:center;color:#5a6a7a;font-size:11px'; holder.textContent = isZh ? '无图片' : 'No Image'; img.parentElement.replaceChild(holder, img); } function _fetchCoverApiUrl(appid, kind) { const k = kind || 'poster'; const good = getPosterGood(appid, k); if (good) return Promise.resolve(good); return _legacyFetchCoverApiUrl(appid, k); } function _legacyFetchCoverApiUrl(appid, kind) { const k = kind || 'poster'; const cacheKey = `${appid}:${k}`; if (_posterApiCache.has(cacheKey)) return Promise.resolve(_posterApiCache.get(cacheKey)); if (_posterApiPending.has(cacheKey)) return _posterApiPending.get(cacheKey); if (_posterApiNegHit(cacheKey)) return Promise.resolve(''); const url = `https://store.steampowered.com/api/appdetails?appids=${appid}&l=${isZh ? 'schinese' : 'english'}&filters=basic`; const p = sglvGmFetchRetry(url, { timeout: 10000, retries: 1 }) .then(data => { const entry = data && data[appid]; const d = entry && entry.success && entry.data; if (!d) { _markPosterApiNeg(cacheKey); return ''; } const u = (k === 'capsule' && d.capsule_image) ? d.capsule_image : (d.header_image || d.capsule_image || ''); const full = u && (u.startsWith('http') ? u : `https://cdn.cloudflare.steamstatic.com/steam/apps/${appid}/${u}`); if (full) { _posterApiCache.set(cacheKey, full); _posterApiNeg.delete(cacheKey); const naturalKind = full.indexOf('library_600x900') >= 0 ? 'poster' : 'header'; recordPosterGood(appid, full, naturalKind); try { const fb = window.SGLVCoverFallback; if (fb && typeof fb.recordGood === 'function') fb.recordGood(String(appid), full, naturalKind); } catch (e) { } } else { _markPosterApiNeg(cacheKey); } return full || ''; }) .catch(() => { _markPosterApiNeg(cacheKey); return ''; }); _posterApiPending.set(cacheKey, p); p.then(() => {}, () => {}).then(() => { _posterApiPending.delete(cacheKey); }); return p; } unsafeWindow._sglvPosterFallback = function(img, appid, kind) { if (!img || !img.isConnected) return; const k = kind || 'poster'; let managed = false; try { managed = !!img._sglvChainLoading || !!(img.closest && img.closest('[data-sglv-cover-handler-bound]')); } catch (e) { } if (managed) return; const cur = img.getAttribute('src') || ''; _fetchCoverApiUrl(appid, k).then(url => { if (url && url !== cur) { img.onerror = function() { img.onerror = null; _posterImgToPlaceholder(img); }; img.src = url; return; } _posterImgToPlaceholder(img); }, () => _posterImgToPlaceholder(img)); }; function coverImgTag(appid, name, kind, cls) { const k = kind || 'poster'; const fb = window.SGLVCoverFallback; const managed = !!(fb && typeof fb.chainLoad === 'function' && typeof fb.bindErrorHandler === 'function'); let first = getPosterGood(appid, k) || ''; if (!first && k !== 'poster' && k !== 'header') first = getPosterGood(appid, 'header') || ''; if (!first && fb && typeof fb.getCoverUrl === 'function') { try { first = fb.getCoverUrl(String(appid), k, isZh ? 'schinese' : '') || ''; } catch (e) { } } if (!first) first = coverChainUrls(appid, k)[0] || ''; const base = `class="${cls}" src="${first}" alt="${name}" loading="lazy" decoding="async" referrerpolicy="no-referrer"` + ` data-sglv-cover="1" data-appid="${appid}" data-kind="${k}"` + ` onload="_sglvRecordPosterGood('${appid}',this.src,'${k}')"`; if (managed) return `<img ${base}>`; return `<img ${base} onerror="if(this.dataset.fb){this.style.display='none'}else{this.dataset.fb='1';_sglvPosterFallback(this,'${appid}','${k}')}">`; } function posterImg(appid, name) { return coverImgTag(appid, name, 'poster', 'sglv-card-img'); } function headerImg(appid, name) { return coverImgTag(appid, name, 'header', 'sglv-card-img'); } function capsuleImg(appid, name) { return coverImgTag(appid, name, 'capsule', 'sglv-wl-cover-img'); } function _ensureCoverFallbackDelegation(root) { if (!root || root.__sglvCoverDelegated) return; const fb = window.SGLVCoverFallback; if (!fb || typeof fb.bindErrorHandler !== 'function') return; root.__sglvCoverDelegated = true; fb.bindErrorHandler(root, (img) => { if (img.nextElementSibling) img.nextElementSibling.style.display = 'flex'; try { const ph = document.createElement('div'); ph.className = (img.className || '') + ' sglv-cover-broken'; ph.textContent = isZh ? '无封面' : 'No Cover'; if (img.parentElement) img.parentElement.replaceChild(ph, img); } catch (e) { } }); } function renderPagination(container, prefix, page, totalPages, totalItems, onPrev, onNext, onJump) { if (!container) return; container.innerHTML = ` <button class="sglv-page-arrow sglv-page-text-btn" id="${prefix}-first" ${page <= 1 ? 'disabled' : ''}>${T.first}</button> <button class="sglv-page-arrow sglv-page-text-btn" id="${prefix}-prev" ${page <= 1 ? 'disabled' : ''}>${T.prev}</button> <button class="sglv-page-arrow sglv-page-text-btn" id="${prefix}-next" ${page >= totalPages ? 'disabled' : ''}>${T.next}</button> <button class="sglv-page-arrow sglv-page-text-btn" id="${prefix}-last" ${page >= totalPages ? 'disabled' : ''}>${T.last}</button> <input type="number" class="sglv-page-jump-input" id="${prefix}-jump" min="1" max="${totalPages}" value="${page}" title="${T.jumpTo}"> <span class="sglv-page-info">${page}/${totalPages} (${totalItems})</span> `; const goPage = (p) => { const target = Math.min(Math.max(1, p), totalPages); if (target === page) return; if (onJump) onJump(target); }; container.querySelector(`#${prefix}-first`)?.addEventListener('click', () => goPage(1)); container.querySelector(`#${prefix}-prev`)?.addEventListener('click', () => goPage(page - 1)); container.querySelector(`#${prefix}-next`)?.addEventListener('click', () => goPage(page + 1)); container.querySelector(`#${prefix}-last`)?.addEventListener('click', () => goPage(totalPages)); const jumpInput = container.querySelector(`#${prefix}-jump`); jumpInput?.addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); const p = parseInt(jumpInput.value); if (!isNaN(p)) goPage(p); } }); jumpInput?.addEventListener('blur', () => { const p = parseInt(jumpInput.value); if (!isNaN(p) && p >= 1 && p <= totalPages && p !== page) goPage(p); else jumpInput.value = page; }); } async function fetchFamilyGameList(authToken, onProgress) { const report = (stage, percent, text) => { if (typeof onProgress === 'function') onProgress(stage, percent, text); }; try { report(1, 25, '正在获取家庭组信息…'); const familyData = await requestSteamAPI( `https://api.steampowered.com/IFamilyGroupsService/GetFamilyGroupForUser/v1/?access_token=${authToken}&include_family_group_response=true` ); if (!familyData?.response?.family_groupid) { report(1, 100, '家庭组信息为空'); return null; } const familyGroupId = familyData.response.family_groupid; report(2, 50, '正在获取家庭组共享游戏库…'); const gameData = await requestSteamAPI( `https://api.steampowered.com/IFamilyGroupsService/GetSharedLibraryApps/v1/?access_token=${authToken}&family_groupid=${familyGroupId}&include_own=true&include_excluded=false&include_non_games=false` ); report(3, 80, '正在整理共享游戏数据…'); if (gameData?.response?.apps) { const apps = gameData.response.apps; const games = apps .filter(app => app.exclude_reason === 0) .map(app => ({ appid: app.appid, name: app.name || `App ${app.appid}`, playtime: 0, icon: app.img_icon_hash || '', lastPlayed: app.rt_time_acquired || 0, acquiredTime: app.rt_time_acquired || 0, owners: app.owner_steamids || [], })); report(4, 100, `已获取 ${games.length} 款家庭组共享游戏`); return games; } } catch (e) { console.warn('[SGLV] fetchFamilyGameList error:', e); } return null; } async function fetchOwnedGames(steamId, authToken) { const apiKey = storage.getApiKey(); if (apiKey) { try { const data = await requestSteamAPI( `https://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=${apiKey}&steamid=${steamId}&include_appinfo=1&include_played_free_games=1&format=json` ); if (data?.response?.games) { console.log(`[SGLV] 通过 API Key 获取 ${data.response.games.length} 款游戏(含时长)`); return { games: data.response.games.map(g => ({ appid: g.appid, name: g.name || `App ${g.appid}`, playtime: g.playtime_forever || 0, icon: g.img_icon_url || '', lastPlayed: g.rtime_last_played || 0, _source: 'api', })), source: 'api' }; } } catch (e) { console.warn('[SGLV] API Key 获取失败:', e); } } if (authToken && steamId) { try { const data = await requestSteamAPI( `https://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?access_token=${authToken}&steamid=${steamId}&include_appinfo=1&include_played_free_games=1&format=json` ); if (data?.response?.games) { console.log(`[SGLV] 通过 access_token 获取 ${data.response.games.length} 款游戏(含时长)`); return { games: data.response.games.map(g => ({ appid: g.appid, name: g.name || `App ${g.appid}`, playtime: g.playtime_forever || 0, icon: g.img_icon_url || '', lastPlayed: g.rtime_last_played || 0, _source: 'api', })), source: 'api' }; } } catch (e) { console.warn('[SGLV] access_token 获取游戏时长失败:', e); } } if (steamId) { try { const scraped = await fetchGamesPage(steamId, 'all'); if (scraped.games.length > 0) { console.log(`[SGLV] 通过页面抓取获取 ${scraped.games.length} 款游戏(含时长)`); return { games: scraped.games.map(g => ({ appid: g.appid, name: g.name, playtime: g.playtime_forever, icon: g.img_icon_url || '', lastPlayed: g.rtime_last_played, _source: 'scrape', })), source: 'scrape' }; } } catch (e) { console.warn('[SGLV] 页面抓取 fallback 失败:', e); } } return { games: [], source: null }; } async function fetchFamilyInfo(authToken) { try { const data = await requestSteamAPI( `https://api.steampowered.com/IFamilyGroupsService/GetFamilyGroupForUser/v1/?access_token=${authToken}&include_family_group_response=true` ); if (data?.response?.family_group) { const fg = data.response.family_group; const members = fg.members || []; const nameMap = {}; if (members.length > 0) { const steamids = members.map(m => m.steamid); const batchSize = 100; for (let i = 0; i < steamids.length; i += batchSize) { const batch = steamids.slice(i, i + batchSize); const params = batch.map((sid, idx) => `steamids[${idx}]=${sid}`).join('&'); try { const pData = await requestSteamAPI( `https://api.steampowered.com/IPlayerService/GetPlayerLinkDetails/v1/?access_token=${authToken}&${params}` ); if (pData?.response?.accounts) { pData.response.accounts.forEach(acc => { if (acc.public_data) { const sid = acc.public_data.steamid || acc.steamid; if (sid && acc.public_data.persona_name) { nameMap[sid] = acc.public_data.persona_name; } } }); } } catch (e) { } } } return { family_groupid: data.response.family_groupid, family_name: fg.name || 'Steam Family', family_member: members.map(m => ({ steamid: m.steamid, userName: nameMap[m.steamid] || '' })), steamIdtoName: nameMap }; } } catch (e) { console.warn('[SGLV] fetchFamilyInfo error:', e); } return null; } async function fetchAllGames(onProgress) { const gamesMap = new Map(); const report = (sub, pct, text) => { if (typeof onProgress === 'function') onProgress(sub, pct, text); }; report(1, 10, isZh ? '正在准备访问令牌…' : 'Preparing access token…'); const authToken = await getAccessToken(); const steamId = getActiveSteamId(); if (steamId) { report(1, 20, isZh ? '正在拉取个人游戏…' : 'Fetching owned games…'); const owned = await fetchOwnedGames(steamId, authToken); if (owned.games.length > 0) { owned.games.forEach(g => { gamesMap.set(g.appid, { appid: g.appid, name: g.name, playtime: g.playtime || 0, icon: g.icon || '', lastPlayed: g.lastPlayed || 0, owners: [], acquiredTime: 0, _source: g._source || owned.source, }); }); console.log(`[SGLV] 个人游戏来源: ${owned.source || 'none'}, 共 ${owned.games.length} 款`); } } if (authToken) { report(2, 50, isZh ? '正在拉取家庭组…' : 'Fetching family…'); const familyInfo = await fetchFamilyInfo(authToken); if (familyInfo) storage.setFamilyInfo(familyInfo); const familyGames = await fetchFamilyGameList(authToken); if (familyGames && familyGames.length > 0) { familyGames.forEach(g => { const existing = gamesMap.get(g.appid); if (!existing) { gamesMap.set(g.appid, { appid: g.appid, name: g.name, playtime: 0, icon: g.icon || '', lastPlayed: g.lastPlayed || 0, owners: g.owners || [], acquiredTime: g.acquiredTime || 0, _source: 'family', }); } else { if (g.owners && g.owners.length) existing.owners = g.owners; if (g.acquiredTime) existing.acquiredTime = g.acquiredTime; } }); try { const all = Array.from(gamesMap.values()); if (all.some(g => (g.owners || []).length > 1)) { const licenseMap = await fetchPersonalLicenseMap(); const corrections = licenseCorrectionsFor(all, licenseMap || {}); let n = 0; gamesMap.forEach(g => { const c = corrections[g.appid]; if (c) { g.acquiredTime = c; n++; } }); if (n > 0) console.log(`[SGLV] 个人入库时间校准:${n} 款共拥游戏已按个人许可页日期修正`); const sid0 = String(steamId || '').trim(); if (sid0) { let zeroed = 0; gamesMap.forEach(g => { const owners = g.owners || []; if (owners.length < 2 || g.acquiredTime <= 0) return; const mine = owners.some(o => String(o).trim() === sid0); const lastIsMe = String(owners[owners.length - 1]).trim() === sid0; if (mine && !lastIsMe && !corrections[g.appid]) { g.acquiredTime = 0; zeroed++; } }); if (zeroed > 0) console.log(`[SGLV] ${zeroed} 款家人购买的共拥游戏入库时间已清零(无本人购买时间,回退估算口径)`); } } } catch (e) { console.warn('[SGLV] 入库时间校准失败(保留家庭组时间):', e); } console.log(`[SGLV] 通过 access_token 获取家庭共享 ${familyGames.length} 款游戏`); } } report(3, 80, isZh ? '正在补充遗漏游戏…' : 'Supplementing missing games…'); const dsOwnedAppIds = await fetchDynamicStoreOwnedAppIds(); if (dsOwnedAppIds && dsOwnedAppIds.size > 0) { let supplemented = 0; dsOwnedAppIds.forEach(appid => { if (!gamesMap.has(appid)) { gamesMap.set(appid, { appid, name: `App ${appid}`, playtime: 0, icon: '', lastPlayed: 0, owners: [], acquiredTime: 0, _source: 'dynamicstore', }); supplemented++; } }); if (supplemented > 0) { console.log(`[SGLV] dynamicstore/userdata 补充 ${supplemented} 款 GetOwnedGames 遗漏的游戏(CD key/促销许可等)`); } } report(3, 100, isZh ? '库存拉取完成' : 'Done'); return Array.from(gamesMap.values()); } let _timelineFamilyGamesCache = null; let _heatmapRenderCache = null; const LICENSE_MAP_TTL = 24 * 60 * 60 * 1000; const MAX_LICENSE_PAGES = 50; let _licenseMapCache = null; function parseLicenseDate(dateStr) { if (!dateStr) return 0; let m = dateStr.match(/(\d{4})年(\d{1,2})月(\d{1,2})日/); if (m) return new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3])).getTime(); const months = { Jan:0, Feb:1, Mar:2, Apr:3, May:4, Jun:5, Jul:6, Aug:7, Sep:8, Oct:9, Nov:10, Dec:11 }; m = dateStr.match(/(\d{1,2})\s+(\w{3})\s+(\d{4})/); if (m && months[m[2]] != null) return new Date(Number(m[3]), months[m[2]], Number(m[1])).getTime(); m = dateStr.match(/(\w{3})\s+(\d{1,2}),?\s+(\d{4})/); if (m && months[m[1]] != null) return new Date(Number(m[3]), months[m[1]], Number(m[2])).getTime(); return 0; } function parseLicenseRows(html, map) { try { const doc = new DOMParser().parseFromString(html, 'text/html'); doc.querySelectorAll('.license_row').forEach(row => { const link = row.querySelector('a[href*="/app/"]'); if (!link) return; const appMatch = (link.getAttribute('href') || '').match(/\/app\/(\d+)/); if (!appMatch) return; const dateEl = row.querySelector('.license_date_col'); if (!dateEl) return; const label = dateEl.querySelector('.license_date_col_label'); if (label) label.remove(); const dateText = (dateEl.textContent || '').trim(); const ts = parseLicenseDate(dateText); const appid = Number(appMatch[1]); if (appid && ts) map[appid] = { dateStr: dateText, ts }; }); } catch (e) { console.warn('[SGLV] 许可页 HTML 解析失败:', e); } } let _licenseMapPromise = null; function fetchPersonalLicenseMap() { if (_licenseMapCache && Date.now() - _licenseMapCache.ts < LICENSE_MAP_TTL) return Promise.resolve(_licenseMapCache.map); if (_licenseMapPromise) return _licenseMapPromise; _licenseMapPromise = (async () => { const map = {}; let fetchFailed = false; try { const html = await sglvGmFetchTextRetry('https://store.steampowered.com/account/licenses/?l=schinese', { timeout: 15000, retries: 1 }); parseLicenseRows(html, map); const sidMatch = (html || '').match(/g_sessionID\s*=\s*"([^"]+)"/); const sessionid = sidMatch ? sidMatch[1] : null; const hasMore = html.includes('load_more_licenses') || html.includes('btn_load_more'); if (hasMore && sessionid) { let cursor = ''; for (let pages = 0; pages < MAX_LICENSE_PAGES; pages++) { const data = await sglvGmFetchRetry('https://store.steampowered.com/account/AjaxLoadMoreLicenses/', { method: 'POST', timeout: 15000, retries: 1, headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, data: `sessionid=${encodeURIComponent(sessionid)}&cursor=${encodeURIComponent(cursor)}`, }); if (data && data.html) parseLicenseRows(data.html, map); if (!(data && data.has_more && data.cursor)) break; cursor = data.cursor; } } } catch (e) { fetchFailed = true; console.warn('[SGLV] 个人许可页获取失败(跳过入库时间校准):', e.message || e); } finally { _licenseMapPromise = null; } if (!fetchFailed) { _licenseMapCache = { map, ts: Date.now() }; if (Object.keys(map).length > 0) console.log(`[SGLV] 个人许可页入库日期已获取:${Object.keys(map).length} 条`); } return map; })(); return _licenseMapPromise; } function licenseCorrectionsFor(games, licenseMap) { const corrections = {}; if (!Array.isArray(games) || !licenseMap) return corrections; for (const g of games) { if (!(g.acquiredTime > 0)) continue; const lic = licenseMap[g.appid]; if (!lic || !lic.ts) continue; const d1 = new Date(g.acquiredTime * 1000); d1.setHours(0, 0, 0, 0); const d2 = new Date(lic.ts); d2.setHours(0, 0, 0, 0); if (d1.getTime() !== d2.getTime()) corrections[g.appid] = Math.floor(lic.ts / 1000); } return corrections; } function isMyAcquisitionEvent(g, mySteamId) { const owners = (g && g.owners) || []; if (!mySteamId || owners.length === 0) return true; const sid = String(mySteamId).trim(); if (!owners.some(o => String(o).trim() === sid)) return false; if (owners.length === 1) return true; return String(owners[owners.length - 1]).trim() === sid; } async function buildCalibratedAcquiredMap() { const familyGames = await fetchTimelineFamilyGames(); if (!familyGames || familyGames.length === 0) return { games: null, map: {}, corrected: new Set() }; const map = {}; for (const g of familyGames) { if (g.acquiredTime > 0) map[g.appid] = g.acquiredTime; } const hasCoOwned = familyGames.some(g => (g.owners || []).length > 1); let corrected = new Set(); if (hasCoOwned) { const licenseMap = await fetchPersonalLicenseMap(); const corrections = licenseCorrectionsFor(familyGames, licenseMap || {}); for (const appid in corrections) { map[appid] = corrections[appid]; corrected.add(Number(appid)); } if (corrected.size > 0) console.log(`[SGLV] 个人入库时间校准:${corrected.size} 款共拥游戏已按个人许可页日期修正`); } const mySid = String(getActiveSteamId() || '').trim(); if (mySid && hasCoOwned) { let dropped = 0; for (const g of familyGames) { const owners = g.owners || []; if (owners.length < 2) continue; const mine = owners.some(o => String(o).trim() === mySid); const lastIsMe = String(owners[owners.length - 1]).trim() === mySid; if (mine && !lastIsMe && !corrected.has(g.appid)) { if (map[g.appid] !== undefined) { delete map[g.appid]; dropped++; } } } if (dropped > 0) console.log(`[SGLV] 个人入库动态:${dropped} 款家人购买的共拥游戏已排除(无本人购买时间)`); } return { games: familyGames, map, corrected }; } async function fetchTimelineFamilyGames(onProgress) { const report = (stage, percent, text) => { if (typeof onProgress === 'function') onProgress(stage, percent, text); }; if (_timelineFamilyGamesCache && Date.now() - _timelineFamilyGamesCache.ts < 10 * 60 * 1000) { report(4, 100, `已从缓存载入 ${_timelineFamilyGamesCache.games.length} 款家庭组游戏`); return _timelineFamilyGamesCache.games; } const hasStaleCache = _timelineFamilyGamesCache && _timelineFamilyGamesCache.games.length > 0; if (hasStaleCache) { report(4, 100, `已从缓存载入 ${_timelineFamilyGamesCache.games.length} 款家庭组游戏`); _refreshTimelineCacheInBackground(); return _timelineFamilyGamesCache.games; } try { report(1, 8, '正在准备访问令牌…'); const authToken = await getAccessToken(); if (authToken) { const games = await fetchFamilyGameList(authToken, (stage, percent, text) => { const mapped = 10 + percent * 0.9; report(Math.min(4, stage + 1), Math.min(99, mapped), text); }); if (games && games.length > 0) { const appidSet = new Set(games.map(g => g.appid)); _timelineFamilyGamesCache = { games, ts: Date.now(), appidSet }; report(4, 100, `已获取 ${games.length} 款家庭组共享游戏`); return games; } } } catch (e) { console.warn('[SGLV] 动态页家庭组数据获取失败:', e); } const fb = (state.ownedGames && state.ownedGames.length > 0) ? state.ownedGames : null; report(4, 100, fb ? `已使用本地游戏库(${fb.length} 款)作为回退` : '家庭组数据不可用'); return fb; } async function _refreshTimelineCacheInBackground() { try { const authToken = await getAccessToken(); if (!authToken) return; const freshGames = await fetchFamilyGameList(authToken); if (!freshGames || freshGames.length === 0) return; const oldCache = _timelineFamilyGamesCache; if (!oldCache) { const appidSet = new Set(freshGames.map(g => g.appid)); _timelineFamilyGamesCache = { games: freshGames, ts: Date.now(), appidSet }; return; } const oldSet = oldCache.appidSet || new Set(oldCache.games.map(g => g.appid)); const newGames = freshGames.filter(g => !oldSet.has(g.appid)); if (newGames.length > 0) { const freshMap = new Map(freshGames.map(g => [g.appid, g])); const mergedGames = oldCache.games.map(g => { const fresh = freshMap.get(g.appid); return fresh ? { ...g, ...fresh } : g; }); mergedGames.push(...newGames); const mergedSet = new Set(mergedGames.map(g => g.appid)); _timelineFamilyGamesCache = { games: mergedGames, ts: Date.now(), appidSet: mergedSet }; console.log(`[SGLV] 时间线增量更新:新增 ${newGames.length} 款,总计 ${mergedGames.length} 款`); } else { _timelineFamilyGamesCache.ts = Date.now(); } } catch (e) { console.warn('[SGLV] 时间线后台增量刷新失败:', e); if (_timelineFamilyGamesCache) _timelineFamilyGamesCache.ts = Date.now(); } } async function buildPersonalTimeline(steamId) { const { games: familyGames, map: acquiredMap, corrected } = await buildCalibratedAcquiredMap(); if (!familyGames || familyGames.length === 0) return null; const mySteamId = String(steamId || getActiveSteamId() || '').trim(); const items = []; for (const g of familyGames) { const acquired = acquiredMap[g.appid] || 0; if (!acquired) continue; const owners = g.owners || []; if (mySteamId && owners.length > 0 && !owners.some(sid => String(sid).trim() === mySteamId)) continue; if (!isMyAcquisitionEvent(g, mySteamId) && !corrected.has(g.appid)) continue; const ts = acquired * 1000; const dateStr = new Date(ts).toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }); items.push({ appid: g.appid, name: g.name || `App ${g.appid}`, ts, dateStr, icon: g.icon || '', playtime: g.playtime || 0, licenseCorrected: corrected.has(g.appid), }); } items.sort((a, b) => (b.ts || 0) - (a.ts || 0)); return { items, total: items.length, corrected: corrected.size }; } async function buildFamilyTimeline(steamId, onProgress) { const report = (stage, percent, text) => { if (typeof onProgress === 'function') onProgress(stage, percent, text); }; const familyGames = await fetchTimelineFamilyGames((stage, percent, text) => { report(stage, percent, text); }); if (!familyGames || familyGames.length === 0) return null; let nameMap = (storage.getFamilyInfo() || {}).steamIdtoName || null; if (!nameMap) { try { const token = await getAccessToken(); if (token) { const fi = await fetchFamilyInfo(token); if (fi) { storage.setFamilyInfo(fi); nameMap = fi.steamIdtoName || {}; } } } catch (e) { console.warn('[SGLV] 家庭组成员名称获取失败(购买者显示降级为仅时间):', e); } } nameMap = nameMap || {}; const items = []; const total = familyGames.length; const BATCH = 200; const yieldFrame = () => new Promise(r => requestAnimationFrame(() => r())); for (let i = 0; i < total; i++) { const g = familyGames[i]; const acquired = g.acquiredTime || 0; if (acquired) { const ts = acquired * 1000; const dateStr = new Date(ts).toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }); const owners = g.owners || []; items.push({ appid: g.appid, name: g.name || `App ${g.appid}`, ts, dateStr, icon: g.icon || '', playtime: g.playtime || 0, owners, purchaserName: owners.length ? String(nameMap[owners[owners.length - 1]] || '').trim() : '', }); } if ((i + 1) % BATCH === 0 && i + 1 < total) { const pct = 50 + Math.round((i + 1) / total * 45); report(4, pct, `已整理 ${i + 1} / ${total} 款游戏…`); await yieldFrame(); } } items.sort((a, b) => (b.ts || 0) - (a.ts || 0)); report(4, 100, `整理完成:共 ${items.length} 条入库记录`); return { items, total: items.length }; } const CollectionHost = { apiVersion: 1, getOwnedGames: () => state.ownedGames, getActiveOwnedAppIds, isGameOwnedByMe, getGameOwnerNames, getShowFamilyShared: () => storage.getShowFamilyShared(), getGameDb: () => supplierDbOverride || GAME_DB, getSeriesDb: () => seriesDb, loadSeriesData, loadSupplierData, getSupplierFetchedAt: () => supplierFetchedAt, getDelistedDb: () => _getDelistedDb(), getResourceText: (name) => { try { return GM_getResourceText(name); } catch (e) { return null; } }, fetchGameZhName, fetchGameEnName, loadGameZhName, coverChainUrls, posterImg, capsuleImg, getGameIconUrl, getPosterGood, recordPosterGood, fetchCoverApiUrl: _fetchCoverApiUrl, renderPagination, paginate, showToast, wlEscape, escHtml, h, formatLastPlayedShort, cacheKey, getCached, cacheGet, cacheSet, cacheDelete, cacheTTL: CACHE_TTL, T, ICONS, isZh, loadBlockedApps, isBlockedApp, isBlockedLoaded: () => state.blockedLoaded, getBlockedApps: () => state.blockedApps, getBlockedSource: () => state.blockedSource, getBlockedFetchedAt: () => (typeof SGLV_API.getBlockedFetchedAt === 'function') ? SGLV_API.getBlockedFetchedAt() : '', parseManualBlockedJson, isDlc, isDlcDbReady: () => !!(dlcDbData || appTypeMap), loadDlcDatabase, loadDlcDatabaseFromCacheSync, enrichOwnedAppTypes, enrichDlcTypes, getDlcType, getBundleCount, isBundleDbReady: () => !!bundleDbData, loadBundleDatabase, getDlcParent: (dlcAppId) => { const e = dlcDbData && dlcDbData[String(dlcAppId)]; return e ? e.base_appID : null; }, getParentDlcTotalMap: () => { const map = {}; if (dlcDbData) { for (const info of Object.values(dlcDbData)) { if (info && info.base_appID) { map[info.base_appID] = (map[info.base_appID] || 0) + 1; } } } console.log(`[SGLV-DLC] getParentDlcTotalMap — 构建 ${Object.keys(map).length} 个父游戏的 DLC 总数映射 (dlcDbData=${dlcDbData ? Object.keys(dlcDbData).length + '条' : 'null'})`); return map; }, getDlcsByParentMap: () => { if (_dlcsByParentCache) return _dlcsByParentCache; const map = {}; if (dlcDbData) { for (const [dlcAppId, info] of Object.entries(dlcDbData)) { if (info && info.base_appID) { const key = String(info.base_appID); if (!map[key]) map[key] = []; map[key].push(Number(dlcAppId)); } } } _dlcsByParentCache = map; console.log(`[SGLV-DLC] getDlcsByParentMap — 构建 ${Object.keys(map).length} 个父游戏的 DLC 列表映射`); return map; }, }; let _collectionReady = false; if (window.SGLVCollection && typeof window.SGLVCollection.init === 'function') { _collectionReady = window.SGLVCollection.init(CollectionHost); if (!_collectionReady) { console.warn('[SGLV] 收藏模块握手失败 (apiVersion 不匹配)'); } } else { console.warn('[SGLV] 收藏模块库未加载 — 收藏功能不可用 (请检查 @require 或 Tampermonkey 外部资源设置)'); } if (window.SGLVCollection) window.SGLVCollection._hostReady = _collectionReady; let _shelfReady = false; if (window.SGLVShelf && typeof window.SGLVShelf.init === 'function') { const ShelfHost = { apiVersion: 1, isZh: isZh, getSteamId: () => storage.getSteamId(), toast: sglvToast, resolveName: async (appid) => { try { const AD = (typeof unsafeWindow !== 'undefined' && unsafeWindow.SGLVAppDetail) || window.SGLVAppDetail; if (AD && typeof AD.loadDetail === 'function') { const d = await AD.loadDetail(appid); return (d && d.name) || ''; } } catch (e) { } return ''; }, openUrl: (url) => { try { window.open(url, '_blank', 'noopener'); } catch (e) { location.href = url; } }, }; _shelfReady = window.SGLVShelf.init(ShelfHost); if (!_shelfReady) console.warn('[SGLV] 暂存箱握手失败 (apiVersion 不匹配)'); } else { console.warn('[SGLV] 暂存箱库未加载 — 暂存箱功能不可用'); } if (window.SGLVShelf) window.SGLVShelf._hostReady = _shelfReady; let _cloudSaveReady = false; if (window.SGLVCloudSave && typeof window.SGLVCloudSave.init === 'function') { const CloudSaveHost = { apiVersion: 1, isZh, showToast, cacheGet, cacheSet, cacheDelete, cacheTTL: CACHE_TTL, storage: { getCloudSaveData: storage.getCloudSaveData, setCloudSaveData: storage.setCloudSaveData, }, }; _cloudSaveReady = window.SGLVCloudSave.init(CloudSaveHost); if (!_cloudSaveReady) { console.warn('[SGLV] 云存档模块握手失败 (apiVersion 不匹配)'); } } else { console.warn('[SGLV] 云存档模块库未加载 — 云存档功能不可用 (请检查 @require 或 Tampermonkey 外部资源设置)'); } const ITAD_API_KEY_FALLBACK = '58eb2271a08c1cf60bd812d701d09d5c694f502e'; function getEffectiveItadKey() { const userKey = storage.getItadApiKey(); return userKey || ITAD_API_KEY_FALLBACK; } let _itadReady = false; if (window.SGLVITAD && typeof window.SGLVITAD.init === 'function') { window.SGLVITAD.init({ apiKey: getEffectiveItadKey() }); _itadReady = true; console.log('[SGLV] ITAD 价格增强库已加载' + (storage.getItadApiKey() ? ' (用户密钥)' : ' (兜底密钥)')); } else { console.warn('[SGLV] ITAD 库未加载 — 价格增强功能不可用 (请检查 @require)'); } const PT_HISTORY_KEY = nsKey('pt_daily_history'); const PT_HISTORY_DAYS = 90; const PT_HISTORY_FRESH_MS = 6 * 3600 * 1000; let _ptHistory = null; let _ptHistoryInflight = null; const SGLVCharts = { PALETTE: { purple: '#a78bfa', blue: '#3b82f6', cyan: '#06b6d4', teal: '#14b8a6', green: '#22c55e', amber: '#f59e0b', red: '#ef4444', pink: '#ec4899', gray: '#94a3b8', text: '#cbd5e1', textMuted: '#64748b', bgGrid: 'rgba(255,255,255,0.06)', bgCard: 'rgba(255,255,255,0.03)' }, accent() { return getThemeId() === 'blue' ? '#66c0f4' : '#a78bfa'; }, accentDeep() { return getThemeId() === 'blue' ? '#1a9fff' : '#8b5cf6'; }, accentGradient() { return getThemeId() === 'blue' ? 'linear-gradient(135deg, #1a9fff, #66c0f4)' : 'linear-gradient(135deg, #8b5cf6, #a78bfa)'; }, seriesColors() { return getThemeId() === 'blue' ? ['#66c0f4', '#8b5cf6', '#22c55e', '#f59e0b', '#ec4899'] : ['#a78bfa', '#38bdf8', '#22c55e', '#f59e0b', '#ec4899']; }, _seq: 0, _uid(type) { SGLVCharts._seq += 1; return `sglv-chart-${type}-${SGLVCharts._seq}`; }, svg(w, h, attrs = '') { return `<svg width="100%" viewBox="0 0 ${w} ${h}" preserveAspectRatio="xMidYMid meet" ${attrs}>`; }, gridLinesY(pL, pR, pT, cH, maxVal, gridCount = 5, fmt, minVal = 0, opts = null) { const o = opts || {}; const labelFill = o.labelFill || SGLVCharts.PALETTE.textMuted; const rightFill = o.rightLabelFill || labelFill; const lines = []; const hasMin = Number.isFinite(minVal) && minVal !== 0; for (let i = 0; i <= gridCount; i++) { const raw = hasMin ? minVal + (maxVal - minVal) * i / gridCount : maxVal / gridCount * i; const y = pT + cH - (cH * i / gridCount); const label = typeof fmt === 'function' ? fmt(raw) : Math.round(raw); lines.push(`<line x1="${pL}" y1="${y}" x2="${pR}" y2="${y}" stroke="${SGLVCharts.PALETTE.bgGrid}" />`); lines.push(`<text x="${pL - 8}" y="${y + 4}" text-anchor="end" fill="${labelFill}" font-size="11">${label}</text>`); if (o.rightMax != null) { const raw2 = o.rightMax / gridCount * i; const label2 = typeof o.rightFmt === 'function' ? o.rightFmt(raw2) : Math.round(raw2); lines.push(`<text x="${pR + 8}" y="${y + 4}" text-anchor="start" fill="${rightFill}" font-size="11">${label2}</text>`); } } return lines.join(''); }, esc(s) { return String(s || '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"'); }, hexToRgba(hex, a) { const r = parseInt(hex.slice(1, 3), 16), g = parseInt(hex.slice(3, 5), 16), b = parseInt(hex.slice(5, 7), 16); return `rgba(${r},${g},${b},${a})`; }, heatColor(r, hex = '#38bdf8') { if (r <= 0) return 'rgba(255,255,255,0.03)'; if (r < 0.2) return SGLVCharts.hexToRgba(hex, 0.18); if (r < 0.4) return SGLVCharts.hexToRgba(hex, 0.35); if (r < 0.6) return SGLVCharts.hexToRgba(hex, 0.55); if (r < 0.8) return SGLVCharts.hexToRgba(hex, 0.78); return hex; }, lineChart(series, options = {}) { const { width = 600, height = 240, pL = 40, pR = 16, pT = 16, pB = 28, smooth = true, colors = SGLVCharts.seriesColors(), area, dots, rangeButtons, activeRange, title, yFormatter, svgAttrs, gridCount = 5, xLabelEvery = 8, xLabelLast = false, } = options; if (!series || !series.length) return ''; const dataLens = series.map(s => (s && Array.isArray(s.data)) ? s.data.length : 0); const n = Math.min(...dataLens); if (new Set(dataLens).size > 1 && options.warnOnMismatch !== false) { console.warn('SGLVCharts.lineChart: series 数据长度不一致,已按最短截断', dataLens); } const norm = series.map(s => ({ ...s, data: (s && Array.isArray(s.data) ? s.data : []).slice(0, n) })); const allY = norm.flatMap(s => s.data.map(v => Number(v) || 0)); const maxV = Math.max(1, ...allY); const cW = width - pL - pR, cH = height - pT - pB; const yMin = Number.isFinite(options.yMin) ? options.yMin : 0; const yMax = Number.isFinite(options.yMax) ? options.yMax : maxV; const ySpan = Math.max(yMax - yMin, 1e-12); const centered = n === 1 && options.centerSinglePoint === true; const xvSrc = Array.isArray(options.xValues) ? options.xValues : null; const xv = xvSrc && xvSrc.length >= n ? xvSrc.slice(0, n).map(Number) : null; let xOf; if (xv) { const x0 = xv[0], x1 = xv[xv.length - 1]; const xSpan = Math.max(x1 - x0, Number(options.xMinSpan) > 0 ? Number(options.xMinSpan) : 0, 1e-12); xOf = i => pL + ((xv[i] - x0) / xSpan) * cW; } else { const stepX = n > 1 ? cW / (n - 1) : 0; xOf = i => (centered ? pL + cW / 2 : pL + i * stepX); } const baseY = pT + cH; const uid = SGLVCharts._uid('line'); const areaOn = area === true || (area !== null && typeof area === 'object'); const areaCfg = areaOn && area !== true ? area : {}; const topOp = areaCfg.opacity != null ? Number(areaCfg.opacity) : 0.4; const dotsOn = dots !== false; const dotsCfg = (dots && typeof dots === 'object') ? dots : {}; const dotR = dotsCfg.r != null ? dotsCfg.r : 3; const dotFill = typeof dotsCfg.fill === 'string' ? dotsCfg.fill : null; const dotStyle = typeof dotsCfg.itemStyle === 'function' ? dotsCfg.itemStyle : null; const dotTitle = typeof dotsCfg.title === 'function' ? dotsCfg.title : null; const dotStroke = dotsCfg.stroke ? ` stroke="${dotsCfg.stroke}" stroke-width="${dotsCfg.strokeWidth != null ? dotsCfg.strokeWidth : 1}"` : ''; const stopOf = (col, a) => /^#[0-9a-f]{6}$/i.test(col) ? `stop-color="${SGLVCharts.hexToRgba(col, a)}"` : `stop-color="${col}" stop-opacity="${a}"`; const parts = []; const defs = []; const allPts = []; norm.forEach((s, idx) => { const col = s.color || colors[idx % colors.length]; const pts = s.data.map((v, i) => { const x = xOf(i); const y = pT + cH - ((Math.max(yMin, Number(v) || 0) - yMin) / ySpan) * cH; return [x, y]; }); allPts[idx] = pts; const d = pts.map((p, i) => (i === 0 ? 'M' : (smooth ? 'C' : 'L')) + p.join(' ')).join(' '); if (areaOn && pts.length) { const gid = `${uid}-g${idx}`; const fill = areaCfg.fill || col; defs.push(`<linearGradient id="${gid}" x1="0" y1="0" x2="0" y2="1">` + `<stop offset="0%" ${stopOf(fill, topOp)}/>` + `<stop offset="100%" ${stopOf(fill, 0.02)}/></linearGradient>`); const areaD = d + ` L ${pts[pts.length - 1][0]} ${baseY} L ${pts[0][0]} ${baseY} Z`; parts.push(`<path d="${areaD}" fill="url(#${gid})" stroke="none"/>`); } const strokeW = Number.isFinite(options.strokeWidth) ? options.strokeWidth : 2; const roundCap = options.strokeRound === true ? ' stroke-linejoin="round" stroke-linecap="round"' : ''; parts.push(`<path d="${d}" fill="none" stroke="${col}" stroke-width="${strokeW}"${roundCap} />`); if (dotsOn) { pts.forEach(([x, y], i) => { const st = dotStyle ? (dotStyle(s.data[i], i, idx) || {}) : {}; const r = st.r != null ? st.r : dotR; const fill = st.fill || dotFill || col; const t = dotTitle ? dotTitle(s.data[i], i, idx) : null; parts.push(t ? `<circle cx="${x}" cy="${y}" r="${r}" fill="${fill}"${dotStroke}><title>${SGLVCharts.esc(t)}` : ``); }); } }); const refLines = []; const pointAnns = []; if (Array.isArray(options.annotations)) { options.annotations.forEach(a => { if (!a || typeof a !== 'object') return; if (a.type === 'refLine') { const y = pT + cH - ((Math.max(yMin, Number(a.value) || 0) - yMin) / ySpan) * cH; refLines.push(``); if (a.label) { refLines.push(`${SGLVCharts.esc(a.label)}`); } } else if (a.type === 'point') { const pts = allPts[a.sIdx || 0] || []; const idx = Math.min(Math.max(0, a.idx | 0), pts.length - 1); const p = pts[idx]; if (!p) return; pointAnns.push(`${SGLVCharts.esc(a.text || '')}`); } }); } const defsHtml = defs.length ? `${defs.join('')}` : ''; let svg = SGLVCharts.svg(width, height, svgAttrs) + defsHtml + SGLVCharts.gridLinesY(pL, width - pR, pT, cH, yMax, gridCount, yFormatter, yMin) + refLines.join('') + parts.join(''); const xLabels = options.xLabels || norm[0].data.map((_, i) => String(i)); const xl = []; const pushLbl = i => { if (!Number.isInteger(i) || i < 0 || i >= xLabels.length) return; xl.push(`${SGLVCharts.esc(xLabels[i])}`); }; if (Array.isArray(options.xLabelAt) && options.xLabelAt.length) { options.xLabelAt.forEach(i => pushLbl(Math.round(Number(i)))); } else { const labelStep = Math.max(1, Math.floor(xLabels.length / Math.max(1, xLabelEvery))); xLabels.forEach((lbl, i) => { if (i % labelStep !== 0 && !(xLabelLast && i === xLabels.length - 1)) return; pushLbl(i); }); } svg += xl.join('') + pointAnns.join('') + ''; if (Array.isArray(rangeButtons) && rangeButtons.length) { const btns = rangeButtons.map(r => `` ).join(''); const titleHtml = title ? `${SGLVCharts.esc(title)}` : ''; const wrapAttr = options.wrapId ? ` id="${SGLVCharts.esc(options.wrapId)}"` : ''; return `
${titleHtml}
${btns}
${svg}
`; } return svg; }, stackedBar(categories, series, options = {}) { const { width = 600, height = 240, pL = 40, pR = 16, pT = 20, pB = 40, colors = SGLVCharts.seriesColors() } = options; if (!categories.length) return ''; const totals = categories.map((_, i) => series.reduce((s, ser) => s + (Number(ser.data[i]) || 0), 0)); const maxV = Math.max(1, ...totals); const cW = width - pL - pR, cH = height - pT - pB; const gap = cW / categories.length; const barW = Math.min(Math.max(gap * 0.6, 16), 40); let svg = SGLVCharts.svg(width, height) + SGLVCharts.gridLinesY(pL, width - pR, pT, cH, maxV); categories.forEach((cat, i) => { const cx = pL + gap * i + gap / 2; let yAcc = pT + cH; series.forEach((ser, sIdx) => { const v = Number(ser.data[i]) || 0; if (v <= 0) return; const h = (v / maxV) * cH; yAcc -= h; const col = ser.color || colors[sIdx % colors.length]; svg += ``; }); svg += `${SGLVCharts.esc(cat)}`; }); return svg + ''; }, donutChart(slices, options = {}) { const { size = 160, thickness = 22, centerText = '', bg = true, title = null, segStyle = '', center = null, legend = null, wrap = false, inner = null, innerGap = 6, } = options; const total = slices.reduce((s, sl) => s + (sl.value || 0), 0); if (total <= 0) return ''; const r = size / 2 - thickness / 2; const cx = size / 2, cy = size / 2; const C = 2 * Math.PI * r; let acc = 0; let svg = SGLVCharts.svg(size, size); if (bg) svg += ``; slices.forEach((sl, i) => { if (!sl.value) return; const len = (sl.value / total) * C; const offset = -acc; const t = title ? title(sl, i) : null; const attrs = `cx="${cx}" cy="${cy}" r="${r}" fill="none" stroke="${sl.color}" stroke-width="${thickness}" stroke-dasharray="${len} ${C - len}" stroke-dashoffset="${offset}" transform="rotate(-90 ${cx} ${cy})"${segStyle ? ` style="${segStyle}"` : ''}`; if (t) svg += `${SGLVCharts.esc(t)}`; else svg += ``; acc += len; }); if (inner && Array.isArray(inner.slices) && inner.slices.length) { const ir = r - thickness - innerGap; if (ir > 12) { const ith = Math.min(inner.thickness || Math.max(8, Math.round(thickness * 0.6)), ir); const ir2 = ir - ith / 2; const iC = 2 * Math.PI * ir2; const iTotal = inner.slices.reduce((s2, sl) => s2 + (sl.value || 0), 0); if (iTotal > 0) { let iacc = 0; if (inner.bg !== false) { svg += ``; } inner.slices.forEach((sl, i) => { if (!sl.value) return; const len = (sl.value / iTotal) * iC; const off = -iacc; const t = inner.title ? inner.title(sl, i) : (title ? title(sl, i) : null); const attrs = `cx="${cx}" cy="${cy}" r="${ir2}" fill="none" stroke="${sl.color}" stroke-width="${ith}" stroke-dasharray="${len} ${iC - len}" stroke-dashoffset="${off}" transform="rotate(-90 ${cx} ${cy})"${segStyle ? ` style="${segStyle}"` : ''}`; if (t) svg += `${SGLVCharts.esc(t)}`; else svg += ``; iacc += len; }); } } } if (center) { const { text = '', sub = '', fontSize = 13, weight = 600, fill = SGLVCharts.PALETTE.text, y = cy + 4, subFontSize = 11, subFill = SGLVCharts.PALETTE.textMuted, subY = y + 14, } = center; if (text) svg += `${SGLVCharts.esc(text)}`; if (sub) svg += `${SGLVCharts.esc(sub)}`; } else if (centerText) { svg += `${SGLVCharts.esc(centerText)}`; } svg += ''; let legendHtml = ''; if (legend) { legendHtml = `
` + slices.filter(sl => sl.value > 0).map(sl => `
${SGLVCharts.esc(sl.label || '')}${legend.value ? legend.value(sl) : SGLVCharts.esc(sl.value)}
` ).join('') + '
'; } if (wrap) { return `
${svg}
${legendHtml}
`; } return svg + legendHtml; }, heatmap(matrix, options = {}) { const { cellSize = 18, gap = 3, xLabels = [], yLabels = [], color = '#38bdf8' } = options; const rows = matrix.length, cols = matrix[0]?.length || 0; if (!rows || !cols) return ''; const w = (xLabels.length ? 30 : 0) + cols * (cellSize + gap) - gap + 6; const h = (yLabels.length ? 16 : 0) + rows * (cellSize + gap) - gap + 4; let maxV = 0; matrix.forEach(r => r.forEach(v => { if (v > maxV) maxV = v; })); let svg = SGLVCharts.svg(w, h); matrix.forEach((row, ri) => { row.forEach((v, ci) => { const x = (xLabels.length ? 30 : 0) + ci * (cellSize + gap); const y = (yLabels.length ? 16 : 0) + ri * (cellSize + gap); const r = maxV > 0 ? v / maxV : 0; svg += `${SGLVCharts.esc(v)}`; }); }); if (xLabels.length) { const step = Math.max(1, Math.floor(xLabels.length / 12)); xLabels.forEach((lbl, i) => { if (i % step !== 0) return; const x = 30 + i * (cellSize + gap) + cellSize / 2; svg += `${SGLVCharts.esc(lbl)}`; }); } if (yLabels.length) { yLabels.forEach((lbl, ri) => { const y = 16 + ri * (cellSize + gap) + cellSize / 2 + 3; svg += `${SGLVCharts.esc(lbl)}`; }); } return svg + ''; }, comboChart(cfg = {}) { const { width = 800, height = 440, pL = 52, pR = 62, pT = 20, pB = 50, n = 0, leftMax = 1, rightMax = null, gridCount = 5, labelFill = '#8a9ba8', bars = null, series = [], xLabel = null, baseStroke = 'rgba(255,255,255,.13)', svgAttrs = '', } = cfg; const cW = width - pL - pR, cH = height - pT - pB; const gap = n > 0 ? cW / n : 0; const cxOf = i => pL + gap * i + gap / 2; let out = SGLVCharts.gridLinesY(pL, width - pR, pT, cH, leftMax, gridCount, undefined, 0, { labelFill, rightMax, rightLabelFill: labelFill }); if (typeof bars === 'function') { for (let i = 0; i < n; i++) { (bars(i, cxOf(i), gap) || []).forEach(b => { if (!b) return; const h = leftMax ? (b.v / leftMax) * cH : 0; const y = pT + cH - h; out += ``; }); } } series.forEach(s => { const data = s.data || []; if (!data.length) return; const sw = s.strokeWidth != null ? s.strokeWidth : 2.5; const pts = data.map((v, i) => `${cxOf(i)},${pT + cH - (rightMax ? (v / rightMax) * cH : 0)}`).join(' '); out += ``; const dots = s.dots; if (dots) { const r = dots.r != null ? dots.r : 3; const fill = dots.fill || s.stroke; const a = dots.attrs; data.forEach((v, i) => { out += `` : ' />'}`; }); } }); if (typeof xLabel === 'function') { for (let i = 0; i < n; i++) { const t = xLabel(i, cxOf(i)); if (t != null && t !== '') out += `${t}`; } } out += ``; return `${out}`; } }; unsafeWindow.SGLVCharts = SGLVCharts; const PTW_HLTB = (function () { const DEFAULT_BASE = 'https://cdn.jsdelivr.net/gh/SmallRob/steam-namespace@main/data'; const FALLBACK_BASES = [ 'https://cdn.jsdelivr.net/gh/SmallRob/steam-namespace@main/data', 'https://fastly.jsdelivr.net/gh/SmallRob/steam-namespace@main/data', 'https://gcore.jsdelivr.net/gh/SmallRob/steam-namespace@main/data', ]; const state = { ready: false, loading: false, err: '', shards: [], reference: null, base: '', missingShards: [], lastProbe: [], }; const shardCount = 8; function base() { try { return String(GM_getValue('sglv_hltb_base', '') || DEFAULT_BASE).replace(/\/+$/, ''); } catch (e) { return DEFAULT_BASE; } } function fetchJson(url) { return new Promise((resolve, reject) => { GM_xmlhttpRequest({ method: 'GET', url, timeout: 20000, onload: (r) => { if (r.status < 200 || r.status >= 300) { reject(new Error('HTTP ' + r.status)); return; } try { resolve(JSON.parse(r.responseText)); } catch (e) { reject(e); } }, onerror: () => reject(new Error('网络错误')), ontimeout: () => reject(new Error('请求超时')), }); }); } async function probeBase() { const candidates = []; const gmBase = base(); for (const b of [gmBase, ...FALLBACK_BASES]) { if (!candidates.includes(b)) candidates.push(b); } state.lastProbe = []; let lastErr = new Error('无可用源'); for (const b of candidates) { try { const manifest = await fetchJson(b + '/hltb-index-v1.manifest.json'); if (!manifest || !manifest.shards) throw new Error('manifest 格式异常'); state.lastProbe.push({ base: b, ok: true }); return { base: b, manifest }; } catch (e) { state.lastProbe.push({ base: b, ok: false, err: e.message || String(e) }); lastErr = e; } } throw lastErr; } async function load() { if (state.ready) return true; if (state.loading) return false; state.loading = true; state.err = ''; try { const { base: okBase, manifest } = await probeBase(); state.base = okBase; try { const ref = await fetchJson(state.base + '/hltb-index-v1.reference.json'); state.reference = ref; } catch (e) { console.warn('[SGLV-HLTB] 参考分布加载失败(年代图将只显示匹配部分)', e.message); } if (manifest.builtAt) { const ageDays = (Date.now() - Date.parse(manifest.builtAt)) / 86400000; if (ageDays > 30) { console.warn('[SGLV-HLTB] 索引已 ' + ageDays.toFixed(0) + ' 天未更新(builtAt=' + manifest.builtAt + ')'); } } async function fetchShard(i) { const url = state.base + '/hltb-index-v1.' + i + '.json'; try { return await fetchJson(url); } catch (e) { return fetchJson(url); } } const settled = await Promise.allSettled( Array.from({ length: shardCount }, (_, i) => fetchShard(i)) ); const shards = []; const missing = []; settled.forEach((r, i) => { if (r.status === 'fulfilled') { const f = r.value; shards[i] = { ids: Int32Array.from(f.ids || []), years: Int32Array.from(f.years || []), story: Float64Array.from(f.story || []), }; } else { shards[i] = null; missing.push(i); } }); if (missing.length === shardCount) throw new Error('全部分片拉取失败(' + (settled[0] && settled[0].reason && settled[0].reason.message || '未知') + ')'); if (missing.length) { console.warn('[SGLV-HLTB] 分片部分缺失,缺失片内的游戏将查不到剧情时长:', missing.join(',')); } state.shards = shards; state.missingShards = missing; state.ready = true; state.loading = false; const entries = shards.reduce((s, sh) => s + (sh ? sh.ids.length : 0), 0); console.log('[SGLV-HLTB] 索引就绪(源 ' + state.base.replace(/^https:\/\//, '').split('/')[0] + '):' + entries + ' 条 / ' + (shardCount - missing.length) + '/' + shardCount + ' 片' + (missing.length ? '(缺 ' + missing.join(',') + ')' : '')); return true; } catch (e) { state.err = e.message || String(e); state.loading = false; console.warn('[SGLV-HLTB] 索引加载失败(库分析/剧情完成度降级)', state.err, '探测结果:', JSON.stringify(state.lastProbe)); return false; } } function get(appid) { if (!state.ready) return null; const id = Number(appid); if (!Number.isFinite(id)) return null; const sh = state.shards[(id >> 1) % shardCount]; if (!sh || !sh.ids.length) return null; let lo = 0, hi = sh.ids.length - 1; while (lo <= hi) { const mid = (lo + hi) >> 1; if (sh.ids[mid] === id) return { y: sh.years[mid], m: sh.story[mid] }; if (sh.ids[mid] < id) lo = mid + 1; else hi = mid - 1; } return null; } return { isReady: () => state.ready, isLoading: () => state.loading, error: () => state.err, load, get, reference: () => state.reference, stats: () => ({ ready: state.ready, loading: state.loading, err: state.err, entries: state.shards.reduce((s, sh) => s + (sh ? sh.ids.length : 0), 0), hasReference: !!state.reference, missingShards: state.missingShards.slice(), probe: state.lastProbe.slice(), }), }; })(); const PTW_HOST = { apiVersion: 1, getOwnedGames() { const all = state.ownedGames || []; const showFamilyShared = storage.getShowFamilyShared(); return showFamilyShared ? all.slice() : all.filter(g => isGameOwnedByMe(g)); }, rawOwnedGames: () => state.ownedGames, getActiveSteamId, isGameOwnedByMe, getShowFamilyShared: () => storage.getShowFamilyShared(), getPlaytimeSnapshot: () => ptSnapLoad(), applySnapshotToGames: ptSnapApplyToGames, playtimeHistory: { collect: (games) => ptHistoryCollect(games), load: () => ptHistoryLoad(), days: () => Object.keys(ptHistoryLoad().days).sort(), dayKey: (ts) => ptDayKey(ts), maxDays: PT_HISTORY_DAYS, clear: () => { _ptHistory = { v: 1, days: {} }; try { sglvIDB.set(PT_HISTORY_KEY, _ptHistory); } catch (e) { } return true; }, }, getAcquiredMap: (force) => ptGetAcquiredMap(force), refreshPlaytime: (force) => ptRefreshPlaytime(force), hltb: PTW_HLTB, getFamilyInfo: () => fetchFamilyInfo(), computePlaytimeStats, computeWishlistStats, kpiCards, ptPlaytimeMedian, fetchRecentPlayedGames: () => _fetchRecentPlayedGames(), calcPlaytimeDist: (games, mode) => calcPlaytimeDist(games, mode), isDlc: (appid) => (SGLV_API && typeof SGLV_API.isDlc === 'function') ? SGLV_API.isDlc(appid) : false, computeInsightData: () => (typeof computeInsightDataCachedSgis === 'function' ? computeInsightDataCachedSgis() : null), familyCache: { get data() { ptFamLoad(); return _ptFamCache; }, load() { ptFamLoad(); }, save() { ptFamSave(_ptFamCache); }, isStale: (rec) => ptFamIsStale(rec), }, storage: { getApiKey: () => storage.getApiKey(), getFamilyInfo: () => storage.getFamilyInfo(), setFamilyInfo: (v) => storage.setFamilyInfo(v), }, fetchFamilyInfo: (authToken) => fetchFamilyInfo(authToken), getPlayerAchievements: (appId) => SGLV_API.fetchPlayerAchievements?.(appId), getGlobalAchievements: (appId) => SGLV_API.fetchGlobalAchievements?.(appId), getReviews: (appId) => SGLV_API.fetchReviews?.(appId), getReviewSummary: (appId) => SGLV_API.fetchReviewSummary?.(appId), getAppDetailsExtra: (appId) => SGLV_API.fetchAppDetailsExtra?.(appId), getDlcNames: (appId) => SGLV_API.fetchDlcNames?.(appId), getGameNews: (appId) => SGLV_API.fetchGameNews?.(appId), getFamilyShareSupport: (appId) => SGLV_API.fetchFamilyShareSupport?.(appId), getGameStatus: (appId) => SGLV_API.fetchGameStatus?.(appId), getMultiRegionPrices: (appId) => SGLV_API.fetchMultiRegionPrices?.(appId), getSteamRegionPrice: (appId) => SGLV_API.fetchSteamRegionPrice?.(appId), getAugRegionPrice: (appId) => SGLV_API.fetchAugRegionPrice?.(appId), getHistoryPrices: (appId) => SGLV_API.fetchHistoryPrices?.(appId), getHistoryPricesCheapShark: (appId) => SGLV_API.fetchHistoryPricesCheapShark?.(appId), refreshRates: () => SGLV_API.refreshRates?.(), itad: { available: () => !!(window.SGLVITAD && typeof window.SGLVITAD.fetchPriceOverview === 'function'), maxBatch: () => (window.SGLVITAD && window.SGLVITAD.MAX_BATCH) || 200, lookupItadIds: (appIds) => (window.SGLVITAD && typeof window.SGLVITAD.lookupItadIds === 'function') ? window.SGLVITAD.lookupItadIds(appIds) : Promise.resolve({}), fetchPriceOverview: (itadIds, opts) => (window.SGLVITAD && typeof window.SGLVITAD.fetchPriceOverview === 'function') ? window.SGLVITAD.fetchPriceOverview(itadIds, opts) : Promise.resolve(null), fetchPrices: (itadIds, opts) => (window.SGLVITAD && typeof window.SGLVITAD.fetchPrices === 'function') ? window.SGLVITAD.fetchPrices(itadIds, opts) : Promise.resolve(null), }, getUserSteamCountry: () => { try { const m = document.cookie.match(/steamCountry=(\w{2})/); return (m && m[1]) ? String(m[1]).toUpperCase() : 'CN'; } catch (e) { return 'CN'; } }, getUserBadges: (steamId) => SGLV_API.fetchUserBadges?.(steamId || getActiveSteamId()), getBadgeValueScores: (badges, markets) => SGLV_API.computeBadgeValueScores?.(badges, markets), getBadgeMarkets: (appIds, opts) => { const list = Array.isArray(appIds) ? appIds : (appIds == null ? [] : [appIds]); if (!list.length) return Promise.resolve({}); return SGLV_API.fetchBadgeMarkets?.(list, opts) || Promise.resolve({}); }, getCardPrices: (appId) => SGLV_API.fetchCardPrices?.(appId), loadCardDatabase: () => SGLV_API.loadCardDatabase?.(), getSteamLevel: (steamid) => SGLV_API.fetchSteamLevel?.(steamid), getCurrentPlayers: (appId) => SGLV_API.fetchCurrentPlayers?.(appId), getOwnersPlaytime: (appId) => SGLV_API.fetchOwnersPlaytime?.(appId), getTagRecommendations: (appId) => SGLV_API.fetchTagRecommendations?.(appId), getProfileFeaturesStatus: () => SGLV_API.fetchProfileFeaturesStatus?.(), achReal: { available: () => (typeof ACH_REAL === 'object' && !!ACH_REAL), summary: () => ACH_REAL.summary(), deep: () => ACH_REAL.deep(), detail: (appid) => ACH_REAL.readDetail(Number(appid)), refreshOne: (appid) => ACH_REAL.refreshOne(Number(appid)), meta: (appid) => ACH_META.read(Number(appid)), fetchMeta: (appid, force) => ACH_META.fetch(Number(appid), force), defOf: (appid, apiName) => ACH_META.defOf(Number(appid), apiName), iconUrl: (appid, icon) => ACH_META.iconUrl(Number(appid), icon), tierOf: (pct) => ACH_PARSE.tierOf(pct), get tiers() { return ACH_PARSE.TIERS; }, }, services: { getAppDetails: (appId) => sglvGmFetchRetry( `https://store.steampowered.com/api/appdetails?appids=${appId}&l=schinese&filters=categories`, { timeout: 15000 } ), getStoreReviews: (appId) => sglvGmFetchRetry( `https://store.steampowered.com/appreviews/${appId}?json=1&filter=summary&language=schinese&purchase_type=all&day_range=999999`, { timeout: 12000 } ), getGlobalAchvPercents: (appId) => sglvGmFetchRetry( `https://api.steampowered.com/ISteamUserStats/GetGlobalAchievementPercentagesForApp/v0002/?gameid=${appId}`, { timeout: 15000 } ), getAugmentedAppData: (appId) => sglvGmFetchRetry( `https://api.augmentedsteam.com/app/${appId}/v2`, { timeout: 12000 } ), getSimilarGames: (appId) => sglvGmFetchRetry( `https://api.augmentedsteam.com/similar/${appId}/v2?count=15`, { timeout: 12000 } ), getCheapSharkDeals: (appId) => sglvGmFetchRetry( `https://www.cheapshark.com/api/1.0/games?steamAppID=${appId}`, { timeout: 12000 } ), }, h, escHtml, T, ICONS, isZh, SGLVCharts, showToast: sglvToast, cacheGet, cacheSet, cacheDelete, cacheTTL: CACHE_TTL, getCached, cacheKey, getGameIconUrl, getPosterGood, formatLastPlayedShort, renderPagination, paginate, buildListToolbar, hbarRow, createSkeleton, emptyHtml, sglvSmartPool, applyGameAliases, getAccessToken, requestSteamAPI, storage, _getPinyinLib: () => _getPinyinLib(), toPinyinAbbr: (name) => { const lib = _getPinyinLib(); try { return lib && typeof lib.toPinyinAbbr === 'function' ? lib.toPinyinAbbr(String(name || '')) : String(name || '').toLowerCase(); } catch (e) { return String(name || '').toLowerCase(); } }, matchGameName(name, query) { const q = String(query == null ? '' : query).trim().toLowerCase(); if (!q) return true; const raw = String(name == null ? '' : name); const lower = raw.toLowerCase(); if (lower.includes(q)) return true; const py = this.toPinyinAbbr(raw); if (py && py.toLowerCase().includes(q)) return true; return false; }, getThemeId, applySglvTheme, getThemes: () => SGLV_THEMES, accent: SGLVCharts?.accent, _inspect() { const out = {}; const mark = (v) => (typeof v === 'function' ? 'fn' : typeof v); const walk = (obj, prefix) => { for (const k of Object.keys(obj)) { if (k.startsWith('_') || k === 'apiVersion') continue; let v; try { v = obj[k]; } catch (e) { out[prefix + k] = 'unavailable'; continue; } if (typeof v === 'function') out[prefix + k] = 'fn'; else if (v && typeof v === 'object' && !Array.isArray(v)) walk(v, prefix + k + '.'); else out[prefix + k] = mark(v); } }; walk(this, ''); return out; }, }; const _ptwInspect = PTW_HOST._inspect(); const _ptwFnCount = Object.values(_ptwInspect).filter(v => v === 'fn').length; let _ptwReady = false; if (window.SGLVPTW && typeof window.SGLVPTW.init === 'function') { _ptwReady = window.SGLVPTW.init(PTW_HOST); if (!_ptwReady) { console.warn('[PTW] 浮窗框架握手失败 (apiVersion 不匹配)'); } else { console.log(`[PTW] 浮窗框架已就绪 (apiVersion=1, 宿主能力 ${_ptwFnCount} 项)`); } } else { console.warn('[PTW] 浮窗框架库未加载 — 游戏数据浮窗不可用 (请检查 @require 或 Tampermonkey 外部资源设置)'); } if (window.SGLVPTW) window.SGLVPTW._hostReady = _ptwReady; // ── Tab 集库(lib/8430)缺失检测 ─────────────────────────────────────────── // 框架库(lib/8427)只负责外壳:没有任何 Tab 注册时,浮窗仍会打开, // 但 Tab 栏和内容区都是空的 —— 看起来就是「游戏数据分析全没了」, // 而控制台只有一条 TM 的外部资源告警,没人会往那儿看。 // 这里显式判定一次:0 个 Tab = Tab 集库没执行(@require 失败 / 版本没发 / TM 缓存了失败结果)。 function ptwTabCount() { try { const d = window.SGLVPTW && typeof window.SGLVPTW.diagnose === 'function' ? window.SGLVPTW.diagnose() : null; return (d && Array.isArray(d.registeredTabs)) ? d.registeredTabs.length : -1; // -1 = 无从判定 } catch (e) { return -1; } } const _ptwTabCount = ptwTabCount(); const PTW_TABS_MISSING_MSG = 'Tab 集库未加载(@require lib/8430 外部资源未生效)'; if (_ptwReady && _ptwTabCount === 0) { console.error('[PTW] Tab 集库未加载:浮窗只会显示空壳。' + '检查头部 @require https://scriptcat.org/lib/8430/3.1.2/SGLV%20PTW%20Tab%20All.js 是否成功 —— ' + 'Tampermonkey → 编辑脚本 → 外部资源列表里该条若是红色/空,重新保存一次脚本即可重新拉取。'); } else if (_ptwReady && _ptwTabCount > 0) { console.log(`[PTW] Tab 集库已注册 ${_ptwTabCount} 个 Tab`); } try { if (window.SGLVPTW && typeof window.SGLVPTW.hideTab === 'function') { window.SGLVPTW.hideTab('overview', true); } else { console.warn('[PTW] 框架库版本过旧,无 hideTab——浮窗「总览」Tab 未隐藏(不影响功能)'); } } catch (e) { } try { GM_addStyle(` .sglv-ptw-ach-panel-title svg,.sglv-ptw-price-panel-title svg,.sglv-ptw-value-panel-title svg, .sglv-ptw-strk-panel-title svg,.sglv-ptcal-tl-title svg,.sglv-fam-title>svg,.sglv-fam-refresh svg, .sglv-pt-quote-panel-title svg, .sglv-ptwin-open svg{width:14px;height:14px;flex-shrink:0;} .sglv-ptw-ach-state-icon svg,.sglv-ptw-price-state-icon svg{width:34px;height:34px;flex-shrink:0;} /* 图表宽度约束——SGLVCharts.svg 输出 width=100%+viewBox(设计宽 640/680), 超宽窗口下被等比放大近 3 倍(字号/线宽随之爆炸,成就时间线变成全屏巨图)。 按各图表设计宽封顶并居中,高度随 viewBox 等比,不再随容器拉伸 */ .sglv-ptw-ach-chart{max-width:680px;margin:0 auto;} .sglv-ptw-ach-chart svg{width:100%;height:auto;} .sglv-ptw-value-chart{max-width:720px;margin:0 auto;} .sglv-ptw-value-chart svg{width:100%;height:auto;} /* 库价行情曲线图同纪律:设计宽 560,面板宽 ~980 时会被等比放大到 1.7 倍 (轴字号 10px→17px,比 11.5px 的面板标题还大)。按设计宽封顶并居中。 */ .sglv-pt-quote-panel-body>svg{max-width:640px;height:auto;display:block;margin:0 auto;} /* 全部游戏 Tab——列表吃满 pane 高度(共享库 .sglv-pt-all-list max-height:500px 只能看 ~13 行),分页钉在 pane 底部;行距紧凑保证 18 行/页完整可视 */ .sglv-ptw-pane.active{display:flex;flex-direction:column;} .sglv-ptw-pane > .sglv-pt-all-list{flex:1 1 0;min-height:0;max-height:none;} .sglv-ptw-pane > .sglv-pt-pagination{flex-shrink:0;margin-top:8px;} .sglv-ptw-pane .sglv-pt-all-item{padding:4px 8px;margin-bottom:2px;} /* 成就 Tab 网格重排(替代居中窄列)——Hero 通栏; 「稀有度分布 + 解锁时间线」双栏;「成就明细」通栏 */ .sglv-ptw-ach-body{display:grid;grid-template-columns:minmax(0,2fr) minmax(0,3fr);gap:12px;align-items:start;} .sglv-ptw-ach-body > div:nth-child(1){grid-column:1/-1;} .sglv-ptw-ach-body > div:nth-child(2){grid-column:1;grid-row:2;} .sglv-ptw-ach-body > div:nth-child(3){grid-column:2;grid-row:2;} .sglv-ptw-ach-body > div:nth-child(4){grid-column:1/-1;grid-row:3;} /* 足迹 Tab 布局 —— v2.22.6 起**移除**本覆盖层: 原 grid 重排(grid-row:3 硬指定行号 + auto auto minmax(0,1fr) 行模板)会把 「采样日历 / 年度游戏」两面板压扁,面板内容溢出网格行后与下方通栏的 「首次上手 / 里程碑」互相压盖(用户截图:两个标题叠在同一格、note 横穿面板), 且 pane 是 overflow:hidden 导致整页无法滚动。 现由 PTW 库统一用 flex-wrap 负责(banner/hero 通栏 + panel 两列平铺 + body 自滚), 此处保留注释以免后续再被加回来。 */ /* 入库月历微调——月卡间距与内边距收紧(年份胶囊 nowrap / 宽度上限 / 时间线高度下限 已在 CSS_PLAYDATA 基线统一治理,此处不再重复覆盖: 原覆盖层的 max-width:46% 是「右侧图例被裁掉」的元凶之一——1080px 窗口下年份胶囊被钉死 在 ~500px,叠加右侧 summary(5 chip + 图例) 后必然溢出,被 pane 的 overflow 裁切。) */ .sglv-ptcal-grid{gap:10px;} .sglv-ptcal-month{padding:7px 7px 5px;} `); } catch (e) { } const PTW_FALLBACK_REASON = window.SGLVPTW ? 'apiVersion 不匹配(脚本与功能库版本不一致)' : '外部资源 scriptcat.org 未返回脚本内容'; function ptwFallbackHtml() { const NSS = 'sglv-ptw-fb'; try { if (!document.getElementById(NSS + '-style')) { const st = document.createElement('style'); st.id = NSS + '-style'; st.textContent = ` .${NSS}-inline{padding:22px 18px;border:1px dashed rgba(232,163,61,.4);border-radius:10px;background:rgba(232,163,61,.06);color:#c7d5e0;font-size:13px;line-height:1.75;} .${NSS}-inline .${NSS}-t{font-size:14px;font-weight:600;color:#e8a33d;margin-bottom:10px;} .${NSS}-k{display:inline-block;padding:1px 7px;margin:0 2px;border-radius:5px;background:rgba(102,192,244,.14);color:#66c0f4;font-family:ui-monospace,monospace;font-size:11px;} .${NSS}{position:fixed;z-index:1000004;inset:0;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,.5);backdrop-filter:blur(3px);} .${NSS}-box{max-width:520px;padding:28px 30px;border-radius:14px;background:#1a2733;border:1px solid rgba(232,163,61,.35);box-shadow:0 18px 60px rgba(0,0,0,.55);color:#c7d5e0;font-size:13px;line-height:1.75;} .${NSS}-t{font-size:15px;font-weight:600;color:#e8a33d;margin-bottom:12px;} .${NSS}-d{opacity:.85;margin-bottom:8px;} .${NSS}-k{display:inline-block;padding:1px 7px;margin:0 2px;border-radius:5px;background:rgba(102,192,244,.14);color:#66c0f4;font-family:ui-monospace,monospace;font-size:11px;} .${NSS}-btn{margin-top:18px;padding:8px 20px;border-radius:8px;border:1px solid rgba(102,192,244,.4);background:rgba(102,192,244,.14);color:#66c0f4;font-size:13px;cursor:pointer;} .${NSS}-btn:hover{background:rgba(102,192,244,.26);} `; document.head.appendChild(st); } return `
游戏数据浮窗功能库未加载
原因:${escHtml(PTW_FALLBACK_REASON)}
常见处置:
1. Tampermonkey → 编辑脚本 → 确认「外部资源设置」允许访问 scriptcat.org
2. 检查网络能否访问该域名,必要时切换 CDN
3. 其余功能不受影响,可正常继续使用
`; } catch (e) { return `
游戏数据浮窗功能库未加载(${escHtml(PTW_FALLBACK_REASON)})
`; } } function showPtwFallback(reason) { try { if (document.getElementById('sglv-ptw-fallback')) return; const NSS = 'sglv-ptw-fb'; const el = document.createElement('div'); el.id = 'sglv-ptw-fallback'; el.className = NSS; el.innerHTML = `
游戏数据浮窗功能库未加载
原因:${escHtml(reason)}
常见处置:
1. Tampermonkey → 编辑脚本 → 确认「外部资源设置」允许访问 scriptcat.org
2. 检查网络能否访问该域名,必要时切换 CDN
3. 其余功能不受影响,可正常继续使用
`; document.body.appendChild(el); } catch (e) { } } if (!_ptwReady) { if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => showPtwFallback( window.SGLVPTW ? 'apiVersion 不匹配(脚本与功能库版本不一致)' : '外部资源 scriptcat.org 未返回脚本内容' ), { once: true }); } else { showPtwFallback( window.SGLVPTW ? 'apiVersion 不匹配(脚本与功能库版本不一致)' : '外部资源 scriptcat.org 未返回脚本内容' ); } } function _sglvNormalizeFetchError(e) { if (e instanceof Error && e.message) return e; let msg = ''; if (e && typeof e === 'object') { if (typeof e.error === 'string' && e.error) msg = e.error; else if (e.status) msg = 'HTTP ' + e.status + (e.statusText ? ' ' + e.statusText : ''); else try { msg = JSON.stringify(e); } catch (_) { msg = ''; } } if (!msg) msg = String(e || 'network error'); if (msg === '{}' || msg === 'undefined' || msg === 'null') msg = 'network error'; return new Error(msg); } (function _sglvPatchGmFetchJson() { try { if (!window.SGLVCore || typeof window.SGLVCore.gmFetchJson !== 'function') return; if (window.SGLVCore.gmFetchJson.__sglvErrNormalized) return; const orig = window.SGLVCore.gmFetchJson; const wrapped = function (url, options) { return orig.call(this, url, options).catch(e => { throw _sglvNormalizeFetchError(e); }); }; wrapped.__sglvErrNormalized = true; window.SGLVCore.gmFetchJson = wrapped; } catch (e) { } })(); async function _sglvItadTestConnection(testKey) { try { return await window.SGLVITAD.testConnection(testKey); } catch (e) { const msg = (e && e.message) ? String(e.message) : String(e || 'unknown error'); if (typeof fetch === 'function' && /network error|timeout|unavailable|Failed to fetch|NetworkError|网络/i.test(msg)) { try { const resp = await fetch('https://api.isthereanydeal.com/service/shops/v1?key=' + encodeURIComponent(testKey), { method: 'GET' }); if (resp.ok) { const data = await resp.json().catch(() => null); return { success: true, shopCount: Array.isArray(data) ? data.length : 0 }; } if (resp.status === 401 || resp.status === 403) { return { success: false, error: 'Invalid API key (HTTP ' + resp.status + ')' }; } return { success: false, error: 'HTTP ' + resp.status }; } catch (e2) { return { success: false, error: '网络请求失败 (GM 与 fetch 均不可达): ' + ((e2 && e2.message) || e2) }; } } return { success: false, error: msg }; } } let overlayEl, panelEl; function buildSglvMenu() { const menuWrap = document.createElement('span'); menuWrap.className = 'sglv-menu-wrap'; menuWrap.setAttribute('data-sglv-plugin-ui', '1'); const fab = document.createElement('a'); fab.className = 'menuitem sglv-fab'; fab.href = 'javascript:void(0)'; fab.textContent = T.title; fab.setAttribute('aria-label', T.title); menuWrap.appendChild(fab); const submenu = document.createElement('div'); submenu.className = 'sglv-submenu'; const panelLink = document.createElement('a'); panelLink.className = 'menuitem sglv-submenu-item is-active'; panelLink.href = 'javascript:void(0)'; panelLink.textContent = T.ptMenuOpenPanel; panelLink.title = T.ptMenuOpenPanelTip; panelLink.addEventListener('click', (e) => { e.preventDefault(); closeSubmenu(); togglePanel(); }); submenu.appendChild(panelLink); const collectionLink = document.createElement('a'); collectionLink.className = 'menuitem sglv-submenu-item'; collectionLink.href = 'javascript:void(0)'; collectionLink.textContent = isZh ? '游戏收藏' : 'Game Collection'; collectionLink.title = isZh ? '供应商分类 / 绝版收藏 / PS会免 / Epic赠送 / 年度大作' : 'Publisher / Delisted / PS Plus / Epic Free / GotY'; collectionLink.addEventListener('click', (e) => { e.preventDefault(); closeSubmenu(); try { if (!window.SGLVCollection) { sglvToast.warning(isZh ? '收藏模块未加载(请检查 @require 外部库或网络)' : 'Collection module not loaded'); console.warn('[SGLV] 游戏收藏不可用: window.SGLVCollection 未定义(收藏库 @require 加载失败?) 主脚本 v' + _v); return; } if (!_collectionReady) { sglvToast.warning(isZh ? '收藏模块握手失败(版本不兼容,请更新主脚本与收藏库)' : 'Collection module handshake failed'); console.warn('[SGLV] 游戏收藏不可用: init 握手失败(apiVersion 不匹配) 主脚本 v' + _v, 'lib apiVersion=', SGLVCollection.apiVersion); return; } if (typeof SGLVCollection.toggleCollection !== 'function') { sglvToast.warning(isZh ? '收藏模块接口异常' : 'Collection module interface error'); console.warn('[SGLV] 游戏收藏不可用: SGLVCollection.toggleCollection 非函数', SGLVCollection); return; } SGLVCollection.toggleCollection(); } catch (err) { console.error('[SGLV] 游戏收藏菜单点击失败(主脚本 v' + _v + '):', err); sglvToast.error(isZh ? '收藏模块异常,详见控制台' : 'Collection error, see console'); } }); submenu.appendChild(collectionLink); const gameDataLink = document.createElement('a'); gameDataLink.className = 'menuitem sglv-submenu-item'; gameDataLink.href = 'javascript:void(0)'; gameDataLink.textContent = T.ptMenuGameData; gameDataLink.title = T.ptMenuGameDataTip; gameDataLink.addEventListener('click', (e) => { e.preventDefault(); closeSubmenu(); openGameDataWindow(); }); submenu.appendChild(gameDataLink); menuWrap.appendChild(submenu); const _hoverUnsupported = (typeof window.matchMedia === 'function') ? window.matchMedia('(hover: none)').matches : false; const SUB_OPEN_DELAY = 140; const SUB_CLOSE_DELAY = 380; let _subOpenTimer = 0; let _subCloseTimer = 0; function _clearSubTimer(which) { if (which === 'open' && _subOpenTimer) { clearTimeout(_subOpenTimer); _subOpenTimer = 0; } if (which === 'close' && _subCloseTimer) { clearTimeout(_subCloseTimer); _subCloseTimer = 0; } } function _cancelSubTimers() { _clearSubTimer('open'); _clearSubTimer('close'); } function _scheduleSubOpen() { if (_hoverUnsupported || isSubOpen() || _subOpenTimer) return; _clearSubTimer('close'); _subOpenTimer = setTimeout(() => { _subOpenTimer = 0; openSubmenu(); }, SUB_OPEN_DELAY); } function _scheduleSubClose() { _clearSubTimer('open'); if (_hoverUnsupported || !isSubOpen()) return; _clearSubTimer('close'); _subCloseTimer = setTimeout(() => { _subCloseTimer = 0; closeSubmenu(); }, SUB_CLOSE_DELAY); } function _subPointerIn() { _clearSubTimer('close'); if (!isSubOpen()) _scheduleSubOpen(); } function _subPointerOut() { _scheduleSubClose(); } fab.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); _cancelSubTimers(); if (_hoverUnsupported) { toggleSubmenu(); return; } closeSubmenu(); togglePanel(); }); menuWrap.addEventListener('mouseenter', _subPointerIn); menuWrap.addEventListener('mouseleave', _subPointerOut); submenu.addEventListener('mouseenter', _subPointerIn); submenu.addEventListener('mouseleave', _subPointerOut); function isSubOpen() { return menuWrap.classList.contains('sglv-open'); } function closeSubmenu() { _cancelSubTimers(); menuWrap.classList.remove('sglv-open'); submenu.classList.remove('sglv-submenu-docked'); } function dockSubmenu() { let r = (typeof fab.getBoundingClientRect === 'function') ? fab.getBoundingClientRect() : null; if (!r || !(r.bottom > 0)) { r = (typeof menuWrap.getBoundingClientRect === 'function') ? menuWrap.getBoundingClientRect() : null; } if (r && submenu.style && typeof submenu.style.setProperty === 'function') { submenu.style.setProperty('--sglv-sub-top', r.bottom + 'px'); submenu.style.setProperty('--sglv-sub-left', r.left + 'px'); } submenu.classList.add('sglv-submenu-docked'); } function openSubmenu() { menuWrap.classList.add('sglv-open'); dockSubmenu(); } function toggleSubmenu() { isSubOpen() ? closeSubmenu() : openSubmenu(); } let _subScrollRaf = 0; window.addEventListener('scroll', () => { if (!isSubOpen() || _subScrollRaf) return; _subScrollRaf = requestAnimationFrame(() => { _subScrollRaf = 0; if (isSubOpen()) dockSubmenu(); }); }, { passive: true }); window.addEventListener('resize', closeSubmenu); document.addEventListener('click', (e) => { if (!isSubOpen()) return; if (menuWrap.contains && menuWrap.contains(e.target)) return; closeSubmenu(); }); document.addEventListener('keydown', (e) => { if (e && e.key === 'Escape') closeSubmenu(); }); function findHeaderSupportLink() { const supernav = document.querySelector('.supernav_container'); if (supernav) { const classic = supernav.querySelector('a.menuitem[href*="help.steampowered.com"]') || Array.from(supernav.querySelectorAll('a.menuitem')).pop(); if (classic) return { link: classic, mode: 'classic' }; } const links = document.querySelectorAll ? document.querySelectorAll('a[href*="help.steampowered.com"]') : []; for (const a of links) { const href = (a.getAttribute && a.getAttribute('href')) || ''; if (href.indexOf('/faqs/') !== -1) continue; if (typeof a.closest === 'function') { if (a.closest('details[name="responsive-menu"]')) continue; if (a.closest('footer')) continue; if (a.closest('[popover]')) continue; } const text = (a.textContent || '').replace(/\s+/g, ' ').trim(); if (!text || text.length > 16) continue; const parent = a.parentElement; if (!parent || (parent.tagName !== 'UL' && parent.tagName !== 'NAV' && parent.tagName !== 'LI')) continue; if (typeof a.closest === 'function' && !a.closest('nav')) continue; return { link: a, mode: 'react' }; } return null; } function syncReactHeaderClasses(helpLink) { const classes = String(helpLink.className || '').split(/\s+/).filter(Boolean); for (const c of classes) { if (c && !fab.classList.contains(c)) fab.classList.add(c); } if (helpLink.style && fab.style && typeof helpLink.style.getPropertyValue === 'function') { const cursor = helpLink.style.getPropertyValue('--cursor'); if (cursor) fab.style.setProperty('--cursor', cursor); } } let _menuObs = []; let _seating = false; let _seatMoves = []; let _seatTimer = 0; function _nodeInForeignUi(node) { const el = node && node.nodeType === 1 ? node : (node && node.parentElement); if (!el || typeof el.closest !== 'function') return false; return !!el.closest('#familyAnalysisPanel, #sgis-panel, #fa-wl-sibling, #setting_btn, #fa_dd_item, #swe-panel, #swe-fab, .swe-nav-entry, .swe-settings-overlay, .swe-loading-overlay, .swe-toast, [data-fa-plugin-ui], [data-swe-plugin-ui]'); } function _menuMutationIsOurs(mutation) { const t = mutation && mutation.target; if (!t) return true; if (menuWrap.contains && (t === menuWrap || menuWrap.contains(t))) return true; if (_nodeInForeignUi(t)) return true; const lists = [mutation.addedNodes, mutation.removedNodes]; let saw = false; for (let li = 0; li < lists.length; li++) { const list = lists[li]; if (!list) continue; for (let j = 0; j < list.length; j++) { const n = list[j]; if (!n || (n.nodeType !== 1 && n.nodeType !== 3)) continue; saw = true; const inMenu = n !== menuWrap && menuWrap.contains && menuWrap.contains(n); if (!inMenu && !_nodeInForeignUi(n)) return false; } } return saw; } function watchMenuHost(node, opts) { if (!node || typeof MutationObserver !== 'function') return; if (_menuObs.some(o => o.target === node)) return; const obs = new MutationObserver((mutations) => { for (let i = 0; i < mutations.length; i++) { if (_menuMutationIsOurs(mutations[i])) continue; if (_seatTimer) return; _seatTimer = setTimeout(() => { _seatTimer = 0; seatMenu(); }, 200); return; } }); obs.target = node; obs.observe(node, opts); _menuObs.push(obs); } function seatMenu() { if (_seating) return false; const now = Date.now(); _seatMoves = _seatMoves.filter(t => now - t < 10000); if (_seatMoves.length >= 6) return !!(menuWrap.isConnected); const found = findHeaderSupportLink(); if (!found) return false; _seating = true; try { const helpLink = found.link; const nav = (typeof helpLink.closest === 'function' && helpLink.closest('nav')) || helpLink.parentElement; const already = !!(menuWrap.isConnected && nav && typeof nav.contains === 'function' && nav.contains(menuWrap)); if (!already) { if (found.mode === 'react') { syncReactHeaderClasses(helpLink); menuWrap.classList.add('sglv-menu-in-header'); } menuWrap.classList.remove('sglv-menu-fixed'); const anchor = (helpLink.parentElement && helpLink.parentElement.tagName === 'LI') ? helpLink.parentElement : helpLink; if (anchor.nextElementSibling !== menuWrap) { _seatMoves.push(Date.now()); if (typeof anchor.after === 'function') anchor.after(menuWrap); else if (anchor.parentNode) anchor.parentNode.insertBefore(menuWrap, anchor.nextSibling); } } if (nav) { watchMenuHost(nav, { childList: true, subtree: true }); if (nav.parentElement) watchMenuHost(nav.parentElement, { childList: true }); } } finally { _seating = false; } return !!(menuWrap.isConnected || (menuWrap.parentNode)); } if (!seatMenu()) { menuWrap.classList.add('sglv-menu-fixed'); if (document.body) document.body.appendChild(menuWrap); let tries = 0; const retry = setInterval(() => { tries++; if (seatMenu() || tries >= 24) clearInterval(retry); }, 250); } return menuWrap; } function initUI() { window.addEventListener('sglv-theme-changed', () => { if (panelEl && panelEl.isConnected && !state.showSettings) { try { renderBody(); } catch (e) { console.warn('[SGLV] 主题切换重渲染失败:', e); } } }); buildSglvMenu(); overlayEl = document.createElement('div'); overlayEl.className = 'sglv-overlay'; overlayEl.addEventListener('click', closePanel); document.body.appendChild(overlayEl); panelEl = document.createElement('div'); panelEl.className = 'sglv-panel'; panelEl.innerHTML = `
Steam
`; document.body.appendChild(panelEl); _ensureCoverFallbackDelegation(panelEl); makeDraggable(panelEl, panelEl.querySelector('.sglv-header')); panelEl.querySelector('.sglv-close-btn').addEventListener('click', closePanel); panelEl.querySelector('.sglv-refresh-btn').addEventListener('click', () => startFetch(true)); panelEl.querySelector('.sglv-settings-btn').addEventListener('click', () => { if (state.showSettings) closeGlobalSettings(); else openGlobalSettings(); }); panelEl.querySelector('.sglv-collection-btn').addEventListener('click', () => { try { if (!window.SGLVCollection || !_collectionReady || typeof SGLVCollection.openCollection !== 'function') { showToast(isZh ? '收藏模块未加载或版本不兼容' : 'Collection module not loaded or incompatible'); console.warn('[SGLV] 游戏收藏不可用(心型按钮): SGLVCollection=', window.SGLVCollection, 'ready=', _collectionReady, '主脚本 v' + _v); return; } SGLVCollection.openCollection(); } catch (err) { console.error('[SGLV] 游戏收藏打开失败(心型按钮, 主脚本 v' + _v + '):', err); showToast(isZh ? '收藏模块异常,详见控制台' : 'Collection error, see console'); } }); const exportBtn = panelEl.querySelector('#sglv-export-btn'); let _exportMenu = null; const _closeExportMenu = () => { if (_exportMenu) { _exportMenu.remove(); _exportMenu = null; } document.removeEventListener('mousedown', _onExportOutside, true); }; const _onExportOutside = (e) => { if (!_exportMenu) return; if (_exportMenu.contains(e.target) || exportBtn.contains(e.target)) return; _closeExportMenu(); }; exportBtn.addEventListener('click', () => { if (_exportMenu) { _closeExportMenu(); return; } _exportMenu = document.createElement('div'); _exportMenu.className = 'sglv-export-menu'; _exportMenu.innerHTML = ` `; document.body.appendChild(_exportMenu); const rect = exportBtn.getBoundingClientRect(); const mw = _exportMenu.offsetWidth || 170; _exportMenu.style.left = Math.min(rect.left, (window.innerWidth || document.documentElement.clientWidth) - mw - 8) + 'px'; _exportMenu.style.top = (rect.bottom + 6) + 'px'; _exportMenu.classList.add('show'); _exportMenu.addEventListener('click', (e) => { const b = e.target.closest('button'); if (!b) return; _closeExportMenu(); if (b.dataset.fmt === 'csv') exportCSV(); else exportJSON(); }); setTimeout(() => document.addEventListener('mousedown', _onExportOutside, true), 0); }); panelEl.querySelector('#sglv-data-analysis-btn').addEventListener('click', () => { try { openGameDataWindow(); } catch (e) { console.error('[SGLV] 打开游戏数据分析失败:', e); showToast(isZh ? '打开失败,详见控制台' : 'Failed to open, see console'); } }); panelEl.querySelectorAll('.sglv-tab').forEach(tab => { tab.addEventListener('click', () => { switchToTab(tab.dataset.tab); }); }); bindGlobalSearchEvents(); if (!_searchIndexBuilt) { try { buildSearchIndex(); } catch (e) { console.warn('[SGLV] 搜索索引预构建失败:', e); } } const _onOpenLibrary = () => { openPanel(); }; document.addEventListener('sglv:open-library', _onOpenLibrary); addDisposer(() => document.removeEventListener('sglv:open-library', _onOpenLibrary)); const _onOpenModal = (e) => { openPanel(); const targetTab = e?.detail?.tab; if (targetTab) { const tabBtn = panelEl.querySelector(`.sglv-tab[data-tab="${targetTab}"]`); if (tabBtn) switchToTab(targetTab); } }; document.addEventListener('sglv:open-modal', _onOpenModal); addDisposer(() => document.removeEventListener('sglv:open-modal', _onOpenModal)); const cached = storage.getCachedGames(); if (cached.length) { cached.sort((a, b) => a.name.localeCompare(b.name)); state.ownedGames = cached; state.ownedAppIds = new Set(cached.map(g => g.appid)); markSearchIndexDirty(); hydrateComputedCache(); } else { clearComputedCache(); } setTimeout(() => { loadDlcDatabaseFromCacheSync(); loadDlcDatabase(); loadSeriesData(); loadSupplierData(); }, 0); } function togglePanel() { if (panelEl.classList.contains('sglv-show')) closePanel(); else openPanel(); } function openPanel() { panelEl.classList.add('sglv-show'); overlayEl.classList.add('sglv-show'); try { renderBody(); } catch (e) { console.error('[SGLV] 面板渲染失败:', e); } try { _preheatShowcase(); } catch (e) { } } function _preheatShowcase() { if (state.showcasePreheating || state.showcasePreheated) return; if (state.ownedGames.length === 0) return; state.showcasePreheating = true; (async () => { try { const configHash = _computeShowcaseCacheHash(); const swr = _swrReadShowcaseCache(configHash); if (swr.data && !swr.stale && !swr.configChanged) { if (!state.showcaseProfile && swr.data.profile) { state.showcaseProfile = swr.data.profile; state.showcaseProfileAt = swr.timestamp || 0; } state.showcasePreheating = false; state.showcasePreheated = true; return; } const data = await _fetchShowcaseDataAll(); _writeShowcaseCache({ ...data, achievements: _showcaseUnlockedOnly(data.achievements) }, configHash); state.showcasePreheating = false; state.showcasePreheated = true; } catch { state.showcasePreheating = false; } })(); } let _showcaseFetchInflight = null; function _fetchShowcaseDataAll() { if (_showcaseFetchInflight) return _showcaseFetchInflight; const p = (async () => { const [profile, achievements, recentGames, allBadges] = await Promise.all([ _fetchShowcaseProfile(), Promise.resolve(computeMyAchievementsCached()), _fetchRecentPlayedGames(), _getShowcaseBadges().catch(() => []), ]); const allGames = getStatFilteredGames(); const gameCount = allGames.length; const totalPlaytimeMin = allGames.reduce((s, g) => s + (g.playtime || 0), 0); const totalHours = Math.floor(totalPlaytimeMin / 60); const unlockedAchs = (achievements || []).filter(a => a.unlocked); const stats = { gameCount, totalHours, achCount: unlockedAchs.length, totalAchPts: unlockedAchs.reduce((s, a) => s + a.pts, 0), steamBadgeCount: (allBadges && allBadges.length) || profile.badgeCount || 0, }; return { profile, recentGames, badges: allBadges, achievements, stats }; })(); _showcaseFetchInflight = p.then( data => { _showcaseFetchInflight = null; return data; }, err => { _showcaseFetchInflight = null; throw err; } ); return _showcaseFetchInflight; } function closePanel() { panelEl.classList.remove('sglv-show'); overlayEl.classList.remove('sglv-show'); closeDetailPopup(); closeSearchPop(); _gsDebouncedRender.cancel(); if (_gsInputEl) _gsInputEl.value = ''; _gsLastResults = []; const ptWin = document.getElementById('sglv-pt-all-overlay'); if (ptWin) ptWin.remove(); } function makeDraggable(el, handle) { if (!el || !handle) return; let isDragging = false, startX = 0, startY = 0, startLeft = 0, startTop = 0; const onDown = (e) => { const t = e.target; if (t.closest('button, input, select, textarea, label, a')) return; isDragging = true; startX = e.clientX; startY = e.clientY; const rect = el.getBoundingClientRect(); startLeft = rect.left; startTop = rect.top; el.style.cursor = 'grabbing'; e.preventDefault(); }; const onMove = (e) => { if (!isDragging) return; el.style.setProperty('left', (startLeft + e.clientX - startX) + 'px', 'important'); el.style.setProperty('top', (startTop + e.clientY - startY) + 'px', 'important'); el.style.setProperty('right', 'auto', 'important'); el.style.setProperty('bottom', 'auto', 'important'); el.style.setProperty('transform', 'none', 'important'); }; const onUp = () => { if (!isDragging) return; isDragging = false; el.style.cursor = ''; }; handle.addEventListener('mousedown', onDown); document.addEventListener('mousemove', onMove); document.addEventListener('mouseup', onUp); addDisposer(() => { handle.removeEventListener('mousedown', onDown); document.removeEventListener('mousemove', onMove); document.removeEventListener('mouseup', onUp); }); } // ==================== ACH-S1-BEGIN ==================== const ACH_RARE_PCT = 5; const ACH_WALL_MIN_ACTIVE = 5; const ACH_PARSE = (function () { const SSR_RE = /]*id=["']valve-ssr-data["'][^>]*>([\s\S]*?)<\/script>/i; function numOrNull(v) { if (v === null || v === undefined || v === '') return null; const n = Number(v); if (!Number.isFinite(n) || n < 0 || n > 100) return null; return n; } const MS_SEC_THRESHOLD = 1e11; const MS_MIN_TRUSTED = 946684800000; function toMs(v) { const n = Number(v); if (!Number.isFinite(n) || n <= 0) return 0; const ms = n < MS_SEC_THRESHOLD ? n * 1000 : n; return ms < MS_MIN_TRUSTED ? 0 : ms; } function extractSsrJson(html) { if (typeof html !== 'string' || !html) return null; const m = html.match(SSR_RE); if (!m) return null; try { return JSON.parse(m[1]); } catch (e) { return null; } } function pickQueries(ssr) { if (!ssr || !ssr.renderContext) return []; let qd = ssr.renderContext.queryData; if (typeof qd === 'string') { try { qd = JSON.parse(qd); } catch (e) { return []; } } return (qd && Array.isArray(qd.queries)) ? qd.queries : []; } function queryPayload(q) { if (!q || typeof q !== 'object') return null; if (q.queryData !== undefined && q.queryData !== null) return q.queryData; if (q.state && q.state.data !== undefined && q.state.data !== null) return q.state.data; return null; } const SCHEMA_KIND_RE = /^schema(_v\d+)?$/; function kindMatches(actual, want) { if (actual === want) return true; if (want === 'schema') return SCHEMA_KIND_RE.test(String(actual)); return false; } function findQuery(queries, appid, kind) { if (!Array.isArray(queries)) return null; const want = Number(appid); for (const q of queries) { const k = q && q.queryKey; if (!Array.isArray(k) || k.length < 3) continue; if (String(k[0]) !== 'achievements') continue; if (!Number.isFinite(Number(k[1])) || Number(k[1]) !== want) continue; if (!kindMatches(String(k[2]), kind)) continue; return queryPayload(q); } return null; } function parsePage(html, appid) { const want = Number(appid); if (!Number.isFinite(want) || want <= 0) return { ok: false, reason: 'bad-appid' }; const ssr = extractSsrJson(html); if (!ssr) return { ok: false, reason: 'no-ssr' }; const queries = pickQueries(ssr); if (!queries.length) return { ok: false, reason: 'no-query' }; const schemaData = findQuery(queries, want, 'schema'); if (!schemaData) return { ok: false, reason: 'no-schema' }; const rawGroups = Array.isArray(schemaData.groups) ? schemaData.groups : (schemaData.groups && typeof schemaData.groups === 'object' ? Object.keys(schemaData.groups).map(k => schemaData.groups[k]) : []); const defs = []; const keyToApi = Object.create(null); let archivedCount = 0; let seen = Object.create(null); for (const g of rawGroups) { const list = (g && Array.isArray(g.achievements)) ? g.achievements : []; for (const a of list) { if (!a || typeof a !== 'object') continue; const apiName = String(a.api_name || '').trim(); if (!apiName) continue; if (seen[apiName]) continue; seen[apiName] = 1; const archived = a.archived === true; defs.push({ apiName, name: String(a.name || apiName), hidden: a.hidden === true, archived, desc: String(a.description || ''), icon: String(a.icon_achieved || a.icon_unachieved || ''), }); const ik = Number(a.internal_key); if (Number.isFinite(ik)) keyToApi[ik] = apiName; if (archived) archivedCount++; } } if (!defs.length) return { ok: false, reason: 'no-defs' }; const pctMap = Object.create(null); const pctData = findQuery(queries, want, 'globalpercentages'); const pcts = pctData && pctData.percentages; if (pcts && typeof pcts === 'object') { for (const k of Object.keys(pcts)) { const apiName = keyToApi[Number(k)]; if (!apiName) continue; const v = Number(pcts[k]); if (Number.isFinite(v)) pctMap[apiName] = v; } } const userData = findQuery(queries, want, 'user_achievements'); let privacy = 'unknown'; const unlockedMap = Object.create(null); if (userData && typeof userData === 'object') { privacy = 'public'; const ua = userData.achievements; if (ua && typeof ua === 'object') { for (const k of Object.keys(ua)) { const v = ua[k]; if (!v || typeof v !== 'object') continue; if (v.unlocked !== true) continue; const apiName = keyToApi[Number(k)] || keyToApi[Number(v.internal_key)]; if (!apiName) continue; const t = toMs(v.unlock_time); unlockedMap[apiName] = t; } } } let unlocked = 0; const items = defs.map(d => { const has = Object.prototype.hasOwnProperty.call(unlockedMap, d.apiName); if (has) unlocked++; const pct = Number.isFinite(pctMap[d.apiName]) ? pctMap[d.apiName] : -1; const flags = (d.hidden ? 1 : 0) | (d.archived ? 2 : 0); return [d.apiName, d.name, has ? 1 : 0, has ? unlockedMap[d.apiName] : 0, pct, flags]; }); const defMap = Object.create(null); for (const d of defs) { if (d.desc || d.icon) defMap[d.apiName] = { desc: d.desc, icon: d.icon }; } return { ok: true, appid: want, privacy, total: defs.length, activeTotal: defs.length - archivedCount, archived: archivedCount, unlocked, items, defs: defMap, }; } function summarize(rows) { const out = { apps: 0, synced: 0, unknown: 0, defs: 0, unlocked: 0, perfect: 0, rare: 0, rareOwned: 0, unrated: 0, rate: 0, perfectApps: [] }; if (!Array.isArray(rows)) return out; for (const r of rows) { if (!r || !Number.isFinite(Number(r.appid))) continue; out.apps++; if (r.privacy === 'unknown') { out.unknown++; continue; } out.synced++; const items = Array.isArray(r.items) ? r.items : []; const st = computeItemsStats(items); let active = st.active, unlocked = st.unlocked, allDone = st.allDone; if (!items.length) { active = Math.max(0, Number(r.activeTotal) || 0); unlocked = Math.max(0, Number(r.unlocked) || 0); allDone = active > 0 && unlocked >= active; } out.defs += active; out.unlocked += unlocked; out.rare += st.rare; out.rareOwned += st.rareOwned; out.unrated += st.unrated; if (allDone && active > 0 && active >= ACH_WALL_MIN_ACTIVE) { out.perfect++; out.perfectApps.push({ appid: Number(r.appid), rare: st.rareOwned, hardest: st.rarestPct }); } } out.rate = out.defs > 0 ? Math.round((out.unlocked / out.defs) * 100) : 0; out.perfectApps.sort((a, b) => (a.hardest - b.hardest) || (b.rare - a.rare)); return out; } function computeItemsStats(items) { const st = { active: 0, unlocked: 0, missing: 0, allDone: false, rare: 0, rareOwned: 0, unrated: 0, rarestPct: -1, rarestName: '', rarestUnlockAt: 0, completedAt: 0, buckets: Object.create(null), weighted: 0, ownedRated: 0, }; for (const t of TIERS) st.buckets[t.key] = { key: t.key, total: 0, owned: 0 }; if (!Array.isArray(items)) return st; const nowMs = Date.now(); for (const it of items) { if (!Array.isArray(it)) continue; if (((Number(it[5]) || 0) & 2) === 2) continue; st.active++; const isUnlocked = it[2] === 1; const pct = numOrNull(it[4]); if (isUnlocked) { st.unlocked++; const at = Number(it[3]) || 0; if (at && at <= nowMs + 86400000 && at > st.completedAt) st.completedAt = at; } else { st.missing++; } if (pct === null) { st.unrated++; continue; } const tk = tierOf(pct); if (tk) { st.buckets[tk].total++; if (isUnlocked) st.buckets[tk].owned++; } if (pct < ACH_RARE_PCT) { st.rare++; if (isUnlocked) st.rareOwned++; } if (isUnlocked) { if (tk) { st.weighted += TIER_BY_KEY[tk].weight; st.ownedRated++; } if (st.rarestPct < 0 || pct < st.rarestPct) { st.rarestPct = pct; st.rarestName = String(it[1] || it[0]); st.rarestUnlockAt = Number(it[3]) || 0; } } } st.allDone = st.active > 0 && st.unlocked >= st.active; return st; } const TIERS = [ { key: 'mythic', max: 1, weight: 50, label: '神话', labelEn: 'Mythic', color: '#f43f5e' }, { key: 'legend', max: 5, weight: 20, label: '传说', labelEn: 'Legend', color: '#f59e0b' }, { key: 'rare', max: 20, weight: 8, label: '稀有', labelEn: 'Rare', color: '#a855f7' }, { key: 'uncommon', max: 50, weight: 3, label: '少见', labelEn: 'Uncommon', color: '#3b82f6' }, { key: 'common', max: 101, weight: 1, label: '常见', labelEn: 'Common', color: '#94a3b8' }, ]; const TIER_BY_KEY = TIERS.reduce((m, t) => { m[t.key] = t; return m; }, Object.create(null)); function tierOf(pct) { const v = numOrNull(pct); if (v === null) return null; for (const t of TIERS) { if (v < t.max) return t.key; } return 'common'; } function analyze(rows, nameOf) { const nameFn = typeof nameOf === 'function' ? nameOf : (id => 'App ' + id); const out = { games: [], perfect: [], nearPerfect: [], popularMissing: [], hardMissing: [], rarestOwned: [], buckets: Object.create(null), hunter: 0, weighted: 0, owned: 0, scanned: 0, unknown: 0, unrated: 0, completedGames: 0, lastCompletedAt: 0, privateGames: [], recentUnlocks: [], percentile: null, }; for (const t of TIERS) out.buckets[t.key] = { key: t.key, total: 0, owned: 0 }; if (!Array.isArray(rows)) return out; const ownedPool = []; const missingPool = []; const hardPool = []; const recentPool = []; for (const r of rows) { if (!r || !Number.isFinite(Number(r.appid))) continue; out.scanned++; const appid = Number(r.appid); const gname = String(nameFn(appid) || ('App ' + appid)); if (r.privacy === 'unknown') { out.unknown++; out.privateGames.push({ appid: appid, name: gname }); continue; } const items = Array.isArray(r.items) ? r.items : []; const defs = (r.defs && typeof r.defs === 'object') ? r.defs : Object.create(null); const defOf = (api) => { const d = defs[api]; return (d && typeof d === 'object') ? d : {}; }; const st = computeItemsStats(items); if (st.active <= 0) continue; for (const t of TIERS) { out.buckets[t.key].total += st.buckets[t.key].total; out.buckets[t.key].owned += st.buckets[t.key].owned; } out.weighted += st.weighted; out.owned += st.ownedRated; out.unrated += st.unrated; const missingItems = []; for (const it of items) { if (!Array.isArray(it)) continue; if (((Number(it[5]) || 0) & 2) === 2) continue; const isU = it[2] === 1; const pct = numOrNull(it[4]); const achName = String(it[1] || it[0]); const api = String(it[0] || ''); const def = defOf(api); if (isU) { const at = Number(it[3]) || 0; if (at > 0) recentPool.push({ appid: appid, game: gname, ach: achName, at: at, pct: pct === null ? -1 : pct }); if (pct !== null && pct < 100) ownedPool.push({ appid, game: gname, ach: achName, pct: pct, at: at, api, icon: def.icon || '', desc: def.desc || '' }); } else { const entry = { appid, game: gname, ach: achName, pct: pct === null ? -1 : pct, api, icon: def.icon || '', desc: def.desc || '' }; missingItems.push(entry); if (pct !== null && pct >= 60) missingPool.push(entry); if (pct !== null && pct < 1) hardPool.push(entry); } } const gp = globalPercentile(items); const g = { appid, name: gname, active: st.active, unlocked: st.unlocked, missing: st.missing, rate: Math.round((st.unlocked / st.active) * 100), rarest: st.rarestPct, rarestName: st.rarestName, rarestUnlockAt: st.rarestUnlockAt, rare: st.rareOwned, unrated: st.unrated, completedAt: st.completedAt, globalTop: gp.top, globalBeat: gp.beat, }; if (g.completedAt > 0) { out.completedGames++; if (g.completedAt > out.lastCompletedAt) out.lastCompletedAt = g.completedAt; } out.games.push(g); const bigEnough = st.active >= ACH_WALL_MIN_ACTIVE; if (bigEnough && st.missing === 0) out.perfect.push(g); else if (bigEnough && st.missing <= 2) { g.missingItems = missingItems.slice().sort((a, b) => (b.pct - a.pct)); out.nearPerfect.push(g); } } const rarityKey = g => (g.rarest < 0 ? 999 : g.rarest); out.perfect.sort((a, b) => rarityKey(a) - rarityKey(b) || b.active - a.active); out.nearPerfect.sort((a, b) => a.missing - b.missing || rarityKey(a) - rarityKey(b)); out.rarestOwned = ownedPool.sort((a, b) => a.pct - b.pct || b.at - a.at).slice(0, 40); out.recentUnlocks = recentPool.sort((a, b) => b.at - a.at).slice(0, 8); out.popularMissing = missingPool.sort((a, b) => b.pct - a.pct).slice(0, 40); out.hardMissing = hardPool.sort((a, b) => a.pct - b.pct || a.appid - b.appid).slice(0, 40); out.percentile = libraryPercentile(rows); out.hunter = out.owned > 0 ? Math.min(100, Math.round(Math.sqrt(out.weighted / (out.owned * 50)) * 100)) : 0; return out; } function validateSeed(payload) { if (!payload || typeof payload !== 'object' || Array.isArray(payload)) { return { ok: false, reason: 'not-object' }; } if (Number(payload.v) !== 1) return { ok: false, reason: 'bad-version' }; const list = payload.games; if (!Array.isArray(list)) return { ok: false, reason: 'no-games' }; if (!list.length) return { ok: false, reason: 'empty-games' }; const games = []; let droppedGames = 0, droppedItems = 0, totalItems = 0; for (const raw of list) { const appid = Number(raw && raw.appid); if (!Number.isFinite(appid) || appid <= 0) { droppedGames++; continue; } const src = raw && raw.items; if (!Array.isArray(src) || !src.length) { droppedGames++; continue; } const items = []; for (const it of src) { if (!Array.isArray(it)) { droppedItems++; continue; } const apiName = typeof it[0] === 'string' ? it[0].trim() : ''; if (!apiName) { droppedItems++; continue; } const name = typeof it[1] === 'string' && it[1].trim() ? it[1].trim() : apiName; const unlocked = Number(it[2]) === 1 ? 1 : 0; const unlockAt = toMs(it[3]); const pct = numOrNull(it[4]); const flags = (Number(it[5]) || 0) & 3; items.push([apiName, name, unlocked, unlockAt, pct === null ? -1 : pct, flags]); } if (!items.length) { droppedGames++; continue; } const privacy = raw.privacy === 'unknown' || raw.privacy === 'private' ? 'unknown' : 'public'; let defs; if (raw.defs && typeof raw.defs === 'object' && !Array.isArray(raw.defs)) { defs = Object.create(null); for (const k of Object.keys(raw.defs)) { const d = raw.defs[k]; if (!d || typeof d !== 'object') continue; const desc = typeof d.desc === 'string' ? d.desc : ''; const icon = typeof d.icon === 'string' ? d.icon : ''; if (desc || icon) defs[k] = { desc, icon }; } } games.push({ appid, privacy, items, defs }); totalItems += items.length; } if (!games.length) return { ok: false, reason: 'no-valid-game' }; return { ok: true, games, totalItems, dropped: { games: droppedGames, items: droppedItems } }; } function normalizeItemsUnits(items) { if (!Array.isArray(items)) return { items: [], changed: 0 }; const out = []; let changed = 0; for (const it of items) { if (!Array.isArray(it)) { out.push(it); continue; } const at = Number(it[3]) || 0; const ms = toMs(at); if (ms !== at) changed++; const copy = it.slice(); copy[3] = ms; out.push(copy); } return { items: out, changed }; } function globalPercentile(items) { let min = -1, known = 0; for (const it of (Array.isArray(items) ? items : [])) { if (!Array.isArray(it)) continue; if (((Number(it[5]) || 0) & 2) === 2) continue; if (it[2] !== 1) continue; const pct = numOrNull(it[4]); if (pct === null) continue; known++; if (min < 0 || pct < min) min = pct; } if (!known) return { known: 0, top: null, beat: null }; return { known, top: Math.round(min * 10) / 10, beat: Math.round((100 - min) * 10) / 10 }; } function libraryPercentile(rows) { const pcts = []; let asOf = 0; for (const r of (Array.isArray(rows) ? rows : [])) { if (!r || typeof r !== 'object' || r.privacy === 'unknown') continue; let contributed = false; for (const it of (Array.isArray(r.items) ? r.items : [])) { if (!Array.isArray(it)) continue; if (((Number(it[5]) || 0) & 2) === 2) continue; if (it[2] !== 1) continue; const pct = numOrNull(it[4]); if (pct === null) continue; pcts.push(pct); contributed = true; } if (contributed && r.ts && (!asOf || r.ts < asOf)) asOf = r.ts; } if (!pcts.length) return { known: 0, top: null, beat: null, asOf: 0 }; pcts.sort((a, b) => a - b); const idx = (pcts.length - 1) * 0.5; const lo = Math.floor(idx), hi = Math.ceil(idx); const med = lo === hi ? pcts[lo] : pcts[lo] + (pcts[hi] - pcts[lo]) * (idx - lo); return { known: pcts.length, top: Math.round(med * 10) / 10, beat: Math.round((100 - med) * 10) / 10, asOf }; } const EXPORT_CSV_HEADER = 'appId,游戏,已解锁成就,成就总数,完成度%,成就API名,成就名,描述,已解锁,解锁时间,全局解锁率%'; function exportTime(ms) { const n = Number(ms) || 0; if (n <= 0) return ''; const d = new Date(n); if (!Number.isFinite(d.getTime())) return ''; const p2 = (v) => String(v).padStart(2, '0'); return d.getFullYear() + '-' + p2(d.getMonth() + 1) + '-' + p2(d.getDate()) + ' ' + p2(d.getHours()) + ':' + p2(d.getMinutes()); } function csvCell(v) { const s = String(v == null ? '' : v); return /[",\r\n]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s; } function htmlEsc(v) { return String(v == null ? '' : v).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', }[c])); } function exportGroups(rows, nameOf) { const nameFn = typeof nameOf === 'function' ? nameOf : (id => 'App ' + id); const out = []; for (const r of (Array.isArray(rows) ? rows : [])) { if (!r || typeof r !== 'object' || r.privacy === 'unknown') continue; const appid = Number(r.appid); if (!appid) continue; const items = (Array.isArray(r.items) ? r.items : []) .filter(it => Array.isArray(it) && ((Number(it[5]) || 0) & 2) !== 2); if (!items.length) continue; out.push({ appid, name: String(nameFn(appid) || ('App ' + appid)), items, row: r }); } return out; } function buildExportCsv(rows, nameOf) { const lines = [EXPORT_CSV_HEADER]; for (const g of exportGroups(rows, nameOf)) { const defs = (g.row.defs && typeof g.row.defs === 'object') ? g.row.defs : {}; const activeTotal = g.items.length; const unlocked = g.items.filter(it => it[2] === 1).length; const rate = Math.round((unlocked / activeTotal) * 1000) / 10; for (const it of g.items) { const def = defs[String(it[0])] || {}; const pct = numOrNull(it[4]); lines.push([ g.appid, csvCell(g.name), unlocked, activeTotal, rate, csvCell(it[0]), csvCell(it[1] || it[0]), csvCell(def.desc || ''), it[2] === 1 ? 1 : 0, csvCell(exportTime(it[3])), pct === null ? '' : pct, ].join(',')); } } return '\uFEFF' + lines.join('\r\n') + '\r\n'; } function buildExportHtml(rows, nameOf, opts) { const o = opts || {}; const groups = exportGroups(rows, nameOf); let gUnlocked = 0, gDefs = 0, gPerfect = 0; const sections = groups.map(g => { const defs = (g.row.defs && typeof g.row.defs === 'object') ? g.row.defs : {}; const activeTotal = g.items.length; const unlocked = g.items.filter(it => it[2] === 1).length; const rate = Math.round((unlocked / activeTotal) * 1000) / 10; const st = computeItemsStats(g.items); const perfect = activeTotal >= ACH_WALL_MIN_ACTIVE && unlocked === activeTotal; gUnlocked += unlocked; gDefs += activeTotal; if (perfect) gPerfect++; const trs = g.items.map(it => { const def = defs[String(it[0])] || {}; const isUn = it[2] === 1; const pct = numOrNull(it[4]); const pctTxt = pct === null ? '—' : (pct < 1 ? pct.toFixed(2) : pct.toFixed(1)) + '%'; const tk = pct === null ? null : tierOf(pct); return '' + '' + (isUn ? '✓' : '—') + '' + '' + htmlEsc(it[1] || it[0]) + '' + (def.desc ? '' + htmlEsc(def.desc) + '' : '') + '' + '' + htmlEsc(exportTime(it[3])) + '' + '' + pctTxt + ''; }).join(''); const sum = []; if (st.completedAt > 0) sum.push('通关日期 ' + htmlEsc(exportTime(st.completedAt).slice(0, 10))); if (st.rarestPct >= 0) sum.push('最稀有已解锁 ' + (st.rarestPct < 1 ? st.rarestPct.toFixed(2) : st.rarestPct.toFixed(1)) + '%'); return '
' + '

' + htmlEsc(g.name) + '' + unlocked + ' / ' + activeTotal + ' · ' + rate + '%' + (perfect ? ' · ★ 完美通关' : '') + '

' + (sum.length ? '

' + sum.join(' · ') + '

' : '') + '' + trs + '
已解锁成就解锁时间全球解锁率
'; }).join(''); const genAt = exportTime(Number(o.now) || Date.now()); const rateAll = gDefs > 0 ? Math.round((gUnlocked / gDefs) * 1000) / 10 : 0; return '' + '' + '我的成就档案 · ' + htmlEsc(o.name || 'Steam') + '
' + '

我的成就档案' + (o.name ? ' · ' + htmlEsc(o.name) : '') + '

' + '

' + groups.length + ' 款游戏 · 已解锁 ' + gUnlocked + ' / ' + gDefs + '(' + rateAll + '%)· 完美通关 ' + gPerfect + ' 款 · 生成于 ' + htmlEsc(genAt) + '

' + '

全球解锁率 = 该游戏被 Steam 计入的玩家中解锁该成就的占比(一位小数,随时间漂移)。' + '「—」= 未知(私密/无数据),不当 0。已下架(archived)成就与私密游戏不在本档案内。

' + sections + '
由游戏库查看器导出 · 数据来自 Steam 官方成就页 · 自包含单文件,无外链。
' + '
'; } return { extractSsrJson, pickQueries, findQuery, kindMatches, parsePage, summarize, analyze, tierOf, TIERS, TIER_BY_KEY, validateSeed, computeItemsStats, numOrNull, toMs, normalizeItemsUnits, globalPercentile, libraryPercentile, buildExportCsv, buildExportHtml, exportTime }; })(); const ACH_REAL = (function () { const DETAIL_PREFIX = nsKey('idb_achd') + '_'; const INDEX_KEY = nsKey('idb_achi'); const ATTEMPTS_KEY = nsKey('idb_acha'); const MIGRATED_KEY = nsKey('idb_achm'); const MIN_PLAYTIME = 120; const PACE_MS = 1000; const BATCH_MAX = 120; const MAX_WALL_MS = 20 * 60 * 1000; const MAX_ATTEMPTS = 3; let _running = false; let _abort = false; let _progress = null; let _ready = false; let _sumCache = null; let _deepCache = null; const _attempts = Object.create(null); function idb() { try { return sglvIDB || null; } catch (e) { return null; } } let _persistState = null; let _persistProbe = null; function _idbFactory() { try { if (typeof window !== 'undefined' && window && window.indexedDB) return window.indexedDB; } catch (e) { } try { if (typeof indexedDB !== 'undefined' && indexedDB) return indexedDB; } catch (e) { } return null; } function persistState() { return _persistState; } function probePersist() { if (_persistProbe) return _persistProbe; const DB = '__sglv_idb_probe__'; _persistProbe = new Promise(resolve => { let settled = false; const finish = ok => { if (settled) return; settled = true; _persistState = !!ok; try { const f = _idbFactory(); if (f) f.deleteDatabase(DB); } catch (e) { } resolve(_persistState); }; try { const f = _idbFactory(); if (!f) { finish(false); return; } const req = f.open(DB, 1); req.onupgradeneeded = e => { try { e.target.result.createObjectStore('p'); } catch (err) { } }; req.onsuccess = e => { let db = null; try { db = e.target.result; const tx = db.transaction('p', 'readwrite'); tx.objectStore('p').put(1, 'k'); tx.oncomplete = () => { try { db.close(); } catch (err) { } finish(true); }; tx.onerror = () => { try { db.close(); } catch (err) { } finish(false); }; tx.onabort = () => { try { db.close(); } catch (err) { } finish(false); }; } catch (err) { try { if (db) db.close(); } catch (e2) { } finish(false); } }; req.onerror = () => finish(false); req.onblocked = () => finish(false); setTimeout(() => finish(false), 5000); } catch (e) { finish(false); } }); return _persistProbe; } function readIndex() { const db = idb(); if (!db) return Object.create(null); try { const v = db.get(INDEX_KEY, null); return (v && typeof v === 'object') ? v : Object.create(null); } catch (e) { return Object.create(null); } } function readDetail(appid) { const db = idb(); if (!db) return null; try { const v = db.get(DETAIL_PREFIX + Number(appid), null); if (!v || typeof v !== 'object') return null; if (Number(v.appid) !== Number(appid)) return null; return v; } catch (e) { return null; } } function detailKeyList() { const db = idb(); if (!db) return []; const out = []; try { if (typeof db.keys === 'function') { for (const k of db.keys()) { if (typeof k !== 'string') continue; if (k.indexOf(DETAIL_PREFIX) !== 0) continue; const id = k.slice(DETAIL_PREFIX.length); if (id) out.push(id); } if (out.length) return out; } } catch (e) { } try { return Object.keys(readIndex()); } catch (e) { return []; } } let _idxTimer = null; function flushIndex() { _idxTimer = null; if (!_ready) return; const db = idb(); if (!db) return; try { db.set(INDEX_KEY, readIndex()); } catch (e) { } } function scheduleIndexFlush() { if (_idxTimer) return; _idxTimer = setTimeout(flushIndex, 1200); } function touchIndex(appid, row) { if (!_ready) return; const db = idb(); if (!db) return; let idx; try { idx = db.get(INDEX_KEY, null); } catch (e) { return; } if (!idx || typeof idx !== 'object') { idx = Object.create(null); try { db.set(INDEX_KEY, idx); } catch (e) { return; } } idx[String(appid)] = [ row.ts || Date.now(), row.activeTotal || 0, row.unlocked || 0, row.privacy === 'unknown' ? 1 : 0, ]; scheduleIndexFlush(); } let _attemptsTimer = null; function flushAttempts() { _attemptsTimer = null; if (!_ready) return; const db = idb(); if (!db) return; try { db.set(ATTEMPTS_KEY, _attempts); } catch (e) { } } function scheduleAttemptsFlush() { if (_attemptsTimer) return; _attemptsTimer = setTimeout(flushAttempts, 1200); } function hydrateAttempts() { const db = idb(); if (!db) return; try { const v = db.get(ATTEMPTS_KEY, null); if (v && typeof v === 'object') { for (const k of Object.keys(v)) { const a = v[k]; if (a && Number.isFinite(Number(a.count))) { _attempts[k] = { count: Number(a.count) || 0, ts: Number(a.ts) || 0 }; } } } } catch (e) { } } function migrateLegacyUnits(force) { const db = idb(); if (!db) return { ok: false, reason: 'no-idb' }; if (!force) { try { if (db.get(MIGRATED_KEY, null)) { return { ok: true, skipped: true, scanned: 0, changedGames: 0, changedItems: 0 }; } } catch (e) { } } let changedGames = 0, changedItems = 0, scanned = 0; for (const key of detailKeyList()) { const appid = Number(key); if (!Number.isFinite(appid) || appid <= 0) continue; const row = readDetail(appid); if (!row || !Array.isArray(row.items) || !row.items.length) continue; scanned++; const res = ACH_PARSE.normalizeItemsUnits(row.items); if (!res.changed) continue; changedItems += res.changed; changedGames++; try { row.items = res.items; db.set(DETAIL_PREFIX + appid, row); } catch (e) { } } try { db.set(MIGRATED_KEY, { at: Date.now(), changedGames, changedItems }); } catch (e) { } _sumCache = null; _deepCache = null; return { ok: true, skipped: false, scanned, changedGames, changedItems }; } function writeDetail(row) { const db = idb(); if (!db || !row) return; try { db.set(DETAIL_PREFIX + Number(row.appid), row); touchIndex(row.appid, row); _sumCache = null; _deepCache = null; } catch (e) { } } try { if (typeof window !== 'undefined' && window.addEventListener) { window.addEventListener('pagehide', flushIndex); } if (typeof document !== 'undefined' && document.addEventListener) { document.addEventListener('visibilitychange', () => { try { if (document.visibilityState === 'hidden') flushIndex(); } catch (e) { } }); } } catch (e) { } function detailRows() { const rows = []; for (const k of detailKeyList()) { const r = readDetail(k); if (r) rows.push(r); } return rows; } function summary(force) { if (_sumCache && !force) return _sumCache; _sumCache = ACH_PARSE.summarize(detailRows()); return _sumCache; } function deep(force) { if (_deepCache && !force) return _deepCache; const nameMap = Object.create(null); try { for (const t of targets()) nameMap[t.appid] = t.name; } catch (e) { } _deepCache = ACH_PARSE.analyze(detailRows(), id => nameMap[id]); return _deepCache; } let _targetsSrc = null; let _targetsCache = null; function targets() { let games = []; try { games = (typeof getStatFilteredGames === 'function') ? (getStatFilteredGames() || []) : []; } catch (e) { games = []; } if (games === _targetsSrc && _targetsCache) return _targetsCache; const out = []; for (const g of games) { const appid = Number(g && g.appid); if (!appid) continue; const mins = Number(g.playtime) || 0; if (mins < MIN_PLAYTIME) continue; out.push({ appid, name: String(g.name || ('App ' + appid)), playtime: mins }); } out.sort((a, b) => b.playtime - a.playtime); _targetsSrc = games; _targetsCache = out; return out; } function pending() { const now = Date.now(); const out = []; for (const t of targets()) { const cached = readDetail(t.appid); if (cached) { if (cached.privacy !== 'unknown') continue; if (now - (Number(cached.ts) || 0) < 864e5) continue; } const a = _attempts[t.appid]; if (a && a.count >= MAX_ATTEMPTS && (now - a.ts) < 864e5) continue; out.push(t); } return out; } function isRunning() { return _running; } function progress() { return _progress; } function stop() { _abort = true; } async function ensureReady() { if (_ready) return true; const db = idb(); if (!db || typeof db.loadAll !== 'function') return false; try { await db.loadAll(); _ready = true; _sumCache = null; _deepCache = null; try { hydrateAttempts(); } catch (e) { } try { migrateLegacyUnits(false); } catch (e) { } return true; } catch (e) { return false; } } function isReady() { return _ready; } function sleep(ms) { return new Promise(res => setTimeout(res, ms)); } function isCommunityHost() { try { return /(^|\.)steamcommunity\.com$/i.test(location.hostname); } catch (e) { return false; } } function pageUrl(appid, steamid) { return 'https://steamcommunity.com/profiles/' + encodeURIComponent(String(steamid)) + '/achievements/' + encodeURIComponent(String(appid)) + '?l=schinese'; } function fetchSameOrigin(url) { const ctrl = (typeof AbortController === 'function') ? new AbortController() : null; let timer = null; const timeout = new Promise((_, reject) => { timer = setTimeout(() => { try { if (ctrl) ctrl.abort(); } catch (e) { } reject(new Error('timeout')); }, 30000); }); const req = fetch(url, { credentials: 'include', signal: ctrl ? ctrl.signal : undefined }) .then(resp => { if (!resp.ok) { const err = new Error('HTTP ' + resp.status); err.status = resp.status; throw err; } return resp.text(); }); return Promise.race([req, timeout]).finally(() => { if (timer) clearTimeout(timer); }); } function fetchCrossOrigin(url) { const fn = (C && typeof C.gmFetchText === 'function') ? C.gmFetchText : null; if (!fn) return Promise.reject(new Error('no-gm-fetch')); return Promise.resolve(fn(url, { timeout: 30000, retries: 1 })); } function fetchPage(appid, steamid) { const url = pageUrl(appid, steamid); return isCommunityHost() ? fetchSameOrigin(url) : fetchCrossOrigin(url); } async function syncOne(appid, steamid) { const html = await fetchPage(appid, steamid); const parsed = ACH_PARSE.parsePage(html, appid); if (!parsed.ok) return parsed; const row = { appid: parsed.appid, ts: Date.now(), privacy: parsed.privacy, total: parsed.total, activeTotal: parsed.activeTotal, archived: parsed.archived, unlocked: parsed.unlocked, items: parsed.items, }; if (parsed.defs && Object.keys(parsed.defs).length) row.defs = parsed.defs; writeDetail(row); return { ok: true, row }; } async function refreshOne(appid) { const id = Number(appid); if (!Number.isFinite(id) || id <= 0) return { error: 'bad-appid' }; if (_running) return { error: 'running' }; let steamid = ''; try { steamid = (typeof getActiveSteamId === 'function') ? String(getActiveSteamId() || '') : ''; } catch (e) { steamid = ''; } if (!steamid) return { error: 'no-steamid' }; await ensureReady(); _running = true; _abort = false; try { const r = await syncOne(id, steamid); if (!r || !r.ok) return { error: (r && r.reason) || 'parse-failed' }; delete _attempts[id]; scheduleAttemptsFlush(); return { ok: true, row: r.row }; } catch (e) { return { error: 'fetch-failed', status: Number(e && e.status) || 0 }; } finally { try { flushIndex(); } catch (e) { } _progress = null; _running = false; } } async function run(opts) { const cfg = opts || {}; const onProgress = typeof cfg.onProgress === 'function' ? cfg.onProgress : null; const limit = Math.max(1, Math.min(BATCH_MAX, Number(cfg.limit) || BATCH_MAX)); if (_running) return { skipped: true, running: true }; _running = true; _abort = false; try { let steamid = ''; try { steamid = (typeof getActiveSteamId === 'function') ? String(getActiveSteamId() || '') : ''; } catch (e) { steamid = ''; } if (!steamid) return { error: 'no-steamid' }; await ensureReady(); _sumCache = null; _deepCache = null; const list = pending().slice(0, limit); if (!list.length) return { done: 0, total: 0, ok: 0, fail: 0, private: 0, empty: true }; const started = Date.now(); let ok = 0, fail = 0, priv = 0, done = 0; _progress = { done: 0, total: list.length, ok: 0, fail: 0, private: 0 }; for (const item of list) { if (_abort) break; if (Date.now() - started > MAX_WALL_MS) break; let backoff = 0; try { const r = await syncOne(item.appid, steamid); if (!r || !r.ok) throw new Error((r && r.reason) || 'parse-failed'); if (r.row.privacy === 'unknown') priv++; else ok++; delete _attempts[item.appid]; scheduleAttemptsFlush(); } catch (e) { fail++; const status = Number(e && e.status); const a = _attempts[item.appid] || { count: 0, ts: 0 }; a.count++; a.ts = Date.now(); _attempts[item.appid] = a; scheduleAttemptsFlush(); if (status === 429 || status === 403) { fail--; a.count--; backoff = 60000 + Math.floor(Math.random() * 60000); } } done++; _progress = { done, total: list.length, ok, fail, private: priv }; if (onProgress) { try { onProgress(_progress, item); } catch (e) { } } await sleep(PACE_MS + backoff); } _sumCache = null; _deepCache = null; return { done, total: list.length, ok, fail, private: priv, aborted: _abort }; } finally { try { flushIndex(); } catch (e) { } _progress = null; _running = false; } } async function importSeed(payload, opts) { const cfg = opts || {}; const v = ACH_PARSE.validateSeed(payload); if (!v.ok) return { error: v.reason }; const db = idb(); if (!db) return { error: 'no-idb' }; await ensureReady(); const now = Date.now(); const idx = readIndex(); let imported = 0, fail = 0, unlocked = 0, items = 0; for (const g of v.games) { let done = 0, archived = 0; for (const it of g.items) { if (it[2] === 1) done++; if (((Number(it[5]) || 0) & 2) === 2) archived++; } const activeTotal = g.items.length - archived; const row = { appid: g.appid, ts: now, privacy: g.privacy, total: g.items.length, activeTotal, archived, unlocked: done, items: g.items, seed: cfg.markSeed === false ? undefined : 1, }; if (g.defs) row.defs = g.defs; try { db.set(DETAIL_PREFIX + g.appid, row); idx[String(g.appid)] = [now, row.activeTotal, done, g.privacy === 'unknown' ? 1 : 0]; imported++; unlocked += done; items += g.items.length; } catch (e) { fail++; } } try { db.set(INDEX_KEY, idx); } catch (e) { return { error: 'index-write' }; } _sumCache = null; _deepCache = null; return { imported, fail, unlocked, items, dropped: v.dropped }; } function clearAll() { const db = idb(); if (!db) return 0; const keys = detailKeyList(); for (const k of keys) { try { db.remove(DETAIL_PREFIX + Number(k)); } catch (e) { } } try { db.set(INDEX_KEY, {}); } catch (e) { } scheduleIndexFlush(); _sumCache = null; _deepCache = null; return keys.length; } return { summary, deep, targets, pending, run, stop, isRunning, progress, clearAll, importSeed, readDetail, isCommunityHost, isReady, ready: ensureReady, MIN_PLAYTIME, persistState, probePersist, migrateLegacyUnits, detailRows, refreshOne, exportCsv: (nameOf) => ACH_PARSE.buildExportCsv(detailRows(), nameOf), exportHtml: (nameOf, opts) => ACH_PARSE.buildExportHtml(detailRows(), nameOf, opts), get targetCount() { try { return targets().length; } catch (e) { return 0; } }, get pendingCount() { try { return pending().length; } catch (e) { return 0; } }, }; })(); const ACH_META = (function () { const DEF_PREFIX = nsKey('idb_achdef') + '_'; const TTL = 7 * 86400000; const URL_B = 'https://api.steampowered.com/IPlayerService/GetGameAchievements/v1/?appid='; const URL_A = 'https://api.steampowered.com/ISteamUserStats/GetGlobalAchievementPercentagesForApp/v0002/?gameid='; function gmJson(url) { const fn = (C && typeof C.gmFetchJson === 'function') ? C.gmFetchJson : null; if (!fn) return Promise.reject(Object.assign(new Error('no-gm-fetch'), { status: 0 })); return Promise.resolve(fn(url, { timeout: 20000 })); } function parseB(data) { const list = (data && data.response && Array.isArray(data.response.achievements)) ? data.response.achievements : []; const defs = []; const seen = Object.create(null); let archived = 0; for (const a of list) { if (!a || typeof a !== 'object') continue; const apiName = String(a.internal_name || '').trim(); if (!apiName || seen[apiName]) continue; seen[apiName] = 1; const isArch = a.archived === true; if (isArch) archived++; const raw = a.player_percent_unlocked; const pct = (raw == null || raw === '') ? -1 : Number(raw); defs.push({ apiName, name: String(a.localized_name || '').trim(), desc: String(a.localized_desc || ''), icon: String(a.icon || ''), iconGray: String(a.icon_gray || ''), hidden: a.hidden === true, archived: isArch, pct: Number.isFinite(pct) ? pct : -1, }); } return { defs, archived }; } function idb() { try { return sglvIDB || null; } catch (e) { return null; } } function read(appid) { const db = idb(); if (!db) return null; try { const v = db.get(DEF_PREFIX + Number(appid), null); return (v && Array.isArray(v.defs)) ? v : null; } catch (e) { return null; } } function fresh(appid) { const v = read(appid); return (v && v.ts && Date.now() - v.ts <= TTL) ? v : null; } async function fetch(appid, force) { const want = Number(appid); if (!Number.isFinite(want) || want <= 0) return null; if (!force) { const cached = fresh(want); if (cached) return cached; } const db = idb(); const put = (row) => { if (db) { try { db.set(DEF_PREFIX + want, row); } catch (e) { } } return row; }; try { const data = await gmJson(URL_B + want + '&language=schinese'); let parsed = parseB(data); if (parsed.defs.length && parsed.defs.every(d => !d.name)) { try { const en = await gmJson(URL_B + want + '&language=english'); const enParsed = parseB(en); if (enParsed.defs.length) parsed = enParsed; } catch (e) { } } return put({ ts: Date.now(), appid: want, source: 'player_service', defs: parsed.defs, archived: parsed.archived, activeTotal: parsed.defs.length - parsed.archived }); } catch (e) { try { const data = await gmJson(URL_A + want + '&format=json'); const list = (data && data.achievementpercentages && data.achievementpercentages.achievements) || []; const defs = []; const seen = Object.create(null); for (const a of list) { const apiName = String((a && a.name) || '').trim(); const pct = Number(a && a.percent); if (!apiName || seen[apiName] || !Number.isFinite(pct)) continue; seen[apiName] = 1; defs.push({ apiName, name: '', desc: '', icon: '', iconGray: '', hidden: false, archived: false, pct }); } if (defs.length) return put({ ts: Date.now(), appid: want, source: 'global_pct', defs, archived: 0, activeTotal: defs.length }); } catch (e2) { } return null; } } function defOf(appid, apiName) { const meta = read(appid); if (!meta) return null; const want = String(apiName || ''); for (const d of meta.defs) { if (d.apiName === want) return d; } return null; } function iconUrl(appid, icon) { const s = String(icon == null ? '' : icon).trim(); if (!s) return ''; if (/^https?:\/\//i.test(s)) return s; const file = /\.(jpe?g|png|webp|gif)$/i.test(s) ? s : s + '.jpg'; return 'https://cdn.cloudflare.steamstatic.com/steamcommunity/public/images/apps/' + Number(appid) + '/' + file; } return { read, fresh, fetch, defOf, iconUrl, TTL }; })(); // ==================== ACH-S1-END ==================== const _ACH_ICONS = { collector: ``, kingCollector: ``, clock: ``, hourglass: ``, perfection: ``, trophy: ``, fire: ``, globe: ``, sunrise: ``, moon: ``, diamond: ``, heart: ``, star: ``, shield: ``, rocket: ``, spending: ``, social: `+1`, explore: `N`, }; const _ACH_RARITY = { common: { label: T.achRarityCommon, pts: 10, color: '#94a3b8' }, rare: { label: T.achRarityRare, pts: 25, color: '#3b82f6' }, epic: { label: T.achRarityEpic, pts: 50, color: '#a855f7' }, legendary: { label: T.achRarityLegendary, pts: 100, color: '#f59e0b' }, }; const _ACH_CATEGORIES = [ { id: 'collector', icon: _ACH_ICONS.collector, label: T.achCategoryCollector, gradient: 'linear-gradient(135deg, #8b5cf6, #3b82f6)' }, { id: 'playtime', icon: _ACH_ICONS.clock, label: T.achCategoryPlaytime, gradient: 'linear-gradient(135deg, #06b6d4, #0891b2)' }, { id: 'mastery', icon: _ACH_ICONS.trophy, label: T.achCategoryMastery, gradient: 'linear-gradient(135deg, #10b981, #059669)' }, { id: 'diversity', icon: _ACH_ICONS.globe, label: T.achCategoryDiversity, gradient: 'linear-gradient(135deg, #f97316, #ea580c)' }, { id: 'loyalty', icon: _ACH_ICONS.heart, label: T.achCategoryLoyalty, gradient: 'linear-gradient(135deg, #f472b6, #db2777)' }, { id: 'special', icon: _ACH_ICONS.star, label: T.achCategorySpecial, gradient: 'linear-gradient(135deg, #fbbf24, #f59e0b)' }, ]; const _ACHIEVEMENT_DEFS = [ { id: 'collector_10', icon: _ACH_ICONS.collector, name: isZh ? '初出茅庐' : 'First Steps', desc: isZh ? '拥有 10 款游戏' : 'Own 10 games', threshold: 10, metric: 'gameCount', cat: 'collector', rarity: 'common' }, { id: 'collector_50', icon: _ACH_ICONS.collector, name: isZh ? '初级收藏家' : 'Novice Collector', desc: isZh ? '拥有 50 款游戏' : 'Own 50 games', threshold: 50, metric: 'gameCount', cat: 'collector', rarity: 'common' }, { id: 'collector_100', icon: _ACH_ICONS.collector, name: isZh ? '中级收藏家' : 'Avid Collector', desc: isZh ? '拥有 100 款游戏' : 'Own 100 games', threshold: 100, metric: 'gameCount', cat: 'collector', rarity: 'rare' }, { id: 'collector_300', icon: _ACH_ICONS.collector, name: isZh ? '高级收藏家' : 'Pro Collector', desc: isZh ? '拥有 300 款游戏' : 'Own 300 games', threshold: 300, metric: 'gameCount', cat: 'collector', rarity: 'rare' }, { id: 'collector_500', icon: _ACH_ICONS.collector, name: isZh ? '超级收藏家' : 'Mega Collector', desc: isZh ? '拥有 500 款游戏' : 'Own 500 games', threshold: 500, metric: 'gameCount', cat: 'collector', rarity: 'epic' }, { id: 'collector_1000', icon: _ACH_ICONS.kingCollector,name: isZh ? '游戏大王' : 'Game Master', desc: isZh ? '拥有 1000 款游戏' : 'Own 1000 games', threshold: 1000, metric: 'gameCount', cat: 'collector', rarity: 'legendary' }, { id: 'playtime_500', icon: _ACH_ICONS.clock, name: isZh ? '初涉江湖' : 'Getting Started', desc: isZh ? '总时长达到 500 小时' : 'Reach 500 hours', threshold: 500, metric: 'totalHours', cat: 'playtime', rarity: 'common' }, { id: 'playtime_1k', icon: _ACH_ICONS.clock, name: isZh ? '入门玩家' : 'Beginner', desc: isZh ? '总时长达到 1000 小时' : 'Reach 1000 hours', threshold: 1000, metric: 'totalHours', cat: 'playtime', rarity: 'common' }, { id: 'playtime_3k', icon: _ACH_ICONS.hourglass, name: isZh ? '熟练玩家' : 'Skilled', desc: isZh ? '总时长达到 3000 小时' : 'Reach 3000 hours', threshold: 3000, metric: 'totalHours', cat: 'playtime', rarity: 'rare' }, { id: 'playtime_5k', icon: _ACH_ICONS.hourglass, name: isZh ? '资深玩家' : 'Veteran', desc: isZh ? '总时长达到 5000 小时' : 'Reach 5000 hours', threshold: 5000, metric: 'totalHours', cat: 'playtime', rarity: 'rare' }, { id: 'playtime_10k', icon: _ACH_ICONS.hourglass, name: isZh ? '硬核玩家' : 'Hardcore', desc: isZh ? '总时长达到 10000 小时' : 'Reach 10000h', threshold: 10000,metric: 'totalHours', cat: 'playtime', rarity: 'epic' }, { id: 'playtime_20k', icon: _ACH_ICONS.fire, name: isZh ? '传奇玩家' : 'Legend', desc: isZh ? '总时长达到 20000 小时' : 'Reach 20000h', threshold: 20000,metric: 'totalHours', cat: 'playtime', rarity: 'legendary' }, { id: 'mastery_1x100', icon: _ACH_ICONS.trophy, name: isZh ? '专精入门' : 'Focused', desc: isZh ? '1 款游戏游玩超过 100 小时' : '1 game 100h+', threshold: 1, metric: 'games100h', cat: 'mastery', rarity: 'common' }, { id: 'mastery_5x100', icon: _ACH_ICONS.trophy, name: isZh ? '多线专精' : 'Multi-Focus', desc: isZh ? '5 款游戏游玩超过 100 小时' : '5 games 100h+', threshold: 5, metric: 'games100h', cat: 'mastery', rarity: 'common' }, { id: 'mastery_10x100', icon: _ACH_ICONS.trophy, name: isZh ? '深度专精' : 'Dedicated', desc: isZh ? '10 款游戏游玩超过 100 小时' : '10 games 100h+',threshold: 10,metric: 'games100h', cat: 'mastery', rarity: 'rare' }, { id: 'mastery_1x500', icon: _ACH_ICONS.fire, name: isZh ? '挚爱之作' : 'Beloved', desc: isZh ? '1 款游戏游玩超过 500 小时' : '1 game 500h+', threshold: 1, metric: 'games500h', cat: 'mastery', rarity: 'rare' }, { id: 'mastery_1x1k', icon: _ACH_ICONS.fire, name: isZh ? '一生挚爱' : 'Soulmate', desc: isZh ? '1 款游戏游玩超过 1000 小时' : '1 game 1000h+',threshold: 1, metric: 'games1kh', cat: 'mastery', rarity: 'epic' }, { id: 'mastery_20x100', icon: _ACH_ICONS.perfection, name: isZh ? '完美主义' : 'Perfectionist', desc: isZh ? '20 款游戏游玩超过 100 小时' : '20 games 100h+',threshold: 20,metric: 'games100h', cat: 'mastery', rarity: 'legendary' }, { id: 'div_played50', icon: isZh ? _ACH_ICONS.globe : _ACH_ICONS.globe, name: isZh ? '广泛涉猎' : 'Explorer', desc: isZh ? '游玩库中 50% 的游戏' : 'Play 50% of library', threshold: 50, metric: 'playRate', cat: 'diversity', rarity: 'common' }, { id: 'div_played80', icon: _ACH_ICONS.globe, name: isZh ? '博览群书' : 'Scholar', desc: isZh ? '游玩库中 80% 的游戏' : 'Play 80% of library', threshold: 80, metric: 'playRate', cat: 'diversity', rarity: 'rare' }, { id: 'div_unplayed100',icon: _ACH_ICONS.shield, name: isZh ? '库存积压' : 'Backlog', desc: isZh ? '拥有 100 款从未游玩的游戏' : '100 unplayed games', threshold: 100, metric: 'unplayedCount', cat: 'diversity', rarity: 'common' }, { id: 'div_recent7d', icon: _ACH_ICONS.sunrise, name: isZh ? '活跃玩家' : 'Active', desc: isZh ? '7 天内游玩过游戏' : 'Played within 7 days', threshold: 1, metric: 'recent7d', cat: 'diversity', rarity: 'common' }, { id: 'div_recent24h', icon: _ACH_ICONS.sunrise, name: isZh ? '今日在线' : 'Today', desc: isZh ? '24 小时内游玩过游戏' : 'Played within 24h', threshold: 1, metric: 'recent24h', cat: 'diversity', rarity: 'rare' }, { id: 'div_played100', icon: _ACH_ICONS.perfection, name: isZh ? '全勤玩家' : 'Completionist', desc: isZh ? '游玩库中 100% 的游戏' : 'Play 100% of library', threshold: 100,metric: 'playRate', cat: 'diversity', rarity: 'legendary' }, { id: 'loy_data50', icon: _ACH_ICONS.heart, name: isZh ? '数据收集者' : 'Data Keeper', desc: isZh ? '50% 游戏有入库时间' : '50% games have acquire time', threshold: 50, metric: 'dataCompleteness', cat: 'loyalty', rarity: 'common' }, { id: 'loy_data80', icon: _ACH_ICONS.heart, name: isZh ? '数据达人' : 'Data Master', desc: isZh ? '80% 游戏有入库时间' : '80% games have acquire time', threshold: 80, metric: 'dataCompleteness', cat: 'loyalty', rarity: 'rare' }, { id: 'loy_family', icon: _ACH_ICONS.shield, name: isZh ? '家庭共享' : 'Family Sharing', desc: isZh ? '启用家庭组共享' : 'Family sharing enabled', threshold: 1, metric: 'hasFamily', cat: 'loyalty', rarity: 'common' }, { id: 'loy_accurate', icon: _ACH_ICONS.diamond, name: isZh ? '精准记录' : 'Precise', desc: isZh ? '95% 游戏有入库时间' : '95% games have acquire time', threshold: 95, metric: 'dataCompleteness', cat: 'loyalty', rarity: 'epic' }, { id: 'sp_night_owl', icon: _ACH_ICONS.moon, name: isZh ? '夜猫子' : 'Night Owl', desc: isZh ? '5000h+ 且拥有 200+ 游戏' : '5000h+ & 200+ games', threshold: 1, metric: 'nightOwl', cat: 'special', rarity: 'epic' }, { id: 'sp_whale', icon: _ACH_ICONS.diamond, name: isZh ? '巨鲸玩家' : 'Whale', desc: isZh ? '10000h+ 且拥有 500+ 游戏' : '10000h+ & 500+ games', threshold: 1, metric: 'whale', cat: 'special', rarity: 'legendary' }, { id: 'sp_pioneer', icon: _ACH_ICONS.rocket, name: isZh ? '先锋玩家' : 'Pioneer', desc: isZh ? '拥有游戏且总时长 1000h+' : 'Has games & 1000h+', threshold: 1, metric: 'pioneer', cat: 'special', rarity: 'common' }, { id: 'sp_liberty', icon: _ACH_ICONS.star, name: isZh ? '自由之魂' : 'Free Spirit', desc: isZh ? '从未游玩的游戏超过 200 款' : '200+ unplayed games', threshold: 200,metric: 'unplayedCount', cat: 'special', rarity: 'rare' }, ]; const _ACH_CACHE_KEY = 'sglv_ach_unlocks_v2'; function _getAchUnlockCache() { try { const raw = GM_getValue(_ACH_CACHE_KEY, '{}'); const data = typeof raw === 'string' ? JSON.parse(raw) : raw; return (data && typeof data === 'object') ? data : {}; } catch (e) { return {}; } } function _saveAchUnlockCache(cache) { try { GM_setValue(_ACH_CACHE_KEY, JSON.stringify(cache)); } catch (e) { } } function _computeAchMetrics() { const allGames = getStatFilteredGames(); const gameCount = allGames.length; const totalPlaytimeMin = allGames.reduce((s, g) => s + (g.playtime || 0), 0); const totalHours = Math.floor(totalPlaytimeMin / 60); const playedGames = allGames.filter(g => (g.playtime || 0) > 0).length; const unplayedCount = gameCount - playedGames; const playRate = gameCount > 0 ? Math.round((playedGames / gameCount) * 100) : 0; const games100h = allGames.filter(g => (g.playtime || 0) >= 6000).length; const games500h = allGames.filter(g => (g.playtime || 0) >= 30000).length; const games1kh = allGames.filter(g => (g.playtime || 0) >= 60000).length; const now = Date.now(); const recent7d = allGames.filter(g => g.lastPlayed && (now - g.lastPlayed * 1000) <= 7 * 86400000).length > 0 ? 1 : 0; const recent24h = allGames.filter(g => g.lastPlayed && (now - g.lastPlayed * 1000) <= 86400000).length > 0 ? 1 : 0; const withAcquired = allGames.filter(g => g.acquiredTime && g.acquiredTime > 0).length; const dataCompleteness = gameCount > 0 ? Math.round((withAcquired / gameCount) * 100) : 0; const hasFamily = (state.familyInfo && state.familyInfo.members && state.familyInfo.members.length > 0) ? 1 : 0; const nightOwl = (totalHours >= 5000 && gameCount >= 200) ? 1 : 0; const whale = (totalHours >= 10000 && gameCount >= 500) ? 1 : 0; const pioneer = (gameCount > 0 && totalHours >= 1000) ? 1 : 0; return { gameCount, totalHours, playRate, unplayedCount, recent7d, recent24h, games100h, games500h, games1kh, dataCompleteness, hasFamily, nightOwl, whale, pioneer, }; } function computeMyAchievements() { const metrics = _computeAchMetrics(); const unlockCache = _getAchUnlockCache(); const now = Date.now(); let cacheDirty = false; const results = _ACHIEVEMENT_DEFS.map(ach => { const current = metrics[ach.metric] || 0; const unlocked = current >= ach.threshold; const progress = ach.threshold > 0 ? Math.min(100, (current / ach.threshold) * 100) : (unlocked ? 100 : 0); const pts = _ACH_RARITY[ach.rarity]?.pts || 10; let unlockedAt = null; if (unlocked) { if (unlockCache[ach.id]) { unlockedAt = unlockCache[ach.id]; } else { unlockCache[ach.id] = now; unlockedAt = now; cacheDirty = true; } } return { ...ach, current, unlocked, progress, pts, unlockedAt }; }); Object.keys(unlockCache).forEach(id => { const ach = results.find(a => a.id === id); if (ach && !ach.unlocked) { delete unlockCache[id]; cacheDirty = true; } }); if (cacheDirty) _saveAchUnlockCache(unlockCache); return results; } function _formatAchTime(ts) { if (!ts) return ''; if (Number(ts) > Date.now() + 86400000) return isZh ? '时间未知' : 'unknown'; const d = new Date(ts); const yyyy = d.getFullYear(); const mm = String(d.getMonth() + 1).padStart(2, '0'); const dd = String(d.getDate()).padStart(2, '0'); return `${yyyy}-${mm}-${dd}`; } function _formatRelTime(ts) { if (!ts) return ''; if (Number(ts) > Date.now() + 86400000) return isZh ? '时间未知' : 'unknown'; const diff = Date.now() - ts; const days = Math.floor(diff / 86400000); if (days === 0) return isZh ? '今天' : 'Today'; if (days === 1) return isZh ? '昨天' : 'Yesterday'; if (days < 7) return isZh ? `${days}天前` : `${days}d ago`; if (days < 30) return isZh ? `${Math.floor(days / 7)}周前` : `${Math.floor(days / 7)}w ago`; if (days < 365) return isZh ? `${Math.floor(days / 30)}月前` : `${Math.floor(days / 30)}mo ago`; return isZh ? `${Math.floor(days / 365)}年前` : `${Math.floor(days / 365)}y ago`; } function _achTierColor(pct) { const v = ACH_PARSE.numOrNull(pct); if (v === null) return '#6e7681'; const t = ACH_PARSE.tierOf(v); const tier = t ? ACH_PARSE.TIER_BY_KEY[t] : null; return tier ? tier.color : '#6e7681'; } function _achSidebarHtml(view, counts, recent) { const items = [ { id: 'all', icon: ICONS.achievement, label: isZh ? '全部已同步' : 'All synced', n: counts.synced }, { id: 'perfect', icon: ICONS.trophy, label: isZh ? '完美通关' : 'Perfect', n: counts.perfect }, { id: 'rare', icon: ICONS.gift, label: isZh ? '稀有收藏' : 'Rare', n: counts.rare }, { id: 'gap', icon: ICONS.barChart, label: isZh ? '待补缺口' : 'Gaps', n: counts.gap }, { id: 'private', icon: ICONS.shield, label: isZh ? '成就私密' : 'Private', n: counts.private }, { id: 'unsynced', icon: ICONS.clock, label: isZh ? '未同步' : 'Not synced', n: counts.unsynced }, ]; const navItems = items.map(it => `
${it.icon}
${it.label} ${it.n}
`).join(''); const recentHtml = (recent && recent.length) ? recent.slice(0, 6).map(r => `
${escHtml(r.ach)}
${escHtml(r.game)} · ${_formatRelTime(r.at)}
`).join('') : `
${isZh ? '还没有解锁记录' : 'No unlocks yet'}
`; return `
${ICONS.achievement} ${T.tabAchievements}
${isZh ? '按游戏浏览' : 'Browse by game'}
${navItems}
${isZh ? '最近解锁' : 'Recent unlocks'}
${recentHtml}
`; } function _achHeaderHtml(p) { const x = p || {}; const n = (v) => Math.max(0, Math.min(100, Math.round(Number(v) || 0))); const rate = n(x.steamRate); const ringR = 38; const ringCirc = 2 * Math.PI * ringR; const ringOffset = ringCirc * (1 - rate / 100); const tip = isZh ? 'Steam 成就完成率 = 已解锁成就数 ÷ 已同步游戏的有效成就总数(已剔除 archived)。可与 Steam 官方成就页逐条核对。' : 'Steam completion rate = unlocked / effective achievements across synced games.'; const card = (color, label, valueHtml, sub, dataKey) => `
${escHtml(label)}
${valueHtml}
${escHtml(sub)}
`; const strip = (label, key, val) => `
${escHtml(label)}${escHtml(val)}
`; const unlockedHtml = `${x.unlocked}/${x.defs}`; return `
${rate}%
${isZh ? 'Steam 完成率' : 'Steam Rate'}
${card('cyan', isZh ? '已同步游戏' : 'Synced', String(x.synced), isZh ? '真实成就已入库' : 'cached', 'synced')} ${card('', isZh ? '已解锁成就' : 'Unlocked', unlockedHtml, isZh ? '已剔除 archived' : 'archived excluded')} ${card('gold', isZh ? '完成率' : 'Rate', `${rate}%`, isZh ? 'Steam 真实口径' : 'real rate', 'ratePct')} ${card('green', isZh ? '完美通关' : 'Perfect', String(x.perfectN), isZh ? '全部成就解锁' : 'all unlocked', 'perfect')} ${card('violet', isZh ? '稀有成就' : 'Rare', String(x.rareOwned), isZh ? `全球 <${ACH_RARE_PCT}%` : `global <${ACH_RARE_PCT}%`, 'rare')} ${card('purple', isZh ? '已通关游戏' : 'Completed', String(x.completedGames), isZh ? '有解锁记录' : 'with unlocks', 'completed')}
${strip(isZh ? '最近解锁' : 'Latest', 'recent', '—')} ${strip(isZh ? '最近通关' : 'Last cleared', 'lastDone', '—')} ${strip(isZh ? '猎手指数' : 'Hunter', 'hunter', String(x.hunter || 0))} ${strip(isZh ? '未评级成就' : 'Unrated', 'unrated', String(x.unrated || 0))} ${strip(isZh ? '全球分位' : 'Global pct', 'globalTop', '—')}
`; } // ==================== ACH-S2-BEGIN ==================== function _achIndexParts(achievements, steamSummary, steamDeep) { const clamp = (v) => Math.max(0, Math.min(100, Math.round(Number(v) || 0))); const achs = Array.isArray(achievements) ? achievements : []; const rareRarity = { rare: 1, epic: 1, legendary: 1 }; const cats = Object.create(null); let rarePts = 0, rareMax = 0; for (const a of achs) { if (!a) continue; const cat = a.cat || '_'; if (!cats[cat]) cats[cat] = { n: 0, u: 0 }; cats[cat].n++; if (a.unlocked) cats[cat].u++; if (rareRarity[a.rarity]) { const pts = Number(a.pts) || 0; rareMax += pts; if (a.unlocked) rarePts += pts; } } const catKeys = Object.keys(cats); const perfectCats = catKeys.filter(k => cats[k].n > 0 && cats[k].u === cats[k].n).length; const cPerfect = catKeys.length ? clamp(perfectCats / catKeys.length * 100) : 0; const cRare = rareMax > 0 ? clamp(rarePts / rareMax * 100) : 0; const custom = clamp(cPerfect * 0.5 + cRare * 0.5); const s = steamSummary || {}; const synced = Number(s.synced) || 0; const perfectN = Number(s.perfect) || 0; const sPerfect = synced > 0 ? clamp(perfectN / synced * 100) : 0; const sRare = clamp(steamDeep && steamDeep.hunter); const steam = clamp(sPerfect * 0.5 + sRare * 0.5); const steamRate = clamp(Number(s.rate) || 0); return { composite: steamRate, steamRate, custom, steam, cRare, cPerfect, sRare, sPerfect, rareBlend: clamp(cRare * 0.6 + sRare * 0.4), perfectBlend: clamp(cPerfect * 0.6 + sPerfect * 0.4), perfectCats, catCount: catKeys.length, perfectN, synced, unlocked: Number(s.unlocked) || 0, defs: Number(s.defs) || 0, unknown: Number(s.unknown) || 0, unrated: Number(s.unrated) || 0, rareOwned: Number(s.rareOwned) || 0, completedGames: (steamDeep && Number(steamDeep.completedGames)) || 0, lastCompletedAt: (steamDeep && Number(steamDeep.lastCompletedAt)) || 0, hunter: sRare, }; } function _achPaintComposite(root) { if (!root || typeof root.querySelector !== 'function') return; let achs = []; try { if (typeof computeMyAchievementsCached === 'function') achs = computeMyAchievementsCached() || []; } catch (e) { achs = []; } let s = null, d = null; try { s = ACH_REAL.summary(); } catch (e) { s = null; } try { d = ACH_REAL.deep(); } catch (e) { d = null; } const p = _achIndexParts(achs, s, d); const put = (key, val) => { const el = root.querySelector('[data-achidx="' + key + '"]'); if (el && el.textContent !== val) el.textContent = val; }; put('ring', p.steamRate + '%'); const ring = root.querySelector('.sglv-ach-ring-fill'); if (ring && ring.setAttribute) { const circ = 2 * Math.PI * 38; ring.setAttribute('stroke-dashoffset', String(circ * (1 - p.steamRate / 100))); } } let _achRealAutoStarted = false; let _achDeepLastAt = 0; let _achPersistProbeStarted = false; function _achPersistProbeOnce() { if (_achPersistProbeStarted) return; _achPersistProbeStarted = true; try { ACH_REAL.probePersist().then(ok => { if (!ok) { try { _achRealRefresh(document); } catch (e) { } } }); } catch (e) { } } function _achRealBlockHtml() { _achPersistProbeOnce(); const s = ACH_REAL.summary(); const target = ACH_REAL.targetCount; const pend = ACH_REAL.pendingCount; const running = ACH_REAL.isRunning(); const prog = ACH_REAL.progress(); const ready = (typeof ACH_REAL.isReady === 'function') ? ACH_REAL.isReady() : true; const persistState = (typeof ACH_REAL.persistState === 'function') ? ACH_REAL.persistState() : null; const covered = target > 0 ? Math.min(100, Math.round(((s.synced + s.unknown) / target) * 100)) : 0; const hours = Math.round(ACH_REAL.MIN_PLAYTIME / 60); const empty = s.synced === 0 && s.unknown === 0; const sub = target > 0 ? (isZh ? `覆盖玩满 ${hours} 小时的 ${target} 款` : `${target} games with ${hours}h+ playtime`) : (isZh ? '请先获取游戏库' : 'Fetch library first'); const btnText = running && prog ? (isZh ? `同步中 ${prog.done}/${prog.total}` : `${prog.done}/${prog.total}`) : (pend > 0 ? (isZh ? `同步(待抓 ${pend})` : `Sync (${pend})`) : (isZh ? '已是最新' : 'Up to date')); const crossOrigin = !ACH_REAL.isCommunityHost(); const disabled = (target === 0 || running || pend === 0) ? 'disabled' : ''; let emptyHint = ''; if (empty) { if (running && prog) { emptyHint = isZh ? `正在同步 ${prog.done}/${prog.total}:每抓到一款就写入本地缓存,上面的统计会立刻跟着涨。` : `Syncing ${prog.done}/${prog.total}: each game is cached and reflected above immediately.`; } else if (!ready) { emptyHint = isZh ? '正在读取本地成就缓存,已同步过的数据会直接显示,不需要重新抓取…' : 'Loading local achievement cache — synced data shows up instantly.'; } else { emptyHint = isZh ? `还没有真实成就数据。点右侧按钮开始同步:每轮最多 120 款、约 2 分钟,全部 ${target} 款会在几次访问里陆续铺满。` : 'No real achievement data yet. Click sync — up to 120 games per run, about 2 minutes.'; } } return `
${isZh ? '同步状态' : 'Sync status'} STEAM
${sub}
${empty ? `
${emptyHint}
` : ''} ${persistState === false ? `
${isZh ? '本地缓存不可用(此浏览器禁用了 IndexedDB):本次同步的数据不会保留,关闭页面后需重新抓取。' : 'Local cache unavailable (IndexedDB blocked): synced data will not be kept.'}
` : ''}
${`${isZh ? '已覆盖' : 'Covered'} ${covered}%${s.unknown > 0 ? (isZh ? ` · ${s.unknown} 款成就私密(不计入统计)` : ` · ${s.unknown} private (excluded)`) : ''}`}${crossOrigin ? (isZh ? ' · 跨域抓取社区成就页(需已登录 Steam);商店页与个人主页的本地缓存各自独立' : ' · cross-origin fetch (Steam login required); store and profile keep separate caches') : ''}
`; } function _achRealRefresh(scope) { const root = scope || document; const host = root.querySelector('#sglv-ach-realwrap') || root.querySelector('.sglv-ach-real'); if (host) { const tpl = document.createElement('div'); try { tpl.innerHTML = `
${_achRealBlockHtml()}
`; } catch (e) { console.warn('[SGLV] 真实成就区块重建失败', e); } const next = tpl.firstElementChild; if (next) { host.replaceWith(next); try { _achRealBind(next.parentElement || root); } catch (e) { } } } try { _achRefreshSubviews(root); } catch (e) { console.warn('[SGLV] 成就子视图刷新失败', e); } try { _achRealPaint(root); } catch (e) { console.warn('[SGLV] 真实成就局部刷新失败', e); } } function _achRefreshSubviews(root) { if (!root || typeof root.querySelector !== 'function') return; let d = null, s = null; try { d = ACH_REAL.deep(); } catch (e) { d = null; } try { s = ACH_REAL.summary(); } catch (e) { s = null; } const navView = state.achNavView || 'all'; const gamesBox = root.querySelector('[data-achsubview="games"]'); if (gamesBox) { try { _achMatrixRefresh(root); } catch (e) { console.warn('[SGLV] 游戏成就矩阵刷新失败', e); } } const insightsBox = root.querySelector('[data-achsubview="insights"]'); if (insightsBox) { try { insightsBox.innerHTML = _achDeepHtml(); _achDeepBind(insightsBox); } catch (e) { console.warn('[SGLV] 聚合分析刷新失败', e); } } try { const counts = _achNavCounts(d, s); const map = { all: counts.synced, perfect: counts.perfect, rare: counts.rare, gap: counts.gap, private: counts.private, unsynced: counts.unsynced, }; const sb = root.querySelector('.sglv-ach-sidebar'); if (sb) { sb.querySelectorAll('[data-achnav]').forEach(el => { const n = map[el.dataset.achnav]; if (typeof n !== 'number') return; const b = el.querySelector('.sglv-ach-nav-item-badge'); if (!b) return; if (b.textContent !== String(n)) b.textContent = String(n); b.className = 'sglv-ach-nav-item-badge ' + (n > 0 ? 'partial' : 'none'); }); } } catch (e) { } } function _achDeepFingerprint(d) { if (!d) return 'null'; return [d.scanned, d.owned, d.perfect.length, d.nearPerfect.length, d.popularMissing.length, (d.hardMissing || []).length, d.rarestOwned.length, d.hunter].join('|'); } function _achRealPaint(scope) { const root = scope || document; if (!root || typeof root.querySelector !== 'function') return; try { _achPaintComposite(root); } catch (e) { console.warn('[SGLV] 成就总览刷新失败', e); } let s; try { s = ACH_REAL.summary(); } catch (e) { console.warn('[SGLV] 真实成就汇总失败', e); return; } const put = (key, val) => { const el = root.querySelector(`[data-achkpi="${key}"]`); if (el && el.textContent !== val) el.textContent = val; }; const target = ACH_REAL.targetCount; const covered = target > 0 ? Math.min(100, Math.round(((s.synced + s.unknown) / target) * 100)) : 0; put('synced', String(s.synced)); put('unlocked', String(s.unlocked)); put('defs', String(s.defs)); put('ratePct', s.rate + '%'); put('perfect', String(s.perfect)); put('rare', String(s.rareOwned)); put('covered', String(covered)); let d = null; try { d = ACH_REAL.deep(); } catch (e) { d = null; } if (d) { put('completed', String(d.completedGames || 0)); put('hunter', String(d.hunter || 0)); put('unrated', String(d.unrated || 0)); const rec = (d.recentUnlocks || [])[0]; put('recent', rec ? `${rec.game} · ${_formatRelTime(rec.at)}` : (isZh ? '暂无' : 'None')); put('lastDone', d.lastCompletedAt > 0 ? _formatAchTime(d.lastCompletedAt) : (isZh ? '暂无' : 'None')); const pc = d.percentile; put('globalTop', pc && pc.top != null ? (isZh ? `前 ${pc.top}%` : `top ${pc.top}%`) : '—'); const gtEl = root.querySelector('[data-achkpi="globalTop"]'); if (gtEl && gtEl.parentElement) { gtEl.parentElement.title = pc && pc.top != null ? (isZh ? `已解锁且全球率已知的 ${pc.known} 个成就,整体位于这些游戏全球玩家的前 ${pc.top}%(100 − 中位数,保守表达,不是排名)。截至 ${_formatAchTime(pc.asOf)},全球率随时间漂移。` : `Median-based conservative percentile across ${pc.known} rated unlocks. As of ${_formatAchTime(pc.asOf)}.`) : (isZh ? '没足够的全球完成率数据(同步后自带)' : 'Not enough global percentage data'); } } const box = root.querySelector('.sglv-ach-real'); if (box) { const bar = box.querySelector('.sglv-ach-real-bar > div'); if (bar) bar.style.width = covered + '%'; } const tabCount = (root.querySelector && root.querySelector('[data-achsub="games"] b')) || (document.querySelector ? document.querySelector('[data-achsub="games"] b') : null); if (tabCount && tabCount.textContent !== String(s.synced)) tabCount.textContent = String(s.synced); const now = Date.now(); if (now - _achDeepLastAt >= 800) { _achDeepLastAt = now; try { const d2 = ACH_REAL.deep(); const fp = _achDeepFingerprint(d2); const gamesBox = root.querySelector('[data-achsubview="games"]'); if (gamesBox && gamesBox.dataset.achMatrixFp !== fp) { gamesBox.dataset.achMatrixFp = fp; try { _achMatrixRefresh(root); } catch (e) { console.warn('[SGLV] 游戏成就矩阵刷新失败', e); gamesBox.innerHTML = `
${isZh ? '矩阵渲染失败,详情见浏览器控制台(SGLV 日志)' : 'Render failed - see console (SGLV log)'}
`; } } const deepBoxes = root.querySelectorAll ? root.querySelectorAll('.sglv-ach-deep') : []; if (deepBoxes.length > 1) { console.warn('[SGLV] 页面上出现多个真实成就深面板(' + deepBoxes.length + ' 个),它们的数据可能不同步'); } const deepBox = deepBoxes[0]; if (deepBox && deepBox.dataset.achDeepFp !== fp) { deepBox.dataset.achDeepFp = fp; const bodyEl = deepBox.querySelector('.sglv-ach-deep-body'); if (bodyEl) { try { bodyEl.innerHTML = _achDeepBodyHtml(d2); } catch (e) { console.warn('[SGLV] 真实成就深面板渲染失败', e); bodyEl.innerHTML = `
${isZh ? '这一栏渲染失败,详情见浏览器控制台(SGLV 日志)' : 'Render failed - see console (SGLV log)'}
`; } _achDeepBind(deepBox); } const badge = (tab, n) => { const b = deepBox.querySelector('[data-achdeep-tab="' + tab + '"] b'); if (b && b.textContent !== String(n)) b.textContent = String(n); }; badge('perfect', d2.perfect.length); badge('rare', _achRareOwned(d2)); badge('gap', d2.nearPerfect.length); const hv = deepBox.querySelector('.sglv-ach-deep-hunter-v'); if (hv && hv.textContent !== String(d2.hunter)) hv.textContent = String(d2.hunter); } } catch (e) { console.warn('[SGLV] 真实成就深度分析失败', e); } } } function _achRealProgressTick(scope, p) { try { _achRealPaint(scope); } catch (e) { console.warn('[SGLV] 真实成就进度刷新失败', e); } const btn = (scope || document).querySelector('#sglv-ach-real-sync'); if (btn && p) { const txt = isZh ? `同步中 ${p.done}/${p.total}` : `${p.done}/${p.total}`; if (btn.textContent !== txt) btn.textContent = txt; } } function _achSeedErrText(code) { const zh = { 'not-object': '快照文件格式无法识别', 'bad-version': '快照版本不匹配(需要 v1)', 'no-games': '快照里没有 games 数组', 'empty-games': '快照内容为空', 'no-valid-game': '快照里没有可用条目(appid 或 apiName 缺失)', 'no-idb': '本地数据库不可用(隐私模式下 IndexedDB 可能被禁用)', 'index-write': '索引写入失败,存储空间可能已满', }; const en = { 'not-object': 'Unrecognized seed format', 'bad-version': 'Seed version mismatch (v1 required)', 'no-games': 'Seed has no games array', 'empty-games': 'Seed is empty', 'no-valid-game': 'Seed has no usable entries', 'no-idb': 'IndexedDB unavailable (private mode?)', 'index-write': 'Index write failed, storage may be full', }; const m = isZh ? zh : en; return m[code] || (isZh ? `导入失败(${code})` : `Import failed (${code})`); } function _achRealBindSeed(scope) { const btn = scope.querySelector('#sglv-ach-real-seed'); const input = scope.querySelector('#sglv-ach-real-seed-input'); if (!btn || !input || btn.dataset.bound === '1') return; btn.dataset.bound = '1'; btn.addEventListener('click', () => { if (ACH_REAL.isRunning()) { showToast(isZh ? '同步进行中,请等这轮结束再导入' : 'Sync in progress, import after it finishes'); return; } input.click(); }); input.addEventListener('change', async () => { const file = input.files && input.files[0]; input.value = ''; if (!file) return; const label = btn.textContent; btn.disabled = true; btn.textContent = isZh ? '导入中…' : 'Importing…'; let toast = ''; try { const text = await file.text(); let payload = null; try { payload = JSON.parse(text); } catch (e) { toast = isZh ? '快照文件不是合法 JSON' : 'Seed file is not valid JSON'; } if (payload) { const r = await ACH_REAL.importSeed(payload); if (!r || r.error) { toast = _achSeedErrText((r && r.error) || 'unknown'); } else { const dropped = (r.dropped && (r.dropped.games + r.dropped.items)) || 0; toast = isZh ? `导入 ${r.imported} 款 / ${r.unlocked} 条解锁${r.fail ? `(${r.fail} 款写失败)` : ''}${dropped ? `,跳过 ${dropped} 条脏数据` : ''}` : `Imported ${r.imported} games / ${r.unlocked} unlocked${r.fail ? ` (${r.fail} failed)` : ''}${dropped ? `, skipped ${dropped} invalid` : ''}`; } } } catch (e) { toast = isZh ? '导入失败,请重试' : 'Import failed, please retry'; } finally { btn.disabled = false; btn.textContent = label; try { _achRealRefresh(scope); } catch (e) { } } if (toast) showToast(toast); }); } function _achRealBind(scope) { if (!scope || typeof scope.querySelector !== 'function') return; _achRealBindSeed(scope); const btn = scope.querySelector('#sglv-ach-real-sync'); if (!btn || btn.dataset.bound === '1') return; btn.dataset.bound = '1'; btn.addEventListener('click', async () => { if (ACH_REAL.isRunning()) return; btn.disabled = true; try { await ACH_REAL.ready(); } catch (e) { } const total = ACH_REAL.pendingCount; const onProgress = p => { try { _achRealProgressTick(scope, p); } catch (e) { } }; onProgress({ done: 0, total }); try { const r = await ACH_REAL.run({ limit: 120, onProgress }); if (r && r.error === 'no-steamid') { showToast(isZh ? '未获取到 SteamID,请先获取游戏库' : 'SteamID not found'); } else if (r && !r.skipped && !r.empty) { const crossHint = (!ACH_REAL.isCommunityHost() && r.ok === 0 && r.fail > 0) ? (isZh ? ';商店页跨域抓取失败,请到个人主页(steamcommunity.com)同步' : '; cross-origin sync failed, try your profile page') : ''; showToast((isZh ? `真实成就:成功 ${r.ok} 款,私密 ${r.private} 款,失败 ${r.fail} 款` : `Achievements: ${r.ok} ok, ${r.private} private, ${r.fail} failed`) + crossHint); } } catch (e) { showToast(isZh ? '同步失败,请稍后重试' : 'Sync failed, try again later'); } _achRealRefresh(scope); }); } function _achRealAutoKick(scope) { if (_achRealAutoStarted) return; if (!ACH_REAL.isCommunityHost()) { _achRealAutoStarted = true; return; } if (ACH_REAL.isRunning()) return; _achRealAutoStarted = true; let tries = 0; const kick = () => { if (ACH_REAL.isRunning()) { _achRealAutoStarted = false; return; } if (ACH_REAL.targetCount === 0) { if (++tries <= 4) { try { setTimeout(kick, 3000); } catch (e) { } return; } _achRealAutoStarted = false; return; } if (ACH_REAL.pendingCount === 0) { _achRealAutoStarted = false; return; } ACH_REAL.run({ limit: 120, onProgress: p => { try { _achRealProgressTick(scope, p); } catch (e) { } }, }).then(r => { if (!r || r.empty || r.error || r.skipped) _achRealAutoStarted = false; try { _achRealRefresh(scope); } catch (e) { } }).catch(() => { _achRealAutoStarted = false; }); }; try { if (ACH_REAL.isReady()) kick(); else ACH_REAL.ready().then(ok => { if (ok) kick(); else _achRealAutoStarted = false; }); } catch (e) { _achRealAutoStarted = false; } } function _achDeepTab() { const t = state && state.achDeepTab; return (t === 'rare' || t === 'gap') ? t : 'perfect'; } function _achPctText(p) { const v = Number(p); if (!Number.isFinite(v) || v < 0) return '—'; return (v < 1 ? v.toFixed(2) : v.toFixed(1)) + '%'; } function _achTierMeta(key) { return (key && ACH_PARSE.TIER_BY_KEY[key]) || null; } function _achTierName(key) { const t = _achTierMeta(key); if (!t) return isZh ? '未知' : 'Unknown'; return isZh ? t.label : t.labelEn; } function _achTierStyle(pct, varName) { const t = _achTierMeta(ACH_PARSE.tierOf(pct)); return `${varName || '--dc'}:${t ? t.color : '#64748b'}`; } function _achRareOwned(d) { const b = d && d.buckets ? d.buckets : null; if (!b) return 0; return (b.mythic ? b.mythic.owned : 0) + (b.legend ? b.legend.owned : 0) + (b.rare ? b.rare.owned : 0); } function _achDeepEmpty(msg) { return `
${msg}
`; } function _achGameIconHtml(appid, alt) { const id = Number(appid) || 0; if (!id) return ''; const src = 'https://cdn.cloudflare.steamstatic.com/steam/apps/' + id + '/capsule_231x87.jpg'; return `${escHtml(alt || '')}`; } function _achAchIconHtml(appid, icon, cls) { const url = ACH_META.iconUrl(appid, icon); if (!url) return ''; return ``; } function _achDeepPerfectHtml(d) { if (!d.perfect.length) { const nearest = d.nearPerfect.length ? (isZh ? `最接近的还差 ${d.nearPerfect[0].missing} 个 —— 去「待补缺口」看看` : `Closest is ${d.nearPerfect[0].missing} away`) : (isZh ? '继续玩吧' : 'Keep playing'); return _achDeepEmpty(isZh ? `已分析 ${d.games.length} 款,还没有完美通关的游戏。${nearest}。` : `Analyzed ${d.games.length} games, no perfect ones yet. ${nearest}.`); } const shown = d.perfect.slice(0, 60); const cards = shown.map(g => { const tk = ACH_PARSE.tierOf(g.rarest); const rareTxt = g.rarest >= 0 ? (isZh ? `最难 ${_achPctText(g.rarest)}` : `hardest ${_achPctText(g.rarest)}`) : (isZh ? '全球完成率未知' : 'pct unknown'); return ``; }).join(''); const more = d.perfect.length > shown.length ? `
${isZh ? `还有 ${d.perfect.length - shown.length} 款完美通关未展示(按稀有度排序,这里只显示最值钱的 ${shown.length} 款)` : `+${d.perfect.length - shown.length} more perfect games not shown`}
` : ''; return `${cards ? `
${cards}
` : ''}${more}`; } function _achDeepRareHtml(d) { const totalOwned = d.owned || 0; const bars = ACH_PARSE.TIERS.map(t => { const b = d.buckets[t.key] || { total: 0, owned: 0 }; const w = b.total > 0 ? Math.round((b.owned / b.total) * 100) : 0; const range = t.max <= 1 ? '<1%' : (t.key === 'legend' ? '1–5%' : (t.key === 'rare' ? '5–20%' : (t.key === 'uncommon' ? '20–50%' : '>50%'))); const label = isZh ? t.label : t.labelEn; return `
${label} ${b.owned}/${b.total}
`; }).join(''); const head = `
${isZh ? '稀有度分布(已解锁 / 全部)' : 'Rarity distribution'}${totalOwned}
${bars}
`; if (!d.rarestOwned.length) { return head + _achDeepEmpty(isZh ? '还没有带全球完成率的成就数据。完成率来自成就页的 globalpercentages,同步过就会带上。' : 'No global percentages yet.'); } const rows = d.rarestOwned.map(a => ``).join(''); return `${head}
${isZh ? '最稀有的解锁' : 'Rarest unlocked'}${d.rarestOwned.length} / ${_achRareOwned(d)}
${rows}
`; } function _achDeepGapHtml(d) { const NEAR_CAP = 30; const nearShown = d.nearPerfect.slice(0, NEAR_CAP); const nearMore = d.nearPerfect.length > nearShown.length ? `
${isZh ? `还有 ${d.nearPerfect.length - nearShown.length} 款未展示(按缺口与稀有度排序)` : `+${d.nearPerfect.length - nearShown.length} more`}
` : ''; const secA = d.nearPerfect.length ? `
${isZh ? '差 1~2 个就完美' : 'Almost perfect'}${d.nearPerfect.length}
${nearShown.map(g => { const chips = (g.missingItems || []).map(m => { const cls = (m.pct >= 0 && m.pct < 1) ? 'hard' : (m.pct >= 80 ? 'free' : ''); const ptxt = m.pct >= 0 ? _achPctText(m.pct) : (isZh ? '未知' : '?'); return `${escHtml(m.ach)}${ptxt}`; }).join(''); return ``; }).join('')}
${nearMore}` : `
${isZh ? '差 1~2 个就完美' : 'Almost perfect'}0
${_achDeepEmpty(isZh ? '没有卡在最后一两个的成就 —— 要么都完美了,要么离得还远。' : 'Nothing stuck at the last step.')}`; const missingRow = a => ``; const secB = d.popularMissing.length ? `
${isZh ? '最容易补 · 全球多数人已拿,你还没拿' : 'Easy wins · popular but missing'}${d.popularMissing.length}
${d.popularMissing.map(missingRow).join('')}
` : `
${isZh ? '最容易补 · 全球多数人已拿,你还没拿' : 'Easy wins · popular but missing'}0
${_achDeepEmpty(isZh ? '没有这种「漏掉的大众成就」—— 常见成就基本都拿到了。' : 'No popular achievements missing.')}`; const hard = d.hardMissing || []; const secC = hard.length ? `
${isZh ? '最难啃 · 全球 <1%,先别碰' : 'Hardest · global <1%'}${hard.length}
${hard.map(missingRow).join('')}
` : `
${isZh ? '最难啃 · 全球 <1%,先别碰' : 'Hardest · global <1%'}0
${_achDeepEmpty(isZh ? '没有全球 <1% 的未解锁硬骨头。' : 'No sub-1% achievements missing.')}`; return secA + secB + secC; } function _achDeepBodyHtml(d) { if (!d || d.scanned === 0) { return _achDeepEmpty(isZh ? '还没有真实成就数据。先点上方「同步」,玩满 2 小时的游戏会按游玩时长顺序排队,每轮 120 款。' : 'No real achievement data yet. Click Sync above — 120 games per run.'); } if (!d.games.length) { return _achDeepEmpty(isZh ? `已同步的 ${d.unknown} 款游戏成就都是私密的,无法参与分析。到 Steam「隐私设置 → 游戏详情」改为公开后再同步。` : `${d.unknown} synced games are private. Set game details to public on Steam, then re-sync.`); } const tab = _achDeepTab(); if (tab === 'rare') return _achDeepRareHtml(d); if (tab === 'gap') return _achDeepGapHtml(d); return _achDeepPerfectHtml(d); } function _achDeepHtml() { let d; try { d = ACH_REAL.deep(); } catch (e) { return ''; } const tab = _achDeepTab(); const rareN = _achRareOwned(d); const gapN = d.nearPerfect.length; const hunterTitle = isZh ? '按已解锁成就的全球稀有度加权(神话 50 / 传说 20 / 稀有 8 / 少见 3 / 常见 1)后开方归一到 0~100。全是常见成就约 14,全神话才是 100。' : 'Weighted by global rarity, sqrt-normalized to 0-100.'; return `
${isZh ? '猎手指数' : 'Hunter Index'} ${d.hunter}
${_achDeepBodyHtml(d)}
`; } function _achDeepBind(scope) { if (!scope || typeof scope.querySelector !== 'function') return; const tabs = scope.querySelectorAll('[data-achdeep-tab]'); tabs.forEach(btn => { if (btn.dataset.bound === '1') return; btn.dataset.bound = '1'; btn.addEventListener('click', () => { const want = btn.dataset.achdeepTab; if (_achDeepTab() === want) return; state.achDeepTab = want; tabs.forEach(b => b.classList.toggle('active', b.dataset.achdeepTab === want)); const body = scope.querySelector('.sglv-ach-deep-body'); if (!body) return; try { body.innerHTML = _achDeepBodyHtml(ACH_REAL.deep()); } catch (e) { console.warn('[SGLV] 真实成就深面板切页渲染失败', e); body.innerHTML = `
${isZh ? '这一栏渲染失败,详情见浏览器控制台(SGLV 日志)' : 'Render failed - see console (SGLV log)'}
`; } _achDeepBind(scope); }); }); scope.querySelectorAll('[data-achgame]').forEach(el => { if (el.dataset.bound === '1') return; el.dataset.bound = '1'; el.addEventListener('click', () => _achOpenGame(Number(el.dataset.achgame))); }); } function _achModalKeydown(e) { if (e.key === 'Escape') { e.stopPropagation(); _achCloseGame(); } } function _achCloseGame() { const el = document.getElementById('sglv-ach-modal'); if (el) el.remove(); document.removeEventListener('keydown', _achModalKeydown, true); if (document.body && document.body.dataset.achLocked === '1') { document.body.style.overflow = document.body.dataset.achPrevOverflow || ''; delete document.body.dataset.achLocked; delete document.body.dataset.achPrevOverflow; } } function _achOpenGame(appid) { let row = null; try { row = ACH_REAL.readDetail(appid); } catch (e) { row = null; } if (!row) { showToast(isZh ? '这款游戏还没有成就缓存' : 'No cached achievements for this game'); return; } let gname = 'App ' + appid; try { const g = (ACH_REAL.deep().games || []).find(x => Number(x.appid) === Number(appid)); if (g) gname = g.name; } catch (e) { } const rowDefs = (row.defs && typeof row.defs === 'object') ? row.defs : {}; const items = (Array.isArray(row.items) ? row.items : []) .filter(it => Array.isArray(it) && ((Number(it[5]) || 0) & 2) !== 2) .map(it => { const def = rowDefs[String(it[0])] || {}; return { ach: String(it[1] || it[0]), on: it[2] === 1, at: Number(it[3]) || 0, pct: Number(it[4]), api: String(it[0] || ''), hidden: ((Number(it[5]) || 0) & 1) === 1, icon: def.icon || '', desc: def.desc || '', }; }) .sort((a, b) => (a.pct < 0 ? 999 : a.pct) - (b.pct < 0 ? 999 : b.pct)); if (!items.length) { showToast(isZh ? '这款游戏没有可显示的成就' : 'No achievements to show'); return; } const active = items.length; const done = items.filter(i => i.on).length; const rate = active > 0 ? Math.round((done / active) * 100) : 0; const priv = row.privacy === 'unknown'; const hiddenN = items.filter(i => i.hidden).length; const bodyHtml = items.map(i => `
${i.icon ? _achAchIconHtml(appid, i.icon, 'sglv-ach-mrow-ico') : ''} ${escHtml(i.ach)}${i.hidden ? `${isZh ? '隐藏' : 'hidden'}` : ''} ${i.on ? (isZh ? '已解锁' : 'Unlocked') + (i.at ? ' · ' + _formatAchTime(i.at) : '') : (isZh ? '未解锁' : 'Locked')}${i.desc ? ' · ' + escHtml(i.desc) : ''} ${_achPctText(i.pct)}${isZh ? '玩家拿到' : 'of players'}
`).join(''); _achCloseGame(); const wrap = document.createElement('div'); wrap.className = 'sglv-ach-modal'; wrap.id = 'sglv-ach-modal'; wrap.innerHTML = `
`; document.body.appendChild(wrap); if (document.body && document.body.dataset.achLocked !== '1') { document.body.dataset.achPrevOverflow = document.body.style.overflow || ''; document.body.dataset.achLocked = '1'; document.body.style.overflow = 'hidden'; } const mask = wrap.querySelector('.sglv-ach-modal-mask'); const closeBtn = wrap.querySelector('.sglv-ach-modal-close'); if (mask) mask.addEventListener('click', _achCloseGame); if (closeBtn) closeBtn.addEventListener('click', _achCloseGame); const refreshBtn = wrap.querySelector('#sglv-ach-modal-refresh'); if (refreshBtn) refreshBtn.addEventListener('click', async () => { if (ACH_REAL.isRunning()) { showToast(isZh ? '同步进行中,请等这轮结束' : 'Sync in progress'); return; } refreshBtn.disabled = true; refreshBtn.textContent = isZh ? '刷新中…' : 'Refreshing…'; try { const r = await ACH_REAL.refreshOne(appid); if (r && r.ok) { showToast(isZh ? '已刷新这款游戏的成就数据' : 'Game achievements refreshed'); try { _achRealRefresh(document); } catch (e) { } _achOpenGame(appid); } else { const code = (r && r.error) || 'unknown'; showToast(code === 'no-steamid' ? (isZh ? '未获取到 SteamID' : 'SteamID not found') : code === 'running' ? (isZh ? '同步进行中' : 'Sync in progress') : (isZh ? `刷新失败(${code}),稍后重试` : `Refresh failed (${code})`)); refreshBtn.disabled = false; refreshBtn.textContent = isZh ? '刷新本款' : 'Refresh'; } } catch (e) { showToast(isZh ? '刷新失败,稍后重试' : 'Refresh failed'); refreshBtn.disabled = false; refreshBtn.textContent = isZh ? '刷新本款' : 'Refresh'; } }); document.addEventListener('keydown', _achModalKeydown, true); } // ==================== ACH-S2-END ==================== function _achNavCounts(d, s) { const deep = d || {}; const sum = s || {}; const synced = Number(sum.synced) || 0; let unsynced = 0; try { unsynced = Math.max(0, ACH_REAL.targetCount - synced); } catch (e) { unsynced = 0; } return { synced: synced, perfect: (deep.perfect || []).length, rare: (deep.games || []).filter(g => (g.rare || 0) > 0).length, gap: (deep.nearPerfect || []).length, private: (deep.privateGames || []).length, unsynced: unsynced, }; } function _achMatrixRows(d, view) { if (!d) return []; const games = d.games || []; const byRate = (a, b) => (b.rate - a.rate) || (b.active - a.active); if (view === 'perfect') return (d.perfect || []).slice(); if (view === 'gap') return (d.nearPerfect || []).slice(); if (view === 'rare') return games.filter(g => (g.rare || 0) > 0).sort((a, b) => (b.rare - a.rare) || byRate(a, b)); if (view === 'private') return (d.privateGames || []).slice(); if (view === 'unsynced') { const rows = []; try { for (const t of ACH_REAL.targets()) { if (!t || !t.appid) continue; if (ACH_REAL.readDetail(t.appid)) continue; rows.push({ appid: t.appid, name: t.name || ('App ' + t.appid), active: 0, unlocked: 0, missing: 0, rate: 0, unsynced: true, }); } } catch (e) { } return rows; } return games.slice().sort(byRate); } const _ACH_MATRIX_SORTS = [ { id: 'rate', label: isZh ? '完成率' : 'Rate' }, { id: 'rare', label: isZh ? '稀有数' : 'Rare' }, { id: 'recent', label: isZh ? '最近解锁' : 'Recent' }, { id: 'count', label: isZh ? '成就数' : 'Count' }, { id: 'name', label: isZh ? '名称' : 'Name' }, ]; function _achMatrixApply(rows) { const list = (rows || []).slice(); const sort = state.achMatrixSort || 'rate'; const byRate = (a, b) => (b.rate - a.rate) || (b.active - a.active); if (sort === 'rare') list.sort((a, b) => ((b.rare || 0) - (a.rare || 0)) || byRate(a, b)); else if (sort === 'recent') list.sort((a, b) => ((b.completedAt || 0) - (a.completedAt || 0)) || byRate(a, b)); else if (sort === 'count') list.sort((a, b) => (b.active - a.active) || byRate(a, b)); else if (sort === 'name') list.sort((a, b) => String(a.name || '').localeCompare(String(b.name || ''))); else list.sort(byRate); const q = String(state.achMatrixQuery || '').trim().toLowerCase(); if (!q) return list; return list.filter(g => String(g.name || '').toLowerCase().includes(q)); } function _achMatrixToolbarHtml(total, filtered) { const sort = state.achMatrixSort || 'rate'; const view = state.achMatrixView === 'card' ? 'card' : 'list'; const q = state.achMatrixQuery || ''; const sortBtns = _ACH_MATRIX_SORTS.map(s => ``).join(''); return `
${sortBtns}
`; } function _achMatrixBodyHtml(rows, allCount, filteredCount) { if (!rows || !rows.length) { const noMatch = (allCount || 0) > 0 && (filteredCount || 0) === 0; const title = noMatch ? (isZh ? '没有匹配的游戏' : 'No matching games') : (isZh ? '这一类下暂时没有游戏' : 'No games in this group'); const hint = noMatch ? (isZh ? '换个关键词或排序条件试试。' : 'Try another keyword or sort.') : (isZh ? '换个左侧分类看看,或点上方「立即同步」补齐数据。' : 'Try another filter on the left, or sync to fetch more.'); return `
${escHtml(title)}
${escHtml(hint)}
`; } const card = state.achMatrixView === 'card'; const R = 15, CIRC = 2 * Math.PI * R; const list = rows.map(g => { const pct = Math.max(0, Math.min(100, Number(g.rate) || 0)); const off = CIRC * (1 - pct / 100); const tags = []; if (g.unsynced) { tags.push(`${isZh ? '待同步' : 'PENDING'}`); } else { if (g.missing === 0) tags.push(`${isZh ? '完美' : 'PERFECT'}`); if ((g.rare || 0) > 0) tags.push(`${g.rare} ${isZh ? '稀有' : 'RARE'}`); if (g.completedAt > 0) tags.push(`${isZh ? '通关' : 'CLEARED'} ${_formatAchTime(g.completedAt)}`); } const meta = g.unsynced ? (isZh ? '还没有抓取成就数据' : 'Not fetched yet') : `${g.unlocked}/${g.active} ${isZh ? '成就' : 'achievements'}${g.missing > 0 ? ` · ${isZh ? '还差' : 'missing'} ${g.missing}` : ''}`; if (card) { return `
${posterImg(g.appid, escHtml(g.name))}
${escHtml(g.name)}
${escHtml(meta)}
${tags.join('')}
`; } return `
${_achGameIconHtml(g.appid, g.name)}
${pct}%
${escHtml(g.name)}
${escHtml(meta)}
${tags.join('')}
`; }).join(''); return card ? `
${list}
` : `
${list}
`; } function _achMatrixHtml(d, view) { if (!d || d.scanned === 0) { const running = ACH_REAL.isRunning(); const prog = ACH_REAL.progress(); const target = ACH_REAL.targetCount; let title, hint, cta = ''; if (running && prog) { title = isZh ? `正在同步 ${prog.done}/${prog.total}` : `Syncing ${prog.done}/${prog.total}`; hint = isZh ? '每抓到一款就写入本地缓存,上面的统计与下面这份列表会立刻跟着涨。' : 'Each game is cached as it is fetched; stats and this list update immediately.'; } else if (target === 0) { title = isZh ? '请先获取游戏库' : 'Fetch your library first'; hint = isZh ? '成就同步只覆盖玩满 2 小时的游戏 —— 先在「我的库存」里拉一次游戏库。' : 'Achievement sync covers games with 2h+ playtime. Fetch your library first.'; } else { title = isZh ? '还没有真实成就数据' : 'No real achievement data yet'; hint = isZh ? `点「立即同步」开始:每轮最多 120 款、约 2 分钟,剩余 ${target} 款会在几次访问里陆续铺满。` : `Click Sync: up to 120 games per run, about 2 minutes. ${target} games in total.`; cta = isZh ? '立即同步' : 'Sync now'; } return `
${escHtml(title)}
${escHtml(hint)}
${cta ? `` : ''}
`; } const all = _achMatrixRows(d, view); const filtered = _achMatrixApply(all); const size = Math.max(10, Number(state.achMatrixPageSize) || 50); const pg = paginate(filtered, state.achMatrixPage || 1, size); state.achMatrixPage = pg.page; return `
${_achMatrixToolbarHtml(all.length, filtered.length)}
${_achMatrixBodyHtml(pg.pageItems, all.length, filtered.length)}
`; } function _achMatrixPaint(root) { if (!root || typeof root.querySelector !== 'function') return; let d = null; try { d = ACH_REAL.deep(); } catch (e) { d = null; } const navView = state.achNavView || 'all'; const all = _achMatrixRows(d, navView); const filtered = _achMatrixApply(all); const size = Math.max(10, Number(state.achMatrixPageSize) || 50); const pg = paginate(filtered, state.achMatrixPage || 1, size); state.achMatrixPage = pg.page; const bodyBox = root.querySelector('[data-achmx-body]'); if (bodyBox) { try { bodyBox.innerHTML = _achMatrixBodyHtml(pg.pageItems, all.length, filtered.length); } catch (e) { console.warn('[SGLV] 矩阵重绘失败', e); } } const metaBox = root.querySelector('[data-achmx-meta]'); if (metaBox) { const txt = isZh ? `共 ${all.length} 款${filtered.length !== all.length ? ` · 筛选出 ${filtered.length} 款` : ''} · 第 ${pg.page}/${pg.totalPages} 页` : `${all.length} games${filtered.length !== all.length ? ` · ${filtered.length} shown` : ''} · page ${pg.page}/${pg.totalPages}`; if (metaBox.textContent !== txt) metaBox.textContent = txt; } const pager = root.querySelector('[data-achmx-pager]'); if (pager) { try { renderPagination(pager, 'sglv-ach-matrix', pg.page, pg.totalPages, filtered.length, () => { state.achMatrixPage = pg.page - 1; _achMatrixPaint(root); }, () => { state.achMatrixPage = pg.page + 1; _achMatrixPaint(root); }, (p) => { state.achMatrixPage = p; _achMatrixPaint(root); }); } catch (e) { console.warn('[SGLV] 矩阵分页渲染失败', e); } } _achMatrixBind(root); } function _achMatrixRefresh(root) { if (!root || typeof root.querySelector !== 'function') return; try { if (!root.querySelector('[data-achmx-body]')) { const gamesBox = root.querySelector('[data-achsubview="games"]'); if (!gamesBox) return; let d0 = null; try { d0 = ACH_REAL.deep(); } catch (e) { d0 = null; } gamesBox.innerHTML = _achMatrixHtml(d0, state.achNavView || 'all'); } _achMatrixPaint(root); } catch (e) { console.warn('[SGLV] 游戏成就矩阵刷新失败', e); } } function _achOpenGameDetail(appid) { const id = Number(appid); if (!Number.isFinite(id) || id <= 0) return; try { _achOpenGame(id); } catch (e) { console.warn('[SGLV] 打开成就详情失败', e); } } function _achMatrixBind(scope) { if (!scope || typeof scope.querySelectorAll !== 'function') return; scope.querySelectorAll('[data-achsort]').forEach(btn => { if (btn.dataset.bound === '1') return; btn.dataset.bound = '1'; btn.addEventListener('click', () => { if ((state.achMatrixSort || 'rate') === btn.dataset.achsort) return; state.achMatrixSort = btn.dataset.achsort; state.achMatrixPage = 1; scope.querySelectorAll('[data-achsort]').forEach(b => b.classList.toggle('active', b.dataset.achsort === state.achMatrixSort)); _achMatrixPaint(scope); }); }); scope.querySelectorAll('[data-achview]').forEach(btn => { if (btn.dataset.bound === '1') return; btn.dataset.bound = '1'; btn.addEventListener('click', () => { const want = btn.dataset.achview === 'card' ? 'card' : 'list'; if ((state.achMatrixView || 'list') === want) return; state.achMatrixView = want; state.achMatrixPage = 1; scope.querySelectorAll('[data-achview]').forEach(b => b.classList.toggle('active', b.dataset.achview === want)); _achMatrixPaint(scope); }); }); scope.querySelectorAll('[data-achq]').forEach(inp => { if (inp.dataset.bound === '1') return; inp.dataset.bound = '1'; inp.addEventListener('input', () => { if (scope._achMxSearchTimer) clearTimeout(scope._achMxSearchTimer); scope._achMxSearchTimer = setTimeout(() => { state.achMatrixQuery = inp.value || ''; state.achMatrixPage = 1; _achMatrixPaint(scope); }, 250); }); }); scope.querySelectorAll('[data-achempty="sync"]').forEach(btn => { if (btn.dataset.bound === '1') return; btn.dataset.bound = '1'; btn.addEventListener('click', () => { const sync = (scope.querySelector && scope.querySelector('#sglv-ach-real-sync')) || (document.querySelector ? document.querySelector('#sglv-ach-real-sync') : null); if (sync && !sync.disabled) { sync.click(); return; } showToast(isZh ? '当前没有待同步的游戏' : 'Nothing to sync'); }); }); scope.querySelectorAll('[data-achgame]').forEach(el => { if (el.dataset.bound === '1') return; el.dataset.bound = '1'; el.addEventListener('click', () => _achOpenGameDetail(el.dataset.achgame)); el.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); _achOpenGameDetail(el.dataset.achgame); } }); }); } function _achShelfHtml(achievements, unlocked, totalPts, maxPts, achLevel, noReal) { const achs = Array.isArray(achievements) ? achievements : []; const un = achs.filter(a => a.unlocked); const open = state.achShelfTouched ? !!state.achShelfOpen : !!noReal; const head = ` `; const body = achs.map(a => `
${a.icon}
${escHtml(a.name)}
`).join(''); return `
${head}
${body}
${isZh ? '自定义成就由本地游戏库指标计算(游戏数 / 时长 / 专精度),与 Steam 真实成就无关,仅作趣味徽章。' : 'Custom achievements are computed from local library metrics — a novelty badge shelf, unrelated to Steam achievements.'}
`; } function renderMyAchievementsTab(parent) { const achievements = computeMyAchievementsCached(); const unlocked = achievements.filter(a => a.unlocked); const totalPts = unlocked.reduce((s, a) => s + (a.pts || 0), 0); const maxPts = achievements.reduce((s, a) => s + (a.pts || 0), 0); const achLevel = Math.floor(totalPts / 100) + 1; const navView = state.achNavView || 'all'; const steamView = (state.achSteamView === 'insights') ? 'insights' : 'games'; let steamS = null, steamD = null; try { steamS = ACH_REAL.summary(); } catch (e) { steamS = null; } try { steamD = ACH_REAL.deep(); } catch (e) { steamD = null; } const achIndex = _achIndexParts(achievements, steamS, steamD); const counts = _achNavCounts(steamD, steamS); const recent = (steamD && Array.isArray(steamD.recentUnlocks)) ? steamD.recentUnlocks : []; const html = `
${_achSidebarHtml(navView, counts, recent)}
${_achHeaderHtml(achIndex)}
${(() => { try { return `
${_achRealBlockHtml()}
`; } catch (e) { console.warn('[SGLV] 真实成就区渲染失败', e); return ''; } })()}
${(() => { try { return _achMatrixHtml(steamD, navView); } catch (e) { console.warn('[SGLV] 游戏成就矩阵渲染失败', e); return `
${isZh ? '矩阵渲染失败,详见控制台' : 'Matrix render failed - see console'}
`; } })()}
${(() => { try { return _achDeepHtml(); } catch (e) { console.warn('[SGLV] 聚合分析渲染失败', e); return ''; } })()}
${_achShelfHtml(achievements, unlocked, totalPts, maxPts, achLevel, !counts.synced && !counts.private)}
`; parent.innerHTML = html; try { _achMatrixBind(parent); } catch (e) { } const switchSub = want => { state.achSteamView = want; parent.querySelectorAll('[data-achsub]').forEach(b => b.classList.toggle('active', b.dataset.achsub === want)); parent.querySelectorAll('[data-achsubview]').forEach(v => v.classList.toggle('active', v.dataset.achsubview === want)); if (want === 'insights') { try { _achDeepBind(parent); } catch (e) { } } }; parent.querySelectorAll('[data-achsub]').forEach(btn => { btn.addEventListener('click', () => { const want = btn.dataset.achsub === 'insights' ? 'insights' : 'games'; if ((state.achSteamView || 'games') === want) return; switchSub(want); }); }); parent.querySelectorAll('[data-achnav]').forEach(el => { el.addEventListener('click', () => { const want = el.dataset.achnav; if ((state.achNavView || 'all') === want) return; state.achNavView = want; state.achSteamView = 'games'; renderMyAchievementsTab(parent); }); }); const shelfToggle = parent.querySelector('[data-achshelf="toggle"]'); if (shelfToggle) { shelfToggle.addEventListener('click', () => { const shelf = parent.querySelector('[data-achshelf]'); if (!shelf) return; const isOpen = shelf.classList.toggle('open'); state.achShelfOpen = isOpen; state.achShelfTouched = true; shelfToggle.setAttribute('aria-expanded', isOpen ? '1' : '0'); const caret = shelfToggle.querySelector('.sglv-ach-shelf-caret'); if (caret) caret.textContent = isOpen ? '▾' : '▸'; }); } const resetBtn = parent.querySelector('#sglv-ach-reset'); if (resetBtn) { resetBtn.addEventListener('click', () => { if (confirm(T.achResetConfirm)) { GM_setValue(_ACH_CACHE_KEY, '{}'); renderMyAchievementsTab(parent); } }); } try { _achRealBind(parent); } catch (e) { console.warn('[SGLV] 真实成就区事件绑定失败', e); } try { _achDeepBind(parent); } catch (e) { console.warn('[SGLV] 深度面板事件绑定失败', e); } try { _achRealAutoKick(parent); } catch (e) { console.warn('[SGLV] 真实成就自动同步启动失败', e); } try { if (!ACH_REAL.isReady()) { ACH_REAL.ready().then(ok => { if (!ok) return; try { _achRealRefresh(parent); } catch (e) { console.warn('[SGLV] 缓存读完后刷新真实成就区失败', e); } }); } } catch (e) { console.warn('[SGLV] 成就缓存预热失败', e); } } const _SC_CONFIG_KEY = nsKey('showcase_config'); function _loadShowcaseConfig() { if (state.showcaseConfigLoaded) return state.showcaseConfig; state.showcaseConfigLoaded = true; try { const raw = GM_getValue(_SC_CONFIG_KEY, ''); if (raw) { const cfg = JSON.parse(raw); if (cfg && Array.isArray(cfg.selectedAppIds)) { if (!Array.isArray(cfg.selectedBadgeIds)) cfg.selectedBadgeIds = []; state.showcaseConfig = cfg; return cfg; } } } catch (e) { } state.showcaseConfig = { selectedAppIds: [], selectedBadgeIds: [] }; return state.showcaseConfig; } function _saveShowcaseConfig(cfg) { state.showcaseConfig = cfg; try { GM_setValue(_SC_CONFIG_KEY, JSON.stringify(cfg)); } catch (e) { } } const _SC_DATA_CACHE_KEY = nsKey('showcase_data_cache'); const _SC_DATA_SCHEMA = 1; const _SC_DATA_TTL = 30 * 60 * 1000; const _SC_DATA_STALE_TTL = 6 * 60 * 60 * 1000; let _scCacheWriteWarned = false; function _showcaseUnlockedOnly(achievements) { return (achievements || []).filter(a => a && a.unlocked); } function _computeShowcaseCacheHash() { const cfg = _loadShowcaseConfig(); const games = getStatFilteredGames(); const coverPart = (cfg.selectedAppIds || []).join(','); const badgePart = (cfg.selectedBadgeIds || []).map(b => b.appid + ':' + b.badgeid + ':' + (b.isFoil ? '1' : '0')).join(','); const libPart = games.length + ':' + (games.length > 0 ? Math.floor(games.reduce((s, g) => s + (g.playtime || 0), 0) / 60) : 0); return [coverPart, badgePart, libPart].join('|'); } function _readShowcaseCache() { try { const raw = GM_getValue(_SC_DATA_CACHE_KEY, ''); if (!raw) return null; const parsed = JSON.parse(raw); if (!parsed || !parsed.data || !parsed.timestamp) return null; if (parsed.schemaVer !== _SC_DATA_SCHEMA) return null; return parsed; } catch { return null; } } function _writeShowcaseCache(data, configHash) { try { const steamId = getActiveSteamId(); GM_setValue(_SC_DATA_CACHE_KEY, JSON.stringify({ schemaVer: _SC_DATA_SCHEMA, timestamp: Date.now(), steamId, configHash, data, })); } catch (e) { if (!_scCacheWriteWarned) { _scCacheWriteWarned = true; console.warn('[SGLV] 展柜缓存写入失败(可能超 GM 存储配额),已跳过本次持久化', e); } } } function _swrReadShowcaseCache(configHash) { const cached = _readShowcaseCache(); if (!cached) return { data: null, stale: false, timestamp: 0 }; const steamId = getActiveSteamId(); if (cached.steamId && steamId && cached.steamId !== steamId) return { data: null, stale: false, timestamp: 0 }; const age = Date.now() - cached.timestamp; if (age > _SC_DATA_STALE_TTL) return { data: null, stale: false, timestamp: 0 }; const configChanged = (cached.configHash !== configHash); const stale = (age > _SC_DATA_TTL) || configChanged; return { data: cached.data, stale, configChanged, timestamp: cached.timestamp }; } function _showcaseDataSignature(profile, recentGames, badges, stats) { const p = profile ? [profile.name, profile.level, profile.badgeCount, profile.country].join(':') : ''; const r = (recentGames || []).map(g => g.appid + ':' + (g.playtime_forever || 0)).join(','); const b = (badges || []).map(b => b.appid + ':' + b.badgeid + ':' + b.level).join(','); const s = stats ? [stats.gameCount, stats.totalHours, stats.achCount, stats.totalAchPts].join(':') : ''; return [p, r, b, s].join('|'); } function _getDefaultCoverAppIds(allGames) { return allGames .filter(g => (g.playtime || 0) > 0) .sort((a, b) => (b.playtime || 0) - (a.playtime || 0)) .slice(0, 8) .map(g => g.appid); } function _getShowcaseCoverAppIds(allGames) { const cfg = _loadShowcaseConfig(); if (cfg.selectedAppIds && cfg.selectedAppIds.length > 0) { const validSet = new Set(allGames.map(g => g.appid)); const valid = cfg.selectedAppIds.filter(id => validSet.has(id)); if (valid.length > 0) return valid.slice(0, 8); } return _getDefaultCoverAppIds(allGames); } function _applyCoverChain(imgEl, appid) { if (!imgEl || !appid) return; const kind = 'poster'; const goodUrl = getPosterGood(appid, kind); if (goodUrl) { imgEl.src = goodUrl; imgEl.onerror = function () { _tryCdnChain(imgEl, appid, kind); }; return; } _tryCdnChain(imgEl, appid, kind); } function _tryCdnChain(imgEl, appid, kind) { const urls = coverChainUrls(appid, kind); let idx = 0; imgEl.src = urls[0]; imgEl.onload = function () { recordPosterGood(appid, imgEl.src, kind); imgEl.onload = null; }; imgEl.onerror = function () { idx++; if (idx < urls.length) { imgEl.src = urls[idx]; } else { imgEl.onload = null; _tryApiFallback(imgEl, appid, kind); } }; } function _tryApiFallback(imgEl, appid, kind) { _fetchCoverApiUrl(appid, kind).then(url => { if (url) { const fullUrl = url.startsWith('http') ? url : `https://cdn.cloudflare.steamstatic.com/steam/apps/${appid}/${url}`; imgEl.onerror = function () { imgEl.onerror = null; _showCoverPlaceholder(imgEl); }; imgEl.onload = function () { recordPosterGood(appid, fullUrl, kind); imgEl.onload = null; }; imgEl.src = fullUrl; } else { _showCoverPlaceholder(imgEl); } }).catch(() => _showCoverPlaceholder(imgEl)); } function _showCoverPlaceholder(imgEl) { if (!imgEl || !imgEl.parentElement) return; imgEl.onerror = null; imgEl.onload = null; imgEl.style.display = 'none'; const ph = document.createElement('div'); ph.className = 'sglv-sc-cover-placeholder'; ph.textContent = isZh ? '无封面' : 'No Cover'; imgEl.parentElement.appendChild(ph); } function _applyGameIcon(imgEl, appid, iconHash) { const good = getPosterGood(appid, 'icon'); imgEl.src = good || communityIconChainUrls(appid, iconHash)[0]; imgEl.onload = function () { recordPosterGood(appid, imgEl.src, 'icon'); imgEl.onload = null; }; imgEl.onerror = function () { imgEl.onerror = null; sglvIconFallback(imgEl, appid, iconHash); }; } async function _fetchShowcaseProfile() { const TTL = 30 * 60 * 1000; if (state.showcaseProfile && (Date.now() - state.showcaseProfileAt) < TTL) { return state.showcaseProfile; } if (state.showcaseProfileLoading) { return new Promise(resolve => { const check = setInterval(() => { if (!state.showcaseProfileLoading) { clearInterval(check); resolve(state.showcaseProfile); } }, 100); }); } state.showcaseProfileLoading = true; const steamId = getActiveSteamId(); let avatar = ''; let name = isZh ? 'Steam 玩家' : 'Steam Player'; let level = 0; let country = ''; let profileUrl = ''; let badgeCount = 0; const sgisProfile = SGLV_API.getSGISProfile && SGLV_API.getSGISProfile(); if (sgisProfile && sgisProfile.summary) { const s = sgisProfile.summary; avatar = s.avatarfull || s.avatarmedium || s.avatar || ''; name = s.personaname || name; country = s.loccountrycode || ''; profileUrl = s.profileurl || ''; if (sgisProfile.userBadges && sgisProfile.userBadges.playerLevel) { level = sgisProfile.userBadges.playerLevel; if (Array.isArray(sgisProfile.userBadges.badges)) { badgeCount = sgisProfile.userBadges.badges.length; } } else if (sgisProfile.level && typeof sgisProfile.level === 'number') { level = sgisProfile.level; } if (avatar && level > 0) { const profile = { avatar, name, level, country, steamId, profileUrl, badgeCount }; state.showcaseProfile = profile; state.showcaseProfileAt = Date.now(); state.showcaseProfileLoading = false; return profile; } } const apiKey = storage.getApiKey(); if (apiKey && steamId) { const [summary, levelFromCommunity] = await Promise.all([ (async () => { try { const url = `https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=${apiKey}&steamids=${steamId}`; const data = await requestSteamAPI(url); const player = data?.response?.players?.[0]; return player || null; } catch { return null; } })(), (async () => { if (level > 0) return level; try { const html = await sglvGmFetchTextRetry(`https://steamcommunity.com/profiles/${steamId}/`, { timeout: 12000 }); const m = html.match(/"player_level":(\d+)/) || html.match(/class="friendPlayerLevelNum"[^>]*>(\d+)/); return m ? parseInt(m[1], 10) : 0; } catch { return 0; } })(), ]); if (summary) { if (!avatar) avatar = summary.avatarfull || summary.avatarmedium || summary.avatar || ''; if (name === (isZh ? 'Steam 玩家' : 'Steam Player')) name = summary.personaname || name; if (!country) country = summary.loccountrycode || ''; if (!profileUrl) profileUrl = summary.profileurl || ''; } if (levelFromCommunity > 0) level = levelFromCommunity; } if (!avatar || !level || !name || name === (isZh ? 'Steam 玩家' : 'Steam Player')) { try { const pulldown = document.querySelector('#account_pulldown'); if (pulldown && pulldown.textContent.trim() && (name === (isZh ? 'Steam 玩家' : 'Steam Player'))) { name = pulldown.textContent.trim(); } if (!avatar) { const avatarImg = document.querySelector('#global_actions .user_avatar img, .playerAvatarAutoSizeInner img, .user_avatar img'); if (avatarImg && avatarImg.src) avatar = avatarImg.src; } if (!level) { const levelEl = document.querySelector('.friendPlayerLevelNum'); if (levelEl) { const lv = parseInt(levelEl.textContent.trim(), 10); if (!isNaN(lv) && lv > 0) level = lv; } } } catch { } } if ((!avatar || !level) && steamId && !apiKey) { try { const html = await sglvGmFetchTextRetry(`https://steamcommunity.com/profiles/${steamId}/`, { timeout: 10000 }); if (!avatar) { const avMatch = html.match(/"avatarfull":"([^"]+)"/) || html.match(/class="playerAvatarAutoSizeInner"[^>]*>[\s\S]*?]+src="([^"]+)"/); if (avMatch) avatar = avMatch[1]; } if (!level) { const lvMatch = html.match(/"player_level":(\d+)/) || html.match(/class="friendPlayerLevelNum"[^>]*>(\d+)/); if (lvMatch) { const lv = parseInt(lvMatch[1], 10); if (!isNaN(lv) && lv > 0) level = lv; } } if (name === (isZh ? 'Steam 玩家' : 'Steam Player')) { const nmMatch = html.match(/"personaname":"([^"]+)"/); if (nmMatch) name = nmMatch[1]; } } catch { } } const profile = { avatar, name, level, country, steamId, profileUrl, badgeCount }; state.showcaseProfile = profile; state.showcaseProfileAt = Date.now(); state.showcaseProfileLoading = false; return profile; } async function _fetchRecentPlayedGames() { const steamId = getActiveSteamId(); const gameMap = new Map(getStatFilteredGames().map(g => [g.appid, g])); const sgisProfile = SGLV_API.getSGISProfile && SGLV_API.getSGISProfile(); if (sgisProfile && Array.isArray(sgisProfile.recentGames) && sgisProfile.recentGames.length > 0) { return sgisProfile.recentGames.map(g => { const local = gameMap.get(g.appid); return { appid: g.appid, name: g.name || (local ? local.name : `App ${g.appid}`), playtime_2weeks: g.playtime_2weeks || 0, playtime_forever: g.playtime_forever || (local ? local.playtime || 0 : 0), img_icon_url: g.img_icon_url || '', iconUrl: getGameIconUrl(g.appid, g.img_icon_url), }; }); } const apiKey = storage.getApiKey(); if (apiKey && steamId) { try { const url = `https://api.steampowered.com/IPlayerService/GetRecentlyPlayedGames/v0001/?key=${apiKey}&steamid=${steamId}&format=json`; const data = await requestSteamAPI(url); const games = data?.response?.games || []; if (games.length > 0) { return games.map(g => { const local = gameMap.get(g.appid); return { appid: g.appid, name: g.name || (local ? local.name : `App ${g.appid}`), playtime_2weeks: g.playtime_2weeks || 0, playtime_forever: g.playtime_forever || (local ? local.playtime || 0 : 0), img_icon_url: g.img_icon_url || '', iconUrl: getGameIconUrl(g.appid, g.img_icon_url), }; }); } } catch { } } const allGames = getStatFilteredGames(); return allGames .filter(g => g.lastPlayed && g.lastPlayed > 0) .sort((a, b) => (b.lastPlayed || 0) - (a.lastPlayed || 0)) .slice(0, 8) .map(g => ({ appid: g.appid, name: g.name, playtime_2weeks: 0, playtime_forever: g.playtime || 0, img_icon_url: g.icon || '', iconUrl: getGameIconUrl(g.appid, g.icon), })); } const _SC_BADGE_ICONS_KEY = nsKey('showcase_badge_icons'); const _SC_BADGE_ICONS_TTL = 60 * 60 * 1000; async function _fetchBadgeIcons(steamId) { if (!steamId) return null; if (state.showcaseBadgeIcons && (Date.now() - state.showcaseBadgeIconsAt) < _SC_BADGE_ICONS_TTL) { return state.showcaseBadgeIcons; } if (state.showcaseBadgeIconsLoading) { return new Promise(resolve => { const check = setInterval(() => { if (!state.showcaseBadgeIconsLoading) { clearInterval(check); resolve(state.showcaseBadgeIcons); } }, 100); }); } state.showcaseBadgeIconsLoading = true; try { const cached = GM_getValue(_SC_BADGE_ICONS_KEY, ''); if (cached) { const parsed = JSON.parse(cached); if (parsed && parsed.timestamp && (Date.now() - parsed.timestamp < _SC_BADGE_ICONS_TTL)) { state.showcaseBadgeIcons = parsed.data || {}; state.showcaseBadgeIconsAt = parsed.timestamp; state.showcaseBadgeIconsLoading = false; return state.showcaseBadgeIcons; } } } catch { } const icons = {}; try { const html = await sglvGmFetchTextRetry(`https://steamcommunity.com/profiles/${steamId}/badges`, { timeout: 15000 }); if (html && html.length > 500) { const doc = new DOMParser().parseFromString(html, 'text/html'); const rows = doc.querySelectorAll('.badge_row'); rows.forEach(row => { try { const linkEl = row.querySelector('.badge_row_overlay'); const url = linkEl ? linkEl.href : ''; let appId = '', isFoil = false; if (url) { const foilMatch = url.match(/\/gamecards\/foil\/(\d+)/); if (foilMatch) { appId = foilMatch[1]; isFoil = true; } else { const norm = url.match(/\/gamecards\/(\d+)/); if (norm) appId = norm[1]; } } let iconUrl = ''; const badgeInfoImg = row.querySelector('.badge_info_image img'); if (badgeInfoImg) iconUrl = badgeInfoImg.getAttribute('data-delayed-image') || badgeInfoImg.src || ''; if (!iconUrl) { const ownedCard = row.querySelector('.badge_progress_card.owned img'); if (ownedCard) iconUrl = ownedCard.getAttribute('data-delayed-image') || ownedCard.src || ''; } if (!iconUrl) { const lockedEl = row.querySelector('.badge_empty_circle img'); if (lockedEl) iconUrl = lockedEl.getAttribute('data-delayed-image') || lockedEl.src || ''; } if (!iconUrl) { const emptyLeftEl = row.querySelector('.badge_empty_left img'); if (emptyLeftEl) iconUrl = emptyLeftEl.getAttribute('data-delayed-image') || emptyLeftEl.src || ''; } if (appId && iconUrl && /^https?:\/\//.test(iconUrl)) { icons[appId + '|' + (isFoil ? '1' : '0')] = iconUrl; } } catch { } }); } } catch { } state.showcaseBadgeIcons = icons; state.showcaseBadgeIconsAt = Date.now(); state.showcaseBadgeIconsLoading = false; try { GM_setValue(_SC_BADGE_ICONS_KEY, JSON.stringify({ timestamp: Date.now(), data: icons })); } catch { } return icons; } function _mergeBadgeData(badgeData, icons) { if (!badgeData || !badgeData.badges) return []; const owned = (state.ownedGames && state.ownedGames.length) ? state.ownedGames : storage.getCachedGames(); const ownedMap = {}; owned.forEach(g => { if (g && g.appid) ownedMap[String(g.appid)] = g.name; }); const getCardDbName = SGLV_API.getCardDbGameName || function() { return ''; }; const getCardDbMaxLv = SGLV_API.getCardDbMaxLevel || function() { return 0; }; const ACTIVITY_CDN = 'https://cdn.cloudflare.steamstatic.com/steamcommunity/public/images/items/'; const result = badgeData.badges.map(b => { const appId = b.appid || 0; let gameName = ''; if (appId > 0) { gameName = ownedMap[String(appId)] || getCardDbName(appId) || ''; } let eventName = ''; const evtMap = SGLV_API.getSteamEventAppIdMap ? SGLV_API.getSteamEventAppIdMap() : null; if (evtMap && evtMap[String(appId)]) { eventName = evtMap[String(appId)]; } else if (appId > 3000000 && !gameName) { eventName = 'Steam 活动'; } let badgeType = 'game'; if (eventName) badgeType = 'event'; else if (b.communityitemid) badgeType = 'community'; const isFoil = !!(b.border_color && b.border_color === 1); let iconUrl = ''; if (icons && icons[appId + '|' + (isFoil ? '1' : '0')]) { iconUrl = icons[appId + '|' + (isFoil ? '1' : '0')]; } else if (icons && icons[appId + '|0']) { iconUrl = icons[appId + '|0']; } if (!iconUrl && eventName && appId > 0) { iconUrl = ACTIVITY_CDN + appId + '/icon_64x64.png'; } if (!iconUrl && appId > 0 && !eventName) { iconUrl = `https://shared.fastly.steamstatic.com/store_item_assets/steam/apps/${appId}/capsule_184x69.jpg`; } return { appid: appId, badgeid: b.badgeid, level: b.level || 0, xp: b.xp || 0, scarcity: b.scarcity || 0, completionTime: b.completion_time || 0, iconUrl, gameName, eventName, name: gameName || eventName || (b.communityitemid ? '社区徽章 #' + b.badgeid : '游戏 #' + appId), badgeType, isFoil, maxLevel: getCardDbMaxLv(appId), badgeUrl: appId > 0 ? `https://steamcommunity.com/profiles/${getActiveSteamId()}/badges/${appId}` : '', }; }); result.sort((a, b) => (b.level || 0) - (a.level || 0) || (b.xp || 0) - (a.xp || 0)); return result; } async function _getShowcaseBadges() { let badgeData = null; const sgisProfile = SGLV_API.getSGISProfile && SGLV_API.getSGISProfile(); if (sgisProfile && sgisProfile.userBadges) { badgeData = sgisProfile.userBadges; } if (!badgeData && SGLV_API.getSGISUserBadges) { badgeData = SGLV_API.getSGISUserBadges(); } if (!badgeData) { const steamId = getActiveSteamId(); const apiKey = storage.getApiKey(); if (apiKey && steamId) { try { const url = `https://api.steampowered.com/IPlayerService/GetBadges/v1/?key=${apiKey}&steamid=${steamId}`; const data = await requestSteamAPI(url); badgeData = { badges: data?.response?.badges || [], playerLevel: data?.response?.player_level || 0, }; } catch { } } } if (!badgeData || !badgeData.badges || badgeData.badges.length === 0) return []; const steamId = getActiveSteamId(); const icons = await _fetchBadgeIcons(steamId); return _mergeBadgeData(badgeData, icons); } function _getSelectedShowcaseBadges(allBadges) { const cfg = _loadShowcaseConfig(); if (!cfg.selectedBadgeIds || cfg.selectedBadgeIds.length === 0) return []; return cfg.selectedBadgeIds.map(sel => { const badge = allBadges.find(b => b.appid === sel.appid && b.badgeid === sel.badgeid && !!b.isFoil === !!sel.isFoil ); return badge || null; }).filter(Boolean); } function _openBadgePicker(allBadges, currentSelected, onSave) { const gameBadges = allBadges.filter(b => b.badgeType === 'game'); const eventBadges = allBadges.filter(b => b.badgeType === 'event'); const communityBadges = allBadges.filter(b => b.badgeType === 'community'); let currentFilter = 'all'; let page = 1; let lastQuery = ''; let lastTotal = 0; let lastTotalPages = 1; const PAGE_SIZE = 200; function filteredList(searchVal) { let list = allBadges; if (currentFilter === 'game') list = gameBadges; else if (currentFilter === 'event') list = eventBadges; else if (currentFilter === 'community') list = communityBadges; const filterLower = (searchVal || '').toLowerCase().trim(); if (filterLower) { list = list.filter(b => (b.name || '').toLowerCase().includes(filterLower) || String(b.appid).includes(filterLower) ); } return list; } openPickerModal({ overlayId: 'sglv-sc-badge-picker-overlay', idBase: 'sglv-sc-badge', modalCls: 'sglv-sc-picker sglv-sc-badge-picker', title: isZh ? '选择展柜徽章(最多 3 个)' : 'Select Showcase Badges (max 3)', searchPlaceholder: isZh ? '搜索徽章…' : 'Search badges…', extraHtml: `
`, gridCls: 'sglv-sc-badge-grid', afterGridHtml: `
`, countInit: currentSelected.length, maxSelect: 3, saveText: isZh ? '保存' : 'Save', currentSelected: currentSelected.map(b => b.appid + '|' + b.badgeid + '|' + (b.isFoil ? '1' : '0')), canSave: size => size > 0 || currentSelected.length > 0, getItems: (searchVal) => { if ((searchVal || '') !== lastQuery) { page = 1; lastQuery = searchVal || ''; } const list = filteredList(searchVal); lastTotal = list.length; const { pageItems, totalPages, page: clamped } = paginate(list, page, PAGE_SIZE); page = clamped; lastTotalPages = totalPages; return pageItems; }, itemKey: b => b.appid + '|' + b.badgeid + '|' + (b.isFoil ? '1' : '0'), renderItem: (b, isSelected) => { const key = b.appid + '|' + b.badgeid + '|' + (b.isFoil ? '1' : '0'); const foilTag = b.isFoil ? 'Foil' : ''; const lvlTag = b.level > 0 ? `Lv.${b.level}${b.maxLevel > 0 ? '/' + b.maxLevel : ''}` : ''; return `
${b.iconUrl ? `` : '
' + (b.badgeType === 'event' ? '🎉' : b.badgeType === 'community' ? '★' : '🎮') + '
'}
${escHtml(b.name)}
${foilTag}${lvlTag}${b.xp || 0} XP
✓
`; }, itemSelector: '.sglv-sc-badge-pick-item', keyFromItem: el => el.dataset.key, onGridRendered: (grid, rerender) => { const pager = grid.parentElement.querySelector('#sglv-sc-badge-pager'); if (!pager) return; if (lastTotalPages > 1) { renderPagination(pager, 'sglv-scb', page, lastTotalPages, lastTotal, () => { page -= 1; rerender(); }, () => { page += 1; rerender(); }, (p) => { page = p; rerender(); }); } else { pager.innerHTML = ''; } }, bindExtra: (overlay, rerender) => { overlay.querySelectorAll('.sglv-sc-badge-tab').forEach(tab => { tab.addEventListener('click', () => { overlay.querySelectorAll('.sglv-sc-badge-tab').forEach(t => t.classList.remove('active')); tab.classList.add('active'); currentFilter = tab.dataset.filter; page = 1; rerender(); }); }); }, buildResult: (selected) => { const selectedBadges = []; selected.forEach(key => { const [appid, badgeid, foil] = key.split('|'); const badge = allBadges.find(b => String(b.appid) === appid && String(b.badgeid) === badgeid && !!b.isFoil === (foil === '1') ); if (badge) selectedBadges.push({ appid: badge.appid, badgeid: badge.badgeid, isFoil: badge.isFoil, }); }); return selectedBadges; }, maxWarningText: isZh ? '最多选择 3 个徽章' : 'Max 3 badges', savedToastText: isZh ? '展柜徽章已更新' : 'Showcase badges updated', onSave, }); } function renderShowcaseTab(parent) { ++state.showcaseRenderToken; const allGames = getStatFilteredGames(); const configHash = _computeShowcaseCacheHash(); parent.innerHTML = createSkeleton('showcase'); const swr = _swrReadShowcaseCache(configHash); if (swr.data && swr.data.profile) { _renderShowcaseContent(parent, swr.data, allGames); if (!state.showcaseProfile && swr.data.profile) { state.showcaseProfile = swr.data.profile; state.showcaseProfileAt = swr.timestamp || 0; } if (!swr.stale && !swr.configChanged) { state.showcasePreheated = true; } } } async function prepareShowcaseTabData(parent) { const myToken = state.showcaseRenderToken; const allGames = getStatFilteredGames(); const configHash = _computeShowcaseCacheHash(); const swr = _swrReadShowcaseCache(configHash); if (swr.data && swr.data.profile && !swr.stale && !swr.configChanged) { state.showcasePreheated = true; return; } const data = await _fetchShowcaseDataAll(); if (myToken !== state.showcaseRenderToken) return; const { profile, recentGames, badges: allBadges, stats } = data; const newData = { profile, recentGames, badges: allBadges, achievements: _showcaseUnlockedOnly(data.achievements), stats }; const cachedSig = swr.data ? _showcaseDataSignature(swr.data.profile, swr.data.recentGames, swr.data.badges, swr.data.stats) : ''; const newSig = _showcaseDataSignature(profile, recentGames, allBadges, stats); if (cachedSig === newSig) { _writeShowcaseCache(newData, configHash); state.showcasePreheated = true; return; } _renderShowcaseContent(parent, newData, allGames); _writeShowcaseCache(newData, configHash); state.showcasePreheated = true; } function _showcaseHeroHtml(profile, gameCount, totalHours, steamBadgeCount, totalAchPts, allBadges, selectedBadges) { const avatarHtml = profile.avatar ? `${escHtml(profile.name)}` : `
${escHtml(profile.name.charAt(0).toUpperCase())}
`; const levelBadgeHtml = profile.level > 0 ? `
Lv.${profile.level}
` : ''; const countryHtml = profile.country ? ` ${escHtml(profile.country)} ${escHtml(profile.country)} ` : ''; const badgeSlotsHtml = []; for (let i = 0; i < 3; i++) { const badge = selectedBadges[i]; if (badge) { const lvlText = badge.level > 0 ? `Lv.${badge.level}${badge.maxLevel > 0 ? '/' + badge.maxLevel : ''}` : ''; const foilTag = badge.isFoil ? 'Foil' : ''; badgeSlotsHtml.push(`
${badge.iconUrl ? `${escHtml(badge.name)} ` : `
${ICONS.medal}
` } ${lvlText} ${foilTag}
`); } else { badgeSlotsHtml.push(`
+
`); } } const badgeAreaHtml = allBadges.length > 0 ? `
${badgeSlotsHtml.join('')}
` : ''; return `
${avatarHtml}
${escHtml(profile.name)} ${levelBadgeHtml} ${countryHtml}
${ICONS.library}
${gameCount.toLocaleString()}
${isZh ? '游戏' : 'Games'}
${ICONS.clock || ICONS.barChart}
${totalHours.toLocaleString()}h
${isZh ? '总时长' : 'Hours'}
${steamBadgeCount > 0 ? `
${ICONS.achievement}
${steamBadgeCount}
${isZh ? '成就' : 'Ach'}
` : ''}
${ICONS.trophy}
${totalAchPts.toLocaleString()}
${isZh ? '点数' : 'Pts'}
${badgeAreaHtml}
`; } function _showcaseCoverCardHtml(coverAppIds, gameMap) { const coverItemsHtml = []; for (let i = 0; i < 8; i++) { const appid = coverAppIds[i]; if (appid) { const g = gameMap.get(appid); const hours = g ? Math.floor((g.playtime || 0) / 60) : 0; coverItemsHtml.push(`
${escHtml(g ? g.name : '')}
${escHtml(g ? g.name : '')}
${hours > 0 ? `
${hours}h
` : ''}
`); } else { coverItemsHtml.push(`
${isZh ? '空位' : 'Empty'}
`); } } return `
${ICONS.showcase} ${isZh ? '我的游戏封面' : 'My Game Covers'}
${coverItemsHtml.join('')}
`; } function _showcasePlaytimeCardHtml(recentGamesDisplay, maxRecentPlaytime) { const playtimeListHtml = recentGamesDisplay.length > 0 ? recentGamesDisplay.map(g => { const totalHours = Math.floor((g.playtime_forever || 0) / 60); const recentHours = Math.floor((g.playtime_2weeks || 0) / 60); const pct = maxRecentPlaytime > 0 ? Math.min(100, ((g.playtime_forever || 0) / maxRecentPlaytime) * 100) : 0; const recentLabel = g.playtime_2weeks > 0 ? `${isZh ? '近2周' : '2w'}: ${recentHours}h` : ''; const totalLabel = `${isZh ? '总计' : 'Total'}: ${totalHours}h`; return `
${escHtml(g.name)}
${recentLabel}${recentLabel && totalLabel ? '·' : ''}${totalLabel}
${hbarRow({ cls: 'sc', pct })}
`; }).join('') : `
${isZh ? '暂无最近游玩记录' : 'No recent playtime'}
`; return `
${ICONS.clock || ICONS.barChart} ${isZh ? '最近游玩时长' : 'Recent Playtime'}
${playtimeListHtml}
`; } function _showcaseAchCardHtml(recentAchs) { const achListHtml = recentAchs.length > 0 ? recentAchs.map(a => `
${a.icon}
${escHtml(a.name)}
${escHtml(_formatRelTime(a.unlockedAt))}
+${a.pts}
`).join('') : `
${isZh ? '暂无解锁的成就' : 'No unlocked achievements'}
`; return `
${ICONS.achievement} ${isZh ? '最近解锁成就' : 'Recent Achievements'}
${achListHtml}
`; } function _showcaseTagCardHtml(unlockedCats) { const tagLabels = { collector: isZh ? '收藏家' : 'Collector', playtime: isZh ? '深度玩家' : 'Dedicated', mastery: isZh ? '完美主义' : 'Perfectionist', diversity: isZh ? '多元品味' : 'Diverse', loyalty: isZh ? '忠实粉丝' : 'Loyal', special: isZh ? '特殊成就' : 'Special', }; const tagsHtml = unlockedCats.size > 0 ? Array.from(unlockedCats).map(cat => `${tagLabels[cat] || cat}`).join('') : `${isZh ? '继续游玩解锁更多标签' : 'Play more to unlock tags'}`; return `
${ICONS.star || ICONS.achievement} ${isZh ? '玩家画像' : 'Player Profile'}
${tagsHtml}
`; } function _bindShowcaseEvents(parent, allGames, allBadges, coverAppIds, selectedBadges) { parent.querySelectorAll('img[data-cover-appid]').forEach(img => { const appid = parseInt(img.dataset.coverAppid, 10); if (appid) _applyCoverChain(img, appid); }); parent.querySelectorAll('img[data-icon-appid]').forEach(img => { const appid = parseInt(img.dataset.iconAppid, 10); const hash = img.dataset.iconHash || ''; if (appid) _applyGameIcon(img, appid, hash); }); const editBtn = parent.querySelector('#sglv-sc-edit-covers'); if (editBtn) { editBtn.addEventListener('click', () => { _openCoverPicker(allGames, coverAppIds, (newAppIds) => { const cfg = _loadShowcaseConfig(); _saveShowcaseConfig({ selectedAppIds: newAppIds, selectedBadgeIds: cfg.selectedBadgeIds || [] }); renderShowcaseTab(parent); prepareShowcaseTabData(parent); }); }); } const editBadgeBtn = parent.querySelector('#sglv-sc-edit-badges'); if (editBadgeBtn) { editBadgeBtn.addEventListener('click', () => { _openBadgePicker(allBadges, selectedBadges, (newBadgeIds) => { const cfg = _loadShowcaseConfig(); _saveShowcaseConfig({ selectedAppIds: cfg.selectedAppIds || [], selectedBadgeIds: newBadgeIds }); renderShowcaseTab(parent); prepareShowcaseTabData(parent); }); }); } parent.querySelectorAll('.sglv-sc-hero-badge[data-badge-url]').forEach(item => { item.addEventListener('click', () => { const url = item.dataset.badgeUrl; if (url) window.open(url, '_blank'); }); }); parent.querySelectorAll('.sglv-sc-hero-badge-empty').forEach(item => { item.addEventListener('click', () => { _openBadgePicker(allBadges, selectedBadges, (newBadgeIds) => { const cfg = _loadShowcaseConfig(); _saveShowcaseConfig({ selectedAppIds: cfg.selectedAppIds || [], selectedBadgeIds: newBadgeIds }); renderShowcaseTab(parent); prepareShowcaseTabData(parent); }); }); }); parent.querySelectorAll('.sglv-sc-cover-item[data-appid]').forEach(item => { item.addEventListener('click', () => { const appid = parseInt(item.dataset.appid, 10); if (appid) window.open(`https://store.steampowered.com/app/${appid}`, '_blank'); }); }); } function _renderShowcaseContent(parent, data, allGames) { const { profile, recentGames, badges: allBadges, achievements, stats } = data; const gameCount = stats ? stats.gameCount : allGames.length; const totalHours = stats ? stats.totalHours : Math.floor(allGames.reduce((s, g) => s + (g.playtime || 0), 0) / 60); const achs = achievements || computeMyAchievementsCached(); const unlockedAchs = achs.filter(a => a.unlocked); const achCount = unlockedAchs.length; const totalAchPts = unlockedAchs.reduce((s, a) => s + a.pts, 0); const steamBadgeCount = (stats && stats.steamBadgeCount) || (allBadges && allBadges.length) || profile.badgeCount || 0; const coverAppIds = _getShowcaseCoverAppIds(allGames); const gameMap = new Map(allGames.map(g => [g.appid, g])); const recentGamesDisplay = (recentGames || []).slice(0, 6); const maxRecentPlaytime = recentGamesDisplay.length > 0 ? Math.max(...recentGamesDisplay.map(g => g.playtime_forever || 0)) : 0; const recentAchs = unlockedAchs .filter(a => a.unlockedAt) .sort((a, b) => b.unlockedAt - a.unlockedAt) .slice(0, 6); const unlockedCats = new Set(unlockedAchs.map(a => a.cat)); const selectedBadges = _getSelectedShowcaseBadges(allBadges); const html = `
${_showcaseHeroHtml(profile, gameCount, totalHours, steamBadgeCount, totalAchPts, allBadges, selectedBadges)}
${_showcaseCoverCardHtml(coverAppIds, gameMap)} ${_showcasePlaytimeCardHtml(recentGamesDisplay, maxRecentPlaytime)}
${_showcaseAchCardHtml(recentAchs)} ${_showcaseTagCardHtml(unlockedCats)}
`; parent.innerHTML = html; _bindShowcaseEvents(parent, allGames, allBadges, coverAppIds, selectedBadges); } function _openCoverPicker(allGames, currentSelected, onSave) { const candidates = allGames .filter(g => (g.playtime || 0) > 0) .sort((a, b) => (b.playtime || 0) - (a.playtime || 0)) .slice(0, 120); openPickerModal({ overlayId: 'sglv-sc-picker-overlay', idBase: 'sglv-sc-picker', title: isZh ? '选择展柜封面(最多 8 张)' : 'Select Showcase Covers (max 8)', searchPlaceholder: isZh ? '搜索游戏…' : 'Search games…', searchAria: isZh ? '搜索游戏' : 'Search games', gridCls: 'sglv-sc-picker-grid', countInit: currentSelected.length, maxSelect: 8, saveText: isZh ? '保存' : 'Save', currentSelected, getItems: (searchVal) => { const filterLower = (searchVal || '').toLowerCase().trim(); return filterLower ? candidates.filter(g => (g.name || '').toLowerCase().includes(filterLower) || String(g.appid).includes(filterLower)) : candidates; }, itemKey: g => g.appid, renderItem: (g, isSelected) => { const hours = Math.floor((g.playtime || 0) / 60); return `
${escHtml(g.name)}
✓
${escHtml(g.name)} (${hours}h)
`; }, itemSelector: '.sglv-sc-picker-item', keyFromItem: el => parseInt(el.dataset.appid, 10), onGridRendered: (grid) => { grid.querySelectorAll('img[data-cover-appid]').forEach(img => { const appid = parseInt(img.dataset.coverAppid, 10); if (appid) _applyCoverChain(img, appid); }); }, buildResult: selected => Array.from(selected), maxWarningText: isZh ? '最多选择 8 张封面' : 'Max 8 covers', savedToastText: isZh ? '展柜封面已更新' : 'Showcase covers updated', onSave, }); } const TAB_RENDERERS = { owned: { render: renderOwnedTab, needsOwned: true, prepare: prepareOwnedTabData }, showcase: { render: renderShowcaseTab, needsOwned: true, prepare: prepareShowcaseTabData }, playtime: { render: renderPlaytimeTab, needsOwned: true }, trend: { render: renderTrendTab, needsOwned: true }, playdata: { render: renderPlaydataTab, needsOwned: true }, achievements: { render: renderMyAchievementsTab, needsOwned: true }, cloudsave: { render: renderCloudSaveTab, prepare: prepareCloudSaveTabData }, wishlist: { render: renderWishlistTab }, }; function renderBody() { const body = panelEl.querySelector('#sglv-body'); if (!body) { console.warn('[SGLV] #sglv-body 未找到,跳过渲染'); return; } body.innerHTML = ''; try { const _setBtn = panelEl.querySelector('.sglv-settings-btn'); if (_setBtn) _setBtn.classList.toggle('sglv-active', !!state.showSettings); if (state.showSettings) { renderSettingsView(body); return; } const spec = TAB_RENDERERS[state.activeTab]; if (spec && spec.needsOwned && state.ownedGames.length === 0) { body.appendChild(_buildOwnedEmptyPlaceholder()); return; } if (spec) { spec.render(body); if (spec.prepare) spec.prepare(body); } else { console.warn('[SGLV] 未知标签页,跳过渲染:', state.activeTab); } } catch (e) { console.error('[SGLV] renderBody 渲染失败:', e); body.innerHTML = `
` + `

${isZh ? '渲染失败' : 'Render failed'}

` + `

${(e.message || String(e)).replace(/` + `

${isZh ? '请尝试切换其他标签页或刷新页面' : 'Try switching tabs or refresh the page'}

` + `
`; } } function _buildOwnedEmptyPlaceholder() { const wrap = document.createElement('div'); wrap.className = 'sglv-body-loading'; const hasKey = !!storage.getApiKey(); const fetching = !!state.isLoading; if (fetching) { wrap.innerHTML = `
${isZh ? '正在获取你的游戏库…' : 'Fetching your library…'}
${isZh ? '首次访问需要从 Steam 拉取库存与时长,请稍候片刻。' : 'First-time load: fetching library and playtime from Steam. Please wait.'}
`; } else { wrap.innerHTML = `
🎮
${isZh ? '游戏库尚未获取' : 'Library not loaded yet'}
${isZh ? '点击下方按钮从 Steam 拉取你的库存与游戏时长(' + (hasKey ? '已配置 API Key' : '未配置 API Key,将自动尝试无 Key 抓取') + ')。' : 'Click below to fetch your library & playtime from Steam (' + (hasKey ? 'API Key configured' : 'no API Key, fallback scraping') + ').'}
`; wrap.querySelector('[data-act="fetch"]').addEventListener('click', () => { wrap.innerHTML = `
${isZh ? '正在获取你的游戏库…' : 'Fetching your library…'}
${isZh ? '请稍候片刻。' : 'Please wait a moment.'}
`; startFetch(true); }); wrap.querySelector('[data-act="settings"]').addEventListener('click', () => { openGlobalSettings(); }); } return wrap; } function getFamilyOtherMembers(allGames, steamId) { const hasOwnerData = steamId && allGames.some(g => g.owners && g.owners.length > 0); if (!(storage.getShowFamilyShared() && hasOwnerData && steamId)) return []; const nameMap = storage.getFamilyInfo()?.steamIdtoName || {}; return Object.entries(nameMap) .filter(([sid]) => sid !== steamId) .map(([sid, name]) => ({ steamid: sid, name })); } function _trendKpiCardsHtml(yearlyStats, personalTotal, totalGames, allGames) { const now = new Date(); const thisYear = now.getFullYear(); const yearCount = yearlyStats.years.length; const thisYearIdx = yearlyStats.years.indexOf(thisYear); const thisYearCount = thisYearIdx >= 0 ? yearlyStats.counts[thisYearIdx] : 0; const avgPerYear = yearCount > 0 ? Math.round(yearlyStats.total / yearCount) : 0; const peakYearIdx = yearlyStats.counts.indexOf(Math.max(...yearlyStats.counts)); const peakYear = yearlyStats.years[peakYearIdx] || '-'; const peakYearCount = yearlyStats.counts[peakYearIdx] || 0; const nowTs = Math.floor(now.getTime() / 1000); const days30 = nowTs - 30 * 86400; const days90 = nowTs - 90 * 86400; let recent30 = 0, recent90 = 0; allGames.forEach(g => { const t = g.acquiredTime || 0; if (t <= 0) return; if (t >= days30) recent30++; if (t >= days90) recent90++; }); const activeDateSet = new Set(); allGames.forEach(g => { const t = g.acquiredTime || 0; if (t <= 0) return; const d = new Date(t * 1000); activeDateSet.add(d.getFullYear() + '-' + d.getMonth() + '-' + d.getDate()); }); const activeDays = activeDateSet.size; const firstYear = yearlyStats.years[0] || '-'; const lastYear = yearlyStats.years[yearlyStats.years.length - 1] || '-'; const kpiRow1 = kpiCards([ { icon: ICONS.library, label: isZh ? '我的游戏' : 'My Games', value: personalTotal.toLocaleString(), sub: T.kpiMyCollection, color: 'mine' }, { icon: ICONS.share, label: isZh ? '家庭组合并' : 'Family Total', value: totalGames.toLocaleString(), sub: T.kpiDedupMerge, color: 'total' }, { icon: ICONS.calendar, label: T.trendKpiThisYear, value: thisYearCount, unit: T.trendKpiGames, sub: thisYear, color: 'blue' }, { icon: ICONS.calendar, label: isZh ? '年份范围' : 'Year Range', value: `${firstYear} ~ ${lastYear}`, sub: `${lastYear - firstYear + 1} ${T.kpiYearSpan}`, color: 'gray' }, ], { tone: 'trend' }); const kpiRow2 = kpiCards([ { icon: ICONS.trend, label: T.trendKpiAvgYear, value: avgPerYear, unit: T.trendKpiGames, sub: isZh ? '年均入库量' : 'per year', color: 'green' }, { icon: ICONS.trend, label: T.trendKpiPeakYear, value: peakYear, sub: `${peakYearCount} ${T.trendKpiGames}`, color: 'orange' }, { icon: ICONS.clock, label: T.trendKpiRecent30, value: recent30, unit: T.trendKpiGames, sub: `${recent90} ${isZh ? '近90天' : '/ 90d'}`, color: 'cyan' }, { icon: ICONS.clock, label: T.trendKpiActiveDays, value: activeDays, unit: isZh ? '天' : 'days', sub: isZh ? `日均 ${activeDays > 0 ? (totalGames / activeDays).toFixed(1) : '0'} 款` : `${activeDays > 0 ? (totalGames / activeDays).toFixed(1) : '0'} / day`, color: 'purple' }, ], { tone: 'trend' }); return `
${kpiRow1}
${kpiRow2}
`; } function renderTrendTab(parent) { const wrap = document.createElement('div'); wrap.className = 'sglv-trend-wrap'; if (state.ownedGames.length === 0) { wrap.innerHTML = emptyHtml(T.noData); parent.appendChild(wrap); return; } const hasAcquiredTime = state.ownedGames.some(g => g.acquiredTime > 0); const isEstimated = !hasAcquiredTime; const allGames = state.ownedGames; const totalGames = allGames.length; const steamId = getActiveSteamId(); let personalGames = []; if (steamId) { personalGames = allGames.filter(g => { const owners = g.owners || []; return owners.length === 0 || owners.includes(steamId); }); } else { personalGames = allGames; } const personalTotal = personalGames.length; const hasOwnerData = steamId && allGames.some(g => g.owners && g.owners.length > 0); const otherMembers = getFamilyOtherMembers(allGames, steamId); const _yearlyAll = computeYearlyStatsAllCached(allGames, steamId, otherMembers); const yearlyStats = _yearlyAll.yearly; const personalYearlyStats = _yearlyAll.personal; const familyCumStats = _yearlyAll.familyCum; const familyYearlyStats = _yearlyAll.familyYearly; const kpiSection = document.createElement('div'); kpiSection.className = 'sglv-trend-kpi-wrap'; kpiSection.innerHTML = _trendKpiCardsHtml(yearlyStats, personalTotal, totalGames, allGames); const splitRow = document.createElement('div'); splitRow.className = 'sglv-trend-split'; const leftCol = document.createElement('div'); leftCol.className = 'sglv-trend-split-left'; leftCol.appendChild(kpiSection); leftCol.insertAdjacentHTML('beforeend', `
${ICONS.trend} ${T.trendChartTitle}
`); splitRow.appendChild(leftCol); const rightCol = document.createElement('div'); rightCol.className = 'sglv-trend-split-right'; rightCol.innerHTML = `
-${T.trendTimelineTotal}
${emptyHtml(T.ptHeatmapLoading)}
`; splitRow.appendChild(rightCol); wrap.appendChild(splitRow); requestAnimationFrame(() => renderTrendChart(yearlyStats, leftCol.querySelector('#sglv-trend-chart-main'), { isEstimated, familyCumStats, personalYearlyStats, familyYearlyStats, hasOwnerData })); renderAcquiredTimeline(rightCol, allGames); const freqLoaded = { done: false }; rightCol.querySelectorAll('.sglv-trend-right-tab').forEach(tab => { tab.addEventListener('click', () => { rightCol.querySelectorAll('.sglv-trend-right-tab').forEach(t => t.classList.remove('active')); tab.classList.add('active'); const target = tab.dataset.tab; rightCol.querySelector('#sglv-trend-right-timeline').style.display = target === 'timeline' ? '' : 'none'; rightCol.querySelector('#sglv-trend-right-frequency').style.display = target === 'frequency' ? '' : 'none'; if (target === 'frequency' && !freqLoaded.done) { freqLoaded.done = true; renderFrequencyAnalysis(rightCol.querySelector('#sglv-trend-freq-content'), rightCol.querySelector('#sglv-trend-freq-loading'), allGames); } }); }); if (isEstimated) { const note = document.createElement('div'); note.className = 'sglv-trend-note'; note.innerHTML = `${isZh ? '提示:当前数据缺少精确入库时间,趋势图基于“最近游玩时间”估算。登录 Steam 商店或获取家庭组数据后可获得更精确结果。' : 'Note: Precise acquisition time is unavailable; trend is estimated from last-played time.'}`; wrap.appendChild(note); } parent.appendChild(wrap); } let _freqStatsCache = null; function computeFreqStats(games) { const sig = games.length + '|' + (games[0]?.appid || 0); if (_freqStatsCache && _freqStatsCache.sig === sig) return _freqStatsCache.stats; const monthData = new Array(12).fill(0); const weekdayData = new Array(7).fill(0); const hourData = new Array(24).fill(0); const dateMap = {}; let total = 0; for (const g of games) { const t = g.acquiredTime || 0; if (t <= 0) continue; const d = new Date(t * 1000); monthData[d.getMonth()]++; weekdayData[d.getDay()]++; hourData[d.getHours()]++; const dk = d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0'); dateMap[dk] = (dateMap[dk] || 0) + 1; total++; } const sortedDates = Object.keys(dateMap).sort(); let maxStreak = 0, curStreak = 0; let prevDate = null; for (const ds of sortedDates) { if (prevDate) { const diff = (new Date(ds) - new Date(prevDate)) / 86400000; curStreak = diff === 1 ? curStreak + 1 : 1; } else { curStreak = 1; } if (curStreak > maxStreak) maxStreak = curStreak; prevDate = ds; } const monthNames = isZh ? ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月'] : ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']; const weekdayNames = T.trendFreqWeekdayLong.split(','); const peakMonth = monthNames[monthData.indexOf(Math.max(...monthData))] || '-'; const peakWeekday = weekdayNames[weekdayData.indexOf(Math.max(...weekdayData))] || '-'; const peakHour = hourData.indexOf(Math.max(...hourData)); const peakHourLabel = peakHour >= 0 ? String(peakHour).padStart(2, '0') + ':00 ~ ' + String((peakHour + 1) % 24).padStart(2, '0') + ':00' : '-'; const stats = { monthData, weekdayData, hourData, total, maxStreak, peakMonth, peakWeekday, peakHourLabel, peakMonthCount: Math.max(...monthData), peakWeekdayCount: Math.max(...weekdayData), peakHourCount: Math.max(...hourData), monthNames, weekdayNames, uniqueDays: sortedDates.length, }; _freqStatsCache = { sig, stats, ts: Date.now() }; return stats; } function renderFrequencyAnalysis(contentEl, loadingEl, games) { (async () => { try { const { map: acquiredMap } = await buildCalibratedAcquiredMap(); const enriched = games.map(g => ({ ...g, acquiredTime: acquiredMap[g.appid] || g.acquiredTime || 0, })); const stats = computeFreqStats(enriched); const wdNames = stats.weekdayNames; const monthMax = Math.max(...stats.monthData, 1); const monthBars = stats.monthData.map((v, i) => { const h = v > 0 ? Math.max(2, (v / monthMax) * 100) : 0; const x = i * (100 / 12) + 1; const isPeak = v === stats.peakMonthCount && v > 0; return ``; }).join(''); const wdMax = Math.max(...stats.weekdayData, 1); const wdBars = stats.weekdayData.map((v, i) => { const h = v > 0 ? Math.max(2, (v / wdMax) * 100) : 0; const x = i * (100 / 7) + 1; const isPeak = v === stats.peakWeekdayCount && v > 0; return ``; }).join(''); const hrMax = Math.max(...stats.hourData, 1); const hrBars = stats.hourData.map((v, i) => { const h = v > 0 ? Math.max(2, (v / hrMax) * 100) : 0; const x = i * (100 / 24) + 0.3; const isPeak = v === stats.peakHourCount && v > 0; return ``; }).join(''); contentEl.innerHTML = `
${T.trendFreqPeakMonth}${stats.peakMonth}${stats.peakMonthCount} ${T.trendKpiGames}
${T.trendFreqPeakWeekday}${stats.peakWeekday}${stats.peakWeekdayCount} ${T.trendKpiGames}
${T.trendFreqPeakHour}${stats.peakHourLabel}${stats.peakHourCount} ${T.trendKpiGames}
${T.trendFreqStreak}${stats.maxStreak}${T.trendFreqDays}
${T.trendFreqByMonth}
${monthBars}
${stats.monthNames.map(m => `${m}`).join('')}
${T.trendFreqByWeekday}
${wdBars}
${wdNames.map(w => `${w}`).join('')}
${T.trendFreqByHour}
${hrBars}
${[0,3,6,9,12,15,18,21].map(h => `${String(h).padStart(2,'0')}`).join('')}
`; loadingEl.style.display = 'none'; contentEl.style.display = ''; const freqTooltip = document.createElement('div'); freqTooltip.className = 'sglv-freq-tooltip'; freqTooltip.style.cssText = 'position:fixed;background:rgba(15,23,42,0.96);border:1px solid rgba(102,192,244,0.3);border-radius:6px;padding:4px 10px;font-size:11px;color:#fff;pointer-events:none;z-index:999;display:none;transform:translateX(-50%);'; document.body.appendChild(freqTooltip); addDisposer(() => freqTooltip.remove()); contentEl.querySelectorAll('.sglv-freq-chart svg rect[data-v]').forEach(rect => { rect.addEventListener('mouseenter', function() { const v = this.getAttribute('data-v'); const l = this.getAttribute('data-l'); this.setAttribute('opacity', '0.7'); freqTooltip.textContent = `${l}: ${v} ${T.trendKpiGames}`; const r = this.getBoundingClientRect(); freqTooltip.style.left = (r.left + r.width / 2) + 'px'; freqTooltip.style.top = (r.top - 28) + 'px'; freqTooltip.style.display = ''; }); rect.addEventListener('mouseleave', function() { this.setAttribute('opacity', '1'); freqTooltip.style.display = 'none'; }); }); } catch (e) { console.warn('[SGLV] 频率分析加载失败:', e); loadingEl.innerHTML = emptyHtml(T.ptHeatmapNoData); } })(); } function renderAcquiredTimeline(container, games) { const scrollEl = container.querySelector('#sglv-tl-scroll'); const countEl = container.querySelector('#sglv-tl-count'); const searchEl = container.querySelector('#sglv-tl-search'); const pagiEl = container.querySelector('#sglv-tl-pagination'); if (!scrollEl || !countEl || !searchEl || !pagiEl) return; const PAGE_SIZE = 20; let allItems = null; let page = 1; let query = ''; const fmtDateKey = (ts) => { const d = new Date(ts * 1000); return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0'); }; const timeOfDay = (ts) => { const d = new Date(ts * 1000); return String(d.getHours()).padStart(2, '0') + ':' + String(d.getMinutes()).padStart(2, '0') + ':' + String(d.getSeconds()).padStart(2, '0'); }; function renderList() { if (!allItems) { scrollEl.innerHTML = createLoadingHtml(T.ptHeatmapLoading, 28); return; } const items = query ? allItems.filter(it => it.name.toLowerCase().includes(query)) : allItems; countEl.textContent = items.length; if (items.length === 0) { scrollEl.innerHTML = emptyHtml(T.ptHeatmapNoData); pagiEl.innerHTML = ''; return; } const pg = paginate(items, page, PAGE_SIZE); page = pg.page; let curDate = null; scrollEl.innerHTML = renderGameView(pg.pageItems, { viewMode: 'card', gridCls: 'sglv-tl-grid', cardCls: 'sglv-tl-card', bodyCls: 'sglv-tl-card-info', bareImg: true, itemAttrs: (it) => ` onclick="window.open('https://store.steampowered.com/app/${it.appid}','_blank')"`, itemPrefixHtml: (it) => { if (it.dateKey === curDate) return ''; curDate = it.dateKey; return `
${curDate}
`; }, imgHtml: (it) => headerImg(it.appid, it.name), bodyHtml: (it) => `
${it.name}
${timeOfDay(it.ts)}✓
`, }); applyGameAliases(scrollEl); renderPagination(pagiEl, 'sglv-tl', page, pg.totalPages, items.length, () => { page--; renderList(); }, () => { page++; renderList(); }, (p) => { page = p; renderList(); }); } searchEl.addEventListener('input', debounce(() => { query = searchEl.value.trim().toLowerCase(); page = 1; renderList(); }, 200)); renderList(); (async () => { try { const { games: familyGames, map: acquiredMap } = await buildCalibratedAcquiredMap(); if (!familyGames || familyGames.length === 0) { allItems = []; renderList(); return; } allItems = games .filter(g => acquiredMap[g.appid]) .map(g => ({ appid: g.appid, name: g.name || `App ${g.appid}`, ts: acquiredMap[g.appid], dateKey: fmtDateKey(acquiredMap[g.appid]) })) .sort((a, b) => b.ts - a.ts); } catch (e) { console.warn('[SGLV] 入库时间线加载失败:', e); allItems = []; } renderList(); })(); } function computeYearlyStats(games) { const map = new Map(); let total = 0; let maxCount = 0; games.forEach(g => { const t = g.acquiredTime || g.lastPlayed || 0; if (t <= 0) return; const year = new Date(t * 1000).getFullYear(); const c = (map.get(year) || 0) + 1; map.set(year, c); total++; if (c > maxCount) maxCount = c; }); if (map.size === 0) return { years: [], counts: [], cumulative: [], total: 0, maxCount: 0, maxCumulative: 0 }; const minYear = Math.min(...map.keys()); const maxYear = Math.max(...map.keys()); const years = []; const counts = []; const cumulative = []; let cum = 0; for (let y = minYear; y <= maxYear; y++) { const c = map.get(y) || 0; cum += c; years.push(y); counts.push(c); cumulative.push(cum); } return { years, counts, cumulative, total, maxCount, maxCumulative: cum }; } function computePersonalYearlyStats(games, steamId, refYears) { const map = new Map(); let total = 0; let maxCount = 0; games.forEach(g => { const owners = g.owners || []; if (owners.length > 0 && !owners.includes(steamId)) return; const t = g.acquiredTime || g.lastPlayed || 0; if (t <= 0) return; const year = new Date(t * 1000).getFullYear(); const c = (map.get(year) || 0) + 1; map.set(year, c); total++; if (c > maxCount) maxCount = c; }); if (map.size === 0) return { years: [], counts: [], cumulative: [], total: 0, maxCount: 0, maxCumulative: 0 }; const years = refYears ? [...refYears] : Array.from(map.keys()).sort((a, b) => a - b); const counts = []; const cumulative = []; let cum = 0; for (const y of years) { const c = map.get(y) || 0; cum += c; counts.push(c); cumulative.push(cum); } return { years, counts, cumulative, total, maxCount, maxCumulative: cum }; } function computeFamilyMemberCumulativeStats(games, members, years) { if (!years || years.length === 0 || members.length === 0) return null; const yearlyMemberCounts = new Map(); const memberIds = new Set(members.map(m => m.steamid)); years.forEach(y => { yearlyMemberCounts.set(y, {}); }); games.forEach(g => { const t = g.acquiredTime || g.lastPlayed || 0; if (t <= 0) return; const owners = g.owners || []; if (owners.length === 0) return; const year = new Date(t * 1000).getFullYear(); const entry = yearlyMemberCounts.get(year); if (!entry) return; owners.forEach(sid => { if (memberIds.has(sid)) { entry[sid] = (entry[sid] || 0) + 1; } }); }); const resultMembers = members.map(m => { let cum = 0; const cumulative = years.map(y => { const entry = yearlyMemberCounts.get(y); cum += (entry ? (entry[m.steamid] || 0) : 0); return cum; }); return { steamid: m.steamid, name: m.name, cumulative }; }); const maxCumulative = Math.max(...resultMembers.map(m => m.cumulative[m.cumulative.length - 1]), 1); return { years, members: resultMembers, maxCumulative }; } function computeFamilyYearlyStats(games, members) { const yearsSet = new Set(); const memberMap = new Map(); members.forEach(m => memberMap.set(m.steamid, { name: m.name, counts: new Map() })); games.forEach(g => { const t = g.acquiredTime || g.lastPlayed || 0; if (t <= 0) return; const year = new Date(t * 1000).getFullYear(); const owners = g.owners || []; members.forEach(m => { if (owners.includes(m.steamid)) { yearsSet.add(year); const counts = memberMap.get(m.steamid).counts; counts.set(year, (counts.get(year) || 0) + 1); } }); }); const years = Array.from(yearsSet).sort((a, b) => a - b); if (years.length === 0) return { years: [], members: [] }; const colors = ['#06cfbe', '#54a0ff', '#ff9f43', '#2ed573', '#ff6b6b', '#a29bfe', '#ffcd56']; const result = []; members.forEach((m, i) => { const data = memberMap.get(m.steamid); const counts = []; years.forEach(y => counts.push(data.counts.get(y) || 0)); result.push({ steamid: m.steamid, name: m.name, counts, color: colors[i % colors.length] }); }); return { years, members: result }; } const _BIZ_SCHEMA_YEARLY = 1; const _BIZ_SCHEMA_INSIGHT = 1; const _BIZ_SCHEMA_ACHIEVEMENTS = 1; function _bizInputSig(games, extra) { let accSum = 0, lpSum = 0, ptSum = 0; const n = games ? games.length : 0; for (let i = 0; i < n; i++) { const g = games[i]; accSum += (g && g.acquiredTime) || 0; lpSum += (g && g.lastPlayed) || 0; ptSum += (g && g.playtime) || 0; } return `${n}|${accSum}|${lpSum}|${ptSum}|${extra || ''}`; } function computeYearlyStatsAllCached(games, steamId, otherMembers) { const sig = _bizInputSig(games, `${steamId || ''}|${otherMembers ? otherMembers.length : 0}`); return getBizCached('biz_yearly_stats_all', _BIZ_SCHEMA_YEARLY, sig, () => { const yearly = computeYearlyStats(games); const personal = steamId ? computePersonalYearlyStats(games, steamId, yearly.years) : null; let familyCum = null; let familyYearly = null; if (otherMembers && otherMembers.length > 0 && yearly.years.length > 0) { familyCum = computeFamilyMemberCumulativeStats(games, otherMembers, yearly.years); familyYearly = computeFamilyYearlyStats(games, otherMembers); } return { yearly, personal, familyCum, familyYearly }; }); } function computeMyAchievementsCached() { const allGames = getStatFilteredGames(); const dlcReady = (SGLV_API.isDlcDbReady && SGLV_API.isDlcDbReady()) ? '1' : '0'; const sig = _bizInputSig(allGames, `myAch|${dlcReady}`); return getBizCached('biz_my_achievements', _BIZ_SCHEMA_ACHIEVEMENTS, sig, () => { return computeMyAchievements(); }); } function _computeInsightDataFull() { const allGames = getStatFilteredGames(); const gameCount = allGames.length; const totalPlaytimeMin = allGames.reduce((s, g) => s + (g.playtime || 0), 0); const totalHours = Math.floor(totalPlaytimeMin / 60); const playedGames = allGames.filter(g => (g.playtime || 0) > 0); const playedCount = playedGames.length; const unplayedCount = Math.max(0, gameCount - playedCount); const avgHours = playedCount > 0 ? Math.round(totalHours / playedCount) : 0; const over100hCount = allGames.filter(g => (g.playtime || 0) >= 6000).length; const over500hCount = allGames.filter(g => (g.playtime || 0) >= 30000).length; const dustRate = gameCount > 0 ? unplayedCount / gameCount : 0; const longGamesCount = allGames.filter(g => (g.playtime || 0) >= 600).length; const completionRate = playedCount > 0 ? Math.round((longGamesCount / playedCount) * 100) : 0; const topGames = allGames.filter(g => (g.playtime || 0) > 0) .sort((a, b) => (b.playtime || 0) - (a.playtime || 0)) .slice(0, 10) .map(g => ({ name: g.name, hours: Math.floor((g.playtime || 0) / 60) })); const recentGames = allGames.filter(g => g.lastPlayed && g.lastPlayed > 0) .sort((a, b) => (b.lastPlayed || 0) - (a.lastPlayed || 0)) .slice(0, 5) .map(g => ({ name: g.name, hours: Math.floor((g.playtime || 0) / 60), lastPlayed: g.lastPlayed })); const dustCollectors = allGames.filter(g => !g.playtime || g.playtime === 0) .slice(0, 5) .map(g => g.name); const breadthScore = Math.min(100, Math.round((gameCount / 300) * 100)); const depthScore = Math.min(100, Math.round((totalHours / 5000) * 100)); const completionScore = completionRate; let diversityScore = 0; if (playedCount > 0 && totalPlaytimeMin > 0) { const shares = playedGames.map(g => (g.playtime || 0) / totalPlaytimeMin); const hhi = shares.reduce((s, x) => s + x * x, 0); diversityScore = Math.round((1 - hhi) * 100 * Math.min(1, playedCount / 10)); diversityScore = Math.max(0, Math.min(100, diversityScore)); } const activityScore = Math.round((1 - dustRate) * 100); const dimensions = [ { label: '收藏广度', score: breadthScore, tag: breadthScore >= 80 ? '收藏大家' : breadthScore >= 60 ? '中量收藏' : breadthScore >= 40 ? '稳步积累' : '初入Steam', gradient: 'linear-gradient(135deg, #3b82f6, #06cfbe)', desc: `${gameCount} 款游戏 · ${over100hCount} 款超 100h · ${over500hCount} 款超 500h` }, { label: '沉浸深度', score: depthScore, tag: depthScore >= 80 ? '硬核玩家' : depthScore >= 60 ? '资深玩家' : depthScore >= 40 ? '入门玩家' : '体验为主', gradient: 'linear-gradient(135deg, #06cfbe, #22d3ee)', desc: `总时长 ${totalHours}h · 平均 ${avgHours}h/款 · 最长 ${topGames[0]?.hours || 0}h (${topGames[0]?.name || '—'})` }, { label: '完成度', score: completionScore, tag: completionScore >= 80 ? '深度游玩' : completionScore >= 60 ? '认真体验' : completionScore >= 40 ? '浅尝辄止' : '走马观花', gradient: SGLVCharts.accentGradient(), desc: `${playedCount}/${gameCount} 已启动 · ${longGamesCount} 款深度游玩(≥10h) · 完成率 ${completionRate}%` }, { label: '偏好多样性', score: diversityScore, tag: diversityScore >= 80 ? '涉猎广泛' : diversityScore >= 60 ? '多元尝试' : diversityScore >= 40 ? '有所偏好' : '专一玩家', gradient: 'linear-gradient(135deg, #f43f5e, #fb7185)', desc: `时长分布集中度 ${diversityScore}% 分散 · Top1 占比 ${topGames[0] && totalHours > 0 ? Math.round((topGames[0].hours / totalHours) * 100) : 0}%` }, { label: '活跃度', score: activityScore, tag: activityScore >= 80 ? '活跃高玩' : activityScore >= 60 ? '稳定玩家' : activityScore >= 40 ? '间歇游玩' : '吃灰严重', gradient: 'linear-gradient(135deg, #f59e0b, #fbbf24)', desc: `吃灰率 ${(dustRate * 100).toFixed(1)}% · ${unplayedCount} 款未启动 · ${dustCollectors.length ? '如: ' + dustCollectors.slice(0, 2).join('、') : '无'}` }, ]; let personaType = '均衡型玩家'; let personaRarity = '常见'; let personaTagline = '游戏风格均衡, 各维度发展稳定'; let personaTraits = []; const maxDim = dimensions.reduce((a, b) => a.score >= b.score ? a : b); if (breadthScore >= 75 && depthScore < 50) { personaType = '收藏型玩家'; personaRarity = '稀有'; personaTagline = '热衷扩充库藏, 拥有海量游戏但未必全部深入'; personaTraits = ['数字收藏家', '促销猎手', 'FOMO 型消费', '广度优先']; } else if (depthScore >= 75 && breadthScore < 60) { personaType = '硬核型玩家'; personaRarity = '史诗'; personaTagline = '少量游戏投入海量时长, 追求深度体验与精通'; personaTraits = ['深度沉浸', '反复游玩', '成就猎人', '精通导向']; } else if (activityScore < 40 && breadthScore >= 60) { personaType = '吃灰型玩家'; personaRarity = '常见'; personaTagline = '库藏丰富但启动率低, 大量游戏长期未触碰'; personaTraits = ['仓鼠症', '冲动消费', '收藏 > 游玩', '潜力待发掘']; } else if (diversityScore >= 70 && completionScore >= 60) { personaType = '探索型玩家'; personaRarity = '稀有'; personaTagline = '涉猎广泛且认真体验, 各类游戏均有深度游玩'; personaTraits = ['多元品味', '开放尝试', '均衡发展', '好奇心强']; } else if (completionScore >= 75) { personaType = '完成型玩家'; personaRarity = '史诗'; personaTagline = '注重游戏完成度, 倾向深度通关而非广度收集'; personaTraits = ['完美主义', '通关导向', '深度体验', '宁缺毋滥']; } else if (breadthScore >= 60 && depthScore >= 60) { personaType = '全能型玩家'; personaRarity = '传说'; personaTagline = '收藏与深度兼备, 游戏库既广且深'; personaTraits = ['收藏 + 深度', '资深 Steam 用户', '多元 + 专注', '高活跃']; } return { kpi: { gameCount, totalHours, playedCount, unplayedCount, avgHours, over100hCount, over500hCount, dustRate, longGamesCount, completionRate }, topGames, recentGames, dustCollectors, dimensions, persona: { type: personaType, rarity: personaRarity, tagline: personaTagline, traits: personaTraits, dominantDim: maxDim.label }, }; } function computeInsightDataCachedSgis() { const allGames = getStatFilteredGames(); const dlcReady = (SGLV_API.isDlcDbReady && SGLV_API.isDlcDbReady()) ? '1' : '0'; const sig = _bizInputSig(allGames, `sgis_insight|${dlcReady}`); return getBizCached('biz_sgis_insight_data', _BIZ_SCHEMA_INSIGHT, sig, () => _computeInsightDataFull()); } function createTrendTooltip(chartEl) { let tooltip = chartEl.querySelector('.sglv-trend-tooltip'); if (!tooltip) { tooltip = document.createElement('div'); tooltip.className = 'sglv-trend-tooltip'; chartEl.appendChild(tooltip); } return tooltip; } function bindTrendBarTooltip(container, cfg) { const { hasMemberBars, hasFamilyLines, hasPersonalLine, hasPersonalBar, familyYearlyStats, familyCumStats, memberColors } = cfg; const tooltip = createTrendTooltip(container); container.querySelectorAll('.sglv-trend-bar').forEach(bar => { bar.addEventListener('mouseenter', () => { const year = bar.dataset.year; const count = bar.dataset.count; const cum = bar.dataset.cum; const membersStr = bar.dataset.members || ''; const memberBarsStr = bar.dataset.memberBars || ''; const rect = bar.getBoundingClientRect(); const chartRect = container.getBoundingClientRect(); let memberBarRows = ''; if (memberBarsStr && hasMemberBars) { memberBarsStr.split('|').forEach(pair => { const [name, val] = pair.split(':'); if (!name) return; const m = familyYearlyStats.members.find(mm => mm.name === name); const color = m ? m.color : '#888'; const num = parseInt(val, 10) || 0; memberBarRows += `
${name}${num}
`; }); } let memberRows = ''; if (membersStr && hasFamilyLines) { membersStr.split('|').forEach(pair => { const [name, val] = pair.split(':'); if (!name || !val) return; const idx = familyCumStats.members.findIndex(m => m.name === name); const color = memberColors[idx % memberColors.length]; memberRows += `
${name} (${isZh ? '累计' : 'cum.'})${val}
`; }); } let cumRows = ''; if (hasPersonalLine) { const personalCumVal = bar.dataset.personalCum || ''; cumRows += `
${isZh ? '我的累计' : 'My cum.'}${personalCumVal}
`; cumRows += `
${isZh ? '家庭组合并' : 'Family total'}${cum}
`; } else { cumRows += `
${isZh ? '累计' : 'Cumulative'}${cum}
`; } tooltip.innerHTML = `
${year}
${isZh ? (hasPersonalBar ? '我的新增' : '年度新增') : (hasPersonalBar ? 'My new' : 'New')}${count}
${memberBarRows ? `
${isZh ? '各成员新增' : 'Per member'}
${memberBarRows}` : ''} ${cumRows} ${memberRows ? `
${isZh ? '各成员累计' : 'Member cumulative'}
${memberRows}` : ''} `; tooltip.style.opacity = '1'; const left = rect.left - chartRect.left + rect.width / 2 - tooltip.offsetWidth / 2; const top = rect.top - chartRect.top - tooltip.offsetHeight - 8; tooltip.style.left = `${Math.max(0, left)}px`; tooltip.style.top = `${Math.max(0, top)}px`; }); bar.addEventListener('mouseleave', () => { tooltip.style.opacity = '0'; }); }); } function renderTrendChart(stats, container, options = {}) { if (!stats.years.length) { container.innerHTML = emptyHtml(isZh ? '无时间数据' : 'No time data'); return; } const { isEstimated = false, familyCumStats = null, personalYearlyStats = null, familyYearlyStats = null, hasOwnerData = false } = options; const hasPersonalBar = hasOwnerData && personalYearlyStats && personalYearlyStats.years.length > 0 && personalYearlyStats.cumulative.length === stats.years.length; const mainCounts = hasPersonalBar ? personalYearlyStats.counts : stats.counts; const n = stats.years.length; const gap = (800 - 52 - 62) / n; const memberColors = ['#06cfbe', '#54a0ff', '#ff9f43', '#2ed573', '#ff6b6b', '#a29bfe']; const hasMemberBars = familyYearlyStats && familyYearlyStats.years.length > 0 && familyYearlyStats.members.length > 0; const memberCount = hasMemberBars ? familyYearlyStats.members.length : 0; const groupCount = hasMemberBars ? (1 + memberCount) : 1; const groupGap = Math.max(2, gap * 0.12); const groupTotalW = Math.min(gap * 0.78, groupCount * 14 + (groupCount - 1) * groupGap); const mainBarW = hasMemberBars ? Math.max(10, groupTotalW * 0.32) : Math.min(gap * 0.55, 38); const memberBarW = hasMemberBars ? Math.max(3, (groupTotalW - mainBarW - groupGap) / memberCount) : 0; const allBarsTotalW = hasMemberBars ? (mainBarW + groupGap + memberBarW * memberCount) : mainBarW; let mainMax = Math.max(...mainCounts, 1); let memberMax = 0; if (hasMemberBars) { familyYearlyStats.members.forEach(m => { m.counts.forEach(c => { if (c > memberMax) memberMax = c; }); }); } const maxCount = Math.max(mainMax, memberMax, 1); const myMaxCumulative = stats.maxCumulative || 1; const familyMaxCum = familyCumStats?.maxCumulative || 0; const personalMaxCum = (personalYearlyStats && personalYearlyStats.years.length > 0) ? personalYearlyStats.maxCumulative : 0; const maxCumulative = Math.max(myMaxCumulative, familyMaxCum, personalMaxCum) || 1; const hasPersonalLine = personalYearlyStats && personalYearlyStats.years.length > 0 && personalYearlyStats.cumulative.length === n; const hasFamilyLines = familyCumStats && familyCumStats.members.length > 0 && familyCumStats.members.every(m => m.cumulative.length === n); const seriesDefs = []; if (hasPersonalLine) { seriesDefs.push({ data: personalYearlyStats.cumulative, stroke: '#22c55e', dots: {} }); seriesDefs.push({ data: stats.cumulative, stroke: '#818cf8', polyAttrs: 'stroke-dasharray="6,4"', dots: { fill: '#818cf8' } }); } else { seriesDefs.push({ data: stats.cumulative, stroke: '#22c55e', dots: {} }); } if (hasFamilyLines) { familyCumStats.members.forEach((m, mi) => { const color = memberColors[mi % memberColors.length]; seriesDefs.push({ data: m.cumulative, stroke: color, strokeWidth: 2, polyAttrs: 'opacity=".75"', dots: { r: 2.5, fill: color, attrs: 'opacity=".8"' } }); }); } const svg = SGLVCharts.comboChart({ n, leftMax: maxCount, rightMax: maxCumulative, bars: (i, cx) => { const year = stats.years[i]; const groupStartX = cx - allBarsTotalW / 2; const mainCount = mainCounts[i] || 0; const memberData = hasFamilyLines ? familyCumStats.members.map(m => `${m.name}:${m.cumulative[i]}`).join('|') : ''; const personalCumVal = hasPersonalLine ? personalYearlyStats.cumulative[i] : ''; const familyTotalCumVal = stats.cumulative[i]; const memberBarPairs = hasMemberBars ? familyYearlyStats.members.map(m => `${m.name}:${(familyYearlyStats.years.includes(year) ? (m.counts[familyYearlyStats.years.indexOf(year)] || 0) : 0)}`).join('|') : ''; const list = [{ v: mainCount, x: groupStartX, w: mainBarW, fill: '#3b82f6', cls: 'sglv-trend-bar', attrs: `data-year="${year}" data-count="${mainCount}" data-cum="${familyTotalCumVal}" data-members="${memberData}" data-personal-cum="${personalCumVal}" data-member-bars="${memberBarPairs}"`, }]; if (hasMemberBars) { const memberStartX = groupStartX + mainBarW + groupGap; familyYearlyStats.members.forEach((m, mi) => { if (!familyYearlyStats.years.includes(year)) return; const yearIdx = familyYearlyStats.years.indexOf(year); const c = m.counts[yearIdx] || 0; list.push({ v: c, x: memberStartX + mi * memberBarW, w: memberBarW - 0.5, fill: m.color, rx: 1.5, cls: 'sglv-trend-bar-member', opacity: '0.85', attrs: `data-year="${year}" data-count="${c}" data-member="${m.name}"`, }); }); } return list; }, series: seriesDefs, xLabel: i => stats.years[i], }); let legendItems = `
${isZh ? (hasPersonalBar ? '我的年度新增' : '年度新增') : (hasPersonalBar ? 'My new this year' : 'New this year')}
`; if (hasMemberBars) { familyYearlyStats.members.forEach((m, mi) => { legendItems += `
${m.name}
`; }); } if (hasPersonalLine) { legendItems += `
${isZh ? '我的累计' : 'My cumulative'}
`; legendItems += `
${isZh ? '家庭组合并' : 'Family total'}
`; } else { legendItems += `
${isZh ? '我的累计' : 'My cumulative'}
`; } const legend = `
${legendItems}
`; const summary = `
${isZh ? '总计' : 'Total'}: ${stats.total} ${isZh ? '年份' : 'Years'}: ${stats.years.length} ${isZh ? '最早' : 'First'}: ${stats.years[0]} ${isZh ? '最新' : 'Latest'}: ${stats.years[stats.years.length - 1]}
`; let compareSummary = ''; if (hasMemberBars && familyYearlyStats.members.length > 0) { const memberTotals = familyYearlyStats.members.map(m => ({ name: m.name, count: m.counts.reduce((s, c) => s + c, 0) })).sort((a, b) => b.count - a.count); const topM = memberTotals[0] || { name: '-', count: 0 }; const lowM = memberTotals[memberTotals.length - 1] || { name: '-', count: 0 }; const avgCnt = memberTotals.length > 0 ? Math.round(memberTotals.reduce((s, x) => s + x.count, 0) / memberTotals.length) : 0; compareSummary = `
` + `${isZh ? '贡献最多' : 'Top'}: ${topM.name} (${topM.count})` + `${isZh ? '平均' : 'Avg'}: ${avgCnt}` + `${isZh ? '贡献最少' : 'Low'}: ${lowM.name} (${lowM.count})` + `
`; } container.innerHTML = svg + legend + compareSummary + summary; if (hasMemberBars) { const memberBars = container.querySelectorAll('.sglv-trend-bar-member'); container.querySelectorAll('.sglv-trend-legend-interactive').forEach(el => { el.addEventListener('mouseenter', function() { const mi = this.dataset.mi; memberBars.forEach(bar => { bar.style.opacity = bar.dataset.member === familyYearlyStats.members[mi].name ? '1' : '.1'; }); }); el.addEventListener('mouseleave', function() { memberBars.forEach(bar => { bar.style.opacity = '0.85'; }); }); }); } bindTrendBarTooltip(container, { hasMemberBars, hasFamilyLines, hasPersonalLine, hasPersonalBar, familyYearlyStats, familyCumStats, memberColors }); } function openGlobalSettings() { if (!panelEl) return; openPanel(); state.showSettings = true; renderBody(); } function closeGlobalSettings() { if (!state.showSettings) return; state.showSettings = false; renderBody(); } function renderSettingsView(body) { const wrap = document.createElement('div'); wrap.className = 'sglv-set-wrap'; wrap.innerHTML = `
${ICONS.settings} ${T.globalSettings}
${ICONS.shield}${T.steamApiSection}
${T.apiKeyHelp}
${_hasApiKeyConsent() ? ` ` : `
🔒 ${isZh ? '尚未同意配置 API Key' : 'You have not agreed to configure an API key'}
${isZh ? 'API Key 是一枚敏感凭据。点击下方按钮先了解它的用途、数据流向与风险,确认同意后才能填写。' : 'An API key is a sensitive credential. Read how it is used, where the data goes and what the risks are before you can fill it in.'}
`}
${ICONS.trend}${T.aiSettingsTitle}
${T.aiApiUrlHelp}
${_getSharedAiConfig() ? `
🔗 ${T.aiSharedHint}
` : ''}
${T.aiModelHelp}
${ICONS.dollar}${T.aiPredictSection}
${T.aiPredictModesHelp}
${PREDICT_MODES.map(m => { const checked = storage.getPredictModes().includes(m.key); return ``; }).join('')}
${ICONS.dollar}${T.itadSection} ${storage.getItadApiKey() ? '● ' + (isZh ? '已配置' : 'Configured') : '○ ' + T.itadConnNoKey}
${T.itadDesc}
📖 ${T.itadHelpTitle}
${T.itadHelpSteps}
${ICONS.palette}${T.themeSection}
${T.themeDesc}
${ICONS.shield}${isZh ? '显示偏好' : 'Display Preferences'}
${isZh ? '控制游戏库浮窗中是否显示家庭组共享的游戏。' : 'Toggle whether family-shared games are shown in the library panel.'}
`; wrap.querySelector('.sglv-set-back').addEventListener('click', closeGlobalSettings); wrap.querySelectorAll('input[name="sglv-gs-theme"]').forEach(radio => { radio.addEventListener('change', () => { wrap.querySelectorAll('.sglv-set-theme-opt').forEach(opt => { opt.classList.toggle('selected', !!opt.querySelector('input') && opt.querySelector('input').checked); }); }); }); const apikeyUnlockBtn = wrap.querySelector('#sglv-apikey-unlock'); if (apikeyUnlockBtn) { apikeyUnlockBtn.addEventListener('click', async () => { apikeyUnlockBtn.disabled = true; const agreed = await _openApiKeyConsent(); apikeyUnlockBtn.disabled = false; if (!agreed) { showToast(isZh ? '未同意配置 API Key' : 'Consent declined'); return; } renderBody(); }); } wrap.querySelector('#sglv-gs-save').addEventListener('click', () => { const apikeyEl = wrap.querySelector('#sglv-gs-apikey'); if (apikeyEl) storage.setApiKey(apikeyEl.value.trim()); storage.setSteamId(wrap.querySelector('#sglv-gs-steamid').value.trim()); storage.setAiApiUrl(wrap.querySelector('#sglv-gs-ai-url').value.trim() || 'https://api.deepseek.com/v1/chat/completions'); storage.setAiApiKey(wrap.querySelector('#sglv-gs-ai-key').value.trim()); storage.setAiModel(wrap.querySelector('#sglv-gs-ai-model').value.trim() || 'deepseek-v4-pro'); const checkedModes = Array.from(wrap.querySelectorAll('#sglv-gs-predict-modes input[type="checkbox"]:checked')).map(cb => cb.value); storage.setPredictModes(checkedModes.length ? checkedModes : ['seasonal', 'trend', 'lowest']); storage.setShowFamilyShared(wrap.querySelector('#sglv-gs-family-toggle').checked); const themeRadio = wrap.querySelector('input[name="sglv-gs-theme"]:checked'); const newThemeId = SGLV_THEMES[themeRadio && themeRadio.value] ? themeRadio.value : DEFAULT_SGLV_THEME; const themeChanged = newThemeId !== getThemeId(); storage.setUiTheme(newThemeId); if (themeChanged) applySglvTheme(newThemeId); const itadKey = wrap.querySelector('#sglv-gs-itad-key').value.trim(); storage.setItadApiKey(itadKey); if (window.SGLVITAD) window.SGLVITAD.setApiKey(itadKey || ITAD_API_KEY_FALLBACK); _activeSteamId = null; clearComputedCache(); const status = wrap.querySelector('#sglv-gs-status'); status.textContent = '✅ ' + T.saved; setTimeout(() => { status.textContent = ''; closeGlobalSettings(); }, 800); if (_pendingFetchAfterKey) { _pendingFetchAfterKey = false; if (storage.getApiKey()) { setTimeout(() => { try { startFetch(true); } catch (e) { console.warn('[SGLV] 同意门续跑拉取失败:', e); } }, 900); } } }); const itadTestBtn = wrap.querySelector('#sglv-gs-itad-test'); if (itadTestBtn) { itadTestBtn.addEventListener('click', async () => { const keyInput = wrap.querySelector('#sglv-gs-itad-key'); const resultEl = wrap.querySelector('#sglv-gs-itad-test-result'); const testKey = keyInput.value.trim(); if (!testKey) { resultEl.innerHTML = '⚠ ' + T.itadConnFail + ': Key 为空'; return; } itadTestBtn.disabled = true; itadTestBtn.textContent = T.itadTesting; resultEl.innerHTML = '' + T.itadTesting + ''; try { const result = await _sglvItadTestConnection(testKey); if (result && result.success) { resultEl.innerHTML = '✅ ' + T.itadConnSuccess + ' · ' + (isZh ? '商店数' : 'Shops') + ': ' + result.shopCount + ''; } else { const errMsg = (result && result.error) ? String(result.error) : 'unknown error'; resultEl.innerHTML = '❌ ' + T.itadConnFail + ': ' + errMsg + ''; } } catch (e) { const errMsg = (e && e.message) ? String(e.message) : String(e || 'unknown error'); resultEl.innerHTML = '❌ ' + T.itadConnFail + ': ' + errMsg + ''; } finally { itadTestBtn.disabled = false; itadTestBtn.textContent = T.itadTestConn; } }); } body.appendChild(wrap); } const BUNDLE_DB_API_URL = 'https://bartervg.com/browse/bundles/json/'; const BUNDLE_DB_CACHE_KEY = 'sglv_bundle_db_cache'; const BUNDLE_DB_NEG_KEY = nsKey('bundle_db_neg'); const BUNDLE_DB_NEG_TTL = 30 * 60 * 1000; const BUNDLE_DB_CACHE_TTL = 48 * 60 * 60 * 1000; let bundleDbData = null; let bundleDbLoading = false; function getBundleCount(appId) { if (!bundleDbData || !appId) return 0; const entry = bundleDbData[String(appId)]; if (!entry) return 0; return typeof entry === 'number' ? entry : (entry.bundles || 0); } const BUNDLE_PARSE_WORKER_SRC = 'self.onmessage = function(e) {\n' + ' var text = e.data.text;\n' + ' var wanted = (e.data.wanted && e.data.wanted.length) ? new Set(e.data.wanted) : null;\n' + ' try {\n' + ' var json = JSON.parse(text);\n' + ' var keys = Object.keys(json);\n' + ' var out = {};\n' + ' for (var i = 0; i < keys.length; i++) {\n' + ' var k = keys[i];\n' + ' if (wanted && !wanted.has(k)) continue;\n' + ' var entry = json[k];\n' + ' var n = (entry && entry.bundles) ? entry.bundles : 0;\n' + ' if (n > 0) out[k] = n;\n' + ' }\n' + ' self.postMessage({ ok: true, total: keys.length, data: out });\n' + ' } catch (err) {\n' + ' self.postMessage({ ok: false, error: String(err) });\n' + ' }\n' + '};'; function parseBundleJsonInWorker(text, wantedAppIds, timeoutMs = 15000) { return new Promise((resolve, reject) => { let worker = null; try { const blob = new Blob([BUNDLE_PARSE_WORKER_SRC], { type: 'application/javascript' }); worker = new Worker(URL.createObjectURL(blob)); } catch (e) { reject(e); return; } const timer = setTimeout(() => { try { worker.terminate(); } catch (e) {} reject(new Error('worker timeout')); }, timeoutMs); worker.onmessage = (e) => { clearTimeout(timer); try { worker.terminate(); } catch (err) {} const msg = e.data || {}; if (msg.ok) resolve(msg); else reject(new Error(msg.error || 'worker parse failed')); }; worker.onerror = () => { clearTimeout(timer); try { worker.terminate(); } catch (err) {} reject(new Error('worker error')); }; worker.postMessage({ text: text, wanted: wantedAppIds }); }); } function parseBundleJsonChunked(text, wantedAppIds) { return new Promise((resolve, reject) => { const wanted = (wantedAppIds && wantedAppIds.length) ? new Set(wantedAppIds) : null; const re = /"(\d+)":\s*\{\s*"bundles":(\d+)/g; const out = {}; let total = 0; function step() { const sliceStart = performance.now(); let m; while ((m = re.exec(text)) !== null) { total++; if (!wanted || wanted.has(m[1])) { const n = parseInt(m[2], 10); if (n > 0) out[m[1]] = n; } if ((total & 1023) === 0 && performance.now() - sliceStart > 12) { setTimeout(step, 0); return; } } if (total === 0) console.warn('[SGLV] Bundle 分片解析 0 匹配——Barter.vg JSON 结构可能已变更'); resolve({ total: total, data: out }); } try { step(); } catch (e) { reject(e); } }); } // CSP 受限页(store.steampowered.com 的 worker-src 回落到 script-src,不含 blob:) // 第一次 new Worker(blob:) 必然被浏览器拦下并打一条 CSP 违规日志(拦不掉), // 所以把「本页不能建 blob worker」记进 sessionStorage(同源共享), // 后续加载直接走主线程分片解析,不再反复触发拦截与控制台告警。 const BUNDLE_WORKER_BLOCK_KEY = 'sglv_bundle_worker_blocked_v1'; function bundleWorkerBlocked() { try { return sessionStorage.getItem(BUNDLE_WORKER_BLOCK_KEY) === '1'; } catch (e) { return false; } } function markBundleWorkerBlocked() { try { sessionStorage.setItem(BUNDLE_WORKER_BLOCK_KEY, '1'); } catch (e) {} } async function loadBundleDatabase() { if (bundleDbData || bundleDbLoading) return bundleDbData; bundleDbLoading = true; try { if (negCacheGet(BUNDLE_DB_NEG_KEY, BUNDLE_DB_NEG_TTL)) { console.log('[SGLV] Bundle 数据库命中负缓存,跳过重试'); return null; } const wantedAppIds = (state.ownedGames || []).map(g => String(g.appid)); const cached = GM_getValue(BUNDLE_DB_CACHE_KEY_V2, null); if (cached && cached.timestamp && (Date.now() - cached.timestamp < BUNDLE_DB_CACHE_TTL) && cached.data) { const covered = new Set(cached.appIds || []); const fullyCovered = wantedAppIds.length === 0 ? !!cached.all : wantedAppIds.every(id => covered.has(id)); if (fullyCovered) { bundleDbData = cached.data; console.log(`[SGLV] Bundle 数据库缓存命中: ${Object.keys(bundleDbData).length} 条记录(精简版)`); return bundleDbData; } } console.log('[SGLV] 正在从 Barter.vg 获取 Bundle 数据库(优先离线程解析)...'); const text = await sglvGmFetchTextRetry(BUNDLE_DB_API_URL, { timeout: 30000, retries: 2 }); let parsed = null; let parseMode = 'worker'; if (bundleWorkerBlocked()) { parseMode = 'main'; parsed = await parseBundleJsonChunked(text, wantedAppIds); } else { try { parsed = await parseBundleJsonInWorker(text, wantedAppIds); } catch (we) { markBundleWorkerBlocked(); parseMode = 'main'; console.warn('[SGLV] Worker 解析不可用(CSP / 浏览器限制),本页后续直接回退主线程分片解析:', we && we.message || we); parsed = await parseBundleJsonChunked(text, wantedAppIds); } } if (!parsed || parsed.total < 7000) { throw new Error('Barter.vg bundles data sanity check failed'); } bundleDbData = parsed.data; GM_setValue(BUNDLE_DB_CACHE_KEY_V2, { data: parsed.data, appIds: wantedAppIds, all: wantedAppIds.length === 0, timestamp: Date.now() }); try { GM_setValue(BUNDLE_DB_CACHE_KEY, null); } catch (e) {} negCacheClear(BUNDLE_DB_NEG_KEY); console.log(`[SGLV] Bundle 数据库加载完成: 全库 ${parsed.total} 条,库存命中 ${Object.keys(parsed.data).length} 条(${parseMode === 'worker' ? '离线程解析' : '主线程分片解析'})`); return bundleDbData; } catch(e) { console.warn('[SGLV] Bundle 数据库加载失败:', e); negCacheSet(BUNDLE_DB_NEG_KEY, e.message || String(e)); sglvNotifyNetFail('Bundle 数据库 (Barter.vg)', e); return null; } finally { bundleDbLoading = false; } } const DLC_DB_API_URL = 'https://bartervg.com/browse/dlc/json/'; const DLC_DB_CACHE_KEY = 'sglv_dlc_db_cache'; const DLC_DB_CACHE_TTL = 72 * 60 * 60 * 1000; let dlcDbData = null; let dlcDbPromise = null; let appTypeMap = null; let appTypePromise = null; let _dlcsByParentCache = null; function isDlc(appId) { if (!appId) return false; const id = String(appId); if (dlcDbData && dlcDbData[id]) return true; if (appTypeMap) { const t = appTypeMap[id]; if (t === 'dlc' || t === 'music') return true; } return false; } function loadDlcDatabaseFromCacheSync() { if (!dlcDbData) { try { const cached = GM_getValue(DLC_DB_CACHE_KEY, null); if (cached && cached.timestamp && (Date.now() - cached.timestamp < DLC_DB_CACHE_TTL)) { dlcDbData = cached.data; console.log(`[SGLV] DLC 数据库缓存命中 (sync): ${Object.keys(dlcDbData).length} 条记录`); } } catch(e) { console.warn('[SGLV] DLC 数据库缓存读取失败:', e); } } if (!appTypeMap) { try { const cached = GM_getValue(APP_TYPES_CACHE_KEY, null); const cachedN = (cached && cached.data) ? Object.keys(cached.data).length : 0; if (cached && cached.timestamp && (Date.now() - cached.timestamp < APP_TYPES_CACHE_TTL) && (cachedN || cached.emptyOk)) { appTypeMap = cached.data; console.log(`[SGLV] 全库存应用类型缓存命中 (sync): ${cachedN} 条`); } else if (cached && !cachedN && !cached.emptyOk) { // 空表且没有 emptyOk 标记 = 旧版「全批失败也写缓存」留下的脏数据,丢掉等重拉 console.log('[SGLV] 应用类型缓存为空表(无 emptyOk 标记),已丢弃'); } } catch(e) { console.warn('[SGLV] 全库存应用类型缓存读取失败:', e); } } } async function loadDlcDatabase() { if (dlcDbData) return dlcDbData; if (dlcDbPromise) return dlcDbPromise; dlcDbPromise = (async () => { try { const cached = GM_getValue(DLC_DB_CACHE_KEY, null); if (cached && cached.timestamp && (Date.now() - cached.timestamp < DLC_DB_CACHE_TTL)) { dlcDbData = cached.data; console.log(`[SGLV] DLC 数据库缓存命中: ${Object.keys(dlcDbData).length} 条记录`); return dlcDbData; } console.log('[SGLV] 正在从 Barter.vg 获取 DLC 数据库...'); const json = await sglvGmFetchRetry(DLC_DB_API_URL, { timeout: 30000, retries: 2 }); if (!json || Object.keys(json).length < 7000) { throw new Error('Barter.vg DLC data sanity check failed'); } dlcDbData = json; GM_setValue(DLC_DB_CACHE_KEY, { data: json, timestamp: Date.now() }); console.log(`[SGLV] DLC 数据库加载完成: ${Object.keys(json).length} 条记录`); return dlcDbData; } catch(e) { console.warn('[SGLV] DLC 数据库加载失败:', e); sglvNotifyNetFail('DLC 数据库 (Barter.vg)', e); return null; } finally { dlcDbPromise = null; } })(); return dlcDbPromise; } let dlcTypeMap = null; let dlcTypeLoading = false; function getDlcType(appId) { if (!dlcTypeMap || !appId) return null; return dlcTypeMap[String(appId)] || null; } async function enrichDlcTypes(dlcAppIds, options = {}) { if (!dlcAppIds || dlcAppIds.length === 0) return; const { onProgress } = options; if (dlcTypeLoading) { console.log('[SGLV] enrichDlcTypes — 等待已有加载完成...'); let waitCount = 0; while (dlcTypeLoading && waitCount < 60) { await new Promise(r => setTimeout(r, 500)); waitCount++; } } if (!dlcTypeMap) { const cached = GM_getValue('sglv_dlc_types_cache', null); if (cached && cached.data) { dlcTypeMap = cached.data; console.log(`[SGLV] DLC 类型 GM 缓存命中: ${Object.keys(dlcTypeMap).length} 条`); } } const needEnrich = dlcAppIds.filter(id => !dlcTypeMap || !dlcTypeMap[String(id)]); if (needEnrich.length === 0) { console.log(`[SGLV] enrichDlcTypes — 全部 ${dlcAppIds.length} 个 DLC 类型已存在,跳过`); return; } dlcTypeLoading = true; try { console.log(`[SGLV] 正在获取 ${needEnrich.length}/${dlcAppIds.length} 个 DLC 的类型信息...`); const CHUNK = 100, CONCURRENCY = 3; const chunks = []; for (let i = 0; i < needEnrich.length; i += CHUNK) chunks.push(needEnrich.slice(i, i + CHUNK)); const typeMap = {}; let qIdx = 0; let doneCount = 0; const worker = async () => { while (qIdx < chunks.length) { const chunk = chunks[qIdx++]; try { const input = { ids: chunk.map(id => ({ appid: id })), context: { language: 'schinese', country_code: 'CN', steam_realm: 1 }, data_request: { include_release: false } }; const url = 'https://api.steampowered.com/IStoreBrowseService/GetItems/v1?input_json=' + encodeURIComponent(JSON.stringify(input)); const resp = await requestSteamAPI(url); const storeItems = resp?.response?.store_items || []; storeItems.forEach(si => { if (si && si.appid) { let typeStr = 'dlc'; if (typeof si.type === 'number') { typeStr = ({ 0: 'game', 1: 'dlc', 2: 'software', 3: 'video', 4: 'series', 6: 'music', 7: 'tool', 8: 'video_series' })[si.type] || 'other'; } else if (si.type) { typeStr = String(si.type).toLowerCase(); } typeMap[String(si.appid)] = typeStr; if (si.name) { const nc = sglvGameNameCacheLoad(); nc[String(si.appid)] = { name: si.name, ts: Date.now() }; } } }); } catch (e) { console.warn('[SGLV] DLC type batch failed:', e); } doneCount += chunk.length; if (onProgress) try { onProgress(doneCount, needEnrich.length); } catch (e) {} await new Promise(r => setTimeout(r, 200)); } }; const workers = []; for (let i = 0; i < CONCURRENCY; i++) workers.push(worker()); await Promise.all(workers); if (!dlcTypeMap) dlcTypeMap = {}; let newCount = 0; for (const [k, v] of Object.entries(typeMap)) { if (!dlcTypeMap[k]) { dlcTypeMap[k] = v; newCount++; } } GM_setValue('sglv_dlc_types_cache', { data: dlcTypeMap, timestamp: Date.now() }); if (isZh) { try { sglvGameNameCacheSave(); } catch (e) {} } console.log(`[SGLV] DLC 类型获取完成: 新增 ${newCount} 条, 累计 ${Object.keys(dlcTypeMap).length} 条`); } catch(e) { console.warn('[SGLV] DLC 类型获取失败:', e); } finally { dlcTypeLoading = false; } } const APP_TYPES_CACHE_KEY = 'sglv_app_types_cache'; const APP_TYPES_CACHE_TTL = 72 * 60 * 60 * 1000; async function enrichOwnedAppTypes(onProgress) { if (appTypeMap || appTypePromise) return appTypePromise; const allItems = (storage.getShowFamilyShared() ? state.ownedGames : state.ownedGames.filter(g => isGameOwnedByMe(g))); const appIds = allItems.map(g => g.appid); if (appIds.length === 0) return null; const report = (pct, text) => { if (typeof onProgress === 'function') onProgress(pct, text); }; appTypePromise = (async () => { try { if (negCacheGet(nsKey('app_types_neg'), 30 * 60 * 1000)) { console.log('[SGLV] app types 命中负缓存,跳过重试'); return null; } const cached = GM_getValue(APP_TYPES_CACHE_KEY, null); const cachedN = (cached && cached.data) ? Object.keys(cached.data).length : 0; // emptyOk:上次「接口正常但库全部不可见」的合法空结果;没有这个标记的空表 // 一律视为「全批失败被误缓存」,丢掉重拉 if (cached && cached.timestamp && (Date.now() - cached.timestamp < APP_TYPES_CACHE_TTL) && (cachedN || cached.emptyOk)) { appTypeMap = cached.data; console.log(`[SGLV] 全库存应用类型缓存命中: ${cachedN} 条`); report(100, isZh ? 'appdetails 缓存命中' : 'appdetails cached'); return appTypeMap; } report(0, isZh ? `正在补全 ${appIds.length} 款游戏详情…` : `Enriching ${appIds.length} games…`); console.log(`[SGLV] 正在获取 ${appIds.length} 个库存应用的类型信息...`); const CHUNK = 200, CONCURRENCY = 3; const chunks = []; for (let i = 0; i < appIds.length; i += CHUNK) chunks.push(appIds.slice(i, i + CHUNK)); const typeMap = {}; let doneCount = 0; let okBatches = 0; // 成功拿回 store_items 的批次数(区分「网络全挂」与「接口正常但库不可见」) let qIdx = 0; const total = chunks.length; const worker = async () => { while (qIdx < chunks.length) { const chunk = chunks[qIdx++]; try { const input = { ids: chunk.map(id => ({ appid: id })), context: { language: 'schinese', country_code: 'CN', steam_realm: 1 }, data_request: { include_release: false } }; const url = 'https://api.steampowered.com/IStoreBrowseService/GetItems/v1?input_json=' + encodeURIComponent(JSON.stringify(input)); const resp = await requestSteamAPI(url); okBatches++; const storeItems = resp?.response?.store_items || []; storeItems.forEach(si => { if (si && si.appid) { let typeStr = 'game'; if (typeof si.type === 'number') { typeStr = ({ 0: 'game', 1: 'dlc', 2: 'software', 3: 'video', 4: 'series', 6: 'music', 7: 'tool', 8: 'video_series' })[si.type] || 'other'; } else if (si.type) { typeStr = String(si.type).toLowerCase(); } typeMap[String(si.appid)] = typeStr; } }); } catch (e) { console.warn('[SGLV] App type batch failed:', e); } doneCount++; if (total > 0) report(Math.round(doneCount / total * 100), isZh ? `已补全 ${doneCount}/${total} 批…` : `${doneCount}/${total} batches…`); await new Promise(r => setTimeout(r, 200)); } }; const workers = []; for (let i = 0; i < CONCURRENCY; i++) workers.push(worker()); await Promise.all(workers); const typeCount = Object.keys(typeMap).length; // 全部批次请求失败(网络 / 接口变更)→ 不能把空表当成「已获取」写进 72h 缓存, // 否则之后三天的 DLC 判定 / 类型过滤都按空索引跑,且 isDlcDbReady() 仍是 true。 // 接口有成功响应但库全部不可见(私密 / 全区下架)属合法空结果 —— 放行并只记一行日志。 if (!okBatches) throw new Error(`appdetails 全部 ${total} 批请求失败`); const missCount = appIds.length - typeCount; if (!typeCount) { console.log('[SGLV] 应用类型索引为空(接口正常返回,但库存应用均不可见)'); } else if (missCount > 0) { console.warn(`[SGLV] 应用类型索引未覆盖 ${missCount}/${appIds.length} 款(多为已下架/区域不可见),已按实际条目缓存`); } appTypeMap = typeMap; GM_setValue(APP_TYPES_CACHE_KEY, { data: typeMap, timestamp: Date.now(), emptyOk: !typeCount }); _cachedDlcCount = null; _cachedDlcCountKey = ''; negCacheClear(nsKey('app_types_neg')); report(100, isZh ? '详情补全完成' : 'Enrichment done'); console.log(`[SGLV] 全库存应用类型获取完成: ${typeCount} 条`); return appTypeMap; } catch(e) { console.warn('[SGLV] 全库存应用类型获取失败:', e); negCacheSet(nsKey('app_types_neg'), e.message || String(e)); return null; } finally { appTypePromise = null; } })(); return appTypePromise; } function renderOwnedTab(parent) { state.ownedSort = storage.getOwnedSort(); const dashboard = document.createElement('div'); dashboard.className = 'sglv-stats-dashboard'; dashboard.id = 'sglv-owned-dashboard'; parent.appendChild(dashboard); const toolbar = buildListToolbar({ search: { id: 'sglv-search', placeholder: T.searchPlaceholder, value: state.searchQuery }, sort: { id: 'sglv-sort', title: T.sortLabel, options: [ { value: 'appidAsc', label: T.sortAppidAsc }, { value: 'appidDesc', label: T.sortAppidDesc }, { value: 'nameAsc', label: T.sortNameAsc }, { value: 'acquiredDesc', label: T.sortAcquiredDesc }, { value: 'acquiredAsc', label: T.sortAcquiredAsc }, { value: 'playtimeDesc', label: T.sortPlaytimeDesc }, { value: 'lastPlayedDesc', label: T.sortLastPlayedDesc }, { value: 'bundleDesc', label: T.sortBundleDesc }, ], }, views: { modes: [ { mode: 'card', title: T.cardView, icon: ICONS.grid }, { mode: 'cover', title: T.coverView, icon: ICONS.cover }, { mode: 'list', title: T.listView, icon: ICONS.list }, ], value: state.viewMode, useDataView: true, }, extraHtml: `
`, onChange: ({ type, value }) => { if (type === 'input') { state.searchQuery = value; state.page = 1; renderGamesList(); } else if (type === 'sort') { state.ownedSort = value; storage.setOwnedSort(value); state.page = 1; renderGamesList(); if (value.startsWith('acquired')) enrichAcquiredTimesForSort(); } else if (type === 'view') { state.viewMode = value; renderGamesList(); } }, }); toolbar.querySelector('#sglv-sort').value = state.ownedSort; parent.appendChild(toolbar); dashboard.addEventListener('click', e => { const card = e.target.closest('[data-filter]'); if (!card) return; const filter = card.dataset.filter; state.ownedFilter = state.ownedFilter === filter ? 'all' : filter; state.page = 1; renderGamesList(); }); const content = document.createElement('div'); content.className = 'sglv-content'; content.id = 'sglv-games-content'; parent.appendChild(content); loadDlcDatabaseFromCacheSync(); renderGamesList(); } function prepareOwnedTabData() { loadBundleDatabase().then(() => { if (document.getElementById('sglv-owned-dashboard')) { renderGamesList(); } }).catch(e => console.warn('[SGLV] Bundle DB load failed:', e)); if (SGLV_API.loadCardDatabase) { SGLV_API.loadCardDatabase().then(() => { if (document.getElementById('sglv-owned-dashboard')) { renderGamesList(); } }).catch(e => console.warn('[SGLV] Card DB load failed:', e)); } loadDlcDatabase().then(() => { if (document.getElementById('sglv-owned-dashboard')) { renderGamesList(); } enrichOwnedAppTypes().then(() => { if (document.getElementById('sglv-owned-dashboard')) { renderGamesList(); } const allItems = (storage.getShowFamilyShared() ? state.ownedGames : state.ownedGames.filter(g => isGameOwnedByMe(g))); const dlcIds = allItems.filter(g => isDlc(g.appid)).map(g => g.appid); if (dlcIds.length > 0) { enrichDlcTypes(dlcIds).then(() => { if (document.getElementById('sglv-owned-dashboard')) renderGamesList(); }); } }).catch(e => console.warn('[SGLV] App types enrichment failed:', e)); }).catch(e => console.warn('[SGLV] DLC DB load failed:', e)); } function renderOwnedKpiSummary(dashboard, showFamilyShared) { const allItems = showFamilyShared ? state.ownedGames : state.ownedGames.filter(g => isGameOwnedByMe(g)); const realGames = allItems.filter(g => !isDlc(g.appid)); const dlcGames = allItems.filter(g => isDlc(g.appid)); const totalGames = realGames.length; const realGamesMinutes = realGames.reduce((s, g) => s + (g.playtime || 0), 0); const allItemsMinutes = allItems.reduce((s, g) => s + (g.playtime || 0), 0); const totalMinutes = Math.max(realGamesMinutes, allItemsMinutes); const playedCount = realGames.filter(g => (g.playtime || 0) > 0).length; const unplayedCount = totalGames - playedCount; const sharedCount = state.ownedGames.filter(g => g.owners && g.owners.length > 0 && !isGameOwnedByMe(g) && !isDlc(g.appid)).length; const avgHoursPerGame = totalGames > 0 ? (totalMinutes / 60 / totalGames).toFixed(1) : '0'; const playedPct = totalGames > 0 ? Math.round(playedCount / totalGames * 100) : 0; const unplayedPct = totalGames > 0 ? Math.round(unplayedCount / totalGames * 100) : 0; const bundledCount = realGames.filter(g => getBundleCount(g.appid) > 0).length; const cardCount = realGames.filter(g => SGLV_API.getCardDbMaxLevel && SGLV_API.getCardDbMaxLevel(g.appid) > 0).length; const dlcTotal = dlcGames.length; const dlcBundled = dlcGames.filter(g => getBundleCount(g.appid) > 0).length; const dlcMusic = dlcGames.filter(g => getDlcType(g.appid) === 'music').length; const dlcSubText = dlcTotal > 0 ? `${T.kpiDlcMusic} ${dlcMusic} · ${T.kpiDlcBundled} ${dlcBundled}` : (isZh ? '加载中...' : 'Loading...'); dashboard.innerHTML = kpiCards([ { icon: ICONS.library, label: T.statsTotalGames, value: totalGames.toLocaleString(), sub: `${T.kpiAvgHours} ${avgHoursPerGame}${T.kpiPerGame}`, color: 'blue', active: state.ownedFilter === 'all', dataFilter: 'all' }, { icon: ICONS.trend, label: T.statsPlayed, value: playedCount.toLocaleString(), sub: `${T.kpiRate} ${playedPct}%`, color: 'green', active: state.ownedFilter === 'played', dataFilter: 'played' }, { icon: ICONS.clock, label: T.statsUnplayed, value: unplayedCount.toLocaleString(), sub: `${T.kpiRate} ${unplayedPct}%`, color: 'red', active: state.ownedFilter === 'unplayed', dataFilter: 'unplayed' }, { icon: ICONS.share, label: T.statsShared, value: sharedCount.toLocaleString(), sub: T.kpiFromFamily, color: 'purple', active: state.ownedFilter === 'shared', dataFilter: 'shared' }, { icon: ICONS.package, label: T.statsBundled, value: bundledCount.toLocaleString(), sub: T.kpiInBundles, color: 'orange', active: state.ownedFilter === 'bundled', dataFilter: 'bundled' }, { icon: ICONS.card, label: T.statsCards, value: cardCount.toLocaleString(), sub: T.kpiHasCards, color: 'teal', active: state.ownedFilter === 'cards', dataFilter: 'cards' }, { icon: ICONS.package, label: T.statsDlcTotal, value: dlcTotal.toLocaleString(), sub: dlcSubText, color: 'pink', active: state.ownedFilter === 'dlconly', dataFilter: 'dlconly' }, ], { tone: 'dash' }); } function renderGamesList() { const content = document.getElementById('sglv-games-content'); const pagination = document.getElementById('sglv-pagination'); const dashboard = document.getElementById('sglv-owned-dashboard'); if (!content) return; let games = [...state.ownedGames]; const showFamilyShared = storage.getShowFamilyShared(); if (!showFamilyShared) { games = games.filter(g => isGameOwnedByMe(g)); } if (state.ownedFilter !== 'dlconly') { games = games.filter(g => !isDlc(g.appid)); } if (state.ownedFilter === 'played') { games = games.filter(g => (g.playtime || 0) > 0); } else if (state.ownedFilter === 'unplayed') { games = games.filter(g => (g.playtime || 0) === 0); } else if (state.ownedFilter === 'shared') { games = games.filter(g => g.owners && g.owners.length > 0 && !isGameOwnedByMe(g)); } else if (state.ownedFilter === 'owned') { games = games.filter(g => isGameOwnedByMe(g)); } else if (state.ownedFilter === 'bundled') { games = games.filter(g => getBundleCount(g.appid) > 0); } else if (state.ownedFilter === 'cards') { games = games.filter(g => SGLV_API.getCardDbMaxLevel && SGLV_API.getCardDbMaxLevel(g.appid) > 0); } else if (state.ownedFilter === 'dlconly') { games = games.filter(g => isDlc(g.appid)); } if (state.searchQuery) { const q = state.searchQuery.toLowerCase(); games = games.filter(g => g.name.toLowerCase().includes(q)); } const sortKey = state.ownedSort || 'appidAsc'; const acqTime = g => g.acquiredTime || 0; games.sort((a, b) => { let r = 0; switch (sortKey) { case 'appidDesc': r = b.appid - a.appid; break; case 'nameAsc': r = _nameCollator.compare(a.name || '', b.name || ''); break; case 'acquiredDesc': r = acqTime(b) - acqTime(a); break; case 'acquiredAsc': { const x = acqTime(a), y = acqTime(b); r = (!x && !y) ? 0 : !x ? 1 : !y ? -1 : x - y; break; } case 'playtimeDesc': r = (b.playtime || 0) - (a.playtime || 0); break; case 'lastPlayedDesc': r = (b.lastPlayed || 0) - (a.lastPlayed || 0); break; case 'bundleDesc': r = getBundleCount(b.appid) - getBundleCount(a.appid); break; default: r = a.appid - b.appid; } return r || (a.appid - b.appid); }); if (dashboard) renderOwnedKpiSummary(dashboard, showFamilyShared); const _effectivePageSize = state.viewMode === 'cover' ? 24 : state.pageSize; const { pageItems: pageGames, totalPages, page: _clampedPage } = paginate(games, state.page, _effectivePageSize); state.page = _clampedPage; if (games.length === 0) { content.innerHTML = emptyHtml(state.ownedGames.length === 0 ? T.noData : (isZh ? '无匹配游戏' : 'No matching games')); if (pagination) pagination.innerHTML = ''; return; } if (state.viewMode === 'cover') { const grid = document.createElement('div'); grid.className = 'sglv-cover-grid'; pageGames.forEach(g => { const card = document.createElement('div'); card.className = 'sglv-cover-card'; const isOwned = isGameOwnedByMe(g); const ownerNames = getGameOwnerNames(g); const hours = Math.round(g.playtime / 60); card.innerHTML = `
${coverImgTag(g.appid, g.name, 'capsule', 'sglv-cover-img')}
${!isOwned ? `${isZh ? '共享' : 'Shared'}` : ''} ${getBundleCount(g.appid) > 0 ? `${ICONS.package}${getBundleCount(g.appid)}` : ''}
${hours > 0 ? `
${ICONS.clock}${hours}h
` : ''}
${g.name}
AppID: ${g.appid}
`; card.addEventListener('click', () => window.open(`https://store.steampowered.com/app/${g.appid}`, '_blank')); grid.appendChild(card); }); content.innerHTML = ''; content.appendChild(grid); } else if (state.viewMode === 'card') { content.innerHTML = renderGameView(pageGames, { viewMode: 'card', imgHtml: g => posterImg(g.appid, g.name), bodyHtml: g => { const isOwned = isGameOwnedByMe(g); const ownerNames = getGameOwnerNames(g); return `
${g.name}
AppID: ${g.appid}
${g.playtime > 0 ? `
${Math.round(g.playtime / 60)}h
` : ''} ${!isOwned ? `
共享
` : ''} ${getBundleCount(g.appid) > 0 ? `${getBundleCount(g.appid)}` : ''}
`; }, }); content.querySelectorAll('.sglv-game-card').forEach((el, i) => { el.addEventListener('click', () => window.open(`https://store.steampowered.com/app/${pageGames[i].appid}`, '_blank')); }); } else { content.innerHTML = renderGameView(pageGames, { viewMode: 'list', imgHtml: g => headerImg(g.appid, g.name).replace('sglv-card-img', 'sglv-list-icon'), bodyHtml: g => { const isOwned = isGameOwnedByMe(g); const ownerNames = getGameOwnerNames(g); return `
${g.name}
AppID: ${g.appid} ${!isOwned ? `👥 共享自: ${ownerNames}` : ''}
`; }, trailingHtml: g => { const hours = Math.round(g.playtime / 60); const isOwned = isGameOwnedByMe(g); return ` ${hours > 0 ? `${hours}h` : ''} ${!isOwned ? `共享` : ''} ${getBundleCount(g.appid) > 0 ? `${getBundleCount(g.appid)}` : ''} `; }, }); content.querySelectorAll('.sglv-list-item').forEach((el, i) => { el.addEventListener('click', () => window.open(`https://store.steampowered.com/app/${pageGames[i].appid}`, '_blank')); }); } renderPagination(pagination, 'sglv', state.page, totalPages, games.length, () => { state.page--; renderGamesList(); }, () => { state.page++; renderGamesList(); }, (p) => { state.page = p; renderGamesList(); }); applyGameAliases(content, { aliasFor: '.sglv-list-name' }); } let _acquiredEnrichPending = false; function enrichAcquiredTimesForSort() { if (_acquiredEnrichPending) return; if (!state.ownedGames.length || state.ownedGames.some(g => g.acquiredTime > 0)) return; _acquiredEnrichPending = true; buildCalibratedAcquiredMap().then(({ games: fg, map }) => { if (fg && fg.length) { let changed = 0; state.ownedGames.forEach(g => { if (!g.acquiredTime && map[g.appid]) { g.acquiredTime = map[g.appid]; changed++; } }); if (changed > 0 && (state.ownedSort || '').startsWith('acquired') && document.getElementById('sglv-games-content')) { renderGamesList(); } } }).catch(e => console.warn('[SGLV] 入库时间补齐失败:', e)) .finally(() => { _acquiredEnrichPending = false; }); } function calcPlaytimeDist(games, mode = 'count') { const cacheK = cacheKey('dist', mode, games.length, games.reduce((s, g) => s + (g.playtime || 0), 0)); return getCached(cacheK, () => { const ranges = [ { label: T.ptRange1, min: 0.01, max: 1, color: '#94a3b8' }, { label: T.ptRange2, min: 1, max: 10, color: '#60a5fa' }, { label: T.ptRange3, min: 10, max: 50, color: '#34d399' }, { label: T.ptRange4, min: 50, max: 100, color: '#fbbf24' }, { label: T.ptRange5, min: 100, max: 500, color: '#f97316' }, { label: T.ptRange6, min: 500, max: Infinity, color: '#ef4444' } ]; if (mode === 'hours') { return ranges.map(r => ({ label: r.label, count: Math.round(games.filter(g => { const h = (g.playtime || 0) / 60; return h >= r.min && h < r.max; }).reduce((s, g) => s + (g.playtime || 0) / 60, 0)), color: r.color })); } const zeroCount = games.filter(g => (g.playtime || 0) === 0).length; return [ { label: T.ptRange0, count: zeroCount, color: '#64748b' }, ...ranges.map(r => ({ label: r.label, count: games.filter(g => { const h = (g.playtime || 0) / 60; return h >= r.min && h < r.max; }).length, color: r.color })) ]; }); } function getPeriodKey(date, mode) { const y = date.getFullYear(); const m = date.getMonth(); if (mode === 'year') return `${y}`; if (mode === 'quarter') return `${y}-Q${Math.floor(m / 3) + 1}`; return `${y}-${String(m + 1).padStart(2, '0')}`; } function renderPlaytimeTrend(games, mode) { const cacheK = cacheKey('trend', mode, games.length, games.reduce((s, g) => s + (g.lastPlayed || 0), 0)); return getCached(cacheK, () => { const played = games.filter(g => g.lastPlayed > 0); if (!played.length) return emptyHtml(isZh ? '暂无趋势数据' : 'No trend data', { style: 'font-size:11px' }); const buckets = {}; played.forEach(g => { const d = new Date(g.lastPlayed * 1000); const key = getPeriodKey(d, mode); buckets[key] = (buckets[key] || 0) + ((g.playtime || 0) / 60); }); const dates = played.map(g => new Date(g.lastPlayed * 1000)); const minDate = new Date(Math.min(...dates)); const maxDate = new Date(Math.max(...dates)); const periods = []; let cursor = new Date(minDate); while (cursor <= maxDate) { periods.push(getPeriodKey(cursor, mode)); if (mode === 'year') cursor.setFullYear(cursor.getFullYear() + 1); else if (mode === 'quarter') cursor.setMonth(cursor.getMonth() + 3); else cursor.setMonth(cursor.getMonth() + 1); } const MAX_POINTS = mode === 'month' ? 12 : mode === 'quarter' ? 12 : 10; const displayPeriods = periods.slice(-MAX_POINTS); const displayValues = displayPeriods.map(p => buckets[p] || 0); if (displayValues.every(v => v === 0)) return emptyHtml(isZh ? '暂无趋势数据' : 'No trend data', { style: 'font-size:11px' }); const maxV = Math.max(...displayValues) || 1; const n = displayValues.length; const avgV = displayValues.reduce((s, v) => s + v, 0) / n; const maxIdx = displayValues.indexOf(maxV); return SGLVCharts.lineChart([{ data: displayValues }], { width: 400, height: 200, pL: 30, pR: 30, pT: 30, pB: 30, smooth: false, colors: [SGLVCharts.accent()], svgAttrs: 'class="sglv-trend-svg"', centerSinglePoint: true, area: { fill: SGLVCharts.accent(), opacity: 0.4 }, gridCount: 4, yFormatter: v => v.toFixed(0) + 'h', xLabels: displayPeriods.map(p => mode === 'year' ? p : p.replace(/^\d{4}-/, '')), xLabelEvery: 6, xLabelLast: true, dots: { r: 3, stroke: '#0f172a', strokeWidth: 1, title: (v, i) => `${displayPeriods[i]}: ${v.toFixed(1)}h` }, annotations: [ { type: 'refLine', value: avgV, color: 'rgba(251,191,36,0.5)', dash: '4,3', label: `${isZh ? '均' : 'avg'} ${avgV.toFixed(0)}h`, labelColor: '#fbbf24', fontSize: 8, fontWeight: 600 }, { type: 'point', idx: maxIdx, text: `${isZh ? '峰' : 'peak'} ${maxV.toFixed(0)}h`, color: '#fbbf24', fontSize: 9, fontWeight: 700, dy: -7 }, ], }); }); } function renderPlaytimeDonut(distData, total, unit = '') { if (total === 0) return emptyHtml(T.ptNoData); const fmt = (n) => n.toLocaleString(); const pct = (n) => (n / total * 100).toFixed(1); const totalStr = fmt(total) + unit; let centerFontSize; if (totalStr.length <= 5) centerFontSize = 28; else if (totalStr.length <= 7) centerFontSize = 24; else if (totalStr.length <= 9) centerFontSize = 20; else centerFontSize = 16; return SGLVCharts.donutChart( distData.map(d => ({ value: d.count, color: d.color, label: d.label })), { size: 240, thickness: 44, bg: false, title: sl => `${sl.label}: ${fmt(sl.value)}${unit} (${pct(sl.value)}%)`, segStyle: 'transition:all .3s ease', center: { text: totalStr, fontSize: centerFontSize, weight: 'bold', fill: '#f8fafc', y: 110.4, sub: isZh ? '总计' : 'Total', subFontSize: 11, subFill: '#8a9ba8', subY: 148.8, }, legend: { value: sl => `${fmt(sl.value)}${unit} (${pct(sl.value)}%)`, }, wrap: true, } ); } function renderAcquiredHeatmap(heatGames) { const valid = heatGames.filter(g => g.acquiredTime && g.acquiredTime > 0); if (valid.length === 0) return emptyHtml(T.ptHeatmapNoData); const sig = valid.length + '_' + valid[0].appid + '_' + valid[valid.length - 1].appid + '_' + valid[0].acquiredTime + '_' + valid[valid.length - 1].acquiredTime; if (_heatmapRenderCache && _heatmapRenderCache.signature === sig && Date.now() - _heatmapRenderCache.ts < 10 * 60 * 1000) { return _heatmapRenderCache.html; } const dayMap = {}; const yearDayMaps = {}; const tsList = []; for (const g of valid) { const t = g.acquiredTime; const d = new Date(t * 1000); const y = d.getFullYear(); const key = y + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0'); dayMap[key] = (dayMap[key] || 0) + 1; const ym = yearDayMaps[y] || (yearDayMaps[y] = {}); ym[key] = (ym[key] || 0) + 1; tsList.push(t); } tsList.sort((a, b) => a - b); const firstTs = tsList[0], lastTs = tsList[tsList.length - 1]; const years = Object.keys(yearDayMaps).map(Number).sort((a, b) => a - b); const cellSize = 12, cellGap = 3, cellStep = cellSize + cellGap; const labelW = 26, yearH = 14, monthH = 16; const monthNames = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']; const dayNames = ['', '一', '', '三', '', '五', '']; const colors = ['#161b22', '#0e4429', '#006832', '#26a641', '#39d353']; const futureColor = '#30363d'; function heatColor(count) { if (count === 0) return colors[0]; if (count <= 1) return colors[1]; if (count <= 2) return colors[2]; if (count <= 4) return colors[3]; return colors[4]; } const fmtD = (d) => d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0'); function buildView(viewDayMap, rangeStartDate, rangeEndDate, avgSpanDays, showYearRow) { const globalStart = new Date(rangeStartDate); globalStart.setHours(0, 0, 0, 0); const endDate = new Date(rangeEndDate); endDate.setHours(0, 0, 0, 0); const gridStart = new Date(globalStart); gridStart.setDate(gridStart.getDate() - globalStart.getDay()); const totalDays = Math.floor((endDate - gridStart) / 86400000) + 1; const totalWeeks = Math.ceil(totalDays / 7); const topH = (showYearRow ? yearH : 0) + monthH; const svgW = labelW + totalWeeks * cellStep + 8; const svgH = topH + 7 * cellStep + 8; let maxDaily = 0, total = 0; for (const k in viewDayMap) { if (viewDayMap[k] > maxDaily) maxDaily = viewDayMap[k]; total += viewDayMap[k]; } const avgDaily = (total / Math.max(1, avgSpanDays)).toFixed(2); const cellParts = [], monthLabelPositions = [], yearBoundaries = []; let lastMonth = -1, lastYear = -1; const startMs = globalStart.getTime(), endMs = endDate.getTime(); for (let w = 0; w < totalWeeks; w++) { for (let d = 0; d < 7; d++) { const cellTs = gridStart.getTime() + (w * 7 + d) * 86400000; if (cellTs < startMs || cellTs > endMs) continue; const cellDate = new Date(cellTs); const key = cellDate.getFullYear() + '-' + String(cellDate.getMonth() + 1).padStart(2, '0') + '-' + String(cellDate.getDate()).padStart(2, '0'); const cnt = viewDayMap[key] || 0; const x = labelW + w * cellStep, y = topH + d * cellStep; if (cnt > 0) { cellParts.push(`${key} · ${cnt} ${T.ptHeatmapAcquired}`); } else { const isFuture = cellDate.getTime() > today.getTime(); cellParts.push(``); } if (d === 0) { if (cellDate.getMonth() !== lastMonth) { lastMonth = cellDate.getMonth(); monthLabelPositions.push({ w, month: cellDate.getMonth() }); } if (showYearRow && cellDate.getFullYear() !== lastYear) { lastYear = cellDate.getFullYear(); yearBoundaries.push({ w, year: cellDate.getFullYear() }); } } } } const yearParts = []; for (const yb of yearBoundaries) { if (yb.w > 0) { const lineX = labelW + yb.w * cellStep - cellGap / 2; yearParts.push(``); } yearParts.push(`${yb.year}`); } const monthParts = monthLabelPositions.map(ml => `${monthNames[ml.month]}` ).join(''); const dayParts = []; for (let di = 0; di < 7; di++) { if (dayNames[di]) dayParts.push(`${dayNames[di]}`); } const svgStr = `${yearParts.join('')}${monthParts}${dayParts.join('')}${cellParts.join('')}`; const summary = `
${T.ptHeatmapLess}${colors.map(c => ``).join('')}${T.ptHeatmapMore} ${T.ptHeatmapTotal}: ${total} ${T.ptHeatmapPeak}: ${maxDaily} ${T.ptHeatmapAvg}: ${avgDaily} ${fmtD(globalStart)} ~ ${fmtD(endDate)}
`; return `
${svgStr}
${summary}`; } const today = new Date(); today.setHours(0, 0, 0, 0); const views = {}; for (const y of years) { const yStart = new Date(y, 0, 1); const yEnd = new Date(y, 11, 31); const avgSpan = Math.floor((yEnd - yStart) / 86400000) + 1; views[String(y)] = buildView(yearDayMaps[y], yStart, yEnd, avgSpan, false); } const allAvgSpan = Math.max(1, Math.ceil((lastTs - firstTs) / 86400) + 1); views.all = buildView(dayMap, new Date(firstTs * 1000), today, allAvgSpan, true); let filterHtml = '', defaultView = 'all'; if (years.length > 1) { const latestYear = String(years[years.length - 1]); const btns = [...years].reverse().map(y => `` ).join(''); filterHtml = `
${btns}
`; defaultView = latestYear; } const html = `
${filterHtml}
${views[defaultView]}
`; _heatmapRenderCache = { signature: sig, html, ts: Date.now(), views }; return html; } function renderMonthlyAcquireChart(heatGames) { const now = new Date(); const months = []; for (let i = 5; i >= 0; i--) { const d = new Date(now.getFullYear(), now.getMonth() - i, 1); months.push({ y: d.getFullYear(), m: d.getMonth(), count: 0 }); } const startTs = new Date(months[0].y, months[0].m, 1).getTime() / 1000; for (const g of heatGames) { const t = g.acquiredTime; if (!t || t < startTs) continue; const d = new Date(t * 1000); const idx = (d.getFullYear() - months[0].y) * 12 + (d.getMonth() - months[0].m); if (idx >= 0 && idx < 6) months[idx].count++; } const max = Math.max(...months.map(o => o.count)); const BAR_COLORS = ['#14b8a6', '#3b82f6', '#f59e0b', '#22c55e', '#ef4444', '#8b5cf6']; const W = 280, H = 200, lw = 32, topPad = 20, botPad = 24; const plotW = W - lw - 2, plotH = H - topPad - botPad; const step = plotW / 6, barW = Math.min(26, step * 0.6); const yMax = max > 0 ? max : 1; const yOf = v => topPad + plotH - (v / yMax) * plotH; let parts = ''; const gridVals = max > 0 ? [...new Set([0, Math.ceil(max / 2), max])] : [0, 1]; for (const v of gridVals) { const y = yOf(v); parts += ``; parts += `${v}`; } months.forEach((o, i) => { const cx = lw + step * i + step / 2; const bh = max > 0 ? (o.count / yMax) * plotH : 0; const bx = cx - barW / 2, by = topPad + plotH - bh; const color = BAR_COLORS[i % BAR_COLORS.length]; const isZero = o.count === 0; const renderBh = isZero ? 2 : Math.max(bh, 0); const renderBy = isZero ? topPad + plotH - 2 : by; const fillOpacity = isZero ? '0.25' : '1'; parts += `${o.y}-${String(o.m + 1).padStart(2, '0')} · ${o.count}${isZero ? (isZh ? ' (进行中)' : ' (in progress)') : ''}`; if (o.count > 0) { parts += `${o.count}`; } const lbl = String(o.y).slice(2) + '.' + String(o.m + 1).padStart(2, '0'); parts += `${lbl}`; }); const totalAcq = months.reduce((s, o) => s + o.count, 0); const maxIdx = months.indexOf(months.reduce((mx, o) => o.count > mx.count ? o : mx, months[0])); const minIdx = months.indexOf(months.reduce((mn, o) => o.count < mn.count ? o : mn, months[0])); const maxMo = String(months[maxIdx].y).slice(2) + '.' + String(months[maxIdx].m + 1).padStart(2, '0'); const minMo = String(months[minIdx].y).slice(2) + '.' + String(months[minIdx].m + 1).padStart(2, '0'); const summaryHtml = `
${totalAcq} ${isZh ? '总计' : 'total'} ${isZh ? '峰值' : 'peak'} ${max} · ${maxMo} ${isZh ? '低谷' : 'low'} ${months[minIdx].count} · ${minMo}
`; return `
${T.ptHeatmapMini6m} · ${totalAcq}
${parts}
${summaryHtml}
`; } function formatLastPlayedShort(ts) { if (!ts || ts <= 0) return T.ptNever; const diff = Date.now() / 1000 - ts; const days = Math.floor(diff / 86400); if (days <= 0) return isZh ? '今天' : 'Today'; if (days === 1) return isZh ? '昨天' : 'Yesterday'; if (days < 30) return `${days} ${T.ptDays}`; if (days < 365) return isZh ? `${Math.floor(days / 30)} 个月前` : `${Math.floor(days / 30)} months ago`; return isZh ? `${Math.floor(days / 365)} 年前` : `${Math.floor(days / 365)} years ago`; } function renderPlaytimeRadar(games, stats) { const cx = 110, cy = 110, R = 80; const dimColors = ['#22d3ee', '#f59e0b', '#34d399', '#f472b6', '#38bdf8']; const dims = [ { label: isZh ? '库存规模' : 'Library', value: Math.min(100, (stats.totalGames / 500) * 100), display: stats.totalGames.toString(), color: dimColors[0] }, { label: isZh ? '游玩时长' : 'Hours', value: Math.min(100, (stats.totalHours / 5000) * 100), display: stats.totalHours.toFixed(0) + 'h', color: dimColors[1] }, { label: isZh ? '游玩率' : 'Play Rate', value: stats.playRate, display: stats.playRate + '%', color: dimColors[2] }, { label: isZh ? '深度完成' : 'Completion', value: stats.completionRate, display: stats.completionRate + '%', color: dimColors[3] }, { label: isZh ? '平均时长' : 'Avg Hours', value: Math.min(100, (stats.avgHours / 50) * 100), display: stats.avgHours.toFixed(1) + 'h', color: dimColors[4] }, ]; const n = dims.length; const angleStep = (Math.PI * 2) / n; const startAngle = -Math.PI / 2; let defsSvg = ` `; let gridSvg = ''; for (let layer = 1; layer <= 4; layer++) { const r = (R / 4) * layer; let pts = ''; for (let i = 0; i < n; i++) { const a = startAngle + i * angleStep; pts += `${cx + r * Math.cos(a)},${cy + r * Math.sin(a)} `; } gridSvg += ``; } let axisSvg = ''; let labelSvg = ''; for (let i = 0; i < n; i++) { const a = startAngle + i * angleStep; const x2 = cx + R * Math.cos(a); const y2 = cy + R * Math.sin(a); axisSvg += ``; const lr = R + 18; const lx = cx + lr * Math.cos(a); const ly = cy + lr * Math.sin(a); const dim = dims[i]; labelSvg += `${dim.label}`; labelSvg += `${dim.display}`; } let dataPts = ''; let pointSvg = ''; for (let i = 0; i < n; i++) { const a = startAngle + i * angleStep; const r = R * (dims[i].value / 100); const x = cx + r * Math.cos(a); const y = cy + r * Math.sin(a); dataPts += `${x},${y} `; pointSvg += ``; } return ` ${defsSvg} ${gridSvg} ${axisSvg} ${pointSvg} ${labelSvg} `; } function renderRadarStatsPanel(games, stats) { const statColors = ['#22d3ee', '#f59e0b', '#34d399', '#f472b6', '#38bdf8', '#fb7185']; const items = [ { icon: ICONS.library, label: isZh ? '游戏总数' : 'Total Games', val: stats.totalGames.toLocaleString(), pct: Math.min(100, (stats.totalGames / 500) * 100), color: statColors[0] }, { icon: ICONS.clock, label: isZh ? '总时长' : 'Total Hours', val: stats.totalHours.toFixed(1) + 'h', pct: Math.min(100, (stats.totalHours / 5000) * 100), color: statColors[1] }, { icon: ICONS.game, label: isZh ? '已启动' : 'Played', val: stats.playedCount.toLocaleString(), pct: stats.playRate, color: statColors[2] }, { icon: ICONS.trophy, label: isZh ? '深度游玩' : 'Deep Play', val: stats.longGames + (isZh ? '款' : ' games'), pct: stats.completionRate, color: statColors[3] }, { icon: ICONS.trend, label: isZh ? '平均时长' : 'Avg Hours', val: stats.avgHours.toFixed(1) + 'h', pct: Math.min(100, (stats.avgHours / 50) * 100), color: statColors[4] }, ]; return items.map(it => `
${it.icon}
${it.label}
${hbarRow({ cls: 'radar', pct: it.pct, color: `linear-gradient(90deg,${it.color}88,${it.color})` })}
${it.val}
`).join(''); } function computePlaytimeStats(games) { const totalGames = games.length; const realGamesForTotal = games.filter(g => !isDlc(g.appid)); const realGamesMinutes = realGamesForTotal.reduce((s, g) => s + (g.playtime || 0), 0); const allGamesMinutes = games.reduce((s, g) => s + (g.playtime || 0), 0); const totalMinutes = Math.max(realGamesMinutes, allGamesMinutes); const totalHours = totalMinutes / 60; const playedGames = games.filter(g => (g.playtime || 0) > 0); const playedCount = playedGames.length; const unplayedCount = totalGames - playedCount; const avgHours = playedCount > 0 ? totalHours / playedCount : 0; const longGames = playedGames.filter(g => (g.playtime || 0) >= 600).length; const playRate = totalGames > 0 ? Math.round(playedCount / totalGames * 100) : 0; const completionRate = playedCount > 0 ? Math.round(longGames / playedCount * 100) : 0; const ptPlayedPct = playRate; const ptUnplayedPct = totalGames > 0 ? Math.round(unplayedCount / totalGames * 100) : 0; const hardcoreGames = playedGames.filter(g => (g.playtime || 0) >= 6000).length; const hardcoreRate = playedCount > 0 ? Math.round(hardcoreGames / playedCount * 100) : 0; return { totalGames, totalHours, playedCount, unplayedCount, avgHours, longGames, playRate, completionRate, ptPlayedPct, ptUnplayedPct, hardcoreGames, hardcoreRate }; } function renderPlaytimeKpi(wrap, stats) { const kpiSection = document.createElement('div'); kpiSection.className = 'sglv-playtime-kpi-row'; kpiSection.innerHTML = kpiCards([ { icon: ICONS.clock, label: T.ptTotalHours, value: stats.totalHours.toFixed(1), sub: `${T.kpiHours} · ${T.kpiAvgHours} ${stats.avgHours.toFixed(1)}${T.kpiPerGame}`, color: 'amber' }, { icon: ICONS.trend, label: T.ptAvgHours, value: stats.avgHours.toFixed(1), sub: `${T.kpiHours}${T.kpiPerGame}`, color: 'blue' }, { icon: ICONS.game, label: T.ptPlayedCount, value: stats.playedCount.toLocaleString(), sub: `${T.kpiRate} ${stats.ptPlayedPct}%`, color: 'green' }, { icon: ICONS.library, label: T.ptUnplayedCount, value: stats.unplayedCount.toLocaleString(), sub: `${T.kpiRate} ${stats.ptUnplayedPct}%`, color: 'purple' }, { icon: ICONS.game, label: T.ptPlayRate, value: stats.playRate, unit: '%', sub: T.kpiPlayRateSub, color: 'cyan' }, { icon: ICONS.trophy, label: T.ptCompletion, value: stats.completionRate, unit: '%', sub: `${stats.longGames} ${T.kpiCompletionSub}`, color: 'rose' }, ], { tone: 'playtime' }); wrap.appendChild(kpiSection); } function renderPlaytimeRadarRow(wrap, games, stats) { const radarStats = { totalGames: stats.totalGames, totalHours: stats.totalHours, playedCount: stats.playedCount, longGames: stats.longGames, avgHours: stats.avgHours, playRate: stats.playRate, completionRate: stats.completionRate, hardcoreRate: stats.hardcoreRate }; const radarRow = document.createElement('div'); radarRow.className = 'sglv-radar-row'; radarRow.innerHTML = `
${ICONS.barChart || ''} ${isZh ? '玩家画像雷达' : 'Player Radar'}
${renderPlaytimeRadar(games, radarStats)}
${renderRadarStatsPanel(games, radarStats)}
`; wrap.appendChild(radarRow); } function renderPlaytimeTab(parent) { const wrap = document.createElement('div'); wrap.className = 'sglv-playtime-wrap'; if (state.ownedGames.length === 0) { wrap.innerHTML = emptyHtml(T.ptNoData); parent.appendChild(wrap); return; } const showFamilyShared = storage.getShowFamilyShared(); const cacheK = cacheKey('pt-games', showFamilyShared, state.ownedGames.length, state.ownedGames.reduce((s, g) => s + (g.playtime || 0), 0)); const games = getCached(cacheK, () => showFamilyShared ? [...state.ownedGames] : state.ownedGames.filter(g => isGameOwnedByMe(g))); const stats = computePlaytimeStats(games); renderPlaytimeKpi(wrap, stats); renderPlaytimeRadarRow(wrap, games, stats); renderPlaytimeChartRow(wrap, games); renderPlaytimeHeatmapRow(wrap, games); parent.appendChild(wrap); } function renderPlaytimeChartRow(wrap, games) { const totalGames = games.length; const chartRow = document.createElement('div'); chartRow.className = 'sglv-playtime-row'; const distCol = document.createElement('div'); distCol.className = 'sglv-playtime-col'; distCol.innerHTML = `
${ICONS.barChart} ${T.ptDistTitle}
`; chartRow.appendChild(distCol); let _distMode = 'hours'; const renderDonutByMode = (mode) => { const dd = calcPlaytimeDist(games, mode); if (mode === 'hours') { const totalH = dd.reduce((s, d) => s + d.count, 0); distCol.querySelector('#sglv-pt-donut').innerHTML = renderPlaytimeDonut(dd, totalH, 'h'); } else { distCol.querySelector('#sglv-pt-donut').innerHTML = renderPlaytimeDonut(dd, totalGames, ''); } }; renderDonutByMode(_distMode); distCol.querySelector('.sglv-trend-filter').addEventListener('click', e => { const btn = e.target.closest('[data-dist]'); if (!btn) return; distCol.querySelectorAll('[data-dist]').forEach(b => b.classList.remove('active')); btn.classList.add('active'); _distMode = btn.dataset.dist; renderDonutByMode(_distMode); }); const trendCol = document.createElement('div'); trendCol.className = 'sglv-playtime-col'; trendCol.innerHTML = `
${ICONS.trend} ${T.ptTrendTitle}
${renderPlaytimeTrend(games, 'month')}
`; chartRow.appendChild(trendCol); wrap.appendChild(chartRow); trendCol.querySelector('.sglv-trend-filter').addEventListener('click', e => { const btn = e.target.closest('.sglv-trend-btn'); if (!btn) return; trendCol.querySelectorAll('.sglv-trend-btn').forEach(b => b.classList.remove('active')); btn.classList.add('active'); trendCol.querySelector('#sglv-pt-trend').innerHTML = renderPlaytimeTrend(games, btn.dataset.mode); }); } function renderPlaytimeHeatmapRow(wrap, games) { const heatmapRow = document.createElement('div'); heatmapRow.className = 'sglv-heatmap-acquire-row'; wrap.appendChild(heatmapRow); const heatmapSection = document.createElement('div'); heatmapSection.className = 'sglv-heatmap-section'; heatmapSection.innerHTML = `
${ICONS.grid} ${T.ptLibHeatmap}
${createSkeleton('heatmap')}
`; heatmapRow.appendChild(heatmapSection); const acquireSection = document.createElement('div'); acquireSection.className = 'sglv-heatmap-mini-section'; acquireSection.id = 'sglv-pt-acquire-mini'; acquireSection.innerHTML = createSkeleton('monthly'); heatmapRow.appendChild(acquireSection); (async () => { const heatmapEl = heatmapSection.querySelector('#sglv-pt-heatmap'); try { const { games: familyGames, map: acquiredMap } = await buildCalibratedAcquiredMap(); if (!familyGames || familyGames.length === 0) { heatmapEl.innerHTML = emptyHtml(T.ptHeatmapNoData); acquireSection.innerHTML = emptyHtml(T.ptHeatmapNoData, { style: 'padding:24px' }); return; } const heatGames = games .filter(g => acquiredMap[g.appid]) .map(g => ({ appid: g.appid, acquiredTime: acquiredMap[g.appid] })); heatmapEl.innerHTML = renderAcquiredHeatmap(heatGames); acquireSection.innerHTML = renderMonthlyAcquireChart(heatGames); const scrollHmRight = () => requestAnimationFrame(() => { const s = heatmapEl.querySelector('.sglv-heatmap-scroll'); if (s) s.scrollLeft = s.scrollWidth; }); const hmFilter = heatmapEl.querySelector('.sglv-hm-year-filter'); const hmBody = heatmapEl.querySelector('.sglv-heatmap-body'); if (hmFilter && hmBody) { hmFilter.addEventListener('click', e => { const btn = e.target.closest('.sglv-hm-year-btn'); if (!btn || !_heatmapRenderCache || !_heatmapRenderCache.views) return; const view = _heatmapRenderCache.views[btn.dataset.year]; if (!view) return; hmFilter.querySelectorAll('.sglv-hm-year-btn').forEach(b => b.classList.remove('active')); btn.classList.add('active'); hmBody.innerHTML = view; scrollHmRight(); }); } scrollHmRight(); } catch (e) { console.warn('[SGLV] 入库热力图加载失败:', e); heatmapEl.innerHTML = emptyHtml(T.ptHeatmapNoData); acquireSection.innerHTML = emptyHtml(T.ptHeatmapNoData, { style: 'padding:24px' }); } })(); } // ====== 游玩数据标签页 (Top 20 + 全部游戏) ====== const PT_WEEK_MS = 7 * 24 * 3600 * 1000; const PT_RETRY_MS = 6 * 3600 * 1000; const PT_FAM_TOP_N = 20; const PT_SNAP_KEY = 'ptPlaytimeSnapshot'; const PT_ACQ_KEY = 'ptAcquiredMap'; const PT_FAM_KEY = 'ptFamilyMembers'; const PT_PERSIST_TTL = 365 * 24 * 3600 * 1000; let _ptSnap = null; let _ptRefreshInflight = null; let _ptAcq = null; let _ptAcqInflight = null; function ptSnapLoad() { if (!_ptSnap) { const raw = cacheGet(PT_SNAP_KEY); _ptSnap = (raw && raw.map) ? raw : { ts: 0, att: 0, map: {} }; } return _ptSnap; } function ptSnapSave() { try { cacheSet(PT_SNAP_KEY, _ptSnap, PT_PERSIST_TTL); } catch (e) { } } function ptSnapSeed(games) { const snap = ptSnapLoad(); if (Object.keys(snap.map).length > 0 || !games || !games.length) return; const map = {}; for (const g of games) map[g.appid] = [g.playtime || 0, g.lastPlayed || 0]; snap.map = map; ptSnapSave(); } function ptSnapApplyToGames(games) { const snap = ptSnapLoad(); let touched = 0; for (const g of games) { const v = snap.map[g.appid]; if (!v) continue; if ((g.playtime || 0) !== v[0]) { g.playtime = v[0]; touched++; } if ((g.lastPlayed || 0) !== v[1]) { g.lastPlayed = v[1]; touched++; } } return touched; } function ptRefreshPlaytime(force = false) { const snap = ptSnapLoad(); const now = Date.now(); if (!force) { if (now - (snap.ts || 0) < PT_WEEK_MS) return Promise.resolve({ ok: true, skipped: true, changed: 0 }); if (now - (snap.att || 0) < PT_RETRY_MS) return Promise.resolve({ ok: false, skipped: true, changed: 0 }); } if (_ptRefreshInflight) return _ptRefreshInflight; snap.att = now; ptSnapSave(); _ptRefreshInflight = (async () => { const steamId = getActiveSteamId(); if (!steamId) return { ok: false, changed: 0 }; const apiKey = storage.getApiKey(); const token = apiKey ? null : await getAccessToken().catch(() => null); const url = apiKey ? `https://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=${apiKey}&steamid=${steamId}&include_played_free_games=1&format=json` : (token ? `https://api.steampowered.com/IPlayerService/GetOwnedGames/v1/?access_token=${token}&steamid=${steamId}&include_played_free_games=1` : ''); if (!url) return { ok: false, changed: 0 }; let list = null; try { list = (await requestSteamAPI(url))?.response?.games || []; } catch (e) { return { ok: false, changed: 0 }; } if (!list.length) return { ok: false, changed: 0 }; let changed = 0; const next = {}; for (const g of list) { const pt = g.playtime_forever || 0; const lp = g.rtime_last_played || 0; next[g.appid] = [pt, lp]; const old = snap.map[g.appid]; if (!old || old[0] !== pt || old[1] !== lp) changed++; } snap.map = Object.assign({}, snap.map, next); snap.ts = Date.now(); ptSnapSave(); ptSnapApplyToGames(state.ownedGames || []); if (state.ownedGames && state.ownedGames.length) { try { storage.setCachedGames(state.ownedGames); } catch (e) { } } return { ok: true, changed, total: list.length }; })().catch(() => ({ ok: false, changed: 0 })).then(res => { _ptRefreshInflight = null; return res; }); return _ptRefreshInflight; } function ptGetAcquiredMap(force = false) { const now = Date.now(); if (!force) { if (_ptAcq && now - _ptAcq.ts < PT_WEEK_MS) return Promise.resolve(_ptAcq.map); const raw = cacheGet(PT_ACQ_KEY); if (raw && raw.map && now - raw.ts < PT_WEEK_MS) { _ptAcq = raw; return Promise.resolve(raw.map); } } if (_ptAcqInflight) return _ptAcqInflight; _ptAcqInflight = buildCalibratedAcquiredMap() .then(({ map }) => { const m = map || {}; if (Object.keys(m).length > 0) { _ptAcq = { ts: Date.now(), map: m }; try { cacheSet(PT_ACQ_KEY, _ptAcq, PT_PERSIST_TTL); } catch (e) { } } return m; }) .catch(() => ({})) .then(res => { _ptAcqInflight = null; return res; }); return _ptAcqInflight; } let _ptFamCache = null; function ptFamLoad() { if (!_ptFamCache) { const raw = cacheGet(PT_FAM_KEY); _ptFamCache = (raw && raw.members) ? raw : { members: {} }; } return _ptFamCache; } function ptFamSave(c) { _ptFamCache = c; try { cacheSet(PT_FAM_KEY, c, PT_PERSIST_TTL); } catch (e) { } } function ptFamIsStale(rec) { return !rec || Date.now() - (rec.ts || 0) >= PT_WEEK_MS; } function ptDayKey(ts) { const d = new Date(ts || Date.now()); const p = (n) => String(n).padStart(2, '0'); return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`; } function ptHistoryLoad() { if (!_ptHistory) { const raw = sglvIDB.get(PT_HISTORY_KEY, null); _ptHistory = (raw && raw.days) ? raw : { v: 1, days: {} }; } return _ptHistory; } function ptHistorySave() { ptHistoryPrune(); try { sglvIDB.set(PT_HISTORY_KEY, _ptHistory); } catch (e) { } } function ptHistoryPrune() { const h = ptHistoryLoad(); const keys = Object.keys(h.days).sort(); if (keys.length <= PT_HISTORY_DAYS) return 0; const drop = keys.slice(0, keys.length - PT_HISTORY_DAYS); drop.forEach(k => { delete h.days[k]; if (h.meta) delete h.meta[k]; }); return drop.length; } function ptHistoryRecord(games, opts) { const h = ptHistoryLoad(); const today = ptDayKey(); const list = Array.isArray(games) ? games : []; if (!list.length) return { ok: false, written: false, reason: 'empty' }; if (h.days[today]) return { ok: true, written: false, reason: 'same_day', day: today }; const prevKeys = Object.keys(h.days).sort(); const prevDay = prevKeys.length ? prevKeys[prevKeys.length - 1] : ''; const prev = prevDay ? (h.days[prevDay] || {}) : {}; const snap = {}; let changed = 0; for (const g of list) { const pt = Math.max(0, Math.round(Number(g.playtime) || 0)); if (pt <= 0) continue; snap[String(g.appid)] = pt; const before = Number(prev[String(g.appid)]) || 0; if (pt > before) changed++; } if (!Object.keys(snap).length) return { ok: false, written: false, reason: 'no_playtime' }; h.days[today] = snap; if (opts && opts.stale) { if (!h.meta) h.meta = {}; h.meta[today] = { stale: true, reason: String(opts.reason || 'stale'), ts: Date.now() }; } const pruned = ptHistoryPrune(); ptHistorySave(); return { ok: true, written: true, day: today, changed, pruned, prevDay }; } function ptHistoryCollect(games) { if (_ptHistoryInflight) return _ptHistoryInflight; _ptHistoryInflight = (async () => { try { const explicit = Array.isArray(games) && games.length > 0; const today = ptDayKey(); if (ptHistoryLoad().days[today]) { return { ok: true, written: false, reason: 'same_day', day: today }; } let refresh = null; if (!explicit) { const snap = ptSnapLoad(); if (Date.now() - (snap.ts || 0) >= PT_HISTORY_FRESH_MS) { ptSnapSeed(state.ownedGames || []); refresh = await ptRefreshPlaytime(true).catch(() => null); } } const stale = !!(refresh && refresh.ok === false); const list = explicit ? games : (state.ownedGames || []); const rec = ptHistoryRecord(list, stale ? { stale: true, reason: 'refresh_failed' } : null); if (stale && rec && rec.written) { rec.staleRefresh = true; console.warn('[SGLV] 每日快照:采集前刷新时长失败,今日样本标记为「观测不完整」' + '(差值可能跨多天重叠,不当作「今日未游玩」)'); } return rec; } catch (e) { return { ok: false, written: false, reason: 'error', error: String((e && e.message) || e) }; } })().then(r => { _ptHistoryInflight = null; return r; }); return _ptHistoryInflight; } // ====== 游玩数据标签页 ====== function ptPlaytimeMedian(list) { if (!list || list.length === 0) return 0; const asc = [...list].sort((a, b) => (a.playtime || 0) - (b.playtime || 0)); const mid = Math.floor(asc.length / 2); return asc.length % 2 ? (asc[mid].playtime || 0) : (((asc[mid - 1].playtime || 0) + (asc[mid].playtime || 0)) / 2); } function renderPlaydataTab(parent) { const wrap = document.createElement('div'); wrap.className = 'sglv-playtime-wrap sglv-pt-tab'; wrap.style.flexDirection = 'column'; if (state.ownedGames.length === 0) { wrap.innerHTML = emptyHtml(T.ptNoData); parent.appendChild(wrap); return; } const showFamilyShared = storage.getShowFamilyShared(); const cacheK = cacheKey('pt-games', showFamilyShared, state.ownedGames.length, state.ownedGames.reduce((s, g) => s + (g.playtime || 0), 0)); const games = getCached(cacheK, () => showFamilyShared ? [...state.ownedGames] : state.ownedGames.filter(g => isGameOwnedByMe(g))); const PTW = window.SGLVPTW; if (PTW && typeof PTW.mountInto === 'function') { PTW.mountInto('overview', wrap, { goTo(key, patch) { try { PTW.open(Object.assign({ tab: key }, patch || {})); } catch (e) { console.error('[PTW] 主面板钻取打开浮窗失败', e); } }, }); } else { wrap.innerHTML = ptwFallbackHtml(); } ptSnapSeed(games); ptRefreshPlaytime().then(res => { if (res && res.changed > 0 && state.activeTab === 'playdata') { try { renderBody(); } catch (e) { } sglvToast.info(T.ptWeeklyUpdated.replace('{n}', String(res.changed))); } }).catch(() => { }); parent.appendChild(wrap); } function openGameDataWindow() { let games = (state.ownedGames && state.ownedGames.length) ? state.ownedGames : storage.getCachedGames(); if (!games || games.length === 0) { sglvToast.warning(T.ptMenuDataEmpty); return; } const PTW = window.SGLVPTW; if (!PTW || typeof PTW.open !== 'function') { showPtwFallback(PTW_FALLBACK_REASON); return; } // 框架在、Tab 集库不在 → 打开也是空壳,直接说清原因(见顶部 ptwTabCount 注释) if (ptwTabCount() === 0) { showPtwFallback(PTW_TABS_MISSING_MSG); return; } const sortedGames = games.slice().sort((a, b) => (b.playtime || 0) - (a.playtime || 0)); PTW.open({ games: sortedGames, tab: 'all' }); if (PTW && typeof PTW.refreshGames === 'function') { if (!window._ptwGamesUpdatedBound) { window._ptwGamesUpdatedBound = true; document.addEventListener('sglv:games-updated', (ev) => { try { const next = (state.ownedGames && state.ownedGames.length) ? state.ownedGames : null; if (next && next.length > 0) PTW.refreshGames(next); } catch (e) { } }); } } } function wlEscape(s) { return escHtml(s); } let _wlPriceSym = ''; let _wlPriceCode = ''; function detectWlPriceSymbol(sampleText) { if (_wlPriceSym) return _wlPriceSym; const text = String(sampleText || document.querySelector('#header_wallet_balance')?.textContent || ''); const m = text.match(/(HK\$|NT\$|A\$|CDN\$|Mex\$|S\$|R\$|₩|€|£|¥|\$|₽|₹|฿|₫|RM)/); _wlPriceSym = m ? m[1] : '¥'; return _wlPriceSym; } function getWishlistOwnedIds() { try { const ids = getActiveOwnedAppIds(); if (ids && ids.size > 0) return ids; } catch { } return getDynamicStoreAppIds('owned'); } const WL_COMING_SOON_RE = /即将推出|即将宣布|coming soon|to be announced|\btba\b|\btbd\b|\bq[1-4]\b|summer|winter|spring|fall|autumn|^\s*\d{4}\s*$|年第[一二三四1-4]季度|[春夏秋冬]季/i; function wlResolveComingSoon(opts) { const rdTs = Number(opts.releaseTs) || 0; let soon = opts.soonFlag === true || opts.releaseSoon === true; if (!soon && rdTs > 0 && rdTs * 1000 > Date.now()) soon = true; if (!soon && opts.releaseStr && WL_COMING_SOON_RE.test(opts.releaseStr)) soon = true; const known = opts.soonFlag != null || opts.releaseSoon != null || !!opts.hasReleaseObj || rdTs > 0 || soon; return { soon, known, date: rdTs > 0 ? new Date(rdTs * 1000).toISOString().slice(0, 10) : '' }; } function normalizeWishlistEntry(info) { const appid = Number(info.appid) || 0; let finalPrice = 0, originalPrice = 0, discountPct = 0; let hasPriceInfo = false; const sub = Array.isArray(info.subs) && info.subs.length > 0 ? info.subs[0] : null; if (sub) { hasPriceInfo = true; finalPrice = (Number(sub.price) || 0) / 100; discountPct = Number(sub.discount_pct) || 0; originalPrice = (discountPct > 0 && discountPct < 100) ? finalPrice / (1 - discountPct / 100) : finalPrice; } if (info.best_purchase_option) { hasPriceInfo = true; const bpo = info.best_purchase_option; finalPrice = (Number(bpo.final_price_in_cents) || 0) / 100; originalPrice = (Number(bpo.original_price_in_cents) || 0) / 100; if (originalPrice === 0) originalPrice = finalPrice; discountPct = Number(bpo.discount_pct || 0); if (bpo.formatted_final_price) detectWlPriceSymbol(bpo.formatted_final_price); try { if (hasSglvCurrency && bpo.formatted_final_price) { const c = CUR.detectFromText(bpo.formatted_final_price); if (c) _wlPriceCode = c; } } catch {} } if (!Number.isFinite(finalPrice) || finalPrice < 0) finalPrice = 0; if (!Number.isFinite(originalPrice) || originalPrice < 0) originalPrice = finalPrice; if (!Number.isFinite(discountPct) || discountPct < 0 || discountPct > 100) discountPct = 0; const name = (info.name && String(info.name).trim()) || ''; const cs = wlResolveComingSoon({ soonFlag: info.is_coming_soon, releaseTs: info.release_date, releaseStr: info.release_string, }); return { appid, name: name || `App ${appid}`, priority: Number(info.priority) || 0, added: Number(info.added || info.date_added) || 0, finalPrice, originalPrice, discountPct, isFree: !!info.is_free || (hasPriceInfo && finalPrice === 0 && discountPct === 0), isComingSoon: cs.soon, releaseDate: cs.date, _releaseKnown: cs.known, type: String(info.type || 'game').toLowerCase(), tags: normalizeWishlistTags(info.tags), categoryIds: Array.isArray(info.category_ids) ? info.category_ids.map(id => String(id)).filter(s => s && s !== '0') : [], _priced: hasPriceInfo, }; } function normalizeWishlistTags(raw) { if (!Array.isArray(raw)) return []; return raw.map(t => typeof t === 'string' ? t : (t && (t.name || t.description)) || '').filter(Boolean).slice(0, 20); } async function fetchWishlistFromStore(steamId) { const out = []; if (!steamId) return out; if (!/^\d{17}$/.test(String(steamId))) { try { const html = await sglvGmFetchTextRetry(`https://store.steampowered.com/wishlist/id/${steamId}/`, { timeout: 30000 }); const m = html.match(/"steamid"\s*:\s*"(\d{17})"/) || html.match(/g_steamID\s*=\s*"(\d{17})"/); if (m) steamId = m[1]; else { console.warn('[SGLV] 愿望单页未解析到 steamid64:', steamId); return out; } } catch (e) { console.warn('[SGLV] vanity 解析失败:', steamId, e); return out; } } try { const data = await requestSteamAPI(`https://api.steampowered.com/IWishlistService/GetWishlist/v1/?steamid=${steamId}`); const arr = data?.response?.items || []; arr.forEach(it => { if (it && it.appid) out.push({ appid: Number(it.appid), priority: it.priority, date_added: it.date_added }); }); console.log(`[SGLV] IWishlistService: ${out.length} 条目`); } catch (e) { console.warn('[SGLV] IWishlistService 获取失败:', e); } return out; } async function fetchWishlistFromApi(steamId) { const out = []; if (!steamId || !/^\d{17}$/.test(String(steamId))) return out; try { const data = await requestSteamAPI(`https://api.steampowered.com/IWishlistService/GetWishlist/v1/?steamid=${steamId}`); const arr = data?.response?.items || []; arr.forEach(it => { if (it && it.appid) out.push({ appid: Number(it.appid), priority: it.priority, date_added: it.date_added }); }); } catch (e) { console.warn('[SGLV] IWishlistService 兜底获取失败:', e); } return out; } function parseWishlistCategoriesResponse(data) { const out = {}; const resp = (data && typeof data === 'object') ? (data.response || data) : {}; const list = resp.categories || resp.wishlist_categories || (Array.isArray(resp) ? resp : null); if (Array.isArray(list)) { list.forEach(c => { if (!c || typeof c !== 'object') return; const id = c.categoryid ?? c.category_id ?? c.id; const name = c.category_name ?? c.name ?? c.label; if (id != null && name) out[String(id)] = String(name); }); } else if (resp && typeof resp === 'object') { Object.entries(resp).forEach(([k, v]) => { if (typeof v === 'string' && v) out[k] = v; else if (v && typeof v === 'object') { const name = v.category_name ?? v.name; if (name) out[k] = String(name); } }); } return out; } async function fetchWishlistCategoryNames() { const tryUrls = []; try { const token = await getAccessToken(); if (token) tryUrls.push(`https://api.steampowered.com/IWishlistService/GetWishlistCategories/v1/?access_token=${token}`); } catch { } const apiKey = storage.getApiKey(); if (apiKey) tryUrls.push(`https://api.steampowered.com/IWishlistService/GetWishlistCategories/v1/?key=${apiKey}`); for (const url of tryUrls) { try { const data = await requestSteamAPI(url); const map = parseWishlistCategoriesResponse(data); if (Object.keys(map).length > 0) return map; } catch (e) { const errMsg = String(e.message || e); if (!errMsg.includes('返回 HTML') && !/\b(401|403)\b/.test(errMsg)) { console.warn('[SGLV] GetWishlistCategories 失败:', e); } } } return {}; } function refreshWishlistCategoryNames() { fetchWishlistCategoryNames().then(map => { if (Object.keys(map).length === 0) { return fetchWishlistFromPage(getActiveSteamId()).then(ssr => { if (ssr && ssr.categoryNames && Object.keys(ssr.categoryNames).length > 0) return ssr.categoryNames; return {}; }).catch(() => ({})); } return map; }).then(map => { if (Object.keys(map).length === 0) return; state.wishlistCategoryNames = map; cacheSet('wishlistCatNames', map, 7 * 24 * 3600 * 1000); if (state.activeTab === 'wishlist' && state.wishlistLoaded) renderWishlistSide(); }).catch(() => {}); } async function enrichWishlistFromStoreBrowse(items, cc, lang, onBatchDone) { const CHUNK = 100, CONCURRENCY = 3; const chunks = []; for (let i = 0; i < items.length; i += CHUNK) chunks.push(items.slice(i, i + CHUNK)); let processed = 0; const applyStoreBrowse = (item, si) => { if (!si || (si.success !== 1 && si.success !== true)) return; if (si.name && (item.name.startsWith('App ') || isZh)) item.name = String(si.name); if (typeof si.type === 'number') { item.type = ({ 0: 'game', 1: 'dlc', 2: 'software', 3: 'video', 4: 'series', 6: 'music', 7: 'tool', 8: 'video_series' })[si.type] || 'other'; } else if (si.type) { item.type = String(si.type).toLowerCase(); } if (si.is_free === true) item.isFree = true; const bpo = si.best_purchase_option; if (bpo) { const final = Number(bpo.final_price_in_cents) || 0; const original = Number(bpo.original_price_in_cents) || 0; item.finalPrice = final / 100; item.originalPrice = (original > 0 ? original : final) / 100; item.discountPct = Number(bpo.discount_pct || bpo.bundle_discount_pct || 0); if (item.originalPrice === item.finalPrice && item.discountPct > 0 && item.discountPct < 100) { item.originalPrice = item.finalPrice / (1 - item.discountPct / 100); } if (bpo.formatted_final_price) detectWlPriceSymbol(bpo.formatted_final_price); try { if (hasSglvCurrency && bpo.formatted_final_price) { const c = CUR.detectFromText(bpo.formatted_final_price); if (c) _wlPriceCode = c; } } catch {} item._priced = true; if (final === 0 && item.discountPct === 0) item.isFree = true; } const rel = si.release || null; const cs = wlResolveComingSoon({ soonFlag: si.is_coming_soon, releaseSoon: rel && rel.is_coming_soon, releaseTs: rel && rel.steam_release_date, hasReleaseObj: !!rel, }); if (cs.known) { item.isComingSoon = cs.soon; item._releaseKnown = true; if (cs.date) item.releaseDate = cs.date; } item._metaDone = true; if (si.name && isZh) { const nc = sglvGameNameCacheLoad(); nc[String(item.appid)] = { name: si.name, ts: Date.now() }; } }; await sglvSmartPool(chunks.map(chunk => async () => { try { const input = { ids: chunk.map(g => ({ appid: g.appid })), context: { language: lang, country_code: cc, steam_realm: 1 }, data_request: { include_release: true, include_all_purchase_options: true, include_platforms: true } }; const url = 'https://api.steampowered.com/IStoreBrowseService/GetItems/v1?input_json=' + encodeURIComponent(JSON.stringify(input)); const resp = await requestSteamAPI(url); const storeItems = resp?.response?.store_items || []; const map = new Map(); storeItems.forEach(si => { if (si && si.appid) map.set(Number(si.appid), si); }); chunk.forEach(g => { const si = map.get(Number(g.appid)); if (si) applyStoreBrowse(g, si); }); } catch (e) { console.warn('[SGLV] GetItems batch failed:', e); } processed += chunk.length; if (onBatchDone) onBatchDone(processed, items.length); await new Promise(r => setTimeout(r, 150)); }), CONCURRENCY); if (isZh) { try { sglvGameNameCacheSave(); } catch (e2) { console.warn('[SGLV] 中文名缓存写入失败:', e2); } } } async function enrichWishlistMeta(items, onBatchDone) { const need = items.filter(i => !i._metaDone); if (need.length === 0) { if (onBatchDone) onBatchDone(0, 0); return; } let cc = 'CN'; try { const win = (typeof unsafeWindow !== 'undefined') ? unsafeWindow : window; cc = win.g_strCountryCode || 'CN'; } catch { } const lang = isZh ? 'schinese' : 'english'; await enrichWishlistFromStoreBrowse(need, cc, lang, onBatchDone); const leftovers = items.filter(i => !i._metaDone && (i.name.startsWith('App ') || !i._priced || !i._releaseKnown)); if (leftovers.length > 0) { const filters = 'name,type,is_free,genres,price_overview,release_date'; const enrichBatch = async (batch) => { const data = await requestSteamAPI(`https://store.steampowered.com/api/appdetails?appids=${batch.map(g => g.appid).join(',')}&filters=${filters}&cc=${cc}&l=${lang}`); batch.forEach(g => { const d = data?.[g.appid]; if (!d || !d.success || !d.data) return; const dd = d.data; if (dd.name && (g.name.startsWith('App ') || isZh)) g.name = dd.name; if (dd.type) g.type = String(dd.type).toLowerCase(); if (dd.is_free === true) g.isFree = true; if (Array.isArray(dd.genres) && dd.genres.length > 0) { g.tags = dd.genres.map(x => x.description).filter(Boolean); } const po = dd.price_overview; if (po && typeof po.final === 'number') { g.finalPrice = po.final / 100; g.originalPrice = (po.initial || po.final) / 100; g.discountPct = po.discount_percent || 0; g.currency = po.currency || g.currency; g.isFree = false; g._priced = true; if (po.final_formatted) detectWlPriceSymbol(po.final_formatted); try { if (hasSglvCurrency && po.final_formatted) { const c = CUR.detectFromText(po.final_formatted); if (c) _wlPriceCode = c; } } catch {} } if (dd.release_date && typeof dd.release_date.coming_soon !== 'undefined') { g.isComingSoon = !!dd.release_date.coming_soon; g._releaseKnown = true; if (dd.release_date.date) g.releaseDate = dd.release_date.date; } g._metaDone = true; if (dd.name && isZh) { const nc = sglvGameNameCacheLoad(); nc[String(g.appid)] = { name: dd.name, ts: Date.now() }; } }); if (isZh) { try { sglvGameNameCacheSave(); } catch (e2) { console.warn('[SGLV] 中文名缓存写入失败:', e2); } } }; let done = 0; const batchTasks = []; for (let i = 0; i < leftovers.length; i += 25) { const batch = leftovers.slice(i, i + 25); batchTasks.push(async () => { try { await enrichBatch(batch); } catch { } done += batch.length; if (onBatchDone) onBatchDone(done, leftovers.length); await new Promise(r => setTimeout(r, 250)); }); } await sglvSmartPool(batchTasks, 2); const retry = leftovers.filter(i => !i._metaDone); for (let i = 0; i < retry.length; i += 10) { const batch = retry.slice(i, i + 10); try { await enrichBatch(batch); } catch { } await new Promise(r => setTimeout(r, 300)); } } if (onBatchDone) onBatchDone(need.length, need.length); } let _wlDynamicRefreshing = false; let _wlDynamicLastRefresh = 0; const WL_DYNAMIC_REFRESH_INTERVAL = 6 * 3600 * 1000; async function refreshWishlistDynamicFields(items) { if (_wlDynamicRefreshing || !items || items.length === 0) return; if (Date.now() - _wlDynamicLastRefresh < WL_DYNAMIC_REFRESH_INTERVAL) return; _wlDynamicRefreshing = true; try { let cc = 'CN'; try { const win = (typeof unsafeWindow !== 'undefined') ? unsafeWindow : window; cc = win.g_strCountryCode || 'CN'; } catch { } const lang = isZh ? 'schinese' : 'english'; const refreshItems = items.map(g => { const copy = Object.assign({}, g); copy._priced = false; copy._releaseKnown = false; copy._metaDone = true; return copy; }); const before = new Map(items.map(g => [g.appid, { finalPrice: g.finalPrice, discountPct: g.discountPct, isComingSoon: g.isComingSoon, isFree: g.isFree, }])); await enrichWishlistFromStoreBrowse(refreshItems, cc, lang); let changed = false; const origMap = new Map(items.map(g => [g.appid, g])); refreshItems.forEach(refreshed => { const orig = origMap.get(refreshed.appid); if (!orig) return; const oldSnap = before.get(orig.appid); if (refreshed._priced && refreshed.finalPrice !== oldSnap.finalPrice) { orig.finalPrice = refreshed.finalPrice; orig.originalPrice = refreshed.originalPrice; orig.discountPct = refreshed.discountPct; orig.isFree = refreshed.isFree; orig._priced = true; changed = true; } if (refreshed._releaseKnown && !!refreshed.isComingSoon !== !!oldSnap.isComingSoon) { orig.isComingSoon = refreshed.isComingSoon; orig._releaseKnown = true; if (refreshed.releaseDate) orig.releaseDate = refreshed.releaseDate; changed = true; } }); if (changed) { cacheSet('wishlistGames', items, CACHE_TTL.wishlist); renderWishlistSections(); } } catch (e) { console.warn('[SGLV] 后台刷新动态字段失败:', e); } finally { _wlDynamicRefreshing = false; _wlDynamicLastRefresh = Date.now(); } } function wlExtractQueryDataFromText(text) { try { const ssrMatch = text.match(/]*id="valve-ssr-data"[^>]*>([\s\S]*?)<\/script>/); if (ssrMatch) { const ssr = JSON.parse(ssrMatch[1]); if (ssr && ssr.renderContext && typeof ssr.renderContext.queryData === 'string') { const qd = JSON.parse(ssr.renderContext.queryData); if (qd && Array.isArray(qd.queries)) return qd.queries; } if (Array.isArray(ssr && ssr.loaderData)) { for (const seg of ssr.loaderData) { if (typeof seg !== 'string' || !seg.includes('queryData')) continue; try { const segObj = JSON.parse(seg); const qdStr = segObj && segObj.queryData; if (typeof qdStr === 'string') { const qd = JSON.parse(qdStr); if (qd && Array.isArray(qd.queries)) return qd.queries; } } catch (_) { } } } console.warn('[SGLV] valve-ssr-data 已找到但未含 queries(愿望单可能为空或加载失败)'); } let idx = 0; while ((idx = text.indexOf('JSON.parse(', idx)) !== -1) { const start = text.indexOf('"', idx + 11); if (start === -1) { idx++; continue; } let i = start + 1, inEsc = false; while (i < text.length) { const c = text[i]; if (inEsc) inEsc = false; else if (c === '\\') inEsc = true; else if (c === '"') break; i++; } const escaped = text.substring(start + 1, i).replace(/[\n\r]/g, ''); let decoded = ''; try { decoded = JSON.parse('"' + escaped + '"'); } catch (_) { idx = i + 1; continue; } if (typeof decoded === 'string' && decoded.includes('queryData')) { try { const outer = JSON.parse(decoded); if (outer && typeof outer.queryData === 'string') { const qd = JSON.parse(outer.queryData); if (qd && Array.isArray(qd.queries)) return qd.queries; } } catch (_) { console.warn('[SGLV] SSR queryData 解析失败'); } } idx = i + 1; } } catch (e) { console.warn('[SGLV] wlExtractQueryDataFromText failed:', e); } return null; } function wlExtractFromQueries(queries) { const entries = []; const tagNameMap = {}; const storeItemCache = new Map(); const categoryNames = {}; for (const query of queries) { if (!query || !query.state || !query.state.data) continue; const data = query.state.data; const qKey = query.queryKey || []; if (qKey[0] === 'WishlistSortedFiltered') { const payload = Array.isArray(data) ? { items: data } : data; if (payload && Array.isArray(payload.items)) entries.push(...payload.items); } if (qKey[0] === 'LocalizedTagNames' && typeof data === 'object' && !Array.isArray(data)) { Object.assign(tagNameMap, data); } if (qKey[0] === 'wishlistcategories') { const list = Array.isArray(data) ? data : (data && (data.categories || data.wishlist_categories)); if (Array.isArray(list)) { Object.assign(categoryNames, parseWishlistCategoriesResponse({ categories: list })); } else if (data && typeof data === 'object') { Object.assign(categoryNames, parseWishlistCategoriesResponse(data)); } } if (qKey.length >= 3 && qKey[0] === 'StoreItem') { const appId = parseInt(String(qKey[1]).replace(/^app_/, ''), 10); if (!appId || isNaN(appId)) continue; if (!storeItemCache.has(appId)) storeItemCache.set(appId, { _appId: appId }); storeItemCache.get(appId)[qKey[2]] = data; } } const seen = new Set(); const unique = entries.filter(e => e && e.appid && !seen.has(e.appid) && seen.add(e.appid)); return { entries: unique, storeItemCache, tagNameMap, categoryNames }; } function applyStoreItemToWlEntry(item, storeData, tagNameMap) { if (!item || !storeData) return; const di = storeData.default_info; if (di) { if (di.name && (item.name.startsWith('App ') || isZh)) item.name = String(di.name); if (typeof di.type === 'number') { item.type = ({ 0: 'game', 1: 'dlc', 2: 'software', 3: 'video', 4: 'series', 6: 'music', 7: 'tool', 8: 'video_series' })[di.type] || 'other'; } else if (di.type) { item.type = String(di.type).toLowerCase(); } if (di.is_free === true) item.isFree = true; const bpo = di.best_purchase_option; if (bpo) { const final = Number(bpo.final_price_in_cents) || 0; const original = Number(bpo.original_price_in_cents) || 0; item.finalPrice = final / 100; item.originalPrice = (original > 0 ? original : final) / 100; item.discountPct = Number(bpo.discount_pct || bpo.bundle_discount_pct || 0); if (bpo.formatted_final_price) detectWlPriceSymbol(bpo.formatted_final_price); try { if (hasSglvCurrency && bpo.formatted_final_price) { const c = CUR.detectFromText(bpo.formatted_final_price); if (c) _wlPriceCode = c; } } catch {} item._priced = true; if (final === 0 && item.discountPct === 0) item.isFree = true; } const rel = di.release || di.release_date; const cs = wlResolveComingSoon({ soonFlag: di.is_coming_soon, releaseSoon: rel && rel.is_coming_soon, releaseTs: rel && (rel.steam_release_date || rel.date), hasReleaseObj: !!rel, }); if (cs.known) { item.isComingSoon = cs.soon; item._releaseKnown = true; if (cs.date) item.releaseDate = cs.date; } } const tt = storeData.top_tags; if (Array.isArray(tt) && tt.length > 0) { item.tags = tt.map(t => { if (!t) return ''; if (t.name) return t.name; if (t.tagid != null) return tagNameMap[t.tagid] || ''; return ''; }).filter(Boolean).slice(0, 20); } item._metaDone = isZh ? false : true; } async function fetchWishlistFromPage(steamId) { if (!steamId) return null; const isProfileId = /^\d{17}$/.test(String(steamId)); const url = isProfileId ? `https://store.steampowered.com/wishlist/profiles/${steamId}/` : `https://store.steampowered.com/wishlist/id/${steamId}/`; try { const text = await sglvGmFetchTextRetry(url, { timeout: 30000 }); const queries = wlExtractQueryDataFromText(text); if (!queries) { console.warn('[SGLV] 愿望单页面未找到 SSR queryData'); return null; } const data = wlExtractFromQueries(queries); console.log(`[SGLV] 愿望单页面 SSR: ${data.entries.length} 条目, ${data.storeItemCache.size} 详情, ${Object.keys(data.tagNameMap).length} 标签, ${Object.keys(data.categoryNames || {}).length} 自定义类别`); if (data.entries.length === 0) return null; return data; } catch (e) { console.warn('[SGLV] fetchWishlistFromPage 失败:', e); return null; } } function wlGetTypeKey(type) { const t = String(type || 'game').toLowerCase(); if (t === 'game' || t === '0') return 'game'; if (t === 'dlc' || t === '1') return 'dlc'; if (t === 'software' || t === '2') return 'software'; return 'other'; } let _wlRenderThrottleTimer = null; let _wlRenderPiggyback = false; function scheduleWishlistRender() { if (_wlRenderThrottleTimer) { _wlRenderPiggyback = true; return; } _wlRenderThrottleTimer = setTimeout(() => { _wlRenderThrottleTimer = null; try { renderWishlistSections(); } catch (e) { console.warn('[SGLV] 节流渲染失败:', e); } if (_wlRenderPiggyback) { _wlRenderPiggyback = false; scheduleWishlistRender(); } }, 800); } async function wlFetchHistoryPrices(appid) { const cacheKey = 'wlHistory_' + appid; const cached = cacheGet(cacheKey); if (cached) return cached; const itad = window.SGLVITAD; if (itad && typeof itad.hasApiKey === 'function' && itad.hasApiKey()) { try { const itadId = await itad.lookupItadId(appid); if (itadId) { const [gameInfo, historyData] = await Promise.all([ itad.fetchGameInfo(itadId), itad.fetchPriceHistory(itadId, { country: 'CN', shops: [itad.SHOP_STEAM] }), ]); if (historyData && (historyData.discounts || []).length) { const result = { history: historyData.history || [], discounts: historyData.discounts || [], lowest: historyData.lowest || null, source: 'itad', }; cacheSet(cacheKey, result, 24 * 3600 * 1000); return result; } } } catch (e) { console.warn('[SGLV] ITAD 历史价格失败:', e); } } try { const data = await sglvGmFetchRetry('https://api.augmentedsteam.com/prices/v2', { method: 'POST', timeout: 12000, headers: { 'Content-Type': 'application/json' }, data: JSON.stringify({ country: 'CN', apps: [parseInt(appid, 10)], subs: [], bundles: [], voucher: false, shops: [] }), }); const aug = data?.prices?.[`app/${appid}`]; if (aug) { const lowest = aug.lowest || (aug.historic && aug.historic[0]) || null; const result = { history: [], discounts: [], lowest, source: 'aug' }; cacheSet(cacheKey, result, 24 * 3600 * 1000); return result; } } catch (e) { console.warn('[SGLV] AugmentedSteam 历史价格失败:', e); } return null; } function wlPredictNextLow(discounts) { const DAY = 86400000; const pts = (discounts || []) .map(d => ({ date: new Date(d.date).getTime(), cut: Number(d.cut) || 0 })) .filter(p => p.date > 0 && !isNaN(p.date)) .sort((a, b) => a.date - b.date || a.cut - b.cut); const lows = []; let run = 0; pts.forEach(p => { if (p.cut > run) { run = p.cut; lows.push(p); } }); if (lows.length === 0) return null; const median = arr => { if (!arr.length) return null; const s = [...arr].sort((a, b) => a - b); const m = s.length >> 1; return s.length % 2 ? s[m] : Math.round((s[m - 1] + s[m]) / 2); }; const now = Date.now(); const gaps = []; for (let i = 1; i < lows.length; i++) gaps.push(Math.max(1, Math.round((lows[i].date - lows[i - 1].date) / DAY))); let gap, conf; if (gaps.length >= 2) { gap = median(gaps); conf = gaps.length >= 3 ? 'high' : 'mid'; } else { gap = gaps[0] || 180; conf = 'low'; } gap = Math.max(1, gap); const last = lows[lows.length - 1]; const nextTs = last.date + gap * DAY; const daysLeft = Math.ceil((nextTs - now) / DAY); const sinceLast = Math.ceil((now - last.date) / DAY); const state = daysLeft >= 0 ? 'upcoming' : ((sinceLast / gap) < 2 ? 'due' : 'stalled'); const steps = []; for (let i = 1; i < lows.length; i++) steps.push(lows[i].cut - lows[i - 1].cut); const step = median(steps) || 10; const nextCut = Math.min(100, Math.max(last.cut, Math.round((last.cut + step) / 5) * 5)); return { gapDays: gap, daysLeft, sinceLast, state, conf, lastCut: last.cut, nextCut, nLows: lows.length }; } function wlRenderCurveSvg(history, lowest) { const pts = (history || []) .map(h => ({ t: new Date(h.date).getTime(), price: Number(h.price) || 0, cut: Number(h.cut) || 0 })) .filter(p => p.t > 0 && !isNaN(p.t) && p.price > 0) .sort((a, b) => a.t - b.t); if (pts.length < 2) return ''; const W = 680, H = 230, PL = 46, PR = 12, PT = 12, PB = 24; const t0 = pts[0].t, t1 = pts[pts.length - 1].t; const lowestPrice = lowest && Number(lowest.price) > 0 ? Number(lowest.price) : null; let pMin = Math.min(...pts.map(p => p.price), lowestPrice != null ? lowestPrice : Infinity); let pMax = Math.max(...pts.map(p => p.price)); if (pMax <= pMin) pMax = pMin + 1; const x = t => PL + (t - t0) / Math.max(1, t1 - t0) * (W - PL - PR); const y = p => PT + (1 - (p - pMin) / (pMax - pMin)) * (H - PT - PB); const path = pts.map((p, i) => `${i ? 'L' : 'M'}${x(p.t).toFixed(1)},${y(p.price).toFixed(1)}`).join(' '); let out = ''; for (let i = 0; i <= 2; i++) { const p = pMin + (pMax - pMin) * i / 2; const yy = y(p).toFixed(1); out += `${p.toFixed(0)}`; } const fmtDate = t => { const d = new Date(t); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`; }; for (let i = 0; i <= 4; i++) { const t = t0 + (t1 - t0) * i / 4; out += `${fmtDate(t)}`; } if (lowestPrice != null && lowestPrice >= pMin) { const ly = y(lowestPrice).toFixed(1); out += `LOW`; } pts.forEach(p => { if (p.cut > 0) out += ``; }); out += ``; return `${out}`; } async function openWlPriceCurve(appid, name, ev) { if (ev) { ev.preventDefault(); ev.stopPropagation(); } const old = document.getElementById('sglv-wl-curve-overlay'); if (old) old.remove(); const overlay = document.createElement('div'); overlay.id = 'sglv-wl-curve-overlay'; overlay.className = 'sglv-overlay'; overlay.innerHTML = `

${T.wlCurveTitle} · ${wlEscape(name)}

${T.wlCurveLoading}
`; document.body.appendChild(overlay); overlay.addEventListener('click', e => { if (e.target === overlay) overlay.remove(); }); overlay.querySelector('.sglv-close-btn').addEventListener('click', () => overlay.remove()); const body = overlay.querySelector('#sglv-wl-curve-body'); try { const data = await wlFetchHistoryPrices(appid); if (!data) { body.innerHTML = `
${T.wlCurveNoData}
`; return; } const pred = wlPredictNextLow(data.discounts); const svg = wlRenderCurveSvg(data.history, data.lowest); let html = svg || `
${T.wlCurveNoData}
`; if (pred) { const stateText = pred.state === 'upcoming' ? `${T.wlPredictIn} ${Math.max(0, pred.daysLeft)} ${T.wlPredictDays}` : (pred.state === 'due' ? T.wlPredictDue : T.wlPredictStalled); const confText = pred.conf === 'high' ? T.wlConfHigh : (pred.conf === 'mid' ? T.wlConfMid : T.wlConfLow); const stateColor = pred.state === 'due' ? '#f59e0b' : (pred.state === 'upcoming' ? '#66c0f4' : '#94a3b8'); html += `
📈 ${T.wlPredictTitle} ${stateText} ${confText}
${T.wlPredictLast}: -${pred.lastCut}% ${T.wlPredictGap}: ~${pred.gapDays} ${T.wlPredictDays} ${T.wlPredictNextCut}: -${pred.nextCut}% ${T.wlCurveSource}: ${data.source}
`; } body.innerHTML = html; } catch (e) { body.innerHTML = `
${wlEscape(String(e.message || e))}
`; } } unsafeWindow._sglvOpenWlCurve = function(ev, appid, name) { openWlPriceCurve(appid, name, ev); }; function wlCurveBtnHtml(g) { const safeName = wlEscape(g.name || '').replace(/'/g, ''').replace(/"/g, '"'); return ``; } async function loadWishlistGames(force = false) { if (state.wishlistLoading) return; if (!force) { const cached = cacheGet('wishlistGames'); if (cached && Array.isArray(cached) && cached.length > 0) { state.wishlistGames = cached; state.wishlistLoaded = true; markSearchIndexDirty(); state.wishlistCategoryNames = cacheGet('wishlistCatNames') || {}; renderWishlistSections(); refreshWishlistCategoryNames(); refreshWishlistDynamicFields(cached); return; } } state.wishlistLoading = true; state.wishlistLoadStage = 1; state.wishlistLoadProgress = 0; renderWishlistGamesList(); try { const steamId = getActiveSteamId(); let ssrData = null; try { ssrData = await fetchWishlistFromPage(steamId); } catch (e) { console.warn('[SGLV] 愿望单页面 SSR 抓取失败:', e); } let raw = (ssrData && ssrData.entries.length > 0) ? ssrData.entries : []; const storeItemCache = ssrData ? ssrData.storeItemCache : new Map(); const tagNameMap = ssrData ? ssrData.tagNameMap : {}; state.wishlistLoadStage = 2; renderWishlistGamesList(); let apiEntries = []; if (steamId) { try { apiEntries = await fetchWishlistFromStore(steamId); } catch (e) { console.warn('[SGLV] IWishlistService 获取失败:', e); } } if (raw.length === 0) { raw = apiEntries; } else if (apiEntries.length > 0) { const apiMap = new Map(apiEntries.map(e => [Number(e.appid), e])); raw = raw.map(ssrEntry => { const apiEntry = apiMap.get(Number(ssrEntry.appid)); if (!apiEntry) return ssrEntry; return Object.assign({}, apiEntry, { date_added: ssrEntry.date_added, priority: ssrEntry.priority, category_ids: ssrEntry.category_ids, }); }); const rawIds = new Set(raw.map(e => Number(e.appid))); for (const [apid, e] of apiMap) { if (!rawIds.has(apid)) raw.push(e); } } if (raw.length === 0) raw = await fetchWishlistFromApi(steamId); if (raw.length === 0) { raw = [...getDynamicStoreAppIds('wishlist')].map(appid => ({ appid })); } const items = raw.map(entry => { const item = normalizeWishlistEntry(entry); if (storeItemCache.has(item.appid)) { applyStoreItemToWlEntry(item, storeItemCache.get(item.appid), tagNameMap); } return item; }).filter(i => i.appid > 0); items.sort((a, b) => { const pa = a.priority > 0 ? a.priority : 999999; const pb = b.priority > 0 ? b.priority : 999999; if (pa !== pb) return pa - pb; return a.name.localeCompare(b.name, 'zh-CN'); }); state.wishlistGames = items; state.wishlistLoaded = true; state.wishlistLoading = false; state.wishlistLoadStage = 0; state.wishlistLoadProgress = 0; markSearchIndexDirty(); const _ssrCatNames = (ssrData && ssrData.categoryNames) || {}; if (Object.keys(_ssrCatNames).length > 0) { state.wishlistCategoryNames = Object.assign({}, cacheGet('wishlistCatNames') || {}, _ssrCatNames); cacheSet('wishlistCatNames', state.wishlistCategoryNames, 7 * 24 * 3600 * 1000); } else { state.wishlistCategoryNames = cacheGet('wishlistCatNames') || {}; } renderWishlistSections(); refreshWishlistCategoryNames(); state.wishlistLoadStage = 3; await enrichWishlistMeta(items, (done, total) => { updateWishlistProgress(done, total); scheduleWishlistRender(); }); cacheSet('wishlistGames', items, CACHE_TTL.wishlist); updateWishlistProgress(0, 0); state.wishlistLoadStage = 0; state.wishlistLoadProgress = 0; renderWishlistSections(); sglvToast.success(T.wlFetchSuccess.replace('{n}', items.length)); } catch (e) { console.error('[SGLV] 愿望单获取失败:', e); sglvToast.error(T.wlFetchFail); state.wishlistLoading = false; state.wishlistLoadStage = 0; state.wishlistLoadProgress = 0; renderWishlistSections(); } } function updateWishlistProgress(done, total) { const el = document.getElementById('sglv-wl-progress'); if (!el) return; if (!done || !total || done >= total) { el.textContent = ''; return; } el.textContent = (isZh ? '正在补全资料… ' : 'Enriching… ') + done + '/' + total; } function regionCurrencyOfCountry(cc) { try { if (SGLV_API.getRegionCurrency) return SGLV_API.getRegionCurrency(cc) || ''; } catch { } return ''; } function wlCurrencyOf(g) { try { const cc = (typeof unsafeWindow !== 'undefined' && unsafeWindow.g_strCountryCode) || ''; return (g && g.currency) || regionCurrencyOfCountry(cc) || _wlPriceCode || 'CNY'; } catch { return _wlPriceCode || 'CNY'; } } function computeWishlistStats() { const games = state.wishlistGames; const ownedIds = getWishlistOwnedIds(); const total = games.length; const inLibrary = games.filter(g => ownedIds.has(Number(g.appid)) || ownedIds.has(String(g.appid))).length; const isOwned = g => ownedIds.has(Number(g.appid)) || ownedIds.has(String(g.appid)); const paidItems = games.filter(g => !g.isFree && g.finalPrice > 0); const prices = paidItems.map(g => g.finalPrice).sort((a, b) => a - b); const _wlTargetCode = wlCurrencyOf(null); const _wlUsdRates = (hasSglvCurrency && SGLV_API.getUsdRates) ? SGLV_API.getUsdRates() : null; const _wlMultiCur = hasSglvCurrency && !!_wlUsdRates; const _rawPriceSum = prices.reduce((s, p) => s + p, 0); let totalValue = _rawPriceSum; let _wlAgg = null; let _convPrice = null; if (_wlMultiCur) { _convPrice = g => { const code = g.currency || wlCurrencyOf(g); if (code === _wlTargetCode) return g.finalPrice; const v = CUR.convert(g.finalPrice, code, _wlTargetCode, _wlUsdRates); return Number.isFinite(v) ? v : null; }; const _aggItems = paidItems.map(g => ({ finalPrice: g.finalPrice, currency: g.currency || wlCurrencyOf(g) })); _wlAgg = CUR.aggregate(_aggItems, _wlTargetCode, _wlUsdRates, { amountKey: 'finalPrice', codeKey: 'currency' }); totalValue = _wlAgg.total; } const avgPrice = paidItems.length > 0 ? _rawPriceSum / paidItems.length : 0; const medianPrice = prices.length > 0 ? (prices.length % 2 === 0 ? (prices[prices.length / 2 - 1] + prices[prices.length / 2]) / 2 : prices[Math.floor(prices.length / 2)]) : 0; const discountedItems = games.filter(g => g.discountPct > 0); const discounts = discountedItems.map(g => g.discountPct); const avgDiscount = discounts.length > 0 ? discounts.reduce((s, d) => s + d, 0) / discounts.length : 0; const maxDiscount = discounts.length > 0 ? Math.max(...discounts) : 0; const discountedRate = total > 0 ? discountedItems.length / total : 0; const freeCount = games.filter(g => g.isFree).length; const freeRate = total > 0 ? freeCount / total : 0; const comingSoonItems = games.filter(g => g.isComingSoon); const comingSoonCount = comingSoonItems.length; const comingSoonRate = total > 0 ? comingSoonCount / total : 0; const purchaseRate = total > 0 ? inLibrary / total : 0; const addedDates = games.filter(g => g.added > 0).map(g => g.added); const earliestAdded = addedDates.length > 0 ? Math.min(...addedDates) : 0; const tagMap = new Map(); games.forEach(g => (g.tags || []).forEach(t => tagMap.set(t, (tagMap.get(t) || 0) + 1))); const topTags = [...tagMap.entries()].sort((a, b) => b[1] - a[1]).slice(0, 15); const monthMap = new Map(); games.forEach(g => { if (g.added > 0) { const d = new Date(g.added * 1000); const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`; monthMap.set(key, (monthMap.get(key) || 0) + 1); } }); const timeline = [...monthMap.entries()].sort((a, b) => a[0].localeCompare(b[0])).slice(-12); const yearMap = new Map(); games.forEach(g => { if (g.added > 0) { const year = String(new Date(g.added * 1000).getFullYear()); yearMap.set(year, (yearMap.get(year) || 0) + 1); } }); const addedByYear = [...yearMap.entries()].sort((a, b) => a[0].localeCompare(b[0])); const _bucketPrices = _wlMultiCur ? paidItems.map(g => _convPrice(g)) : null; const priceBuckets = _wlMultiCur ? [ { label: T.wlPriceFree, count: games.filter(g => g.isFree).length, color: '#6366f1' }, { label: T.wlPriceLt50, count: _bucketPrices.filter(p => p != null && p < 50).length, color: '#10b981' }, { label: T.wlPrice50_100, count: _bucketPrices.filter(p => p != null && p >= 50 && p < 100).length, color: '#22c55e' }, { label: T.wlPrice100_200, count: _bucketPrices.filter(p => p != null && p >= 100 && p < 200).length, color: '#84cc16' }, { label: T.wlPrice200_500, count: _bucketPrices.filter(p => p != null && p >= 200 && p < 500).length, color: '#f59e0b' }, { label: T.wlPriceGte500, count: _bucketPrices.filter(p => p != null && p >= 500).length, color: '#ef4444' }, ] : [ { label: T.wlPriceFree, count: games.filter(g => g.isFree).length, color: '#6366f1' }, { label: T.wlPriceLt50, count: paidItems.filter(g => g.finalPrice < 50).length, color: '#10b981' }, { label: T.wlPrice50_100, count: paidItems.filter(g => g.finalPrice >= 50 && g.finalPrice < 100).length, color: '#22c55e' }, { label: T.wlPrice100_200, count: paidItems.filter(g => g.finalPrice >= 100 && g.finalPrice < 200).length, color: '#84cc16' }, { label: T.wlPrice200_500, count: paidItems.filter(g => g.finalPrice >= 200 && g.finalPrice < 500).length, color: '#f59e0b' }, { label: T.wlPriceGte500, count: paidItems.filter(g => g.finalPrice >= 500).length, color: '#ef4444' }, ]; const discountBuckets = [ { label: T.wlDisc0, count: games.filter(g => g.discountPct === 0).length, color: '#64748b' }, { label: T.wlDisc1_25, count: games.filter(g => g.discountPct > 0 && g.discountPct <= 25).length, color: '#84cc16' }, { label: T.wlDisc26_50, count: games.filter(g => g.discountPct > 25 && g.discountPct <= 50).length, color: '#22c55e' }, { label: T.wlDisc51_75, count: games.filter(g => g.discountPct > 50 && g.discountPct <= 75).length, color: '#f59e0b' }, { label: T.wlDisc76plus, count: games.filter(g => g.discountPct > 75).length, color: '#ef4444' }, ]; const typeMap = new Map(); games.forEach(g => { const key = wlGetTypeKey(g.type); typeMap.set(key, (typeMap.get(key) || 0) + 1); }); const typeDist = [...typeMap.entries()].sort((a, b) => b[1] - a[1]); const catNames = state.wishlistCategoryNames || {}; const catStatsMap = new Map(); games.forEach(g => { const ids = Array.isArray(g.categoryIds) ? g.categoryIds : []; if (ids.length === 0) return; ids.forEach(id => { if (!catStatsMap.has(id)) catStatsMap.set(id, { count: 0, totalValue: 0, paidCount: 0, discountCount: 0, comingSoonCount: 0, inLibraryCount: 0, freeCount: 0, }); const cs = catStatsMap.get(id); cs.count++; if (!g.isFree && g.finalPrice > 0) { if (_wlMultiCur) { const cv = _convPrice(g); if (cv != null) cs.totalValue += cv; } else { cs.totalValue += g.finalPrice; } cs.paidCount++; } if (g.discountPct > 0) cs.discountCount++; if (g.isComingSoon) cs.comingSoonCount++; if (isOwned(g)) cs.inLibraryCount++; if (g.isFree) cs.freeCount++; }); }); const categoryStats = [...catStatsMap.entries()] .map(([id, cs]) => ({ id, name: catNames[id] || `#${id}`, ...cs, avgPrice: cs.paidCount > 0 ? cs.totalValue / cs.paidCount : 0, pct: total > 0 ? cs.count / total : 0, })) .sort((a, b) => b.count - a.count); const uncatGames = games.filter(g => { const ids = Array.isArray(g.categoryIds) ? g.categoryIds : []; return ids.length === 0; }); const uncatPaid = uncatGames.filter(g => !g.isFree && g.finalPrice > 0); const uncategorizedStats = { count: uncatGames.length, totalValue: _wlMultiCur ? uncatPaid.reduce((s, g) => { const cv = _convPrice(g); return cv != null ? s + cv : s; }, 0) : uncatPaid.reduce((s, g) => s + g.finalPrice, 0), discountCount: uncatGames.filter(g => g.discountPct > 0).length, comingSoonCount: uncatGames.filter(g => g.isComingSoon).length, inLibraryCount: uncatGames.filter(g => isOwned(g)).length, freeCount: uncatGames.filter(g => g.isFree).length, pct: total > 0 ? uncatGames.length / total : 0, }; return { total, inLibrary, purchaseRate, totalValue, avgPrice, medianPrice, discountedCount: discountedItems.length, discountedRate, avgDiscount, maxDiscount, freeCount, freeRate, comingSoonCount, comingSoonRate, earliestAdded, topTags, timeline, addedByYear, priceBuckets, discountBuckets, typeDist, categoryStats, uncategorizedStats, byCurrency: _wlAgg ? _wlAgg.byCurrency : {}, unsupported: _wlAgg ? _wlAgg.unsupported : [], targetCode: _wlTargetCode, }; } function computeWishlistStatsCached() { const games = state.wishlistGames; let finalPriceSum = 0, originalPriceSum = 0, discountSum = 0, addedSum = 0; const curSet = new Set(); const n = games ? games.length : 0; for (let i = 0; i < n; i++) { const g = games[i]; finalPriceSum += (g && g.finalPrice) || 0; originalPriceSum += (g && g.originalPrice) || 0; discountSum += (g && g.discountPct) || 0; addedSum += (g && g.added) || 0; curSet.add((g && g.currency) || wlCurrencyOf(g)); } const catNames = state.wishlistCategoryNames || {}; const catKey = Object.keys(catNames).sort().map(k => `${k}:${catNames[k]}`).join(','); let ratesHour = 0; try { if (SGLV_API.getRatesTs) ratesHour = Math.floor((SGLV_API.getRatesTs() || 0) / 3600000); } catch { ratesHour = 0; } const curFp = [...curSet].sort().join(',') + '|' + ratesHour + '|' + wlCurrencyOf(null); const sig = `${n}|${finalPriceSum}|${originalPriceSum}|${discountSum}|${addedSum}|${catKey}|${curFp}`; return getBizCached('biz_wishlist_stats', 2, sig, () => computeWishlistStats()); } function getFilteredWishlist() { const q = state.wishlistSearch.toLowerCase().trim(); const ownedIds = getWishlistOwnedIds(); return state.wishlistGames.filter(g => { if (q && !g.name.toLowerCase().includes(q) && !String(g.appid).includes(q)) return false; if (state.wishlistFilter === 'discount' && !(g.discountPct > 0)) return false; if (state.wishlistFilter === 'inlibrary' && !(ownedIds.has(Number(g.appid)) || ownedIds.has(String(g.appid)))) return false; if (state.wishlistFilter === 'coming' && !g.isComingSoon) return false; if (state.wishlistFilter === 'category' && state.wishlistCategoryFilter) { const ids = Array.isArray(g.categoryIds) ? g.categoryIds : []; if (state.wishlistCategoryFilter === '__uncat__') { if (ids.length > 0) return false; } else { if (!ids.includes(state.wishlistCategoryFilter)) return false; } } return true; }); } function renderCloudSaveTab(parent) { const wrap = document.createElement('div'); wrap.className = 'sglv-cs-wrap'; if (!window.SGLVCloudSave || !_cloudSaveReady) { wrap.innerHTML = `
⚠️
${isZh ? '云存档模块未加载' : 'Cloud save module not loaded'}
${isZh ? '请检查 @require 外部库配置' : 'Please check @require external library config'}
`; parent.innerHTML = ''; parent.appendChild(wrap); return; } if (state.cloudSaveLoading) { wrap.innerHTML = `
${T.csFetching}
`; parent.innerHTML = ''; parent.appendChild(wrap); return; } if (state.cloudSaveError) { const isLogin = state.cloudSaveError === 'LOGIN_REQUIRED'; wrap.innerHTML = `
${isLogin ? '🔐' : '⚠️'}
${isLogin ? T.csLoginRequired : T.csFetchFail}
`; parent.innerHTML = ''; parent.appendChild(wrap); wrap.querySelector('#sglv-cs-retry').addEventListener('click', () => loadCloudSaveData(true)); return; } if (!state.cloudSaveLoaded || !state.cloudSaveGames || state.cloudSaveGames.length === 0) { wrap.innerHTML = `
☁️
${T.csNoData}
`; parent.innerHTML = ''; parent.appendChild(wrap); wrap.querySelector('#sglv-cs-fetch').addEventListener('click', () => loadCloudSaveData(true)); return; } renderCloudSaveDashboard(parent, wrap); } function prepareCloudSaveTabData() { if (!window.SGLVCloudSave || !_cloudSaveReady) return; if (state.cloudSaveLoading || state.cloudSaveError) return; if (!state.cloudSaveLoaded || !state.cloudSaveGames || state.cloudSaveGames.length === 0) { _initCloudSaveTab(); return; } if (Date.now() - (state.cloudSaveBgRefreshAt || 0) >= CLOUDSAVE_BG_REFRESH_INTERVAL) { _backgroundRefreshCloudSave(); } _enrichCloudSaveFileCounts(); } async function loadCloudSaveData(force) { state.cloudSaveLoading = true; state.cloudSaveError = null; renderBody(); try { const result = await window.SGLVCloudSave.fetchGlobalCloudSaves(force); state.cloudSaveGames = result.games || []; state.cloudSaveSource = result.source; state.cloudSaveLastUpdate = result.lastUpdate; state.cloudSaveDiff = result.diff; state.cloudSaveLoaded = true; state.cloudSaveError = null; showToast(T.csFetchSuccess.replace('{n}', state.cloudSaveGames.length)); _enrichCloudSaveFileCounts(); } catch (err) { state.cloudSaveError = err.message || 'UNKNOWN_ERROR'; console.error('[SGLV] 云存档数据获取失败:', err); } finally { state.cloudSaveLoading = false; renderBody(); } } async function _tryLoadCloudSaveFromIDBCache() { if (state.cloudSaveLoaded && state.cloudSaveGames.length > 0) return; if (!window.SGLVCloudSave?.getCachedCloudSavesAsync) return; try { const cached = await window.SGLVCloudSave.getCachedCloudSavesAsync(); if (cached && cached.games && cached.games.length > 0) { cached.games.forEach(g => { if (g._status) g._status = null; }); state.cloudSaveGames = cached.games; state.cloudSaveSource = 'cache'; state.cloudSaveLastUpdate = cached.lastUpdate || 0; state.cloudSaveFileCountAt = cached.fileCountAt || 0; state.cloudSaveDiff = null; state.cloudSaveLoaded = true; state.cloudSaveError = null; console.log(`[SGLV] 云存档 IDB 缓存命中: ${cached.games.length} 款游戏, 更新于 ${new Date(cached.lastUpdate).toLocaleString()}`); renderBody(); return true; } } catch (e) { console.warn('[SGLV] 云存档 IDB 缓存加载失败:', e); } return false; } async function _backgroundRefreshCloudSave() { if (state.cloudSaveBgRefresh) return; if (!window.SGLVCloudSave?.fetchGlobalCloudSaves) return; if (Date.now() - (state.cloudSaveBgRefreshAt || 0) < CLOUDSAVE_BG_REFRESH_INTERVAL) { return; } state.cloudSaveBgRefresh = true; state.cloudSaveBgRefreshAt = Date.now(); const prevCount = state.cloudSaveGames.length; try { const result = await window.SGLVCloudSave.fetchGlobalCloudSaves(false, { additive: true, silent: true }); if (result && result.games) { state.cloudSaveGames = result.games; state.cloudSaveSource = result.source; state.cloudSaveLastUpdate = result.lastUpdate; state.cloudSaveDiff = result.diff; state.cloudSaveLoaded = true; state.cloudSaveError = null; const newCount = result.games.length - prevCount; if (newCount > 0) { console.log(`[SGLV] 云存档后台增量更新: 新增 ${newCount} 款, 总计 ${result.games.length} 款`); showToast(T.csBgRefreshDone.replace('{n}', newCount)); } renderBody(); } } catch (err) { console.warn('[SGLV] 云存档后台刷新失败:', err); } finally { state.cloudSaveBgRefresh = false; } } let _csFileCountAbort = null; async function _enrichCloudSaveFileCounts() { if (state.cloudSaveFileCountEnriching) return; if (!window.SGLVCloudSave?.enrichFileCounts) return; if (Date.now() - (state.cloudSaveFileCountAt || 0) < CLOUDSAVE_FILECOUNT_INTERVAL) return; const needEnrich = state.cloudSaveGames.some(g => g.appid && (!g.fileCount || g.fileCount === 0)); if (!needEnrich) return; state.cloudSaveFileCountEnriching = true; state.cloudSaveFileCountAt = Date.now(); _csFileCountAbort = new AbortController(); let renderTimer = null; try { console.log(`[SGLV] 云存档文件数填充开始 (${state.cloudSaveGames.filter(g => !g.fileCount || g.fileCount === 0).length} 款待获取)`); await window.SGLVCloudSave.enrichFileCounts(state.cloudSaveGames, { concurrency: 3, delay: 500, signal: _csFileCountAbort.signal, onProgress: (updatedGame, allGames) => { if (!renderTimer) { renderTimer = setTimeout(() => { renderTimer = null; if (state.activeTab !== 'cloudsave') return; document.querySelectorAll('.sglv-cs-game-list .sglv-cs-game-row[data-appid]').forEach(row => { const g = state.cloudSaveGames.find(x => String(x.appid) === row.dataset.appid); if (!g) return; const files = row.querySelector('.sglv-cs-game-files'); if (files) files.textContent = `${g.fileCount || 0} ${T.csFiles}`; }); }, 800); } }, }); console.log('[SGLV] 云存档文件数填充完成'); } catch (err) { console.warn('[SGLV] 云存档文件数填充失败:', err); } finally { state.cloudSaveFileCountEnriching = false; _csFileCountAbort = null; if (state.activeTab === 'cloudsave') renderBody(); } } async function _initCloudSaveTab() { const loaded = await _tryLoadCloudSaveFromIDBCache(); if (!loaded) { await loadCloudSaveData(false); return; } _backgroundRefreshCloudSave(); _enrichCloudSaveFileCounts(); } function renderCloudSaveDashboard(parent, wrap) { const games = state.cloudSaveGames; const fmt = window.SGLVCloudSave.formatSize; const _ownedGameMap = {}; if (state.ownedGames && state.ownedGames.length > 0) { state.ownedGames.forEach(g => { if (g.appid) _ownedGameMap[String(g.appid)] = g.name || ''; }); } function resolveGameName(csGame) { const appid = String(csGame.appid || ''); if (_ownedGameMap[appid]) return _ownedGameMap[appid]; const raw = csGame.name || ''; if (raw && raw !== '显示文件' && raw !== 'Show Files' && !/^App\s+\d+$/.test(raw)) return raw; return `App ${appid}`; } function getCsCoverUrl(appId, kind) { if (window.SGLVCoverFallback && window.SGLVCoverFallback.getCoverUrl) { return window.SGLVCoverFallback.getCoverUrl(appId, kind || 'capsule'); } return `https://cdn.cloudflare.steamstatic.com/steam/apps/${appId}/capsule_231x87.jpg`; } const totalGames = games.length; const totalSize = games.reduce((s, g) => s + (g.sizeBytes || 0), 0); const totalFiles = games.reduce((s, g) => s + (g.fileCount || 0), 0); const avgSize = totalGames > 0 ? Math.round(totalSize / totalGames) : 0; const sizeBuckets = [0, 0, 0, 0, 0]; const sizeLabels = [T.csSizeLt1, T.csSize1_10, T.csSize10_50, T.csSize50_100, T.csSize100plus]; games.forEach(g => { const mb = (g.sizeBytes || 0) / (1024 * 1024); if (mb < 1) sizeBuckets[0]++; else if (mb < 10) sizeBuckets[1]++; else if (mb < 50) sizeBuckets[2]++; else if (mb < 100) sizeBuckets[3]++; else sizeBuckets[4]++; }); const fileBuckets = [0, 0, 0, 0]; const fileLabels = [T.csFilesLt3, T.csFiles3_5, T.csFiles5_10, T.csFiles10plus]; games.forEach(g => { const f = g.fileCount || 0; if (f < 3) fileBuckets[0]++; else if (f <= 5) fileBuckets[1]++; else if (f <= 10) fileBuckets[2]++; else fileBuckets[3]++; }); const top10 = [...games].sort((a, b) => (b.sizeBytes || 0) - (a.sizeBytes || 0)).slice(0, 10); const maxTopSize = top10[0]?.sizeBytes || 1; const diff = state.cloudSaveDiff; const hasDiff = diff && (diff.new.length || diff.changed.length || diff.removed.length); const sourceLabel = state.cloudSaveSource === 'web' ? T.csSourceWeb : T.csSourceCache; const updatedTime = state.cloudSaveLastUpdate ? new Date(state.cloudSaveLastUpdate).toLocaleString() : ''; const fileCountTime = state.cloudSaveFileCountAt ? new Date(state.cloudSaveFileCountAt).toLocaleString() : ''; const side = document.createElement('div'); side.className = 'sglv-cs-side'; side.innerHTML = `
${kpiCards([ { icon: ICONS.cloud, label: T.csTotalGames, value: totalGames.toLocaleString(), sub: isZh ? '云存档游戏' : 'cloud games', color: 'purple' }, { icon: ICONS.package, label: T.csTotalSize, value: fmt(totalSize), sub: isZh ? '全部存档' : 'all saves', color: 'cyan' }, { icon: ICONS.card, label: T.csTotalFiles, value: totalFiles.toLocaleString(), suffixHtml: state.cloudSaveFileCountEnriching ? ' ' : '', sub: state.cloudSaveFileCountEnriching ? (isZh ? '正在获取文件数…' : 'Fetching file counts…') : (isZh ? '存档文件' : 'save files'), color: 'amber' }, { icon: ICONS.trend, label: T.csAvgSize, value: fmt(avgSize), sub: isZh ? '平均每款' : 'avg per game', color: 'rose' }, ], { tone: 'playtime' })}
${T.csTopSizes}
${top10.map((g, i) => { const gName = resolveGameName(g); return `
${i + 1} ${hbarRow({ cls: 'cs10', name: gName, nameTitle: gName, pct: ((g.sizeBytes || 0) / maxTopSize * 100).toFixed(1), val: fmt(g.sizeBytes || 0) })}
`; }).join('')}
${T.csSizeDist}
${sizeBuckets.map((v, i) => { const mx = Math.max(...sizeBuckets, 1); return `
${v} ${sizeLabels[i]}
`; }).join('')}
${T.csFileDist}
${fileBuckets.map((v, i) => { const mx = Math.max(...fileBuckets, 1); return `
${v} ${fileLabels[i]}
`; }).join('')}
${hasDiff ? `
${diff.new.length ? `${T.csBadgeNew} ${diff.new.length}` : ''} ${diff.changed.length ? `${T.csBadgeChanged} ${diff.changed.length}` : ''} ${diff.removed.length ? `${T.csBadgeRemoved} ${diff.removed.length}` : ''}
` : ''} `; const listWrap = document.createElement('div'); listWrap.className = 'sglv-cs-list-wrap'; const toolbar = buildListToolbar({ cls: 'sglv-cs-toolbar', search: { cls: 'sglv-cs-search', placeholder: T.csSearch, value: state.cloudSaveSearch || '' }, sort: { cls: 'sglv-cs-sort', value: state.cloudSaveSort, options: [ { value: 'sizeDesc', label: T.csSortSizeDesc }, { value: 'sizeAsc', label: T.csSortSizeAsc }, { value: 'filesDesc', label: T.csSortFilesDesc }, { value: 'nameAsc', label: T.csSortNameAsc }, ], }, onChange: ({ type, value }) => { if (type === 'input') state.cloudSaveSearch = value; else state.cloudSaveSort = value; renderGameList(); }, }); const listHeader = document.createElement('div'); listHeader.className = 'sglv-cs-list-header'; listHeader.innerHTML = `${T.csGameList}${games.length}`; const listEl = document.createElement('div'); listEl.className = 'sglv-cs-game-list'; listWrap.appendChild(toolbar); listWrap.appendChild(listHeader); listWrap.appendChild(listEl); const _csRowCoverHtml = (g, gName) => { return g.appid ? `${gName}` : ''; }; const _csRowInfoHtml = (g, gName) => ` ${gName} App ${g.appid}`; const _csRowStatsHtml = (g) => { const badge = g._status === 'new' ? `${T.csBadgeNew}` : g._status === 'changed' ? `${T.csBadgeChanged}` : ''; return `
${badge} ${g.fileCount || 0} ${T.csFiles} ${g.totalSize || fmt(g.sizeBytes || 0)} ${isZh ? '去下载' : 'Download'}
`; }; function renderGameList() { let list = [...state.cloudSaveGames]; if (state.cloudSaveSearch) { const q = state.cloudSaveSearch.toLowerCase(); list = list.filter(g => { const resolved = resolveGameName(g).toLowerCase(); return resolved.includes(q) || String(g.appid).includes(q) || (g.name || '').toLowerCase().includes(q); }); } switch (state.cloudSaveSort) { case 'sizeAsc': list.sort((a, b) => (a.sizeBytes || 0) - (b.sizeBytes || 0)); break; case 'filesDesc': list.sort((a, b) => (b.fileCount || 0) - (a.fileCount || 0)); break; case 'nameAsc': list.sort((a, b) => resolveGameName(a).localeCompare(resolveGameName(b))); break; default: list.sort((a, b) => (b.sizeBytes || 0) - (a.sizeBytes || 0)); } if (list.length === 0) { listEl.innerHTML = `
${isZh ? '无匹配结果' : 'No matching results'}
`; return; } listEl.innerHTML = renderGameView(list, { viewMode: 'list', rowsOnly: true, listItemCls: 'sglv-cs-game-row', listInfoCls: 'sglv-cs-game-info', itemAttrs: g => ` data-appid="${g.appid}"`, imgHtml: g => _csRowCoverHtml(g, resolveGameName(g)), bodyHtml: g => _csRowInfoHtml(g, resolveGameName(g)), trailingHtml: g => _csRowStatsHtml(g), }); } wrap.appendChild(side); wrap.appendChild(listWrap); parent.innerHTML = ''; parent.appendChild(wrap); renderGameList(); const refreshBtn = wrap.querySelector('#sglv-cs-refresh'); if (refreshBtn) { refreshBtn.addEventListener('click', () => { state.cloudSaveFileCountAt = 0; loadCloudSaveDataAdditive(true); }); } const exportGvBtn = wrap.querySelector('#sglv-cs-export-gv'); if (exportGvBtn) { exportGvBtn.addEventListener('click', () => { exportCloudSavesForGameVault(); }); } if (window.SGLVCoverFallback) { window.SGLVCoverFallback.bindErrorHandler(wrap, (img) => { if (img.nextElementSibling) img.nextElementSibling.style.display = 'flex'; }); } else { console.warn('[SGLV] SGLVCoverFallback 未加载 — 封面降级不可用 (请检查 @require sglv-cover-fallback.lib.js)'); } } async function loadCloudSaveDataAdditive(force) { state.cloudSaveLoading = true; state.cloudSaveError = null; renderBody(); try { const result = await window.SGLVCloudSave.fetchGlobalCloudSaves(force, { additive: true, silent: !force }); state.cloudSaveGames = result.games || []; state.cloudSaveSource = result.source; state.cloudSaveLastUpdate = result.lastUpdate; state.cloudSaveDiff = result.diff; state.cloudSaveLoaded = true; state.cloudSaveError = null; showToast(T.csFetchSuccess.replace('{n}', state.cloudSaveGames.length)); _enrichCloudSaveFileCounts(); } catch (err) { state.cloudSaveError = err.message || 'UNKNOWN_ERROR'; console.error('[SGLV] 云存档数据获取失败:', err); } finally { state.cloudSaveLoading = false; renderBody(); } } function renderWishlistTab(parent) { const wrap = document.createElement('div'); wrap.className = 'sglv-wishlist-wrap'; const side = document.createElement('div'); side.className = 'sglv-wl-side'; side.innerHTML = `
`; wrap.appendChild(side); const main = document.createElement('div'); main.className = 'sglv-wl-main'; const filterBtns = [ { key: 'all', label: T.all }, { key: 'discount', label: T.wlFilterDiscount }, { key: 'coming', label: T.wlFilterComingSoon }, { key: 'inlibrary', label: T.wlFilterInLibrary }, ]; const toolbar = buildListToolbar({ search: { id: 'sglv-wishlist-search', placeholder: T.wlSearch, value: wlEscape(state.wishlistSearch) }, views: { modes: [ { mode: 'card', title: T.cardView, icon: ICONS.grid }, { mode: 'cover', title: T.coverView, icon: ICONS.cover }, { mode: 'list', title: T.listView, icon: ICONS.list }, ], value: state.wishlistViewMode, idPrefix: 'sglv-wl-', }, extraHtml: ``, onChange: ({ type, value }) => { if (type === 'input') { state.wishlistSearch = value; state.wishlistPage = 1; renderWishlistGamesList(); } else { state.wishlistViewMode = value; renderWishlistGamesList(); } }, }); main.appendChild(toolbar); const filterBar = document.createElement('div'); filterBar.className = 'sglv-filter-bar'; filterBar.innerHTML = `
${filterBtns.map(fb => `` ).join('')}
`; main.appendChild(filterBar); const content = document.createElement('div'); content.className = 'sglv-content'; content.id = 'sglv-wishlist-content'; main.appendChild(content); wrap.appendChild(main); parent.appendChild(wrap); if (!state.wishlistLoaded) { createSkeleton('wishlist', wrap); } filterBar.querySelectorAll('.sglv-wl-filter-btn').forEach(btn => { btn.addEventListener('click', () => { state.wishlistFilter = btn.dataset.filter; state.wishlistCategoryFilter = null; state.wishlistPage = 1; filterBar.querySelectorAll('.sglv-wl-filter-btn').forEach(b => b.classList.remove('active')); btn.classList.add('active'); renderWishlistSide(); renderWishlistGamesList(); }); }); toolbar.querySelector('#sglv-wl-refresh').addEventListener('click', () => { sglvToast.info(isZh ? '正在刷新愿望单…' : 'Refreshing wishlist…'); loadWishlistGames(true); }); if (!state.wishlistLoaded && !state.wishlistLoading) { loadWishlistGames(); } else { renderWishlistSections(); } } function renderWishlistSections() { if (state.activeTab !== 'wishlist' || !document.getElementById('sglv-wishlist-content')) return; renderWishlistKpi(); renderWishlistSide(); renderWishlistGamesList(); } function renderWishlistKpi() { const el = document.getElementById('sglv-wishlist-kpi'); if (!el) return; if (!state.wishlistLoaded) { el.innerHTML = ''; return; } const s = computeWishlistStatsCached(); const sym = detectWlPriceSymbol(); const multiCurHint = (s.unsupported && s.unsupported.length > 0) ? ` · ${escHtml(T.wlMultiCurHint)}` : ''; const fmtPrice = (v) => { if (v >= 10000) return `${sym}${(v / 1000).toFixed(1)}k`; if (v >= 1000) return `${sym}${Math.round(v).toLocaleString()}`; return `${sym}${v.toFixed(0)}`; }; const earliestStr = s.earliestAdded > 0 ? new Date(s.earliestAdded * 1000).toLocaleDateString(isZh ? 'zh-CN' : 'en-US') : '-'; el.className = 'sglv-wl-kpi-row'; el.innerHTML = kpiCards([ { icon: ICONS.heart, value: s.total.toLocaleString(), label: T.wlTotal, sub: `${T.wlEarliest} ${earliestStr}`, color: 'kpi-total' }, { icon: ICONS.dollar, value: fmtPrice(s.totalValue), label: T.wlKpiTotalValue, sub: `${T.wlAvgPrice} ${fmtPrice(s.avgPrice)} · ${T.wlMedian} ${fmtPrice(s.medianPrice)}`, subSuffixHtml: multiCurHint, color: 'kpi-value' }, { icon: ICONS.tag, value: s.discountedCount.toLocaleString(), label: T.wlKpiOnSale, sub: `${T.wlRate} ${(s.discountedRate * 100).toFixed(1)}% · ${T.wlAvgDisc} ${s.avgDiscount.toFixed(0)}% · ${T.wlMaxDisc} ${s.maxDiscount}%`, color: 'kpi-sale' }, { icon: ICONS.rocket, value: s.comingSoonCount.toLocaleString(), label: T.wlKpiComingSoon, sub: `${T.wlRate} ${(s.comingSoonRate * 100).toFixed(1)}%`, color: 'kpi-coming' }, { icon: ICONS.library, value: s.inLibrary.toLocaleString(), label: T.wlKpiInLib, sub: `${T.wlPurchaseRate} ${(s.purchaseRate * 100).toFixed(1)}%`, color: 'kpi-lib' }, { icon: ICONS.calendar, value: s.addedByYear.length, label: isZh ? '添加年份' : 'Years', sub: s.addedByYear.length > 0 ? `${s.addedByYear[0][0]} - ${s.addedByYear[s.addedByYear.length - 1][0]}` : '-', color: 'kpi-year' }, ], { tone: 'wl' }); } const WL_TAG_COLORS = ['#66c0f4', '#a78bfa', '#34d399', '#f59e0b', '#ef4444', '#ec4899', '#06b6d4', '#f97316', '#84cc16', '#6366f1', '#14b8a6', '#e11d48', '#8b5cf6', '#0ea5e9', '#10b981']; function renderWishlistSide() { const tagsEl = document.getElementById('sglv-wl-tags'); const tlEl = document.getElementById('sglv-wl-timeline'); const upEl = document.getElementById('sglv-wl-upcoming'); const ytEl = document.getElementById('sglv-wl-year-trend'); const pdEl = document.getElementById('sglv-wl-price-dist'); const ddEl = document.getElementById('sglv-wl-disc-dist'); const csEl = document.getElementById('sglv-wl-catstats'); if (!tagsEl || !tlEl) return; if (!state.wishlistLoaded) { [tagsEl, tlEl, upEl, ytEl, pdEl, ddEl, csEl].forEach(e => { if (e) e.innerHTML = ''; }); return; } const s = computeWishlistStatsCached(); if (ytEl) { const maxY = s.addedByYear.length > 0 ? Math.max(...s.addedByYear.map(x => x[1])) : 1; ytEl.innerHTML = `
${ICONS.calendar} ${T.wlAddedByYear}
${s.addedByYear.length === 0 ? emptyHtml(T.wlNoData, { style: 'padding:8px' }) : `
${s.addedByYear.map(([year, count]) => `
${count}
${year}
`).join('')}
`} `; } if (pdEl) { const maxP = s.priceBuckets.length > 0 ? Math.max(...s.priceBuckets.map(b => b.count)) : 1; const hasP = s.priceBuckets.some(b => b.count > 0); pdEl.innerHTML = `
${ICONS.dollar} ${T.wlPriceDist}
${!hasP ? emptyHtml(T.wlNoData, { style: 'padding:8px' }) : `
${s.priceBuckets.map(b => `
${b.count}
${b.label}
`).join('')}
`} `; } if (ddEl) { const maxD = s.discountBuckets.length > 0 ? Math.max(...s.discountBuckets.map(b => b.count)) : 1; const hasD = s.discountBuckets.some(b => b.count > 0); ddEl.innerHTML = `
${ICONS.tag} ${T.wlDiscountDist}
${!hasD ? emptyHtml(T.wlNoData, { style: 'padding:8px' }) : `
${s.discountBuckets.map(b => `
${b.count}
${b.label}
`).join('')}
`} `; } const maxTag = s.topTags.length > 0 ? s.topTags[0][1] : 1; tagsEl.innerHTML = `
${ICONS.barChart} ${T.wlTopTags}
${s.topTags.length === 0 ? emptyHtml(T.wlNoData, { style: 'padding:8px' }) : s.topTags.map(([name, count], i) => hbarRow({ cls: 'wl', name: wlEscape(name), nameTitle: wlEscape(name), pct: (count / maxTag * 100).toFixed(1), color: WL_TAG_COLORS[i % WL_TAG_COLORS.length], val: count, })).join('')} `; const maxTl = s.timeline.length > 0 ? Math.max(...s.timeline.map(x => x[1])) : 1; tlEl.innerHTML = `
${ICONS.clock} ${T.wlTimeline}
${s.timeline.length === 0 ? emptyHtml(T.wlNoData, { style: 'padding:8px' }) : s.timeline.map(([month, count]) => hbarRow({ cls: 'wl', name: month, pct: (count / maxTl * 100).toFixed(1), color: '#22d3ee', val: count, })).join('')} `; if (upEl) { const now = Date.now(); const day30 = 30 * 864e5, day90 = 90 * 864e5; const upcoming = state.wishlistGames .filter(g => g.isComingSoon) .map(g => { let ts = 0; if (g.releaseDate) { const d = new Date(g.releaseDate); if (!isNaN(d.getTime())) ts = d.getTime(); } return { appid: g.appid, name: g.name, ts, releaseDate: g.releaseDate || '' }; }); const within30 = upcoming.filter(g => g.ts > 0 && g.ts - now <= day30 && g.ts - now >= 0).length; const within90 = upcoming.filter(g => g.ts > 0 && g.ts - now > day30 && g.ts - now <= day90).length; const far = upcoming.filter(g => g.ts > 0 && g.ts - now > day90).length; const noDate = upcoming.filter(g => g.ts === 0).length; const maxUp = Math.max(within30, within90, far, noDate, 1); const nextRelease = upcoming.filter(g => g.ts > 0 && g.ts >= now).sort((a, b) => a.ts - b.ts)[0]; const upBuckets = [ { label: T.wlUpcoming30d, count: within30, color: '#10b981' }, { label: T.wlUpcoming90d, count: within90, color: '#06b6d4' }, { label: T.wlUpcomingFar, count: far, color: '#a78bfa' }, { label: T.wlUpcomingNoDate, count: noDate, color: '#94a3b8' }, ]; upEl.innerHTML = `
${ICONS.rocket} ${T.wlUpcoming} ${upcoming.length}
${upcoming.length === 0 ? emptyHtml(T.wlNoData, { style: 'padding:8px' }) : `
${upBuckets.map(b => hbarRow({ cls: 'wl', name: b.label, pct: (b.count / maxUp * 100).toFixed(1), color: b.color, val: b.count, })).join('')}
`} ${nextRelease ? `
${ICONS.clock} ${wlEscape(nextRelease.name)} ${nextRelease.releaseDate}
` : ''} `; } if (csEl) { const catStats = s.categoryStats || []; const uncat = s.uncategorizedStats || { count: 0, totalValue: 0, discountCount: 0, comingSoonCount: 0, inLibraryCount: 0, pct: 0 }; const sym = detectWlPriceSymbol(); const activeCat = state.wishlistCategoryFilter; const catCount = catStats.length; const titleHtml = `
${ICONS.barChart} ${T.wlCatStats} ${catCount}
`; if (s.total === 0) { csEl.innerHTML = titleHtml + emptyHtml(T.wlNoData, { style: 'padding:8px' }); } else if (catCount === 0) { csEl.innerHTML = titleHtml + emptyHtml(T.wlUncatEmpty.replace('{n}', uncat.count.toLocaleString()), { style: 'padding:8px' }); } else { const maxCount = Math.max(...catStats.map(c => c.count), uncat.count, 1); const renderCatCard = (c, color, isUncat) => { const catId = isUncat ? '__uncat__' : c.id; const isActive = activeCat === catId; const nameStyle = isUncat ? 'font-style:italic;color:var(--sglv-text-secondary)' : ''; return `
${wlEscape(c.name)} ${c.count}${(c.pct * 100).toFixed(0)}%
${ICONS.dollar}${sym}${c.totalValue.toFixed(0)} ${ICONS.tag}${c.discountCount} ${ICONS.rocket}${c.comingSoonCount} ${ICONS.library}${c.inLibraryCount}
${hbarRow({ cls: 'wlBare', pct: (c.count / maxCount * 100).toFixed(1), color })}
`; }; csEl.innerHTML = `${titleHtml}
${catStats.map((c, i) => renderCatCard(c, WL_TAG_COLORS[i % WL_TAG_COLORS.length], false)).join('')} ${uncat.count > 0 ? renderCatCard({ ...uncat, name: T.wlCatStatsNoCat }, '#64748b', true) : ''}
`; csEl.querySelectorAll('.sglv-wl-cat-card').forEach(card => { card.addEventListener('click', () => { const catId = card.dataset.catId; if (state.wishlistCategoryFilter === catId) { state.wishlistCategoryFilter = null; state.wishlistFilter = 'all'; } else { state.wishlistCategoryFilter = catId; state.wishlistFilter = 'category'; } state.wishlistPage = 1; document.querySelectorAll('.sglv-wl-filter-btn').forEach(b => b.classList.toggle('active', b.dataset.filter === state.wishlistFilter)); renderWishlistSide(); renderWishlistGamesList(); }); }); } } } function renderWishlistGamesList() { const content = document.getElementById('sglv-wishlist-content'); if (!content) return; const clearPagination = () => { const p = document.getElementById('sglv-wishlist-pagination'); if (p) p.innerHTML = ''; }; if (state.wishlistLoading) { const existing = content.querySelector('.sglv-wl-loading'); if (existing) { const st = getWishlistLoadStage(); const textEl = existing.querySelector('.sglv-wl-loading-text'); const barEl = existing.querySelector('.sglv-wl-loading-bar-fill'); if (textEl) textEl.textContent = st.text; if (barEl) barEl.style.width = st.pct + '%'; } else { content.innerHTML = wishlistLoadingHtml(); } clearPagination(); return; } if (!state.wishlistLoaded || state.wishlistGames.length === 0) { content.innerHTML = emptyHtml(state.wishlistLoaded ? T.wlNoData : T.wlFetching); clearPagination(); return; } const games = getFilteredWishlist(); if (games.length === 0) { content.innerHTML = emptyHtml(T.wlNoData); clearPagination(); return; } const { pageItems: pageGames, totalPages, page: _clampedPage } = paginate(games, state.wishlistPage, state.wishlistPageSize); state.wishlistPage = _clampedPage; const ownedIds = getWishlistOwnedIds(); const sym = detectWlPriceSymbol(); const isOwned = g => ownedIds.has(Number(g.appid)) || ownedIds.has(String(g.appid)); const myOwnedIds = new Set(); const familySharedIds = new Set(); state.ownedGames.forEach(og => { if (isGameOwnedByMe(og)) myOwnedIds.add(Number(og.appid)); else familySharedIds.add(Number(og.appid)); }); const showFamily = storage.getShowFamilyShared(); const ownershipBadgeHtml = g => { const id = Number(g.appid); const ownedByMe = state.ownedGames.length > 0 ? myOwnedIds.has(id) : isOwned(g); if (ownedByMe) return `✓ ${T.wlInLibrary}`; if (showFamily && familySharedIds.has(id)) { const _fsIcon = ICONS.familyShare.replace('${_fsIcon}${isZh ? '共享' : 'Shared'}`; } return ''; }; const priceHtml = g => { if (g.isComingSoon) return `${T.wlComingSoon}`; if (g.isFree) return `${T.wlFree}`; if (!g._priced || g.finalPrice <= 0) return `${T.wlNoPrice}`; const orig = (g.discountPct > 0 && g.originalPrice > g.finalPrice) ? `${sym}${g.originalPrice.toFixed(2)}` : ''; return `${sym}${g.finalPrice.toFixed(2)}${orig}`; }; const addedText = g => g.added > 0 ? new Date(g.added * 1000).toLocaleDateString(isZh ? 'zh-CN' : 'en-US') : '-'; const rankHtml = g => g.priority > 0 ? `#${g.priority}` : ''; const cardBodyHtml = g => `
${wlEscape(g.name)}${g.appid}
${priceHtml(g)} ${wlCurveBtnHtml(g)} ${ownershipBadgeHtml(g)}
${rankHtml(g)} ${ICONS.clock}${addedText(g)}
`; const listInfoHtml = g => `
${wlEscape(g.name)}${g.appid}
${rankHtml(g)} ${ownershipBadgeHtml(g)} ${ICONS.clock}${addedText(g)}
`; const coverBodyHtml = g => `
${wlEscape(g.name)}${g.appid}
${priceHtml(g)} ${wlCurveBtnHtml(g)} ${rankHtml(g)}
${ICONS.clock}${addedText(g)}
`; const idsKey = state.wishlistViewMode + ':' + pageGames.map(g => g.appid).join(','); const existView = content.querySelector('[data-ids-key]'); if (existView && existView.dataset.idsKey === idsKey) { pageGames.forEach(g => { if (state.wishlistViewMode === 'card') { const body = existView.querySelector(`.sglv-game-card[data-appid="${g.appid}"] .sglv-card-body`); if (body) body.innerHTML = cardBodyHtml(g); } else if (state.wishlistViewMode === 'cover') { const body = existView.querySelector(`.sglv-wl-cover-card[data-appid="${g.appid}"] .sglv-wl-cover-body`); if (body) body.innerHTML = coverBodyHtml(g); const badges = existView.querySelector(`.sglv-wl-cover-card[data-appid="${g.appid}"] .sglv-wl-cover-badges`); if (badges) badges.innerHTML = ownershipBadgeHtml(g); } else { const item = existView.querySelector(`.sglv-list-item[data-appid="${g.appid}"]`); if (!item) return; const info = item.querySelector('.sglv-list-info'); if (info) info.innerHTML = listInfoHtml(g); const priceBox = item.querySelector('.sglv-list-price'); if (priceBox) priceBox.innerHTML = priceHtml(g); } }); applyGameAliases(existView); } else if (state.wishlistViewMode === 'card') { content.innerHTML = renderGameView(pageGames, { viewMode: 'card', wrapAttrs: ` data-ids-key="${idsKey}"`, itemAttrs: g => ` data-appid="${g.appid}" onclick="window.open('https://store.steampowered.com/app/${g.appid}','_blank')"`, imgHtml: g => posterImg(g.appid, wlEscape(g.name)), bodyHtml: cardBodyHtml, }); } else if (state.wishlistViewMode === 'cover') { content.innerHTML = `
${pageGames.map(g => `
${capsuleImg(g.appid, wlEscape(g.name))}
${ownershipBadgeHtml(g)}
${coverBodyHtml(g)}
`).join('')}
`; } else { content.innerHTML = renderGameView(pageGames, { viewMode: 'list', wrapAttrs: ` data-ids-key="${idsKey}"`, itemAttrs: g => ` data-appid="${g.appid}" onclick="window.open('https://store.steampowered.com/app/${g.appid}','_blank')"`, imgHtml: g => `${wlEscape(g.name)}`, bodyHtml: listInfoHtml, trailingHtml: g => `
${priceHtml(g)}${wlCurveBtnHtml(g)}
`, }); } const pagination = document.getElementById('sglv-wishlist-pagination'); if (pagination) { renderPagination(pagination, 'sglv-wishlist', state.wishlistPage, totalPages, games.length, () => { state.wishlistPage--; renderWishlistGamesList(); }, () => { state.wishlistPage++; renderWishlistGamesList(); }, (p) => { state.wishlistPage = p; renderWishlistGamesList(); }); } applyGameAliases(content); } /** * v2.48.0:导出云端云存档全量列表给 GameVault 插件的「已存档」筛选汇总。 * 契约(GameVault 侧 gvp-games.lib.js parseCloudSavesImport 严格对齐): * { schema: 'sglv.cloud-saves.v1', exportedAt: , * source: 'sglv-web', games: [{ appid, name, fileCount, sizeBytes }] } * ★ 纯游戏清单,不含 app ticket / cookie / sessionid 等任何凭据。 * ★ 导出的是 state.cloudSaveGames 全量(不受页面内搜索/排序影响)。 */ function exportCloudSavesForGameVault() { const list = Array.isArray(state.cloudSaveGames) ? state.cloudSaveGames : []; if (list.length === 0) { showToast(isZh ? '没有可导出的云存档数据,请先刷新' : 'No cloud save data to export'); return; } const owned = {}; (state.ownedGames || []).forEach(g => { if (g.appid) owned[String(g.appid)] = g.name || ''; }); const games = list .filter(g => g && g.appid != null && Number(g.appid) > 0) .map(g => { const appid = Number(g.appid); return { appid: appid, name: owned[String(appid)] || g.name || `App ${appid}`, fileCount: Number(g.fileCount) || 0, sizeBytes: Number(g.sizeBytes) || 0 }; }); const payload = { schema: 'sglv.cloud-saves.v1', exportedAt: Date.now(), source: 'sglv-web', games: games }; const stamp = new Date().toISOString().slice(0, 10).replace(/-/g, ''); downloadFile(JSON.stringify(payload, null, 2), `sglv-cloud-saves-${stamp}.json`, 'application/json'); showToast(isZh ? `已导出 ${games.length} 款云存档游戏,可在 GameVault 设置里导入` : `Exported ${games.length} cloud-save games`); } function downloadFile(content, filename, type) { const blob = new Blob([content], { type }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = filename; a.click(); URL.revokeObjectURL(url); } function getExportData() { let list = [...state.ownedGames]; const showFamilyShared = storage.getShowFamilyShared(); if (!showFamilyShared) { list = list.filter(g => isGameOwnedByMe(g)); } if (state.searchQuery) { const q = state.searchQuery.toLowerCase(); list = list.filter(g => g.name.toLowerCase().includes(q)); } list.sort((a, b) => a.name.localeCompare(b.name)); return list; } function exportCSV() { const data = getExportData(); if (!data.length) { showToast(isZh ? '没有可导出的数据' : 'No data to export'); return; } const headers = ['AppID', 'GameName', 'PlaytimeHours', 'IsOwned', 'Owners', 'OwnerCount', 'AcquiredTime', 'Publisher', 'Series']; const rows = data.map(g => { const isOwned = isGameOwnedByMe(g); const ownerNames = getGameOwnerNames(g); const meta = getGameDBMeta(g.appid); const playtimeHours = (g.playtime / 60).toFixed(1); const acquiredTime = g.lastPlayed ? new Date(g.lastPlayed * 1000).toISOString() : ''; return [ g.appid, `"${(g.name || '').replace(/"/g, '""')}"`, playtimeHours, isOwned ? 'Yes' : 'No', `"${ownerNames.replace(/"/g, '""')}"`, g.owners ? g.owners.length : 1, acquiredTime, `"${(meta.publisher || '').replace(/"/g, '""')}"`, `"${(meta.series || '').replace(/"/g, '""')}"` ]; }); const csv = '\uFEFF' + [headers.join(','), ...rows.map(r => r.join(','))].join('\n'); downloadFile(csv, `steam_games_${Date.now()}.csv`, 'text/csv;charset=utf-8'); } function exportJSON() { const data = getExportData(); if (!data.length) { showToast(isZh ? '没有可导出的数据' : 'No data to export'); return; } const json = JSON.stringify(data.map(g => { const isOwned = isGameOwnedByMe(g); const ownerNames = getGameOwnerNames(g); const meta = getGameDBMeta(g.appid); return { appid: g.appid, name: g.name, playtime_hours: Number((g.playtime / 60).toFixed(1)), is_owned: isOwned, owners: g.owners || [], owner_names: ownerNames, owner_count: g.owners ? g.owners.length : 1, acquired_time: g.lastPlayed ? new Date(g.lastPlayed * 1000).toISOString() : null, publisher: meta.publisher || null, series: meta.series || null }; }), null, 2); downloadFile(json, `steam_games_${Date.now()}.json`, 'application/json'); } async function startFetch(force = false) { const refreshBtn = document.getElementById('sglv-refresh-btn'); const setLoading = (loading) => { if (refreshBtn) refreshBtn.classList.toggle('sglv-spin', loading); }; try { if (!storage.getApiKey()) { const allowed = await _requireApiKeyConsent({ thenFetch: true }); if (!allowed) return; } const steamId = getActiveSteamId(); const apiKey = storage.getApiKey(); const authToken = await getAccessToken(); if (!steamId) { showToast(isZh ? '未检测到 SteamID,请先在设置中填写' : 'SteamID not detected. Please configure in settings.'); state.showSettings = true; renderBody(); return; } if (!apiKey) { showToast(isZh ? '未设置 API Key,将尝试页面抓取(数据可能不完整)' : 'No API Key set, will try page scraping (data may be incomplete).'); } if (force) { invalidateActiveOwnedAppIdsCache(); clearComputedCache(); cacheClear('achievements_'); cacheClear('globalAchievements_'); cacheClear('news_'); cacheClear('historyPrices_'); cacheClear('familyShare_'); } setLoading(true); state.isLoading = true; StageProgress.show(); StageProgress.setStage(1, 4, isZh ? '正在拉取库存…' : 'Fetching owned games…'); const games = await fetchAllGames((sub, pct, text) => { const mappedPct = Math.min(30, Math.round(pct * 0.3)); StageProgress.setProgress(mappedPct, text); }); if (games.length === 0) { StageProgress.fail(isZh ? '未获取到游戏数据' : 'No games fetched'); showToast(isZh ? '未获取到游戏数据,请检查 SteamID、API Key 或登录状态(上次的库数据已保留)' : 'No games fetched. Check SteamID, API Key or login status. (Previous library kept.)'); return; } games.sort((a, b) => a.name.localeCompare(b.name)); const _prevCached = storage.getCachedGames(); const _prevCount = Array.isArray(_prevCached) ? _prevCached.length : 0; state.ownedGames = games; state.ownedAppIds = new Set(games.map(g => g.appid)); storage.setCachedGames(games); _activeSteamId = null; invalidateActiveOwnedAppIdsCache(); markSearchIndexDirty(); if (_prevCount > 0 && games.length < Math.ceil(_prevCount * 0.8)) { console.warn(`[SGLV] 本次拉取比缓存少 ${_prevCount - games.length} 款(${_prevCount} → ${games.length})` + ':家庭组成员离开 / 退款属正常;若量级明显不对,检查 API Key 是否被降权、令牌是否过期'); } document.dispatchEvent(new CustomEvent('sglv:games-updated', { detail: { count: games.length } })); StageProgress.setProgress(30, isZh ? `已获取 ${games.length} 款游戏,补全详情…` : `Got ${games.length} games, enriching…`); StageProgress.setStage(2, 4, isZh ? '正在补全游戏详情…' : 'Enriching game details…'); if (typeof enrichOwnedAppTypes === 'function') { try { await enrichOwnedAppTypes((pct, text) => { const mapped = 30 + Math.round(pct * 0.3); StageProgress.setProgress(mapped, text); }); } catch (e) { console.warn('[SGLV] 补全 appdetails 失败:', e); } } StageProgress.setProgress(60, isZh ? '正在加载进包 / DLC 数据…' : 'Loading bundles / DLC…'); StageProgress.setStage(3, 4, isZh ? '正在加载进包 / DLC / 锁区…' : 'Loading bundles / DLC / region…'); const subProgress = { bundle: 0, dlc: 0, blocked: 0 }; const updateCombined = () => { const avg = (subProgress.bundle + subProgress.dlc + subProgress.blocked) / 3; StageProgress.setProgress(60 + Math.round(avg * 0.3)); }; await Promise.allSettled([ typeof loadBundleDatabase === 'function' ? loadBundleDatabase().catch(() => null) : null, typeof loadDlcDatabase === 'function' ? loadDlcDatabase().catch(() => null) : null, typeof loadBlockedApps === 'function' ? loadBlockedApps(force, (stage, text) => { subProgress.blocked = stage * 33; updateCombined(); }).catch(() => null) : null, ].filter(Boolean)); StageProgress.setProgress(90, isZh ? '正在完成渲染准备…' : 'Finalizing…'); StageProgress.setStage(4, 4, isZh ? '完成' : 'Done'); sglvToast.success(force ? T.refreshSuccess : T.fetchSuccess.replace('{n}', games.length)); renderBody(); StageProgress.finish(isZh ? '完成' : 'Done'); if (typeof _progressiveUpdateAfterFetch === 'function') { _progressiveUpdateAfterFetch(games); } } catch (e) { console.error('[SGLV] Fetch error:', e); StageProgress.fail(e.message || String(e)); sglvToast.error(T.fetchFail + ': ' + (e.message || e)); } finally { state.isLoading = false; setLoading(false); } } function _progressiveUpdateAfterFetch(games) { setTimeout(() => { if (!panelEl || !panelEl.classList.contains('sglv-show')) return; if (state.isLoading) return; try { if (typeof computeYearlyStatsAllCached === 'function' && state.ownedGames.length > 0) { const steamId = getActiveSteamId(); const allGames = state.ownedGames; const otherMembers = getFamilyOtherMembers(allGames, steamId); computeYearlyStatsAllCached(allGames, steamId, otherMembers); } if (typeof computeInsightDataCachedSgis === 'function' && state.ownedGames.length > 0) { computeInsightDataCachedSgis(); } if (typeof computeMyAchievementsCached === 'function' && state.ownedGames.length > 0) { computeMyAchievementsCached(); } _patchActiveTabKpis(); console.log('[SGLV-Compute] 数据刷新后渐进式更新完成 — PCC 已预热'); } catch (e) { console.warn('[SGLV-Compute] 渐进式更新失败:', e); } }, 0); } function _patchActiveTabKpis() { const tab = state.activeTab; if (!tab) return; try { if (tab === 'trend') { const trendKpi = document.getElementById('sglv-trend-kpi') || document.querySelector('.sglv-trend-kpi-wrap'); if (trendKpi) { const parent = trendKpi.parentNode; if (parent) { const allGames = state.ownedGames; if (allGames.length === 0) return; const steamId = getActiveSteamId(); const otherMembers = getFamilyOtherMembers(allGames, steamId); const _ya = computeYearlyStatsAllCached(allGames, steamId, otherMembers); if (_ya && _ya.yearly) { const yearlyStats = _ya.yearly; const now = new Date(); const thisYear = now.getFullYear(); const thisYearIdx = yearlyStats.years.indexOf(thisYear); const thisYearCount = thisYearIdx >= 0 ? yearlyStats.counts[thisYearIdx] : 0; const cards = trendKpi.querySelectorAll('.sglv-trend-kpi-card'); cards.forEach(card => { const label = card.querySelector('.sglv-trend-kpi-label'); if (!label) return; const ltxt = label.textContent || ''; const valueEl = card.querySelector('.sglv-trend-kpi-value'); if (!valueEl) return; if (ltxt.includes(T.trendKpiThisYear)) { valueEl.firstChild && (valueEl.firstChild.nodeValue = String(thisYearCount)); } else if (ltxt.includes(T.trendKpiAvgYear)) { const yc = yearlyStats.years.length; const avg = yc > 0 ? Math.round(yearlyStats.total / yc) : 0; valueEl.firstChild && (valueEl.firstChild.nodeValue = String(avg)); } }); } } } } } catch (e) { console.warn('[SGLV-Compute] 局部 patch 失败,回退到 renderBody:', e); try { renderBody(); } catch (_) { } } } async function autoScan() { try { if (!storage.getApiKey() && state.ownedGames.length === 0) return; if (state.ownedGames.length > 0) return; const steamId = getActiveSteamId(); const authToken = await getAccessToken(); if (!steamId && !authToken) return; console.log('[SGLV] 自动扫描游戏库...'); const games = await fetchAllGames(); if (games.length > 0) { games.sort((a, b) => a.name.localeCompare(b.name)); state.ownedGames = games; state.ownedAppIds = new Set(games.map(g => g.appid)); storage.setCachedGames(games); _activeSteamId = null; clearComputedCache(); markSearchIndexDirty(); document.dispatchEvent(new CustomEvent('sglv:games-updated', { detail: { count: games.length, source: 'auto' } })); console.log(`[SGLV] 自动扫描完成,共 ${games.length} 款游戏`); } } catch (e) { console.warn('[SGLV] 自动扫描失败:', e); } } SGLV_API.initUI = initUI; SGLV_API.autoScan = autoScan; SGLV_API.getThemeId = getThemeId; SGLV_API.applySglvTheme = applySglvTheme; SGLV_API.getThemes = () => SGLV_THEMES; SGLV_API.buildPersonalTimeline = buildPersonalTimeline; SGLV_API.buildFamilyTimeline = buildFamilyTimeline; SGLV_API.fetchWishlistFromApi = fetchWishlistFromApi; SGLV_API.openGlobalSettings = openGlobalSettings; SGLV_API.getGameIconUrl = getGameIconUrl; SGLV_API.isDlc = isDlc; SGLV_API.loadDlcDatabase = loadDlcDatabase; SGLV_API.loadDlcDatabaseFromCacheSync = loadDlcDatabaseFromCacheSync; SGLV_API.enrichOwnedAppTypes = enrichOwnedAppTypes; SGLV_API.invalidateAppTypeCache = () => { appTypeMap = null; }; SGLV_API.isDlcDbReady = () => !!(dlcDbData || appTypeMap); SGLV_API.renderBody = renderBody; SGLV_API.getPanelEl = () => panelEl; SGLV_API.computeInsightDataCachedSgis = computeInsightDataCachedSgis; SGLV_API.detectWlPriceSymbol = detectWlPriceSymbol; SGLV_API.hydratePccCache = function () { if (!_PCC_CACHE) return; try { const r = _PCC_CACHE.hydrate(); if (r && r.hydrated > 0) console.log(`[SGLV-Compute] PCC IDB hydrate 完成,${r.hydrated} 项已就绪`); } catch (e) { } }; const STEAM_TRACKER_API = 'https://steam-tracker.com/api?action=GetAppListV3'; const STEAM_TRACKER_REGIONAL_URL = 'https://steam-tracker.com/user/76561198027066612/apps/10'; const BLOCKED_STATIC_URL = 'https://fastly.jsdelivr.net/gh/SmallRob/steam-namespace@main/data/steam_blocked_apps.json'; const BLOCKED_CATEGORY_IDS = new Set([3, 20]); function fetchBlockedFromStatic() { return sglvGmFetchRetry(BLOCKED_STATIC_URL, { timeout: 15000, headers: { 'Accept': 'application/json' }, }).then(data => { const apps = Array.isArray(data) ? data : (Array.isArray(data.data) ? data.data : []); if (apps.length === 0) throw new Error('Empty static data'); const mappedApps = apps.map(a => ({ appid: Number(a.appid) || 0, name: (a.name || '').trim(), category: a.category || '', categoryId: a.categoryId || a.category_id || 0, type: a.type || 'game', source: 'static', changedAt: a.changedAt || a.changed_at || '', })); const fetchedAt = (!Array.isArray(data) && data.fetchedAt) ? data.fetchedAt : ''; return { apps: mappedApps, fetchedAt }; }); } function fetchBlockedFromApi() { return sglvGmFetchRetry(STEAM_TRACKER_API, { timeout: 20000, headers: { 'Accept': 'application/json' }, }).then(data => { if (!data || !data.success || !Array.isArray(data.removed_apps)) { throw new Error('Invalid API response'); } return data.removed_apps .filter(a => BLOCKED_CATEGORY_IDS.has(a.category_id)) .map(a => ({ appid: a.appid, name: (a.name || '').trim(), category: a.category || '', categoryId: a.category_id, type: a.type || 'game', source: 'api', changedAt: a.changed_at || '', })); }); } function fetchRegionalVariants() { return sglvGmFetchTextRetry(STEAM_TRACKER_REGIONAL_URL, { timeout: 15000, headers: { 'Accept': 'text/html', 'Accept-Language': 'en-US,en;q=0.9' }, }).then(html => { const doc = new DOMParser().parseFromString(html, 'text/html'); const rows = doc.querySelectorAll('table tbody tr'); const apps = []; rows.forEach(row => { const cells = row.querySelectorAll('td'); if (cells.length < 4) return; const appidText = cells[1]?.textContent?.trim() || ''; const appid = parseInt(appidText); if (!appid) return; const name = cells[2]?.textContent?.trim() || ''; const changedAt = cells[4]?.textContent?.trim() || ''; apps.push({ appid, name, category: 'Regional variant', categoryId: 10, type: 'game', source: 'html', changedAt, }); }); return apps; }); } function parseManualBlockedJson(text) { const obj = JSON.parse(text); const apps = []; if (Array.isArray(obj)) { obj.forEach(a => { if (a.appid) apps.push({ appid: Number(a.appid), name: String(a.name || '').trim(), category: a.category || 'User imported', categoryId: a.categoryId || 0, type: a.type || 'game', source: 'manual', changedAt: a.changedAt || '', }); }); } else if (obj && typeof obj === 'object') { Object.entries(obj).forEach(([id, info]) => { const appid = Number(id); if (appid && info && typeof info === 'object') { apps.push({ appid, name: String(info.name || '').trim(), category: 'User imported', categoryId: 0, type: 'game', source: 'manual', changedAt: info.at ? new Date(info.at).toISOString().slice(0, 10) : '', }); } }); } return apps; } async function _checkBlockedRemoteVersion(cachedFetchedAt) { try { const result = await fetchBlockedFromStatic(); if (result.fetchedAt && result.fetchedAt !== cachedFetchedAt) { const apps = result.apps; state.blockedApps = apps; state.blockedSource = 'static'; state.blockedLoaded = true; cacheSet('blockedApps', { apps, source: 'static', fetchedAt: result.fetchedAt }, CACHE_TTL.blockedApps); document.dispatchEvent(new CustomEvent('sglv:blocked-data-updated', { detail: { apps, source: 'static', fetchedAt: result.fetchedAt } })); console.log(`[SGLV] 锁区数据远程已更新: fetchedAt ${cachedFetchedAt || 'N/A'} → ${result.fetchedAt} (${apps.length} 款)`); } } catch (e) { } } async function loadBlockedApps(force = false, onProgress) { const report = (stage, text) => { if (typeof onProgress === 'function') onProgress(stage, text); }; if (!force) { const cached = cacheGet('blockedApps'); if (cached && Array.isArray(cached.apps) && cached.apps.length > 0) { state.blockedApps = cached.apps; state.blockedSource = cached.source || 'api'; state.blockedLoaded = true; report(3, isZh ? '缓存命中' : 'Cached'); _checkBlockedRemoteVersion(cached.fetchedAt || ''); return { apps: state.blockedApps, source: state.blockedSource, fetchedAt: cached.fetchedAt || '' }; } if (negCacheGet(nsKey('blocked_neg'), 30 * 60 * 1000)) { console.log('[SGLV] blocked apps 命中负缓存,跳过重试'); report(0, isZh ? '负缓存命中,跳过' : 'Negative cache'); return { apps: [], source: 'none' }; } } state.blockedLoading = true; state.blockedError = null; try { const merged = new Map(); let source = 'static'; let remoteFetchedAt = ''; report(1, isZh ? '正在加载静态数据源…' : 'Fetching static source…'); try { const staticResult = await fetchBlockedFromStatic(); staticResult.apps.forEach(a => merged.set(a.appid, a)); remoteFetchedAt = staticResult.fetchedAt; if (merged.size > 0) source = 'static'; } catch (e) { console.warn('[SGLV] 静态数据源失败:', e.message); } if (merged.size === 0) { report(1, isZh ? '正在拉取 steam-tracker API…' : 'Fetching API…'); try { const apiApps = await fetchBlockedFromApi(); apiApps.forEach(a => merged.set(a.appid, a)); if (merged.size > 0) source = 'api'; } catch (e) { console.warn('[SGLV] steam-tracker API 失败:', e.message); } } report(2, isZh ? '正在抓取 HTML 兜底…' : 'Fetching HTML fallback…'); try { const htmlApps = await fetchRegionalVariants(); htmlApps.forEach(a => { if (!merged.has(a.appid)) merged.set(a.appid, a); }); if (merged.size > 0 && source !== 'static') source = 'mixed'; } catch (e) { console.warn('[SGLV] steam-tracker HTML 抓取失败:', e.message); } if (merged.size === 0) { throw new Error('No blocked apps data found'); } const apps = Array.from(merged.values()); state.blockedApps = apps; state.blockedSource = source; state.blockedLoaded = true; state.blockedLoading = false; cacheSet('blockedApps', { apps, source, fetchedAt: remoteFetchedAt }, CACHE_TTL.blockedApps); negCacheClear(nsKey('blocked_neg')); report(3, isZh ? `完成 (${apps.length} 款)` : `Done (${apps.length})`); document.dispatchEvent(new CustomEvent('sglv:blocked-data-updated', { detail: { apps, source, fetchedAt: remoteFetchedAt } })); return { apps, source, fetchedAt: remoteFetchedAt }; } catch (e) { state.blockedLoading = false; state.blockedError = e.message || 'Unknown error'; console.warn('[SGLV] 锁区数据加载失败:', e); if (!force) negCacheSet(nsKey('blocked_neg'), e.message || String(e)); throw e; } } function isBlockedApp(appid) { if (!state.blockedApps || !state.blockedApps.length) return false; const id = Number(appid); return state.blockedApps.some(a => a.appid === id); } SGLV_API.loadBlockedApps = loadBlockedApps; SGLV_API.isBlockedApp = isBlockedApp; SGLV_API.isBlockedLoaded = () => state.blockedLoaded; SGLV_API.getBlockedFetchedAt = () => { const cached = cacheGet('blockedApps'); return (cached && cached.fetchedAt) ? cached.fetchedAt : ''; }; SGLV_API.ensureCoverFallbackDelegation = _ensureCoverFallbackDelegation; })(); // ==================== 信息侧边栏 (sgis) ==================== (function () { const buildPersonalTimeline = SGLV_API.buildPersonalTimeline; const buildFamilyTimeline = SGLV_API.buildFamilyTimeline; const fetchWishlistFromApi = SGLV_API.fetchWishlistFromApi; const openGlobalSettings = SGLV_API.openGlobalSettings; const getGameIconUrl = SGLV_API.getGameIconUrl; const IS_WISHLIST_PAGE = /\/wishlist(new)?\//i.test(location.pathname); const PAGE_CTX = (function () { const path = location.pathname; const moreLike = path.match(/^\/recommended\/morelike\/app\/(\d+)/); if (moreLike) { return { type: 'morelike', appId: moreLike[1], hasAppId: true, hasSimilarGrid: !!document.querySelector('.similar_grid_ctn') }; } const app = path.match(/^\/(?:agecheck\/)?app\/(\d+)/); if (app) { return { type: 'app', appId: app[1], hasAppId: true, hasSimilarGrid: !!document.querySelector('#steampeek, .similar_grid_ctn') }; } return { type: 'home', appId: '', hasAppId: false, hasSimilarGrid: false }; })(); const APP_ID = PAGE_CTX.appId; const HAS_APP_ID = PAGE_CTX.hasAppId; const IS_MORELIKE = PAGE_CTX.type === 'morelike'; const num = (v) => { const n = Number(v); return isNaN(n) ? 0 : n; }; const SGIS = { appId: APP_ID, open: false, tab: HAS_APP_ID ? 'overview' : 'profile', overview: null, cards: null, cardsLoading: false, prices: null, pricesLoading: false, pricesFetchedAt: 0, itadOverview: null, rateReady: false, medalTab: 'regular', achievements: null, achievementsLoading: false, globalAchievements: null, dynamics: null, dynamicsLoading: false, dynamicsMode: 'original', aiSummary: null, aiSummaryLoading: false, aiSummaryError: null, historyPrices: null, historyPricesLoading: false, historyFetchedAt: 0, prediction: null, predictionLoading: false, predictionError: null, familyShareSupported: null, appDetailsExtra: null, appDetailsExtraLoading: false, dlcNames: null, dlcNamesLoading: false, ownersPlaytime: {}, ownersPlaytimeFetching: false, similarGames: null, similarFilter: 'all', similarSort: 'default', similarDisplayLimit: 12, similarExpanded: false, dynamicStore: null, dynamicStoreChecked: false, dynamicStoreOwnedApps: null, dynamicStoreFetching: false, tagRecs: null, tagRecsLoading: false, tagRecsError: null, activeTagId: null, tagRecDisplayLimit: 12, reviews: null, reviewsLoading: false, reviewsFilter: { rec: 'all', playtime: 'all', language: 'all', purchase: 'all', keyword: '', regexMode: false }, reviewsExpanded: new Set(), priceChartRange: 'all', drmInfo: null, gameStatusInfo: null, gameStatusLoading: false, profileFeaturesStatus: null, profileFeaturesLoading: false, giftRec: null, giftRecLoading: false, profile: null, profileLoading: false, profileError: null, activity: null, activityLoading: false, activitySubTab: 'personal', personalTimeline: null, personalTimelineLoading: false, personalTimelinePage: 1, familyTimeline: null, familyTimelineLoading: false, familyTimelinePage: 1, familyInfo: null, userBadges: null, userBadgesLoading: false, userBadgeMarkets: {}, userAchievements: null, userAchievementsLoading: false, aiPersona: null, aiPersonaLoading: false, aiPersonaError: null, insightData: null, insightDataLoading: false, aiInsight: null, aiInsightLoading: false, aiInsightError: null, aiMarketInsight: null, aiMarketInsightLoading: false, aiMarketInsightError: null, friendsList: null, friendsListLoading: false, friendsListError: null, friendsLevels: null, friendsLevelsLoading: false, friendsLevelsProgress: 0, friendsLevelsTotal: 0, friendsBansLoading: false, friendsBansProgress: 0, friendsBansTotal: 0, friendsGameCounts: null, friendsGameCountsLoading: false, friendsGameCountsProgress: 0, friendsGameCountsTotal: 0, friendsFilter: 'all', friendsSearch: '', friendsSort: 'status', currentPlayers: null, currentPlayersLoading: false, currentPlayersUnavailable: false, reviewSummary: null, reviewSummaryLoading: false, reviewSummaryUnavailable: false, }; function getCurrentGameInfo() { const all = (state.ownedGames && state.ownedGames.length) ? state.ownedGames : storage.getCachedGames(); const g = all.find(x => String(x.appid) === String(APP_ID)); if (!g) { const ds = getDynamicStoreStatus(); if (ds && ds.owned && ds.owned.has(Number(APP_ID))) { const pageName = (document.getElementById('appHubAppName') || {}).textContent?.trim() || ''; return { found: true, name: pageName || `App ${APP_ID}`, playtime: 0, lastPlayed: 0, acquiredTime: 0, icon: '', _source: 'dynamicstore', isOwnedByMe: true, isSharedOnly: false, isFamilyLib: false, owners: [], }; } if (SGIS.dynamicStoreOwnedApps && SGIS.dynamicStoreOwnedApps.has(Number(APP_ID))) { const pageName = (document.getElementById('appHubAppName') || {}).textContent?.trim() || ''; return { found: true, name: pageName || `App ${APP_ID}`, playtime: 0, lastPlayed: 0, acquiredTime: 0, icon: '', _source: 'dynamicstore_api', isOwnedByMe: true, isSharedOnly: false, isFamilyLib: false, owners: [], }; } return { found: false }; } const mySteamId = getActiveSteamId(); const familyInfo = storage.getFamilyInfo() || {}; const nameMap = familyInfo.steamIdtoName || {}; const owners = g.owners || []; const isOwnedByMe = !owners.length || (mySteamId && owners.includes(mySteamId)); const isSharedOnly = owners.length > 0 && !isOwnedByMe; return { found: true, name: g.name, playtime: g.playtime || 0, lastPlayed: g.lastPlayed || 0, acquiredTime: g.acquiredTime || 0, icon: g.icon || '', _source: g._source || 'cache', isOwnedByMe, isSharedOnly, isFamilyLib: owners.length > 0, owners: owners.map(sid => ({ steamId: sid, name: nameMap[sid] || ('ID:' + String(sid).slice(-4)), isMe: mySteamId && String(sid) === String(mySteamId), playtime: SGIS.ownersPlaytime[sid] != null ? SGIS.ownersPlaytime[sid] : null, })), }; } function formatAcquiredTime(ts) { if (!ts) return '—'; try { const d = new Date(ts * 1000); return d.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }); } catch { return '—'; } } function formatRelativeDate(ts) { if (!ts) return '—'; const t = ts * 1000; const diff = Date.now() - t; if (diff < 0) return new Date(t).toLocaleDateString('zh-CN'); const min = Math.floor(diff / 60000); if (min < 1) return '刚刚'; if (min < 60) return `${min} 分钟前`; const hr = Math.floor(min / 60); if (hr < 24) return `${hr} 小时前`; const day = Math.floor(hr / 24); if (day < 30) return `${day} 天前`; const mon = Math.floor(day / 30); if (mon < 12) return `${mon} 个月前`; const yr = Math.floor(day / 365); return `${yr} 年前`; } function httpGet(url, opts) { return sglvGmFetchTextRetry(url, opts).then(text => ({ status: 200, responseText: text })); } function fetchJson(url, opts) { return sglvGmFetchRetry(url, opts); } function fetchText(url, opts) { return sglvGmFetchTextRetry(url, opts); } function mapLimit(items, limit, mapper) { const tasks = items.map((item, idx) => () => mapper(item, idx)); return C.concurrentPool(tasks, limit).then(results => results.map(r => r.status === 'fulfilled' ? r.value : r.reason) ); } function getRates() { try { return GM_getValue('sgis-rates', null); } catch { return null; } } function getRatesTs() { try { return GM_getValue('sgis-rates-ts', 0); } catch { return 0; } } function setRates(r) { try { GM_setValue('sgis-rates', r); GM_setValue('sgis-rates-ts', Date.now()); } catch { } try { scheduleSaaBridge(); } catch { } } function _convertToSgisRatesFormat(rates) { const out = { CNY: 1 }; for (const [code, val] of Object.entries(rates || {})) { if (typeof val === 'number' && val > 0) out[code] = 1 / val; } return out; } async function refreshRates() { if (Date.now() - getRatesTs() < 3600000 && getRates()) { SGIS.rateReady = true; return; } try { const A = unsafeWindow.SGLVAppDetail; if (A && typeof A.getRates === 'function') { const info = await A.getRates(); if (info && info.ready && info.rates) { setRates(_convertToSgisRatesFormat(info.rates)); SGIS.rateReady = true; return; } } } catch (e) { } try { const r = await httpGet('https://api.augmentedsteam.com/rates/v1', { timeout: 10000 }); const data = JSON.parse(r.responseText); if (data?.data?.CNY) { const cny = data.data.CNY; const rates = {}; for (const [code, val] of Object.entries(data.data)) { if (typeof val === 'number' && val > 0) rates[code] = cny / val; } setRates(rates); SGIS.rateReady = true; return; } } catch (e) { } try { const r = await httpGet('https://open.er-api.com/v6/latest/CNY', { timeout: 10000 }); const data = JSON.parse(r.responseText); if (data?.rates) { const rates = { CNY: 1 }; for (const [code, val] of Object.entries(data.rates)) { if (typeof val === 'number' && val > 0) rates[code] = 1 / val; } setRates(rates); SGIS.rateReady = true; } } catch (e) { } } function toCNY(amount, currency) { if (currency === 'CNY' || currency === 'RMB') return amount; const rates = getRates(); if (!rates || !rates[currency]) return null; return amount * rates[currency]; } let _usdRatesMemo = null, _usdRatesMemoTs = -1; function getUsdRates() { if (!SGIS.rateReady) return null; const ts = getRatesTs(); if (_usdRatesMemoTs === ts) return _usdRatesMemo; _usdRatesMemoTs = ts; _usdRatesMemo = hasSglvCurrency ? CUR.sgisRatesToUsdRates(getRates()) : null; return _usdRatesMemo; } function convertToCNY(amount, code) { if (code === 'CNY' || code === 'RMB') return amount; if (!SGIS.rateReady) return null; if (hasSglvCurrency) { const usdRates = getUsdRates(); if (usdRates) { const v = CUR.convert(amount, code, 'CNY', usdRates); if (Number.isFinite(v)) return v; } } return toCNY(amount, code); } const PRICE_TARGET_CURRENCIES = [ { code: 'CNY', symbol: '¥', name: '人民币' }, { code: 'INR', symbol: '₹', name: '印度卢比' }, { code: 'UAH', symbol: '₴', name: '乌克兰格里夫纳' }, { code: 'HKD', symbol: 'HK$', name: '港币' }, { code: 'TRY', symbol: '₺', name: '土耳其里拉' }, { code: 'ARS', symbol: 'AR$', name: '阿根廷比索' }, { code: 'KZT', symbol: '₸', name: '哈萨克斯坦坚戈' }, { code: 'RUB', symbol: '₽', name: '俄罗斯卢布' }, { code: 'USD', symbol: '$', name: '美元' }, { code: 'EUR', symbol: '€', name: '欧元' }, { code: 'GBP', symbol: '£', name: '英镑' }, { code: 'JPY', symbol: '¥', name: '日元' }, { code: 'KRW', symbol: '₩', name: '韩元' }, { code: 'BRL', symbol: 'R$', name: '巴西雷亚尔' }, { code: 'MXN', symbol: 'MX$', name: '墨西哥比索' }, { code: 'CLP', symbol: 'CLP$', name: '智利比索' }, { code: 'COP', symbol: 'COL$', name: '哥伦比亚比索' }, { code: 'PLN', symbol: 'zł', name: '波兰兹罗提' }, ]; function priceTargetCurInfo(code) { return PRICE_TARGET_CURRENCIES.find(c => c.code === code) || { code: String(code || 'CNY'), symbol: String(code || 'CNY'), name: String(code || 'CNY') }; } function convertToCurrency(amount, fromCode, toCode) { const cny = convertToCNY(amount, fromCode); if (cny == null) return null; if (!toCode || toCode === 'CNY' || toCode === 'RMB') return cny; const rates = getRates(); if (!rates || typeof rates[toCode] !== 'number' || !(rates[toCode] > 0)) return null; return cny / rates[toCode]; } function getEffectivePriceTarget(stored) { const t = stored != null ? stored : storage.getPriceTargetCurrency(); if (!t || t === 'CNY') return { code: 'CNY', fallback: false }; const rates = getRates(); if (rates && typeof rates[t] === 'number' && rates[t] > 0) return { code: t, fallback: false }; return { code: 'CNY', fallback: true, wanted: t }; } const MARKET_SEARCH_API = 'https://steamcommunity.com/market/search/render/'; const MARKET_LISTING_PAGE = 'https://steamcommunity.com/market/listings/753/'; const BUY_ORDER_CONCURRENCY = 3; const STEAM_TX_FEE_PERCENT = 0.05; const DEFAULT_PUBLISHER_FEE_PERCENT = 0.10; function _readPublisherFeeFromItem(item) { const desc = item && item.asset_description ? item.asset_description : {}; const ownerActions = desc.owner_actions || []; for (let i = 0; i < ownerActions.length; i++) { const link = ownerActions[i].link || ''; const m = link.match(/publisherFeePercentDbl=([0-9.]+)/); if (m) { const v = Number(m[1]); if (Number.isFinite(v) && v >= 0) return v / 100; } } return DEFAULT_PUBLISHER_FEE_PERCENT; } function _calcFees(receivedAmount, publisherFee, steamFeePercent) { const steamFee = Math.max(Math.floor(receivedAmount * steamFeePercent), 1); const publisherFeeAmount = publisherFee > 0 ? Math.max(Math.floor(receivedAmount * publisherFee), 1) : 0; return { steamFee, publisherFee: publisherFeeAmount, fees: steamFee + publisherFeeAmount, amount: receivedAmount + steamFee + publisherFeeAmount, }; } function _calculateSellerReceives(buyerPaysCents, publisherFeePercent) { const amount = Math.round(Number(buyerPaysCents)); if (!Number.isFinite(amount) || amount <= 0) return null; publisherFeePercent = publisherFeePercent == null ? DEFAULT_PUBLISHER_FEE_PERCENT : publisherFeePercent; const steamFeePercent = STEAM_TX_FEE_PERCENT; let estimatedReceived = parseInt(amount / (steamFeePercent + publisherFeePercent + 1), 10); if (!Number.isFinite(estimatedReceived)) estimatedReceived = amount; estimatedReceived = Math.max(1, estimatedReceived); let iterations = 0, everUndershot = false; let fees = _calcFees(estimatedReceived, publisherFeePercent, steamFeePercent); while (fees.amount !== amount && iterations < 100) { if (fees.amount > amount) { if (everUndershot) { fees = _calcFees(estimatedReceived - 1, publisherFeePercent, steamFeePercent); fees.steamFee += amount - fees.amount; fees.fees += amount - fees.amount; fees.amount = amount; break; } estimatedReceived--; } else { everUndershot = true; estimatedReceived++; } estimatedReceived = Math.max(1, estimatedReceived); fees = _calcFees(estimatedReceived, publisherFeePercent, steamFeePercent); iterations++; } return amount > fees.fees ? amount - fees.fees : 1; } async function fetchCardGroup(appId, foil) { const cards = []; let total = Infinity, start = 0, count = 100; while (start < total && cards.length < 200) { const params = new URLSearchParams(); params.set('query', ''); params.set('start', String(start)); params.set('count', String(count)); params.set('search_descriptions', '0'); params.set('sort_column', 'name'); params.set('sort_dir', 'asc'); params.set('appid', '753'); params.set('norender', '1'); params.append('category_753_Game[]', 'tag_app_' + appId); params.append('category_753_item_class[]', 'tag_item_class_2'); params.append('category_753_cardborder[]', foil ? 'tag_cardborder_1' : 'tag_cardborder_0'); const data = await fetchJson(MARKET_SEARCH_API + '?' + params.toString(), { timeout: 12000 }); if (data?.success === false) throw new Error('Steam 市场返回失败'); const results = Array.isArray(data?.results) ? data.results : []; total = Number.isFinite(Number(data?.total_count)) ? Number(data.total_count) : results.length; for (const item of results) { const desc = item.asset_description || {}; const hashName = String(item.hash_name || desc.market_hash_name || '').trim(); if (!hashName) continue; const sellPrice = Number.isFinite(Number(item.sell_price)) ? Number(item.sell_price) : null; const publisherFeePercent = _readPublisherFeeFromItem(item); const netPrice = sellPrice != null ? _calculateSellerReceives(sellPrice, publisherFeePercent) : null; const iconPath = desc.icon_url_large || desc.icon_url || ''; const iconUrl = iconPath ? `https://community.fastly.steamstatic.com/economy/image/${iconPath}/64fx64f` : ''; cards.push({ foil, name: String(item.name || desc.market_name || hashName).trim(), hashName, classId: String(desc.classid || '').trim(), type: String(desc.type || '').trim(), listings: parseInt(item.sell_listings, 10) || 0, sellPrice, netPrice, publisherFeePercent, sellPriceText: String(item.sell_price_text || '').trim(), salePriceText: String(item.sale_price_text || '').trim(), iconUrl, marketUrl: MARKET_LISTING_PAGE + encodeURIComponent(hashName), }); } if (results.length < count) break; start += count; } return cards; } async function enrichBuyOrder(card) { try { const html = await fetchText(card.marketUrl, { timeout: 8000 }); const m1 = html.match(/"amtMaxBuyOrder"\s*:\s*(\d+)/); const m2 = html.match(/"cBuyOrders"\s*:\s*(\d+)/); return Object.assign({}, card, { buyPrice: m1 ? parseInt(m1[1], 10) : null, buyOrderCount: m2 ? parseInt(m2[1], 10) : 0, }); } catch (e) { return Object.assign({}, card, { buyPrice: null, buyOrderCount: 0, buyError: e.message }); } } function toMajorUnit(minor) { return Number.isFinite(minor) ? minor / 100 : null; } async function fetchCardPrices(appId) { const result = { regular: [], foil: [], regularQueried: false, foilQueried: false }; await Promise.all([ fetchCardGroup(appId, false).then(c => { result.regular = c; result.regularQueried = true; }).catch(e => { result.regularError = e.message; }), fetchCardGroup(appId, true).then(c => { result.foil = c; result.foilQueried = true; }).catch(e => { result.foilError = e.message; }), ]); const tasks = []; if (result.regular.length) tasks.push(mapLimit(result.regular, BUY_ORDER_CONCURRENCY, c => enrichBuyOrder(c))); if (result.foil.length) tasks.push(mapLimit(result.foil, BUY_ORDER_CONCURRENCY, c => enrichBuyOrder(c))); await Promise.all(tasks); return result; } async function fetchCardMarketLight(appId) { const cacheKey = 'sgis_badge_market_' + appId; const cached = cacheGet(cacheKey); if (cached) return cached; const params = new URLSearchParams(); params.set('query', ''); params.set('start', '0'); params.set('count', '100'); params.set('search_descriptions', '0'); params.set('sort_column', 'name'); params.set('sort_dir', 'asc'); params.set('appid', '753'); params.set('norender', '1'); params.append('category_753_Game[]', 'tag_app_' + appId); params.append('category_753_item_class[]', 'tag_item_class_2'); params.append('category_753_cardborder[]', 'tag_cardborder_0'); const url = MARKET_SEARCH_API + '?' + params.toString(); const data = await fetchJson(url, { timeout: 10000 }); const results = Array.isArray(data?.results) ? data.results : []; let totalCost = 0, priceCount = 0; const seenHash = new Set(); const cards = []; for (const item of results) { const desc = item.asset_description || {}; const hashName = String(item.hash_name || desc.market_hash_name || '').trim(); if (!hashName || seenHash.has(hashName)) continue; seenHash.add(hashName); const sellPrice = Number.isFinite(Number(item.sell_price)) ? Number(item.sell_price) : null; if (sellPrice != null) { totalCost += sellPrice; priceCount++; } const publisherFeePercent = _readPublisherFeeFromItem(item); const iconPath = desc.icon_url_large || desc.icon_url || ''; const iconUrl = iconPath ? `https://community.fastly.steamstatic.com/economy/image/${iconPath}/64fx64f` : ''; cards.push({ name: String(item.name || desc.market_name || hashName).replace(/\s*\(Foil\)\s*$/i, '').trim(), hashName, iconUrl, sellPrice, publisherFeePercent, sellPriceText: String(item.sell_price_text || '').trim(), listings: parseInt(item.sell_listings, 10) || 0, marketUrl: MARKET_LISTING_PAGE + encodeURIComponent(hashName), }); } const summary = { appId, cards, cardCount: cards.length, totalCost, priceCount, avgPrice: priceCount > 0 ? Math.round(totalCost / priceCount) : 0, medianPrice: 0, avgNoMax: 0, netIncome: 0, updatedAt: Date.now(), }; if (priceCount > 0) { const prices = cards.filter(c => c.sellPrice != null).map(c => c.sellPrice).sort((a, b) => a - b); if (prices.length > 0) { const mid = Math.floor(prices.length / 2); summary.medianPrice = prices.length % 2 !== 0 ? prices[mid] : Math.round((prices[mid - 1] + prices[mid]) / 2); if (prices.length > 1) { const sumNoMax = prices.slice(0, -1).reduce((s, p) => s + p, 0); summary.avgNoMax = Math.round(sumNoMax / (prices.length - 1)); } else { summary.avgNoMax = summary.avgPrice; } const dropCount = Math.ceil(cards.length / 2); const grossIncome = summary.avgPrice * dropCount; summary.netIncome = _calculateSellerReceives(grossIncome, DEFAULT_PUBLISHER_FEE_PERCENT) || 0; } } cacheSet(cacheKey, summary, 10 * 60 * 1000); return summary; } function formatMarketPrice(cents) { if (cents == null) return '—'; try { const m = document.cookie.match(/steamCountry=(\w{2})/) || []; const cc = (m[1] || 'CN').toLowerCase(); const symbols = { cn: '¥', us: '$', eu: '€', uk: '£', jp: '¥', kr: '₩', ru: '₽' }; const symbol = symbols[cc] || '¥'; return symbol + (cents / 100).toFixed(2); } catch (e) { return '¥' + (cents / 100).toFixed(2); } } const BADGE_VALUE_WEIGHTS = { xp: 0.25, level: 0.20, cardPrice: 0.30, completionBonus: 0.15, dropBonus: 0.10, }; function computeBadgeValueScores(badges, markets) { const scores = {}; const gameBadges = badges.filter(b => b.appid > 0); if (gameBadges.length === 0) return scores; const maxXp = Math.max(...gameBadges.map(b => b.xp || 0), 1); gameBadges.forEach(badge => { const appId = String(badge.appid); const xpScore = (badge.xp || 0) / maxXp; const realMaxLevel = badge._maxLevel || getCardDbMaxLevel(badge.appid) || 5; const levelScore = realMaxLevel > 1 ? ((badge.level || 1) - 1) / (realMaxLevel - 1) : 0; const marketData = markets[appId]; let cardPriceScore = 0; if (marketData && marketData.avgPrice > 0) { cardPriceScore = Math.max(0, 1 - (marketData.avgPrice / 50000)); } const completionBonus = badge.completion_time ? 1 : 0; const dropBonus = Math.min(1, (badge.level || 1) / realMaxLevel); const w = BADGE_VALUE_WEIGHTS; const score = Math.round( (w.xp * xpScore + w.level * levelScore + w.cardPrice * cardPriceScore + w.completionBonus * completionBonus + w.dropBonus * dropBonus) * 100 ); scores[appId] = { score, appId, gameName: badge._gameName || '', level: badge.level || 1, maxLevel: realMaxLevel, xp: badge.xp || 0, completed: !!badge.completion_time, marketData, breakdown: { xp: Math.round(xpScore * 100), level: Math.round(levelScore * 100), cardPrice: Math.round(cardPriceScore * 100), completion: Math.round(completionBonus * 100), level_max: Math.round(dropBonus * 100), }, }; }); return scores; } function getTopValueBadges(scores, n) { n = n || 6; return Object.values(scores).sort((a, b) => b.score - a.score).slice(0, n); } function getBadgeLevelDistribution(badges) { const dist = { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0 }; badges.filter(b => b.appid > 0).forEach(b => { const lv = Math.min(5, Math.max(1, b.level || 1)); dist[lv] = (dist[lv] || 0) + 1; }); return dist; } async function fetchBadgeMarkets(appIds, opts) { opts = opts || {}; const concurrency = opts.concurrency || 3; const maxApps = opts.maxApps || 20; const targets = appIds.slice(0, maxApps); const results = {}; for (let i = 0; i < targets.length; i += concurrency) { const batch = targets.slice(i, i + concurrency); await Promise.all(batch.map(async (appId) => { try { results[String(appId)] = await fetchCardMarketLight(appId); } catch (e) { results[String(appId)] = { appId, cardCount: 0, totalCost: 0, avgPrice: 0, cards: [], error: e.message }; } })); if (i + concurrency < targets.length) { await new Promise(r => setTimeout(r, 500)); } } return results; } function flagUrl(code) { const cc = String(code || '').toLowerCase(); if (cc === 'eu') return 'https://flagcdn.com/w40/eu.png'; return `https://flagcdn.com/w40/${cc}.png`; } const REGIONS = [ { code: 'CN', name: '中国', currency: 'CNY' }, { code: 'US', name: '美国', currency: 'USD' }, { code: 'AR', name: '阿根廷', currency: 'USD', curAlt: ['ARS'], usd: true }, { code: 'TR', name: '土耳其', currency: 'USD', curAlt: ['TRY'], usd: true }, { code: 'KZ', name: '哈萨克斯坦', currency: 'KZT' }, { code: 'UA', name: '乌克兰', currency: 'UAH' }, { code: 'IN', name: '印度', currency: 'INR' }, { code: 'BR', name: '巴西', currency: 'BRL' }, { code: 'CL', name: '智利', currency: 'CLP' }, { code: 'CO', name: '哥伦比亚', currency: 'COP' }, { code: 'PL', name: '波兰', currency: 'PLN' }, { code: 'MX', name: '墨西哥', currency: 'MXN' }, { code: 'RU', name: '俄罗斯', currency: 'RUB' }, { code: 'JP', name: '日本', currency: 'JPY' }, { code: 'KR', name: '韩国', currency: 'KRW' }, { code: 'GB', name: '英国', currency: 'GBP' }, { code: 'EU', name: '欧元区', currency: 'EUR' }, ]; const PRIORITY_REGIONS = ['CN', 'US', 'RU', 'IN', 'BR', 'UA', 'KZ', 'CL', 'CO']; const EXTENDED_REGIONS = ['CN', 'US', 'RU', 'IN', 'BR', 'UA', 'KZ', 'CL', 'CO', 'PL', 'MX', 'JP', 'KR', 'GB', 'VN', 'ID']; function regionExpectedCurrency(code) { const r = REGIONS.find(x => x.code === code); return r ? r.currency : ''; } function regionAltCurrencies(code) { const r = REGIONS.find(x => x.code === code); return (r && Array.isArray(r.curAlt)) ? r.curAlt : []; } function regionAcceptsCurrency(code, cur) { if (!cur) return true; if (cur === regionExpectedCurrency(code)) return true; return regionAltCurrencies(code).indexOf(cur) >= 0; } async function fetchSteamRegionPrice(appId, countryCode) { try { const url = `https://store.steampowered.com/api/appdetails?appids=${appId}&cc=${countryCode}&l=english&_=${Date.now()}`; const data = await fetchJson(url, { timeout: 12000 }); if (data[appId] && data[appId].success) { const g = data[appId].data; if (g.is_free) return { success: true, data: { region: countryCode, price: 0, currency: 'FREE', discount: 0, initial: 0, source: 'steam' } }; if (g.price_overview) { const actualCurrency = g.price_overview.currency; const expectedRegion = REGIONS.find(r => r.code === countryCode); if (expectedRegion && expectedRegion.currency && !regionAcceptsCurrency(countryCode, actualCurrency)) { return { success: false, error: `币种不匹配(期望${expectedRegion.currency}, 实际${actualCurrency}, 疑似Steam返回用户本区数据)` }; } return { success: true, data: { region: countryCode, price: g.price_overview.final / 100, currency: actualCurrency, discount: g.price_overview.discount_percent || 0, initial: g.price_overview.initial / 100, source: 'steam', }}; } } return { success: false, error: '无价格数据' }; } catch (e) { return { success: false, error: e.message }; } } async function fetchAugRegionPrice(appId, countryCode) { try { const data = await sglvGmFetchRetry('https://api.augmentedsteam.com/prices/v2', { method: 'POST', timeout: 12000, headers: { 'Content-Type': 'application/json' }, data: JSON.stringify({ country: countryCode, apps: [parseInt(appId, 10)], subs: [], bundles: [], voucher: true, shops: [], }), }); const key = `app/${appId}`; const aug = data?.prices?.[key]; if (!aug?.current?.price) return { success: false, error: 'Aug 无数据' }; const cur = aug.current; const cur2 = cur.price; const _expCur = regionExpectedCurrency(countryCode); if (_expCur && cur2.currency && cur2.currency !== _expCur) { console.debug(`[SGLV] Aug 币种不匹配 ${countryCode}: 期望 ${_expCur}, 实际 ${cur2.currency}, 降级 Steam 兜底`); return { success: false, error: `Aug 币种不匹配(期望${_expCur}, 实际${cur2.currency})` }; } const regular = cur.regular || cur2; const discount = (regular.amount > cur2.amount) ? Math.round((1 - cur2.amount / regular.amount) * 100) : 0; return { success: true, data: { region: countryCode, price: cur2.amount, currency: cur2.currency, discount, initial: regular.amount, source: 'aug', }}; } catch (e) { return { success: false, error: 'Aug: ' + e.message }; } } async function fetchOneRegionPrice(appId, countryCode) { const aug = await fetchAugRegionPrice(appId, countryCode); if (aug.success) return aug; return await fetchSteamRegionPrice(appId, countryCode); } let _steamApiLastReq = 0; const STEAM_API_MIN_INTERVAL = 1000; async function steamApiRateLimit() { const now = Date.now(); const wait = STEAM_API_MIN_INTERVAL - (now - _steamApiLastReq); _steamApiLastReq = now + Math.max(0, wait); if (wait > 0) await new Promise(r => setTimeout(r, wait)); } async function fetchOneRegionPriceRateLimited(appId, countryCode) { await steamApiRateLimit(); return await fetchOneRegionPrice(appId, countryCode); } async function fetchMultiRegionPrices(appId) { const userCc = (document.cookie.match(/steamCountry=(\w{2})/) || [])[1] || ''; const regions = (userCc && PRIORITY_REGIONS.indexOf(userCc) < 0 && REGIONS.find(r => r.code === userCc)) ? [userCc].concat(PRIORITY_REGIONS) : PRIORITY_REGIONS.slice(); const results = await mapLimit(regions, 3, r => fetchOneRegionPriceRateLimited(appId, r)); const prices = []; const failed = []; const seenKey = new Set(); const successList = []; results.forEach((r, i) => { if (r.success) successList.push({ data: r.data, idx: i }); else failed.push({ region: regions[i], error: r.error }); }); const expCurSet = new Set(regions.map(cc => regionExpectedCurrency(cc))); const curSharedInSet = expCurSet.size < regions.length; const allSameCurrency = !curSharedInSet && successList.length > 1 && successList.every(s => s.data.currency === successList[0].data.currency) && successList.every(s => Math.abs(s.data.price - successList[0].data.price) < 0.01); if (allSameCurrency && successList.length > 1) { successList.forEach(s => failed.push({ region: regions[s.idx], error: '区域数据相同(疑似被缓存)' })); } else { successList.forEach(s => { const cc = regions[s.idx]; const k = `${s.data.currency}:${Number(s.data.price).toFixed(2)}`; const expCur = regionExpectedCurrency(cc); const curShared = regions.filter(x => regionExpectedCurrency(x) === expCur).length > 1; const dupKey = curShared ? null : k; if (dupKey === null || !seenKey.has(dupKey)) { if (dupKey !== null) seenKey.add(dupKey); prices.push(s.data); } else { failed.push({ region: cc, error: '与已有地区价格重复' }); } }); } return { prices, failed }; } const _S = 'viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"'; const SGIS_ICONS = { overview: ` `, medal: ` `, price: ` `, review: ` `, trophy: ` `, activity: ` `, user: ` `, social: ` `, insight: ` `, close: ``, refresh: ``, settings: ``, check: ``, star: ``, share: ``, news: ``, info: ``, game: ``, card: ``, library: ``, chevronRight: ``, sparkle: ``, brain: ``, clock: ``, users: ``, package: ``, gift: ``, link: ``, heart: ``, barChart: ``, trend: ``, target: ``, market: ``, zap: ``, shield: ``, external: ``, heart: ``, copy: ``, workshop: ``, image: ``, tag: ``, video: ``, globe: ``, gamepad: ``, puzzle: ``, fire: ``, rocket: ``, flag: ``, profileLimited: ``, medalFallback: ``, }; function ensureFab() { if (IS_WISHLIST_PAGE) return; if (document.getElementById('sgis-fab')) return; const btn = document.createElement('button'); btn.id = 'sgis-fab'; btn.title = '个人信息面板'; btn.setAttribute('aria-label', '个人信息面板'); btn.addEventListener('click', togglePanel); document.body.appendChild(btn); } function ensurePanel() { if (document.getElementById('sgis-panel')) return; const titleIcon = HAS_APP_ID ? SGIS_ICONS.game : SGIS_ICONS.user; const titleText = HAS_APP_ID ? '游戏信息面板' : '个人信息面板'; const panel = document.createElement('div'); panel.id = 'sgis-panel'; panel.setAttribute('data-sglv-plugin-ui', '1'); panel.innerHTML = `
${titleIcon} ${titleText}
${HAS_APP_ID ? ` ` : ` `}
`; document.body.appendChild(panel); try { if (typeof SGLV_API.ensureCoverFallbackDelegation === 'function') { SGLV_API.ensureCoverFallbackDelegation(panel); } } catch (e) { console.warn('[SGIS] 封面降级委托注册失败', e); } panel.querySelector('#sgis-close-btn').addEventListener('click', closePanel); panel.querySelector('#sgis-settings-btn').addEventListener('click', () => openGlobalSettings()); const _themeBtn = panel.querySelector('#sgis-theme-btn'); const _updateThemeBtnTitle = () => { const next = SGLV_THEMES[getThemeId() === 'purple' ? 'blue' : 'purple']; _themeBtn.title = isZh ? `切换主题:${next.zh}` : `Switch theme: ${next.en}`; }; _themeBtn.addEventListener('click', () => { const nextId = getThemeId() === 'purple' ? 'blue' : 'purple'; storage.setUiTheme(nextId); applySglvTheme(nextId); const t = SGLV_THEMES[nextId]; sglvToast.success(isZh ? `已切换主题:${t.zh}` : `Theme switched: ${t.en}`); _updateThemeBtnTitle(); }); _updateThemeBtnTitle(); panel.querySelector('#sgis-collection-btn').addEventListener('click', () => { const col = window.SGLVCollection; if (!col || !col._hostReady || typeof col.openCollection !== 'function') { if (typeof sglvToast !== 'undefined' && sglvToast) { sglvToast.warning(isZh ? '收藏模块未加载或版本不兼容' : 'Collection module not loaded or incompatible'); } console.warn('[SGIS] 游戏收藏不可用: SGLVCollection=', col, 'ready=', col && col._hostReady); return; } try { col.openCollection(); } catch (err) { console.error('[SGIS] 收藏浮窗打开失败:', err); if (typeof sglvToast !== 'undefined' && sglvToast) { sglvToast.warning(isZh ? '收藏模块异常,详见控制台' : 'Collection error, see console'); } } }); const _shelfBtn = panel.querySelector('#sgis-shelf-btn'); if (_shelfBtn) { const _shelf = window.SGLVShelf; const _shelfUsable = () => !!(window.SGLVShelf && window.SGLVShelf._hostReady && typeof window.SGLVShelf.openShelf === 'function'); if (!_shelfUsable()) { _shelfBtn.title = isZh ? '暂存箱模块未加载或版本不兼容' : 'Shelf module unavailable'; _shelfBtn.style.opacity = '0.45'; _shelfBtn.addEventListener('click', () => { sglvToast.warning(isZh ? '暂存箱模块未加载,请检查脚本依赖' : 'Shelf module not loaded'); console.warn('[SGIS] 暂存箱不可用: SGLVShelf=', _shelf, 'ready=', _shelf && _shelf._hostReady); }); } else { _shelfBtn.addEventListener('click', () => { try { window.SGLVShelf.openShelf(); } catch (err) { console.error('[SGIS] 暂存箱打开失败:', err); sglvToast.warning(isZh ? '暂存箱异常,详见控制台' : 'Shelf error, see console'); } }); try { window.SGLVShelf.setBadge(window.SGLVShelf.getCount()); } catch (e) { console.warn('[SGIS] 暂存箱角标初始化失败', e); } } } panel.querySelector('#sgis-refresh-btn').addEventListener('click', () => { const refreshBtn = panel.querySelector('#sgis-refresh-btn'); refreshBtn.classList.add('sgis-spin'); const cached = _tabPanes.get(SGIS.tab); if (cached) cached.dataset.ready = ''; _activateSgisTab(SGIS.tab, { force: true }); requestAnimationFrame(() => requestAnimationFrame(() => refreshBtn.classList.remove('sgis-spin'))); }); panel.querySelectorAll('.sgis-tab').forEach(tabBtn => { tabBtn.addEventListener('click', () => { _activateSgisTab(tabBtn.dataset.tab, { force: false }); }); }); document.addEventListener('keydown', e => { if (e.key !== 'Escape' || !SGIS.open) return; const sh = window.SGLVShelf; if (sh && typeof sh.isOpen === 'function' && sh.isOpen()) return; closePanel(); }); } function openPanel() { const overlay = document.getElementById('sf-wf-overlay'); if (overlay && overlay.classList.contains('sf-wf-open')) return; SGIS.open = true; document.body.classList.add('sgis-open'); document.getElementById('sgis-panel').classList.add('sgis-open'); const f = document.getElementById('sgis-fab'); if (f) f.classList.add('sgis-open'); _activateSgisTab(SGIS.tab, { force: false }); } function closePanel() { SGIS.open = false; document.body.classList.remove('sgis-open'); const p = document.getElementById('sgis-panel'); if (p) p.classList.remove('sgis-open'); const f = document.getElementById('sgis-fab'); if (f) f.classList.remove('sgis-open'); } function togglePanel() { if (SGIS.open) closePanel(); else openPanel(); } const _tabPanes = new Map(); const _tabScroll = new Map(); let _sgisSwitchGen = 0; let _paintTab = null; let _sgisSwitchTimer = 0; let _pricesGen = 0; let _historyGen = 0; const SGIS_TAB_SWITCH_MS = 250; function _ensureSgisPane(tab) { let pane = _tabPanes.get(tab); if (!pane) { pane = document.createElement('div'); pane.className = 'sgis-pane'; pane.dataset.sgisPane = tab; _tabPanes.set(tab, pane); } return pane; } function _armSgisTabs(on) { const tabs = document.getElementById('sgis-tabs'); if (!tabs) return; tabs.classList.toggle('is-arming', !!on); if (on) tabs.setAttribute('aria-busy', 'true'); else tabs.removeAttribute('aria-busy'); } function _sgisPaneReady(pane) { if (!pane || pane.dataset.ready !== '1') return false; for (const ch of pane.children) { if (ch.classList.contains('sgis-tab-pending') || ch.classList.contains('sgis-load-block')) return false; } return true; } function _showSgisPane(tab) { const body = document.getElementById('sgis-body'); if (!body) return; const pane = _ensureSgisPane(tab); const already = pane.parentNode === body; Array.from(body.children).forEach(ch => { if (ch === pane) return; if (ch.classList && ch.classList.contains('is-active')) ch.classList.remove('is-active'); ch.remove(); }); if (pane.parentNode !== body) body.appendChild(pane); if (!pane.classList.contains('is-active')) pane.classList.add('is-active'); if (!already) body.scrollTop = _tabScroll.get(tab) || 0; } function _showSgisPending(tab) { const pane = _ensureSgisPane(tab); pane.dataset.ready = ''; pane.innerHTML = '
'; _showSgisPane(tab); const body = document.getElementById('sgis-body'); if (body) body.scrollTop = 0; } function _invalidateSgisPanes() { _tabPanes.forEach(p => { p.dataset.ready = ''; }); } function _activateSgisTab(next, opts) { const force = !!(opts && opts.force); const fromOther = SGIS.tab !== next; const body = document.getElementById('sgis-body'); if (body && SGIS.tab && SGIS.tab !== next) _tabScroll.set(SGIS.tab, body.scrollTop); const root = document.getElementById('sgis-panel'); if (root) root.querySelectorAll('.sgis-tab').forEach(b => b.classList.toggle('active', b.dataset.tab === next)); const pane = _tabPanes.get(next); const ready = _sgisPaneReady(pane); if (!force && next === SGIS.tab && ready) return; if (!force && next === SGIS.tab && pane && !ready) { if (_sgisSwitchTimer || (next === 'prices' && SGIS.pricesLoading)) return; if (pane.querySelector('.sgis-load-block')) return; if (!pane.querySelector('.sgis-tab-pending') && pane.querySelector('.sgis-state')) return; } SGIS.tab = next; if (_sgisSwitchTimer) { clearTimeout(_sgisSwitchTimer); _sgisSwitchTimer = 0; } if (!force && ready) { _armSgisTabs(false); _showSgisPane(next); return; } const gen = ++_sgisSwitchGen; _showSgisPending(next); const run = () => { _sgisSwitchTimer = 0; _armSgisTabs(false); if (gen !== _sgisSwitchGen || SGIS.tab !== next) return; _paintTab = next; renderTab(next, force); }; if (force || !fromOther) { if (typeof requestAnimationFrame === 'function') requestAnimationFrame(run); else setTimeout(run, 0); return; } _armSgisTabs(true); _sgisSwitchTimer = setTimeout(run, SGIS_TAB_SWITCH_MS); } function setBody(html, tab) { const key = tab || _paintTab || SGIS.tab; const pane = _ensureSgisPane(key); pane.innerHTML = html; pane.dataset.ready = '1'; if (key === SGIS.tab) _showSgisPane(key); } function renderLoading(text, tab) { setBody(`
${text || '正在加载…'}
`, tab); if (tab) { const pane = _tabPanes.get(tab); if (pane) pane.dataset.ready = ''; } } function renderProgressLoading(opts) { const cfg = Object.assign({ stage: 1, totalStages: 4, text: '正在加载…', skeletonCount: 8, }, opts || {}); const stagesHtml = stageBarsHtml(cfg.totalStages, cfg.stage, 'sgis-load-stages'); const skelHtml = createSkeleton('sgis', cfg.skeletonCount); setBody(`
${cfg.text}
0%
${stagesHtml}
${skelHtml}
`); return { update(u) { if (!u) return; const fill = document.getElementById('sgis-load-fill'); const pct = document.getElementById('sgis-load-pct'); const text = document.getElementById('sgis-load-stage-text'); const counter = document.getElementById('sgis-load-counter'); const stagesWrap = document.getElementById('sgis-load-stages'); if (u.percent != null) { const p = Math.max(0, Math.min(100, Math.round(u.percent))); if (fill) fill.style.width = p + '%'; if (pct) pct.textContent = p + '%'; } if (u.text != null && text) text.textContent = u.text; if (u.counter != null) { if (counter) { counter.textContent = u.counter; counter.style.display = ''; } } if (u.stage != null && stagesWrap) { const bars = stagesWrap.querySelectorAll('.sgis-load-stage-bar'); bars.forEach((b, i) => { b.classList.remove('active', 'done'); if (i + 1 < u.stage) b.classList.add('done'); else if (i + 1 === u.stage) b.classList.add('active'); }); } }, remove() { const blk = document.getElementById('sgis-load-block'); if (blk) blk.remove(); }, }; } function renderError(text, tab) { setBody(`
${text || '加载失败'}
请检查网络连接或 Steam 登录状态后重试
`, tab); const errTab = tab || _paintTab || SGIS.tab; const retryBtn = (_tabPanes.get(errTab) || document).querySelector('.sgis-retry-btn'); if (retryBtn) { retryBtn.addEventListener('click', () => { resetTabCache(errTab, 'retry'); const cached = _tabPanes.get(errTab); if (cached) cached.dataset.ready = ''; if (SGIS.tab === errTab) _activateSgisTab(errTab, { force: true }); }); } } function extractOverviewFromDOM() { const data = { appId: APP_ID, name: '', cover: '', developer: '', publisher: '', releaseDate: '', platforms: [], tags: [], genres: [], priceCurrent: '', priceOriginal: '', discountPercent: 0, isFree: false, reviews: { recent: { label: '', summary: '', count: '', pos: 0 }, all: { label: '', summary: '', count: '', pos: 0 } }, shortDesc: '', }; const nameEl = document.getElementById('appHubAppName'); if (nameEl) data.name = nameEl.textContent.trim(); if (!data.name) { const og = document.querySelector('meta[property="og:title"]'); if (og) data.name = og.content.replace(/\s+on Steam$/i, '').trim(); } const ogImg = document.querySelector('meta[property="og:image"]'); if (ogImg) data.cover = ogImg.content; const devLink = document.querySelector('#developers_list a, .glance_details a[href*="/developer/"], .game_details a.dev_link'); if (devLink) data.developer = devLink.textContent.trim(); const pubLink = document.querySelector('.glance_details a[href*="/publisher/"]'); if (pubLink) data.publisher = pubLink.textContent.trim(); const releaseEl = document.querySelector('.release_date .date'); if (releaseEl) data.releaseDate = releaseEl.textContent.trim(); const platformsSet = new Set(); const platformNodes = document.querySelectorAll( '.game_area_purchase_game .platform_img, .game_details .platform_img, .game_purchase_platform .platform_img' ); platformNodes.forEach(img => { const cls = (img.className || '').toLowerCase(); if (cls.includes('win')) platformsSet.add('Windows'); else if (cls.includes('mac')) platformsSet.add('macOS'); else if (cls.includes('linux') || cls.includes('steamos')) platformsSet.add('SteamOS + Linux'); }); data.platforms = Array.from(platformsSet); if (data.platforms.length === 0) { const detailsText = (document.querySelector('#game_details, .game_details')?.textContent || '').toLowerCase(); if (/win/i.test(detailsText)) platformsSet.add('Windows'); if (/mac/i.test(detailsText)) platformsSet.add('macOS'); if (/linux/i.test(detailsText)) platformsSet.add('SteamOS + Linux'); data.platforms = Array.from(platformsSet); } document.querySelectorAll('.glance_tags .app_tag, .popular_tags .app_tag').forEach(t => { const txt = t.textContent.trim(); if (txt) data.tags.push(txt); }); data.tags = [...new Set(data.tags)].slice(0, 12); document.querySelectorAll('.glance_details a[href*="/genre/"]').forEach(a => { const g = a.textContent.trim(); if (g) data.genres.push(g); }); const basePurchase = document.querySelector('.game_area_purchase_game'); const qs = sel => (basePurchase || document).querySelector(sel); const freeText = basePurchase ? Array.from(basePurchase.querySelectorAll('.game_purchase_price')).find(p => /free/i.test(p.textContent)) : Array.from(document.querySelectorAll('.game_purchase_price')).find(p => /free/i.test(p.textContent)); const finalPrice = qs('.discount_final_price'); const originalPrice = qs('.discount_original_price'); const discountPct = qs('.discount_pct'); if (freeText) { data.isFree = true; data.priceCurrent = '免费'; } else if (finalPrice) { data.priceCurrent = finalPrice.textContent.trim(); if (originalPrice) data.priceOriginal = originalPrice.textContent.trim(); if (discountPct) { const m = discountPct.textContent.match(/(\d+)/); if (m) data.discountPercent = parseInt(m[1], 10); } } else { const pn = qs('.game_purchase_price'); if (pn) data.priceCurrent = pn.textContent.trim(); } document.querySelectorAll('.user_reviews_summary_row').forEach(row => { const subtitle = row.querySelector('.subtitle')?.textContent?.trim() || ''; const summary = row.querySelector('.game_review_summary')?.textContent?.trim() || ''; const countText = row.querySelector('.responsive_reviewdesc_summary, .review_summary_with_link')?.textContent?.trim() || ''; const countMatch = countText.match(/(\d+(?:[,.]\d+)*)\s*user reviews/); const count = countMatch ? countMatch[1] : ''; const pctMatch = countText.match(/\((\d+)%\)/); const pos = pctMatch ? parseInt(pctMatch[1], 10) : 0; const target = subtitle.includes('All') ? 'all' : 'recent'; data.reviews[target] = { label: subtitle, summary, count, pos }; }); const shortDesc = document.querySelector('.game_description_snippet'); if (shortDesc) data.shortDesc = shortDesc.textContent.trim(); return data; } function extractMoreLikeOverview() { const headerImg = document.querySelector('.recommendation_highlight .header_image'); const tagIdsAttr = headerImg?.getAttribute('data-ds-tagids'); const priceEl = document.querySelector('.highlight_description .regular_price, .highlight_description .discount_final_price'); const priceText = priceEl?.textContent.trim() || ''; const isFree = /免费|free/i.test(priceText); const data = { appId: APP_ID, name: document.querySelector('h2.pageheader')?.textContent.trim() || '', cover: headerImg?.querySelector('img')?.src || '', developer: '', publisher: '', releaseDate: '', platforms: [], tags: [], genres: [], priceCurrent: priceText, priceOriginal: '', discountPercent: 0, isFree, reviews: { recent: { label: '', summary: '', count: '', pos: 0 }, all: { label: '', summary: '', count: '', pos: 0 } }, shortDesc: '', sourceTagIds: tagIdsAttr ? (() => { try { return JSON.parse(tagIdsAttr); } catch { return []; } })() : [], pageType: 'morelike', }; return data; } function extractSimilarGames() { const items = Array.from(document.querySelectorAll('.similar_grid_capsule')).map(a => { const item = a.closest('.similar_grid_item'); const href = a.getAttribute('href') || ''; const nameSlug = (href.match(/\/app\/\d+\/([^/?]+)/) || [])[1] || ''; const priceEl = item?.querySelector('.similar_grid_price .regular_price, .similar_grid_price .discount_final_price, .similar_grid_price .discount_original_price'); const priceText = priceEl?.textContent.trim() || ''; const tagIdsAttr = a.getAttribute('data-ds-tagids'); return { appId: Number(a.getAttribute('data-ds-appid')), tagIds: tagIdsAttr ? (() => { try { return JSON.parse(tagIdsAttr); } catch { return []; } })() : [], href: href.split('?snr=')[0], capsule: a.querySelector('img')?.getAttribute('src') || '', nameSlug: decodeURIComponent(nameSlug).replace(/_/g, ' ').trim() || ('App ' + a.getAttribute('data-ds-appid')), priceText, isFree: /免费|free/i.test(priceText), status: null, }; }).filter(g => g.appId && g.appId !== Number(APP_ID)); return items; } function getDynamicStoreStatus() { if (SGIS.dynamicStoreChecked) return SGIS.dynamicStore; SGIS.dynamicStoreChecked = true; const win = (typeof unsafeWindow !== 'undefined') ? unsafeWindow : window; const store = win.GDynamicStore; if (!store) { SGIS.dynamicStore = null; return null; } const toSet = (raw) => { if (!raw) return new Set(); const arr = Array.isArray(raw) ? raw : Object.keys(raw); return new Set(arr.map(Number)); }; const result = { owned: toSet(store.s_rgOwnedApps), wishlist: toSet(store.s_rgWishlist || win.g_rgWishlist), ignored: toSet(store.s_rgIgnoredApps || win.g_rgIgnoredApps), }; SGIS.dynamicStore = result; return result; } async function fetchDynamicStoreUserData() { if (SGIS.dynamicStoreOwnedApps || SGIS.dynamicStoreFetching) return SGIS.dynamicStoreOwnedApps; SGIS.dynamicStoreFetching = true; try { const ownedApps = await fetchDynamicStoreOwnedAppIds(); SGIS.dynamicStoreOwnedApps = ownedApps; } catch (e) { console.warn('[SGLV] 侧边栏 dynamicstore/userdata 获取失败:', e); } finally { SGIS.dynamicStoreFetching = false; } return SGIS.dynamicStoreOwnedApps; } function annotateSimilarStatus() { if (!SGIS.similarGames) return; const ds = getDynamicStoreStatus(); const hasDs = ds && (ds.owned.size > 0 || ds.wishlist.size > 0 || ds.ignored.size > 0); const localOwned = (!hasDs || ds.owned.size === 0) ? state.ownedAppIds : null; for (const g of SGIS.similarGames) { if (ds) { if (ds.owned.has(g.appId)) { g.status = 'owned'; continue; } if (ds.wishlist.has(g.appId)) { g.status = 'wishlist'; continue; } if (ds.ignored.has(g.appId)) { g.status = 'ignored'; continue; } } if (localOwned && localOwned.has(g.appId)) { g.status = 'owned'; continue; } g.status = null; } } function renderSimilarGamesSection() { if (!IS_MORELIKE) return ''; if (!SGIS.similarGames) return ''; const games = SGIS.similarGames; if (!games.length) return ''; annotateSimilarStatus(); let filtered = games.slice(); if (SGIS.similarFilter === 'owned') filtered = filtered.filter(g => g.status === 'owned'); else if (SGIS.similarFilter === 'unowned') filtered = filtered.filter(g => g.status !== 'owned'); else if (SGIS.similarFilter === 'wishlist') filtered = filtered.filter(g => g.status === 'wishlist'); const parsePrice = (text) => { if (!text || /免费|free/i.test(text)) return 0; const m = text.match(/([\d,.]+)/); return m ? parseFloat(m[1].replace(/,/g, '')) : 0; }; if (SGIS.similarSort === 'priceAsc') filtered.sort((a, b) => parsePrice(a.priceText) - parsePrice(b.priceText)); else if (SGIS.similarSort === 'priceDesc') filtered.sort((a, b) => parsePrice(b.priceText) - parsePrice(a.priceText)); else if (SGIS.similarSort === 'name') filtered.sort((a, b) => a.nameSlug.localeCompare(b.nameSlug)); const limit = SGIS.similarExpanded ? filtered.length : SGIS.similarDisplayLimit; const shown = filtered.slice(0, limit); const ownedCount = games.filter(g => g.status === 'owned').length; const wishlistCount = games.filter(g => g.status === 'wishlist').length; const unownedCount = games.length - ownedCount; const ds = SGIS.dynamicStore; const noDsData = !ds || (ds.owned.size === 0 && ds.wishlist.size === 0 && ds.ignored.size === 0); const loginHint = noDsData ? `` : ''; const sortLabels = { default: '默认', priceAsc: '价格↑', priceDesc: '价格↓', name: '名称' }; const filterButtons = [ { id: 'all', label: '全部', count: games.length, color: null }, { id: 'unowned', label: '未拥有', count: unownedCount, color: null }, { id: 'owned', label: '在库中', count: ownedCount, color: ownedCount ? '#67c1f5' : null }, ]; if (wishlistCount) filterButtons.push({ id: 'wishlist', label: '愿望单', count: wishlistCount, color: null }); const filterHtml = `
${filterButtons.map(f => `` ).join('')}
`; const cardItems = shown.map(g => { const tagHtml = g.status === 'owned' ? '在库中' : g.status === 'wishlist' ? '愿望单' : g.status === 'ignored' ? '已忽略' : ''; const priceClass = g.isFree ? 'free' : (g.priceText ? '' : 'unknown'); const priceDisplay = g.priceText || '价格未知'; return { g, tagHtml, priceClass, priceDisplay }; }); const cardsHtml = (typeof renderGameView === 'function') ? renderGameView(cardItems, { viewMode: 'card', gridCls: 'sgis-sim-grid', cardCls: 'sgis-sim-card', bodyCls: 'sgis-sim-card-body', bareImg: true, imgHtml: (item) => item.g.capsule ? `${item.g.nameSlug}` : '
', bodyHtml: (item) => `${item.tagHtml}
${item.g.nameSlug}
${item.priceDisplay}
`, itemAttrs: (item) => ` href="${item.g.href}" target="_blank" rel="noopener" title="${item.g.nameSlug} (AppID: ${item.g.appId})"`, }) : cardItems.map(item => `${item.tagHtml}${item.g.capsule ? `${item.g.nameSlug}` : '
'}
${item.g.nameSlug}
${item.priceDisplay}
`).join(''); const moreHtml = filtered.length > limit ? `
显示 ${shown.length}/${filtered.length} · 查看全部 →
` : filtered.length > SGIS.similarDisplayLimit && SGIS.similarExpanded ? `` : ''; return `
${SGIS_ICONS.game} 相似游戏推荐 (来自本页 · ${games.length})
${loginHint} ${filterHtml} ${cardsHtml} ${moreHtml}
`; } function bindSimilarGamesEvents() { if (!IS_MORELIKE || !SGIS.similarGames) return; const body = document.getElementById('sgis-body'); if (!body) return; body.querySelectorAll('[data-sim-filter]').forEach(btn => { btn.addEventListener('click', (e) => { e.preventDefault(); SGIS.similarFilter = btn.getAttribute('data-sim-filter'); renderOverview(); }); }); const sortBtn = body.querySelector('[data-sim-sort]'); if (sortBtn) { sortBtn.addEventListener('click', (e) => { e.preventDefault(); const order = ['default', 'priceAsc', 'priceDesc', 'name']; const idx = order.indexOf(SGIS.similarSort); SGIS.similarSort = order[(idx + 1) % order.length]; renderOverview(); }); } const expandBtn = body.querySelector('[data-sim-expand]'); if (expandBtn) { expandBtn.addEventListener('click', (e) => { e.preventDefault(); SGIS.similarExpanded = true; renderOverview(); }); } const collapseBtn = body.querySelector('[data-sim-collapse]'); if (collapseBtn) { collapseBtn.addEventListener('click', (e) => { e.preventDefault(); SGIS.similarExpanded = false; renderOverview(); }); } } const TAG_ID_NAME_MAP = { 19: '动作', 21: '冒险', 122: 'RPG', 128: '单人', 1695: '开放世界', 1754: '大型多人在线', 3859: '免费开玩', 3870: '俯视角', 3964: '像素图形', 4135: '重玩价值', 4168: '视觉小说', 4231: '角色扮演', 4345: '生存', 4747: '多人', 492: '独立', 493: '早期访问', 599: '策略', 597: '休闲', 5350: '类魂', 4625: '派对', 4444: '叙事', 1719: '奇幻', 1720: '科幻', 1742: '射击', 1775: '军事', 1665: '生存', 1646: 'Roguelike', 1684: '合作', 3843: '农场模拟', 4106: '时间管理', 4172: '2D', 4182: '3D', 4663: '卡牌', 4684: '在线对战', 6730: '蒸汽工作室', 723991: '收纳', }; function resolveTagName(tagId) { if (TAG_ID_NAME_MAP[tagId]) return TAG_ID_NAME_MAP[tagId]; const extra = SGIS.appDetailsExtra; if (extra) { const cat = extra.categories.find(c => c.id === tagId); if (cat) return cat.description; const genre = (extra.genreObjs || []).find(g => g.id === tagId); if (genre) return genre.description; } return '标签 ' + tagId; } async function fetchTagRecommendations(tagIds) { if (!tagIds || !tagIds.length) return []; const cacheKey = 'tagRecs_' + tagIds.join(','); const cached = cacheGet(cacheKey); if (cached) return cached; SGIS.tagRecsLoading = true; SGIS.tagRecsError = null; try { const results = await mapLimit(tagIds, 4, async (tagId) => { try { const url = `https://steamcommunity.com/actions/QueryAppsWithTag/${tagId}`; const data = await fetchJson(url, { timeout: 10000 }); const appIds = (data.appids || data || []).slice(0, 50).map(Number); return { tagId, tagName: resolveTagName(tagId), appIds, }; } catch (e) { return { tagId, tagName: resolveTagName(tagId), appIds: [], error: e.message }; } }); const merged = results.filter(r => r.appIds.length); const similarSet = new Set((SGIS.similarGames || []).map(g => g.appId)); for (const r of merged) { r.appIds = r.appIds.filter(id => !similarSet.has(id) && id !== Number(APP_ID)); } const final = merged.filter(r => r.appIds.length); cacheSet(cacheKey, final, 6 * 3600 * 1000); return final; } catch (e) { SGIS.tagRecsError = e.message || '标签推荐获取失败'; return []; } finally { SGIS.tagRecsLoading = false; } } function renderTagRecsSection() { if (!IS_MORELIKE) return ''; const o = SGIS.overview; if (!o || !o.sourceTagIds || !o.sourceTagIds.length) return ''; if (SGIS.tagRecsLoading && !SGIS.tagRecs) { return `
${SGIS_ICONS.tag} 同类型游戏 (按标签扩展)
${(typeof createLoadingHtml === 'function') ? createLoadingHtml('正在从 Steam 标签 API 拉取同类型游戏…', 24) : '正在从 Steam 标签 API 拉取同类型游戏…'}
`; } if (SGIS.tagRecsError && !SGIS.tagRecs) { return `
${SGIS_ICONS.tag} 同类型游戏
${(typeof emptyHtml === 'function') ? emptyHtml('⚠ ' + SGIS.tagRecsError, { icon: '⚠' }) : '⚠ ' + SGIS.tagRecsError}
`; } const recs = SGIS.tagRecs; if (!recs || !recs.length) return ''; const activeTag = SGIS.activeTagId || recs[0].tagId; SGIS.activeTagId = activeTag; const tabsHtml = recs.map(r => { const active = r.tagId === activeTag; return ``; }).join(''); const activeRec = recs.find(r => r.tagId === activeTag); if (!activeRec) return ''; const limit = SGIS.tagRecDisplayLimit; const shownIds = activeRec.appIds.slice(0, limit); const total = activeRec.appIds.length; const ds = SGIS.dynamicStore; const cardItems = shownIds.map(appId => { const status = ds && ds.owned.has(appId) ? 'owned' : ds && ds.wishlist.has(appId) ? 'wishlist' : ds && ds.ignored.has(appId) ? 'ignored' : null; const tagHtml = status === 'owned' ? '在库中' : status === 'wishlist' ? '愿望单' : status === 'ignored' ? '已忽略' : ''; return { appId, tagHtml }; }); const cardsHtml = (typeof renderGameView === 'function') ? renderGameView(cardItems, { viewMode: 'card', gridCls: 'sgis-sim-grid', cardCls: 'sgis-sim-card', bodyCls: 'sgis-sim-card-body', bareImg: true, imgHtml: (item) => `
App ${item.appId}
`, bodyHtml: (item) => `${item.tagHtml}
AppID ${item.appId}
点击查看
`, itemAttrs: (item) => ` href="https://store.steampowered.com/app/${item.appId}/" target="_blank" rel="noopener" title="AppID: ${item.appId}"`, }) : cardItems.map(item => `${item.tagHtml}
App ${item.appId}
AppID ${item.appId}
点击查看
`).join(''); const moreHtml = total > limit ? `
该标签下 ${total} 款 · 仅展示评分较高 ${limit} 款 · 查看全部 →
` : ``; return `
${SGIS_ICONS.tag} 同类型游戏 (按标签扩展)
${tabsHtml}
${cardsHtml} ${moreHtml}
`; } function bindTagRecsEvents() { if (!IS_MORELIKE || !SGIS.tagRecs) return; const body = document.getElementById('sgis-body'); if (!body) return; body.querySelectorAll('[data-tagrec-tab]').forEach(btn => { btn.addEventListener('click', (e) => { e.preventDefault(); SGIS.activeTagId = Number(btn.getAttribute('data-tagrec-tab')); renderOverview(); }); }); } function reviewBar(posPercent) { const color = posPercent >= 80 ? 'var(--sgis-green)' : posPercent >= 50 ? 'var(--sgis-amber)' : 'var(--sgis-rose)'; return `
`; } function renderMyGameStatus() { const info = getCurrentGameInfo(); if (!info.found) { const checkingHint = (!SGIS.dynamicStoreOwnedApps && !SGIS.dynamicStoreFetching) ? '
正在检查 Steam 商店动态数据(CD Key 激活的游戏可能需要此检测)…
' : ''; return `
${SGIS_ICONS.library} 我的游戏库
未在你的游戏库中找到此游戏。
打开导航栏【游戏库】面板,点击「刷新」按钮,即可获取完整的个人游戏库 + 家庭组共享数据。
${checkingHint}
`; } const playtimeHours = info.playtime > 0 ? (info.playtime / 60).toFixed(1) : '0'; const acquiredTime = formatAcquiredTime(info.acquiredTime); let heroClass = '', heroIcon = SGIS_ICONS.check, heroMain = '已拥有', heroSub = ''; if (info.isOwnedByMe) { heroClass = ''; heroMain = '你已拥有'; const sourceLabels = { 'api': 'Web API', 'family': '家庭组', 'scrape': '页面抓取', 'dynamicstore': '商店动态数据', 'dynamicstore_api': '商店动态API', }; heroSub = `来源: ${sourceLabels[info._source] || '缓存'} · ${playtimeHours}h · 入库 ${acquiredTime}`; } else if (info.isSharedOnly) { heroClass = 'shared'; heroIcon = SGIS_ICONS.share; heroMain = '家庭组共享'; const sharer = info.owners.find(o => !o.isMe); heroSub = sharer ? `${sharer.name} 已拥有 · 共享给你 · 入库 ${acquiredTime}` : '由家庭组成员购买'; } let ownerListHtml = ''; if (info.owners.length > 0) { ownerListHtml = `
${SGIS_ICONS.share} 家庭组购买情况
${info.owners.map(o => { const tag = o.isMe ? '你' : (info.isOwnedByMe ? '' : '共享人'); const cls = o.isMe ? 'me' : (info.isOwnedByMe ? '' : 'sharer'); const avatarText = (o.name || '?').slice(0, 1).toUpperCase(); return `
${avatarText}
${o.name} ${tag}
${info.acquiredTime ? `
入库 ${acquiredTime}
` : ''} ${o.playtime != null ? `
${o.playtime > 0 ? `已游玩 ${(o.playtime / 60).toFixed(1)} 小时` : '未游玩'}
` : ''}
`; }).join('')}
${info.owners.filter(o => !o.isMe).length > 0 ? `
共 ${info.owners.length} 位家庭组成员拥有${(!SGIS.familyShareSupported || SGIS.familyShareSupported.supported !== false) ? `,${info.owners.filter(o => !o.isMe).length} 位可共享` : ''}
` : ''}
`; } return `
${heroIcon}
${heroMain}${heroSub}
商店页
${renderFamilyShareIndicator(info)} ${ownerListHtml} `; } async function fetchOwnersPlaytime() { const apiKey = storage.getApiKey(); if (!apiKey) return; if (SGIS.ownersPlaytimeFetching) return; const info = getCurrentGameInfo(); if (!info.found || !info.owners.length) return; const ownersToFetch = info.owners.filter(o => !o.isMe && SGIS.ownersPlaytime[o.steamId] == null); if (!ownersToFetch.length) return; SGIS.ownersPlaytimeFetching = true; try { const results = {}; await Promise.all(ownersToFetch.map(async o => { try { const data = await fetchJson(`https://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=${apiKey}&steamid=${o.steamId}&include_played_free_games=1&format=json`, { timeout: 12000 }); const games = data?.response?.games || []; const target = games.find(g => String(g.appid) === String(APP_ID)); results[o.steamId] = target ? (target.playtime_forever || 0) : 0; } catch { results[o.steamId] = 0; } })); Object.assign(SGIS.ownersPlaytime, results); if (SGIS.tab === 'overview') renderOverview(); } finally { SGIS.ownersPlaytimeFetching = false; } } function sgisIsComingSoon() { try { if (document.querySelector('[class*="game_area_coming_soon"]')) return true; const o = SGIS.overview; const str = String((o && o.releaseDate) || '').trim() || String((document.querySelector('.release_date .date') || {}).textContent || '').trim(); if (!str) return false; if (/coming soon|即将推出|即将宣布|即将发售|to be announced|\btba\b/i.test(str)) return true; const norm = str.replace(/(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日?/, '$1-$2-$3').replace(/,/g, ' '); const ts = Date.parse(norm); return Number.isFinite(ts) && ts > Date.now(); } catch { return false; } } async function fetchCurrentPlayers() { if (SGIS.currentPlayers !== null || SGIS.currentPlayersLoading || SGIS.currentPlayersUnavailable) return; if (sgisIsComingSoon()) { SGIS.currentPlayersUnavailable = true; return; } SGIS.currentPlayersLoading = true; try { const url = `https://api.steampowered.com/ISteamUserStats/GetNumberOfCurrentPlayers/v1/?appid=${APP_ID}`; const data = await sglvGmFetchRetry(url, { timeout: 5000, retries: 0 }); if (data && data.response && data.response.result === 1 && data.response.player_count != null) { SGIS.currentPlayers = { count: data.response.player_count }; } else { SGIS.currentPlayers = null; SGIS.currentPlayersUnavailable = true; } } catch (e) { console.warn('[SGIS] fetchCurrentPlayers failed:', e.message); SGIS.currentPlayers = null; SGIS.currentPlayersUnavailable = true; } finally { SGIS.currentPlayersLoading = false; if (SGIS.tab === 'overview') renderOverview(); } } async function fetchReviewSummary() { if (SGIS.reviewSummary !== null || SGIS.reviewSummaryLoading || SGIS.reviewSummaryUnavailable) return; if (sgisIsComingSoon()) { SGIS.reviewSummaryUnavailable = true; return; } SGIS.reviewSummaryLoading = true; try { const baseUrl = `https://store.steampowered.com/appreviews/${APP_ID}?json=1&purchase_type=all&num_per_page=0`; const [allData, recentData] = await Promise.all([ sglvGmFetchRetry(baseUrl + '&language=all', { timeout: 8000, retries: 0 }), sglvGmFetchRetry(baseUrl + '&language=all&filter=recent', { timeout: 8000, retries: 0 }), ]); const summary = {}; if (allData && allData.query_summary) { const qs = allData.query_summary; summary.totalPositive = qs.total_positive || 0; summary.totalNegative = qs.total_negative || 0; summary.totalReviews = qs.total_reviews || 0; summary.reviewScore = qs.review_score || 0; summary.reviewScoreDesc = qs.review_score_desc || ''; } if (recentData && recentData.query_summary) { const rqs = recentData.query_summary; summary.recentPositive = rqs.total_positive || 0; summary.recentNegative = rqs.total_negative || 0; summary.recentReviews = rqs.total_reviews || 0; summary.recentScoreDesc = rqs.review_score_desc || ''; } if (summary.totalReviews > 0) { SGIS.reviewSummary = summary; } else { SGIS.reviewSummary = null; SGIS.reviewSummaryUnavailable = true; } } catch (e) { console.warn('[SGIS] fetchReviewSummary failed:', e.message); SGIS.reviewSummary = null; SGIS.reviewSummaryUnavailable = true; } finally { SGIS.reviewSummaryLoading = false; if (SGIS.tab === 'overview') renderOverview(); } } function prepareOverviewData() { if (!SGIS.overview) SGIS.overview = IS_MORELIKE ? extractMoreLikeOverview() : extractOverviewFromDOM(); if (IS_MORELIKE && !SGIS.similarGames) { SGIS.similarGames = extractSimilarGames(); annotateSimilarStatus(); } const o = SGIS.overview; const extra = SGIS.appDetailsExtra; return { o, extra, devName: o.developer || (extra && extra.developers.length ? extra.developers.join(', ') : ''), pubName: o.publisher || (extra && extra.publishers.length ? extra.publishers.join(', ') : ''), releaseDate: o.releaseDate || (extra && extra.releaseDate) || '', coverUrl: o.cover || (extra && extra.headerImage) || '', genres: o.genres.length ? o.genres : (extra && extra.genres) || [], platforms: o.platforms.length ? o.platforms : (extra && extra.platforms) || [], }; } function _renderOverviewReviewRow(rev) { if (!rev.count) return ''; const cls = rev.pos >= 80 ? 'pos' : rev.pos >= 50 ? 'mix' : 'neg'; const thumb = rev.pos >= 70 ? 'up' : 'down'; return `
${rev.label || '评测'} ${rev.summary || ''} ${rev.count}
${reviewBar(rev.pos)}`; } function _renderOverviewTagList(tags) { if (!tags.length) return '
无标签
'; return `
${tags.map(t => `${t}`).join('')}
`; } function _renderOverviewPriceRow(o) { const priceLabel = isZh ? '基础价格' : 'Base Price'; if (o.isFree) { return `
${priceLabel}免费
`; } if (o.discountPercent > 0) { return `
${priceLabel}${o.priceCurrent} -${o.discountPercent}%
${o.priceOriginal}
`; } if (o.priceCurrent) { return `
${priceLabel}${o.priceCurrent}
`; } return ''; } function _renderOverviewLinksRow() { return ``; } function _renderOverviewMetaChips(extra) { if (!extra) return ''; const chips = []; if (extra.metacritic && extra.metacritic.score) { const cls = extra.metacritic.score >= 75 ? 'pos' : extra.metacritic.score >= 50 ? 'warn' : 'neg'; const url = extra.metacritic.url || ''; const inner = `${SGIS_ICONS.star} Metacritic ${extra.metacritic.score}`; chips.push(url ? `${inner}` : `${inner}`); } if (extra.recommendations > 0) { chips.push(`${SGIS_ICONS.barChart} ${formatBigNumber(extra.recommendations)} 评测`); } if (extra.achievementsTotal > 0) { chips.push(`${SGIS_ICONS.trophy} ${extra.achievementsTotal} 成就`); } if (extra.dlc.length > 0) { const dlcUrl = `https://store.steampowered.com/dlc/${APP_ID}/`; chips.push(`${SGIS_ICONS.puzzle} ${extra.dlc.length} 个 DLC`); } if (extra.controllerSupport === 'full') { chips.push(`${SGIS_ICONS.gamepad} 完全支持控制器`); } else if (extra.controllerSupport === 'partial') { chips.push(`${SGIS_ICONS.gamepad} 部分支持控制器`); } if (extra.website) { chips.push(`${SGIS_ICONS.external} 官网`); } return chips.length ? `
${chips.join('')}
` : ''; } function _renderOverviewAgeBadge(extra) { if (!extra) return ''; const info = ageBadgeInfo(extra.requiredAge); let html = `${info.icon} ${info.text}`; if (extra.isFree) { html += `免费游戏`; } return html; } function _renderOverviewContentNote(extra) { return (extra && extra.contentDescriptors && extra.contentDescriptors.notes) ? `
${SGIS_ICONS.shield} ${extra.contentDescriptors.notes}
` : ''; } function _renderOverviewXhhInfoRow() { return `
`; } function _renderOverviewSubStatus() { const badges = []; const appIdNum = Number(APP_ID); try { const psplusCache = cacheGet('psplus'); if (psplusCache && Array.isArray(psplusCache) && psplusCache.includes(appIdNum)) { badges.push(`${ICONS.playstation} ${isZh ? 'PS会免' : 'PS Plus'}`); } } catch (e) { } try { const epicCache = cacheGet('epic'); if (epicCache && Array.isArray(epicCache) && epicCache.includes(appIdNum)) { badges.push(`${ICONS.epic} ${isZh ? 'Epic赠送' : 'Epic Free'}`); } } catch (e) { } return badges.length ? `
${badges.join('')}
` : ''; } function _renderOverviewDlcList(extra) { if (!extra || !extra.dlc.length) return ''; const dlcNames = SGIS.dlcNames || {}; const items = extra.dlc.map(dlcId => { const info = dlcNames[dlcId]; const nameClass = info && info.name ? '' : 'loading'; const nameText = info && info.name ? info.name : '加载中…'; const url = `https://store.steampowered.com/app/${dlcId}/`; return ` ${dlcId} ${nameText} ${info && info.isFree ? '免费' : ''} → `; }).join(''); const dlcAllUrl = `https://store.steampowered.com/dlc/${APP_ID}/`; return `
${SGIS_ICONS.puzzle} DLC 列表 (${extra.dlc.length})
${items}
查看全部 DLC →
`; } function _renderOverviewLanguages(extra) { if (!extra || !extra.supportedLanguages || !extra.supportedLanguages.list.length) return ''; const langs = extra.supportedLanguages.list; const shown = langs.slice(0, 12).map(l => `${l.name}${l.audio ? ' ♪' : ''}` ).join(''); const more = langs.length > 12 ? `+${langs.length - 12}` : ''; const noteHtml = extra.supportedLanguages.note ? `
♪ ${extra.supportedLanguages.note}
` : ''; return `
${SGIS_ICONS.globe} 支持语言 (${langs.length})
${shown}${more}
${noteHtml}
`; } function _renderOverviewMovies(extra) { if (!extra || !extra.movies.length) return ''; const storeUrl = `https://store.steampowered.com/app/${APP_ID}/`; const items = extra.movies.map(m => { const playIcon = ``; const streamUrl = m.hls_h264 || m.dash_h264 || m.dash_av1 || ''; const titleParts = [m.name]; if (streamUrl) titleParts.push(`\n流媒体: ${streamUrl}\n(需 VLC/mpv 等播放器打开)`); return ` ${m.name}
${playIcon}
${m.name}
`; }).join(''); return `
${SGIS_ICONS.video} 预告片 (${extra.movies.length})
${items}
点击缩略图在 Steam 商店页观看 · 悬停可查看流媒体清单 URL
`; } function _renderOverviewCategories(extra) { if (!extra || !extra.categories.length) return ''; const pills = extra.categories.map(c => { const isWorkshop = c.id === 30 || /创意工坊|steam\s*workshop/i.test(c.description); return `${c.description}`; }).join(''); return `
${SGIS_ICONS.tag} 游戏特性
${pills}
`; } function _renderOverviewPackages(extra) { if (!extra || !extra.packages.length) return ''; if (extra.packages.length === 1 && !extra.packages[0].discount) return ''; const items = extra.packages.map(p => { const flagHtml = p.isFree ? '免费' : (p.discount > 0 ? `-${p.discount}%` : ''); const priceHtml = p.isFree ? '免费' : (p.priceText ? `${p.priceText}` : ''); return `
${flagHtml} ${p.name} ${priceHtml}
`; }).join(''); return `
${SGIS_ICONS.package} 购买选项
${items}
`; } function _renderOverviewScreenshots(extra) { if (!extra || !extra.screenshots.length) return ''; const items = extra.screenshots.map(s => ` 截图 `).join(''); return `
${SGIS_ICONS.image} 游戏截图
${items}
`; } function _renderOverviewCurrentPlayers() { const cp = SGIS.currentPlayers; if (!cp || cp.count == null) return ''; const countStr = cp.count >= 1000 ? (cp.count / 1000).toFixed(1) + 'k' : String(cp.count); return `
${SGIS_ICONS.users || '👥'}
${countStr} ${isZh ? '人正在游玩' : 'in-game now'}
${isZh ? '当前在线玩家数' : 'Current players'}
`; } function _renderOverviewReviewSummary(o) { const rs = SGIS.reviewSummary; const hasDomReviews = o.reviews.recent.count || o.reviews.all.count; if (!hasDomReviews && !rs) return ''; let apiReviewHtml = ''; if (rs && rs.totalReviews > 0) { const posRate = rs.totalReviews > 0 ? Math.round(rs.totalPositive / rs.totalReviews * 100) : 0; const cls = posRate >= 80 ? 'pos' : posRate >= 50 ? 'mix' : 'neg'; const thumb = posRate >= 70 ? 'up' : 'down'; let recentHtml = ''; if (rs.recentReviews > 0) { const rPosRate = Math.round(rs.recentPositive / rs.recentReviews * 100); const rCls = rPosRate >= 80 ? 'pos' : rPosRate >= 50 ? 'mix' : 'neg'; const rThumb = rPosRate >= 70 ? 'up' : 'down'; recentHtml = `
${isZh ? '近期' : 'Recent'} ${rs.recentScoreDesc || ''} ${rs.recentReviews.toLocaleString()}
${reviewBar(rPosRate)}`; } apiReviewHtml = `
${isZh ? '全部' : 'All'} ${rs.reviewScoreDesc || ''} ${rs.totalReviews.toLocaleString()} ${isZh ? '篇评测' : 'reviews'}
${reviewBar(posRate)}${recentHtml}`; } const domReviewHtml = apiReviewHtml ? '' : (_renderOverviewReviewRow(o.reviews.recent) + _renderOverviewReviewRow(o.reviews.all)); return `
${SGIS_ICONS.star} 评测摘要
${apiReviewHtml || domReviewHtml}
`; } function renderOverview() { _paintTab = 'overview'; const d = prepareOverviewData(); const { o, extra, devName, pubName, releaseDate, coverUrl, genres, platforms } = d; const compactBadges = [renderDRMBadge(), renderChineseAudioBadge(), _renderOverviewAgeBadge(extra), renderProfileStatusBadge()].filter(Boolean).join(''); const compactBadgesHtml = compactBadges ? `
${compactBadges}
` : ''; setBody(`
${coverUrl ? `` : ''}
${o.name || ('游戏 ' + APP_ID)}
${_renderOverviewAliasRow()}
${devName ? `${SGIS_ICONS.package} 开发商 ${devName}` : ''} ${pubName && pubName !== devName ? `${SGIS_ICONS.share} 发行 ${pubName}` : ''} ${releaseDate ? `${releaseDate}` : ''}
${renderMyGameStatus()} ${_renderOverviewSubStatus()} ${compactBadgesHtml} ${_renderOverviewContentNote(extra)} ${renderCrackStatusBadge()} ${renderWorkshopIndicator()}
${SGIS_ICONS.info} 基本信息
${_renderOverviewPriceRow(o)} ${genres.length ? `
类型${genres.join(' / ')}
` : ''} ${_renderOverviewXhhInfoRow()} ${(extra && extra.appType) ? `
应用类型${localizeAppType(extra.appType)}
` : ''} ${platforms.length ? `
平台${platforms.join(' / ')}
` : ''}
AppID${APP_ID}
${_renderOverviewMetaChips(extra)}
${_renderOverviewCategories(extra)} ${_renderOverviewLanguages(extra)} ${o.tags.length ? `
${SGIS_ICONS.info} 热门标签
${_renderOverviewTagList(o.tags)}
` : ''} ${_renderOverviewPackages(extra)} ${_renderOverviewDlcList(extra)} ${_renderOverviewMovies(extra)} ${_renderOverviewScreenshots(extra)} ${o.shortDesc ? `
${SGIS_ICONS.info} 简介
${o.shortDesc}
` : ''} ${_renderOverviewCurrentPlayers()} ${_renderOverviewReviewSummary(o)} ${renderSimilarGamesSection()} ${renderTagRecsSection()}
${SGIS_ICONS.info} 快捷链接
${_renderOverviewLinksRow()}
`); document.querySelectorAll('#sgis-body .sgis-screenshot-item img[data-src]').forEach(img => { img.src = img.dataset.src; }); document.querySelectorAll('#sgis-body .sgis-movie-item img[data-src]').forEach(img => { img.src = img.dataset.src; }); bindSimilarGamesEvents(); bindTagRecsEvents(); if (IS_MORELIKE && o.sourceTagIds && o.sourceTagIds.length && !SGIS.tagRecs && !SGIS.tagRecsLoading) { fetchTagRecommendations(o.sourceTagIds).then(recs => { SGIS.tagRecs = recs; if (SGIS.tab === 'overview') renderOverview(); }).catch(() => {}); } fetchOwnersPlaytime().catch(() => {}); if (HAS_APP_ID) { fetchCurrentPlayers().catch(() => {}); fetchReviewSummary().catch(() => {}); } if (HAS_APP_ID) { fetchGameAlias(APP_ID).then(() => { if (SGIS.tab === 'overview') _applyAliasToDom(APP_ID); }).catch(() => {}); } if (HAS_APP_ID && !SGIS.dynamicStoreOwnedApps && !SGIS.dynamicStoreFetching) { const info = getCurrentGameInfo(); if (!info.found) { fetchDynamicStoreUserData().then(ownedApps => { if (ownedApps && ownedApps.has(Number(APP_ID)) && SGIS.tab === 'overview') { renderOverview(); } }).catch(() => {}); } } } function _getBadgeLib() { return (typeof unsafeWindow !== 'undefined' && unsafeWindow.SGLVBadge) || (typeof window !== 'undefined' && window.SGLVBadge); } function _injectCardDbToBadgeLib() { const B = _getBadgeLib(); if (B && typeof B.setCardDb === 'function' && cardDbData) { B.setCardDb(cardDbData); } } function renderMedals() { if (SGIS.cardsLoading) return; if (SGIS.cards) { renderMedalsContent(); return; } SGIS.cardsLoading = true; renderLoading('正在获取集换式卡牌价格…'); _injectCardDbToBadgeLib(); fetchCardPrices(APP_ID).then(data => { const allCards = [...(data.regular || []), ...(data.foil || [])]; if (allCards.length === 0) { _handleEmptyMarketCards(); } else { SGIS.cards = data; SGIS.cardsLoading = false; renderMedalsContent(); } }).catch(e => { _handleCardFetchError(e); }); } async function _handleEmptyMarketCards() { const B = _getBadgeLib(); if (!B || typeof B.checkCardSupport !== 'function') { SGIS.cards = { regular: [], foil: [], _source: 'market-empty' }; SGIS.cardsLoading = false; renderMedalsContent(); return; } renderLoading('正在检测卡牌支持状态…'); try { const categories = (SGIS.appDetailsExtra && SGIS.appDetailsExtra.categories) || []; const support = await B.checkCardSupport(APP_ID, { categories }); if (support.supported) { _renderSCEFallback(support, 'empty'); } else { SGIS.cards = { regular: [], foil: [], _source: 'no-cards' }; SGIS.cardsLoading = false; renderMedalsContent(); } } catch (e) { SGIS.cards = { regular: [], foil: [], _source: 'market-empty' }; SGIS.cardsLoading = false; renderMedalsContent(); } } async function _handleCardFetchError(error) { _paintTab = 'medals'; const B = _getBadgeLib(); if (!B || typeof B.checkCardSupport !== 'function') { SGIS.cardsLoading = false; renderError('卡牌价格获取失败: ' + error.message); return; } renderLoading('正在检测卡牌支持状态…'); try { const categories = (SGIS.appDetailsExtra && SGIS.appDetailsExtra.categories) || []; const support = await B.checkCardSupport(APP_ID, { categories }); if (support.supported) { _renderSCEFallback(support, 'error', error.message); } else if (support.source === 'none') { SGIS.cardsLoading = false; setBody(`
⚠️
网络错误,无法获取卡牌数据
${error.message}
请检查网络连接后重试
`); } else { SGIS.cards = { regular: [], foil: [], _source: 'no-cards' }; SGIS.cardsLoading = false; renderMedalsContent(); } } catch (e) { SGIS.cardsLoading = false; renderError('卡牌价格获取失败: ' + error.message); } } async function _renderSCEFallback(support, reason, errorMsg) { const B = _getBadgeLib(); let sceData = null; if (support.cards && support.cards.regular) { sceData = support.cards; } else { try { const pageData = await B.fetchCardExchangePage(APP_ID); if (pageData && pageData.supported) { sceData = { regular: pageData.regular, foil: pageData.foil }; } } catch (e) { SGIS.cardsLoading = false; if (reason === 'error') { renderError('卡牌价格获取失败: ' + (errorMsg || '')); } else { SGIS.cards = { regular: [], foil: [], _source: 'market-empty' }; renderMedalsContent(); } return; } } if (!sceData || (!sceData.regular.length && !sceData.foil.length)) { SGIS.cards = { regular: [], foil: [], _source: 'no-cards' }; SGIS.cardsLoading = false; renderMedalsContent(); return; } SGIS.cards = { regular: sceData.regular || [], foil: sceData.foil || [], regularQueried: false, foilQueried: false, _source: 'steamcardexchange', _reason: reason, _errorMsg: errorMsg || '', _supportSource: support.source, }; SGIS.cardsLoading = false; renderMedalsContent(); } function renderMedalsContent() { _paintTab = 'medals'; const data = SGIS.cards; if (data._source === 'steamcardexchange') { renderMedalsSCEContent(data); return; } const allCards = [...(data.regular || []), ...(data.foil || [])]; if (allCards.length === 0) { const isConfirmedNoCards = data._source === 'no-cards'; setBody(`
🎴
${isConfirmedNoCards ? '该游戏没有可交易的集换式卡牌' : '未获取到卡牌数据'}
${isConfirmedNoCards ? '可能不支持 Steam 集换式卡牌' : '可能是网络问题或该游戏不支持卡牌,请重试'}
`); return; } const samplePriceText = allCards.find(c => c.sellPriceText)?.sellPriceText || ''; const curSymbol = (samplePriceText.match(/^([^\d.,\s]+)/) || [])[1] || '¥'; const sellTotal = (data.regular || []).reduce((s, c) => s + (c.sellPrice || 0), 0) / 100; const foilSellTotal = (data.foil || []).reduce((s, c) => s + (c.sellPrice || 0), 0) / 100; const buyTotal = (data.regular || []).reduce((s, c) => s + (c.buyPrice || 0), 0) / 100; const netTotal = (data.regular || []).reduce((s, c) => s + (c.netPrice || 0), 0) / 100; const regPrices = (data.regular || []).filter(c => c.sellPrice != null).map(c => c.sellPrice).sort((a, b) => a - b); let medianPrice = 0, avgNoMax = 0; if (regPrices.length > 0) { const mid = Math.floor(regPrices.length / 2); medianPrice = regPrices.length % 2 !== 0 ? regPrices[mid] : Math.round((regPrices[mid - 1] + regPrices[mid]) / 2); if (regPrices.length > 1) { avgNoMax = Math.round(regPrices.slice(0, -1).reduce((s, p) => s + p, 0) / (regPrices.length - 1)); } else { avgNoMax = regPrices[0]; } } const medianDisplay = medianPrice > 0 ? `${curSymbol}${(medianPrice / 100).toFixed(2)}` : '—'; const avgNoMaxDisplay = avgNoMax > 0 ? `${curSymbol}${(avgNoMax / 100).toFixed(2)}` : '—'; const showing = SGIS.medalTab; const cards = showing === 'foil' ? (data.foil || []) : (data.regular || []); const cardItemHtml = (c) => { const sellMajor = toMajorUnit(c.sellPrice); const buyMajor = toMajorUnit(c.buyPrice); const sellDisplay = c.sellPriceText || (sellMajor != null ? curSymbol + sellMajor.toFixed(2) : ''); const buyDisplay = c.buyPrice != null ? curSymbol + buyMajor.toFixed(2) : (c.buyError ? '—' : ''); const iconHtml = c.iconUrl ? `` : `
${SGIS_ICONS.medalFallback}
`; const hasBg = !!c.iconUrl; return ` ${iconHtml}
${c.name.replace(/\(Foil\)$/i, '').trim()}${c.foil ? '闪' : ''}
${sellDisplay ? `出售 ${sellDisplay}` : ''} ${buyDisplay ? `求购 ${buyDisplay}` : ''}
${c.listings ? `${c.listings}件` : ''}
`; }; setBody(`
${curSymbol}${sellTotal.toFixed(2)}
普通出售合计
${curSymbol}${netTotal.toFixed(2)}
到手价合计
${curSymbol}${buyTotal.toFixed(2)}
求购合计
中位价 (抗极端高价)${medianDisplay}
均价 (忽略最高价)${avgNoMaxDisplay}
${SGIS_ICONS.card} ${showing === 'foil' ? '闪卡' : '普通卡'} 列表
${cards.length ? cards.map(cardItemHtml).join('') : '
无此类卡牌
'}
${(data.foil || []).length ? `
${SGIS_ICONS.info} 闪卡市场
闪卡出售合计${curSymbol}${foilSellTotal.toFixed(2)}
闪卡数量${data.foil.length}
` : ''}
出价数据来自 Steam 社区市场 · ${data.regularQueried ? '已查询' : '查询中'} · v2.9.32 到手价采用可变发行商费率精确计算
`); const body = document.getElementById('sgis-body'); if (body) { body.querySelectorAll('.sgis-card-toggle button').forEach(btn => { btn.addEventListener('click', () => { SGIS.medalTab = btn.dataset.group; renderMedalsContent(); }); }); body.querySelectorAll('.sgis-card-pending-bg[data-bg-url]').forEach(card => { const url = card.dataset.bgUrl; if (!url) return; const probe = new Image(); probe.onload = () => { card.style.setProperty('--sgis-card-bg', `url('${url}')`); card.classList.remove('sgis-card-pending-bg'); card.classList.add('sgis-card-with-bg'); }; probe.onerror = () => { card.classList.remove('sgis-card-pending-bg'); }; probe.src = url; }); } } function renderMedalsSCEContent(data) { _paintTab = 'medals'; const showing = SGIS.medalTab; const cards = showing === 'foil' ? (data.foil || []) : (data.regular || []); const regCount = (data.regular || []).length; const foilCount = (data.foil || []).length; const reasonText = data._reason === 'error' ? `市场数据获取失败(${data._errorMsg || '网络错误'})` : '市场未返回卡牌数据'; const sourceText = data._supportSource === 'appdetails' ? 'Steam 应用详情' : data._supportSource === 'steamcardexchange-api' ? 'SteamCardExchange API' : data._supportSource === 'steamcardexchange-page' ? 'SteamCardExchange 页面' : '卡牌数据库'; const cardItemHtml = (c) => { const iconHtml = `
${SGIS_ICONS.medalFallback}
`; return ` ${iconHtml}
${c.name.replace(/\(Foil\)$/i, '').trim()}${c.foil ? '闪' : ''}
价格数据不可用
`; }; setBody(`
⚠️ ${reasonText}
卡牌列表来自 ${sourceText} · 市场价格需访问 Steam 社区市场获取
${regCount}
普通卡
${foilCount}
闪卡
${regCount + foilCount}
总计
${SGIS_ICONS.card} ${showing === 'foil' ? '闪卡' : '普通卡'} 列表
${cards.length ? cards.map(cardItemHtml).join('') : '
无此类卡牌
'}
`); const body = document.getElementById('sgis-body'); if (body) { body.querySelectorAll('.sgis-card-toggle button').forEach(btn => { btn.addEventListener('click', () => { SGIS.medalTab = btn.dataset.group; renderMedalsContent(); }); }); } } function _pricesPane() { return _tabPanes.get('prices') || null; } function _predictHost() { const pane = _pricesPane(); if (!pane) return null; return pane.querySelector('[data-sgis-price-block="history"]') || pane; } function _fillPriceBlock(name, html) { const pane = _pricesPane(); if (!pane) return null; let el = pane.querySelector('[data-sgis-price-block="' + name + '"]'); if (!html) { if (el) el.remove(); return null; } if (!el) { el = document.createElement('div'); el.dataset.sgisPriceBlock = name; pane.appendChild(el); } el.innerHTML = html; return el; } function _ensurePriceBlock(name) { const pane = _pricesPane(); if (!pane) return null; let el = pane.querySelector('[data-sgis-price-block="' + name + '"]'); if (!el) { el = document.createElement('div'); el.dataset.sgisPriceBlock = name; pane.appendChild(el); } return el; } function _mountHistoryPlaceholder() { _fillPriceBlock('history', `
${SGIS_ICONS.price} 历史价格走势
正在读取历史价格…
`); } function appendHistoryPricesToBody(historyData) { const pane = _pricesPane(); if (!pane) return; const hasData = !!(historyData && (historyData.history?.length || historyData.lowest || historyData.discounts?.length)); const block = _ensurePriceBlock('history'); if (!block) return; block.innerHTML = hasData ? renderHistoryPricesSection(historyData) : ''; if (hasData) bindPriceChartRangeEvents(historyData); appendPredictButton(block, hasData); if (SGIS.prediction) appendPredictionResult(block); } function appendPredictButton(bodyEl, hasHistoryData) { const enabledModes = storage.getPredictModes(); const modesLabel = enabledModes.map(m => { const mode = PREDICT_MODES.find(p => p.key === m); return mode ? mode.name : ''; }).filter(Boolean).join(' / '); const disabled = !hasHistoryData; const disabledText = isZh ? '暂无历史价格数据,无法AI预测' : 'No price history, AI prediction unavailable'; const btnHtml = `
${SGIS.predictionLoading ? `
${T.aiPredicting}
` : ''} ${SGIS.predictionError ? `
⚠️ ${T.aiPredictFail}: ${SGIS.predictionError}
` : ''}
`; const temp = document.createElement('div'); temp.innerHTML = btnHtml; while (temp.firstChild) bodyEl.appendChild(temp.firstChild); const btn = bodyEl.querySelector('#sgis-predict-trigger'); if (btn && !disabled) { btn.addEventListener('click', () => triggerPrediction()); } } function triggerPrediction() { if (SGIS.predictionLoading) { console.log('[SGIS] AI预测已在进行中, 忽略重复点击'); return; } if (!SGIS.historyPrices || (!SGIS.historyPrices.discounts?.length && !SGIS.historyPrices.history?.length)) { console.log('[SGIS] AI预测取消: 无历史价格数据'); showToast(T.aiPredictNoData); return; } const apiKey = storage.getAiApiKey(); if (!apiKey) { console.log('[SGIS] AI预测取消: 未配置 API Key'); showToast(T.aiPredictNoKey); return; } console.log('[SGIS] AI预测按钮点击, 开始流程'); SGIS.predictionLoading = true; SGIS.predictionError = null; SGIS.prediction = null; const liveBtn = () => { const host = _predictHost(); return host && host.querySelector('#sgis-predict-trigger'); }; const restoreBtn = () => { const b = liveBtn(); if (!b) return; b.disabled = false; b.style.opacity = ''; b.style.cursor = ''; b.innerHTML = ` ${T.aiPredictBtn}`; }; const showPredictError = (message) => { const host = _predictHost(); if (!host) return; host.querySelectorAll('.sgis-predict-error').forEach(n => n.remove()); const errDiv = document.createElement('div'); errDiv.className = 'sgis-state sgis-error sgis-predict-error'; errDiv.style.cssText = 'padding:8px'; errDiv.textContent = message; host.appendChild(errDiv); }; const btn = liveBtn(); if (btn) { btn.disabled = true; btn.style.opacity = '0.5'; btn.style.cursor = 'wait'; btn.innerHTML = `
${T.aiPredicting}`; } const host = _predictHost(); let loadingEl = host && host.querySelector('#sgis-predict-loading'); if (!loadingEl && host) { loadingEl = document.createElement('div'); loadingEl.id = 'sgis-predict-loading'; loadingEl.className = 'sgis-state'; loadingEl.style.cssText = 'padding:12px'; loadingEl.innerHTML = `
${T.aiPredicting}`; host.appendChild(loadingEl); } const overview = SGIS.overview || {}; const currentPrice = overview.priceCurrent ? parseFloat(overview.priceCurrent.replace(/[^0-9.]/g, '')) : null; const originalPrice = overview.priceOriginal ? parseFloat(overview.priceOriginal.replace(/[^0-9.]/g, '')) : null; const gameName = overview.name || ''; let timeoutReached = false; const timeoutId = setTimeout(() => { if (SGIS.predictionLoading) { timeoutReached = true; console.warn('[SGIS] AI预测超时 (120s无响应)'); SGIS.predictionLoading = false; const timeoutHost = _predictHost(); const ld = timeoutHost && timeoutHost.querySelector('#sgis-predict-loading'); if (ld) ld.remove(); restoreBtn(); showPredictError(`⚠️ ${T.aiPredictFail}: ${isZh ? '请求超时(120s无响应), 请检查网络或API配置' : 'Request timeout (120s), check network or API config'}`); } }, 120000); callAiPricePredict(SGIS.historyPrices, gameName, APP_ID, currentPrice, originalPrice) .then(result => { clearTimeout(timeoutId); if (timeoutReached) return; console.log('[SGIS] AI预测成功, result:', result); SGIS.prediction = result; SGIS.predictionLoading = false; const doneHost = _predictHost(); const ld = doneHost && doneHost.querySelector('#sgis-predict-loading'); if (ld) ld.remove(); restoreBtn(); if (doneHost) appendPredictionResult(doneHost); }) .catch(e => { clearTimeout(timeoutId); if (timeoutReached) return; console.error('[SGIS] AI预测失败:', e); SGIS.predictionError = e.message; SGIS.predictionLoading = false; const failHost = _predictHost(); const ld = failHost && failHost.querySelector('#sgis-predict-loading'); if (ld) ld.remove(); restoreBtn(); showPredictError(`⚠️ ${T.aiPredictFail}: ${e.message}`); }); } function appendPredictionResult(bodyEl) { if (!SGIS.prediction || !bodyEl) return; bodyEl.querySelectorAll('.sgis-predict-section').forEach(n => n.remove()); const temp = document.createElement('div'); temp.innerHTML = renderPredictionSection(SGIS.prediction); while (temp.firstChild) bodyEl.appendChild(temp.firstChild); } function renderPredictionSection(prediction) { const models = prediction.models || []; const bestBuy = prediction.best_buy || {}; const enabledModes = storage.getPredictModes(); const modesLabel = enabledModes.map(m => { const mode = PREDICT_MODES.find(p => p.key === m); return mode ? mode.name : ''; }).filter(Boolean).join(' / '); const modelsHtml = models.map(m => { const confClass = m.confidence >= 70 ? 'high' : (m.confidence >= 45 ? 'mid' : 'low'); const dateStr = m.target_date ? new Date(m.target_date).toLocaleDateString('zh-CN') : '—'; const saleBadge = m.sale_event ? `${m.sale_event}` : ''; const indicatorsHtml = m.indicators ? Object.entries(m.indicators).map(([k, v]) => `
${k}: ${v}
`).join('') : ''; return `
${m.mode_name || m.mode} ${T.aiPredictConfidence} ${m.confidence}%
${m.prediction || ''}
预测折扣: -${m.discount_percent || 0}% · 到手: ${m.currency || ''}${m.predicted_price != null ? Number(m.predicted_price).toFixed(2) : '—'} · 时间: ${m.days_until != null ? m.days_until + T.aiPredictDays : '—'}${dateStr !== '—' ? ` (${dateStr})` : ''} ${saleBadge}
${m.detail ? `
${m.detail}
` : ''} ${indicatorsHtml ? `
${indicatorsHtml}
` : ''}
`; }).join(''); const urgencyLabel = bestBuy.urgency === 'high' ? '🔴 尽快入手' : (bestBuy.urgency === 'medium' ? '🟡 可以等待' : '🟢 不急'); const bestBuyHtml = bestBuy.recommendation ? `
${T.aiPredictRecommendation} · ${urgencyLabel}
${bestBuy.recommendation}
${bestBuy.best_time ? `
${T.aiPredictBestTime}: ${bestBuy.best_time}
` : ''} ${bestBuy.best_price ? `
预测最佳价格: ${Number(bestBuy.best_price).toFixed(2)}
` : ''} ${bestBuy.wait_days != null ? `
建议等待: ${bestBuy.wait_days}天
` : ''}
` : ''; return `
${SGIS_ICONS.trend || '🔮'} ${T.aiPredictResult}
${modelsHtml} ${bestBuyHtml}
分析模式: ${modesLabel}
`; } function normalizeItadRegionPrices(regionPrices) { const prices = []; const failed = []; const seenKey = new Set(); for (const [country, data] of Object.entries(regionPrices)) { if (!data || !data.deals || !data.deals.length) { failed.push({ region: country, error: 'ITAD 无数据' }); continue; } const deal = data.deals[0]; const priceObj = deal.price || {}; const regularObj = deal.regular || {}; const expCur = (REGIONS.find(r => r.code === country) || {}).currency; if (expCur && priceObj.currency && priceObj.currency !== expCur) { console.debug(`[SGLV] ITAD 币种不匹配 ${country}: 期望 ${expCur}, 实际 ${priceObj.currency}, 跳过该区域`); failed.push({ region: country, error: `币种不匹配(期望${expCur}, 实际${priceObj.currency})` }); continue; } const k = `${priceObj.currency}:${Number(priceObj.amount || 0).toFixed(2)}`; const curShared = Object.keys(regionPrices).filter(x => regionExpectedCurrency(x) === expCur).length > 1; const dupKey = curShared ? null : k; if (dupKey !== null && seenKey.has(dupKey)) { failed.push({ region: country, error: '与已有地区价格重复' }); continue; } if (dupKey !== null) seenKey.add(dupKey); prices.push({ region: country, price: priceObj.amount || 0, currency: priceObj.currency || '', discount: deal.cut || 0, initial: regularObj.amount || 0, source: 'itad', }); } return { prices, failed }; } function appendItadOverviewToBody() { const overview = SGIS.itadOverview; if (!overview || !overview.prices || !overview.prices.length) return; const fmt = (v) => num(v).toFixed(2); const item = overview.prices[0]; let storeCompareHtml = ''; if (item.current) { const cur = item.current; const curPrice = cur.price || {}; const curRegular = cur.regular || {}; const curCut = cur.cut || 0; const isLowest = item.lowest && curPrice.amount <= (item.lowest.price || {}).amount; const cny = convertToCNY(num(curPrice.amount), curPrice.currency); storeCompareHtml = `
${SGIS_ICONS.price} ${isZh ? '最优商店价格' : 'Best Store Price'} ${isLowest ? '史低' : ''}
${isZh ? '商店' : 'Store'}${(cur.shop || {}).name || '—'}
${isZh ? '当前价' : 'Current'}${fmt(curPrice.amount)} ${curPrice.currency || ''} ${curCut > 0 ? '-' + curCut + '%' : ''}
${curCut > 0 ? `
${isZh ? '原价' : 'Regular'}${fmt(curRegular.amount)} ${curRegular.currency || ''}
` : ''} ${cny != null ? `
≈ CNY¥${fmt(cny)}
` : ''}
`; } let histLowHtml = ''; if (item.lowest) { const low = item.lowest; const lowPrice = low.price || {}; const lowCny = convertToCNY(num(lowPrice.amount), lowPrice.currency); const lowDate = low.timestamp ? new Date(low.timestamp).toLocaleDateString(isZh ? 'zh-CN' : 'en-US') : '—'; histLowHtml = `
${isZh ? '历史最低' : 'Historical Low'}${fmt(lowPrice.amount)} ${lowPrice.currency || ''} ${low.cut ? '(-' + low.cut + '%)' : ''} · ${(low.shop || {}).name || ''} · ${lowDate}
`; if (lowCny != null) histLowHtml += `
≈ CNY¥${fmt(lowCny)}
`; } let bundleHtml = ''; if (overview.bundles && overview.bundles.length) { const bundleItems = overview.bundles.map(b => { const tier = b.tiers && b.tiers[0]; const tierPrice = tier && tier.price ? tier.price : {}; const gameCount = b.tiers ? b.tiers.reduce((s, t) => s + (t.games ? t.games.length : 0), 0) : 0; const cny = convertToCNY(num(tierPrice.amount), tierPrice.currency); return `
${b.title || 'Bundle'}${tierPrice.amount ? fmt(tierPrice.amount) + ' ' + (tierPrice.currency || '') : '—'}${cny != null ? ' · ≈¥' + fmt(cny) : ''}${gameCount ? ' · ' + gameCount + (isZh ? '款' : ' games') : ''}
`; }).join(''); bundleHtml = `
${SGIS_ICONS.trend} ${isZh ? '活跃 Bundle' : 'Active Bundles'} (${overview.bundles.length})
${bundleItems}
`; } const badge = `
⚡ ${isZh ? 'ITAD 增强模式' : 'ITAD Enhanced'} · ${isZh ? '数据来自 IsThereAnyDeal API' : 'Data from IsThereAnyDeal API'}
`; _fillPriceBlock('itad', storeCompareHtml + histLowHtml + bundleHtml + badge); } const PRICE_REGIONS_SIG = PRIORITY_REGIONS.join('') + '|' + EXTENDED_REGIONS.join(''); function _pricesCacheKey() { return 'prices_' + APP_ID + '_' + PRICE_REGIONS_SIG; } function _itadCacheKey() { return 'itadOverview_' + APP_ID; } function _historyCacheKey() { return 'historyPrices_' + APP_ID; } function _pricesAreFresh() { if (SGIS.pricesFetchedAt && Date.now() - SGIS.pricesFetchedAt < CACHE_TTL.prices) return true; if (!APP_ID) return false; const peek = cachePeek(_pricesCacheKey()); return !!(peek && peek.fresh); } function _historyIsFresh() { if (!SGIS.historyPrices) return false; if (SGIS.historyFetchedAt && Date.now() - SGIS.historyFetchedAt < CACHE_TTL.historyPrices) return true; if (!APP_ID) return false; const peek = cachePeek(_historyCacheKey()); return !!(peek && peek.fresh); } function _hydratePricesCache() { if (!APP_ID) return; if (!SGIS.prices) { const peeked = cachePeek(_pricesCacheKey()); if (peeked && peeked.data && peeked.data.prices) { SGIS.prices = Object.assign({}, peeked.data, { ratesReady: SGIS.rateReady }); if (peeked.fresh) SGIS.pricesFetchedAt = Date.now(); } } if (!SGIS.historyPrices) { const peeked = cachePeek(_historyCacheKey()); if (peeked && peeked.data) { SGIS.historyPrices = peeked.data; if (peeked.fresh) SGIS.historyFetchedAt = Date.now(); } } if (!SGIS.itadOverview) { const peeked = cachePeek(_itadCacheKey()); if (peeked && peeked.data) SGIS.itadOverview = peeked.data; } } function _clearPricesCache() { SGIS.prices = null; SGIS.historyPrices = null; SGIS.itadOverview = null; SGIS.giftRec = null; SGIS.prediction = null; SGIS.predictionError = null; SGIS.pricesFetchedAt = 0; SGIS.historyFetchedAt = 0; if (!APP_ID) return; cacheDelete(_pricesCacheKey()); cacheDelete(_historyCacheKey()); cacheDelete(_itadCacheKey()); } function _rememberPrices(priceData, opts) { const stored = { prices: (priceData && priceData.prices) || [], failed: (priceData && priceData.failed) || [], }; SGIS.prices = Object.assign({}, stored, { ratesReady: SGIS.rateReady }); if (stored.prices.length) { SGIS.pricesFetchedAt = Date.now(); if (APP_ID) cacheSet(_pricesCacheKey(), stored, CACHE_TTL.prices); } else { SGIS.pricesFetchedAt = 0; } if (!(opts && opts.itad)) { SGIS.itadOverview = null; if (APP_ID) cacheDelete(_itadCacheKey()); } } function _paintPricesFromState() { const body = document.getElementById('sgis-body'); const keepScroll = (SGIS.tab === 'prices' && body) ? body.scrollTop : 0; renderPricesContent(); if (SGIS.itadOverview) appendItadOverviewToBody(); if (SGIS.historyPrices) appendHistoryPricesToBody(SGIS.historyPrices); appendGiftRecommendationToBody(); if (SGIS.tab === 'prices' && body) body.scrollTop = keepScroll; } function _applyPricesResult(priceData, gen, opts) { if (gen !== _pricesGen) return; _rememberPrices(priceData, opts); SGIS.giftRec = calculateGiftRecommendation(SGIS.prices); _paintPricesFromState(); _ensureHistory(gen); } function _ensureHistory(gen) { if (_historyIsFresh() || SGIS.historyPricesLoading) return; _loadHistoryPricesAppend(gen); } function _loadHistoryPricesAppend(gen) { const token = ++_historyGen; if (!SGIS.historyPrices) _mountHistoryPlaceholder(); SGIS.historyPricesLoading = true; fetchHistoryPrices(APP_ID).then(historyData => { if (gen !== _pricesGen || token !== _historyGen) return; const prevLow = SGIS.historyPrices && SGIS.historyPrices.lowest; const nextLow = historyData && historyData.lowest; const lowChanged = JSON.stringify(prevLow || null) !== JSON.stringify(nextLow || null); SGIS.historyPrices = historyData; SGIS.historyFetchedAt = Date.now(); if (lowChanged) _paintPricesFromState(); else appendHistoryPricesToBody(historyData); }).catch(() => { if (gen !== _pricesGen || token !== _historyGen) return; if (!SGIS.historyPrices) appendHistoryPricesToBody(null); }).finally(() => { if (token === _historyGen) SGIS.historyPricesLoading = false; }); } function _startPricesFetch(opts) { const gen = ++_pricesGen; const silent = !!(opts && opts.silent); SGIS.pricesLoading = true; const useItadEnhanced = _itad && storage.getItadApiKey() && _itad.hasApiKey(); if (!silent) { renderLoading(useItadEnhanced ? (isZh ? '正在获取 ITAD 增强价格…' : 'Fetching ITAD enhanced prices…') : (isZh ? '正在获取多地区价格…' : 'Fetching multi-region prices…'), 'prices'); } refreshRates().catch(() => {}); const fail = (err) => { if (gen !== _pricesGen) return; const message = (err && err.message) || ''; console.warn('[SGIS] 价格获取失败:', message); if (!silent || !SGIS.prices) { renderError(isZh ? '价格获取失败: ' + message : 'Price fetch failed: ' + message, 'prices'); } }; const done = () => { if (gen === _pricesGen) SGIS.pricesLoading = false; }; if (useItadEnhanced) { (async () => { try { const itadId = await _itad.lookupItadId(APP_ID); if (!itadId) throw new Error('ITAD lookup 失败'); const [overview, regionPrices] = await Promise.all([ _itad.fetchPriceOverview([itadId], { country: 'US' }), _itad.fetchMultiRegionPrices(itadId, EXTENDED_REGIONS, { shops: [_itad.SHOP_STEAM], concurrency: 3 }), ]); if (gen !== _pricesGen) return; const normalized = normalizeItadRegionPrices(regionPrices); SGIS.itadOverview = overview; if (APP_ID) cacheSet(_itadCacheKey(), overview, CACHE_TTL.prices); _applyPricesResult(normalized, gen, { itad: true }); } catch (e) { console.warn('[SGIS] ITAD 增强失败, 回退基础模式:', e.message); try { const priceData = await fetchMultiRegionPrices(APP_ID); if (gen !== _pricesGen) return; _applyPricesResult(priceData, gen); } catch (err) { fail(err); } } finally { done(); } })(); return; } fetchMultiRegionPrices(APP_ID) .then(priceData => { if (gen === _pricesGen) _applyPricesResult(priceData, gen); }) .catch(fail) .finally(done); } function renderPrices(force) { force = force === true; if (force) _clearPricesCache(); else if (!SGIS.prices) _hydratePricesCache(); if (!force && SGIS.prices) { _paintPricesFromState(); if (_pricesAreFresh() || SGIS.pricesLoading) { _ensureHistory(_pricesGen); return; } _startPricesFetch({ silent: true }); return; } if (!force && SGIS.pricesLoading) return; _startPricesFetch({ silent: false }); } function renderPricesContent() { const data = SGIS.prices; const userRegion = (document.cookie.match(/steamCountry=(\w{2})/) || [])[1] || 'CN'; if (!data.prices || !data.prices.length) { const failText = data.failed && data.failed.length ? data.failed.map(f => `${f.region}: ${f.error}`).slice(0, 5).join(' / ') : '未知原因'; setBody(`
💱
未获取到任何地区的价格数据
失败: ${failText}
可能是 Steam 限流或网络问题,稍后重试
`, 'prices'); return; } const fmt = (v) => num(v).toFixed(2); const storedTarget = storage.getPriceTargetCurrency(); const targetInfo = getEffectivePriceTarget(storedTarget); const targetCur = targetInfo.code; const curSym = priceTargetCurInfo(targetCur).symbol; const enriched = data.prices.map(p => { const safePrice = num(p.price); const conv = convertToCurrency(safePrice, p.currency, targetCur); const info = REGIONS.find(r => r.code === p.region) || { name: p.region, code: p.region }; return Object.assign({}, p, { price: safePrice, initial: num(p.initial), discount: num(p.discount), conv: conv != null ? num(conv) : null, regionName: info, }); }).filter(p => p.conv != null && p.currency !== 'FREE' && p.price > 0); if (!enriched.length) { setBody(`
💱
未获取到有效的价格数据 (${data.prices.length} 个地区失败)
`, 'prices'); return; } enriched.sort((a, b) => a.conv - b.conv); const lowest = enriched[0]; const highest = enriched[enriched.length - 1]; const flagHtml = (p) => { const url = flagUrl(p.region); return `${p.region}`; }; const lowestDiscount = lowest.discount > 0 ? `-${lowest.discount}%` : ''; const lowestOriginal = lowest.discount > 0 ? `${fmt(lowest.initial)}` : ''; const featuredHtml = ` `; const priceTableRowHtml = (p) => { const isUser = p.region === userRegion; const isLowest = p.region === lowest.region; const isHighest = p.region === highest.region && enriched.length > 1; const rowCls = isLowest ? 'sgis-price-tbl-row-lowest' : (isHighest ? 'sgis-price-tbl-row-highest' : ''); const userTag = isUser ? '本区' : ''; const badge = isLowest ? '最低' : (isHighest ? '最高' : ''); const discountCell = p.discount > 0 ? `-${p.discount}%` : '—'; const initialCell = p.discount > 0 ? `${fmt(p.initial)}` : `—`; return `
${flagHtml(p)} ${p.regionName.name} ${userTag}${badge}
${initialCell}
${fmt(p.price)} ${p.currency}
${discountCell}
${curSym}${fmt(p.conv)}
`; }; const userPrice = enriched.find(p => p.region === userRegion); let historyCompareHtml = ''; if (SGIS.historyPrices && SGIS.historyPrices.lowest && userPrice) { const histLow = SGIS.historyPrices.lowest; const histConv = convertToCurrency(num(histLow.price), histLow.currency, targetCur); if (histConv != null) { const diff = userPrice.conv - num(histConv); const diffPct = (diff / userPrice.conv) * 100; const isHigher = diff > 0; historyCompareHtml = `
${SGIS_ICONS.trend} 当前价格 vs 历史最低
本区当前${curSym}${fmt(userPrice.conv)}
历史最低${curSym}${fmt(histConv)}${histLow.cut ? ` (-${histLow.cut}%)` : ''}
价差${isHigher ? '↑' : '↓'} ${curSym}${fmt(Math.abs(diff))} (${Math.abs(diffPct).toFixed(1)}%)
`; } } const sources = [...new Set(enriched.map(p => p.source))]; const sourceText = sources.map(s => s === 'aug' ? 'AugmentedSteam' : s === 'steam' ? 'Steam 官方' : s).join(' + '); const attemptedRegions = data.prices.length + (data.failed || []).length; const usdRegionsNote = (() => { const names = REGIONS.filter(r => r.usd).map(r => r.name); return names.length ? `${names.join('、')}已按美元结算(与美区同源),默认不比价` : ''; })(); const failedList = data.failed || []; const failedDetailHtml = failedList.length ? `
${SGIS_ICONS.info} 未取到报价的区
${failedList.map(f => { const ri = REGIONS.find(x => x.code === f.region); return `${escHtml(ri ? ri.name : f.region)}:${escHtml(f.error || '未知原因')}`; }).join('
')}
` : ''; const curOptions = PRICE_TARGET_CURRENCIES.map(c => ``).join(''); const curFallbackHint = targetInfo.fallback ? `
⚠ ${targetInfo.wanted} 汇率未就绪,暂按 ¥ CNY 折算(刷新汇率后生效)
` : ''; setBody(`
${SGIS_ICONS.price} 多地区低价排行 比价
${curFallbackHint} ${featuredHtml}
${SGIS_ICONS.barChart} ${attemptedRegions}区完整价格对比
区域
原价
折后价
折扣
${targetCur}
${enriched.map(priceTableRowHtml).join('')}
${historyCompareHtml}
${SGIS_ICONS.info} 比价概览
最低价${curSym}${fmt(lowest.conv)} (${lowest.regionName.name})
最高价${curSym}${fmt(highest.conv)} (${highest.regionName.name})
价差幅度${curSym}${fmt(highest.conv - lowest.conv)} (${((highest.conv - lowest.conv) / lowest.conv * 100).toFixed(1)}%)
本地区${userRegion}${userPrice ? ` · ${curSym}${fmt(userPrice.conv)}` : ''}
有效价格${enriched.length} / ${attemptedRegions} 区
失败/重复${(data.failed || []).length}
数据源${sourceText}
${failedDetailHtml} ${usdRegionsNote ? `
${usdRegionsNote}
` : ''}
旗帜来自 flagcdn.com · 价格仅供参考 · 3并发+1s限速
`, 'prices'); const curSelect = (_pricesPane() || document).querySelector('#sgis-price-target-cur'); if (curSelect) { curSelect.addEventListener('change', () => { storage.setPriceTargetCurrency(curSelect.value); _paintPricesFromState(); }); } } function detectDRM() { if (SGIS.drmInfo) return SGIS.drmInfo; const results = []; const purchaseSections = document.querySelectorAll('.game_area_purchase_game, .game_area_description, .game_details'); const drmPatterns = [ { regex: /denuvo/i, label: 'Denuvo Anti-Tamper', severity: 'warn' }, { regex: /securom/i, label: 'SecuROM', severity: 'warn' }, { regex: /games for windows live|GFWL/i, label: 'Games for Windows Live', severity: 'warn' }, { regex: /uplay/i, label: 'Ubisoft Connect (Uplay)', severity: 'info' }, { regex: /rockstar.*launcher|RGL/i, label: 'Rockstar Launcher', severity: 'info' }, { regex: /ea.*app|origin.*client/i, label: 'EA App', severity: 'info' }, { regex: /bethesda.*launcher/i, label: 'Bethesda Launcher', severity: 'info' }, { regex: /3rd.party.drm|third.party.drm/i, label: '第三方 DRM', severity: 'warn' }, ]; const found = new Set(); purchaseSections.forEach(sec => { const text = sec.textContent || ''; drmPatterns.forEach(p => { if (p.regex.test(text) && !found.has(p.label)) { found.add(p.label); results.push({ label: p.label, severity: p.severity }); } }); }); const extra = SGIS.appDetailsExtra; if (extra && extra.contentDescriptors && extra.contentDescriptors.notes) { const notes = extra.contentDescriptors.notes; if (/denuvo/i.test(notes) && !found.has('Denuvo Anti-Tamper')) { results.push({ label: 'Denuvo Anti-Tamper', severity: 'warn' }); } } SGIS.drmInfo = { list: results, hasDRM: results.length > 0 }; return SGIS.drmInfo; } const _DETECT_BADGE_DEFS = { drm: { iconKey: 'shield', cls: 'sgis-drm-badge', label: 'DRM', detect: () => { const drm = (typeof detectDRM === 'function') ? detectDRM() : null; if (!drm) return { state: 'unknown' }; if (drm.hasDRM) return { state: 'true', items: drm.list.map(x => x.label) }; return { state: 'false' }; }, render: (info) => { if (info.state !== 'true' || !info.items || !info.items.length) return ''; return info.items.map(label => `${SGIS_ICONS.shield} ${label}`).join(''); }, }, audio: { iconKey: 'globe', cls: 'sgis-audio-badge', label: '中文语音', detect: () => { const extra = (typeof SGIS !== 'undefined') ? SGIS.appDetailsExtra : null; if (!extra || !extra.supportedLanguages || !extra.supportedLanguages.list.length) return { state: 'unknown' }; const langs = extra.supportedLanguages.list; const chineseAudio = langs.find(l => /chinese|中文/i.test(l.name) && l.audio); if (!chineseAudio) return { state: 'false' }; return { state: 'true', name: chineseAudio.name }; }, render: (info) => { if (info.state !== 'true') return ''; return `${SGIS_ICONS.globe} ${info.name} 语音支持`; }, }, profile: { iconKey: 'profileLimited', cls: 'sgis-profile-badge', label: '资料状态', detect: () => { const info = (typeof detectProfileFeaturesStatus === 'function') ? detectProfileFeaturesStatus() : null; if (!info) return { state: 'unknown' }; if (info.status === 'normal') return { state: 'false' }; return { state: 'true', subStatus: info.status, label: info.label }; }, render: (info) => { if (info.state !== 'true') return ''; const title = info.subStatus === 'restricted' ? 'Profile Features Limited:该游戏的卡片、成就、游玩时长等资料不会显示在 Steam 个人资料页' : 'Steam 正在了解该游戏,部分资料功能可能暂时受限'; return `${SGIS_ICONS.profileLimited} ${escHtml(info.label)}`; }, }, crack: { iconKey: 'shield', cls: 'sgis-crack-badge', label: '破解状态', detect: () => { const info = (typeof SGIS !== 'undefined') ? SGIS.gameStatusInfo : null; if (!info) return { state: 'unknown' }; if (info.notFound) return { state: 'unknown' }; const status = String(info.status || '').toLowerCase(); let cls = ''; if (/cracked|взлом/.test(status)) cls = 'cracked'; else if (/bypass|обход|hypervisor/.test(status) || /bypass|обход/.test(String(info.hackedGroups || '').toLowerCase())) cls = 'bypass'; else if (/not cracked|не взлом|unbroken|unreleased/.test(status)) cls = 'not-cracked'; else if (/release today|релиз сегодня|выходит сегодня/.test(status)) cls = 'release-today'; return { state: 'true', cls, label: info.status || '未知' }; }, render: (info) => { if (info.state !== 'true') return ''; return `${SGIS_ICONS.shield} ${escHtml(info.label)}`; }, }, aaa: { iconKey: 'shield', cls: 'sgis-crack-badge aaa', label: 'AAA', detect: () => { const info = (typeof SGIS !== 'undefined') ? SGIS.gameStatusInfo : null; if (!info || info.notFound) return { state: 'unknown' }; return info.isAAA ? { state: 'true' } : { state: 'false' }; }, render: (info) => { if (info.state !== 'true') return ''; return 'AAA'; }, }, protection: { iconKey: 'shield', cls: 'sgis-crack-protection', label: '保护机制', detect: () => { const info = (typeof SGIS !== 'undefined') ? SGIS.gameStatusInfo : null; if (!info || info.notFound || !info.protections) return { state: 'unknown' }; const items = String(info.protections).split(/[,;/|]+/).map(s => s.trim()).filter(Boolean); if (!items.length) return { state: 'false' }; return { state: 'true', items }; }, render: (info) => { if (info.state !== 'true' || !info.items) return ''; return info.items.map(p => `${escHtml(p)}`).join(''); }, }, }; function renderDRMBadge() { const drm = detectDRM(); if (!drm.hasDRM) return ''; return drm.list.map(d => { const cls = d.severity === 'warn' ? 'warn' : ''; return `${SGIS_ICONS.shield} ${d.label}`; }).join(''); } function renderChineseAudioBadge() { const extra = SGIS.appDetailsExtra; if (!extra || !extra.supportedLanguages || !extra.supportedLanguages.list.length) return ''; const langs = extra.supportedLanguages.list; const chineseAudio = langs.find(l => /chinese|中文/i.test(l.name) && l.audio ); if (!chineseAudio) return ''; return `${SGIS_ICONS.globe} ${chineseAudio.name} 语音支持`; } function detectProfileFeaturesStatus() { if (SGIS.profileFeaturesStatus) return SGIS.profileFeaturesStatus; const learningEl = document.querySelector('.game_area_details_specs_ctn.learning_about'); let result; if (!learningEl) { result = { status: 'normal', label: '资料正常', source: 'dom' }; } else { const labelEl = learningEl.querySelector('.label'); const labelText = (labelEl ? labelEl.textContent : '') || learningEl.textContent || ''; if (/Profile\s+Features\s+Limited/i.test(labelText)) { result = { status: 'restricted', label: '资料受限', source: 'dom' }; } else { result = { status: 'learning', label: 'Steam正在了解', source: 'dom' }; } } SGIS.profileFeaturesStatus = result; return result; } async function fetchProfileFeaturesStatus(appId) { if (!appId) return null; if (SGIS.profileFeaturesStatus && SGIS.profileFeaturesStatus._appId === String(appId)) { return SGIS.profileFeaturesStatus; } const cached = cacheGet('profileFeatures_' + appId); if (cached) { SGIS.profileFeaturesStatus = { ...cached, _appId: String(appId) }; return SGIS.profileFeaturesStatus; } const url = `https://store.steampowered.com/app/${appId}/?l=english&cc=us`; try { const html = await sglvGmFetchTextRetry(url, { timeout: 15000, headers: { 'Accept': 'text/html', 'Accept-Language': 'en-US,en;q=0.9', 'Cookie': 'mature_content=1; birthtime=441734400; lastagecheckage=1-January-1900; Steam_Language=english', }, }); const doc = new DOMParser().parseFromString(html, 'text/html'); const learningEl = doc.querySelector('.game_area_details_specs_ctn.learning_about'); let result; if (!learningEl) { result = { status: 'normal', label: '资料正常', source: 'fetch' }; } else { const labelEl = learningEl.querySelector('.label'); const labelText = (labelEl ? labelEl.textContent : '') || learningEl.textContent || ''; if (/Profile\s+Features\s+Limited/i.test(labelText)) { result = { status: 'restricted', label: '资料受限', source: 'fetch' }; } else { result = { status: 'learning', label: 'Steam正在了解', source: 'fetch' }; } } result._appId = String(appId); SGIS.profileFeaturesStatus = result; cacheSet('profileFeatures_' + appId, result, CACHE_TTL.profileFeatures); return result; } catch (e) { console.warn('[SGIS] 资料受限状态获取失败:', appId, e.message); return null; } } function renderProfileStatusBadge() { const info = detectProfileFeaturesStatus(); if (!info || info.status === 'normal') return ''; const cls = info.status || 'normal'; const title = info.status === 'restricted' ? 'Profile Features Limited:该游戏的卡片、成就、游玩时长等资料不会显示在 Steam 个人资料页' : 'Steam 正在了解该游戏,部分资料功能可能暂时受限'; return `${SGIS_ICONS.profileLimited} ${escHtml(info.label)}`; } const GAMESTATUS_API = 'https://gamestatus.info/back/api/gameinfo/game'; const GAMESTATUS_MAX_SLUGS = 2; function slugifyGameStatus(text) { return String(text || '') .toLowerCase() .normalize('NFKD') .replace(/[\u0300-\u036f]/g, '') .replace(/[™®©'':"]/g, '') .replace(/[^a-z0-9]+/g, '-') .replace(/^-+|-+$/g, '') .replace(/-+/g, '-'); } function buildGameStatusSlugs(appId, gameName) { const candidates = []; const add = (slug) => { if (slug && slug.length > 1 && !candidates.includes(slug)) candidates.push(slug); }; const pathMatch = location.pathname.match(/\/app\/\d+\/([^/?#]+)/i); if (pathMatch) add(slugifyGameStatus(pathMatch[1].replace(/_/g, '-'))); const name = String(gameName || '').replace(/\s+/g, ' ').trim(); if (name) { add(slugifyGameStatus(name)); add(slugifyGameStatus(name.replace(/\s*[-–—:|].*$/, ''))); } return candidates.slice(0, GAMESTATUS_MAX_SLUGS); } async function fetchGameStatus(appId, gameName) { if (SGIS.gameStatusInfo) return SGIS.gameStatusInfo; const cached = cacheGet('gameStatus_' + appId); if (cached) { SGIS.gameStatusInfo = cached; return cached; } const slugs = buildGameStatusSlugs(appId, gameName); if (!slugs.length) return null; for (const slug of slugs) { try { const url = `${GAMESTATUS_API}/${encodeURIComponent(slug)}/`; const data = await sglvGmFetchRetry(url, { timeout: 10000, headers: { 'Accept': 'application/json', 'Accept-Language': 'zh-CN' }, }); if (data && (!data.steam_prod_id || String(data.steam_prod_id) === String(appId))) { const hw = [ data.cpu_info && { k: 'CPU', v: data.cpu_info }, data.ram_info && { k: 'RAM', v: data.ram_info }, data.gpu_info && { k: 'GPU', v: data.gpu_info }, data.os_info && { k: 'OS', v: data.os_info }, ].filter(Boolean); const result = { status: data.readable_status || '', protections: data.protections || '', hackedGroups: data.hacked_groups_en || data.hacked_groups || '', crackDate: data.crack_date || '', isAAA: !!data.is_AAA, userScore: data.user_score || null, metacriticScore: data.mata_score || null, releaseDate: data.release_date || '', hardware: hw.length ? hw : null, slug: data.slug || slug, }; SGIS.gameStatusInfo = result; cacheSet('gameStatus_' + appId, result, CACHE_TTL.gameStatus); return result; } } catch { } } SGIS.gameStatusInfo = { notFound: true }; cacheSet('gameStatus_' + appId, { notFound: true }, CACHE_TTL.gameStatus); return SGIS.gameStatusInfo; } const XIAOHEIHE_GAME_API = 'https://api.xiaoheihe.cn/game/web/get_game_detail/'; const _gameAliasInflight = new Map(); const SGIS_ALIAS_BLOCK = ['你妈', '妈的', '傻逼', '草泥马']; function sgisFilterAlias(s) { if (!s || typeof s !== 'string') return ''; const t = s.trim(); if (!t || t.length > 30) return ''; if (!/[\u3400-\u4dbf\u4e00-\u9fff]/.test(t)) return ''; for (const w of SGIS_ALIAS_BLOCK) { if (t.indexOf(w) >= 0) return ''; } return t; } function sgisResolveDisplayName(currentName, info) { const cur = String(currentName || '').trim(); const zh = sgisFilterAlias(info && info.xhhName); const en = String((info && info.enName) || '').trim(); const replaced = !!(zh && zh !== cur); const contains = (hay, sub) => !!hay && !!sub && hay.toLowerCase().indexOf(sub.toLowerCase()) >= 0; const showEnPill = !!(en && !contains(cur, en) && !contains(zh, en)); return { zh, en, replaced, showEnPill }; } function fetchGameAlias(appId) { if (!appId) return Promise.resolve(null); const key = String(appId); if (SGIS.gameAlias && SGIS.gameAlias._appId === key) { return Promise.resolve(SGIS.gameAlias); } if (_gameAliasInflight.has(key)) return _gameAliasInflight.get(key); const cached = cacheGet('gameAlias_' + key); if (cached) { SGIS.gameAlias = cached; return Promise.resolve(cached); } const p = Promise.all([ fetchGameEnName(appId).catch(() => null), fetchXiaoheiheGameName(appId).catch(() => null), ]).then(([enRes, xhhRes]) => { const result = { _appId: key, enName: enRes, xhhName: xhhRes && xhhRes.name || '', xhhScore: xhhRes && xhhRes.score || '', xhhGenres: xhhRes && xhhRes.genres || [], _fetchedAt: Date.now(), }; const hasAny = !!(result.enName || result.xhhName); SGIS.gameAlias = hasAny ? result : { _appId: key, notFound: true, _fetchedAt: Date.now() }; cacheSet('gameAlias_' + key, SGIS.gameAlias, hasAny ? CACHE_TTL.gameAlias : CACHE_TTL.gameAliasMiss); _gameAliasInflight.delete(key); return SGIS.gameAlias; }).catch((e) => { console.warn('[SGIS] 游戏别名获取失败:', appId, e && e.message); _gameAliasInflight.delete(key); SGIS.gameAlias = { _appId: key, notFound: true, _fetchedAt: Date.now() }; cacheSet('gameAlias_' + key, SGIS.gameAlias, CACHE_TTL.gameAliasMiss); return SGIS.gameAlias; }); _gameAliasInflight.set(key, p); return p; } async function fetchXiaoheiheGameName(appId) { const url = `${XIAOHEIHE_GAME_API}?_time=${Math.floor(Date.now() / 1000)}&appid=${encodeURIComponent(appId)}`; try { const text = await sglvGmFetchTextRetry(url, { timeout: 12000, headers: { 'Accept': 'application/json', 'Accept-Language': 'zh-CN,zh;q=0.9' }, }); if (!text || /
`; } function _applyAliasToDom(appId) { const info = SGIS.gameAlias; if (!info || info._appId !== String(appId)) return; const curName = String((SGIS.overview && SGIS.overview.name) || '').trim(); const alias = sgisResolveDisplayName(curName, info); const heroNameEl = document.querySelector('#sgis-body .sgis-hero-name'); if (heroNameEl && alias.replaced) { heroNameEl.textContent = alias.zh; heroNameEl.title = `${alias.zh} (${curName})`; } const slot = document.querySelector(`#sgis-body [data-sgis-alias-appid="${appId}"]`); if (slot) { slot.innerHTML = (!info.notFound && alias.en && alias.showEnPill) ? ` Steam EN ${escHtml(alias.en)} ` : ''; } const xhhSlot = document.querySelector(`#sgis-body [data-sgis-xhh-info-appid="${appId}"]`); if (xhhSlot) { if (!info || info.notFound || (!info.xhhScore && (!info.xhhGenres || !info.xhhGenres.length))) { xhhSlot.innerHTML = ''; } else { const rows = []; if (info.xhhScore) { rows.push(`
小黑盒评分${escHtml(info.xhhScore)}
`); } if (info.xhhGenres && info.xhhGenres.length) { rows.push(`
小黑盒分类${info.xhhGenres.map(escHtml).join(' / ')}
`); } xhhSlot.innerHTML = rows.join(''); } } } function renderCrackStatusBadge() { const info = SGIS.gameStatusInfo; if (!info || info.notFound) return ''; const status = String(info.status || '').toLowerCase(); let cls = '', label = info.status || '未知'; if (/cracked|взлом/.test(status)) { cls = 'cracked'; label = info.status; } else if (/bypass|обход|hypervisor/.test(status) || /bypass|обход/.test(String(info.hackedGroups).toLowerCase())) { cls = 'bypass'; } else if (/not cracked|не взлом|unbroken|unreleased/.test(status)) { cls = 'not-cracked'; } else if (/release today|релиз сегодня|выходит сегодня/.test(status)) { cls = 'release-today'; } const crackDateStr = info.crackDate ? new Date(info.crackDate).toLocaleDateString('zh-CN') : ''; const groups = String(info.hackedGroups || '').split(/[,;/|]+/).map(s => s.trim()).filter(Boolean); const groupChips = groups.map(g => `破解组${escHtml(g)}` ).join(''); const chips = [ `${SGIS_ICONS.shield} ${label}`, crackDateStr ? `破解于 ${crackDateStr}` : '', groupChips, ].filter(Boolean).join(''); if (!chips && !info.hardware) return ''; const escHw = (s) => String(s || '').replace(/&/g,'&').replace(//g,'>').replace(/"/g,'"'); const hwHtml = info.hardware && info.hardware.length ? `
${SGIS_ICONS.info} 硬件需求 (gamestatus.info)
${info.hardware.map(h => `
${h.k}${escHw(h.v)}
`).join('')}
` : ''; return `
${chips ? `
${chips}
` : ''} ${hwHtml}
`; } function detectFamilyShareSupport() { const shareEl = document.querySelector('.game_area_purchase_game .game_area_purchase_family_share, .family_sharing_notice'); if (shareEl) return { supported: true, source: 'dom' }; const purchaseSection = document.querySelector('.game_area_purchase_game, #purchaseOptions'); if (purchaseSection) { const text = purchaseSection.textContent || ''; if (/family sharing|家庭共享|Steam Family/i.test(text)) return { supported: true, source: 'dom-text' }; if (/not eligible for family sharing|不支持家庭共享/i.test(text)) return { supported: false, source: 'dom-text' }; } const cached = cacheGet('familyShare_' + APP_ID); if (cached !== null) return cached; return null; } async function fetchFamilyShareSupport() { const domResult = detectFamilyShareSupport(); if (domResult) return domResult; const cached = cacheGet('familyShare_' + APP_ID); if (cached !== null) return cached; try { const A = (typeof unsafeWindow !== 'undefined' && unsafeWindow.SGLVAppDetail) || (typeof window !== 'undefined' && window.SGLVAppDetail); if (A && typeof A.loadDetail === 'function') { const detail = await A.loadDetail(APP_ID, { useCache: true }); if (detail && detail.categoryObjs) { const hasFamilyShare = detail.categoryObjs.some(c => c.id === 41 || /family sharing/i.test(c.description || '')); const result = { supported: !!hasFamilyShare, source: 'api' }; cacheSet('familyShare_' + APP_ID, result, CACHE_TTL.familyShare); return result; } } } catch { } const fallback = { supported: null, source: 'unknown' }; return fallback; } function renderFamilyShareIndicator(info) { if (info && info.isSharedOnly) { return ``; } if (!SGIS.familyShareSupported) return ''; const s = SGIS.familyShareSupported; if (s.supported === true) { return `
✓ 支持家庭组共享 ${s.source}
`; } else if (s.supported === false) { return `
✕ 不支持家庭组共享
`; } return ''; } async function fetchAppDetailsExtra() { const A = (typeof unsafeWindow !== 'undefined' && unsafeWindow.SGLVAppDetail) || (typeof window !== 'undefined' && window.SGLVAppDetail); if (!A || typeof A.loadDetail !== 'function') { console.warn('[SGIS] SGLVAppDetail 库未加载,概览增强信息不可用'); return null; } try { const detail = await A.loadDetail(APP_ID, { useCache: true }); if (!detail) return null; const platforms = []; if (detail.platforms) { if (detail.platforms.win) platforms.push('Windows'); if (detail.platforms.mac) platforms.push('macOS'); if (detail.platforms.linux) platforms.push('SteamOS + Linux'); } return { workshopSupported: (detail.categoryObjs || []).some(c => c.id === 30 || /steam\s*workshop|steam\s*创意工坊|创意工坊/i.test(c.description || '') ), workshopUrl: `https://steamcommunity.com/workshop/browse/?appid=${APP_ID}`, categories: detail.categoryObjs || [], platforms, packages: detail.packages || [], screenshots: detail.screenshots || [], movies: detail.movies || [], supportedLanguages: detail.supportedLanguages || { list: [], note: '' }, controllerSupport: detail.controllerSupport || null, requiredAge: detail.requiredAge || 0, contentDescriptors: detail.contentDescriptors || null, appType: detail.type || '', background: detail.background || '', genres: detail.genres || [], genreObjs: detail.genreObjs || [], developers: detail.developers || [], publishers: detail.publishers || [], releaseDate: detail.releaseDate || '', recommendations: detail.recommendations || 0, metacritic: detail.metacritic || null, achievementsTotal: detail.achievementsTotal || 0, dlc: detail.dlc || [], isFree: detail.isFree || false, website: detail.website || '', headerImage: detail.cover || '', shortDesc: detail.shortDesc || '', source: detail.source || 'api', fetchedAt: Date.now(), }; } catch (e) { console.warn('[SGIS] appdetails 增强信息获取失败:', e.message); return null; } } function extractDlcIdsFromDom() { try { if (!/^(store\.steampowered\.com)$/.test(location.hostname)) return []; const ids = new Set(); document.querySelectorAll('.game_area_dlc_row[data-ds-appid]').forEach(el => { const v = el.getAttribute('data-ds-appid'); if (v && /^\d+$/.test(v.trim())) ids.add(v.trim()); }); document.querySelectorAll('.game_area_dlc_row a[href]').forEach(a => { const m = (a.getAttribute('href') || '').match(/\/app\/(\d+)/); if (m) ids.add(m[1]); }); ids.delete(String(APP_ID)); return Array.from(ids).map(Number).filter(n => n > 0); } catch (e) { return []; } } function mergeDlcFromDom(extra) { try { const domIds = extractDlcIdsFromDom(); if (!domIds.length) return extra; if (!extra) { return { workshopSupported: undefined, workshopUrl: '', categories: [], platforms: [], packages: [], screenshots: [], movies: [], supportedLanguages: { list: [], note: '' }, controllerSupport: null, requiredAge: 0, contentDescriptors: null, appType: 'dlc-list-only', background: '', genres: [], genreObjs: [], developers: [], publishers: [], releaseDate: '', recommendations: 0, metacritic: null, achievementsTotal: 0, dlc: domIds, isFree: false, website: '', headerImage: '', shortDesc: '', source: 'dom', fetchedAt: Date.now(), }; } const cur = new Set((extra.dlc || []).map(String)); const merged = Array.isArray(extra.dlc) ? extra.dlc.slice() : []; let added = false; domIds.forEach(id => { if (!cur.has(String(id))) { merged.push(id); added = true; } }); if (added) extra.dlc = merged; return extra; } catch (e) { return extra; } } function renderWorkshopIndicator() { const extra = SGIS.appDetailsExtra; if (!extra || extra.workshopSupported === undefined || extra.workshopSupported === null) return ''; if (extra.workshopSupported) { return `
${SGIS_ICONS.workshop} 支持 Steam 创意工坊 浏览工坊 →
`; } return `
${SGIS_ICONS.workshop} 不支持 Steam 创意工坊
`; } function formatBigNumber(n) { if (!n || n <= 0) return ''; if (n < 10000) return String(n); if (n < 100000000) return (n / 10000).toFixed(1) + '万'; return (n / 100000000).toFixed(1) + '亿'; } function localizeAppType(t) { const map = { game: '游戏', dlc: 'DLC', music: '音乐', series: '系列', mod: '模组', demo: '试玩版', advertising: '宣传', series_episode: '系列剧集', tool: '工具', video: '视频', hardware: '硬件', episode: '剧集', }; return map[t] || t || ''; } function ageBadgeInfo(age) { if (!age || age <= 0) return { cls: 'unrestricted', text: '全年龄', icon: SGIS_ICONS.shield }; if (age >= 18) return { cls: 'restricted', text: age + '+ 限制级', icon: SGIS_ICONS.shield }; if (age >= 16) return { cls: 'mature', text: age + '+ 成熟内容', icon: SGIS_ICONS.shield }; if (age >= 13) return { cls: 'mature', text: age + '+ 青少年', icon: SGIS_ICONS.shield }; return { cls: 'unrestricted', text: age + '+', icon: SGIS_ICONS.shield }; } async function fetchDlcNames(dlcIds) { if (!dlcIds || !dlcIds.length) return {}; const cacheKey = 'dlcNames_' + dlcIds.join(','); const cached = cacheGet(cacheKey); if (cached) return cached; const result = {}; const concurrency = 4; const queue = dlcIds.slice(); const workers = []; const fetchOne = async (dlcId) => { try { const url = `https://store.steampowered.com/api/appdetails?appids=${dlcId}&filters=basic&l=schinese&_=${Date.now()}`; const data = await fetchJson(url, { timeout: 8000 }); const d = data?.[dlcId]?.data; if (d) { result[dlcId] = { name: d.name || ('DLC ' + dlcId), isFree: !!d.is_free, headerImage: d.header_image || '', shortDesc: d.short_description || '', }; } } catch (e) { } }; while (queue.length > 0) { const batch = queue.splice(0, concurrency); await Promise.all(batch.map(fetchOne)); } cacheSet(cacheKey, result, CACHE_TTL.appDetailsExtra); return result; } const _itad = window.SGLVITAD; async function fetchHistoryPrices(appId) { const cacheKey = 'historyPrices_' + appId; const peeked = cachePeek(cacheKey); if (peeked && peeked.fresh) return peeked.data; if (_itad && _itad.hasApiKey()) { const itadId = await _itad.lookupItadId(appId); if (!itadId) { return await fetchHistoryPricesCheapShark(appId, 'ITAD lookup 失败'); } const [gameInfo, historyData] = await Promise.all([ _itad.fetchGameInfo(itadId), _itad.fetchPriceHistory(itadId, { country: 'CN', shops: [_itad.SHOP_STEAM] }), ]); if (!historyData || !historyData.discounts.length) { return await fetchHistoryPricesCheapShark(appId, 'ITAD 无价格历史'); } const releaseDate = gameInfo?.releaseDate || null; if (releaseDate) { for (const d of historyData.discounts) { if (d.date) { try { d.daysFromRelease = Math.floor((new Date(d.date) - new Date(releaseDate)) / 86400000); } catch { } } } } const result = { history: historyData.history, discounts: historyData.discounts, lowest: historyData.lowest, releaseDate: releaseDate, gameTitle: gameInfo?.title || '', source: 'itad', }; cacheSet(cacheKey, result, CACHE_TTL.historyPrices); return result; } return await fetchHistoryPricesCheapShark(appId, 'ITAD 库未加载'); } async function fetchHistoryPricesFallback(appId, reason) { try { const data = await sglvGmFetchRetry('https://api.augmentedsteam.com/prices/v2', { method: 'POST', timeout: 12000, headers: { 'Content-Type': 'application/json' }, data: JSON.stringify({ country: 'US', apps: [parseInt(appId, 10)], subs: [], bundles: [], voucher: false, shops: [], }), }); const key = `app/${appId}`; const aug = data?.prices?.[key]; if (!aug) return { history: [], discounts: [], lowest: null, source: 'aug', error: reason }; const lowest = aug.lowest || (aug.historic?.[0] ? { price: aug.historic[0].price, currency: aug.historic[0].currency, store: aug.historic[0].store, date: aug.historic[0].date } : null); const history = (aug.historic || []).map(h => ({ price: h.price, currency: h.currency, cut: 0, store: h.store || '', date: h.date || '', })).sort((a, b) => new Date(b.date) - new Date(a.date)).slice(0, 20); const result = { history, discounts: [], lowest, releaseDate: null, source: 'aug', error: reason }; cacheSet('historyPrices_' + appId, result, CACHE_TTL.historyPrices); return result; } catch (e) { return { history: [], discounts: [], lowest: null, source: 'error', error: reason + ' / ' + e.message }; } } function renderDiscountTrendChart(discounts) { const pts = (discounts || []) .filter(d => d && d.date && d.cut > 0) .map(d => ({ t: new Date(d.date).getTime(), cut: Number(d.cut) || 0, date: d.date })) .filter(p => !isNaN(p.t)) .sort((a, b) => a.t - b.t); if (pts.length <= 2) return ''; const W = 340, H = 120, PL = 22, PR = 10, PT = 14, PB = 16; const maxCut = Math.max(...pts.map(p => p.cut), 10); const svg = SGLVCharts.lineChart([{ data: pts.map(p => p.cut) }], { width: W, height: H, pL: PL, pR: PR, pT: PT, pB: PB, smooth: false, colors: ['#a4d007'], xValues: pts.map(p => p.t), xMinSpan: 86400000, yMin: 0, yMax: maxCut, gridCount: 4, yFormatter: v => Math.round(v) + '%', area: { fill: '#a4d007', opacity: 0.28 }, strokeWidth: 1.8, strokeRound: true, dots: { r: 3, fill: '#a4d007', stroke: '#0e141b', strokeWidth: 1.5, title: (v, i) => `${new Date(pts[i].t).toLocaleDateString('zh-CN')} · -${pts[i].cut}%`, }, xLabels: pts.map(p => new Date(p.t).toLocaleDateString('zh-CN', { year: '2-digit', month: '2-digit' })), xLabelAt: pts.map((_, i) => i), annotations: pts.map((p, i) => ({ type: 'point', idx: i, text: `-${p.cut}%`, dy: -6, color: '#c8d6e5', fontSize: 8 })), svgAttrs: 'style="width:100%;height:auto;display:block" role="img" aria-label="折扣趋势图"', }); return `
折扣趋势 (按首次到达日期)
${svg}
`; } function renderPriceHistoryChart(historyData) { const allPoints = (historyData?.history || []) .filter(h => h && h.date && h.price > 0) .map(h => ({ t: new Date(h.date).getTime(), price: Number(h.price) || 0, cut: Number(h.cut) || 0, currency: h.currency || '', store: h.store || '', date: h.date, })) .filter(p => !isNaN(p.t)) .sort((a, b) => a.t - b.t); if (allPoints.length < 2) return ''; const now = Date.now(); const ranges = [ { key: '6m', label: '6月', ms: 180 * 86400000 }, { key: '1y', label: '12月', ms: 365 * 86400000 }, { key: 'all', label: '全部', ms: Infinity }, ]; const activeRange = SGIS.priceChartRange || 'all'; const filterByRange = (rangeKey) => { if (rangeKey === 'all') return allPoints; const r = ranges.find(x => x.key === rangeKey); if (!r) return allPoints; const filtered = allPoints.filter(p => p.t >= now - r.ms); return filtered.length >= 2 ? filtered : allPoints; }; const points = filterByRange(activeRange); const W = 340, H = 140, PL = 34, PR = 10, PT = 14, PB = 20; const prices = points.map(p => p.price); const minP = Math.min(...prices); const maxP = Math.max(...prices); const padP = (maxP - minP) * 0.15 || maxP * 0.1 || 1; const yMin = Math.max(0, minP - padP); const yMax = maxP + padP; const lowestIdx = prices.indexOf(minP); const labelCount = Math.min(5, points.length); const xLabelAt = Array.from({ length: labelCount }, (_, i) => Math.floor(i * (points.length - 1) / (labelCount - 1))); const currency = points[0]?.currency || ''; return SGLVCharts.lineChart([{ data: prices }], { width: W, height: H, pL: PL, pR: PR, pT: PT, pB: PB, smooth: false, colors: [SGLVCharts.accent()], xValues: points.map(p => p.t), xMinSpan: 86400000, yMin, yMax, gridCount: 4, yFormatter: v => (v >= 100 ? Math.round(v).toString() : v.toFixed(1)), area: { fill: SGLVCharts.accent(), opacity: 0.25 }, strokeWidth: 1.8, strokeRound: true, dots: { stroke: '#0e141b', strokeWidth: 1.5, itemStyle: (v, i) => (i === lowestIdx ? { r: 4, fill: '#a4d007' } : { r: 2.5, fill: SGLVCharts.accent() }), title: (v, i) => { const p = points[i]; return `${new Date(p.t).toLocaleDateString('zh-CN')} · ${p.currency}${p.price.toFixed(2)}${p.cut > 0 ? ` (-${p.cut}%)` : ''}${p.store ? ' @ ' + p.store : ''}`; }, }, xLabels: points.map(p => new Date(p.t).toLocaleDateString('zh-CN', { year: '2-digit', month: '2-digit' })), xLabelAt, annotations: [{ type: 'point', idx: lowestIdx, text: `${points[lowestIdx].currency}${points[lowestIdx].price.toFixed(2)}`, dy: -8, color: '#a4d007', fontSize: 8.5, fontWeight: 600 }], rangeButtons: ranges, activeRange, title: `价格走势 (${currency})`, wrapId: 'sgis-price-chart-wrap', svgAttrs: 'style="width:100%;height:auto;display:block" role="img" aria-label="价格历史走势图"', }); } function bindPriceChartRangeEvents(historyData) { const root = _pricesPane() || document; const wrap = root.querySelector('#sgis-price-chart-wrap'); if (!wrap) return; wrap.querySelectorAll('.sgis-chart-range-btn').forEach(btn => { btn.addEventListener('click', () => { SGIS.priceChartRange = btn.dataset.range; const newChartHtml = renderPriceHistoryChart(historyData); if (newChartHtml) { const temp = document.createElement('div'); temp.innerHTML = newChartHtml; const newWrap = temp.firstChild; wrap.replaceWith(newWrap); bindPriceChartRangeEvents(historyData); } }); }); } function renderHistoryPricesSection(historyData) { if (!historyData || (!historyData.history?.length && !historyData.lowest && !historyData.discounts?.length)) { return `
${SGIS_ICONS.price} 历史价格
暂无历史价格数据${historyData?.error ? '(' + historyData.error + ')' : ''}
`; } const lowest = historyData.lowest; const discounts = historyData.discounts || []; const releaseDate = historyData.releaseDate; const _f = (v) => { const n = Number(v); return isNaN(n) ? '—' : n.toFixed(2); }; const lowestHtml = lowest ? `
史低价格 ${lowest.cut ? `(-${lowest.cut}%)` : ''}
${lowest.currency || '$'}${_f(lowest.price)}
${lowest.store ? `
@ ${lowest.store}
` : ''} ${lowest.date ? `
${new Date(lowest.date).toLocaleDateString('zh-CN')}
` : ''}
` : ''; const discountSummaryHtml = discounts.length ? `
${discounts.map(d => { const daysStr = d.daysFromRelease != null ? `第${d.daysFromRelease}天` : ''; return `-${d.cut}%${daysStr}`; }).join('')}
` : ''; const historyRows = (historyData.history || []).slice(0, 10).map(h => { const dateStr = h.date ? new Date(h.date).toLocaleDateString('zh-CN', { year: '2-digit', month: '2-digit', day: '2-digit' }) : '—'; const cutBadge = h.cut > 0 ? `-${h.cut}%` : ''; let daysStr = ''; if (releaseDate && h.date) { try { const days = Math.floor((new Date(h.date) - new Date(releaseDate)) / 86400000); if (days >= 0) daysStr = `+${days}天`; } catch { } } return `
${dateStr} ${cutBadge} ${h.cut > 0 && h.regular > 0 ? `${h.currency || '$'}${_f(h.regular)}` : ''}${h.currency || '$'}${_f(h.price)} ${h.store || ''} ${daysStr}
`; }).join(''); const sourceLabel = historyData.source === 'itad' ? 'ITAD' : historyData.source === 'aug' ? 'AugmentedSteam' : historyData.source; return `
${SGIS_ICONS.price} 历史价格走势
${lowestHtml} ${discountSummaryHtml} ${renderPriceHistoryChart(historyData)} ${historyRows ? `
${historyRows}
` : ''} ${renderDiscountTrendChart(discounts)} ${releaseDate ? `
发行日期: ${new Date(releaseDate).toLocaleDateString('zh-CN')}
` : ''}
数据源: ${sourceLabel}${discounts.length ? ` · ${discounts.length} 个折扣记录` : ''}
`; } async function fetchPlayerAchievements(appId) { const apiKey = storage.getApiKey(); const steamId = getActiveSteamId(); if (!apiKey || !steamId) return { error: 'NO_KEY', achievements: [], total: 0, unlocked: 0 }; const cacheKey = 'achievements_' + appId; const cached = cacheGet(cacheKey); if (cached) return cached; const url = `https://api.steampowered.com/ISteamUserStats/GetPlayerAchievements/v0001/?appid=${appId}&key=${apiKey}&steamid=${steamId}&l=schinese`; let data; try { data = await fetchJson(url, { timeout: 15000, onHttpError(status, body) { if (status === 400 && /"success"\s*:\s*false/.test(String(body || ''))) return 'NO_ACHIEVEMENTS'; return ''; }, }); } catch (e) { if (e && e.message === 'NO_ACHIEVEMENTS') { const result = { error: 'NO_ACHIEVEMENTS', achievements: [], total: 0, unlocked: 0 }; cacheSet(cacheKey, result, 30 * 60 * 1000); return result; } throw e; } if (!data?.playerstats?.success) return { error: 'API_FAIL', achievements: [], total: 0, unlocked: 0 }; const ach = data.playerstats.achievements || []; const result = { achievements: ach.map(a => ({ name: a.name || '', apiname: a.apiname || '', achieved: a.achieved === 1, unlocktime: a.unlocktime || 0, })), total: ach.length, unlocked: ach.filter(a => a.achieved === 1).length, gameName: data.playerstats.gameName || '', }; cacheSet(cacheKey, result, CACHE_TTL.achievements); return result; } async function fetchGlobalAchievements(appId) { const cacheKey = 'globalAchievements_' + appId; const cached = cacheGet(cacheKey); if (cached) return cached; const url = `https://api.steampowered.com/ISteamUserStats/GetGlobalAchievementPercentagesForApp/v0002/?gameid=${appId}&l=schinese`; const data = await fetchJson(url, { timeout: 15000 }); const ach = data?.achievementpercentages?.achievements || []; const result = ach.map(a => ({ name: a.name || '', percent: a.percent || 0, })).sort((a, b) => b.percent - a.percent); cacheSet(cacheKey, result, CACHE_TTL.globalAchievements); return result; } function renderAchievements() { if (SGIS.achievementsLoading) return; if (SGIS.achievements && SGIS.globalAchievements) { renderAchievementsContent(); return; } SGIS.achievementsLoading = true; renderLoading('正在获取成就数据…'); Promise.all([ fetchPlayerAchievements(APP_ID).catch(e => ({ error: e.message, achievements: [], total: 0, unlocked: 0 })), fetchGlobalAchievements(APP_ID).catch(e => []), ]).then(([playerData, globalData]) => { SGIS.achievements = playerData; SGIS.globalAchievements = globalData; renderAchievementsContent(); }).catch(e => { renderError('成就获取失败: ' + e.message); }).finally(() => { SGIS.achievementsLoading = false; }); } function _prepareAchievementsData() { const player = SGIS.achievements; const global = SGIS.globalAchievements || []; if (player?.error === 'NO_KEY') return { state: 'no_key' }; if (player?.error === 'NO_ACHIEVEMENTS') return { state: 'empty' }; if (player?.error && player.error !== 'API_FAIL') return { state: 'error', error: player.error }; if (!player || player.total === 0) { if (global.length === 0) return { state: 'empty' }; return { state: 'global_only', global }; } const unlocked = player.unlocked; const total = player.total; const pct = total > 0 ? (unlocked / total * 100) : 0; const globalMap = {}; global.forEach(g => { globalMap[g.name] = g.percent; }); const merged = player.achievements.map(a => ({ name: a.name, achieved: a.achieved, unlocktime: a.unlocktime, globalPct: globalMap[a.name] || null, })); const unlockedList = merged.filter(a => a.achieved).sort((a, b) => (b.unlocktime || 0) - (a.unlocktime || 0)); const lockedList = merged.filter(a => !a.achieved).sort((a, b) => (b.globalPct || 0) - (a.globalPct || 0)); return { state: 'normal', player, global, unlocked, total, pct, merged, unlockedList, lockedList }; } function _renderAchievementsNoKey() { return `
🏆
需要 API Key 才能查看成就
请在设置中配置 Steam Web API Key。
打开 steamcommunity.com/dev/apikey 获取免费 Key。
`; } function _renderAchievementsError(d) { const msg = String(d.error || ''); let reason; if (/HTTP 403/.test(msg)) { reason = '成就详情无法访问(HTTP 403)。常见原因:
① Steam 隐私设置中「游戏详情」未公开;
② API Key 无效或无该资料权限'; } else if (/HTTP 401/.test(msg)) { reason = 'API Key 无效或已过期(HTTP 401),请在设置中更新后重试'; } else if (/HTTP 5\d\d/.test(msg)) { reason = `Steam 服务暂时不可用(${(msg.match(/HTTP 5\d\d/) || ['服务端错误'])[0]}),请稍后重试`; } else if (/^HTTP \d+/.test(msg)) { reason = `Steam 接口返回错误(${(msg.match(/^HTTP \d+/) || [''])[0]}),请稍后重试`; } else { reason = '网络异常,请检查网络连接后重试'; } return `
🏆
成就数据获取失败
${reason}
`; } function _renderAchievementsEmpty() { return `
🏆
该游戏暂无成就数据
`; } function _renderAchievementsGlobalOnly(d) { const globalList = d.global.slice(0, 20).map(a => { const barColor = a.percent >= 50 ? 'var(--sgis-green)' : a.percent >= 20 ? 'var(--sgis-amber)' : 'var(--sgis-rose)'; return `
${a.name}
${hbarRow({ cls: 'ach', pct: a.percent, color: barColor })}
${a.percent.toFixed(1)}%
`; }).join(''); return `
${SGIS_ICONS.star} 全球成就达成率
该游戏不在你的库中,仅展示全球数据
${globalList}
`; } function _renderAchievementsNormal(d) { const formatUnlockTime = (ts) => { if (!ts) return ''; try { return new Date(ts * 1000).toLocaleDateString('zh-CN', { year: '2-digit', month: '2-digit', day: '2-digit' }); } catch { return ''; } }; const unlockedHtml = d.unlockedList.slice(0, 15).map(a => `
✓
${a.name || '(隐藏成就)'}
${a.unlocktime ? `${formatUnlockTime(a.unlocktime)}` : ''} ${a.globalPct != null ? `全球 ${a.globalPct.toFixed(1)}%` : ''}
`).join(''); const lockedHtml = d.lockedList.slice(0, 15).map(a => { const barColor = (a.globalPct || 0) >= 50 ? 'var(--sgis-green)' : (a.globalPct || 0) >= 20 ? 'var(--sgis-amber)' : 'var(--sgis-rose)'; return `
○
${a.name || '(隐藏成就)'}
${hbarRow({ cls: 'ach', pct: a.globalPct || 0, color: barColor })} ${a.globalPct != null ? `
全球 ${a.globalPct.toFixed(1)}%
` : ''}
`; }).join(''); const donutR = 52, donutSw = 10, donutCx = 60, donutCy = 60; const donutC = 2 * Math.PI * donutR; const donutDash = (d.pct / 100) * donutC; const rainbowIntensity = Math.max(0.3, Math.min(1.0, 0.25 + d.pct / 100 * 0.85)); const rainbowId = `sgis-rainbow-${APP_ID || 'p'}`; const rainbowGlowId = `${rainbowId}-glow`; const rainbowStops = [ [0.00, '#ff0080'], [0.17, '#ff4500'], [0.34, '#ffb300'], [0.50, '#00ff7f'], [0.67, '#00bfff'], [0.84, '#7b2cff'], [1.00, '#ff00d4'], ].map(([off, c]) => ``).join(''); return `
${rainbowStops} ${d.pct.toFixed(0)}% ${d.unlocked}/${d.total}
${d.unlocked}已解锁
${d.total - d.unlocked}未解锁
${d.total}总成就
${unlockedHtml ? `
${SGIS_ICONS.check} 已解锁 (${d.unlockedList.length})
${unlockedHtml}
` : ''} ${lockedHtml ? `
${SGIS_ICONS.star} 未解锁 (${d.lockedList.length})
${lockedHtml}
` : ''}
玩家成就来自 Steam Web API · 全球数据每12小时更新
`; } function renderAchievementsContent() { _paintTab = 'achievements'; const d = _prepareAchievementsData(); let html; if (d.state === 'no_key') html = _renderAchievementsNoKey(); else if (d.state === 'error') html = _renderAchievementsError(d); else if (d.state === 'empty') html = _renderAchievementsEmpty(); else if (d.state === 'global_only') html = _renderAchievementsGlobalOnly(d); else html = _renderAchievementsNormal(d); setBody(html); if (d.state === 'no_key') { const pane = _ensureSgisPane('achievements'); const keyBtn = pane.querySelector('#sgis-ach-apikey-btn'); if (keyBtn) { keyBtn.addEventListener('click', async () => { keyBtn.disabled = true; const allowed = await _requireApiKeyConsent({ thenFetch: false }); keyBtn.disabled = false; if (!allowed) return; _openApiKeySettings(); }); } } if (d.state === 'error') { const pane = _ensureSgisPane('achievements'); const retryBtn = pane.querySelector('#sgis-ach-retry-btn'); if (retryBtn) retryBtn.addEventListener('click', () => { SGIS.achievements = null; SGIS.globalAchievements = null; renderAchievements(); }); } } function sglvCleanNewsText(text) { return String(text || '') .replace(/\{STEAM_CLAN(?:_LOC)?_(?:IMAGE|VIDEO)\}\S*/gi, '') .replace(/\[img\][\s\S]*?\[\/img\]/gi, '') .replace(/\[url=[^\]]*\]([\s\S]*?)\[\/url\]/gi, '$1') .replace(/\[\/?[a-z0-9_=#.\s:%{}|\/\\-]*\]/gi, '') .replace(/https?:\/\/\S+/g, m => (m.length > 80 ? '' : m)) .replace(/[ \t]{2,}/g, ' ') .replace(/\n{3,}/g, '\n\n') .trim(); } async function fetchGameNews(appId) { const cacheKey = 'news_' + appId; const cached = cacheGet(cacheKey); if (cached) return cached; let newsItems = []; try { const officialUrl = `https://api.steampowered.com/ISteamNews/GetNewsForApp/v0002/?appid=${appId}&count=20&maxlength=500&l=schinese&feeds=steam_community_announcements`; const officialData = await fetchJson(officialUrl, { timeout: 15000 }); newsItems = officialData?.appnews?.newsitems || []; } catch { newsItems = []; } if (!newsItems.length) { const allUrl = `https://api.steampowered.com/ISteamNews/GetNewsForApp/v0002/?appid=${appId}&count=20&maxlength=500&l=schinese`; const allData = await fetchJson(allUrl, { timeout: 15000 }); newsItems = allData?.appnews?.newsitems || []; } const result = newsItems.map(n => ({ title: n.title || '', url: n.url || '', contents: sglvCleanNewsText(n.contents).slice(0, 300), date: n.date || 0, feedname: n.feedname || '', author: n.author || '', })); cacheSet(cacheKey, result, CACHE_TTL.news); return result; } function renderDynamics() { if (SGIS.dynamicsLoading) return; if (SGIS.dynamics) { renderDynamicsContent(); return; } SGIS.dynamicsLoading = true; renderLoading('正在获取游戏动态…'); fetchGameNews(APP_ID).then(news => { SGIS.dynamics = news; renderDynamicsContent(); }).catch(e => { renderError('动态获取失败: ' + e.message); }).finally(() => { SGIS.dynamicsLoading = false; }); } function _formatNewsDate(ts) { if (!ts) return ''; try { const d = new Date(ts * 1000); const now = new Date(); const diff = (now - d) / 1000; if (diff < 3600) return Math.floor(diff / 60) + ' 分钟前'; if (diff < 86400) return Math.floor(diff / 3600) + ' 小时前'; if (diff < 30 * 86400) return Math.floor(diff / 86400) + ' 天前'; return d.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }); } catch { return ''; } } const _FEED_LABELS = { steam_community_announcements: '社区公告', steam_blog: '官方博客', patch_notes: '更新日志', product_updates: '产品更新', }; function _feedLabel(name) { return _FEED_LABELS[name] || name || '动态'; } function _prepareDynamicsData() { const news = SGIS.dynamics || []; const isAiMode = SGIS.dynamicsMode === 'ai'; const hasTruncationFlag = SGIS.aiSummary && SGIS.aiSummary.some(it => it._truncated); return { news, isAiMode, hasTruncationFlag }; } function _renderDynamicsEmpty() { return `
📢
暂无游戏动态
该游戏近期没有发布新闻或更新公告
`; } function _renderDynamicsOriginal(d) { return d.news.map(n => { const feedLabel = _feedLabel(n.feedname); const desc = n.contents ? n.contents.slice(0, 200) + (n.contents.length > 200 ? '...' : '') : ''; return `
${feedLabel} ${_formatNewsDate(n.date)}
${n.title}
${desc ? `
${desc}
` : ''} ${n.author ? `
— ${n.author}
` : ''}
`; }).join(''); } function _renderDynamicsAiSummary(d) { const truncationBanner = d.hasTruncationFlag ? `
⚠️ AI 响应因长度限制被截断, 已通过修复算法恢复 ${SGIS.aiSummary.length} 条结果。切换到"原文"可查看完整新闻。
` : ''; return truncationBanner + SGIS.aiSummary.map((item, i) => { const origNews = d.news[i] || {}; const feedLabel = _feedLabel(origNews.feedname); const badge = item.is_translated ? `已翻译` : ''; return `
${feedLabel} ${_formatNewsDate(origNews.date)}
${item.title || origNews.title || ''}${badge}
${item.summary || ''}
`; }).join(''); } function _renderDynamicsAiLoading() { return `
${T.aiTranslating}
`; } function _renderDynamicsAiError() { return `
⚠️ ${T.aiTranslateFail}: ${SGIS.aiSummaryError}
`; } function _renderDynamicsToggleBar(d) { const aiStatusText = d.isAiMode ? (SGIS.aiSummary ? (d.hasTruncationFlag ? `⚠️ 已恢复 ${SGIS.aiSummary.length} 条 (部分结果因长度限制被截断)` : `✅ ${SGIS.aiSummary.length} 条已总结`) : T.aiTranslating) : ''; return `
${aiStatusText}
`; } function _bindDynamicsEvents() { const body = document.getElementById('sgis-body'); if (!body) return; body.querySelectorAll('.sgis-ai-toggle-btn').forEach(btn => { btn.addEventListener('click', () => { const mode = btn.dataset.mode; if (SGIS.dynamicsMode === mode) return; SGIS.dynamicsMode = mode; if (mode === 'original') SGIS.aiSummaryError = null; renderDynamicsContent(); }); }); const aiRetryBtn = body.querySelector('#sgis-ai-retry'); if (aiRetryBtn) { aiRetryBtn.addEventListener('click', () => { SGIS.aiSummaryError = null; SGIS.aiSummary = null; renderDynamicsContent(); }); } } function _renderDynamicsAiTrigger(d) { SGIS.aiSummaryLoading = true; const gameName = (document.getElementById('appHubAppName') || {}).textContent || ''; callAiTranslateSummary(d.news, gameName, APP_ID).then(result => { SGIS.aiSummary = result; SGIS.aiSummaryLoading = false; if (SGIS.tab === 'dynamics') renderDynamicsContent(); }).catch(e => { SGIS.aiSummaryLoading = false; SGIS.aiSummaryError = e.message; if (SGIS.tab === 'dynamics' && SGIS.dynamicsMode === 'ai') { renderDynamicsContent(); } }); return _renderDynamicsAiLoading(); } function renderDynamicsContent() { _paintTab = 'dynamics'; const d = _prepareDynamicsData(); if (d.news.length === 0) { setBody(_renderDynamicsEmpty()); return; } let contentHtml; if (d.isAiMode) { if (SGIS.aiSummaryLoading) contentHtml = _renderDynamicsAiLoading(); else if (SGIS.aiSummaryError) contentHtml = _renderDynamicsAiError(); else if (SGIS.aiSummary) contentHtml = _renderDynamicsAiSummary(d); else contentHtml = _renderDynamicsAiTrigger(d); } else { contentHtml = _renderDynamicsOriginal(d); } setBody(`
${SGIS_ICONS.news} 游戏动态与新闻
共 ${d.news.length} 条动态 · 来自 Steam 官方公告/新闻源
${_renderDynamicsToggleBar(d)} ${contentHtml}
数据来自 Steam News API · 每30分钟刷新缓存${d.isAiMode ? ' · AI翻译总结由用户配置的模型提供' : ''}
`); _bindDynamicsEvents(); } async function fetchPlayerSummaries(steamId) { const apiKey = storage.getApiKey(); if (!apiKey || !steamId) return null; const cacheKey = 'playerSummary_' + steamId; const cached = cacheGet(cacheKey); if (cached) return cached; try { const url = `https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=${apiKey}&steamids=${steamId}`; const data = await fetchJson(url, { timeout: 12000 }); const player = data?.response?.players?.[0]; if (player) { cacheSet(cacheKey, player, 30 * 60 * 1000); return player; } return null; } catch { return null; } } async function fetchRecentlyPlayedGames(steamId) { const apiKey = storage.getApiKey(); if (!apiKey || !steamId) return []; try { const url = `https://api.steampowered.com/IPlayerService/GetRecentlyPlayedGames/v0001/?key=${apiKey}&steamid=${steamId}&format=json`; const data = await fetchJson(url, { timeout: 12000 }); return (data?.response?.games || []).map(g => ({ appid: g.appid, name: g.name || `App ${g.appid}`, playtime_2weeks: g.playtime_2weeks || 0, playtime_forever: g.playtime_forever || 0, img_icon_url: g.img_icon_url || '', })); } catch { return []; } } function formatPlaytimeShort(minutes) { if (!minutes || minutes === 0) return '0h'; return Math.floor(minutes / 60) + 'h'; } async function fetchSteamLevel(steamId) { if (!steamId) return null; const cacheKey = 'steamLevel_' + steamId; const cached = cacheGet(cacheKey); if (cached) return cached; try { const html = await sglvGmFetchTextRetry(`https://steamcommunity.com/profiles/${steamId}/`, { timeout: 12000, }); const m = html.match(/"player_level":(\d+)/) || html.match(/class="friendPlayerLevelNum"[^>]*>(\d+)/); const level = m ? parseInt(m[1], 10) : null; if (level != null) cacheSet(cacheKey, level, 60 * 60 * 1000); return level; } catch { return null; } } async function fetchFriendCount(steamId) { if (!steamId) return null; const cacheKey = 'friendCount_' + steamId; const cached = cacheGet(cacheKey); if (cached != null) return cached; try { const auth = await sgisAuthParams(); if (!auth) return null; const url = `https://api.steampowered.com/ISteamUser/GetFriendList/v0001/?${auth}&steamid=${steamId}&relationship=friend`; const data = await fetchJson(url, { timeout: 12000 }); const count = data?.friendslist?.friends?.length || 0; cacheSet(cacheKey, count, 60 * 60 * 1000); return count; } catch { return null; } } async function fetchWishlistCount(steamId) { if (Array.isArray(state.wishlistGames) && state.wishlistGames.length > 0) { return state.wishlistGames.length; } try { const dsIds = getDynamicStoreAppIds('wishlist'); if (dsIds.size > 0) return dsIds.size; } catch { } const cachedList = cacheGet('wishlistGames'); if (Array.isArray(cachedList) && cachedList.length > 0) return cachedList.length; const cacheKey = 'wishlistCount_' + steamId; const cachedCount = cacheGet(cacheKey); if (cachedCount != null) return cachedCount; if (steamId) { try { const entries = await fetchWishlistFromApi(steamId); if (entries.length > 0) { cacheSet(cacheKey, entries.length, 6 * 3600 * 1000); return entries.length; } } catch { } } return null; } const SUMMARY_BATCH = 100; const VAC_BATCH = 100; const SGIS_FLAGS = { CN:'', US:'', JP:'', KR:'', TW:'', HK:'', MO:'', GB:'', DE:'', FR:'', RU:'', AU:'', CA:'', BR:'', IN:'', SG:'', MY:'', TH:'', VN:'', ID:'', PH:'', NZ:'', SE:'', NO:'', FI:'', DK:'', NL:'', IT:'', ES:'', PL:'', UA:'', TR:'', SA:'', AE:'', EG:'', ZA:'', IL:'', MX:'', AR:'', CL:'', AT:'', BE:'', CH:'', PT:'', GR:'', CZ:'', HU:'', RO:'', IE:'', EU:'' }; const SGIS_COUNTRY_MAP = { CN:'中国',US:'美国',JP:'日本',KR:'韩国',TW:'中国台湾',HK:'中国香港',MO:'中国澳门', SG:'新加坡',MY:'马来西亚',TH:'泰国',VN:'越南',ID:'印度尼西亚',PH:'菲律宾', IN:'印度',AU:'澳大利亚',NZ:'新西兰',GB:'英国',DE:'德国',FR:'法国',IT:'意大利', ES:'西班牙',RU:'俄罗斯',BR:'巴西',CA:'加拿大',MX:'墨西哥',AR:'阿根廷',CL:'智利', SE:'瑞典',NO:'挪威',FI:'芬兰',DK:'丹麦',NL:'荷兰',BE:'比利时',AT:'奥地利', CH:'瑞士',PL:'波兰',CZ:'捷克',PT:'葡萄牙',GR:'希腊',TR:'土耳其', SA:'沙特阿拉伯',AE:'阿联酋',EG:'埃及',ZA:'南非',IL:'以色列',UA:'乌克兰', RO:'罗马尼亚',HU:'匈牙利',SK:'斯洛伐克',BG:'保加利亚',HR:'克罗地亚', SI:'斯洛文尼亚',LT:'立陶宛',LV:'拉脱维亚',EE:'爱沙尼亚',IE:'爱尔兰', IS:'冰岛',LU:'卢森堡',MT:'马耳他',CY:'塞浦路斯',EU:'欧盟' }; function flagSvg(cc, w, h) { if (!cc || cc.length < 2) return ''; const uc = cc.toUpperCase(); const svg = SGIS_FLAGS[uc]; const ww = w || 18, hh = h || 13; const style = `display:inline-block;width:${ww}px;height:${hh}px;vertical-align:middle;flex-shrink:0;border-radius:1px;box-shadow:0 0 0 1px rgba(255,255,255,0.08)`; if (svg) return svg.replace('${uc}`; } function getCountryInfo(code) { if (!code) return null; const uc = code.toUpperCase(); return { code: uc, name: SGIS_COUNTRY_MAP[uc] || uc, flag: flagSvg(uc) }; } function calcFriendDays(friendSince) { if (!friendSince) return { days: 0, text: '未知', cls: 'd-old' }; const days = Math.floor((Date.now() / 1000 - friendSince) / 86400); let text, cls; if (days < 30) { text = `${days}天`; cls = 'd-new'; } else if (days < 365) { text = `${Math.floor(days / 30)}个月`; cls = 'd-mid'; } else { text = `${(days / 365).toFixed(1)}年`; cls = 'd-old'; } return { days, text, cls }; } function getPersonaStateText(state) { const map = ['离线', '在线', '忙碌', '离开', '休眠', '交易中', '游戏中']; return map[state] || '离线'; } async function sgisAuthParams() { const apiKey = storage.getApiKey(); if (apiKey) return `key=${apiKey}`; try { const token = await getAccessToken(); if (token) return `access_token=${token}`; } catch { } return ''; } async function fetchFriendsList(steamId, opts = {}) { const auth = await sgisAuthParams(); if (!auth || !steamId) return { error: 'NO_KEY', friends: [] }; const { force = false } = opts; const listCacheKey = 'friendsList_' + steamId; if (!force) { const cached = cacheGet(listCacheKey); if (cached && cached.friends && cached.friends.length > 0) { return cached; } } const listUrl = `https://api.steampowered.com/ISteamUser/GetFriendList/v0001/?${auth}&steamid=${steamId}&relationship=friend&format=json`; const listData = await fetchJson(listUrl, { timeout: 15000 }); const rawFriends = listData?.friendslist?.friends || []; if (rawFriends.length === 0) { return { error: 'EMPTY', friends: [], steamId }; } const steamIds = rawFriends.map(f => f.steamid); const summaries = []; for (let i = 0; i < steamIds.length; i += SUMMARY_BATCH) { const batch = steamIds.slice(i, i + SUMMARY_BATCH); try { const sumUrl = `https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v2/?${auth}&steamids=${batch.join(',')}`; const sumData = await fetchJson(sumUrl, { timeout: 15000 }); if (sumData?.response?.players) summaries.push(...sumData.response.players); } catch (e) { console.warn('[SGIS] GetPlayerSummaries batch failed:', e); } } const sumMap = new Map(summaries.map(s => [s.steamid, s])); const vacCacheKey = 'friendsVac_' + steamId; const vacCached = cacheGet(vacCacheKey) || {}; const vacMap = { ...vacCached }; const needVacIds = steamIds.filter(sid => !vacMap[sid]); for (let i = 0; i < needVacIds.length; i += VAC_BATCH) { const batch = needVacIds.slice(i, i + VAC_BATCH); try { const banUrl = `https://api.steampowered.com/ISteamUser/GetPlayerBans/v1/?${auth}&steamids=${batch.join(',')}`; const banData = await fetchJson(banUrl, { timeout: 15000 }); if (banData?.players) { for (const p of banData.players) { vacMap[p.SteamId] = { VACBanned: !!p.VACBanned, DaysSinceLastBan: p.DaysSinceLastBan || 0, NumberOfVACBans: p.NumberOfVACBans || 0, NumberOfGameBans: p.NumberOfGameBans || 0, }; } } } catch (e) { console.warn('[SGIS] GetPlayerBans batch failed:', e); } } cacheSet(vacCacheKey, vacMap, CACHE_TTL.friendsVac); const friends = rawFriends.map(f => { const s = sumMap.get(f.steamid) || {}; const daysInfo = calcFriendDays(f.friend_since); const vacInfo = vacMap[f.steamid] || {}; const countryInfo = getCountryInfo(s.loccountrycode); return { steamid: f.steamid, friend_since: f.friend_since || 0, friend_days: daysInfo.days, friend_days_text: daysInfo.text, friend_days_class: daysInfo.cls, personaname: s.personaname || '匿名玩家', avatar: s.avatar || '', avatarmedium: s.avatarmedium || s.avatar || '', avatarfull: s.avatarfull || s.avatar || '', personastate: s.personastate !== undefined ? s.personastate : 0, lastlogoff: s.lastlogoff || 0, gameextrainfo: s.gameextrainfo || '', gameid: s.gameid || '', loccountrycode: s.loccountrycode || '', country_name: countryInfo ? countryInfo.name : '', country_flag: countryInfo ? countryInfo.flag : '', profileurl: s.profileurl || `https://steamcommunity.com/profiles/${f.steamid}/`, vac_banned: !!vacInfo.VACBanned, vac_days_since_last_ban: vacInfo.DaysSinceLastBan || 0, vac_ban_count: vacInfo.NumberOfVACBans || 0, game_ban_count: vacInfo.NumberOfGameBans || 0, level: null, }; }); const levelCacheKey = 'friendsLevels_' + steamId; const levelCached = cacheGet(levelCacheKey) || {}; for (const f of friends) { if (levelCached[f.steamid] != null) f.level = levelCached[f.steamid]; } const result = { friends, steamId, total: friends.length, _ts: Date.now() }; cacheSet(listCacheKey, result, CACHE_TTL.friendsList); cacheSet('friendCount_' + steamId, friends.length, 60 * 60 * 1000); return result; } async function fetchFriendsLevels(steamId, opts = {}) { const auth = await sgisAuthParams(); if (!auth || !steamId) return null; const { force = false, maxCount = Infinity } = opts; const levelCacheKey = 'friendsLevels_' + steamId; const levelCached = force ? {} : (cacheGet(levelCacheKey) || {}); let changed = false; const friends = (SGIS.friendsList && SGIS.friendsList.friends) || []; let toFetch = friends.filter(f => f.level == null).map(f => f.steamid); if (maxCount !== Infinity && maxCount > 0) { toFetch = toFetch.slice(0, maxCount); } if (toFetch.length === 0) { SGIS.friendsLevels = levelCached; return levelCached; } const LEVEL_CONCURRENCY = 100; const RENDER_INTERVAL = 800; let lastRenderTime = 0; if (SGIS.friendsLevelsLoading) { SGIS.friendsLevelsTotal = toFetch.length; SGIS.friendsLevelsProgress = 0; } async function fetchOne(sid, attempt = 0) { const url = `https://api.steampowered.com/IPlayerService/GetSteamLevel/v1/?${auth}&steamid=${sid}`; try { const data = await fetchJson(url, { timeout: 8000 }); return data?.response?.player_level ?? 0; } catch (e) { if (attempt < 2) { await new Promise(r => setTimeout(r, (attempt + 1) * 800)); return fetchOne(sid, attempt + 1); } return undefined; } } await mapLimit(toFetch, LEVEL_CONCURRENCY, async (sid) => { const level = await fetchOne(sid); if (level !== undefined) { levelCached[sid] = level; const f = friends.find(x => x.steamid === sid); if (f) f.level = level; changed = true; } if (SGIS.friendsLevelsLoading) { SGIS.friendsLevelsProgress++; const now = Date.now(); if (now - lastRenderTime >= RENDER_INTERVAL) { lastRenderTime = now; if (SGIS.tab === 'social') renderSocialContent(); } } }); if (changed) { cacheSet(levelCacheKey, levelCached, CACHE_TTL.friendsLevels); for (const f of friends) { if (levelCached[f.steamid] != null) f.level = levelCached[f.steamid]; } } } async function fetchFriendsBans(steamId, opts = {}) { const auth = await sgisAuthParams(); if (!auth || !steamId) return null; const { force = false } = opts; const friends = (SGIS.friendsList && SGIS.friendsList.friends) || []; const steamIds = friends.map(f => f.steamid); if (steamIds.length === 0) return null; const vacCacheKey = 'friendsVac_' + steamId; const vacCached = cacheGet(vacCacheKey) || {}; const vacMap = { ...vacCached }; let toFetch = steamIds; if (!force) { toFetch = steamIds.filter(sid => !vacMap[sid]); } if (toFetch.length === 0) return vacMap; const BAN_BATCH = 100; const RENDER_INTERVAL = 800; let lastRenderTime = 0; if (SGIS.friendsBansLoading) { SGIS.friendsBansTotal = toFetch.length; SGIS.friendsBansProgress = 0; } for (let i = 0; i < toFetch.length; i += BAN_BATCH) { const batch = toFetch.slice(i, i + BAN_BATCH); let retry = 0; while (retry < 3) { try { const banUrl = `https://api.steampowered.com/ISteamUser/GetPlayerBans/v1/?${auth}&steamids=${batch.join(',')}`; const banData = await fetchJson(banUrl, { timeout: 15000 }); if (banData?.players) { for (const p of banData.players) { vacMap[p.SteamId] = { VACBanned: !!p.VACBanned, DaysSinceLastBan: p.DaysSinceLastBan || 0, NumberOfVACBans: p.NumberOfVACBans || 0, NumberOfGameBans: p.NumberOfGameBans || 0, }; } } break; } catch (e) { retry++; console.warn(`[SGIS] GetPlayerBans batch retry ${retry}:`, e); if (retry < 3) await new Promise(r => setTimeout(r, retry * 600)); } } for (const sid of batch) { const info = vacMap[sid]; const f = friends.find(x => x.steamid === sid); if (f && info) { f.vac_banned = info.VACBanned; f.vac_days_since_last_ban = info.DaysSinceLastBan || 0; f.vac_ban_count = info.NumberOfVACBans || 0; f.game_ban_count = info.NumberOfGameBans || 0; } } if (SGIS.friendsBansLoading) { SGIS.friendsBansProgress += batch.length; const now = Date.now(); if (now - lastRenderTime >= RENDER_INTERVAL) { lastRenderTime = now; if (SGIS.tab === 'social') renderSocialContent(); } } } cacheSet(vacCacheKey, vacMap, CACHE_TTL.friendsVac); SGIS.friendsVac = vacMap; if (SGIS.friendsBansLoading) SGIS.friendsBansProgress = toFetch.length; return vacMap; } async function fetchFriendsGameCounts(steamId, opts = {}) { const auth = await sgisAuthParams(); if (!auth || !steamId) return null; const { force = false } = opts; const GC_TTL = 12 * 3600 * 1000; const cacheKey = 'friendsGameCounts_' + steamId; const gcMap = force ? {} : (cacheGet(cacheKey) || {}); const friends = (SGIS.friendsList && SGIS.friendsList.friends) || []; if (friends.length === 0) return gcMap; const now = Date.now(); const toFetch = friends.map(f => f.steamid).filter(sid => !(gcMap[sid] && now - gcMap[sid].ts < GC_TTL)); if (toFetch.length === 0) { SGIS.friendsGameCounts = gcMap; return gcMap; } if (SGIS.friendsGameCountsLoading) { SGIS.friendsGameCountsTotal = toFetch.length; SGIS.friendsGameCountsProgress = 0; } let done = 0; await mapLimit(toFetch, 6, async (sid) => { try { const data = await fetchJson(`https://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?${auth}&steamid=${sid}&include_appinfo=0&include_played_free_games=1&format=json`, { timeout: 15000 }); const resp = data && data.response; if (resp && typeof resp.game_count === 'number' && resp.game_count > 0) { let tm = 0; (resp.games || []).forEach(g => { tm += g.playtime_forever || 0; }); gcMap[sid] = { gc: resp.game_count, tm, ts: now }; } else { gcMap[sid] = { gc: 0, tm: 0, ts: now, priv: true }; } } catch { } done++; if (SGIS.friendsGameCountsLoading) { SGIS.friendsGameCountsProgress = done; const btn = document.getElementById('sgis-social-load-gc'); if (btn) btn.textContent = `${isZh ? '加载中' : 'Loading'} ${done}/${toFetch.length}`; } }); cacheSet(cacheKey, gcMap, GC_TTL); SGIS.friendsGameCounts = gcMap; return gcMap; } async function fetchSteamOfficialNews() { const cacheKey = 'steamOfficialNews'; const cached = cacheGet(cacheKey); if (cached && !Array.isArray(cached) && cached.totalCount !== undefined) return cached; const result = { specials: [], dailyDeals: [], spotlights: [], news: [], totalCount: 0, fetchedAt: Date.now() }; try { const fcUrl = 'https://store.steampowered.com/api/featuredcategories?cc=us&l=schinese'; const fcData = await fetchJson(fcUrl, { timeout: 15000 }); if (fcData.specials && Array.isArray(fcData.specials.items)) { result.specials = fcData.specials.items .filter(it => it && it.discounted && Number(it.discount_percent) > 0) .slice(0, 20) .map(it => { const discount = Number(it.discount_percent) || 0; const original = Number(it.original_price) || 0; const final = Number(it.final_price) || 0; const exp = Number(it.discount_expiration) || 0; return { appid: it.id, name: it.name || '', discount, originalPrice: original, finalPrice: final, currency: it.currency || 'USD', expiration: exp, headerImage: it.header_image || it.large_capsule_image || '', url: `https://store.steampowered.com/app/${it.id}`, }; }); } const dailyDealKey = Object.keys(fcData).find(k => { const v = fcData[k]; return v && v.id === 'cat_dailydeal' && Array.isArray(v.items); }); if (dailyDealKey) { result.dailyDeals = fcData[dailyDealKey].items .filter(it => it && it.discounted) .slice(0, 5) .map(it => { const discount = Number(it.discount_percent) || 0; const original = Number(it.original_price) || 0; const final = Number(it.final_price) || 0; return { appid: it.id, name: it.name || '', discount, originalPrice: original, finalPrice: final, currency: it.currency || 'USD', headerImage: it.header_image || '', url: `https://store.steampowered.com/app/${it.id}`, }; }); } const spotlightKeys = Object.keys(fcData).filter(k => { const v = fcData[k]; return v && v.id === 'cat_spotlight' && Array.isArray(v.items); }); for (const sk of spotlightKeys) { for (const sp of fcData[sk].items) { if (sp && sp.url && sp.url.includes('/sale/')) { const saleNameMatch = sp.url.match(/\/sale\/([^\/\?]+)/); const saleId = saleNameMatch ? saleNameMatch[1] : ''; if (saleId && result.spotlights.some(s => s.saleId === saleId)) continue; result.spotlights.push({ name: sp.name || '促销活动', url: sp.url, saleId, headerImage: sp.header_image || sp.large_capsule_image || '', body: sp.body || '', discountExpiration: Number(sp.discount_expiration) || 0, }); } } } } catch (e) { console.warn('[SGIS] featuredcategories 获取失败:', e); } try { const raw = await fetchText('https://store.steampowered.com/feeds/news.xml', { timeout: 12000 }); const blocks = String(raw).match(/][\s\S]*?<\/item>/g) || []; const decodeXml = s => String(s || '') .replace(//g, '') .replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>') .replace(/"/g, '"').replace(/'|'/g, "'") .trim(); const pickTag = (block, tag) => decodeXml((block.match(new RegExp(`<${tag}[^>]*>([\\s\\S]*?)`)) || [])[1]); const items = blocks.slice(0, 15).map(b => { const dateStr = (b.match(/]*>([\s\S]*?)<\/dc:date>/) || [])[1] || ''; const ts = dateStr ? Math.floor(new Date(decodeXml(dateStr)).getTime() / 1000) : 0; return { title: pickTag(b, 'title'), url: pickTag(b, 'link'), date: ts || 0, contents: sglvCleanNewsText(pickTag(b, 'description').replace(/<[^>]+>/g, '')).slice(0, 300), feedname: 'steam_blog', author: 'Steam', }; }).filter(n => n.title); if (!items.length) throw new Error('RSS 无条目'); result.news = items; } catch (e) { console.warn('[SGIS] 官方新闻 RSS 获取失败,回退 ISteamNews:', e.message); try { const newsAppIds = [593050]; const allNews = []; for (const aid of newsAppIds) { try { const newsUrl = 'https://api.steampowered.com/ISteamNews/GetNewsForApp/v2/?appid=' + aid + '&count=20&maxlength=500&format=json'; const data = await fetchJson(newsUrl, { timeout: 12000 }); const items = (data && data.appnews && data.appnews.newsitems) || []; allNews.push(...items.map(n => ({ title: n.title || '', url: n.url || '', date: n.date || 0, contents: sglvCleanNewsText(n.contents).slice(0, 300), feedname: n.feedname || 'steam', author: n.author || '', }))); } catch { } } allNews.sort((a, b) => b.date - a.date); result.news = allNews.slice(0, 15); } catch (e2) { console.warn('[SGIS] ISteamNews 获取失败:', e2); } } result.totalCount = result.specials.length + result.dailyDeals.length + result.spotlights.length + result.news.length; cacheSet(cacheKey, result, 30 * 60 * 1000); return result; } const CARD_DB_API_URL = 'https://www.steamcardexchange.net/api/request.php?GetInventory'; const CARD_DB_CACHE_KEY = 'sgis_card_db_cache'; const CARD_DB_CACHE_TTL = 24 * 60 * 60 * 1000; let cardDbData = null; let cardDbLoading = false; function getCardDbMaxLevel(appId) { if (!cardDbData || !appId) return 0; const info = cardDbData[String(appId)]; return info ? info.maxLevel : 0; } function getCardDbGameName(appId) { if (!cardDbData || !appId) return ''; const info = cardDbData[String(appId)]; return info ? info.name : ''; } async function loadCardDatabase() { if (cardDbData || cardDbLoading) return cardDbData; cardDbLoading = true; try { const cached = GM_getValue(CARD_DB_CACHE_KEY, null); if (cached && cached.timestamp && (Date.now() - cached.timestamp < CARD_DB_CACHE_TTL)) { cardDbData = cached.data; console.log(`[SGIS] 卡牌数据库缓存命中: ${Object.keys(cardDbData).length} 款游戏`); return cardDbData; } console.log('[SGIS] 正在从 SteamCardExchange 获取卡牌数据库...'); const text = await sglvGmFetchTextRetry(CARD_DB_API_URL, { timeout: 30000 }); const json = JSON.parse(text); if (!json || !json.data || !Array.isArray(json.data)) { throw new Error('API 返回数据格式异常'); } const db = {}; let count = 0; json.data.forEach((current) => { if (!current || !current[0] || !current[3]) return; const appId = String(current[0][0]); const name = current[0][1] || ''; const size = current[3][0] || 0; if (appId && size) { db[appId] = { name, maxLevel: size }; count++; } }); cardDbData = db; GM_setValue(CARD_DB_CACHE_KEY, { timestamp: Date.now(), data: db }); console.log(`[SGIS] 卡牌数据库加载完成: ${count} 款游戏`); const _badgeLib = (typeof unsafeWindow !== 'undefined' && unsafeWindow.SGLVBadge) || (typeof window !== 'undefined' && window.SGLVBadge); if (_badgeLib && typeof _badgeLib.setCardDb === 'function') { _badgeLib.setCardDb(db); } return cardDbData; } catch (e) { console.warn('[SGIS] 卡牌数据库加载失败(不影响基本功能):', e.message); sglvNotifyNetFail('卡牌数据库 (SteamCardExchange)', e); return null; } finally { cardDbLoading = false; } } SGLV_API.getCardDbMaxLevel = getCardDbMaxLevel; SGLV_API.getCardDbGameName = getCardDbGameName; SGLV_API.loadCardDatabase = loadCardDatabase; SGLV_API.getSGISProfile = () => SGIS.profile || null; SGLV_API.fetchSGISProfile = () => { renderProfile({ force: false }); }; SGLV_API.getSGISUserBadges = () => SGIS.userBadges || null; SGLV_API.getSteamEventAppIdMap = () => typeof STEAM_EVENT_APPID_MAP !== 'undefined' ? STEAM_EVENT_APPID_MAP : null; SGLV_API.getRegionCurrency = (cc) => { const r = REGIONS.find(x => x.code === String(cc || '').toUpperCase()); return r ? r.currency : ''; }; SGLV_API.getUsdRates = () => getUsdRates(); SGLV_API.getRatesTs = () => getRatesTs(); const PROFILE_CACHE_KEY = 'sgis_profile_cache_v1'; const USER_BADGES_CACHE_KEY = 'sgis_user_badges_cache_v1'; const PROFILE_CACHE_TTL = 7 * 24 * 3600 * 1000; function readPersistentProfileCache(steamId) { try { const raw = GM_getValue(PROFILE_CACHE_KEY, null); if (!raw) return null; const obj = JSON.parse(raw); if (!obj || obj.steamId !== steamId) return null; if (obj.expires && Date.now() > obj.expires) { GM_setValue(PROFILE_CACHE_KEY, ''); return null; } return obj.data || null; } catch { return null; } } function writePersistentProfileCache(steamId, data) { try { GM_setValue(PROFILE_CACHE_KEY, JSON.stringify({ steamId, data, expires: Date.now() + PROFILE_CACHE_TTL })); } catch { } } function readPersistentUserBadgesCache(steamId) { try { const raw = GM_getValue(USER_BADGES_CACHE_KEY, null); if (!raw) return null; const obj = JSON.parse(raw); if (!obj || obj.steamId !== steamId) return null; if (obj.expires && Date.now() > obj.expires) { GM_setValue(USER_BADGES_CACHE_KEY, ''); return null; } return obj.data || null; } catch { return null; } } function writePersistentUserBadgesCache(steamId, data) { try { GM_setValue(USER_BADGES_CACHE_KEY, JSON.stringify({ steamId, data, expires: Date.now() + PROFILE_CACHE_TTL })); } catch { } } function isBadgeDataBetterThanCache(newData, cachedData) { if (!cachedData) return true; if (!newData) return false; if ((newData.playerLevel || 0) < (cachedData.playerLevel || 0)) return false; if ((newData.playerXp || 0) < (cachedData.playerXp || 0)) return false; function curLevelThreshold(d) { const L = d.playerLevel || 0; if (L <= 0) return 0; let xp = 0; let bracketStart = 1; let perLevel = 100; while (bracketStart < L) { const bracketEnd = Math.min(bracketStart + 10, L); xp += (bracketEnd - bracketStart) * perLevel; bracketStart += 10; perLevel += 100; } return xp; } const newProgress = Math.max(0, (newData.playerXp || 0) - curLevelThreshold(newData)); const cachedProgress = Math.max(0, (cachedData.playerXp || 0) - curLevelThreshold(cachedData)); if (newProgress < cachedProgress - 100) return false; return true; } async function fetchUserBadges(steamId, opts = {}) { const apiKey = storage.getApiKey(); if (!apiKey || !steamId) return null; const { force = false } = opts; const cacheKey = 'userBadges_' + steamId; const ttlCache = cacheGet(cacheKey); const persistentCache = readPersistentUserBadgesCache(steamId); const cached = force ? null : (ttlCache || persistentCache); if (cached && !force) { return enrichBadgesWithGameNames(cached); } try { const url = `https://api.steampowered.com/IPlayerService/GetBadges/v1/?key=${apiKey}&steamid=${steamId}`; const data = await fetchJson(url, { timeout: 12000 }); const badges = data?.response?.badges || []; const playerLevel = data?.response?.player_level || 0; const playerXp = data?.response?.player_xp || 0; const playerXpNeededCurrentLevel = data?.response?.player_xp_needed_current_level || 0; const playerXpNeededToLevelUp = data?.response?.player_xp_needed_to_level_up || 0; const result = { badges, playerLevel, playerXp, playerXpNeededCurrentLevel, playerXpNeededToLevelUp, _ts: Date.now() }; const keepOld = cached && !isBadgeDataBetterThanCache(result, cached); if (keepOld) { console.log('[SGIS] GetBadges API 数据异常(进度低于缓存), 保留旧缓存'); return enrichBadgesWithGameNames(cached); } cacheSet(cacheKey, result, 6 * 3600 * 1000); writePersistentUserBadgesCache(steamId, result); return enrichBadgesWithGameNames(result); } catch { if (persistentCache) return enrichBadgesWithGameNames(persistentCache); return null; } } function enrichBadgesWithGameNames(badgeData) { if (!badgeData || !badgeData.badges) return badgeData; const owned = (state.ownedGames && state.ownedGames.length) ? state.ownedGames : storage.getCachedGames(); const ownedMap = {}; owned.forEach(g => { if (g && g.appid) ownedMap[String(g.appid)] = g.name; }); badgeData.badges.forEach(b => { if (b.appid > 0) { b._gameName = ownedMap[String(b.appid)] || getCardDbGameName(b.appid) || ''; b._hasGameName = !!b._gameName; b._maxLevel = getCardDbMaxLevel(b.appid); } if (b.communityitemid) { b._isCommunityBadge = true; } }); return badgeData; } const STEAM_EVENT_APPID_MAP = { 4761370: '2026 年夏日特卖', 4113600: '2025 年冬日特卖', 4098760: '2025 年夏日特卖', 3902760: '2025 年春季特卖', 3567630: '2024 年冬日特卖', 3443010: '2024 年夏日特卖', 3220140: '2024 年春季特卖', 3091960: '2023 年冬日特卖', 2881690: '2023 年夏日特卖', 2700500: '2023 年春季特卖', 2682730: '2022 年冬日特卖', 2489650: '2022 年夏日特卖', 2320430: '2022 年秋季特卖', 2285690: '2021 年冬日特卖', 2111170: '2021 年夏日特卖', 1977630: '2021 年秋季特卖', 1919510: '2020 年冬日特卖', 1708140: '2020 年夏日特卖', 1624910: '2020 年秋季特卖', 1531430: '2019 年冬日特卖', 1411040: '2019 年夏日特卖', 1283310: '2019 年秋季特卖', 1254900: '2018 年冬日特卖', 1111370: '2018 年夏日特卖', 977950: '2018 年秋季特卖', 991980: '2017 年冬日特卖', 866930: '2017 年夏日特卖', 748210: '2017 年冬日特卖', 630870: '2016 年夏日特卖', 516940: '2016 年冬日特卖', 408590: '2015 年夏日特卖', 302200: '2015 年冬日特卖', 224260: '2014 年夏日特卖', 161330: '2014 年冬日特卖', 104700: '2013 年夏日特卖', 57430: '2013 年冬日特卖', 207250: '2012 年假日特卖', 4770200: '2025 Steam 大奖投票', 4149180: '2024 Steam 大奖投票', 3934100: '2023 Steam 大奖投票', 3711000: '2022 Steam 大奖投票', 3510200: '2021 Steam 大奖投票', 3326500: '2020 Steam 大奖投票', 3125400: '2019 Steam 大奖投票', 2944230: '2018 Steam 大奖投票', 1510: 'Steam 大奖 (2016)', 660: 'Steam 大奖 (2015)', 531: 'Steam 大奖 (2014)', 2519800: 'Steam 20 周年纪念', 1978740: 'Steam 18 周年纪念', }; const ACTIVITY_ICON_CDN = 'https://cdn.cloudflare.steamstatic.com/steamcommunity/public/images/items/'; function getActivityIconUrl(appid) { if (!appid) return ''; return ACTIVITY_ICON_CDN + appid + '/icon_64x64.png'; } function detectEventBadge(b) { if (!b.appid) return null; const eventName = STEAM_EVENT_APPID_MAP[String(b.appid)]; if (eventName) return { name: eventName, appid: b.appid }; if (b.appid > 3000000 && !b._hasGameName) { return { name: 'Steam 活动 #' + b.appid, appid: b.appid }; } return null; } function shouldInvalidateProfileCache(steamId) { try { const cached = readPersistentProfileCache(steamId); if (!cached) return true; const currentGameCount = getStatFilteredGames().length; if ((cached.gameCount || 0) !== currentGameCount) return true; return false; } catch { return true; } } function renderProfile(opts = {}) { _paintTab = 'profile'; const { force = false } = opts; const steamId = getActiveSteamId(); if (SGLV_API.loadDlcDatabase) { SGLV_API.loadDlcDatabase().then(() => { if (SGIS.profile && !SGIS.profileLoading) renderProfileContent(); if (SGLV_API.enrichOwnedAppTypes) { SGLV_API.enrichOwnedAppTypes().then(() => { if (SGIS.profile && !SGIS.profileLoading) renderProfileContent(); }).catch(() => {}); } }).catch(() => {}); } if (!force && SGIS.profile) { renderProfileContent(); return; } if (SGIS.profileLoading) return; SGIS.profileLoading = true; renderLoading('正在获取用户档案…'); if (!steamId) { SGIS.profileLoading = false; setBody(`
${SGIS_ICONS.user}
未检测到 SteamID
请在设置中配置 SteamID64,或访问你的 Steam 个人主页后重试。
`); return; } const cacheInvalid = force || shouldInvalidateProfileCache(steamId); const cachedProfile = !cacheInvalid ? readPersistentProfileCache(steamId) : null; if (cachedProfile && cachedProfile.summary) { SGIS.profile = cachedProfile; SGIS.profileLoading = false; renderProfileContent(); return; } Promise.all([ fetchPlayerSummaries(steamId), fetchSteamLevel(steamId), fetchFriendCount(steamId), fetchUserBadges(steamId, { force }).catch(() => null), fetchRecentlyPlayedGames(steamId).catch(() => []), fetchWishlistCount(steamId).catch(() => null), ]).then(([summary, level, friendCount, userBadges, recentGames, wishlistCount]) => { const gameCount = getStatFilteredGames().length; const profileData = { summary, level, friendCount, userBadges, steamId, gameCount, recentGames, wishlistCount }; SGIS.profile = profileData; SGIS.profileLoading = false; writePersistentProfileCache(steamId, profileData); renderProfileContent(); }).catch(e => { SGIS.profileLoading = false; renderError('用户档案获取失败: ' + e.message); }); } function xpRequiredToReachLevel(L) { if (L <= 1) return 0; let xp = 0; let bracketStart = 1; let perLevel = 100; while (bracketStart < L) { const bracketEnd = Math.min(bracketStart + 10, L); const levelsInBracket = bracketEnd - bracketStart; xp += levelsInBracket * perLevel; bracketStart += 10; perLevel += 100; } return xp; } function _renderProfileHeader(data) { return `
${data.personaName}
Lv.${data.playerLevel}
${data.steamIdShort || '?'}
${data.steamIdShort ? `` : ''}
${data.friendCount}/ ${data.friendLimit}
好友数
${data.SGIS_ICONS.barChart}
${data.gameCount.toLocaleString()}
Games
${data.SGIS_ICONS.package}
${data.dlcDisplay}
DLC
${data.SGIS_ICONS.medal}
${data.badgeCount.toLocaleString()}
Badges
${data.SGIS_ICONS.heart}
${data.wishlistDisplay}
Wishlist
${data.SGIS_ICONS.clock}
${data.totalHours >= 1000 ? (data.totalHours / 1000).toFixed(1) + 'k' : data.totalHours}h
Playtime
`; } function _renderProfileXp(data) { return `
经验值 · 等级进度
Lv.${data.playerLevel} → ${data.isMaxLevel ? `MAX` : `Lv.${data.playerLevel + 1}`}
${data.hbarRow({ cls: 'xp', pct: data.xpPercent.toFixed(1) })}
${data.isMaxLevel ? `
已达成 · 满级
100%
` : `
${data.currentIntoLevel.toLocaleString()} / ${data.xpDelta.toLocaleString()} XP · 还差 ${data.xpToNext.toLocaleString()} XP
${data.xpPercent.toFixed(0)}%
`}
`; } function _renderProfileFeatures(data) { return `
${data.SGIS_ICONS.trophy}
战绩总览
Battle Stats
已游玩
${data.playedGames}
完成度
${data.completeRate}%
平均时长
${data.avgHours}h
${data.SGIS_ICONS.sparkle}
游戏人生
Gamer Profile
总时长
${data.totalHours >= 1000 ? (data.totalHours / 1000).toFixed(1) + 'k' : data.totalHours}h
成就数
${data.badgeCount}
`; } function _renderProfileSections(data) { return `
${data.SGIS_ICONS.game} 最近游玩
${data.recentGames.length === 0 ? '
最近 2 周未游玩任何游戏
' : data.recentGamesHtml}
${data.wishlistSaleHtml}
${data.SGIS_ICONS.link} 快捷链接
数据来自 Steam Web API · 缓存30分钟
`; } function _prepareProfileData(p, s) { if (SGLV_API.loadDlcDatabaseFromCacheSync) SGLV_API.loadDlcDatabaseFromCacheSync(); const allGames = getStatFilteredGames(); const gameCount = allGames.length; const dlcCount = getOwnedDlcCount(); const dlcReady = !!(SGLV_API.isDlcDbReady && SGLV_API.isDlcDbReady()); const dlcDisplay = dlcReady ? dlcCount.toLocaleString() : '—'; const totalPlaytime = allGames.reduce((sum, g) => sum + (g.playtime || 0), 0); const totalHours = Math.floor(totalPlaytime / 60); const friendCount = p.friendCount != null ? p.friendCount : '?'; const badgeCount = (p.userBadges && p.userBadges.badges) ? p.userBadges.badges.length : 0; const totalXp = (p.userBadges && p.userBadges.playerXp) ? p.userBadges.playerXp : 0; const level = p.level || '?'; const playerLevel = (p.userBadges && p.userBadges.playerLevel) ? p.userBadges.playerLevel : (typeof level === 'number' ? level : 0); const friendLimit = 300 + playerLevel * 5; const fcNum = (typeof friendCount === 'number' && isFinite(friendCount)) ? friendCount : 0; const friendRatio = Math.min(1, fcNum / Math.max(1, friendLimit)); const ringCirc = (Math.PI * 48).toFixed(1); const ringDash = (friendRatio * Math.PI * 48).toFixed(1); const wishlistCount = p.wishlistCount; const wishlistDisplay = (wishlistCount != null) ? Number(wishlistCount).toLocaleString() : '?'; const apiCurLevelXp = (p.userBadges && p.userBadges.playerXpNeededCurrentLevel) ? p.userBadges.playerXpNeededCurrentLevel : 0; const apiLevelUpXp = (p.userBadges && p.userBadges.playerXpNeededToLevelUp) ? p.userBadges.playerXpNeededToLevelUp : 0; let useApiXp = apiCurLevelXp > 0 && apiLevelUpXp > 0; if (useApiXp && totalXp > 0 && totalXp < apiCurLevelXp - 1000) useApiXp = false; const curLevelXp = useApiXp ? apiCurLevelXp : xpRequiredToReachLevel(playerLevel); const xpDelta = useApiXp ? apiLevelUpXp : (xpRequiredToReachLevel(playerLevel + 1) - curLevelXp); const effectiveXp = totalXp > 0 ? totalXp : (playerLevel > 0 ? curLevelXp : 0); let currentIntoLevel = Math.max(0, effectiveXp - curLevelXp); let safeCurrentIntoLevel = currentIntoLevel; let safeXpDelta = Math.max(1, xpDelta); if (safeCurrentIntoLevel > safeXpDelta) { safeCurrentIntoLevel = Math.max(0, effectiveXp - xpRequiredToReachLevel(playerLevel)); safeXpDelta = Math.max(1, xpRequiredToReachLevel(playerLevel + 1) - xpRequiredToReachLevel(playerLevel)); if (safeCurrentIntoLevel > safeXpDelta) safeCurrentIntoLevel = safeXpDelta; } const xpPercent = Math.max(0, Math.min(100, (safeCurrentIntoLevel / safeXpDelta) * 100)); const xpToNext = Math.max(0, safeXpDelta - safeCurrentIntoLevel); const isMaxLevel = playerLevel <= 0; const totalXpDisplay = effectiveXp; const playedGames = allGames.filter(g => (g.playtime || 0) > 0).length; const unplayedGames = Math.max(0, gameCount - playedGames); const avgHours = playedGames > 0 ? Math.round(totalHours / playedGames) : 0; const longGames = allGames.filter(g => (g.playtime || 0) >= 600).length; const completeRate = playedGames > 0 ? Math.round((longGames / playedGames) * 100) : 0; const profileUrl = s.profileurl || `https://steamcommunity.com/profiles/${p.steamId}/`; const recentGames = p.recentGames || []; const recentGamesHtml = recentGames.slice(0, 8).map(game => { const recentH = formatPlaytimeShort(game.playtime_2weeks); const totalH = formatPlaytimeShort(game.playtime_forever); const iconUrl = getGameIconUrl(game.appid, game.img_icon_url); return `
${game.name}
近2周: ${recentH} · 总计: ${totalH}
`; }).join(''); const wishlistOnSale = (Array.isArray(state.wishlistGames) ? state.wishlistGames : []).filter(g => g && g.discountPct > 0 && !g.isFree).sort((a, b) => (b.discountPct || 0) - (a.discountPct || 0)).slice(0, 8); const wishlistSaleHtml = wishlistOnSale.length === 0 ? '' : (() => { const items = wishlistOnSale.map(g => { const finalStr = g.finalPrice > 0 ? `¥${g.finalPrice.toFixed(2)}` : (isZh ? '免费' : 'Free'); const origStr = g.originalPrice > g.finalPrice ? `¥${g.originalPrice.toFixed(2)}` : ''; return `
${escHtml(g.name)}
-${g.discountPct}% ${finalStr} ${origStr ? `${origStr}` : ''}
`; }).join(''); return `
${SGIS_ICONS.heart || '💝'} ${isZh ? '愿望单促销' : 'Wishlist on Sale'} ${wishlistOnSale.length} ${isZh ? '款打折中' : 'on sale'}
${items}
`; })(); return { p, s, avatarUrl: s.avatarfull || s.avatarmedium || s.avatar || '', personaName: s.personaname || '未知玩家', level, realName: s.realname || '', country: s.loccountrycode || '', profileUrl, steamIdShort: p.steamId ? String(p.steamId) : '', allGames, gameCount, dlcCount, dlcReady, dlcDisplay, totalPlaytime, totalHours, friendCount, badgeCount, totalXp, playerLevel, friendLimit, fcNum, friendRatio, ringCirc, ringDash, wishlistCount, wishlistDisplay, apiCurLevelXp, apiLevelUpXp, useApiXp, curLevelXp, xpDelta, effectiveXp, currentIntoLevel, safeCurrentIntoLevel, safeXpDelta, xpPercent, xpToNext, isMaxLevel, totalXpDisplay, playedGames, unplayedGames, avgHours, longGames, completeRate, recentGames, recentGamesHtml, wishlistOnSale, wishlistSaleHtml, SGIS_ICONS, hbarRow, escHtml, }; } function renderProfileContent() { _paintTab = 'profile'; const p = SGIS.profile; if (!p || !p.summary) { setBody(`
${SGIS_ICONS.user}
无法获取用户档案
请确保 API Key 和 SteamID 配置正确
`); return; } const s = p.summary; const data = _prepareProfileData(p, s); setBody(_renderProfileHeader(data) + _renderProfileXp(data) + _renderProfileFeatures(data) + _renderProfileSections(data)); applyGameAliases(document, { scope: '#sgis-body' }); const featureStats = document.getElementById('sgis-feature-stats'); if (featureStats) { featureStats.addEventListener('click', () => { if (typeof SGIS !== 'undefined') { const panel = document.getElementById('sgis-panel'); if (panel) { const tab = panel.querySelector('.sgis-tab[data-tab="userAchievements"]'); if (tab) tab.click(); } } }); } const featureAch = document.getElementById('sgis-feature-achievements'); if (featureAch) { featureAch.addEventListener('click', () => { if (typeof SGIS !== 'undefined') { const panel = document.getElementById('sgis-panel'); if (panel) { const tab = panel.querySelector('.sgis-tab[data-tab="userAchievements"]'); if (tab) tab.click(); } } }); } const statGames = document.getElementById('sgis-stat-games'); if (statGames) { statGames.addEventListener('click', () => { closePanel(); document.dispatchEvent(new CustomEvent('sglv:open-library')); }); } const statDlc = document.getElementById('sgis-stat-dlc'); if (statDlc) { statDlc.addEventListener('click', () => { closePanel(); document.dispatchEvent(new CustomEvent('sglv:open-library')); setTimeout(() => { const dashCard = document.querySelector('.sglv-stat-dash-card[data-filter="dlconly"]'); if (dashCard) dashCard.click(); }, 300); }); } const statBadges = document.getElementById('sgis-stat-badges'); if (statBadges) { statBadges.addEventListener('click', () => { window.open(`${data.profileUrl}badges/`, '_blank'); }); } const statWishlist = document.getElementById('sgis-stat-wishlist'); if (statWishlist) { statWishlist.addEventListener('click', () => { const sid = p.steamId || getActiveSteamId(); window.open(sid ? `https://store.steampowered.com/wishlist/profiles/${sid}/` : 'https://store.steampowered.com/wishlist/', '_blank'); }); } const friendGauge = document.getElementById('sgis-friend-gauge'); if (friendGauge) { friendGauge.addEventListener('click', () => { const panel = document.getElementById('sgis-panel'); const tab = panel ? panel.querySelector('.sgis-tab[data-tab="social"]') : null; if (tab) tab.click(); }); } const copySidBtn = document.getElementById('sgis-copy-steamid'); if (copySidBtn) { copySidBtn.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); copyTextToClipboard(data.steamIdShort); sglvToast.success(isZh ? 'SteamID 已复制' : 'SteamID copied'); }); } if (p.wishlistCount == null) { fetchWishlistCount(p.steamId || getActiveSteamId()).then(n => { if (n == null) return; p.wishlistCount = n; const el = document.getElementById('sgis-stat-wishlist-val'); if (el) el.textContent = Number(n).toLocaleString(); }).catch(() => { }); } } function renderActivity() { const sub = SGIS.activitySubTab || 'personal'; if (sub === 'official') { if (SGIS.activity) { renderActivityContent(); return; } if (SGIS.activityLoading) return; SGIS.activityLoading = true; renderLoading('正在获取 Steam 官方动态…'); fetchSteamOfficialNews().then(news => { SGIS.activity = news; SGIS.activityLoading = false; renderActivityContent(); }).catch(e => { SGIS.activityLoading = false; renderError('动态获取失败: ' + e.message); }); } else if (sub === 'personal') { if (SGIS.personalTimeline) { renderActivityContent(); return; } if (SGIS.personalTimelineLoading) return; SGIS.personalTimelineLoading = true; renderLoading('正在加载个人入库历史…'); const steamId = getActiveSteamId(); buildPersonalTimeline(steamId).then(data => { SGIS.personalTimeline = data; SGIS.personalTimelineLoading = false; renderActivityContent(); }).catch(e => { SGIS.personalTimelineLoading = false; console.warn('[SGIS] 个人入库历史加载失败:', e); sglvToast.error(isZh ? '个人入库历史加载失败' : 'Personal timeline load failed'); renderError('个人入库历史加载失败: ' + (e.message || '网络错误')); }); } else if (sub === 'family') { if (SGIS.familyTimeline) { renderActivityContent(); return; } if (SGIS.familyTimelineLoading) { if (!document.getElementById('sgis-load-block')) { renderProgressLoading({ stage: 3, totalStages: 4, text: '正在加载家庭组入库历史…', skeletonCount: 8 }); } return; } SGIS.familyTimelineLoading = true; const prog = renderProgressLoading({ stage: 1, totalStages: 4, text: '正在准备家庭组数据…', skeletonCount: 8 }); const steamId = getActiveSteamId(); buildFamilyTimeline(steamId, (stage, percent, text) => { if (!SGIS.familyTimelineLoading) return; prog.update({ stage, percent, text }); }).then(data => { SGIS.familyTimeline = data; SGIS.familyTimelineLoading = false; renderActivityContent(); }).catch(e => { SGIS.familyTimelineLoading = false; console.warn('[SGIS] 家庭组入库历史加载失败:', e); sglvToast.error(isZh ? '家庭组入库历史加载失败' : 'Family timeline load failed'); renderError('家庭组入库历史加载失败: ' + (e.message || '网络错误')); }); } } function renderActivityLibraryHistory(data) { if (!data || !data.items || data.items.length === 0) return '
暂无入库记录
'; const items = data.items; let html = ''; let curDate = ''; items.forEach(it => { const dateKey = it.dateStr || ''; if (dateKey && dateKey !== curDate) { curDate = dateKey; html += `
${dateKey}
`; } const iconUrl = getGameIconUrl(it.appid, it.icon); const timeText = it.ts && !it.licenseCorrected ? new Date(it.ts).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }) : ''; const metaParts = []; if (it.purchaserName) metaParts.push(`${escHtml(it.purchaserName)} 购入`); if (timeText) metaParts.push(timeText); html += `
${it.name} ${metaParts.length ? `
${metaParts.join(' · ')}
` : ''}
`; }); return html; } const _ACTIVITY_SUB_TABS = [ { key: 'personal', icon: SGIS_ICONS.package, label: '个人入库' }, { key: 'family', icon: SGIS_ICONS.users, label: '家庭组入库' }, { key: 'official', icon: SGIS_ICONS.news, label: '官方动态' }, ]; function _actFormatPrice(cents, currency) { const v = Number(cents); if (isNaN(v) || v === 0) return '免费'; const symbol = (currency === 'USD') ? '$' : ''; return symbol + (v / 100).toFixed(2); } function _actFormatExpiration(expTs) { const exp = Number(expTs); if (!exp || isNaN(exp)) return ''; const now = Math.floor(Date.now() / 1000); const diff = exp - now; if (diff <= 0) return '已结束'; const days = Math.floor(diff / 86400); const hours = Math.floor((diff % 86400) / 3600); if (days > 0) return `剩余${days}天${hours}小时`; if (hours > 0) return `剩余${hours}小时`; return `剩余${Math.floor(diff / 60)}分钟`; } function _actFormatNewsDate(ts) { if (!ts) return ''; const d = new Date(ts * 1000); return `${d.getMonth() + 1}月${d.getDate()}日`; } function _actSpotlightBody(sp) { if (!sp.body) return ''; let body = sp.body; if (!body.match(/%\d\$s/)) return body; let timeStr = ''; if (sp.discountExpiration && sp.discountExpiration > 0) { timeStr = _actFormatExpiration(sp.discountExpiration); } if (!timeStr) { const name = (sp.name || '').toLowerCase(); if (name.includes('周末') || name.includes('weekend')) { timeStr = isZh ? '预计明天截止' : 'Est. ends tomorrow'; } else { timeStr = isZh ? '预计2-3天后截止' : 'Est. ends in 2-3 days'; } } body = body.replace(/%\d\$s/g, timeStr); return body; } function _renderActivityOfficial() { const data = SGIS.activity || { specials: [], dailyDeals: [], spotlights: [], news: [], totalCount: 0 }; const totalCount = Number(data.totalCount) || 0; if (totalCount === 0) { return `
📢
暂无官方动态
`; } let html = ''; if (Array.isArray(data.spotlights) && data.spotlights.length > 0) { html += `
`; html += `
🎯 促销活动${data.spotlights.length} 个活动
`; html += data.spotlights.map(sp => { const processedBody = _actSpotlightBody(sp); return ` ${sp.headerImage ? `` : ''}
${sp.name}
${processedBody ? `
${processedBody}
` : ''}
`; }).join(''); html += `
`; } if (Array.isArray(data.dailyDeals) && data.dailyDeals.length > 0) { html += `
`; html += `
⚡ 每日优惠${data.dailyDeals.length} 款
`; html += `
`; } if (Array.isArray(data.specials) && data.specials.length > 0) { html += ``; } if (Array.isArray(data.news) && data.news.length > 0) { html += `
`; html += `
📰 官方新闻${data.news.length} 条
`; html += data.news.map(n => { const desc = n.contents ? n.contents.slice(0, 150) + (n.contents.length > 150 ? '...' : '') : ''; return ` 新闻
${_actFormatNewsDate(n.date)}
${n.title}
${desc ? `
${desc}
` : ''}
`; }).join(''); html += `
`; } return html; } function _renderActivityTimelineSection({ loading, timeline, page, loadMoreId }) { if (loading) return `
正在加载…
`; if (!timeline) return `
暂无数据
`; const allItems = timeline.items || []; const PAGE_SIZE = 100; const curPage = Math.max(1, page || 1); const visibleItems = allItems.slice(0, curPage * PAGE_SIZE); const hasMore = visibleItems.length < allItems.length; let html = renderActivityLibraryHistory({ items: visibleItems }); if (hasMore) { html += `
向下滚动加载更多(已显示 ${visibleItems.length}/${allItems.length})
`; } else if (allItems.length > 0) { html += `
已加载全部 ${allItems.length} 条
`; } return html; } function _bindActivityEvents(sub) { const body = document.getElementById('sgis-body'); if (body) { body.querySelectorAll('.sgis-sub-tab').forEach(btn => { btn.addEventListener('click', () => { const newSub = btn.dataset.sub; if (SGIS.activitySubTab === newSub) return; SGIS.activitySubTab = newSub; SGIS.familyTimelinePage = 1; SGIS.personalTimelinePage = 1; renderActivity(); }); }); } const bindTimelineLoadMore = (elId, getPage, setPage, getTotal) => { const el = document.getElementById(elId); if (!el) return; const io = new IntersectionObserver(entries => { if (!entries[0].isIntersecting) return; io.disconnect(); const nextPage = getPage() + 1; if (nextPage * 100 - 100 < getTotal()) { setPage(nextPage); renderActivityContent(); } }, { root: document.getElementById('sgis-body'), rootMargin: '300px' }); io.observe(el); }; if (sub === 'family') { bindTimelineLoadMore('sgis-family-load-more', () => SGIS.familyTimelinePage || 1, p => { SGIS.familyTimelinePage = p; }, () => (SGIS.familyTimeline && SGIS.familyTimeline.items ? SGIS.familyTimeline.items.length : 0)); } if (sub === 'personal') { bindTimelineLoadMore('sgis-personal-load-more', () => SGIS.personalTimelinePage || 1, p => { SGIS.personalTimelinePage = p; }, () => (SGIS.personalTimeline && SGIS.personalTimeline.items ? SGIS.personalTimeline.items.length : 0)); } } function renderActivityContent() { _paintTab = 'activity'; const sub = SGIS.activitySubTab || 'personal'; const subTabHtml = `
${_ACTIVITY_SUB_TABS.map(t => ``).join('')}
`; let contentHtml = ''; let footerText = ''; if (sub === 'official') { contentHtml = _renderActivityOfficial(); footerText = '数据来自 Steam Storefront API + Steam News API · 缓存30分钟'; } else if (sub === 'personal') { contentHtml = _renderActivityTimelineSection({ loading: SGIS.personalTimelineLoading, timeline: SGIS.personalTimeline, page: SGIS.personalTimelinePage, loadMoreId: 'sgis-personal-load-more', }); const pTotal = (SGIS.personalTimeline && SGIS.personalTimeline.items) ? SGIS.personalTimeline.items.length : 0; const pShown = Math.min(pTotal, Math.max(1, SGIS.personalTimelinePage || 1) * 100); const pCorrected = (SGIS.personalTimeline && SGIS.personalTimeline.corrected) || 0; footerText = `基于家庭组共享库入库时间(rt_time_acquired)· 按入库时间排序${pTotal > 0 ? ` · 已显示 ${pShown}/${pTotal}` : ''}${pCorrected > 0 ? ` · ${pCorrected} 款已按个人许可页校准` : ''}`; } else if (sub === 'family') { contentHtml = _renderActivityTimelineSection({ loading: SGIS.familyTimelineLoading, timeline: SGIS.familyTimeline, page: SGIS.familyTimelinePage, loadMoreId: 'sgis-family-load-more', }); const totalItems = (SGIS.familyTimeline && SGIS.familyTimeline.items) ? SGIS.familyTimeline.items.length : 0; const shownItems = Math.min(totalItems, Math.max(1, SGIS.familyTimelinePage || 1) * 100); footerText = `基于家庭组共享库入库时间(rt_time_acquired)· 按入库时间排序 · 购买者=最新入库成员${totalItems > 0 ? ` · 已显示 ${shownItems}/${totalItems}` : ''}`; } setBody(`
${SGIS_ICONS.news} Steam 动态
${subTabHtml}
${contentHtml}
${footerText}
`); applyGameAliases(document, { scope: '#sgis-body' }); _bindActivityEvents(sub); } function renderUserBadges() { _paintTab = 'userBadges'; if (SGIS.userBadges) { renderUserBadgesContent(); return; } if (SGIS.userBadgesLoading) return; SGIS.userBadgesLoading = true; renderLoading('正在获取勋章数据…'); const steamId = getActiveSteamId(); if (!steamId) { SGIS.userBadgesLoading = false; setBody(`
🎖️
未检测到 SteamID
`); return; } fetchUserBadges(steamId).then(data => { SGIS.userBadges = data; SGIS.userBadgesLoading = false; renderUserBadgesContent(); if (!cardDbData && !cardDbLoading) { loadCardDatabase().then(() => { if (cardDbData && SGIS.userBadges) { SGIS.userBadges = enrichBadgesWithGameNames(SGIS.userBadges); if (SGIS.tab === 'userBadges') renderUserBadgesContent(); } }).catch(() => { }); } }).catch(e => { SGIS.userBadgesLoading = false; renderError('勋章获取失败: ' + e.message); }); } function _userBadgeFormatTime(ts) { if (!ts) return ''; try { return new Date(ts * 1000).toLocaleDateString('zh-CN', { year: '2-digit', month: '2-digit', day: '2-digit' }); } catch { return ''; } } function _userBadgeRarityLabel(s) { if (!s) return null; if (s >= 5) return { label: '史诗', cls: 'r5' }; if (s >= 4) return { label: '极稀有', cls: 'r4' }; if (s >= 3) return { label: '稀有', cls: 'r3' }; if (s >= 2) return { label: '少见', cls: 'r2' }; return { label: '普通', cls: 'r1' }; } function _userBadgeScoreColor(s) { return s >= 70 ? 'high' : s >= 40 ? 'mid' : 'low'; } function _getUserBadgeIcon(b, markets) { const market = markets[String(b.appid)]; if (market && market.cards && market.cards.length > 0) { const cardWithIcon = market.cards.find(c => c.iconUrl); if (cardWithIcon) return cardWithIcon.iconUrl; } if (b._eventName && b.appid > 0) { return getActivityIconUrl(b.appid); } if (b.appid > 0) { return `https://shared.fastly.steamstatic.com/store_item_assets/steam/apps/${b.appid}/capsule_184x69.jpg`; } return ''; } function _renderUserBadgeRow(b, ctx) { const gname = b._gameName || (b._eventName ? b._eventName + ' 徽章' : (b.communityitemid ? `社区徽章 #${b.badgeid}` : `游戏 #${b.appid}`)); const eventBadge = b._eventName; const rar = _userBadgeRarityLabel(b.scarcity); const icon = eventBadge ? SGIS_ICONS.gift : (b._gameName ? SGIS_ICONS.game : SGIS_ICONS.sparkle); const valueData = ctx.valueScores[String(b.appid)]; const hasValue = !!valueData; const scoreCls = hasValue ? _userBadgeScoreColor(valueData.score) : ''; const market = ctx.markets[String(b.appid)]; const hasCardIcon = !!(market && market.cards && market.cards.find(c => c.iconUrl)); const tooltip = hasValue ? `
${gname}
价值 ${valueData.score}
${valueData.marketData ? `
市场卡价 ${valueData.marketData.cardCount} 张 · 均 ${formatMarketPrice(valueData.marketData.avgPrice)}
中位/税后 ${formatMarketPrice(valueData.marketData.medianPrice)} / ${formatMarketPrice(valueData.marketData.netIncome)}
` : '
市场数据加载中...
'}
Lv.${b.level || 1}${b._maxLevel > 0 ? '/' + b._maxLevel : ''}${b.xp || 0} XP
XP
等级
卡价
完成
` : ''; return `
${b.appid > 0 ? `` : `
${icon}
`}
${gname}
Lv.${b.level || 1}${b._maxLevel > 0 ? '/' + b._maxLevel : ''} ${(b.xp || 0).toLocaleString()} XP ${rar ? `${rar.label}` : ''} ${b.completion_time ? `${_userBadgeFormatTime(b.completion_time)}` : ''} ${hasValue ? `${valueData.score}分` : ''}
${b.appid > 0 ? `${SGIS_ICONS.chevronRight}` : ''} ${tooltip}
`; } function _renderUserBadgeGroup(id, icon, title, sub, badges, defaultExpanded, ctx) { const expClass = defaultExpanded ? ' sgis-badge-group-expanded' : ''; const totalXp = badges.reduce((s, b) => s + (b.xp || 0), 0); const maxLevel = badges.reduce((m, b) => Math.max(m, b.level || 1), 1); const realMaxLevel = badges.reduce((m, b) => Math.max(m, b._maxLevel || 0), 0); const completedN = badges.filter(b => (b.completion_time || 0) > 0).length; const completedPct = badges.length ? Math.round(completedN / badges.length * 100) : 0; return `
${icon}
${title}
${sub}
${badges.length}枚 Lv.${maxLevel}${realMaxLevel > 0 ? `/ ${realMaxLevel}` : ''}
${SGIS_ICONS.chevronRight}
${badges.map(b => _renderUserBadgeRow(b, ctx)).join('')}
${completedN}/${badges.length} 已合成 · ${totalXp.toLocaleString()} XP
`; } function _renderUserValueBadgeCard(vd) { if (!vd) return ''; const market = vd.marketData; const avgPrice = market ? formatMarketPrice(market.avgPrice) : '—'; const medianPrice = market && market.medianPrice ? formatMarketPrice(market.medianPrice) : '—'; const netIncome = market && market.netIncome ? formatMarketPrice(market.netIncome) : '—'; const cardCount = market ? `${market.cardCount} 张` : '加载中'; const appIdNum = Number(vd.appId) || 0; const capsule = `https://shared.fastly.steamstatic.com/store_item_assets/steam/apps/${appIdNum}/capsule_184x69.jpg`; let imgSrc = capsule; if (market && market.cards && market.cards.length > 0) { const cardWithIcon = market.cards.find(c => c.iconUrl); if (cardWithIcon && /^https:\/\/[^\s"'<>\\]+$/i.test(String(cardWithIcon.iconUrl))) imgSrc = String(cardWithIcon.iconUrl); } const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); const safeName = esc(vd.gameName || ''); if (!window.__sglvValueCardImgBound) { window.__sglvValueCardImgBound = true; document.addEventListener('error', (ev) => { const img = ev.target; if (!img || !img.getAttribute || img.getAttribute('data-sglv-vcard') !== '1' || img.dataset.fbDone) return; img.dataset.fbDone = '1'; const fb = img.getAttribute('data-fallback'); if (fb && img.getAttribute('src') !== fb) { img.src = fb; img.style.opacity = '0.2'; } }, true); } return `
${safeName || ('游戏 #' + appIdNum)}
Lv.${vd.level}${vd.maxLevel > 0 ? '/' + vd.maxLevel : ''} · ${vd.xp} XP
${vd.score}
价值
${cardCount} · 均 ${avgPrice} 中位 ${medianPrice} · 税后 ${netIncome}
`; } function _renderUserBadgeHero(totalBadges, completedCount, avgValueScore, totalXpFromBadges, levelDist, maxLvCount) { return `
${totalBadges}
勋章总数
${completedCount}
已合成
${avgValueScore}
均价值
${(totalXpFromBadges / 1000).toFixed(1)}k
总 XP
完成进度 ${completedCount}/${totalBadges} (${totalBadges ? Math.round(completedCount / totalBadges * 100) : 0}%)
等级分布
${[1, 2, 3, 4, 5].map(lv => { const count = levelDist[lv] || 0; const pct = Math.max(3, (count / maxLvCount) * 100); return `
${count}
Lv.${lv}
`; }).join('')}
`; } function _renderUserBadgeFooter(eventBadgeCount, gameBadgeCount, communityBadgeCount) { return ` `; } function _refreshUserBadgeIconsToCardCover(newMarkets) { const bodyEl = document.getElementById('sgis-body'); if (!bodyEl) return; bodyEl.querySelectorAll('.sgis-badge-row[data-appid]').forEach(row => { if (row.dataset.hasCardIcon === '1') return; const appid = row.dataset.appid; if (!appid) return; const market = newMarkets[appid]; if (!market || !market.cards || !market.cards.length) return; const cardWithIcon = market.cards.find(c => c.iconUrl); if (!cardWithIcon) return; const imgEl = row.querySelector('.sgis-badge-row-img'); if (!imgEl) return; row.dataset.hasCardIcon = '1'; imgEl.dataset.originalSrc = imgEl.src; imgEl.src = cardWithIcon.iconUrl; imgEl.addEventListener('error', function onError() { imgEl.removeEventListener('error', onError); if (imgEl.dataset.originalSrc) { imgEl.src = imgEl.dataset.originalSrc; delete imgEl.dataset.originalSrc; } }, { once: true }); }); } function renderUserBadgesContent() { _paintTab = 'userBadges'; const data = SGIS.userBadges; if (!data || !data.badges) { setBody(`
${SGIS_ICONS.medal}
无法获取勋章数据
请确保 API Key 和 SteamID 配置正确
`); return; } const badges = data.badges || []; const eventBadges = []; const gameBadges = []; const communityBadges = []; badges.forEach(b => { if (b.appid > 0) { const evt = detectEventBadge(b); if (evt) { b._eventName = evt.name; eventBadges.push(b); } else { gameBadges.push(b); } } else { communityBadges.push(b); } }); const eventGroups = {}; eventBadges.forEach(b => { if (!eventGroups[b._eventName]) eventGroups[b._eventName] = []; eventGroups[b._eventName].push(b); }); const gameGroups = {}; gameBadges.forEach(b => { const gname = b._gameName || `游戏 #${b.appid}`; if (!gameGroups[gname]) gameGroups[gname] = { name: gname, appid: b.appid, badges: [] }; gameGroups[gname].badges.push(b); }); const eventNames = Object.keys(eventGroups).sort((a, b) => b.localeCompare(a, 'zh-CN')); const gameNames = Object.keys(gameGroups).sort((a, b) => gameGroups[b].badges.length - gameGroups[a].badges.length); const totalBadges = badges.length; const completedCount = badges.filter(b => (b.completion_time || 0) > 0).length; const gameBadgeCount = gameBadges.length; const eventBadgeCount = eventBadges.length; const totalXpFromBadges = badges.reduce((s, b) => s + (b.xp || 0), 0); const levelDist = getBadgeLevelDistribution(badges); const maxLvCount = Math.max(...Object.values(levelDist), 1); const markets = SGIS.userBadgeMarkets || {}; const needFetchAppIds = gameBadges .filter(b => !markets[String(b.appid)]) .map(b => b.appid) .filter((v, i, a) => a.indexOf(v) === i) .slice(0, 15); const valueScores = computeBadgeValueScores(badges, markets); const topValueBadges = getTopValueBadges(valueScores, 6); const ctx = { markets, valueScores }; const collapseStateKey = 'sgis_badge_group_collapse'; const getCollapseState = () => { try { return JSON.parse(GM_getValue(collapseStateKey, '{}')); } catch { return {}; } }; const setCollapseState = (state) => { try { GM_setValue(collapseStateKey, JSON.stringify(state)); } catch { } }; const collapseState = getCollapseState(); const groupId = (k) => 'sgis-bg-' + String(k).replace(/[^\w]/g, '_').slice(0, 60); const valueSectionHtml = _renderUserBadgeValueSection(topValueBadges); const totalValueScore = badges.reduce((s, b) => { const v = valueScores[String(b.appid)]; return s + (v ? v.score : 0); }, 0); const avgValueScore = totalBadges ? Math.round(totalValueScore / totalBadges) : 0; const heroHtml = _renderUserBadgeHero(totalBadges, completedCount, avgValueScore, totalXpFromBadges, levelDist, maxLvCount); const TOP_EXPAND = 5; const eventSectionHtml = _renderUserBadgeEventSection(eventNames, eventGroups, eventBadgeCount, collapseState, groupId, ctx); const gameSectionHtml = _renderUserBadgeGameSection(gameNames, gameGroups, gameBadgeCount, collapseState, groupId, TOP_EXPAND, ctx); const communitySectionHtml = _renderUserBadgeCommunitySection(communityBadges, collapseState, ctx); const footerHtml = _renderUserBadgeFooter(eventBadgeCount, gameBadgeCount, communityBadges.length); const html = heroHtml + valueSectionHtml + eventSectionHtml + gameSectionHtml + communitySectionHtml + footerHtml; setBody(html); if (needFetchAppIds.length > 0) { fetchBadgeMarkets(needFetchAppIds, { concurrency: 3, maxApps: 15 }).then(newMarkets => { SGIS.userBadgeMarkets = Object.assign({}, markets, newMarkets); _refreshUserBadgeIconsToCardCover(newMarkets); }).catch(e => console.warn('[SGLV] 徽章市场数据获取失败:', e)); } const body = document.getElementById('sgis-body'); if (body) { body.querySelectorAll('[data-toggle]').forEach(head => { head.addEventListener('click', () => { const group = head.closest('.sgis-badge-group'); if (group) { const isExp = group.classList.toggle('sgis-badge-group-expanded'); const gid = head.getAttribute('data-toggle'); collapseState[gid] = isExp; setCollapseState(collapseState); } }); }); } } function _renderUserBadgeValueSection(topValueBadges) { const valueCardsHtml = topValueBadges.length ? `
${topValueBadges.map(_renderUserValueBadgeCard).join('')}
` : `
暂无可分析的游戏勋章 (需要先获取游戏库数据)
`; return `
${SGIS_ICONS.star} 价值 Top ${topValueBadges.length} ${topValueBadges.length > 0 ? `综合价值评分` : ''}
${valueCardsHtml}
`; } function _renderUserBadgeEventSection(eventNames, eventGroups, eventBadgeCount, collapseState, groupId, ctx) { return `
${SGIS_ICONS.gift} 节日活动 ${eventBadgeCount} 枚 / ${eventNames.length} 个活动
${eventNames.length === 0 ? `
暂无节日活动徽章
` : eventNames.map(name => { const list = eventGroups[name]; const id = groupId('event_' + name); const expanded = collapseState[id] === true; return _renderUserBadgeGroup(id, SGIS_ICONS.gift, name, 'Steam 限定徽章', list, expanded, ctx); }).join('')}
`; } function _renderUserBadgeGameSection(gameNames, gameGroups, gameBadgeCount, collapseState, groupId, TOP_EXPAND, ctx) { return `
${SGIS_ICONS.game} 游戏勋章 ${gameBadgeCount} 枚 / ${gameNames.length} 个游戏
${gameNames.length === 0 ? `
暂无游戏勋章 (需要先获取游戏库数据)
` : gameNames.slice(0, 30).map((name, idx) => { const g = gameGroups[name]; const id = groupId('game_' + g.appid); const userSetExpanded = collapseState[id] === true; const userSetCollapsed = collapseState[id] === false; const expanded = userSetExpanded || (!userSetCollapsed && idx < TOP_EXPAND); return _renderUserBadgeGroup(id, SGIS_ICONS.game, g.name, `AppID: ${g.appid}`, g.badges, expanded, ctx); }).join('')} ${gameNames.length > 30 ? `
还有 ${gameNames.length - 30} 个游戏的勋章未显示
` : ''}
`; } function _renderUserBadgeCommunitySection(communityBadges, collapseState, ctx) { if (communityBadges.length === 0) return ''; const showComm = communityBadges.slice(0, 12); const id = 'sgis-bg-community'; const expanded = collapseState[id] === true; return `
${SGIS_ICONS.sparkle} 社区勋章 ${communityBadges.length} 枚
${SGIS_ICONS.sparkle}
社区勋章
Steam 社区授予的成就
${communityBadges.length} 枚
${SGIS_ICONS.chevronRight}
${showComm.map(b => _renderUserBadgeRow(b, ctx)).join('')}
`; } const ACHIEVEMENT_SVG_ICONS = { collector: ``, kingCollector: ``, clock: ``, hourglass: ``, perfection: ``, dice: ``, sunrise: ``, moon: ``, diamond: ``, }; const USER_ACHIEVEMENTS = [ { id: 'collector_50', icon: ACHIEVEMENT_SVG_ICONS.collector, name: '初级收藏家', desc: '拥有 50 款游戏', threshold: 50, metric: 'gameCount' }, { id: 'collector_100', icon: ACHIEVEMENT_SVG_ICONS.collector, name: '中级收藏家', desc: '拥有 100 款游戏', threshold: 100, metric: 'gameCount' }, { id: 'collector_500', icon: ACHIEVEMENT_SVG_ICONS.collector, name: '高级收藏家', desc: '拥有 500 款游戏', threshold: 500, metric: 'gameCount' }, { id: 'collector_1000', icon: ACHIEVEMENT_SVG_ICONS.kingCollector, name: '游戏大王', desc: '拥有 1000 款游戏', threshold: 1000, metric: 'gameCount' }, { id: 'playtime_1k', icon: ACHIEVEMENT_SVG_ICONS.clock, name: '入门玩家', desc: '总游戏时长达到 1000 小时', threshold: 1000, metric: 'totalHours' }, { id: 'playtime_5k', icon: ACHIEVEMENT_SVG_ICONS.hourglass, name: '资深玩家', desc: '总游戏时长达到 5000 小时', threshold: 5000, metric: 'totalHours' }, { id: 'playtime_10k', icon: ACHIEVEMENT_SVG_ICONS.hourglass, name: '硬核玩家', desc: '总游戏时长达到 10000 小时', threshold: 10000, metric: 'totalHours' }, { id: 'completionist', icon: ACHIEVEMENT_SVG_ICONS.perfection, name: '完美主义者', desc: '有 10 款游戏达成 100% 成就', threshold: 10, metric: 'perfectGames' }, { id: 'diverse_10', icon: ACHIEVEMENT_SVG_ICONS.dice, name: '涉猎广泛', desc: '游玩 10 种不同类型的游戏', threshold: 10, metric: 'genres' }, { id: 'early_bird', icon: ACHIEVEMENT_SVG_ICONS.sunrise, name: '早鸟玩家', desc: '在游戏发行 7 天内入库 5 款游戏', threshold: 5, metric: 'earlyAccess' }, { id: 'night_owl', icon: ACHIEVEMENT_SVG_ICONS.moon, name: '夜猫子', desc: '总游戏时长超过 5000 小时且拥有 200+ 游戏', threshold: 1, metric: 'nightOwl' }, { id: 'patron', icon: ACHIEVEMENT_SVG_ICONS.diamond, name: 'Steam 老用户', desc: 'Steam 账号超过 10 年', threshold: 1, metric: 'veteran' }, ]; function computeUserAchievements() { const allGames = getStatFilteredGames(); const gameCount = allGames.length; const totalPlaytimeMin = allGames.reduce((s, g) => s + (g.playtime || 0), 0); const totalHours = Math.floor(totalPlaytimeMin / 60); const perfectGames = allGames.filter(g => g.playtime && g.playtime > 3600).length; const genres = 0; const earlyAccess = allGames.filter(g => { if (!g.acquiredTime || !g.releaseDate) return false; const diff = g.acquiredTime - g.releaseDate; return diff >= 0 && diff <= 7 * 86400000; }).length; const nightOwl = (totalHours > 5000 && gameCount > 200) ? 1 : 0; const veteran = 0; const metrics = { gameCount, totalHours, perfectGames, genres, earlyAccess, nightOwl, veteran }; return USER_ACHIEVEMENTS.map(ach => { const current = metrics[ach.metric] || 0; const unlocked = current >= ach.threshold; const progress = Math.min(100, (current / ach.threshold) * 100); return { ...ach, current, unlocked, progress }; }); } function renderSocial() { _paintTab = 'social'; if (SGIS.friendsList) { renderSocialContent(); return; } if (SGIS.friendsListLoading) return; const steamId = getActiveSteamId(); if (!steamId) { setBody(`
${SGIS_ICONS.social}
无法获取好友列表
请先配置 SteamID 或登录 Steam 商店
`, 'social'); return; } SGIS.friendsListLoading = true; renderLoading('正在获取好友列表…'); fetchFriendsList(steamId).then(result => { SGIS.friendsList = result; SGIS.friendsListLoading = false; SGIS.friendsListError = result.error || null; renderSocialContent(); }).catch(e => { SGIS.friendsListLoading = false; SGIS.friendsListError = e.message || '获取好友列表失败'; renderSocialContent(); }); } const KPI_GRADIENTS = { blue: 'linear-gradient(135deg, #3b82f6, #06b6d4)', cyan: 'linear-gradient(135deg, #06b6d4, #22d3ee)', purple: 'linear-gradient(135deg, #8b5cf6, #a78bfa)', amber: 'linear-gradient(135deg, #f59e0b, #fbbf24)', rose: 'linear-gradient(135deg, #f43f5e, #fb7185)', green: 'linear-gradient(135deg, #10b981, #34d399)', }; const renderKpi = (icon, label, val, sub, grad, color) => kpiCards( [{ icon, label, value: val, sub, grad, color }], { tone: 'sgis' }); function _prepareSocialData() { const data = SGIS.friendsList || { friends: [], total: 0 }; const friends = data.friends || []; const totalCount = friends.length; const ingameFriends = friends.filter(f => f.gameextrainfo || f.personastate === 6); const onlineFriends = friends.filter(f => f.personastate > 0 && !f.gameextrainfo); const vacBanned = friends.filter(f => f.vac_banned); const newFriends = friends.filter(f => f.friend_days != null && f.friend_days < 30); const knownLevels = friends.filter(f => f.level != null); const maxLevel = knownLevels.length > 0 ? Math.max(...knownLevels.map(f => f.level)) : null; const filter = SGIS.friendsFilter || 'all'; const sort = SGIS.friendsSort || 'status'; const search = SGIS.friendsSearch || ''; return { data, friends, totalCount, ingameFriends, onlineFriends, vacBanned, newFriends, knownLevels, maxLevel, filter, sort, search, }; } function _renderSocialKPI(d) { return `
${renderKpi(SGIS_ICONS.social, '好友总数', d.totalCount, `在线 ${d.onlineFriends.length + d.ingameFriends.length}`, KPI_GRADIENTS.blue, 'blue')} ${renderKpi(SGIS_ICONS.sparkle, '游戏中', d.ingameFriends.length, '正在玩游戏', KPI_GRADIENTS.cyan, 'cyan')} ${renderKpi(SGIS_ICONS.check, '在线', d.onlineFriends.length, '未在游戏中', KPI_GRADIENTS.green, 'green')} ${renderKpi(SGIS_ICONS.shield, 'VAC 封禁', d.vacBanned.length, d.vacBanned.length > 0 ? `最近 ${d.vacBanned[0].vac_days_since_last_ban}天` : '安全', d.vacBanned.length > 0 ? KPI_GRADIENTS.rose : KPI_GRADIENTS.green, d.vacBanned.length > 0 ? 'rose' : 'green')} ${renderKpi(SGIS_ICONS.clock, '新好友(30天)', d.newFriends.length, '最近添加', KPI_GRADIENTS.amber, 'amber')} ${renderKpi(SGIS_ICONS.trophy, '最高等级', d.maxLevel != null ? 'Lv.' + d.maxLevel : '—', d.knownLevels.length > 0 ? `${knownFriends(d.friends)} 人已加载` : '点击下方加载', KPI_GRADIENTS.purple, 'purple')}
`; } function _renderSocialToolbar(d) { const filterBtns = [ { id: 'all', label: '全部', count: d.totalCount }, { id: 'ingame', label: '游戏中', count: d.ingameFriends.length }, { id: 'online', label: '在线', count: d.onlineFriends.length }, { id: 'vac', label: 'VAC', count: d.vacBanned.length }, { id: 'new', label: '新好友', count: d.newFriends.length }, ]; const sortOptions = [ { id: 'status', label: '按状态' }, { id: 'days', label: '按好友天数' }, { id: 'level', label: '按等级' }, { id: 'name', label: '按昵称' }, ]; return `
${filterBtns.map(f => ``).join('')}
`; } function _filterSortFriends(d) { let filtered = [...d.friends]; if (d.filter === 'ingame') filtered = filtered.filter(f => f.gameextrainfo || f.personastate === 6); else if (d.filter === 'online') filtered = filtered.filter(f => f.personastate > 0 && !f.gameextrainfo); else if (d.filter === 'offline') filtered = filtered.filter(f => f.personastate === 0); else if (d.filter === 'vac') filtered = filtered.filter(f => f.vac_banned); else if (d.filter === 'new') filtered = filtered.filter(f => f.friend_days != null && f.friend_days < 30); if (d.search) { const q = d.search.toLowerCase(); filtered = filtered.filter(f => (f.personaname || '').toLowerCase().includes(q) || String(f.steamid).includes(q) ); } if (d.sort === 'days') filtered.sort((a, b) => (b.friend_days || 0) - (a.friend_days || 0)); else if (d.sort === 'level') filtered.sort((a, b) => (b.level || 0) - (a.level || 0)); else if (d.sort === 'name') filtered.sort((a, b) => (a.personaname || '').localeCompare(b.personaname || '')); else { const rank = f => f.gameextrainfo ? 0 : (f.personastate > 0 ? 1 : 2); filtered.sort((a, b) => rank(a) - rank(b)); } return filtered; } function _renderSocialList(d, filtered) { if (d.sort === 'status' && d.filter === 'all') { const groups = [ { id: 'ingame', label: '游戏中', icon: SGIS_ICONS.sparkle, friends: filtered.filter(f => f.gameextrainfo || f.personastate === 6) }, { id: 'online', label: '在线', icon: SGIS_ICONS.check, friends: filtered.filter(f => f.personastate > 0 && !f.gameextrainfo) }, { id: 'offline', label: '离线', icon: SGIS_ICONS.clock, friends: filtered.filter(f => f.personastate === 0) }, ]; return groups.map(g => g.friends.length > 0 ? `
${g.icon}${g.label}${g.friends.length}
${g.friends.slice(0, 50).map(renderFriendCard).join('')} ${g.friends.length > 50 ? `
还有 ${g.friends.length - 50} 位好友未显示, 请使用筛选或搜索查看
` : ''}
` : '').join(''); } else { let html = filtered.slice(0, 100).map(renderFriendCard).join(''); if (filtered.length > 100) { html += `
显示前 100 位, 共 ${filtered.length} 位匹配好友
`; } return html; } } function _renderSocialHeaderActions(d) { const unknownLevelCount = d.friends.filter(f => f.level == null).length; const knownLevelCount = d.friends.length - unknownLevelCount; const loadLevelsBtn = ``; const banSyncBtn = ``; return `
${SGIS_ICONS.social} 好友概览
${banSyncBtn} ${loadLevelsBtn}
`; } function _renderSocialErrorState() { return `
${SGIS_ICONS.social}
获取好友列表失败
${SGIS.friendsListError}
`; } function renderSocialContent() { if (SGIS.friendsListError && (!SGIS.friendsList || !SGIS.friendsList.friends || SGIS.friendsList.friends.length === 0)) { setBody(_renderSocialErrorState(), 'social'); const retry = (_tabPanes.get('social') || document).querySelector('#sgis-social-retry'); if (retry) retry.addEventListener('click', () => { SGIS.friendsList = null; SGIS.friendsListError = null; renderSocial(); }); return; } const d = _prepareSocialData(); const filtered = _filterSortFriends(d); setBody(`
${_renderSocialHeaderActions(d)} ${_renderSocialKPI(d)}
${SGIS_ICONS.users} 好友列表 (${filtered.length}/${d.totalCount})
${_renderSocialToolbar(d)}
${_renderSocialList(d, filtered) || '
无匹配好友
'}
好友数据缓存 6h · VAC 状态缓存 24h · 等级缓存 7天 · 数据源 Steam Web API
`, 'social'); _bindSocialEvents(getActiveSteamId()); } function _paintSocialList() { const list = document.getElementById('sgis-social-list'); if (!list) { renderSocialContent(); return; } const d = _prepareSocialData(); const filtered = _filterSortFriends(d); const count = document.getElementById('sgis-social-list-count'); if (count) count.innerHTML = `${SGIS_ICONS.users} 好友列表 (${filtered.length}/${d.totalCount})`; list.innerHTML = _renderSocialList(d, filtered) || '
无匹配好友
'; document.querySelectorAll('#sgis-body .sgis-social-filter').forEach(btn => { btn.classList.toggle('active', btn.dataset.filter === SGIS.friendsFilter); }); } function knownFriends(friends) { return friends.filter(f => f.level != null).length; } function renderFriendCard(f) { const hasGame = !!f.gameextrainfo; const isIngame = hasGame || f.personastate === 6; const isOnline = f.personastate > 0 && !hasGame; const stateCls = isIngame ? 'ingame' : isOnline ? 'online' : 'offline'; const statusText = hasGame ? `🎮 ${f.gameextrainfo}` : getPersonaStateText(f.personastate); const statusCls = isIngame ? 'ingame' : isOnline ? 'online' : 'offline'; const avatarUrl = f.avatarmedium || f.avatar || ''; const avatarFallback = `data:image/svg+xml;utf8,${(f.personaname || '?').slice(0, 1).toUpperCase()}`; const levelBadge = f.level != null ? `Lv.${f.level}` : ''; const vacShield = f.vac_banned ? `${SGIS_ICONS.shield}VAC` : ''; const countryBadge = f.country_flag ? `${f.country_flag}${f.country_name || f.loccountrycode}` : ''; return `
${f.personaname} ${levelBadge} ${vacShield}
${statusText} ${f.friend_days_text ? `🤝 ${f.friend_days_text}` : ''} ${countryBadge}
`; } function _bindSocialEvents(steamId) { const root = _tabPanes.get('social') || document; const searchInput = root.querySelector('#sgis-social-search'); if (searchInput) { let timer; searchInput.addEventListener('input', e => { clearTimeout(timer); timer = setTimeout(() => { SGIS.friendsSearch = e.target.value; _paintSocialList(); }, 250); }); } root.querySelectorAll('.sgis-social-filter').forEach(btn => { btn.addEventListener('click', () => { SGIS.friendsFilter = btn.dataset.filter; _paintSocialList(); }); }); const sortSelect = root.querySelector('#sgis-social-sort'); if (sortSelect) { sortSelect.addEventListener('change', e => { SGIS.friendsSort = e.target.value; _paintSocialList(); }); } const loadLevelsBtn = root.querySelector('#sgis-social-load-levels'); if (loadLevelsBtn) { loadLevelsBtn.addEventListener('click', async () => { if (SGIS.friendsLevelsLoading) return; const friends = (SGIS.friendsList && SGIS.friendsList.friends) || []; const unknown = friends.filter(f => f.level == null).length; if (unknown === 0) { showToast(isZh ? '所有好友等级已加载' : 'All friend levels already loaded'); return; } SGIS.friendsLevelsLoading = true; SGIS.friendsLevelsProgress = 0; SGIS.friendsLevelsTotal = unknown; renderSocialContent(); try { const totalUnknown = unknown; await fetchFriendsLevels(steamId, { maxCount: Infinity }); const remaining = (SGIS.friendsList.friends || []).filter(f => f.level == null).length; if (remaining > 0) { showToast(isZh ? `已同步 ${totalUnknown - remaining}/${totalUnknown} 个等级,${remaining} 位获取失败` : `Synced ${totalUnknown - remaining}/${totalUnknown}, ${remaining} failed`); } else { showToast(isZh ? '所有好友等级同步完成' : 'All friend levels synced'); } } catch (e) { console.warn('[SGIS] 加载好友等级失败:', e); showToast(isZh ? `同步失败: ${e.message || '网络错误'}` : `Sync failed: ${e.message || 'network error'}`); } finally { SGIS.friendsLevelsLoading = false; renderSocialContent(); } }); } const banSyncBtn = root.querySelector('#sgis-social-ban-sync'); if (banSyncBtn) { banSyncBtn.addEventListener('click', async () => { if (SGIS.friendsBansLoading) return; const friends = (SGIS.friendsList && SGIS.friendsList.friends) || []; if (friends.length === 0) { showToast(isZh ? '暂无好友数据' : 'No friend data'); return; } SGIS.friendsBansLoading = true; SGIS.friendsBansProgress = 0; SGIS.friendsBansTotal = friends.length; renderSocialContent(); try { await fetchFriendsBans(steamId, { force: true }); const vacCount = (SGIS.friendsList.friends || []).filter(f => f.vac_banned).length; showToast(isZh ? `封禁状态同步完成,发现 ${vacCount} 位封禁好友` : `Ban sync complete, ${vacCount} banned friends found`); } catch (e) { console.warn('[SGIS] 同步封禁状态失败:', e); showToast(isZh ? `同步失败: ${e.message || '网络错误'}` : `Sync failed: ${e.message || 'network error'}`); } finally { SGIS.friendsBansLoading = false; renderSocialContent(); } }); } } function renderUserAchievements() { if (SGIS.userAchievements && SGIS.insightData) { renderUserAchievementsContent(); return; } if (SGIS.userAchievementsLoading) return; SGIS.userAchievementsLoading = true; renderLoading('正在分析游戏数据…'); setTimeout(() => { SGIS.userAchievements = computeUserAchievements(); SGIS.insightData = computeInsightData(); SGIS.userAchievementsLoading = false; renderUserAchievementsContent(); }, 200); } function computeInsightData() { if (typeof SGLV_API.computeInsightDataCachedSgis === 'function') { return SGLV_API.computeInsightDataCachedSgis(); } console.warn('[SGIS] computeInsightData: SGLV_API桥接不可用,返回 null'); return null; } function _renderInsightEmpty() { return `
${SGIS_ICONS.insight}
暂无洞察数据
请先获取游戏库数据
`; } function _renderInsightKpi(k) { return `
${renderKpi(SGIS_ICONS.barChart, '游戏库', k.gameCount, `${k.over100hCount} 款超 100h`, KPI_GRADIENTS.blue, 'blue')} ${renderKpi(SGIS_ICONS.clock, '总时长', k.totalHours + ' h', `平均 ${k.avgHours}h/款`, KPI_GRADIENTS.cyan, 'cyan')} ${renderKpi(SGIS_ICONS.check, '已启动', k.playedCount, `占比 ${k.gameCount > 0 ? Math.round(k.playedCount / k.gameCount * 100) : 0}%`, KPI_GRADIENTS.purple, 'purple')} ${renderKpi(SGIS_ICONS.sparkle, '未启动', k.unplayedCount, `吃灰率 ${(k.dustRate * 100).toFixed(1)}%`, KPI_GRADIENTS.amber, 'amber')} ${renderKpi(SGIS_ICONS.trophy, '深度游玩', k.longGamesCount, '≥10h 的游戏数', KPI_GRADIENTS.rose, 'rose')} ${renderKpi(SGIS_ICONS.target, '完成度', k.completionRate + '%', '深度游玩/已启动', KPI_GRADIENTS.purple, 'purple')}
`; } function _renderInsightPersona(k, p) { return `
${SGIS_ICONS.insight}
${p.type}${p.rarity}
${p.tagline}
${p.traits.map(t => `${t}`).join('')}
${SGIS_ICONS.barChart}
总游戏
${k.gameCount}
${SGIS_ICONS.clock}
总时长
${k.totalHours}h
${SGIS_ICONS.trend}
超100h
${k.over100hCount}
${SGIS_ICONS.sparkle}
吃灰率
${(k.dustRate * 100).toFixed(1)}%
${SGIS_ICONS.target}
主导维度
${p.dominantDim}
`; } function _renderInsightDimensions(data) { const getDimTagClass = (s) => s >= 80 ? 't-high' : s >= 60 ? 't-mid' : s >= 40 ? 't-low' : 't-bad'; const getDimProgressColor = (s) => s >= 80 ? '#10b981' : s >= 60 ? '#3b82f6' : s >= 40 ? '#f59e0b' : '#f43f5e'; return `
${data.dimensions.map(d => `
${d.label} ${d.tag}
${d.score}
${d.desc}
`).join('')}
`; } function _renderInsightAi() { const aiConfigured = !!storage.getAiApiKey(); const aiSectionHtml = SGIS.aiInsight ? ` ${SGIS.aiInsight.oneLiner ? `
${SGIS_ICONS.target}
${SGIS.aiInsight.oneLiner}
` : ''} ${SGIS.aiInsight.sections.map((s, i) => { const grad = [KPI_GRADIENTS.blue, KPI_GRADIENTS.cyan, KPI_GRADIENTS.purple, KPI_GRADIENTS.rose, KPI_GRADIENTS.amber, KPI_GRADIENTS.green][i % 6]; return `
${SGIS_ICONS.sparkle}${s.title}
${s.content}
`; }).join('')} ` : SGIS.aiInsightLoading ? `
${SGIS_ICONS.refresh}
AI 正在分析你的游戏库…
六维度犀利点评生成中, 预计 15-30 秒
` : SGIS.aiInsightError ? `
⚠️
分析失败: ${SGIS.aiInsightError}
` : `
${SGIS_ICONS.brain}
点击「开始深度分析」
AI 将从库存概况、游玩习惯、偏好画像、亮点槽点、购买建议、犀利毒舌六个维度犀利点评
${!aiConfigured ? `
⚠️ 未配置 AI API Key, 请先在设置中配置
` : ''}
`; return `
${SGIS_ICONS.brain}
AI 深度分析
六维度犀利点评你的 Steam 库存
${aiSectionHtml}
`; } function _renderInsightAchEntry() { const achievements = SGIS.userAchievements || []; const unlocked = achievements.filter(a => a.unlocked); return `
${SGIS_ICONS.trophy}
`; } function _renderInsightGameTaste(data, k, p) { const tagFreq = {}; if (Array.isArray(state.wishlistGames)) { for (const g of state.wishlistGames) { if (g && Array.isArray(g.tags)) { for (const t of g.tags) { const tag = String(t).trim(); if (tag) tagFreq[tag] = (tagFreq[tag] || 0) + 1; } } } } const sortedTags = Object.entries(tagFreq) .filter(([, c]) => c >= 2) .sort((a, b) => b[1] - a[1]) .slice(0, 20); const tasteTags = []; if (k.over100hCount >= 5) tasteTags.push({ label: '长篇沉浸', cat: 'style' }); if (k.gameCount > 0 && k.playedCount / k.gameCount < 0.5) tasteTags.push({ label: '收藏型', cat: 'style' }); if (k.avgHours >= 50) tasteTags.push({ label: '硬核深度', cat: 'style' }); if (k.dustRate > 0.5) tasteTags.push({ label: '吃灰大户', cat: 'style' }); if (k.completionRate >= 60) tasteTags.push({ label: '认真通关', cat: 'feature' }); if (k.gameCount >= 200) tasteTags.push({ label: '量大管饱', cat: 'feature' }); if (k.over500hCount >= 1) tasteTags.push({ label: '极致专注', cat: 'feature' }); if (p.traits && p.traits.length) { p.traits.slice(0, 3).forEach(t => tasteTags.push({ label: t, cat: 'theme' })); } const genreKeywords = { '动作': 'genre', '冒险': 'genre', '策略': 'genre', 'RPG': 'genre', '独立': 'genre', '模拟': 'genre', '休闲': 'genre', '竞速': 'genre', '体育': 'genre', '恐怖': 'genre', '射击': 'genre', '解谜': 'genre', '平台': 'genre', '开放世界': 'genre', '生存': 'genre', '多人': 'feature', '合作': 'feature', '单机': 'feature', 'PvP': 'feature', '沙盒': 'style', 'Roguelike': 'style', '像素': 'style', '剧情': 'theme', '科幻': 'theme', '奇幻': 'theme', '二次元': 'theme' }; const wlTasteTags = sortedTags.slice(0, 12).map(([tag, count]) => { let cat = 'theme'; for (const [kw, c] of Object.entries(genreKeywords)) { if (tag.includes(kw) || kw.includes(tag)) { cat = c; break; } } return { label: tag, cat, count }; }); const allTags = [...tasteTags, ...wlTasteTags]; const seen = new Set(); const dedupedTags = allTags.filter(t => { if (seen.has(t.label)) return false; seen.add(t.label); return true; }).slice(0, 18); const maxCount = Math.max(...sortedTags.map(([, c]) => c), 1); const tagCloudHtml = dedupedTags.map(t => { const weight = t.count ? t.count / maxCount : 0.5; const sizeCls = weight > 0.7 ? 't-xl' : weight > 0.5 ? 't-lg' : weight > 0.3 ? 't-md' : 't-sm'; return `${escHtml(t.label)}`; }).join(''); const bars = data.dimensions.slice(0, 5).map(d => { const color = d.score >= 80 ? '#10b981' : d.score >= 60 ? '#3b82f6' : d.score >= 40 ? '#f59e0b' : '#f43f5e'; return hbarRow({ cls: 'taste', name: escHtml(d.label), nameTag: 'div', pct: d.score, color, val: `${d.score} · ${escHtml(d.tag)}`, valTag: 'div', }); }).join(''); return `
${SGIS_ICONS.tag || '🏷️'} ${isZh ? '游戏口味' : 'Game Taste'} ${isZh ? '标签画像' : 'Profile'}
${isZh ? '基于愿望单标签与游玩习惯推断' : 'Inferred from wishlist tags & play habits'}
${tagCloudHtml}
${bars}
`; } function _bindInsightEvents() { const triggerBtn = document.getElementById('sgis-insight-trigger'); if (triggerBtn) triggerBtn.addEventListener('click', triggerAiInsight); const retryBtn = document.getElementById('sgis-insight-retry'); if (retryBtn) retryBtn.addEventListener('click', () => { SGIS.aiInsightError = null; triggerAiInsight(); }); const marketBtn = document.getElementById('sgis-market-trigger'); if (marketBtn) marketBtn.addEventListener('click', triggerAiMarketInsight); const marketRetry = document.getElementById('sgis-market-retry'); if (marketRetry) marketRetry.addEventListener('click', () => { SGIS.aiMarketInsightError = null; triggerAiMarketInsight(); }); const achOpenBtn = document.getElementById('sgis-insight-ach-open'); if (achOpenBtn) achOpenBtn.addEventListener('click', () => { try { if (typeof closePanel === 'function') closePanel(); document.dispatchEvent(new CustomEvent('sglv:open-modal', { detail: { tab: 'achievements' } })); } catch (e) { } }); } function renderUserAchievementsContent() { _paintTab = 'userAchievements'; const data = SGIS.insightData; if (!data || !data.kpi) { setBody(_renderInsightEmpty()); return; } const k = data.kpi; const p = data.persona; const kpiHtml = _renderInsightKpi(k); const personaHtml = _renderInsightPersona(k, p); const dimensionsHtml = _renderInsightDimensions(data); const aiHtml = _renderInsightAi(); const marketHtml = renderMarketInsightSection(); const achievementsHtml = _renderInsightAchEntry(); const gameTasteHtml = _renderInsightGameTaste(data, k, p); setBody(`
${SGIS_ICONS.barChart} KPI 概览
${kpiHtml}
${personaHtml} ${gameTasteHtml}
${SGIS_ICONS.target} 五维度评分
${dimensionsHtml}
${aiHtml} ${marketHtml}
${SGIS_ICONS.trophy} 成就系统
${achievementsHtml}
洞察数据基于本地游戏库本地计算 · AI 分析需配置 AI API Key · 参考 steam-game-hub-2.0 AIPage 设计
`); applyGameAliases(document, { scope: '#sgis-body' }); _bindInsightEvents(); } function renderMarketInsightSection() { const markets = SGIS.userBadgeMarkets || {}; const aiConfigured = !!storage.getAiApiKey(); const gameMarkets = Object.entries(markets) .filter(([appId, m]) => m && m.cards && m.cards.length > 0) .map(([appId, m]) => { const totalValue = (m.cards || []).reduce((s, c) => s + (c.lowestPrice || 0), 0); const avgValue = totalValue / (m.cards || []).length; const gameName = (m.gameName || state.ownedGames?.find(g => String(g.appid) === String(appId))?.name || `App ${appId}`); return { appId, gameName, cardCount: (m.cards || []).length, totalValue, avgValue }; }) .sort((a, b) => b.totalValue - a.totalValue); const totalCardValue = gameMarkets.reduce((s, g) => s + g.totalValue, 0); const totalCards = gameMarkets.reduce((s, g) => s + g.cardCount, 0); const top5 = gameMarkets.slice(0, 5); const aiMarketHtml = SGIS.aiMarketInsight ? ` ${SGIS.aiMarketInsight.summary ? `
${SGIS.aiMarketInsight.summary}
` : ''} ${SGIS.aiMarketInsight.recommendations && SGIS.aiMarketInsight.recommendations.length > 0 ? SGIS.aiMarketInsight.recommendations.map(r => `
${r.name} ${r.action}
${r.reason}
`).join('') : ''} ` : SGIS.aiMarketInsightLoading ? `
${SGIS_ICONS.refresh}
AI 正在分析市场数据…
生成投资建议中
` : SGIS.aiMarketInsightError ? `
⚠️
分析失败: ${SGIS.aiMarketInsightError}
` : `
${SGIS_ICONS.market}
点击「生成投资建议」
AI 将基于你的卡牌库分析哪些游戏卡牌值得合成/出售
${!aiConfigured ? `
⚠️ 未配置 AI API Key
` : ''} ${top5.length === 0 ? `
📡 暂无卡牌市场数据, 请先访问「勋章」标签页加载
` : ''}
`; return `
${SGIS_ICONS.market}
游戏市场洞察
基于你的卡牌库分析市场价值与投资机会
${top5.length > 0 ? `
${gameMarkets.length}
有卡牌游戏
${totalCards}
卡牌总数
¥${totalCardValue.toFixed(0)}
总价值
价值 Top 5
${top5.map((g, i) => `
${i + 1}
${g.gameName}
¥${g.totalValue.toFixed(2)} · ${g.cardCount}卡
`).join('')} ` : `
暂无卡牌市场数据
请先访问「勋章」标签页加载卡牌数据
`}
${aiMarketHtml}
`; } async function triggerAiInsight() { if (SGIS.aiInsightLoading) return; const apiKey = storage.getAiApiKey(); if (!apiKey) { showToast('未配置 AI API Key,请在设置中配置'); return; } SGIS.aiInsightLoading = true; SGIS.aiInsightError = null; SGIS.aiInsight = null; renderUserAchievementsContent(); try { const data = SGIS.insightData || computeInsightData(); const k = data.kpi; const p = data.persona; const profile = SGIS.profile?.summary; const personaName = profile?.personaname || '未知'; const level = SGIS.profile?.level || SGIS.userBadges?.playerLevel || '?'; const topGamesStr = data.topGames.map(g => `${g.name}(${g.hours}h)`).join(', '); const recentStr = data.recentGames.map(g => `${g.name}(${g.hours}h)`).join(', '); const dustStr = data.dustCollectors.join(', '); const dimsStr = data.dimensions.map(d => `${d.label}=${d.score}分(${d.tag})`).join(', '); const traitsStr = p.traits.join('、'); const tasteTags = []; if (k.over100hCount >= 5) tasteTags.push('长篇沉浸'); if (k.gameCount > 0 && k.playedCount / k.gameCount < 0.5) tasteTags.push('收藏型'); if (k.avgHours >= 50) tasteTags.push('硬核深度'); if (k.dustRate > 0.5) tasteTags.push('吃灰大户'); if (k.completionRate >= 60) tasteTags.push('认真通关'); if (k.gameCount >= 200) tasteTags.push('量大管饱'); if (k.over500hCount >= 1) tasteTags.push('极致专注'); const wlTagFreq = {}; if (Array.isArray(state.wishlistGames)) { for (const g of state.wishlistGames) { if (g && Array.isArray(g.tags)) { for (const t of g.tags) { const tag = String(t).trim(); if (tag) wlTagFreq[tag] = (wlTagFreq[tag] || 0) + 1; } } } } const topWlTags = Object.entries(wlTagFreq) .filter(([, c]) => c >= 2) .sort((a, b) => b[1] - a[1]) .slice(0, 10) .map(([t]) => t); const tasteTagsStr = [...tasteTags, ...p.traits].join('、'); const wlTagsStr = topWlTags.join('、'); const dimsDetailStr = data.dimensions.map(d => `${d.label}=${d.score}分(${d.tag}) - ${d.desc}`).join('\n'); let prompt = await getInsightPromptTemplate(); prompt = prompt.replace(/\{PERSONA_NAME\}/g, personaName) .replace(/\{STEAM_LEVEL\}/g, String(level)) .replace(/\{GAME_COUNT\}/g, String(k.gameCount)) .replace(/\{TOTAL_HOURS\}/g, String(k.totalHours)) .replace(/\{PLAYED_COUNT\}/g, String(k.playedCount)) .replace(/\{PLAYED_PERCENT\}/g, String(k.gameCount > 0 ? Math.round(k.playedCount / k.gameCount * 100) : 0)) .replace(/\{UNPLAYED_COUNT\}/g, String(k.unplayedCount)) .replace(/\{DUST_RATE\}/g, (k.dustRate * 100).toFixed(1)) .replace(/\{OVER_100H_COUNT\}/g, String(k.over100hCount)) .replace(/\{OVER_500H_COUNT\}/g, String(k.over500hCount)) .replace(/\{LONG_GAMES_COUNT\}/g, String(k.longGamesCount)) .replace(/\{AVG_HOURS\}/g, String(k.avgHours)) .replace(/\{PERSONA_TYPE\}/g, p.type) .replace(/\{PERSONA_RARITY\}/g, p.rarity) .replace(/\{TRAITS\}/g, traitsStr || '无') .replace(/\{TASTE_TAGS\}/g, tasteTagsStr || '无') .replace(/\{WISHLIST_TAGS\}/g, wlTagsStr || '无') .replace(/\{DIM_SCORES\}/g, dimsStr) .replace(/\{DIM_DETAILS\}/g, dimsDetailStr) .replace(/\{TOP_GAMES\}/g, topGamesStr || '无数据') .replace(/\{RECENT_GAMES\}/g, recentStr || '无数据') .replace(/\{DUST_EXAMPLES\}/g, dustStr || '无'); const content = await callAiApi(prompt, { temperature: 0.6, timeout: 90000, maxTokens: 6144 }); const result = safeParseAiJson(content, '{'); if (!result.oneLiner || !Array.isArray(result.sections)) { throw new Error('AI 返回结构不完整'); } SGIS.aiInsight = result; } catch (e) { SGIS.aiInsightError = e.message || 'AI 分析失败'; } finally { SGIS.aiInsightLoading = false; renderUserAchievementsContent(); } } async function triggerAiMarketInsight() { if (SGIS.aiMarketInsightLoading) return; const apiKey = storage.getAiApiKey(); if (!apiKey) { showToast('未配置 AI API Key,请在设置中配置'); return; } const markets = SGIS.userBadgeMarkets || {}; const gameMarkets = Object.entries(markets) .filter(([appId, m]) => m && m.cards && m.cards.length > 0) .map(([appId, m]) => { const totalValue = (m.cards || []).reduce((s, c) => s + (c.lowestPrice || 0), 0); const gameName = m.gameName || state.ownedGames?.find(g => String(g.appid) === String(appId))?.name || `App ${appId}`; return { appId, gameName, cardCount: (m.cards || []).length, totalValue, avgValue: totalValue / (m.cards || []).length, cards: m.cards }; }) .sort((a, b) => b.totalValue - a.totalValue) .slice(0, 10); if (gameMarkets.length === 0) { showToast('暂无卡牌市场数据, 请先访问「勋章」标签页加载'); return; } SGIS.aiMarketInsightLoading = true; SGIS.aiMarketInsightError = null; SGIS.aiMarketInsight = null; renderUserAchievementsContent(); try { const totalValue = gameMarkets.reduce((s, g) => s + g.totalValue, 0); const totalCards = gameMarkets.reduce((s, g) => s + g.cardCount, 0); const gamesDataStr = gameMarkets.map(g => { const cardDetails = g.cards.slice(0, 5).map(c => `${c.name || '卡'}(¥${(c.lowestPrice || 0).toFixed(2)})`).join(', '); return `- ${g.gameName} (AppID:${g.appId}): ${g.cardCount}张卡牌, 总价值¥${g.totalValue.toFixed(2)}, 均价¥${g.avgValue.toFixed(2)} | 卡牌示例: ${cardDetails}`; }).join('\n'); const prompt = `# 角色\n你是一位 Steam 卡牌市场投资顾问, 精通卡牌合成、徽章升级、市场套利策略。\n\n# 任务\n基于玩家的 Steam 卡牌库数据, 生成市场洞察报告和投资建议。\n\n# 输入数据\n- 有卡牌游戏数: ${gameMarkets.length}\n- 卡牌总数: ${totalCards}\n- 卡牌总价值: ¥${totalValue.toFixed(2)}\n\n## 游戏卡牌详情 (Top ${gameMarkets.length})\n${gamesDataStr}\n\n# 输出格式\n严格按以下 JSON 格式输出, 不要输出任何其他文字。\n{\n "summary": "2-3句话市场总览, 评价卡牌库整体价值、合成潜力、套利空间",\n "recommendations": [\n {"name": "游戏名称", "action": "买入/卖出/持有/合成", "reason": "1-2句话具体建议理由, 包含数据"}\n ]\n}\n\n# 要求\n- recommendations 数组包含 3-5 条建议, 优先选择价值最高或最有套利空间的游戏\n- action 只能是: 买入(补全卡牌合成徽章)、卖出(出售多余卡牌获利)、持有(暂不操作)、合成(立即合成徽章升级)\n- reason 必须包含具体数据支撑\n- 语言简洁有力, 避免空话`; const content = await callAiApi(prompt, { temperature: 0.4, timeout: 90000 }); const result = safeParseAiJson(content, '{'); if (!result.summary || !Array.isArray(result.recommendations)) { throw new Error('AI 返回结构不完整'); } SGIS.aiMarketInsight = result; } catch (e) { SGIS.aiMarketInsightError = e.message || 'AI 市场分析失败'; } finally { SGIS.aiMarketInsightLoading = false; renderUserAchievementsContent(); } } const SGIS_TAB_RENDERERS = { overview: { render: () => renderOverview(), prepare: () => { if (!SGIS.familyShareSupported) { fetchFamilyShareSupport().then(r => { SGIS.familyShareSupported = r; if (SGIS.tab === 'overview') renderOverview(); }).catch(() => {}); } if (!SGIS.appDetailsExtra && !SGIS.appDetailsExtraLoading) { SGIS.appDetailsExtraLoading = true; fetchAppDetailsExtra().then(extra => { extra = mergeDlcFromDom(extra); SGIS.appDetailsExtra = extra; SGIS.appDetailsExtraLoading = false; if (SGIS.tab === 'overview') renderOverview(); if (extra && extra.dlc && extra.dlc.length && !SGIS.dlcNames && !SGIS.dlcNamesLoading) { SGIS.dlcNamesLoading = true; fetchDlcNames(extra.dlc).then(names => { SGIS.dlcNames = names; SGIS.dlcNamesLoading = false; if (SGIS.tab === 'overview') renderOverview(); }).catch(() => { SGIS.dlcNamesLoading = false; }); } }).catch(() => { SGIS.appDetailsExtraLoading = false; }); } else if (SGIS.appDetailsExtra && SGIS.appDetailsExtra.dlc && SGIS.appDetailsExtra.dlc.length && !SGIS.dlcNames && !SGIS.dlcNamesLoading) { SGIS.dlcNamesLoading = true; fetchDlcNames(SGIS.appDetailsExtra.dlc).then(names => { SGIS.dlcNames = names; SGIS.dlcNamesLoading = false; if (SGIS.tab === 'overview') renderOverview(); }).catch(() => { SGIS.dlcNamesLoading = false; }); } if (!SGIS.gameStatusInfo && !SGIS.gameStatusLoading) { SGIS.gameStatusLoading = true; const gsName = (SGIS.overview && SGIS.overview.name) || ''; fetchGameStatus(APP_ID, gsName).then(() => { SGIS.gameStatusLoading = false; if (SGIS.tab === 'overview') renderOverview(); }).catch(() => { SGIS.gameStatusLoading = false; }); } if (HAS_APP_ID && !SGIS._profileFeaturesDelayedCheck) { SGIS._profileFeaturesDelayedCheck = true; setTimeout(() => { SGIS._profileFeaturesDelayedCheck = false; const prev = SGIS.profileFeaturesStatus; SGIS.profileFeaturesStatus = null; const latest = detectProfileFeaturesStatus(); if (prev && latest && prev.status !== latest.status && SGIS.tab === 'overview') { renderOverview(); } }, 1500); } }, }, medals: { render: () => renderMedals() }, prices: { render: (force) => renderPrices(!!force) }, reviews: { render: () => renderReviews() }, achievements: { render: () => renderAchievements() }, dynamics: { render: () => renderDynamics() }, profile: { render: () => {} }, activity: { render: () => renderActivity() }, userBadges: { render: () => renderUserBadges() }, social: { render: () => renderSocial() }, userAchievements: { render: () => renderUserAchievements() }, }; const TAB_CACHE_RESET = { overview: { both: { overview: null, familyShareSupported: null, appDetailsExtra: null, dlcNames: null, drmInfo: null, priceChartRange: 'all', gameStatusInfo: null, profileFeaturesStatus: null }, retry: { currentPlayers: null, reviewSummary: null }, force: { similarGames: null, dynamicStoreChecked: false }, }, medals: { both: { cards: null } }, prices: { both: { prices: null, historyPrices: null, prediction: null, predictionError: null, giftRec: null, priceChartRange: 'all', itadOverview: null, pricesFetchedAt: 0, historyFetchedAt: 0 } }, reviews: { both: { reviews: null, reviewsExpanded: () => new Set(), reviewsFilter: () => ({ rec: 'all', playtime: 'all', language: 'all', purchase: 'all', keyword: '', regexMode: false }) } }, achievements: { both: { achievements: null, globalAchievements: null } }, dynamics: { both: { dynamics: null, aiSummary: null }, force: { aiSummaryLoading: false, aiSummaryError: null } }, profile: { both: { profile: null, profileError: null } }, activity: { both: { activity: null, personalTimeline: null, familyTimeline: null } }, userBadges: { both: { userBadges: null } }, social: { both: { friendsList: null, friendsListError: null }, retry: { friendsLevels: null } }, userAchievements: { both: { userAchievements: null, aiPersona: null, aiPersonaError: null, insightData: null, aiInsight: null, aiInsightError: null, aiMarketInsight: null, aiMarketInsightError: null } }, }; function _applyTabReset(map) { for (const k in map) { const v = map[k]; SGIS[k] = (typeof v === 'function') ? v() : v; } } function resetTabCache(tab, scope) { const spec = TAB_CACHE_RESET[tab]; if (!spec) return; _applyTabReset(spec.both); _applyTabReset(scope === 'force' ? spec.force : spec.retry); } function renderTab(tab, force) { _paintTab = tab; try { if (force) resetTabCache(tab, 'force'); const spec = SGIS_TAB_RENDERERS[tab]; if (!spec) { console.warn('[SGIS] 未知标签页:', tab); return; } if (tab === 'profile') { renderProfile({ force: !!force }); } else { spec.render(!!force); } if (spec.prepare) spec.prepare(); } catch (e) { console.error('[SGIS] renderTab error:', e); renderError('渲染失败: ' + e.message); } } function watchActivityOverlay() { const overlay = document.getElementById('sf-wf-overlay'); if (!overlay) { const mo = new MutationObserver((_, obs) => { if (document.getElementById('sf-wf-overlay')) { obs.disconnect(); watchActivityOverlay(); } }); mo.observe(document.body, { childList: true }); addDisposer(() => mo.disconnect()); return; } const handle = () => { if (overlay.classList.contains('sf-wf-open') && SGIS.open) closePanel(); }; handle(); const mo = new MutationObserver(handle); mo.observe(overlay, { attributes: true, attributeFilter: ['class'] }); addDisposer(() => mo.disconnect()); } function initSidebar() { ensureFab(); ensurePanel(); refreshRates().catch(() => { }); document.addEventListener('sglv:games-updated', () => { _invalidateSgisPanes(); if (SGIS.open) _activateSgisTab(SGIS.tab, { force: true }); }); window.addEventListener('sglv-theme-changed', () => { _invalidateSgisPanes(); if (SGIS.open) _activateSgisTab(SGIS.tab, { force: true }); }); watchActivityOverlay(); console.log('%c[Steam 个人信息面板 v2.8.0] UI 初始化完成 · AppID:', `color:${SGLVCharts.accent()};font-weight:bold`, APP_ID || '(首页模式)'); } const REVIEW_SCORE_MAP = { 9: { desc: '好评如潮', icon: '🎉', cls: 'overwhelmingly-positive' }, 8: { desc: '特别好评', icon: '👍', cls: 'very-positive' }, 7: { desc: '多半好评', icon: '✅', cls: 'mostly-positive' }, 6: { desc: '好评', icon: '🙂', cls: 'positive' }, 5: { desc: '褒贬不一', icon: '⚖️', cls: 'mixed' }, 4: { desc: '差评', icon: '😕', cls: 'negative' }, 3: { desc: '多半差评', icon: '❌', cls: 'mostly-negative' }, 2: { desc: '特别差评', icon: '👎', cls: 'very-negative' }, 1: { desc: '差评如潮', icon: '💢', cls: 'overwhelmingly-negative' }, }; const SCORE_CLS_TO_TIER = { 'overwhelmingly-positive': 'pos', 'very-positive': 'pos', 'mostly-positive': 'pos', 'positive': 'pos', 'mixed': 'mix', 'overwhelmingly-negative': 'neg', 'very-negative': 'neg', 'mostly-negative': 'neg', 'negative': 'neg', }; async function fetchReviews(appId) { const cacheKey = 'reviews_' + appId; const cached = cacheGet(cacheKey); if (cached) return cached; const summaryUrl = `https://store.steampowered.com/appreviews/${appId}?json=1&filter=summary&language=schinese&purchase_type=all&day_range=999999`; const detailUrl = `https://store.steampowered.com/appreviews/${appId}?json=1&filter=all&language=schinese&purchase_type=all&num_per_page=20`; const [summaryRes, detailRes] = await Promise.all([ fetchJson(summaryUrl, { timeout: 12000 }).catch(() => null), fetchJson(detailUrl, { timeout: 12000 }).catch(() => null), ]); const allTimeSummary = summaryRes?.query_summary || {}; const recentSummary = detailRes?.query_summary || {}; const reviews = (detailRes?.reviews || []).map(r => { const a = r.author || {}; const realName = (a.personaname || '').trim(); return { id: r.recommendationid || '', steamid: a.steamid || '', authorName: realName || 'Steam 用户', profileUrl: a.profileurl || '', avatar: a.avatar || '', avatarMedium: a.avatar_medium || a.avatar || '', avatarFull: a.avatar_full || a.avatar || '', playtimeForever: a.playtime_forever || 0, playtimeAtReview: a.playtime_at_review || 0, numGamesOwned: a.num_games_owned || 0, numReviews: a.num_reviews || 0, language: r.language || '', review: r.review || '', timestampCreated: r.timestamp_created || 0, timestampUpdated: r.timestamp_updated || 0, votedUp: !!r.voted_up, votesUp: r.votes_up || 0, votesFunny: r.votes_funny || 0, weightedVoteScore: r.weighted_vote_score || '0', commentCount: r.comment_count || 0, steamPurchase: !!r.steam_purchase, receivedForFree: !!r.received_for_free, writtenDuringEarlyAccess: !!r.written_during_early_access, }; }); const result = { allTime: { totalReviews: allTimeSummary.total_reviews || 0, totalPositive: allTimeSummary.total_positive || 0, totalNegative: allTimeSummary.total_negative || 0, reviewScore: allTimeSummary.review_score || 0, reviewScoreDesc: allTimeSummary.review_score_desc || '无数据', }, recent: { numReviews: recentSummary.num_reviews || 0, totalPositive: recentSummary.total_positive || 0, totalNegative: recentSummary.total_negative || 0, totalReviews: recentSummary.total_reviews || 0, reviewScore: recentSummary.review_score || 0, reviewScoreDesc: recentSummary.review_score_desc || '', }, reviews: reviews, fetchedAt: Date.now(), }; cacheSet(cacheKey, result, CACHE_TTL.reviews); return result; } function renderReviews() { if (SGIS.reviewsLoading) return; if (SGIS.reviews) { renderReviewsContent(SGIS.reviews); return; } SGIS.reviewsLoading = true; renderLoading('正在获取评测数据…'); fetchReviews(APP_ID) .then(data => { SGIS.reviews = data; renderReviewsContent(data); }) .catch(e => renderError('评测获取失败: ' + e.message)) .finally(() => { SGIS.reviewsLoading = false; }); } function _prepareReviewData(data, filter) { const fmt = (v) => num(v).toLocaleString('zh-CN'); const pct = (a, b) => b > 0 ? ((a / b) * 100).toFixed(1) : '0.0'; const allTime = data.allTime; const recent = data.recent; const scoreInfo = REVIEW_SCORE_MAP[allTime.reviewScore] || { desc: allTime.reviewScoreDesc, icon: '❓', cls: 'unknown' }; const scoreTier = SCORE_CLS_TO_TIER[scoreInfo.cls] || 'mix'; const positiveRate = pct(allTime.totalPositive, allTime.totalReviews); const positiveBarWidth = positiveRate; const recentPositiveRate = recent.totalReviews > 0 ? pct(recent.totalPositive, recent.totalReviews) : null; let trendHtml = ''; if (recentPositiveRate != null && allTime.totalReviews > 0) { const diff = (Number(recentPositiveRate) - Number(positiveRate)).toFixed(1); const trendIcon = Number(diff) > 0 ? '📈' : (Number(diff) < 0 ? '📉' : '➡️'); const trendColor = Number(diff) > 0 ? '#4bb54f' : (Number(diff) < 0 ? '#e63946' : 'var(--sgis-text-2)'); trendHtml = `
最近30天 ${recentPositiveRate}% (${fmt(recent.totalReviews)}条)
全部时间 ${positiveRate}% (${fmt(allTime.totalReviews)}条)
趋势 ${trendIcon} ${diff > 0 ? '+' : ''}${diff}%
`; } const filterBtn = (group, value, label) => { const active = filter[group] === value ? 'active' : ''; return ``; }; const filteredReviews = applyReviewFilters(data.reviews, filter); const reviewsHtml = filteredReviews.length ? filteredReviews.map(r => renderReviewItem(r)).join('') : '
无符合条件的评测
尝试调整筛选条件或更换关键词
'; return { num, fmt, pct, allTime, recent, scoreInfo, scoreTier, positiveRate, positiveBarWidth, trendHtml, filterBtn, filteredReviews, reviewsHtml, }; } function _renderReviewSummary(d) { return `
${SGIS_ICONS.review} 评测摘要
${d.scoreInfo.icon}
${d.scoreInfo.desc}
${d.fmt(d.allTime.totalReviews)} 条评测 · 来自 Steam 用户
${d.positiveRate}%
👍 ${d.fmt(d.allTime.totalPositive)} 好评 👎 ${d.fmt(d.allTime.totalNegative)} 差评
${d.trendHtml}
`; } function _renderReviewFilters(d, filter) { return `
${SGIS_ICONS.target} 多维筛选
${filter.keyword ? '' : ''}
推荐: ${d.filterBtn('rec', 'all', '全部')} ${d.filterBtn('rec', 'yes', '好评')} ${d.filterBtn('rec', 'no', '差评')}
时长: ${d.filterBtn('playtime', 'all', '全部')} ${d.filterBtn('playtime', 'lt1', '<1h')} ${d.filterBtn('playtime', '1to10', '1-10h')} ${d.filterBtn('playtime', '10to50', '10-50h')} ${d.filterBtn('playtime', 'gt50', '50h+')}
语言: ${d.filterBtn('language', 'all', '全部')} ${d.filterBtn('language', 'schinese', '中文')} ${d.filterBtn('language', 'english', '英文')}
获取: ${d.filterBtn('purchase', 'all', '全部')} ${d.filterBtn('purchase', 'steam', '购买')} ${d.filterBtn('purchase', 'free', '免费')} ${d.filterBtn('purchase', 'key', 'Key')}
${SGIS_ICONS.review} 显示 ${d.filteredReviews.length} / ${d.data ? d.data.reviews.length : 0} 条评测 ${d.filteredReviews.length !== (d.data ? d.data.reviews.length : 0) ? '已筛选' : ''}
`; } function _renderReviewList(d) { return `
${SGIS_ICONS.review} 评测列表
${d.reviewsHtml}
`; } function _renderReviewEmptyState() { return `
暂无评测数据
该游戏可能没有中文评测,或 Steam API 暂未返回
`; } function renderReviewsContent(data) { _paintTab = 'reviews'; if (!data || (!data.allTime.totalReviews && !data.reviews.length)) { setBody(_renderReviewEmptyState()); return; } const filter = SGIS.reviewsFilter; const d = _prepareReviewData(data, filter); d.data = data; setBody(_renderReviewSummary(d) + _renderReviewFilters(d, filter) + _renderReviewList(d)); bindReviewFilterEvents(data); bindReviewExpandEvents(); } function _prepareReviewItemData(r) { const playtimeHours = r.playtimeForever > 0 ? (r.playtimeForever / 60).toFixed(1) : '0'; const recCls = r.votedUp ? 'sgis-review-rec-yes' : 'sgis-review-rec-no'; const recText = r.votedUp ? '推荐' : '不推荐'; const dateStr = r.timestampCreated > 0 ? formatRelativeDate(r.timestampCreated) : '—'; const dateAbs = r.timestampCreated > 0 ? new Date(r.timestampCreated * 1000).toLocaleDateString('zh-CN') : ''; let purchaseType = ''; if (r.receivedForFree) purchaseType = '免费获取'; else if (r.steamPurchase) purchaseType = 'Steam 购买'; else purchaseType = 'Key 激活'; const langMap = { schinese: '中文', tchinese: '繁中', english: '英文', japanese: '日文' }; const langText = langMap[r.language] || r.language || '—'; const avatarSrc = r.avatarMedium || r.avatar || ''; const initial = (r.authorName || '?').trim().charAt(0).toUpperCase(); const esc = escHtml; const escReview = esc(r.review).replace(/\n/g, '
'); const isExpanded = SGIS.reviewsExpanded.has(r.id); const reviewLen = (r.review || '').length; const isLong = reviewLen > 200; return { r, num, playtimeHours, recCls, recText, dateStr, dateAbs, purchaseType, langText, avatarSrc, initial, esc, escReview, isExpanded, reviewLen, isLong, }; } function _renderReviewItemHeader(d) { const avatarHtml = d.avatarSrc ? `` : `
${d.initial}
`; const authorHtml = d.r.profileUrl ? `${d.r.authorName}` : `${d.r.authorName}`; return `
${avatarHtml}
${authorHtml} ${d.esc(d.dateStr)}
${d.recText}
`; } function _renderReviewItemMeta(d) { return `
⏱ ${d.playtimeHours}h 📦 ${d.purchaseType} 🌐 ${d.esc(d.langText)} ${d.r.numGamesOwned ? `🎮 ${d.r.numGamesOwned} 款` : ''}
`; } function _renderReviewItemText(d) { return `
${d.escReview}
`; } function _renderReviewItemActions(d) { return `
${d.isLong ? `` : ''}
`; } function _renderReviewItemVotes(d) { return `
👍 ${d.num(d.r.votesUp)} 😄 ${d.num(d.r.votesFunny)} ${d.r.commentCount > 0 ? `💬 ${d.num(d.r.commentCount)}` : ''}
`; } function renderReviewItem(r) { const d = _prepareReviewItemData(r); return `
${_renderReviewItemHeader(d)} ${_renderReviewItemMeta(d)} ${_renderReviewItemText(d)} ${_renderReviewItemActions(d)} ${_renderReviewItemVotes(d)}
`; } function applyReviewFilters(reviews, filter) { let compiledRegex = null; if (filter.keyword && filter.regexMode) { try { compiledRegex = new RegExp(filter.keyword, 'i'); } catch { compiledRegex = null; } } return reviews.filter(r => { if (filter.rec === 'yes' && !r.votedUp) return false; if (filter.rec === 'no' && r.votedUp) return false; const minutes = r.playtimeForever; if (filter.playtime === 'lt1' && minutes >= 60) return false; if (filter.playtime === '1to10' && (minutes < 60 || minutes >= 600)) return false; if (filter.playtime === '10to50' && (minutes < 600 || minutes >= 3000)) return false; if (filter.playtime === 'gt50' && minutes < 3000) return false; if (filter.language === 'schinese' && !r.language.startsWith('schinese')) return false; if (filter.language === 'english' && !r.language.startsWith('english')) return false; if (filter.purchase === 'steam' && !r.steamPurchase) return false; if (filter.purchase === 'free' && !r.receivedForFree) return false; if (filter.purchase === 'key' && (r.steamPurchase || r.receivedForFree)) return false; if (filter.keyword && filter.keyword.trim()) { const text = r.review || ''; if (filter.regexMode) { if (!compiledRegex || !compiledRegex.test(text)) return false; } else { if (!text.toLowerCase().includes(filter.keyword.toLowerCase())) return false; } } return true; }); } function _handleReviewOnChange(type, value, btn) { if (type === 'filter') { SGIS.reviewsFilter[value.group] = value.value; document.querySelectorAll(`.sgis-review-filter-btn[data-filter-group="${value.group}"]`).forEach(b => b.classList.remove('active')); if (btn) btn.classList.add('active'); } else if (type === 'search') { SGIS.reviewsFilter.keyword = value; } else if (type === 'regex') { SGIS.reviewsFilter.regexMode = value; const toggle = document.getElementById('sgis-review-regex-toggle'); if (toggle) toggle.classList.toggle('active', value); } else if (type === 'clear') { const input = document.getElementById('sgis-review-search'); if (input) input.value = ''; SGIS.reviewsFilter.keyword = ''; if (input) input.focus(); } } function bindReviewFilterEvents(data) { const rerenderReviews = () => { const filteredReviews = applyReviewFilters(data.reviews, SGIS.reviewsFilter); const listEl = document.getElementById('sgis-review-list'); if (listEl) { listEl.innerHTML = filteredReviews.length ? filteredReviews.map(r => renderReviewItem(r)).join('') : '
无符合条件的评测
尝试调整筛选条件或更换关键词
'; bindReviewExpandEvents(); } const countSummary = document.querySelector('[data-count-summary]'); if (countSummary) { countSummary.innerHTML = ` ${SGIS_ICONS.review} 显示 ${filteredReviews.length} / ${data.reviews.length} 条评测 ${filteredReviews.length !== data.reviews.length ? '已筛选' : ''}`; } }; const onChange = (type, value, btn) => { _handleReviewOnChange(type, value, btn); rerenderReviews(); }; document.querySelectorAll('.sgis-review-filter-btn').forEach(btn => { btn.addEventListener('click', () => { onChange('filter', { group: btn.dataset.filterGroup, value: btn.dataset.filterValue }, btn); }); }); const searchInput = document.getElementById('sgis-review-search'); if (searchInput) { let searchTimer = null; searchInput.addEventListener('input', () => { clearTimeout(searchTimer); searchTimer = setTimeout(() => onChange('search', searchInput.value), 300); }); } const regexToggle = document.getElementById('sgis-review-regex-toggle'); if (regexToggle) { regexToggle.addEventListener('click', () => { onChange('regex', !SGIS.reviewsFilter.regexMode); }); } const clearBtn = document.getElementById('sgis-review-search-clear'); if (clearBtn && searchInput) { clearBtn.addEventListener('click', () => onChange('clear', null)); } } function bindReviewExpandEvents() { document.querySelectorAll('.sgis-review-text').forEach(el => { el.addEventListener('click', (e) => { if (e.target.closest('.sgis-review-action-btn, a, button')) return; const id = el.dataset.reviewId; toggleReviewExpand(id); }); }); document.querySelectorAll('.sgis-review-expand-btn').forEach(btn => { btn.addEventListener('click', (e) => { e.stopPropagation(); toggleReviewExpand(btn.dataset.reviewId); const isExpanded = btn.classList.contains('is-expanded'); btn.classList.toggle('is-expanded', !isExpanded); btn.querySelector('span').textContent = !isExpanded ? '收起' : '展开'; }); }); document.querySelectorAll('.sgis-review-copy-btn').forEach(btn => { btn.addEventListener('click', async (e) => { e.stopPropagation(); const id = btn.dataset.reviewId; const review = (SGIS.reviews?.reviews || []).find(x => String(x.id) === String(id)); if (!review || !review.review) return; const ok = await copyTextToClipboard(review.review); btn.classList.add('copied'); const label = btn.querySelector('span'); const origText = label.textContent; label.textContent = ok ? '已复制' : '失败'; setTimeout(() => { btn.classList.remove('copied'); label.textContent = origText; }, 1500); }); }); } function toggleReviewExpand(id) { const textEl = document.querySelector(`.sgis-review-text[data-review-id="${id}"]`); if (!textEl) return; if (SGIS.reviewsExpanded.has(id)) { SGIS.reviewsExpanded.delete(id); textEl.classList.remove('expanded'); } else { SGIS.reviewsExpanded.add(id); textEl.classList.add('expanded'); } } const GIFT_RESTRICTED_REGIONS = new Set(['RU']); const GIFT_MARKUP_FACTOR = 1.15; function calculateGiftRecommendation(pricesData) { if (!pricesData || !pricesData.prices || !pricesData.prices.length) return null; const userRegion = (document.cookie.match(/steamCountry=(\w{2})/) || [])[1] || 'CN'; const recipientData = pricesData.prices.find(p => p.region === userRegion); if (!recipientData) return null; const recipientCny = convertToCNY(num(recipientData.price), recipientData.currency); if (recipientCny == null || recipientCny <= 0) return null; const candidates = []; for (const p of pricesData.prices) { if (p.region === userRegion) continue; if (GIFT_RESTRICTED_REGIONS.has(p.region)) continue; const senderCny = convertToCNY(num(p.price), p.currency); if (senderCny == null || senderCny <= 0) continue; if (senderCny >= recipientCny) continue; if (!(senderCny * GIFT_MARKUP_FACTOR > recipientCny)) continue; const savings = recipientCny - senderCny; const savingsPercent = (savings / senderCny) * 100; const regionInfo = REGIONS.find(r => r.code === p.region) || { name: p.region, code: p.region }; candidates.push({ region: p.region, regionName: regionInfo.name, senderCny: num(senderCny), recipientCny: num(recipientCny), savings: num(savings), savingsPercent: num(savingsPercent), senderPrice: num(p.price), senderCurrency: p.currency, senderDiscount: num(p.discount), }); } if (!candidates.length) return null; candidates.sort((a, b) => b.savings - a.savings); const best = candidates[0]; const alternatives = candidates.slice(1, 4); return { best: best, alternatives: alternatives, userRegion: userRegion, userRegionName: (REGIONS.find(r => r.code === userRegion) || { name: userRegion }).name, recipientCny: num(recipientCny), allCandidates: candidates.length, timestamp: Date.now(), }; } function renderGiftRecommendation(giftData) { if (!giftData || !giftData.best) return ''; const fmt = (v) => num(v).toFixed(2); const best = giftData.best; const altText = giftData.alternatives.length ? `
其他可赠送: ${giftData.alternatives.map(a => `${a.regionName} (省¥${fmt(a.savings)})` ).join(' · ')}
` : ''; return `
${SGIS_ICONS.gift} 跨区送礼推荐
${best.regionName} → ${giftData.userRegionName} 赠送最划算
¥${fmt(best.savings)} 节约 ${best.savingsPercent.toFixed(1)}%
送礼区(${best.regionName}) ¥${fmt(best.senderCny)}${best.senderDiscount > 0 ? ` (-${best.senderDiscount}%)` : ''}
收礼区(${giftData.userRegionName}) ¥${fmt(best.recipientCny)}
✓ 可赠送(符合低价区×1.15>收礼区规则)
⚠ 注意事项:Steam跨区送礼政策可能随时调整,请确认当前政策。部分区域有送礼限制(如俄罗斯不能向其他区域送礼)。
${altText}
`; } function appendGiftRecommendationToBody() { if (!SGIS.prices) return; if (!_pricesPane()) return; if (!SGIS.giftRec) SGIS.giftRec = calculateGiftRecommendation(SGIS.prices); if (!SGIS.giftRec) { _fillPriceBlock('gift', ''); return; } _fillPriceBlock('gift', renderGiftRecommendation(SGIS.giftRec)); } async function fetchHistoryPricesCheapShark(appId, reason) { try { const url = `https://api.cheapshark.com/api/1.0/games?id=${appId}`; const data = await fetchJson(url, { timeout: 10000 }); if (!data || !data.deals || !data.deals.length) { return await fetchHistoryPricesFallback(appId, reason + ' / CheapShark 无数据'); } const history = data.deals.map(d => ({ price: Number(d.price) || 0, regular: Number(d.retailPrice) || 0, currency: 'USD', cut: d.savings ? Math.round(Number(d.savings)) : 0, store: d.storeName || '', date: d.lastChange ? new Date(Number(d.lastChange) * 1000).toISOString() : '', })).filter(h => h.price > 0).sort((a, b) => new Date(b.date) - new Date(a.date)).slice(0, 20); let lowest = null; if (history.length) { const minPrice = Math.min(...history.map(h => h.price)); lowest = history.find(h => h.price === minPrice); if (lowest) lowest = { price: lowest.price, currency: 'USD', store: lowest.store, date: lowest.date, cut: lowest.cut }; } const result = { history, discounts: history.filter(h => h.cut > 0).sort((a, b) => b.cut - a.cut), lowest, releaseDate: null, source: 'cheapshark', error: reason, }; cacheSet('historyPrices_' + appId, result, CACHE_TTL.historyPrices); return result; } catch (e) { return await fetchHistoryPricesFallback(appId, reason + ' / CheapShark: ' + e.message); } } try { initSidebar(); } catch (e) { console.error('[SGIS] 侧边栏初始化失败,不影响游戏库功能:', e); } if (typeof SGLV_API !== 'undefined') { SGLV_API.fetchPlayerAchievements = fetchPlayerAchievements; SGLV_API.fetchGlobalAchievements = fetchGlobalAchievements; SGLV_API.fetchReviews = fetchReviews; SGLV_API.fetchReviewSummary = fetchReviewSummary; SGLV_API.fetchAppDetailsExtra = fetchAppDetailsExtra; SGLV_API.fetchDlcNames = fetchDlcNames; SGLV_API.fetchGameNews = fetchGameNews; SGLV_API.fetchFamilyShareSupport = fetchFamilyShareSupport; SGLV_API.fetchGameStatus = fetchGameStatus; SGLV_API.fetchMultiRegionPrices = fetchMultiRegionPrices; SGLV_API.fetchSteamRegionPrice = fetchSteamRegionPrice; SGLV_API.fetchAugRegionPrice = fetchAugRegionPrice; SGLV_API.fetchHistoryPrices = fetchHistoryPrices; SGLV_API.fetchHistoryPricesCheapShark = fetchHistoryPricesCheapShark; SGLV_API.refreshRates = refreshRates; SGLV_API.computeBadgeValueScores = computeBadgeValueScores; SGLV_API.fetchBadgeMarkets = fetchBadgeMarkets; SGLV_API.fetchCardPrices = fetchCardPrices; SGLV_API.fetchUserBadges = fetchUserBadges; SGLV_API.fetchSteamLevel = fetchSteamLevel; SGLV_API.fetchCurrentPlayers = fetchCurrentPlayers; SGLV_API.fetchOwnersPlaytime = fetchOwnersPlaytime; SGLV_API.fetchTagRecommendations = fetchTagRecommendations; SGLV_API.fetchProfileFeaturesStatus = fetchProfileFeaturesStatus; } })(); async function init() { const _tId = getThemeId(); const _tName = (SGLV_THEMES[_tId] && SGLV_THEMES[_tId][isZh ? 'zh' : 'en']) || _tId; console.log(`%c[Steam 游戏库展示] v${_v} 已启动 · ${_tName} · 设置→外观可切换主题`, `color:${_tId === 'blue' ? '#66c0f4' : '#a78bfa'};font-weight:bold;font-size:13px`); try { await sglvIDB.loadAll(); const upgraded = ensureCacheVersions(); if (Object.keys(upgraded).length) { console.log('[SGLV] 缓存 schema 已升级:', upgraded); if (upgraded.bundle_db) { try { GM_setValue(BUNDLE_DB_CACHE_KEY_V2, null); } catch (e) {} } } migrateLegacyGmKeysToIDB(); if (SGLV_API.hydratePccCache) SGLV_API.hydratePccCache(); } catch (e) { console.warn('[SGLV] IDB 初始化失败,降级使用 GM_setValue:', e); } try { SGLV_API.initUI(); } catch (e) { console.error('[SGLV] UI 初始化失败:', e); } try { SGLV_API.autoScan(); } catch (e) { console.warn('[SGLV] 自动扫描失败:', e); } console.log('[Steam 游戏库展示] UI 初始化完成'); window.addEventListener('pagehide', runDisposers); } if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => init().catch(e => console.error('[SGLV] 启动失败:', e))); else init().catch(e => console.error('[SGLV] 启动失败:', e)); })();