Files
pdga-rating/index.html
T
Samuel Enocsson 2994f221f7 Add cache management and smart delay optimization
- Add subtle "clear cache" link (gear icon) in top-right corner
- Implement cache clearing endpoint with user feedback
- Fix delay logic to skip delays for cached data
- Only apply rate limiting delays when actually scraping fresh data
- Add cache size reporting when clearing cache
- Improve performance for repeat visits with cached data
- Maintain server-friendly rate limiting for fresh scrapes

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-08-12 17:04:14 +02:00

544 lines
22 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PDGA Ratings</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 40px;
background-color: #f5f5f5;
}
.container {
max-width: 800px;
margin: 0 auto;
background: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
h1 {
color: #333;
text-align: center;
margin-bottom: 30px;
}
.loading {
text-align: center;
padding: 20px;
font-size: 18px;
color: #666;
}
.progress-container {
width: 100%;
background-color: #f0f0f0;
border-radius: 10px;
padding: 3px;
margin: 20px 0;
}
.progress-bar {
width: 0%;
height: 30px;
background-color: #007bff;
border-radius: 8px;
text-align: center;
line-height: 30px;
color: white;
font-weight: bold;
transition: width 0.3s ease;
}
.progress-text {
text-align: center;
margin: 10px 0;
font-size: 16px;
color: #666;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
th, td {
padding: 12px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background-color: #f8f9fa;
font-weight: bold;
color: #495057;
}
tr:hover {
background-color: #f5f5f5;
}
.expandable-row {
cursor: pointer;
}
.expandable-row:hover {
background-color: #e3f2fd;
}
.expanded-content {
display: none;
background-color: #f8f9fa;
border-top: 2px solid #007bff;
}
.expanded-content td {
padding: 20px;
}
.chart-container {
width: 100%;
height: 300px;
margin: 10px 0;
border: 1px solid #ddd;
border-radius: 4px;
background: white;
}
.chart-title {
text-align: center;
font-weight: bold;
margin-bottom: 10px;
color: #333;
}
.loading-chart {
display: flex;
justify-content: center;
align-items: center;
height: 200px;
color: #666;
}
.chart-tooltip {
position: fixed;
background-color: rgba(0, 0, 0, 0.9);
color: white;
padding: 8px 12px;
border-radius: 4px;
font-size: 12px;
pointer-events: none;
z-index: 10000;
display: none;
white-space: nowrap;
box-shadow: 0 2px 8px rgba(0,0,0,0.3);
border: 1px solid rgba(255,255,255,0.2);
}
.rating {
font-weight: bold;
color: #007bff;
}
.pdga-number {
color: #6c757d;
font-size: 14px;
}
.difference {
font-weight: bold;
}
.positive {
color: #28a745;
}
.negative {
color: #dc3545;
}
.neutral {
color: #6c757d;
}
.calc-btn {
background-color: #17a2b8;
color: white;
border: none;
padding: 5px 10px;
border-radius: 3px;
cursor: pointer;
font-size: 12px;
}
.calc-btn:hover {
background-color: #138496;
}
.calc-btn:disabled {
background-color: #6c757d;
cursor: not-allowed;
}
.rating-change {
font-weight: bold;
font-size: 14px;
}
a {
color: #007bff;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<div class="container">
<h1>PDGA Player Ratings</h1>
<div style="position: absolute; top: 10px; right: 15px;">
<a href="#" onclick="clearCache(); return false;" style="color: #ccc; font-size: 10px; text-decoration: none; opacity: 0.3;" title="Clear cache"></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>
</div>
<div id="progress-text" class="progress-text">Preparing to load ratings...</div>
</div>
<div id="ratings-table"></div>
</div>
<script>
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';
displayRatings(data.ratings);
eventSource.close();
} else if (data.status === 'error') {
progressSection.style.display = 'none';
tableDiv.innerHTML = '<p>Error loading ratings. Please try again.</p>';
eventSource.close();
}
};
eventSource.onerror = function() {
progressSection.style.display = 'none';
tableDiv.innerHTML = '<p>Connection error. Please refresh the page.</p>';
eventSource.close();
};
}
function displayRatings(ratings) {
const tableDiv = document.getElementById('ratings-table');
if (ratings.length === 0) {
tableDiv.innerHTML = '<p>No ratings found.</p>';
return;
}
let tableHTML = `
<table>
<thead>
<tr>
<th>Rank</th>
<th>Player Name</th>
<th>PDGA #</th>
<th>Current Rating</th>
<th>Rating Change</th>
<th>Predicted Rating</th>
<th>Difference</th>
</tr>
</thead>
<tbody>
`;
ratings.forEach((player, index) => {
const difference = player.predictedRating && player.rating ?
player.predictedRating - player.rating : 0;
const diffText = difference > 0 ? `+${difference}` : difference.toString();
const diffClass = difference > 0 ? 'positive' : difference < 0 ? 'negative' : 'neutral';
const ratingChangeText = player.ratingChange ?
(player.ratingChange > 0 ? `+${player.ratingChange}` : player.ratingChange.toString()) : 'N/A';
const ratingChangeClass = player.ratingChange > 0 ? 'positive' :
player.ratingChange < 0 ? 'negative' : 'neutral';
tableHTML += `
<tr id="row-${player.pdgaNumber}" class="expandable-row" onclick="togglePlayerHistory(${player.pdgaNumber})">
<td>${index + 1}</td>
<td><a href="https://www.pdga.com/player/${player.pdgaNumber}" target="_blank" onclick="event.stopPropagation()">${player.name}</a></td>
<td class="pdga-number">#${player.pdgaNumber}</td>
<td class="rating">${player.rating || 'N/A'}</td>
<td class="rating-change ${ratingChangeClass}">${ratingChangeText}</td>
<td class="predicted-rating" id="predicted-${player.pdgaNumber}">
${player.predictedRating || 'N/A'}
</td>
<td class="difference ${diffClass}" id="diff-${player.pdgaNumber}">
${difference ? diffText :
`<button class="calc-btn" onclick="event.stopPropagation(); calculatePredictedRating(${player.pdgaNumber})">Predict Rating</button>`}
</td>
</tr>
<tr id="history-${player.pdgaNumber}" class="expanded-content">
<td colspan="7">
<div class="chart-title">Rating History for ${player.name}</div>
<div class="chart-container" id="chart-${player.pdgaNumber}" style="position: relative;">
<div class="loading-chart">Click to load rating history...</div>
</div>
<div class="chart-tooltip" id="tooltip-${player.pdgaNumber}"></div>
</td>
</tr>
`;
});
tableHTML += `
</tbody>
</table>
`;
tableDiv.innerHTML = tableHTML;
}
async function calculatePredictedRating(pdgaNumber) {
const button = document.querySelector(`#diff-${pdgaNumber} .calc-btn`);
const predictedCell = document.getElementById(`predicted-${pdgaNumber}`);
const diffCell = document.getElementById(`diff-${pdgaNumber}`);
button.disabled = true;
button.textContent = 'Calculating...';
try {
const response = await fetch(`/api/predicted-rating/${pdgaNumber}`, {
method: 'POST'
});
const data = await response.json();
if (data.predictedRating && data.predictedRating > 0) {
predictedCell.textContent = data.predictedRating;
const currentRating = parseInt(document.querySelector(`#row-${pdgaNumber} .rating`).textContent);
const difference = data.predictedRating - currentRating;
const diffText = difference > 0 ? `+${difference}` : difference.toString();
const diffClass = difference > 0 ? 'positive' : difference < 0 ? 'negative' : 'neutral';
diffCell.className = `difference ${diffClass}`;
diffCell.textContent = diffText;
} else {
predictedCell.textContent = 'N/A';
diffCell.innerHTML = '<span style="color: #999; font-size: 12px;">Unable to calculate<br>(Try again later)</span>';
}
} catch (error) {
console.error('Error calculating predicted rating:', error);
predictedCell.textContent = 'Error';
button.disabled = false;
button.textContent = 'Predict Rating';
}
}
async function togglePlayerHistory(pdgaNumber) {
const historyRow = document.getElementById(`history-${pdgaNumber}`);
const chartContainer = document.getElementById(`chart-${pdgaNumber}`);
if (historyRow.style.display === 'table-row') {
historyRow.style.display = 'none';
return;
}
historyRow.style.display = 'table-row';
// Check if chart is already loaded
if (chartContainer.dataset.loaded === 'true') {
return;
}
// Show loading state
chartContainer.innerHTML = '<div class="loading-chart">Loading rating history...</div>';
try {
const response = await fetch(`/api/rating-history/${pdgaNumber}`);
const data = await response.json();
if (data.history && data.history.length > 0) {
createRatingChart(chartContainer, data.history);
chartContainer.dataset.loaded = 'true';
} else {
chartContainer.innerHTML = '<div class="loading-chart">No rating history available</div>';
}
} catch (error) {
console.error('Error loading rating history:', error);
chartContainer.innerHTML = '<div class="loading-chart">Error loading rating history</div>';
}
}
function createRatingChart(container, history) {
const width = container.clientWidth - 40;
const height = 250;
const margin = { top: 20, right: 30, bottom: 40, left: 60 };
const chartWidth = width - margin.left - margin.right;
const chartHeight = height - margin.top - margin.bottom;
// Get the tooltip element
const pdgaNumber = container.id.replace('chart-', '');
const tooltip = document.getElementById(`tooltip-${pdgaNumber}`);
// Calculate scales
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);
// Create SVG
let svg = `<svg width="${width}" height="${height}" style="font-family: Arial, sans-serif;" id="svg-${pdgaNumber}">`;
// Background
svg += `<rect x="0" y="0" width="${width}" height="${height}" fill="white" stroke="#ddd"/>`;
// Chart area background
svg += `<rect x="${margin.left}" y="${margin.top}" width="${chartWidth}" height="${chartHeight}" fill="#f9f9f9" stroke="#ccc"/>`;
// Grid lines
for (let i = 0; i <= 5; i++) {
const y = margin.top + (i * chartHeight / 5);
const rating = Math.round(maxRating - (i * (maxRating - minRating) / 5));
svg += `<line x1="${margin.left}" y1="${y}" x2="${margin.left + chartWidth}" y2="${y}" stroke="#e0e0e0"/>`;
svg += `<text x="${margin.left - 5}" y="${y + 4}" text-anchor="end" font-size="12" fill="#666">${rating}</text>`;
}
// Data line
let pathData = '';
const points = [];
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 });
if (i === 0) {
pathData += `M ${x} ${y}`;
} else {
pathData += ` L ${x} ${y}`;
}
});
// Draw line
svg += `<path d="${pathData}" stroke="#007bff" stroke-width="2" fill="none"/>`;
// Draw points with enhanced hover areas
points.forEach((point, i) => {
svg += `<circle cx="${point.x}" cy="${point.y}" r="12" fill="transparent" class="hover-area" data-index="${i}" style="cursor: pointer;"/>`;
svg += `<circle cx="${point.x}" cy="${point.y}" r="4" fill="#007bff" stroke="white" stroke-width="2" class="data-point" data-index="${i}" style="pointer-events: none;"/>`;
});
// X-axis labels (show every few dates to avoid crowding)
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 - 10}" text-anchor="middle" font-size="11" fill="#666">${date}</text>`;
}
});
// Y-axis label
svg += `<text x="20" y="${height/2}" text-anchor="middle" font-size="12" fill="#333" transform="rotate(-90, 20, ${height/2})">Rating</text>`;
svg += '</svg>';
container.innerHTML = svg;
// Add event listeners for tooltips after a small delay to ensure DOM is ready
setTimeout(() => {
const svgElement = document.getElementById(`svg-${pdgaNumber}`);
if (svgElement) {
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) => {
// Clear any pending hide
if (tooltipTimeout) {
clearTimeout(tooltipTimeout);
tooltipTimeout = null;
}
// Hide current tooltip if different
if (currentTooltip !== null && currentTooltip !== i) {
dataPoints[currentTooltip].setAttribute('r', '4');
dataPoints[currentTooltip].setAttribute('fill', '#007bff');
}
currentTooltip = i;
const point = points[i];
tooltip.innerHTML = `<strong>${point.date}</strong><br>Rating: ${point.rating}`;
tooltip.style.display = 'block';
tooltip.style.left = `${e.clientX + 15}px`;
tooltip.style.top = `${e.clientY - 35}px`;
// Highlight the data point
dataPoints[i].setAttribute('r', '6');
dataPoints[i].setAttribute('fill', '#0056b3');
});
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) {
// Delay hiding to prevent flicker
tooltipTimeout = setTimeout(() => {
tooltip.style.display = 'none';
dataPoints[i].setAttribute('r', '4');
dataPoints[i].setAttribute('fill', '#007bff');
currentTooltip = null;
}, 100);
}
});
});
}
}, 100);
}
async function clearCache() {
try {
const response = await fetch('/api/clear-cache', {
method: 'POST'
});
const data = await response.json();
if (data.success) {
alert(data.message);
// Optionally reload the page to reflect fresh data
if (confirm('Reload page to fetch fresh data?')) {
location.reload();
}
} else {
alert('Failed to clear cache');
}
} catch (error) {
console.error('Error clearing cache:', error);
alert('Error clearing cache');
}
}
fetchRatingsWithProgress();
</script>
</body>
</html>