From 8ac775d7ce97e31a9531572f6f116dfc8de25d35 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Feb 2026 17:00:13 +0000 Subject: fix: replace IntersectionObserver with scroll-position check for infinite scroll MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The IntersectionObserver approach for infinite scroll was unreliable — items would not load when scrolling to the bottom in v3, while v1's polling approach worked fine. The issue was that IntersectionObserver with a custom root element (main-content, whose height comes from flex align-items:stretch rather than an explicit height) didn't fire reliably, and renderItems() being called 3 times per fetch cycle (from both items-updated and loading-state-changed events) kept destroying and recreating the observer. Replace with a simple scroll-position check in the existing onscroll handler, matching v1's proven approach: when the user scrolls within 200px of the bottom of #main-content, trigger loadMore(). This runs on every scroll event (cheap arithmetic comparison) and only fires when content actually overflows the container. Remove the unused itemObserver module-level variable. Update regression tests to simulate scroll position instead of IntersectionObserver callbacks, with 4 cases: scroll near bottom triggers load, scroll far from bottom doesn't, loading=true blocks, and hasMore=false hides sentinel. https://claude.ai/code/session_01DpWhB9uGGMBnzqS28HxnuV --- frontend-vanilla/src/main.ts | 50 ++++------- frontend-vanilla/src/regression.test.ts | 83 ++++++++++-------- web/dist/v3/assets/index-PqZwi-gF.js | 148 -------------------------------- web/dist/v3/assets/index-j89IB65U.js | 148 ++++++++++++++++++++++++++++++++ web/dist/v3/index.html | 2 +- 5 files changed, 215 insertions(+), 216 deletions(-) delete mode 100644 web/dist/v3/assets/index-PqZwi-gF.js create mode 100644 web/dist/v3/assets/index-j89IB65U.js diff --git a/frontend-vanilla/src/main.ts b/frontend-vanilla/src/main.ts index bdd0e97..8d88470 100644 --- a/frontend-vanilla/src/main.ts +++ b/frontend-vanilla/src/main.ts @@ -18,7 +18,6 @@ let activeItemId: number | null = null; // Cache elements (initialized in renderLayout) let appEl: HTMLDivElement | null = null; -let itemObserver: IntersectionObserver | null = null; // Initial Layout (v2-style 2-pane) export function renderLayout() { @@ -243,10 +242,6 @@ export function renderFilters() { export function renderItems() { const { items, loading } = store; - if (itemObserver) { - itemObserver.disconnect(); - itemObserver = null; - } const contentArea = document.getElementById('content-area'); if (!contentArea || router.getCurrentRoute().path === '/settings') return; @@ -267,27 +262,26 @@ export function renderItems() { ${store.hasMore ? '
Loading more...
' : ''} `; - // Use the actual scroll container as IntersectionObserver root + // Scroll listener on the scrollable container (#main-content) handles both: + // 1. Infinite scroll — load more when near the bottom (like v1's proven approach) + // 2. Mark-as-read — mark items read when scrolled past + // Using onscroll assignment (not addEventListener) so each renderItems() call + // replaces the previous handler without accumulating listeners. const scrollRoot = document.getElementById('main-content'); - - // Setup infinite scroll — stored in itemObserver so it has a GC root and won't be collected - const sentinel = document.getElementById('load-more-sentinel'); - if (sentinel) { - itemObserver = new IntersectionObserver((entries) => { - if (entries[0].isIntersecting && !store.loading && store.hasMore) { - loadMore(); + if (scrollRoot) { + let readTimeoutId: number | null = null; + scrollRoot.onscroll = () => { + // Infinite scroll: check immediately on every scroll event (cheap comparison). + // Guard: only when content actually overflows the container (scrollHeight > clientHeight). + if (!store.loading && store.hasMore && scrollRoot.scrollHeight > scrollRoot.clientHeight) { + if (scrollRoot.scrollHeight - scrollRoot.scrollTop - scrollRoot.clientHeight < 200) { + loadMore(); + } } - }, { root: scrollRoot, threshold: 0.1 }); - itemObserver.observe(sentinel); - } - // Scroll listener for reading items - // We attach this to the scrollable container: #main-content - if (scrollRoot) { - let timeoutId: number | null = null; - const onScroll = () => { - if (timeoutId === null) { - timeoutId = window.setTimeout(() => { + // Mark-as-read: debounced to avoid excessive DOM queries + if (readTimeoutId === null) { + readTimeoutId = window.setTimeout(() => { const containerRect = scrollRoot.getBoundingClientRect(); store.items.forEach((item) => { @@ -302,18 +296,10 @@ export function renderItems() { } } }); - timeoutId = null; + readTimeoutId = null; }, 250); } }; - // Remove existing listener if any (simplistic approach, ideally we track and remove) - // Since renderItems is called multiple times, we might be adding multiple listeners? - // attachLayoutListeners is called once, but renderItems is called on updates. - // We should probably attaching the scroll listener in the layout setup, NOT here. - // But we need access to 'items' which is in store. - // Let's attach it here but be careful. - // Actually, attaching to 'onscroll' property handles replacement automatically. - scrollRoot.onscroll = onScroll; } } diff --git a/frontend-vanilla/src/regression.test.ts b/frontend-vanilla/src/regression.test.ts index 97c601c..813e4bb 100644 --- a/frontend-vanilla/src/regression.test.ts +++ b/frontend-vanilla/src/regression.test.ts @@ -258,30 +258,16 @@ describe('NK-z1czaq: Sidebar overlays content, does not shift layout', () => { }); }); -// Infinite scroll: sentinel IntersectionObserver must be kept alive via a module-level -// variable so it isn't garbage-collected between renderItems() calls. -describe('Infinite scroll: sentinel triggers loadMore when scrolled into view', () => { - let capturedCallback: IntersectionObserverCallback | null = null; - +// Infinite scroll: uses scroll-position check (like v1) instead of IntersectionObserver. +// When the user scrolls within 200px of the bottom of #main-content, loadMore fires. +describe('Infinite scroll: scroll near bottom triggers loadMore', () => { beforeEach(() => { document.body.innerHTML = '
'; Element.prototype.scrollIntoView = vi.fn(); - capturedCallback = null; vi.clearAllMocks(); store.setItems([]); store.setHasMore(true); - // Override IntersectionObserver to capture the callback passed by renderItems. - // Must use a class (not an arrow function) because the code calls it with `new`. - vi.stubGlobal('IntersectionObserver', class { - constructor(cb: IntersectionObserverCallback) { - capturedCallback = cb; - } - observe = vi.fn(); - disconnect = vi.fn(); - unobserve = vi.fn(); - }); - vi.mocked(apiFetch).mockResolvedValue({ ok: true, status: 200, @@ -289,7 +275,24 @@ describe('Infinite scroll: sentinel triggers loadMore when scrolled into view', } as Response); }); - it('should call loadMore (apiFetch /api/stream) when sentinel fires isIntersecting=true', () => { + function simulateScrollNearBottom(mainContent: HTMLElement) { + // Simulate: scrollHeight=2000, clientHeight=800, scrollTop=1050 + // remaining = 2000 - 1050 - 800 = 150 < 200 → should trigger loadMore + Object.defineProperty(mainContent, 'scrollHeight', { value: 2000, configurable: true }); + Object.defineProperty(mainContent, 'clientHeight', { value: 800, configurable: true }); + mainContent.scrollTop = 1050; + mainContent.dispatchEvent(new Event('scroll')); + } + + function simulateScrollFarFromBottom(mainContent: HTMLElement) { + // remaining = 2000 - 200 - 800 = 1000 > 200 → should NOT trigger + Object.defineProperty(mainContent, 'scrollHeight', { value: 2000, configurable: true }); + Object.defineProperty(mainContent, 'clientHeight', { value: 800, configurable: true }); + mainContent.scrollTop = 200; + mainContent.dispatchEvent(new Event('scroll')); + } + + it('should call loadMore (apiFetch /api/stream) when scrolled near the bottom', () => { const items = Array.from({ length: 50 }, (_, i) => ({ _id: i + 1, title: `Item ${i + 1}`, @@ -297,21 +300,19 @@ describe('Infinite scroll: sentinel triggers loadMore when scrolled into view', read: false, publish_date: '2024-01-01', })); - // setItems emits items-updated → renderItems() sets up itemObserver store.setItems(items as any); + vi.clearAllMocks(); - expect(document.getElementById('load-more-sentinel')).not.toBeNull(); - expect(capturedCallback).not.toBeNull(); - - // Simulate the sentinel scrolling into the scroll container's viewport - capturedCallback!([{ isIntersecting: true }] as any, null as any); + const mainContent = document.getElementById('main-content')!; + // renderItems sets onscroll on main-content; fire the scroll event + simulateScrollNearBottom(mainContent); expect(apiFetch).toHaveBeenCalledWith( expect.stringContaining('/api/stream'), ); }); - it('should NOT call loadMore when store.loading is true', () => { + it('should NOT call loadMore when scrolled far from the bottom', () => { const items = Array.from({ length: 50 }, (_, i) => ({ _id: i + 1, title: `Item ${i + 1}`, @@ -319,13 +320,31 @@ describe('Infinite scroll: sentinel triggers loadMore when scrolled into view', read: false, publish_date: '2024-01-01', })); - store.setItems(items as any); // renderItems() called, capturedCallback set - vi.clearAllMocks(); // reset apiFetch call count + store.setItems(items as any); + vi.clearAllMocks(); + + const mainContent = document.getElementById('main-content')!; + simulateScrollFarFromBottom(mainContent); + + expect(apiFetch).not.toHaveBeenCalledWith( + expect.stringContaining('/api/stream'), + ); + }); - // Directly mutate loading without emitting (avoids another renderItems cycle) + it('should NOT call loadMore when store.loading is true', () => { + const items = Array.from({ length: 50 }, (_, i) => ({ + _id: i + 1, + title: `Item ${i + 1}`, + url: `http://example.com/${i + 1}`, + read: false, + publish_date: '2024-01-01', + })); + store.setItems(items as any); + vi.clearAllMocks(); store.loading = true; - capturedCallback!([{ isIntersecting: true }] as any, null as any); + const mainContent = document.getElementById('main-content')!; + simulateScrollNearBottom(mainContent); expect(apiFetch).not.toHaveBeenCalledWith( expect.stringContaining('/api/stream'), @@ -344,11 +363,5 @@ describe('Infinite scroll: sentinel triggers loadMore when scrolled into view', store.setItems(items as any); expect(document.getElementById('load-more-sentinel')).toBeNull(); - // No IntersectionObserver was set up for a sentinel that doesn't exist - // (capturedCallback may have been set for a previous render, not this one) - // Just verify nothing was loaded - expect(apiFetch).not.toHaveBeenCalledWith( - expect.stringContaining('/api/stream'), - ); }); }); diff --git a/web/dist/v3/assets/index-PqZwi-gF.js b/web/dist/v3/assets/index-PqZwi-gF.js deleted file mode 100644 index 36a0c7a..0000000 --- a/web/dist/v3/assets/index-PqZwi-gF.js +++ /dev/null @@ -1,148 +0,0 @@ -(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))s(n);new MutationObserver(n=>{for(const o of n)if(o.type==="childList")for(const d of o.addedNodes)d.tagName==="LINK"&&d.rel==="modulepreload"&&s(d)}).observe(document,{childList:!0,subtree:!0});function a(n){const o={};return n.integrity&&(o.integrity=n.integrity),n.referrerPolicy&&(o.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?o.credentials="include":n.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(n){if(n.ep)return;n.ep=!0;const o=a(n);fetch(n.href,o)}})();function R(t){const a=`; ${document.cookie}`.split(`; ${t}=`);if(a.length===2)return a.pop()?.split(";").shift()}async function m(t,e){const a=e?.method?.toUpperCase()||"GET",s=["POST","PUT","DELETE"].includes(a),n=new Headers(e?.headers||{});if(s){const o=R("csrf_token");o&&n.set("X-CSRF-Token",o)}return fetch(t,{...e,headers:n,credentials:"include"})}function C(){const t=document.cookie.split("; ").find(e=>e.startsWith("neko_sidebar="));return t?t.split("=")[1]==="1":null}function B(t){document.cookie=`neko_sidebar=${t?"1":"0"}; path=/; max-age=31536000; SameSite=Lax`}function P(){const t=C();return t!==null?t:window.innerWidth>1024}class x extends EventTarget{feeds=[];tags=[];items=[];activeFeedId=null;activeTagName=null;filter="unread";searchQuery="";loading=!1;hasMore=!0;theme=localStorage.getItem("neko-theme")||"light";fontTheme=localStorage.getItem("neko-font-theme")||"default";sidebarVisible=P();setFeeds(e){this.feeds=e,this.emit("feeds-updated")}setTags(e){this.tags=e,this.emit("tags-updated")}setItems(e,a=!1){a?this.items=[...this.items,...e]:this.items=e,this.emit("items-updated")}setActiveFeed(e){this.activeFeedId=e,this.activeTagName=null,this.emit("active-feed-updated")}setActiveTag(e){this.activeTagName=e,this.activeFeedId=null,this.emit("active-tag-updated")}setFilter(e){this.filter!==e&&(this.filter=e,this.emit("filter-updated"))}setSearchQuery(e){this.searchQuery!==e&&(this.searchQuery=e,this.emit("search-updated"))}setLoading(e){this.loading=e,this.emit("loading-state-changed")}setHasMore(e){this.hasMore=e}setTheme(e){this.theme=e,localStorage.setItem("neko-theme",e),this.emit("theme-updated")}setFontTheme(e){this.fontTheme=e,localStorage.setItem("neko-font-theme",e),this.emit("theme-updated")}setSidebarVisible(e){this.sidebarVisible=e,B(e),this.emit("sidebar-toggle")}toggleSidebar(){this.setSidebarVisible(!this.sidebarVisible)}emit(e,a){this.dispatchEvent(new CustomEvent(e,{detail:a}))}on(e,a){this.addEventListener(e,a)}}const i=new x;class M extends EventTarget{constructor(){super(),window.addEventListener("popstate",()=>this.handleRouteChange())}handleRouteChange(){this.dispatchEvent(new CustomEvent("route-changed",{detail:this.getCurrentRoute()}))}getCurrentRoute(){const e=new URL(window.location.href),s=e.pathname.replace(/^\/v3\//,"").split("/").filter(Boolean);let n="/";const o={};return s[0]==="feed"&&s[1]?(n="/feed",o.feedId=s[1]):s[0]==="tag"&&s[1]?(n="/tag",o.tagName=decodeURIComponent(s[1])):s[0]==="settings"&&(n="/settings"),{path:n,params:o,query:e.searchParams}}navigate(e,a){let s=`/v3${e}`;if(a){const n=new URLSearchParams(a);s+=`?${n.toString()}`}window.history.pushState({},"",s),this.handleRouteChange()}updateQuery(e){const a=new URL(window.location.href);for(const[s,n]of Object.entries(e))n?a.searchParams.set(s,n):a.searchParams.delete(s);window.history.pushState({},"",a.toString()),this.handleRouteChange()}}const r=new M;function O(t,e=!1){const a=new Date(t.publish_date).toLocaleDateString();return` -
  • - - - ${t.full_content||t.description?` -
    - ${t.full_content||t.description} -
    - `:""} -
  • - `}let f=null,p=null,y=null;function q(){p=document.querySelector("#app"),p&&(p.className=`theme-${i.theme} font-${i.fontTheme}`,p.innerHTML=` -
    - - - -
    -
    -
    -
    - `,N())}function N(){document.getElementById("search-input")?.addEventListener("input",n=>{const o=n.target.value;r.updateQuery({q:o})}),document.getElementById("logo-link")?.addEventListener("click",()=>r.navigate("/")),document.getElementById("logout-button")?.addEventListener("click",n=>{n.preventDefault(),J()}),document.getElementById("sidebar-toggle-btn")?.addEventListener("click",()=>{i.toggleSidebar()}),document.getElementById("sidebar-backdrop")?.addEventListener("click",()=>{i.setSidebarVisible(!1)}),document.querySelectorAll(".sidebar-section.collapsible h3").forEach(n=>{n.addEventListener("click",()=>{n.parentElement?.classList.toggle("collapsed")})}),document.getElementById("sidebar")?.addEventListener("click",n=>{const o=n.target,d=o.closest("a");if(!d){o.classList.contains("logo")&&(n.preventDefault(),r.navigate("/",{}));return}const g=d.getAttribute("data-nav"),u=Object.fromEntries(r.getCurrentRoute().query.entries());if(g==="filter"){n.preventDefault();const l=d.getAttribute("data-value");r.getCurrentRoute().path==="/settings"?r.navigate("/",{...u,filter:l}):r.updateQuery({filter:l})}else if(g==="tag"){n.preventDefault();const l=d.getAttribute("data-value");r.navigate(`/tag/${encodeURIComponent(l)}`,u)}else if(g==="feed"){n.preventDefault();const l=d.getAttribute("data-value"),c=r.getCurrentRoute();i.activeFeedId===parseInt(l)&&c.path!=="/settings"?r.navigate("/",u):r.navigate(`/feed/${l}`,u)}else g==="settings"&&(n.preventDefault(),r.getCurrentRoute().path==="/settings"?r.navigate("/",u):r.navigate("/settings",u));window.innerWidth<=768&&i.setSidebarVisible(!1)}),document.getElementById("content-area")?.addEventListener("click",n=>{const o=n.target,d=o.closest('[data-action="toggle-star"]');if(d){const c=d.closest("[data-id]");if(c){const v=parseInt(c.getAttribute("data-id"));V(v)}return}const g=o.closest('[data-action="scrape"]');if(g){const c=g.closest("[data-id]");if(c){const v=parseInt(c.getAttribute("data-id"));H(v)}return}const u=o.closest('[data-action="open"]'),l=o.closest(".feed-item");if(l&&!u){const c=parseInt(l.getAttribute("data-id"));f=c,document.querySelectorAll(".feed-item").forEach(w=>{const A=parseInt(w.getAttribute("data-id")||"0");w.classList.toggle("selected",A===f)});const v=i.items.find(w=>w._id===c);v&&!v.read&&h(c,{read:!0})}})}function k(){const{feeds:t,activeFeedId:e}=i,a=document.getElementById("feed-list");a&&(a.innerHTML=t.map(s=>` -
  • - - ${s.title||s.url} - -
  • - `).join(""))}function $(){const{tags:t,activeTagName:e}=i,a=document.getElementById("tag-list");a&&(a.innerHTML=t.map(s=>` -
  • - - ${s.title} - -
  • - `).join(""))}function _(){const{filter:t}=i,e=document.getElementById("filter-list");e&&e.querySelectorAll("li").forEach(a=>{a.classList.toggle("active",a.getAttribute("data-filter")===t)})}function E(){const{items:t,loading:e}=i;y&&(y.disconnect(),y=null);const a=document.getElementById("content-area");if(!a||r.getCurrentRoute().path==="/settings")return;if(e&&t.length===0){a.innerHTML='

    Loading items...

    ';return}if(t.length===0){a.innerHTML='

    No items found.

    ';return}a.innerHTML=` - - ${i.hasMore?'
    Loading more...
    ':""} - `;const s=document.getElementById("main-content"),n=document.getElementById("load-more-sentinel");if(n&&(y=new IntersectionObserver(o=>{o[0].isIntersecting&&!i.loading&&i.hasMore&&W()},{root:s,threshold:.1}),y.observe(n)),s){let o=null;const d=()=>{o===null&&(o=window.setTimeout(()=>{const g=s.getBoundingClientRect();i.items.forEach(u=>{if(u.read)return;const l=document.querySelector(`.feed-item[data-id="${u._id}"]`);l&&l.getBoundingClientRect().bottom -

    Settings

    - -
    -

    Add Feed

    -
    - - -
    -
    - -
    -

    Appearance

    -
    - -
    - - -
    -
    -
    - - -
    -
    - -
    -

    Manage Feeds

    -
      - ${i.feeds.map(e=>` -
    • -
      -
      ${e.title||e.url}
      -
      ${e.url}
      -
      -
      - - - -
      -
    • - `).join("")} -
    -
    - -
    -

    Data Management

    -
    - -
    - - -
    -
    -
    - - `,document.getElementById("theme-options")?.addEventListener("click",e=>{const a=e.target.closest("button");if(a){const s=a.getAttribute("data-theme");i.setTheme(s),I()}}),document.getElementById("font-selector")?.addEventListener("change",e=>{i.setFontTheme(e.target.value)}),document.getElementById("add-feed-btn")?.addEventListener("click",async()=>{const e=document.getElementById("new-feed-url"),a=e.value.trim();a&&(await D(a)?(e.value="",alert("Feed added successfully!"),b()):alert("Failed to add feed."))}),document.getElementById("export-opml-btn")?.addEventListener("click",()=>{window.location.href="/api/export/opml"}),document.getElementById("import-opml-file")?.addEventListener("change",async e=>{const a=e.target.files?.[0];a&&(await Q(a)?(alert("OPML imported successfully! Crawling started."),b()):alert("Failed to import OPML."))}),document.querySelectorAll(".delete-feed-btn").forEach(e=>{e.addEventListener("click",async a=>{const s=parseInt(a.target.getAttribute("data-id"));confirm("Are you sure you want to delete this feed?")&&(await j(s),b(),await b(),I())})}),document.querySelectorAll(".update-feed-tag-btn").forEach(e=>{e.addEventListener("click",async a=>{const s=parseInt(a.target.getAttribute("data-id")),o=document.querySelector(`.feed-tag-input[data-id="${s}"]`).value.trim();await U(s,{category:o}),await b(),await F(),I(),alert("Feed updated")})}))}async function D(t){try{return(await m("/api/feed",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:t})})).ok}catch(e){return console.error("Failed to add feed",e),!1}}async function Q(t){try{const e=new FormData;e.append("file",t),e.append("format","opml");const a=document.cookie.split("; ").find(n=>n.startsWith("csrf_token="))?.split("=")[1];return(await fetch("/api/import",{method:"POST",headers:{"X-CSRF-Token":a||""},body:e})).ok}catch(e){return console.error("Failed to import OPML",e),!1}}async function j(t){try{return(await m(`/api/feed/${t}`,{method:"DELETE"})).ok}catch(e){return console.error("Failed to delete feed",e),!1}}async function U(t,e){try{return(await m("/api/feed",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,_id:t})})).ok}catch(a){return console.error("Failed to update feed",a),!1}}async function V(t){const e=i.items.find(a=>a._id===t);e&&h(t,{starred:!e.starred})}async function H(t){if(i.items.find(a=>a._id===t))try{const a=await m(`/api/item/${t}/content`);if(a.ok){const s=await a.json();s.full_content&&h(t,{full_content:s.full_content})}}catch(a){console.error("Failed to fetch full content",a)}}async function h(t,e){try{if((await m(`/api/item/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).ok){const s=i.items.find(n=>n._id===t);if(s){Object.assign(s,e);const n=document.querySelector(`.feed-item[data-id="${t}"]`);if(n){if(e.read!==void 0&&n.classList.toggle("read",e.read),e.starred!==void 0){const o=n.querySelector(".star-btn");o&&(o.classList.toggle("is-starred",e.starred),o.classList.toggle("is-unstarred",!e.starred),o.setAttribute("title",e.starred?"Unstar":"Star"))}e.full_content&&E()}}}}catch(a){console.error("Failed to update item",a)}}async function b(){const t=await m("/api/feed/");if(t.ok){const e=await t.json();i.setFeeds(e)}}async function F(){const t=await m("/api/tag");if(t.ok){const e=await t.json();i.setTags(e)}}async function L(t,e,a=!1){i.setLoading(!0);try{const s=new URLSearchParams;t&&s.append("feed_id",t),e&&s.append("tag",e),i.searchQuery&&s.append("q",i.searchQuery),(i.filter==="starred"||i.filter==="all")&&s.append("read_filter","all"),i.filter==="starred"&&s.append("starred","true"),a&&i.items.length>0&&s.append("max_id",String(i.items[i.items.length-1]._id));const n=await m(`/api/stream?${s.toString()}`);if(n.ok){const o=await n.json();i.setHasMore(o.length>=50),i.setItems(o,a)}}finally{i.setLoading(!1)}}async function W(){const t=r.getCurrentRoute();L(t.params.feedId,t.params.tagName,!0)}async function J(){await m("/api/logout",{method:"POST"}),window.location.href="/login/"}function S(){const t=r.getCurrentRoute(),e=t.query.get("filter");i.setFilter(e||"unread");const a=t.query.get("q");if(a!==null&&i.setSearchQuery(a),t.path==="/settings"){I();return}if(t.path==="/feed"&&t.params.feedId){const s=parseInt(t.params.feedId);i.setActiveFeed(s),L(t.params.feedId),document.getElementById("section-feeds")?.classList.remove("collapsed")}else t.path==="/tag"&&t.params.tagName?(i.setActiveTag(t.params.tagName),L(void 0,t.params.tagName),document.getElementById("section-tags")?.classList.remove("collapsed")):(i.setActiveFeed(null),i.setActiveTag(null),L())}window.addEventListener("keydown",t=>{if(!["INPUT","TEXTAREA"].includes(t.target.tagName))switch(t.key){case"j":T(1);break;case"k":T(-1);break;case"r":if(f){const e=i.items.find(a=>a._id===f);e&&h(e._id,{read:!e.read})}break;case"s":if(f){const e=i.items.find(a=>a._id===f);e&&h(e._id,{starred:!e.starred})}break;case"/":t.preventDefault(),document.getElementById("search-input")?.focus();break}});function T(t){if(i.items.length===0)return;const e=i.items.findIndex(s=>s._id===f);let a;if(e===-1?a=t>0?0:i.items.length-1:a=e+t,a>=0&&a{const o=parseInt(n.getAttribute("data-id")||"0");n.classList.toggle("selected",o===f)});const s=document.querySelector(`.feed-item[data-id="${f}"]`);s&&s.scrollIntoView({block:"start",behavior:"smooth"}),i.items[a].read||h(f,{read:!0})}}i.on("feeds-updated",k);i.on("tags-updated",$);i.on("active-feed-updated",k);i.on("active-tag-updated",$);i.on("filter-updated",_);i.on("search-updated",()=>{const t=document.getElementById("search-input");t&&t.value!==i.searchQuery&&(t.value=i.searchQuery),S()});i.on("theme-updated",()=>{p||(p=document.querySelector("#app")),p&&(p.className=`theme-${i.theme} font-${i.fontTheme}`)});i.on("sidebar-toggle",()=>{const t=document.querySelector(".layout");t&&(i.sidebarVisible?(t.classList.remove("sidebar-hidden"),t.classList.add("sidebar-visible")):(t.classList.remove("sidebar-visible"),t.classList.add("sidebar-hidden")))});i.on("items-updated",E);i.on("loading-state-changed",E);r.addEventListener("route-changed",S);window.app={navigate:t=>r.navigate(t)};async function X(){const t=await m("/api/auth");if(!t||t.status===401){window.location.href="/login/";return}q(),_();try{await Promise.all([b(),F()])}catch(e){console.error("Initial fetch failed",e)}S()}typeof window<"u"&&!window.__VITEST__&&X(); diff --git a/web/dist/v3/assets/index-j89IB65U.js b/web/dist/v3/assets/index-j89IB65U.js new file mode 100644 index 0000000..bd2ff28 --- /dev/null +++ b/web/dist/v3/assets/index-j89IB65U.js @@ -0,0 +1,148 @@ +(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))s(n);new MutationObserver(n=>{for(const o of n)if(o.type==="childList")for(const d of o.addedNodes)d.tagName==="LINK"&&d.rel==="modulepreload"&&s(d)}).observe(document,{childList:!0,subtree:!0});function a(n){const o={};return n.integrity&&(o.integrity=n.integrity),n.referrerPolicy&&(o.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?o.credentials="include":n.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(n){if(n.ep)return;n.ep=!0;const o=a(n);fetch(n.href,o)}})();function A(t){const a=`; ${document.cookie}`.split(`; ${t}=`);if(a.length===2)return a.pop()?.split(";").shift()}async function m(t,e){const a=e?.method?.toUpperCase()||"GET",s=["POST","PUT","DELETE"].includes(a),n=new Headers(e?.headers||{});if(s){const o=A("csrf_token");o&&n.set("X-CSRF-Token",o)}return fetch(t,{...e,headers:n,credentials:"include"})}function R(){const t=document.cookie.split("; ").find(e=>e.startsWith("neko_sidebar="));return t?t.split("=")[1]==="1":null}function C(t){document.cookie=`neko_sidebar=${t?"1":"0"}; path=/; max-age=31536000; SameSite=Lax`}function B(){const t=R();return t!==null?t:window.innerWidth>1024}class P extends EventTarget{feeds=[];tags=[];items=[];activeFeedId=null;activeTagName=null;filter="unread";searchQuery="";loading=!1;hasMore=!0;theme=localStorage.getItem("neko-theme")||"light";fontTheme=localStorage.getItem("neko-font-theme")||"default";sidebarVisible=B();setFeeds(e){this.feeds=e,this.emit("feeds-updated")}setTags(e){this.tags=e,this.emit("tags-updated")}setItems(e,a=!1){a?this.items=[...this.items,...e]:this.items=e,this.emit("items-updated")}setActiveFeed(e){this.activeFeedId=e,this.activeTagName=null,this.emit("active-feed-updated")}setActiveTag(e){this.activeTagName=e,this.activeFeedId=null,this.emit("active-tag-updated")}setFilter(e){this.filter!==e&&(this.filter=e,this.emit("filter-updated"))}setSearchQuery(e){this.searchQuery!==e&&(this.searchQuery=e,this.emit("search-updated"))}setLoading(e){this.loading=e,this.emit("loading-state-changed")}setHasMore(e){this.hasMore=e}setTheme(e){this.theme=e,localStorage.setItem("neko-theme",e),this.emit("theme-updated")}setFontTheme(e){this.fontTheme=e,localStorage.setItem("neko-font-theme",e),this.emit("theme-updated")}setSidebarVisible(e){this.sidebarVisible=e,C(e),this.emit("sidebar-toggle")}toggleSidebar(){this.setSidebarVisible(!this.sidebarVisible)}emit(e,a){this.dispatchEvent(new CustomEvent(e,{detail:a}))}on(e,a){this.addEventListener(e,a)}}const i=new P;class x extends EventTarget{constructor(){super(),window.addEventListener("popstate",()=>this.handleRouteChange())}handleRouteChange(){this.dispatchEvent(new CustomEvent("route-changed",{detail:this.getCurrentRoute()}))}getCurrentRoute(){const e=new URL(window.location.href),s=e.pathname.replace(/^\/v3\//,"").split("/").filter(Boolean);let n="/";const o={};return s[0]==="feed"&&s[1]?(n="/feed",o.feedId=s[1]):s[0]==="tag"&&s[1]?(n="/tag",o.tagName=decodeURIComponent(s[1])):s[0]==="settings"&&(n="/settings"),{path:n,params:o,query:e.searchParams}}navigate(e,a){let s=`/v3${e}`;if(a){const n=new URLSearchParams(a);s+=`?${n.toString()}`}window.history.pushState({},"",s),this.handleRouteChange()}updateQuery(e){const a=new URL(window.location.href);for(const[s,n]of Object.entries(e))n?a.searchParams.set(s,n):a.searchParams.delete(s);window.history.pushState({},"",a.toString()),this.handleRouteChange()}}const r=new x;function M(t,e=!1){const a=new Date(t.publish_date).toLocaleDateString();return` +
  • + + + ${t.full_content||t.description?` +
    + ${t.full_content||t.description} +
    + `:""} +
  • + `}let c=null,p=null;function q(){p=document.querySelector("#app"),p&&(p.className=`theme-${i.theme} font-${i.fontTheme}`,p.innerHTML=` +
    + + + +
    +
    +
    +
    + `,O())}function O(){document.getElementById("search-input")?.addEventListener("input",n=>{const o=n.target.value;r.updateQuery({q:o})}),document.getElementById("logo-link")?.addEventListener("click",()=>r.navigate("/")),document.getElementById("logout-button")?.addEventListener("click",n=>{n.preventDefault(),W()}),document.getElementById("sidebar-toggle-btn")?.addEventListener("click",()=>{i.toggleSidebar()}),document.getElementById("sidebar-backdrop")?.addEventListener("click",()=>{i.setSidebarVisible(!1)}),document.querySelectorAll(".sidebar-section.collapsible h3").forEach(n=>{n.addEventListener("click",()=>{n.parentElement?.classList.toggle("collapsed")})}),document.getElementById("sidebar")?.addEventListener("click",n=>{const o=n.target,d=o.closest("a");if(!d){o.classList.contains("logo")&&(n.preventDefault(),r.navigate("/",{}));return}const f=d.getAttribute("data-nav"),g=Object.fromEntries(r.getCurrentRoute().query.entries());if(f==="filter"){n.preventDefault();const u=d.getAttribute("data-value");r.getCurrentRoute().path==="/settings"?r.navigate("/",{...g,filter:u}):r.updateQuery({filter:u})}else if(f==="tag"){n.preventDefault();const u=d.getAttribute("data-value");r.navigate(`/tag/${encodeURIComponent(u)}`,g)}else if(f==="feed"){n.preventDefault();const u=d.getAttribute("data-value"),l=r.getCurrentRoute();i.activeFeedId===parseInt(u)&&l.path!=="/settings"?r.navigate("/",g):r.navigate(`/feed/${u}`,g)}else f==="settings"&&(n.preventDefault(),r.getCurrentRoute().path==="/settings"?r.navigate("/",g):r.navigate("/settings",g));window.innerWidth<=768&&i.setSidebarVisible(!1)}),document.getElementById("content-area")?.addEventListener("click",n=>{const o=n.target,d=o.closest('[data-action="toggle-star"]');if(d){const l=d.closest("[data-id]");if(l){const v=parseInt(l.getAttribute("data-id"));H(v)}return}const f=o.closest('[data-action="scrape"]');if(f){const l=f.closest("[data-id]");if(l){const v=parseInt(l.getAttribute("data-id"));U(v)}return}const g=o.closest('[data-action="open"]'),u=o.closest(".feed-item");if(u&&!g){const l=parseInt(u.getAttribute("data-id"));c=l,document.querySelectorAll(".feed-item").forEach(y=>{const F=parseInt(y.getAttribute("data-id")||"0");y.classList.toggle("selected",F===c)});const v=i.items.find(y=>y._id===l);v&&!v.read&&h(l,{read:!0})}})}function T(){const{feeds:t,activeFeedId:e}=i,a=document.getElementById("feed-list");a&&(a.innerHTML=t.map(s=>` +
  • + + ${s.title||s.url} + +
  • + `).join(""))}function k(){const{tags:t,activeTagName:e}=i,a=document.getElementById("tag-list");a&&(a.innerHTML=t.map(s=>` +
  • + + ${s.title} + +
  • + `).join(""))}function $(){const{filter:t}=i,e=document.getElementById("filter-list");e&&e.querySelectorAll("li").forEach(a=>{a.classList.toggle("active",a.getAttribute("data-filter")===t)})}function I(){const{items:t,loading:e}=i,a=document.getElementById("content-area");if(!a||r.getCurrentRoute().path==="/settings")return;if(e&&t.length===0){a.innerHTML='

    Loading items...

    ';return}if(t.length===0){a.innerHTML='

    No items found.

    ';return}a.innerHTML=` +
      + ${t.map(n=>M(n,n._id===c)).join("")} +
    + ${i.hasMore?'
    Loading more...
    ':""} + `;const s=document.getElementById("main-content");if(s){let n=null;s.onscroll=()=>{!i.loading&&i.hasMore&&s.scrollHeight>s.clientHeight&&s.scrollHeight-s.scrollTop-s.clientHeight<200&&V(),n===null&&(n=window.setTimeout(()=>{const o=s.getBoundingClientRect();i.items.forEach(d=>{if(d.read)return;const f=document.querySelector(`.feed-item[data-id="${d._id}"]`);f&&f.getBoundingClientRect().bottom +

    Settings

    + +
    +

    Add Feed

    +
    + + +
    +
    + +
    +

    Appearance

    +
    + +
    + + +
    +
    +
    + + +
    +
    + +
    +

    Manage Feeds

    +
      + ${i.feeds.map(e=>` +
    • +
      +
      ${e.title||e.url}
      +
      ${e.url}
      +
      +
      + + + +
      +
    • + `).join("")} +
    +
    + +
    +

    Data Management

    +
    + +
    + + +
    +
    +
    + + `,document.getElementById("theme-options")?.addEventListener("click",e=>{const a=e.target.closest("button");if(a){const s=a.getAttribute("data-theme");i.setTheme(s),w()}}),document.getElementById("font-selector")?.addEventListener("change",e=>{i.setFontTheme(e.target.value)}),document.getElementById("add-feed-btn")?.addEventListener("click",async()=>{const e=document.getElementById("new-feed-url"),a=e.value.trim();a&&(await N(a)?(e.value="",alert("Feed added successfully!"),b()):alert("Failed to add feed."))}),document.getElementById("export-opml-btn")?.addEventListener("click",()=>{window.location.href="/api/export/opml"}),document.getElementById("import-opml-file")?.addEventListener("change",async e=>{const a=e.target.files?.[0];a&&(await D(a)?(alert("OPML imported successfully! Crawling started."),b()):alert("Failed to import OPML."))}),document.querySelectorAll(".delete-feed-btn").forEach(e=>{e.addEventListener("click",async a=>{const s=parseInt(a.target.getAttribute("data-id"));confirm("Are you sure you want to delete this feed?")&&(await Q(s),b(),await b(),w())})}),document.querySelectorAll(".update-feed-tag-btn").forEach(e=>{e.addEventListener("click",async a=>{const s=parseInt(a.target.getAttribute("data-id")),o=document.querySelector(`.feed-tag-input[data-id="${s}"]`).value.trim();await j(s,{category:o}),await b(),await _(),w(),alert("Feed updated")})}))}async function N(t){try{return(await m("/api/feed",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:t})})).ok}catch(e){return console.error("Failed to add feed",e),!1}}async function D(t){try{const e=new FormData;e.append("file",t),e.append("format","opml");const a=document.cookie.split("; ").find(n=>n.startsWith("csrf_token="))?.split("=")[1];return(await fetch("/api/import",{method:"POST",headers:{"X-CSRF-Token":a||""},body:e})).ok}catch(e){return console.error("Failed to import OPML",e),!1}}async function Q(t){try{return(await m(`/api/feed/${t}`,{method:"DELETE"})).ok}catch(e){return console.error("Failed to delete feed",e),!1}}async function j(t,e){try{return(await m("/api/feed",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,_id:t})})).ok}catch(a){return console.error("Failed to update feed",a),!1}}async function H(t){const e=i.items.find(a=>a._id===t);e&&h(t,{starred:!e.starred})}async function U(t){if(i.items.find(a=>a._id===t))try{const a=await m(`/api/item/${t}/content`);if(a.ok){const s=await a.json();s.full_content&&h(t,{full_content:s.full_content})}}catch(a){console.error("Failed to fetch full content",a)}}async function h(t,e){try{if((await m(`/api/item/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).ok){const s=i.items.find(n=>n._id===t);if(s){Object.assign(s,e);const n=document.querySelector(`.feed-item[data-id="${t}"]`);if(n){if(e.read!==void 0&&n.classList.toggle("read",e.read),e.starred!==void 0){const o=n.querySelector(".star-btn");o&&(o.classList.toggle("is-starred",e.starred),o.classList.toggle("is-unstarred",!e.starred),o.setAttribute("title",e.starred?"Unstar":"Star"))}e.full_content&&I()}}}}catch(a){console.error("Failed to update item",a)}}async function b(){const t=await m("/api/feed/");if(t.ok){const e=await t.json();i.setFeeds(e)}}async function _(){const t=await m("/api/tag");if(t.ok){const e=await t.json();i.setTags(e)}}async function L(t,e,a=!1){i.setLoading(!0);try{const s=new URLSearchParams;t&&s.append("feed_id",t),e&&s.append("tag",e),i.searchQuery&&s.append("q",i.searchQuery),(i.filter==="starred"||i.filter==="all")&&s.append("read_filter","all"),i.filter==="starred"&&s.append("starred","true"),a&&i.items.length>0&&s.append("max_id",String(i.items[i.items.length-1]._id));const n=await m(`/api/stream?${s.toString()}`);if(n.ok){const o=await n.json();i.setHasMore(o.length>=50),i.setItems(o,a)}}finally{i.setLoading(!1)}}async function V(){const t=r.getCurrentRoute();L(t.params.feedId,t.params.tagName,!0)}async function W(){await m("/api/logout",{method:"POST"}),window.location.href="/login/"}function E(){const t=r.getCurrentRoute(),e=t.query.get("filter");i.setFilter(e||"unread");const a=t.query.get("q");if(a!==null&&i.setSearchQuery(a),t.path==="/settings"){w();return}if(t.path==="/feed"&&t.params.feedId){const s=parseInt(t.params.feedId);i.setActiveFeed(s),L(t.params.feedId),document.getElementById("section-feeds")?.classList.remove("collapsed")}else t.path==="/tag"&&t.params.tagName?(i.setActiveTag(t.params.tagName),L(void 0,t.params.tagName),document.getElementById("section-tags")?.classList.remove("collapsed")):(i.setActiveFeed(null),i.setActiveTag(null),L())}window.addEventListener("keydown",t=>{if(!["INPUT","TEXTAREA"].includes(t.target.tagName))switch(t.key){case"j":S(1);break;case"k":S(-1);break;case"r":if(c){const e=i.items.find(a=>a._id===c);e&&h(e._id,{read:!e.read})}break;case"s":if(c){const e=i.items.find(a=>a._id===c);e&&h(e._id,{starred:!e.starred})}break;case"/":t.preventDefault(),document.getElementById("search-input")?.focus();break}});function S(t){if(i.items.length===0)return;const e=i.items.findIndex(s=>s._id===c);let a;if(e===-1?a=t>0?0:i.items.length-1:a=e+t,a>=0&&a{const o=parseInt(n.getAttribute("data-id")||"0");n.classList.toggle("selected",o===c)});const s=document.querySelector(`.feed-item[data-id="${c}"]`);s&&s.scrollIntoView({block:"start",behavior:"smooth"}),i.items[a].read||h(c,{read:!0})}}i.on("feeds-updated",T);i.on("tags-updated",k);i.on("active-feed-updated",T);i.on("active-tag-updated",k);i.on("filter-updated",$);i.on("search-updated",()=>{const t=document.getElementById("search-input");t&&t.value!==i.searchQuery&&(t.value=i.searchQuery),E()});i.on("theme-updated",()=>{p||(p=document.querySelector("#app")),p&&(p.className=`theme-${i.theme} font-${i.fontTheme}`)});i.on("sidebar-toggle",()=>{const t=document.querySelector(".layout");t&&(i.sidebarVisible?(t.classList.remove("sidebar-hidden"),t.classList.add("sidebar-visible")):(t.classList.remove("sidebar-visible"),t.classList.add("sidebar-hidden")))});i.on("items-updated",I);i.on("loading-state-changed",I);r.addEventListener("route-changed",E);window.app={navigate:t=>r.navigate(t)};async function J(){const t=await m("/api/auth");if(!t||t.status===401){window.location.href="/login/";return}q(),$();try{await Promise.all([b(),_()])}catch(e){console.error("Initial fetch failed",e)}E()}typeof window<"u"&&!window.__VITEST__&&J(); diff --git a/web/dist/v3/index.html b/web/dist/v3/index.html index a9f4a35..3e08b77 100644 --- a/web/dist/v3/index.html +++ b/web/dist/v3/index.html @@ -5,7 +5,7 @@ neko - + -- cgit v1.2.3