perf: optimize re-render when switch view

Signed-off-by: Innei <tukon479@gmail.com>
This commit is contained in:
Innei
2025-04-11 17:27:26 +08:00
parent 755e895b6e
commit ac39545c39
16 changed files with 264 additions and 925 deletions
@@ -1,3 +1,4 @@
import type { FeedViewType } from "@follow/constants"
import { useEffect, useMemo, useState } from "react"
import { ScrollView, View } from "react-native"
import Animated, {
@@ -20,11 +21,13 @@ export const MediaCarousel = ({
media,
onPreview,
aspectRatio,
view,
}: {
entryId: string
media: MediaModel[]
onPreview?: () => void
aspectRatio: number
view?: FeedViewType
}) => {
const [containerWidth, setContainerWidth] = useState(0)
const containerHeight = Math.floor(containerWidth / aspectRatio)
@@ -65,7 +68,7 @@ export const MediaCarousel = ({
className="relative"
style={{ width: containerWidth, height: containerHeight }}
>
<ImageContextMenu entryId={entryId} imageUrl={m.url}>
<ImageContextMenu entryId={entryId} imageUrl={m.url} view={view}>
<Galeria.Image onPreview={onPreview} index={index}>
<Image
proxy={{
@@ -83,7 +86,12 @@ export const MediaCarousel = ({
)
} else if (m.type === "video") {
return (
<ImageContextMenu key={index} entryId={entryId} imageUrl={m.preview_image_url}>
<ImageContextMenu
key={index}
entryId={entryId}
imageUrl={m.preview_image_url}
view={view}
>
<Video
source={{ uri: m.url }}
style={{ width: containerWidth, height: containerHeight }}
@@ -1,3 +1,4 @@
import type { FeedViewType } from "@follow/constants"
import ImageEditor from "@react-native-community/image-editor"
import { requireNativeModule } from "expo"
import * as FileSystem from "expo-file-system"
@@ -11,7 +12,6 @@ import { findNodeHandle, Image, Pressable } from "react-native"
import { isIOS } from "@/src/lib/platform"
import { toast } from "@/src/lib/toast"
import { useSelectedView } from "@/src/modules/screen/atoms"
import { useIsEntryStarred } from "@/src/store/collection/hooks"
import { collectionSyncService } from "@/src/store/collection/store"
import { useEntry } from "@/src/store/entry/hooks"
@@ -22,6 +22,7 @@ import { ContextMenu } from "../context-menu"
type ImageContextMenuProps = PropsWithChildren<{
imageUrl?: string
entryId?: string
view?: FeedViewType
}>
interface IOSNativeImageActions {
@@ -35,11 +36,11 @@ const getIOSNativeImageActions = () => {
return requireNativeModule<IOSNativeImageActions>("Helper")
}
export const ImageContextMenu = ({ imageUrl, entryId, children }: ImageContextMenuProps) => {
export const ImageContextMenu = ({ imageUrl, entryId, children, view }: ImageContextMenuProps) => {
const { t } = useTranslation()
const entry = useEntry(entryId!)
const feedId = entry?.feedId
const view = useSelectedView()
const isEntryStarred = useIsEntryStarred(entryId!)
const contextMenuTriggerRef = useRef<View>(null)
+217 -194
View File
@@ -1,240 +1,263 @@
import { FeedViewType } from "@follow/constants"
import dayjs from "dayjs"
import { setStringAsync } from "expo-clipboard"
import { t } from "i18next"
import type { CSSProperties, FC, PropsWithChildren } from "react"
import { useCallback, useMemo } from "react"
import { useCallback, useEffect, useMemo, useState } from "react"
import { useTranslation } from "react-i18next"
import type { ListRenderItemInfo } from "react-native"
import { Alert, Clipboard, FlatList, View } from "react-native"
import { Alert, FlatList, View } from "react-native"
import { ContextMenu } from "@/src/components/ui/context-menu"
import { views } from "@/src/constants/views"
import { useNavigation } from "@/src/lib/navigation/hooks"
import type { Navigation } from "@/src/lib/navigation/Navigation"
import { toast } from "@/src/lib/toast"
import { FeedScreen } from "@/src/screens/(stack)/feeds/[feedId]"
import { useEntryIdsByFeedId, usePrefetchEntries } from "@/src/store/entry/hooks"
import { getFeed } from "@/src/store/feed/getter"
import { useFeed } from "@/src/store/feed/hooks"
import { getSubscription } from "@/src/store/subscription/getter"
import { useSubscriptionCategory } from "@/src/store/subscription/hooks"
import { getSubscriptionCategory } from "@/src/store/subscription/hooks"
import { subscriptionSyncService } from "@/src/store/subscription/store"
import { unreadSyncService } from "@/src/store/unread/store"
import { ItemSeparator } from "../entry-list/ItemSeparator"
import { EntryNormalItem } from "../entry-list/templates/EntryNormalItem"
import { getSelectedView } from "../screen/atoms"
export const SubscriptionFeedItemContextMenu: FC<
PropsWithChildren & {
id: string
view?: FeedViewType
}
> = ({ id, children, view }) => {
const feed = useFeed(id)
const { t } = useTranslation()
const allCategories = useSubscriptionCategory(view)
> = ({ id, children }) => {
const navigation = useNavigation()
const [open, setOpen] = useState(false)
const [Content, setContent] = useState<React.ReactNode>(() =>
generateSubscriptionContextMenu(navigation, id),
)
useEffect(() => {
if (open) {
setContent(generateSubscriptionContextMenu(navigation, id))
}
}, [id, navigation, open])
return (
<ContextMenu.Root>
<ContextMenu.Root onOpenChange={setOpen}>
<ContextMenu.Trigger asChild>{children}</ContextMenu.Trigger>
<ContextMenu.Content>
{view === FeedViewType.Articles && (
<ContextMenu.Preview
size="STRETCH"
onPress={() => {
navigation.pushControllerView(FeedScreen, {
feedId: id,
})
}}
>
{() => <PreviewFeeds id={id} view={view!} />}
</ContextMenu.Preview>
)}
{!!feed?.errorAt && (
<ContextMenu.Item
key="ShowErrorMessage"
onSelect={() => {
Alert.alert(
`${t("operation.error_since")} ${dayjs
.duration(dayjs(feed.errorAt).diff(dayjs(), "minute"), "minute")
.humanize(true)}`,
feed.errorMessage ?? undefined,
)
}}
>
<ContextMenu.ItemTitle>{t("operation.show_error_message")}</ContextMenu.ItemTitle>
<ContextMenu.ItemIcon
ios={{
name: "exclamationmark.triangle",
}}
/>
</ContextMenu.Item>
)}
<ContextMenu.Item
key="MarkAllAsRead"
onSelect={useCallback(() => {
unreadSyncService.markFeedAsRead(id)
}, [id])}
>
<ContextMenu.ItemTitle>{t("operation.mark_all_as_read")}</ContextMenu.ItemTitle>
<ContextMenu.ItemIcon
ios={{
name: "checkmark.circle",
}}
/>
</ContextMenu.Item>
{/* <ContextMenu.Item key="Claim">
<ContextMenu.ItemTitle>Claim</ContextMenu.ItemTitle>
<ContextMenu.ItemIcon
ios={{
name: "checkmark.seal",
}}
/>
</ContextMenu.Item> */}
{/* <ContextMenu.Item key="Boost">
<ContextMenu.ItemTitle>Boost</ContextMenu.ItemTitle>
<ContextMenu.ItemIcon
ios={{
name: "bolt",
}}
/>
</ContextMenu.Item> */}
<ContextMenu.Sub key="AddToCategory">
<ContextMenu.SubTrigger key="SubTrigger/AddToCategory">
<ContextMenu.ItemTitle>{t("operation.add_feeds_to_category")}</ContextMenu.ItemTitle>
</ContextMenu.SubTrigger>
<ContextMenu.SubContent>
<>
{allCategories.map((category) => {
const onSelect = () => {
const subscription = getSubscription(id)
if (!subscription) return
// add to category
subscriptionSyncService.edit({
...subscription,
category,
})
}
return (
<ContextMenu.Item key={`SubContent/${category}`} onSelect={onSelect}>
<ContextMenu.ItemTitle>{category}</ContextMenu.ItemTitle>
</ContextMenu.Item>
)
})}
</>
<ContextMenu.Item
key={`SubContent/CreateNewCategory`}
onSelect={useCallback(() => {
// create new category
const subscription = getSubscription(id)
if (!subscription) return
Alert.prompt(
"Create New Category",
"Enter the name of the new category",
(text) => {
subscriptionSyncService.edit({
...subscription,
category: text,
})
},
)
}, [id])}
>
<ContextMenu.ItemTitle>Create New Category</ContextMenu.ItemTitle>
<ContextMenu.ItemIcon ios={{ name: "plus" }} />
</ContextMenu.Item>
</ContextMenu.SubContent>
</ContextMenu.Sub>
<ContextMenu.Item key="Edit">
<ContextMenu.ItemTitle>{t("operation.edit")}</ContextMenu.ItemTitle>
<ContextMenu.ItemIcon
ios={{
name: "square.and.pencil",
}}
/>
</ContextMenu.Item>
<ContextMenu.Item
key="CopyLink"
onSelect={useCallback(() => {
const subscription = getSubscription(id)
if (!subscription) return
switch (subscription.type) {
case "feed": {
if (!subscription.feedId) return
const feed = getFeed(subscription.feedId)
if (!feed) return
Clipboard.setString(feed.url)
toast.success("Link copied to clipboard")
return
}
}
}, [id])}
>
<ContextMenu.ItemTitle>{t("operation.copy_link")}</ContextMenu.ItemTitle>
<ContextMenu.ItemIcon
ios={{
name: "link",
}}
/>
</ContextMenu.Item>
<ContextMenu.Item
key="Unsubscribe"
destructive
onSelect={useCallback(() => {
// unsubscribe
Alert.alert("Unsubscribe?", "This will remove the feed from your subscriptions", [
{
text: "Cancel",
style: "cancel",
},
{
text: t("operation.unfollow"),
style: "destructive",
onPress: () => {
subscriptionSyncService.unsubscribe(id)
},
},
])
}, [id, t])}
>
<ContextMenu.ItemTitle>{t("operation.unfollow")}</ContextMenu.ItemTitle>
<ContextMenu.ItemIcon
ios={{
name: "xmark",
}}
/>
</ContextMenu.Item>
</ContextMenu.Content>
{Content}
</ContextMenu.Root>
)
}
const generateSubscriptionContextMenu = (navigation: Navigation, id: string) => {
const view = getSelectedView()
const feed = getFeed(id)
const allCategories = getSubscriptionCategory(view)
return (
<ContextMenu.Content>
{view === FeedViewType.Articles && (
<ContextMenu.Preview
size="STRETCH"
onPress={() => {
navigation.pushControllerView(FeedScreen, {
feedId: id,
})
}}
>
{() => <PreviewFeeds id={id} view={view!} />}
</ContextMenu.Preview>
)}
{!!feed?.errorAt && (
<ContextMenu.Item
key="ShowErrorMessage"
onSelect={() => {
Alert.alert(
`${t("operation.error_since")} ${dayjs
.duration(dayjs(feed.errorAt).diff(dayjs(), "minute"), "minute")
.humanize(true)}`,
feed.errorMessage ?? undefined,
)
}}
>
<ContextMenu.ItemTitle>{t("operation.show_error_message")}</ContextMenu.ItemTitle>
<ContextMenu.ItemIcon
ios={{
name: "exclamationmark.triangle",
}}
/>
</ContextMenu.Item>
)}
<ContextMenu.Item
key="MarkAllAsRead"
onSelect={() => {
unreadSyncService.markFeedAsRead(id)
}}
>
<ContextMenu.ItemTitle>{t("operation.mark_all_as_read")}</ContextMenu.ItemTitle>
<ContextMenu.ItemIcon
ios={{
name: "checkmark.circle",
}}
/>
</ContextMenu.Item>
{/* <ContextMenu.Item key="Claim">
<ContextMenu.ItemTitle>Claim</ContextMenu.ItemTitle>
<ContextMenu.ItemIcon
ios={{
name: "checkmark.seal",
}}
/>
</ContextMenu.Item> */}
{/* <ContextMenu.Item key="Boost">
<ContextMenu.ItemTitle>Boost</ContextMenu.ItemTitle>
<ContextMenu.ItemIcon
ios={{
name: "bolt",
}}
/>
</ContextMenu.Item> */}
<ContextMenu.Sub key="AddToCategory">
<ContextMenu.SubTrigger key="SubTrigger/AddToCategory">
<ContextMenu.ItemTitle>{t("operation.add_feeds_to_category")}</ContextMenu.ItemTitle>
</ContextMenu.SubTrigger>
<ContextMenu.SubContent>
<>
{allCategories.map((category) => {
const onSelect = () => {
const subscription = getSubscription(id)
if (!subscription) return
// add to category
subscriptionSyncService.edit({
...subscription,
category,
})
}
return (
<ContextMenu.Item key={`SubContent/${category}`} onSelect={onSelect}>
<ContextMenu.ItemTitle>{category}</ContextMenu.ItemTitle>
</ContextMenu.Item>
)
})}
</>
<ContextMenu.Item
key={`SubContent/CreateNewCategory`}
onSelect={() => {
// create new category
const subscription = getSubscription(id)
if (!subscription) return
Alert.prompt("Create New Category", "Enter the name of the new category", (text) => {
subscriptionSyncService.edit({
...subscription,
category: text,
})
})
}}
>
<ContextMenu.ItemTitle>Create New Category</ContextMenu.ItemTitle>
<ContextMenu.ItemIcon ios={{ name: "plus" }} />
</ContextMenu.Item>
</ContextMenu.SubContent>
</ContextMenu.Sub>
<ContextMenu.Item key="Edit">
<ContextMenu.ItemTitle>{t("operation.edit")}</ContextMenu.ItemTitle>
<ContextMenu.ItemIcon
ios={{
name: "square.and.pencil",
}}
/>
</ContextMenu.Item>
<ContextMenu.Item
key="CopyLink"
onSelect={() => {
const subscription = getSubscription(id)
if (!subscription) return
switch (subscription.type) {
case "feed": {
if (!subscription.feedId) return
const feed = getFeed(subscription.feedId)
if (!feed) return
setStringAsync(feed.url)
toast.success("Link copied to clipboard")
return
}
}
}}
>
<ContextMenu.ItemTitle>{t("operation.copy_link")}</ContextMenu.ItemTitle>
<ContextMenu.ItemIcon
ios={{
name: "link",
}}
/>
</ContextMenu.Item>
<ContextMenu.Item
key="Unsubscribe"
destructive
onSelect={() => {
// unsubscribe
Alert.alert("Unsubscribe?", "This will remove the feed from your subscriptions", [
{
text: "Cancel",
style: "cancel",
},
{
text: t("operation.unfollow"),
style: "destructive",
onPress: () => {
subscriptionSyncService.unsubscribe(id)
},
},
])
}}
>
<ContextMenu.ItemTitle>{t("operation.unfollow")}</ContextMenu.ItemTitle>
<ContextMenu.ItemIcon
ios={{
name: "xmark",
}}
/>
</ContextMenu.Item>
</ContextMenu.Content>
)
}
export const SubscriptionFeedCategoryContextMenu = ({
category: _,
feedIds,
view: currentView,
children,
asChild,
style,
}: PropsWithChildren<{
category: string
feedIds: string[]
view: FeedViewType
asChild?: boolean
style?: CSSProperties
}>) => {
const { t } = useTranslation()
const [currentView, setCurrentView] = useState<FeedViewType>(FeedViewType.Articles)
return (
<ContextMenu.Root>
<ContextMenu.Root
onOpenChange={(open) => {
if (open) {
setCurrentView(getSelectedView())
}
}}
>
<ContextMenu.Trigger asChild={asChild} style={style}>
{children}
</ContextMenu.Trigger>
@@ -268,7 +291,7 @@ export const SubscriptionFeedCategoryContextMenu = ({
value={isSelected}
// onSelect={onSelect}
>
<ContextMenu.ItemTitle>{view.name}</ContextMenu.ItemTitle>
<ContextMenu.ItemTitle>{t(view.name as any)}</ContextMenu.ItemTitle>
</ContextMenu.CheckboxItem>
)
})}
@@ -1,10 +1,10 @@
import { FeedViewType } from "@follow/constants"
import type { PropsWithChildren } from "react"
import { useTranslation } from "react-i18next"
import { Share } from "react-native"
import { ContextMenu } from "@/src/components/ui/context-menu"
import { toast } from "@/src/lib/toast"
import { useSelectedView } from "@/src/modules/screen/atoms"
import { useIsEntryStarred } from "@/src/store/collection/hooks"
import { collectionSyncService } from "@/src/store/collection/store"
import { useEntry } from "@/src/store/entry/hooks"
@@ -18,7 +18,7 @@ export const VideoContextMenu = ({ entryId, children }: VideoContextMenuProps) =
const { t } = useTranslation()
const entry = useEntry(entryId)
const feedId = entry?.feedId
const view = useSelectedView()
const isEntryStarred = useIsEntryStarred(entryId)
if (!entry) {
@@ -47,7 +47,7 @@ export const VideoContextMenu = ({ entryId, children }: VideoContextMenuProps) =
}}
/>
</ContextMenu.Item>
{feedId && view !== undefined && (
{feedId && (
<ContextMenu.Item
key="Star"
onSelect={() => {
@@ -58,7 +58,7 @@ export const VideoContextMenu = ({ entryId, children }: VideoContextMenuProps) =
collectionSyncService.starEntry({
feedId,
entryId,
view,
view: FeedViewType.Videos,
})
toast.success("Starred")
}
@@ -10,7 +10,7 @@ import { useRegisterNavigationScrollView } from "@/src/components/layouts/tabbar
import { EntryListContentPicture } from "@/src/modules/entry-list/EntryListContentPicture"
import { useWhoami } from "@/src/store/user/hooks"
import { useFetchEntriesControls } from "../feed-drawer/atoms"
import { useFetchEntriesControls } from "../screen/atoms"
import { EntryListContentArticle } from "./EntryListContentArticle"
import { EntryListContentSocial } from "./EntryListContentSocial"
import { EntryListContentVideo } from "./EntryListContentVideo"
@@ -1,3 +1,4 @@
import { FeedViewType } from "@follow/constants"
import { tracker } from "@follow/tracker"
import { uniqBy } from "es-toolkit/compat"
import { useMemo } from "react"
@@ -84,6 +85,7 @@ const MediaItems = ({
return (
<MediaCarousel
view={FeedViewType.Pictures}
entryId={entryId}
media={uniqMedia}
onPreview={onPreview}
@@ -1,197 +0,0 @@
import { FeedViewType } from "@follow/constants"
import { jotaiStore } from "@follow/utils"
import { atom, useAtom, useAtomValue, useSetAtom } from "jotai"
import { createContext, useCallback, useContext, useMemo } from "react"
import { views } from "@/src/constants/views"
import { getFetchEntryPayload } from "@/src/store/entry/getter"
import { usePrefetchEntries } from "@/src/store/entry/hooks"
import { FEED_COLLECTION_LIST } from "@/src/store/entry/utils"
import { useFeed } from "@/src/store/feed/hooks"
import { useInbox } from "@/src/store/inbox/hooks"
import { useList } from "@/src/store/list/hooks"
import { useSubscription } from "@/src/store/subscription/hooks"
// drawer open state
const drawerOpenAtom = atom<boolean>(false)
export function useFeedDrawer() {
const [state, setState] = useAtom(drawerOpenAtom)
return {
isDrawerOpen: state,
openDrawer: useCallback(() => setState(true), [setState]),
closeDrawer: useCallback(() => setState(false), [setState]),
toggleDrawer: useCallback(() => setState(!state), [setState, state]),
}
}
export const closeDrawer = () => jotaiStore.set(drawerOpenAtom, false)
// is drawer swipe disabled
const isDrawerSwipeDisabledAtom = atom<boolean>(true)
export function useIsDrawerSwipeDisabled() {
return useAtomValue(isDrawerSwipeDisabledAtom)
}
export function useSetDrawerSwipeDisabled() {
return useSetAtom(isDrawerSwipeDisabledAtom)
}
// collection panel selected state
type CollectionPanelState =
| {
type: "view"
viewId: FeedViewType
}
| {
type: "list"
listId: string
}
const collectionPanelStateAtom = atom<CollectionPanelState>({
type: "view",
viewId: FeedViewType.Articles,
})
export function useSelectedCollection() {
return useAtomValue(collectionPanelStateAtom)
}
export const selectCollection = (state: CollectionPanelState) => {
jotaiStore.set(collectionPanelStateAtom, state)
if (state.type === "view" || state.type === "list") {
jotaiStore.set(selectedTimelineAtom, state)
}
}
// feed panel selected state
export type SelectedTimeline =
| {
type: "view"
viewId: FeedViewType
}
| {
type: "list"
listId: string
}
| {
type: "inbox"
inboxId: string
}
export type SelectedFeed =
| {
type: "feed"
feedId: string
}
| {
type: "category"
categoryName: string
}
| null
const selectedTimelineAtom = atom<SelectedTimeline>({
type: "view",
viewId: FeedViewType.Articles,
})
const selectedFeedAtom = atom<SelectedFeed>(null)
export const EntryListContext = createContext<{ type: "timeline" | "feed" }>({ type: "timeline" })
export const useEntryListContext = () => {
return useContext(EntryListContext)
}
function useSelectedView() {
const selectedTimeLine = useAtomValue(selectedTimelineAtom)
const selectedFeed = useAtomValue(selectedFeedAtom)
const list = useList(selectedTimeLine.type === "list" ? selectedTimeLine.listId : "")
const subscription = useSubscription(
selectedFeed && selectedFeed.type === "feed" ? selectedFeed.feedId : "",
)
const view =
selectedTimeLine.type === "view"
? selectedTimeLine.viewId
: selectedTimeLine.type === "list"
? list?.view
: selectedFeed?.type === "feed"
? subscription?.view
: undefined
return view
}
export function useSelectedFeed() {
const entryListContext = useEntryListContext()
const selectedTimeline = useAtomValue(selectedTimelineAtom)
const selectedFeed = useAtomValue(selectedFeedAtom)
const view = useSelectedView()
const payload = getFetchEntryPayload(
entryListContext.type === "feed" ? selectedFeed : selectedTimeline,
view,
)
usePrefetchEntries(payload)
return entryListContext.type === "feed" ? selectedFeed : selectedTimeline
}
export function useFetchEntriesControls() {
const selectedFeed = useSelectedFeed()
const view = useSelectedView()
const payload = getFetchEntryPayload(selectedFeed, view)
return usePrefetchEntries(payload)
}
export const useSelectedFeedTitle = () => {
const selectedFeed = useSelectedFeed()
const viewDef = useViewDefinition(
selectedFeed && selectedFeed.type === "view" ? selectedFeed.viewId : undefined,
)
const feed = useFeed(selectedFeed && selectedFeed.type === "feed" ? selectedFeed.feedId : "")
const list = useList(selectedFeed && selectedFeed.type === "list" ? selectedFeed.listId : "")
const inbox = useInbox(selectedFeed && selectedFeed.type === "inbox" ? selectedFeed.inboxId : "")
if (!selectedFeed) {
return ""
}
switch (selectedFeed.type) {
case "view": {
return viewDef?.name
}
case "feed": {
return selectedFeed.feedId === FEED_COLLECTION_LIST ? "Collections" : (feed?.title ?? "")
}
case "category": {
return selectedFeed.categoryName
}
case "list": {
return list?.title
}
case "inbox": {
return inbox?.title ?? "Inbox"
}
}
}
export const selectTimeline = (state: SelectedTimeline) => {
jotaiStore.set(selectedTimelineAtom, state)
}
export const selectFeed = (state: SelectedFeed) => {
jotaiStore.set(selectedFeedAtom, state)
}
export const useViewDefinition = (view?: FeedViewType) => {
const viewDef = useMemo(() => views.find((v) => v.view === view), [view])
return viewDef
}
@@ -1,152 +0,0 @@
import type { PropsWithChildren } from "react"
import { useEffect } from "react"
import { Image, ScrollView, StyleSheet, TouchableOpacity, View } from "react-native"
import Animated, { useAnimatedStyle, useSharedValue, withTiming } from "react-native-reanimated"
import { useSafeAreaInsets } from "react-native-safe-area-context"
import { FallbackIcon } from "@/src/components/ui/icon/fallback-icon"
import { Logo } from "@/src/components/ui/logo"
import type { ViewDefinition } from "@/src/constants/views"
import { views } from "@/src/constants/views"
import { useList } from "@/src/store/list/hooks"
import { useAllListSubscription } from "@/src/store/subscription/hooks"
import { selectCollection, useSelectedCollection } from "./atoms"
export const CollectionPanel = () => {
const lists = useAllListSubscription()
const insets = useSafeAreaInsets()
return (
<View className="bg-secondary-system-fill dark:bg-tertiary-system-background w-[65px]">
<ScrollView
contentContainerClassName="flex gap-4 px-3.5"
contentContainerStyle={{ marginTop: insets.top + 10, paddingBottom: insets.bottom }}
>
<View className="flex-1 items-center">
<Logo width={37} height={37} color="#222" />
</View>
<View style={styles.hairline} className="bg-opaque-separator mx-1" />
{views.map((viewDef) => (
<ViewButton key={viewDef.name} viewDef={viewDef} />
))}
<View style={styles.hairline} className="bg-opaque-separator mx-1" />
{lists.map((listId) => (
<ListButton key={listId} listId={listId} />
))}
</ScrollView>
</View>
)
}
const styles = StyleSheet.create({
hairline: {
height: StyleSheet.hairlineWidth,
},
})
const Item = ({
isActive,
onPress,
children,
}: { isActive: boolean; onPress: () => void } & PropsWithChildren) => {
const scaleY = useSharedValue(21)
useEffect(() => {
if (isActive) {
scaleY.value = withTiming(15, { duration: 200 })
} else {
scaleY.value = withTiming(21, { duration: 200 })
}
}, [isActive, scaleY])
const animatedStyle = useAnimatedStyle(() => {
return {
borderRadius: scaleY.value,
}
})
return (
<TouchableOpacity
className="relative flex aspect-square items-center justify-center rounded-full"
onPress={onPress}
>
<ActiveIndicator isActive={isActive} />
<Animated.View
className="flex size-full items-center justify-center overflow-hidden"
style={animatedStyle}
>
{children}
</Animated.View>
</TouchableOpacity>
)
}
const ActiveIndicator = ({ isActive }: { isActive: boolean }) => {
const scaleY = useSharedValue(1)
useEffect(() => {
if (isActive) {
scaleY.value = withTiming(1, { duration: 200 })
} else {
scaleY.value = withTiming(0, { duration: 200 })
}
}, [isActive, scaleY])
const animatedStyle = useAnimatedStyle(() => {
return {
transform: [{ scaleY: scaleY.value }],
}
})
return (
<Animated.View
className="absolute -left-3.5 h-9 w-1 rounded-r-xl bg-black"
style={animatedStyle}
/>
)
}
const ViewButton = ({ viewDef }: { viewDef: ViewDefinition }) => {
const selectedCollection = useSelectedCollection()
const isActive = selectedCollection.type === "view" && selectedCollection.viewId === viewDef.view
return (
<Item
isActive={isActive}
onPress={() => selectCollection({ type: "view", viewId: viewDef.view })}
>
<View
className="flex size-full items-center justify-center"
style={{ backgroundColor: viewDef.activeColor }}
>
<viewDef.icon key={viewDef.name} color={"#fff"} />
</View>
</Item>
)
}
const ListButton = ({ listId }: { listId: string }) => {
const list = useList(listId)
const selectedCollection = useSelectedCollection()
const isActive = selectedCollection.type === "list" && selectedCollection.listId === listId
if (!list) return null
return (
<Item
isActive={isActive}
onPress={() =>
selectCollection({
type: "list",
listId,
})
}
>
{list.image ? (
<Image source={{ uri: list.image }} resizeMode="cover" className="size-full" />
) : (
<FallbackIcon title={list.title} size="100%" />
)}
</Item>
)
}
@@ -1,271 +0,0 @@
import { cn } from "@follow/utils"
import type { FC } from "react"
import { createContext, memo, useContext, useState } from "react"
import {
Animated,
Easing,
ScrollView,
StyleSheet,
Text,
TouchableOpacity,
useAnimatedValue,
View,
} from "react-native"
import { useSharedValue } from "react-native-reanimated"
import { useSafeAreaInsets } from "react-native-safe-area-context"
import { ErrorBoundary } from "@/src/components/common/ErrorBoundary"
import { ListErrorView } from "@/src/components/errors/ListErrorView"
import { BottomTabBarHeightContext } from "@/src/components/layouts/tabbar/contexts/BottomTabBarHeightContext"
import { NavigationHeaderHeightContext } from "@/src/components/layouts/views/NavigationHeaderContext"
import { AccordionItem } from "@/src/components/ui/accordion/AccordionItem"
import { FeedIcon } from "@/src/components/ui/icon/feed-icon"
import { PlatformActivityIndicator } from "@/src/components/ui/loading/PlatformActivityIndicator"
import { ItemPressable } from "@/src/components/ui/pressable/ItemPressable"
import { MingcuteRightLine } from "@/src/icons/mingcute_right_line"
import { useNavigation } from "@/src/lib/navigation/hooks"
import { FeedScreen } from "@/src/screens/(stack)/feeds/[feedId]"
import { useFeed, usePrefetchFeed } from "@/src/store/feed/hooks"
import { useList } from "@/src/store/list/hooks"
import { useSortedUngroupedSubscription, useSubscription } from "@/src/store/subscription/hooks"
import { useUnreadCount, useUnreadCounts } from "@/src/store/unread/hooks"
import {
SubscriptionFeedCategoryContextMenu,
SubscriptionFeedItemContextMenu,
} from "../context-menu/feeds"
import { useCurrentView, useFeedListSortMethod, useFeedListSortOrder } from "../subscription/atoms"
import { ViewPageCurrentViewProvider } from "../subscription/ctx"
import { SubscriptionList } from "../subscription/SubscriptionLists"
import { closeDrawer, selectFeed, useSelectedCollection } from "./atoms"
import { ListHeaderComponent, ViewHeaderComponent } from "./header"
export const FeedPanel = () => {
const selectedCollection = useSelectedCollection()
const [headerHeight, setHeaderHeight] = useState(0)
const insets = useSafeAreaInsets()
if (selectedCollection.type === "view") {
return (
<View className="flex flex-1 overflow-hidden">
<ViewHeaderComponent
view={selectedCollection.viewId}
onLayout={(e) => {
setHeaderHeight(e.nativeEvent.layout.height)
}}
/>
<NavigationHeaderHeightContext.Provider value={headerHeight}>
<BottomTabBarHeightContext.Provider value={insets.bottom}>
<ViewPageCurrentViewProvider
key={selectedCollection.viewId}
value={selectedCollection.viewId}
>
<ErrorBoundary fallbackRender={ListErrorView}>
<SubscriptionList view={selectedCollection.viewId} />
</ErrorBoundary>
</ViewPageCurrentViewProvider>
</BottomTabBarHeightContext.Provider>
</NavigationHeaderHeightContext.Provider>
</View>
)
}
return (
<View className="flex flex-1 overflow-hidden">
<ListHeaderComponent listId={selectedCollection.listId} />
<ListView listId={selectedCollection.listId} />
</View>
)
}
const ListView = ({ listId }: { listId: string }) => {
const list = useList(listId)
if (!list) {
console.warn("list not found:", listId)
return null
}
const { feedIds } = list
return (
<ScrollView>
{feedIds.map((item, index) => (
<ItemRender key={item} item={item} index={index} />
))}
{/* Just a placeholder */}
<View className="h-10" />
</ScrollView>
)
}
const ItemRender = ({
item,
}: {
item: string | { category: string; subscriptionIds: string[] }
index: number
extraData?: {
total: number
}
}) => {
if (typeof item === "string") {
return <SubscriptionItem id={item} />
}
const { category, subscriptionIds } = item
return <CategoryGrouped category={category} subscriptionIds={subscriptionIds} />
}
const UnGroupedList: FC<{
subscriptionIds: string[]
}> = ({ subscriptionIds }) => {
const sortBy = useFeedListSortMethod()
const sortOrder = useFeedListSortOrder()
const sortedSubscriptionIds = useSortedUngroupedSubscription(subscriptionIds, sortBy, sortOrder)
const lastSubscriptionId = sortedSubscriptionIds.at(-1)
return sortedSubscriptionIds.map((id) => {
return (
<SubscriptionItem
key={id}
id={id}
className={id === lastSubscriptionId ? "border-b-transparent" : ""}
/>
)
})
}
const GroupedContext = createContext<string | null>(null)
const AnimatedTouchableOpacity = Animated.createAnimatedComponent(TouchableOpacity)
const CategoryGrouped = memo(
({ category, subscriptionIds }: { category: string; subscriptionIds: string[] }) => {
const unreadCounts = useUnreadCounts(subscriptionIds)
const isExpanded = useSharedValue(false)
const rotateValue = useAnimatedValue(1)
const selectedCollection = useSelectedCollection()
const view = selectedCollection.type === "view" ? selectedCollection.viewId : undefined
const navigation = useNavigation()
if (view === undefined) {
console.warn("view is undefined", selectedCollection)
return null
}
return (
<SubscriptionFeedCategoryContextMenu
view={view}
category={category}
feedIds={subscriptionIds}
>
<ItemPressable
onPress={() => {
selectFeed({
type: "category",
categoryName: category,
})
closeDrawer()
navigation.pushControllerView(FeedScreen, {
feedId: category,
})
}}
className="h-12 flex-row items-center px-3"
>
<AnimatedTouchableOpacity
hitSlop={10}
onPress={() => {
Animated.timing(rotateValue, {
toValue: isExpanded.value ? 1 : 0,
easing: Easing.linear,
useNativeDriver: true,
}).start()
isExpanded.value = !isExpanded.value
}}
style={[
{
transform: [
{
rotate: rotateValue.interpolate({
inputRange: [0, 1],
outputRange: ["90deg", "0deg"],
}),
},
],
},
style.accordionIcon,
]}
>
<MingcuteRightLine color="gray" height={18} width={18} />
</AnimatedTouchableOpacity>
<Text className="text-text ml-3">{category}</Text>
{!!unreadCounts && (
<Text className="text-tertiary-label ml-auto text-xs">{unreadCounts}</Text>
)}
</ItemPressable>
<AccordionItem isExpanded={isExpanded} viewKey={category}>
<GroupedContext.Provider value={category}>
<UnGroupedList subscriptionIds={subscriptionIds} />
</GroupedContext.Provider>
</AccordionItem>
</SubscriptionFeedCategoryContextMenu>
)
},
)
const SubscriptionItem = memo(({ id, className }: { id: string; className?: string }) => {
const subscription = useSubscription(id)
const unreadCount = useUnreadCount(id)
const feed = useFeed(id)!
const inGrouped = !!useContext(GroupedContext)
const view = useCurrentView()
const { isLoading } = usePrefetchFeed(id, { enabled: !feed })
if (isLoading) {
return (
<View className="mt-24 flex-1 flex-row items-start justify-center">
<PlatformActivityIndicator />
</View>
)
}
if (!subscription && !feed) return null
return (
<SubscriptionFeedItemContextMenu id={id} view={view}>
<ItemPressable
className={cn(
"flex h-12 flex-row items-center",
inGrouped ? "pl-8 pr-4" : "px-4",
className,
)}
onPress={() => {
selectFeed({
type: "feed",
feedId: id,
})
closeDrawer()
}}
>
<View className="dark:border-tertiary-system-background mr-3 size-5 items-center justify-center overflow-hidden rounded-full border border-transparent dark:bg-[#222]">
<FeedIcon feed={feed} />
</View>
<Text numberOfLines={1} className="text-text flex-1">
{subscription?.title || feed.title}
</Text>
{!!unreadCount && (
<Text className="text-tertiary-label ml-auto text-xs">{unreadCount}</Text>
)}
</ItemPressable>
</SubscriptionFeedItemContextMenu>
)
})
const style = StyleSheet.create({
accordionIcon: {
height: 20,
width: 20,
alignItems: "center",
justifyContent: "center",
},
})
@@ -1,55 +0,0 @@
import type { FeedViewType } from "@follow/constants"
import type { LayoutChangeEvent } from "react-native"
import { Text, View } from "react-native"
import { useSafeAreaInsets } from "react-native-safe-area-context"
import { BlurEffect } from "@/src/components/common/BlurEffect"
import { useList } from "@/src/store/list/hooks"
import { SortActionButton } from "../subscription/header-actions"
import { useViewDefinition } from "./atoms"
export const ViewHeaderComponent = ({
view,
onLayout,
}: {
view: FeedViewType
onLayout?: (event: LayoutChangeEvent) => void
}) => {
const viewDef = useViewDefinition(view)
const insets = useSafeAreaInsets()
return (
<View
onLayout={onLayout}
className="border-b-opaque-separator bg-system-background/90 border-b-hairline absolute inset-x-0 top-0 z-[999] flex flex-row items-center justify-between gap-2 px-4"
style={{ paddingTop: insets.top }}
>
<BlurEffect />
<Text className="text-text my-4 text-2xl font-bold">{viewDef?.name}</Text>
<SortActionButton />
</View>
)
}
export const ListHeaderComponent = ({ listId }: { listId: string }) => {
const list = useList(listId)
const insets = useSafeAreaInsets()
if (!list) {
console.warn("list not found:", listId)
return null
}
return (
<View
className="border-b-opaque-separator border-b-hairline flex flex-col gap-2 py-4"
style={{ paddingTop: insets.top }}
>
<View className="flex flex-row items-center gap-2">
<Text className="text-text ml-4 text-2xl font-bold">{list.title}</Text>
</View>
{list.description && (
<Text className="text-secondary-label ml-4 text-sm font-medium">{list.description}</Text>
)}
</View>
)
}
+4
View File
@@ -86,6 +86,10 @@ export function useSelectedView() {
return useAtomValue(useMemo(() => selectAtom(selectedTimelineAtom, (state) => state.viewId), []))
}
export const getSelectedView = () => {
return jotaiStore.get(selectedTimelineAtom).viewId
}
export function useSelectedFeed(): SelectedTimeline | SelectedFeed
export function useSelectedFeed<T>(
selector?: (selectedFeed: SelectedTimeline | SelectedFeed) => T,
@@ -8,12 +8,7 @@ import { ItemPressableStyle } from "@/src/components/ui/pressable/enum"
import { ItemPressable } from "@/src/components/ui/pressable/ItemPressable"
import { RightCuteFiIcon } from "@/src/icons/right_cute_fi"
import { useNavigation } from "@/src/lib/navigation/hooks"
import {
closeDrawer,
getHorizontalScrolling,
selectFeed,
useSelectedFeed,
} from "@/src/modules/screen/atoms"
import { closeDrawer, getHorizontalScrolling, selectFeed } from "@/src/modules/screen/atoms"
import { FeedScreen } from "@/src/screens/(stack)/feeds/[feedId]"
import { useUnreadCounts } from "@/src/store/unread/hooks"
import { useColor } from "@/src/theme/colors"
@@ -46,22 +41,12 @@ export const CategoryGrouped = memo(
}, [rotateSharedValue])
const secondaryLabelColor = useColor("label")
const selectedFeed = useSelectedFeed()
const navigation = useNavigation()
if (selectedFeed?.type !== "view") {
return null
}
const view = selectedFeed.viewId
return (
<>
<View style={{ marginHorizontal: GROUPED_LIST_MARGIN }}>
<SubscriptionFeedCategoryContextMenu
category={category}
feedIds={subscriptionIds}
view={view}
asChild
>
<SubscriptionFeedCategoryContextMenu feedIds={subscriptionIds} asChild>
<ItemPressable
itemStyle={ItemPressableStyle.Grouped}
onPress={() => {
@@ -111,3 +96,5 @@ export const CategoryGrouped = memo(
)
},
)
CategoryGrouped.displayName = "CategoryGrouped"
@@ -1,5 +1,4 @@
import type { FC } from "react"
import { View } from "react-native"
import { useSortedUngroupedSubscription } from "@/src/store/subscription/hooks"
@@ -14,18 +13,12 @@ export const UnGroupedList: FC<{
const sortOrder = useFeedListSortOrder()
const sortedSubscriptionIds = useSortedUngroupedSubscription(subscriptionIds, sortBy, sortOrder)
return (
<>
{sortedSubscriptionIds.map((id, index) => (
<View key={id}>
<SubscriptionItem
key={id}
id={id}
isFirst={false}
isLast={!!isGroupLast && index === sortedSubscriptionIds.length - 1}
/>
</View>
))}
</>
)
return sortedSubscriptionIds.map((id, index) => (
<SubscriptionItem
key={id}
id={id}
isFirst={false}
isLast={!!isGroupLast && index === sortedSubscriptionIds.length - 1}
/>
))
}
@@ -1,4 +1,3 @@
import type { FeedViewType } from "@follow/constants"
import { cn } from "@follow/utils"
import { memo, useContext } from "react"
import { Text, View } from "react-native"
@@ -12,12 +11,7 @@ import { ItemPressableStyle } from "@/src/components/ui/pressable/enum"
import { ItemPressable } from "@/src/components/ui/pressable/ItemPressable"
import { WifiOffCuteReIcon } from "@/src/icons/wifi_off_cute_re"
import { useNavigation } from "@/src/lib/navigation/hooks"
import {
closeDrawer,
getHorizontalScrolling,
selectFeed,
useSelectedFeed,
} from "@/src/modules/screen/atoms"
import { closeDrawer, getHorizontalScrolling, selectFeed } from "@/src/modules/screen/atoms"
import { FeedScreen } from "@/src/screens/(stack)/feeds/[feedId]"
import { useFeed, usePrefetchFeed } from "@/src/store/feed/hooks"
import { useSubscription } from "@/src/store/subscription/hooks"
@@ -38,10 +32,6 @@ export const SubscriptionItem = memo(
const inGrouped = !!useContext(GroupedContext)
const { isLoading } = usePrefetchFeed(id, { enabled: !subscription && !feed })
const view = useSelectedFeed((r) => (r && r.type === "view" ? r.viewId : undefined)) as
| FeedViewType
| undefined
const navigation = useNavigation()
if (isLoading) {
return (
@@ -63,7 +53,7 @@ export const SubscriptionItem = memo(
"rounded-b-[10px]": isLast,
})}
>
<SubscriptionFeedItemContextMenu id={id} view={view}>
<SubscriptionFeedItemContextMenu id={id}>
<ItemPressable
itemStyle={ItemPressableStyle.Grouped}
className={cn(
@@ -109,3 +99,4 @@ export const SubscriptionItem = memo(
)
},
)
SubscriptionItem.displayName = "SubscriptionItem"
+6 -1
View File
@@ -150,7 +150,7 @@ export const useSortedUngroupedSubscription = (
const result = sortMethod(a, b)
return sortOrder === "asc" ? result : -result
})
}, [ids, sortBy, sortOrder]),
}, [ids.toString(), sortBy, sortOrder]),
)
}
@@ -228,6 +228,11 @@ export const useSubscriptionCategory = (view?: FeedViewType) => {
)
}
export const getSubscriptionCategory = (view?: FeedViewType) => {
const state = useSubscriptionStore.getState()
return view === undefined ? [] : Array.from(state.categories[view])
}
export const useSubscriptionByFeedId = (feedId: string) =>
useSubscriptionStore(useCallback((state) => state.data[feedId] || null, [feedId]))
+1 -1
View File
@@ -54,7 +54,7 @@ export const useUnreadCounts = (subscriptionIds?: string[]): number => {
}
return count
},
[subscriptionIds],
[subscriptionIds?.toString()],
),
)
}