feat: players page redesign — deltas, KPI tiles, sparklines, expanded row #9

Merged
shcizo merged 27 commits from feat/shared-visual-layer-topbar-4 into main 2026-05-21 16:14:01 +02:00
18 changed files with 1582 additions and 721 deletions
+1 -51
View File
@@ -2,46 +2,7 @@
Players Page
═══════════════════════════════════════════════════ */
/* ── Add Player Button ─────────────────────────── */
.btn-add {
background: var(--green);
}
.btn-add:hover {
background: #059669;
}
/* ── Progress ─────────────────────────────────── */
.progress-container {
width: 100%;
background: var(--surface-3);
border-radius: var(--radius-xl);
padding: 3px;
margin: 20px 0;
overflow: hidden;
}
.progress-bar {
width: 0%;
height: 26px;
background: linear-gradient(135deg, var(--accent), var(--accent-hover));
border-radius: var(--radius-xl);
text-align: center;
line-height: 26px;
color: white;
font-weight: 600;
font-size: 12px;
transition: width 0.4s ease;
}
.progress-text {
text-align: center;
margin: 8px 0;
font-size: 13px;
color: var(--text-secondary);
}
/* ── (Add player now uses .btn-primary from shared.css) ── */
/* ── Mobile helpers ───────────────────────────── */
@@ -61,12 +22,6 @@
/* ── Rating values ────────────────────────────── */
.rating {
font-weight: 700;
color: var(--accent);
font-variant-numeric: tabular-nums;
}
.rating-value {
font-variant-numeric: tabular-nums;
}
@@ -95,11 +50,6 @@
font-variant-numeric: tabular-nums;
}
.refresh-section {
display: inline-flex;
align-items: center;
}
.predicted-value {
position: relative;
display: inline-block;
+820 -176
View File
File diff suppressed because it is too large Load Diff
+124 -136
View File
@@ -1,150 +1,138 @@
function createRatingChart(container, history) {
const width = container.clientWidth;
const height = 280;
const margin = { top: 24, right: 20, bottom: 44, left: 56 };
const chartWidth = width - margin.left - margin.right;
const chartHeight = height - margin.top - margin.bottom;
const pdgaNumber = container.id.replace('chart-', '');
const tooltip = document.getElementById(`tooltip-${pdgaNumber}`);
const ratings = history.map(h => h.rating);
const minRating = Math.min(...ratings) - 10;
const maxRating = Math.max(...ratings) + 10;
const xStep = chartWidth / (history.length - 1 || 1);
const yScale = chartHeight / (maxRating - minRating);
// Build points array
const points = [];
let pathData = '';
history.forEach((point, i) => {
const x = margin.left + (i * xStep);
const y = margin.top + ((maxRating - point.rating) * yScale);
points.push({ x, y, rating: point.rating, date: point.displayDate });
pathData += i === 0 ? `M ${x} ${y}` : ` L ${x} ${y}`;
});
// Area fill path (close to bottom)
const areaPath = pathData +
` L ${points[points.length - 1].x} ${margin.top + chartHeight}` +
` L ${points[0].x} ${margin.top + chartHeight} Z`;
let svg = `<svg width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" style="display: block;">`;
// Defs: gradient + glow
svg += `<defs>
<linearGradient id="areaGrad-${pdgaNumber}" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stop-color="#3b82f6" stop-opacity="0.15"/>
<stop offset="100%" stop-color="#3b82f6" stop-opacity="0.01"/>
</linearGradient>
<linearGradient id="lineGrad-${pdgaNumber}" x1="0" y1="0" x2="1" y2="0">
<stop offset="0%" stop-color="#3b82f6"/>
<stop offset="100%" stop-color="#2563eb"/>
</linearGradient>
</defs>`;
// Background
svg += `<rect x="0" y="0" width="${width}" height="${height}" fill="white" rx="10"/>`;
// Grid lines
const gridCount = 5;
for (let i = 0; i <= gridCount; i++) {
const y = margin.top + (i * chartHeight / gridCount);
const rating = Math.round(maxRating - (i * (maxRating - minRating) / gridCount));
svg += `<line x1="${margin.left}" y1="${y}" x2="${margin.left + chartWidth}" y2="${y}" stroke="#f1f5f9" stroke-width="1"/>`;
svg += `<text x="${margin.left - 10}" y="${y + 4}" text-anchor="end" font-size="11" font-family="'DM Sans', sans-serif" fill="#94a3b8" font-weight="500">${rating}</text>`;
if (!history || history.length === 0) {
container.textContent = '';
var empty = document.createElement('div');
empty.className = 'loading-chart';
empty.textContent = 'No rating history available';
container.appendChild(empty);
return;
}
// Area fill
svg += `<path d="${areaPath}" fill="url(#areaGrad-${pdgaNumber})"/>`;
var W = 880, H = 240;
var pad = { left: 44, right: 16, top: 20, bottom: 32 };
var chartW = W - pad.left - pad.right;
var chartH = H - pad.top - pad.bottom;
// Line
svg += `<path d="${pathData}" stroke="url(#lineGrad-${pdgaNumber})" stroke-width="2.5" fill="none" stroke-linejoin="round" stroke-linecap="round"/>`;
var ratings = history.map(function(h) { return h.rating; });
var minR = Math.min.apply(null, ratings) - 5;
var maxR = Math.max.apply(null, ratings) + 5;
var range = maxR - minR || 1;
// Data points
points.forEach((point, i) => {
svg += `<circle cx="${point.x}" cy="${point.y}" r="14" fill="transparent" class="hover-area" data-index="${i}" style="cursor: pointer;"/>`;
svg += `<circle cx="${point.x}" cy="${point.y}" r="3.5" fill="#3b82f6" stroke="white" stroke-width="2" class="data-point" data-index="${i}" style="pointer-events: none;"/>`;
function xOf(i) {
return pad.left + (i / Math.max(history.length - 1, 1)) * chartW;
}
function yOf(r) {
return pad.top + ((maxR - r) / range) * chartH;
}
var pts = history.map(function(h, i) {
return { x: xOf(i), y: yOf(h.rating), rating: h.rating, date: h.date };
});
// X-axis labels
const labelStep = Math.max(1, Math.floor(history.length / 6));
history.forEach((point, i) => {
if (i % labelStep === 0 || i === history.length - 1) {
const x = margin.left + (i * xStep);
const date = new Date(point.date).toLocaleDateString('en-US', { month: 'short', year: '2-digit' });
svg += `<text x="${x}" y="${height - 12}" text-anchor="middle" font-size="11" font-family="'DM Sans', sans-serif" fill="#94a3b8" font-weight="500">${date}</text>`;
var linePath = pts.map(function(p, i) {
return (i === 0 ? 'M' : 'L') + ' ' + p.x.toFixed(1) + ' ' + p.y.toFixed(1);
}).join(' ');
var last = pts[pts.length - 1];
var bottomY = (pad.top + chartH).toFixed(1);
var areaPath = linePath +
' L ' + last.x.toFixed(1) + ' ' + bottomY +
' L ' + pad.left.toFixed(1) + ' ' + bottomY + ' Z';
// Build SVG using DOM API to avoid innerHTML on user-supplied content
var ns = 'http://www.w3.org/2000/svg';
function el(tag, attrs) {
var e = document.createElementNS(ns, tag);
Object.keys(attrs).forEach(function(k) { e.setAttribute(k, attrs[k]); });
return e;
}
function txt(tag, attrs, text) {
var e = el(tag, attrs);
e.textContent = text;
return e;
}
var svg = el('svg', {
viewBox: '0 0 ' + W + ' ' + H,
width: '100%',
style: 'display:block;overflow:visible',
'aria-hidden': 'true'
});
// Grid lines + y-axis labels (4 ticks)
var tickCount = 4;
for (var i = 0; i <= tickCount; i++) {
var gy = pad.top + (i / tickCount) * chartH;
var gr = Math.round(maxR - (i / tickCount) * range);
svg.appendChild(el('line', {
x1: pad.left, y1: gy.toFixed(1),
x2: pad.left + chartW, y2: gy.toFixed(1),
stroke: 'var(--line)', 'stroke-width': '1', 'stroke-dasharray': '2 4'
}));
svg.appendChild(txt('text', {
x: pad.left - 8, y: (gy + 4).toFixed(1),
'text-anchor': 'end', 'font-size': '10',
'font-family': "'JetBrains Mono', monospace",
fill: 'var(--ink-3)'
}, String(gr)));
}
// Area fill (8% opacity)
svg.appendChild(el('path', {
d: areaPath, fill: 'var(--accent)', 'fill-opacity': '0.08'
}));
// Line
svg.appendChild(el('path', {
d: linePath, stroke: 'var(--accent)', 'stroke-width': '2',
fill: 'none', 'stroke-linejoin': 'round', 'stroke-linecap': 'round'
}));
// Dots
pts.forEach(function(p, i) {
var isLast = i === pts.length - 1;
if (isLast) {
svg.appendChild(el('circle', {
cx: p.x.toFixed(1), cy: p.y.toFixed(1),
r: '4', fill: 'var(--accent)', stroke: 'var(--paper)', 'stroke-width': '2'
}));
} else {
svg.appendChild(el('circle', {
cx: p.x.toFixed(1), cy: p.y.toFixed(1),
r: '3', fill: 'var(--accent)'
}));
}
});
// Y-axis label
svg += `<text x="16" y="${height / 2}" text-anchor="middle" font-size="11" font-family="'DM Sans', sans-serif" fill="#94a3b8" font-weight="500" transform="rotate(-90, 16, ${height / 2})">Rating</text>`;
// X-axis labels (5 evenly spaced)
var labelCount = Math.min(5, history.length);
var labelIndices = [];
if (labelCount <= 1) {
labelIndices.push(0);
} else {
for (var k = 0; k < labelCount; k++) {
labelIndices.push(Math.round(k * (history.length - 1) / (labelCount - 1)));
}
}
svg += '</svg>';
var seen = {};
labelIndices.forEach(function(idx) {
if (seen[idx]) return;
seen[idx] = true;
var p = pts[idx];
var d = new Date(history[idx].date);
var label = d.toLocaleDateString('en-US', { month: 'short', year: '2-digit' });
svg.appendChild(txt('text', {
x: p.x.toFixed(1),
y: (pad.top + chartH + 16).toFixed(1),
'text-anchor': 'middle', 'font-size': '10',
'font-family': "'JetBrains Mono', monospace",
fill: 'var(--ink-3)'
}, label));
});
container.textContent = '';
container.insertAdjacentHTML('beforeend', svg);
setTimeout(() => {
const svgElement = document.getElementById(`svg-${pdgaNumber}`) || container.querySelector('svg');
if (!svgElement) return;
const hoverAreas = svgElement.querySelectorAll('.hover-area');
const dataPoints = svgElement.querySelectorAll('.data-point');
let currentTooltip = null;
let tooltipTimeout = null;
hoverAreas.forEach((area, i) => {
area.addEventListener('mouseenter', (e) => {
if (tooltipTimeout) {
clearTimeout(tooltipTimeout);
tooltipTimeout = null;
}
if (currentTooltip !== null && currentTooltip !== i) {
dataPoints[currentTooltip].setAttribute('r', '3.5');
dataPoints[currentTooltip].setAttribute('fill', '#3b82f6');
}
currentTooltip = i;
const point = points[i];
tooltip.textContent = '';
const strong = document.createElement('strong');
strong.textContent = point.date;
tooltip.appendChild(strong);
tooltip.appendChild(document.createElement('br'));
tooltip.appendChild(document.createTextNode('Rating: ' + point.rating));
tooltip.style.display = 'block';
tooltip.style.left = `${e.clientX + 15}px`;
tooltip.style.top = `${e.clientY - 35}px`;
dataPoints[i].setAttribute('r', '6');
dataPoints[i].setAttribute('fill', '#2563eb');
});
area.addEventListener('mousemove', (e) => {
if (currentTooltip === i) {
tooltip.style.left = `${e.clientX + 15}px`;
tooltip.style.top = `${e.clientY - 35}px`;
}
});
area.addEventListener('mouseleave', () => {
if (currentTooltip === i) {
tooltipTimeout = setTimeout(() => {
tooltip.style.display = 'none';
dataPoints[i].setAttribute('r', '3.5');
dataPoints[i].setAttribute('fill', '#3b82f6');
currentTooltip = null;
}, 100);
}
});
});
}, 100);
container.appendChild(svg);
}
+121 -74
View File
@@ -1,5 +1,30 @@
let cachedDebugInfo = {};
const cachedDebugInfo = {};
let pendingPlayerData = null;
let openPdgaNumber = null;
// ── Delta-pill helper ─────────────────────────────
function renderDeltaPill(value, extraClass) {
const isNull = (value == null);
const cls = isNull ? 'flat' : value > 0 ? 'up' : value < 0 ? 'down' : 'flat';
const glyph = (isNull || value === 0) ? '' : value > 0 ? '▲' : '▼';
const num = isNull ? '—' : value > 0 ? '+' + value : String(value);
return { glyph, num, cls };
}
function applyDeltaPill(pillEl, value) {
if (!pillEl) return;
const pill = renderDeltaPill(value);
pillEl.className = 'delta-pill ' + pill.cls;
while (pillEl.firstChild) pillEl.removeChild(pillEl.firstChild);
const glyphSpan = document.createElement('span');
glyphSpan.className = 'delta-glyph';
glyphSpan.textContent = pill.glyph;
const numSpan = document.createElement('span');
numSpan.className = 'delta-num';
numSpan.textContent = pill.num;
pillEl.appendChild(glyphSpan);
pillEl.appendChild(numSpan);
}
function setupTooltipsAfterSwap() {
document.body.addEventListener('htmx:afterSwap', function(event) {
@@ -9,7 +34,7 @@ function setupTooltipsAfterSwap() {
// After player history partial loads, render the chart
const target = event.detail.target;
if (target.id && target.id.startsWith('history-content-')) {
const container = target.querySelector('.chart-container');
const container = target.querySelector('.player-chart, .chart-container');
if (container && container.dataset.history) {
try {
const history = JSON.parse(container.dataset.history);
@@ -48,21 +73,46 @@ function initRatingsTooltips() {
}
function togglePlayerHistory(pdgaNumber) {
const historyRow = document.getElementById(`history-${pdgaNumber}`);
const contentDiv = document.getElementById(`history-content-${pdgaNumber}`);
const historyRow = document.getElementById('history-' + pdgaNumber);
const contentDiv = document.getElementById('history-content-' + pdgaNumber);
const expandableRow = document.getElementById('row-' + pdgaNumber);
if (historyRow.style.display === 'table-row') {
const isOpen = historyRow.style.display === 'table-row';
// Close any previously-open row
if (openPdgaNumber !== null && openPdgaNumber !== pdgaNumber) {
const prevHistory = document.getElementById('history-' + openPdgaNumber);
const prevRow = document.getElementById('row-' + openPdgaNumber);
if (prevHistory) {
prevHistory.style.display = 'none';
prevHistory.classList.remove('is-open');
}
if (prevRow) prevRow.classList.remove('row-open');
openPdgaNumber = null;
}
if (isOpen) {
historyRow.style.display = 'none';
historyRow.classList.remove('is-open');
expandableRow.classList.remove('row-open');
openPdgaNumber = null;
return;
}
historyRow.style.display = 'table-row';
// Force reflow so animation plays each open
historyRow.classList.remove('is-open');
void historyRow.offsetWidth;
historyRow.classList.add('is-open');
expandableRow.classList.add('row-open');
openPdgaNumber = pdgaNumber;
if (contentDiv.dataset.loaded === 'true') {
return;
}
htmx.ajax('GET', `/partials/player-history/${pdgaNumber}`, {target: `#history-content-${pdgaNumber}`, swap: 'innerHTML'});
htmx.ajax('GET', '/partials/player-history/' + pdgaNumber, {target: '#history-content-' + pdgaNumber, swap: 'innerHTML'});
contentDiv.dataset.loaded = 'true';
}
@@ -85,28 +135,39 @@ async function clearCache() {
}
}
async function refreshPlayer(pdgaNumber) {
const icon = document.querySelector(`#row-${pdgaNumber} .rating .refresh-icon`);
icon.classList.add('spinning');
// Refreshes both the current rating and the prediction in one click, then
// re-swaps the table so every derived value (deltas, pills, sparkline) reflects
// the new state. Cheaper than fine-grained DOM updates and guaranteed consistent
// because the server renders the truth.
async function refreshPlayerData(pdgaNumber) {
const icon = document.querySelector(`#row-${pdgaNumber} .cell-actions .refresh-icon`);
if (icon) icon.classList.add('spinning');
try {
await Promise.allSettled([
fetch(`/api/refresh-player/${pdgaNumber}`, { method: 'POST' }),
fetch(`/api/refresh-round-history/${pdgaNumber}`, { method: 'POST' })
]);
htmx.ajax('GET', '/partials/ratings-table', { target: '#ratings-table', swap: 'innerHTML' });
} catch (error) {
console.error('Error refreshing player data:', error);
} finally {
if (icon) icon.classList.remove('spinning');
}
}
async function refreshPlayer(pdgaNumber) {
try {
const response = await fetch(`/api/refresh-player/${pdgaNumber}`, { method: 'POST' });
const data = await response.json();
if (data.success) {
const row = document.getElementById(`row-${pdgaNumber}`);
const ratingCell = row.querySelector('.rating');
const ratingChangeCell = row.querySelector('.rating-change');
const ratingCell = row.querySelector('.cell-rating');
const nameLink = row.querySelector('.player-name a');
nameLink.textContent = data.player.name;
if (nameLink) nameLink.textContent = data.player.name;
const ratingChangeText = data.player.ratingChange ?
(data.player.ratingChange > 0 ? `+${data.player.ratingChange}` : data.player.ratingChange.toString()) : 'N/A';
const ratingChangeClass = data.player.ratingChange > 0 ? 'positive' :
data.player.ratingChange < 0 ? 'negative' : 'neutral';
const ratingValue = ratingCell.querySelector('.rating-value');
const ratingValue = ratingCell ? ratingCell.querySelector('.rating-value') : null;
if (ratingValue) {
ratingValue.textContent = data.player.rating || 'N/A';
ratingValue.dataset.rating = data.player.rating || '';
@@ -122,27 +183,16 @@ async function refreshPlayer(pdgaNumber) {
}
}
if (ratingChangeCell) ratingChangeCell.textContent = ratingChangeText;
if (ratingChangeCell) ratingChangeCell.className = `rating-change ${ratingChangeClass} mobile-hide`;
const mobileChange = ratingCell.querySelector('.mobile-only.rating-change');
if (mobileChange) {
mobileChange.textContent = ratingChangeText;
mobileChange.className = `mobile-only rating-change ${ratingChangeClass}`;
}
const deltaMonthPill = ratingCell ? ratingCell.querySelector('.delta-pill') : null;
applyDeltaPill(deltaMonthPill, data.player.ratingChange);
}
} catch (error) {
console.error('Error refreshing player:', error);
alert('Failed to refresh player data');
} finally {
icon.classList.remove('spinning');
}
}
async function refreshRoundHistory(pdgaNumber) {
const icon = document.querySelector(`#predicted-${pdgaNumber} .refresh-icon`);
icon.classList.add('spinning');
try {
const response = await fetch(`/api/refresh-round-history/${pdgaNumber}`, { method: 'POST' });
const data = await response.json();
@@ -171,8 +221,8 @@ async function refreshRoundHistory(pdgaNumber) {
}
const row = document.getElementById(`row-${pdgaNumber}`);
const ratingCell = row.querySelector('.rating');
const ratingValue = ratingCell.querySelector('.rating-value');
const ratingCell = row.querySelector('.cell-rating');
const ratingValue = ratingCell ? ratingCell.querySelector('.rating-value') : null;
if (ratingValue && data.stdDev) {
ratingValue.dataset.stddev = data.stdDev;
@@ -188,43 +238,16 @@ async function refreshRoundHistory(pdgaNumber) {
}
}
} catch (error) {
// Rate-limited or scrape failure — common when refresh runs alongside the
// current-rating refresh. Log but don't alert; the user-facing surface is
// the spinner stopping (data may or may not have updated).
console.error('Error refreshing round history:', error);
let errorMessage = 'Failed to refresh prediction data';
let errorDetails = '';
try {
const errorData = JSON.parse(error.message);
errorMessage = errorData.error || errorMessage;
if (errorData.message) {
errorDetails = errorData.message;
} else {
errorDetails = errorData.details || '';
if (errorData.suggestion) {
errorDetails += '\n\nSuggestion: ' + errorData.suggestion;
}
if (errorData.errorType) {
errorDetails += '\n\nError Type: ' + errorData.errorType;
}
if (errorData.timestamp) {
errorDetails += '\n\nTime: ' + new Date(errorData.timestamp).toLocaleString();
}
}
} catch (parseError) {
errorDetails = error.message;
}
const fullMessage = errorDetails ? errorMessage + '\n\n' + errorDetails : errorMessage;
alert(fullMessage);
} finally {
icon.classList.remove('spinning');
}
}
async function refreshRatingHistory(pdgaNumber) {
const icon = document.querySelector(`#history-${pdgaNumber} .chart-title .refresh-icon`);
icon.classList.add('spinning');
// No dedicated icon in the expanded row; spinner state not needed here
const icon = null;
try {
const response = await fetch(`/api/refresh-rating-history/${pdgaNumber}`, { method: 'POST' });
@@ -239,8 +262,6 @@ async function refreshRatingHistory(pdgaNumber) {
} catch (error) {
console.error('Error refreshing rating history:', error);
alert('Failed to refresh rating history');
} finally {
icon.classList.remove('spinning');
}
}
@@ -281,7 +302,8 @@ function closeDebugModal(event) {
document.getElementById('debug-modal').style.display = 'none';
}
async function searchAndAddPlayer() {
async function searchAndAddPlayer(event) {
if (event) event.preventDefault();
const input = document.getElementById('pdga-number-input');
const pdgaNumber = input.value.trim();
@@ -290,10 +312,9 @@ async function searchAndAddPlayer() {
return;
}
const button = document.querySelector('.btn-add');
const originalText = button.textContent;
button.disabled = true;
button.textContent = 'Searching...';
const button = document.querySelector('.add-bar button[type="submit"]');
const originalText = button ? button.textContent : '';
if (button) { button.disabled = true; button.textContent = 'Searching...'; }
try {
const response = await fetch(`/api/search-player/${pdgaNumber}`);
@@ -316,8 +337,7 @@ async function searchAndAddPlayer() {
console.error('Error searching for player:', error);
showErrorModal('Failed to search for player. Please try again.');
} finally {
button.disabled = false;
button.textContent = originalText;
if (button) { button.disabled = false; button.textContent = originalText; }
}
}
@@ -486,3 +506,30 @@ function closeAddPlayerModal(event) {
document.getElementById('add-player-modal').style.display = 'none';
pendingPlayerData = null;
}
// ── Sparkline toggle ───────────────────────────────
document.addEventListener('DOMContentLoaded', function() {
const btn = document.getElementById('trendchart-toggle');
if (!btn) return;
const state = localStorage.getItem('ratingtracker.sparklines') || 'on';
document.body.dataset.sparklines = state;
btn.setAttribute('aria-pressed', state === 'on' ? 'true' : 'false');
btn.addEventListener('click', function() {
const next = document.body.dataset.sparklines === 'on' ? 'off' : 'on';
document.body.dataset.sparklines = next;
btn.setAttribute('aria-pressed', next === 'on' ? 'true' : 'false');
localStorage.setItem('ratingtracker.sparklines', next);
});
});
// ── Expandable row keyboard support ───────────────
document.addEventListener('keydown', function(e) {
if (e.key !== 'Enter' && e.key !== ' ') return;
const row = e.target;
if (!row.classList || !row.classList.contains('expandable-row')) return;
e.preventDefault();
const pdgaNumber = row.id.replace('row-', '');
togglePlayerHistory(parseInt(pdgaNumber, 10));
});
-97
View File
@@ -1,97 +0,0 @@
function fetchRatingsWithProgress() {
const progressSection = document.getElementById('progress-section');
const progressBar = document.getElementById('progress-bar');
const progressText = document.getElementById('progress-text');
const tableDiv = document.getElementById('ratings-table');
progressSection.style.display = 'block';
tableDiv.innerHTML = '';
const eventSource = new EventSource('/api/ratings/progress');
eventSource.onmessage = function(event) {
const data = JSON.parse(event.data);
if (data.status === 'loading') {
const percentage = Math.round((data.current / data.total) * 100);
progressBar.style.width = `${percentage}%`;
progressBar.textContent = `${percentage}%`;
progressText.textContent = `Loading player ${data.current}/${data.total}: PDGA #${data.pdgaNumber}`;
} else if (data.status === 'completed') {
const percentage = Math.round((data.current / data.total) * 100);
progressBar.style.width = `${percentage}%`;
progressBar.textContent = `${percentage}%`;
progressText.textContent = `Loaded ${data.name} (${data.current}/${data.total})`;
} else if (data.status === 'error') {
const percentage = Math.round((data.current / data.total) * 100);
progressBar.style.width = `${percentage}%`;
progressBar.textContent = `${percentage}%`;
progressText.textContent = `Error loading PDGA #${data.pdgaNumber} (${data.current}/${data.total})`;
} else if (data.status === 'complete') {
progressSection.style.display = 'none';
htmx.ajax('GET', '/partials/ratings-table', '#ratings-table');
eventSource.close();
}
};
eventSource.onerror = function() {
progressSection.style.display = 'none';
tableDiv.textContent = 'Connection error. Please refresh the page.';
eventSource.close();
};
}
function loadAllPlayers() {
const button = document.getElementById('load-all-btn');
const originalText = button.textContent;
button.textContent = 'Loading...';
button.style.pointerEvents = 'none';
try {
const progressSection = document.getElementById('progress-section');
const progressBar = document.getElementById('progress-bar');
const progressText = document.getElementById('progress-text');
const tableDiv = document.getElementById('ratings-table');
progressSection.style.display = 'block';
tableDiv.textContent = '';
const eventSource = new EventSource('/api/load-all-players');
eventSource.onmessage = function(event) {
const data = JSON.parse(event.data);
if (data.status === 'loading' || data.status === 'completed' || data.status === 'error') {
const percentage = Math.round((data.current / data.total) * 100);
progressBar.style.width = `${percentage}%`;
progressBar.textContent = `${percentage}%`;
if (data.status === 'loading') {
progressText.textContent = `Loading player ${data.current}/${data.total}: PDGA #${data.pdgaNumber}`;
} else if (data.status === 'completed') {
progressText.textContent = `Loaded ${data.name} (${data.current}/${data.total})`;
} else if (data.status === 'error') {
progressText.textContent = `Error loading PDGA #${data.pdgaNumber} (${data.current}/${data.total})`;
}
} else if (data.status === 'complete') {
progressSection.style.display = 'none';
htmx.ajax('GET', '/partials/ratings-table', '#ratings-table');
eventSource.close();
button.textContent = originalText;
button.style.pointerEvents = 'auto';
}
};
eventSource.onerror = function() {
progressSection.style.display = 'none';
tableDiv.textContent = 'Connection error. Please refresh the page.';
eventSource.close();
button.textContent = originalText;
button.style.pointerEvents = 'auto';
};
} catch (error) {
console.error('Error loading all players:', error);
button.textContent = originalText;
button.style.pointerEvents = 'auto';
}
}
+1
View File
@@ -14,6 +14,7 @@ app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views/pages'));
app.use(express.static('public'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(playerRoutes);
app.use(courseRoutes);
+98 -14
View File
@@ -33,7 +33,7 @@ function getRatingHistoryFromDB(pdgaNumber) {
db.get('SELECT id FROM players WHERE pdga_number = ?', [pdgaNumber], (err, player) => {
if (err) return reject(err);
if (!player) return resolve(null);
db.all(
'SELECT * FROM rating_history WHERE player_id = ? ORDER BY date ASC',
[player.id],
@@ -51,26 +51,26 @@ function saveRatingHistoryToDB(pdgaNumber, ratingHistory) {
db.get('SELECT id FROM players WHERE pdga_number = ?', [pdgaNumber], (err, player) => {
if (err) return reject(err);
if (!player) return reject(new Error('Player not found'));
db.run('DELETE FROM rating_history WHERE player_id = ?', [player.id], (err) => {
if (err) return reject(err);
if (ratingHistory.length === 0) {
return resolve();
}
let completed = 0;
const total = ratingHistory.length;
ratingHistory.forEach(entry => {
const parsedDate = parseDate(entry.date);
db.run(
'INSERT INTO rating_history (player_id, date, rating) VALUES (?, ?, ?)',
[player.id, parsedDate.toISOString().split('T')[0], entry.rating],
(err) => {
if (err) return reject(err);
completed++;
if (completed === total) {
resolve();
@@ -88,7 +88,7 @@ function getRoundHistoryFromDB(pdgaNumber) {
db.get('SELECT id FROM players WHERE pdga_number = ?', [pdgaNumber], (err, player) => {
if (err) return reject(err);
if (!player) return resolve([]);
db.all(
'SELECT * FROM round_history WHERE player_id = ? ORDER BY date DESC',
[player.id],
@@ -132,7 +132,7 @@ function saveRoundHistoryToDB(pdgaNumber, roundData, isIncremental = false) {
db.get('SELECT id FROM players WHERE pdga_number = ?', [pdgaNumber], (err, player) => {
if (err) return reject(err);
if (!player) return reject(new Error('Player not found'));
const processRounds = () => {
if (roundData.length === 0) {
db.run('UPDATE players SET last_round_update = datetime("now") WHERE pdga_number = ?', [pdgaNumber], (err) => {
@@ -141,13 +141,13 @@ function saveRoundHistoryToDB(pdgaNumber, roundData, isIncremental = false) {
});
return;
}
const stmt = db.prepare('INSERT OR REPLACE INTO round_history (player_id, date, competition_name, rating) VALUES (?, ?, ?, ?)');
for (const round of roundData) {
stmt.run([player.id, round.date.toISOString().split('T')[0], round.competition || 'Unknown', round.rating]);
}
stmt.finalize((err) => {
if (err) {
reject(err);
@@ -159,7 +159,7 @@ function saveRoundHistoryToDB(pdgaNumber, roundData, isIncremental = false) {
}
});
};
if (!isIncremental) {
db.run('DELETE FROM round_history WHERE player_id = ?', [player.id], (err) => {
if (err) return reject(err);
@@ -185,6 +185,87 @@ function savePredictedRatingToDB(pdgaNumber, predictedRating, stdDev = null) {
});
}
/**
* Returns monthly rating snapshots for one player (latest entry per calendar month),
* ordered oldest → newest. At most `months` entries; [] if none.
*/
function getMonthlyHistory(pdgaNumber, months = 12) {
return new Promise((resolve, reject) => {
db.get('SELECT id FROM players WHERE pdga_number = ?', [pdgaNumber], (err, player) => {
if (err) return reject(err);
if (!player) return resolve([]);
db.all(
`SELECT rating
FROM rating_history
WHERE player_id = ?
AND date IN (
SELECT MAX(date)
FROM rating_history
WHERE player_id = ?
GROUP BY strftime('%Y-%m', date)
)
ORDER BY date DESC
LIMIT ?`,
[player.id, player.id, months],
(err, rows) => {
if (err) return reject(err);
resolve(rows.map(r => r.rating).reverse());
}
);
});
});
}
/**
* Fetches the last `months` monthly rating snapshots for ALL players in one query.
* Returns a Map<pdgaNumber, number[]> (oldest → newest per player).
* Use this in bulk-fetch paths to avoid N+1 queries.
*/
function getAllMonthlyHistoriesFromDB(months = 12) {
return new Promise((resolve, reject) => {
db.all(
`SELECT p.pdga_number, rh.date, rh.rating
FROM rating_history rh
JOIN players p ON rh.player_id = p.id
INNER JOIN (
SELECT player_id, MAX(date) AS max_date
FROM rating_history
GROUP BY player_id, strftime('%Y-%m', date)
) latest ON rh.player_id = latest.player_id AND rh.date = latest.max_date
ORDER BY p.pdga_number, rh.date ASC`,
[],
(err, rows) => {
if (err) return reject(err);
const map = new Map();
for (const row of rows) {
if (!map.has(row.pdga_number)) map.set(row.pdga_number, []);
map.get(row.pdga_number).push(row.rating);
}
// Trim each player's history to the requested window
for (const [key, arr] of map) {
if (arr.length > months) map.set(key, arr.slice(-months));
}
resolve(map);
}
);
});
}
function getLastRefresh() {
return new Promise((resolve, reject) => {
db.get(
'SELECT MAX(last_updated) AS lastRefresh FROM players',
[],
(err, row) => {
if (err) reject(err);
else resolve(row ? row.lastRefresh : null);
}
);
});
}
module.exports = {
getPlayerFromDB,
savePlayerToDB,
@@ -194,5 +275,8 @@ module.exports = {
getLastRoundUpdateDate,
updateLastRoundUpdateDate,
saveRoundHistoryToDB,
savePredictedRatingToDB
savePredictedRatingToDB,
getLastRefresh,
getMonthlyHistory,
getAllMonthlyHistoriesFromDB
};
+10 -4
View File
@@ -1,12 +1,18 @@
const express = require('express');
const router = express.Router();
const { getTopbarLocals } = require('../services/topbar-service');
const { getAllRatingsFromDB, computeKpis } = require('../services/player-service');
router.get('/', (req, res) => {
res.render('index');
router.get('/', async (req, res) => {
const topbar = await getTopbarLocals();
const players = await getAllRatingsFromDB();
const kpis = computeKpis(players);
res.render('index', { activePage: 'players', kpis, ...topbar });
});
router.get('/courses', (req, res) => {
res.render('courses');
router.get('/courses', async (req, res) => {
const topbar = await getTopbarLocals();
res.render('courses', { activePage: 'courses', ...topbar });
});
// Keep old URL working
+27 -70
View File
@@ -6,9 +6,34 @@ const { fetchPlayerDataHTTP, parsePlayerData, fetchRatingHistory, parseRatingHis
const { getOfficialRatingHistory, getOptimizedPlayerRounds } = require('../scrapers/player-puppeteer');
const { launchBrowser } = require('../scrapers/browser');
const { getPlayerDataFromDB, scrapePDGARating, getAllRatingsFromDB, refreshAllPlayersInDB, getPredictedRatingFromDB } = require('../services/player-service');
const { getTopbarLocals } = require('../services/topbar-service');
const { calculatePredictedRating } = require('../services/rating-calculator');
const logger = require('../logger');
let refreshInProgress = false;
router.post('/api/refresh-all', async (req, res, next) => {
if (refreshInProgress) {
logger.info('refresh-all already in progress, rejecting');
return res.status(409).json({ error: 'Refresh already in progress' });
}
refreshInProgress = true;
try {
try {
await refreshAllPlayersInDB();
} catch (err) {
logger.error({ err }, 'refresh-all failed');
}
const page = req.body?.page === 'courses' ? 'courses' : 'players';
const locals = await getTopbarLocals();
res.render('../partials/topbar', { activePage: page, ...locals });
} catch (err) {
next(err);
} finally {
refreshInProgress = false;
}
});
router.get('/partials/ratings-table', async (req, res) => {
try {
const ratings = await getAllRatingsFromDB();
@@ -39,7 +64,8 @@ router.get('/partials/player-history/:pdgaNumber', async (req, res) => {
displayDate: new Date(row.date).toLocaleDateString('en-US', { day: '2-digit', month: 'short', year: 'numeric' })
}));
res.render('../partials/player-history', { pdgaNumber, history: formattedHistory });
const player = await getPlayerDataFromDB(pdgaNumber);
res.render('../partials/player-history', { pdgaNumber, history: formattedHistory, player });
} catch (error) {
logger.error('Error loading player history:', error.message);
res.status(500).send('<div class="loading-chart">Error loading rating history</div>');
@@ -81,75 +107,6 @@ router.get('/api/ratings/progress', (req, res) => {
});
});
router.post('/api/populate-database', (req, res) => {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'Access-Control-Allow-Origin': '*',
});
const progressCallback = (progress) => {
res.write(`data: ${JSON.stringify(progress)}\n\n`);
};
logger.info('=== Starting database population from database players ===');
refreshAllPlayersInDB(progressCallback).then(ratings => {
logger.info(`=== Database population complete: ${ratings.length} players refreshed ===`);
res.write(`data: ${JSON.stringify({ status: 'complete', ratings, message: `Successfully refreshed ${ratings.length} players` })}\n\n`);
res.end();
}).catch(error => {
logger.error('Error populating database:', error);
res.write(`data: ${JSON.stringify({ status: 'error', message: error.message })}\n\n`);
res.end();
});
});
router.get('/api/database-status', async (req, res) => {
try {
const playerCount = await new Promise((resolve, reject) => {
db.get('SELECT COUNT(*) as count FROM players', [], (err, row) => {
if (err) reject(err);
else resolve(row.count);
});
});
res.json({
playersInDB: playerCount,
needsPopulation: playerCount === 0
});
} catch (error) {
res.status(500).json({ error: 'Failed to check database status' });
}
});
router.get('/api/load-all-players', (req, res) => {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Cache-Control'
});
const progressCallback = (progress) => {
res.write(`data: ${JSON.stringify(progress)}\n\n`);
};
refreshAllPlayersInDB(progressCallback).then(ratings => {
res.write(`data: ${JSON.stringify({ status: 'complete', ratings })}\n\n`);
res.end();
}).catch(error => {
res.write(`data: ${JSON.stringify({ status: 'error', error: error.message })}\n\n`);
res.end();
});
req.on('close', () => {
res.end();
});
});
router.get('/api/rating-history/:pdgaNumber', async (req, res) => {
try {
const { pdgaNumber } = req.params;
+83 -11
View File
@@ -1,10 +1,32 @@
const { db } = require('../db');
const { getPlayerFromDB, getRoundHistoryFromDB, savePredictedRatingToDB, savePlayerToDB } = require('../models/player');
const { getPlayerFromDB, getRoundHistoryFromDB, savePredictedRatingToDB, savePlayerToDB, getMonthlyHistory, getAllMonthlyHistoriesFromDB } = require('../models/player');
const { fetchPlayerDataHTTP, parsePlayerData } = require('../scrapers/player-http');
const { calculatePredictedRating } = require('./rating-calculator');
const logger = require('../logger');
async function getPlayerDataFromDB(pdgaNumber) {
// Derives previous-month rating and the delta to it. Prefers PDGA's reported
// rating_change (canonical), falls back to our own monthly snapshots when
// rating_change is missing — common for players whose latest scrape failed.
function deriveMonthlyDeltas(rating, rawRatingChange, monthlyHistory) {
if (rating != null && rawRatingChange != null) {
return { lastMonthRating: rating - rawRatingChange, ratingChange: rawRatingChange };
}
if (rating != null && monthlyHistory && monthlyHistory.length >= 1) {
// The "last month" snapshot depends on whether current_rating is already in
// history. If equal, current is the most recent entry — last month is the one
// before it. If not, current is newer than history — the latest entry IS last month.
const lastIdx = monthlyHistory.length - 1;
const lastMonth = (monthlyHistory[lastIdx] === rating)
? (monthlyHistory.length >= 2 ? monthlyHistory[lastIdx - 1] : null)
: monthlyHistory[lastIdx];
if (lastMonth != null) {
return { lastMonthRating: lastMonth, ratingChange: rating - lastMonth };
}
}
return { lastMonthRating: null, ratingChange: rawRatingChange };
}
async function getPlayerDataFromDB(pdgaNumber, { includeMonthlyHistory = true } = {}) {
try {
const cachedPlayer = await getPlayerFromDB(pdgaNumber);
if (cachedPlayer) {
@@ -18,13 +40,29 @@ async function getPlayerDataFromDB(pdgaNumber) {
stdDev = updatedPlayer?.std_dev;
}
const rating = cachedPlayer.current_rating;
const rawRatingChange = cachedPlayer.rating_change;
const resolvedPredicted = predictedRating > 0 ? predictedRating : null;
const resolvedStdDev = stdDev > 0 ? stdDev : null;
// Skip in bulk-fetch paths where caller supplies history via getAllMonthlyHistoriesFromDB
const monthlyHistory = includeMonthlyHistory
? await getMonthlyHistory(cachedPlayer.pdga_number)
: [];
const { lastMonthRating, ratingChange } = deriveMonthlyDeltas(rating, rawRatingChange, monthlyHistory);
return {
pdgaNumber: cachedPlayer.pdga_number,
name: cachedPlayer.name,
rating: cachedPlayer.current_rating,
ratingChange: cachedPlayer.rating_change,
predictedRating: predictedRating > 0 ? predictedRating : null,
stdDev: stdDev > 0 ? stdDev : null
rating,
ratingChange,
predictedRating: resolvedPredicted,
stdDev: resolvedStdDev,
lastMonthRating,
// gap between next predicted update and current rating (null when either is missing)
deltaPredicted: (resolvedPredicted != null && rating != null) ? resolvedPredicted - rating : null,
monthlyHistory
};
}
return null;
@@ -127,6 +165,9 @@ async function getAllRatingsFromDB(progressCallback = null) {
logger.info(`Loading ${allPlayers.length} players from database...`);
// Fetch all monthly histories in one query so the per-player loop doesn't add N extra queries
const monthlyHistoryMap = await getAllMonthlyHistoriesFromDB(12);
const ratings = [];
const total = allPlayers.length;
@@ -144,9 +185,14 @@ async function getAllRatingsFromDB(progressCallback = null) {
}
try {
const playerData = await getPlayerDataFromDB(pdgaNumber);
const playerData = await getPlayerDataFromDB(pdgaNumber, { includeMonthlyHistory: false });
if (playerData) {
playerData.monthlyHistory = monthlyHistoryMap.get(pdgaNumber) ?? [];
// Re-derive now that history is attached — bulk path skipped includeMonthlyHistory
const derived = deriveMonthlyDeltas(playerData.rating, player.rating_change, playerData.monthlyHistory);
playerData.lastMonthRating = derived.lastMonthRating;
playerData.ratingChange = derived.ratingChange;
ratings.push(playerData);
}
@@ -161,12 +207,18 @@ async function getAllRatingsFromDB(progressCallback = null) {
}
} catch (error) {
logger.error(`Failed to load PDGA ${pdgaNumber} from database:`, error.message);
const errorRating = player.current_rating;
const errorRatingChange = player.rating_change;
const errorData = {
pdgaNumber: parseInt(pdgaNumber),
name: player.name || 'Database Error',
rating: player.current_rating,
ratingChange: player.rating_change,
predictedRating: null
rating: errorRating,
ratingChange: errorRatingChange,
predictedRating: null,
stdDev: null,
lastMonthRating: (errorRating != null && errorRatingChange != null) ? errorRating - errorRatingChange : null,
deltaPredicted: null,
monthlyHistory: []
};
ratings.push(errorData);
@@ -267,10 +319,30 @@ async function refreshAllPlayersInDB(progressCallback = null) {
}
}
/**
* Aggregates KPI summary stats from an already-fetched player array.
* All fields are derived from the player list — no extra DB queries.
*/
function computeKpis(players) {
const active = players.filter(p => p.rating != null && p.rating > 0);
const avg = active.length > 0
? Math.round(active.reduce((sum, p) => sum + p.rating, 0) / active.length)
: null;
return {
tracked: players.length,
active: active.length,
avg,
climbing: players.filter(p => p.ratingChange != null && p.ratingChange > 0).length,
slipping: players.filter(p => p.ratingChange != null && p.ratingChange < 0).length
};
}
module.exports = {
getPlayerDataFromDB,
scrapePDGARating,
getPredictedRatingFromDB,
getAllRatingsFromDB,
refreshAllPlayersInDB
refreshAllPlayersInDB,
computeKpis
};
+43
View File
@@ -0,0 +1,43 @@
const { getLastRefresh } = require('../models/player');
const logger = require('../logger');
function formatRelative(isoString) {
if (!isoString) return 'Never';
const then = new Date(isoString.replace(' ', 'T') + (isoString.endsWith('Z') ? '' : 'Z'));
const diffMs = Date.now() - then.getTime();
if (Number.isNaN(diffMs) || diffMs < 0) return 'Just now';
const sec = Math.floor(diffMs / 1000);
if (sec < 60) return 'Just now';
const min = Math.floor(sec / 60);
if (min < 60) return `${min} min ago`;
const hr = Math.floor(min / 60);
if (hr < 24) return `${hr} h ago`;
const day = Math.floor(hr / 24);
if (day === 1) return 'Yesterday';
if (day < 7) return `${day} days ago`;
return then.toISOString().slice(0, 10);
}
// First Tuesday of next month — approximation of PDGA's monthly cycle
function computeNextUpdate(now = new Date()) {
const year = now.getUTCFullYear();
const month = now.getUTCMonth() + 1; // next month, may roll over
const candidate = new Date(Date.UTC(month === 12 ? year + 1 : year, month === 12 ? 0 : month, 1));
// 0=Sun, 1=Mon, 2=Tue
const offset = (2 - candidate.getUTCDay() + 7) % 7;
candidate.setUTCDate(1 + offset);
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
return `${['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][candidate.getUTCDay()]} ${candidate.getUTCDate()} ${months[candidate.getUTCMonth()]}`;
}
async function getTopbarLocals() {
try {
const lastIso = await getLastRefresh();
return { lastRefresh: formatRelative(lastIso), nextUpdate: computeNextUpdate() };
} catch (err) {
logger.warn({ err }, 'topbar locals fallback');
return { lastRefresh: 'Unknown', nextUpdate: computeNextUpdate() };
}
}
module.exports = { getTopbarLocals };
-2
View File
@@ -19,13 +19,11 @@
</div>
</div>
<div id="loading" class="loading" style="display: none;">Loading courses...</div>
<div id="courses-table" hx-get="/partials/course-table" hx-trigger="load"></div>
`; %>
<%- include('../partials/layout', {
title: 'PDGA Courses - Sweden',
heading: 'PDGA Courses - Sweden',
activePage: 'courses',
cssFiles: ['courses.css'],
jsFiles: ['courses.js'],
+77 -28
View File
@@ -1,33 +1,83 @@
<% var body = `
<!-- Add Player Section -->
<div class="card-section">
<h3>Add Yourself to Tracked Players</h3>
<div class="card-section-form">
<input
type="number"
id="pdga-number-input"
class="input"
placeholder="Enter your PDGA number"
min="1"
style="width: 240px;"
/>
<button class="btn btn-add" onclick="searchAndAddPlayer()">
<i class="fas fa-user-plus"></i> Add Player
<!-- Add Player Card -->
<form class="add-bar" onsubmit="searchAndAddPlayer(event)">
<div class="add-bar-label">
<span class="add-bar-kicker">Track a player</span>
<span class="add-bar-hint">Add a PDGA number to start following their rating.</span>
</div>
<div class="add-bar-controls">
<div class="input-wrap">
<span class="input-prefix">#</span>
<input
type="text"
id="pdga-number-input"
inputmode="numeric"
placeholder="277890"
aria-label="PDGA number"
oninput="this.value = this.value.replace(/[^0-9]/g, '')"
/>
</div>
<button type="submit" class="btn-primary">
<i class="fas fa-user-plus"></i> Add player
</button>
</div>
</div>
<div style="display: flex; justify-content: flex-end; gap: 12px; margin-bottom: 16px;">
<a href="#" onclick="loadAllPlayers(); return false;" style="color: var(--accent); font-size: 12px; text-decoration: none;" title="Load all player data" id="load-all-btn">Load All</a>
<a href="#" onclick="clearCache(); return false;" style="color: var(--text-muted); font-size: 12px; text-decoration: none; opacity: 0.4;" title="Clear cache"><i class="fas fa-cog"></i></a>
</div>
<div id="loading" class="loading" style="display: none;">Loading ratings...</div>
<div id="progress-section" style="display: none;">
<div class="progress-container">
<div id="progress-bar" class="progress-bar">0%</div>
</form>
<!-- KPI Summary Tiles -->
<section class="kpi-strip" aria-label="Tracker overview">
<article class="kpi-tile">
<span class="kpi-rail"></span>
<div class="kpi-body">
<div class="kpi-value">${kpis.tracked}</div>
<div class="kpi-label">Tracked</div>
<div class="kpi-sub">${kpis.active} active</div>
</div>
<div id="progress-text" class="progress-text">Preparing to load ratings...</div>
</article>
<article class="kpi-tile">
<span class="kpi-rail"></span>
<div class="kpi-body">
<div class="kpi-value">${kpis.avg ?? '—'}</div>
<div class="kpi-label">Avg rating</div>
<div class="kpi-sub">across active players</div>
</div>
</article>
<article class="kpi-tile">
<span class="kpi-rail up"></span>
<div class="kpi-body">
<div class="kpi-value">${kpis.climbing}</div>
<div class="kpi-label">Climbing</div>
<div class="kpi-sub">this month</div>
</div>
</article>
<article class="kpi-tile">
<span class="kpi-rail down"></span>
<div class="kpi-body">
<div class="kpi-value">${kpis.slipping}</div>
<div class="kpi-label">Slipping</div>
<div class="kpi-sub">this month</div>
</div>
</article>
</section>
<!-- Players Table Card -->
<div class="table-card">
<div class="table-toolbar">
<span class="kicker">TRACKED PLAYERS</span>
<div class="toolbar-actions">
<button id="trendchart-toggle" class="pill-toggle" type="button" aria-pressed="false">
<svg class="pill-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M3 17l5-6 4 4 4-7 5 6" />
</svg>
<span class="pill-label">Trend chart</span>
<span class="pill-dot"></span>
</button>
</div>
</div>
<div id="ratings-table" hx-get="/partials/ratings-table" hx-trigger="load"></div>
</div>
<div id="ratings-table" hx-get="/partials/ratings-table" hx-trigger="load"></div>
<!-- Footnote -->
<p class="footnote">Unofficial PDGA rating tracker. Ratings scraped from pdga.com on each refresh.</p>
`; %>
<% var modals = `
@@ -56,11 +106,10 @@
<%- include('../partials/layout', {
title: 'PDGA Ratings',
heading: 'PDGA Player Ratings',
activePage: 'players',
cssFiles: ['players.css'],
jsFiles: ['tooltips.js', 'chart.js', 'progress.js', 'players.js'],
jsFiles: ['tooltips.js', 'chart.js', 'players.js'],
initScript: 'setupTooltipsAfterSwap();',
body: body,
modals: modals
}) %>
}) %>
+12
View File
@@ -0,0 +1,12 @@
<%/* delta-pill.ejs — renders a Δ-pill span.
Locals:
value {number|null} — the delta value (null/undefined → flat pill with '—')
extraClass {string} — optional additional CSS class (e.g. 'delta-predicted-pill')
*/%>
<%
const _isNull = (typeof value === 'undefined' || value == null);
const _cls = _isNull ? 'flat' : value > 0 ? 'up' : value < 0 ? 'down' : 'flat';
const _glyph = (_isNull || value === 0) ? '' : value > 0 ? '▲' : '▼';
const _num = _isNull ? '—' : value > 0 ? '+' + value : value.toString();
const _xtra = (typeof extraClass !== 'undefined' && extraClass) ? ' ' + extraClass : '';
%><span class="delta-pill <%= _cls %><%= _xtra %>"><span class="delta-glyph"><%= _glyph %></span><span class="delta-num"><%= _num %></span></span>
+4 -9
View File
@@ -5,6 +5,9 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><%= title %></title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:ital,wght@0,300..800;1,300..800&family=JetBrains+Mono:wght@400;500;600;700&display=swap" rel="stylesheet">
<script src="https://unpkg.com/htmx.org@2.0.4"></script>
<link rel="stylesheet" href="/css/shared.css">
<% if (typeof cssFiles !== 'undefined') { %>
@@ -14,15 +17,7 @@
<% } %>
</head>
<body>
<header class="app-header">
<div class="header-inner">
<a href="/" class="app-logo">
<span class="logo-icon"><i class="fas fa-compact-disc"></i></span>
PDGA Ratings
</a>
<%- include('../partials/nav') %>
</div>
</header>
<%- include('../partials/topbar', { activePage, lastRefresh, nextUpdate }) %>
<div class="container">
<%- body %>
+42 -12
View File
@@ -1,12 +1,42 @@
<% if (history && history.length > 0) { %>
<div class="chart-container" id="chart-<%= pdgaNumber %>"
data-history="<%= JSON.stringify(history) %>"
style="position: relative;">
<div class="loading-chart">Loading chart...</div>
</div>
<div class="chart-tooltip" id="tooltip-<%= pdgaNumber %>"></div>
<% } else { %>
<div class="chart-container">
<div class="loading-chart">No rating history available</div>
</div>
<% } %>
<%
const hasPlayer = (typeof player !== 'undefined' && player);
const chartPdgaNumber = hasPlayer ? player.pdgaNumber : pdgaNumber;
%>
<div class="player-detail">
<% if (hasPlayer) { %>
<div class="player-detail-left">
<dl class="detail-grid">
<div>
<dt>Current rating</dt>
<dd><%= player.rating ?? '—' %></dd>
</div>
<div>
<dt>Last month</dt>
<dd><%= player.lastMonthRating ?? '—' %></dd>
</div>
<div>
<dt>Change vs last month</dt>
<dd><%- include('delta-pill', { value: player.ratingChange }) %></dd>
</div>
<div>
<dt>Predicted next update</dt>
<dd><%= player.predictedRating ?? '—' %></dd>
</div>
<div>
<dt>Gap to predicted</dt>
<dd><%- include('delta-pill', { value: player.deltaPredicted, extraClass: 'delta-predicted-pill' }) %></dd>
</div>
</dl>
<button class="link-btn" onclick="showDebugInfo(<%= player.pdgaNumber %>)" style="margin-top: 4px;">View calculation details →</button>
</div>
<% } %>
<% if (history && history.length > 0) { %>
<div class="player-chart" id="chart-<%= chartPdgaNumber %>"
data-history="<%= JSON.stringify(history) %>">
</div>
<% } else { %>
<div class="loading-chart">No rating history available</div>
<% } %>
</div>
<div class="chart-tooltip" id="tooltip-<%= chartPdgaNumber %>"></div>
+73 -37
View File
@@ -1,58 +1,94 @@
<%
function renderSparkline(values) {
if (!values || values.length < 2) return '';
var w = 96, h = 28;
var min = Math.min.apply(null, values);
var max = Math.max.apply(null, values);
var range = max - min || 1;
var xStep = w / (values.length - 1);
var pts = values.map(function(v, i) {
return {
x: (i * xStep).toFixed(1),
y: (((max - v) / range) * (h - 4) + 2).toFixed(1)
};
});
var linePath = pts.map(function(p, i) {
return (i === 0 ? 'M' : 'L') + ' ' + p.x + ' ' + p.y;
}).join(' ');
var last = pts[pts.length - 1];
var areaPath = linePath + ' L ' + last.x + ' ' + h + ' L 0 ' + h + ' Z';
return '<svg width="' + w + '" height="' + h + '" viewBox="0 0 ' + w + ' ' + h + '" class="spark" aria-hidden="true">' +
'<path d="' + areaPath + '" style="fill:var(--accent);fill-opacity:0.10"/>' +
'<path d="' + linePath + '" style="stroke:var(--accent);stroke-width:1.5;fill:none;stroke-linejoin:round;stroke-linecap:round"/>' +
'<circle cx="' + last.x + '" cy="' + last.y + '" r="2.5" style="fill:var(--accent)"/>' +
'</svg>';
}
%>
<% if (ratings.length === 0) { %>
<p style="text-align: center; color: var(--text-muted); padding: 40px 0;">No ratings found.</p>
<p style="text-align: center; color: var(--ink-3); padding: 40px 0;">No players tracked yet.</p>
<% } else { %>
<table>
<thead>
<tr>
<th class="mobile-hide">Rank</th>
<th>Player Name</th>
<th class="mobile-hide">PDGA #</th>
<th>Rating</th>
<th class="mobile-hide">Change</th>
<th class="mobile-hide">Predicted</th>
<th class="col-rank">#</th>
<th class="col-player">Player</th>
<th class="col-rating">Rating<span class="th-hint">+ Δ since last update</span></th>
<th class="col-predicted">Predicted<span class="th-hint">+ gap from today</span></th>
<th class="col-actions"></th>
</tr>
</thead>
<tbody>
<% ratings.forEach(function(player, index) {
var difference = player.predictedRating && player.rating ? player.predictedRating - player.rating : 0;
var diffText = difference > 0 ? '+' + difference : difference.toString();
var diffClass = difference > 0 ? 'positive' : difference < 0 ? 'negative' : 'neutral';
var ratingChangeText = player.ratingChange ? (player.ratingChange > 0 ? '+' + player.ratingChange : player.ratingChange.toString()) : 'N/A';
var ratingChangeClass = player.ratingChange > 0 ? 'positive' : player.ratingChange < 0 ? 'negative' : 'neutral';
const sparklineSvg = renderSparkline(player.monthlyHistory || []);
%>
<tr id="row-<%= player.pdgaNumber %>" class="expandable-row" onclick="togglePlayerHistory(<%= player.pdgaNumber %>)">
<td class="mobile-hide"><%= index + 1 %></td>
<td class="player-name">
<a href="https://www.pdga.com/player/<%= player.pdgaNumber %>" target="_blank" onclick="event.stopPropagation()"><%= player.name %></a>
<div class="mobile-only pdga-number" style="font-size: 11px; margin-top: 2px;">PDGA #<%= player.pdgaNumber %></div>
<tr id="row-<%= player.pdgaNumber %>" class="expandable-row" tabindex="0" onclick="togglePlayerHistory(<%= player.pdgaNumber %>)">
<td class="col-rank">
<span class="rank-num mono"><%= index + 1 %></span>
</td>
<td class="pdga-number mobile-hide">#<%= player.pdgaNumber %></td>
<td class="rating">
<div class="refresh-section">
<span class="rating-value" data-rating="<%= player.rating || '' %>" data-stddev="<%= player.stdDev || '' %>" data-pdga="<%= player.pdgaNumber %>" style="cursor: help;"><%- player.rating || '<span style="color: var(--text-muted); font-style: italic;">Click refresh</span>' %></span>
<i class="fas fa-sync-alt refresh-icon" onclick="refreshPlayer(<%= player.pdgaNumber %>)" title="Refresh player data"></i>
<td class="col-player">
<div class="cell-name">
<span class="player-name"><a href="https://www.pdga.com/player/<%= player.pdgaNumber %>" target="_blank" onclick="event.stopPropagation()"><%= player.name %></a></span>
<span class="pdga-num mono">#<%= player.pdgaNumber %></span>
</div>
<div class="mobile-only rating-change <%= ratingChangeClass %>" style="font-size: 11px; margin-top: 2px;"><%= ratingChangeText %></div>
</td>
<td class="col-rating cell-rating">
<% if (player.rating) { %>
<div class="rating-stack">
<span class="rating-value rating-big mono" data-rating="<%= player.rating || '' %>" data-stddev="<%= player.stdDev || '' %>" data-pdga="<%= player.pdgaNumber %>"><%= player.rating %></span>
<%- include('delta-pill', { value: player.ratingChange }) %>
<% if (sparklineSvg) { %><span class="sparkline"><%- sparklineSvg %></span><% } %>
</div>
<% } else { %>
<span class="rating-pending">Click to load</span>
<% } %>
<div class="std-dev-tooltip" id="tooltip-rating-<%= player.pdgaNumber %>"></div>
</td>
<td class="rating-change <%= ratingChangeClass %> mobile-hide"><%= ratingChangeText %></td>
<td class="predicted-rating mobile-hide" id="predicted-<%= player.pdgaNumber %>">
<div class="refresh-section">
<span class="predicted-value" data-stddev="<%= player.stdDev || '' %>" data-pdga="<%= player.pdgaNumber %>" style="cursor: help;"><%= player.predictedRating || 'N/A' %></span>
<i class="fas fa-question-circle debug-icon" onclick="showDebugInfo(<%= player.pdgaNumber %>)" title="Show calculation details" style="margin-left: 5px; color: var(--text-muted); cursor: pointer; opacity: 0.6;"></i>
<i class="fas fa-sync-alt refresh-icon" onclick="refreshRoundHistory(<%= player.pdgaNumber %>)" title="Refresh prediction data"></i>
<td class="col-predicted" id="predicted-<%= player.pdgaNumber %>">
<% if (player.predictedRating) { %>
<div class="pred-stack">
<span class="predicted-value pred-num mono" data-stddev="<%= player.stdDev || '' %>" data-pdga="<%= player.pdgaNumber %>"><%= player.predictedRating %></span>
<%- include('delta-pill', { value: player.deltaPredicted, extraClass: 'delta-predicted-pill' }) %>
</div>
<% } else { %>
<span class="rating-pending">—</span>
<% } %>
<div class="std-dev-tooltip" id="tooltip-stddev-<%= player.pdgaNumber %>"></div>
</td>
<td class="col-actions cell-actions" onclick="event.stopPropagation()">
<button class="icon-btn refresh-icon" onclick="refreshPlayerData(<%= player.pdgaNumber %>)" title="Refresh rating + prediction" aria-label="Refresh rating and prediction">
<i class="fas fa-sync-alt"></i>
</button>
<button class="icon-btn icon-chev" onclick="togglePlayerHistory(<%= player.pdgaNumber %>)" title="Expand row" aria-label="Expand">
<i class="fas fa-chevron-down"></i>
</button>
</td>
</tr>
<tr id="history-<%= player.pdgaNumber %>" class="expanded-content">
<td colspan="6" class="expanded-cell">
<div class="chart-title">
<div class="refresh-section">
Rating History for <%= player.name %>
<i class="fas fa-sync-alt refresh-icon" onclick="refreshRatingHistory(<%= player.pdgaNumber %>)" title="Refresh rating history"></i>
</div>
</div>
<td colspan="5" class="expanded-cell">
<div id="history-content-<%= player.pdgaNumber %>">
<div class="loading-chart">Click to load rating history...</div>
</div>
@@ -61,4 +97,4 @@
<% }); %>
</tbody>
</table>
<% } %>
<% } %>
+46
View File
@@ -0,0 +1,46 @@
<header class="topbar" id="topbar">
<div class="topbar__inner">
<a href="/" class="topbar__brand">
<span class="topbar__brand-mark" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M3 17 L9 11 L13 15 L21 6" />
<path d="M14 6 L21 6 L21 13" />
</svg>
</span>
<span class="topbar__brand-text">
<span class="topbar__brand-title">Rating Tracker</span>
<span class="topbar__brand-sub">Disc golf · unofficial</span>
</span>
</a>
<nav class="topbar__nav" aria-label="Primary">
<a href="/" class="<%= activePage === 'players' ? 'active' : '' %>">Players</a>
<a href="/courses" class="<%= activePage === 'courses' ? 'active' : '' %>">Courses</a>
</nav>
<div class="topbar__meta">
<div class="topbar__meta-item">
<span class="topbar__meta-label">Next update</span>
<span class="topbar__meta-value"><%= nextUpdate %></span>
</div>
<div class="topbar__meta-item">
<span class="topbar__meta-label">Last refresh</span>
<span class="topbar__meta-value"><%= lastRefresh %></span>
</div>
<span class="topbar__divider" aria-hidden="true"></span>
<button
class="topbar__refresh"
type="button"
hx-post="/api/refresh-all"
hx-vals='{"page": "<%= activePage %>"}'
hx-target="#topbar"
hx-swap="outerHTML"
hx-disabled-elt="this"
>
<span class="topbar__refresh-icon" aria-hidden="true">↻</span>
<span class="topbar__refresh-spinner" aria-hidden="true"></span>
<span class="topbar__refresh-label">Refresh all</span>
</button>
</div>
</div>
</header>