From b3a0f785d829c851b12266077ba0108f66645073 Mon Sep 17 00:00:00 2001 From: Chewbacca Date: Tue, 13 Dec 2022 14:42:18 -0500 Subject: [PATCH] Fix sorting of Chat List --- app/soapbox/utils/chats.ts | 7 +++++-- app/soapbox/utils/queries.ts | 23 +++++++++++++++++++---- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/app/soapbox/utils/chats.ts b/app/soapbox/utils/chats.ts index e740e6b8e..b7f0eb4ec 100644 --- a/app/soapbox/utils/chats.ts +++ b/app/soapbox/utils/chats.ts @@ -26,8 +26,11 @@ const updateChatInChatSearchQuery = (newChat: ChatPayload) => { */ const reOrderChatListItems = () => { sortQueryData(ChatKeys.chatSearch(), (chatA, chatB) => { - return compareDate(chatA.last_message?.created_at as string, chatB.last_message?.created_at as string); - }); + return compareDate( + chatA.last_message?.created_at as string, + chatB.last_message?.created_at as string, + ); + }, 'default'); }; /** diff --git a/app/soapbox/utils/queries.ts b/app/soapbox/utils/queries.ts index 263d2407b..e9d44210c 100644 --- a/app/soapbox/utils/queries.ts +++ b/app/soapbox/utils/queries.ts @@ -25,10 +25,21 @@ const deduplicateById = (entities: T[]): T[] => { return Array.from(map.values()); }; +export type SortOrder = 'reverse' | 'default' + /** Flatten paginated results into a single array. */ -const flattenPages = (queryData: InfiniteData> | undefined) => { +const flattenPages = ( + queryData: InfiniteData> | undefined, + order: SortOrder = 'reverse', +) => { const data = queryData?.pages.reduce( - (prev: T[], curr) => [...prev, ...curr.result], + (prev: T[], curr) => { + if (order === 'reverse') { + return [...curr.result, ...prev]; + } else { + return [...prev, ...curr.result]; + } + }, [], ); @@ -90,11 +101,15 @@ const paginateQueryData = (array: T[] | undefined) => { }, []); }; -const sortQueryData = (queryKey: QueryKey, comparator: (a: T, b: T) => number) => { +const sortQueryData = ( + queryKey: QueryKey, + comparator: (a: T, b: T) => number, + order: SortOrder = 'reverse', +) => { queryClient.setQueryData>>(queryKey, (prevResult) => { if (prevResult) { const nextResult = { ...prevResult }; - const flattenedQueryData = flattenPages(nextResult); + const flattenedQueryData = flattenPages(nextResult, order); const sortedQueryData = flattenedQueryData?.sort(comparator); const paginatedPages = paginateQueryData(sortedQueryData); const newPages = paginatedPages.map((page: T, idx: number) => ({