rss-reader/static/js/app.js

447 lines
15 KiB
JavaScript
Raw Normal View History

2025-02-02 11:36:15 -08:00
// Fetch and display feeds
async function fetchFeeds() {
try {
const response = await fetch('/feeds');
if (response.ok) {
const feeds = await response.json();
2025-02-02 14:09:11 -08:00
return feeds;
2025-02-02 11:36:15 -08:00
} else {
console.error('Failed to load feeds:', response.status);
2025-02-02 14:09:11 -08:00
return null;
2025-02-02 11:36:15 -08:00
}
} catch (error) {
console.error('Error loading feeds:', error);
2025-02-02 14:09:11 -08:00
return null;
}
}
// Close any open feed menus
function closeAllFeedMenus() {
document.querySelectorAll('.feed-menu.show').forEach(menu => {
menu.classList.remove('show');
});
}
// Add click handler to close menus when clicking outside
document.addEventListener('click', (e) => {
if (!e.target.closest('.feed-menu') && !e.target.closest('.feed-menu-button')) {
closeAllFeedMenus();
}
});
function formatDate(dateStr) {
if (!dateStr) return 'Not available';
const date = new Date(dateStr);
return date.toLocaleString();
}
function renderFeedEntries(entries) {
2025-02-05 04:19:47 -08:00
const mainContent = document.querySelector('#main-content');
mainContent.innerHTML = '';
entries.forEach(entry => {
2025-02-05 01:32:33 -08:00
const entryDiv = document.createElement('article');
entryDiv.className = 'feed-entry';
2025-02-05 01:32:33 -08:00
if (entry.marked_read) {
entryDiv.classList.add('read');
}
const title = document.createElement('h2');
title.className = 'feed-entry-title';
2025-02-05 01:01:10 -08:00
const readToggle = document.createElement('button');
readToggle.className = 'read-toggle';
readToggle.title = entry.marked_read ? 'Mark as unread' : 'Mark as read';
readToggle.innerHTML = entry.marked_read
2025-02-05 01:20:40 -08:00
? '<i class="fa-solid fa-square-check"></i>'
: '<i class="fa-regular fa-square"></i>';
2025-02-05 01:01:10 -08:00
readToggle.onclick = async () => {
try {
2025-02-05 02:31:29 -08:00
const response = await fetch(`/entries/${entry.local_id}/state`, {
2025-02-05 01:01:10 -08:00
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
read: !entry.marked_read
})
});
if (response.ok) {
entry.marked_read = !entry.marked_read;
readToggle.title = entry.marked_read ? 'Mark as unread' : 'Mark as read';
readToggle.innerHTML = entry.marked_read
2025-02-05 01:20:40 -08:00
? '<i class="fa-solid fa-square-check"></i>'
: '<i class="fa-regular fa-square"></i>';
2025-02-05 01:32:33 -08:00
entryDiv.classList.toggle('read', entry.marked_read);
2025-02-05 01:01:10 -08:00
} else {
console.error('Failed to update read state:', response.status);
}
} catch (error) {
console.error('Failed to update read state:', error);
}
};
title.appendChild(readToggle);
2025-02-05 01:20:40 -08:00
const titleLink = document.createElement('a');
titleLink.href = entry.link || '#';
titleLink.target = '_blank';
titleLink.textContent = entry.title;
2025-02-05 01:26:49 -08:00
titleLink.onclick = () => {
if (!entry.marked_read) {
// Mark as read in the background, don't wait for it
2025-02-05 02:31:29 -08:00
fetch(`/entries/${entry.local_id}/state`, {
2025-02-05 01:26:49 -08:00
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
read: true
})
}).then(response => {
if (response.ok) {
entry.marked_read = true;
readToggle.title = 'Mark as unread';
readToggle.innerHTML = '<i class="fa-solid fa-square-check"></i>';
2025-02-05 01:32:33 -08:00
entryDiv.classList.add('read');
2025-02-05 01:26:49 -08:00
} else {
console.error('Failed to update read state:', response.status);
}
}).catch(error => {
console.error('Failed to update read state:', error);
});
}
// Let the default link behavior happen immediately
};
2025-02-05 01:20:40 -08:00
title.appendChild(titleLink);
const meta = document.createElement('div');
meta.className = 'feed-entry-meta';
if (entry.published) {
const published = document.createElement('span');
published.textContent = `Published: ${formatDate(entry.published)}`;
meta.appendChild(published);
}
if (entry.updated) {
const updated = document.createElement('span');
updated.textContent = `Updated: ${formatDate(entry.updated)}`;
meta.appendChild(updated);
}
const summary = document.createElement('div');
summary.className = 'feed-entry-summary';
summary.textContent = entry.summary;
entryDiv.appendChild(title);
entryDiv.appendChild(meta);
entryDiv.appendChild(summary);
2025-02-05 04:19:47 -08:00
mainContent.appendChild(entryDiv);
});
}
2025-02-03 00:36:23 -08:00
function openFeed(feed) {
2025-02-02 14:09:11 -08:00
const name = document.createElement('span');
name.className = 'feed-name';
name.textContent = feed.name;
2025-02-03 00:36:23 -08:00
const spinner = document.createElement('div');
spinner.className = 'feed-spinner';
name.appendChild(spinner);
2025-02-05 05:29:40 -08:00
// Create unread count element
const unreadCount = document.createElement('span');
unreadCount.className = 'feed-unread-count';
if (feed.unread_count > 0) {
unreadCount.textContent = feed.unread_count;
unreadCount.style.display = 'inline';
}
name.appendChild(unreadCount);
2025-02-02 15:24:33 -08:00
name.onclick = async () => {
2025-02-03 00:36:23 -08:00
name.classList.add('loading');
2025-02-02 15:24:33 -08:00
try {
const response = await fetch(`/poll/${feed.feed_id}`, {
method: 'POST'
});
if (response.ok) {
const data = await response.json();
console.log('Feed poll response:', data);
renderFeedEntries(data.entries);
2025-02-05 05:29:40 -08:00
// Update the unread count
feed.unread_count = data.unread_count;
if (feed.unread_count > 0) {
unreadCount.textContent = feed.unread_count;
unreadCount.style.display = 'inline';
} else {
unreadCount.style.display = 'none';
}
2025-02-05 01:07:26 -08:00
// Update the top bar title
const topBarTitle = document.querySelector('.top-bar-title');
topBarTitle.innerHTML = `RSS Reader <span class="feed-title-separator">-</span> ${feed.name}`;
// Update the browser document title
document.title = `RSS Reader - ${feed.name}`;
2025-02-02 15:24:33 -08:00
} else {
console.error('Failed to poll feed:', response.status);
}
} catch (error) {
console.error('Error polling feed:', error);
2025-02-03 00:36:23 -08:00
} finally {
name.classList.remove('loading');
2025-02-02 15:24:33 -08:00
}
2025-02-02 14:09:11 -08:00
};
const menuButton = document.createElement('button');
menuButton.className = 'feed-menu-button';
2025-02-04 03:33:03 -08:00
menuButton.innerHTML = '<i class="fas fa-ellipsis-v"></i>';
2025-02-02 14:09:11 -08:00
menuButton.title = 'Feed options';
menuButton.onclick = (e) => {
e.stopPropagation();
closeAllFeedMenus();
menu.classList.toggle('show');
};
const menu = document.createElement('div');
menu.className = 'feed-menu';
2025-02-04 03:33:03 -08:00
const copyItem = document.createElement('a');
copyItem.className = 'feed-menu-item copy';
copyItem.innerHTML = '<span class="menu-icon"><i class="fas fa-copy"></i></span> Copy feed URL';
copyItem.onclick = async (e) => {
e.stopPropagation();
try {
await navigator.clipboard.writeText(feed.url);
// Briefly show success feedback
const originalText = copyItem.innerHTML;
copyItem.innerHTML = '<span class="menu-icon"><i class="fas fa-check"></i></span> Copied!';
setTimeout(() => {
copyItem.innerHTML = originalText;
}, 1500);
} catch (error) {
console.error('Failed to copy URL:', error);
}
menu.classList.remove('show');
};
2025-02-02 14:09:11 -08:00
const deleteItem = document.createElement('a');
deleteItem.className = 'feed-menu-item delete';
2025-02-04 03:33:03 -08:00
deleteItem.innerHTML = '<span class="menu-icon"><i class="fas fa-trash-alt"></i></span> Remove Feed';
2025-02-02 14:09:11 -08:00
deleteItem.onclick = async (e) => {
e.stopPropagation();
if (confirm(`Are you sure you want to delete "${feed.name}"?`)) {
try {
const response = await fetch(`/feeds/${feed.feed_id}`, {
method: 'DELETE',
});
if (response.ok) {
handleFeeds();
} else {
console.error('Failed to delete feed:', response.status);
}
} catch (error) {
console.error('Error deleting feed:', error);
}
}
menu.classList.remove('show');
};
2025-02-04 03:33:03 -08:00
menu.appendChild(copyItem);
2025-02-02 14:09:11 -08:00
menu.appendChild(deleteItem);
name.appendChild(menuButton);
name.appendChild(menu);
2025-02-02 14:13:02 -08:00
return name;
2025-02-02 14:09:11 -08:00
}
async function handleFeeds() {
const feeds = await fetchFeeds();
const feedList = document.getElementById('feedList');
if (feeds) {
2025-02-04 02:33:26 -08:00
console.log('Loaded feeds:', feeds);
2025-02-02 14:09:11 -08:00
feedList.innerHTML = '';
if (feeds.length === 0) {
const emptyMessage = document.createElement('div');
emptyMessage.className = 'feed-empty';
emptyMessage.textContent = 'No feeds added yet';
feedList.appendChild(emptyMessage);
} else {
2025-02-04 02:33:26 -08:00
// Group feeds by category
const feedsByCategory = {};
const uncategorizedFeeds = [];
2025-02-02 14:09:11 -08:00
feeds.forEach(feed => {
2025-02-04 02:33:26 -08:00
const category = feed.categorization.length > 0 ? feed.categorization[0] : null;
if (category) {
if (!feedsByCategory[category]) {
feedsByCategory[category] = [];
}
feedsByCategory[category].push(feed);
} else {
uncategorizedFeeds.push(feed);
}
});
// Sort categories alphabetically, but keep "Uncategorized" at the end
const sortedCategories = Object.keys(feedsByCategory).sort((a, b) => a.localeCompare(b));
sortedCategories.push("<No Category>");
feedsByCategory["<No Category>"] = uncategorizedFeeds;
// Create category sections
sortedCategories.forEach(category => {
const categorySection = document.createElement('div');
categorySection.className = 'feed-category';
const categoryHeader = document.createElement('h3');
categoryHeader.className = 'feed-category-header';
categoryHeader.textContent = category;
categorySection.appendChild(categoryHeader);
// Add feeds for this category
feedsByCategory[category].forEach(feed => {
categorySection.appendChild(openFeed(feed));
});
feedList.appendChild(categorySection);
2025-02-02 14:09:11 -08:00
});
}
} else {
feedList.innerHTML = '<div class="feed-error">Failed to load feeds</div>';
2025-02-02 11:36:15 -08:00
}
}
// Load feeds when page loads
2025-02-02 14:09:11 -08:00
document.addEventListener('DOMContentLoaded', handleFeeds);
2025-02-02 11:36:15 -08:00
2025-02-03 17:50:14 -08:00
// User menu functionality
const userMenuButton = document.getElementById('userMenuButton');
const userMenuDropdown = document.getElementById('userMenuDropdown');
// Toggle menu on button click
userMenuButton.addEventListener('click', (e) => {
e.stopPropagation();
userMenuDropdown.classList.toggle('show');
});
// Close menu when clicking outside
document.addEventListener('click', (e) => {
if (!e.target.closest('.user-menu')) {
userMenuDropdown.classList.remove('show');
}
});
// Prevent menu from closing when clicking inside it
userMenuDropdown.addEventListener('click', (e) => {
e.stopPropagation();
});
2025-02-02 01:23:21 -08:00
// Logout functionality
document.getElementById('logoutButton').addEventListener('click', async () => {
try {
const response = await fetch('/logout', {
method: 'POST',
});
if (response.ok) {
window.location.href = '/login';
}
} catch (error) {
console.error('Logout failed:', error);
}
});
// Modal functionality
const modal = document.getElementById('addFeedModal');
const addFeedButton = document.getElementById('addFeedButton');
const cancelButton = document.getElementById('cancelAddFeed');
const confirmButton = document.getElementById('confirmAddFeed');
const addFeedForm = document.getElementById('addFeedForm');
2025-02-02 02:11:13 -08:00
const errorMessage = document.getElementById('feedErrorMessage');
2025-02-02 03:25:51 -08:00
const loadingMessage = document.getElementById('loadingMessage');
2025-02-02 01:23:21 -08:00
function showModal() {
modal.classList.add('show');
2025-02-02 02:11:13 -08:00
errorMessage.style.display = 'none';
2025-02-02 03:25:51 -08:00
loadingMessage.style.display = 'none';
2025-02-02 02:11:13 -08:00
addFeedForm.reset();
2025-02-02 03:25:51 -08:00
confirmButton.disabled = false;
2025-02-02 01:23:21 -08:00
}
function hideModal() {
modal.classList.remove('show');
2025-02-02 02:11:13 -08:00
errorMessage.style.display = 'none';
2025-02-02 03:25:51 -08:00
loadingMessage.style.display = 'none';
2025-02-02 01:23:21 -08:00
addFeedForm.reset();
2025-02-02 03:25:51 -08:00
confirmButton.disabled = false;
2025-02-02 01:23:21 -08:00
}
2025-02-02 02:11:13 -08:00
function showError(message) {
errorMessage.textContent = message;
errorMessage.style.display = 'block';
2025-02-02 03:25:51 -08:00
loadingMessage.style.display = 'none';
confirmButton.disabled = false;
}
function showLoading() {
loadingMessage.style.display = 'block';
errorMessage.style.display = 'none';
confirmButton.disabled = true;
2025-02-02 02:11:13 -08:00
}
2025-02-02 01:23:21 -08:00
addFeedButton.addEventListener('click', showModal);
cancelButton.addEventListener('click', hideModal);
// Close modal when clicking outside
modal.addEventListener('click', (e) => {
if (e.target === modal) {
hideModal();
}
});
2025-02-05 04:40:01 -08:00
// Close modal when pressing escape
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && modal.classList.contains('show')) {
hideModal();
}
});
2025-02-02 01:23:21 -08:00
confirmButton.addEventListener('click', async () => {
2025-02-02 02:11:13 -08:00
const url = document.getElementById('feedUrl').value.trim();
2025-02-02 03:25:51 -08:00
if (!url) {
showError('Please enter a feed URL');
2025-02-02 01:23:21 -08:00
return;
}
2025-02-02 03:25:51 -08:00
showLoading();
2025-02-02 02:11:13 -08:00
try {
const response = await fetch('/feeds', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
2025-02-02 03:25:51 -08:00
body: JSON.stringify({ url }),
2025-02-02 02:11:13 -08:00
});
if (response.ok) {
hideModal();
2025-02-02 11:36:15 -08:00
// Refresh the feed list
2025-02-02 14:09:11 -08:00
handleFeeds();
2025-02-02 02:11:13 -08:00
} else {
switch (response.status) {
case 409:
showError('You already have this feed added');
break;
case 422:
2025-02-02 03:25:51 -08:00
showError('Invalid feed URL. Please make sure it\'s a valid RSS or Atom feed.');
2025-02-02 02:11:13 -08:00
break;
default:
showError('Failed to add feed. Please try again.');
}
}
} catch (error) {
console.error('Add feed failed:', error);
showError('An error occurred. Please try again.');
}
2025-02-02 14:13:02 -08:00
});