@lovebowls/leagueelements
Version:
League Elements package for LoveBowls
1,307 lines (1,223 loc) • 61.5 kB
JavaScript
var LeagueMatchesAttention = (function () {
'use strict';
const panelStyles = `
.panel-header-shared {
padding: var(--le-padding-s, 0.75em) var(--le-padding-m, 1.25em); /* Increased padding */
border-bottom: 1px solid var(--le-border-color-medium, #eee);
font-weight: bold;
color: var(--le-text-color-primary, #333);
background-color: var(--le-background-color-header, #f9f9f9);
display: flex;
justify-content: space-between;
align-items: center;
}
.panel-content-shared {
padding: var(--le-padding-m, 1.25em);
background-color: var(--le-background-color-panel, #fff);
/* Common border for content area if needed
border: 1px solid var(--le-border-color-light, #f0f0f0);
*/
}
`;
const buttonStyles = `
.button-shared {
padding: var(--le-padding-s, 0.75em) var(--le-padding-m, 1.25em); /* Increased padding */
border: 1px solid var(--le-border-color-medium, #ccc);
background-color: var(--le-background-color-button, #f0f0f0);
color: var(--le-text-color-primary, #333); /* Ensure text color contrasts with button background */
cursor: pointer;
border-radius: var(--le-border-radius-standard, 4px);
font-size: var(--le-font-size-medium, 1.15em); /* Increased font size */
text-decoration: none;
display: inline-block;
text-align: center;
line-height: normal; /* Ensure consistent line height */
white-space: nowrap; /* Prevent text wrapping */
vertical-align: middle; /* Align nicely if next to text/icons */
user-select: none; /* Prevent text selection on click */
transition: background-color 0.2s ease-in-out, border-color 0.2s ease-in-out; /* Smooth transitions */
}
.button-shared:hover:not(:disabled) {
background-color: var(--le-background-color-button-hover, #e0e0e0);
border-color: var(--le-border-color-dark, #bbb); /* Slightly darker border on hover */
/* color: var(--le-text-color-accent-hover, inherit); Optional: change text color on hover */
}
.button-shared:active:not(:disabled) {
/* Optional: style for active (pressed) state */
/* background-color: var(--le-background-color-button-active, #d0d0d0); */
}
.button-shared:disabled,
.button-shared.disabled { /* Allow class-based disabling too */
background-color: var(--le-background-color-button-disabled, #eee);
color: var(--le-text-color-secondary, #aaa);
border-color: var(--le-border-color-medium, #ccc); /* Use medium border for disabled state */
cursor: not-allowed;
opacity: 0.7; /* Visually indicate disabled state */
}
/* Small button variant */
.button-shared.button-sm {
padding: var(--le-padding-xs, 0.4rem) var(--le-padding-s, 0.75rem); /* Increased padding */
font-size: var(--le-font-size-small, 1em); /* Increased small font size */
/* line-height can be tighter if needed for small buttons */
/* line-height: 1.2; */
}
/* Variations */
.button-shared.button-primary {
background-color: var(--le-color-primary, #007bff);
color: var(--le-text-color-on-primary, #fff);
border-color: var(--le-color-primary, #007bff);
}
.button-shared.button-primary:hover:not(:disabled) {
background-color: var(--le-color-primary-hover, #0056b3);
border-color: var(--le-color-primary-hover, #0056b3);
}
.button-shared.button-secondary-light {
background-color: var(--le-background-color-button-secondary-light, #f8f9fa);
color: var(--le-text-color-secondary-light-text, #212529);
border-color: var(--le-border-color-secondary-light, #ced4da);
}
.button-shared.button-secondary-light:hover:not(:disabled) {
background-color: var(--le-background-color-button-secondary-light-hover, #e2e6ea);
border-color: var(--le-border-color-secondary-light-hover, #dae0e5);
color: var(--le-text-color-secondary-light-text-hover, #212529);
}
/* Example for a darker secondary button if needed elsewhere
.button-shared.button-secondary {
background-color: var(--le-color-secondary, #6c757d);
color: var(--le-text-color-on-secondary, #fff);
border-color: var(--le-color-secondary, #6c757d);
}
.button-shared.button-secondary:hover:not(:disabled) {
background-color: var(--le-color-secondary-hover, #5a6268);
border-color: var(--le-color-secondary-hover, #5a6268);
}
*/
`;
const listItemStyles = `
.list-item-shared {
padding: var(--le-padding-s, 0.75em) var(--le-padding-xs, 0.4em); /* Increased padding */
border-bottom: 1px solid var(--le-border-color-light, #eee);
display: flex;
align-items: center;
justify-content: space-between; /* Common for items with actions on the right */
gap: var(--le-padding-s, 0.75em); /* Increased gap */
}
.list-item-shared:last-child {
border-bottom: none;
}
/* Example of a text part within a list item that should grow */
.list-item-shared .list-item-text-primary {
flex-grow: 1;
font-size: var(--le-font-size-small, 1.0em); /* Added explicit font size */
/* Potentially add text overflow properties if needed */
/* white-space: nowrap; */
/* overflow: hidden; */
/* text-overflow: ellipsis; */
}
/* Example of an actions container part within a list item */
.list-item-shared .list-item-actions {
flex-shrink: 0; /* Prevent actions from shrinking */
display: flex;
gap: var(--le-padding-xs, 0.4em); /* Increased gap */
}
`;
const mobileStyles = `
/* Mobile-specific styling that can be added to host elements */
/* Increased font sizes for better readability on mobile */
--le-font-size-base: 1.4em;
--le-font-size-small: 1.2em;
--le-font-size-medium: 1.6em;
--le-font-size-large: 1.8em;
--le-font-size-xlarge: 2em;
/* Adjust padding for better touch targets */
--le-padding-s: 0.6rem;
--le-padding-m: 1rem;
/* Other mobile optimizations */
font-size: var(--le-font-size-base);
line-height: 1.4;
`;
const BASE_STYLES = `
${panelStyles}
${buttonStyles}
${listItemStyles}
:host {
display: block;
font-family: var(--le-font-family-main, 'Open Sans', Helvetica, Arial, sans-serif);
box-sizing: border-box;
color: var(--le-text-color-primary, #333);
font-size: var(--le-font-size-base, 1em);
}
.match-item {
padding: var(--lae-padding-xs, 0.2rem) 0;
display: flex;
align-items: center;
gap: var(--le-padding-xs, 0.25em);
}
.match-date {
color: var(--le-text-color-secondary, #666);
font-size: 0.85em;
margin-bottom: var(--le-padding-xs, 0.2em);
}
.paging-controls {
display: flex;
justify-content: flex-end;
gap: var(--le-padding-s, 0.5rem);
margin-top: var(--le-padding-s, 0.5rem);
}
.error {
color: var(--le-text-color-error, #ff0000);
padding: var(--le-padding-s, 0.5rem);
background-color: var(--le-background-color-error, #fff0f0);
border-radius: var(--lae-border-radius-standard, 4px);
}
.warning-icon-future-result { color: var(--le-color-status-warning, #f39c12); }
.warning-icon-conflict { color: var(--le-color-status-conflict, #e67e22); }
.warning-icon-pending-result { color: var(--le-color-status-pending, #e74c3c); }
.warning-icon-no-date { color: var(--le-color-status-info, #2196f3); }
.warning-icon {
font-size:1.2em;
flex-shrink: 0;
}
.no-matches {
padding: var(--le-padding-m, 1rem);
text-align: center;
color: var(--le-text-color-secondary, #666);
}
`;
const MOBILE_STYLES = `
${BASE_STYLES}
:host {
${mobileStyles}
}
.paging-btn {
}
.match-item {
font-size: 1em;
padding: var(--lae-padding-xs, 0.2rem) 0;
}
`;
const DESKTOP_STYLES = `
${BASE_STYLES}
:host {
}
.match-item {
font-size: 1em;
padding: var(--lae-padding-xs, 0.2rem) 0;
}
`;
const TEMPLATE = `
<div class="attention-matches">
{{attentionMatches}}
</div>
<div class="paging-controls" id="attention-paging" {{showPaging}}>
<button class="paging-btn button-shared button-sm" id="attention-prev" {{prevDisabled}}>< Prev</button>
<button class="paging-btn button-shared button-sm" id="attention-next" {{nextDisabled}}>Next ></button>
</div>
`;
/**
* Safely register a custom element, avoiding duplicate registration errors
* in single-page applications where modules may be loaded multiple times.
*
* @param {string} tagName - The custom element tag name (e.g., 'league-element')
* @param {CustomElementConstructor} elementClass - The element class constructor
* @param {boolean} [logRegistration=false] - Whether to log successful registrations
*/
function safeDefine(tagName, elementClass, logRegistration = false) {
if (!customElements.get(tagName)) {
customElements.define(tagName, elementClass);
if (logRegistration) {
console.log(`[ElementRegistry] Registered custom element: ${tagName}`);
}
} else if (logRegistration) {
console.log(`[ElementRegistry] Custom element already registered: ${tagName}`);
}
}
// Define custom event types for the LeagueMatchesAttention element
class LeagueMatchesAttentionEvent extends CustomEvent {
constructor(detail) {
super('league-matches-attention-event', {
detail,
bubbles: true,
// Ensure event bubbles up through the DOM
composed: true,
// Ensure event crosses shadow DOM boundaries
cancelable: true // Make the event cancelable
});
}
}
/**
* Custom element to display matches requiring attention with paging.
*
* @element league-matches-attention
* @attr {string} data - JSON stringified League instance object
* @attr {boolean} [is-mobile] - Whether to use mobile styles
* @attr {string} [team-mapping] - JSON stringified array of {value, label} objects mapping team values to display names
*
* Emits 'league-matches-attention-event' with detail { type: 'matchClick', match }
*/
class LeagueMatchesAttention extends HTMLElement {
constructor() {
super();
this.shadow = this.attachShadow({
mode: 'open'
});
this.league = null; // Store the league instance instead of just matches
this.currentPage = 0;
this.itemsPerPage = 5;
this.teamMapping = {};
}
static get observedAttributes() {
return ['data', 'is-mobile', 'team-mapping'];
}
connectedCallback() {
if (this.hasAttribute('team-mapping')) {
this._setTeamMapping(this.getAttribute('team-mapping'));
}
this.render();
}
attributeChangedCallback(name, oldValue, newValue) {
if (oldValue === newValue) return;
if (name === 'data') {
this.loadData(newValue);
} else if (name === 'is-mobile') {
this.render();
} else if (name === 'team-mapping') {
this._setTeamMapping(newValue);
this.render(); // Re-render to apply new team names
}
}
_setTeamMapping(mappingData) {
try {
if (!mappingData) {
this.teamMapping = {};
return;
}
// Parse mapping from the attribute string
const dataObj = typeof mappingData === 'string' ? JSON.parse(mappingData) : mappingData;
// Handle either array of {_id, name} objects or direct _id -> name mapping object
if (Array.isArray(dataObj)) {
// Convert array of objects to a simple map
this.teamMapping = {};
dataObj.forEach(team => {
if (team._id) {
this.teamMapping[team._id] = team.name || team._id;
}
});
} else {
// Assume we already have a direct mapping object
this.teamMapping = dataObj;
}
} catch (error) {
console.error('[LeagueMatchesAttention] Error parsing team mapping:', error);
this.teamMapping = {};
}
}
// Add a utility method to get display name for a team
getTeamDisplayName(teamId) {
if (!teamId || !this.teamMapping) {
return teamId;
}
// With standardized team model, teamMapping is a simple object map of _id -> name
const teamName = this.teamMapping[teamId];
if (teamName) {
return teamName;
}
return teamId;
}
/**
* Loads and parses the league data.
* @param {string|Object} data - League instance or JSON string
*/
async loadData(data) {
try {
if (typeof data === 'string') {
const parsedData = JSON.parse(data);
// Import League class to create a proper instance
const {
League
} = await Promise.resolve().then(function () { return index; });
this.league = new League(parsedData);
} else if (data && typeof data === 'object') {
// If it's already a League instance, use it directly
if (data.getMatchesRequiringAttention && data.getConflictingMatchIds) {
this.league = data;
} else {
// It's plain data, create a League instance
const {
League
} = await Promise.resolve().then(function () { return index; });
this.league = new League(data);
}
} else {
this.league = null;
}
this.currentPage = 0;
this.render();
this.dispatchEvent(new LeagueMatchesAttentionEvent({
type: 'dataLoaded',
league: this.league
}));
} catch (error) {
const errorMessage = 'Failed to load league data for attention matches';
this.showError(errorMessage);
console.error('Error loading league data for attention matches:', error);
this.dispatchEvent(new LeagueMatchesAttentionEvent({
type: 'error',
message: errorMessage,
error
}));
}
}
/**
* Shows an error message in the component.
* @param {string} message
*/
showError(message) {
const content = this.shadow.querySelector('.attention-matches');
if (content) {
content.innerHTML = `<div class="error">${message}</div>`;
}
}
_hasNextPage() {
if (!this.league || typeof this.league.getMatchesRequiringAttention !== 'function') {
return false;
}
const list = this.league.getMatchesRequiringAttention();
return (this.currentPage + 1) * this.itemsPerPage < list.length;
}
/**
* Renders the list of matches requiring attention for the current page.
* @returns {string}
*/
renderAttentionMatches() {
if (!this.league || typeof this.league.getMatchesRequiringAttention !== 'function') {
return '<div class="no-matches">No league data available</div>';
}
const matches = this.league.getMatchesRequiringAttention();
const start = this.currentPage * this.itemsPerPage;
const pageItems = matches.slice(start, start + this.itemsPerPage);
if (pageItems.length === 0) {
if (matches.length > 0) {
return '<div class="no-matches">None</div>';
}
return '<div class="no-matches">None</div>';
}
const today = new Date();
today.setHours(0, 0, 0, 0);
let conflictingIds = new Set();
if (typeof this.league.getConflictingMatchIds === 'function') {
conflictingIds = this.league.getConflictingMatchIds();
}
return pageItems.map(match => {
// Get display names for teams
const homeTeamId = match.homeTeam?._id;
const awayTeamId = match.awayTeam?._id;
const homeTeamDisplay = match.homeTeam?.name || this.getTeamDisplayName(homeTeamId);
const awayTeamDisplay = match.awayTeam?.name || this.getTeamDisplayName(awayTeamId);
let warningSymbol = '';
let warningClass = '';
let tooltipText = '';
if (match.result && match.date) {
const matchDate = new Date(match.date);
matchDate.setHours(0, 0, 0, 0);
if (matchDate > today) {
tooltipText = "Result entered for a future match date";
warningSymbol = '⚠';
warningClass = 'warning-icon-future-result';
}
} else if (conflictingIds.has(match._id)) {
tooltipText = "Scheduling conflict on this date.";
warningSymbol = '⚠';
warningClass = 'warning-icon-conflict';
} else if (match.date && !match.result) {
const matchDate = new Date(match.date);
matchDate.setHours(0, 0, 0, 0);
if (matchDate < today) {
tooltipText = "Match date passed, result pending.";
warningSymbol = '⏳';
warningClass = 'warning-icon-pending-result';
}
} else if (!match.date && !match.result) {
tooltipText = "No date set for match";
warningSymbol = '📅';
warningClass = 'warning-icon-no-date';
}
const titleAttr = tooltipText ? ` title="${this.escapeHtml(tooltipText)}"` : '';
const dataAttr = tooltipText ? ` data-attention-reason="${this.escapeHtml(tooltipText)}"` : '';
const warningSpan = warningSymbol ? `<span class="warning-icon ${warningClass}" title="${this.escapeHtml(tooltipText)}">${warningSymbol}</span>` : '';
return `
<div class="match-item list-item-shared">
${warningSpan}
<a href="#" class="match-link list-item-text-primary" data-match-id="${match._id}"${titleAttr}${dataAttr}>
${this.escapeHtml(homeTeamDisplay)} vs ${this.escapeHtml(awayTeamDisplay)}
</a>
</div>
`;
}).join('');
}
_fillTemplate(template) {
const showPaging = this.currentPage > 0 || this._hasNextPage();
return template.replace('{{attentionMatches}}', this.renderAttentionMatches()).replace('{{prevDisabled}}', this.currentPage === 0 ? 'disabled' : '').replace('{{nextDisabled}}', this._hasNextPage() ? '' : 'disabled').replace('{{showPaging}}', showPaging ? '' : 'style="display: none;"');
}
render() {
const isMobile = this.getAttribute('is-mobile') === 'true';
this.shadow.innerHTML = `
<style>${isMobile ? MOBILE_STYLES : DESKTOP_STYLES}</style>
${this._fillTemplate(TEMPLATE)}
`;
this.setupEventListeners();
}
setupEventListeners() {
// Paging buttons
const prevBtn = this.shadow.querySelector('#attention-prev');
const nextBtn = this.shadow.querySelector('#attention-next');
if (prevBtn) {
prevBtn.onclick = () => {
if (this.currentPage > 0) {
this.currentPage--;
this.render();
}
};
}
if (nextBtn) {
nextBtn.onclick = () => {
if (this._hasNextPage()) {
this.currentPage++;
this.render();
}
};
}
// Match click handlers
const matchLinks = this.shadow.querySelectorAll('.match-link');
matchLinks.forEach((link, index) => {
link.onclick = e => {
e.preventDefault();
e.stopPropagation();
const matchId = link.dataset.matchId;
const attentionReason = link.dataset.attentionReason;
let match = null;
if (this.league && typeof this.league.getMatchesRequiringAttention === 'function') {
match = this.league.getMatchesRequiringAttention().find(m => m._id === matchId);
}
if (match) {
// Create and dispatch the event
const event = new LeagueMatchesAttentionEvent({
type: 'matchClick',
match: match,
attentionReason: attentionReason
});
const dispatchResult = this.dispatchEvent(event);
// If the event was canceled, log it
if (!dispatchResult) {
console.warn('[LeagueMatchesAttention] Event was canceled by a listener');
}
} else {
console.warn('[LeagueMatchesAttention] No match found for ID:', matchId);
}
};
});
// Add a global click handler to the shadow root to see if clicks are reaching it
this.shadow.addEventListener('click', e => {
if (e.target.classList.contains('match-link')) {
console.log('[LeagueMatchesAttention] Shadow root click handler - match link clicked');
}
}, {
capture: true
});
}
// Public API methods
setPage(pageNumber) {
if (pageNumber >= 0 && pageNumber !== this.currentPage) {
this.currentPage = pageNumber;
this.render();
}
}
// Helper method for HTML escaping
escapeHtml(unsafe = '') {
const str = String(unsafe);
return str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
}
}
// Register the custom element
safeDefine('league-matches-attention', LeagueMatchesAttention);
/**
* Validation utilities for the leagueJS
*/
function validateLeague(data) {
const errors = [];
if (!data.name) {
errors.push('League name is required');
}
if (data.settings) {
if (typeof data.settings.pointsForWin !== 'undefined') {
if (typeof data.settings.pointsForWin !== 'number' || data.settings.pointsForWin < 0) {
errors.push('Invalid points settings');
}
}
if (typeof data.settings.pointsForDraw !== 'undefined') {
if (typeof data.settings.pointsForDraw !== 'number' || data.settings.pointsForDraw < 0) {
errors.push('Invalid points settings');
}
}
if (typeof data.settings.pointsForLoss !== 'undefined') {
if (typeof data.settings.pointsForLoss !== 'number' || data.settings.pointsForLoss < 0) {
errors.push('Invalid points settings');
}
}
// Validate timesTeamsPlayOther
if (typeof data.settings.timesTeamsPlayOther !== 'undefined') {
if (typeof data.settings.timesTeamsPlayOther !== 'number' || data.settings.timesTeamsPlayOther < 1 || data.settings.timesTeamsPlayOther > 10) {
errors.push('timesTeamsPlayOther must be an integer between 1 and 10');
}
}
}
return {
isValid: errors.length === 0,
errors
};
}
function validateTeam(data) {
const errors = [];
if (!data._id || !data._id.trim()) {
errors.push('Team ID is required');
}
return {
isValid: errors.length === 0,
errors
};
}
function validateMatch(data) {
const errors = [];
if (!data.homeTeam || !data.homeTeam._id) {
errors.push('Home team is required');
}
if (!data.awayTeam || !data.awayTeam._id) {
errors.push('Away team is required');
}
if (data.date && !(data.date instanceof Date) && isNaN(new Date(data.date).getTime())) {
errors.push('Invalid date format');
}
// Validate result scores if result object exists
if (data.result) {
if (typeof data.result.homeScore !== 'number' || data.result.homeScore < 0) {
errors.push('Home score must be a non-negative number');
}
if (typeof data.result.awayScore !== 'number' || data.result.awayScore < 0) {
errors.push('Away score must be a non-negative number');
}
// Optionally, could add validation for rinkScores structure here if needed
}
return {
isValid: errors.length === 0,
errors
};
}
/**
* Generates a GUID (Globally Unique Identifier)
* @returns {string} A GUID string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
*/
function generateGUID() {
// Generate random hex digits
const hex = () => Math.floor(Math.random() * 16).toString(16);
// Build GUID in format: 8-4-4-4-12
return [
// 8 hex digits
Array(8).fill(0).map(hex).join(''),
// 4 hex digits
Array(4).fill(0).map(hex).join(''),
// 4 hex digits
Array(4).fill(0).map(hex).join(''),
// 4 hex digits
Array(4).fill(0).map(hex).join(''),
// 12 hex digits
Array(12).fill(0).map(hex).join('')].join('-');
}
/**
* Team model representing a bowls team
*/
class Team {
/**
* Create a new Team
* @param {Object} data - Team data
* @param {string} data._id - Unique identifier for the team
* @param {string} [data.name] - Name of the team (defaults to _id if not provided)
* @param {Date} [data.createdAt] - Creation date (defaults to current date)
* @param {Date} [data.updatedAt] - Last update date (defaults to current date)
*/
constructor(data) {
const validationResult = validateTeam(data);
if (!validationResult.isValid) {
throw new Error(validationResult.errors[0]);
}
this._id = data._id || generateGUID();
this.name = data.name || data._id;
this.createdAt = data.createdAt || new Date();
this.updatedAt = data.updatedAt || new Date();
}
/**
* Update team details
* @param {Object} updates - Updated team details
*/
update(updates) {
Object.assign(this.details, updates);
this.updatedAt = new Date();
}
/**
* Convert team to JSON
* @returns {Object} - JSON representation of the team
*/
toJSON() {
return {
_id: this._id,
name: this.name,
createdAt: this.createdAt,
updatedAt: this.updatedAt
};
}
}
/**
* Match model representing a bowls match between two teams
* @typedef {Object} MatchData
* @property {Object} homeTeam - Home team object with _id property
* @property {Object} awayTeam - Away team object with _id property
* @property {string} [_id] - Unique identifier for the match
* @property {Date|string|null} [date] - Match date (can be null for unscheduled matches)
* @property {Object} [result] - Optional match result data containing scores
* @property {number} [result.homeScore] - Home team's score
* @property {number} [result.awayScore] - Away team's score
* @property {Array<Object>} [result.rinkScores] - Optional individual rink scores
* @property {Date} [createdAt] - Creation date (defaults to current date)
* @property {Date} [updatedAt] - Last update date (defaults to current date)
*/
class Match {
/**
* Create a new Match
* @param {Object} data - Match data
* @param {Object} data.homeTeam - Home team object with _id property
* @param {Object} data.awayTeam - Away team object with _id property
* @param {Date|string|null} [data.date] - Match date (can be null for unscheduled matches)
* @param {Object} [data.result] - Optional match result data containing scores
* @param {number} [data.result.homeScore] - Home team's score
* @param {number} [data.result.awayScore] - Away team's score
* @param {Array<Object>} [data.result.rinkScores] - Optional individual rink scores
* @param {Date} [data.createdAt] - Creation date (defaults to current date)
* @param {Date} [data.updatedAt] - Last update date (defaults to current date)
*/
constructor(data) {
const validationResult = validateMatch(data);
if (!validationResult.isValid) {
throw new Error(validationResult.errors[0]);
}
if (data.homeTeam._id === data.awayTeam._id) {
throw new Error('Home and away teams must be different');
}
this._id = data._id || generateGUID();
this.homeTeam = data.homeTeam;
this.awayTeam = data.awayTeam;
this.date = data.date ? new Date(data.date) : null;
this.createdAt = data.createdAt || new Date();
this.updatedAt = data.updatedAt || new Date();
// Process result if scores are provided
if (data.result && typeof data.result.homeScore === 'number' && typeof data.result.awayScore === 'number') {
this.result = {
homeScore: data.result.homeScore,
awayScore: data.result.awayScore,
rinkScores: data.result.rinkScores || null
};
} else {
this.result = null; // Ensure result is null if scores are not provided
}
}
/**
* Get the home team name
* @returns {string} - The name of the home team
*/
get homeTeamName() {
return this.homeTeam.name;
}
/**
* Get the away team name
* @returns {string} - The name of the away team
*/
get awayTeamName() {
return this.awayTeam.name;
}
/**
* Determines the winner of the match based on scores.
* @returns {string|null} - The name of the winning team, 'draw', or null if no result is set.
*/
getWinner() {
if (!this.result) {
return null;
}
if (this.result.homeScore > this.result.awayScore) {
return this.homeTeamName;
}
if (this.result.awayScore > this.result.homeScore) {
return this.awayTeamName;
}
return 'draw';
}
/**
* Checks if the match resulted in a draw.
* @returns {boolean|null} - True if it's a draw, false otherwise, or null if no result is set.
*/
isDraw() {
if (!this.result) {
return null;
}
return this.result.homeScore === this.result.awayScore;
}
/**
* Set rink scores for an existing match result
* @param {Array} rinkScores - Array of rink scores [{homeScore, awayScore}, ...]
* @returns {boolean} - True if scores were set, false if no result exists
*/
setRinkScores(rinkScores) {
if (!this.result) return false;
this.result.rinkScores = rinkScores;
this.updatedAt = new Date();
return true;
}
/**
* Get rink win/draw counts
* @returns {Object|null} - Object with rink win counts or null if no rink scores
*/
getRinkResults() {
if (!this.result || !this.result.rinkScores) return null;
const rinkResults = {
homeWins: 0,
awayWins: 0,
draws: 0,
total: this.result.rinkScores.length
};
this.result.rinkScores.forEach(rink => {
if (rink.homeScore > rink.awayScore) {
rinkResults.homeWins++;
} else if (rink.awayScore > rink.homeScore) {
rinkResults.awayWins++;
} else {
rinkResults.draws++;
}
});
return rinkResults;
}
/**
* Convert match to JSON
* @returns {Object} - JSON representation of the match
*/
toJSON() {
const jsonResult = this.result ? {
...this.result,
winner: this.getWinner(),
isDraw: this.isDraw()
} : null;
return {
_id: this._id,
homeTeam: this.homeTeam,
awayTeam: this.awayTeam,
date: this.date,
result: jsonResult,
createdAt: this.createdAt,
updatedAt: this.updatedAt
};
}
}
/**
* League model representing a bowls league
*/
class League {
/**
* Create a League instance from JSON data
* @param {Object|string} jsonData - League data as JSON object or string
* @returns {League} - New League instance
*/
static fromJSON(jsonData) {
try {
const data = typeof jsonData === 'string' ? JSON.parse(jsonData) : jsonData;
return new League(data);
} catch (error) {
throw new Error(`Failed to load league: ${error.message}`);
}
}
/**
* Create a new League
* @param {Object} data - League data
* @param {string} [data._id] - Unique identifier for the league (auto-generated if not provided)
* @param {string} data.name - Name of the league
* @param {Object} [data.settings] - League settings
* @param {number} [data.settings.pointsForWin=3] - Points awarded for a win
* @param {number} [data.settings.pointsForDraw=1] - Points awarded for a draw
* @param {number} [data.settings.pointsForLoss=0] - Points awarded for a loss
* @param {number} [data.settings.promotionPositions] - Number of teams that get promoted
* @param {number} [data.settings.relegationPositions] - Number of teams that get relegated
* @param {number} [data.settings.timesTeamsPlayOther=2] - Number of times teams play against each other (1-10)
* @param {Object} [data.settings.rinkPoints] - Settings for rink-based scoring
* @param {number} [data.settings.rinkPoints.pointsPerRinkWin=2] - Points awarded per winning rink
* @param {number} [data.settings.rinkPoints.pointsPerRinkDraw=1] - Points awarded per drawn rink
* @param {number} [data.settings.rinkPoints.defaultRinks=4] - Default number of rinks per match
* @param {boolean} [data.settings.rinkPoints.enabled=false] - Whether rink points are enabled
* @param {Array<Team>} [data.teams=[]] - Initial list of teams
* @param {Array<>} [data.matches=[]] - Initial list of matches
* @param {Date} [data.createdAt] - Creation date (defaults to current date)
* @param {Date} [data.updatedAt] - Last update date (defaults to current date)
*/
constructor(data) {
var _data$settings, _data$settings2, _data$settings3, _data$settings4, _data$settings5, _data$settings6, _data$settings7;
const validationResult = validateLeague(data);
if (!validationResult.isValid) {
throw new Error(`Invalid league data: ${validationResult.errors.join(', ')}`);
}
this._id = data._id || generateGUID();
this.name = data.name;
this.settings = {
pointsForWin: ((_data$settings = data.settings) === null || _data$settings === void 0 ? void 0 : _data$settings.pointsForWin) || 3,
pointsForDraw: ((_data$settings2 = data.settings) === null || _data$settings2 === void 0 ? void 0 : _data$settings2.pointsForDraw) || 1,
pointsForLoss: ((_data$settings3 = data.settings) === null || _data$settings3 === void 0 ? void 0 : _data$settings3.pointsForLoss) || 0,
promotionPositions: (_data$settings4 = data.settings) === null || _data$settings4 === void 0 ? void 0 : _data$settings4.promotionPositions,
relegationPositions: (_data$settings5 = data.settings) === null || _data$settings5 === void 0 ? void 0 : _data$settings5.relegationPositions,
timesTeamsPlayOther: ((_data$settings6 = data.settings) === null || _data$settings6 === void 0 ? void 0 : _data$settings6.timesTeamsPlayOther) || 2
};
if ((_data$settings7 = data.settings) !== null && _data$settings7 !== void 0 && _data$settings7.rinkPoints) {
this.settings.rinkPoints = {
pointsPerRinkWin: data.settings.rinkPoints.pointsPerRinkWin || 2,
pointsPerRinkDraw: data.settings.rinkPoints.pointsPerRinkDraw || 1,
defaultRinks: data.settings.rinkPoints.defaultRinks || 4,
enabled: data.settings.rinkPoints.enabled || false
};
}
this.teams = (data.teams || []).map(team => new Team(team));
this.matches = (data.matches || []).map(match => new Match(match));
this.createdAt = data.createdAt || new Date();
this.updatedAt = data.updatedAt || new Date();
}
/**
* Add a team to the league
* @param {Team|Object} team - Team to add (either a Team instance or team data)
* @returns {boolean} - True if team was added, false if already exists
* @throws {Error} - If team data is invalid
*/
addTeam(team) {
// If team is not already a Team instance, try to create one (which will validate the data)
const teamInstance = team instanceof Team ? team : new Team(team);
// Check if team with same ID already exists
if (!this.teams.some(t => t._id === teamInstance._id)) {
this.teams.push(teamInstance);
this.updatedAt = new Date();
return true;
}
return false;
}
/**
* Remove a team from the league
* @param {string} teamId - ID of team to remove
* @returns {boolean} - True if team was removed, false if not found
*/
removeTeam(teamId) {
const initialLength = this.teams.length;
this.teams = this.teams.filter(team => team._id !== teamId);
if (this.teams.length !== initialLength) {
this.updatedAt = new Date();
return true;
}
return false;
}
/**
* Add a match to the league
* @param {Match|Object} match - Match instance or match data
* @returns {boolean} - True if match was added, false otherwise
* @throws {Error} - If match data is invalid
*/
addMatch(match) {
// If match is not already a Match instance, try to create one (which will validate the data)
const matchInstance = match instanceof Match ? match : new Match(match);
// Validate that both teams are in this league using IDs
const homeTeamExists = this.teams.some(team => team._id === matchInstance.homeTeam._id);
const awayTeamExists = this.teams.some(team => team._id === matchInstance.awayTeam._id);
if (homeTeamExists && awayTeamExists) {
// Check if a match with the same _id already exists
if (this.matches.some(m => m._id === matchInstance._id)) {
return false; // Match already exists
}
this.matches.push(matchInstance);
this.updatedAt = new Date();
return true;
}
return false;
}
/**
* Get a team by its ID
* @param {string} teamId - ID of the team
* @returns {Team|undefined} - The team if found, undefined otherwise
*/
getTeam(teamId) {
return this.teams.find(team => team._id === teamId);
}
/**
* Get a match by its ID
* @param {string} matchId - The ID of the match
* @returns {Match|undefined} - The match if found, undefined otherwise
*/
getMatch(matchId) {
return this.matches.find(match => match._id === matchId);
}
/**
* Get all matches for a team
* @param {string} teamId - ID of the team
* @returns {Array<Match>} - Array of matches involving the team
*/
getTeamMatches(teamId) {
const team = this.getTeam(teamId);
if (!team) {
throw new Error(`Team not found with ID: ${teamId}`);
}
return this.matches.filter(match => match.homeTeam._id === teamId || match.awayTeam._id === teamId);
}
/**
* Get statistics for a team
* @param {string} teamId - ID of the team
* @returns {Object} - Team statistics
*/
getTeamStats(teamId) {
const team = this.getTeam(teamId);
if (!team) {
throw new Error(`Team not found with ID: ${teamId}`);
}
const matches = this.getTeamMatches(teamId);
const stats = {
teamId: teamId,
teamName: team.name,
played: 0,
won: 0,
drawn: 0,
lost: 0,
shotsFor: 0,
shotsAgainst: 0,
points: 0,
inPromotionPosition: false,
inRelegationPosition: false
};
// Sort matches by date to determine form/recent matches
const playedMatches = matches.filter(match => match.result && match.date) // Ensure match has result and date
.sort((a, b) => new Date(a.date) - new Date(b.date)); // Sort oldest to newest
const recentMatchDetails = []; // Array to store details for tooltip
playedMatches.forEach(match => {
// Ensure result object and scores exist
if (!match.result || typeof match.result.homeScore !== 'number' || typeof match.result.awayScore !== 'number') {
console.warn(`Match ${match._id} for team ${team.name} missing valid result or scores.`);
return; // Skip this match if data is incomplete
}
const isHome = match.homeTeam._id === teamId;
const teamScore = isHome ? match.result.homeScore : match.result.awayScore;
const opponentScore = isHome ? match.result.awayScore : match.result.homeScore;
// const opponentName = isHome ? match.awayTeamName : match.homeTeamName; // Not needed for description format below
stats.played++;
stats.shotsFor += teamScore;
stats.shotsAgainst += opponentScore;
let resultChar = '';
if (teamScore > opponentScore) {
stats.won++;
stats.points += this.settings.pointsForWin;
resultChar = 'W';
} else if (teamScore < opponentScore) {
stats.lost++;
stats.points += this.settings.pointsForLoss;
resultChar = 'L';
} else {
stats.drawn++;
stats.points += this.settings.pointsForDraw;
resultChar = 'D';
}
// Format date for description - adjust locale/options as needed
const matchDateStr = new Date(match.date).toLocaleDateString(undefined, {
year: 'numeric',
month: 'short',
day: 'numeric'
});
const description = `${matchDateStr}: ${match.homeTeam.name} ${match.result.homeScore} - ${match.result.awayScore} ${match.awayTeam.name}`;
recentMatchDetails.push({
result: resultChar,
description: description,
date: match.date // Keep the original date object if needed elsewhere
});
});
// Keep only the details for the last 5 matches
stats.matches = recentMatchDetails.slice(-5);
// Promotion/relegation positions are set in getLeagueTable after sorting
return stats;
}
getLeagueTable() {
// First, calculate basic stats for all teams
const teamStats = this.teams.map(team => {
const stats = this.getTeamStats(team._id);
return {
teamId: team._id,
teamName: team.name,
...stats,
shotDifference: stats.shotsFor - stats.shotsAgainst
};
});
// Sort the table
const sortedTable = teamStats.sort((a, b) => {
// Sort by points first
if (b.points !== a.points) {
return b.points - a.points;
}
// Then by shot difference
if (b.shotDifference !== a.shotDifference) {
return b.shotDifference - a.shotDifference;
}
// Then by shots scored
if (b.shotsFor !== a.shotsFor) {
return b.shotsFor - a.shotsFor;
}
// Finally by team name
return a.teamName.localeCompare(b.teamName);
});
// Now update promotion/relegation positions
if (this.settings.promotionPositions || this.settings.relegationPositions) {
sortedTable.forEach((team, index) => {
const position = index + 1;
if (this.settings.promotionPositions && position <= this.settings.promotionPositions) {
team.inPromotionPosition = true;
}
if (this.settings.relegationPositions && position > sortedTable.length - this.settings.relegationPositions) {
team.inRelegationPosition = true;
}
});
}
return {
leagueData: sortedTable,
metaData: {
name: this.name
}
};
}
/*
* Initialise fixtures for the league using a round-robin algorithm.
* Each team plays once per match day. Fixtures are scheduled according to the provided scheduling parameters.
* Teams will play each other `this.settings.timesTeamsPlayOther` times, with home and away fixtures balanced
* as per the cycles of the round-robin generation (e.g., first cycle A vs B, second cycle B vs A).
*
* @param {Date} [startDate] - The start date for the first round of matches. If null, matches will have null dates.
* @param {Object} [schedulingParams] - Advanced scheduling parameters
* @param {string} [schedulingParams.schedulingPattern='interval'] - 'interval' or 'dayOfWeek'
* @param {number} [schedulingParams.intervalNumber=1] - Number of interval units between match days
* @param {string} [schedulingParams.intervalUnit='weeks'] - 'days' or 'weeks'
* @param {Array<number>} [schedulingParams.selectedDays] - Array of day numbers (0=Sunday, 1=Monday, etc.) for dayOfWeek pattern
* @param {number} [schedulingParams.maxMatchesPerDay] - Maximum matches per day (optional)
* @returns {boolean} - True if fixtures were successfully created, false if there are fewer than 2 teams or if a match fails to be added.
*/
initialiseFixtures(startDate, schedulingParams = {}) {
this.matches = []; // Clear any existing matches
if (this.teams.length < 2) {
return false; // Not enough teams to create fixtures
}
// Set default scheduling parameters
const {
schedulingPattern = 'interval',
intervalNumber = 1,
intervalUnit = 'weeks',
selectedDays = [],
maxMatchesPerDay = null
} = schedulingParams;
// Prepare team list for scheduling. Add a dummy "BYE" team if the number of teams is odd.
let scheduleTeams = [...this.teams];
const BYE_TEAM_MARKER = {
_id: `__BYE_TEAM_INTERNAL_${Date.now()}__`,
name: 'BYE'
}; // Unique marker for the bye team
if (scheduleTeams.length % 2 !== 0) {
scheduleTeams.push(BYE_TEAM_MARKER);
}
const numEffectiveTeams = scheduleTeams.length; // This will now always be even
// Calculate the number of rounds needed for all unique pairings once
const roundsPerCycle = numEffectiveTeams - 1;
// Generate all matches first, then assign dates
const allMatches = [];
// The round-robin algorithm fixes one team and rotates the others.
// We'll fix the last team in the `scheduleTeams` list.
const fixedTeam = scheduleTeams[numEffectiveTeams - 1];
// The list of teams that will be rotated.
const initialRotatingTeams = scheduleTeams.slice(0, numEffectiveTeams - 1);
// Loop for each full set of fixtures (e.g., once for "home" games, once for "away" games if timesTeamsPlayOther is 2)
for (let cycle = 0; cycle < this.settings.timesTeamsPlayOther; cycle++) {
// For each cycle, re-initialize the rotating teams to ensure the same sequence of pairings.
let currentRotatingTeams = [...initialRotatingTeams];
for (let roundNum = 0; roundNum < roundsPerCycle; roundNum++) {
const conceptualPairsForThisRound = []; // Stores {team1, team2} for this specific round
// 1. Match involving the fixed team (e.g., scheduleTeams[n-1])
// Its opponent is the first team in the current rotated list.
const opponentForFixed = currentRotatingTeams[0];
if (fixedTeam._id !== BYE_TEAM_MARKER._id && opponentForFixed._id !== BYE_TEAM_MARKER._id) {
conceptualPairsForThisRound.push({
team1: fixedTeam,
team2: opponentForFixed
});
}
// 2. Other matches from the `currentRotatingTeams` list.
// The list has `numEffectiveTeams - 1` elements (an odd number).
// The first element `currentRotatingTeams[0]` is already paired with `fixedTeam`.
// The remaining elements `currentRotatingTeams[1]` to `currentRotatingTeams[length-1]` are paired up.
const rotatingListLength = currentRotatingTeams.length;
for (let j = 1; j <= (rotatingListLength - 1) / 2; j++) {
const teamA_idx = j;
const teamB_idx = rotatingListLength - j; // Pairs j-th from start with j-th from end (0-indexed list)
const teamA = currentRotatingTeams[teamA_idx];
const teamB = currentRotatingTeams[teamB_idx];
if (teamA._id !== BYE_TEAM_MARKER._id && teamB._id !== BYE_TEAM_MARKER._id) {
conceptualPairsForThisRound.push({
team1: teamA,
team2: teamB
});
}
}
// Store matches for this round
for (const pair of conceptualPairsForThisRound) {
let homeTeam, awayTeam;
// For even cycles (0, 2, ...), team1 is home. For odd cycles (1, 3, ...), team2 is home.
// This ensures that if pair (X,Y) is generated, cycle 0 schedules X vs Y, cycle 1 schedules Y vs X.
if (cycle % 2 === 0) {
homeTeam = pair.team1;
awayTeam = pair.team2;
} else {
homeTeam = pair.team2;
awayTeam = pair.team1;
}
allMatches.push({
homeTeam,
awayTeam,
roundKey: `${cycle}-${roundNum}`
});
}
// Rotate `currentRotatingTeams` for the next round: the last element moves to the front.
if (currentRotatingTeams.length > 1) {
// Rotation only makes sense for 2+ teams
const lastTeamInRotatingList = currentRotatingTeams.pop();
currentRotatingTeams.unshift(lastTeamInRotatingList);
}
}
}
// Now assign dates to matches based on scheduling pattern
if (startDate) {
this._assignMatchDates(allMatches, startDate, schedulingPattern, intervalNumber, intervalUnit, selectedDays, maxMatchesPerDay);
} else {
// No start date provided - create matches without dates
for (const matchData of allMatches) {
const match = new Match({
homeTeam: matchData.homeTeam,
awayTeam: matchData.awayTeam,
date: null
});
if (!this.addMatch(match)) {
return false; // If addMatch fails (e.g., duplicate _id), abort.
}
}
}
return true;
}
/**
* Private helper method to assign dates to matches based on scheduling parameters
*/
_assignMatchDates(allMatches, startDate, schedulingPattern, intervalNumber, intervalUnit, selectedDays, maxMatchesPerDay) {
// Group matches by round for scheduling