diff --git a/apps/desktop/layer/renderer/src/main.tsx b/apps/desktop/layer/renderer/src/main.tsx index 439da6cbb..283988fef 100644 --- a/apps/desktop/layer/renderer/src/main.tsx +++ b/apps/desktop/layer/renderer/src/main.tsx @@ -3,7 +3,11 @@ import "@follow/components/tailwind" import "./styles/main.css" import { IN_ELECTRON, WEB_BUILD } from "@follow/shared/constants" -import { apiClientSimpleContext, authClientSimpleContext } from "@follow/store/context" +import { + apiClientSimpleContext, + authClientSimpleContext, + queryClientSimpleContext, +} from "@follow/store/context" import { getOS } from "@follow/utils/utils" import * as React from "react" import ReactDOM from "react-dom/client" @@ -16,10 +20,12 @@ import { setAppIsReady } from "./atoms/app" import { ElECTRON_CUSTOM_TITLEBAR_HEIGHT } from "./constants" import { initializeApp } from "./initialize" import { registerAppGlobalShortcuts } from "./initialize/global-shortcuts" +import { queryClient } from "./lib/query-client" import { router } from "./router" apiClientSimpleContext.provide(apiClient) authClientSimpleContext.provide(authClient) +queryClientSimpleContext.provide(queryClient) initializeApp().finally(() => { import("./push-notification").then(({ registerWebPushNotifications }) => { diff --git a/apps/desktop/layer/renderer/src/modules/discover/FeedForm.tsx b/apps/desktop/layer/renderer/src/modules/discover/FeedForm.tsx index ab8414db5..6232ea55f 100644 --- a/apps/desktop/layer/renderer/src/modules/discover/FeedForm.tsx +++ b/apps/desktop/layer/renderer/src/modules/discover/FeedForm.tsx @@ -15,6 +15,7 @@ import { ScrollArea } from "@follow/components/ui/scroll-area/index.js" import { Switch } from "@follow/components/ui/switch/index.jsx" import { FeedViewType } from "@follow/constants" import type { EntryModelSimple, FeedAnalyticsModel, FeedModel } from "@follow/models/types" +import { invalidateEntriesQuery } from "@follow/store/entry/hooks" import { useFeedByIdOrUrl } from "@follow/store/feed/hooks" import { useCategories, useSubscriptionByFeedId } from "@follow/store/subscription/hooks" import { subscriptionSyncService } from "@follow/store/subscription/store" @@ -36,7 +37,6 @@ import { getRouteParams } from "~/hooks/biz/useRouteParams" import { useI18n } from "~/hooks/common" import { apiClient } from "~/lib/api-fetch" import { toastFetchError } from "~/lib/error-parser" -import { entries as entriesQuery } from "~/queries/entries" import { feed as feedQuery, useFeedQuery } from "~/queries/feed" import { ViewSelectorRadioGroup } from "../shared/ViewSelectorRadioGroup" @@ -250,13 +250,7 @@ const FeedInnerForm = ({ }, onSuccess: (data, variables) => { if (getGeneralSettings().hidePrivateSubscriptionsInTimeline) { - entriesQuery - .entries({ - feedId: "all", - view: Number(variables.view), - excludePrivate: true, - }) - .invalidate({ exact: true }) + invalidateEntriesQuery({ views: [Number(variables.view)] }) } if ("unread" in data) { diff --git a/apps/desktop/layer/renderer/src/modules/discover/ListForm.tsx b/apps/desktop/layer/renderer/src/modules/discover/ListForm.tsx index 94ea6c832..1dc27b409 100644 --- a/apps/desktop/layer/renderer/src/modules/discover/ListForm.tsx +++ b/apps/desktop/layer/renderer/src/modules/discover/ListForm.tsx @@ -13,6 +13,7 @@ import { LoadingCircle } from "@follow/components/ui/loading/index.jsx" import { Switch } from "@follow/components/ui/switch/index.jsx" import { FeedViewType } from "@follow/constants" import type { ListAnalyticsModel } from "@follow/models/types" +import { invalidateEntriesQuery } from "@follow/store/entry/hooks" import { useListById, usePrefetchListById } from "@follow/store/list/hooks" import type { ListModel } from "@follow/store/list/types" import { useSubscriptionByFeedId } from "@follow/store/subscription/hooks" @@ -34,7 +35,6 @@ import { useI18n } from "~/hooks/common" import { apiClient } from "~/lib/api-fetch" import { getFetchErrorMessage, toastFetchError } from "~/lib/error-parser" import { getNewIssueUrl } from "~/lib/issues" -import { entries as entriesQuery } from "~/queries/entries" import { useTOTPModalWrapper } from "../profile/hooks" import { ViewSelectorRadioGroup } from "../shared/ViewSelectorRadioGroup" @@ -224,13 +224,7 @@ const ListInnerForm = ({ }, onSuccess: (data, variables) => { if (getGeneralSettings().hidePrivateSubscriptionsInTimeline) { - entriesQuery - .entries({ - feedId: "all", - view: Number(variables.view), - excludePrivate: true, - }) - .invalidate({ exact: true }) + invalidateEntriesQuery({ views: [Number(variables.view)] }) } if ("unread" in data) { diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/hooks/useEntriesByView.ts b/apps/desktop/layer/renderer/src/modules/entry-column/hooks/useEntriesByView.ts index 2c30f8f42..b373f6479 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/hooks/useEntriesByView.ts +++ b/apps/desktop/layer/renderer/src/modules/entry-column/hooks/useEntriesByView.ts @@ -1,6 +1,7 @@ import { views } from "@follow/constants" import { useCollectionEntryList } from "@follow/store/collection/hooks" import { + useEntriesQuery, useEntryIdsByFeedId, useEntryIdsByFeedIds, useEntryIdsByInboxId, @@ -21,7 +22,7 @@ import { useGeneralSettingKey } from "~/atoms/settings/general" import { ROUTE_FEED_PENDING } from "~/constants/app" import { useRouteParams } from "~/hooks/biz/useRouteParams" import { useAuthQuery } from "~/hooks/common" -import { entries, useEntries } from "~/queries/entries" +import { entries } from "~/queries/entries" import { useIsPreviewFeed } from "./useIsPreviewFeed" @@ -45,8 +46,10 @@ const useRemoteEntries = (): UseEntriesReturn => { inboxId, listId, view, - ...(unreadOnly === true && !isPreview && { read: false }), - ...(hidePrivateSubscriptionsInTimeline === true && { excludePrivate: true }), + ...(unreadOnly === true && !isPreview && { unreadOnly: true }), + ...(hidePrivateSubscriptionsInTimeline === true && { + hidePrivateSubscriptionsInTimeline: true, + }), } if (feedId && listId && isBizId(feedId)) { @@ -64,7 +67,7 @@ const useRemoteEntries = (): UseEntriesReturn => { view, hidePrivateSubscriptionsInTimeline, ]) - const query = useEntries(entriesOptions) + const query = useEntriesQuery(entriesOptions) const [fetchedTime, setFetchedTime] = useState() useEffect(() => { @@ -155,15 +158,16 @@ const useLocalEntries = (): UseEntriesReturn => { const allEntries = useEntryStore( useCallback( (state) => { - const ids = showEntriesByView - ? (entryIdsByView ?? []) - : (getEntryIdsFromMultiplePlace( - entryIdsByCollections, - entryIdsByFeedId, - entryIdsByCategory, - entryIdsByListId, - entryIdsByInboxId, - ) ?? []) + const ids = isCollection + ? entryIdsByCollections + : showEntriesByView + ? (entryIdsByView ?? []) + : (getEntryIdsFromMultiplePlace( + entryIdsByFeedId, + entryIdsByCategory, + entryIdsByListId, + entryIdsByInboxId, + ) ?? []) return ids .map((id) => { diff --git a/apps/desktop/layer/renderer/src/modules/subscription-column/FeedCategory.tsx b/apps/desktop/layer/renderer/src/modules/subscription-column/FeedCategory.tsx index 3b30ed0a8..2eaa1fb9e 100644 --- a/apps/desktop/layer/renderer/src/modules/subscription-column/FeedCategory.tsx +++ b/apps/desktop/layer/renderer/src/modules/subscription-column/FeedCategory.tsx @@ -35,7 +35,6 @@ import { useNavigateEntry } from "~/hooks/biz/useNavigateEntry" import { getRouteParams, useRouteParamsSelector } from "~/hooks/biz/useRouteParams" import { useContextMenu } from "~/hooks/common/useContextMenu" import { createErrorToaster } from "~/lib/error-parser" -import { invalidateEntriesQuery } from "~/queries/entries" import { getPreferredTitle } from "~/store/feed/hooks" import { useModalStack } from "../../components/ui/modal/stacked/hooks" @@ -162,12 +161,6 @@ function FeedCategoryImpl({ data: ids, view, categoryOpenStateData }: FeedCatego newView: nextView, }) }, - - onSuccess(_data, variables) { - invalidateEntriesQuery({ - views: [view, variables], - }) - }, }) const [isCategoryEditing, setIsCategoryEditing] = useState(false) diff --git a/apps/desktop/layer/renderer/src/queries/entries.ts b/apps/desktop/layer/renderer/src/queries/entries.ts index 10a0773e7..50b17f172 100644 --- a/apps/desktop/layer/renderer/src/queries/entries.ts +++ b/apps/desktop/layer/renderer/src/queries/entries.ts @@ -1,61 +1,9 @@ -import type { FeedViewType } from "@follow/constants" -import { useFeedUnreadIsDirty } from "@follow/store/atoms/feed" -import { entrySyncServices } from "@follow/store/entry/store" - -import { useAuthInfiniteQuery, useAuthQuery } from "~/hooks/common" +import { useAuthQuery } from "~/hooks/common" import { apiClient } from "~/lib/api-fetch" import { defineQuery } from "~/lib/defineQuery" -import { queryClient } from "~/lib/query-client" import { getEntriesParams } from "~/lib/utils" -export function invalidateEntriesQuery({ views }: { views: FeedViewType[] }) { - return queryClient.invalidateQueries({ - predicate: (query) => { - const { queryKey } = query - if (Array.isArray(queryKey) && queryKey[0] === "entries") { - const view = queryKey[2] - return views.includes(view as FeedViewType) - } - return false - }, - }) -} - export const entries = { - entries: ({ - feedId, - inboxId, - listId, - view, - read, - excludePrivate, - limit, - }: { - feedId?: string - inboxId?: string - listId?: string - view?: number - read?: boolean - excludePrivate?: boolean - limit?: number - }) => - defineQuery( - ["entries", inboxId || listId || feedId, view, read, excludePrivate, limit], - async ({ pageParam }) => - entrySyncServices.fetchEntries({ - feedId, - inboxId, - listId, - view, - read, - excludePrivate, - limit, - pageParam: pageParam as string, - }), - { - rootKey: ["entries", inboxId || listId || feedId], - }, - ), preview: (id: string) => defineQuery( ["entries-preview", id], @@ -123,45 +71,6 @@ export const entries = { ), } -const defaultStaleTime = 10 * (60 * 1000) // 10 minutes - -export const useEntries = ({ - feedId, - inboxId, - listId, - view, - read, - excludePrivate, -}: { - feedId?: string - inboxId?: string - listId?: string - view?: number - read?: boolean - excludePrivate?: boolean -}) => { - const fetchUnread = read === false - const feedUnreadDirty = useFeedUnreadIsDirty((feedId as string) || "") - - return useAuthInfiniteQuery( - entries.entries({ feedId, inboxId, listId, view, read, excludePrivate }), - { - enabled: feedId !== undefined || inboxId !== undefined || listId !== undefined, - getNextPageParam: (lastPage) => lastPage.data?.at(-1)?.entries.publishedAt, - initialPageParam: undefined, - refetchOnWindowFocus: false, - refetchOnReconnect: false, - // DON'T refetch when the router is pop to previous page - refetchOnMount: fetchUnread && feedUnreadDirty && !history.isPop ? "always" : false, - - staleTime: - // Force refetch unread entries when feed is dirty - // HACK: disable refetch when the router is pop to previous page - history.isPop ? Infinity : fetchUnread && feedUnreadDirty ? 0 : defaultStaleTime, - }, - ) -} - export const useEntriesPreview = ({ id }: { id?: string }) => useAuthQuery(entries.preview(id!), { enabled: !!id, diff --git a/apps/desktop/layer/renderer/src/queries/feed.ts b/apps/desktop/layer/renderer/src/queries/feed.ts index 882574f15..f32ecbed5 100644 --- a/apps/desktop/layer/renderer/src/queries/feed.ts +++ b/apps/desktop/layer/renderer/src/queries/feed.ts @@ -12,8 +12,6 @@ import { apiClient } from "~/lib/api-fetch" import { defineQuery } from "~/lib/defineQuery" import { toastFetchError } from "~/lib/error-parser" -import { entries } from "./entries" - type FeedQueryParams = { id?: string; url?: string } export const feed = { @@ -76,15 +74,6 @@ export const useRefreshFeedMutation = (feedId?: string) => useMutation({ mutationKey: ["refreshFeed", feedId], mutationFn: () => apiClient.feeds.refresh.$get({ query: { id: feedId! } }), - - onSuccess() { - if (!feedId) return - entries - .entries({ - feedId: feedId!, - }) - .invalidateRoot() - }, async onError(err) { toastFetchError(err) }, @@ -99,8 +88,7 @@ export const useResetFeed = () => { toastIDRef.current = toast.loading(t("sidebar.feed_actions.resetting_feed")) await apiClient.feeds.reset.$get({ query: { id: feedId } }) }, - onSuccess: (_, feedId) => { - entries.entries({ feedId }).invalidateRoot() + onSuccess: () => { toast.success( t("sidebar.feed_actions.reset_feed_success"), toastIDRef.current ? { id: toastIDRef.current } : undefined, diff --git a/apps/mobile/src/main.tsx b/apps/mobile/src/main.tsx index 7167ada68..d812e0b82 100644 --- a/apps/mobile/src/main.tsx +++ b/apps/mobile/src/main.tsx @@ -1,6 +1,10 @@ import "./global.css" -import { apiClientSimpleContext, authClientSimpleContext } from "@follow/store/context" +import { + apiClientSimpleContext, + authClientSimpleContext, + queryClientSimpleContext, +} from "@follow/store/context" import { registerRootComponent } from "expo" import { Image } from "expo-image" import { LinearGradient } from "expo-linear-gradient" @@ -20,6 +24,7 @@ import { TabBarPortal } from "./lib/navigation/bottom-tab/TabBarPortal" import { TabRoot } from "./lib/navigation/bottom-tab/TabRoot" import { TabScreen } from "./lib/navigation/bottom-tab/TabScreen" import { RootStackNavigation } from "./lib/navigation/StackNavigation" +import { queryClient } from "./lib/query-client" import { RootProviders } from "./providers" import { IndexTabScreen } from "./screens/(stack)/(tabs)" import { DiscoverTabScreen } from "./screens/(stack)/(tabs)/discover" @@ -33,6 +38,7 @@ global.APP_NAME = "Folo" global.ELECTRON = false apiClientSimpleContext.provide(apiClient) authClientSimpleContext.provide(authClient) +queryClientSimpleContext.provide(queryClient) enableFreeze(true) ;[Image, LinearGradient].forEach((Component) => { diff --git a/apps/mobile/src/modules/context-menu/feeds.tsx b/apps/mobile/src/modules/context-menu/feeds.tsx index 5e0027469..387d2b0d1 100644 --- a/apps/mobile/src/modules/context-menu/feeds.tsx +++ b/apps/mobile/src/modules/context-menu/feeds.tsx @@ -1,9 +1,5 @@ import { FeedViewType } from "@follow/constants" -import { - getInvalidateEntriesQueryPredicate, - useEntriesQuery, - useEntryIdsByFeedId, -} from "@follow/store/entry/hooks" +import { useEntriesQuery, useEntryIdsByFeedId } from "@follow/store/entry/hooks" import { getFeedById } from "@follow/store/feed/getter" import { getSubscriptionById } from "@follow/store/subscription/getter" import { getSubscriptionCategory } from "@follow/store/subscription/hooks" @@ -24,7 +20,6 @@ import { PlatformActivityIndicator } from "@/src/components/ui/loading/PlatformA import { views } from "@/src/constants/views" import { useNavigation } from "@/src/lib/navigation/hooks" import type { Navigation } from "@/src/lib/navigation/Navigation" -import { queryClient } from "@/src/lib/query-client" import { toast } from "@/src/lib/toast" import { FollowScreen } from "@/src/screens/(modal)/FollowScreen" import { FeedScreen } from "@/src/screens/(stack)/feeds/[feedId]/FeedScreen" @@ -315,17 +310,11 @@ export const SubscriptionFeedCategoryContextMenu = ({ key={`SubContent/${view.name}`} value={isSelected} onSelect={() => { - subscriptionSyncService - .changeCategoryView({ - category, - currentView, - newView: view.view, - }) - .then(() => { - queryClient.invalidateQueries({ - predicate: getInvalidateEntriesQueryPredicate([view.view, currentView]), - }) - }) + subscriptionSyncService.changeCategoryView({ + category, + currentView, + newView: view.view, + }) }} > {t(view.name, { ns: "common" })} diff --git a/apps/mobile/src/modules/screen/atoms.ts b/apps/mobile/src/modules/screen/atoms.ts index bf576e804..2a185d890 100644 --- a/apps/mobile/src/modules/screen/atoms.ts +++ b/apps/mobile/src/modules/screen/atoms.ts @@ -234,15 +234,16 @@ function useLocalEntries(props?: UseEntriesProps): UseEntriesReturn { const allEntries = useEntryStore( useCallback( (state) => { - const ids = showEntriesByView - ? (entryIdsByView ?? []) - : (getEntryIdsFromMultiplePlace( - entryIdsByCollections, - entryIdsByFeedId, - entryIdsByCategory, - entryIdsByListId, - entryIdsByInboxId, - ) ?? []) + const ids = isCollection + ? entryIdsByCollections + : showEntriesByView + ? (entryIdsByView ?? []) + : (getEntryIdsFromMultiplePlace( + entryIdsByFeedId, + entryIdsByCategory, + entryIdsByListId, + entryIdsByInboxId, + ) ?? []) return ids .map((id) => { diff --git a/packages/internal/database/src/services/collection.ts b/packages/internal/database/src/services/collection.ts index 7ee0dab39..ea19e3821 100644 --- a/packages/internal/database/src/services/collection.ts +++ b/packages/internal/database/src/services/collection.ts @@ -11,8 +11,13 @@ class CollectionServiceStatic implements Resetable { await db.delete(collectionsTable).execute() } - async upsertMany(collections: CollectionSchema[]) { + async upsertMany(collections: CollectionSchema[], options?: { reset?: boolean }) { if (collections.length === 0) return + + if (options?.reset) { + await db.delete(collectionsTable).execute() + } + await db .insert(collectionsTable) .values(collections) @@ -26,6 +31,11 @@ class CollectionServiceStatic implements Resetable { await db.delete(collectionsTable).where(eq(collectionsTable.entryId, entryId)) } + async deleteMany(entryId: string[]) { + if (entryId.length === 0) return + await db.delete(collectionsTable).where(inArray(collectionsTable.entryId, entryId)) + } + getCollectionMany(entryId: string[]) { return db.query.collectionsTable.findMany({ where: inArray(collectionsTable.entryId, entryId) }) } diff --git a/packages/internal/store/src/collection/store.ts b/packages/internal/store/src/collection/store.ts index b997f32c9..af55bdf8c 100644 --- a/packages/internal/store/src/collection/store.ts +++ b/packages/internal/store/src/collection/store.ts @@ -4,7 +4,8 @@ import { CollectionService } from "@follow/database/services/collection" import { apiClient } from "../context" import { getEntry } from "../entry/getter" -import type { Hydratable } from "../internal/base" +import { invalidateEntriesQuery } from "../entry/hooks" +import type { Hydratable, Resetable } from "../internal/base" import { createTransaction, createZustandStore } from "../internal/helper" interface CollectionState { @@ -52,6 +53,8 @@ class CollectionSyncService { }) await tx.run() + + invalidateEntriesQuery({ collection: true }) } async unstarEntry(entryId: string) { @@ -75,20 +78,24 @@ class CollectionSyncService { }) await tx.run() + + invalidateEntriesQuery({ collection: true }) } } -class CollectionActions implements Hydratable { +class CollectionActions implements Hydratable, Resetable { async hydrate() { const collections = await CollectionService.getCollectionAll() collectionActions.upsertManyInSession(collections) } - upsertManyInSession(collections: CollectionSchema[]) { + upsertManyInSession(collections: CollectionSchema[], options?: { reset?: boolean }) { const state = get() - const nextCollections: CollectionState["collections"] = { - ...state.collections, - } + const nextCollections: CollectionState["collections"] = options?.reset + ? {} + : { + ...state.collections, + } collections.forEach((collection) => { if (!collection.entryId) return nextCollections[collection.entryId] = collection @@ -99,18 +106,18 @@ class CollectionActions implements Hydratable { }) } - async upsertMany(collections: CollectionSchema[]) { + async upsertMany(collections: CollectionSchema[], options?: { reset?: boolean }) { const tx = createTransaction() tx.store(() => { - this.upsertManyInSession(collections) + this.upsertManyInSession(collections, options) }) tx.persist(() => { - return CollectionService.upsertMany(collections) + return CollectionService.upsertMany(collections, options) }) await tx.run() } - async deleteInSession(entryId: string) { + deleteInSession(entryId: string) { const state = useCollectionStore.getState() const nextCollections: CollectionState["collections"] = { ...state.collections, @@ -133,8 +140,17 @@ class CollectionActions implements Hydratable { tx.run() } - reset() { - set(defaultState) + async reset() { + const tx = createTransaction() + tx.store(() => { + set(defaultState) + }) + + tx.persist(() => { + return CollectionService.reset() + }) + + await tx.run() } } diff --git a/packages/internal/store/src/context.ts b/packages/internal/store/src/context.ts index 403f0d526..720efea67 100644 --- a/packages/internal/store/src/context.ts +++ b/packages/internal/store/src/context.ts @@ -1,4 +1,5 @@ import type { AuthClient } from "@follow/shared/auth" +import type { QueryClient } from "@tanstack/react-query" import type { APIClient } from "./types" @@ -27,5 +28,7 @@ function createSimpleContext() { export const apiClientSimpleContext = createSimpleContext() export const authClientSimpleContext = createSimpleContext() +export const queryClientSimpleContext = createSimpleContext() export const apiClient = apiClientSimpleContext.consumer export const authClient = authClientSimpleContext.consumer +export const queryClient = queryClientSimpleContext.consumer diff --git a/packages/internal/store/src/entry/hooks.ts b/packages/internal/store/src/entry/hooks.ts index 14e830d59..dca313b5d 100644 --- a/packages/internal/store/src/entry/hooks.ts +++ b/packages/internal/store/src/entry/hooks.ts @@ -1,26 +1,48 @@ import type { FeedViewType } from "@follow/constants" -import type { Query } from "@tanstack/react-query" import { useInfiniteQuery, useQuery } from "@tanstack/react-query" import { useCallback } from "react" +import { useFeedUnreadIsDirty } from "../atoms/feed" +import { FEED_COLLECTION_LIST } from "../constants/app" +import { queryClient } from "../context" import { getSubscriptionByEntryId } from "../subscription/getter" import { getEntry } from "./getter" import { entrySyncServices, useEntryStore } from "./store" import type { EntryModel, FetchEntriesProps, FetchEntriesPropsSettings } from "./types" -export const getInvalidateEntriesQueryPredicate = (views: FeedViewType[]) => { - return (query: Query) => { - const { queryKey } = query - if (Array.isArray(queryKey) && queryKey[0] === "entries") { - const view = queryKey[4] - return views.includes(view as FeedViewType) - } - return false - } +export const invalidateEntriesQuery = ({ + views, + collection, +}: { + views?: FeedViewType[] + collection?: true +}) => { + return queryClient().invalidateQueries({ + predicate: (query) => { + const { queryKey } = query + if (Array.isArray(queryKey) && queryKey[0] === "entries") { + const feedId = queryKey[1] + const view = queryKey[4] + + const isCollection = queryKey[7] + if (views) { + return views.includes(view as FeedViewType) + } + + if (collection) { + return isCollection === true || feedId === FEED_COLLECTION_LIST + } + } + return false + }, + }) } +const defaultStaleTime = 10 * (60 * 1000) // 10 minutes + export const useEntriesQuery = ( - props?: Omit & FetchEntriesPropsSettings, + props?: Omit & + FetchEntriesPropsSettings, ) => { const { feedId, @@ -29,10 +51,17 @@ export const useEntriesQuery = ( view, limit, feedIdList, + isCollection, unreadOnly, hidePrivateSubscriptionsInTimeline, } = props || {} + const fetchUnread = unreadOnly + const feedUnreadDirty = useFeedUnreadIsDirty((feedId as string) || "") + + const isPop = + "history" in globalThis && "isPop" in globalThis.history && !!globalThis.history.isPop + return useInfiniteQuery({ queryKey: [ "entries", @@ -40,9 +69,10 @@ export const useEntriesQuery = ( inboxId, listId, view, - unreadOnly, limit, feedIdList, + isCollection, + unreadOnly, hidePrivateSubscriptionsInTimeline, ], queryFn: ({ pageParam }) => @@ -52,11 +82,18 @@ export const useEntriesQuery = ( read: unreadOnly ? false : undefined, excludePrivate: hidePrivateSubscriptionsInTimeline, }), - staleTime: 3 * 60 * 1000, + getNextPageParam: (lastPage) => lastPage.data?.at(-1)?.entries.publishedAt, initialPageParam: undefined as undefined | string, refetchOnWindowFocus: false, refetchOnReconnect: false, + // DON'T refetch when the router is pop to previous page + refetchOnMount: fetchUnread && feedUnreadDirty && !isPop ? "always" : false, + + staleTime: + // Force refetch unread entries when feed is dirty + // HACK: disable refetch when the router is pop to previous page + isPop ? Infinity : fetchUnread && feedUnreadDirty ? 0 : defaultStaleTime, enabled: !!props, }) } @@ -104,7 +141,7 @@ function sortEntryIdsByPublishDate(a: string, b: string) { return entryB.publishedAt.getTime() - entryA.publishedAt.getTime() } -export const useEntryIdsByView = (view: FeedViewType, excludePrivate: boolean) => { +export const useEntryIdsByView = (view: FeedViewType, excludePrivate: boolean | undefined) => { return useEntryStore( useCallback( (state) => { diff --git a/packages/internal/store/src/entry/store.ts b/packages/internal/store/src/entry/store.ts index 79a07adb1..830d57a32 100644 --- a/packages/internal/store/src/entry/store.ts +++ b/packages/internal/store/src/entry/store.ts @@ -489,12 +489,11 @@ class EntrySyncServices { await entryActions.upsertMany(entries) - if (isCollection && res.data) { - if (view === undefined) { - console.error("view is required for collection") - } - const collections = honoMorph.toCollections(res.data, view ?? 0) - await collectionActions.upsertMany(collections) + if (typeof view === "number") { + const collections = honoMorph.toCollections(res.data, view) + await collectionActions.upsertMany(collections, { + reset: params.isCollection && !pageParam, + }) } const dataFeeds = res.data?.map((e) => e.feeds).filter((f) => f.type === "feed") diff --git a/packages/internal/store/src/entry/types.ts b/packages/internal/store/src/entry/types.ts index 80fdd74d0..7a60b5a5e 100644 --- a/packages/internal/store/src/entry/types.ts +++ b/packages/internal/store/src/entry/types.ts @@ -16,8 +16,8 @@ export type FetchEntriesProps = { } export type FetchEntriesPropsSettings = { - hidePrivateSubscriptionsInTimeline: boolean - unreadOnly: boolean + hidePrivateSubscriptionsInTimeline?: boolean + unreadOnly?: boolean } export type UseEntriesProps = { diff --git a/packages/internal/store/src/morph/hono.ts b/packages/internal/store/src/morph/hono.ts index 49f7d9b8d..f82937ebd 100644 --- a/packages/internal/store/src/morph/hono.ts +++ b/packages/internal/store/src/morph/hono.ts @@ -146,7 +146,7 @@ class Morph { } toCollections( - data: HonoApiClient.Entry_Post | HonoApiClient.Entry_Inbox_Post, + data: HonoApiClient.Entry_Post | HonoApiClient.Entry_Inbox_Post | undefined, view: FeedViewType, ): CollectionModel[] { if (!data) return [] satisfies CollectionModel[] diff --git a/packages/internal/store/src/subscription/store.ts b/packages/internal/store/src/subscription/store.ts index 1c2ec7d7b..aa93a25e4 100644 --- a/packages/internal/store/src/subscription/store.ts +++ b/packages/internal/store/src/subscription/store.ts @@ -4,6 +4,7 @@ import { tracker } from "@follow/tracker" import { omit } from "es-toolkit" import { apiClient } from "../context" +import { invalidateEntriesQuery } from "../entry/hooks" import { getFeedById } from "../feed/getter" import { feedActions } from "../feed/store" import { inboxActions } from "../inbox/store" @@ -585,6 +586,10 @@ class SubscriptionSyncService { feedIds: folderFeedIds, view: newView, }) + + invalidateEntriesQuery({ + views: [currentView, newView], + }) } async renameCategory({