@lovebowls/leagueelements
Version:
League Elements package for LoveBowls
305 lines (267 loc) • 13.3 kB
HTML
<html lang="en">
<head>
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test league-element</title>
<script type="importmap">
{
"imports": {
"@lovebowls/leaguejs": "/node_modules/@lovebowls/leaguejs/dist/index.js"
}
}
</script>
<!-- Load JSBI globally -->
<script src="https://unpkg.com/jsbi@4.3.0/dist/jsbi-umd.js"></script>
</head>
<body>
<h1>Test: <league-element></h1>
<div>
<button id="reset-data-btn" style="margin-bottom: 1em; padding: 0.5em; background: #ff6b6b; color: white; border: none; border-radius: 4px; cursor: pointer;">Reset Current League</button>
</div>
<div style="margin-bottom: 1em; padding: 0.5em; background: #f0f0f0; border: 1px solid #ccc; border-radius: 4px;">
<label style="display: flex; align-items: center; gap: 0.5em; cursor: pointer;">
<input type="checkbox" id="can-edit-toggle" checked style="margin: 0;">
<span>Enable Editing (can-edit)</span>
</label>
<small style="color: #666; display: block; margin-top: 0.25em;">
When unchecked, the "Requiring Attention" panel will be hidden and match editing will be disabled.
</small>
</div>
<!-- Remove hardcoded data attribute; we'll set it via JavaScript after checking session storage -->
<league-element id="test-league" can-edit="true"></league-element>
<div id="event-log" style="margin-top:2em; background:#f9f9f9; padding:1em; border:1px solid #ccc; word-wrap: break-word;"><b>Event Log:</b><br></div>
<script type="module">
import '../../../dist/browser/leagueElement.js';
import { generateTestLeagueData } from '../../test-data/league-test-data.js';
const el = document.getElementById('test-league');
const STORAGE_KEY = 'lovebowlsTestHarnessData';
// Define lovebowls team data using standardized {_id, name} model
const lovebowlsTeamsData = [
{ _id: "lb-guid-a123", name: "Lovebowls Club Alpha" },
{ _id: "lb-guid-b456", name: "Lovebowls Club Beta" },
{ _id: "lb-guid-c789", name: "Lovebowls Club Gamma" },
{ _id: "lb-guid-d012", name: "Lovebowls Club Delta" },
{ _id: "lb-guid-e345", name: "Lovebowls Club Epsilon" }
];
// This page should not generate its own default data.
// It should ONLY display data passed to it.
// Try to load league data from session storage. If it fails, it's an error.
function loadLeagueData() {
try {
const urlParams = new URLSearchParams(window.location.search);
const leagueId = urlParams.get('leagueId');
const storedData = sessionStorage.getItem(STORAGE_KEY);
if (!storedData) {
throw new Error("No data found in sessionStorage. Please start from the admin page.");
}
const parsedData = JSON.parse(storedData);
console.log('SessionStorage data:', parsedData);
if (!parsedData.leagues || !Array.isArray(parsedData.leagues) || parsedData.leagues.length === 0) {
throw new Error("No leagues found in sessionStorage data.");
}
// If no leagueId provided, use the first league
if (!leagueId) {
console.log('No leagueId provided in URL, using first league from cache');
return parsedData.leagues[0];
}
// Try to find the specific league
const league = parsedData.leagues.find(l => (l._id || l.name) === leagueId);
if (league) {
console.log('Found requested league:', league);
return league;
}
// If league not found, log available leagues and use first one
console.warn(`League with ID "${leagueId}" not found in sessionStorage. Available leagues:`,
parsedData.leagues.map(l => ({ id: l._id, name: l.name })));
console.log('Falling back to first league in cache');
return parsedData.leagues[0];
} catch (e) {
console.error('Error loading data from session storage:', e);
// Instead of returning null, throw the error to be caught by the outer try-catch
throw e;
}
}
// Save league data to session storage
function saveLeagueData(data) {
try {
const allLeaguesData = sessionStorage.getItem(STORAGE_KEY);
if (allLeaguesData) {
const allLeagues = JSON.parse(allLeaguesData).leagues;
const updatedAllLeagues = allLeagues.map(league => {
if (league._id === data._id || league.name === data.name) {
return data; // replace with updated data
}
return league;
});
sessionStorage.setItem(STORAGE_KEY, JSON.stringify({ leagues: updatedAllLeagues }));
logEvent('Updated league list saved to session storage (lovebowlsTestHarnessData)');
}
} catch (e) {
console.error('Error saving data to session storage:', e);
}
}
// Helper function to log events to the UI
function logEvent(message) {
const log = document.getElementById('event-log');
log.innerHTML += `<div>${message}</div>`;
}
// Set is-mobile attribute based on device detection
const userAgentIsMobile_init = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
const windowIsNarrow_init = window.innerWidth <= 768;
const calculatedIsMobile_init = userAgentIsMobile_init || windowIsNarrow_init;
console.log('[Test Harness - league-element] Initial Load - navigator.userAgent:', navigator.userAgent);
console.log('[Test Harness - league-element] Initial Load - userAgentIsMobile:', userAgentIsMobile_init);
console.log('[Test Harness - league-element] Initial Load - window.innerWidth:', window.innerWidth);
console.log('[Test Harness - league-element] Initial Load - windowIsNarrow:', windowIsNarrow_init);
console.log('[Test Harness - league-element] Initial Load - Calculated isMobile for attribute logic:', calculatedIsMobile_init);
if (calculatedIsMobile_init) {
el.setAttribute('is-mobile', 'true');
el.setAttribute('font-scale', 1.5);
console.log('[Test Harness - league-element] Initial Load - el.setAttribute("is-mobile", "true")');
} else {
el.removeAttribute('is-mobile');
console.log('[Test Harness - league-element] Initial Load - el.removeAttribute("is-mobile")');
}
// IMPORTANT: Set the lovebowls teams attribute FIRST before setting data
el.setAttribute('lovebowls-teams', JSON.stringify(lovebowlsTeamsData));
// Pass team mapping directly for sub-components
const teamMap = {};
lovebowlsTeamsData.forEach(team => {
teamMap[team._id] = team.name;
});
el.setAttribute('team-map', JSON.stringify(teamMap));
// Initialize with saved or default data - AFTER setting lovebowls-teams
try {
const initialData = loadLeagueData();
if (initialData) {
el.setAttribute('data', JSON.stringify(initialData));
}
} catch (error) {
// Handle the error case where data could not be loaded
document.body.innerHTML = `
<h1 style="color: red;">Error Loading League</h1>
<p>Could not load league data: ${error.message}</p>
<p>Please <a href="../leagueAdminElement/test-league-admin-element.html">return to the Admin Page</a> and select a league to view.</p>
<p>Debug Info:</p>
<pre>${JSON.stringify({
sessionStorageKey: STORAGE_KEY,
sessionStorageExists: !!sessionStorage.getItem(STORAGE_KEY),
error: error.message
}, null, 2)}</pre>
`;
// Stop further script execution
throw new Error("Stopping script execution due to data load failure.");
}
// Handle can-edit toggle checkbox
document.getElementById('can-edit-toggle').addEventListener('change', (e) => {
const isChecked = e.target.checked;
if (isChecked) {
el.setAttribute('can-edit', 'true');
logEvent('Editing enabled - can-edit set to true');
} else {
el.setAttribute('can-edit', 'false');
logEvent('Editing disabled - can-edit set to false');
}
});
// Handle Reset button
document.getElementById('reset-data-btn').addEventListener('click', () => {
try {
// Get current league data to identify which league to reset
const currentLeagueData = loadLeagueData();
if (!currentLeagueData || !currentLeagueData._id) {
logEvent('Error: Cannot reset - no current league data found');
alert('Cannot reset: No current league data found');
return;
}
const leagueId = currentLeagueData._id;
const leagueName = currentLeagueData.name || 'Test League';
// Get all leagues from session storage
const allLeaguesData = sessionStorage.getItem(STORAGE_KEY);
if (!allLeaguesData) {
logEvent('Error: Cannot reset - no session storage data found');
alert('Cannot reset: No session storage data found');
return;
}
const parsedData = JSON.parse(allLeaguesData);
if (!parsedData.leagues || !Array.isArray(parsedData.leagues)) {
logEvent('Error: Cannot reset - invalid session storage format');
alert('Cannot reset: Invalid session storage format');
return;
}
// Generate fresh test data for this league
const freshLeague = generateTestLeagueData(lovebowlsTeamsData, 6, leagueName);
// Preserve the original league ID to maintain consistency
freshLeague._id = leagueId;
// Update the league in the array
const updatedLeagues = parsedData.leagues.map(league => {
if (league._id === leagueId || league.name === leagueName) {
return freshLeague;
}
return league;
});
// Save updated leagues back to session storage
sessionStorage.setItem(STORAGE_KEY, JSON.stringify({ leagues: updatedLeagues }));
// Update the component with the fresh league data
el.setAttribute('data', JSON.stringify(freshLeague));
logEvent(`League "${leagueName}" reset with fresh test data including skill-based results`);
console.log('Reset league data:', freshLeague);
} catch (error) {
console.error('Error resetting league:', error);
logEvent(`Error resetting league: ${error.message}`);
alert(`Error resetting league: ${error.message}`);
}
});
// Listen for league update events from leagueElement.js
el.addEventListener('league-event', (e) => {
// Check if this is an update request
if (e.detail && e.detail.type === 'requestSaveLeague' && e.detail.league) {
const updatedLeague = e.detail.league;
// Clear any attention reasons from matches after saving
// This prevents the warning banner from persisting after issues are fixed
if (updatedLeague.matches && Array.isArray(updatedLeague.matches)) {
updatedLeague.matches.forEach(match => {
if (match.attentionReason) {
delete match.attentionReason;
}
});
}
// Save updated data
saveLeagueData(updatedLeague);
// Update the component with new data
el.setAttribute('data', JSON.stringify(updatedLeague));
logEvent(`League "${updatedLeague.name}" updated and saved`);
}
// Log all league-events for debugging
logEvent(`Event: league-event - ${JSON.stringify(e.detail)}`);
});
// Handle navigation back to the admin page
el.addEventListener('league-event', (e) => {
if (e.detail && e.detail.type === 'requestAdminView' && e.detail.leagueId) {
const leagueId = e.detail.leagueId;
logEvent(`Request to return to admin view for league: ${leagueId}`);
// Navigate back to the admin test page, passing the leagueId
window.location.href = `../leagueAdminElement/test-league-admin-element.html?leagueId=${encodeURIComponent(leagueId)}`;
}
});
// Update is-mobile on window resize
window.addEventListener('resize', () => {
console.log('[Test Harness - league-element] Resize event triggered.');
const userAgentIsMobile_resize = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
const windowIsNarrow_resize = window.innerWidth <= 768;
const calculatedIsMobile_resize = userAgentIsMobile_resize || windowIsNarrow_resize;
if (calculatedIsMobile_resize) {
if (el.getAttribute('is-mobile') !== 'true') {
el.setAttribute('is-mobile', 'true');
console.log('[Test Harness - league-element] Resize - el.setAttribute("is-mobile", "true")');
}
} else {
if (el.hasAttribute('is-mobile')) {
el.removeAttribute('is-mobile');
console.log('[Test Harness - league-element] Resize - el.removeAttribute("is-mobile")');
}
}
console.log('[Test Harness - league-element] Resize - el.getAttribute("is-mobile") after resize logic:', el.getAttribute('is-mobile'));
});
</script>
</body>
</html>