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
This commit is contained in:
Stephen Zhou
2025-02-13 18:51:39 +08:00
committed by GitHub
parent 614c9b70b5
commit ddd6a2c8cd
18 changed files with 217 additions and 83 deletions
@@ -161,7 +161,7 @@ export const SubscriptionFeedCategoryContextMenu = ({
<ContextMenu.Item
key="MarkAllAsRead"
onSelect={useCallback(() => {
unreadSyncService.markAsReadMany(feedIds)
unreadSyncService.markFeedAsRead(feedIds)
}, [feedIds])}
>
<ContextMenu.ItemTitle>Mark All As Read</ContextMenu.ItemTitle>
@@ -97,6 +97,7 @@ function EntryItem({ entryId }: { entryId: string }) {
return (
<EntryItemContextMenu id={entryId}>
<ItemPressable className="flex flex-row items-center p-4" onPress={handlePress}>
{!entry.read && <View className="bg-red absolute left-1 top-6 size-2 rounded-full" />}
<View className="flex-1 space-y-2">
<Text numberOfLines={2} className="text-label text-lg font-semibold">
{title}
+4 -5
View File
@@ -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 <EntryListScreen entryIds={list.entryIds ?? []} />
const entryIds = useListEntryIds(listId)
if (!entryIds) return null
return <EntryListScreen entryIds={entryIds} />
}
function InboxEntryList({ inboxId }: { inboxId: string }) {
@@ -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 (
<ItemWrapper
@@ -82,10 +84,12 @@ function ViewItem({ view }: { view: ViewDefinition }) {
style={isActive ? { backgroundColor: view.activeColor } : undefined}
>
<view.icon color={isActive ? "#fff" : textColor} height={21} width={21} />
{isActive && (
{isActive ? (
<Text className="text-sm font-semibold text-white" numberOfLines={1}>
{view.name}
{view.name + (unreadCount ? ` (${unreadCount})` : "")}
</Text>
) : (
!!unreadCount && <View className="bg-gray absolute right-2 top-2 size-2 rounded-full" />
)}
</ItemWrapper>
)
@@ -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()
+1 -1
View File
@@ -128,7 +128,7 @@ class Morph {
feedId: item.feeds.id,
// TODO: handle inboxHandle
inboxHandle: "",
read: false,
read: item.read,
})
}
return entries
+1 -1
View File
@@ -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}`
@@ -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)
@@ -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()
+19 -1
View File
@@ -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<EntrySchema>
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) })
}
+41 -25
View File
@@ -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
}
}
}
}
+37 -8
View File
@@ -27,6 +27,7 @@ interface EntryState {
entryIdByCategory: Record<Category, Set<EntryId>>
entryIdByFeed: Record<FeedId, Set<EntryId>>
entryIdByInbox: Record<InboxId, Set<EntryId>>
entryIdSet: Set<EntryId>
}
const defaultState: EntryState = {
@@ -42,6 +43,7 @@ const defaultState: EntryState = {
entryIdByCategory: {},
entryIdByFeed: {},
entryIdByInbox: {},
entryIdSet: new Set(),
}
export const useEntryStore = createZustandStore<EntryState>("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) => {
+1 -1
View File
@@ -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
})
}
+4 -11
View File
@@ -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])]
})
}
+1 -1
View File
@@ -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),
+20 -4
View File
@@ -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 () => {
+13 -4
View File
@@ -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) => {
+60 -16
View File
@@ -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: {},