// Функция для включения темного режима
function initializeTheme() {
const themeCheckbox = document.getElementById('theme-checkbox');
const savedTheme = localStorage.getItem('theme') || 'light';
// Функция для включения режима редактирования
function enableEditing(content, feedItem) {
editorWrapper.classList.remove('hidden');
overlay.classList.remove('hidden');
currentEditingItem = feedItem;
// Сохранение изменений в новости
saveButton.addEventListener('click', () => {
if (currentEditingItem) {
const updatedContent = DOMPurify.sanitize(quill.root.innerHTML);
const descriptionElement = currentEditingItem.querySelector('.news-content p');
code
if (descriptionElement) {
descriptionElement.innerHTML = updatedContent;
updateFeedData(currentEditingItem, updatedContent);
showNotification('success', 'Изменения сохранены успешно!');
} else {
console.warn('Элемент для обновления не найден');
showNotification('error', 'Не удалось сохранить изменения.');
}
closeEditor();
} else {
console.warn('Нет текущего редактируемого элемента');
showNotification('error', 'Произошла ошибка при сохранении изменений.');
}
});
// Функция для обновления данных в хранилище
function updateFeedData(feedItem, updatedContent) {
const title = feedItem.querySelector('h2 a').textContent;
const source = feedItem.querySelector('.source').textContent.replace('Источник: ', '');
const category = feedItem.getAttribute('data-category');
code
for (let feed of feeds) {
if (feed.url.includes(source)) {
const newsItem = feed.news.find(news => news.title === title);
if (newsItem) {
newsItem.description = updatedContent;
break;
}
}
}
saveToLocalStorage();
}
// Функция для загрузки RSS ленты
async function fetchRSS(url) {
try {
showNotification('loading', Загрузка RSS-ленты: ${url});
const proxyUrl = 'https://api.allorigins.win/get?url='; // Прокси для обхода CORS
const response = await fetch(proxyUrl + encodeURIComponent(url));
if (!response.ok) {
throw new Error(Ошибка загрузки RSS: ${response.statusText});
}
code
const data = await response.json();
const rssText = data.contents;
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(rssText, "application/xml");
const parseError = xmlDoc.querySelector("parsererror");
if (parseError) {
throw new Error("Ошибка парсинга XML.");
}
const items = xmlDoc.querySelectorAll("item");
const parsedItems = Array.from(items).map(item => {
// Попытка извлечения изображения из различных источников
let image = '';
const mediaContent = item.querySelector('media\\:content, content');
if (mediaContent && mediaContent.getAttribute('url')) {
image = mediaContent.getAttribute('url');
} else {
// Попытка извлечения изображения из описания через регулярное выражение
const desc = item.querySelector("description")?.textContent || "";
const imgMatch = desc.match(/<img[^>]+src="([^">]+)"/);
if (imgMatch && imgMatch[1]) {
image = imgMatch[1];
}
}
return {
title: item.querySelector("title")?.textContent || "Без названия",
link: item.querySelector("link")?.textContent || "Без ссылки",
description: item.querySelector("description")?.textContent || "Без описания",
pubDate: item.querySelector("pubDate")?.textContent || "Без даты",
image: image
};
});
showNotification('success', `RSS-лента загружена успешно: ${url}`);
return parsedItems;
} catch (error) {
console.error(error);
showNotification('error', error.message);
return [];
}
}
// Функция для отображения RSS фидов с пагинацией
function displayFeed(data) {
const feedContainer = document.getElementById("feed");
feedContainer.innerHTML = ''; // Очистить предыдущие новости
// Функция для сохранения всех новостей в HTML-документ
function saveAllNewsAsDocument() {
const feedContainer = document.getElementById("feed");
const feedItems = feedContainer.querySelectorAll('.feed-item');
// Функция для получения данных изображения в формате Base64
async function getImageDataURL(url) {
const response = await fetch(url);
const blob = await response.blob();
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result.split(',')[1]);
reader.onerror = reject;
reader.readAsDataURL(blob);
});
}
// Функция для экспорта новостей в CSV
function exportToCSV() {
const feedContainer = document.getElementById("feed");
const feedItems = feedContainer.querySelectorAll('.feed-item');
// Функция для добавления RSS-ленты в список с категорией
function addFeedToList(feedUrl, category = 'Без категории') {
const feedsUl = document.getElementById('feeds-ul');
const li = document.createElement('li');
li.textContent = ${feedUrl} [${category}];
// Функция для сохранения всех новостей в CSV-документ
function exportToCSV() {
const feedContainer = document.getElementById("feed");
const feedItems = feedContainer.querySelectorAll('.feed-item');
// Добавление обработчика кнопки "Экспортировать новости в CSV"
exportCsvBtn.addEventListener('click', exportToCSV);
// Функция для сохранения всех новостей в HTML-документ
function saveAllNewsAsDocument() {
const feedContainer = document.getElementById("feed");
const feedItems = feedContainer.querySelectorAll('.feed-item');
// Функция для экспортирования RSS-лент в JSON
function exportFeeds() {
if (feeds.length === 0) {
showNotification('error', 'Нет RSS-лент для экспорта.');
return;
}
// Функция для обновления фильтра по категориям
function updateCategoryFilter() {
const categoryFilter = document.getElementById('category-filter');
categoryFilter.innerHTML = <option value="all">Все категории</option>;
// Функция для добавления RSS-ленты в список с категорией
function addFeedToList(feedUrl, category = 'Без категории') {
const feedsUl = document.getElementById('feeds-ul');
const li = document.createElement('li');
li.textContent = ${feedUrl} [${category}];
// Функция для сохранения всех новостей в HTML-документ
function saveAllNewsAsDocument() {
const feedContainer = document.getElementById("feed");
const feedItems = feedContainer.querySelectorAll('.feed-item');
// Функция для экспортирования RSS-лент в JSON
function exportFeeds() {
if (feeds.length === 0) {
showNotification('error', 'Нет RSS-лент для экспорта.');
return;
}
// Функция для агрегирования новостей из всех RSS-лент
function getAggregatedNews() {
let allNews = [];
feeds.forEach(feed => {
if (Array.isArray(feed.news)) {
allNews = allNews.concat(feed.news.map(newsItem => ({
...newsItem,
source: new URL(feed.url).hostname,
category: feed.category || 'Без категории'
})));
}
});
// Функция для сохранения всех новостей в HTML-документ
function saveAllNewsAsDocument() {
const feedContainer = document.getElementById("feed");
const feedItems = feedContainer.querySelectorAll('.feed-item');
// Функция для экспортирования RSS-лент в JSON
function exportFeeds() {
if (feeds.length === 0) {
showNotification('error', 'Нет RSS-лент для экспорта.');
return;
}
// Функция для экспортирования новостей в CSV
function exportToCSV() {
const feedContainer = document.getElementById("feed");
const feedItems = feedContainer.querySelectorAll('.feed-item');
// Добавление обработчика кнопки "Экспортировать новости в CSV"
exportCsvBtn.addEventListener('click', exportToCSV);
// Функция для сохранения всех новостей в HTML-документ
function saveAllNewsAsDocument() {
const feedContainer = document.getElementById("feed");
const feedItems = feedContainer.querySelectorAll('.feed-item');
// Функция для экспорта новостей в PDF
// Уже реализована выше через exportToPDF
// Функция для сохранения всех новостей в HTML-документ
// Уже реализована выше через saveAllNewsAsDocument
// Функция для сохранения данных в localStorage
function saveToLocalStorage() {
localStorage.setItem('rssFeeds', JSON.stringify(feeds));
}
// Функция для загрузки данных из localStorage
function loadFromLocalStorage() {
const storedFeeds = localStorage.getItem('rssFeeds');
if (storedFeeds) {
feeds = JSON.parse(storedFeeds);
feeds.forEach(feed => {
addFeedToList(feed.url, feed.category || 'Без категории');
});
displayFeed(getAggregatedNews());
updateFeedFilter();
}
}
// Функция для добавления RSS-ленты в список с категорией
function addFeedToList(feedUrl, category = 'Без категории') {
const feedsUl = document.getElementById('feeds-ul');
const li = document.createElement('li');
li.textContent = ${feedUrl} [${category}];
// Функция для агрегирования новостей из всех RSS-лент
function getAggregatedNews() {
let allNews = [];
feeds.forEach(feed => {
if (Array.isArray(feed.news)) {
allNews = allNews.concat(feed.news.map(newsItem => ({
...newsItem,
source: new URL(feed.url).hostname,
category: feed.category || 'Без категории'
})));
}
});
code
// Сортировка по дате публикации (новые сначала)
allNews.sort((a, b) => new Date(b.pubDate) - new Date(a.pubDate));
return allNews;
}
// Функция для отображения RSS фидов с пагинацией
function displayFeed(data) {
const feedContainer = document.getElementById("feed");
feedContainer.innerHTML = ''; // Очистить предыдущие новости
// Функция для сохранения всех новостей в HTML-документ
function saveAllNewsAsDocument() {
const feedContainer = document.getElementById("feed");
const feedItems = feedContainer.querySelectorAll('.feed-item');
// Функция для экспорта новостей в PDF
// Реализована выше
// Функция для экспортирования RSS-лент в JSON
function exportFeeds() {
if (feeds.length === 0) {
showNotification('error', 'Нет RSS-лент для экспорта.');
return;
}
// Функция для экспортирования новостей в CSV
function exportToCSV() {
const feedContainer = document.getElementById("feed");
const feedItems = feedContainer.querySelectorAll('.feed-item');
// Функция для агрегирования новостей из всех RSS-лент
function getAggregatedNews() {
let allNews = [];
feeds.forEach(feed => {
if (Array.isArray(feed.news)) {
allNews = allNews.concat(feed.news.map(newsItem => ({
...newsItem,
source: new URL(feed.url).hostname,
category: feed.category || 'Без категории'
})));
}
});
code
// Сортировка по дате публикации (новые сначала)
allNews.sort((a, b) => new Date(b.pubDate) - new Date(a.pubDate));
return allNews;
}
// Функция для отображения RSS фидов с пагинацией
function displayFeed(data) {
const feedContainer = document.getElementById("feed");
feedContainer.innerHTML = ''; // Очистить предыдущие новости
// Функция для сохранения всех новостей в HTML-документ
function saveAllNewsAsDocument() {
const feedContainer = document.getElementById("feed");
const feedItems = feedContainer.querySelectorAll('.feed-item');
// Функция для экспорта новостей в PDF
// Реализована выше
// Функция для экспортирования RSS-лент в JSON
exportFeedsBtn.addEventListener('click', exportFeeds);
// Функция для экспортирования новостей в CSV
function exportToCSV() {
const feedContainer = document.getElementById("feed");
const feedItems = feedContainer.querySelectorAll('.feed-item');
// Функция для экспорта RSS-лент в JSON
function exportFeeds() {
if (feeds.length === 0) {
showNotification('error', 'Нет RSS-лент для экспорта.');
return;
}
// Функция для агрегирования новостей из всех RSS-лент
function getAggregatedNews() {
let allNews = [];
feeds.forEach(feed => {
if (Array.isArray(feed.news)) {
allNews = allNews.concat(feed.news.map(newsItem => ({
...newsItem,
source: new URL(feed.url).hostname,
category: feed.category || 'Без категории'
})));
}
});
// Функция для сохранения всех новостей в CSV-документ
// Реализована выше
// Функция для сохранения данных в localStorage
function saveToLocalStorage() {
localStorage.setItem('rssFeeds', JSON.stringify(feeds));
}
// Функция для загрузки данных из localStorage
function loadFromLocalStorage() {
const storedFeeds = localStorage.getItem('rssFeeds');
if (storedFeeds) {
feeds = JSON.parse(storedFeeds);
feeds.forEach(feed => {
addFeedToList(feed.url, feed.category || 'Без категории');
});
displayFeed(getAggregatedNews());
updateFeedFilter();
}
}
// Функция для автоматического обновления RSS-лент
function autoRefreshFeeds() {
const REFRESH_INTERVAL = 10 * 60 * 1000; // 10 минут
code
setInterval(async () => {
if (feeds.length === 0) return;
showNotification('loading', 'Автоматическое обновление RSS-лент...');
for (let i = 0; i < feeds.length; i++) {
const feed = feeds[i];
const newNews = await fetchRSS(feed.url);
// Проверка на новые новости
const existingTitles = feed.news.map(news => news.title);
const uniqueNews = newNews.filter(news => !existingTitles.includes(news.title));
if (uniqueNews.length > 0) {
feeds[i].news = feeds[i].news.concat(uniqueNews);
showNotification('success', `Найдено ${uniqueNews.length} новых новостей в RSS-ленте: ${feed.url}`);
}
}
saveToLocalStorage();
displayFeed(getAggregatedNews());
}, REFRESH_INTERVAL);
}
// Функция для инициализации приложения
window.addEventListener('load', () => {
loadFromLocalStorage();
displayFeed(getAggregatedNews());
updateFeedFilter();
initializeTheme();
autoRefreshFeeds();
});
Your script.js file implements a comprehensive RSS reader application with various features such as:
RSS Feed Management: Adding, removing, importing, and exporting RSS feeds.
News Display: Fetching, sanitizing, and displaying news items with pagination.
Editing: Allowing users to edit news content using the Quill editor within a modal.
Theme Support: Enabling light and dark modes with persistent preferences.
Exporting News: Providing options to export news in HTML, PDF, and CSV formats.
Local Storage: Persisting feed data using localStorage.
Auto-Refresh: Periodically updating feeds to fetch new news items.
However, upon reviewing the script, there are several duplicate function definitions and redundant code blocks that need attention. Here's a detailed analysis and recommendations to improve your script:
1. Duplicate Function Definitions
Issue:
Several functions are defined multiple times in the script. For example:
exportToPDF
saveAllNewsAsDocument
exportToCSV
exportFeeds
addFeedToList
displayFeed
updatePagination
getAggregatedNews
importForm event listeners
Impact:
Overriding Functions: Later definitions override earlier ones, leading to unexpected behaviors.
Increased File Size: Redundant code increases the file size unnecessarily.
Maintenance Challenges: Multiple definitions make the code harder to read and maintain.
Recommendation:
Remove Duplicates: Ensure each function is defined only once.
Consolidate Logic: If you intended to have variations, consider parameterizing the functions or creating distinct function names.
Use Modularization: Split functionalities into separate modules or files if the script becomes too large.
2. Functionality Overlaps and Redundancies
Issue:
Some functionalities appear multiple times with slight variations, leading to confusion and potential bugs.
Impact:
Inconsistent Behavior: Different versions of the same function might not operate identically.
Debugging Difficulties: Tracing issues becomes more complex with overlapping code.
Recommendation:
Centralize Functionality: Keep a single, well-documented version of each function.
Review Logic Flow: Ensure that all parts of the script reference the correct function versions.
3. Asynchronous Operations and Error Handling
Issue:
While functions like fetchRSS use async/await for asynchronous operations, some other sections might benefit from enhanced error handling.
Impact:
Uncaught Errors: Potential errors might go unnoticed without proper handling.
Poor User Experience: Users might not receive adequate feedback on failures.
Recommendation:
Consistent Error Handling: Use try-catch blocks where necessary to handle errors gracefully.
User Notifications: Ensure that all error scenarios provide meaningful feedback to the user.
4. Code Organization and Readability
Issue:
The script is lengthy and contains repetitive patterns, making it harder to navigate and understand.
Impact:
Reduced Maintainability: Harder to update or extend the codebase.
Onboarding Challenges: New developers might find it difficult to comprehend the code structure.
Recommendation:
Modularize Code: Break down the script into smaller, focused modules or functions.
Use Consistent Naming Conventions: Ensure function and variable names are descriptive and consistent.
Add Documentation: Include comments and documentation for complex sections to aid understanding.
5. Potential Bugs and Improvements
Issue:
Multiple Event Listeners: Adding multiple event listeners to the same elements can lead to unexpected behaviors.
Local Storage Updates: Ensure that feeds data is correctly updated and synchronized across all functions.
Recommendation:
Single Source of Truth: Maintain a centralized state for feeds and ensure all functions interact with this state consistently.
Event Listener Management: Attach event listeners once and manage their callbacks effectively.
6. Sample Refactored Function
Here's an example of how you can refactor the exportToCSV function to eliminate duplication and improve clarity:
javascript
// Function to export news to CSV
function exportToCSV() {
const feedContainer = document.getElementById("feed");
const feedItems = feedContainer.querySelectorAll('.feed-item');
if (feedItems.length === 0) {
showNotification('error', 'Нет новостей для экспорта.');
return;
}
let csvContent = "data:text/csv;charset=utf-8,";
csvContent += "Заголовок,Ссылка,Описание,Дата публикации,Источник,Изображение\n";
feedItems.forEach(item => {
const title = item.querySelector('h2 a').textContent.replace(/,/g, ' ');
const link = item.querySelector('h2 a').href;
const description = item.querySelector('p').innerText.replace(/,/g, ' ').replace(/"/g, '""');
const pubDate = item.querySelector('.pubDate').textContent;
const source = item.querySelector('.source') ? item.querySelector('.source').textContent.replace('Источник: ', '') : '';
const image = item.querySelector('img') ? item.querySelector('img').src : '';
csvContent += `"${title}","${link}","${description}","${pubDate}","${source}","${image}"\n`;
});
const encodedUri = encodeURI(csvContent);
const a = document.createElement('a');
a.href = encodedUri;
a.download = 'news.csv';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
showNotification('success', 'Новости успешно экспортированы в CSV!');
}
// Attach the event listener once
exportCsvBtn.addEventListener('click', exportToCSV);
Benefits:
Eliminates Duplication: Ensures the function is defined once.
Enhances Readability: Clean and concise implementation.
Reliable Event Handling: Attaches the event listener a single time.
7. Additional Recommendations
Use Modern JavaScript Features:
ES6 Modules: Consider using modules to organize your code better.
Arrow Functions: Utilize arrow functions for cleaner syntax where appropriate.
Optimize Performance:
Debounce Search Input: Implement debouncing for the search input to reduce unnecessary function calls.
Enhance User Experience:
Loading Indicators: Ensure all asynchronous operations have corresponding loading indicators.
Responsive Design: Verify the application is responsive across different devices and screen sizes.
Security Considerations:
Sanitize Inputs: While you're already using DOMPurify, ensure all user inputs and external data are properly sanitized to prevent XSS attacks.
Testing:
Unit Tests: Implement unit tests for critical functions to ensure reliability.
Manual Testing: Regularly test all functionalities to identify and fix issues promptly.
8. Final Thoughts
Your script demonstrates a robust attempt at building a feature-rich RSS reader application. By addressing the duplication and organizing the code more effectively, you'll enhance maintainability, performance, and user experience. If you encounter specific issues or need further assistance with particular functionalities, feel free to ask!