HuaRenCa
Back to Forum
Community

CardCenter 增强助手(油猴脚本)

美辰
美辰

1 week ago

本工具是基于两个油猴小脚本:CardCenter / Aligned Incentives 自动隐藏 negative margin/profit 修改后的产物

适用于 CardCenter 的 Deals 和 Rates 页面,主要功能:

自定义 Margin 筛选:在表头输入最低门槛,点击“应用”或按 Enter,保留 Margin 大于或等于该值的报价,并自动记住设置。

点击表头排序:列名旁的箭头支持切换降序、升序和原始顺序。

保留分组:报价按品牌或 Deal 分组,组内同步排序;整组报价均不符合门槛时,隐藏该组标题。

一键恢复排序:点击 ↺ 恢复原始顺序,保留当前筛选条件。

自动更新:页面内容变化后,自动重新筛选和排序。

排序时,组间按符合筛选条件的报价最大值或最小值排列。Margin 为空的报价会隐藏。

脚本只调整本地页面显示,不会自动提交、预订或下单。

效果如下:

// ==UserScript== // @name CardCenter - Deals Margin Filter // @namespace cardcenter-deals-filter // @version 2.3 // @description Margin filter and column sorting for Deals and Rates. // @match https://cardcenter.cc/Deals* // @match https://www.cardcenter.cc/Deals* // @match https://cardcenter.cc/Rates* // @match https://www.cardcenter.cc/Rates* // @run-at document-idle // @grant none // ==/UserScript==

(() => { 'use strict';

const DEFAULT_MIN_MARGIN = -4; const STORAGE_KEY = 'tm-cardcenter-min-margin'; const PANEL_ID = 'tm-cardcenter-margin-panel'; const HIDDEN_CLASS = 'tm-cardcenter-margin-hidden'; const SORT_CLASS = 'tm-cc-sort';

if (document.getElementById(PANEL_ID)) return;

let minMargin = DEFAULT_MIN_MARGIN;

try { const saved = localStorage.getItem(STORAGE_KEY);

if ( saved !== null && saved.trim() && Number.isFinite(Number(saved)) ) { minMargin = Number(saved); } } catch (error) { console.warn('[CardCenter Filter]', error); }

const style = document.createElement('style');

style.textContent = ` .${HIDDEN_CLASS} { display: none !important; }

/* 保持列名和排序箭头在同一行,并统一垂直对齐。 */ table > thead > tr > th { white-space: nowrap !important; vertical-align: middle !important; }

.${SORT_CLASS} { display: inline-flex !important; align-items: center; justify-content: center; vertical-align: middle !important; box-sizing: border-box; width: 22px; height: 24px; margin-left: 5px; padding: 0; border: 1px solid #788390; border-radius: 4px; background: transparent; color: inherit; font: inherit; font-size: 12px; line-height: 1 !important; cursor: pointer; }

.${SORT_CLASS}[data-active="true"] { background: #2563eb; border-color: #2563eb; color: #fff; }

/* 箭头通过 CSS 显示,不进入表头 textContent。 */ .${SORT_CLASS}::after { content: attr(data-symbol); }

.tm-cc-margin-heading { white-space: nowrap; }

#${PANEL_ID} { display: inline-flex; position: static; vertical-align: middle; align-items: center; gap: 4px; margin-left: 8px; padding: 0; border: 0; background: transparent; color: inherit; font: 12px/1.5 Arial, sans-serif; font-weight: normal; white-space: nowrap; }

#${PANEL_ID} input { width: 64px; min-width: 0; box-sizing: border-box; height: 26px; padding: 2px 4px; border: 1px solid #87919c; border-radius: 4px; background: transparent; color: inherit; font: inherit; }

#${PANEL_ID} button { height: 26px; padding: 2px 6px; border: 0; border-radius: 4px; background: #2563eb; color: #fff; font: inherit; cursor: pointer; }

#${PANEL_ID} .tm-reset { background: #495057; }

#${PANEL_ID} button::after, #${PANEL_ID} .tm-ui-label::after { content: attr(data-ui); }

.tm-cc-announcement { position: absolute; width: 1px; height: 1px; padding: 0; overflow: hidden; clip-path: inset(50%); white-space: nowrap; } `;

document.head.appendChild(style);

const panel = document.createElement('span');

panel.id = PANEL_ID; panel.setAttribute('role', 'group'); panel.setAttribute('aria-label', '最低 Margin 筛选与排序');

// 表头内的文字由 CSS 显示,避免污染网站的 data-label。 panel.innerHTML = ` <span class="tm-ui-label" data-ui="≥" aria-hidden="true"

</span>

<input id="tm-cardcenter-margin-input" type="number" step="any" required aria-label="最低 Margin 百分比" title="最低 Margin,包含等于;按 Enter 应用"

<span class="tm-ui-label" data-ui="%" aria-hidden="true"

</span>

<button type="button" class="tm-apply" data-ui="应用" aria-label="应用 Margin 筛选" title="应用最低 Margin"

</button>

<button type="button" class="tm-reset" data-ui="↺" aria-label="恢复原始排序" title="恢复原始排序"

</button>

`;

const input = panel.querySelector('input');

const status = document.createElement('span'); status.className = 'tm-cc-announcement'; status.setAttribute('aria-live', 'polite'); document.body.appendChild(status);

panel.addEventListener('click', event => { event.stopPropagation(); });

input.value = String(minMargin);

const states = new WeakMap(); const order = new WeakMap();

let nextOrder = 0;

function originalOrder(node) { if (!node) return Number.MAX_SAFE_INTEGER;

if (!order.has(node)) { order.set(node, nextOrder++); }

return order.get(node); }

// 兼容旧版箭头被网站复制进 data-label 的情况。 const normalize = text => text .replace(/[↕↑↓⇅▲▼]/g, '') .replace(/\s+/g, ' ') .trim() .toLowerCase();

const normalizeSigns = text => text .replace(/\u00a0/g, ' ') .replace(/[−–﹣-]/g, '-') .trim();

function parsePercent(text) { const match = normalizeSigns(text).match( /(()?\s*([+-]?)\s*(\d+(?:,\d{3})(?:.\d+)?|.\d+)\s%\s*())?/ );

if (!match) return null;

const value = Number(match[3].replace(/,/g, ''));

const negative = match[2] === '-' || Boolean(match[1] && match[4]);

return negative ? -value : value; }

function columnKey(th) { const clone = th.cloneNode(true);

clone .querySelectorAll('.' + SORT_CLASS + ', #' + PANEL_ID) .forEach(element => element.remove());

return normalize(clone.textContent); }

function cellFor(row, key, columns) { const cells = Array.from(row.cells);

const labelled = cells.find(cell => normalize(cell.getAttribute('data-label') || '') === key );

if (labelled) return labelled;

// 已有 data-label 时,不用列序号猜测缺失的列。 if (cells.some(cell => cell.hasAttribute('data-label'))) { return null; }

return row.cells[columns.indexOf(key)] || null; }

function valueFor(row, key, columns) { const text = normalizeSigns( cellFor(row, key, columns)?.textContent || '' );

if (!text) return null;

if (['margin', 'you pay', 'we pay'].includes(key)) { return parsePercent(text); }

if (['brand', 'deal'].includes(key)) { return normalize(text); }

if ( key === 'available cap' && /^(none left|expired)$/i.test(text) ) { return null; }

if (key === 'submission deadline') { const relative = text.match( /^(\d+(?:.\d+)?)\s*(hours?|days?|weeks?)\s+after\s+approval/i );

if (!relative) return null;

const factor = /^hour/i.test(relative[2]) ? 1 / 24 : /^week/i.test(relative[2]) ? 7 : 1;

return Number(relative[1]) * factor; }

// 面额范围取下限;额度取括号前的总额度。 const match = text.match( /^[^\d+-]([+-]?(?:\d[\d,](?:.\d+)?|.\d+))\s*([kKmM])?/ );

if (!match) return null;

const multiplier = match[2] ? match[2].toLowerCase() === 'k' ? 1000 : 1000000 : 1;

return Number(match[1].replace(/,/g, '')) * multiplier; }

function compareValues(a, b, direction) { if (a === null && b === null) return 0; if (a === null) return 1; if (b === null) return -1;

const comparison = typeof a === 'string' ? a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' }) : a - b;

return comparison * direction; }

function isHeader(row) { return Array.from(row.cells).some(cell => cell.colSpan > 1 ); }

function groupsFor(table) { const groups = []; const bodies = Array.from(table.tBodies);

const splitBodies = bodies.some(body => body.classList.contains('table-stacked-child') );

if (splitBodies) { // Rates:品牌标题和每条报价分别位于独立 tbody。 let group = null;

for (const body of bodies) { originalOrder(body);

if (!body.classList.contains('table-stacked-child')) { group = { node: body, header: body.rows[0], entries: [], split: true };

groups.push(group); } else { if (!group) { group = { node: null, header: null, entries: [], split: true };

groups.push(group); }

if (body.rows[0]) { group.entries.push({ node: body, row: body.rows[0] }); } } } } else { // Deals:一个 tbody 包含标题行及报价行。 for (const body of bodies) { originalOrder(body);

const rows = Array.from(body.rows); const header = rows.find(isHeader) || null;

const entries = rows .filter(row => !isHeader(row) && !row.querySelector('th') ) .map(row => { originalOrder(row); return { node: row, row }; });

groups.push({ node: body, header, entries, split: false }); } }

return groups; }

function reorder(parent, desired) { const selected = new Set(desired);

const current = Array.from(parent.children).filter(node => selected.has(node) );

if ( !current.length || current.every((node, index) => node === desired[index]) ) { return; }

const anchor = current[current.length - 1].nextSibling;

desired.forEach(node => { parent.insertBefore(node, anchor); }); }

function prepareTable(table) { const header = table.querySelector('thead tr'); if (!header) return null;

const columns = Array.from(header.cells).map(columnKey); if (!columns.includes('margin')) return null;

if (!states.has(table)) { states.set(table, { key: null, direction: -1 }); }

const state = states.get(table);

Array.from(header.cells).forEach((th, index) => { const key = columns[index]; if (!key) return;

let button = th.querySelector('.' + SORT_CLASS);

if (!button) { button = document.createElement('button'); button.type = 'button'; button.className = SORT_CLASS;

button.addEventListener('click', event => { event.preventDefault(); event.stopPropagation();

if (state.key !== key) { state.key = key; state.direction = -1; } else if (state.direction === -1) { state.direction = 1; } else { state.key = null; }

refresh(); });

th.appendChild(button); }

const active = state.key === key;

// 保持按钮 textContent 为空,箭头由 CSS 显示。 if (button.textContent) { button.textContent = ''; }

button.dataset.symbol = active ? state.direction === -1 ? '↓' : '↑' : '↕';

button.dataset.active = String(active); button.title = key + ':点击切换降序 / 升序 / 原始顺序'; button.setAttribute('aria-label', key + ' 排序');

th.setAttribute( 'aria-sort', active ? state.direction === -1 ? 'descending' : 'ascending' : 'none' );

// 把最低 Margin 控件放在列名旁边。 if (key === 'margin') { th.classList.add('tm-cc-margin-heading');

if (panel.parentElement !== th) { th.appendChild(panel); } } });

return { columns, state }; }

function processTable(table, columns, state) { const groups = groupsFor(table);

let total = 0; let shown = 0;

for (const group of groups) { let anyVisible = false;

for (const entry of group.entries) { total++;

const margin = parsePercent( cellFor(entry.row, 'margin', columns)?.textContent || '' );

entry.visible = margin !== null && margin >= minMargin;

entry.node.classList.toggle( HIDDEN_CLASS, !entry.visible );

if (entry.visible) { shown++; anyVisible = true; } }

if (group.header) { group.header.classList.toggle( HIDDEN_CLASS, !anyVisible ); }

if (group.node) { group.node.classList.toggle( HIDDEN_CLASS, !anyVisible ); }

group.entries.sort((a, b) => { if (!state.key) { return originalOrder(a.node) - originalOrder(b.node); }

return compareValues( valueFor(a.row, state.key, columns), valueFor(b.row, state.key, columns), state.direction ) || originalOrder(a.node) - originalOrder(b.node); });

if (!group.split && group.node) { reorder( group.node, group.entries.map(entry => entry.node) ); }

const candidates = group.entries .filter(entry => entry.visible) .map(entry => valueFor(entry.row, state.key, columns) ) .filter(value => value !== null);

candidates.sort((a, b) => compareValues(a, b, state.direction) );

group.score = candidates.length ? candidates[0] : null; }

groups.sort((a, b) => { const ordinal = originalOrder(a.node || a.entries[0]?.node) - originalOrder(b.node || b.entries[0]?.node);

return state.key ? compareValues(a.score, b.score, state.direction) || ordinal : ordinal; });

const desired = groups.flatMap(group => group.split ? [ ...(group.node ? [group.node] : []), ...group.entries.map(entry => entry.node) ] : [group.node] );

reorder(table, desired);

return { total, shown }; }

let timer;

const observer = new MutationObserver(mutations => { if ( mutations.every(mutation => panel.contains(mutation.target) ) ) { return; }

clearTimeout(timer); timer = setTimeout(refresh, 100); });

function refresh() { clearTimeout(timer);

// 排序期间暂停观察,避免脚本自身触发循环。 observer.disconnect();

let total = 0; let shown = 0;

try { for (const table of document.querySelectorAll('table')) { const meta = prepareTable(table); if (!meta) continue;

const counts = processTable( table, meta.columns, meta.state );

total += counts.total; shown += counts.shown; }

status.textContent = Margin ≥ ${minMargin}% · 显示 ${shown} / ${total} 条;

panel.title = status.textContent; } catch (error) { status.textContent = '处理失败,请查看控制台。'; panel.title = status.textContent; console.error('[CardCenter Filter]', error); } finally { observer.observe(document.body, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ['data-label'] }); } }

function applySettings() { if ( !input.reportValidity() || !Number.isFinite(input.valueAsNumber) ) { return; }

minMargin = input.valueAsNumber;

try { localStorage.setItem(STORAGE_KEY, String(minMargin)); } catch (error) { console.warn('[CardCenter Filter]', error); }

refresh(); }

panel .querySelector('.tm-apply') .addEventListener('click', applySettings);

input.addEventListener('keydown', event => { if (event.key === 'Enter') { event.preventDefault(); applySettings(); } });

panel .querySelector('.tm-reset') .addEventListener('click', () => { document.querySelectorAll('table').forEach(table => { const state = states.get(table);

if (state) { state.key = null; } });

refresh(); });

refresh(); })();

CardCenter 增强助手(油猴脚本)

5
1.7K

Comments (5)

Your avatar
Sign in to comment
任城东
任城东1 week ago

保守の観点から言うと、まずスクリプトにバージョン番号と更新履歴のコメントブロックを追加し、その後でフィルタリングのしきい値を複数のプリセット値にすることを検討するのがよいでしょう。そうすれば、後でコードを変更したりデバイスを替えたりするときにも、どのバージョンが動いているのかを自分で素早く確認できます。

nihao997847
nihao9978471 week ago

ブラウザやユーザースクリプトマネージャーによって localStorage や @match の対応状況は異なるため、環境を変える前にまず小規模な範囲で試すことをおすすめします。

深圳门窗人
深圳门窗人1 week ago

前提を確認したいのですが、スクリプトはヘッダー文字と data-label で列を特定しています。もし CardCenter の改版で列名が略称に変わったり、同じ表に同名の Margin 列が2つ現れたりした場合、現在の columnKey と cellFor はどう処理しますか?列全体の値が取得できず、フィルタがそのまま機能しなくなるようなことはありますか?

不废话
不废话1 week ago

自動更新の部分については、少し懸念があります。ページ内容が変わるたびに再フィルタリングと並べ替えが行われると、CardCenter 自体も動的に更新されている場合、頻繁な再配置によって閲覧中の行が飛んでしまったり、サイト自身の並べ替えと競合する可能性があります。スロットリングを追加するか、ヘッダーが変化したときだけトリガーすることをおすすめします。

优米
优米1 week ago

デフォルト値の-4と空のMarginでこの2点がそのまま非表示になるのはかなり重要で、つまりデフォルトで見積もりの一部が隠されているのと同じです。