Added descriptive comments to the script file.

This commit is contained in:
2026-03-14 03:44:20 -04:00
parent 90dcc10956
commit b6d7060e79

View File

@@ -1,4 +1,4 @@
/*************************************************************************************************** /****************************************************************************************************
* Copyright (C) 2026 by WallyHackenslacker wallyhackenslacker@noreply.git.hackenslacker.space * * 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 * * Permission to use, copy, modify, and/or distribute this software for any purpose with or without *
@@ -12,16 +12,36 @@
* OF THIS SOFTWARE. * * 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 // Theme management
const themeToggle = document.getElementById('theme-toggle'); const themeToggle = document.getElementById('theme-toggle');
const themeIcon = document.getElementById('theme-icon'); const themeIcon = document.getElementById('theme-icon');
const themes = ['auto', 'light', 'dark']; const themes = ['auto', 'light', 'dark'];
let currentThemeIndex = 0; let currentThemeIndex = 0;
// Returns the current OS/browser theme preference.
function getSystemTheme() { function getSystemTheme() {
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'; 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() { function updateThemeIcon() {
const theme = themes[currentThemeIndex]; const theme = themes[currentThemeIndex];
if (theme === 'auto') { if (theme === 'auto') {
@@ -39,6 +59,15 @@ function updateThemeIcon() {
} }
} }
/*
* 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() { function applyTheme() {
const theme = themes[currentThemeIndex]; const theme = themes[currentThemeIndex];
if (theme === 'auto') { if (theme === 'auto') {
@@ -51,6 +80,7 @@ function applyTheme() {
updateChartColors(); updateChartColors();
} }
// Restores previously saved theme mode; defaults to "auto" when absent/invalid.
function loadSavedTheme() { function loadSavedTheme() {
const saved = localStorage.getItem('theme'); const saved = localStorage.getItem('theme');
if (saved) { if (saved) {
@@ -60,11 +90,13 @@ function loadSavedTheme() {
applyTheme(); applyTheme();
} }
// Cycle theme modes in a fixed order: auto -> light -> dark -> auto.
themeToggle.addEventListener('click', () => { themeToggle.addEventListener('click', () => {
currentThemeIndex = (currentThemeIndex + 1) % themes.length; currentThemeIndex = (currentThemeIndex + 1) % themes.length;
applyTheme(); applyTheme();
}); });
// When system theme changes and mode is "auto", refresh theme-dependent UI pieces.
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => { window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
if (themes[currentThemeIndex] === 'auto') { if (themes[currentThemeIndex] === 'auto') {
updateThemeIcon(); updateThemeIcon();
@@ -79,6 +111,7 @@ const topN = __TOP_N__;
// Theme-specific configuration // Theme-specific configuration
const themeConfig = __THEME_CONFIG__; const themeConfig = __THEME_CONFIG__;
// Converts decimal hours to a compact human-friendly string (e.g. 1.5 -> "1h 30m").
function formatTime(hours) { function formatTime(hours) {
const h = Math.floor(hours); const h = Math.floor(hours);
const m = Math.round((hours - h) * 60); const m = Math.round((hours - h) * 60);
@@ -87,6 +120,11 @@ function formatTime(hours) {
return h + 'h ' + m + 'm'; 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() { function getServices() {
const services = {}; const services = {};
allGames.forEach(g => { allGames.forEach(g => {
@@ -102,6 +140,8 @@ function getServices() {
const services = getServices(); const services = getServices();
const filtersDiv = document.getElementById('filters'); const filtersDiv = document.getElementById('filters');
// Build one checkbox per service so users can include/exclude data dynamically.
services.forEach(service => { services.forEach(service => {
const label = document.createElement('label'); const label = document.createElement('label');
label.className = 'filter-label'; label.className = 'filter-label';
@@ -125,6 +165,7 @@ const ctxSources = document.getElementById('sources-chart').getContext('2d');
// Initialize theme after chart variables are declared // Initialize theme after chart variables are declared
loadSavedTheme(); loadSavedTheme();
// Reads currently checked service filters from the filter panel.
function getSelectedServices() { function getSelectedServices() {
const checkboxes = filtersDiv.querySelectorAll('input[type="checkbox"]'); const checkboxes = filtersDiv.querySelectorAll('input[type="checkbox"]');
return Array.from(checkboxes) return Array.from(checkboxes)
@@ -132,6 +173,19 @@ function getSelectedServices() {
.map(cb => cb.value); .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) { function getFilteredData(selectedServices) {
const filtered = allGames const filtered = allGames
.filter(g => selectedServices.includes(g.service)) .filter(g => selectedServices.includes(g.service))
@@ -144,6 +198,7 @@ function getFilteredData(selectedServices) {
const totalPlaytime = filtered.reduce((sum, g) => sum + g.playtime, 0); const totalPlaytime = filtered.reduce((sum, g) => sum + g.playtime, 0);
const totalGames = filtered.length; const totalGames = filtered.length;
// Keep only top N games for chart readability.
const topGames = filtered.slice(0, topN).map(g => ({ const topGames = filtered.slice(0, topN).map(g => ({
name: g.name, name: g.name,
playtime: g.playtime, playtime: g.playtime,
@@ -153,6 +208,7 @@ function getFilteredData(selectedServices) {
let othersGames = []; let othersGames = [];
// Collapse remaining entries into a single "Others" slice while preserving detail rows.
if (filtered.length > topN) { if (filtered.length > topN) {
othersGames = filtered.slice(topN).map(g => ({ othersGames = filtered.slice(topN).map(g => ({
name: g.name, name: g.name,
@@ -169,6 +225,14 @@ function getFilteredData(selectedServices) {
}); });
} }
/*
* 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 = {}; const categoryMap = {};
filtered.forEach(g => { filtered.forEach(g => {
if (g.categories && g.categories.length > 0) { if (g.categories && g.categories.length > 0) {
@@ -185,6 +249,7 @@ function getFilteredData(selectedServices) {
const categoriesData = Object.values(categoryMap) const categoriesData = Object.values(categoryMap)
.sort((a, b) => b.playtime - a.playtime); .sort((a, b) => b.playtime - a.playtime);
// Aggregate by runner (wine, native, dosbox, etc.). Missing values become "unknown".
const runnerMap = {}; const runnerMap = {};
filtered.forEach(g => { filtered.forEach(g => {
const runner = g.runner || 'unknown'; const runner = g.runner || 'unknown';
@@ -197,6 +262,7 @@ function getFilteredData(selectedServices) {
const runnersData = Object.values(runnerMap) const runnersData = Object.values(runnerMap)
.sort((a, b) => b.playtime - a.playtime); .sort((a, b) => b.playtime - a.playtime);
// Aggregate by source/service to power the Sources chart.
const sourceMap = {}; const sourceMap = {};
filtered.forEach(g => { filtered.forEach(g => {
const source = g.service || 'unknown'; const source = g.service || 'unknown';
@@ -212,6 +278,7 @@ function getFilteredData(selectedServices) {
return { chartData: topGames, othersGames, categoriesData, runnersData, sourcesData, totalPlaytime, totalGames }; return { chartData: topGames, othersGames, categoriesData, runnersData, sourcesData, totalPlaytime, totalGames };
} }
// Theme-aware chart text color (explicit mode or system-driven when in auto).
function getChartTextColor() { function getChartTextColor() {
const theme = themes[currentThemeIndex]; const theme = themes[currentThemeIndex];
if (theme === 'dark') return themeConfig.textColorDark; if (theme === 'dark') return themeConfig.textColorDark;
@@ -219,6 +286,7 @@ function getChartTextColor() {
return getSystemTheme() === 'dark' ? themeConfig.textColorDark : themeConfig.textColorLight; return getSystemTheme() === 'dark' ? themeConfig.textColorDark : themeConfig.textColorLight;
} }
// Theme-aware border color for chart segment separators.
function getChartBorderColor() { function getChartBorderColor() {
const theme = themes[currentThemeIndex]; const theme = themes[currentThemeIndex];
if (theme === 'dark') return themeConfig.borderColorDark; if (theme === 'dark') return themeConfig.borderColorDark;
@@ -226,6 +294,12 @@ function getChartBorderColor() {
return getSystemTheme() === 'dark' ? themeConfig.borderColorDark : 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() { function updateChartColors() {
const textColor = getChartTextColor(); const textColor = getChartTextColor();
if (typeof chart !== 'undefined' && chart) { if (typeof chart !== 'undefined' && chart) {
@@ -246,6 +320,19 @@ function updateChartColors() {
} }
} }
/*
* 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() { function updateDisplay() {
const selectedServices = getSelectedServices(); const selectedServices = getSelectedServices();
const { chartData, othersGames, categoriesData, runnersData, sourcesData, totalPlaytime, totalGames } = getFilteredData(selectedServices); const { chartData, othersGames, categoriesData, runnersData, sourcesData, totalPlaytime, totalGames } = getFilteredData(selectedServices);
@@ -253,6 +340,7 @@ function updateDisplay() {
document.getElementById('total-games').textContent = totalGames; document.getElementById('total-games').textContent = totalGames;
document.getElementById('total-time').textContent = formatTime(totalPlaytime); document.getElementById('total-time').textContent = formatTime(totalPlaytime);
// Destroy old chart instances before creating new ones to avoid stacked canvases/memory leaks.
if (chart) { if (chart) {
chart.destroy(); chart.destroy();
} }
@@ -279,6 +367,14 @@ function updateDisplay() {
const textColor = getChartTextColor(); const textColor = getChartTextColor();
const borderColor = getChartBorderColor(); 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, { chart = new Chart(ctx, {
type: 'doughnut', type: 'doughnut',
data: { data: {
@@ -340,6 +436,12 @@ function updateDisplay() {
} }
}); });
/*
* 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 topCategoriesChart = categoriesData.slice(0, topN);
const otherCategoriesChart = categoriesData.slice(topN); const otherCategoriesChart = categoriesData.slice(topN);
const categoriesChartData = topCategoriesChart.map(c => ({ const categoriesChartData = topCategoriesChart.map(c => ({
@@ -406,7 +508,7 @@ function updateDisplay() {
}); });
} }
// Runners Chart // Runners chart: identical bucketing strategy applied to runner aggregation.
const topRunnersChart = runnersData.slice(0, topN); const topRunnersChart = runnersData.slice(0, topN);
const otherRunnersChart = runnersData.slice(topN); const otherRunnersChart = runnersData.slice(topN);
const runnersChartData = topRunnersChart.map(r => ({ const runnersChartData = topRunnersChart.map(r => ({
@@ -473,7 +575,7 @@ function updateDisplay() {
}); });
} }
// Sources Chart // Sources chart: grouped by service/source, also with topN + Others bucketing.
const topSourcesChart = sourcesData.slice(0, topN); const topSourcesChart = sourcesData.slice(0, topN);
const otherSourcesChart = sourcesData.slice(topN); const otherSourcesChart = sourcesData.slice(topN);
const sourcesChartData = topSourcesChart.map(s => ({ const sourcesChartData = topSourcesChart.map(s => ({
@@ -540,9 +642,20 @@ function updateDisplay() {
}); });
} }
/*
* 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'); const tbody = document.getElementById('games-table');
tbody.innerHTML = ''; tbody.innerHTML = '';
chartData.forEach((game, index) => { chartData.forEach((game, index) => {
// Percentages are always based on currently filtered total playtime.
const percent = ((game.playtime / totalPlaytime) * 100).toFixed(1); const percent = ((game.playtime / totalPlaytime) * 100).toFixed(1);
const isOthers = game.service === 'others'; const isOthers = game.service === 'others';
const serviceBadge = !isOthers const serviceBadge = !isOthers
@@ -594,6 +707,7 @@ function updateDisplay() {
detailRows.push(detailRow); detailRows.push(detailRow);
}); });
// Expand/collapse all detail rows tied to this "Others" summary row.
row.addEventListener('click', () => { row.addEventListener('click', () => {
row.classList.toggle('expanded'); row.classList.toggle('expanded');
detailRows.forEach(dr => dr.classList.toggle('visible')); detailRows.forEach(dr => dr.classList.toggle('visible'));
@@ -601,6 +715,7 @@ function updateDisplay() {
} }
}); });
// Categories table mirrors chart grouping and supports expandable "Others" rows.
const catTbody = document.getElementById('categories-table'); const catTbody = document.getElementById('categories-table');
catTbody.innerHTML = ''; catTbody.innerHTML = '';
if (categoriesData.length === 0) { if (categoriesData.length === 0) {
@@ -666,6 +781,7 @@ function updateDisplay() {
} }
} }
// Runners table mirrors chart grouping and supports expandable "Others" rows.
const runnersTbody = document.getElementById('runners-table'); const runnersTbody = document.getElementById('runners-table');
runnersTbody.innerHTML = ''; runnersTbody.innerHTML = '';
if (runnersData.length === 0) { if (runnersData.length === 0) {
@@ -732,10 +848,13 @@ function updateDisplay() {
} }
} }
// Re-render whenever any service checkbox state changes.
filtersDiv.addEventListener('change', updateDisplay); filtersDiv.addEventListener('change', updateDisplay);
// Initial render with all services selected by default.
updateDisplay(); updateDisplay();
// Tab switching // Tab switching
// Activates selected tab and matching panel while deactivating the rest.
document.querySelectorAll('.tab').forEach(tab => { document.querySelectorAll('.tab').forEach(tab => {
tab.addEventListener('click', () => { tab.addEventListener('click', () => {
const tabId = tab.dataset.tab; const tabId = tab.dataset.tab;
@@ -749,6 +868,7 @@ document.querySelectorAll('.tab').forEach(tab => {
// Scroll to top button // Scroll to top button
const scrollTopBtn = document.getElementById('scroll-top'); const scrollTopBtn = document.getElementById('scroll-top');
// Show the floating button only after user has scrolled past a threshold.
function updateScrollTopVisibility() { function updateScrollTopVisibility() {
if (window.scrollY > 100) { if (window.scrollY > 100) {
scrollTopBtn.classList.add('visible'); scrollTopBtn.classList.add('visible');
@@ -760,6 +880,7 @@ function updateScrollTopVisibility() {
window.addEventListener('scroll', updateScrollTopVisibility); window.addEventListener('scroll', updateScrollTopVisibility);
updateScrollTopVisibility(); updateScrollTopVisibility();
// Smoothly jump to top for better UX on long reports.
scrollTopBtn.addEventListener('click', () => { scrollTopBtn.addEventListener('click', () => {
window.scrollTo({ window.scrollTo({
top: 0, top: 0,