Merge pull request #349 from Xyphyn/infinite-scroll

feat: add infinite scroll
This commit is contained in:
Xylight authored and GitHub committed 2024-07-09 16:22:28 -07:00
commit 49a0e983df
19 files changed
+561 -110

No files matched your search

+2 -1
View File
@@ -1,6 +1,7 @@
<script lang="ts">
import { goto } from '$app/navigation'
import { page } from '$app/stores'
import { t } from '$lib/translations'
import { Button } from 'mono-svelte'
import { Icon, XMark } from 'svelte-hero-icons'
</script>
@@ -18,6 +19,6 @@
{$page.error?.message}
</code>
<Button size="sm" class="w-max" on:click={() => goto($page.url)}>
Retry
{$t('message.retry')}
</Button>
</div>
+178 -15
View File
@@ -1,26 +1,143 @@
<script lang="ts" context="module">
export interface CachedPosts {
data: GetPostsResponse
params: URLSearchParams
lastSeen: number
instance: string
}
export const _posts = writable<CachedPosts>(undefined)
export const shouldReload = (
cache: CachedPosts | undefined,
params: string,
instance: string
): boolean =>
cache?.instance != instance || cache?.params.toString() != params
</script>
<script lang="ts">
import { page } from '$app/stores'
import StickyCard from '$lib/components/ui/StickyCard.svelte'
import SiteCard from '$lib/components/lemmy/SiteCard.svelte'
import Pageination from '$lib/components/ui/Pageination.svelte'
import Sort from '$lib/components/lemmy/dropdowns/Sort.svelte'
import ViewSelect from '$lib/components/lemmy/dropdowns/ViewSelect.svelte'
import { searchParam } from '$lib/util.js'
import PostFeed from '$lib/components/lemmy/post/PostFeed.svelte'
import { Button, Modal, Select, Spinner } from 'mono-svelte'
import { ChartBar, GlobeAmericas, Icon, ServerStack } from 'svelte-hero-icons'
import { profile } from '$lib/auth.js'
import { site } from '$lib/lemmy.js'
import { amModOfAny } from '$lib/components/lemmy/moderation/moderation.js'
import { feature } from '$lib/version.js'
import { userSettings } from '$lib/settings.js'
import FormattedNumber from '$lib/components/util/FormattedNumber.svelte'
import {
ChartBar,
ExclamationCircle,
ExclamationTriangle,
GlobeAmericas,
Icon,
ServerStack,
} from 'svelte-hero-icons'
import { getClient, site } from '$lib/lemmy.js'
import Location from '$lib/components/lemmy/dropdowns/Location.svelte'
import Header from '$lib/components/ui/layout/pages/Header.svelte'
import { t } from '$lib/translations.js'
import { enhance } from '$app/forms'
import InfiniteScroll from 'svelte-infinite-scroll'
import { Button, Material, Spinner } from 'mono-svelte'
import { get, writable } from 'svelte/store'
import type { GetPostsResponse } from 'lemmy-js-client'
import { userSettings } from '$lib/settings.js'
import { afterNavigate } from '$app/navigation'
import { browser } from '$app/environment'
import { onMount } from 'svelte'
import { instance } from '$lib/instance.js'
import VirtualFeed from '$lib/components/lemmy/post/feed/VirtualFeed.svelte'
import PostFeed from '$lib/components/lemmy/post/feed/PostFeed.svelte'
export let data
const limit = 20
let hasMore = data.posts.posts.length != 0
let error: any = undefined
let loading = false
async function loadMore() {
if (!hasMore || loading) return
try {
loading = true
const newPosts = await getClient()
.getPosts({
limit: limit,
page: data.page,
sort: data.sort,
type_: data.listingType,
page_cursor: data.cursor.next,
})
.catch((e) => {
throw new Error(e)
})
error = null
hasMore = newPosts.posts.length != 0
data.cursor.next = newPosts.next_page
data.posts.posts = [...data.posts.posts, ...newPosts.posts]
_posts.update((ps) => ({
data: data.posts,
params: ps.params,
lastSeen: ps.lastSeen,
instance: ps.instance,
}))
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
$_posts.lastSeen = Number(id)
observer.unobserve(element)
})
}
onMount(() => {
const observer = new IntersectionObserver(callback, {
root: null,
rootMargin: '0px',
threshold: 0.25,
})
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,
})
}
})
</script>
<div class="flex flex-col gap-4 max-w-full w-full min-w-0">
@@ -34,8 +151,48 @@
<ViewSelect />
</div>
</div>
<PostFeed posts={data.posts.posts} />
<div class="mt-auto">
<svelte:component
this={browser ? VirtualFeed : PostFeed}
posts={data.posts.posts}
>
{#if $userSettings.infiniteScroll && browser}
{#if error}
<div
class="flex flex-col justify-center items-center
rounded-xl gap-2 py-8 mt-6
border !border-b !border-red-500 bg-red-500/5 px-4"
>
<div class="bg-red-500/30 rounded-full p-3 text-red-500">
<Icon src={ExclamationTriangle} size="24" solid></Icon>
</div>
<pre class="py-0.5">{error}</pre>
<Button
color="primary"
{loading}
disabled={loading}
on:click={loadMore}
>
{$t('message.retry')}
</Button>
</div>
{:else if hasMore}
<div class="w-full flex flex-col skeleton gap-2 animate-pulse pt-6">
<div class="w-96 h-8"></div>
<div class="w-full h-48"></div>
<div class="!bg-transparent h-8 flex justify-between">
<div class="w-48 h-8"></div>
<div class="w-24 h-8"></div>
</div>
</div>
{/if}
<InfiniteScroll window threshold={1000} on:loadMore={loadMore} />
{/if}
</svelte:component>
<svelte:element
this={$userSettings.infiniteScroll ? 'noscript' : 'div'}
class="mt-auto"
>
<Pageination
page={data.page}
cursor={{ next: data.cursor.next, back: data.cursor.back }}
@@ -52,5 +209,11 @@
})}
</span>
</Pageination>
</div>
</svelte:element>
</div>
<style lang="postcss">
.skeleton * {
@apply bg-slate-100 dark:bg-zinc-800 rounded-md;
}
</style>
+28 -12
View File
@@ -1,10 +1,11 @@
import { getClient } from '$lib/lemmy.js'
import { userSettings } from '$lib/settings.js'
import type { ListingType, SortType } from 'lemmy-js-client'
import { get } from 'svelte/store'
import type { GetPostsResponse, ListingType, SortType } from 'lemmy-js-client'
import { get, writable } from 'svelte/store'
import { error } from '@sveltejs/kit'
import { profile } from '$lib/auth.js'
import { feature } from '$lib/version.js'
import { _posts, shouldReload, type CachedPosts } from './+page.svelte'
import { browser } from '$app/environment'
import { instance } from '$lib/instance'
export async function load({ url, fetch }) {
const cursor = url.searchParams.get('cursor') as string | undefined
@@ -18,14 +19,29 @@ export async function load({ url, fetch }) {
const listingType: ListingType =
(url.searchParams.get('type') as ListingType) || settings.defaultSort.feed
const posts = await getClient(undefined, fetch).getPosts({
limit: 20,
page: page,
sort: sort,
type_: listingType,
page_cursor: cursor,
show_hidden: settings.posts.showHidden,
})
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
if (
shouldReload(cached, url.searchParams.toString(), get(instance)) &&
browser
)
_posts.set({
data: posts,
params: url.searchParams,
lastSeen: 0,
instance: get(instance),
})
try {
return {
+1 -1
View File
@@ -7,7 +7,7 @@
import { fullCommunityName, searchParam } from '$lib/util.js'
import { onDestroy, onMount } from 'svelte'
import { setSessionStorage } from '$lib/session.js'
import PostFeed from '$lib/components/lemmy/post/PostFeed.svelte'
import PostFeed from '$lib/components/lemmy/post/feed/PostFeed.svelte'
import { Button, Modal, toast } from 'mono-svelte'
import { afterNavigate } from '$app/navigation'
import { browser } from '$app/environment'
@@ -42,6 +42,7 @@
import Expandable from '$lib/components/ui/Expandable.svelte'
import { Popover } from 'mono-svelte'
import { t } from '$lib/translations.js'
import { createWindowVirtualizer } from '@tanstack/svelte-virtual'
export let data
@@ -112,7 +113,24 @@
$: remoteView =
$page.params.instance?.toLowerCase() != $instance.toLowerCase()
const test = 'wow'
const virtualizer = createWindowVirtualizer({
count: 0,
estimateSize: () => 50,
})
onMount(async () => {
const comments = await data.comments
$virtualizer.setOptions({ count: comments.comments.length })
})
let virtualItemEls: HTMLElement[] = []
$: items = $virtualizer.getVirtualItems()
$: {
if (virtualItemEls.length)
virtualItemEls.forEach((el) => $virtualizer.measureElement(el))
}
</script>
<svelte:head>
@@ -1,56 +1,57 @@
import { browser } from '$app/environment'
import { env } from '$env/dynamic/public'
import { profile } from '$lib/auth.js'
import CommunityCard from '$lib/components/lemmy/community/CommunityCard.svelte'
import { getClient } from '$lib/lemmy.js'
import { awaitIfServer } from '$lib/promise.js'
import { SSR_ENABLED, userSettings } from '$lib/settings.js'
import { error } from '@sveltejs/kit'
import { get } from 'svelte/store'
import { browser } from "$app/environment";
import { env } from "$env/dynamic/public";
import { profile } from "$lib/auth.js";
import CommunityCard from "$lib/components/lemmy/community/CommunityCard.svelte";
import { getClient } from "$lib/lemmy.js";
import { awaitIfServer } from "$lib/promise.js";
import { SSR_ENABLED, userSettings } from "$lib/settings.js";
import { error } from "@sveltejs/kit";
import type { GetComments } from "lemmy-js-client";
import { get } from "svelte/store";
export async function load({ params, url, fetch }) {
const thread = url.searchParams.get('thread')
let parentId: number | undefined
let showContext: string | undefined = undefined
const thread = url.searchParams.get("thread");
let parentId: number | undefined;
let showContext: string | undefined = undefined;
let max_depth = 3
let max_depth = 3;
if (thread) {
const split = thread.split('.')
const split = thread.split(".");
if (split.length >= 9) {
const sliced = split.slice(0, split.length - 4)
showContext = sliced[sliced.length - 1]
parentId = Number(split[split.length - 5])
const sliced = split.slice(0, split.length - 4);
showContext = sliced[sliced.length - 1];
parentId = Number(split[split.length - 5]);
} else {
parentId = Number(split[1])
parentId = Number(split[1]);
}
if (!Number.isInteger(parentId)) {
parentId = undefined
parentId = undefined;
}
}
if (parentId) {
max_depth = 10
max_depth = 10;
}
const sort = get(userSettings)?.defaultSort?.comments ?? 'Hot'
const sort = get(userSettings)?.defaultSort?.comments ?? "Hot";
const commentParams: any = {
const commentParams: GetComments = {
post_id: Number(params.id),
type_: 'All',
type_: "All",
limit: 50,
page: 1,
max_depth: max_depth,
saved_only: false,
sort: sort,
parent_id: parentId,
}
};
const comments = getClient(params.instance, fetch).getComments(commentParams);
const post = await getClient(params.instance.toLowerCase(), fetch).getPost({
id: Number(params.id),
})
const comments = getClient(params.instance, fetch).getComments(commentParams)
});
return {
thread: {
@@ -60,13 +61,13 @@ export async function load({ params, url, fetch }) {
post: post,
commentSort: sort,
comments: (await awaitIfServer(comments)).data,
// slots: {
// sidebar: {
// component: CommunityCard,
// props: {
// community_view: post.community_view,
// },
// },
// },
}
slots: {
sidebar: {
component: CommunityCard,
props: {
community_view: post.community_view,
},
},
},
};
}
+6
View File
@@ -222,6 +222,12 @@
</div>
</div>
</Setting>
<ToggleSetting
beta
bind:checked={$userSettings.infiniteScroll}
title={$t('settings.app.infiniteScroll.title')}
description={$t('settings.app.infiniteScroll.description')}
/>
<ToggleSetting
bind:checked={$userSettings.openLinksInNewTab}
title={$t('settings.app.postsInNewTab.title')}
+23 -17
View File
@@ -11,6 +11,7 @@
export let title: string
export let description: string | undefined = undefined
export let checked: boolean = false
export let beta = false
export let supportedPlatforms = {
desktop: true,
@@ -20,25 +21,30 @@
</script>
<div class="flex flex-col w-full justify-between gap-2 max-w-full">
{#if Object.values(supportedPlatforms).some((v) => v == false)}
{#if Object.values(supportedPlatforms).some((v) => v == false) || beta}
<div class="flex items-center gap-2 flex-wrap">
{#if supportedPlatforms.desktop}
<Badge>
<Icon src={ComputerDesktop} micro size="14" slot="icon" />
{$t('settings.desktop')}
</Badge>
{#if beta}
<Badge>Beta</Badge>
{/if}
{#if supportedPlatforms.tablet}
<Badge>
<Icon src={DeviceTablet} micro size="14" slot="icon" />
{$t('settings.tablet')}
</Badge>
{/if}
{#if supportedPlatforms.mobile}
<Badge>
<Icon src={DevicePhoneMobile} micro size="14" slot="icon" />
{$t('settings.mobile')}
</Badge>
{#if Object.values(supportedPlatforms).some((v) => v == false)}
{#if supportedPlatforms.desktop}
<Badge>
<Icon src={ComputerDesktop} micro size="14" slot="icon" />
{$t('settings.desktop')}
</Badge>
{/if}
{#if supportedPlatforms.tablet}
<Badge>
<Icon src={DeviceTablet} micro size="14" slot="icon" />
{$t('settings.tablet')}
</Badge>
{/if}
{#if supportedPlatforms.mobile}
<Badge>
<Icon src={DevicePhoneMobile} micro size="14" slot="icon" />
{$t('settings.mobile')}
</Badge>
{/if}
{/if}
</div>
{/if}