refactor: use sonner (#48)

This commit is contained in:
Stephen Zhou
2024-06-09 22:02:10 +08:00
committed by GitHub
parent c46c90b5ef
commit 66ae2d2cc3
13 changed files with 85 additions and 417 deletions
+2 -1
View File
@@ -60,7 +60,7 @@
"idb-keyval": "6.2.1",
"immer": "10.1.1",
"jotai": "2.8.2",
"jotai-dark": "0.3.1",
"jotai-dark": "0.3.2",
"jotai-effect": "1.0.0",
"lethargy": "1.0.9",
"lodash-es": "4.17.21",
@@ -75,6 +75,7 @@
"rehype-parse": "9.0.0",
"rehype-sanitize": "6.0.0",
"rehype-stringify": "10.0.0",
"sonner": "^1.5.0",
"swiper": "11.1.4",
"tailwind-merge": "2.3.0",
"tailwindcss-animate": "1.0.7",
+20 -9
View File
@@ -125,8 +125,8 @@ importers:
specifier: 2.8.2
version: 2.8.2(@types/react@18.3.3)(react@18.3.1)
jotai-dark:
specifier: 0.3.1
version: 0.3.1(jotai-effect@1.0.0(jotai@2.8.2(@types/react@18.3.3)(react@18.3.1)))(jotai@2.8.2(@types/react@18.3.3)(react@18.3.1))(react@18.3.1)
specifier: 0.3.2
version: 0.3.2(jotai-effect@1.0.0(jotai@2.8.2(@types/react@18.3.3)(react@18.3.1)))(jotai@2.8.2(@types/react@18.3.3)(react@18.3.1))(react@18.3.1)
jotai-effect:
specifier: 1.0.0
version: 1.0.0(jotai@2.8.2(@types/react@18.3.3)(react@18.3.1))
@@ -169,6 +169,9 @@ importers:
rehype-stringify:
specifier: 10.0.0
version: 10.0.0
sonner:
specifier: ^1.5.0
version: 1.5.0(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
swiper:
specifier: 11.1.4
version: 11.1.4
@@ -3482,16 +3485,13 @@ packages:
jose@5.3.0:
resolution: {integrity: sha512-IChe9AtAE79ru084ow8jzkN2lNrG3Ntfiv65Cvj9uOCE2m5LNsdHG+9EbxWxAoWRF9TgDOqLN5jm08++owDVRg==}
jotai-dark@0.3.1:
resolution: {integrity: sha512-6yW4qk+xG9kv/YkDr4aCWHMPQZHd+q/p1orFzg5NFJwlBCfK/UBlUJfPTRLMdbMf1+U5u4pBQWPGa7ZHOqSFBQ==}
jotai-dark@0.3.2:
resolution: {integrity: sha512-bcxbfze/lQPC6Q7NmceMKmHBkW0ei1wbhEj5Fg0VebQMBeTYkqlzIPeLz8MEsRup/AiKN8mrwNbHLBh5456Yww==}
peerDependencies:
foxact: ^0.2.33
jotai: '>=2.5.0'
jotai-effect: '*'
react: ^18.2.0
react: '>=18.2.0'
peerDependenciesMeta:
foxact:
optional: true
jotai:
optional: true
jotai-effect:
@@ -4612,6 +4612,12 @@ packages:
resolution: {integrity: sha512-l5x7VUUWbjVFbafGLxPWkYsHIhEvmF85tbIeFZWc8ZPtoMyybuEhL7Jye/ooC4/d48FgOjSJXgsF/AJPYCW8Zw==}
engines: {node: '>= 10.0.0', npm: '>= 3.0.0'}
sonner@1.5.0:
resolution: {integrity: sha512-FBjhG/gnnbN6FY0jaNnqZOMmB73R+5IiyYAw8yBj7L54ER7HB3fOSE5OFiQiE2iXWxeXKvg6fIP4LtVppHEdJA==}
peerDependencies:
react: ^18.0.0
react-dom: ^18.0.0
sort-object-keys@1.1.3:
resolution: {integrity: sha512-855pvK+VkU7PaKYPc+Jjnmt4EzejQHyhhF33q31qG8x7maDzkeFhAAThdCYay11CISO+qAMwjOBP+fPZe0IPyg==}
@@ -8959,7 +8965,7 @@ snapshots:
jose@5.3.0: {}
jotai-dark@0.3.1(jotai-effect@1.0.0(jotai@2.8.2(@types/react@18.3.3)(react@18.3.1)))(jotai@2.8.2(@types/react@18.3.3)(react@18.3.1))(react@18.3.1):
jotai-dark@0.3.2(jotai-effect@1.0.0(jotai@2.8.2(@types/react@18.3.3)(react@18.3.1)))(jotai@2.8.2(@types/react@18.3.3)(react@18.3.1))(react@18.3.1):
optionalDependencies:
jotai: 2.8.2(@types/react@18.3.3)(react@18.3.1)
jotai-effect: 1.0.0(jotai@2.8.2(@types/react@18.3.3)(react@18.3.1))
@@ -10203,6 +10209,11 @@ snapshots:
ip-address: 9.0.5
smart-buffer: 4.2.0
sonner@1.5.0(react-dom@18.3.1(react@18.3.1))(react@18.3.1):
dependencies:
react: 18.3.1
react-dom: 18.3.1(react@18.3.1)
sort-object-keys@1.1.3: {}
sort-package-json@1.57.0:
@@ -1,5 +1,4 @@
import { FeedIcon } from "@renderer/components/feed-icon"
import { ToastAction } from "@renderer/components/ui/toast"
import {
Tooltip,
TooltipContent,
@@ -7,7 +6,6 @@ import {
TooltipProvider,
TooltipTrigger,
} from "@renderer/components/ui/tooltip"
import { useToast } from "@renderer/components/ui/use-toast"
import { apiClient } from "@renderer/lib/api-fetch"
import { levels } from "@renderer/lib/constants"
import dayjs from "@renderer/lib/dayjs"
@@ -21,6 +19,7 @@ import {
useUnreadStore,
} from "@renderer/store"
import { useMutation } from "@tanstack/react-query"
import { toast } from "sonner"
export function FeedItem({
feed,
@@ -45,8 +44,6 @@ export function FeedItem({
})
}
const { toast } = useToast()
const deleteMutation = useMutation({
mutationFn: async (feed: SubscriptionResponse[number]) =>
apiClient.subscriptions.$delete({
@@ -58,21 +55,19 @@ export function FeedItem({
onSuccess: (_, variables) => {
Queries.subscription.byView(variables.view).invalidate()
toast({
duration: 3000,
description: (
<>
Feed
{" "}
<i className="mr-px font-semibold">{variables.feeds.title}</i>
{" "}
has been unfollowed.
</>
),
action: (
<ToastAction
altText="Undo"
onClick={async () => {
toast(
<>
Feed
{" "}
<i className="mr-px font-semibold">{variables.feeds.title}</i>
{" "}
has been unfollowed.
</>,
{
duration: 3000,
action: {
label: "Undo",
onClick: async () => {
await apiClient.subscriptions.$post({
json: {
url: variables.feeds.url,
@@ -83,12 +78,10 @@ export function FeedItem({
})
Queries.subscription.byView(feed.view).invalidate()
}}
>
Undo
</ToastAction>
),
})
},
},
},
)
},
})
+2 -4
View File
@@ -1,10 +1,10 @@
import { useToast } from "@renderer/components/ui/use-toast"
import { client } from "@renderer/lib/client"
import { getProxyUrl } from "@renderer/lib/img-proxy"
import { showNativeMenu } from "@renderer/lib/native-menu"
import { cn } from "@renderer/lib/utils"
import type { FC, ImgHTMLAttributes } from "react"
import { memo, useState } from "react"
import { toast } from "sonner"
import { useEventCallback } from "usehooks-ts"
import { usePreviewImages } from "./image/hooks"
@@ -57,7 +57,6 @@ const ImageImpl: FC<ImageProps> = ({
props.onClick?.(e)
},
)
const { toast } = useToast()
return (
<div className={cn("overflow-hidden rounded", className)}>
@@ -92,9 +91,8 @@ const ImageImpl: FC<ImageProps> = ({
click: () => {
if (props.src) {
navigator.clipboard.writeText(props.src)
toast({
toast("Address copied to clipboard.", {
duration: 1000,
description: "Address copied to clipboard.",
})
}
},
+26
View File
@@ -0,0 +1,26 @@
import { useDark } from "@renderer/hooks/useDark"
import { Toaster as Sonner } from "sonner"
type ToasterProps = React.ComponentProps<typeof Sonner>
const Toaster = ({ ...props }: ToasterProps) => {
const { theme } = useDark()
return (
<Sonner
theme={theme as ToasterProps["theme"]}
className="toaster group"
toastOptions={{
classNames: {
toast: "group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
description: "group-[.toast]:text-muted-foreground",
actionButton: "group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
cancelButton: "group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
},
}}
{...props}
/>
)
}
export { Toaster }
-125
View File
@@ -1,125 +0,0 @@
import * as ToastPrimitives from "@radix-ui/react-toast"
import { cn } from "@renderer/lib/utils"
import type { VariantProps } from "class-variance-authority"
import { cva } from "class-variance-authority"
import { X } from "lucide-react"
import * as React from "react"
const ToastProvider = ToastPrimitives.Provider
const ToastViewport = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Viewport>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Viewport
ref={ref}
className={cn(
"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",
className,
)}
{...props}
/>
))
ToastViewport.displayName = ToastPrimitives.Viewport.displayName
const toastVariants = cva(
"group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",
{
variants: {
variant: {
default: "border bg-background text-foreground",
destructive:
"destructive group border-destructive bg-destructive text-destructive-foreground",
},
},
defaultVariants: {
variant: "default",
},
},
)
const Toast = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> &
VariantProps<typeof toastVariants>
>(({ className, variant, ...props }, ref) => (
<ToastPrimitives.Root
ref={ref}
className={cn(toastVariants({ variant }), className)}
{...props}
/>
))
Toast.displayName = ToastPrimitives.Root.displayName
const ToastAction = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Action>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Action
ref={ref}
className={cn(
"inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",
className,
)}
{...props}
/>
))
ToastAction.displayName = ToastPrimitives.Action.displayName
const ToastClose = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Close>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Close
ref={ref}
className={cn(
"absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",
className,
)}
toast-close=""
{...props}
>
<X className="size-4" />
</ToastPrimitives.Close>
))
ToastClose.displayName = ToastPrimitives.Close.displayName
const ToastTitle = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Title>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Title
ref={ref}
className={cn("text-sm font-semibold", className)}
{...props}
/>
))
ToastTitle.displayName = ToastPrimitives.Title.displayName
const ToastDescription = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Description>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Description
ref={ref}
className={cn("text-sm opacity-90", className)}
{...props}
/>
))
ToastDescription.displayName = ToastPrimitives.Description.displayName
type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>
type ToastActionElement = React.ReactElement<typeof ToastAction>
export {
Toast,
ToastAction,
type ToastActionElement,
ToastClose,
ToastDescription,
type ToastProps,
ToastProvider,
ToastTitle,
ToastViewport,
}
@@ -1,31 +0,0 @@
import {
Toast,
ToastClose,
ToastDescription,
ToastProvider,
ToastTitle,
ToastViewport,
} from "@renderer/components/ui/toast"
import { useToast } from "@renderer/components/ui/use-toast"
export function Toaster() {
const { toasts } = useToast()
return (
<ToastProvider>
{toasts.map(({ id, title, description, action, ...props }) => (
<Toast key={id} {...props}>
<div className="grid gap-1">
{title && <ToastTitle>{title}</ToastTitle>}
{description && (
<ToastDescription>{description}</ToastDescription>
)}
</div>
{action}
<ToastClose />
</Toast>
))}
<ToastViewport />
</ToastProvider>
)
}
-194
View File
@@ -1,194 +0,0 @@
// Inspired by react-hot-toast library
import type {
ToastActionElement,
ToastProps,
} from "@renderer/components/ui/toast"
import * as React from "react"
const TOAST_LIMIT = 1
const TOAST_REMOVE_DELAY = 1_000_000
type ToasterToast = ToastProps & {
id: string
title?: React.ReactNode
description?: React.ReactNode
action?: ToastActionElement
}
const actionTypes = {
ADD_TOAST: "ADD_TOAST",
UPDATE_TOAST: "UPDATE_TOAST",
DISMISS_TOAST: "DISMISS_TOAST",
REMOVE_TOAST: "REMOVE_TOAST",
} as const
let count = 0
function genId() {
count = (count + 1) % Number.MAX_SAFE_INTEGER
return count.toString()
}
type ActionType = typeof actionTypes
type Action =
| {
type: ActionType["ADD_TOAST"]
toast: ToasterToast
}
| {
type: ActionType["UPDATE_TOAST"]
toast: Partial<ToasterToast>
}
| {
type: ActionType["DISMISS_TOAST"]
toastId?: ToasterToast["id"]
}
| {
type: ActionType["REMOVE_TOAST"]
toastId?: ToasterToast["id"]
}
interface State {
toasts: ToasterToast[]
}
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>()
const addToRemoveQueue = (toastId: string) => {
if (toastTimeouts.has(toastId)) {
return
}
const timeout = setTimeout(() => {
toastTimeouts.delete(toastId)
dispatch({
type: "REMOVE_TOAST",
toastId,
})
}, TOAST_REMOVE_DELAY)
toastTimeouts.set(toastId, timeout)
}
export const reducer = (state: State, action: Action): State => {
switch (action.type) {
case "ADD_TOAST": {
return {
...state,
toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),
}
}
case "UPDATE_TOAST": {
return {
...state,
toasts: state.toasts.map((t) =>
t.id === action.toast.id ? { ...t, ...action.toast } : t,
),
}
}
case "DISMISS_TOAST": {
const { toastId } = action
// ! Side effects ! - This could be extracted into a dismissToast() action,
// but I'll keep it here for simplicity
if (toastId) {
addToRemoveQueue(toastId)
} else {
for (const toast of state.toasts) {
addToRemoveQueue(toast.id)
}
}
return {
...state,
toasts: state.toasts.map((t) =>
t.id === toastId || toastId === undefined ?
{
...t,
open: false,
} :
t,
),
}
}
case "REMOVE_TOAST": {
if (action.toastId === undefined) {
return {
...state,
toasts: [],
}
}
return {
...state,
toasts: state.toasts.filter((t) => t.id !== action.toastId),
}
}
}
}
const listeners: Array<(state: State) => void> = []
let memoryState: State = { toasts: [] }
function dispatch(action: Action) {
memoryState = reducer(memoryState, action)
for (const listener of listeners) {
listener(memoryState)
}
}
type Toast = Omit<ToasterToast, "id">
function toast({ ...props }: Toast) {
const id = genId()
const update = (props: ToasterToast) =>
dispatch({
type: "UPDATE_TOAST",
toast: { ...props, id },
})
const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id })
dispatch({
type: "ADD_TOAST",
toast: {
...props,
id,
open: true,
onOpenChange: (open) => {
if (!open) dismiss()
},
},
})
return {
id,
dismiss,
update,
}
}
function useToast() {
const [state, setState] = React.useState<State>(memoryState)
React.useEffect(() => {
listeners.push(setState)
return () => {
const index = listeners.indexOf(setState)
if (index > -1) {
listeners.splice(index, 1)
}
}
}, [state])
return {
...state,
toast,
dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }),
}
}
export { toast, useToast }
+1 -3
View File
@@ -4,9 +4,7 @@ import { atomDark } from "jotai-dark"
const isDarkAtom = atomDark({
storageKey: "theme",
disableTransition: true,
applyDarkMode(isDark) {
document.documentElement.dataset.theme = isDark ? "dark" : "light"
},
mode: "data-theme",
})
export function useDark() {
+6 -13
View File
@@ -1,4 +1,3 @@
import { useToast } from "@renderer/components/ui/use-toast"
import { apiClient } from "@renderer/lib/api-fetch"
import { client } from "@renderer/lib/client"
import type { EntryModel } from "@renderer/models"
@@ -6,6 +5,7 @@ import { entryActions } from "@renderer/store/entry"
import { useMutation, useQuery } from "@tanstack/react-query"
import type { FetchError } from "ofetch"
import { ofetch } from "ofetch"
import { toast } from "sonner"
export const useEntryActions = ({
view,
@@ -44,9 +44,8 @@ export const useEntryActions = ({
})
},
onSuccess: () => {
toast({
toast("Collected.", {
duration: 1000,
description: "Collected.",
})
},
})
@@ -65,9 +64,8 @@ export const useEntryActions = ({
})
},
onSuccess: () => {
toast({
toast("Uncollected.", {
duration: 1000,
description: "Uncollected.",
})
},
})
@@ -100,8 +98,6 @@ export const useEntryActions = ({
},
})
const { toast } = useToast()
if (!entry?.entries.url || view === undefined) return { items: [] }
const items = [
@@ -128,9 +124,8 @@ export const useEntryActions = ({
onClick: () => {
if (!entry.entries.url) return
navigator.clipboard.writeText(entry.entries.url)
toast({
toast("Link copied to clipboard.", {
duration: 1000,
description: "Link copied to clipboard.",
})
},
},
@@ -155,14 +150,12 @@ export const useEntryActions = ({
images: entry.entries.images,
})
if (response?.status === "success") {
toast({
toast("Saved to Eagle.", {
duration: 3000,
description: "Saved to Eagle.",
})
} else {
toast({
toast("Failed to save to Eagle.", {
duration: 3000,
description: "Failed to save to Eagle.",
})
}
},
+7 -6
View File
@@ -20,7 +20,6 @@ import {
SelectValue,
} from "@renderer/components/ui/select"
import { Switch } from "@renderer/components/ui/switch"
import { useToast } from "@renderer/components/ui/use-toast"
import { useBizQuery } from "@renderer/hooks/useBizQuery"
import { apiClient } from "@renderer/lib/api-fetch"
import { client } from "@renderer/lib/client"
@@ -32,6 +31,7 @@ import { useFeed } from "@renderer/queries/feed"
import { useMutation } from "@tanstack/react-query"
import { useEffect } from "react"
import { useForm } from "react-hook-form"
import { toast } from "sonner"
import { z } from "zod"
const formSchema = z.object({
@@ -68,7 +68,6 @@ export function Component() {
}
}, [feed.data?.subscription])
const { toast } = useToast()
const followMutation = useMutation({
mutationFn: async (values: z.infer<typeof formSchema>) => {
const body = {
@@ -103,10 +102,12 @@ export function Component() {
client?.invalidateQuery(
Queries.feed.byId({ id: feed.data?.feed.id }).key,
)
toast({
duration: 1000,
description: isSubscribed ? "🎉 Updated." : "🎉 Followed.",
})
toast(
isSubscribed ? "🎉 Updated." : "🎉 Followed.",
{
duration: 1000,
},
)
if (!isSubscribed) {
window.close()
+2 -5
View File
@@ -12,10 +12,10 @@ import {
FormMessage,
} from "@renderer/components/ui/form"
import { Input } from "@renderer/components/ui/input"
import { useToast } from "@renderer/components/ui/use-toast"
import { apiClient } from "@renderer/lib/api-fetch"
import { useMutation } from "@tanstack/react-query"
import { useForm } from "react-hook-form"
import { toast } from "sonner"
import { z } from "zod"
const formSchema = z.object({
@@ -36,17 +36,14 @@ export function Component() {
},
})
const { toast } = useToast()
const updateMutation = useMutation({
mutationFn: async (values: z.infer<typeof formSchema>) =>
apiClient["auth-app"]["update-account"].$patch({
json: values,
}),
onSuccess: () => {
toast({
toast("Profile updated.", {
duration: 3000,
description: "Profile updated.",
})
},
})
@@ -1,6 +1,6 @@
import { SessionProvider } from "@hono/auth-js/react"
import { ModalStackProvider } from "@renderer/components/ui/modal"
import { Toaster } from "@renderer/components/ui/toaster"
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"