import { ref, unref, nextTick } from 'vue'; import axios from 'axios'; import { Readability } from '@mozilla/readability'; // Module-level state — declared outside useFeeds() so every caller shares the // same singleton refs (a Pinia-free "store" for the feed list and its UI state). const showMessage = ref(false) const feeds = ref([]); const message = ref('') const showModal = ref(false) const viewMode = ref('list') // 'list' | 'article' — toggled from the hamburger menu const currentIndex = ref(0) const layout = ref(localStorage.getItem('layout') || 'list') // 'list' | 'cards' — list-view display style, toggled from the hamburger menu let observer; // Declare observer outside the setup function let initialLoad = false function authHeaders() { return { headers: { 'Content-Type': 'application/json', 'user-token': localStorage.getItem("user-token") } } } // Some feeds (e.g. Deutsche Welle) ship tags whose `src` and various // lazy-load attributes (`data-url`, `data-src`, `srcset`, ...) contain an // unresolved `${placeholderName}` template — or its URL-encoded `%7B...%7D` // form — that their own frontend fills in from the sibling `data-format` // attribute before loading; verbatim they 404. Resolve every such attribute // the same way (so Readability's own lazy-image handling can't resurrect a // stale template into `src`), preferring `data-url` as the source of truth // for `src`, and drop the entirely if a template still remains. const TEMPLATE_PATTERN = /\$\{[^}]+\}|%7[bB][^%]*%7[dD]/ const TEMPLATE_PATTERN_GLOBAL = /\$\{[^}]+\}|%7[bB][^%]*%7[dD]/g function resolveTemplatedImage(img) { const format = img.getAttribute('data-format') const dataUrl = img.getAttribute('data-url') if (format) { if (dataUrl && TEMPLATE_PATTERN.test(dataUrl)) { img.setAttribute('src', dataUrl.replace(TEMPLATE_PATTERN_GLOBAL, format)) } for (const attr of [...img.attributes]) { if (attr.name !== 'src' && TEMPLATE_PATTERN.test(attr.value)) { img.setAttribute(attr.name, attr.value.replace(TEMPLATE_PATTERN_GLOBAL, format)) } } } if (TEMPLATE_PATTERN.test(img.getAttribute('src') ?? '')) { img.remove() } } function showMessageForXSeconds(text, seconds) { message.value = text; showMessage.value = true; // Set a timeout to hide the message after x seconds setTimeout(() => { showMessage.value = false; message.value = ''; }, seconds * 1000); // Convert seconds to milliseconds } async function getReadable(feed, index) { try { const response = await axios.post("/api/v1/article/read", { url: feed.url }, authHeaders()) const doc = new DOMParser().parseFromString(response.data.content, 'text/html'); // Scraped articles often contain image/link URLs that are relative to the // source site. A tag makes the browser (and Readability) resolve // them against the article's original URL instead of our own origin. const base = doc.createElement('base'); base.setAttribute('href', feed.url); doc.head.prepend(base); doc.querySelectorAll('img').forEach(resolveTemplatedImage); doc.querySelectorAll('video, audio').forEach(el => el.remove()); const article = new Readability(doc).parse(); feeds.value[index].content = article.content; feeds.value[index].readable = true; } catch (error) { console.error('Error fetching data:', error) showMessageForXSeconds(error, 5) } } async function markRead(id) { try { const response = await axios.put("/api/v1/article/read/" + id, null, authHeaders()) console.log(response.status) } catch (error) { console.log(error) } } const fetchData = async () => { const user_id = localStorage.getItem("user-id") try { const response = await axios.get("/api/v1/article/get/" + user_id, authHeaders()); const items = []; response.data.feeds.forEach(feed => { feed.items.forEach(item => items.push({ ...item, feedTitle: feed.title })); }); // timestamps are zero-padded "YYYY-MM-DD HH:MM:SS" strings, so a plain // lexicographic comparison sorts them chronologically. items.sort((a, b) => b.timestamp.localeCompare(a.timestamp)); feeds.value = items; await nextTick(); setupIntersectionObserver(); } catch (error) { console.error('Error fetching data:', error) showMessageForXSeconds(error, 5) } }; async function sync() { try { const response = await axios.post('/api/v1/article/sync', { user_id: parseInt(localStorage.getItem("user-id")) }, authHeaders()) if (response.status == 200) { showMessageForXSeconds('Sync successful.', 5) } fetchData(); } catch (error) { console.error('Error sync', error) showMessageForXSeconds(error, 5) } } function setupIntersectionObserver() { if (observer) { observer.disconnect(); } observer = new IntersectionObserver(handleIntersection, { root: null, // Use the viewport as the root rootMargin: '0px', // threshold: 0.5, // Fire the callback when at least 50% of the element is visible }); const observedDivs = document.querySelectorAll(".observe"); if (observedDivs.length > 0) { observedDivs.forEach(observedDiv => { observer.observe(observedDiv); }) } } async function handleIntersection(entries) { // The callback function for when the target element enters or exits the viewport for (const entry of entries) { // An article that has scrolled above the viewport (not intersecting, // bounding box above the top edge) has been read — mark it and remove it. if (initialLoad === true && !entry.isIntersecting && entry.boundingClientRect.y < 0) { await markRead(feeds.value[entry.target.id].id) removeFeed(entry.target.id) document.getElementById(0)?.scrollIntoView() } } } function removeFeed(index) { const array = unref(feeds); array.splice(index, 1); } function setInitialLoad(value) { initialLoad = value } async function markAllRead() { if (feeds.value.length === 0) return if (!window.confirm('Mark all articles as read?')) return const ids = feeds.value.map(feed => feed.id) feeds.value = [] currentIndex.value = 0 // markRead swallows its own errors, so Promise.all can't reject here. await Promise.all(ids.map(id => markRead(id))) showMessageForXSeconds('All articles marked as read.', 5) } function markCurrentArticleRead() { const feed = feeds.value[currentIndex.value] // Marking read here (rather than via removeFeed, as the scroll-based list // view does) keeps the array stable so currentIndex stays valid while paging. // The local `read` flag lets leaveArticleView() drop these once we're done. if (feed) { feed.read = true markRead(feed.id) } } async function leaveArticleView() { // Articles paged past in article view were marked read but deliberately kept // in place so currentIndex stayed valid — drop them now so they don't keep // showing up in the list view. feeds.value = feeds.value.filter(feed => !feed.read) currentIndex.value = 0 viewMode.value = 'list' // The v-if on the list container tears down and recreates all .observe DOM // nodes when switching views, so the intersection observer must be // re-pointed at the new elements after Vue has finished rendering. await nextTick() setupIntersectionObserver() } function toggleViewMode() { if (viewMode.value === 'article') { leaveArticleView() } else { viewMode.value = 'article' currentIndex.value = 0 markCurrentArticleRead() } } function toggleLayout() { layout.value = layout.value === 'list' ? 'cards' : 'list' localStorage.setItem('layout', layout.value) } function nextArticle() { if (currentIndex.value < feeds.value.length - 1) { currentIndex.value += 1 markCurrentArticleRead() } } function prevArticle() { if (currentIndex.value > 0) { currentIndex.value -= 1 markCurrentArticleRead() } } export function useFeeds() { return { feeds, showMessage, message, showModal, viewMode, currentIndex, toggleViewMode, leaveArticleView, layout, toggleLayout, nextArticle, prevArticle, fetchData, sync, getReadable, markRead, markAllRead, showMessageForXSeconds, setupIntersectionObserver, removeFeed, setInitialLoad, } }