Files
Lutris-Playtime-Report-Gene…/templates/script.js

890 lines
35 KiB
JavaScript
Raw Normal View History

/****************************************************************************************************
* Copyright (C) 2026 by WallyHackenslacker wallyhackenslacker@noreply.git.hackenslacker.space *
* *
* Permission to use, copy, modify, and/or distribute this software for any purpose with or without *
* fee is hereby granted. *
* *
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS *
* SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE *
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES *
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, *
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE *
* OF THIS SOFTWARE. *
****************************************************************************************************/
/*
* Report UI controller
* --------------------
* This script powers all client-side behavior for the generated report page:
* 1) Theme handling (auto/light/dark) + persistence in localStorage
* 2) Data aggregation from embedded game data
* 3) Chart.js chart creation and refresh after filter/theme changes
* 4) Table rendering with expandable "Others" rows
* 5) Small UI helpers (tabs, scroll-to-top button)
*
* The generator injects placeholders such as __ALL_GAMES__, __TOP_N__, and __THEME_CONFIG__
* before this script reaches the browser.
*/
// Theme management
const themeToggle = document.getElementById('theme-toggle');
const themeIcon = document.getElementById('theme-icon');
const themes = ['auto', 'light', 'dark'];
let currentThemeIndex = 0;
// Returns the current OS/browser theme preference.
function getSystemTheme() {
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
/*
* Updates button icon/title to reflect currently selected mode.
*
* Note: "auto" does not hard-force a theme; it follows system preference.
*/
function updateThemeIcon() {
const theme = themes[currentThemeIndex];
if (theme === 'auto') {
themeIcon.textContent = '';
themeIcon.className = 'icon icon-auto';
themeToggle.title = 'Theme: Auto (click to change)';
} else if (theme === 'light') {
themeIcon.textContent = '\u2600\uFE0F';
themeIcon.className = 'icon';
themeToggle.title = 'Theme: Light (click to change)';
} else {
themeIcon.textContent = '\uD83C\uDF19';
themeIcon.className = 'icon';
themeToggle.title = 'Theme: Dark (click to change)';
}
}
/*
* Applies the selected theme mode to the root element and re-syncs all dependent UI.
*
* Behavior:
* - auto: remove data-theme so CSS/media-query driven defaults can apply
* - light/dark: set data-theme explicitly for deterministic styling
*
* Also updates chart legend colors because those are configured in JS, not pure CSS.
*/
function applyTheme() {
const theme = themes[currentThemeIndex];
if (theme === 'auto') {
document.documentElement.removeAttribute('data-theme');
} else {
document.documentElement.setAttribute('data-theme', theme);
}
updateThemeIcon();
localStorage.setItem('theme', theme);
updateChartColors();
}
// Restores previously saved theme mode; defaults to "auto" when absent/invalid.
function loadSavedTheme() {
const saved = localStorage.getItem('theme');
if (saved) {
currentThemeIndex = themes.indexOf(saved);
if (currentThemeIndex === -1) currentThemeIndex = 0;
}
applyTheme();
}
// Cycle theme modes in a fixed order: auto -> light -> dark -> auto.
themeToggle.addEventListener('click', () => {
currentThemeIndex = (currentThemeIndex + 1) % themes.length;
applyTheme();
});
// When system theme changes and mode is "auto", refresh theme-dependent UI pieces.
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
if (themes[currentThemeIndex] === 'auto') {
updateThemeIcon();
updateChartColors();
}
});
// Data and chart logic
const allGames = __ALL_GAMES__;
const topN = __TOP_N__;
// Theme-specific configuration
const themeConfig = __THEME_CONFIG__;
// Converts decimal hours to a compact human-friendly string (e.g. 1.5 -> "1h 30m").
function formatTime(hours) {
const h = Math.floor(hours);
const m = Math.round((hours - h) * 60);
if (h === 0) return m + 'm';
if (m === 0) return h + 'h';
return h + 'h ' + m + 'm';
}
/*
* Aggregates game list by service/source for checkbox filter creation.
*
* Output is sorted by playtime descending so the most relevant services appear first.
*/
function getServices() {
const services = {};
allGames.forEach(g => {
const s = g.service;
if (!services[s]) services[s] = { count: 0, playtime: 0 };
services[s].count++;
services[s].playtime += g.playtime;
});
return Object.entries(services)
.sort((a, b) => b[1].playtime - a[1].playtime)
.map(([name, data]) => ({ name, ...data }));
}
const services = getServices();
const filtersDiv = document.getElementById('filters');
// Build one checkbox per service so users can include/exclude data dynamically.
services.forEach(service => {
const label = document.createElement('label');
label.className = 'filter-label';
label.innerHTML = `
<input type="checkbox" value="${service.name}" checked>
<span class="service-name">${service.name}</span>
<span class="service-count">(${service.count})</span>
`;
filtersDiv.appendChild(label);
});
let chart = null;
let categoriesChart = null;
let runnersChart = null;
let sourcesChart = null;
const ctx = document.getElementById('playtime-chart').getContext('2d');
const ctxCategories = document.getElementById('categories-chart').getContext('2d');
const ctxRunners = document.getElementById('runners-chart').getContext('2d');
const ctxSources = document.getElementById('sources-chart').getContext('2d');
// Initialize theme after chart variables are declared
loadSavedTheme();
// Reads currently checked service filters from the filter panel.
function getSelectedServices() {
const checkboxes = filtersDiv.querySelectorAll('input[type="checkbox"]');
return Array.from(checkboxes)
.filter(cb => cb.checked)
.map(cb => cb.value);
}
/*
* Produces all derived datasets required by charts and tables for the current filters.
*
* Returns:
* - chartData: top games list used by the main playtime chart/table
* - othersGames: the overflow games collapsed into chartData's "Others" bucket
* - categoriesData/runnersData/sourcesData: grouped aggregations for secondary views
* - totalPlaytime/totalGames: summary statistics for header counters and percentages
*
* Example (topN = 5):
* - 18 filtered games => 5 explicit entries + 1 synthetic "Others (13 games)" entry
* - the 13 overflow games are still accessible in expandable table detail rows
*/
function getFilteredData(selectedServices) {
const filtered = allGames
.filter(g => selectedServices.includes(g.service))
.sort((a, b) => b.playtime - a.playtime);
if (filtered.length === 0) {
return { chartData: [], othersGames: [], categoriesData: [], totalPlaytime: 0, totalGames: 0 };
}
const totalPlaytime = filtered.reduce((sum, g) => sum + g.playtime, 0);
const totalGames = filtered.length;
// Keep only top N games for chart readability.
const topGames = filtered.slice(0, topN).map(g => ({
name: g.name,
playtime: g.playtime,
service: g.service,
categories: g.categories || []
}));
let othersGames = [];
// Collapse remaining entries into a single "Others" slice while preserving detail rows.
if (filtered.length > topN) {
othersGames = filtered.slice(topN).map(g => ({
name: g.name,
playtime: g.playtime,
service: g.service,
categories: g.categories || []
}));
const othersPlaytime = othersGames.reduce((sum, g) => sum + g.playtime, 0);
const othersCount = othersGames.length;
topGames.push({
name: `Others (${othersCount} games)`,
playtime: othersPlaytime,
service: 'others'
});
}
/*
* Category aggregation notes:
* - A game's full playtime contributes to each of its categories.
* - Internal/special categories are intentionally hidden from report views.
*
* Example:
* Game X (10h) in [RPG, Coop] increases RPG by 10h and Coop by 10h.
*/
const categoryMap = {};
filtered.forEach(g => {
if (g.categories && g.categories.length > 0) {
g.categories.forEach(cat => {
if (cat === '.hidden' || cat === 'favorite') return;
if (!categoryMap[cat]) {
categoryMap[cat] = { name: cat, playtime: 0, gameCount: 0 };
}
categoryMap[cat].playtime += g.playtime;
categoryMap[cat].gameCount++;
});
}
});
const categoriesData = Object.values(categoryMap)
.sort((a, b) => b.playtime - a.playtime);
// Aggregate by runner (wine, native, dosbox, etc.). Missing values become "unknown".
const runnerMap = {};
filtered.forEach(g => {
const runner = g.runner || 'unknown';
if (!runnerMap[runner]) {
runnerMap[runner] = { name: runner, playtime: 0, gameCount: 0 };
}
runnerMap[runner].playtime += g.playtime;
runnerMap[runner].gameCount++;
});
const runnersData = Object.values(runnerMap)
.sort((a, b) => b.playtime - a.playtime);
// Aggregate by source/service to power the Sources chart.
const sourceMap = {};
filtered.forEach(g => {
const source = g.service || 'unknown';
if (!sourceMap[source]) {
sourceMap[source] = { name: source, playtime: 0, gameCount: 0 };
}
sourceMap[source].playtime += g.playtime;
sourceMap[source].gameCount++;
});
const sourcesData = Object.values(sourceMap)
.sort((a, b) => b.playtime - a.playtime);
return { chartData: topGames, othersGames, categoriesData, runnersData, sourcesData, totalPlaytime, totalGames };
}
// Theme-aware chart text color (explicit mode or system-driven when in auto).
function getChartTextColor() {
const theme = themes[currentThemeIndex];
if (theme === 'dark') return themeConfig.textColorDark;
if (theme === 'light') return themeConfig.textColorLight;
return getSystemTheme() === 'dark' ? themeConfig.textColorDark : themeConfig.textColorLight;
}
// Theme-aware border color for chart segment separators.
function getChartBorderColor() {
const theme = themes[currentThemeIndex];
if (theme === 'dark') return themeConfig.borderColorDark;
if (theme === 'light') return themeConfig.borderColorLight;
return getSystemTheme() === 'dark' ? themeConfig.borderColorDark : themeConfig.borderColorLight;
}
/*
* Updates existing chart instances after theme changes.
*
* We only patch runtime options that are theme-sensitive here (legend text color),
* then call chart.update() so Chart.js redraws without rebuilding datasets.
*/
function updateChartColors() {
const textColor = getChartTextColor();
if (typeof chart !== 'undefined' && chart) {
chart.options.plugins.legend.labels.color = textColor;
chart.update();
}
if (typeof categoriesChart !== 'undefined' && categoriesChart) {
categoriesChart.options.plugins.legend.labels.color = textColor;
categoriesChart.update();
}
if (typeof runnersChart !== 'undefined' && runnersChart) {
runnersChart.options.plugins.legend.labels.color = textColor;
runnersChart.update();
}
if (typeof sourcesChart !== 'undefined' && sourcesChart) {
sourcesChart.options.plugins.legend.labels.color = textColor;
sourcesChart.update();
}
}
/*
* Main render pipeline.
*
* This function is triggered on:
* - initial page load
* - service filter changes
*
* Steps:
* 1) read active filters and compute all derived data
* 2) refresh summary counters
* 3) rebuild charts
* 4) rebuild data tables (including expandable Others rows)
*/
function updateDisplay() {
const selectedServices = getSelectedServices();
const { chartData, othersGames, categoriesData, runnersData, sourcesData, totalPlaytime, totalGames } = getFilteredData(selectedServices);
document.getElementById('total-games').textContent = totalGames;
document.getElementById('total-time').textContent = formatTime(totalPlaytime);
// Destroy old chart instances before creating new ones to avoid stacked canvases/memory leaks.
if (chart) {
chart.destroy();
}
if (categoriesChart) {
categoriesChart.destroy();
}
if (runnersChart) {
runnersChart.destroy();
}
if (sourcesChart) {
sourcesChart.destroy();
}
if (chartData.length === 0) {
document.getElementById('games-table').innerHTML =
'<tr><td colspan="4" class="no-data">No games match the selected filters</td></tr>';
document.getElementById('categories-table').innerHTML =
'<tr><td colspan="4" class="no-data">No categories found</td></tr>';
document.getElementById('runners-table').innerHTML =
'<tr><td colspan="4" class="no-data">No runners found</td></tr>';
return;
}
const textColor = getChartTextColor();
const borderColor = getChartBorderColor();
/*
* Primary chart: top games by playtime (plus optional Others slice).
*
* Tooltip details:
* - title: game/slice name
* - beforeBody: service label (when available and not Others)
* - label: absolute time + percentage of currently filtered total
*/
chart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: chartData.map(g => g.name),
datasets: [{
data: chartData.map(g => g.playtime),
backgroundColor: themeConfig.colors.slice(0, chartData.length),
borderColor: borderColor,
borderWidth: themeConfig.borderWidth
}]
},
options: {
responsive: true,
plugins: {
legend: {
position: 'bottom',
labels: {
color: textColor,
font: {
family: themeConfig.fontFamily,
size: 11,
weight: themeConfig.fontWeight
},
padding: 12,
usePointStyle: true,
pointStyle: themeConfig.pointStyle
}
},
tooltip: {
backgroundColor: themeConfig.tooltipBg,
titleColor: themeConfig.tooltipTitleColor,
bodyColor: themeConfig.tooltipBodyColor,
borderColor: themeConfig.tooltipBorderColor,
borderWidth: themeConfig.tooltipBorderWidth,
titleFont: { weight: 'bold', family: themeConfig.fontFamily },
bodyFont: { weight: 'normal', family: themeConfig.fontFamily },
cornerRadius: themeConfig.tooltipCornerRadius,
padding: 12,
callbacks: {
title: function(context) {
return themeConfig.uppercaseTooltip ? context[0].label.toUpperCase() : context[0].label;
},
beforeBody: function(context) {
const index = context[0].dataIndex;
const service = chartData[index].service;
if (service && service !== 'others') {
return themeConfig.uppercaseTooltip ? service.toUpperCase() : service.charAt(0).toUpperCase() + service.slice(1);
}
return '';
},
label: function(context) {
const value = context.raw;
const percent = ((value / totalPlaytime) * 100).toFixed(1);
return formatTime(value) + ' (' + percent + '%)';
}
}
}
}
}
});
/*
* Categories chart uses the same topN + Others strategy as games.
*
* Example (topN = 8):
* 12 categories => 8 visible slices + "Others (4 categories)" slice.
*/
const topCategoriesChart = categoriesData.slice(0, topN);
const otherCategoriesChart = categoriesData.slice(topN);
const categoriesChartData = topCategoriesChart.map(c => ({
name: c.name,
playtime: c.playtime
}));
if (otherCategoriesChart.length > 0) {
const othersPlaytime = otherCategoriesChart.reduce((sum, c) => sum + c.playtime, 0);
categoriesChartData.push({
name: `Others (${otherCategoriesChart.length} categories)`,
playtime: othersPlaytime
});
}
if (categoriesChartData.length > 0) {
categoriesChart = new Chart(ctxCategories, {
type: 'doughnut',
data: {
labels: categoriesChartData.map(c => c.name),
datasets: [{
data: categoriesChartData.map(c => c.playtime),
backgroundColor: themeConfig.colors.slice(0, categoriesChartData.length),
borderColor: borderColor,
borderWidth: themeConfig.borderWidth
}]
},
options: {
responsive: true,
plugins: {
legend: {
position: 'bottom',
labels: {
color: textColor,
font: {
family: themeConfig.fontFamily,
size: 11,
weight: themeConfig.fontWeight
},
padding: 12,
usePointStyle: true,
pointStyle: themeConfig.pointStyle
}
},
tooltip: {
backgroundColor: themeConfig.tooltipBg,
titleColor: themeConfig.tooltipTitleColor,
bodyColor: themeConfig.tooltipBodyColor,
borderColor: themeConfig.tooltipBorderColor,
borderWidth: themeConfig.tooltipBorderWidth,
cornerRadius: themeConfig.tooltipCornerRadius,
padding: 12,
titleFont: { family: themeConfig.fontFamily },
bodyFont: { family: themeConfig.fontFamily },
callbacks: {
label: function(context) {
const value = context.raw;
const percent = ((value / totalPlaytime) * 100).toFixed(1);
return ' ' + formatTime(value) + ' (' + percent + '%)';
}
}
}
}
}
});
}
// Runners chart: identical bucketing strategy applied to runner aggregation.
const topRunnersChart = runnersData.slice(0, topN);
const otherRunnersChart = runnersData.slice(topN);
const runnersChartData = topRunnersChart.map(r => ({
name: r.name,
playtime: r.playtime
}));
if (otherRunnersChart.length > 0) {
const othersPlaytime = otherRunnersChart.reduce((sum, r) => sum + r.playtime, 0);
runnersChartData.push({
name: `Others (${otherRunnersChart.length} runners)`,
playtime: othersPlaytime
});
}
if (runnersChartData.length > 0) {
runnersChart = new Chart(ctxRunners, {
type: 'doughnut',
data: {
labels: runnersChartData.map(r => r.name),
datasets: [{
data: runnersChartData.map(r => r.playtime),
backgroundColor: themeConfig.colors.slice(0, runnersChartData.length),
borderColor: borderColor,
borderWidth: themeConfig.borderWidth
}]
},
options: {
responsive: true,
plugins: {
legend: {
position: 'bottom',
labels: {
color: textColor,
font: {
family: themeConfig.fontFamily,
size: 11,
weight: themeConfig.fontWeight
},
padding: 12,
usePointStyle: true,
pointStyle: themeConfig.pointStyle
}
},
tooltip: {
backgroundColor: themeConfig.tooltipBg,
titleColor: themeConfig.tooltipTitleColor,
bodyColor: themeConfig.tooltipBodyColor,
borderColor: themeConfig.tooltipBorderColor,
borderWidth: themeConfig.tooltipBorderWidth,
cornerRadius: themeConfig.tooltipCornerRadius,
padding: 12,
titleFont: { family: themeConfig.fontFamily },
bodyFont: { family: themeConfig.fontFamily },
callbacks: {
label: function(context) {
const value = context.raw;
const percent = ((value / totalPlaytime) * 100).toFixed(1);
return ' ' + formatTime(value) + ' (' + percent + '%)';
}
}
}
}
}
});
}
// Sources chart: grouped by service/source, also with topN + Others bucketing.
const topSourcesChart = sourcesData.slice(0, topN);
const otherSourcesChart = sourcesData.slice(topN);
const sourcesChartData = topSourcesChart.map(s => ({
name: s.name,
playtime: s.playtime
}));
if (otherSourcesChart.length > 0) {
const othersPlaytime = otherSourcesChart.reduce((sum, s) => sum + s.playtime, 0);
sourcesChartData.push({
name: `Others (${otherSourcesChart.length} sources)`,
playtime: othersPlaytime
});
}
if (sourcesChartData.length > 0) {
sourcesChart = new Chart(ctxSources, {
type: 'doughnut',
data: {
labels: sourcesChartData.map(s => s.name),
datasets: [{
data: sourcesChartData.map(s => s.playtime),
backgroundColor: themeConfig.colors.slice(0, sourcesChartData.length),
borderColor: borderColor,
borderWidth: themeConfig.borderWidth
}]
},
options: {
responsive: true,
plugins: {
legend: {
position: 'bottom',
labels: {
color: textColor,
font: {
family: themeConfig.fontFamily,
size: 11,
weight: themeConfig.fontWeight
},
padding: 12,
usePointStyle: true,
pointStyle: themeConfig.pointStyle
}
},
tooltip: {
backgroundColor: themeConfig.tooltipBg,
titleColor: themeConfig.tooltipTitleColor,
bodyColor: themeConfig.tooltipBodyColor,
borderColor: themeConfig.tooltipBorderColor,
borderWidth: themeConfig.tooltipBorderWidth,
cornerRadius: themeConfig.tooltipCornerRadius,
padding: 12,
titleFont: { family: themeConfig.fontFamily },
bodyFont: { family: themeConfig.fontFamily },
callbacks: {
label: function(context) {
const value = context.raw;
const percent = ((value / totalPlaytime) * 100).toFixed(1);
return ' ' + formatTime(value) + ' (' + percent + '%)';
}
}
}
}
}
});
}
/*
* Games table rendering
* ---------------------
* Mirrors the main chart ordering and values.
*
* "Others" behavior:
* - parent row shows combined totals
* - click toggles child detail rows for each hidden game
* - detail index format uses parent.child numbering (e.g. 6.1, 6.2)
*/
const tbody = document.getElementById('games-table');
tbody.innerHTML = '';
chartData.forEach((game, index) => {
// Percentages are always based on currently filtered total playtime.
const percent = ((game.playtime / totalPlaytime) * 100).toFixed(1);
const isOthers = game.service === 'others';
const serviceBadge = !isOthers
? `<span class="service-badge">${game.service}</span>`
: '';
const categoriesBadges = !isOthers && game.categories && game.categories.length > 0
? game.categories
.filter(cat => cat !== '.hidden' && cat !== 'favorite')
.map(cat => `<span class="category-badge">${cat}</span>`)
.join('')
: '';
const row = document.createElement('tr');
if (isOthers) {
row.className = 'others-row';
}
row.innerHTML = `
<td>${index + 1}</td>
<td>
<span class="color-box" style="background: ${themeConfig.colors[index]}"></span>
${game.name}${serviceBadge}${categoriesBadges}
</td>
<td class="time">${formatTime(game.playtime)}</td>
<td class="percent">${percent}%</td>
`;
tbody.appendChild(row);
if (isOthers && othersGames.length > 0) {
const detailRows = [];
othersGames.forEach((otherGame, otherIndex) => {
const otherPercent = ((otherGame.playtime / totalPlaytime) * 100).toFixed(1);
const otherCategoriesBadges = otherGame.categories && otherGame.categories.length > 0
? otherGame.categories
.filter(cat => cat !== '.hidden' && cat !== 'favorite')
.map(cat => `<span class="category-badge">${cat}</span>`)
.join('')
: '';
const detailRow = document.createElement('tr');
detailRow.className = 'others-detail';
detailRow.innerHTML = `
<td>${index + 1}.${otherIndex + 1}</td>
<td>
${otherGame.name}
<span class="service-badge">${otherGame.service}</span>${otherCategoriesBadges}
</td>
<td class="time">${formatTime(otherGame.playtime)}</td>
<td class="percent">${otherPercent}%</td>
`;
tbody.appendChild(detailRow);
detailRows.push(detailRow);
});
// Expand/collapse all detail rows tied to this "Others" summary row.
row.addEventListener('click', () => {
row.classList.toggle('expanded');
detailRows.forEach(dr => dr.classList.toggle('visible'));
});
}
});
// Categories table mirrors chart grouping and supports expandable "Others" rows.
const catTbody = document.getElementById('categories-table');
catTbody.innerHTML = '';
if (categoriesData.length === 0) {
catTbody.innerHTML = '<tr><td colspan="4" class="no-data">No categories found</td></tr>';
} else {
const topCategories = categoriesData.slice(0, topN);
const otherCategories = categoriesData.slice(topN);
topCategories.forEach((cat, index) => {
const percent = ((cat.playtime / totalPlaytime) * 100).toFixed(1);
const row = document.createElement('tr');
row.innerHTML = `
<td>${index + 1}</td>
<td>
<span class="color-box" style="background: ${themeConfig.colors[index]}"></span>
${cat.name} <span class="service-badge">${cat.gameCount} games</span>
</td>
<td class="time">${formatTime(cat.playtime)}</td>
<td class="percent">${percent}%</td>
`;
catTbody.appendChild(row);
});
if (otherCategories.length > 0) {
const othersPlaytime = otherCategories.reduce((sum, c) => sum + c.playtime, 0);
const othersPercent = ((othersPlaytime / totalPlaytime) * 100).toFixed(1);
const othersIndex = topCategories.length;
const othersRow = document.createElement('tr');
othersRow.className = 'others-row';
othersRow.innerHTML = `
<td>${othersIndex + 1}</td>
<td>
<span class="color-box" style="background: ${themeConfig.colors[othersIndex]}"></span>
Others (${otherCategories.length} categories)
</td>
<td class="time">${formatTime(othersPlaytime)}</td>
<td class="percent">${othersPercent}%</td>
`;
catTbody.appendChild(othersRow);
const detailRows = [];
otherCategories.forEach((otherCat, otherIndex) => {
const otherPercent = ((otherCat.playtime / totalPlaytime) * 100).toFixed(1);
const detailRow = document.createElement('tr');
detailRow.className = 'others-detail';
detailRow.innerHTML = `
<td>${othersIndex + 1}.${otherIndex + 1}</td>
<td>
${otherCat.name} <span class="service-badge">${otherCat.gameCount} games</span>
</td>
<td class="time">${formatTime(otherCat.playtime)}</td>
<td class="percent">${otherPercent}%</td>
`;
catTbody.appendChild(detailRow);
detailRows.push(detailRow);
});
othersRow.addEventListener('click', () => {
othersRow.classList.toggle('expanded');
detailRows.forEach(dr => dr.classList.toggle('visible'));
});
}
}
// Runners table mirrors chart grouping and supports expandable "Others" rows.
const runnersTbody = document.getElementById('runners-table');
runnersTbody.innerHTML = '';
if (runnersData.length === 0) {
runnersTbody.innerHTML = '<tr><td colspan="4" class="no-data">No runners found</td></tr>';
} else {
const topRunners = runnersData.slice(0, topN);
const otherRunners = runnersData.slice(topN);
topRunners.forEach((runner, index) => {
const percent = ((runner.playtime / totalPlaytime) * 100).toFixed(1);
const row = document.createElement('tr');
row.innerHTML = `
<td>${index + 1}</td>
<td>
<span class="color-box" style="background: ${themeConfig.colors[index]}"></span>
${runner.name} <span class="service-badge">${runner.gameCount} games</span>
</td>
<td class="time">${formatTime(runner.playtime)}</td>
<td class="percent">${percent}%</td>
`;
runnersTbody.appendChild(row);
});
if (otherRunners.length > 0) {
const othersPlaytime = otherRunners.reduce((sum, r) => sum + r.playtime, 0);
const othersPercent = ((othersPlaytime / totalPlaytime) * 100).toFixed(1);
const othersIndex = topRunners.length;
const othersRow = document.createElement('tr');
othersRow.className = 'others-row';
othersRow.innerHTML = `
<td>${othersIndex + 1}</td>
<td>
<span class="color-box" style="background: ${themeConfig.colors[othersIndex]}"></span>
Others (${otherRunners.length} runners)
</td>
<td class="time">${formatTime(othersPlaytime)}</td>
<td class="percent">${othersPercent}%</td>
`;
runnersTbody.appendChild(othersRow);
const detailRows = [];
otherRunners.forEach((otherRunner, otherIndex) => {
const otherPercent = ((otherRunner.playtime / totalPlaytime) * 100).toFixed(1);
const detailRow = document.createElement('tr');
detailRow.className = 'others-detail';
detailRow.innerHTML = `
<td>${othersIndex + 1}.${otherIndex + 1}</td>
<td>
${otherRunner.name} <span class="service-badge">${otherRunner.gameCount} games</span>
</td>
<td class="time">${formatTime(otherRunner.playtime)}</td>
<td class="percent">${otherPercent}%</td>
`;
runnersTbody.appendChild(detailRow);
detailRows.push(detailRow);
});
othersRow.addEventListener('click', () => {
othersRow.classList.toggle('expanded');
detailRows.forEach(dr => dr.classList.toggle('visible'));
});
}
}
}
// Re-render whenever any service checkbox state changes.
filtersDiv.addEventListener('change', updateDisplay);
// Initial render with all services selected by default.
updateDisplay();
// Tab switching
// Activates selected tab and matching panel while deactivating the rest.
document.querySelectorAll('.tab').forEach(tab => {
tab.addEventListener('click', () => {
const tabId = tab.dataset.tab;
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
tab.classList.add('active');
document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
document.getElementById('tab-' + tabId).classList.add('active');
});
});
// Scroll to top button
const scrollTopBtn = document.getElementById('scroll-top');
// Show the floating button only after user has scrolled past a threshold.
function updateScrollTopVisibility() {
if (window.scrollY > 100) {
scrollTopBtn.classList.add('visible');
} else {
scrollTopBtn.classList.remove('visible');
}
}
window.addEventListener('scroll', updateScrollTopVisibility);
updateScrollTopVisibility();
// Smoothly jump to top for better UX on long reports.
scrollTopBtn.addEventListener('click', () => {
window.scrollTo({
top: 0,
behavior: 'smooth'
});
});