diff --git a/package.json b/package.json index 474321d24..cfd119ef8 100644 --- a/package.json +++ b/package.json @@ -79,6 +79,7 @@ "rehype-sanitize": "6.0.0", "rehype-stringify": "10.0.0", "sonner": "^1.5.0", + "superjson": "2.2.1", "swiper": "11.1.4", "tailwind-merge": "2.3.0", "tailwindcss-animate": "1.0.7", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 601678206..a6c57ac7a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -181,6 +181,9 @@ importers: sonner: specifier: ^1.5.0 version: 1.5.0(patch_hash=6s3tquyt5wnkqaogymn3mkivuq)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + superjson: + specifier: 2.2.1 + version: 2.2.1 swiper: specifier: 11.1.4 version: 11.1.4 @@ -2472,6 +2475,10 @@ packages: resolution: {integrity: sha512-U71cyTamuh1CRNCfpGY6to28lxvNwPG4Guz/EVjgf3Jmzv0vlDp1atT9eS5dDjMYHucpHbWns6Lwf3BKz6svdw==} engines: {node: '>= 0.6'} + copy-anything@3.0.5: + resolution: {integrity: sha512-yCEafptTtb4bk7GLEQoM8KVJpxAfdBJYaXyzQEgQQQgYrZiDp8SJmGKlYza6CYjEDNstAdNdKA3UuoULlEbS6w==} + engines: {node: '>=12.13'} + core-js-compat@3.37.1: resolution: {integrity: sha512-9TNiImhKvQqSUkOvk/mMRZzOANTiEVC7WaBNhHcKM7x+/5E1l5NvsysR19zuDQScE8k+kfQXWRN3AtS/eOSHpg==} @@ -3531,6 +3538,10 @@ packages: resolution: {integrity: sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==} engines: {node: '>=10'} + is-what@4.1.16: + resolution: {integrity: sha512-ZhMwEosbFJkA0YhFnNDgTM4ZxDRsS6HqTo7qsZM08fehyRYIYa0yHu5R6mgo1n/8MgaPBXiPimPD77baVFYg+A==} + engines: {node: '>=12.13'} + isarray@1.0.0: resolution: {integrity: sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==} @@ -4840,6 +4851,10 @@ packages: resolution: {integrity: sha512-MvjXzkz/BOfyVDkG0oFOtBxHX2u3gKbMHIF/dXblZsgD3BWOFLmHovIpZY7BykJdAjcqRCBi1WYBNdEC9yI7vg==} engines: {node: '>= 8.0'} + superjson@2.2.1: + resolution: {integrity: sha512-8iGv75BYOa0xRJHK5vRLEjE2H/i4lulTjzpUXic3Eg8akftYjkmQDa8JARQ42rlczXyFR3IeRoeFCc7RxHsYZA==} + engines: {node: '>=16'} + supports-color@5.5.0: resolution: {integrity: sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==} engines: {node: '>=4'} @@ -7771,6 +7786,10 @@ snapshots: cookie@0.6.0: {} + copy-anything@3.0.5: + dependencies: + is-what: 4.1.16 + core-js-compat@3.37.1: dependencies: browserslist: 4.23.0 @@ -9186,6 +9205,8 @@ snapshots: is-unicode-supported@0.1.0: {} + is-what@4.1.16: {} + isarray@1.0.0: {} isbinaryfile@4.0.10: {} @@ -10612,6 +10633,10 @@ snapshots: transitivePeerDependencies: - supports-color + superjson@2.2.1: + dependencies: + copy-anything: 3.0.5 + supports-color@5.5.0: dependencies: has-flag: 3.0.0 diff --git a/src/renderer/src/components/entry-column/index.tsx b/src/renderer/src/components/entry-column/index.tsx index 5d55c1b03..5febdd889 100644 --- a/src/renderer/src/components/entry-column/index.tsx +++ b/src/renderer/src/components/entry-column/index.tsx @@ -10,20 +10,19 @@ import { views } from "@renderer/lib/constants" import { FeedViewType } from "@renderer/lib/enum" import { buildStorageNS } from "@renderer/lib/ns" import { getEntriesParams } from "@renderer/lib/utils" -import type { EntryModel } from "@renderer/models" import { useEntries } from "@renderer/queries/entries" import { feedActions, subscriptionActions, useFeedStore, } from "@renderer/store" -import { entryActions } from "@renderer/store/entry" +import { entryActions, useEntryIdsByFeedIdOrView } from "@renderer/store/entry" import { m } from "framer-motion" import { useAtom, useAtomValue } from "jotai" import { atomWithStorage } from "jotai/utils" import { debounce } from "lodash-es" import type { FC } from "react" -import { forwardRef, useCallback, useState } from "react" +import { forwardRef, useCallback, useMemo, useRef, useState } from "react" import type { ListRange } from "react-virtuoso" import { Virtuoso, VirtuosoGrid } from "react-virtuoso" import { useEventCallback } from "usehooks-ts" @@ -48,11 +47,8 @@ const { setActiveEntry } = feedActions export function EntryColumn() { const activeList = useFeedStore((state) => state.activeList) - const entries = useEntriesByTab() - - const entriesIds = (entries.data?.pages?.flatMap((page) => - page.data?.map((entry) => entry.entries.id), - ) || []) as string[] + const entries = useEntriesByView() + const { entriesIds } = entries let Item: FC @@ -128,18 +124,18 @@ export function EntryColumn() { rangeChanged: handleRangeChange, totalCount: entries.data?.pages?.[0]?.total, endReached: () => entries.hasNextPage && entries.fetchNextPage(), - data: entries.data?.pages.flatMap((page) => page.data) || [], + data: entriesIds, itemContent: useCallback( - (_, entry: EntryModel | undefined) => { - if (!entry) return null + (_, entryId: string) => { + if (!entryId) return null return ( - + ) }, @@ -169,22 +165,52 @@ export function EntryColumn() { ) } -const useEntriesByTab = () => { +const useEntriesByView = () => { const activeList = useFeedStore(useShallow((state) => state.activeList)) const unreadOnly = useAtomValue(unreadOnlyAtom) - return useEntries({ + const query = useEntries({ level: activeList?.level, id: activeList?.id, view: activeList?.view, ...(unreadOnly === true && { read: false }), }) + const entries = useEntryIdsByFeedIdOrView(activeList.id, { + unread: unreadOnly, + }) + + // in unread only entries only can grow the data, but not shrink + // so we memo this previous data to avoid the flicker + const prevEntries = useRef(entries) + const nextEntries = useMemo(() => { + if (!unreadOnly) { + prevEntries.current = [] + return entries + } + if (!prevEntries.current) { + prevEntries.current = entries + return entries + } + if (entries.length > prevEntries.current.length) { + prevEntries.current = entries + return entries + } + // merge the new entries with the old entries, and unqiue them + const nextIds = [...new Set([...prevEntries.current, ...entries])] + prevEntries.current = nextIds + return nextIds + }, [entries, prevEntries, unreadOnly]) + + return { + ...query, + entriesIds: nextEntries, + } } const ListHeader: FC = () => { const activeList = useFeedStore(useShallow((state) => state.activeList)) const [unreadOnly, setUnreadOnly] = useAtom(unreadOnlyAtom) - const entries = useEntriesByTab() + const entries = useEntriesByView() const [markPopoverOpen, setMarkPopoverOpen] = useState(false) const handleMarkAllAsRead = useCallback(async () => { diff --git a/src/renderer/src/components/entry-content/index.tsx b/src/renderer/src/components/entry-content/index.tsx index 8a237f03e..6dca8202c 100644 --- a/src/renderer/src/components/entry-content/index.tsx +++ b/src/renderer/src/components/entry-content/index.tsx @@ -2,80 +2,89 @@ import { useBizQuery } from "@renderer/hooks/useBizQuery" import { parseHtml } from "@renderer/lib/parse-html" import type { ActiveEntry } from "@renderer/models" import { Queries } from "@renderer/queries" -import { useFeedStore } from "@renderer/store" +import { useEntry, useFeedStore } from "@renderer/store" import { m } from "framer-motion" import { useEffect, useState } from "react" import { EntryShare } from "./share" -export function EntryContent({ entryId }: { entryId: ActiveEntry }) { - const entry = useBizQuery(Queries.entries.byId(entryId), { - enabled: !!entryId, - }) +export const EntryContent = ({ entry }: { entry: ActiveEntry }) => { const activeList = useFeedStore((state) => state.activeList) + if (!entry) { + return ( + + logo + {activeList?.name} + + ) + } + + return +} + +function EntryContentRender({ entryId }: { entryId: string }) { + useBizQuery(Queries.entries.byId(entryId), { + staleTime: 300_000, + }) + + const entry = useEntry(entryId) + const [content, setContent] = useState() useEffect(() => { - if (entry.data?.entries.content) { - parseHtml(entry.data?.entries.content).then((parsed) => { + if (entry?.entries.content) { + parseHtml(entry?.entries.content).then((parsed) => { setContent(parsed.content) }) } else { setContent(undefined) } - }, [entry.data?.entries.content]) + }, [entry?.entries.content]) - return entry.data ? - ( - <> - -
- - - -
- - ) : - ( + return ( + <> + + + + ) } diff --git a/src/renderer/src/components/feed-column/index.tsx b/src/renderer/src/components/feed-column/index.tsx index 269c31e98..074f89993 100644 --- a/src/renderer/src/components/feed-column/index.tsx +++ b/src/renderer/src/components/feed-column/index.tsx @@ -1,5 +1,5 @@ import { ActionButton } from "@renderer/components/ui/button" -import { UserButton } from "@renderer/components/user-button" +import { ProfileButton } from "@renderer/components/user-button" import { APP_NAME, levels, views } from "@renderer/lib/constants" import { stopPropagation } from "@renderer/lib/dom" import { clamp, cn } from "@renderer/lib/utils" @@ -91,11 +91,7 @@ export function FeedColumn() { )}
- - - - - + @@ -103,6 +99,7 @@ export function FeedColumn() {
+
{ - const query = useBizQuery(Queries.subscription.byView(view)) +const useData = (view: FeedViewType) => { + useBizQuery(Queries.subscription.byView(view)) + const data = useSubscriptionByView(view) // TODO Refactor this into category store return useMemo(() => { - if (!query.data) return null const categories = { list: {}, } as { @@ -33,44 +34,42 @@ const useData = (view?: FeedViewType) => { > } const domains: Record = {} - const subscriptions = structuredClone(query.data) + const subscriptions = structuredClone(data) - if (query) { - for (const subscription of subscriptions) { - if (!subscription.category && subscription.feeds.siteUrl) { + for (const subscription of subscriptions) { + if (!subscription.category && subscription.feeds.siteUrl) { + const { domain } = parse(subscription.feeds.siteUrl) + if (domain) { + if (!domains[domain]) { + domains[domain] = 0 + } + domains[domain]++ + } + } + } + + for (const subscription of subscriptions) { + if (!subscription.category) { + if (subscription.feeds.siteUrl) { const { domain } = parse(subscription.feeds.siteUrl) - if (domain) { - if (!domains[domain]) { - domains[domain] = 0 - } - domains[domain]++ + if (domain && domains[domain] > 1) { + subscription.category = + domain.slice(0, 1).toUpperCase() + domain.slice(1) } } - } - } - if (query) { - for (const subscription of subscriptions) { if (!subscription.category) { - if (subscription.feeds.siteUrl) { - const { domain } = parse(subscription.feeds.siteUrl) - if (domain && domains[domain] > 1) { - subscription.category = - domain.slice(0, 1).toUpperCase() + domain.slice(1) - } - } - if (!subscription.category) { - subscription.category = "" - } + subscription.category = "" } - if (!categories.list[subscription.category]) { - categories.list[subscription.category] = { - list: [], - } - } - - categories.list[subscription.category].list.push(subscription) } + if (!categories.list[subscription.category]) { + categories.list[subscription.category] = { + list: [], + } + } + + categories.list[subscription.category].list.push(subscription) } + const list = Object.entries(categories.list).map(([name, list]) => ({ name, list: list.list, @@ -79,7 +78,7 @@ const useData = (view?: FeedViewType) => { return { list, } as FeedListModel - }, [query]) + }, [data]) } export function FeedList({ className, @@ -87,7 +86,7 @@ export function FeedList({ hideTitle, }: { className?: string - view?: number + view: number hideTitle?: boolean }) { const [expansion, setExpansion] = useState(false) diff --git a/src/renderer/src/components/icons/user.tsx b/src/renderer/src/components/icons/user.tsx new file mode 100644 index 000000000..926d681cd --- /dev/null +++ b/src/renderer/src/components/icons/user.tsx @@ -0,0 +1,22 @@ +import type { SVGAttributes } from "react" + +export function UserArrowLeftIcon(props: SVGAttributes) { + return ( + + + + ) +} diff --git a/src/renderer/src/components/ui/button/index.tsx b/src/renderer/src/components/ui/button/index.tsx index 4b10d5ca2..9cd2dad71 100644 --- a/src/renderer/src/components/ui/button/index.tsx +++ b/src/renderer/src/components/ui/button/index.tsx @@ -64,7 +64,7 @@ export const ActionButton = React.forwardRef< // @see https://github.com/radix-ui/primitives/issues/2248#issuecomment-2147056904 onFocusCapture={stopPropagation} className={cn( - "no-drag-region flex items-center text-xl", + "no-drag-region flex size-8 items-center text-xl", active && "bg-zinc-500/15 hover:bg-zinc-500/20", className, )} diff --git a/src/renderer/src/components/ui/modal/stacked/constants.ts b/src/renderer/src/components/ui/modal/stacked/constants.ts new file mode 100644 index 000000000..77eda61f8 --- /dev/null +++ b/src/renderer/src/components/ui/modal/stacked/constants.ts @@ -0,0 +1,19 @@ +import type { Target } from "framer-motion" + +import { microReboundPreset } from "../../constants/spring" + +const enterStyle: Target = { + scale: 1, + opacity: 1, +} +const initialStyle: Target = { + scale: 0.96, + opacity: 0, +} + +export const modalMontionConfig = { + initial: initialStyle, + animate: enterStyle, + exit: initialStyle, + transition: microReboundPreset, +} diff --git a/src/renderer/src/components/ui/modal/stacked/modal.tsx b/src/renderer/src/components/ui/modal/stacked/modal.tsx index 12c956b86..e368af529 100644 --- a/src/renderer/src/components/ui/modal/stacked/modal.tsx +++ b/src/renderer/src/components/ui/modal/stacked/modal.tsx @@ -1,7 +1,6 @@ import * as Dialog from "@radix-ui/react-dialog" import { stopPropagation } from "@renderer/lib/dom" import { cn } from "@renderer/lib/utils" -import type { Target, Transition } from "framer-motion" import { m, useAnimationControls } from "framer-motion" import { useSetAtom } from "jotai" import type { SyntheticEvent } from "react" @@ -16,9 +15,9 @@ import { } from "react" import { useEventCallback } from "usehooks-ts" -import { microReboundPreset } from "../../constants/spring" import { DialogOverlay } from "../../dialog" import { Divider } from "../../divider" +import { modalMontionConfig } from "./constants" import type { CurrentModalContentProps, ModalContentPropsInternal, @@ -26,18 +25,6 @@ import type { import { CurrentModalContext, modalStackAtom } from "./context" import type { ModalProps } from "./types" -const enterStyle: Target = { - scale: 1, - opacity: 1, -} -const initialStyle: Target = { - scale: 0.96, - opacity: 0, -} -const modalTransition: Transition = { - ...microReboundPreset, -} - export const ModalInternal: Component<{ item: ModalProps & { id: string } index: number @@ -87,7 +74,7 @@ export const ModalInternal: Component<{ const animateController = useAnimationControls() useEffect(() => { - animateController.start(enterStyle) + animateController.start(modalMontionConfig.animate) }, [animateController]) const noticeModal = useCallback(() => { animateController @@ -183,14 +170,11 @@ export const ModalInternal: Component<{ > { + const modal = useCurrentModal() + return ( +
+ +
+ Sign in to + + + {APP_NAME} + +
+
+ + +
+
+
+ ) +} + +interface LoginProps { + method?: "redirect" | "modal" +} +export const LoginButton: FC = (props) => { + const { method } = props + const modalStack = useModalStack() + const Content = ( + { + modalStack.present({ + CustomModalComponent: ({ children }) => children, + title: "Login", + content: LoginModalContent, + clickOutsideToDismiss: true, + }) + } : + undefined + } + tooltip="Login" + > + + + ) + return method === "modal" ? + ( + Content + ) : + ( + + {Content} + + ) +} +export const ProfileButton: FC = (props) => { + const { status } = useSession() + + if (status !== "authenticated") { + return + } + return ( + + + + + + ) +} export function UserButton({ className, hideName, + ...props }: { className?: string hideName?: boolean -}) { - const { data: session, status } = useSession() +} & LoginProps) { + const { session, status } = useSession() if (status !== "authenticated") { - return ( - - - - ) + return } return ( diff --git a/src/renderer/src/hono.ts b/src/renderer/src/hono.ts index 9189f8f8f..c54391de1 100644 --- a/src/renderer/src/hono.ts +++ b/src/renderer/src/hono.ts @@ -373,6 +373,7 @@ declare const routes: hono_hono_base.HonoBase useCallback(() => { - signOut() -}, []) +export const useSignOut = () => + useCallback(() => { + signOut() + + // clear local store data + clearLocalPersistStoreData() + + // Clear query cache + localStorage.removeItem(QUERY_PERSIST_KEY) + // Clear local storage + // TODO + }, []) diff --git a/src/renderer/src/lib/api-fetch.ts b/src/renderer/src/lib/api-fetch.ts index 6c08d7f09..322ca790d 100644 --- a/src/renderer/src/lib/api-fetch.ts +++ b/src/renderer/src/lib/api-fetch.ts @@ -6,6 +6,7 @@ import { ofetch } from "ofetch" export const apiFetch = ofetch.create({ baseURL: import.meta.env.VITE_API_URL, credentials: "include", + retry: false, onRequest: async ({ options }) => { if (options.method && options.method.toLowerCase() !== "get") { const csrfToken = await getCsrfToken() diff --git a/src/renderer/src/lib/auth.ts b/src/renderer/src/lib/auth.ts new file mode 100644 index 000000000..7d49b0d10 --- /dev/null +++ b/src/renderer/src/lib/auth.ts @@ -0,0 +1,14 @@ +import { signIn } from "@hono/auth-js/react" + +export const LOGIN_CALLBACK_URL = `${import.meta.env.VITE_WEB_URL}/redirect?app=follow` +export const loginHandler = (provider: string) => { + if (window.electron) { + window.open( + `${import.meta.env.VITE_WEB_URL}/login?provider=${provider}`, + ) + } else { + signIn(provider, { + callbackUrl: LOGIN_CALLBACK_URL, + }) + } +} diff --git a/src/renderer/src/lib/constants.tsx b/src/renderer/src/lib/constants.tsx index c5b0cb133..a82e5046e 100644 --- a/src/renderer/src/lib/constants.tsx +++ b/src/renderer/src/lib/constants.tsx @@ -1,3 +1,5 @@ +import { buildStorageNS } from "./ns" + export const levels = { view: "view", folder: "folder", @@ -43,8 +45,6 @@ export const views = [ }, ] -export const APP_NAME = "Follow" - export const settingTabs = [ { name: "General", @@ -67,3 +67,8 @@ export const settingTabs = [ className: "i-mingcute-user-setting-line", }, ] + +//// +export const APP_NAME = "Follow" +/// Local storage keys +export const QUERY_PERSIST_KEY = buildStorageNS("REACT_QUERY_OFFLINE_CACHE") diff --git a/src/renderer/src/lib/query-client.ts b/src/renderer/src/lib/query-client.ts index 96c978ff2..00f125ce1 100644 --- a/src/renderer/src/lib/query-client.ts +++ b/src/renderer/src/lib/query-client.ts @@ -1,23 +1,32 @@ import { createSyncStoragePersister } from "@tanstack/query-sync-storage-persister" import { QueryClient } from "@tanstack/react-query" -import { persistQueryClient } from "@tanstack/react-query-persist-client" +import { FetchError } from "ofetch" + +import { QUERY_PERSIST_KEY } from "./constants" const queryClient = new QueryClient({ defaultOptions: { queries: { gcTime: Infinity, refetchInterval: 1000 * 60 * 10, - throwOnError: import.meta.env.DEV, + retryDelay: 1000, + retry(failureCount, error) { + console.error(error) + if (error instanceof FetchError && error.statusCode === undefined) { + return false + } + + return !!(3 - failureCount) + }, + // throwOnError: import.meta.env.DEV, }, }, }) - const localStoragePersister = createSyncStoragePersister({ storage: window.localStorage, + key: QUERY_PERSIST_KEY, }) - -persistQueryClient({ - queryClient, +export const persistConfig = { persister: localStoragePersister, dehydrateOptions: { shouldDehydrateQuery: (query) => { @@ -29,6 +38,6 @@ persistQueryClient({ } }, }, -}) +} export { queryClient } diff --git a/src/renderer/src/models/types.ts b/src/renderer/src/models/types.ts index b9c60a2b2..f47ba8f6c 100644 --- a/src/renderer/src/models/types.ts +++ b/src/renderer/src/models/types.ts @@ -10,7 +10,7 @@ export type ActiveList = { id: string | number name: string view: number -} | null +} export type FeedResponse = SubscriptionResponse[number]["feeds"] diff --git a/src/renderer/src/pages/(external)/layout.tsx b/src/renderer/src/pages/(external)/layout.tsx index 62ac36aa3..36969b874 100644 --- a/src/renderer/src/pages/(external)/layout.tsx +++ b/src/renderer/src/pages/(external)/layout.tsx @@ -1,7 +1,10 @@ +import { SessionProvider } from "@hono/auth-js/react" import { Outlet } from "react-router-dom" export function Component() { return ( - + + + ) } diff --git a/src/renderer/src/pages/(external)/login.tsx b/src/renderer/src/pages/(external)/login.tsx index a069d148f..2245fdd8c 100644 --- a/src/renderer/src/pages/(external)/login.tsx +++ b/src/renderer/src/pages/(external)/login.tsx @@ -1,21 +1,10 @@ import { signIn, useSession } from "@hono/auth-js/react" import { Button } from "@renderer/components/ui/button" +import { LOGIN_CALLBACK_URL, loginHandler } from "@renderer/lib/auth" import { APP_NAME } from "@renderer/lib/constants" import { useEffect, useState } from "react" import { useNavigate } from "react-router-dom" -const LOGIN_CALLBACK_URL = `${import.meta.env.VITE_WEB_URL}/redirect?app=follow` -const loginHandler = (provider: string) => { - if (window.electron) { - window.open( - `${import.meta.env.VITE_WEB_URL}/login?provider=${provider}`, - ) - } else { - signIn(provider, { - callbackUrl: LOGIN_CALLBACK_URL, - }) - } -} export function Component() { const { status } = useSession() const navigate = useNavigate() diff --git a/src/renderer/src/pages/(main)/(context)/(nonhome)/profile/index.tsx b/src/renderer/src/pages/(main)/(context)/(nonhome)/profile/index.tsx index 7419b95df..6ff8ec5a1 100644 --- a/src/renderer/src/pages/(main)/(context)/(nonhome)/profile/index.tsx +++ b/src/renderer/src/pages/(main)/(context)/(nonhome)/profile/index.tsx @@ -1,4 +1,3 @@ -import { useSession } from "@hono/auth-js/react" import { FeedList } from "@renderer/components/feed-column/list" import { Avatar, @@ -9,9 +8,10 @@ import { Button } from "@renderer/components/ui/button" import { useSignOut } from "@renderer/hooks/useAuth" import { views } from "@renderer/lib/constants" import { cn } from "@renderer/lib/utils" +import { useSession } from "@renderer/queries/auth" export function Component() { - const { data: session } = useSession() + const { session } = useSession() const signOut = useSignOut() return (
diff --git a/src/renderer/src/pages/(main)/(context)/index.tsx b/src/renderer/src/pages/(main)/(context)/index.tsx index 6bb92bf40..ecffb35bf 100644 --- a/src/renderer/src/pages/(main)/(context)/index.tsx +++ b/src/renderer/src/pages/(main)/(context)/index.tsx @@ -65,7 +65,7 @@ export function Component() { {!inWideMode && (
- +
)}
diff --git a/src/renderer/src/pages/(main)/layout.tsx b/src/renderer/src/pages/(main)/layout.tsx index 84290ceba..6702108cd 100644 --- a/src/renderer/src/pages/(main)/layout.tsx +++ b/src/renderer/src/pages/(main)/layout.tsx @@ -1,10 +1,8 @@ -import { useSession } from "@hono/auth-js/react" import { feedActions, useFeedStore } from "@renderer/store" import { useEffect } from "react" import { Outlet, useNavigate } from "react-router-dom" function MainLayout() { - const { status } = useSession() const navigate = useNavigate() const changed = useFeedStore( @@ -18,11 +16,6 @@ function MainLayout() { } }, [changed]) - if (status !== "authenticated") { - navigate("/login") - return null - } - return } diff --git a/src/renderer/src/pages/settings/profile.tsx b/src/renderer/src/pages/settings/profile.tsx index 24eaa6cf9..14fee338c 100644 --- a/src/renderer/src/pages/settings/profile.tsx +++ b/src/renderer/src/pages/settings/profile.tsx @@ -1,4 +1,3 @@ -import { useSession } from "@hono/auth-js/react" import { zodResolver } from "@hookform/resolvers/zod" import { SettingsTitle } from "@renderer/components/settings/title" import { Button } from "@renderer/components/ui/button" @@ -13,6 +12,7 @@ import { } from "@renderer/components/ui/form" import { Input } from "@renderer/components/ui/input" import { apiClient } from "@renderer/lib/api-fetch" +import { useSession } from "@renderer/queries/auth" import { useMutation } from "@tanstack/react-query" import { useForm } from "react-hook-form" import { toast } from "sonner" @@ -25,7 +25,7 @@ const formSchema = z.object({ }) export function Component() { - const { data: session } = useSession() + const { session } = useSession() const form = useForm>({ resolver: zodResolver(formSchema), diff --git a/src/renderer/src/providers/root-providers.tsx b/src/renderer/src/providers/root-providers.tsx index 9c611e990..ccd66139e 100644 --- a/src/renderer/src/providers/root-providers.tsx +++ b/src/renderer/src/providers/root-providers.tsx @@ -1,10 +1,9 @@ -import { SessionProvider } from "@hono/auth-js/react" import { ModalStackProvider } from "@renderer/components/ui/modal" import { Toaster } from "@renderer/components/ui/sonner" import { TooltipProvider } from "@renderer/components/ui/tooltip" import { jotaiStore } from "@renderer/lib/jotai" -import { queryClient } from "@renderer/lib/query-client" -import { QueryClientProvider } from "@tanstack/react-query" +import { persistConfig, queryClient } from "@renderer/lib/query-client" +import { PersistQueryClientProvider } from "@tanstack/react-query-persist-client" import { LazyMotion, MotionConfig } from "framer-motion" import { Provider } from "jotai" import type { FC, PropsWithChildren } from "react" @@ -21,16 +20,17 @@ export const RootProviders: FC = ({ children }) => ( ease: "easeInOut", }} > - - - - - - {children} - - - - + + + + + {children} + + + diff --git a/src/renderer/src/queries/auth.ts b/src/renderer/src/queries/auth.ts new file mode 100644 index 000000000..7642262b5 --- /dev/null +++ b/src/renderer/src/queries/auth.ts @@ -0,0 +1,72 @@ +import type { Session } from "@auth/core/types" +import type { GetSessionParams } from "@hono/auth-js/react" +import { authConfigManager } from "@hono/auth-js/react" +import { useBizQuery } from "@renderer/hooks/useBizQuery" +import { defineQuery } from "@renderer/lib/defineQuery" +import type { FetchError } from "ofetch" +import { ofetch } from "ofetch" + +export const auth = { + getSession: () => defineQuery(["auth", "session"], () => getSession()), +} + +export const useSession = () => { + const { data, isLoading, ...rest } = useBizQuery(auth.getSession(), { + retry(failureCount, error) { + const fetchError = error as FetchError + + if (fetchError.statusCode === undefined) { + return false + } + + return !!(3 - failureCount) + }, + }) + const { error } = rest + const fetchError = error as FetchError + + return { + session: data, + ...rest, + status: isLoading ? + "loading" : + data ? + "authenticated" : + fetchError?.statusCode === 401 ? + "unauthenticated" : + "error", + } +} + +/** + * Fetch session data, copy and patch code from @hono/auth-js/react + */ +export async function fetchData( + path: string, + + req: any = {}, +): Promise { + const config = authConfigManager.getConfig() + const url = `${config.baseUrl}${config.basePath}/${path}` + + const options: RequestInit = { + headers: { + "Content-Type": "application/json", + ...(req?.headers?.cookie ? { cookie: req.headers.cookie } : {}), + }, + credentials: config.credentials, + } + + if (req?.body) { + options.body = JSON.stringify(req.body) + options.method = "POST" + } + + const data = await ofetch(url, options) + + return data as T +} + +function getSession(params?: GetSessionParams) { + return fetchData("session", params) +} diff --git a/src/renderer/src/queries/entries.ts b/src/renderer/src/queries/entries.ts index 848957d4c..b6afd2481 100644 --- a/src/renderer/src/queries/entries.ts +++ b/src/renderer/src/queries/entries.ts @@ -1,4 +1,3 @@ -import { UnprocessableEntityError } from "@renderer/biz/error" import { useBizInfiniteQuery, useBizQuery } from "@renderer/hooks/useBizQuery" import { apiClient } from "@renderer/lib/api-fetch" import { defineQuery } from "@renderer/lib/defineQuery" @@ -24,31 +23,17 @@ export const entries = { id, view, read, + pageParam: pageParam as string, }), { rootKey: ["entries"], }, ), - byId: (id?: string | null) => - defineQuery( - ["entry", id], - async () => { - if (!id) { - throw new UnprocessableEntityError("id is required") - } - const res = await apiClient.entries.$get({ - query: { - id, - }, - }) - - return res.data - }, - { - rootKey: ["entries"], - }, - ), + byId: (id: string) => + defineQuery(["entry", id], async () => entryActions.fetchEntryById(id), { + rootKey: ["entries"], + }), preview: (id: string) => defineQuery( ["entries-preview", id], @@ -89,11 +74,7 @@ export const useEntries = ({ initialPageParam: undefined, }) -export const useEntriesPreview = ({ - id, -}: { - id?: string -}) => +export const useEntriesPreview = ({ id }: { id?: string }) => useBizQuery(entries.preview(id!), { enabled: !!id, }) diff --git a/src/renderer/src/queries/index.ts b/src/renderer/src/queries/index.ts index 8afd6de39..7b6a296bb 100644 --- a/src/renderer/src/queries/index.ts +++ b/src/renderer/src/queries/index.ts @@ -1,4 +1,5 @@ import { action } from "./actions" +import { auth } from "./auth" import { entries } from "./entries" import { feed } from "./feed" import { subscription } from "./subscriptions" @@ -8,4 +9,5 @@ export const Queries = { entries, feed, action, + auth, } diff --git a/src/renderer/src/store/entry.ts b/src/renderer/src/store/entry.ts index 588c83391..0dc7da98a 100644 --- a/src/renderer/src/store/entry.ts +++ b/src/renderer/src/store/entry.ts @@ -1,8 +1,11 @@ import { apiClient } from "@renderer/lib/api-fetch" +import type { FeedViewType } from "@renderer/lib/enum" import { getEntriesParams } from "@renderer/lib/utils" import type { EntryModel } from "@renderer/models" import { produce } from "immer" +import { merge, omit } from "lodash-es" +import { useFeedIdByView } from "./subscription" import { unreadActions } from "./unread" import { createZustandStore, getStoreActions } from "./utils/helper" @@ -11,9 +14,20 @@ type EntryId = string type EntriesIdTable = Record interface EntryState { + /** + * A map of feedId to entryIds + */ entries: EntriesIdTable + /** + * A map of entryId to entry + */ + flatMapEntries: Record + /** + * A map of feedId to entryId set, to quickly check if an entryId is in the feed + * The array is used to keep the order of the entries, and this set is used to quickly check if an entryId is in the feed + */ - flatMapEntries: Record + internal_feedId2entryIdSet: Record> } interface EntryActions { @@ -25,6 +39,7 @@ interface EntryActions { pageParam?: string }) => Promise>> + fetchEntryById: (entryId: string) => Promise upsertMany: (entries: EntryModel[]) => void optimisticUpdate: (entryId: string, changed: Partial) => void @@ -36,17 +51,42 @@ interface EntryActions { getFlattenMapEntries: () => Record markRead: (feedId: string, entryId: string, read: boolean) => void markReadByFeedId: (feedId: string) => void + + clear: () => void } export const useEntryStore = createZustandStore( "entry", { - version: 0, + version: 1, }, )((set, get) => ({ entries: {}, flatMapEntries: {}, + internal_feedId2entryIdSet: {}, + clear: () => { + set({ + entries: {}, + flatMapEntries: {}, + internal_feedId2entryIdSet: {}, + }) + }, + + fetchEntryById: async (entryId: string) => { + const { data } = await apiClient.entries.$get({ + query: { + id: entryId, + }, + }) + if (data) { + get().upsertMany([ + // patch data, should omit `read` because the network race condition or server cache + omit(data, "read") as any, + ]) + } + return data + }, fetchEntries: async ({ level, id, @@ -59,6 +99,7 @@ export const useEntryStore = createZustandStore( json: { publishedAfter: pageParam as string, read, + // withContent: true, ...getEntriesParams({ level, id, @@ -118,8 +159,26 @@ export const useEntryStore = createZustandStore( if (!draft.entries[entry.feeds.id]) { draft.entries[entry.feeds.id] = [] } - draft.entries[entry.feeds.id].push(entry.entries.id) - draft.flatMapEntries[entry.entries.id] = entry + + if (!draft.internal_feedId2entryIdSet[entry.feeds.id]) { + draft.internal_feedId2entryIdSet[entry.feeds.id] = new Set() + } + + if ( + !draft.internal_feedId2entryIdSet[entry.feeds.id].has( + entry.entries.id, + ) + ) { + draft.entries[entry.feeds.id].push(entry.entries.id) + draft.internal_feedId2entryIdSet[entry.feeds.id].add( + entry.entries.id, + ) + } + + draft.flatMapEntries[entry.entries.id] = merge( + draft.flatMapEntries[entry.entries.id] || {}, + entry, + ) } return draft }), @@ -127,7 +186,6 @@ export const useEntryStore = createZustandStore( }, markRead: (feedId: string, entryId: string, read: boolean) => { - console.log(feedId, "feedId") unreadActions.incrementByFeedId(feedId, read ? -1 : 1) entryActions.optimisticUpdate(entryId, { read, @@ -145,10 +203,60 @@ export const useEntryStore = createZustandStore( export const entryActions = getStoreActions(useEntryStore) -export const useEntriesByFeedId = (feedId: string) => - useEntryStore((state) => { - const entryIds = state.entries[feedId] || [] - return entryIds.map((id) => state.flatMapEntries[id]) - }) +interface EntryFilter { + unread?: boolean +} export const useEntry = (entryId: string) => useEntryStore((state) => state.flatMapEntries[entryId]) +export const useEntryIdsByFeedId = (feedId: string, filter?: EntryFilter) => + useEntryStore((state) => { + const data = state.entries[feedId] || [] + if (filter?.unread) { + const result = [] as string[] + for (const entryId of data) { + const entry = state.flatMapEntries[entryId] + if (!entry?.read) { + result.push(entryId) + } + } + return result + } + return data + }) + +export const useEntryIdsByView = (view: FeedViewType, filter?: EntryFilter) => { + const feedIds = useFeedIdByView(view) + return useEntryStore((state) => { + const data = [] as string[] + for (const feedId of feedIds) { + const entries = state.entries[feedId] || [] + + data.push(...entries) + } + + if (filter?.unread) { + const result = [] as string[] + for (const entryId of data) { + const entry = state.flatMapEntries[entryId] + if (!entry?.read) { + result.push(entryId) + } + } + return result + } + return data + }) +} + +export const useEntryIdsByFeedIdOrView = ( + feedIdOrView: string | FeedViewType, + filter: EntryFilter = {}, +) => { + const byView = useEntryIdsByView(feedIdOrView as FeedViewType, filter) + const byId = useEntryIdsByFeedId(feedIdOrView as string, filter) + + if (typeof feedIdOrView === "string") { + return byId + } + return byView +} diff --git a/src/renderer/src/store/subscription.ts b/src/renderer/src/store/subscription.ts index 6eaed2964..e6a02b03f 100644 --- a/src/renderer/src/store/subscription.ts +++ b/src/renderer/src/store/subscription.ts @@ -1,5 +1,5 @@ import { apiClient } from "@renderer/lib/api-fetch" -import type { FeedViewType } from "@renderer/lib/enum" +import { FeedViewType } from "@renderer/lib/enum" import type { SubscriptionModel } from "@renderer/models" import { produce } from "immer" @@ -10,56 +10,96 @@ import { createZustandStore, getStoreActions } from "./utils/helper" type FeedId = string interface SubscriptionState { data: Record + dataIdByView: Record } + interface SubscriptionActions { upsert: (feedId: FeedId, subscription: SubscriptionModel) => void fetchByView: (view?: FeedViewType) => Promise markReadByView: (view?: FeedViewType) => void internal_reset: () => void + clear: () => void } + +const emptyDataIdByView: Record = { + [FeedViewType.Articles]: [], + [FeedViewType.Audios]: [], + [FeedViewType.Notifications]: [], + [FeedViewType.Pictures]: [], + [FeedViewType.SocialMedia]: [], + [FeedViewType.Videos]: [], +} + export const useSubscriptionStore = createZustandStore< SubscriptionState & SubscriptionActions - >("subscription", { - version: 0, - })((set, get) => ({ - data: {}, - internal_reset() { - set({ data: {} }) - }, - async fetchByView(view) { - const res = await apiClient.subscriptions.$get({ - query: { view: String(view) }, - }) +>("subscription", { + version: 1, +})((set, get) => ({ + data: {}, + dataIdByView: { ...emptyDataIdByView }, - get().internal_reset() - res.data.forEach((subscription) => { - set((state) => - produce(state, (state) => { - state.data[subscription.feeds.id] = subscription - return state - }), - ) - }) + internal_reset() { + set({ + data: {}, + dataIdByView: { ...emptyDataIdByView }, + }) + }, + clear() { + get().internal_reset() + }, + async fetchByView(view) { + const res = await apiClient.subscriptions.$get({ + query: { view: String(view) }, + }) - return res.data - }, - upsert: (feedId, subscription) => { + // reset dataIdByView + if (view !== undefined) { + set((state) => ({ + ...state, + dataIdByView: { ...state.dataIdByView, [view]: [] }, + })) + } else { + set((state) => ({ + ...state, + dataIdByView: { ...emptyDataIdByView }, + })) + } + res.data.forEach((subscription) => { set((state) => produce(state, (state) => { - state.data[feedId] = subscription + state.data[subscription.feeds.id] = subscription + state.dataIdByView[subscription.view].push(subscription.feeds.id) return state }), ) - }, - markReadByView(view) { - const state = get() - for (const feedId in state.data) { - if (state.data[feedId].view === view) { - unreadActions.updateByFeedId(feedId, 0) - entryActions.optimisticUpdateManyByFeedId(feedId, { read: true }) - } + }) + + return res.data + }, + upsert: (feedId, subscription) => { + set((state) => + produce(state, (state) => { + state.data[feedId] = subscription + return state + }), + ) + }, + markReadByView(view) { + const state = get() + for (const feedId in state.data) { + if (state.data[feedId].view === view) { + unreadActions.updateByFeedId(feedId, 0) + entryActions.optimisticUpdateManyByFeedId(feedId, { read: true }) } - }, - })) + } + }, +})) export const subscriptionActions = getStoreActions(useSubscriptionStore) + +export const useFeedIdByView = (view: FeedViewType) => + useSubscriptionStore((state) => state.dataIdByView[view] || []) +export const useSubscriptionByView = (view: FeedViewType) => + useSubscriptionStore((state) => + state.dataIdByView[view].map((id) => state.data[id]), + ) diff --git a/src/renderer/src/store/ui.ts b/src/renderer/src/store/ui.ts index 9350da1de..926df750d 100644 --- a/src/renderer/src/store/ui.ts +++ b/src/renderer/src/store/ui.ts @@ -3,16 +3,24 @@ import { createZustandStore, getStoreActions } from "./utils/helper" interface UIState { entryColWidth: number } + +const createDefaultUIState = (): UIState => ({ + entryColWidth: 340, +}) interface UIActions { setEntryColWidth: (width: number) => void + + clear: () => void } -export const useUIStore = createZustandStore( - "ui", - { - version: 0, +export const useUIStore = createZustandStore("ui", { + version: 1, +})((set) => ({ + ...createDefaultUIState(), + + clear() { + set(createDefaultUIState()) }, -)((set) => ({ - entryColWidth: 340, + setEntryColWidth(width) { set({ entryColWidth: width }) }, diff --git a/src/renderer/src/store/unread.ts b/src/renderer/src/store/unread.ts index e3f227ebb..4135323fe 100644 --- a/src/renderer/src/store/unread.ts +++ b/src/renderer/src/store/unread.ts @@ -1,3 +1,6 @@ +/** + * Store for `feed` unread count + */ import { apiClient } from "@renderer/lib/api-fetch" import type { FeedViewType } from "@renderer/lib/enum" import { produce } from "immer" @@ -14,11 +17,13 @@ interface UnreadActions { incrementByFeedId: (feedId: string, inc: number) => void internal_reset: () => void + + clear: () => void } export const useUnreadStore = createZustandStore( "unread", { - version: 0, + version: 1, }, )((set) => ({ data: {}, @@ -27,6 +32,10 @@ export const useUnreadStore = createZustandStore( set({ data: {} }) }, + clear() { + this.internal_reset() + }, + async fetchUnreadByView(view) { const unread = await apiClient.reads.$get({ query: { view: String(view) }, @@ -64,10 +73,10 @@ export const useUnreadStore = createZustandStore( produce(state, (state) => { const cur = state.data[feedId] if (cur === undefined) { - state.data[feedId] = inc + state.data[feedId] = Math.max(0, inc) return state } - state.data[feedId] = (cur || 0) + inc + state.data[feedId] = Math.max(0, (cur || 0) + inc) return state }), ) diff --git a/src/renderer/src/store/utils/helper.ts b/src/renderer/src/store/utils/helper.ts index 60afdb686..b20391cb6 100644 --- a/src/renderer/src/store/utils/helper.ts +++ b/src/renderer/src/store/utils/helper.ts @@ -1,22 +1,35 @@ import { del, get, set } from "idb-keyval" +import { enableMapSet } from "immer" +import superjson from "superjson" // can use anything: serialize-javascript, devalue, etc. import type { StateCreator } from "zustand" -import type { PersistOptions, StateStorage } from "zustand/middleware" -import { createJSONStorage, persist } from "zustand/middleware" +import type { + PersistOptions, + PersistStorage, +} from "zustand/middleware" +import { persist } from "zustand/middleware" import { shallow } from "zustand/shallow" import { createWithEqualityFn } from "zustand/traditional" -export const dbStorage: StateStorage = { - getItem: async (name: string): Promise => - (await get(name)) || null, - setItem: async (name: string, value: string): Promise => { - await set(name, value) +declare const window: any +export const dbStorage: PersistStorage = { + getItem: async (name: string) => { + const data = (await get(name)) || null + + if (data === null) { + return null + } + + return superjson.parse(data) + }, + setItem: async (name, value) => { + await set(name, superjson.stringify(value)) }, removeItem: async (name: string): Promise => { await del(name) }, } - -export const zustandStorage = createJSONStorage(() => dbStorage) as any +enableMapSet() +export const zustandStorage = dbStorage export const createZustandStore = < @@ -40,8 +53,9 @@ export const createZustandStore = shallow, ) - Object.assign(window, { - [`__${name}`]() { + window.store = window.store || {} + Object.assign(window.store, { + [name]() { return newStore.getState() }, }) diff --git a/src/renderer/src/store/utils/local.ts b/src/renderer/src/store/utils/local.ts new file mode 100644 index 000000000..0ccbe8c14 --- /dev/null +++ b/src/renderer/src/store/utils/local.ts @@ -0,0 +1,13 @@ +import { entryActions } from "../entry" +import { subscriptionActions } from "../subscription" +import { uiActions } from "../ui" +import { unreadActions } from "../unread" + +export const clearLocalPersistStoreData = () => { + // All clear and reset method will aggregate here + [entryActions, subscriptionActions, unreadActions, uiActions].forEach( + (actions) => { + actions.clear() + }, + ) +} diff --git a/src/renderer/src/styles/base.css b/src/renderer/src/styles/base.css index 425b8b9c8..fce12fe18 100644 --- a/src/renderer/src/styles/base.css +++ b/src/renderer/src/styles/base.css @@ -5,7 +5,8 @@ body, @apply select-none; /* @apply bg-white; */ - font-family: "SN Pro", sans-serif; + --fo-font-family: "SN Pro", system-ui, sans-serif; + @apply font-theme; } button, diff --git a/src/renderer/src/styles/tailwind-extend.css b/src/renderer/src/styles/tailwind-extend.css index 96378f3ba..c1579de6d 100644 --- a/src/renderer/src/styles/tailwind-extend.css +++ b/src/renderer/src/styles/tailwind-extend.css @@ -22,4 +22,35 @@ .center { @apply flex items-center justify-center; } + + .shadow-perfect { + /* https://codepen.io/jh3y/pen/yLWgjpd */ + --tint: 214; + --alpha: 3; + --base: hsl(var(--tint, 214) 80% 27% / calc(var(--alpha, 4) * 1%)); + /** + * Use relative syntax to get to: hsl(221 25% 22% / 40%) + */ + --shade: hsl(from var(--base) calc(h + 8) 25 calc(l - 5)); + --perfect-shadow: 0 0 0 1px var(--base), 0 1px 1px -0.5px var(--shade), + 0 3px 3px -1.5px var(--shade), 0 6px 6px -3px var(--shade), + 0 12px 12px -6px var(--base), 0 24px 24px -12px var(--base); + box-shadow: var(--perfect-shadow); + } + + .perfect-sm { + --alpha: 1; + } + + .perfect-md { + --alpha: 2; + } + + [theme="dark"] .shadow-perfect { + --tint: 221; + } + + .shadow-modal { + @apply shadow-2xl shadow-stone-300 dark:shadow-stone-800; + } } diff --git a/tailwind.config.cjs b/tailwind.config.cjs index 7fccc894e..0515eaf98 100644 --- a/tailwind.config.cjs +++ b/tailwind.config.cjs @@ -18,7 +18,11 @@ module.exports = { "2xl": "1400px", }, }, + extend: { + fontFamily: { + theme: "var(--fo-font-family)", + }, colors: { border: "hsl(var(--border))", input: "hsl(var(--input))", diff --git a/types/authjs.d.ts b/types/authjs.d.ts index b3123273c..d309de7ea 100644 --- a/types/authjs.d.ts +++ b/types/authjs.d.ts @@ -1,5 +1,13 @@ declare module "@auth/core/types" { interface User { handle?: string | null + + id: string + name: string + image: string + } + + interface Session { + user: User } }