bewcloud/public/components/news/Feeds.js
Bruno Bernardino 917649b97a
Some checks are pending
Build Docker Image / build-and-push (push) Waiting to run
Deploy / deploy (push) Waiting to run
Run Tests / test (push) Waiting to run
Fix ring opacity in dropdowns
2026-02-25 15:14:18 +00:00

294 lines
No EOL
10 KiB
JavaScript

import { useSignal } from '@preact/signals';
import { escapeHtml, validateUrl } from '/public/ts/utils/misc.ts';
function formatNewsFeedsToOpml(feeds) {
return `<?xml version="1.0" encoding="UTF-8"?>
<opml version="2.0">
<head>
<title>Subscriptions</title>
</head>
<body>
${feeds.map(feed => `<outline title="${escapeHtml(feed.extra.title || '')}" text="${escapeHtml(feed.extra.title || '')}" type="${feed.extra.feed_type || 'rss'}" xmlUrl="${escapeHtml(feed.feed_url)}" htmlUrl="${escapeHtml(feed.feed_url)}"/>`).join('\n ')}
</body>
</opml>`;
}
function parseOpmlFromTextContents(html) {
const feedUrls = [];
const document = new DOMParser().parseFromString(html, 'text/html');
const feeds = Array.from(document.getElementsByTagName('outline'));
for (const feed of feeds) {
const url = (feed.getAttribute('xmlUrl') || feed.getAttribute('htmlUrl') || '').trim();
if (validateUrl(url)) {
feedUrls.push(url);
}
}
return feedUrls;
}
export default function Feeds({
initialFeeds
}) {
const isAdding = useSignal(false);
const isDeleting = useSignal(false);
const isExporting = useSignal(false);
const isImporting = useSignal(false);
const feeds = useSignal(initialFeeds);
const isOptionsDropdownOpen = useSignal(false);
const dateFormatOptions = {
dateStyle: 'medium',
timeStyle: 'short'
};
const dateFormat = new Intl.DateTimeFormat('en-GB', dateFormatOptions);
async function onClickAddFeed() {
if (isAdding.value) {
return;
}
const url = (prompt(`What's the **URL** for the new feed?`) || '').trim();
if (!url) {
alert('A URL is required for a new feed!');
return;
}
if (!validateUrl(url)) {
alert('Invalid URL!');
return;
}
isAdding.value = true;
try {
const requestBody = {
feedUrl: url
};
const response = await fetch(`/api/news/add-feed`, {
method: 'POST',
body: JSON.stringify(requestBody)
});
if (!response.ok) {
throw new Error(`Failed to add feed. ${response.statusText} ${await response.text()}`);
}
const result = await response.json();
if (!result.success) {
throw new Error('Failed to add feed!');
}
feeds.value = [...result.newFeeds];
} catch (error) {
console.error(error);
}
isAdding.value = false;
}
function toggleOptionsDropdown() {
isOptionsDropdownOpen.value = !isOptionsDropdownOpen.value;
}
async function onClickDeleteFeed(feedId) {
if (confirm('Are you sure you want to delete this feed and all its articles?')) {
if (isDeleting.value) {
return;
}
isDeleting.value = true;
try {
const requestBody = {
feedId
};
const response = await fetch(`/api/news/delete-feed`, {
method: 'POST',
body: JSON.stringify(requestBody)
});
if (!response.ok) {
throw new Error(`Failed to delete feed. ${response.statusText} ${await response.text()}`);
}
const result = await response.json();
if (!result.success) {
throw new Error('Failed to delete feed!');
}
feeds.value = [...result.newFeeds];
} catch (error) {
console.error(error);
}
isDeleting.value = false;
}
}
function onClickImportOpml() {
isOptionsDropdownOpen.value = false;
if (isImporting.value) {
return;
}
const fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.click();
fileInput.onchange = event => {
const files = event.target?.files;
const file = files[0];
if (!file) {
return;
}
const reader = new FileReader();
reader.onload = async fileRead => {
const importFileContents = fileRead.target?.result;
if (!importFileContents || isImporting.value) {
return;
}
isImporting.value = true;
try {
const feedUrls = parseOpmlFromTextContents(importFileContents.toString());
const requestBody = {
feedUrls
};
const response = await fetch(`/api/news/import-feeds`, {
method: 'POST',
body: JSON.stringify(requestBody)
});
if (!response.ok) {
throw new Error(`Failed to import feeds. ${response.statusText} ${await response.text()}`);
}
const result = await response.json();
if (!result.success) {
throw new Error('Failed to import feeds!');
}
feeds.value = [...result.newFeeds];
} catch (error) {
console.error(error);
}
isImporting.value = false;
};
reader.readAsText(file, 'UTF-8');
};
}
function onClickExportOpml() {
isOptionsDropdownOpen.value = false;
if (isExporting.value) {
return;
}
isExporting.value = true;
const fileName = `feeds-${new Date().toISOString().substring(0, 19).replace(/:/g, '-')}.opml`;
const exportContents = formatNewsFeedsToOpml([...feeds.peek()]);
const xmlContent = `data:application/xml; charset=utf-8,${exportContents}`;
const data = encodeURI(xmlContent);
const link = document.createElement('a');
link.setAttribute('href', data);
link.setAttribute('download', fileName);
link.click();
link.remove();
isExporting.value = false;
}
return h(Fragment, null, h("section", {
class: "flex flex-row items-center justify-between mb-4"
}, h("a", {
href: "/news",
class: "mr-2"
}, "View articles"), h("section", {
class: "flex items-center"
}, h("section", {
class: "relative inline-block text-left ml-2"
}, h("div", null, h("button", {
type: "button",
class: "inline-flex w-full justify-center gap-x-1.5 rounded-md bg-slate-700 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-slate-600",
id: "filter-button",
"aria-expanded": "true",
"aria-haspopup": "true",
onClick: () => toggleOptionsDropdown()
}, "OPML", h("svg", {
class: "-mr-1 h-5 w-5 text-slate-400",
viewBox: "0 0 20 20",
fill: "currentColor",
"aria-hidden": "true"
}, h("path", {
"fill-rule": "evenodd",
d: "M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z",
"clip-rule": "evenodd"
})))), h("div", {
class: `absolute right-0 z-10 mt-2 w-44 origin-top-right rounded-md bg-slate-700 shadow-lg ring-1 ring-black/15 focus:outline-none ${!isOptionsDropdownOpen.value ? 'hidden' : ''}`,
role: "menu",
"aria-orientation": "vertical",
"aria-labelledby": "filter-button",
tabindex: -1
}, h("div", {
class: "py-1"
}, h("button", {
class: `text-white block px-4 py-2 text-sm w-full text-left hover:bg-slate-600`,
onClick: () => onClickImportOpml(),
type: "button"
}, "Import OPML"), h("button", {
class: `text-white block px-4 py-2 text-sm w-full text-left hover:bg-slate-600`,
onClick: () => onClickExportOpml(),
type: "button"
}, "Export OPML")))), h("button", {
class: "inline-block justify-center gap-x-1.5 rounded-md bg-[#51A4FB] px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-sky-400 ml-2",
type: "button",
title: "Add new feed",
onClick: () => onClickAddFeed()
}, h("img", {
src: "/public/images/add.svg",
alt: "Add new feed",
class: `white ${isAdding.value ? 'animate-spin' : ''}`,
width: 20,
height: 20
})))), h("section", {
class: "mx-auto max-w-7xl my-8"
}, h("table", {
class: "w-full border-collapse bg-gray-900 text-left text-sm text-slate-500 shadow-sm rounded-md"
}, h("thead", null, h("tr", null, h("th", {
scope: "col",
class: "px-6 py-4 font-medium text-white"
}, "Title & URL"), h("th", {
scope: "col",
class: "px-6 py-4 font-medium text-white"
}, "Last Crawl"), h("th", {
scope: "col",
class: "px-6 py-4 font-medium text-white"
}, "Type"), h("th", {
scope: "col",
class: "px-6 py-4 font-medium text-white w-20"
}))), h("tbody", {
class: "divide-y divide-slate-600 border-t border-slate-600"
}, feeds.value.map(newsFeed => h("tr", {
class: "bg-slate-700 hover:bg-slate-600 group"
}, h("td", {
class: "flex gap-3 px-6 py-4 font-normal text-white"
}, h("div", {
class: "text-sm"
}, h("div", {
class: "font-medium text-white"
}, newsFeed.extra.title || 'N/A'), h("div", {
class: "text-slate-400"
}, newsFeed.feed_url))), h("td", {
class: "px-6 py-4 text-slate-200"
}, newsFeed.last_crawled_at ? dateFormat.format(new Date(newsFeed.last_crawled_at)) : 'N/A'), h("td", {
class: "px-6 py-4"
}, h("div", {
class: "text-xs font-semibold text-slate-200"
}, newsFeed.extra.feed_type?.split('').map(character => character.toUpperCase()).join('') || 'N/A')), h("td", {
class: "px-6 py-4"
}, h("span", {
class: "invisible cursor-pointer group-hover:visible opacity-50 hover:opacity-100",
onClick: () => onClickDeleteFeed(newsFeed.id)
}, h("img", {
src: "/public/images/delete.svg",
class: "red drop-shadow-md",
width: 24,
height: 24,
alt: "Delete feed",
title: "Delete feed"
}))))), feeds.value.length === 0 ? h("tr", {
class: "hover:bg-slate-600"
}, h("td", {
class: "flex gap-3 px-6 py-4 font-normal",
colspan: 4
}, h("div", {
class: "text-md"
}, h("div", {
class: "font-medium text-slate-400"
}, "No feeds to show")))) : null)), h("span", {
class: `flex justify-end items-center text-sm mt-1 mx-2 text-slate-100`
}, isDeleting.value ? h(Fragment, null, h("img", {
src: "/public/images/loading.svg",
class: "white mr-2",
width: 18,
height: 18
}), "Deleting...") : null, isExporting.value ? h(Fragment, null, h("img", {
src: "/public/images/loading.svg",
class: "white mr-2",
width: 18,
height: 18
}), "Exporting...") : null, isImporting.value ? h(Fragment, null, h("img", {
src: "/public/images/loading.svg",
class: "white mr-2",
width: 18,
height: 18
}), "Importing...") : null, !isDeleting.value && !isExporting.value && !isImporting.value ? h(Fragment, null, "\xA0") : null)));
}