From 950b5af8ec0316875ed3ce5a99baaaecb56c6d37 Mon Sep 17 00:00:00 2001 From: Innei Date: Wed, 8 Jan 2025 00:05:26 +0800 Subject: [PATCH] feat(rn-component): implement toast manager Signed-off-by: Innei --- apps/mobile/postcss.config.js | 3 - .../src/components/ui/toast/CenteredToast.tsx | 74 ++++++++++++ .../components/ui/toast/ToastContainer.tsx | 50 ++++++++ .../src/components/ui/toast/constants.ts | 9 ++ apps/mobile/src/components/ui/toast/ctx.tsx | 13 +++ .../src/components/ui/toast/manager.tsx | 108 ++++++++++++++++++ apps/mobile/src/components/ui/toast/types.ts | 31 +++++ apps/mobile/src/icons/close_circle_fill.tsx | 14 +++ apps/mobile/src/icons/info_circle_fill.tsx | 14 +++ apps/mobile/src/lib/toast.tsx | 26 +++++ apps/mobile/src/screens/(headless)/debug.tsx | 11 ++ .../src/screens/(modal)/rsshub-form.tsx | 6 +- packages/utils/src/color.ts | 6 +- 13 files changed, 358 insertions(+), 7 deletions(-) create mode 100644 apps/mobile/src/components/ui/toast/CenteredToast.tsx create mode 100644 apps/mobile/src/components/ui/toast/ToastContainer.tsx create mode 100644 apps/mobile/src/components/ui/toast/constants.ts create mode 100644 apps/mobile/src/components/ui/toast/ctx.tsx create mode 100644 apps/mobile/src/components/ui/toast/manager.tsx create mode 100644 apps/mobile/src/components/ui/toast/types.ts create mode 100644 apps/mobile/src/icons/close_circle_fill.tsx create mode 100644 apps/mobile/src/icons/info_circle_fill.tsx create mode 100644 apps/mobile/src/lib/toast.tsx diff --git a/apps/mobile/postcss.config.js b/apps/mobile/postcss.config.js index ef15a530a..90d9fffcb 100644 --- a/apps/mobile/postcss.config.js +++ b/apps/mobile/postcss.config.js @@ -1,8 +1,5 @@ module.exports = { plugins: { - // tailwindcss: { - // config: "./tailwind.dom.config.ts", - // }, autoprefixer: {}, }, } diff --git a/apps/mobile/src/components/ui/toast/CenteredToast.tsx b/apps/mobile/src/components/ui/toast/CenteredToast.tsx new file mode 100644 index 000000000..b64321776 --- /dev/null +++ b/apps/mobile/src/components/ui/toast/CenteredToast.tsx @@ -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 ? ( + {props.message} + ) : 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 ?? ( + + {createElement(toastTypeToIcons[props.type], { + color: "white", + height: 20, + width: 20, + })} + + )) + + const [measureHeight, setMeasureHeight] = useState(-1) + return ( + { + setMeasureHeight(nativeEvent.layout.height) + }} + exiting={FadeOut} + style={StyleSheet.flatten([ + styles.toast, + measureHeight === -1 ? styles.hidden : {}, + measureHeight > 50 ? styles.rounded : styles.roundedFull, + ])} + > + {renderIcon} + {renderMessage} + + ) +} + +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, + }, +}) diff --git a/apps/mobile/src/components/ui/toast/ToastContainer.tsx b/apps/mobile/src/components/ui/toast/ToastContainer.tsx new file mode 100644 index 000000000..ee6dff9d9 --- /dev/null +++ b/apps/mobile/src/components/ui/toast/ToastContainer.tsx @@ -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 ( + + {/* Center replace container */} + + {renderCenterReplaceToast && } + + {/* Bottom stack */} + {/* */} + + ) +} diff --git a/apps/mobile/src/components/ui/toast/constants.ts b/apps/mobile/src/components/ui/toast/constants.ts new file mode 100644 index 000000000..1d1dc5af8 --- /dev/null +++ b/apps/mobile/src/components/ui/toast/constants.ts @@ -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 diff --git a/apps/mobile/src/components/ui/toast/ctx.tsx b/apps/mobile/src/components/ui/toast/ctx.tsx new file mode 100644 index 000000000..18e2a156b --- /dev/null +++ b/apps/mobile/src/components/ui/toast/ctx.tsx @@ -0,0 +1,13 @@ +import type { PrimitiveAtom } from "jotai" +import { createContext } from "react" + +import type { ToastProps, ToastRef } from "./types" + +export const ToastContainerContext = createContext>(null!) + +type Disposer = () => void +interface ToastActionContext { + register: (currentIndex: number, ref: ToastRef) => Disposer +} + +export const ToastActionContext = createContext(null!) diff --git a/apps/mobile/src/components/ui/toast/manager.tsx b/apps/mobile/src/components/ui/toast/manager.tsx new file mode 100644 index 000000000..8c10e7f61 --- /dev/null +++ b/apps/mobile/src/components/ui/toast/manager.tsx @@ -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([]) + private portal: RootSiblings | null = null + + private propsMap = {} as Record + private currentIndex = 0 + + private defaultProps: Omit = { + duration: 3000, + action: [], + type: "info", + variant: "bottom-stack", + message: "", + render: null, + icon: null, + canClose: true, + } + + private toastRefs = {} as Record + + private register(currentIndex: number, ref: ToastRef) { + this.toastRefs[currentIndex] = ref + return () => { + delete this.toastRefs[currentIndex] + } + } + + mount() { + this.portal = new RootSiblings( + ( + + + + + + + + + + ), + ) + } + + 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, "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) + } +} diff --git a/apps/mobile/src/components/ui/toast/types.ts b/apps/mobile/src/components/ui/toast/types.ts new file mode 100644 index 000000000..d176d94cc --- /dev/null +++ b/apps/mobile/src/components/ui/toast/types.ts @@ -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 +> & { + variant: "center-replace" +} + +export type BottomToastProps = Partial & { + variant: "bottom-stack" + canClose?: boolean +} + +export interface ToastRef { + dimiss: () => Promise +} diff --git a/apps/mobile/src/icons/close_circle_fill.tsx b/apps/mobile/src/icons/close_circle_fill.tsx new file mode 100644 index 000000000..8597960ba --- /dev/null +++ b/apps/mobile/src/icons/close_circle_fill.tsx @@ -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 }) => ( + + + + + + +) diff --git a/apps/mobile/src/icons/info_circle_fill.tsx b/apps/mobile/src/icons/info_circle_fill.tsx new file mode 100644 index 000000000..22381e0b1 --- /dev/null +++ b/apps/mobile/src/icons/info_circle_fill.tsx @@ -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 }) => ( + + + + + + +) diff --git a/apps/mobile/src/lib/toast.tsx b/apps/mobile/src/lib/toast.tsx new file mode 100644 index 000000000..31c500b1d --- /dev/null +++ b/apps/mobile/src/lib/toast.tsx @@ -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> +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, + }) + } +}) diff --git a/apps/mobile/src/screens/(headless)/debug.tsx b/apps/mobile/src/screens/(headless)/debug.tsx index af1903bc0..13cfca3c1 100644 --- a/apps/mobile/src/screens/(headless)/debug.tsx +++ b/apps/mobile/src/screens/(headless)/debug.tsx @@ -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", + }) + }, + }, ], }, diff --git a/apps/mobile/src/screens/(modal)/rsshub-form.tsx b/apps/mobile/src/screens/(modal)/rsshub-form.tsx index f2f5206ab..1b86665c5 100644 --- a/apps/mobile/src/screens/(modal)/rsshub-form.tsx +++ b/apps/mobile/src/screens/(modal)/rsshub-form.tsx @@ -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, diff --git a/packages/utils/src/color.ts b/packages/utils/src/color.ts index 40ad3bdd5..291a91b00 100644 --- a/packages/utils/src/color.ts +++ b/packages/utils/src/color.ts @@ -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)