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
}
+8 -6
View File
@@ -7,10 +7,9 @@
import { PostFeed, VirtualFeed } from '$lib/components/lemmy/post'
import EndPlaceholder from '$lib/components/ui/EndPlaceholder.svelte'
import Skeleton from '$lib/components/ui/generic/Skeleton.svelte'
import Pageination from '$lib/components/ui/layout/Pageination.svelte'
import { Header } from '$lib/components/ui/layout'
import Pageination from '$lib/components/ui/layout/Pageination.svelte'
import { t } from '$lib/i18n/translations.js'
import { postFeeds } from '$lib/lemmy/postfeed.svelte.js'
import { settings, SSR_ENABLED } from '$lib/settings.svelte.js'
import Button from 'mono-svelte/button/Button.svelte'
import { ArrowRight, ChartBar, Icon } from 'svelte-hero-icons'
@@ -87,9 +86,12 @@
</div>{/each}
{:then feed}
<FeedComponent
bind:posts={feed.posts.posts}
bind:feedData={() => feed, (v) => (postFeeds.value.main.data = v)}
feedId="main"
bind:posts={feed.posts}
bind:lastSeen={
() => feed.client.lastSeen ?? 0, (v) => (feed.client.lastSeen = v)
}
bind:params={feed.params}
virtualList={{ itemHeights: feed.client?.itemHeights ?? [] }}
/>
<svelte:element
this={settings.infiniteScroll && !settings.posts.noVirtualize
@@ -105,7 +107,7 @@
})}
{#snippet action()}
<Pageination
cursor={{ next: feed.cursor.next }}
cursor={{ next: feed.next_page }}
href={(page) =>
typeof page == 'number' ? `?page=${page}` : `?cursor=${page}`}
back={false}
+18 -18
View File
@@ -1,12 +1,13 @@
import { env } from '$env/dynamic/public'
import { t } from '$lib/i18n/translations.js'
import { postFeed } from '$lib/lemmy/postfeed.svelte.js'
import { ReactiveState, awaitIfServer } from '$lib/util.svelte.js'
import { settings } from '$lib/settings.svelte'
import { client } from '$lib/client/lemmy.svelte.js'
import type { ListingType, SortType } from '$lib/client/types'
import { t } from '$lib/i18n/translations.js'
import { feed } from '$lib/lemmy/feeds/feed.svelte.js'
import { settings } from '$lib/settings.svelte'
import { ReactiveState, awaitIfServer } from '$lib/util.svelte.js'
import { ChevronDoubleUp } from 'svelte-hero-icons'
export async function load({ url, fetch }) {
export async function load({ url, fetch, route }) {
const cursor = url.searchParams.get('cursor') as string | undefined
const sort: SortType =
@@ -14,23 +15,22 @@ export async function load({ url, fetch }) {
const listingType: ListingType =
(url.searchParams.get('type') as ListingType) || settings.defaultSort.feed
const feed = postFeed({
id: 'main',
request: {
page_cursor: cursor,
sort: sort,
type_: listingType,
limit: 20,
show_hidden: settings.posts.showHidden,
},
url: url,
fetch: fetch,
const feedData = feed(route.id, async (params) => ({
...(await client({ func: fetch }).getPosts(params)),
params: params,
client: {},
})).load({
page_cursor: cursor,
sort: sort,
type_: listingType,
limit: 20,
show_hidden: settings.posts.showHidden,
})
if (env.PUBLIC_SSR_ENABLED?.toLowerCase() == 'true') await feed
if (env.PUBLIC_SSR_ENABLED?.toLowerCase() == 'true') await feedData
return {
feed: new ReactiveState((await awaitIfServer(feed)).data),
feed: new ReactiveState((await awaitIfServer(feedData)).data),
filters: new ReactiveState({
sort: sort,
type_: listingType,
-19
View File
@@ -1,19 +0,0 @@
<script lang="ts">
let { data, children } = $props()
</script>
<svelte:head>
<title>{data.community.value.community_view.community.title}</title>
<meta
name="og:title"
content={data.community.value.community_view.community.title}
/>
{#if data.community.value.community_view.community.description}
<meta
name="og:description"
content={data.community.value.community_view.community.description}
/>
{/if}
</svelte:head>
{@render children?.()}
+38 -22
View File
@@ -2,22 +2,22 @@
import { browser } from '$app/environment'
import { navigating, page } from '$app/state'
import { profile } from '$lib/auth.svelte.js'
import { site } from '$lib/client/lemmy.svelte'
import CommunityCard from '$lib/components/lemmy/community/CommunityCard.svelte'
import CommunityHeader from '$lib/components/lemmy/community/CommunityHeader.svelte'
import Sort from '$lib/components/lemmy/dropdowns/Sort.svelte'
import ViewSelect from '$lib/components/lemmy/dropdowns/ViewSelect.svelte'
import { PostFeed, VirtualFeed } from '$lib/components/lemmy/post'
import { Header } from '$lib/components/ui/layout'
import Pageination from '$lib/components/ui/layout/Pageination.svelte'
import Placeholder from '$lib/components/ui/Placeholder.svelte'
import { t } from '$lib/i18n/translations.js'
import { site } from '$lib/client/lemmy.svelte'
import { resumables } from '$lib/lemmy/item'
import { setSessionStorage } from '$lib/session.js'
import { settings } from '$lib/settings.svelte.js'
import { Badge, Button, Modal, Note } from 'mono-svelte'
import { onDestroy, onMount } from 'svelte'
import { ArrowRight, ChartBar, Icon, Plus, XMark } from 'svelte-hero-icons'
import { PostFeed, VirtualFeed } from '$lib/components/lemmy/post'
let { data } = $props()
@@ -27,14 +27,14 @@
if (browser)
setSessionStorage(
'lastSeenCommunity',
data.community.value.community_view.community,
data.community.community_view.community,
)
resumables.add({
name: data.community.value.community_view.community.title,
name: data.community.community_view.community.title,
type: 'community',
url: page.url.toString(),
avatar: data.community.value.community_view.community.icon,
avatar: data.community.community_view.community.icon,
})
})
@@ -47,6 +47,21 @@
})
</script>
<svelte:head>
<title>{data.community.community_view.community.title}</title>
<meta
name="og:title"
content={data.community.community_view.community.title}
/>
{#if data.community.community_view.community.description}
<meta
name="og:description"
content={data.community.community_view.community.description}
/>
{/if}
</svelte:head>
{#if sidebar}
<Modal bind:open={sidebar}>
{#snippet customTitle()}
@@ -54,8 +69,8 @@
{/snippet}
<div>
<CommunityCard
bind:community_view={data.community.value.community_view}
moderators={data.community.value.moderators}
bind:community_view={data.community.community_view}
moderators={data.community.moderators}
/>
</div>
</Modal>
@@ -64,11 +79,11 @@
<Header pageHeader>
<div class="flex flex-col w-full">
<CommunityHeader
bind:community={data.community.value.community_view.community}
bind:subscribed={data.community.value.community_view.subscribed}
blocked={data.community.value.community_view.blocked}
moderators={data.community.value.moderators}
counts={data.community.value.community_view.counts}
bind:community={data.community.community_view.community}
bind:subscribed={data.community.community_view.subscribed}
blocked={data.community.community_view.blocked}
moderators={data.community.moderators}
counts={data.community.community_view.counts}
class="w-full relative"
compact="lg"
avatarCircle={false}
@@ -76,15 +91,15 @@
</div>
{#snippet extended()}
<div class="flex flex-row gap-2">
<Sort selected={data.sort} />
<Sort selected={data.params.sort!} />
<ViewSelect showLabel />
</div>
{/snippet}
</Header>
{#if profile.current.user}
{#if !data.community.value.discussion_languages.every( (l) => profile.current.user?.discussion_languages.includes(l), ) && profile.current.user.discussion_languages.length > 0}
{@const missing = data.community.value.discussion_languages.filter(
{#if !data.community.discussion_languages.every( (l) => profile.current.user?.discussion_languages.includes(l), ) && profile.current.user.discussion_languages.length > 0}
{@const missing = data.community.discussion_languages.filter(
(i) => !profile.current.user?.discussion_languages.includes(i),
)}
<Note class="p-1! pl-3! flex-col md:flex-row">
@@ -118,7 +133,7 @@
{/if}
{/if}
{#if data.community.value.community_view.blocked}
{#if data.community.community_view.blocked}
<Placeholder
icon={XMark}
title="Blocked"
@@ -134,10 +149,12 @@
{:else}
{@const SvelteComponent = browser ? VirtualFeed : PostFeed}
<SvelteComponent
posts={data.posts.posts}
bind:feedData={data}
feedId="community"
community
bind:posts={data.posts}
bind:lastSeen={
() => data.client.lastSeen ?? 0, (v) => (data.client.lastSeen = v)
}
bind:params={data.params}
virtualList={{ itemHeights: data.client?.itemHeights ?? [] }}
/>
{/if}
@@ -146,8 +163,7 @@
class="mt-auto"
>
<Pageination
page={data.page}
cursor={{ next: data.cursor.next }}
cursor={{ next: data.next_page }}
href={(page) =>
typeof page == 'number' ? `?page=${page}` : `?cursor=${page}`}
>
+35 -14
View File
@@ -1,26 +1,47 @@
import { postFeed } from '$lib/lemmy/postfeed.svelte.js'
import { settings } from '$lib/settings.svelte'
import type { SortType } from '$lib/client/types'
import { feed } from '$lib/lemmy/feeds/feed.svelte.js'
import { client } from '$lib/client/lemmy.svelte.js'
import { CommunityCard } from '$lib/components/lemmy/community'
export async function load({ params, fetch, url }) {
export async function load({ params, fetch, url, route }) {
const cursor: string | undefined = url.searchParams.get('cursor') as
| string
| undefined
const page = Number(url.searchParams.get('page')) || undefined
const sort: SortType =
(url.searchParams.get('sort') as SortType) || settings.defaultSort.sort
return await postFeed({
id: 'community',
url: url,
request: {
page: page,
page_cursor: cursor,
sort: sort,
limit: 20,
community_name: params.name,
},
fetch: fetch,
const feedData = await feed(route.id, async (p) => {
const postPromise = client({ func: fetch }).getPosts(p)
const communityPromise = client({ func: fetch }).getCommunity({
name: p.community_name,
})
return {
community: await communityPromise,
posts: (await postPromise).posts,
next_page: (await postPromise).next_page,
params: p,
client: {},
}
}).load({
community_name: params.name,
sort: sort,
limit: 20,
page_cursor: cursor,
})
return {
...feedData,
slots: {
sidebar: {
component: CommunityCard,
props: {
community_view: feedData.community.community_view,
moderators: feedData.community.moderators,
},
},
},
}
}
@@ -19,6 +19,21 @@
)
</script>
<svelte:head>
<title>{data.community.value.community_view.community.title}</title>
<meta
name="og:title"
content={data.community.value.community_view.community.title}
/>
{#if data.community.value.community_view.community.description}
<meta
name="og:description"
content={data.community.value.community_view.community.description}
/>
{/if}
</svelte:head>
<div class="flex flex-col gap-4 h-full">
<Tabs
routes={[
@@ -1,9 +1,9 @@
import { client } from '$lib/client/lemmy.svelte'
import CommunityCard from '$lib/components/lemmy/community/CommunityCard.svelte'
import { getClient } from '$lib/client/lemmy.svelte'
import { ReactiveState } from '$lib/util.svelte'
export async function load({ fetch, params }) {
const community = await getClient(undefined, fetch).getCommunity({
const community = await client({ func: fetch }).getCommunity({
name: params.name,
})
+1 -1
View File
@@ -7,7 +7,7 @@ import {
generalizePostReport,
generalizePrivateMessageReport,
type ReportView,
} from '$lib/lemmy/report.js'
} from '$lib/components/lemmy/moderation/report'
import { ReactiveState } from '$lib/util.svelte'
import { error } from '@sveltejs/kit'
+1 -1
View File
@@ -3,12 +3,12 @@
import { getClient } from '$lib/client/lemmy.svelte'
import { CommentItem } from '$lib/components/lemmy/comment'
import PrivateMessage from '$lib/components/lemmy/inbox/PrivateMessage.svelte'
import type { ReportView } from '$lib/components/lemmy/moderation/report'
import { PostItem } from '$lib/components/lemmy/post'
import UserLink from '$lib/components/lemmy/user/UserLink.svelte'
import Avatar from '$lib/components/ui/Avatar.svelte'
import { t } from '$lib/i18n/translations'
import { errorMessage } from '$lib/lemmy/error'
import type { ReportView } from '$lib/lemmy/report.js'
import { Badge, Button, Label, Material, Modal, toast } from 'mono-svelte'
import { CheckBadge } from 'svelte-hero-icons'
@@ -1,6 +1,16 @@
<script lang="ts">
import { page } from '$app/state'
import { profile } from '$lib/auth.svelte.js'
import { client } from '$lib/client/lemmy.svelte'
import {
mediaType,
parseTags,
Post,
PostActions,
postLink,
PostMedia,
PostMeta,
} from '$lib/components/lemmy/post'
import Markdown from '$lib/components/markdown/Markdown.svelte'
import EndPlaceholder from '$lib/components/ui/EndPlaceholder.svelte'
import Expandable from '$lib/components/ui/Expandable.svelte'
@@ -8,10 +18,7 @@
import { publishedToDate } from '$lib/components/util/date.js'
import FormattedNumber from '$lib/components/util/FormattedNumber.svelte'
import { t } from '$lib/i18n/translations.js'
import { client } from '$lib/client/lemmy.svelte'
import { resumables } from '$lib/lemmy/item.js'
import { postFeeds } from '$lib/lemmy/postfeed.svelte'
import { ReactiveState } from '$lib/util.svelte'
import { settings } from '$lib/settings.svelte.js'
import { Button, toast } from 'mono-svelte'
import { onMount } from 'svelte'
@@ -24,49 +31,26 @@
import { expoOut } from 'svelte/easing'
import { fly } from 'svelte/transition'
import CommentProvider from './CommentProvider.svelte'
import {
mediaType,
parseTags,
Post,
PostActions,
postLink,
PostMedia,
PostMeta,
} from '$lib/components/lemmy/post'
let { data } = $props()
onMount(() => {
data.meta.then((i) => data.post == i.post_view)
resumables.add({
name: data.post.value.post_view.post.name,
name: data.post.post.name,
type: 'post',
url: page.url.toString(),
avatar: data.post.value.post_view.post.thumbnail_url,
avatar: data.post.post.thumbnail_url,
})
if (
!(data.post.value.post_view.read && settings.markPostsAsRead) &&
profile.current?.jwt
) {
if (!(data.post.read && settings.markPostsAsRead) && profile.current?.jwt) {
client()
.markPostAsRead({
read: true,
post_ids: [data.post.value.post_view.post.id],
post_ids: [data.post.post.id],
})
.then(() => (data.post.value.post_view.read = true))
}
})
$effect(() => {
data.post.value.meta.then(
(res) => (data.post.value.post_view = res.post_view),
)
})
$effect(() => {
if (data.cachedFeed && data.post.value.post_view) {
const { id, index } = data.cachedFeed!
postFeeds.value[id].data.posts.posts[index] = data.post.value.post_view
.then(() => (data.post.read = true))
}
})
@@ -74,59 +58,48 @@
async function reloadComments() {
loading = true
data.comments.value = client().getComments({
page: 1,
limit: 25,
type_: 'All',
post_id: data.post.value.post_view.post.id,
sort: settings.defaultSort.comments,
max_depth: data.post.value.post_view.counts.comments > 100 ? 1 : 3,
})
data.comments = client()
.getComments({
page: 1,
limit: 25,
type_: 'All',
post_id: data.post.post.id,
sort: settings.defaultSort.comments,
max_depth: data.post.counts.comments > 100 ? 1 : 3,
})
.then((i) => i.comments)
loading = false
data.thread.value.singleThread = false
data.thread.singleThread = false
}
</script>
<svelte:head>
<title>
{data.post.value.post_view.community.title} | {data.post.value.post_view
.post.name}
{data.post.community.title} | {data.post.post.name}
</title>
<meta property="og:title" content={data.post.value.post_view.post.name} />
{#if !data.post.value.post_view.post.local}
<meta property="og:title" content={data.post.post.name} />
{#if !data.post.post.local}
<meta name="robots" content="noindex, follow" />
{/if}
<link rel="canonical" href={data.post.value.post_view.post.ap_id} />
{#if data.post.value.post_view.post.body}
<meta
property="description"
content={data.post.value.post_view.post.body.slice(0, 500)}
/>
<link rel="canonical" href={data.post.post.ap_id} />
{#if data.post.post.body}
<meta property="description" content={data.post.post.body.slice(0, 500)} />
<meta
property="og:description"
content={data.post.value.post_view.post.body.slice(0, 500)}
content={data.post.post.body.slice(0, 500)}
/>
<meta
property="twitter:description"
content={data.post.value.post_view.post.body.slice(0, 500)}
content={data.post.post.body.slice(0, 500)}
/>
{/if}
<meta property="og:url" content={page.url.toString()} />
{#if mediaType(data.post.value.post_view.post.url) == 'image'}
<meta property="og:image" content={data.post.value.post_view.post.url} />
<meta
property="twitter:card"
content={data.post.value.post_view.post.url}
/>
{:else if data.post.value.post_view.post.thumbnail_url}
<meta
property="og:image"
content={data.post.value.post_view.post.thumbnail_url}
/>
<meta
property="twitter:card"
content={data.post.value.post_view.post.thumbnail_url}
/>
{#if mediaType(data.post.post.url) == 'image'}
<meta property="og:image" content={data.post.post.url} />
<meta property="twitter:card" content={data.post.post.url} />
{:else if data.post.post.thumbnail_url}
<meta property="og:image" content={data.post.post.thumbnail_url} />
<meta property="twitter:card" content={data.post.post.thumbnail_url} />
{/if}
</svelte:head>
@@ -134,54 +107,52 @@
<header class="flex flex-col gap-2">
<div class="flex flex-row items-center gap-2 flex-wrap">
<PostMeta
community={data.post.value.post_view.community}
user={data.post.value.post_view.creator}
community={data.post.community}
user={data.post.creator}
subscribed={profile.current.user?.follows.find(
(i) => i.community.id == data.post.value.post_view.community.id,
(i) => i.community.id == data.post.community.id,
)
? 'Subscribed'
: 'NotSubscribed'}
badges={{
deleted: data.post.value.post_view.post.deleted,
removed: data.post.value.post_view.post.removed,
locked: data.post.value.post_view.post.locked,
deleted: data.post.post.deleted,
removed: data.post.post.removed,
locked: data.post.post.locked,
featured:
data.post.value.post_view.post.featured_community ||
data.post.value.post_view.post.featured_local,
nsfw: data.post.value.post_view.post.nsfw,
saved: data.post.value.post_view.saved,
admin: data.post.value.post_view.creator_is_admin,
moderator: data.post.value.post_view.creator_is_moderator,
data.post.post.featured_community || data.post.post.featured_local,
nsfw: data.post.post.nsfw,
saved: data.post.saved,
admin: data.post.creator_is_admin,
moderator: data.post.creator_is_moderator,
}}
published={publishedToDate(data.post.value.post_view.post.published)}
edited={data.post.value.post_view.post.updated}
title={data.post.value.post_view.post.name}
published={publishedToDate(data.post.post.published)}
edited={data.post.post.updated}
title={data.post.post.name}
style="width: max-content;"
tags={parseTags(data.post.value.post_view.post.name).tags}
tags={parseTags(data.post.post.name).tags}
/>
</div>
<h1 class="font-medium text-xl leading-5">
<Markdown
source={parseTags(data.post.value.post_view.post.name).title ??
data.post.value.post_view.post.name}
source={parseTags(data.post.post.name).title ?? data.post.post.name}
inline
/>
</h1>
</header>
<PostMedia
type={mediaType(data.post.value.post_view.post.url)}
post={data.post.value.post_view.post}
type={mediaType(data.post.post.url)}
post={data.post.post}
opened
view="cozy"
/>
{#if data.post.value.post_view.post.body}
{#if data.post.post.body}
<div class="text-base text-slate-800 dark:text-zinc-300 leading-normal">
<Markdown source={data.post.value.post_view.post.body} />
<Markdown source={data.post.post.body} />
</div>
{/if}
<div class="w-full relative">
<PostActions
post={data.post.value.post_view}
bind:post={data.post}
onedit={() =>
toast({
content: 'The post was edited successfully.',
@@ -189,7 +160,7 @@
})}
/>
</div>
{#await data.post.value.meta then meta}
{#await data.meta then meta}
{@const crossposts = meta.cross_posts}
{#if crossposts?.length > 0}
<Expandable class="text-base mt-2 w-full cursor-pointer">
@@ -216,8 +187,8 @@
{/if}
{/await}
</article>
{#await data.comments.value then comments}
{#if data.thread.value.showContext || data.thread.value.singleThread}
{#await data.comments then comments}
{#if data.thread.showContext || data.thread.singleThread}
<div
class="sticky mx-auto z-50 max-w-md min-w-0 flex flex-col items-center overflow-auto gap-1
bg-slate-50/50 dark:bg-zinc-900/50 backdrop-blur-xl border border-slate-200/50 dark:border-zinc-800/50
@@ -228,17 +199,17 @@
rounding="pill"
{loading}
disabled={loading}
href={data.thread.value.showContext
href={data.thread.showContext
? `/comment/${
// split first comment path to get 5 before
comments.comments[0].comment.path.split('.').slice(-5)[1]
comments[0].comment.path.split('.').slice(-5)[1]
}`
: data.thread.value.singleThread
? postLink(data.post.value.post_view.post)
: data.thread.singleThread
? postLink(data.post.post)
: undefined}
class="hover:bg-white/50 dark:hover:bg-zinc-800/30"
>
{data.thread.value.showContext
{data.thread.showContext
? $t('routes.post.thread.context')
: $t('routes.post.thread.allComments')}
{#snippet suffix()}
@@ -254,7 +225,7 @@
{$t('routes.post.commentCount')}
{#snippet action()}
<span class="font-bold">
<FormattedNumber number={data.post.value.post_view.counts.comments} />
<FormattedNumber number={data.post.counts.comments} />
</span>
{/snippet}
</EndPlaceholder>
@@ -266,7 +237,7 @@
</Button>
</noscript>
{/if}
{#await data.comments.value}
{#await data.comments}
<div class="flex flex-col gap-4">
{#each new Array(10) as _, index}
{_}
@@ -286,17 +257,16 @@
</div>
{/each}
</div>
{:then passedComments}
{@const comments = new ReactiveState(passedComments)}
{:then comments}
<CommentProvider
comments={comments.value}
post={data.post.value.post_view}
focus={data.thread.value.focus}
{comments}
post={data.post}
focus={data.thread.focus}
onupdate={reloadComments}
bind:sort={data.commentSort.value}
bind:sort={data.params.comments.sort}
virtualize={!page.url.searchParams.get('noVirtualize')}
/>
{#if comments.value.comments.length == 0}
{#if comments.length == 0}
<Placeholder
icon={ChatBubbleLeftRight}
title={$t('routes.post.emptyComments.title')}
@@ -304,13 +274,12 @@
></Placeholder>
{/if}
{/await}
{#if data.post.value.post_view.counts.comments > 5}
{#if data.post.counts.comments > 5}
<EndPlaceholder>
{$t('routes.post.commentCount')}
{#snippet action()}
<span class="text-black dark:text-white font-bold">
{data.post.value.post_view.counts.comments}
{data.post.counts.comments}
</span>
<Button
color="tertiary"
@@ -1,27 +1,10 @@
import { resolveRoute } from '$app/paths'
import { profile } from '$lib/auth.svelte.js'
import CommunityCard from '$lib/components/lemmy/community/CommunityCard.svelte'
import { client } from '$lib/client/lemmy.svelte'
import { postFeeds } from '$lib/lemmy/postfeed.svelte.js'
import { ReactiveState, awaitIfServer } from '$lib/util.svelte.js'
import CommunityCard from '$lib/components/lemmy/community/CommunityCard.svelte'
import { feed } from '$lib/lemmy/feeds/feed.svelte.js'
import { settings } from '$lib/settings.svelte'
import { redirect } from '@sveltejs/kit'
import type {
GetComments,
PostView,
CommunityModeratorView,
CommunityView,
} from '$lib/client/types'
interface PartialPost {
post_view: PostView
meta: Promise<{
community_view: CommunityView
moderators: Array<CommunityModeratorView>
cross_posts: Array<PostView>
post_view: PostView
}>
}
function buildContext(thread?: string) {
let parentId: number | undefined
@@ -42,34 +25,18 @@ function buildContext(thread?: string) {
return { parentId, showContext, max_depth, focus: thread?.split('.').at(-1) }
}
function findInFeed(
postId: number,
feedId: 'main' | 'community',
):
| {
post_view: PostView
feedData?: {
id: 'main' | 'community'
index: number
}
}
| undefined {
const index = postFeeds.value[feedId]?.data.posts.posts.findIndex(
(i) => i.post.id == postId,
)
if ((index ?? -1) == -1) return
return {
post_view: postFeeds.value[feedId]?.data.posts.posts[index],
feedData: {
id: feedId,
index: index,
},
}
function findInFeed(id: '/' | '/c/[name]', postId: string) {
return feed(id, async (p) => ({
// this will never run
...(await client().getPosts(p)),
client: {},
params: p,
}))
.peek()
?.posts.find((i) => i.post.id.toString() == postId)
}
export async function load({ params, url, fetch }) {
export async function load({ params, url, route }) {
if (profile.current.instance != params.instance)
redirect(302, resolveRoute('/post/[instance]/[id]/confirm', params))
@@ -77,8 +44,7 @@ export async function load({ params, url, fetch }) {
const sort = settings?.defaultSort?.comments ?? 'Hot'
const cachedPost =
findInFeed(Number(params.id), 'main') ??
findInFeed(Number(params.id), 'community')
findInFeed('/', params.id) ?? findInFeed('/c/[name]', params.id)
const {
parentId,
@@ -86,47 +52,53 @@ export async function load({ params, url, fetch }) {
focus,
max_depth: passedMaxDepth,
} = buildContext(url.searchParams.get('thread') || undefined)
const max_depth = passedMaxDepth
const max_depth =
(cachedPost?.post_view.counts.comments ?? 0) > 100 ? 1 : passedMaxDepth
const commentParams: GetComments = {
post_id: Number(params.id),
type_: 'All',
max_depth: max_depth,
saved_only: false,
sort: sort,
parent_id: parentId,
}
const feedData = feed(route.id, async (p) => {
const commentPromise = client().getComments(p.comments)
const postPromise = client().getPost(p.posts)
const comments = client({ func: fetch }).getComments(commentParams)
const post = client({ func: fetch }).getPost({
id: Number(params.id),
const post = p.preload ?? (await postPromise).post_view
return {
post: post,
comments: commentPromise.then((i) => i.comments),
meta: postPromise.then((i) => ({
community_view: i.community_view,
cross_posts: i.cross_posts,
post_view: i.post_view,
})),
thread: {
showContext,
focus,
singleThread: parentId != null,
},
params: p,
}
})
const partialPost: PartialPost = {
post_view: cachedPost ? cachedPost.post_view : (await post).post_view,
meta: post.then((i) => ({
...i,
})),
}
const loaded = await feedData.load({
comments: {
post_id: Number(params.id),
type_: 'All',
max_depth: max_depth,
saved_only: false,
sort: sort,
parent_id: parentId,
},
posts: { id: Number(params.id) },
preload: cachedPost,
})
return {
thread: new ReactiveState({
showContext: showContext,
singleThread: parentId != undefined,
focus,
}),
post: new ReactiveState(partialPost),
commentSort: new ReactiveState(sort),
comments: new ReactiveState((await awaitIfServer(comments)).data),
...loaded,
slots: {
sidebar: {
component: CommunityCard,
props: {
community_view: post.then((i) => i.community_view),
community_view: loaded.meta.then((i) => i.community_view),
},
},
},
cachedFeed: cachedPost?.feedData,
}
}
@@ -2,14 +2,20 @@
import { browser } from '$app/environment'
import { page } from '$app/state'
import { profile } from '$lib/auth.svelte'
import type {
CommentSortType,
CommentView,
PostView,
} from '$lib/client/types'
import {
buildCommentsTree,
CommentForm,
CommentListVirtualizer,
CommentTree,
} from '$lib/components/lemmy/comment'
import EndPlaceholder from '$lib/components/ui/EndPlaceholder.svelte'
import { t } from '$lib/i18n/translations'
import { settings } from '$lib/settings.svelte'
import type {
CommentSortType,
GetCommentsResponse,
PostView,
} from '$lib/client/types'
import { Button, Option, Select } from 'mono-svelte'
import { onMount } from 'svelte'
import {
@@ -22,16 +28,10 @@
Star,
Trophy,
} from 'svelte-hero-icons'
import {
buildCommentsTree,
CommentForm,
CommentListVirtualizer,
CommentTree,
} from '$lib/components/lemmy/comment'
interface Props {
post: PostView
comments: GetCommentsResponse
comments: CommentView[]
sort?: CommentSortType
onupdate?: () => void
focus?: string
@@ -48,9 +48,9 @@
}: Props = $props()
let commenting = $state(false)
let tree = $state(buildCommentsTree(comments.comments))
let tree = $state(buildCommentsTree(comments))
$effect(() => {
tree = buildCommentsTree(comments.comments)
tree = buildCommentsTree(comments)
})
onMount(() => {
@@ -116,7 +116,7 @@
<CommentForm
postId={post.post.id}
oncomment={(comment) => {
comments.comments.unshift(comment.comment_view)
comments.unshift(comment.comment_view)
}}
onfocus={() => (commenting = true)}
tools={commenting}
+22 -11
View File
@@ -1,20 +1,31 @@
<script lang="ts">
import { browser } from '$app/environment'
import { PostFeed, VirtualFeed } from '$lib/components/lemmy/post'
import { Header } from '$lib/components/ui/layout'
import { CommentItem } from '$lib/components/lemmy/comment'
import { PostItem } from '$lib/components/lemmy/post'
import Fixate from '$lib/components/ui/generic/Fixate.svelte'
import { CommonList, Header, Pageination } from '$lib/components/ui/layout'
import { t } from '$lib/i18n/translations.js'
import { isCommentView } from '$lib/lemmy/item.js'
let { data = $bindable() } = $props()
const SvelteComponent = $derived(browser ? VirtualFeed : PostFeed)
</script>
<Header>
<Header pageHeader>
{data.upvoted ? $t('routes.profile.upvoted') : $t('routes.profile.downvoted')}
</Header>
<SvelteComponent
posts={data.feed.posts.posts}
bind:feedData={data.feed}
feedId="main"
/>
<CommonList items={data.items}>
{#snippet item(item)}
{#if isCommentView(item)}
<CommentItem comment={item} />
{:else if !isCommentView(item)}
<PostItem post={item} />
{/if}
{/snippet}
</CommonList>
<Fixate placement="bottom">
<Pageination
bind:page={data.filters.value.page}
href={(page) => `?page=${page}`}
/>
</Fixate>
+34 -13
View File
@@ -1,23 +1,44 @@
import { postFeed } from '$lib/lemmy/postfeed.svelte.js'
import { client } from '$lib/client/lemmy.svelte.js'
import { getItemPublished } from '$lib/lemmy/item.js'
import { ReactiveState } from '$lib/util.svelte.js'
import { error } from '@sveltejs/kit'
export async function load({ url, params, fetch }) {
export async function load({ url, params }) {
if (params.type.toLowerCase() != 'up' && params.type.toLowerCase() != 'down')
error(404)
const upvoted = params.type.toLowerCase() == 'up'
const page = Number(url.searchParams.get('page')) || 1
const upvoted = params.type == 'up'
const data = await Promise.all([
client().getPosts({
liked_only: upvoted,
disliked_only: !upvoted,
page: page,
sort: 'New',
type_: 'All',
limit: 20,
}),
client().getComments({
liked_only: upvoted,
disliked_only: !upvoted,
page: page,
sort: 'New',
type_: 'All',
limit: 20,
}),
])
const everything = [...data[0].posts, ...data[1].comments].sort(
(a, b) => Date.parse(getItemPublished(b)) - Date.parse(getItemPublished(a)),
)
return {
feed: await postFeed({
id: 'votes',
request: {
sort: 'New',
liked_only: upvoted || undefined,
disliked_only: !upvoted || undefined,
},
url: url,
fetch: fetch,
}),
items: everything,
upvoted: upvoted,
filters: new ReactiveState({
page: page,
}),
}
}
-7
View File
@@ -9,7 +9,6 @@
import { settings } from '$lib/settings.svelte'
import { Button, Option, Select } from 'mono-svelte'
import {
ArrowPath,
ArrowsPointingOut,
ArrowsRightLeft,
ArrowsUpDown,
@@ -263,12 +262,6 @@
<Option value="browser">Browser</Option>
</Select>
</Setting>
<ToggleSetting
icon={ArrowPath}
bind:checked={settings.randomPlaceholders}
title={$t('settings.app.placeholders.title')}
description={$t('settings.app.placeholders.description')}
/>
<ToggleSetting
icon={ArrowsPointingOut}
bind:checked={settings.expandImages}