next.js Shadcn Toasts(受react-hot-toast库启发)持续时间问题

gtlvzcf8  于 2023-08-04  发布在  React
关注(0)|答案(1)|浏览(204)

在一个13.4版本的Nextjs项目(app router)中,使用Typescript和TailwindCSS。

我正在尝试使用(不可思议的)shadcnUI库提供的toast。它的灵感来自于React热吐司,并带来了这个图书馆闻名的酱汁味道。
我对吐司功能的一般实现没有问题。然而,当我试图在每个吐司的底部添加一个计时器栏,显示祝酒词的持续时间时,事情发生了变化。我已经设法显示了计时器栏(一个自定义进度栏元素),并使其与每个吐司的持续时间相对应。
但是在这样做的时候,我注意到吐司的持续时间实际上不是我作为 prop 给它的,也不是通过shadcn组件的use-toast.ts中设置的TOAST_REMOVE_DELAY常量给出的。
我尝试了不同的设置,但似乎Toaster的默认值(由react-hot-toast中的根toaster提供)为5000 ms(5s),并且在实际Toast中作为 prop 传递的“duration”值不会覆盖它。至少这是我到目前为止所认为的。在对提供的代码进行了一点修改之后,我无法设法传递持续时间属性,并将其作为Toaster使用的唯一持续时间值(除非为null,则为默认值ofc)。
不管怎样,对于那些好心帮我的人...
下面是使用吐司:

import * as React from "react"

import type {
  ToastActionElement,
  ToastProps,
} from "@/components/ui/toast"

const TOAST_LIMIT = 3
export const TOAST_REMOVE_DELAY = 2000

type ToasterToast = ToastProps & {
  id: string
  title?: React.ReactNode
  description?: React.ReactNode
  action?: ToastActionElement
  duration?: number
}

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_VALUE
  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(() => {
    console.log(new Date().toLocaleTimeString(), "REMOVE_TOAST:", toastId )
    toastTimeouts.delete(toastId)
    dispatch({
      type: "REMOVE_TOAST",
      toastId: toastId,
    })
  }, TOAST_REMOVE_DELAY)

  toastTimeouts.set(toastId, timeout)
}

export const reducer = (state: State, action: Action): State => {
  switch (action.type) {
    case "ADD_TOAST":
      console.log(new Date().toLocaleTimeString(),"ADD_TOAST", action.toast.id, "duration:", action.toast.duration);
      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
      console.log(new Date().toLocaleTimeString() ,"DISMISS_TOAST:", toastId, "duration:", state.toasts[0].duration)
      if (toastId) {
        addToRemoveQueue(toastId)
      } else {
        state.toasts.forEach((toast) => {
          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)
  listeners.forEach((listener) => {
    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: 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 { useToast, toast }

字符串
这里是烤面包机:

/** @format */

'use client';

import {
  Toast,
  ToastClose,
  ToastDescription,
  ToastProvider,
  ToastTitle,
  ToastViewport,
} from '@/components/ui/toast';
import { useToast } from '@/components/ui/use-toast';
import { TimerBar } from '@/components/ui/timerBar';
import { TOAST_REMOVE_DELAY } from '@/components/ui/use-toast';

export function Toaster() {
  const { toasts } = useToast();

  return (
    <div className="absolute max-w-full">
      <ToastProvider>
        {toasts.map(function ({
          id,
          title,
          description,
          action,
          duration,
          ...props
        }) {
          return (
            <Toast key={id} {...props}>
              <div className="flex flex-col w-full">
                <div className="flex justify-start items-center w-full p-2 gap-2 mr-4">
                  <div className="grid gap-1">
                    {title && <ToastTitle>{title}</ToastTitle>}
                    {description && (
                      <ToastDescription>{description}</ToastDescription>
                    )}
                  </div>
                  {action}
                </div>
                <ToastClose />
                <TimerBar max={duration || TOAST_REMOVE_DELAY} />
              </div>
            </Toast>
          );
        })}
        <ToastViewport />
      </ToastProvider>
    </div>
  );
}


这是吐司(没有用,但有用的复制)

/** @format */

import * as React from 'react';
import * as ToastPrimitives from '@radix-ui/react-toast';
import { cva, type VariantProps } from 'class-variance-authority';
import { Icon } from '@/components/icons/icons';
import { cn } from '@/lib/helpers/utils';

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-2 right-2 sm:bottom-0 md: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',
        danger: 'danger group border-danger bg-danger-foreground text-danger',
        success:
          'success group border-success bg-success-foreground text-success',
        warning:
          'warning group border-warning bg-warning text-warning-foreground',
        info: 'info group border-info bg-info text-info-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) => {
  return (
    <ToastPrimitives.Root
      ref={ref}
      className={cn(toastVariants({ variant }), className, 'my-1 mx-2 p-0')}
      {...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 mr-6 h-8 shrink-0 items-center justify-center rounded 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-[.danger]:border-muted/40 group-[.danger]:hover:border-danger/30 group-[.danger]:hover:bg-danger group-[.danger]:hover:text-danger-foreground group-[.danger]:focus:ring-danger',
      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 p-1 text-foreground/50 opacity-0 transition-opacity hover:bg-muted hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.danger]:text-red-300 group-[.danger]:hover:text-red-50 group-[.danger]:focus:ring-red-400 group-[.danger]:focus:ring-offset-red-600',
      className
    )}
    toast-close=""
    {...props}
  >
    <Icon.close className="h-4 w-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 {
  type ToastProps,
  type ToastActionElement,
  ToastProvider,
  ToastViewport,
  Toast,
  ToastTitle,
  ToastDescription,
  ToastClose,
  ToastAction,
};


我还没有花时间做一个单独的repo来测试这个(如果需要的话会做的),但是下面是我做的测试页面:

/** @format */

'use client';

import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { ToastAction } from '@/components/ui/toast';
import { useToast } from '@/components/ui/use-toast';
import {useState } from 'react';

interface PageProps {}

export default function Page({}: PageProps) {
  const { toast } = useToast();

  function successToast(duration?: number) {
    toast({
      title: 'Success!',
      description: `This is a success toast of ${duration}ms`,
      variant: 'success',
      duration: duration,
    });
  }

  function errorToast(duration?: number) {
    toast({
      title: 'Error!',
      description: `This is an error toast of ${duration}ms`,
      variant: 'danger',
      duration: duration,
    });
  }

  function warningToast(duration?: number) {
    toast({
      title: 'Warning!',
      description: `This is a warning toast of ${duration}ms`,
      variant: 'warning',
      duration: duration,
    });
  }

  function infoToast(duration?: number) {
    toast({
      title: 'Info!',
      description: `This is an info toast of ${duration}ms`,
      variant: 'info',
      duration: duration,
    });
  }

  function defaultToast(duration?: number) {
    toast({
      title: 'Default!',
      description: `This is a default toast of ${duration}ms`,
      variant: 'default',
      duration: duration,
    });
  }

  function actionToast(duration?: number) {
    toast({
      title: 'Action!',
      description: `This is an action toast of ${duration}ms`,
      variant: 'default',
      duration: duration,
      action: (
        <ToastAction
          onClick={() => alert('Clicked!')}
          className="text-sm"
          altText="Action!"
        >
          Action!
        </ToastAction>
      ),
    });
  }

  const [duration, setDuration] = useState(3000);

  return (
    <div className="max-w-lg flex flex-col justify-center items-center gap-4">
      <div className="">
        <Label>Toast duration (in ms)</Label>
        <Input
          value={duration.toString()}
          type="number"
          max={10000}
          placeholder="Duration"
          onChange={(e) => setDuration(parseInt(e.target.value))}
        />
      </div>

      <div className="flex gap-4">
        <div className="flex flex-col gap-4">
          <Button variant="primary" onClick={() => successToast(duration)}>
            Primary Button
          </Button>
          <Button variant="secondary" onClick={() => warningToast(duration)}>
            Secondary Button
          </Button>
          <Button variant="danger" onClick={() => errorToast(duration)}>
            Danger Button
          </Button>
        </div>
        <div className="flex flex-col gap-4">
          <Button variant="link" onClick={() => defaultToast(duration)}>
            Link Button
          </Button>
          <Button variant="outline" onClick={() => infoToast(duration)}>
            Outline Button
          </Button>
          <Button variant="ghost" onClick={() => actionToast(duration)}>
            Ghost Button
          </Button>
        </div>
      </div>
    </div>
  );
}


我已经尝试了不同的选择:

  • 直接设置吐司_REMOVE_DELAY常量(不影响烤面包持续时间)
  • 在addToRemoveQueue的setTimeout中添加另一个计时器
const addToRemoveQueue = (toastId: string, delay: number) => {
  if (toastTimeouts.has(toastId)) {
    return
  }

  const timeout = setTimeout(() => {
    console.log(new Date().toLocaleTimeString(), "REMOVE_TOAST:", toastId )
    toastTimeouts.delete(toastId)
    dispatch({
      type: "REMOVE_TOAST",
      toastId: toastId,
    })
  }, delay | TOAST_REMOVE_DELAY)

  toastTimeouts.set(toastId, timeout)
}


其中delay是一个传递吐司持续时间的常量,但似乎即使是基本的TOAST_REMOVE_DELAY也不会影响toast持续时间。它默认设置为1000000,但每次敬酒持续5000次。

  • 我尝试添加另一个计时器来调用DISMISS_吐司操作,但这只适用于小于5s的时间,否则Toaster中的计时器似乎之前被触发过。
  • 我甚至怀疑这可能是一个开发模式的问题,但我试图把它推向生产和行为是完全相同的。
wlzqhblo

wlzqhblo1#

显然我错过了在烤面包机 prop 持续时间的传递:

export function Toaster() {
  const { toasts } = useToast();

  return (
    <div className="absolute max-w-full">
<ToastProvider
      duration={TOAST_REMOVE_DELAY}>
        {toasts. Map(function ({
          id,
          title,
          description,
          action,
          duration,
          ...props
        }) {
          return (
            <Toast key={id} **duration={duration}** {...props}>
              <div className="flex flex-col w-full">
                <div className="flex justify-start items-center w-full p-2 gap-2 mr-4">
                  <div className="grid gap-1">
                    {title && <ToastTitle>{title}</ToastTitle>}
                    {description && (
                      <ToastDescription>{description}</ToastDescription>
                    )}
                  </div>
                  {action}
                </div>
                <ToastClose />
                <TimerBar max={duration || TOAST_REMOVE_DELAY} />
              </div>
            </Toast>
          );
        })}
        <ToastViewport />
      </ToastProvider>
    </div>
  );
}

字符串
对于那些感兴趣的人,这里是其他文件更正:use-toast:

// Inspired by react-hot-toast library
import * as React from "react"
import type {
  ToastActionElement,
  ToastProps,
} from "@/components/ui/toast"

const TOAST_LIMIT = 3
export const TOAST_REMOVE_DELAY = 3000

type ToasterToast = ToastProps & {
  id: string
  title?: React.ReactNode
  description?: React.ReactNode
  action?: ToastActionElement
  duration?: number
}

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_VALUE
  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(() => {
    console.log(new Date().toLocaleTimeString(), "REMOVE_TOAST:", toastId )
    toastTimeouts.delete(toastId)
    dispatch({
      type: "REMOVE_TOAST",
      toastId: toastId,
    })
  }, TOAST_REMOVE_DELAY)

  toastTimeouts.set(toastId, timeout)
}

export const reducer = (state: State, action: Action): State => {
  switch (action.type) {
    case "ADD_TOAST":
      console.log(new Date().toLocaleTimeString(),"ADD_TOAST", action.toast.id, "duration:", action.toast.duration);
      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
      console.log(new Date().toLocaleTimeString() ,"DISMISS_TOAST:", toastId, "duration:", state.toasts[0].duration)
      if (toastId) {
        addToRemoveQueue(toastId)
      } else {
        state.toasts.forEach((toast) => {
          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)
  listeners.forEach((listener) => {
    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: 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 { useToast, toast }

x

Toaster:
/** @format */

'use client';

import {
  Toast,
  ToastClose,
  ToastDescription,
  ToastProvider,
  ToastTitle,
  ToastViewport,
} from '@/components/ui/toast';
import { useToast } from '@/components/ui/use-toast';
import { TimerBar } from '@/components/ui/timerBar';
import { TOAST_REMOVE_DELAY } from '@/components/ui/use-toast';

export function Toaster() {
  const { toasts } = useToast();

  return (
    <div className="absolute max-w-full">
      <ToastProvider>
        {toasts.map(function ({
          id,
          title,
          description,
          action,
          duration,
          ...props
        }) {
          return (
            <Toast key={id} duration={duration} {...props}>
              <div className="flex flex-col w-full">
                <div className="flex justify-start items-center w-full p-2 gap-2 mr-4">
                  <div className="grid gap-1">
                    {title && <ToastTitle>{title}</ToastTitle>}
                    {description && (
                      <ToastDescription>{description}</ToastDescription>
                    )}
                  </div>
                  {action}
                </div>
                <ToastClose />
                <TimerBar max={duration || TOAST_REMOVE_DELAY} />
              </div>
            </Toast>
          );
        })}
        <ToastViewport />
      </ToastProvider>
    </div>
  );
}
toast:
/** @format */

import * as React from 'react';
import * as ToastPrimitives from '@radix-ui/react-toast';
import { cva, type VariantProps } from 'class-variance-authority';
import { Icon } from '@/components/icons/icons';
import { cn } from '@/lib/helpers/utils';

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-2 right-2 sm:bottom-0 md: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',
        danger: 'danger group border-danger bg-danger-foreground text-danger',
        success:
          'success group border-success bg-success-foreground text-success',
        warning:
          'warning group border-warning bg-warning text-warning-foreground',
        info: 'info group border-info bg-info text-info-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) => {
  return (
    <ToastPrimitives.Root
      ref={ref}
      className={cn(toastVariants({ variant }), className, 'my-1 mx-2 p-0')}
      {...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 mr-6 h-8 shrink-0 items-center justify-center rounded 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-[.danger]:border-muted/40 group-[.danger]:hover:border-danger/30 group-[.danger]:hover:bg-danger group-[.danger]:hover:text-danger-foreground group-[.danger]:focus:ring-danger',
      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 p-1 text-foreground/50 opacity-0 transition-opacity hover:bg-muted hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.danger]:text-red-300 group-[.danger]:hover:text-red-50 group-[.danger]:focus:ring-red-400 group-[.danger]:focus:ring-offset-red-600',
      className
    )}
    toast-close=""
    {...props}
  >
    <Icon.close className="h-4 w-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 {
  type ToastProps,
  type ToastActionElement,
  ToastProvider,
  ToastViewport,
  Toast,
  ToastTitle,
  ToastDescription,
  ToastClose,
  ToastAction,
};

And the page to test it out:
/** @format */

'use client';

import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { ToastAction } from '@/components/ui/toast';
import { TOAST_REMOVE_DELAY, useToast } from '@/components/ui/use-toast';
import {useState } from 'react';

interface PageProps {}

export default function Page({}: PageProps) {
  const { toast } = useToast();

  function successToast(duration?: number) {
    toast({
      title: 'Success!',
      description: `This is a success toast of ${duration}ms`,
      variant: 'success',
      duration: duration,
    });
  }

  function errorToast(duration?: number) {
    toast({
      title: 'Error!',
      description: `This is an error toast of ${duration}ms`,
      variant: 'danger',
      duration: duration,
    });
  }

  function warningToast(duration?: number) {
    toast({
      title: 'Warning!',
      description: `This is a warning toast of ${duration}ms`,
      variant: 'warning',
      duration: duration,
    });
  }

  function infoToast(duration?: number) {
    toast({
      title: 'Info!',
      description: `This is an info toast of ${duration}ms`,
      variant: 'info',
      duration: duration,
    });
  }

  function defaultToast(duration?: number) {
    toast({
      title: 'Default!',
      description: `This is a default toast of ${duration}ms`,
      variant: 'default',
      duration: duration,
    });
  }

  function actionToast(duration?: number) {
    toast({
      title: 'Action!',
      description: `This is an action toast of ${duration}ms`,
      variant: 'default',
      duration: duration,
      action: (
        <ToastAction
          onClick={() => alert('Clicked!')}
          className="text-sm"
          altText="Action!"
        >
          Action!
        </ToastAction>
      ),
    });
  }

  const [duration, setDuration] = useState(3000);

  return (
    <div className="max-w-lg flex flex-col justify-center items-center gap-4">
      <div className="">
        <Label>Toast duration (in ms)</Label>
        <Input
          value={duration.toString()}
          type="number"
          max={10000}
          placeholder="Duration"
          onChange={(e) => setDuration(parseInt(e.target.value))}
        />
      </div>

      <div className="flex gap-4">
        <div className="flex flex-col gap-4">
          <Button
            variant="primary"
            onClick={() =>
              successToast(duration ? duration : TOAST_REMOVE_DELAY)
            }
          >
            Primary Button
          </Button>
          <Button
            variant="secondary"
            onClick={() =>
              warningToast(duration ? duration : TOAST_REMOVE_DELAY)
            }
          >
            Secondary Button
          </Button>
          <Button
            variant="danger"
            onClick={() => errorToast(duration ? duration : TOAST_REMOVE_DELAY)}
          >
            Danger Button
          </Button>
        </div>
        <div className="flex flex-col gap-4">
          <Button
            variant="link"
            onClick={() =>
              defaultToast(duration ? duration : TOAST_REMOVE_DELAY)
            }
          >
            Link Button
          </Button>
          <Button
            variant="outline"
            onClick={() => infoToast(duration ? duration : TOAST_REMOVE_DELAY)}
          >
            Outline Button
          </Button>
          <Button
            variant="ghost"
            onClick={() =>
              actionToast(duration ? duration : TOAST_REMOVE_DELAY)
            }
          >
            Ghost Button
          </Button>
        </div>
      </div>
    </div>
  );
}

的字符串
如果你想测试它,不要忘记在RootLayout中添加Toaster作为ToastPrivider:

return (
    <NextAuthSessionProvider session={session}>
      <html lang="en">
        <body
          className={`${circularBold.variable} ${gambettaReg.variable} ${gambettaSemi.variable} ${nunito.variable} ${inter.variable} font-inter`}
        >
          <ThemeProvider attribute="class" defaultTheme="system" enableSystem>
            <main className="flex flex-col justify-between items-center min-h-screen min-w-screen">
              <Header user={session?.user} />
              {children}
              <Footer />
              **<Toaster />**
            </main>
          </ThemeProvider>
        </body>
      </html>
    </NextAuthSessionProvider>
  );
}

相关问题