/**
* Channel List Component
* Handles the sidebar channel list
*/
class ChannelList {
constructor() {
this.container = document.getElementById('channel-list');
this.searchInput = document.getElementById('channel-search');
this.sourceSelect = document.getElementById('source-select');
this.showHiddenCheckbox = document.getElementById('show-hidden');
this.toggleGroupsBtn = document.getElementById('toggle-groups');
this.contextMenu = document.getElementById('context-menu');
this.channels = [];
this.groups = [];
this.hiddenItems = new Set(); // Set<"type:sourceId:itemId">
this.collapsedGroups = new Set(); // Track collapsed groups
this._userExpandedGroups = new Set(); // Track groups user has explicitly expanded
this.favorites = []; // Array of favorite objects
this.visibleFavorites = new Set(); // Set<"sourceId:channelId">
this.currentChannel = null;
this.sources = [];
this.isLoading = false;
this.renderedChannels = [];
this.catalogVersion = 0;
this.hasMore = false;
this.catalogQuery = '';
this.catalogStatus = document.createElement('div');
this.catalogStatus.setAttribute('role', 'status');
this.catalogStatus.className = 'live-catalog-status';
this.container.after(this.catalogStatus);
this.loadMoreButton = document.createElement('button');
this.loadMoreButton.type = 'button';
this.loadMoreButton.className = 'btn btn-sm live-catalog-more';
this.loadMoreButton.textContent = 'Load more';
this.loadMoreButton.hidden = true;
this.catalogStatus.after(this.loadMoreButton);
this.loadMoreButton.addEventListener('click', () => this.loadCatalogPage(this.channels.length > 0));
this.loadCollapsedState();
this.init();
}
/**
* Get proxied image URL to avoid mixed content errors on HTTPS
* Only proxies HTTP URLs when on HTTPS page
*/
getProxiedImageUrl(url) {
if (!url || url.length === 0) return '/img/placeholder.png';
// Only proxy if we're on HTTPS and the image is HTTP
if (window.location.protocol === 'https:' && url.startsWith('http://')) {
return `/api/proxy/image?url=${encodeURIComponent(url)}`;
}
return url;
}
/**
* Load collapsed state from localStorage
*/
loadCollapsedState() {
try {
const saved = localStorage.getItem('nodecast_tv_collapsed_groups');
if (saved) {
this.collapsedGroups = new Set(JSON.parse(saved));
this._hasCollapsedState = true;
} else {
this._hasCollapsedState = false; // First load - will collapse all by default
}
} catch (err) {
console.error('Error loading collapsed state:', err);
this._hasCollapsedState = false;
}
}
/**
* Save collapsed state to localStorage
*/
saveCollapsedState() {
try {
localStorage.setItem('nodecast_tv_collapsed_groups', JSON.stringify([...this.collapsedGroups]));
} catch (err) {
console.error('Error saving collapsed state:', err);
}
}
/**
* Toggle group collapsed state
*/
toggleGroup(groupName) {
if (this.collapsedGroups.has(groupName)) {
this.collapsedGroups.delete(groupName);
// Track that user explicitly expanded this group
this._userExpandedGroups.add(groupName);
} else {
this.collapsedGroups.add(groupName);
// User collapsed it, remove from expanded tracking
this._userExpandedGroups.delete(groupName);
}
this.saveCollapsedState();
}
/**
* Expand all groups
*/
expandAll() {
this.collapsedGroups.clear();
this.saveCollapsedState();
// Expand all and render channels for empty containers
this.container.querySelectorAll('.group-header.collapsed').forEach(h => {
h.classList.remove('collapsed');
const groupName = h.dataset.group;
const groupEl = h.closest('.channel-group');
const channelsContainer = groupEl?.querySelector('.group-channels');
if (channelsContainer && channelsContainer.children.length === 0) {
this.renderGroupChannels(groupName, channelsContainer);
}
});
// Update toggle button
if (this.toggleGroupsBtn) {
this.toggleGroupsBtn.innerHTML = Icons.collapseAll;
this.toggleGroupsBtn.title = 'Collapse All';
}
}
/**
* Collapse all groups
*/
collapseAll() {
this.container.querySelectorAll('.group-header').forEach(h => {
const groupName = h.dataset.group;
this.collapsedGroups.add(groupName);
h.classList.add('collapsed');
});
this.saveCollapsedState();
// Update toggle button
if (this.toggleGroupsBtn) {
this.toggleGroupsBtn.innerHTML = Icons.expandAll;
this.toggleGroupsBtn.title = 'Expand All';
}
}
/**
* Toggle between expand/collapse all
*/
toggleAllGroups() {
const allHeaders = this.container.querySelectorAll('.group-header');
const allCollapsed = [...allHeaders].every(h => h.classList.contains('collapsed'));
if (allCollapsed) {
this.expandAll();
} else {
this.collapseAll();
}
}
init() {
// Search handler (debounced)
const searchNow = () => {
clearTimeout(this.searchTimeout);
this.loadChannels();
};
this.searchInput.addEventListener('input', () => {
clearTimeout(this.searchTimeout);
this.catalogVersion++;
this.catalogController?.abort();
this.loadMoreButton.hidden = true;
this.searchTimeout = setTimeout(searchNow, 300);
});
this.searchInput.addEventListener('keydown', e => {
if (e.key === 'Enter') { e.preventDefault(); searchNow(); }
});
document.getElementById('channel-search-submit')?.addEventListener('click', searchNow);
this.searchInput.parentElement.querySelector('.search-clear')?.addEventListener('click', () => {
this.searchInput.value = '';
searchNow();
this.searchInput.focus();
});
this.sourceSelect.addEventListener('change', searchNow);
this.showHiddenCheckbox?.addEventListener('change', searchNow);
// Context menu handlers
document.addEventListener('click', (e) => {
// Don't close if clicking inside context menu
if (!this.contextMenu.contains(e.target)) {
this.hideContextMenu();
}
});
this.contextMenu.querySelectorAll('.context-item').forEach(item => {
item.addEventListener('click', (e) => {
e.stopPropagation(); // Prevent document click from firing
this.handleContextAction(e);
});
});
// Intersection Observer for lazy loading
this.observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
this.renderNextBatch();
}
}, { rootMargin: '100px' });
// Start EPG refresh timer (updates visible program info every 60 seconds)
this.startEpgRefreshTimer();
}
/**
* Start timer to refresh EPG info in visible channel items
* Updates every 60 seconds to keep "Now Playing" program info current
*/
startEpgRefreshTimer() {
// Clear any existing timer
if (this._epgRefreshTimer) {
clearInterval(this._epgRefreshTimer);
}
// Refresh every 60 seconds
this._epgRefreshTimer = setInterval(() => {
this.updateVisibleEpgInfo();
}, 60000);
}
/**
* Update EPG info for visible channel items without full re-render
* Only updates the program text, not the entire channel item
*/
updateVisibleEpgInfo() {
if (!window.app || !window.app.epgGuide) return;
// Clear the cache so we get fresh data
this.clearProgramInfoCache();
// Find all visible channel items and update their program info
const channelItems = this.container.querySelectorAll('.channel-item');
channelItems.forEach(item => {
const channelId = item.dataset.channelId;
const sourceId = item.dataset.sourceId;
// Find the channel data
const channel = this.channels.find(c =>
String(c.id) === String(channelId) &&
String(c.sourceId) === String(sourceId)
);
if (channel) {
const programInfo = this.getProgramInfo(channel);
const programElement = item.querySelector('.channel-program');
if (programElement) {
programElement.textContent = programInfo || '';
}
}
});
}
/**
* Get current program info string - cached for performance
*/
getProgramInfo(channel) {
try {
if (!window.app || !window.app.epgGuide) return null;
// Cache key: channel_id + current_minute (invalidate every minute)
const currentMinute = Math.floor(Date.now() / 60000);
const cacheKey = `${channel.tvgId || channel.name}:${currentMinute}`;
if (this._programInfoCache && this._programInfoCache.has(cacheKey)) {
return this._programInfoCache.get(cacheKey);
}
// Clear old cache entries if minute changed
if (!this._lastCacheMinute || this._lastCacheMinute !== currentMinute) {
this._programInfoCache = new Map();
this._lastCacheMinute = currentMinute;
}
const program = window.app.epgGuide.getCurrentProgram(channel.tvgId, channel.name);
const result = program ? program.title : null;
this._programInfoCache.set(cacheKey, result);
return result;
} catch (e) {
console.warn("Error in getProgramInfo", e);
return null;
}
}
/**
* Clear program info cache
* Useful when EPG data has been updated
*/
clearProgramInfoCache() {
if (this._programInfoCache) {
this._programInfoCache.clear();
}
}
escapeHtml(text) {
if (!text) return '';
return String(text)
.replace(/&/g, "&")
.replace(//g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
compareBinary(left, right) {
const a = Array.from(String(left ?? ''));
const b = Array.from(String(right ?? ''));
for (let i = 0; i < Math.min(a.length, b.length); i++) {
const difference = a[i].codePointAt(0) - b[i].codePointAt(0);
if (difference) return difference;
}
return a.length - b.length;
}
catalogSortKey(value) {
return String(value ?? '').replace(/^ +| +$/g, '').replace(/[A-Z]/g, character => character.toLowerCase());
}
compareCatalogTitles(a, b) {
return this.compareBinary(this.catalogSortKey(a), this.catalogSortKey(b)) || this.compareBinary(a, b);
}
compareCatalogChannels(a, b) {
return this.compareCatalogTitles(a.name, b.name) || Number(a.sourceId) - Number(b.sourceId) ||
this.compareBinary(a.streamId ?? a.id, b.streamId ?? b.id);
}
/**
* Render channel list
*/
render() {
const searchTerm = this.catalogQuery;
const showHidden = this.showHiddenCheckbox ? this.showHiddenCheckbox.checked : false;
// Reset batching
this.currentBatch = 0;
this.batchSize = 100; // Number of groups to render per batch (increased to handle many hidden groups)
this.observer.disconnect();
this.container.innerHTML = ''; // Clear container
// Filter and Group channels
const groupedChannels = Object.create(null);
// 1. Filter
this.filteredChannels = this.channels;
let filteredChannels = this.filteredChannels;
// 2. Group
filteredChannels.forEach(ch => {
const groupKey = ch.groupTitle ?? 'Uncategorized';
if (!groupedChannels[groupKey]) {
groupedChannels[groupKey] = [];
}
groupedChannels[groupKey].push(ch);
});
Object.values(groupedChannels).forEach(channels => channels.sort((a, b) => this.compareCatalogChannels(a, b)));
// Keep the synthetic Favorites group separate even from a provider's "Favorites" group.
this.favoriteGroupKey = '__nodecast_favorites__';
while (Object.hasOwn(groupedChannels, this.favoriteGroupKey)) this.favoriteGroupKey += '_';
// 3. Add Favorites
const favoritedChannels = this.channels.filter(ch => this.isFavorite(ch.sourceId, ch.id));
if (favoritedChannels.length > 0) {
favoritedChannels.sort((a, b) => this.compareCatalogChannels(a, b));
groupedChannels[this.favoriteGroupKey] = favoritedChannels;
}
// 4. Sort Groups and filter to only those with visible channels
const allGroups = Object.keys(groupedChannels).sort((a, b) => {
if (a === this.favoriteGroupKey) return -1;
if (b === this.favoriteGroupKey) return 1;
return this.compareCatalogTitles(a, b);
});
// Pre-filter to only include groups with visible channels (so hidden groups don't consume batch slots)
this.sortedGroups = allGroups.filter(groupName => {
if (groupName === this.favoriteGroupKey) return true;
const channels = groupedChannels[groupName];
// Check if any channel in this group is visible
return channels.some(channel => {
const rawChannelId = channel.streamId ?? channel.id;
const isHidden = this.isHidden('channel', channel.sourceId, rawChannelId);
return !isHidden || showHidden;
});
});
this.groupedChannels = groupedChannels;
this.showHidden = showHidden;
// Collapse all groups by default on first load (for large playlists)
// This prevents rendering 100K+ channel items on initial load
if (!this._hasCollapsedState && this.sortedGroups.length > 0) {
this.sortedGroups.forEach(groupName => {
if (groupName !== this.favoriteGroupKey) {
this.collapsedGroups.add(groupName);
}
});
this._hasCollapsedState = true;
this.saveCollapsedState();
}
// Build rendered channel list for navigation (matches visual order)
this.renderedChannels = [];
this.sortedGroups.forEach(groupName => {
const channels = this.groupedChannels[groupName];
const isFavoritesGroup = groupName === this.favoriteGroupKey;
const visibleChannels = channels.filter(channel => {
if (isFavoritesGroup) return true;
const rawChannelId = channel.streamId ?? channel.id;
const channelHidden = this.isHidden('channel', channel.sourceId, rawChannelId);
return !channelHidden || this.showHidden;
});
// Assign unique render IDs for linear navigation
visibleChannels.forEach(ch => {
// We clone the object for the rendered list to attach the unique ID
// ensuring no side effects on the main channel object
const renderedCh = {
...ch,
_renderId: `rid_${encodeURIComponent(groupName)}_${ch.sourceId}_${encodeURIComponent(ch.id)}`,
_renderGroup: groupName // Track visual group for navigation
};
this.renderedChannels.push(renderedCh);
});
});
// Empty State
if (this.sortedGroups.length === 0) {
this.container.innerHTML = `
${searchTerm ? 'No channels match your search' : 'No channels loaded'}
${searchTerm ? 'Try a different search term' : 'Add a source in Settings to get started'}
`;
return;
}
// Wrap container content in a specific list div to append to
this.listContainer = document.createElement('div');
this.listContainer.className = 'channel-list-content';
this.container.appendChild(this.listContainer);
// Add loader element at bottom
this.loader = document.createElement('div');
this.loader.className = 'batch-loader';
this.loader.innerHTML = '';
this.loader.style.opacity = '0'; // Hide initially
this.container.appendChild(this.loader);
// Render initial batches - load just enough to fill visible area + buffer
// Reduced from 10 to 2 to significantly speed up initial load time for large lists
const maxInitialBatches = 2;
for (let i = 0; i < maxInitialBatches; i++) {
if (this.currentBatch * this.batchSize >= this.sortedGroups.length) break;
this.renderNextBatch();
}
// Start observing loader for additional batches
this.observer.observe(this.loader);
}
/**
* Render next batch of groups
*/
renderNextBatch() {
const start = this.currentBatch * this.batchSize;
const end = start + this.batchSize;
const groupsToRender = this.sortedGroups.slice(start, end);
if (groupsToRender.length === 0) {
// No more groups
this.loader.style.display = 'none';
return;
}
this.loader.style.opacity = '1';
let html = '';
let renderIndex = this.sortedGroups.slice(0, start).reduce((count, name) => count + this.renderedChannels.filter(c => c._renderGroup === name).length, 0); // Keep track of global index for mapping to renderedChannels
for (const groupName of groupsToRender) {
const channels = this.groupedChannels[groupName];
if (channels.length === 0) continue;
const isFavoritesGroup = groupName === this.favoriteGroupKey;
// Pre-filter visible channels for this group
const visibleChannels = channels.filter(channel => {
if (isFavoritesGroup) return true;
const rawChannelId = channel.streamId ?? channel.id;
const channelHidden = this.isHidden('channel', channel.sourceId, rawChannelId);
return !channelHidden || this.showHidden;
});
// Skip group if no visible channels (derived visibility)
if (visibleChannels.length === 0) continue;
// Default new groups to collapsed (except Favorites)
// This handles groups loaded via scroll that weren't in the initial collapse
if (!isFavoritesGroup && !this.collapsedGroups.has(groupName) && !this._userExpandedGroups?.has(groupName)) {
this.collapsedGroups.add(groupName);
}
html += `
`;
// Skip rendering channel items if group is collapsed (major performance optimization)
// Channels will be rendered when user expands the group
if (this.collapsedGroups.has(groupName)) {
renderIndex += visibleChannels.length;
html += '
';
continue;
}
for (const channel of visibleChannels) {
// Check hidden again for styling (showHidden mode)
const rawChannelId = channel.streamId ?? channel.id;
const channelHidden = !isFavoritesGroup && this.isHidden('channel', channel.sourceId, rawChannelId);
const isActive = this.currentChannel?.id === channel.id;
// Check if this specific instance is the "active" one for navigation purposes
const isRenderActive = this.currentRenderId && this.renderedChannels[renderIndex]?._renderId === this.currentRenderId;
const isFavorite = this.isFavorite(channel.sourceId, channel.id);
const renderId = this.renderedChannels[renderIndex]?._renderId || '';
const renderGroup = this.renderedChannels[renderIndex]?._renderGroup || groupName;
renderIndex++;
html += `