feat(rn-component): implement toast manager

Signed-off-by: Innei <tukon479@gmail.com>
This commit is contained in:
Innei
2025-01-08 00:05:26 +08:00
parent 5a7160d5af
commit 950b5af8ec
13 changed files with 358 additions and 7 deletions
-3
View File
@@ -1,8 +1,5 @@
module.exports = {
plugins: {
// tailwindcss: {
// config: "./tailwind.dom.config.ts",
// },
autoprefixer: {},
},
}
@@ -0,0 +1,74 @@
import { withOpacity } from "@follow/utils"
import { createElement, useContext, useEffect, useState } from "react"
import { StyleSheet, Text, View } from "react-native"
import Animated, { FadeOut } from "react-native-reanimated"
import { toastTypeToIcons } from "./constants"
import { ToastActionContext } from "./ctx"
import type { ToastProps } from "./types"
export const CenteredToast = (props: ToastProps) => {
const renderMessage = props.render ? null : props.message ? (
<Text className="font-semibold text-white">{props.message}</Text>
) : null
const { register } = useContext(ToastActionContext)
useEffect(() => {
const disposer = register(props.currentIndex, {
dimiss: async () => {},
})
return () => {
disposer()
}
}, [props.currentIndex, register])
const renderIcon =
props.icon === false
? null
: (props.icon ?? (
<View className="mr-2">
{createElement(toastTypeToIcons[props.type], {
color: "white",
height: 20,
width: 20,
})}
</View>
))
const [measureHeight, setMeasureHeight] = useState(-1)
return (
<Animated.View
onLayout={({ nativeEvent }) => {
setMeasureHeight(nativeEvent.layout.height)
}}
exiting={FadeOut}
style={StyleSheet.flatten([
styles.toast,
measureHeight === -1 ? styles.hidden : {},
measureHeight > 50 ? styles.rounded : styles.roundedFull,
])}
>
{renderIcon}
{renderMessage}
</Animated.View>
)
}
const styles = StyleSheet.create({
toast: {
borderWidth: StyleSheet.hairlineWidth,
flexDirection: "row",
paddingHorizontal: 16,
paddingVertical: 12,
borderColor: withOpacity("#ffffff", 0.3),
backgroundColor: withOpacity("#000000", 0.9),
},
hidden: {
opacity: 0,
},
rounded: {
borderRadius: 16,
},
roundedFull: {
borderRadius: 9999,
},
})
@@ -0,0 +1,50 @@
import { useAtomValue } from "jotai"
import { useContext, useMemo } from "react"
import { View } from "react-native"
import { CenteredToast } from "./CenteredToast"
import { ToastContainerContext } from "./ctx"
import type { ToastProps } from "./types"
export const ToastContainer = () => {
const stackAtom = useContext(ToastContainerContext)
const stack = useAtomValue(stackAtom)
const { renderCenterReplaceToast, renderBottomStackToasts } = useMemo(() => {
const { centerToasts, bottomToasts } = stack.reduce(
(acc, toast) => {
if (toast.variant === "center-replace") {
acc.centerToasts.push(toast)
} else if (toast.variant === "bottom-stack") {
acc.bottomToasts.push(toast)
}
return acc
},
{ centerToasts: [] as ToastProps[], bottomToasts: [] as ToastProps[] },
)
const renderCenterReplaceToast =
centerToasts.length > 0
? centerToasts.reduce((latest, toast) =>
latest.currentIndex > toast.currentIndex ? latest : toast,
)
: null
const renderBottomStackToasts = bottomToasts.sort((a, b) => a.currentIndex - b.currentIndex)
return { renderCenterReplaceToast, renderBottomStackToasts }
}, [stack])
void renderBottomStackToasts
return (
<View className="absolute inset-0" pointerEvents="box-only">
{/* Center replace container */}
<View className="absolute inset-0 items-center justify-center px-5" pointerEvents="box-only">
{renderCenterReplaceToast && <CenteredToast {...renderCenterReplaceToast} />}
</View>
{/* Bottom stack */}
{/* <View className="absolute bottom-safe" pointerEvents="box-only"></View> */}
</View>
)
}
@@ -0,0 +1,9 @@
import { CheckCircleFilledIcon } from "@/src/icons/check_circle_filled"
import { CloseCircleFillIcon } from "@/src/icons/close_circle_fill"
import { InfoCircleFillIcon } from "@/src/icons/info_circle_fill"
export const toastTypeToIcons = {
success: CheckCircleFilledIcon,
error: CloseCircleFillIcon,
info: InfoCircleFillIcon,
} as const
@@ -0,0 +1,13 @@
import type { PrimitiveAtom } from "jotai"
import { createContext } from "react"
import type { ToastProps, ToastRef } from "./types"
export const ToastContainerContext = createContext<PrimitiveAtom<ToastProps[]>>(null!)
type Disposer = () => void
interface ToastActionContext {
register: (currentIndex: number, ref: ToastRef) => Disposer
}
export const ToastActionContext = createContext<ToastActionContext>(null!)
@@ -0,0 +1,108 @@
import { jotaiStore } from "@follow/utils"
import { atom, Provider } from "jotai"
import RootSiblings from "react-native-root-siblings"
import { FullWindowOverlay } from "../../common/FullWindowOverlay"
import { ToastActionContext, ToastContainerContext } from "./ctx"
import { ToastContainer } from "./ToastContainer"
import type { BottomToastProps, CenterToastProps, ToastProps, ToastRef } from "./types"
export class ToastManager {
private stackAtom = atom<ToastProps[]>([])
private portal: RootSiblings | null = null
private propsMap = {} as Record<number, ToastProps>
private currentIndex = 0
private defaultProps: Omit<ToastProps, "currentIndex"> = {
duration: 3000,
action: [],
type: "info",
variant: "bottom-stack",
message: "",
render: null,
icon: null,
canClose: true,
}
private toastRefs = {} as Record<number, ToastRef>
private register(currentIndex: number, ref: ToastRef) {
this.toastRefs[currentIndex] = ref
return () => {
delete this.toastRefs[currentIndex]
}
}
mount() {
this.portal = new RootSiblings(
(
<FullWindowOverlay>
<Provider store={jotaiStore}>
<ToastContainerContext.Provider value={this.stackAtom}>
<ToastActionContext.Provider value={{ register: this.register.bind(this) }}>
<ToastContainer />
</ToastActionContext.Provider>
</ToastContainerContext.Provider>
</Provider>
</FullWindowOverlay>
),
)
}
private push(props: ToastProps) {
this.propsMap[props.currentIndex] = props
jotaiStore.set(this.stackAtom, [...jotaiStore.get(this.stackAtom), props])
}
private remove(index: number) {
delete this.propsMap[index]
jotaiStore.set(
this.stackAtom,
jotaiStore.get(this.stackAtom).filter((toast) => toast.currentIndex !== index),
)
}
private scheduleDismiss(index: number) {
const props = this.propsMap[index]
if (props.duration === Infinity) {
return
}
setTimeout(async () => {
await this.toastRefs[index].dimiss()
this.remove(index)
}, props.duration)
}
// @ts-expect-error
show(props: CenterToastProps): Promise<() => void>
show(props: BottomToastProps): Promise<() => void>
show(props: Omit<Partial<ToastProps>, "currentIndex">) {
if (!this.portal) {
this.mount()
}
const nextProps = { ...this.defaultProps, ...props }
if (nextProps.canClose === false) {
nextProps.duration = Infinity
}
if (nextProps.variant === "center-replace") {
// Find and remove the toast if it exists
const index = jotaiStore
.get(this.stackAtom)
.findIndex((toast) => toast.variant === "center-replace")
if (index !== -1) {
this.remove(index)
}
}
const currentIndex = ++this.currentIndex
this.push({ ...nextProps, currentIndex })
this.scheduleDismiss(currentIndex)
return () => this.remove(currentIndex)
}
}
@@ -0,0 +1,31 @@
export interface ToastProps {
currentIndex: number
variant: "bottom-stack" | "center-replace"
type: "success" | "error" | "info"
message: string
render: React.ReactNode
action: {
label: React.ReactNode
onPress: () => void
variant?: "normal" | "destructive"
}[]
duration: number
icon?: React.ReactNode | false
canClose?: boolean
}
export type CenterToastProps = Partial<
Pick<ToastProps, "message" | "render" | "type" | "duration" | "icon">
> & {
variant: "center-replace"
}
export type BottomToastProps = Partial<ToastProps> & {
variant: "bottom-stack"
canClose?: boolean
}
export interface ToastRef {
dimiss: () => Promise<void>
}
@@ -0,0 +1,14 @@
import type { SvgProps } from "react-native-svg"
import { G, Path, Svg } from "react-native-svg"
export const CloseCircleFillIcon = (props: SvgProps & { color?: string }) => (
<Svg width={24} height={24} viewBox="0 0 24 24" {...props}>
<G fill="none">
<Path d="M24 0v24H0V0h24ZM12.593 23.258l-.011.002-.071.035-.02.004-.014-.004-.071-.035c-.01-.004-.019-.001-.024.005l-.004.01-.017.428.005.02.01.013.104.074.015.004.012-.004.104-.074.012-.016.004-.017-.017-.427c-.002-.01-.009-.017-.017-.018Zm.265-.113-.013.002-.185.093-.01.01-.003.011.018.43.005.012.008.007.201.093c.012.004.023 0 .029-.008l.004-.014-.034-.614c-.003-.012-.01-.02-.02-.022Zm-.715.002a.023.023 0 0 0-.027.006l-.006.014-.034.614c0 .012.007.02.017.024l.015-.002.201-.093.01-.008.004-.011.017-.43-.003-.012-.01-.01-.184-.092Z" />
<Path
fill={props.color || "#10161F"}
d="M12 2c5.523 0 10 4.477 10 10s-4.477 10-10 10S2 17.523 2 12 6.477 2 12 2ZM9.879 8.464a1 1 0 0 0-1.498 1.32l.084.095 2.12 2.12-2.12 2.122a1 1 0 0 0 1.32 1.498l.094-.083L12 13.414l2.121 2.122a1 1 0 0 0 1.498-1.32l-.083-.095L13.414 12l2.122-2.121a1 1 0 0 0-1.32-1.498l-.095.083L12 10.586 9.879 8.464Z"
/>
</G>
</Svg>
)
@@ -0,0 +1,14 @@
import type { SvgProps } from "react-native-svg"
import { G, Path, Svg } from "react-native-svg"
export const InfoCircleFillIcon = (props: SvgProps & { color?: string }) => (
<Svg width={24} height={24} viewBox="0 0 24 24" {...props}>
<G fill="none">
<Path d="M24 0v24H0V0h24ZM12.593 23.258l-.011.002-.071.035-.02.004-.014-.004-.071-.035c-.01-.004-.019-.001-.024.005l-.004.01-.017.428.005.02.01.013.104.074.015.004.012-.004.104-.074.012-.016.004-.017-.017-.427c-.002-.01-.009-.017-.017-.018Zm.265-.113-.013.002-.185.093-.01.01-.003.011.018.43.005.012.008.007.201.093c.012.004.023 0 .029-.008l.004-.014-.034-.614c-.003-.012-.01-.02-.02-.022Zm-.715.002a.023.023 0 0 0-.027.006l-.006.014-.034.614c0 .012.007.02.017.024l.015-.002.201-.093.01-.008.004-.011.017-.43-.003-.012-.01-.01-.184-.092Z" />
<Path
fill={props.color || "#10161F"}
d="M12 2c5.523 0 10 4.477 10 10s-4.477 10-10 10S2 17.523 2 12 6.477 2 12 2Zm-.01 8H11a1 1 0 0 0-.117 1.993L11 12v4.99c0 .52.394.95.9 1.004l.11.006h.49a1 1 0 0 0 .596-1.803L13 16.134V11.01c0-.52-.394-.95-.9-1.004L11.99 10ZM12 7a1 1 0 1 0 0 2 1 1 0 0 0 0-2Z"
/>
</G>
</Svg>
)
+26
View File
@@ -0,0 +1,26 @@
import { ToastManager } from "../components/ui/toast/manager"
import type { ToastProps } from "../components/ui/toast/types"
export const toastInstance = new ToastManager()
type CommandToastOptions = Partial<Pick<ToastProps, "duration" | "icon" | "render" | "message">>
type Toast = {
// [key in "error" | "success" | "info"]: (message: string) => void;
show: typeof toastInstance.show
error: (message: string, options?: CommandToastOptions) => void
success: (message: string, options?: CommandToastOptions) => void
info: (message: string, options?: CommandToastOptions) => void
}
export const toast = {
show: toastInstance.show.bind(toastInstance),
} as Toast
;(["error", "success", "info"] as const).forEach((type) => {
toast[type] = (message: string, options: CommandToastOptions = {}) => {
toastInstance.show({
type,
message,
variant: "center-replace",
...options,
})
}
})
@@ -20,6 +20,7 @@ import { useSafeAreaInsets } from "react-native-safe-area-context"
import { getDbPath } from "@/src/database"
import { clearSessionToken, getSessionToken, setSessionToken } from "@/src/lib/cookie"
import { loading } from "@/src/lib/loading"
import { toast } from "@/src/lib/toast"
interface MenuSection {
title: string
@@ -95,6 +96,16 @@ export default function DebugPanel() {
loading.start(sleep(2000))
},
},
{
title: "Toast",
onPress: () => {
toast.show({
message: "Hello, world!".repeat(10),
type: "success",
variant: "center-replace",
})
},
},
],
},
@@ -23,6 +23,7 @@ import { FormProvider, useFormContext } from "@/src/components/ui/form/FormProvi
import { Select } from "@/src/components/ui/form/Select"
import { TextField } from "@/src/components/ui/form/TextField"
import MarkdownWeb from "@/src/components/ui/typography/MarkdownWeb"
import { toast } from "@/src/lib/toast"
import { feedSyncServices } from "@/src/store/feed/store"
interface RsshubFormParams {
@@ -310,15 +311,14 @@ const ModalHeaderSubmitButtonImpl = ({ routePrefix, route }: ModalHeaderSubmitBu
})
})
.catch(() => {
// TODO impl toast
// toast.error("Failed to fetch feed")
toast.error("Failed to fetch feed")
})
.finally(() => {
setIsLoading(false)
})
} catch (err: unknown) {
if (err instanceof MissingOptionalParamError) {
// toast.error(err.message)
toast.error(err.message)
// const idx = keys.findIndex((item) => item.name === err.param)
// form.setFocus(keys[idx === 0 ? 0 : idx - 1].name, {
// shouldSelect: true,
+5 -1
View File
@@ -142,7 +142,11 @@ export const isRGBAColor = (color: string) => {
export const withOpacity = (color: string, opacity: number) => {
switch (true) {
case isHexColor(color): {
return `${color}${opacity.toString(16).slice(1)}`
// Convert decimal opacity to hex (0-255)
const alpha = Math.round(opacity * 255)
.toString(16)
.padStart(2, "0")
return `${color}${alpha}`
}
case isRGBColor(color): {
const [r, g, b] = color.match(/\d+/g)!.map(Number)