// ==UserScript== // @name Steam Wishlist Helper // @namespace https://store.steampowered.com/wishlist/ // @version 1.0.0 // @description 愿望单筛选与批量移除 // @author RayRoad // @match https://store.steampowered.com/wishlist/* // @grant GM_addStyle // @grant GM_registerMenuCommand // @run-at document-end // @noframes // @license MIT // ==/UserScript== (() => { 'use strict'; if (window.top !== window.self) return; const VERSION = '1.3.5'; const CONFIG = { pageSize: 50, detailBatch: 20, loadDelay: 150, requestTimeout: 15000, itemDelay: 800 }; const emptyFilters = () => ({ query: '', fromDate: '', toDate: '' }); const state = { items: new Map(), selected: new Set(), removed: new Set(), index: new Set(), steamid: '', own: false, root: null, context: null, tagNames: {}, totalWishlist: 0, filters: emptyFilters(), appliedFilters: null, resultIDs: new Set(), hasResults: false, dirty: false, loading: false, preparing: false, busy: false, ready: false, cancel: false, closeWhenIdle: false, reloadWhenIdle: true, needsRefresh: false, session: 0, limit: CONFIG.pageSize, loadController: null, prepareController: null, loadStatus: 'idle', loadError: '', status: '', observer: null, sentinel: null, timer: null, menuRegistered: false, revision: 0, route: location.pathname + location.search, }; const esc = value => String(value ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); const json = value => typeof value === 'string' ? JSON.parse(value) : value; const isID = value => /^\d+$/.test(String(value)) && Number(value) > 0; const appID = href => href?.match(/\/app\/(\d+)(?:\/|\?|$)/)?.[1]; function parseSnapshot(ssr, user) { const loaders = Object.values(ssr?.loaderData || {}).map(value => { try { return json(value); } catch { return null; } }); const route = loaders.find(value => value?.steamid && value?.filters && value?.sort); if (!route || !/^765\d{14}$/.test(route.steamid)) throw new Error('未找到当前愿望单身份,请刷新页面'); const queries = json(ssr?.renderContext?.queryData)?.queries; const query = queries?.find(value => value.queryKey?.[0] === 'WishlistSortedFiltered' && value.queryKey[1] === route.steamid && Array.isArray(value.state?.data?.items)); if (!query) throw new Error('Steam 未提供愿望单快照;请等待原生列表加载后刷新'); const entries = new Map(); for (const item of query.state.data.items) { if (isID(item.appid)) entries.set(String(item.appid), { id: String(item.appid), added: Number(item.date_added) || 0, rank: Number(item.priority) || 0 }); } const context = loaders.find(value => value?.storeBrowseContext)?.storeBrowseContext || {}; const language = context.language || ssr?.Config?.LANGUAGE; const country = user?.country_code || context.country || ssr?.Config?.COUNTRY; const tags = queries.find(value => value.queryKey?.[0] === 'LocalizedTagNames')?.state?.data || {}; const count = queries.find(value => value.queryKey?.[0] === 'wishlistitemcount' && value.queryKey[1] === route.steamid)?.state?.data; const storeItems = new Map(); for (const cached of queries) { if (cached.queryKey?.[0] !== 'StoreItem') continue; const id = cached.queryKey[1]?.match(/^app_(\d+)$/)?.[1]; if (!entries.has(id)) continue; const item = storeItems.get(id) || { id: Number(id) }; const part = cached.queryKey[2]; if (part === 'default_info') Object.assign(item, cached.state?.data); if (part === 'include_assets') item.assets = cached.state?.data; if (part === 'include_reviews') item.reviews = cached.state?.data; if (part === 'include_release') item.release = cached.state?.data; if (part === 'top_tags') item.tagids = (cached.state?.data || []).map(tag => typeof tag === 'object' ? tag.tagid : tag); storeItems.set(id, item); } return { steamid: route.steamid, own: user?.logged_in === true && user?.steamid === route.steamid, entries, storeItems, tags, total: Number.isInteger(count) && count >= entries.size ? count : entries.size, context: /^[A-Z]{2}$/.test(country || '') && /^[a-z_]+$/.test(language || '') ? { country_code: country, language } : null }; } function seed(snapshot, reset = false) { if (reset) { state.items.clear(); state.selected.clear(); state.removed.clear(); state.loadStatus = 'idle'; state.loadError = ''; } state.steamid = snapshot.steamid; state.own = snapshot.own; state.context = snapshot.context; state.totalWishlist = snapshot.total || snapshot.entries.size; state.tagNames = snapshot.tags || {}; state.index = new Set(snapshot.entries.keys()); for (const [id, meta] of snapshot.entries) { if (state.removed.has(id)) continue; state.items.set(id, { name: `App ${id}`, detail: false, price: null, discount: null, review: null, image: fallbackCover(id), ...state.items.get(id), ...meta }); } for (const [id, raw] of snapshot.storeItems || []) if (raw.success === 1 && state.items.has(id)) state.items.set(id, normalizeStoreItem(raw, state.items.get(id))); state.revision++; } const fallbackCover = id => `https://shared.akamai.steamstatic.com/store_item_assets/steam/apps/${id}/header.jpg`; function safeImage(value) { try { const url = new URL(value); return url.protocol === 'https:' && (url.hostname === 'steamstatic.com' || url.hostname.endsWith('.steamstatic.com') || url.hostname === 'steamcdn-a.akamaihd.net') ? url.href : ''; } catch { return ''; } } function assetCover(assets, id) { if (!assets?.asset_url_format || !assets.header) return fallbackCover(id); const path = assets.asset_url_format.replace('${FILENAME}', assets.header); return safeImage(/^https:\/\//.test(path) ? path : `https://shared.akamai.steamstatic.com/store_item_assets/${path.replace(/^\//, '')}`) || fallbackCover(id); } function normalizeStoreItem(raw, previous) { const option = raw.best_purchase_option; const free = raw.is_free === true && !raw.is_coming_soon; const priceText = option?.formatted_final_price || (free ? '免费' : '无价格'); const reviews = Number.isFinite(raw.reviews?.summary_language_specific?.percent_positive) ? raw.reviews.summary_language_specific : raw.reviews?.summary_filtered; const tags = (raw.tagids || raw.tags?.map(tag => tag.tagid) || []).map(tag => state.tagNames[tag]).filter(Boolean).slice(0, 5); const review = Number(reviews?.percent_positive); return { ...previous, name: raw.name || previous.name, detail: true, origin: 'api', price: option?.formatted_final_price ? amount(priceText) : free ? 0 : null, priceText, originalPrice: option?.formatted_original_price || '', discount: Number(option?.discount_pct) || (option || free ? 0 : null), review: Number.isFinite(review) ? review : null, reviewLabel: reviews?.review_score_label || '', coming: raw.is_coming_soon === true, release: Number(raw.release?.steam_release_date) || 0, image: assetCover(raw.assets, previous.id), tags, unavailable: raw.visible === false, hasDemo: Boolean(raw.related_items?.demo_appid?.length || raw.related_items?.standalone_demo_appid?.length), text: [raw.name, ...tags].filter(Boolean).join(' '), }; } function nativeRows() { const rows = new Map(); for (const link of document.querySelectorAll('a[href*="/app/"]')) { if (link.closest('#swh-root, #swh-dialog')) continue; const id = appID(link.href); if (!state.index.has(id)) continue; const row = link.closest('div[role="button"], .wishlist_row'); if (row && !row.closest('header, nav')) rows.set(id, row); } return rows; } function amount(text) { const raw = String(text).replace(/[^\d.,]/g, ''); if (!raw) return null; const comma = raw.lastIndexOf(','), dot = raw.lastIndexOf('.'); let normalized = raw; if (comma > dot && /,\d{1,2}$/.test(raw)) normalized = raw.replace(/\./g, '').replace(',', '.'); else normalized = raw.replace(/,/g, ''); const value = Number(normalized); return Number.isFinite(value) ? value : null; } function parseRow(id, row) { const links = Array.from(row.querySelectorAll('a[href*="/app/"]')); const title = links.find(link => appID(link.href) === id && link.textContent.trim() && !link.querySelector('[aria-label]')); const priceBlock = row.querySelector('[role="link"][aria-label]'); const priceLabel = priceBlock?.getAttribute('aria-label') || ''; // Use the final leaf price; original and discounted prices are separate leaves. const priceLeaves = priceBlock ? Array.from(priceBlock.querySelectorAll('div')).filter(el => !el.children.length && /\d/.test(el.textContent) && !/%/.test(el.textContent)) : []; const priceText = priceLeaves.at(-1)?.textContent.trim() || ''; const text = row.textContent.replace(/\s+/g, ' ').trim(); const percent = row.querySelector('[title*="%"]')?.getAttribute('title')?.match(/(\d+(?:\.\d+)?)\s*%/); const discount = priceBlock?.textContent.match(/-\s*(\d+)\s*%/); const release = text.match(/发行日期[::]\s*(\d{4})年(\d{1,2})月(\d{1,2})日/); const tags = Array.from(row.querySelectorAll('button.U3ndjc3qoW8-')).map(el => el.textContent.trim()).filter(Boolean).slice(0, 5); const free = /^(免费|免費|Free To Play|Free)$/i.test(priceLabel.trim()) || Array.from(row.querySelectorAll('a, button')).some(el => /^(免费开玩|免费游玩|免費遊玩|Play for Free)$/i.test(el.textContent.trim())); const img = row.querySelector('img'); const image = safeImage(img?.currentSrc || img?.getAttribute('src') || img?.getAttribute('data-src')); return { ...state.items.get(id), id, name: title?.textContent.trim() || state.items.get(id)?.name || `App ${id}`, detail: true, text, price: priceText ? amount(priceText) : free ? 0 : null, priceText: priceText || (free ? '免费' : '无价格'), discount: discount ? Number(discount[1]) : priceText || free ? 0 : null, review: percent ? Number(percent[1]) : null, reviewLabel: row.querySelector('[title*="%"]')?.textContent.trim() || '', originalPrice: discount && priceLeaves.length > 1 ? priceLeaves[0].textContent.trim() : '', release: release ? new Date(Number(release[1]), Number(release[2]) - 1, Number(release[3])).getTime() / 1000 : 0, tags, hasDemo: /有试用版可用|有試玩版|Demo Available/i.test(text), coming: /即将推出|即將推出|Coming soon|To be announced|尚未推出|待定/i.test(text), image: image || state.items.get(id)?.image || fallbackCover(id), }; } function collect() { const rows = nativeRows(); for (const [id, row] of rows) { if (state.removed.has(id)) continue; if (state.items.get(id)?.origin === 'api') continue; const item = parseRow(id, row), previous = state.items.get(id); if (!previous?.detail || ['name', 'text', 'price', 'priceText', 'discount', 'review', 'coming', 'image'].some(key => previous[key] !== item[key])) { state.items.set(id, item); state.revision++; } } return rows; } function validation(filters = state.filters) { for (const key of ['fromDate', 'toDate']) if (filters[key] && !dateBoundary(filters[key])) return '请输入有效的添加日期'; if (filters.fromDate && filters.toDate && filters.fromDate > filters.toDate) return '开始日期不能晚于结束日期'; return ''; } function dateBoundary(value, nextDay = false) { const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value || ''); if (!match) return null; const [, y, m, d] = match.map(Number); const date = new Date(y, m - 1, d); if (date.getFullYear() !== y || date.getMonth() !== m - 1 || date.getDate() !== d) return null; if (nextDay) date.setDate(date.getDate() + 1); return date.getTime() / 1000; } function filtered() { const f = state.appliedFilters || state.filters; if (validation(f)) return []; const words = f.query.toLocaleLowerCase().trim().split(/\s+/).filter(Boolean); return Array.from(state.items.values()).filter(item => state.resultIDs.has(item.id) && item.detail && indexMatches(item, f) && words.every(word => `${item.name} ${item.id} ${(item.tags || []).join(' ')}`.toLocaleLowerCase().includes(word))); } async function requestDetails(ids) { const input = { ids: ids.map(id => ({ appid: Number(id) })), context: state.context, data_request: { include_assets: true, include_tag_count: 5 } }; const url = new URL('https://api.steampowered.com/IStoreBrowseService/GetItems/v1/'); url.searchParams.set('input_json', JSON.stringify(input)); const controller = new AbortController(); state.loadController = controller; const timeout = setTimeout(() => controller.abort(), CONFIG.requestTimeout); try { const response = await fetch(url.href, { credentials: 'omit', signal: controller.signal, redirect: 'error' }); if (!response.ok) throw new Error(`游戏详情加载失败 HTTP ${response.status}`); const result = response.headers?.get('X-eresult'); if (result && result !== '1') throw new Error(`Steam 拒绝详情请求(${result})`); const body = await response.json(); if (!Array.isArray(body?.response?.store_items)) throw new Error('Steam 详情响应格式已改变,未覆盖现有数据'); const wanted = new Set(ids), seen = new Set(); for (const raw of body.response.store_items) { const id = String(raw.appid || raw.id); if (!wanted.has(id) || seen.has(id)) throw new Error('Steam 返回了不匹配或重复的 App ID,已停止加载'); seen.add(id); } return body.response.store_items; } finally { clearTimeout(timeout); if (state.loadController === controller) state.loadController = null; } } async function serverSnapshot() { const url = new URL(`/wishlist/profiles/${state.steamid}/`, location.origin); const language = new URL(location.href).searchParams.get('l'); if (language) url.searchParams.set('l', language); const response = await fetch(url, { credentials: 'same-origin', cache: 'no-store', redirect: 'error', signal: AbortSignal.timeout(CONFIG.requestTimeout) }); if (!response.ok) throw new Error(`Steam 快照读取失败 HTTP ${response.status}`); const doc = new DOMParser().parseFromString(await response.text(), 'text/html'); const payload = doc.querySelector('#valve-ssr-data'); if (!payload) throw new Error('Steam 未返回可核验快照,可能登录已过期'); const data = JSON.parse(payload.textContent); const snapshot = parseSnapshot(data, data.UserConfig); if (snapshot.steamid !== state.steamid) throw new Error('愿望单身份发生变化,操作已停止'); return snapshot; } function confirmBatch(items) { return new Promise(resolve => { const previousFocus = document.activeElement; const visible = new Set(filtered().map(item => item.id)); const hidden = items.filter(item => !visible.has(item.id)).length; const overlay = document.createElement('div'); overlay.id = 'swh-dialog'; overlay.innerHTML = ``; document.body.append(overlay); const no = overlay.querySelector('[data-no]'), yes = overlay.querySelector('[data-yes]'); let resolved = false; const close = value => { if (resolved) return; resolved = true; state.cancelConfirm = null; overlay.remove(); previousFocus?.focus(); resolve(value); }; state.cancelConfirm = () => close(false); no.onclick = () => close(false); yes.onclick = () => close(true); overlay.addEventListener('keydown', event => { if (event.key === 'Escape') { event.preventDefault(); close(false); } if (event.key === 'Tab') { const focusable = Array.from(overlay.querySelectorAll('button:not(:disabled), input')); const first = focusable[0], last = focusable.at(-1); if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); } else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); } } }); no.focus(); }); } function sessionFromText(text) { for (const pattern of [ /g_sessionID\s*[:=]\s*["']([0-9a-fA-F]{8,48})["']/, /\\?["'](?:g_sessionID|session[-_]?id)\\?["']\s*:\s*\\?["']([0-9a-fA-F]{8,48})\\?["']/i, ]) { const match = String(text || '').match(pattern); if (match) return match[1]; } return ''; } function sessionFromDocument(doc = document, cookie = document.cookie) { const match = cookie.match(/(?:^|;\s*)sessionid=([^;]*)/); if (match) { try { const value = decodeURIComponent(match[1]); if (/^[0-9a-fA-F]{8,48}$/.test(value)) return value; } catch { /* try the scoped DOM sources */ } } const node = doc.querySelector('meta[name="sessionid"],input[name="sessionid"]'); const value = node?.getAttribute('content') || node?.getAttribute('value') || ''; if (/^[0-9a-fA-F]{8,48}$/.test(value)) return value; for (const script of doc.querySelectorAll('script:not([src])')) { const value = sessionFromText(script.textContent); if (value) return value; } return ''; } async function resolveSessionId() { const local = sessionFromDocument(); if (local) return local; // The official classic store page initializes g_sessionID. No token is logged or persisted. const response = await fetch(new URL('/app/570/', location.origin).href, { credentials: 'same-origin', cache: 'no-store', redirect: 'error', signal: AbortSignal.timeout(CONFIG.requestTimeout), }); if (!response.ok) throw new Error(`Steam 会话读取失败 HTTP ${response.status},未提交移除`); const doc = new DOMParser().parseFromString(await response.text(), 'text/html'); const value = sessionFromDocument(doc); if (!value) throw new Error('未获取到 Steam sessionid,未提交移除;请重新登录并刷新页面'); return value; } async function removeWishlistItem(id, sessionid) { if (!/^\d+$/.test(String(id)) || !Number.isInteger(Number(id)) || Number(id) < 1 || Number(id) > 0xffffffff) throw new Error('无效的 App ID,未提交移除'); if (!/^[0-9a-fA-F]{8,48}$/.test(sessionid)) throw new Error('无效的 Steam 会话,未提交移除'); let response; try { state.needsRefresh = true; response = await fetch(new URL('/api/removefromwishlist', location.origin).href, { method: 'POST', credentials: 'same-origin', redirect: 'error', headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, body: new URLSearchParams({ sessionid, appid: String(id) }), signal: AbortSignal.timeout(CONFIG.requestTimeout), }); } catch { throw new Error('移除请求连接失败或超时;结果不确定,已停止,请刷新核对,勿直接重复操作'); } if (!response.ok) throw new Error(`移除接口 HTTP ${response.status};已停止,不重复提交,请刷新核对`); let data; try { data = await response.json(); } catch { throw new Error('移除接口响应无法解析;结果不确定,已停止,请刷新核对,勿直接重复操作'); } if (data?.success === 0 || data?.success === false) throw new Error('Steam 接口拒绝移除,已停止;请核对登录状态后重试'); if (data?.success !== 1 && data?.success !== true) throw new Error('移除接口未明确确认成功;结果不确定,已停止,请刷新核对'); } async function verifyRemoved(id) { for (let attempt = 0; attempt < 3; attempt++) { await sleep(CONFIG.itemDelay); const snapshot = await serverSnapshot(); if (!snapshot.own) throw new Error('登录身份无法确认,已停止'); if (!snapshot.entries.has(id)) return snapshot; } throw new Error(`App ${id} 尚未被服务器确认移除;结果不确定,已停止,请刷新核对,勿直接重复操作`); } async function runBatch(onlyIds) { if (!state.root?.isConnected || state.busy || state.preparing || state.loading || state.dirty || !state.own) return; const items = Array.from(onlyIds || state.selected).map(id => state.items.get(id)).filter(Boolean); if (!items.length) return; state.busy = true; state.cancel = false; setStatus('等待核对移除名单,确认后才会提交'); syncControls(); let successes = 0, attempted = 0; try { if (!await confirmBatch(items)) { setStatus('已取消移除,未执行任何写入'); return; } const sessionid = await resolveSessionId(); if (state.cancel) return; let baseline = await serverSnapshot(); if (!baseline.own) throw new Error('当前不是已登录的本人愿望单,已停止'); for (const item of items) { if (state.cancel) break; if (state.route !== location.pathname + location.search) throw new Error('页面或原生筛选已改变,已停止后续移除'); if (!baseline.entries.has(item.id)) throw new Error(`App ${item.id} 不在服务器当前快照中,请刷新核对后重新选择`); setStatus(`准备移除 ${successes + 1}/${items.length} · ${item.name}`); const currentSession = sessionFromDocument(); if (currentSession && currentSession !== sessionid) throw new Error('Steam 会话已变化,已停止;请重新打开筛选后再试'); // Send this mutation once. Ambiguous failures must never trigger automatic replay. attempted++; await removeWishlistItem(item.id, sessionid); setStatus(`正在核验 ${successes + 1}/${items.length} · ${item.name}(不重复提交)`); baseline = await verifyRemoved(item.id); state.removed.add(item.id); state.items.delete(item.id); state.selected.delete(item.id); state.index.delete(item.id); state.revision++; successes++; } setStatus(`${state.cancel ? '已停止后续操作' : '批量操作完成'} · 服务器确认移除 ${successes}/${items.length} 项。其余项目保留选择;关闭弹框后自动刷新原生页面。`); } catch (error) { setStatus(`已停止 · 确认移除 ${successes} 项 / 已提交 ${attempted} 项 · ${error.message}`); console.warn('[SWH]', error); } finally { state.busy = false; renderResults(false); if (state.closeWhenIdle) closeDialog(true, state.reloadWhenIdle); } } function mount() { if (!/^\/wishlist(?:\/|$)/.test(location.pathname)) return false; const share = Array.from(document.querySelectorAll('button,a,[role="button"]')).find(el => !el.closest('#swh-root,#swh-dialog,#swh-filter-button,.native-row') && (/^(创建分享链接|建立分享連結|创建共享链接|create (?:a )?share link)$/i.test((el.getAttribute('aria-label') || el.getAttribute('title') || el.textContent).trim()) || el.matches('button') && el.querySelector('svg.V7Sgmg4CTV0-'))); if (!share) { document.getElementById('swh-filter-button')?.remove(); return false; } let button = document.getElementById('swh-filter-button'); if (button?.previousElementSibling === share) return true; button?.remove(); button = document.createElement('button'); button.id = 'swh-filter-button'; button.type = 'button'; button.title = '筛选愿望单'; button.setAttribute('aria-label', '筛选愿望单'); button.setAttribute('aria-haspopup', 'dialog'); button.setAttribute('aria-expanded', String(Boolean(state.root?.isConnected))); button.className = share.className; button.innerHTML = ''; button.querySelector('svg').setAttribute('class', share.querySelector('svg')?.getAttribute('class') || ''); button.addEventListener('click', () => { void openDialog(); }); share.after(button); return true; } function setStatus(message) { state.status = message; const node = state.root?.querySelector('[data-status]'); if (node) node.textContent = message; updateLoadUI(); } function updateLoadUI() { const root = state.root; if (!root) return; const ids = state.resultIDs || new Set(); const loaded = Array.from(ids).filter(id => state.items.get(id)?.detail).length; const progress = root.querySelector('progress'); if (progress) { progress.max = ids.size || 1; progress.value = loaded; progress.hidden = !state.loading; } root.querySelector('[role="dialog"]')?.setAttribute('aria-busy', String(state.loading || state.preparing || state.busy)); } function syncControls() { const root = state.root; if (!root) return; const locked = state.loading || state.preparing || state.busy; root.querySelector('fieldset').disabled = locked; root.querySelector('[data-action="submit"]').disabled = locked; root.querySelector('[data-action="reset"]').disabled = locked; const stop = root.querySelector('[data-action="stop"]'); stop.hidden = !state.loading && !state.busy; stop.textContent = state.busy ? '停止后续移除' : '取消加载'; for (const el of root.querySelectorAll('[data-id],[data-all],[data-action="more"]')) el.disabled = locked || state.dirty; root.querySelector('[data-action="clear"]').disabled = locked; for (const el of root.querySelectorAll('[data-action="remove"],[data-remove-id]')) el.disabled = locked || state.dirty || !state.own || (el.dataset.action === 'remove' && !state.selected.size); updateLoadUI(); } function stopWork() { state.cancel = true; if (state.loading) state.loadController?.abort(); setStatus(state.busy ? '已请求停止;正在提交的项目完成核验后停止,不重复提交' : '正在取消加载,已加载的结果将保留'); } function reloadWishlistPage() { location.reload(); } function closeDialog(force = false, reload = true) { if (!state.root?.isConnected) return; if (state.busy && !force) { state.closeWhenIdle = true; state.reloadWhenIdle = reload; stopWork(); state.cancelConfirm?.(); return; } const shouldReload = reload && state.needsRefresh && state.route === location.pathname + location.search; state.cancel = true; state.session++; state.loadController?.abort(); state.prepareController?.abort(); state.loading = false; state.preparing = false; state.sentinel?.disconnect(); state.root?.remove(); state.root = null; const button = document.getElementById('swh-filter-button'); button?.setAttribute('aria-expanded', 'false'); if (shouldReload) reloadWishlistPage(); else button?.focus(); } function trapFocus(event, scope) { if (event.key !== 'Tab') return; const nodes = Array.from(scope.querySelectorAll('button:not(:disabled):not([hidden]),input:not(:disabled),select:not(:disabled),a[href]')).filter(el => !el.closest('[hidden]')); const first = nodes[0], last = nodes.at(-1); if (!first) { event.preventDefault(); return; } if (event.shiftKey && (document.activeElement === first || !scope.contains(document.activeElement))) { event.preventDefault(); last.focus(); } else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); } } const field = (key, label, attrs = '') => ``; async function openDialog() { if (state.root?.isConnected) { state.root.querySelector('[data-action="close"]').focus(); return; } if (state.loading || state.preparing || state.busy) return; state.route = location.pathname + location.search; state.selected.clear(); state.resultIDs = new Set(); state.hasResults = false; state.dirty = false; state.ready = false; state.needsRefresh = false; state.closeWhenIdle = false; state.reloadWhenIdle = true; state.limit = CONFIG.pageSize; const session = ++state.session; const root = document.createElement('div'); root.id = 'swh-root'; root.dataset.version = VERSION; root.innerHTML = ``; state.root = root; root.addEventListener('click', event => { if (event.target === root) { closeDialog(); return; } const single = event.target.closest('[data-remove-id]'); if (single && !state.loading && !state.preparing && !state.busy && !state.dirty) { void runBatch([single.dataset.removeId]); return; } const action = event.target.closest('[data-action]')?.dataset.action; if (action === 'close') { closeDialog(); return; } if (action === 'stop') { stopWork(); return; } if (state.loading || state.preparing || state.busy) return; if (action === 'more') appendMore(); if (action === 'clear') { state.selected.clear(); updateSelection(); } if (action === 'remove' && !state.dirty) void runBatch(); if (action === 'reset') { for (const key of Object.keys(state.filters)) state.filters[key] = ''; for (const el of root.querySelectorAll('[data-filter]')) el.value = ''; markDirty(); } }); root.querySelector('form').addEventListener('submit', event => { event.preventDefault(); void loadMatching(); }); const change = event => { const el = event.target; if (el.matches('[data-filter]')) { state.filters[el.dataset.filter] = el.value; markDirty(); } if (event.type !== 'change' || state.loading || state.preparing || state.busy || state.dirty) return; if (el.matches('[data-id]')) { el.checked ? state.selected.add(el.dataset.id) : state.selected.delete(el.dataset.id); updateSelection(); } if (el.matches('[data-all]')) { for (const item of filtered()) el.checked ? state.selected.add(item.id) : state.selected.delete(item.id); updateSelection(); } }; root.addEventListener('input', change); root.addEventListener('change', change); root.addEventListener('keydown', event => { if (event.key === 'Escape') { event.preventDefault(); closeDialog(); return; } trapFocus(event, root); }); root.addEventListener('wheel', event => { if (!event.target.closest('.swh-results-scroll,fieldset')) event.preventDefault(); }, { passive: false }); root.addEventListener('error', event => { const img = event.target; if (!img.matches?.('[data-cover-id]')) return; const fallback = fallbackCover(img.dataset.coverId); if (!img.dataset.fallback && img.src !== fallback) { img.dataset.fallback = '1'; img.src = fallback; return; } img.hidden = true; img.nextElementSibling.hidden = false; }, true); document.body.append(root); document.getElementById('swh-filter-button')?.setAttribute('aria-expanded', 'true'); root.querySelector('[data-action="close"]').focus(); await prepareSnapshot(session); } function markDirty() { state.dirty = state.hasResults; state.selected.clear(); updateSelection(); if (state.hasResults) setStatus('条件已修改;请点击“加载符合条件的项目”更新结果'); } async function readSnapshot(url, externalSignal) { const controller = new AbortController(); const abort = () => controller.abort(); if (externalSignal?.aborted) abort(); externalSignal?.addEventListener('abort', abort, { once: true }); const timer = setTimeout(abort, CONFIG.requestTimeout); try { const response = await fetch(url, { credentials: 'same-origin', cache: 'no-store', redirect: 'error', signal: controller.signal }); if (!response.ok) throw new Error(`Steam 页面读取失败 HTTP ${response.status}`); const doc = new DOMParser().parseFromString(await response.text(), 'text/html'); const node = doc.getElementById('valve-ssr-data'); if (!node) throw new Error('Steam 未返回愿望单数据,请确认已登录并能看到原生列表'); const data = JSON.parse(node.textContent); return parseSnapshot(data, data.UserConfig); } finally { clearTimeout(timer); externalSignal?.removeEventListener('abort', abort); } } async function prepareSnapshot(session) { state.preparing = true; state.prepareController = new AbortController(); setStatus('正在读取当前 Steam 筛选范围…'); syncControls(); try { const snapshot = await readSnapshot(location.href, state.prepareController.signal); if (session !== state.session || state.route !== location.pathname + location.search) return; seed(snapshot, true); collect(); state.ready = true; setStatus('请填写关键词和添加日期区间;日期包含起止当天。'); } catch (error) { if (session === state.session) setStatus(`${error.message};可点击加载按钮重试读取`); } finally { if (session === state.session) { state.preparing = false; state.prepareController = null; syncControls(); } } } function indexMatches(item, f) { if (f.fromDate && (!item.added || item.added < dateBoundary(f.fromDate))) return false; if (f.toDate && (!item.added || item.added >= dateBoundary(f.toDate, true))) return false; return true; } async function loadMatching() { if (!state.root?.isConnected || state.loading || state.preparing || state.busy) return; if (validation()) { setStatus(`${validation()};尚未应用新条件`); return; } const session = state.session; if (!state.ready) { await prepareSnapshot(session); if (!state.ready || session !== state.session) return; } state.appliedFilters = { ...state.filters }; state.selected.clear(); state.dirty = false; state.resultIDs = new Set(Array.from(state.items.values()).filter(item => indexMatches(item, state.appliedFilters)).map(item => item.id)); state.hasResults = true; state.loading = true; state.cancel = false; state.loadStatus = 'loading'; renderResults(); setStatus('正在加载候选游戏详情,并应用筛选条件…'); try { const ids = Array.from(state.resultIDs).filter(id => !state.items.get(id).detail); if (ids.length && !state.context) throw new Error('未识别当前商店地区和语言,无法加载游戏详情'); for (let start = 0; start < ids.length && !state.cancel; start += CONFIG.detailBatch) { if (state.route !== location.pathname + location.search) throw new Error('Steam 原生范围已改变,请关闭后重新打开筛选'); const raws = await requestDetails(ids.slice(start, start + CONFIG.detailBatch)); if (session !== state.session || state.cancel) break; if (state.route !== location.pathname + location.search) throw new Error('Steam 原生范围已改变,已丢弃旧响应'); for (const raw of raws) { const id = String(raw.appid || raw.id); if (raw.success === 1 && state.items.has(id) && !state.removed.has(id)) state.items.set(id, normalizeStoreItem(raw, state.items.get(id))); } renderResults(false); const loaded = Array.from(state.resultIDs).filter(id => state.items.get(id)?.detail).length; setStatus(`候选详情 ${loaded}/${state.resultIDs.size} 项 · 已匹配 ${filtered().length} 项`); if (start + CONFIG.detailBatch < ids.length) await sleep(CONFIG.loadDelay); } if (session !== state.session) return; const missing = Array.from(state.resultIDs).filter(id => !state.items.get(id)?.detail).length; state.loadStatus = state.cancel ? 'cancelled' : missing ? 'partial' : 'complete'; setStatus(`${state.cancel ? '已取消,当前仅显示已加载的匹配结果' : missing ? `仍有 ${missing} 项详情未返回,结果不完整;可重新加载` : '筛选完成'} · 匹配 ${filtered().length} 项`); } catch (error) { if (session === state.session) { state.loadStatus = state.cancel ? 'cancelled' : 'error'; setStatus(state.cancel ? '已取消;仅显示已加载的匹配结果' : `${error.message};当前结果不完整,可重新加载`); } } finally { if (session === state.session) { state.loading = false; renderResults(false); } } } function card(item) { const added = item.added ? new Date(item.added * 1000).toLocaleDateString('zh-CN') : '未知'; return `
${esc(item.name)}
`; } function renderResults(reset = true) { const root = state.root; if (!root?.isConnected) return; if (reset) state.limit = CONFIG.pageSize; const results = filtered(), scroll = root.querySelector('.swh-results-scroll'), top = reset ? 0 : scroll.scrollTop; root.querySelector('[data-results]').innerHTML = `${!results.length ? `

${state.loading ? '正在加载匹配项目…' : '没有已加载且符合条件的项目。'}

` : ''}
${results.slice(0, state.limit).map(card).join('')}
`; scroll.scrollTop = top; root.querySelector('.swh-selection').hidden = !state.hasResults; state.sentinel?.disconnect(); if (typeof IntersectionObserver !== 'undefined') { state.sentinel = new IntersectionObserver(entries => { if (entries.some(entry => entry.isIntersecting) && !state.loading && !state.busy && !state.dirty && state.limit < filtered().length) appendMore(); }, { root: scroll, rootMargin: '150px' }); state.sentinel.observe(root.querySelector('[data-sentinel]')); } updateSelection(); } function appendMore() { if (!state.root?.isConnected || state.loading || state.busy || state.dirty) return; state.limit += CONFIG.pageSize; renderResults(false); } function updateSelection() { if (!state.root) return; const results = filtered(), selected = results.filter(item => state.selected.has(item.id)).length; const all = state.root.querySelector('[data-all]'); all.checked = results.length > 0 && selected === results.length; all.indeterminate = selected > 0 && selected < results.length; for (const box of state.root.querySelectorAll('[data-id]')) { box.checked = state.selected.has(box.dataset.id); box.closest('.swh-card').classList.toggle('swh-selected', box.checked); } state.root.querySelector('[data-selection]').textContent = `匹配 ${results.length} 项 · 已选 ${state.selected.size} 项`; syncControls(); } function observe() { if (state.observer) return; state.observer = new MutationObserver(records => { if (records.every(record => record.target.closest?.('#swh-root,#swh-dialog,#swh-filter-button'))) return; clearTimeout(state.timer); state.timer = setTimeout(() => { if (state.root?.isConnected && state.route !== location.pathname + location.search) closeDialog(false, false); mount(); }, 100); }); state.observer.observe(document.body, { childList: true, subtree: true }); } function main() { if (!/^\/wishlist(?:\/|$)/.test(location.pathname)) return; mount(); observe(); if (!state.menuRegistered) { GM_registerMenuCommand('打开愿望单筛选', () => { mount(); void openDialog(); }); state.menuRegistered = true; } } GM_addStyle(` #swh-filter-button:focus-visible,#swh-root :focus-visible,#swh-dialog :focus-visible { outline:2px solid #66c0f4; outline-offset:3px } #swh-root,#swh-dialog { position:fixed; inset:0; z-index:100000; display:flex; align-items:center; justify-content:center; padding:20px; background:#000b; color:#dcdedf; font:14px/1.5 Arial,"Microsoft YaHei",sans-serif } #swh-dialog { z-index:100002 } #swh-root *,#swh-dialog * { box-sizing:border-box } #swh-root [hidden],#swh-dialog [hidden] { display:none!important } #swh-root .swh-modal { display:flex; flex-direction:column; width:min(940px,100%); max-height:calc(100dvh - 40px); background:#1b2838; border:1px solid #526779; padding:18px; box-shadow:0 12px 48px #0009; overflow:hidden } #swh-root .swh-modal-header { padding:0; background:transparent; font:inherit; display:flex; align-items:center; justify-content:space-between; gap:12px; margin-bottom:10px; flex-shrink:0 } #swh-root h2 { color:#fff; font-size:20px; font-weight:500; margin:0 } #swh-root button,#swh-dialog button { color:#dcdedf; background:linear-gradient(90deg,#354b60,#2b4255); border:1px solid #526779; border-radius:2px; padding:7px 11px; min-height:36px; font:inherit; cursor:pointer } #swh-root button:hover,#swh-dialog button:hover { background:#466781; color:#fff } #swh-root button:disabled,#swh-dialog button:disabled { opacity:.45; cursor:default } #swh-root .swh-danger,#swh-dialog .swh-danger { background:#713b3d; border-color:#b86b6d; color:#fff } #swh-root .swh-danger:hover,#swh-dialog .swh-danger:hover { background:#994c50 } #swh-root .swh-filter-form { display:flex; align-items:flex-end; gap:10px; flex-shrink:0; margin:0; padding:8px 0 12px; border-block:1px solid #3d5060 } #swh-root fieldset { flex:1 1 auto; border:0; margin:0; padding:0; min-width:0; max-height:35dvh; overflow:auto; overscroll-behavior:contain } #swh-root .swh-fields { display:grid; grid-template-columns:minmax(0,1.2fr) repeat(2,minmax(0,1fr)); align-items:end; gap:10px 12px; padding:0 4px 4px } #swh-root .swh-fields label { display:flex; flex-direction:column; gap:4px; min-width:0; color:#c6d4df; font-size:13px } #swh-root input:not([type=checkbox]),#swh-root select { width:100%; min-width:0; max-width:100%; min-height:36px; padding:6px 8px; background:#111d29; border:1px solid #526779; border-radius:2px; color:#fff; font:inherit } #swh-root .swh-form-actions,#swh-root .swh-selection { display:flex; align-items:center; flex-wrap:wrap; gap:8px; padding:10px 0; flex-shrink:0 } #swh-root .swh-form-actions { flex-wrap:nowrap; padding:0 0 4px; white-space:nowrap } #swh-root [data-action=submit] { background:#2b5877; border-color:#5585a5 } #swh-root .swh-feedback { display:flex; align-items:center; flex-wrap:wrap; gap:8px; padding:10px 0 4px; flex-shrink:0; font-size:13px; color:#c6d4df } #swh-root progress { width:100px; height:5px; accent-color:#66c0f4 } #swh-root [data-status] { overflow-wrap:anywhere } #swh-root .swh-selection { border-top:1px solid #3d5060; margin-top:6px } #swh-root [data-selection] { margin-right:auto; color:#b8d8ed; font-size:13px } #swh-root .swh-results-scroll { flex:1 1 auto; min-height:120px; max-height:55dvh; overflow:auto; overscroll-behavior:contain; scrollbar-gutter:stable } #swh-root .swh-card { position:relative; display:grid; grid-template-columns:28px 160px minmax(0,1fr) max-content; align-items:center; gap:12px; margin:6px 0; padding:10px; background:linear-gradient(105deg,#213b51,#1b2c3d); border:1px solid transparent } #swh-root .swh-card.swh-selected { border-color:#66c0f4; background:#25445c } #swh-root .swh-check { display:flex; align-items:center; justify-content:center; min-height:44px; align-self:stretch; cursor:pointer } #swh-root input[type=checkbox],#swh-dialog input[type=checkbox] { width:18px; height:18px; accent-color:#66c0f4; vertical-align:middle; cursor:pointer } #swh-root .swh-cover { position:relative; width:160px; height:75px; background:#14202d; overflow:hidden } #swh-root .swh-cover img { display:block; width:100%; height:100%; object-fit:cover } #swh-root .swh-cover span { position:absolute; inset:0; display:grid; place-items:center; color:#8f9dab; font-size:12px } #swh-root .swh-info { min-width:0 } #swh-root .swh-info a { color:#fff; text-decoration:none; font-size:16px; overflow-wrap:anywhere } #swh-root .swh-info a:hover { color:#66c0f4 } #swh-root .swh-info time { display:block; margin-top:7px; font-size:12px; color:#a8b7c5 } #swh-root .swh-empty { color:#a8b7c5; text-align:center; padding:25px 10px } #swh-root [data-action=more] { width:100%; margin-top:8px } #swh-root [data-sentinel] { height:1px } #swh-dialog .swh-modal { width:min(620px,100%); max-height:90dvh; overflow:auto; padding:24px; background:#1b2838; border:1px solid #526779; box-shadow:0 12px 48px #0009 } #swh-dialog h2 { margin-top:0; color:#fff; font-size:21px } #swh-dialog ul { max-height:30dvh; overflow:auto; padding-left:24px; background:#111d29; overflow-wrap:anywhere } #swh-dialog li { padding:4px } #swh-dialog .swh-modal-actions { display:flex; flex-wrap:wrap; gap:8px; justify-content:flex-end } @media(max-width:640px) { #swh-root,#swh-dialog { padding:10px } #swh-root .swh-modal { padding:12px; max-height:calc(100dvh - 20px) } #swh-root .swh-filter-form { flex-direction:column; align-items:stretch } #swh-root .swh-fields { grid-template-columns:repeat(2,minmax(0,1fr)) } #swh-root .swh-form-actions { flex-wrap:wrap } #swh-root .swh-fields label:first-child { grid-column:1/-1 } #swh-root button,#swh-dialog button { min-height:44px } #swh-root .swh-card { grid-template-columns:minmax(0,1fr); gap:8px; padding:8px } #swh-root .swh-cover { width:100%; height:auto; aspect-ratio:460/215; grid-column:1 } #swh-root .swh-cover img { position:absolute; inset:0 } #swh-root .swh-check { position:absolute; left:14px; top:14px; z-index:2; width:44px; background:#111d29df; border-radius:2px } #swh-root .swh-info { grid-column:1 } #swh-root [data-remove-id] { justify-self:end } #swh-root .swh-selection { gap:6px } #swh-root .swh-selection label { flex:1 1 100% } } `); // SWH_BOOTSTRAP: kept separate for offline tests; no runtime test hooks exposed. if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', main, { once: true }); else main(); })();