impr: switch to refactored feed handler (#654)

* impr: use refactored feed handler for main & community

* refactor: re-add post preloading to feed handler

* fix: remove unused setting & improve consistency of postmedia compact
This commit is contained in:
xylight authored and GitHub committed 2025-09-12 02:18:32 +00:00
1 parent 2d01124bbf
commit 9460eec7e1
26 files changed
+489 -467

No files matched your search

File renamed without changes.
@@ -78,6 +78,7 @@
type IconSource,
} from 'svelte-hero-icons'
import { CommunityLink } from '../community'
import { SvelteMap } from 'svelte/reactivity'
interface Props {
community?: Community
@@ -134,7 +135,7 @@
color: 'red-subtle' | 'yellow-subtle' | 'green-subtle'
label: string
}
> = new Map([
> = new SvelteMap([
[
'nsfw',
{
@@ -184,7 +184,7 @@
<Spinner width={20} />
</div>
{:then { default: PostActionsMenu }}
<PostActionsMenu {post} {onhide} bind:editing />
<PostActionsMenu bind:post {onhide} bind:editing />
{/await}
{/if}
{/snippet}
@@ -32,7 +32,7 @@
editing: boolean
}
let { post, onhide, editing = $bindable() }: Props = $props()
let { post = $bindable(), onhide, editing = $bindable() }: Props = $props()
function share(global: boolean = true) {
const link = global
@@ -1,17 +1,13 @@
<script lang="ts">
import { browser } from '$app/environment'
import { client } from '$lib/client/lemmy.svelte'
import type { GetPosts } from '$lib/client/types'
import VirtualList from '$lib/components/render/VirtualList.svelte'
import EndPlaceholder from '$lib/components/ui/EndPlaceholder.svelte'
import Placeholder from '$lib/components/ui/Placeholder.svelte'
import { t } from '$lib/i18n/translations'
import { client } from '$lib/client/lemmy.svelte'
import {
postFeeds,
type PostFeed,
type PostFeedID,
} from '$lib/lemmy/postfeed.svelte'
import { settings } from '$lib/settings.svelte.js'
import type { PostView } from '$lib/client/types'
import type { PostView } from 'lemmy-js-client'
import { Button } from 'mono-svelte'
import { onDestroy, onMount, untrack } from 'svelte'
import {
@@ -29,17 +25,19 @@
interface Props {
posts: PostView[]
params: GetPosts
virtualList?: { itemHeights: (number | null)[] }
lastSeen?: number
community?: boolean
feedId: PostFeedID
feedData: PostFeed['data']
children?: import('svelte').Snippet
}
let {
posts = $bindable(),
params = $bindable(),
virtualList = $bindable(),
lastSeen = $bindable(0),
community = false,
feedId,
feedData = $bindable(),
children,
}: Props = $props()
@@ -53,9 +51,7 @@
let hasMore = $state(true)
const abortLoad = new AbortController()
let seenIds = new SvelteSet<number>(
feedData.posts.posts.map((post) => post.post.id),
)
let seenIds = new SvelteSet<number>(posts.map((post) => post.post.id))
async function loadMore() {
if (!hasMore || loading) return
@@ -67,19 +63,7 @@
func: (input, init) =>
fetch(input, { ...init, signal: abortLoad.signal }),
})
.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_,
})
.getPosts(params)
.catch((e) => {
throw new Error(e)
})
@@ -88,8 +72,9 @@
hasMore = newPosts.posts.length != 0
feedData.cursor.next = newPosts.next_page
feedData.posts.posts.push(
params.page_cursor = newPosts.next_page
posts.push(
...newPosts.posts.filter((post) => {
if (seenIds.has(post.post.id)) return false
seenIds.add(post.post.id)
@@ -97,8 +82,6 @@
}),
)
postFeeds.value[feedId].data = feedData
loading = false
} catch (e) {
error = e
@@ -115,7 +98,7 @@
if (!id) return
postFeeds.value[feedId].lastSeen = Number(id)
lastSeen = Number(id)
observer.unobserve(element)
})
@@ -158,8 +141,8 @@
$effect(() => {
if (listComp) {
untrack(() => {
if (postFeeds.value[feedId].lastSeen != 0) {
listComp?.scrollToIndex(postFeeds.value[feedId].lastSeen, true)
if (lastSeen != 0) {
listComp?.scrollToIndex(lastSeen, true)
}
})
}
@@ -199,7 +182,7 @@
{initialOffset}
overscan={3}
estimatedHeight={settings.view == 'cozy' ? 500 : 150}
bind:restore={postFeeds.value[feedId].clientData}
bind:restore={virtualList}
bind:this={listComp}
>
{#snippet item(row)}
@@ -264,7 +247,7 @@
<div style="border-top-width: 0">
<EndPlaceholder>
{$t('routes.frontpage.endFeed', {
community_name: feedData.community_name ?? 'undefined',
community_name: params.community_name ?? 'undefined',
})}
{#snippet action()}
<Button color="tertiary" icon={ChevronDoubleUp}>
@@ -34,7 +34,6 @@
Language,
Link,
Photo,
Plus,
Sparkles,
XMark,
} from 'svelte-hero-icons'
@@ -64,7 +64,7 @@
<div
class={[
'relative overflow-hidden rounded-2xl max-h-full h-full',
'border border-slate-200 dark:border-zinc-800 hover-scale-effect',
'border border-slate-200 dark:border-zinc-800 hover-scale-effect bg-slate-200 dark:bg-zinc-800',
]}
>
{#if post.thumbnail_url || type == 'image'}
+111
View File
@@ -0,0 +1,111 @@
import { browser } from '$app/environment'
import type {
CommentView,
CommunityView,
GetComments,
GetCommunityResponse,
GetPersonDetails,
GetPersonDetailsResponse,
GetPost,
GetPosts,
PostView,
} from '$lib/client/types'
import { recursiveEqual } from '$lib/util.svelte'
import { SvelteMap } from 'svelte/reactivity'
type FetchFn<P, R> = (params: P) => R
export class Feed<Params, Response> {
#data = $state<Response>()
#fetch: FetchFn<Params, Response>
#lastParams?: Params
constructor(fetch: FetchFn<Params, Response>) {
this.#fetch = fetch
}
async load(params: Params) {
if (
this.#lastParams &&
params &&
!recursiveEqual<Params>(params, this.#lastParams)
)
this.#data = undefined
this.#lastParams = params
if (this.#data == null) this.#data = await this.#fetch(params)
return this.#data
}
peek() {
return this.#data
}
update(value: Response) {
this.#data = value
}
}
interface FeedTypes {
'/': [
GetPosts,
{
posts: PostView[]
next_page?: string
params: GetPosts
client: {
itemHeights?: (number | null)[]
lastSeen?: number
}
},
]
'/c/[name]': [
GetPosts,
{
posts: PostView[]
community: GetCommunityResponse
next_page?: string
params: GetPosts
client: { itemHeights?: (number | null)[]; lastSeen?: number }
},
]
'/u/[name]': [GetPersonDetails, { data: GetPersonDetailsResponse }]
'/post/[instance]/[id=integer]': [
{
posts: GetPost
comments: GetComments
preload?: PostView
},
{
post: PostView
comments: Promise<CommentView[]>
meta: Promise<{
community_view: CommunityView
cross_posts: PostView[]
post_view: PostView
}>
thread: {
showContext?: boolean
singleThread?: boolean
focus?: string
}
params: { posts: GetPost; comments: GetComments }
},
]
}
const feeds = new SvelteMap<keyof FeedTypes, Feed<any, any>>()
export function feed<Type extends keyof FeedTypes>(
id: Type,
init: (params: FeedTypes[Type][0]) => Promise<FeedTypes[Type][1]>,
): Feed<FeedTypes[Type][0], FeedTypes[Type][1]> {
const feed = feeds.get(id)
if (browser && feed) return feed
const feedData = new Feed<any, any>(init)
feeds.set(id, feedData)
return feedData
}
-107
View File
@@ -1,107 +0,0 @@
import { browser } from '$app/environment'
import { instance } from '$lib/instance.svelte'
import { client } from '$lib/client/lemmy.svelte'
import type {
GetPosts,
GetPostsResponse,
ListingType,
SortType,
} from '$lib/client/types'
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
fetch?: (
input: RequestInfo | URL,
init?: RequestInit | undefined,
) => Promise<Response>
}) {
const feed = postFeeds.value[args.id]
const posts = shouldReload(feed, args.url, instance.data)
? await client({ func: args.fetch }).getPosts(args.request)
: feed.data.posts
if (shouldReload(feed, args.url, instance.data) && browser)
postFeeds.value[args.id] = {
id: args.id,
data: {
...args.request,
posts: posts,
cursor: {
next: posts.next_page,
},
type_: args.request.type_,
},
url: args.url,
lastSeen: 0,
instance: instance.data,
clientData: {
itemHeights: [],
},
}
const defaultFeed = $state({
...args.request,
posts: posts,
cursor: {
next: posts.next_page,
},
type_: args.request.type_,
})
return postFeeds.value[args.id]?.data ?? defaultFeed
}
export function getPostFeed(feeds: Map<PostFeedID, PostFeed>, id: PostFeedID) {
return feeds.get(id)
}
class PostFeedState {
#value: Record<PostFeedID, PostFeed> = $state({}) as Record<
PostFeedID,
PostFeed
>
get value() {
return this.#value
}
set value(value) {
this.#value = value
}
}
export type PostFeedID = 'main' | 'community' | 'profile' | 'votes'
export interface PostFeed {
data: GetPosts & {
posts: GetPostsResponse
cursor: {
next?: string
}
sort: SortType
}
url: URL
lastSeen: number
instance: string
id: PostFeedID
clientData: {
itemHeights: (number | null)[]
}
}
export const postFeeds = new PostFeedState()
+2 -2
View File
@@ -96,9 +96,9 @@
<Label
text={label}
customText={customLabel}
class={['space-y-1 relative', baseClass]}
class={['space-y-1 relative max-w-full w-max', baseClass]}
>
<div class="relative w-max max-w-full" role="presentation">
<div class="relative max-w-full" role="presentation">
<select
{@attach attachment}
{...rest}
+34
View File
@@ -160,6 +160,10 @@ export class ReactiveState<T> {
}
}
export function snapshot<T>(item: T) {
return $state.snapshot(item)
}
export const isImage = (url: string | undefined) => {
try {
if (!url) return false
@@ -185,3 +189,33 @@ export const communityLink = (community: Community, prefix: string = '') =>
export const userLink = (person: Person, prefix: string = '') =>
`${prefix}/u/${person.name}@${new SvelteURL(person.actor_id).hostname}`
/**
* Basic types only, don't use for anything more than basic equality
*/
export function recursiveEqual<T>(
a: NonNullable<T>,
b: NonNullable<T>,
): boolean {
if (a === b) return true
if (typeof a !== 'object' || typeof b !== 'object') return false
const keysA = Object.keys(a) as (keyof typeof a)[]
const keysB = Object.keys(b) as (keyof typeof b)[]
if (keysA.length != keysB.length) return false
for (const key of keysA) {
const valA = a[key]
const valB = b[key]
if (typeof valA == 'object' && typeof valB == 'object') {
const result = recursiveEqual(valA!, valB!)
if (!result) return false
} else {
if (valA != valB) return false
}
}
return true
}