refactor: store action to class (#118)

* refactor: store action to class

Signed-off-by: Innei <i@innei.in>

* chore: cleanup

Signed-off-by: Innei <i@innei.in>

---------

Signed-off-by: Innei <i@innei.in>
This commit is contained in:
Innei
2024-07-08 19:30:36 +08:00
committed by GitHub
parent 6023993d3a
commit d134be201d
9 changed files with 146 additions and 159 deletions
+1 -2
View File
@@ -1,11 +1,10 @@
import { FEED_COLLECTION_LIST } from "@renderer/lib/constants"
import type { CombinedEntryModel } from "@renderer/models"
import { useRouteParamsSelector } from "./useRouteParams"
export function useAsRead(entry?: CombinedEntryModel) {
return useRouteParamsSelector((params) => {
if (params.feedId === FEED_COLLECTION_LIST) {
if (params.isCollection) {
return true
}
if (!entry) return false
+27 -13
View File
@@ -1,4 +1,12 @@
import { getReadonlyRoute, useReadonlyRouteSelector } from "@renderer/atoms/route"
import {
getReadonlyRoute,
useReadonlyRouteSelector,
} from "@renderer/atoms/route"
import {
FEED_COLLECTION_LIST,
ROUTE_ENTRY_PENDING,
ROUTE_FEED_PENDING,
} from "@renderer/lib/constants"
import { FeedViewType } from "@renderer/lib/enum"
import type { Params } from "react-router-dom"
import { useParams, useSearchParams } from "react-router-dom"
@@ -28,23 +36,34 @@ export const useRouteFeedId = () => {
return feedId
}
const parseRouteParams = (
params: Params<any>,
search: URLSearchParams,
) => {
export interface BizRouteParams {
view: FeedViewType
entryId?: string
feedId?: string
level?: string
isCollection: boolean
isAllFeeds: boolean
isPendingEntry: boolean
}
const parseRouteParams = (params: Params<any>, search: URLSearchParams): BizRouteParams => {
const _view = search.get("view")
const view = (
const view =
(_view && FeedViewTypeValues.includes(_view) ?
+_view :
FeedViewType.Articles) || FeedViewType.Articles
)
return {
view,
entryId: params.entryId || undefined,
feedId: params.feedId || undefined,
level: search.get("level") || undefined,
// alias
isCollection: params.feedId === FEED_COLLECTION_LIST,
isAllFeeds: params.feedId === ROUTE_FEED_PENDING,
isPendingEntry: params.entryId === ROUTE_ENTRY_PENDING,
}
}
@@ -56,12 +75,7 @@ export const useRouteParms = () => {
}
const noop = [] as any[]
export const useRouteParamsSelector = <T>(
selector: (params: {
entryId: string | undefined
feedId: string | undefined
level: string | undefined
view: FeedViewType
}) => T,
selector: (params: BizRouteParams) => T,
deps = noop,
): T =>
useReadonlyRouteSelector((route) => {
@@ -4,9 +4,7 @@ import {
useRouteParms,
} from "@renderer/hooks/biz/useRouteParams"
import {
FEED_COLLECTION_LIST,
levels,
ROUTE_FEED_PENDING,
views,
} from "@renderer/lib/constants"
import { shortcuts } from "@renderer/lib/shortcuts"
@@ -67,7 +65,7 @@ export const useEntriesByView = () => {
const routeParams = useRouteParms()
const unreadOnly = useGeneralSettingKey("unreadOnly")
const { level, feedId, view } = routeParams
const { level, feedId, view, isAllFeeds, isCollection } = routeParams
const folderIds = useFolderFeedsByFeedId(feedId)
@@ -78,7 +76,7 @@ export const useEntriesByView = () => {
...(unreadOnly === true && { read: false }),
})
const entries = useEntryIdsByFeedIdOrView(
feedId === ROUTE_FEED_PENDING ? view : feedId!,
isAllFeeds ? view : feedId!,
{
unread: unreadOnly,
view,
@@ -120,10 +118,10 @@ export const useEntriesByView = () => {
}, [entries, prevEntries, unreadOnly])
const sortedLocalEntries = useMemo(
() =>
feedId === FEED_COLLECTION_LIST ?
isCollection ?
sortEntriesIdByStarAt(localEntries) :
sortEntriesIdByEntryPublishedAt(localEntries),
[feedId, localEntries],
[isCollection, localEntries],
)
return {
@@ -28,7 +28,6 @@ import {
levels,
ROUTE_ENTRY_PENDING,
ROUTE_FEED_IN_FOLDER,
ROUTE_FEED_PENDING,
views,
} from "@renderer/lib/constants"
import { shortcuts } from "@renderer/lib/shortcuts"
@@ -63,20 +62,20 @@ export function EntryColumn() {
const entries = useEntriesByView()
const { entriesIds, isFetchingNextPage } = entries
const { entryId: activeEntryId, view, feedId: routeFeedId } = useRouteParms()
const { entryId: activeEntryId, view, feedId: routeFeedId, isPendingEntry, isCollection } = useRouteParms()
const activeEntry = useEntry(activeEntryId)
useEffect(() => {
if (!activeEntryId) return
if (
activeEntryId === ROUTE_ENTRY_PENDING ||
routeFeedId === FEED_COLLECTION_LIST
) { return }
isCollection || isPendingEntry
) return
const feedId = activeEntry?.feeds.id
if (!feedId) return
batchMarkUnread([feedId, activeEntryId])
}, [activeEntry, activeEntryId, routeFeedId])
}, [activeEntry?.feeds.id, activeEntryId, isCollection, isPendingEntry])
const handleMarkReadInRange = useEntryMarkReadHandler(entriesIds)
@@ -170,7 +169,7 @@ const ListHeader: FC<{
if (
typeof routerParams.feedId === "number" ||
routerParams.feedId === ROUTE_FEED_PENDING
routerParams.isAllFeeds
) {
subscriptionActions.markReadByView(routerParams.view)
} else if (
+48 -37
View File
@@ -1,15 +1,19 @@
import { apiClient } from "@renderer/lib/api-fetch"
import { getEntriesParams } from "@renderer/lib/utils"
import type { EntryModel, FeedModel } from "@renderer/models"
import type {
CombinedEntryModel,
EntryModel,
FeedModel,
} from "@renderer/models"
import { EntryService } from "@renderer/services"
import { produce } from "immer"
import { merge, omit } from "lodash-es"
import { feedActions } from "../feed"
import { feedUnreadActions } from "../unread"
import { createZustandStore, getStoreActions } from "../utils/helper"
import { createZustandStore } from "../utils/helper"
import { isHydrated } from "../utils/hydrate"
import type { EntryActions, EntryState } from "./types"
import type { EntryState } from "./types"
const createState = (): EntryState => ({
entries: {},
@@ -18,15 +22,18 @@ const createState = (): EntryState => ({
starIds: new Set(),
})
export const useEntryStore = createZustandStore<EntryState & EntryActions>(
"entry",
)((set, get) => ({
export const useEntryStore = createZustandStore<EntryState>("entry")(() => ({
...createState(),
}))
clear: () => {
const get = useEntryStore.getState
const set = useEntryStore.setState
class EntryActions {
clear() {
set(createState)
},
clearByFeedId(feedId) {
}
clearByFeedId(feedId: string) {
set((state) =>
produce(state, (draft) => {
const entryIds = draft.entries[feedId]
@@ -38,30 +45,31 @@ export const useEntryStore = createZustandStore<EntryState & EntryActions>(
delete draft.internal_feedId2entryIdSet[feedId]
}),
)
},
}
fetchEntryById: async (entryId: string) => {
async fetchEntryById(entryId: string) {
const { data } = await apiClient.entries.$get({
query: {
id: entryId,
},
})
if (data) {
get().upsertMany([
this.upsertMany([
// patch data, should omit `read` because the network race condition or server cache
omit(data, "read") as any,
])
}
return data
},
fetchEntries: async ({
}
async fetchEntries({
level,
id,
view,
read,
pageParam,
}) => {
}) {
const data = await apiClient.entries.$post({
json: {
publishedAfter: pageParam as string,
@@ -76,15 +84,16 @@ export const useEntryStore = createZustandStore<EntryState & EntryActions>(
})
if (data.data) {
get().upsertMany(data.data)
this.upsertMany(data.data)
}
return data
},
}
getFlattenMapEntries() {
return get().flatMapEntries
},
patch(entryId, changed) {
}
patch(entryId: string, changed: Partial<CombinedEntryModel>) {
set((state) =>
produce(state, (draft) => {
const entry = draft.flatMapEntries[entryId]
@@ -93,8 +102,9 @@ export const useEntryStore = createZustandStore<EntryState & EntryActions>(
return draft
}),
)
},
patchManyByFeedId(feedId, changed) {
}
patchManyByFeedId(feedId: string, changed: Partial<CombinedEntryModel>) {
set((state) =>
produce(state, (draft) => {
const ids = draft.entries[feedId]
@@ -107,8 +117,9 @@ export const useEntryStore = createZustandStore<EntryState & EntryActions>(
return draft
}),
)
},
patchAll(changed) {
}
patchAll(changed: Partial<CombinedEntryModel>) {
set((state) =>
produce(state, (draft) => {
for (const entry of Object.values(draft.flatMapEntries)) {
@@ -117,9 +128,9 @@ export const useEntryStore = createZustandStore<EntryState & EntryActions>(
return draft
}),
)
},
}
upsertMany(data) {
upsertMany(data: CombinedEntryModel[]) {
const feeds = [] as FeedModel[]
const entries = [] as EntryModel[]
const entry2Read = {} as Record<string, boolean>
@@ -186,26 +197,26 @@ export const useEntryStore = createZustandStore<EntryState & EntryActions>(
EntryService.bulkStoreFeedId(entryFeedMap)
EntryService.bulkStoreCollection(entryCollection)
}
},
}
markRead: (feedId: string, entryId: string, read: boolean) => {
markRead(feedId: string, entryId: string, read: boolean) {
feedUnreadActions.incrementByFeedId(feedId, read ? -1 : 1)
entryActions.patch(entryId, {
this.patch(entryId, {
read,
})
},
}
markReadByFeedId: (feedId: string) => {
markReadByFeedId(feedId: string) {
const state = get()
const entries = state.entries[feedId] || []
entries.forEach((entryId) => {
entryActions.markRead(feedId, entryId, true)
this.markRead(feedId, entryId, true)
})
feedUnreadActions.updateByFeedId(feedId, 0)
},
}
markStar: (entryId, star) => {
entryActions.patch(entryId, {
markStar(entryId: string, star: boolean) {
this.patch(entryId, {
collections: star ?
{
createdAt: new Date().toISOString(),
@@ -229,10 +240,10 @@ export const useEntryStore = createZustandStore<EntryState & EntryActions>(
} else {
EntryService.deleteCollection(entryId)
}
},
}))
}
}
export const entryActions = getStoreActions(useEntryStore)
export const entryActions = new EntryActions()
export const getEntry = (entryId: string) =>
useEntryStore.getState().flatMapEntries[entryId]
-28
View File
@@ -1,4 +1,3 @@
import type { apiClient } from "@renderer/lib/api-fetch"
import type { FeedViewType } from "@renderer/lib/enum"
import type { CombinedEntryModel } from "@renderer/models"
@@ -26,33 +25,6 @@ export interface EntryState {
// internal_updateSortIds: Record<FeedId, EntryId[]>
}
export interface EntryActions {
fetchEntries: (params: {
level?: string
id?: number | string
view?: number
read?: boolean
pageParam?: string
}) => Promise<Awaited<ReturnType<typeof apiClient.entries.$post>>>
fetchEntryById: (entryId: string) => Promise<CombinedEntryModel | undefined>
upsertMany: (entries: CombinedEntryModel[]) => void
patch: (entryId: string, changed: Partial<CombinedEntryModel>) => void
patchManyByFeedId: (
feedId: string,
changed: Partial<CombinedEntryModel>
) => void
patchAll: (changed: Partial<CombinedEntryModel>) => void
getFlattenMapEntries: () => Record<string, CombinedEntryModel>
markRead: (feedId: string, entryId: string, read: boolean) => void
markReadByFeedId: (feedId: string) => void
markStar: (entryId: string, starred: boolean) => void
clear: () => void
clearByFeedId: (feedId: string) => void
}
export interface EntryFilter {
unread?: boolean
view?: FeedViewType
+17 -11
View File
@@ -2,19 +2,25 @@ import type { FeedModel } from "@renderer/models"
import { FeedService } from "@renderer/services"
import { produce } from "immer"
import { createZustandStore, getStoreActions } from "../utils/helper"
import { createZustandStore } from "../utils/helper"
import { isHydrated } from "../utils/hydrate"
import type { FeedActions, FeedState } from "./types"
import type { FeedState } from "./types"
export const useFeedStore = createZustandStore<FeedState & FeedActions>(
export const useFeedStore = createZustandStore<FeedState >(
"feed",
)((set) => ({
)(() => ({
feeds: {},
}))
const set = useFeedStore.setState
// const get = useFeedStore.getState
class FeedActions {
clear() {
set({ feeds: {} })
},
upsertMany(feeds) {
}
upsertMany(feeds: FeedModel[]) {
if (isHydrated()) {
FeedService.upsertMany(feeds)
}
@@ -27,9 +33,9 @@ export const useFeedStore = createZustandStore<FeedState & FeedActions>(
}
}),
)
},
}
patch(feedId, patch) {
patch(feedId: string, patch: Partial<FeedModel>) {
set((state) =>
produce(state, (state) => {
const feed = state.feeds[feedId]
@@ -38,9 +44,9 @@ export const useFeedStore = createZustandStore<FeedState & FeedActions>(
Object.assign(feed, patch)
}),
)
},
}))
export const feedActions = getStoreActions(useFeedStore)
}
}
export const feedActions = new FeedActions()
export const getFeedById = (feedId: string): Nullable<FeedModel> =>
useFeedStore.getState().feeds[feedId]
+2 -4
View File
@@ -59,8 +59,6 @@ const set = useSubscriptionStore.setState
const get = useSubscriptionStore.getState
class SubscriptionActions {
static shared = new SubscriptionActions()
async fetchByView(view?: FeedViewType) {
const res = await apiClient.subscriptions.$get({
query: { view: String(view) },
@@ -80,7 +78,7 @@ class SubscriptionActions {
}
morphResponseData(res.data)
SubscriptionActions.shared.upsertMany(res.data)
this.upsertMany(res.data)
feedActions.upsertMany(res.data.map((s) => s.feeds))
return res.data
@@ -178,4 +176,4 @@ class SubscriptionActions {
}
}
export const subscriptionActions = SubscriptionActions.shared
export const subscriptionActions = new SubscriptionActions()
+41 -51
View File
@@ -2,51 +2,33 @@ import { apiClient } from "@renderer/lib/api-fetch"
import type { FeedViewType } from "@renderer/lib/enum"
import { FeedUnreadService } from "@renderer/services"
import { createZustandStore, getStoreActions } from "./utils/helper"
import { createZustandStore } from "./utils/helper"
interface UnreadState {
data: Record<string, number>
}
interface FeedUnreadActions {
updateByFeedId: (feedId: string, unread: number) => void
fetchUnreadByView: (view?: FeedViewType) => Promise<Record<string, number>>
fetchUnreadAll: () => Promise<Record<string, number>>
incrementByFeedId: (feedId: string, inc: number) => void
subscribeUnreadCount: (
fn: (count: number) => void,
immediately?: boolean
) => () => void
internal_reset: () => void
internal_setValue: (data: [string, number][]) => void
clear: () => void
hydrate: (
data: {
id: string
count: number
}[],
) => void
}
/**
* Store for `feed` unread count
*/
export const useFeedUnreadStore = createZustandStore<
UnreadState & FeedUnreadActions
>("unread")((set, get) => ({
data: {},
export const useFeedUnreadStore = createZustandStore<UnreadState>("unread")(
() => ({
data: {},
}),
)
internal_reset() {
const set = useFeedUnreadStore.setState
const get = useFeedUnreadStore.getState
class FeedUnreadActions {
private internal_reset() {
set({ data: {} })
FeedUnreadService.clear()
},
}
clear() {
this.internal_reset()
},
internal_setValue(data) {
}
private internal_setValue(data: [string, number][]) {
set((state) => {
state.data = { ...state.data }
for (const [key, value] of data) {
@@ -55,19 +37,20 @@ export const useFeedUnreadStore = createZustandStore<
FeedUnreadService.updateFeedUnread(data)
return { ...state }
})
},
}
async fetchUnreadByView(view) {
async fetchUnreadByView(view: FeedViewType | undefined) {
const unread = await apiClient.reads.$get({
query: { view: String(view) },
})
const { data } = unread
get().internal_setValue(Object.entries(data))
this.internal_setValue(Object.entries(data))
return data
},
}
async fetchUnreadAll() {
const unread = await apiClient.reads.$get({
query: {},
@@ -76,21 +59,23 @@ export const useFeedUnreadStore = createZustandStore<
const { data } = unread
this.internal_reset()
get().internal_setValue(Object.entries(data))
this.internal_setValue(Object.entries(data))
return data
},
incrementByFeedId: (feedId, inc: number) => {
}
incrementByFeedId(feedId: string, inc: number) {
const state = get()
const cur = state.data[feedId]
state.internal_setValue([[feedId, Math.max(0, (cur || 0) + inc)]])
},
updateByFeedId: (feedId, unread) => {
get().internal_setValue([[feedId, unread]])
},
this.internal_setValue([[feedId, Math.max(0, (cur || 0) + inc)]])
}
subscribeUnreadCount(fn, immediately) {
const handler = (state: UnreadState & FeedUnreadActions): void => {
updateByFeedId(feedId: string, unread: number) {
this.internal_setValue([[feedId, unread]])
}
subscribeUnreadCount(fn: (count: number) => void, immediately?: boolean) {
const handler = (state: UnreadState): void => {
let unread = 0
for (const key in state.data) {
unread += state.data[key]
@@ -102,9 +87,14 @@ export const useFeedUnreadStore = createZustandStore<
handler(get())
}
return useFeedUnreadStore.subscribe(handler)
},
}
hydrate(data) {
hydrate(
data: {
id: string
count: number
}[],
) {
set((state) => {
state.data = { ...state.data }
@@ -114,7 +104,7 @@ export const useFeedUnreadStore = createZustandStore<
return { ...state }
})
},
}))
}
}
export const feedUnreadActions = getStoreActions(useFeedUnreadStore)
export const feedUnreadActions = new FeedUnreadActions()