Thanks for your efforts, this is reflected in the latest version of the script, namely 8.0.0. It sure works much faster now.
// ==UserScript==
// @name BitcoinTalk Merit History Plotter 8.0.0
// @namespace https://bitcointalk.org/
// @version 8.0.0
// @description Plot a bitcointalk.org user's received-merit history in a single chart, switchable between By day By Month By last 120 days By last 240 days By last 360 days, combining loyce.club's history with any newer days on bitcointalk.org's own merit page (including entries shown as "Today"/"Yesterday" instead of a full date), with the account's real username (from its bitcointalk.org profile) shown alongside its ID
// @author satscraper
// @match https://bitcointalk.org/*
// @grant GM_xmlhttpRequest
// @grant GM_registerMenuCommand
// @connect loyce.club
// @run-at document-idle
// ==/UserScript==
//
// Credits:
// theymos - administrator of bitcointalk.org and creator its Merit system, the data this script visualizes
// LoyceV - creator of loyce.club, the merit-history archive this script reads from
// Claude - Anthropic's AI assistant, used to help write this script
(function () {
'use strict';
const BTN_ID = 'merit-plotter-btn';
// Escapes a string for safe interpolation as HTML text content. Used
// wherever data read from a remote page (username, etc.) is written into
// the generated plot tab's markup \u2014 remote-sourced strings are never
// trusted at the point they're turned into HTML, regardless of any
// upstream regex constraints already applied when extracting them.
function escapeHtml(str) {
return String(str)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
// ---------- UI ----------
function createButton() {
if (document.getElementById(BTN_ID)) return;
const btn = document.createElement('button');
btn.id = BTN_ID;
btn.textContent = 'Plot Merit History';
btn.style.cssText = [
'position:fixed', 'bottom:20px', 'right:20px', 'z-index:999999',
'padding:10px 14px', 'background:#f7931a', 'color:#fff', 'border:none',
'border-radius:6px', 'font-size:14px', 'font-family:sans-serif',
'cursor:pointer', 'box-shadow:0 2px 6px rgba(0,0,0,.35)'
].join(';');
btn.addEventListener('click', onButtonClick);
document.body.appendChild(btn);
}
function guessUserIdFromPage() {
// Works when currently viewing a profile: index.php?action=profile;u=NNN
const m = location.href.match(/[?;&]u=(\d+)/);
return m ? m[1] : '';
}
function onButtonClick() {
const guess = guessUserIdFromPage();
const id = prompt(
'Enter the bitcointalk.org User ID (the numeric "u=" value from a profile URL, e.g. 3442679):',
guess || ''
);
if (id === null) return;/ cancelled
const trimmed = id.trim();
if (!/^\d+$/.test(trimmed)) {
alert('Please enter a numeric user ID, e.g. 3442679');
return;
}
fetchAndPlot(trimmed);
}
// ---------- Data fetching ----------
// Two sources are combined:
// 1) loyce.club/Merit/merit.all/<id>.txt \u2014 loyce.club's per-user slice of
// its merit.all dump (space-separated: unix time, amount, topic.msg id,
// sender user id, receiver user id). Only the lines whose receiver is
// the requested user id are kept, so any merit the user sent is
// ignored.
// 2) bitcointalk.org's own index.php?action=merit;u=<id> page \u2014 only the
// last 120 days, but always current. Same-origin, so a plain fetch()
// works with the signed-in session automatically, no CORS/GM grant
// needed, and it's also where we read the account's real username.
//
// Only bitcointalk.org entries dated AFTER loyce.club's most recent date are
// appended \u2014 anything on or before that cutoff day is discarded outright,
// rather than trying to de-duplicate by matching timestamps. An earlier
// version tried exact timestamp+sender+amount matching, but bitcointalk.org
// displays times in each viewer's own forum timezone setting while
// loyce.club gives unix timestamps, so the same transaction can carry two
// different clock times across the two sources \u2014 exact-time matching
// then fails to recognize it as a duplicate and double-counts it. A plain
// date cutoff (loyce.club's last calendar day and everything on/before it is
// never touched) sidesteps that entirely.
function fetchLoyceHistory(userId) {
return new Promise((resolve, reject) => {
GM_xmlhttpRequest({
method: 'GET',
url: 'https://loyce.club/Merit/merit.all/' + encodeURIComponent(userId) + '.txt',
onload: function (res) {
if (res.status !== 200) {
reject(new Error('loyce.club HTTP ' + res.status));
return;
}
try {
resolve(parseMeritUserFile(res.responseText, userId));
} catch (e) {
reject(e);
}
},
onerror: function () {
reject(new Error('loyce.club network error'));
}
});
});
}
function fetchBitcointalkMeritPage(userId) {
const url = `https://bitcointalk.org/index.php?action=merit;u=${userId}`;
return fetch(url, { credentials: 'same-origin' })
.then(res => {
if (!res.ok) throw new Error('bitcointalk.org merit page HTTP ' + res.status);
return res.text();
})
.then(html => parseBitcointalkMeritPage(html));
}
function fetchBitcointalkUsername(userId) {
// The merit page's own title doesn't reliably contain the username, so the
// profile page is used instead \u2014 its title is a fixed, confirmed SMF
// string: "... - View the profile of <username>".
const url = `https://bitcointalk.org/index.php?action=profile;u=${userId}`;
return fetch(url, { credentials: 'same-origin' })
.then(res => {
if (!res.ok) throw new Error('bitcointalk.org profile page HTTP ' + res.status);
return res.text();
})
.then(html => {
const m = html.match(/<title>[^<]*?View the profile of\s+([^<]+?)\s*<\/title>/i);
return m ? m[1].trim() : null;
});
}
function startOfNextDay(d) {
return new Date(d.getFullYear(), d.getMonth(), d.getDate() + 1, 0, 0, 0);
}
function mergeReceived(loyceReceived, btReceived) {
// loyceReceived is sorted ascending, so the last entry is the most recent
// date loyce.club has for this user.
const lastLoyceDate = loyceReceived.length ? loyceReceived[loyceReceived.length - 1].date : null;
const cutoff = lastLoyceDate ? startOfNextDay(lastLoyceDate) : null;
const appendedRecords = cutoff ? btReceived.filter(r => r.date >= cutoff) : btReceived.slice();
const discardedCount = btReceived.length - appendedRecords.length;
const merged = loyceReceived.concat(appendedRecords).sort((a, b) => a.date - b.date);
return {
merged,
appended: appendedRecords.length,
discarded: discardedCount,
cutoffDate: cutoff
};
}
function fetchAndPlot(userId) {
Promise.all([
fetchLoyceHistory(userId).catch(e => {
console.warn('[Merit Plotter] loyce.club fetch/parse failed:', e);
return { received: [], totalLines: 0, otherLines: 0, badLines: 0 };
}),
fetchBitcointalkMeritPage(userId).catch(e => {
console.warn('[Merit Plotter] bitcointalk.org merit page fetch/parse failed:', e);
const empty = [];
empty.candidateLines = 0;
empty.username = null;
return empty;
}),
fetchBitcointalkUsername(userId).catch(e => {
console.warn('[Merit Plotter] bitcointalk.org profile page fetch failed:', e);
return null;
})
]).then(([loyceParsed, btReceived, profileUsername]) => {
const { merged, appended, discarded, cutoffDate } = mergeReceived(loyceParsed.received, btReceived);
const computedSum = merged.reduce((s, r) => s + r.merit, 0);
const loyceReceivedSum = loyceParsed.received.reduce((s, r) => s + r.merit, 0);
const lastLoyce = loyceParsed.received.length ? loyceParsed.received[loyceParsed.received.length - 1] : null;
const diagnostics = {
loyceTotalLines: loyceParsed.totalLines || 0,
loyceReceivedCount: loyceParsed.received.length,
loyceOtherLines: loyceParsed.otherLines || 0,
loyceBadLines: loyceParsed.badLines || 0,
loyceReceivedSum,
loyceLastDate: lastLoyce ? lastLoyce.dateText : '(none)',
cutoffDate: cutoffDate ? cutoffDate.toDateString() : '(no loyce data, no cutoff applied)',
btCandidateLines: btReceived.candidateLines || 0,
btReceivedCount: btReceived.length,
btReceivedSum: btReceived.reduce((s, r) => s + r.merit, 0),
appended,
discarded,
computedSum
};
console.log('[Merit Plotter] diagnostics:', diagnostics);
if (!merged.length) {
alert('No received-merit records were found for that user ID from either source. Double-check the ID, and that you\u2019re logged in to bitcointalk.org.');
return;
}
const username = profileUsername || btReceived.username || null;
openPlotTab(userId, { received: merged, diagnostics, username });
});
}
// ---------- Parsing ----------
// loyce.club/Merit/merit.all/<id>.txt: one merit transaction per line,
// space-separated:
// <unix time> <amount> <topic.msgNNN> <sender user id> <receiver user id>
// e.g. 1789699495 1 5376945.msg67512515 252510 3742576
// Only lines whose receiver column is the requested id count as received
// merit; everything else in the file is counted and ignored. No thread
// titles or usernames are in these lines, so records carry the topic id
// instead of a subject. Lines that don't fit this layout are counted as
// failed (shown in the diagnostics panel) rather than silently dropped.
function parseMeritUserFile(text, userId) {
const received = [];
let totalLines = 0;
let otherLines = 0;
let badLines = 0;
const lines = text.split('\n');
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
if (!line) continue;
totalLines++;
const parts = line.split(/[ \t]+/);
const time = parseInt(parts[0], 10);
const amount = parseInt(parts[1], 10);
if (parts.length < 5 || !isFinite(time) || !isFinite(amount)) {
badLines++;
continue;
}
if (parts[4] !== userId) {
otherLines++;
continue;
}
const date = new Date(time * 1000);
const topicMatch =^(\d+)\./.exec(parts[2]);
received.push({
date,
merit: amount,
dateText: date.toLocaleString(),
otherUser: parts[3],
topicId: topicMatch ? topicMatch[1] : null,
subject: null
});
}
if (totalLines === 0) throw new Error('merit.all/' + userId + '.txt was empty');
received.sort((a, b) => a.date - b.date);
return { received, totalLines, otherLines, badLines };
}
// bitcointalk.org's own action=merit page format (only covers the last 120 days
const BT_MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const BT_LINE_RE =(?:([A-Za-z]+)\s+(\d{1,2}),\s+(\d{4})|(Today|Yesterday))(?:\s+at)?,?\s+(\d{1,2}):(\d{2}):(\d{2})\s+(AM|PM):\s*(\d+)\s+from\s+(.+?)\s+for\s+([^\n\r]*)/g;
function parseBtDate(monthName, day, year, relativeWord, hh, mm, ss, ampm) {
let hour = parseInt(hh, 10) % 12;
if (ampm.toUpperCase() === 'PM') hour += 12;
const minute = parseInt(mm, 10);
const second = parseInt(ss, 10);
if (monthName) {
const monthIdx = BT_MONTHS.indexOf(monthName);
if (monthIdx === -1) return null;
const d = new Date(parseInt(year, 10), monthIdx, parseInt(day, 10), hour, minute, second);
return isNaN(d.getTime()) ? null : d;
}
// "Today" "Yesterday": relative to the actual current date this script
// is running on (the date the page itself was generated for).
const base = new Date();
if (relativeWord.toLowerCase() === 'yesterday') base.setDate(base.getDate() - 1);
const d = new Date(base.getFullYear(), base.getMonth(), base.getDate(), hour, minute, second);
return isNaN(d.getTime()) ? null : d;
}
function extractReceivedSectionText(text) {
const headingRe =(Received|Sent)\s+in\s+the\s+last\s+\d+\s+days/gi;
const marks = [];
let hm;
while ((hm = headingRe.exec(text)) !== null) {
marks.push({ type: hm[1].toLowerCase(), index: hm.index, end: headingRe.lastIndex });
}
if (!marks.length) return text;/ unknown layout: best effort, scan everything
let combined = '';
for (let i = 0; i < marks.length; i++) {
if (marks[i].type !== 'received') continue;
const start = marks[i].end;
const end = i + 1 < marks.length ? marks[i + 1].index : text.length;
combined += text.slice(start, end) + '\n';
}
return combined;
}
function extractUsernameFromMeritPage(html) {
// Try the <title> tag first: typically something like
// "Bitcoin Forum - Merit for <username>" or similar phrasing.
let m = html.match(/<title>([^<]*)<\/title>/i);
if (m) {
const t = m[1];
const nm = t.match(/merit\s+for\s+(.+?)\s*$/i);
if (nm) return nm[1].trim();
}
// Fallback: the phrase "Merit for X" appearing anywhere on the page,
// e.g. as a heading above the Received/Sent sections.
m = html.match(/merit\s+for\s+([^<\r\n]{1,60}?)(?:\s*<|\r|\n)/i);
if (m) return m[1].trim();
// Fallback: og:title meta tag.
m = html.match(/<meta[^>]+property=["']og:title["'][^>]+content=["']([^"'<]+)["']/i);
if (m) {
const name = m[1].replace(/merit\s+for\s+/i, '').trim();
if (name) return name;
}
return null;
}
function parseBitcointalkMeritPage(html) {
const normalized = html
.replace(/<br\s*\/?>/gi, '\n')
.replace(/<\/(p|div|li|tr)>/gi, '\n');
const doc = new DOMParser().parseFromString(normalized, 'text/html');
const text = doc.body ? doc.body.textContent : normalized.replace(/<[^>]+>/g, '');
const scanText = extractReceivedSectionText(text);
// Diagnostic: candidate lines (start with a date-looking prefix, either
// absolute or the "Today"/"Yesterday" relative form) vs successfully
// parsed ones.
const candidateLines = (scanText.match(/(?:[A-Za-z]+\s+\d{1,2},\s+\d{4}|Today|Yesterday)(?:\s+at)?,?\s+\d{1,2}:\d{2}:\d{2}\s+(AM|PM)/g) || []).length;
const records = [];
let m;
BT_LINE_RE.lastIndex = 0;
while ((m = BT_LINE_RE.exec(scanText)) !== null) {
const [, monthName, day, year, relativeWord, hh, mm, ss, ampm, amountStr, sender, subject] = m;
const date = parseBtDate(monthName, day, year, relativeWord, hh, mm, ss, ampm);
const merit = parseFloat(amountStr);
if (!date || isNaN(merit)) continue;
records.push({ date, merit, otherUser: sender.trim(), subject: subject.trim() });
}
records.candidateLines = candidateLines;/ stowed on the array for convenience
records.username = extractUsernameFromMeritPage(html);
return records;
}
// ---------- Aggregation ----------
const MONTH_NAMES = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
function aggregateByDay(records) {
const map = new Map();/ "YYYY-MM-DD" -> { date, total, count }
for (const r of records) {
const d = r.date;
const key = d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');
let entry = map.get(key);
if (!entry) {
entry = { date: new Date(d.getFullYear(), d.getMonth(), d.getDate()), total: 0, count: 0 };
map.set(key, entry);
}
entry.total += r.merit;
entry.count += 1;
}
return Array.from(map.values()).sort((a, b) => a.date - b.date);
}
function aggregateByMonth(records) {
const map = new Map();/ "YYYY-MM" -> { date, total, count }
for (const r of records) {
const d = r.date;
const key = d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0');
let entry = map.get(key);
if (!entry) {
entry = { date: new Date(d.getFullYear(), d.getMonth(), 1), total: 0, count: 0 };
map.set(key, entry);
}
entry.total += r.merit;
entry.count += 1;
}
return Array.from(map.values()).sort((a, b) => a.date - b.date);
}
function formatDay(d) {
return String(d.getDate()).padStart(2, '0') + ' ' + MONTH_NAMES[d.getMonth()] + ' ' + d.getFullYear();
}
function formatMonth(d) {
return MONTH_NAMES[d.getMonth()] + ' ' + d.getFullYear();
}
function aggregateByThread(records) {
// Groups by subject text (with a leading "Re: " stripped), since neither
// data source exposes a thread id or URL \u2014 the subject line is the
// closest thing we have to a thread identity. Two distinct threads that
// happen to share an identical title will be merged; that's a known
// limitation, not a bug.
const map = new Map();/ grouping key -> { subject (display form), total, count, url }
for (const r of records) {
let subject = (r.subject || '').trim().replace(/^Re:\s*/i, '').trim();
let key;
let url = null;
if (!subject && r.topicId) {
// loyce.club's merit.all lines have topic ids but no titles.
key = 'topic:' + r.topicId;
subject = 'Topic #' + r.topicId;
url = 'https://bt.irlbtc.com/view/' + r.topicId;
} else {
if (!subject) subject = '(no subject)';
key = 'subject:' + subject.toLowerCase();
}
let entry = map.get(key);
if (!entry) {
entry = { subject, total: 0, count: 0, url };
map.set(key, entry);
}
entry.total += r.merit;
entry.count += 1;
}
return Array.from(map.values()).sort((a, b) => b.total - a.total);
}
function toSeries(records, aggregateFn, formatFn) {
const buckets = aggregateFn(records);
return {
labels: buckets.map(b => formatFn(b.date)),
perEvent: buckets.map(b => b.total),
tooltips: buckets.map(b => b.count + ' merit event' + (b.count > 1 ? 's' : ''))
};
}
// ---------- Plot tab ----------
function windowRecords(records, days) {
if (days == null) return records;/ no filtering
const cutoff = new Date(Date.now() - days * 24 * 60 * 60 * 1000);
return records.filter(r => r.date >= cutoff);
}
// Exactly six view modes, switched by their own button \u2014 all rendered
// into the same single chart area rather than separate sections.
const MODE_DEFS = [
{ key: 'daily', label: 'By day', days: null, aggregate: aggregateByDay, format: formatDay },
{ key: 'monthly', label: 'By Month', days: null, aggregate: aggregateByMonth, format: formatMonth },
{ key: 'last120', label: 'By last 120 days', days: 120, aggregate: aggregateByDay, format: formatDay },
{ key: 'last240', label: 'By last 240 days', days: 240, aggregate: aggregateByDay, format: formatDay },
{ key: 'last360', label: 'By last 360 days', days: 360, aggregate: aggregateByDay, format: formatDay }
];
// Dates the all-time running total first reached each multiple of 1,000
// merit. Always computed on the full merged history (not the window), so a
// flag in a "last N days" view still means "all-time total crossed X here".
const MILESTONE_STEP = 1000;
function computeMilestones(records) {
const sorted = records.slice().sort((a, b) => a.date - b.date);
const out = [];
let cum = 0;
let next = MILESTONE_STEP;
for (const r of sorted) {
cum += r.merit;
while (cum >= next) {
out.push({ value: next, date: r.date });
next += MILESTONE_STEP;
}
}
return out;
}
function calendarDaysBetween(a, b) {
const da = new Date(a.getFullYear(), a.getMonth(), a.getDate());
const db = new Date(b.getFullYear(), b.getMonth(), b.getDate());
return Math.round((db - da) 86400000);/ rounding absorbs DST hour shifts
}
function buildModes(receivedRecords) {
const modes = {};
const milestones = computeMilestones(receivedRecords);
for (const m of MODE_DEFS) {
const recs = windowRecords(receivedRecords, m.days);
const series = toSeries(recs, m.aggregate, m.format);
modes[m.key] = {
label: m.label,
labels: series.labels,
perEvent: series.perEvent,
tooltips: series.tooltips,
total: recs.reduce((s, r) => s + r.merit, 0),
milestones: []
};
// Pin each milestone to the chart bucket (day or month) containing its
// date; ones outside this view's window simply have no bucket.
// Also carries the all-time gap (in calendar days) to the previous
// milestone and that milestone's bucket in this view (-1 if it falls
// outside the window), so the chart can draw a measured span between
// two flags only when both are visible.
milestones.forEach((ms, i) => {
const idx = series.labels.indexOf(m.format(ms.date));
if (idx === -1) return;
const prev = i > 0 ? milestones[i - 1] : null;
modes[m.key].milestones.push({
index: idx,
label: ms.value.toLocaleString('en-US'),
dateText: formatDay(ms.date),
prevIndex: prev ? series.labels.indexOf(m.format(prev.date)) : -1,
prevLabel: prev ? prev.value.toLocaleString('en-US') : null,
prevDateText: prev ? formatDay(prev.date) : null,
daysSincePrev: prev ? calendarDaysBetween(prev.date, ms.date) : null
});
});
}
// Sixth mode: all-time, grouped by thread instead of by date. Kept
// outside the loop above since it doesn't fit the date-bucket shape the
// other five share (no window filtering \u2014 always all-time, per your
// call to keep it consistent with By day By Month).
const threads = aggregateByThread(receivedRecords);
modes.thread = {
label: 'By thread',
threads,
total: threads.reduce((s, t) => s + t.total, 0)
};
return modes;
}
function openPlotTab(userId, parsed) {
const win = window.open('', '_blank');
if (!win) {
alert('Popup blocked \u2014 please allow popups for bitcointalk.org and click the button again.');
return;
}
const modes = buildModes(parsed.received);
const payload = {
modes,
receivedTotal: modes.daily.total,/ all-time total, for the headline
diagnostics: parsed.diagnostics,
username: parsed.username || null
};
win.document.open();
win.document.write(buildPlotHtml(userId, payload));
win.document.close();
}
function buildPlotHtml(userId, payload) {
const dataJson = JSON.stringify(payload).replace(/</g, '\\u003c');/ avoid premature </script>
const rawDisplayName = 'user ' + userId + (payload.username ? ' (' + payload.username + ')' : '');
// Defense in depth: userId is always numeric (validated on input) and the
// username is regex-constrained not to contain "<" at extraction time,
// but this is escaped again here too since it's about to be interpolated
// as raw HTML text (in <title> and <h1>) \u2014 never trust a remote-sourced
// string at the point it's written into markup, regardless of what
// upstream validation already did.
const displayName = escapeHtml(rawDisplayName);
return `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Merit history \u2014 ${displayName}</title>
<style>
body { font-family: -apple-system, Segoe UI, Roboto, sans-serif; background:#111; color:#eee; margin:0; padding:24px; }
h1 { font-size:18px; font-weight:600; margin:0 0 4px; }
#wrap { max-width:1000px; margin:0 auto; }
.meta { color:#999; font-size:13px; margin-bottom:16px; }
details.diag { margin-bottom:16px; font-size:12px; color:#aaa; }
details.diag summary { cursor:pointer; color:#f7931a; }
details.diag table { border-collapse:collapse; margin-top:8px; }
details.diag td { padding:2px 10px 2px 0; }
details.diag .warn { color:#ff8080; font-weight:600; }
details.diag .ok { color:#7dd87d; }
.toggle { margin-bottom:16px; }
.toggle button { background:#222; color:#ccc; border:1px solid #444; padding:8px 14px; font-size:13px; cursor:pointer; border-radius:6px; margin-right:8px; }
.toggle button.active { background:#f7931a; color:#111; border-color:#f7931a; font-weight:600; }
.chart-box { background:#1b1b1b; border-radius:8px; padding:16px 16px 8px; margin-bottom:28px; overflow-x:auto; position:relative; }
.total-badge { position:sticky; left:8px; display:inline-block; background:#1b1b1b; border:2px solid #f7931a; border-radius:6px; padding:6px 12px; font-size:13px; font-weight:700; color:#f7931a; margin-bottom:10px; }
svg { display:block; }
.line-path { fill:none; stroke:#4dabf7; stroke-width:2; }
.line-area { fill:rgba(77,171,247,0.15); stroke:none; }
.dot { fill:#4dabf7; }
.dot:hover { fill:#8ecbff; }
.value-label-bg { fill:#222; stroke:#4dabf7; stroke-width:1; }
.value-label-text { fill:#eee; font-size:10px; font-weight:600; }
.axis-label { fill:#999; font-size:10px; }
.grid-line { stroke:#333; stroke-width:1; }
.thread-row { display:flex; align-items:center; gap:12px; padding:10px 4px; border-bottom:1px solid #2a2a2a; }
.thread-rank { font-size:13px; color:#777; width:20px; flex-shrink:0; }
.thread-info { flex:1; min-width:0; }
.ms-line { stroke:#f7931a; stroke-width:1; stroke-dasharray:4 3; opacity:0.85; }
.ms-flag-bg { fill:#f7931a; }
.ms-flag-text { fill:#111; font-size:10px; font-weight:700; }
.ms-gap-line { stroke:#f7931a; stroke-width:1.6; stroke-dasharray:1 4; stroke-linecap:round; }
.ms-gap-tick { stroke:#f7931a; stroke-width:1.5; }
.ms-gap-bg { fill:#1b1b1b; stroke:#f7931a; stroke-width:1; }
.ms-gap-text { fill:#f7931a; font-size:10px; font-weight:600; }
.ms-note { color:#999; font-size:12px; margin:-6px 0 12px; }
.thread-title a { color:#eee; text-decoration:none; }
.thread-title a:hover { text-decoration:underline; }
.thread-title { font-size:14px; margin:0 0 5px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.thread-bar-bg { background:#111; border-radius:3px; height:5px; overflow:hidden; }
.thread-bar-fill { background:#4dabf7; height:100%; }
.thread-events { font-size:12px; color:#777; white-space:nowrap; flex-shrink:0; }
.thread-total { font-size:15px; font-weight:700; color:#f7931a; width:44px; text-align:right; flex-shrink:0; }
.thread-showmore { display:block; width:100%; margin-top:10px; background:#222; color:#ccc; border:1px solid #444; padding:8px; font-size:13px; cursor:pointer; border-radius:6px; }
a { color:#f7931a; }
#errorBox { display:none; white-space:pre-wrap; background:#3a1414; color:#ff8080; border:1px solid #661f1f; border-radius:6px; padding:12px; margin-bottom:20px; font-family:monospace; font-size:12px; }
</style>
</head>
<body>
<div id="wrap">
<div id="errorBox"></div>
<h1 id="title">Merit received over time \u2014 ${displayName}</h1>
<div class="meta">
Total received: <span id="totalReceived"></span>
\u2014 sources: <a href="https://loyce.club/Merit/history/${userId}.html" target="_blank" rel="noopener">loyce.club</a>
+ <a href="https://bitcointalk.org/index.php?action=merit;u=${userId}" target="_blank" rel="noopener">bitcointalk.org merit page</a>, merged & de-duplicated
</div>
<details class="diag" id="diagBox"><summary>Diagnostics (click to expand)</summary><div id="diagContent"></div></details>
<div class="toggle" id="modeToggle"></div>
<div class="ms-note" id="msNote"></div>
<div class="chart-box">
<div class="total-badge" id="totalBadge"></div>
<div id="perEvent"></div>
</div>
</div>
<script>
window.onerror = function (msg, src, line, col, err) {
const box = document.getElementById('errorBox');
box.style.display = 'block';
box.textContent = 'Script error: ' + msg + ' (line ' + line + ')' + (err && err.stack ? '\\n' + err.stack : '');
return false;
};
// Local copy: this inline script runs in a separate document from the
// outer Tampermonkey script, so it needs its own escaping helper. Used on
// every diagnostics value below (even ones this script itself computed)
// since it's cheap and one less thing to have to re-verify later if the
// diagnostics table grows.
function escapeHtml(str) {
return String(str)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
try {
const data = ${dataJson};
document.getElementById('totalReceived').textContent = data.receivedTotal;
if (data.diagnostics) {
const d = data.diagnostics;
const rows = [
['loyce.club merit.all/ID.txt \u2014 lines in this user file', d.loyceTotalLines],
['loyce.club \u2014 received entries (receiver = this user)', d.loyceReceivedCount],
['loyce.club \u2014 other lines ignored (not received by this user)', d.loyceOtherLines],
['loyce.club \u2014 lines that failed to parse', d.loyceBadLines],
['loyce.club \u2014 our sum of received amounts', d.loyceReceivedSum],
['loyce.club \u2014 last date it has for this user', d.loyceLastDate],
['bitcointalk.org merit page \u2014 candidate lines found (Received section)', d.btCandidateLines],
['bitcointalk.org merit page \u2014 received entries parsed', d.btReceivedCount],
['bitcointalk.org merit page \u2014 sum of those entries', d.btReceivedSum],
['cutoff \u2014 only bitcointalk.org entries strictly after this date are kept', d.cutoffDate],
['merge \u2014 new entries appended (after cutoff)', d.appended],
['merge \u2014 entries discarded (on/before loyce.club\\'s last date)', d.discarded],
['FINAL \u2014 computed total across merged data', d.computedSum]
];
let html = '<table>' + rows.map(r => '<tr><td>' + escapeHtml(r[0]) + '</td><td>' + escapeHtml(r[1]) + '</td></tr>').join('') + '</table>';
if (d.loyceBadLines > 0) {
html += '<p class="warn">' + d.loyceBadLines + ' line(s) in the loyce.club user file did not parse as ' +
'time amount message id sender receiver \u2014 the file format may differ from what this script expects.</p>';
}
if (d.btCandidateLines > d.btReceivedCount) {
html += '<p class="warn">' + (d.btCandidateLines - d.btReceivedCount) + ' line(s) on the bitcointalk.org ' +
'merit page looked like entries but failed to fully parse \u2014 check the console (F12).</p>';
}
document.getElementById('diagContent').innerHTML = html;
} else {
document.getElementById('diagBox').style.display = 'none';
}
const SVG_NS = 'http://www.w3.org/2000/svg';
const MARGIN = { top: 72, right: 10, bottom: 60, left: 40 };
const CHART_H = 444;
const POINT_GAP = 36;
function el(tag, attrs) {
const e = document.createElementNS(SVG_NS, tag);
for (const k in attrs) e.setAttribute(k, attrs[k]);
return e;
}
function clearAndAppend(container, svg) {
container.innerHTML = '';
container.appendChild(svg);
}
function niceMax(v) {
if (v <= 0) return 1;
const mag = Math.pow(10, Math.floor(Math.log10(v)));
const norm = v mag;
let step;
if (norm <= 1) step = 1;
else if (norm <= 2) step = 2;
else if (norm <= 5) step = 5;
else step = 10;
return step * mag;
}
function renderLineChart(container, labels, values, tooltips, milestones) {
const n = Math.max(values.length, 1);
const width = Math.max(n * POINT_GAP + MARGIN.left + MARGIN.right, 300);
const height = CHART_H;
const innerW = width - MARGIN.left - MARGIN.right;
const innerH = height - MARGIN.top - MARGIN.bottom;
const maxVal = niceMax(Math.max(1, ...values));
const svg = el('svg', { width, height, viewBox: '0 0 ' + width + ' ' + height });
const g = el('g', { transform: 'translate(' + MARGIN.left + ',' + MARGIN.top + ')' });
svg.appendChild(g);
const gridCount = 5;
for (let i = 0; i <= gridCount; i++) {
const y = innerH - (innerH * i) gridCount;
const val = Math.round((maxVal * i) gridCount);
g.appendChild(el('line', { class: 'grid-line', x1: 0, x2: innerW, y1: y, y2: y }));
const t = el('text', { class: 'axis-label', x: -6, y: y + 3, 'text-anchor': 'end' });
t.textContent = val;
g.appendChild(t);
}
const points = values.map((v, i) => {
const x = i * POINT_GAP + POINT_GAP 2;
const y = innerH - (v maxVal) * innerH;
return [x, y];
});
if (points.length) {
const linePath = 'M ' + points.map(p => p[0] + ' ' + p[1]).join(' L ');
const areaPath = linePath + ' L ' + points[points.length - 1][0] + ' ' + innerH + ' L ' + points[0][0] + ' ' + innerH + ' Z';
g.appendChild(el('path', { class: 'line-area', d: areaPath }));
g.appendChild(el('path', { class: 'line-path', d: linePath }));
}
points.forEach(([x, y], i) => {
const dot = el('circle', { class: 'dot', cx: x, cy: y, r: 3 });
const title = el('title', {});
title.textContent = labels[i] + ': ' + values[i] + ' merit' + (values[i] === 1 ? '' : 's') + (tooltips && tooltips[i] ? ' (' + tooltips[i] + ')' : '');
dot.appendChild(title);
g.appendChild(dot);
});
values.forEach((v, i) => {
const [x, y] = points[i];
const text = String(v);
const labelW = Math.max(text.length * 7 + 10, 18);
const labelH = 16;
let labelY = y - 10 - labelH;
if (labelY < 0) labelY = y + 10;
const labelX = x - labelW 2;
g.appendChild(el('rect', { class: 'value-label-bg', x: labelX, y: labelY, width: labelW, height: labelH, rx: 3 }));
const t = el('text', { class: 'value-label-text', x, y: labelY + labelH - 4, 'text-anchor': 'middle' });
t.textContent = text;
g.appendChild(t);
});
// Milestone flags: dashed vertical line through the plot plus a flag in
// the top margin (two flag rows so neighbours don't overlap). Directly
// below the flags, just above the plot, sits a "measure" row: a dotted
// horizontal line between two consecutive milestones, labelled with the
// days between them. The flags' vertical lines run straight through it.
const FLAG_H = 16;
const FLAG_TOP = -68;
const GAP_Y = -16;
const xOf = i => i * POINT_GAP + POINT_GAP 2;
const ms = milestones || [];
const gaps = ms.filter(m => m.prevIndex >= 0 && m.daysSincePrev !== null && m.daysSincePrev !== undefined);
const rowRight = [-1000, -1000];
ms.forEach(m => {
const x = xOf(m.index);
const w = Math.max(String(m.label).length * 7 + 12, 30);
const left = x - w 2;
const row = rowRight[0] + 4 <= left ? 0 : (rowRight[1] + 4 <= left ? 1 : (rowRight[0] <= rowRight[1] ? 0 : 1));
rowRight[row] = left + w;
const flagY = FLAG_TOP + row * (FLAG_H + 3);
g.appendChild(el('line', { class: 'ms-line', x1: x, x2: x, y1: flagY + FLAG_H, y2: innerH }));
const flagBg = el('rect', { class: 'ms-flag-bg', x: left, y: flagY, width: w, height: FLAG_H, rx: 3 });
const tip = el('title', {});
tip.textContent = 'All-time total crossed ' + m.label + ' merit on ' + m.dateText;
flagBg.appendChild(tip);
g.appendChild(flagBg);
const ft = el('text', { class: 'ms-flag-text', x: x, y: flagY + FLAG_H - 4, 'text-anchor': 'middle' });
ft.textContent = m.label;
g.appendChild(ft);
});
gaps.forEach(m => {
const x1 = xOf(m.prevIndex);
const x2 = xOf(m.index);
const d = m.daysSincePrev;
const span = Math.abs(x2 - x1);
const txt = span >= 70 ? d + (d === 1 ? ' day' : ' days') : d + 'd';
const w = Math.max(txt.length * 6 + 12, 26);
const cx = (x1 + x2) 2;
g.appendChild(el('line', { class: 'ms-gap-line', x1: x1, x2: x2, y1: GAP_Y, y2: GAP_Y }));
g.appendChild(el('line', { class: 'ms-gap-tick', x1: x1, x2: x1, y1: GAP_Y - 4, y2: GAP_Y + 4 }));
g.appendChild(el('line', { class: 'ms-gap-tick', x1: x2, x2: x2, y1: GAP_Y - 4, y2: GAP_Y + 4 }));
const bg = el('rect', { class: 'ms-gap-bg', x: cx - w 2, y: GAP_Y - 8, width: w, height: 16, rx: 3 });
const tip = el('title', {});
tip.textContent = d + (d === 1 ? ' day' : ' days') + ' between ' + m.prevLabel + ' (' + m.prevDateText + ') and ' + m.label + ' (' + m.dateText + ')';
bg.appendChild(tip);
g.appendChild(bg);
const t = el('text', { class: 'ms-gap-text', x: cx, y: GAP_Y + 3.5, 'text-anchor': 'middle' });
t.textContent = txt;
g.appendChild(t);
});
appendXLabels(g, labels, innerH, n);
clearAndAppend(container, svg);
}
function appendXLabels(g, labels, innerH, n) {
const step = Math.max(1, Math.ceil(n 25));
labels.forEach((lab, i) => {
if (i % step !== 0) return;
const x = i * POINT_GAP + POINT_GAP 2;
const t = el('text', {
class: 'axis-label', x, y: innerH + 14,
'text-anchor': 'end', transform: 'rotate(-60 ' + x + ' ' + (innerH + 14) + ')'
});
t.textContent = lab;
g.appendChild(t);
});
}
function renderThreadList(container, threads) {
container.innerHTML = '';
const SHOW_LIMIT = 15;
const maxTotal = threads.length ? threads[0].total : 0;/ already sorted descending
let expanded = false;
const list = document.createElement('div');
function draw() {
list.innerHTML = '';
const toShow = expanded ? threads : threads.slice(0, SHOW_LIMIT);
toShow.forEach((t, i) => {
const row = document.createElement('div');
row.className = 'thread-row';
const pct = maxTotal ? Math.round((t.total maxTotal) * 100) : 0;
const rank = document.createElement('span');
rank.className = 'thread-rank';
rank.textContent = String(i + 1);
const info = document.createElement('div');
info.className = 'thread-info';
const titleEl = document.createElement('p');
titleEl.className = 'thread-title';
const TOPIC_PREFIX = 'https://bt.irlbtc.com/view/';
if (t.url && t.url.indexOf(TOPIC_PREFIX) === 0 &&^[0-9]+$/.test(t.url.slice(TOPIC_PREFIX.length))) {
const a = document.createElement('a');
a.href = t.url;
a.target = '_blank';
a.rel = 'noopener';
a.textContent = t.subject;
titleEl.appendChild(a);
} else {
titleEl.textContent = t.subject;/ textContent only \u2014 subject is remote-sourced text
}
titleEl.title = t.subject;/ full text on hover, since it's truncated visually
const barBg = document.createElement('div');
barBg.className = 'thread-bar-bg';
const barFill = document.createElement('div');
barFill.className = 'thread-bar-fill';
barFill.style.width = pct + '%';
barBg.appendChild(barFill);
info.appendChild(titleEl);
info.appendChild(barBg);
const events = document.createElement('span');
events.className = 'thread-events';
events.textContent = t.count + ' event' + (t.count === 1 ? '' : 's');
const total = document.createElement('span');
total.className = 'thread-total';
total.textContent = String(t.total);
row.appendChild(rank);
row.appendChild(info);
row.appendChild(events);
row.appendChild(total);
list.appendChild(row);
});
if (threads.length > SHOW_LIMIT) {
const btn = document.createElement('button');
btn.className = 'thread-showmore';
btn.textContent = expanded ? 'Show fewer' : 'Show all ' + threads.length + ' threads';
btn.addEventListener('click', () => { expanded = !expanded; draw(); });
list.appendChild(btn);
}
}
draw();
container.appendChild(list);
}
const MODE_KEYS = ['daily', 'monthly', 'last120', 'last240', 'last360', 'thread'];
const modeToggle = document.getElementById('modeToggle');
const totalBadge = document.getElementById('totalBadge');
const chartDiv = document.getElementById('perEvent');
const buttons = {};
MODE_KEYS.forEach(key => {
const btn = document.createElement('button');
btn.textContent = data.modes[key].label;
btn.addEventListener('click', () => renderMode(key));
modeToggle.appendChild(btn);
buttons[key] = btn;
});
function renderMode(key) {
const mode = data.modes[key];
MODE_KEYS.forEach(k => buttons[k].classList.toggle('active', k === key));
document.getElementById('totalReceived').textContent = mode.total;
totalBadge.textContent = 'Total received: ' + mode.total + ' merit' + (mode.total === 1 ? '' : 's');
const noteEl = document.getElementById('msNote');
const hasFlags = !mode.threads && mode.milestones && mode.milestones.length > 0;
noteEl.style.display = hasFlags ? 'block' : 'none';
const hasGaps = hasFlags && mode.milestones.some(m => m.prevIndex >= 0);
noteEl.textContent = hasFlags ? 'Orange flags: the day your all-time total first reached each 1,000 merit (hover a flag for the date).' + (hasGaps ? ' Dotted lines: days between consecutive milestones.' : '') : '';
if (mode.threads) {
if (!mode.threads.length) {
chartDiv.innerHTML = '<p style="color:#777">No received-merit records found.</p>';
return;
}
renderThreadList(chartDiv, mode.threads);
return;
}
if (!mode.labels.length) {
chartDiv.innerHTML = '<p style="color:#777">No received-merit records in this view.</p>';
return;
}
renderLineChart(chartDiv, mode.labels, mode.perEvent, mode.tooltips, mode.milestones);
}
renderMode('daily');
} catch (e) {
const box = document.getElementById('errorBox');
box.style.display = 'block';
box.textContent = 'Render error: ' + e.message + '\\n' + (e.stack || '');
}
<\/script>
</body>
</html>`;
}
// ---------- init ----------
if (typeof GM_registerMenuCommand === 'function') {
GM_registerMenuCommand('Plot Merit History\u2026', onButtonClick);
}
createButton();
})();