Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "blacksky.community",
"version": "1.127.1",
"version": "1.128.0",
"private": true,
"packageManager": "pnpm@11.7.0",
"engines": {
Expand Down
90 changes: 90 additions & 0 deletions src/state/queries/__tests__/community-timeline-sort.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import {type BskyAgent} from '@atproto/api'

jest.mock('@atproto/api', () => ({
...jest.requireActual('@atproto/api'),
jsonToLex: (value: unknown) => value,
}))
jest.mock('#/state/session', () => ({useAgent: jest.fn()}))
jest.mock('#/state/preferences/moderation-opts', () => ({
useModerationOpts: jest.fn(),
}))
jest.mock('#/state/queries/preferences', () => ({
usePreferencesQuery: jest.fn(),
}))

import {
fetchCommunityTimelinePage,
TIMELINE_RQKEY,
TIMELINE_RQKEY_ROOT,
} from '../community-feed'

function mockAgent() {
const fetchHandler = jest.fn<Promise<Response>, [string, RequestInit]>()
fetchHandler.mockResolvedValue(
new Response(JSON.stringify({cursor: 'next', feed: []})),
)
return {agent: {fetchHandler} as unknown as BskyAgent, fetchHandler}
}

function requestedParams(
fetchHandler: jest.Mock<Promise<Response>, [string, RequestInit]>,
) {
const path = fetchHandler.mock.calls[0][0]
return new URL(path, 'https://example.test').searchParams
}

describe('fetchCommunityTimelinePage', () => {
it('sends the same request as before for the recent sort', async () => {
const {agent, fetchHandler} = mockAgent()

await fetchCommunityTimelinePage(agent, {limit: 30, sort: 'recent'})

const params = requestedParams(fetchHandler)
expect(params.get('limit')).toBe('30')
expect(params.has('sort')).toBe(false)
expect(params.has('cursor')).toBe(false)
})

it('sends the hot sort together with its cursor', async () => {
const {agent, fetchHandler} = mockAgent()

await fetchCommunityTimelinePage(agent, {
limit: 30,
cursor: '2026-09-03T00:00:00.000Z::123::bafycid',
sort: 'hot',
})

const params = requestedParams(fetchHandler)
expect(params.get('sort')).toBe('hot')
expect(params.get('cursor')).toBe('2026-09-03T00:00:00.000Z::123::bafycid')
})

it('returns the page cursor', async () => {
const {agent} = mockAgent()

const page = await fetchCommunityTimelinePage(agent, {
limit: 30,
sort: 'hot',
})

expect(page.cursor).toBe('next')
expect(page.feed).toEqual([])
})

it('throws on a non-2xx response', async () => {
const {agent, fetchHandler} = mockAgent()
fetchHandler.mockResolvedValue(new Response('{}', {status: 500}))

await expect(
fetchCommunityTimelinePage(agent, {limit: 30, sort: 'recent'}),
).rejects.toThrow('getCommunityTimeline failed: 500')
})
})

describe('TIMELINE_RQKEY', () => {
it('keys each sort separately under the shared root', () => {
expect(TIMELINE_RQKEY()).toEqual([TIMELINE_RQKEY_ROOT, 'recent'])
expect(TIMELINE_RQKEY('hot')).toEqual([TIMELINE_RQKEY_ROOT, 'hot'])
expect(TIMELINE_RQKEY('hot')).not.toEqual(TIMELINE_RQKEY('recent'))
})
})
77 changes: 48 additions & 29 deletions src/state/queries/community-feed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,13 @@ type RQPageParam = string | undefined
export const RQKEY_ROOT = 'community-feed'
export const RQKEY = (actor: string) => [RQKEY_ROOT, actor]

const TIMELINE_RQKEY_ROOT = 'community-timeline'
export const TIMELINE_RQKEY = () => [TIMELINE_RQKEY_ROOT]
export type CommunityTimelineSort = 'recent' | 'hot'

export const TIMELINE_RQKEY_ROOT = 'community-timeline'
export const TIMELINE_RQKEY = (sort: CommunityTimelineSort = 'recent') => [
TIMELINE_RQKEY_ROOT,
sort,
]

// Server returns feedViewPost format with hydrated posts
// Support both old 'posts' format (raw) and new 'feed' format (hydrated)
Expand Down Expand Up @@ -93,7 +98,36 @@ export function useCommunityFeedQuery(actor: string | undefined) {
* Query for the global community timeline (all community posts).
* Used on the Home screen Community tab.
*/
export function useCommunityTimelineQuery(enabled: boolean) {
export async function fetchCommunityTimelinePage(
agent: BskyAgent,
{
limit,
cursor,
sort,
}: {limit: number; cursor?: string; sort: CommunityTimelineSort},
) {
const params: Record<string, string> = {limit: String(limit)}
if (cursor) {
params.cursor = cursor
}
if (sort !== 'recent') {
params.sort = sort
}
const res = await communityXrpc(
agent,
'community.blacksky.feed.getCommunityTimeline',
{params},
)
if (!res.ok) {
throw new Error(`getCommunityTimeline failed: ${res.status}`)
}
return toSpaceFeedPage(jsonToLex(await res.json()))
}

export function useCommunityTimelineQuery(
enabled: boolean,
sort: CommunityTimelineSort = 'recent',
) {
const agent = useAgent()
return useInfiniteQuery<
CommunityFeedPage,
Expand All @@ -102,23 +136,13 @@ export function useCommunityTimelineQuery(enabled: boolean) {
QueryKey,
RQPageParam
>({
queryKey: TIMELINE_RQKEY(),
async queryFn({pageParam}: {pageParam: RQPageParam}) {
const params: Record<string, string> = {
limit: String(PAGE_SIZE),
}
if (pageParam) {
params.cursor = pageParam
}
const res = await communityXrpc(
agent,
'community.blacksky.feed.getCommunityTimeline',
{params},
)
if (!res.ok) {
throw new Error(`getCommunityTimeline failed: ${res.status}`)
}
return toSpaceFeedPage(jsonToLex(await res.json()))
queryKey: TIMELINE_RQKEY(sort),
queryFn({pageParam}: {pageParam: RQPageParam}) {
return fetchCommunityTimelinePage(agent, {
limit: PAGE_SIZE,
cursor: pageParam,
sort,
})
},
initialPageParam: undefined,
getNextPageParam: lastPage => lastPage.cursor,
Expand All @@ -138,15 +162,10 @@ export function useCommunityTimelineQuery(enabled: boolean) {
export async function fetchCommunityTimelineHead(
agent: BskyAgent,
): Promise<AppBskyFeedDefs.FeedViewPost | undefined> {
const res = await communityXrpc(
agent,
'community.blacksky.feed.getCommunityTimeline',
{params: {limit: '10'}},
)
if (!res.ok) {
throw new Error(`getCommunityTimeline failed: ${res.status}`)
}
const page = toSpaceFeedPage(jsonToLex(await res.json()))
const page = await fetchCommunityTimelinePage(agent, {
limit: 10,
sort: 'recent',
})
return page.feed.find(surfacesInCommunityFeed)
}

Expand Down
4 changes: 2 additions & 2 deletions src/state/queries/peer-mod-label.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {communityXrpc} from '#/lib/api/community'
import {
COMMUNITY_POST_RQKEY,
RQKEY_ROOT as COMMUNITY_FEED_RQKEY_ROOT,
TIMELINE_RQKEY,
TIMELINE_RQKEY_ROOT,
} from '#/state/queries/community-feed'
import {useAgent} from '#/state/session'
import {BLACKSKY_LABELER} from '#/state/session/additional-moderation-authorities'
Expand Down Expand Up @@ -133,7 +133,7 @@ function useInvalidateLabelState() {
void queryClient.invalidateQueries({
queryKey: COMMUNITY_POST_RQKEY(subjectUri),
})
void queryClient.invalidateQueries({queryKey: TIMELINE_RQKEY()})
void queryClient.invalidateQueries({queryKey: [TIMELINE_RQKEY_ROOT]})
void queryClient.invalidateQueries({
queryKey: [COMMUNITY_FEED_RQKEY_ROOT],
})
Expand Down
12 changes: 12 additions & 0 deletions src/storage/hooks/community-feed-sort.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import {useSession} from '#/state/session'
import {account, useStorage} from '#/storage'

export function useCommunityFeedSort() {
const {currentAccount} = useSession()
const [sort = 'recent', setSort] = useStorage(account, [
currentAccount?.did ?? '',
'communityFeedSort',
])

return [sort, setSort] as const
}
5 changes: 5 additions & 0 deletions src/storage/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ export type Account = {

lastSelectedHomeFeed?: string

/**
* Sort order for the Home screen's Community tab.
*/
communityFeedSort?: 'recent' | 'hot'

/**
* Recently selected GIFs in the GIF picker. Most recent first, capped at 20.
*/
Expand Down
55 changes: 49 additions & 6 deletions src/view/com/feeds/CommunityFeedPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,16 @@ import {logger} from '#/logger'
import {useModerationOpts} from '#/state/preferences/moderation-opts'
import {
type CommunityFeedSlice,
type CommunityTimelineSort,
fetchCommunityTimelineHead,
TIMELINE_RQKEY,
useCommunityFeedSlices,
useCommunityTimelineQuery,
} from '#/state/queries/community-feed'
import {truncateAndInvalidate} from '#/state/queries/util'
import {useAgent, useSession} from '#/state/session'
import {CommunityFeedSortMenu} from '#/view/com/feeds/CommunityFeedSortMenu'
import {ComposerPrompt} from '#/view/com/feeds/ComposerPrompt'
import {isThreadChildAt, isThreadParentAt} from '#/view/com/posts/PostFeed'
import {PostFeedItem} from '#/view/com/posts/PostFeedItem'
import {ViewFullThread} from '#/view/com/posts/ViewFullThread'
Expand All @@ -34,6 +37,7 @@ import {useHeaderOffset} from '#/components/hooks/useHeaderOffset'
import {EditBig_Stroke2_Corner2_Rounded as EditBigIcon} from '#/components/icons/EditBig'
import {Text} from '#/components/Typography'
import {IS_NATIVE} from '#/env'
import {useCommunityFeedSort} from '#/storage/hooks/community-feed-sort'

type CommunityFeedRow =
| {
Expand Down Expand Up @@ -64,6 +68,7 @@ export function CommunityFeedPage({isPageFocused}: {isPageFocused: boolean}) {
openComposer({logContext: 'Fab'})
}, [openComposer])

const [sort, setSort] = useCommunityFeedSort()
const {
data,
isLoading,
Expand All @@ -73,7 +78,7 @@ export function CommunityFeedPage({isPageFocused}: {isPageFocused: boolean}) {
fetchNextPage,
isFetchingNextPage,
refetch,
} = useCommunityTimelineQuery(isPageFocused)
} = useCommunityTimelineQuery(isPageFocused, sort)

const feedItems = useMemo(
() => data?.pages.flatMap(page => page.feed ?? []) ?? [],
Expand Down Expand Up @@ -133,12 +138,25 @@ export function CommunityFeedPage({isPageFocused}: {isPageFocused: boolean}) {
const onRefresh = useCallback(async () => {
setIsRefreshing(true)
try {
await truncateAndInvalidate(queryClient, TIMELINE_RQKEY())
await truncateAndInvalidate(queryClient, TIMELINE_RQKEY(sort))
setHasNew(false)
} finally {
setIsRefreshing(false)
}
}, [queryClient])
}, [queryClient, sort])

const onChangeSort = useCallback(
(next: CommunityTimelineSort) => {
if (next === sort) return
setSort(next)
setHasNew(false)
scrollElRef.current?.scrollToOffset({
animated: false,
offset: -headerOffset,
})
},
[sort, setSort, headerOffset],
)

// Refetching an infinite query replays every loaded page, so doing it on
// a timer shifts content under the user's scroll position (see upstream
Expand All @@ -155,6 +173,8 @@ export function CommunityFeedPage({isPageFocused}: {isPageFocused: boolean}) {
void refetch()
return
}
// The head probe only means something in chronological order.
if (sort !== 'recent') return
const head = await fetchCommunityTimelineHead(agent)
if (!head) return
if (
Expand Down Expand Up @@ -186,8 +206,31 @@ export function CommunityFeedPage({isPageFocused}: {isPageFocused: boolean}) {
offset: -headerOffset,
})
setHasNew(false)
void truncateAndInvalidate(queryClient, TIMELINE_RQKEY())
}, [scrollElRef, headerOffset, queryClient])
void truncateAndInvalidate(queryClient, TIMELINE_RQKEY(sort))
}, [scrollElRef, headerOffset, queryClient, sort])

const renderHeader = useCallback(
() => (
<>
<HomeAppviewOutageNotice />
<View
style={[
a.flex_row,
a.align_center,
a.border_b,
t.atoms.border_contrast_low,
]}>
<View style={a.flex_1}>
<ComposerPrompt />
</View>
<View style={[a.pr_lg]}>
<CommunityFeedSortMenu sort={sort} onChange={onChangeSort} />
</View>
</View>
</>
),
[sort, onChangeSort, t],
)

const renderItem = useCallback(
({item, index}: ListRenderItemInfo<CommunityFeedRow>) => {
Expand Down Expand Up @@ -292,7 +335,7 @@ export function CommunityFeedPage({isPageFocused}: {isPageFocused: boolean}) {
data={rows}
renderItem={renderItem}
keyExtractor={keyExtractor}
ListHeaderComponent={HomeAppviewOutageNotice}
ListHeaderComponent={renderHeader}
ListEmptyComponent={renderEmpty}
ListFooterComponent={renderFooter}
onEndReached={onEndReached}
Expand Down
Loading
Loading