import { browser } from '$app/environment' import { profile } from '$lib/auth.svelte' import type { CommentView, CommunityView, FeedView, GetComments, GetCommunityResponse, GetPersonDetails, GetPersonDetailsResponse, GetPost, GetPosts, PostView, TopicView, } from '$lib/client/types' import { recursiveEqual } from '$lib/util.svelte' import { SvelteMap } from 'svelte/reactivity' type FetchFn = (params: P) => R export class Feed { #data = $state() #fetch: FetchFn #lastParams?: Params constructor(fetch: FetchFn) { this.#fetch = fetch } async load(params: Params) { if ( this.#lastParams && params && !recursiveEqual(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 } } export 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 meta: Promise<{ community_view: CommunityView cross_posts: PostView[] post_view: PostView }> thread: { showContext?: boolean singleThread?: boolean focus?: string } params: { posts: GetPost; comments: GetComments } }, ] '/f/[id]': [ GetPosts, { posts: PostView[] next_page?: string params: GetPosts feed: Promise client: { itemHeights?: (number | null)[] lastSeen?: number } }, ] '/topic/[id]': [ GetPosts, { posts: PostView[] next_page?: string params: GetPosts topic: Promise client: { itemHeights?: (number | null)[] lastSeen?: number } }, ] } const feeds = new SvelteMap>() export function feed( id: Type, init: (params: FeedTypes[Type][0]) => Promise, ): Feed { const feed = feeds.get(id) if (browser && feed) return feed const feedData = new Feed(init) feeds.set(id, feedData) return feedData } // feed hooks $effect.root(() => { $effect(() => { if (profile.meta.profile) feeds.clear() }) })