diff --git a/src/lib/components/lemmy/post/feed/PostFeed.svelte b/src/lib/components/lemmy/post/feed/PostFeed.svelte index 9ce82f95..f8e51328 100644 --- a/src/lib/components/lemmy/post/feed/PostFeed.svelte +++ b/src/lib/components/lemmy/post/feed/PostFeed.svelte @@ -7,15 +7,11 @@ import { ArchiveBox, Icon, Minus, Plus } from 'svelte-hero-icons' import { expoOut } from 'svelte/easing' import { fly, slide } from 'svelte/transition' - import { browser } from '$app/environment' - import { afterUpdate, onMount, tick, type SvelteComponent } from 'svelte' - import { createWindowVirtualizer } from '@tanstack/svelte-virtual' - import { afterNavigate, beforeNavigate } from '$app/navigation' - import { _posts } from '../../../../../routes/+page.svelte' import { combineCrossposts } from './crosspost' export let posts: PostView[] export let community: boolean = false + let etc = $$restProps $: combinedPosts = combineCrossposts(posts) diff --git a/src/lib/components/lemmy/post/feed/VirtualFeed.svelte b/src/lib/components/lemmy/post/feed/VirtualFeed.svelte index 24cbbeac..97b9597d 100644 --- a/src/lib/components/lemmy/post/feed/VirtualFeed.svelte +++ b/src/lib/components/lemmy/post/feed/VirtualFeed.svelte @@ -2,20 +2,40 @@ import Post from '$lib/components/lemmy/post/Post.svelte' import Placeholder from '$lib/components/ui/Placeholder.svelte' import { userSettings } from '$lib/settings.js' - import type { PostView } from 'lemmy-js-client' + import type { + GetPostsResponse, + ListingType, + PostView, + SortType, + } from 'lemmy-js-client' import { Badge, Button } from 'mono-svelte' - import { ArchiveBox, Icon, Minus, Plus } from 'svelte-hero-icons' + import { + ArchiveBox, + ExclamationTriangle, + Icon, + Minus, + Plus, + } from 'svelte-hero-icons' import { expoOut } from 'svelte/easing' import { fly, slide } from 'svelte/transition' import { browser } from '$app/environment' import { afterUpdate, onMount, tick, type SvelteComponent } from 'svelte' import { createWindowVirtualizer } from '@tanstack/svelte-virtual' import { afterNavigate, beforeNavigate } from '$app/navigation' - import { _posts } from '../../../../../routes/+page.svelte' import { combineCrossposts } from './crosspost' + import { client } from '$lib/lemmy' + import { + postFeeds, + type PostFeed, + type PostFeedID, + } from '$lib/lemmy/postfeed' + import { t } from '$lib/translations' + import InfiniteScroll from 'svelte-infinite-scroll' export let posts: PostView[] export let community: boolean = false + export let lastSeen: number | undefined = undefined + export let feedId: PostFeedID let combinedPosts = combineCrossposts(posts) $: combinedPosts = combineCrossposts(posts) @@ -39,7 +59,104 @@ } afterNavigate(() => { - $virtualizer.scrollToIndex($_posts?.lastSeen) + $virtualizer.scrollToIndex(lastSeen ?? 0, { align: 'auto' }) + }) + + export let feedData: PostFeed['data'] + + const limit = 20 + let error: any = undefined + let loading = false + let hasMore = true + + async function loadMore() { + if (!hasMore || loading) return + + try { + loading = true + + const newPosts = await client() + .getPosts({ + page_cursor: feedData.cursor.next, + disliked_only: feedData.disliked_only, + liked_only: feedData.liked_only, + community_id: feedData.community_id, + community_name: feedData.community_name, + limit: feedData.limit, + page: feedData.page, + saved_only: feedData.saved_only, + show_hidden: feedData.show_hidden, + sort: feedData.sort, + type_: feedData.type_, + }) + .catch((e) => { + throw new Error(e) + }) + + error = null + + hasMore = newPosts.posts.length != 0 + + feedData.cursor.next = newPosts.next_page + feedData.posts.posts = [...feedData.posts.posts, ...newPosts.posts] + + postFeeds.updateFeed(feedId, { + data: feedData, + }) + + loading = false + } catch (e) { + error = e + loading = false + } + } + + const callback: IntersectionObserverCallback = (entries, observer) => { + entries.forEach((entry) => { + if (!entry.isIntersecting) return + + const element = entry.target as HTMLElement + const id = element.getAttribute('data-index') + + if (!id) return + + $postFeeds.main.lastSeen = Number(id) + observer.unobserve(element) + }) + } + + onMount(() => { + const observer = new IntersectionObserver(callback, { + root: null, + rootMargin: '0px', + threshold: 0.5, + }) + + const elements = document.querySelectorAll('.post-container') + elements.forEach((el) => observer.observe(el)) + + const postContainer = document.querySelector('#feed') + if (postContainer) { + const mutationObserver = new MutationObserver((mutations) => { + mutations.forEach((mutation) => { + if (mutation.type === 'childList') { + mutation.addedNodes.forEach((node) => { + if ( + node instanceof HTMLElement && + node.classList.contains('post-container') + ) { + observer.observe(node) + } + }) + } + }) + }) + + mutationObserver.observe(postContainer, { + childList: true, + subtree: true, + }) + } }) @@ -114,5 +231,38 @@ {/if} + + {#if $userSettings.infiniteScroll && browser} + {#if error} +
+
+ +
+
{error}
+ +
+ {:else if hasMore} +
+
+
+
+
+
+
+
+ {/if} + + {/if} diff --git a/src/lib/components/ui/Pageination.svelte b/src/lib/components/ui/Pageination.svelte index f58a7c9a..e85975bd 100644 --- a/src/lib/components/ui/Pageination.svelte +++ b/src/lib/components/ui/Pageination.svelte @@ -10,7 +10,7 @@ Icon, } from 'svelte-hero-icons' - export let page: number + export let page: number = 0 export let cursor: { next?: string; back?: string } | undefined = undefined const dispatcher = createEventDispatcher<{ change: number; cursor: string }>() diff --git a/src/lib/lemmy/postfeed.ts b/src/lib/lemmy/postfeed.ts new file mode 100644 index 00000000..cbe1c025 --- /dev/null +++ b/src/lib/lemmy/postfeed.ts @@ -0,0 +1,93 @@ +import { browser } from "$app/environment" +import { instance } from "$lib/instance" +import { client } from "$lib/lemmy" +import type { GetPosts, GetPostsResponse, ListingType, SortType } from "lemmy-js-client" +import { get, writable } from "svelte/store" + +export const shouldReload = ( + cache: PostFeed | undefined, + url: URL, + instance: string, +): boolean => + cache?.instance != instance || cache?.url.toString() != url.toString() + +interface FetchPostFeed extends GetPosts { + sort: SortType + type_?: ListingType +} + +export async function postFeed(args: { + id: PostFeedID + request: FetchPostFeed, + url: URL +}) { + const feed = get(postFeeds)[args.id] + + const posts = shouldReload(feed, args.url, get(instance)) + ? await client().getPosts(args.request) + : feed.data.posts + + if ( + shouldReload(feed, args.url, get(instance)) && + browser + ) + postFeeds.updateFeed(args.id, { + data: { + ...args.request, + posts: posts, + cursor: { + next: posts.next_page + }, + type_: args.request.type_ + }, + url: args.url, + lastSeen: 0, + instance: get(instance), + }) + + return get(postFeeds)[args.id].data +} + +export function getPostFeed(feeds: Map, id: PostFeedID) { + return feeds.get(id) +} + +function createPostFeedsStore() { + // @ts-ignore + const { subscribe, update, set } = writable>({}); + + return { + subscribe, + addFeed: (id: PostFeedID, feed: PostFeed) => update(feeds => ({ ...feeds, [id]: feed })), + updateFeed: (id: PostFeedID, feed: Partial) => update(feeds => { + return { + ...feeds, + [id]: { ...feeds[id], ...feed } as PostFeed + }; + }), + removeFeed: (id: PostFeedID) => update(feeds => { + const { [id]: _, ...rest } = feeds; + return rest as Record; + }), + clearAll: () => set({} as Record), + set + }; +} + +export type PostFeedID = 'main' | 'community' | 'profile' + +export interface PostFeed { + data: GetPosts & { + posts: GetPostsResponse, + cursor: { + next?: string + }, + sort: SortType, + } + url: URL + lastSeen: number + instance: string + id: PostFeedID +} + +export let postFeeds = createPostFeedsStore() \ No newline at end of file diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte index 141a0846..d6cfe541 100644 --- a/src/routes/+page.svelte +++ b/src/routes/+page.svelte @@ -1,27 +1,4 @@
{$t('routes.frontpage.title')}
- + {#if data.type_} + + {/if}
@@ -152,46 +41,15 @@ - {#if $userSettings.infiniteScroll && browser} - {#if error} -
-
- -
-
{error}
- -
- {:else if hasMore} -
-
-
-
-
-
-
-
- {/if} - - {/if} -
+ bind:feedData={data} + lastSeen={$postFeeds.main.lastSeen} + feedId="main" + /> searchParam($page.url, 'page', p.detail.toString())} on:cursor={(c) => { diff --git a/src/routes/+page.ts b/src/routes/+page.ts index 5c785106..271b2d61 100644 --- a/src/routes/+page.ts +++ b/src/routes/+page.ts @@ -3,14 +3,13 @@ import { userSettings } from '$lib/settings.js' import type { GetPostsResponse, ListingType, SortType } from 'lemmy-js-client' import { get, writable } from 'svelte/store' import { error } from '@sveltejs/kit' -import { _posts, shouldReload, type CachedPosts } from './+page.svelte' import { browser } from '$app/environment' import { instance } from '$lib/instance' +import { postFeed, postFeeds, shouldReload } from '$lib/lemmy/postfeed.js' export async function load({ url, fetch }) { const cursor = url.searchParams.get('cursor') as string | undefined const prevCursor = url.searchParams.get('prevCursor') as string | undefined - const page = Number(url.searchParams.get('page')) || undefined const settings = get(userSettings) @@ -19,55 +18,16 @@ export async function load({ url, fetch }) { const listingType: ListingType = (url.searchParams.get('type') as ListingType) || settings.defaultSort.feed - const cached: CachedPosts | undefined = get(_posts) - const posts = shouldReload(cached, url.searchParams.toString(), get(instance)) - ? await getClient(undefined, fetch).getPosts({ - limit: 20, - page: page, - sort: sort, - type_: listingType, - page_cursor: cursor, - show_hidden: settings.posts.showHidden, - }) - : cached.data.posts - - if ( - shouldReload(cached, url.searchParams.toString(), get(instance)) && - browser - ) - _posts.set({ - data: { - sort: sort, - listingType: listingType, - page: page || 1, - posts: posts, - cursor: { - next: posts.next_page, - }, - }, - params: url.searchParams, - lastSeen: 0, - instance: get(instance), - }) - - try { - return shouldReload(cached, url.searchParams.toString(), get(instance)) - ? { - sort: sort, - listingType: listingType, - page: page || 1, - posts: posts, - cursor: { - next: posts.next_page, - back: prevCursor, - current: cursor, - }, - } - : cached.data - } catch (err) { - error(500, { - message: 'Failed to fetch homepage.', - }) - } + return await postFeed({ + id: 'main', + request: { + page_cursor: cursor, + sort: sort, + type_: listingType, + limit: 20, + show_hidden: settings.posts.showHidden + }, + url: url + }) } diff --git a/src/routes/c/[name]/+page.svelte b/src/routes/c/[name]/+page.svelte index 5f5b0dd8..318cf563 100644 --- a/src/routes/c/[name]/+page.svelte +++ b/src/routes/c/[name]/+page.svelte @@ -8,6 +8,7 @@ import { onDestroy, onMount } from 'svelte' import { setSessionStorage } from '$lib/session.js' import PostFeed from '$lib/components/lemmy/post/feed/PostFeed.svelte' + import VirtualFeed from '$lib/components/lemmy/post/feed/VirtualFeed.svelte' import { Button, Modal, toast } from 'mono-svelte' import { afterNavigate } from '$app/navigation' import { browser } from '$app/environment' @@ -22,6 +23,9 @@ import Placeholder from '$lib/components/ui/Placeholder.svelte' import { profile } from '$lib/auth' import { t } from '$lib/translations.js' + import { userSettings } from '$lib/settings.js' + import { site } from '$lib/lemmy.js' + import { postFeeds } from '$lib/lemmy/postfeed.js' export let data @@ -31,7 +35,7 @@ if (browser) setSessionStorage( 'lastSeenCommunity', - data.community.community_view.community + data.community.community_view.community, ) }) @@ -81,7 +85,7 @@ `!${data.community.community_view.community.name}@${ new URL(data.community.community_view.community.actor_id) .hostname - }` + }`, ) toast({ content: $t('toast.copied') }) @@ -89,7 +93,7 @@ class="dark:text-zinc-400 text-slate-600 text-sm text-left" > !{data.community.community_view.community.name}@{new URL( - data.community.community_view.community.actor_id + data.community.community_view.community.actor_id, ).hostname}
@@ -102,7 +106,7 @@ color="secondary" href="/c/{fullCommunityName( data.community.community_view.community.name, - data.community.community_view.community.actor_id + data.community.community_view.community.actor_id, )}/settings" > @@ -132,30 +136,36 @@ {:else} - + {/if} - searchParam($page.url, 'cursor', c.detail)} - on:change={(p) => searchParam($page.url, 'page', p.detail.toString())} + - {#if data.posts.posts.length > 0} + searchParam($page.url, 'page', p.detail.toString())} + on:cursor={(c) => { + searchParam($page.url, 'cursor', c.detail) + }} + > - - {data.community.community_view.counts.users_active_day} - - - Active user{data.community.community_view.counts.users_active_day > - 1 - ? 's' - : ''} - + {$t('routes.frontpage.footer', { + // @ts-ignore + users: $site?.site_view.counts.users_active_day ?? '??', + })} - {/if} - + + diff --git a/src/routes/c/[name]/+page.ts b/src/routes/c/[name]/+page.ts index 7863a5b9..6581da01 100644 --- a/src/routes/c/[name]/+page.ts +++ b/src/routes/c/[name]/+page.ts @@ -1,4 +1,5 @@ import { client } from '$lib/lemmy.js' +import { postFeed } from '$lib/lemmy/postfeed.js' import { userSettings } from '$lib/settings.js' import type { SortType } from 'lemmy-js-client' import { get } from 'svelte/store' @@ -16,13 +17,16 @@ export async function load({ params, fetch, url }) { return { sort: sort, page: page || 1, - posts: await client({ func: fetch }).getPosts({ - limit: 40, - community_name: params.name, - page: page, - sort: sort, - page_cursor: cursor, - show_hidden: get(userSettings).posts.showHidden, + posts: await postFeed({ + id: 'community', + url: url, + request: { + page: page, + page_cursor: cursor, + sort: sort, + limit: 20, + community_name: params.name, + } }), } }