refactor: resign entry data flow and stroage, to support data offline, fix hono auth getSession (#55)
* feat: offline init Signed-off-by: Innei <i@innei.in> * feat: login modal Signed-off-by: Innei <i@innei.in> * fix: click area Signed-off-by: Innei <i@innei.in> * refactor: store persist engine Signed-off-by: Innei <i@innei.in> * fix: filter unread Signed-off-by: Innei <i@innei.in> * fix: unread race condition Signed-off-by: Innei <i@innei.in> --------- Signed-off-by: Innei <i@innei.in>
This commit is contained in:
@@ -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",
|
||||
|
||||
Generated
+25
@@ -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
|
||||
|
||||
@@ -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<UniversalItemProps>
|
||||
|
||||
@@ -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 (
|
||||
<EntryItemWrapper
|
||||
key={entry.entries.id}
|
||||
entryId={entry.entries.id}
|
||||
key={entryId}
|
||||
entryId={entryId}
|
||||
view={activeList?.view}
|
||||
>
|
||||
<Item entryId={entry.entries.id} />
|
||||
<Item entryId={entryId} />
|
||||
</EntryItemWrapper>
|
||||
)
|
||||
},
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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 (
|
||||
<m.div
|
||||
className="-mt-2 flex size-full flex-col items-center justify-center gap-1 text-lg font-medium text-zinc-400"
|
||||
initial={{ opacity: 0.01, y: 300 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
>
|
||||
<img
|
||||
src="./icon.svg"
|
||||
alt="logo"
|
||||
className="size-16 opacity-40 grayscale"
|
||||
/>
|
||||
{activeList?.name}
|
||||
</m.div>
|
||||
)
|
||||
}
|
||||
|
||||
return <EntryContentRender entryId={entry} />
|
||||
}
|
||||
|
||||
function EntryContentRender({ entryId }: { entryId: string }) {
|
||||
useBizQuery(Queries.entries.byId(entryId), {
|
||||
staleTime: 300_000,
|
||||
})
|
||||
|
||||
const entry = useEntry(entryId)
|
||||
|
||||
const [content, setContent] = useState<JSX.Element>()
|
||||
|
||||
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 ?
|
||||
(
|
||||
<>
|
||||
<EntryShare entryId={entry.data.entries.id} view={0} />
|
||||
<div className="h-[calc(100%-3.5rem)] overflow-y-auto @container">
|
||||
<m.div
|
||||
className="p-5"
|
||||
initial={{ opacity: 0.01, y: 100 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0.01, y: -100 }}
|
||||
key={entry.data?.entries.id}
|
||||
>
|
||||
<article className="relative m-auto min-w-0 max-w-[550px] @4xl:max-w-[70ch]">
|
||||
<a
|
||||
href={entry.data?.entries.url || void 0}
|
||||
target="_blank"
|
||||
className="-mx-6 block rounded-md p-6 transition-colors hover:bg-theme-item-hover"
|
||||
rel="noreferrer"
|
||||
>
|
||||
<div className="select-text break-words text-3xl font-bold">
|
||||
{entry.data?.entries.title}
|
||||
</div>
|
||||
<div className="mt-2 text-[13px] font-medium text-zinc-500">
|
||||
{entry.data?.feeds?.title}
|
||||
</div>
|
||||
<div className="text-[13px] text-zinc-500">
|
||||
{entry.data?.entries.publishedAt &&
|
||||
new Date(entry.data?.entries.publishedAt).toUTCString()}
|
||||
</div>
|
||||
</a>
|
||||
<div className="prose prose-zinc mx-auto mb-32 mt-10 max-w-full cursor-auto select-text break-all text-[15px] dark:prose-invert">
|
||||
{content}
|
||||
</div>
|
||||
</article>
|
||||
</m.div>
|
||||
</div>
|
||||
</>
|
||||
) :
|
||||
(
|
||||
return (
|
||||
<>
|
||||
<EntryShare entryId={entry.entries.id} view={0} />
|
||||
<div className="h-[calc(100%-3.5rem)] overflow-y-auto @container">
|
||||
<m.div
|
||||
className="-mt-2 flex size-full flex-col items-center justify-center gap-1 text-lg font-medium text-zinc-400"
|
||||
initial={{ opacity: 0.01, y: 300 }}
|
||||
className="p-5"
|
||||
initial={{ opacity: 0.01, y: 100 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0.01, y: -100 }}
|
||||
key={entry.entries.id}
|
||||
>
|
||||
<img
|
||||
src="./icon.svg"
|
||||
alt="logo"
|
||||
className="size-16 opacity-40 grayscale"
|
||||
/>
|
||||
{activeList?.name}
|
||||
<article className="relative m-auto min-w-0 max-w-[550px] @4xl:max-w-[70ch]">
|
||||
<a
|
||||
href={entry.entries.url || void 0}
|
||||
target="_blank"
|
||||
className="-mx-6 block rounded-md p-6 transition-colors hover:bg-theme-item-hover"
|
||||
rel="noreferrer"
|
||||
>
|
||||
<div className="select-text break-words text-3xl font-bold">
|
||||
{entry.entries.title}
|
||||
</div>
|
||||
<div className="mt-2 text-[13px] font-medium text-zinc-500">
|
||||
{entry.feeds?.title}
|
||||
</div>
|
||||
<div className="text-[13px] text-zinc-500">
|
||||
{entry.entries.publishedAt &&
|
||||
new Date(entry.entries.publishedAt).toUTCString()}
|
||||
</div>
|
||||
</a>
|
||||
<div className="prose prose-zinc mx-auto mb-32 mt-10 max-w-full cursor-auto select-text break-all text-[15px] dark:prose-invert">
|
||||
{content}
|
||||
</div>
|
||||
</article>
|
||||
</m.div>
|
||||
)
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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() {
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center gap-2" onClick={stopPropagation}>
|
||||
<Link to="/profile">
|
||||
<ActionButton tooltip="Profile">
|
||||
<UserButton className="h-5 p-0" hideName />
|
||||
</ActionButton>
|
||||
</Link>
|
||||
<ProfileButton method="modal" />
|
||||
<Link to="/discover">
|
||||
<ActionButton tooltip="Add">
|
||||
<i className="i-mingcute-add-line size-5 text-theme-vibrancyFg" />
|
||||
@@ -103,6 +99,7 @@ export function FeedColumn() {
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="flex w-full justify-between px-3 text-xl text-theme-vibrancyFg"
|
||||
onClick={stopPropagation}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { Queries } from "@renderer/queries"
|
||||
import {
|
||||
feedActions,
|
||||
useFeedActiveList,
|
||||
useSubscriptionByView,
|
||||
useUnreadStore,
|
||||
} from "@renderer/store"
|
||||
import { useMemo, useState } from "react"
|
||||
@@ -16,12 +17,12 @@ import { parse } from "tldts"
|
||||
|
||||
import { FeedCategory } from "./category"
|
||||
|
||||
const useData = (view?: FeedViewType) => {
|
||||
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<string, number> = {}
|
||||
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)
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { SVGAttributes } from "react"
|
||||
|
||||
export function UserArrowLeftIcon(props: SVGAttributes<SVGElement>) {
|
||||
return (
|
||||
<svg
|
||||
width="1em"
|
||||
height="1em"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
{...props}
|
||||
>
|
||||
<path
|
||||
d="M11 15H7C4.79086 15 3 16.7909 3 19C3 20.1046 3.89543 21 5 21H15M16.8744 13C16.2164 13.4935 15.6221 14.066 15.1049 14.7043C15.035 14.7906 15 14.8953 15 15M16.8744 17C16.2164 16.5065 15.6221 15.934 15.1049 15.2957C15.035 15.2094 15 15.1047 15 15M15 15H21M15 7C15 9.20914 13.2091 11 11 11C8.79086 11 7 9.20914 7 7C7 4.79086 8.79086 3 11 3C13.2091 3 15 4.79086 15 7Z"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
@@ -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,
|
||||
)}
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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<{
|
||||
>
|
||||
<m.div
|
||||
style={modalStyle}
|
||||
exit={initialStyle}
|
||||
initial={initialStyle}
|
||||
animate={animateController}
|
||||
transition={modalTransition}
|
||||
{...modalMontionConfig}
|
||||
className={cn(
|
||||
"relative flex flex-col overflow-hidden rounded-lg",
|
||||
"bg-zinc-50/80 dark:bg-neutral-900/80",
|
||||
"p-2 shadow-2xl shadow-stone-300 backdrop-blur-sm dark:shadow-stone-800",
|
||||
"shadow-modal p-2 backdrop-blur-sm",
|
||||
max ?
|
||||
"h-[90vh] w-[90vw]" :
|
||||
"max-h-[70vh] min-w-[300px] max-w-[90vw] lg:max-h-[calc(100vh-20rem)] lg:max-w-[70vw]",
|
||||
|
||||
@@ -1,29 +1,134 @@
|
||||
import { useSession } from "@hono/auth-js/react"
|
||||
import {
|
||||
Avatar,
|
||||
AvatarFallback,
|
||||
AvatarImage,
|
||||
} from "@renderer/components/ui/avatar"
|
||||
import { loginHandler } from "@renderer/lib/auth"
|
||||
import { APP_NAME } from "@renderer/lib/constants"
|
||||
import { stopPropagation } from "@renderer/lib/dom"
|
||||
import { cn } from "@renderer/lib/utils"
|
||||
import { useSession } from "@renderer/queries/auth"
|
||||
import { m } from "framer-motion"
|
||||
import type { FC } from "react"
|
||||
import { Link } from "react-router-dom"
|
||||
|
||||
import { Button } from "./ui/button"
|
||||
import { FollowIcon } from "./icons/follow"
|
||||
import { UserArrowLeftIcon } from "./icons/user"
|
||||
import { ActionButton, Button } from "./ui/button"
|
||||
import { useCurrentModal } from "./ui/modal"
|
||||
import { modalMontionConfig } from "./ui/modal/stacked/constants"
|
||||
import { useModalStack } from "./ui/modal/stacked/hooks"
|
||||
|
||||
const LoginModalContent = () => {
|
||||
const modal = useCurrentModal()
|
||||
return (
|
||||
<div className="center flex h-full" onClick={modal.dismiss}>
|
||||
<m.div
|
||||
className="shadow-modal rounded-lg border border-border bg-background p-4 px-8 pb-8"
|
||||
onClick={stopPropagation}
|
||||
{...modalMontionConfig}
|
||||
>
|
||||
<div className="mb-8 mt-4 text-center align-middle font-sans text-2xl font-bold leading-relaxed">
|
||||
<span className="text-xl">Sign in to </span>
|
||||
<span className="center flex translate-y-px gap-2 font-theme text-theme-accent">
|
||||
<FollowIcon className="size-4" />
|
||||
{APP_NAME}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex flex-col gap-4">
|
||||
<Button
|
||||
className="h-[48px] w-[320px] rounded-[8px] !bg-black font-sans text-base text-white hover:!bg-black/80"
|
||||
size="lg"
|
||||
onClick={() => {
|
||||
loginHandler("github")
|
||||
}}
|
||||
>
|
||||
<i className="i-mingcute-github-fill mr-2 text-xl" />
|
||||
{" "}
|
||||
Continue with
|
||||
GitHub
|
||||
</Button>
|
||||
<Button
|
||||
className="h-[48px] w-[320px] rounded-[8px] bg-blue-500 font-sans text-base text-white hover:bg-blue-500/90"
|
||||
size="xl"
|
||||
onClick={() => {
|
||||
loginHandler("google")
|
||||
}}
|
||||
>
|
||||
<i className="i-mingcute-google-fill mr-2 text-xl" />
|
||||
{" "}
|
||||
Continue with
|
||||
Google
|
||||
</Button>
|
||||
</div>
|
||||
</m.div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
interface LoginProps {
|
||||
method?: "redirect" | "modal"
|
||||
}
|
||||
export const LoginButton: FC<LoginProps> = (props) => {
|
||||
const { method } = props
|
||||
const modalStack = useModalStack()
|
||||
const Content = (
|
||||
<ActionButton
|
||||
className="relative z-[1]"
|
||||
onClick={
|
||||
method === "modal" ?
|
||||
() => {
|
||||
modalStack.present({
|
||||
CustomModalComponent: ({ children }) => children,
|
||||
title: "Login",
|
||||
content: LoginModalContent,
|
||||
clickOutsideToDismiss: true,
|
||||
})
|
||||
} :
|
||||
undefined
|
||||
}
|
||||
tooltip="Login"
|
||||
>
|
||||
<UserArrowLeftIcon className="size-4" />
|
||||
</ActionButton>
|
||||
)
|
||||
return method === "modal" ?
|
||||
(
|
||||
Content
|
||||
) :
|
||||
(
|
||||
<Link to="/login">
|
||||
{Content}
|
||||
</Link>
|
||||
)
|
||||
}
|
||||
export const ProfileButton: FC<LoginProps> = (props) => {
|
||||
const { status } = useSession()
|
||||
|
||||
if (status !== "authenticated") {
|
||||
return <LoginButton {...props} />
|
||||
}
|
||||
return (
|
||||
<Link to="/profile">
|
||||
<ActionButton tooltip="Profile">
|
||||
<UserButton className="h-5 p-0" hideName />
|
||||
</ActionButton>
|
||||
</Link>
|
||||
)
|
||||
}
|
||||
|
||||
export function UserButton({
|
||||
className,
|
||||
hideName,
|
||||
...props
|
||||
}: {
|
||||
className?: string
|
||||
hideName?: boolean
|
||||
}) {
|
||||
const { data: session, status } = useSession()
|
||||
} & LoginProps) {
|
||||
const { session, status } = useSession()
|
||||
|
||||
if (status !== "authenticated") {
|
||||
return (
|
||||
<Link to="/login">
|
||||
<Button>Login</Button>
|
||||
</Link>
|
||||
)
|
||||
return <LoginButton {...props} />
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
@@ -373,6 +373,7 @@ declare const routes: hono_hono_base.HonoBase<hono.Env, {
|
||||
feedIdList?: string[] | undefined;
|
||||
publishedAfter?: string | undefined;
|
||||
collected?: boolean | undefined;
|
||||
withContent?: boolean | undefined;
|
||||
};
|
||||
};
|
||||
output: {
|
||||
@@ -392,6 +393,7 @@ declare const routes: hono_hono_base.HonoBase<hono.Env, {
|
||||
publishedAt: string;
|
||||
images: string[] | null;
|
||||
categories: string[] | null;
|
||||
content?: string | null | undefined;
|
||||
enclosures?: {
|
||||
url: string;
|
||||
length?: number | undefined;
|
||||
|
||||
@@ -1,6 +1,17 @@
|
||||
import { signOut } from "@hono/auth-js/react"
|
||||
import { QUERY_PERSIST_KEY } from "@renderer/lib/constants"
|
||||
import { clearLocalPersistStoreData } from "@renderer/store/utils/local"
|
||||
import { useCallback } from "react"
|
||||
|
||||
export const useSignOut = () => useCallback(() => {
|
||||
signOut()
|
||||
}, [])
|
||||
export const useSignOut = () =>
|
||||
useCallback(() => {
|
||||
signOut()
|
||||
|
||||
// clear local store data
|
||||
clearLocalPersistStoreData()
|
||||
|
||||
// Clear query cache
|
||||
localStorage.removeItem(QUERY_PERSIST_KEY)
|
||||
// Clear local storage
|
||||
// TODO
|
||||
}, [])
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -10,7 +10,7 @@ export type ActiveList = {
|
||||
id: string | number
|
||||
name: string
|
||||
view: number
|
||||
} | null
|
||||
}
|
||||
|
||||
export type FeedResponse = SubscriptionResponse[number]["feeds"]
|
||||
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { SessionProvider } from "@hono/auth-js/react"
|
||||
import { Outlet } from "react-router-dom"
|
||||
|
||||
export function Component() {
|
||||
return (
|
||||
<Outlet />
|
||||
<SessionProvider>
|
||||
<Outlet />
|
||||
</SessionProvider>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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 (
|
||||
<div className="flex w-full gap-10 px-10 py-16">
|
||||
|
||||
@@ -65,7 +65,7 @@ export function Component() {
|
||||
<AnimatePresence>
|
||||
{!inWideMode && (
|
||||
<div className="flex-1">
|
||||
<EntryContent entryId={activeEntry} />
|
||||
<EntryContent entry={activeEntry} />
|
||||
</div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
|
||||
@@ -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 <Outlet />
|
||||
}
|
||||
|
||||
|
||||
@@ -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<z.infer<typeof formSchema>>({
|
||||
resolver: zodResolver(formSchema),
|
||||
|
||||
@@ -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<PropsWithChildren> = ({ children }) => (
|
||||
ease: "easeInOut",
|
||||
}}
|
||||
>
|
||||
<SessionProvider>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<TooltipProvider>
|
||||
<Provider store={jotaiStore}>
|
||||
<ModalStackProvider />
|
||||
<HelmetProvider>{children}</HelmetProvider>
|
||||
</Provider>
|
||||
</TooltipProvider>
|
||||
</QueryClientProvider>
|
||||
</SessionProvider>
|
||||
<PersistQueryClientProvider
|
||||
persistOptions={persistConfig}
|
||||
client={queryClient}
|
||||
>
|
||||
<TooltipProvider>
|
||||
<Provider store={jotaiStore}>
|
||||
<ModalStackProvider />
|
||||
<HelmetProvider>{children}</HelmetProvider>
|
||||
</Provider>
|
||||
</TooltipProvider>
|
||||
</PersistQueryClientProvider>
|
||||
</MotionConfig>
|
||||
<Toaster />
|
||||
</LazyMotion>
|
||||
|
||||
@@ -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<T = any>(
|
||||
path: string,
|
||||
|
||||
req: any = {},
|
||||
): Promise<T | null> {
|
||||
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>("session", params)
|
||||
}
|
||||
@@ -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,
|
||||
})
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
+118
-10
@@ -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<FeedId, EntryId[]>
|
||||
|
||||
interface EntryState {
|
||||
/**
|
||||
* A map of feedId to entryIds
|
||||
*/
|
||||
entries: EntriesIdTable
|
||||
/**
|
||||
* A map of entryId to entry
|
||||
*/
|
||||
flatMapEntries: Record<FeedId, EntryModel>
|
||||
/**
|
||||
* 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<string, EntryModel>
|
||||
internal_feedId2entryIdSet: Record<FeedId, Set<EntryId>>
|
||||
}
|
||||
|
||||
interface EntryActions {
|
||||
@@ -25,6 +39,7 @@ interface EntryActions {
|
||||
|
||||
pageParam?: string
|
||||
}) => Promise<Awaited<ReturnType<typeof apiClient.entries.$post>>>
|
||||
fetchEntryById: (entryId: string) => Promise<EntryModel | undefined>
|
||||
upsertMany: (entries: EntryModel[]) => void
|
||||
|
||||
optimisticUpdate: (entryId: string, changed: Partial<EntryModel>) => void
|
||||
@@ -36,17 +51,42 @@ interface EntryActions {
|
||||
getFlattenMapEntries: () => Record<string, EntryModel>
|
||||
markRead: (feedId: string, entryId: string, read: boolean) => void
|
||||
markReadByFeedId: (feedId: string) => void
|
||||
|
||||
clear: () => void
|
||||
}
|
||||
|
||||
export const useEntryStore = createZustandStore<EntryState & EntryActions>(
|
||||
"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<EntryState & EntryActions>(
|
||||
json: {
|
||||
publishedAfter: pageParam as string,
|
||||
read,
|
||||
// withContent: true,
|
||||
...getEntriesParams({
|
||||
level,
|
||||
id,
|
||||
@@ -118,8 +159,26 @@ export const useEntryStore = createZustandStore<EntryState & EntryActions>(
|
||||
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<EntryState & EntryActions>(
|
||||
},
|
||||
|
||||
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<EntryState & EntryActions>(
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
@@ -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<FeedId, SubscriptionModel>
|
||||
dataIdByView: Record<FeedViewType, FeedId[]>
|
||||
}
|
||||
|
||||
interface SubscriptionActions {
|
||||
upsert: (feedId: FeedId, subscription: SubscriptionModel) => void
|
||||
fetchByView: (view?: FeedViewType) => Promise<SubscriptionModel[]>
|
||||
markReadByView: (view?: FeedViewType) => void
|
||||
internal_reset: () => void
|
||||
clear: () => void
|
||||
}
|
||||
|
||||
const emptyDataIdByView: Record<FeedViewType, FeedId[]> = {
|
||||
[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]),
|
||||
)
|
||||
|
||||
@@ -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<UIState & UIActions>(
|
||||
"ui",
|
||||
{
|
||||
version: 0,
|
||||
export const useUIStore = createZustandStore<UIState & UIActions>("ui", {
|
||||
version: 1,
|
||||
})((set) => ({
|
||||
...createDefaultUIState(),
|
||||
|
||||
clear() {
|
||||
set(createDefaultUIState())
|
||||
},
|
||||
)((set) => ({
|
||||
entryColWidth: 340,
|
||||
|
||||
setEntryColWidth(width) {
|
||||
set({ entryColWidth: width })
|
||||
},
|
||||
|
||||
@@ -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<UnreadState & UnreadActions>(
|
||||
"unread",
|
||||
{
|
||||
version: 0,
|
||||
version: 1,
|
||||
},
|
||||
)((set) => ({
|
||||
data: {},
|
||||
@@ -27,6 +32,10 @@ export const useUnreadStore = createZustandStore<UnreadState & UnreadActions>(
|
||||
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<UnreadState & UnreadActions>(
|
||||
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
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -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<string | null> =>
|
||||
(await get(name)) || null,
|
||||
setItem: async (name: string, value: string): Promise<void> => {
|
||||
await set(name, value)
|
||||
declare const window: any
|
||||
export const dbStorage: PersistStorage<any> = {
|
||||
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<void> => {
|
||||
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()
|
||||
},
|
||||
})
|
||||
|
||||
@@ -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()
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,7 +18,11 @@ module.exports = {
|
||||
"2xl": "1400px",
|
||||
},
|
||||
},
|
||||
|
||||
extend: {
|
||||
fontFamily: {
|
||||
theme: "var(--fo-font-family)",
|
||||
},
|
||||
colors: {
|
||||
border: "hsl(var(--border))",
|
||||
input: "hsl(var(--input))",
|
||||
|
||||
Vendored
+8
@@ -1,5 +1,13 @@
|
||||
declare module "@auth/core/types" {
|
||||
interface User {
|
||||
handle?: string | null
|
||||
|
||||
id: string
|
||||
name: string
|
||||
image: string
|
||||
}
|
||||
|
||||
interface Session {
|
||||
user: User
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user