From ddd6a2c8cdf8fc6a06acd52345eb8c5b157c2e12 Mon Sep 17 00:00:00 2001 From: Stephen Zhou <38493346+hyoban@users.noreply.github.com> Date: Thu, 13 Feb 2025 18:51:39 +0800 Subject: [PATCH] feat(mobile): unread state for entry (#2730) * feat: unread state for entry * mark feed as read * fix type * feat: mark as read when entering entry detail * prefetch unread * show unread count for view * fix: use feed subscription for view unread count * fix: clean not exist subscriptions * Pre fetch subscriptions in advance * fix: add entry ids to list --- .../mobile/src/modules/context-menu/feeds.tsx | 2 +- .../src/modules/entry-list/entry-list.tsx | 1 + apps/mobile/src/modules/entry-list/index.tsx | 9 +-- .../src/modules/screen/view-selector.tsx | 8 +- .../subscription/SubscriptionLists.tsx | 2 - apps/mobile/src/morph/hono.ts | 2 +- apps/mobile/src/morph/store-db.ts | 2 +- .../src/screens/(stack)/(tabs)/_layout.tsx | 5 ++ .../(stack)/entries/[entryId]/index.tsx | 2 + apps/mobile/src/services/entry.ts | 20 ++++- apps/mobile/src/services/subscription.ts | 66 ++++++++++------ apps/mobile/src/store/entry/store.ts | 45 +++++++++-- apps/mobile/src/store/list/hooks.ts | 2 +- apps/mobile/src/store/list/store.ts | 15 +--- apps/mobile/src/store/subscription/hooks.ts | 2 +- apps/mobile/src/store/subscription/store.ts | 24 +++++- apps/mobile/src/store/unread/hooks.ts | 17 ++++- apps/mobile/src/store/unread/store.ts | 76 +++++++++++++++---- 18 files changed, 217 insertions(+), 83 deletions(-) diff --git a/apps/mobile/src/modules/context-menu/feeds.tsx b/apps/mobile/src/modules/context-menu/feeds.tsx index f8d867d3b..8d3ad2592 100644 --- a/apps/mobile/src/modules/context-menu/feeds.tsx +++ b/apps/mobile/src/modules/context-menu/feeds.tsx @@ -161,7 +161,7 @@ export const SubscriptionFeedCategoryContextMenu = ({ { - unreadSyncService.markAsReadMany(feedIds) + unreadSyncService.markFeedAsRead(feedIds) }, [feedIds])} > Mark All As Read diff --git a/apps/mobile/src/modules/entry-list/entry-list.tsx b/apps/mobile/src/modules/entry-list/entry-list.tsx index 59939b821..6f1a176f2 100644 --- a/apps/mobile/src/modules/entry-list/entry-list.tsx +++ b/apps/mobile/src/modules/entry-list/entry-list.tsx @@ -97,6 +97,7 @@ function EntryItem({ entryId }: { entryId: string }) { return ( + {!entry.read && } {title} diff --git a/apps/mobile/src/modules/entry-list/index.tsx b/apps/mobile/src/modules/entry-list/index.tsx index c4f8a510f..724cf2928 100644 --- a/apps/mobile/src/modules/entry-list/index.tsx +++ b/apps/mobile/src/modules/entry-list/index.tsx @@ -9,7 +9,7 @@ import { useEntryIdsByInboxId, useEntryIdsByView, } from "@/src/store/entry/hooks" -import { useList } from "@/src/store/list/hooks" +import { useListEntryIds } from "@/src/store/list/hooks" import { EntryListScreen } from "./entry-list" @@ -63,10 +63,9 @@ function CategoryEntryList({ categoryName }: { categoryName: string }) { } function ListEntryList({ listId }: { listId: string }) { - const list = useList(listId) - if (!list) return null - - return + const entryIds = useListEntryIds(listId) + if (!entryIds) return null + return } function InboxEntryList({ inboxId }: { inboxId: string }) { diff --git a/apps/mobile/src/modules/screen/view-selector.tsx b/apps/mobile/src/modules/screen/view-selector.tsx index c5343f90c..f328e16b1 100644 --- a/apps/mobile/src/modules/screen/view-selector.tsx +++ b/apps/mobile/src/modules/screen/view-selector.tsx @@ -12,6 +12,7 @@ import { views } from "@/src/constants/views" import { selectTimeline, useSelectedFeed } from "@/src/modules/screen/atoms" import { useList } from "@/src/store/list/hooks" import { useAllListSubscription } from "@/src/store/subscription/hooks" +import { useUnreadCountByView } from "@/src/store/unread/hooks" import { accentColor, useColor } from "@/src/theme/colors" export function ViewSelector() { @@ -74,6 +75,7 @@ function ViewItem({ view }: { view: ViewDefinition }) { const selectedFeed = useSelectedFeed() const isActive = selectedFeed?.type === "view" && selectedFeed.viewId === view.view + const unreadCount = useUnreadCountByView(view.view) return ( - {isActive && ( + {isActive ? ( - {view.name} + {view.name + (unreadCount ? ` (${unreadCount})` : "")} + ) : ( + !!unreadCount && )} ) diff --git a/apps/mobile/src/modules/subscription/SubscriptionLists.tsx b/apps/mobile/src/modules/subscription/SubscriptionLists.tsx index ad0ce9b11..046abb15c 100644 --- a/apps/mobile/src/modules/subscription/SubscriptionLists.tsx +++ b/apps/mobile/src/modules/subscription/SubscriptionLists.tsx @@ -10,7 +10,6 @@ import { TimelineSelectorList } from "@/src/modules/screen/timeline-selector-lis import { FEED_COLLECTION_LIST } from "@/src/store/entry/utils" import { useGroupedSubscription, - usePrefetchSubscription, useSortedGroupedSubscription, useSortedUngroupedSubscription, } from "@/src/store/subscription/hooks" @@ -29,7 +28,6 @@ const keyExtractor = (item: string | { category: string; subscriptionIds: string } export const SubscriptionList = ({ view }: { view: FeedViewType }) => { - usePrefetchSubscription(view) const { grouped, unGrouped } = useGroupedSubscription(view) const sortBy = useFeedListSortMethod() diff --git a/apps/mobile/src/morph/hono.ts b/apps/mobile/src/morph/hono.ts index 01e7f69e2..4256c97c5 100644 --- a/apps/mobile/src/morph/hono.ts +++ b/apps/mobile/src/morph/hono.ts @@ -128,7 +128,7 @@ class Morph { feedId: item.feeds.id, // TODO: handle inboxHandle inboxHandle: "", - read: false, + read: item.read, }) } return entries diff --git a/apps/mobile/src/morph/store-db.ts b/apps/mobile/src/morph/store-db.ts index f6ff8f190..fc2a0c69a 100644 --- a/apps/mobile/src/morph/store-db.ts +++ b/apps/mobile/src/morph/store-db.ts @@ -24,7 +24,7 @@ class StoreDbMorph { export const storeDbMorph = new StoreDbMorph() -const buildSubscriptionDbId = (subscription: SubscriptionModel) => { +export const buildSubscriptionDbId = (subscription: SubscriptionModel) => { if (subscription.feedId) return `${subscription.type}/${subscription.feedId}` if (subscription.listId) return `${subscription.type}/${subscription.listId}` if (subscription.inboxId) return `${subscription.type}/${subscription.inboxId}` diff --git a/apps/mobile/src/screens/(stack)/(tabs)/_layout.tsx b/apps/mobile/src/screens/(stack)/(tabs)/_layout.tsx index 20b22276b..ccb57eb31 100644 --- a/apps/mobile/src/screens/(stack)/(tabs)/_layout.tsx +++ b/apps/mobile/src/screens/(stack)/(tabs)/_layout.tsx @@ -25,6 +25,8 @@ import { Settings1CuteFiIcon } from "@/src/icons/settings_1_cute_fi" import { Settings1CuteReIcon } from "@/src/icons/settings_1_cute_re" import { FeedDrawer } from "@/src/modules/feed-drawer/drawer" import { setCurrentView } from "@/src/modules/subscription/atoms" +import { usePrefetchSubscription } from "@/src/store/subscription/hooks" +import { usePrefetchUnread } from "@/src/store/unread/hooks" import { useColor } from "@/src/theme/colors" const doubleTap = Gesture.Tap() @@ -40,6 +42,9 @@ const fifthTap = Gesture.Tap() }) export default function TabLayout() { + usePrefetchUnread() + usePrefetchSubscription() + const opacity = useSharedValue(1) const animatedTransformY = useAnimatedValue(1) diff --git a/apps/mobile/src/screens/(stack)/entries/[entryId]/index.tsx b/apps/mobile/src/screens/(stack)/entries/[entryId]/index.tsx index b4194de95..96850a2b3 100644 --- a/apps/mobile/src/screens/(stack)/entries/[entryId]/index.tsx +++ b/apps/mobile/src/screens/(stack)/entries/[entryId]/index.tsx @@ -26,6 +26,7 @@ import { EntryAISummary } from "@/src/modules/entry-content/EntryAISummary" import { EntryContentHeaderRightActions } from "@/src/modules/entry-content/HeaderActions" import { useEntry, usePrefetchEntryContent } from "@/src/store/entry/hooks" import { useFeed } from "@/src/store/feed/hooks" +import { useAutoMarkAsRead } from "@/src/store/unread/hooks" function Media({ media }: { media: MediaModel }) { const isVideo = media.type === "video" @@ -76,6 +77,7 @@ function Media({ media }: { media: MediaModel }) { export default function EntryDetailPage() { const { entryId } = useLocalSearchParams() usePrefetchEntryContent(entryId as string) + useAutoMarkAsRead(entryId as string) const entry = useEntry(entryId as string) const insets = useSafeAreaInsets() diff --git a/apps/mobile/src/services/entry.ts b/apps/mobile/src/services/entry.ts index 854f7515a..e6d6e95fd 100644 --- a/apps/mobile/src/services/entry.ts +++ b/apps/mobile/src/services/entry.ts @@ -1,4 +1,4 @@ -import { eq, inArray } from "drizzle-orm" +import { eq, inArray, or } from "drizzle-orm" import { db } from "../database" import { entriesTable } from "../database/schemas" @@ -28,6 +28,24 @@ class EntryServiceStatic implements Hydratable, Resetable { await db.update(entriesTable).set(entry).where(eq(entriesTable.id, entry.id)) } + async patchMany({ + entry, + entryIds, + feedIds, + }: { + entry: Partial + entryIds?: string[] + feedIds?: string[] + }) { + if (!entryIds && !feedIds) return + await db + .update(entriesTable) + .set(entry) + .where( + or(inArray(entriesTable.id, entryIds ?? []), inArray(entriesTable.feedId, feedIds ?? [])), + ) + } + getEntryMany(entryId: string[]) { return db.query.entriesTable.findMany({ where: inArray(entriesTable.id, entryId) }) } diff --git a/apps/mobile/src/services/subscription.ts b/apps/mobile/src/services/subscription.ts index 49643d98f..c45241caa 100644 --- a/apps/mobile/src/services/subscription.ts +++ b/apps/mobile/src/services/subscription.ts @@ -1,4 +1,5 @@ -import { eq, sql } from "drizzle-orm" +import type { FeedViewType } from "@follow/constants/src/enums" +import { and, eq, inArray, notInArray, sql } from "drizzle-orm" import { db } from "../database" import { feedsTable, inboxesTable, listsTable, subscriptionsTable } from "../database/schemas" @@ -43,11 +44,26 @@ class SubscriptionServiceStatic implements Hydratable, Resetable { ) } - async delete(subscription: SubscriptionSchema) { - const { id } = subscription + async deleteNotExists(existsIds: string[], view?: FeedViewType) { + const notExistsIds = await db.query.subscriptionsTable.findMany({ + where: and( + notInArray(subscriptionsTable.id, existsIds), + typeof view === "number" ? eq(subscriptionsTable.view, view) : undefined, + ), + columns: { + id: true, + }, + }) + if (notExistsIds.length === 0) return - const result = await db.query.subscriptionsTable.findFirst({ - where: eq(subscriptionsTable.id, id), + this.delete(notExistsIds.map((s) => s.id)) + } + + async delete(id: string | string[]) { + const ids = Array.isArray(id) ? id : [id] + + const results = await db.query.subscriptionsTable.findMany({ + where: inArray(subscriptionsTable.id, ids), columns: { feedId: true, listId: true, @@ -56,29 +72,29 @@ class SubscriptionServiceStatic implements Hydratable, Resetable { }, }) - await db.delete(subscriptionsTable).where(eq(subscriptionsTable.id, id)).execute() + await db.delete(subscriptionsTable).where(inArray(subscriptionsTable.id, ids)).execute() - if (!result) { - return - } + if (!results || results.length === 0) return // Cleanup - const { type, feedId, listId, inboxId } = result - switch (type) { - case "feed": { - if (!feedId) break - await db.delete(feedsTable).where(eq(feedsTable.id, feedId)).execute() - break - } - case "list": { - if (!listId) break - await db.delete(listsTable).where(eq(listsTable.id, listId)).execute() - break - } - case "inbox": { - if (!inboxId) break - await db.delete(inboxesTable).where(eq(inboxesTable.id, inboxId)).execute() - break + for (const result of results) { + const { type, feedId, listId, inboxId } = result + switch (type) { + case "feed": { + if (!feedId) break + await db.delete(feedsTable).where(eq(feedsTable.id, feedId)).execute() + break + } + case "list": { + if (!listId) break + await db.delete(listsTable).where(eq(listsTable.id, listId)).execute() + break + } + case "inbox": { + if (!inboxId) break + await db.delete(inboxesTable).where(eq(inboxesTable.id, inboxId)).execute() + break + } } } } diff --git a/apps/mobile/src/store/entry/store.ts b/apps/mobile/src/store/entry/store.ts index fde5d36bd..6ce61d66b 100644 --- a/apps/mobile/src/store/entry/store.ts +++ b/apps/mobile/src/store/entry/store.ts @@ -27,6 +27,7 @@ interface EntryState { entryIdByCategory: Record> entryIdByFeed: Record> entryIdByInbox: Record> + entryIdSet: Set } const defaultState: EntryState = { @@ -42,6 +43,7 @@ const defaultState: EntryState = { entryIdByCategory: {}, entryIdByFeed: {}, entryIdByInbox: {}, + entryIdSet: new Set(), } export const useEntryStore = createZustandStore("entry")(() => defaultState) @@ -65,14 +67,6 @@ class EntryActions { if (typeof subscription?.view === "number") { draft.entryIdByView[subscription.view].add(entryId) } - if (subscription?.category) { - const entryIdSetByCategory = draft.entryIdByCategory[subscription.category] - if (!entryIdSetByCategory) { - draft.entryIdByCategory[subscription.category] = new Set([entryId]) - } else { - entryIdSetByCategory.add(entryId) - } - } } private addEntryIdToCategory({ @@ -137,6 +131,7 @@ class EntryActions { immerSet((draft) => { for (const entry of entries) { + draft.entryIdSet.add(entry.id) draft.data[entry.id] = entry const { feedId, inboxHandle } = entry @@ -209,6 +204,40 @@ class EntryActions { await tx.run() } + markEntryReadStatusInSession({ + entryIds, + feedIds, + read, + }: { + entryIds?: EntryId[] + feedIds?: FeedId[] + read: boolean + }) { + immerSet((draft) => { + if (entryIds) { + for (const entryId of entryIds) { + const entry = draft.data[entryId] + if (entry) { + entry.read = read + } + } + } + + if (feedIds) { + const entries = Array.from(draft.entryIdSet) + .map((id) => draft.data[id]) + .filter( + (entry): entry is EntryModel => + !!entry && !!entry.feedId && feedIds.includes(entry.feedId), + ) + + for (const entry of entries) { + entry.read = read + } + } + }) + } + resetByView({ view, entries }: { view?: FeedViewType; entries: EntryModel[] }) { if (view === undefined) return immerSet((draft) => { diff --git a/apps/mobile/src/store/list/hooks.ts b/apps/mobile/src/store/list/hooks.ts index 583344fd5..4b75951da 100644 --- a/apps/mobile/src/store/list/hooks.ts +++ b/apps/mobile/src/store/list/hooks.ts @@ -18,7 +18,7 @@ export const useIsOwnList = (id: string) => { export const useListEntryIds = (id: string) => { return useListStore((state) => { - return state.lists[id]?.entryIds || [] + return state.lists[id]?.entryIds }) } diff --git a/apps/mobile/src/store/list/store.ts b/apps/mobile/src/store/list/store.ts index 20a4bb671..e993d4668 100644 --- a/apps/mobile/src/store/list/store.ts +++ b/apps/mobile/src/store/list/store.ts @@ -51,17 +51,10 @@ class ListActions { } addEntryIdsInSession(params: { listId: string; entryIds: string[] }) { - const state = get() - const list = state.lists[params.listId] - - if (!list) return - - set({ - ...state, - lists: { - ...state.lists, - [params.listId]: { ...list, feedIds: [...list.feedIds, ...params.entryIds] }, - }, + immerSet((draft) => { + const list = draft.lists[params.listId] + if (!list) return + list.entryIds = [...new Set([...(list.entryIds ?? []), ...params.entryIds])] }) } diff --git a/apps/mobile/src/store/subscription/hooks.ts b/apps/mobile/src/store/subscription/hooks.ts index a064594d5..4171b1a45 100644 --- a/apps/mobile/src/store/subscription/hooks.ts +++ b/apps/mobile/src/store/subscription/hooks.ts @@ -14,7 +14,7 @@ import { } from "./getter" import { subscriptionSyncService, useSubscriptionStore } from "./store" -export const usePrefetchSubscription = (view: FeedViewType) => { +export const usePrefetchSubscription = (view?: FeedViewType) => { return useQuery({ queryKey: ["subscription", view], queryFn: () => subscriptionSyncService.fetch(view), diff --git a/apps/mobile/src/store/subscription/store.ts b/apps/mobile/src/store/subscription/store.ts index fa7db930e..1830b60f7 100644 --- a/apps/mobile/src/store/subscription/store.ts +++ b/apps/mobile/src/store/subscription/store.ts @@ -3,7 +3,7 @@ import { FeedViewType } from "@follow/constants" import type { SubscriptionSchema } from "@/src/database/schemas/types" import { apiClient } from "@/src/lib/api-fetch" import { honoMorph } from "@/src/morph/hono" -import { storeDbMorph } from "@/src/morph/store-db" +import { buildSubscriptionDbId, storeDbMorph } from "@/src/morph/store-db" import { SubscriptionService } from "@/src/services/subscription" import { feedActions } from "../feed/store" @@ -115,19 +115,35 @@ class SubscriptionActions { draft.subscriptionIdSet = new Set() }) } + + reset() { + immerSet((draft) => { + Object.assign(draft, defaultState) + }) + } } class SubscriptionSyncService { - async fetch(view: FeedViewType) { + async fetch(view?: FeedViewType) { const res = await apiClient.subscriptions.$get({ query: { view: view !== undefined ? String(view) : undefined, }, }) - subscriptionActions.resetByView(view) + if (typeof view === "number") { + subscriptionActions.resetByView(view) + } else { + subscriptionActions.reset() + } const { subscriptions, feeds, lists, inboxes } = honoMorph.toSubscription(res.data) + + await SubscriptionService.deleteNotExists( + subscriptions.map((s) => buildSubscriptionDbId(s)), + view, + ) + feedActions.upsertMany(feeds) subscriptionActions.upsertMany(subscriptions) listActions.upsertMany(lists) @@ -250,7 +266,7 @@ class SubscriptionSyncService { }) tx.persist(() => { - return SubscriptionService.delete(storeDbMorph.toSubscriptionSchema(subscription)) + return SubscriptionService.delete(buildSubscriptionDbId(subscription)) }) tx.request(async () => { diff --git a/apps/mobile/src/store/unread/hooks.ts b/apps/mobile/src/store/unread/hooks.ts index 864cdee10..ae4e50ddb 100644 --- a/apps/mobile/src/store/unread/hooks.ts +++ b/apps/mobile/src/store/unread/hooks.ts @@ -1,8 +1,8 @@ import type { FeedViewType } from "@follow/constants" -import { useQuery } from "@tanstack/react-query" -import { useCallback } from "react" +import { useMutation, useQuery } from "@tanstack/react-query" +import { useCallback, useEffect } from "react" -import { useSubscriptionByView } from "../subscription/hooks" +import { useFeedSubscriptionByView } from "../subscription/hooks" import { unreadSyncService, useUnreadStore } from "./store" export const usePrefetchUnread = () => { @@ -13,6 +13,15 @@ export const usePrefetchUnread = () => { }) } +export const useAutoMarkAsRead = (entryId: string) => { + const { mutate } = useMutation({ + mutationFn: (entryId: string) => unreadSyncService.markEntryAsRead(entryId), + }) + useEffect(() => { + mutate(entryId) + }, [entryId, mutate]) +} + export const useUnreadCount = (subscriptionId: string) => { return useUnreadStore((state) => state.data[subscriptionId]) } @@ -33,7 +42,7 @@ export const useUnreadCounts = (subscriptionIds: string[]): number => { } export const useUnreadCountByView = (view: FeedViewType) => { - const subscriptionIds = useSubscriptionByView(view) + const subscriptionIds = useFeedSubscriptionByView(view) return useUnreadStore( useCallback( (state) => { diff --git a/apps/mobile/src/store/unread/store.ts b/apps/mobile/src/store/unread/store.ts index 5f86ee4e8..160e5f750 100644 --- a/apps/mobile/src/store/unread/store.ts +++ b/apps/mobile/src/store/unread/store.ts @@ -2,8 +2,11 @@ import type { FeedViewType } from "@follow/constants" import type { UnreadSchema } from "@/src/database/schemas/types" import { apiClient } from "@/src/lib/api-fetch" +import { EntryService } from "@/src/services/entry" import { UnreadService } from "@/src/services/unread" +import { getEntry } from "../entry/getter" +import { entryActions } from "../entry/store" import { createTransaction, createZustandStore } from "../internal/helper" import { getSubscriptionByView } from "../subscription/getter" @@ -37,28 +40,57 @@ class UnreadSyncService { await unreadActions.upsertMany(subscriptionIds.map((id) => ({ subscriptionId: id, count: 0 }))) } - async markFeedAsRead(feedId: string) { - await apiClient.reads.all.$post({ - json: { feedId }, - }) + async markFeedAsRead(feedId: string | string[]) { + const feedIds = Array.isArray(feedId) ? feedId : [feedId] - await unreadActions.upsertMany([{ subscriptionId: feedId, count: 0 }]) - } - - async markEntryAsRead(entryId: string) { - await apiClient.reads.$post({ - json: { entryIds: [entryId] }, - }) - // TODO update unreadActions - // await unreadActions.upsertMany([{ subscriptionId: feedId, count: 0 }]) - } - - async markAsReadMany(feedIds: string[]) { await apiClient.reads.all.$post({ json: { feedIdList: feedIds }, }) await unreadActions.upsertMany(feedIds.map((id) => ({ subscriptionId: id, count: 0 }))) + entryActions.markEntryReadStatusInSession({ feedIds, read: true }) + await EntryService.patchMany({ + feedIds, + entry: { read: true }, + }) + } + + async markEntryAsRead(entryId: string) { + const entry = getEntry(entryId) + if (entry?.read) return + + const feedId = entry?.feedId + + const tx = createTransaction() + tx.store(() => { + entryActions.markEntryReadStatusInSession({ entryIds: [entryId], read: true }) + + if (feedId) { + unreadActions.removeUnread(feedId) + } + }) + tx.rollback(() => { + entryActions.markEntryReadStatusInSession({ entryIds: [entryId], read: false }) + + if (feedId) { + unreadActions.addUnread(feedId) + } + }) + + tx.request(() => { + apiClient.reads.$post({ + json: { entryIds: [entryId] }, + }) + }) + + tx.persist(() => { + return EntryService.patchMany({ + entry: { read: true }, + entryIds: [entryId], + }) + }) + + await tx.run() } } @@ -87,6 +119,18 @@ class UnreadActions { await tx.run() } + async addUnread(subscriptionId: string, count = 1) { + const state = useUnreadStore.getState() + const currentCount = state.data[subscriptionId] || 0 + await unreadActions.upsertMany([{ subscriptionId, count: currentCount + count }]) + } + + async removeUnread(subscriptionId: string, count = 1) { + const state = useUnreadStore.getState() + const currentCount = state.data[subscriptionId] || 0 + await unreadActions.upsertMany([{ subscriptionId, count: Math.max(0, currentCount - count) }]) + } + reset() { set({ data: {},