{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "toast",
  "type": "registry:ui",
  "title": "Toast",
  "description": "An accessible React toast for Next.js: notifications that slide in, stack like a deck and swipe away, with a toast() function and Radix Toast parts.",
  "author": "FewTone <https://fewtone.com>",
  "dependencies": [
    "class-variance-authority@^0.7.1",
    "lucide-react@^1.52.0",
    "motion@^14.0.0",
    "radix-ui@^1.7.0"
  ],
  "registryDependencies": [
    "https://ui.fewtone.com/r/tokens.json",
    "https://ui.fewtone.com/r/motion.json",
    "https://ui.fewtone.com/r/button.json",
    "https://ui.fewtone.com/r/spinner.json"
  ],
  "files": [
    {
      "path": "registry/fewtone/ui/toast.tsx",
      "type": "registry:ui",
      "content": "\"use client\";\n\nimport { buttonVariants } from \"@/components/ui/button\";\nimport { Spinner } from \"@/components/ui/spinner\";\nimport { blur, duration, ease, spring, swap } from \"@/lib/motion\";\nimport { cn } from \"@/lib/utils\";\nimport { cva } from \"class-variance-authority\";\nimport { XIcon } from \"lucide-react\";\nimport {\n  AnimatePresence,\n  type AnimationPlaybackControls,\n  animate,\n  motion,\n  useMotionValue,\n  useReducedMotion,\n  type Variants,\n} from \"motion/react\";\nimport { Portal, Toast as ToastPrimitive } from \"radix-ui\";\nimport {\n  type ComponentProps,\n  createContext,\n  isValidElement,\n  type MouseEvent,\n  type ReactNode,\n  type Ref,\n  useCallback,\n  useContext,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n  useSyncExternalStore,\n} from \"react\";\n\n/*\n * Toast: short notifications at a corner of the screen that stack and leave on their own (owner's roadmap,\n * 2026-10-16). Built on Radix Toast: each toast is announced to screen readers, F8 jumps to them, Escape\n * closes the newest, and they swipe away. The close timers are this file's own (see Toast): they wait while\n * the pointer or focus is on the toasts, or the window is in the background.\n * Two ways in:\n * - `<Toaster />` placed once, then `toast(\"Saved\")` from anywhere (`toast.success`, `.error`, `.loading`,\n *   `.promise`, `.dismiss`), like sonner. The toasts live in a tiny store read with useSyncExternalStore.\n * - The parts (ToastProvider, Toast, ToastTitle, ToastDescription, ToastAction, ToastClose, ToastViewport),\n *   shaped like shadcn's, for toasts you render yourself with `open` state.\n * Motion (.agents/rules/motion.md):\n * - A new toast slides in from the screen edge through the blur; one that closes slides back out to it.\n * - Several stack like a deck: older toasts tuck behind the newest, each a little narrower, showing a 12px\n *   edge with their content hidden. Hovering, or keyboard focus, fans them out into a list. Every shift is on\n *   spring.snappy; a tucked toast takes the front one's height, and heights glide on an eased tween (the\n *   height pattern), never a spring.\n * - A swipe follows the finger. Let go past the threshold and it flies off; short of it, it springs back.\n * - A toast whose content changes (toast.promise settling) swaps it through the blur, like Loading Button.\n * - Reduced motion: opacity only, and the toasts sit in a plain list.\n * Error toasts keep the neutral surface: the title and the cross turn the destructive colour.\n */\n\nexport type ToastPosition =\n  | \"top-left\"\n  | \"top-center\"\n  | \"top-right\"\n  | \"bottom-left\"\n  | \"bottom-center\"\n  | \"bottom-right\";\n\n/** The deck, in px: how much of each older toast shows behind the newest, and the gap once fanned out */\nconst PEEK = 12;\nconst GAP = 12;\n/** Each older toast in the deck is 5% narrower than the one in front of it */\nconst SHRINK = 0.05;\n\n/* ------------------------------------------------------------------------------------------------------ */\n/* The stack: which toasts are open, how tall each is, and whether the deck is fanned out                  */\n\ntype StackSettings = { position: ToastPosition; expand: boolean; visibleToasts: number };\n\ntype Stack = StackSettings & {\n  /** Open toasts, oldest first */\n  ids: string[];\n  /** Each open toast's full height, measured from its content */\n  heights: Record<string, number>;\n  /** Fanned out into a list: hovered, focused from the keyboard, `expand`, or reduced motion */\n  expanded: boolean;\n  /** The timers wait: the pointer is on the toasts, focus is in them, or the window is in the background */\n  paused: boolean;\n  /** How long a toast stays open, unless it sets its own duration */\n  duration: number;\n  reduce: boolean;\n  add: (id: string) => void;\n  remove: (id: string) => void;\n  measure: (id: string, height: number) => void;\n  configure: (settings: StackSettings) => void;\n  setHovered: (hovered: boolean) => void;\n  /** Where focus is: outside the toasts, in them from a click, or in them from the keyboard */\n  setFocus: (focus: Focus) => void;\n};\n\ntype Focus = \"none\" | \"pointer\" | \"keyboard\";\n\nconst defaultSettings: StackSettings = { position: \"bottom-right\", expand: false, visibleToasts: 3 };\nconst noop = () => {};\n// Outside a ToastProvider, a toast still shows; it just doesn't stack\nconst looseStack: Stack = {\n  ...defaultSettings,\n  ids: [],\n  heights: {},\n  expanded: true,\n  paused: false,\n  duration: 5000,\n  reduce: false,\n  add: noop,\n  remove: noop,\n  measure: noop,\n  configure: noop,\n  setHovered: noop,\n  setFocus: noop,\n};\n\nconst StackContext = createContext<Stack>(looseStack);\n\n/** Hands a node to our ref (a state setter, so effects rerun when it mounts) and to the caller's */\nfunction useMergedRef<T>(own: (node: T | null) => void, theirs?: Ref<T>) {\n  return useCallback(\n    (node: T | null) => {\n      own(node);\n      if (typeof theirs === \"function\") theirs(node);\n      else if (theirs) theirs.current = node;\n    },\n    [own, theirs],\n  );\n}\n\nexport type ToastProviderProps = Omit<ComponentProps<typeof ToastPrimitive.Provider>, \"swipeDirection\">;\n\n/**\n * Wraps the toasts and their viewport: Radix Toast's provider (the `label` screen readers say before each\n * toast, the swipe threshold), plus the stack the deck is drawn from and the default `duration`. Toasts\n * swipe towards the nearer side of the screen: left for left positions, right otherwise.\n */\nfunction ToastProvider({ children, duration = 5000, ...props }: ToastProviderProps) {\n  const reduce = useReducedMotion() ?? false;\n  const [settings, setSettings] = useState(defaultSettings);\n  const [ids, setIds] = useState<string[]>([]);\n  const [heights, setHeights] = useState<Record<string, number>>({});\n  const [hovered, setHovered] = useState(false);\n  const [focus, setFocus] = useState<Focus>(\"none\");\n  const [away, setAway] = useState(false);\n  const empty = ids.length === 0;\n\n  // With nothing left, the deck folds again and the timers are free: the pointer or focus may still be\n  // where the last toast was\n  useEffect(() => {\n    if (!empty) return;\n    setHovered(false);\n    setFocus(\"none\");\n  }, [empty]);\n\n  // The timers wait while the window is in the background, as Radix's do\n  useEffect(() => {\n    const leave = () => setAway(true);\n    const back = () => setAway(false);\n    window.addEventListener(\"blur\", leave);\n    window.addEventListener(\"focus\", back);\n    return () => {\n      window.removeEventListener(\"blur\", leave);\n      window.removeEventListener(\"focus\", back);\n    };\n  }, []);\n\n  const add = useCallback(\n    (id: string) => setIds((current) => (current.includes(id) ? current : [...current, id])),\n    [],\n  );\n  const remove = useCallback((id: string) => {\n    setIds((current) => current.filter((other) => other !== id));\n    setHeights(({ [id]: _, ...rest }) => rest);\n  }, []);\n  const measure = useCallback(\n    (id: string, height: number) =>\n      setHeights((current) => (current[id] === height ? current : { ...current, [id]: height })),\n    [],\n  );\n  const configure = useCallback(\n    (next: StackSettings) =>\n      setSettings((current) =>\n        current.position === next.position &&\n        current.expand === next.expand &&\n        current.visibleToasts === next.visibleToasts\n          ? current\n          : next,\n      ),\n    [],\n  );\n\n  const expanded = settings.expand || reduce || hovered || focus === \"keyboard\";\n  const paused = hovered || focus !== \"none\" || away;\n  const stack = useMemo<Stack>(\n    () => ({\n      ...settings,\n      ids,\n      heights,\n      expanded,\n      paused,\n      duration,\n      reduce,\n      add,\n      remove,\n      measure,\n      configure,\n      setHovered,\n      setFocus,\n    }),\n    [settings, ids, heights, expanded, paused, duration, reduce, add, remove, measure, configure],\n  );\n\n  return (\n    <ToastPrimitive.Provider\n      swipeDirection={settings.position.endsWith(\"left\") ? \"left\" : \"right\"}\n      {...props}\n    >\n      <StackContext.Provider value={stack}>{children}</StackContext.Provider>\n    </ToastPrimitive.Provider>\n  );\n}\n\n/* ------------------------------------------------------------------------------------------------------ */\n/* Viewport                                                                                                */\n\n// 16px in from the screen's edges; full width on phones, 24rem from the sm breakpoint\nconst toastViewportVariants = cva(\n  [\n    \"fixed inset-x-4 z-(--z-toast) sm:w-sm\",\n    \"rounded-lg outline-ring focus-visible:outline-(length:--focus-ring-width) focus-visible:outline-offset-(--focus-ring-offset)\",\n  ],\n  {\n    variants: {\n      position: {\n        \"top-left\": \"top-4 sm:right-auto\",\n        \"top-center\": \"top-4 sm:right-auto sm:left-1/2 sm:-translate-x-1/2\",\n        \"top-right\": \"top-4 sm:left-auto\",\n        \"bottom-left\": \"bottom-4 sm:right-auto\",\n        \"bottom-center\": \"bottom-4 sm:right-auto sm:left-1/2 sm:-translate-x-1/2\",\n        \"bottom-right\": \"bottom-4 sm:left-auto\",\n      },\n    },\n    defaultVariants: { position: \"bottom-right\" },\n  },\n);\n\n/** Keyboard focus fans the deck out; a click doesn't (the pointer already has, by hovering) */\nfunction isFocusVisible(target: EventTarget | null) {\n  if (!(target instanceof Element)) return false;\n  try {\n    return target.matches(\":focus-visible\");\n  } catch {\n    return true;\n  }\n}\n\nexport type ToastViewportProps = ComponentProps<typeof ToastPrimitive.Viewport> & {\n  /** The corner, or the middle of the top or bottom edge, where toasts appear */\n  position?: ToastPosition;\n  /** Always show the toasts as a list, instead of a deck that fans out on hover */\n  expand?: boolean;\n  /** How many toasts show at once; older ones wait out of sight until newer ones go */\n  visibleToasts?: number;\n};\n\n/**\n * Where the toasts appear: a list fixed to a corner of the screen, portalled to the end of the body so no\n * transformed or clipped parent can trap it. Place it once, inside ToastProvider.\n */\nfunction ToastViewport({\n  className,\n  position = \"bottom-right\",\n  expand = false,\n  visibleToasts = 3,\n  style,\n  ref,\n  ...props\n}: ToastViewportProps) {\n  const stack = useContext(StackContext);\n  const { configure, setHovered, setFocus } = stack;\n  const [list, setList] = useState<HTMLOListElement | null>(null);\n  const setRef = useMergedRef(setList, ref);\n  const visible = Math.max(1, Math.floor(visibleToasts));\n\n  useLayoutEffect(\n    () => configure({ position, expand, visibleToasts: visible }),\n    [configure, position, expand, visible],\n  );\n\n  // Native listeners: Radix portals the toasts into this list, so they're its children in the DOM but not\n  // in React's tree, and React's own pointer events wouldn't see the pointer reach them\n  useEffect(() => {\n    if (!list) return;\n    const enter = () => setHovered(true);\n    const leave = () => setHovered(false);\n    const focusIn = (event: FocusEvent) => setFocus(isFocusVisible(event.target) ? \"keyboard\" : \"pointer\");\n    const focusOut = (event: FocusEvent) => {\n      if (!(event.relatedTarget instanceof Node && list.contains(event.relatedTarget))) setFocus(\"none\");\n    };\n    list.addEventListener(\"pointerenter\", enter);\n    list.addEventListener(\"pointerleave\", leave);\n    list.addEventListener(\"focusin\", focusIn);\n    list.addEventListener(\"focusout\", focusOut);\n    return () => {\n      list.removeEventListener(\"pointerenter\", enter);\n      list.removeEventListener(\"pointerleave\", leave);\n      list.removeEventListener(\"focusin\", focusIn);\n      list.removeEventListener(\"focusout\", focusOut);\n    };\n  }, [list, setHovered, setFocus]);\n\n  // The list is as tall as the deck or the fanned-out toasts, so the gaps between them count as hovering\n  const shown = stack.ids.slice(-visible);\n  const front = shown[shown.length - 1];\n  const sizes = shown.map((id) => stack.heights[id] ?? 0);\n  const height = !front\n    ? 0\n    : stack.expanded\n      ? sizes.reduce((total, size) => total + size, 0) + GAP * (sizes.length - 1)\n      : (stack.heights[front] ?? 0) + PEEK * (sizes.length - 1);\n\n  return (\n    <Portal.Root>\n      <ToastPrimitive.Viewport\n        ref={setRef}\n        data-slot=\"toast-viewport\"\n        data-position={position}\n        data-expanded={stack.expanded || undefined}\n        className={cn(toastViewportVariants({ position }), className)}\n        style={{ height, ...style }}\n        {...props}\n      />\n    </Portal.Root>\n  );\n}\n\n/* ------------------------------------------------------------------------------------------------------ */\n/* Toast                                                                                                   */\n\n/** A toast's surface, exported for anything that should look like one */\nconst toastVariants = cva(\"rounded-lg border border-border bg-popover text-popover-foreground shadow-lg\");\n\n/** What a leaving toast needs to know: swiped away, which edge it goes back to, and reduced motion */\ntype Leave = { swiped: boolean; toward: number; reduce: boolean };\n\nconst leaveVariants = {\n  exit: ({ swiped, toward, reduce }: Leave) =>\n    reduce\n      ? { opacity: 0, transition: { duration: duration.fast } }\n      : swiped\n        ? // It's already flying off sideways (onSwipeEnd); it only fades as it goes\n          { opacity: 0, filter: blur.hidden, transition: { duration: duration.base, ease: ease.out } }\n        : // Back out to the edge it came in from, on a timed curve so it's quickly gone\n          {\n            opacity: 0,\n            filter: blur.hidden,\n            y: `${-toward * 100}%`,\n            transition: { duration: duration.base, ease: ease.in },\n          },\n} satisfies Variants;\n\nconst settle = { duration: duration.base, ease: ease.out };\n\nexport type ToastProps = Omit<ComponentProps<typeof ToastPrimitive.Root>, \"asChild\" | \"forceMount\"> & {\n  /** Destructive turns the title (and the icon, in toasts from `toast.error`) the destructive colour */\n  variant?: \"default\" | \"destructive\";\n  /** Called once the toast has finished leaving, for example to drop it from your own list */\n  onExitComplete?: () => void;\n};\n\n/**\n * One notification, built on Radix Toast's root. It stays open for the provider's `duration` (or its own),\n * paused while hovered or focused. Use `open` and `onOpenChange` to show it, or leave them out and it opens\n * as it mounts. Escape, a swipe, ToastClose and ToastAction close it.\n */\nfunction Toast({\n  className,\n  variant = \"default\",\n  open: openProp,\n  defaultOpen = true,\n  onOpenChange,\n  onExitComplete,\n  onSwipeStart,\n  onSwipeMove,\n  onSwipeCancel,\n  onSwipeEnd,\n  duration: durationProp,\n  style,\n  children,\n  ...props\n}: ToastProps) {\n  // The open state lives here, controlled or not, so the toast can play its exit before Radix unmounts it\n  const [own, setOwn] = useState(defaultOpen);\n  const open = openProp ?? own;\n  const stack = useContext(StackContext);\n  const { add, remove, measure, reduce } = stack;\n  const id = useId();\n  const [box, setBox] = useState<HTMLLIElement | null>(null);\n  const [content, setContent] = useState<HTMLDivElement | null>(null);\n  // The swipe moves the toast sideways through `x`, separate from its place in the deck (`y`, `scale`)\n  const swipeX = useMotionValue(0);\n  const [swiped, setSwiped] = useState(false);\n  const flight = useRef<AnimationPlaybackControls | null>(null);\n  const stay = durationProp ?? stack.duration;\n  const remaining = useRef(stay);\n\n  // Open toasts join the stack. One that closes leaves it at once, so the rest move up while it slides out.\n  useLayoutEffect(() => {\n    if (!open) return;\n    add(id);\n    setSwiped(false);\n    swipeX.jump(0);\n    return () => remove(id);\n  }, [open, id, add, remove, swipeX]);\n\n  // Its full height, measured from the content: a tucked toast's own box is the front one's height\n  useLayoutEffect(() => {\n    if (!open || !box || !content) return;\n    const update = () => measure(id, content.offsetHeight + box.offsetHeight - box.clientHeight);\n    update();\n    const observer = new ResizeObserver(update);\n    observer.observe(content);\n    return () => observer.disconnect();\n  }, [open, box, content, id, measure]);\n\n  // Unmounting mid-swipe stops the swipe's spring or flight\n  useEffect(() => () => flight.current?.stop(), []);\n\n  const setOpen = (next: boolean) => {\n    if (openProp === undefined) setOwn(next);\n    onOpenChange?.(next);\n  };\n  // The timer calls the latest close, without restarting whenever the parent renders\n  const close = useRef(() => {});\n  useLayoutEffect(() => {\n    close.current = () => setOpen(false);\n  });\n\n  // The close timer runs here rather than in Radix. Radix keeps its paused flag in a ref that only its own\n  // listeners reset, and they detach with the last toast, so closing one with the mouse could leave the\n  // next one paused for good. This one waits on the deck's own hover and focus, and on the window.\n  // A new duration (toast.promise settling) or reopening starts the time again.\n  // biome-ignore lint/correctness/useExhaustiveDependencies: reopening starts the time again too\n  useEffect(() => {\n    remaining.current = stay;\n  }, [stay, open]);\n  // biome-ignore lint/correctness/useExhaustiveDependencies: a new duration starts the timer again\n  useEffect(() => {\n    if (!open || stack.paused || !Number.isFinite(remaining.current)) return;\n    const started = Date.now();\n    const timer = setTimeout(() => close.current(), Math.max(0, remaining.current));\n    return () => {\n      clearTimeout(timer);\n      remaining.current -= Date.now() - started;\n    };\n  }, [open, stack.paused, stay]);\n\n  // Its place: 0 is the newest, in front. Older toasts sit behind it (collapsed) or after it (fanned out).\n  const edge = stack.position.startsWith(\"top\") ? \"top\" : \"bottom\";\n  const toward = edge === \"bottom\" ? -1 : 1; // older toasts go up from the bottom, down from the top\n  const order = stack.ids.indexOf(id);\n  const index = order < 0 ? 0 : stack.ids.length - 1 - order;\n  const front = stack.ids[stack.ids.length - 1];\n  const place = Math.min(index, stack.visibleToasts - 1); // past the limit, it waits behind the last one shown\n  const hidden = index >= stack.visibleToasts;\n  const tucked = !stack.expanded && index > 0;\n  const ahead = order < 0 ? [] : stack.ids.slice(order + 1);\n  const before = ahead.reduce((total, other) => total + (stack.heights[other] ?? 0), 0);\n  const y = toward * (stack.expanded ? before + index * GAP : place * PEEK);\n  const scale = stack.expanded ? 1 : 1 - place * SHRINK;\n  const height = tucked && front ? stack.heights[front] : stack.heights[id];\n  const leave: Leave = { swiped, toward, reduce };\n\n  return (\n    <AnimatePresence custom={leave} onExitComplete={onExitComplete}>\n      {open ? (\n        <ToastPrimitive.Root\n          key=\"toast\"\n          asChild\n          open\n          // The timer above closes it; Radix's never starts\n          duration={Number.POSITIVE_INFINITY}\n          onOpenChange={(next) => {\n            if (!next) setOpen(false);\n          }}\n          onSwipeStart={(event) => {\n            onSwipeStart?.(event);\n            flight.current?.stop();\n          }}\n          onSwipeMove={(event) => {\n            onSwipeMove?.(event);\n            // It follows the finger exactly: jump() sets the value without counting it as speed\n            if (!event.defaultPrevented) swipeX.jump(event.detail.delta.x);\n          }}\n          onSwipeCancel={(event) => {\n            onSwipeCancel?.(event);\n            if (!event.defaultPrevented)\n              flight.current = animate(swipeX, 0, reduce ? { duration: 0 } : spring.snappy);\n          }}\n          onSwipeEnd={(event) => {\n            onSwipeEnd?.(event);\n            if (event.defaultPrevented) return;\n            setSwiped(true);\n            // Past the threshold it carries on the way it was going, off the side of the screen\n            if (!reduce)\n              flight.current = animate(swipeX, Math.sign(event.detail.delta.x) * (box?.offsetWidth ?? 0), {\n                duration: duration.base,\n                ease: ease.out,\n              });\n          }}\n          {...props}\n        >\n          <motion.li\n            ref={setBox}\n            data-slot=\"toast\"\n            data-variant={variant}\n            data-edge={edge}\n            data-front={index === 0 || undefined}\n            data-tucked={tucked || undefined}\n            data-hidden={hidden || undefined}\n            inert={hidden || undefined}\n            className={cn(\n              toastVariants(),\n              \"group/toast absolute inset-x-0 overflow-hidden\",\n              \"outline-ring focus-visible:outline-(length:--focus-ring-width) focus-visible:outline-offset-(--focus-ring-offset)\",\n              // It sits at the screen's edge of the list, and scales from the side that shows behind the newest\n              \"data-[edge=bottom]:bottom-0 data-[edge=bottom]:origin-top data-[edge=top]:top-0 data-[edge=top]:origin-bottom\",\n              \"data-hidden:pointer-events-none\",\n              className,\n            )}\n            style={{ x: swipeX, zIndex: stack.ids.length - index, ...style }}\n            custom={leave}\n            variants={leaveVariants}\n            initial={reduce ? { opacity: 0 } : { opacity: 0, filter: blur.hidden, y: `${-toward * 100}%` }}\n            animate={{\n              opacity: hidden ? 0 : 1,\n              filter: blur.shown,\n              y,\n              scale,\n              ...(height === undefined ? {} : { height }),\n            }}\n            exit=\"exit\"\n            transition={\n              reduce\n                ? { duration: 0, opacity: { duration: duration.fast } }\n                : {\n                    y: spring.snappy,\n                    scale: spring.snappy,\n                    opacity: settle,\n                    filter: settle,\n                    height: { duration: duration.slow, ease: ease.out },\n                  }\n            }\n          >\n            {/* Tucked behind the newest, a toast's content goes; it comes back through the blur as the deck fans out */}\n            <motion.div\n              ref={setContent}\n              data-slot=\"toast-content\"\n              className=\"flex items-center gap-3 py-3 ps-4 pe-3\"\n              initial={false}\n              animate={tucked ? { opacity: 0, filter: blur.hidden } : { opacity: 1, filter: blur.shown }}\n              transition={settle}\n            >\n              {children}\n            </motion.div>\n          </motion.li>\n        </ToastPrimitive.Root>\n      ) : null}\n    </AnimatePresence>\n  );\n}\n\nfunction ToastTitle({ className, ...props }: ComponentProps<typeof ToastPrimitive.Title>) {\n  return (\n    <ToastPrimitive.Title\n      data-slot=\"toast-title\"\n      className={cn(\"text-sm font-medium group-data-[variant=destructive]/toast:text-destructive\", className)}\n      {...props}\n    />\n  );\n}\n\nfunction ToastDescription({ className, ...props }: ComponentProps<typeof ToastPrimitive.Description>) {\n  return (\n    <ToastPrimitive.Description\n      data-slot=\"toast-description\"\n      className={cn(\"text-sm text-muted-foreground\", className)}\n      {...props}\n    />\n  );\n}\n\n/**\n * A button that acts on the toast (\"Undo\"), then closes it. `altText` says how to do the same without the\n * toast, for screen readers, which may hear the toast after it's gone.\n */\nfunction ToastAction({ className, ...props }: ComponentProps<typeof ToastPrimitive.Action>) {\n  return (\n    <ToastPrimitive.Action\n      data-slot=\"toast-action\"\n      className={cn(buttonVariants({ variant: \"outline\", size: \"sm\" }), \"bg-transparent\", className)}\n      {...props}\n    />\n  );\n}\n\n/** Closes the toast. An X named \"Close\" unless you give it children or another aria-label. */\nfunction ToastClose({\n  className,\n  children,\n  \"aria-label\": label = \"Close\",\n  ...props\n}: ComponentProps<typeof ToastPrimitive.Close>) {\n  return (\n    <ToastPrimitive.Close\n      data-slot=\"toast-close\"\n      aria-label={label}\n      className={cn(\n        buttonVariants({ variant: \"ghost\", size: \"icon-sm\" }),\n        \"size-6 rounded-md text-muted-foreground hover:text-foreground\",\n        className,\n      )}\n      {...props}\n    >\n      {children ?? <XIcon aria-hidden className=\"size-(--size-icon-sm)\" />}\n    </ToastPrimitive.Close>\n  );\n}\n\n/* ------------------------------------------------------------------------------------------------------ */\n/* toast(): a tiny store, read by <Toaster /> with useSyncExternalStore                                     */\n\ntype Kind = \"default\" | \"success\" | \"error\" | \"loading\";\n\nexport type ToastOptions = {\n  /** Updates the toast with this id, if it's showing, instead of adding another */\n  id?: string;\n  /** A second line under the title */\n  description?: ReactNode;\n  /** A button on the toast, such as Undo. It closes the toast after onClick, unless onClick prevents it. */\n  action?: { label: string; onClick?: (event: MouseEvent<HTMLButtonElement>) => void; altText?: string };\n  /** Milliseconds before it closes; Infinity to keep it until it's dismissed */\n  duration?: number;\n};\n\ntype ToastRecord = ToastOptions & {\n  id: string;\n  kind: Kind;\n  title: ReactNode;\n  open: boolean;\n  /** Counts updates, so changed content swaps in */\n  version: number;\n};\n\nlet records: ToastRecord[] = [];\nlet count = 0;\nconst listeners = new Set<() => void>();\nconst noRecords: ToastRecord[] = [];\n\nfunction commit(next: ToastRecord[]) {\n  records = next;\n  for (const listener of listeners) listener();\n}\n\nfunction subscribe(listener: () => void) {\n  listeners.add(listener);\n  return () => {\n    listeners.delete(listener);\n  };\n}\n\nconst getRecords = () => records;\nconst getNoRecords = () => noRecords;\n\nfunction show(kind: Kind, title: ReactNode, options: ToastOptions = {}) {\n  const id = options.id ?? `toast-${++count}`;\n  const current = records.find((record) => record.id === id);\n  commit(\n    current\n      ? records.map((record) =>\n          record === current\n            ? { ...record, ...options, id, kind, title, open: true, version: record.version + 1 }\n            : record,\n        )\n      : [...records, { ...options, id, kind, title, open: true, version: 0 }],\n  );\n  return id;\n}\n\n/** Closes one toast, or every toast without an id. It leaves the store once its exit has played. */\nfunction dismiss(id?: string) {\n  if (!records.some((record) => record.open && (id === undefined || record.id === id))) return;\n  commit(\n    records.map((record) =>\n      record.open && (id === undefined || record.id === id) ? { ...record, open: false } : record,\n    ),\n  );\n}\n\nfunction drop(id: string) {\n  commit(records.filter((record) => record.id !== id));\n}\n\ntype Message<T> = ReactNode | ((value: T) => ReactNode);\n\nfunction promise<T>(\n  work: Promise<T> | (() => Promise<T>),\n  messages: { loading: ReactNode; success: Message<T>; error: Message<unknown> },\n  options?: Omit<ToastOptions, \"id\">,\n) {\n  const id = show(\"loading\", messages.loading, options);\n  const running = typeof work === \"function\" ? work() : work;\n  running.then(\n    (value) =>\n      show(\"success\", typeof messages.success === \"function\" ? messages.success(value) : messages.success, {\n        ...options,\n        id,\n      }),\n    (error: unknown) =>\n      show(\"error\", typeof messages.error === \"function\" ? messages.error(error) : messages.error, {\n        ...options,\n        id,\n      }),\n  );\n  return id;\n}\n\n/**\n * Shows a toast in the Toaster and returns its id. `toast.success`, `toast.error` and `toast.loading` add an\n * icon (loading stays until it's updated or dismissed); `toast.promise` shows loading, then the result, in\n * the same toast; `toast.dismiss(id?)` closes one toast, or all of them.\n */\nconst toast = Object.assign((title: ReactNode, options?: ToastOptions) => show(\"default\", title, options), {\n  success: (title: ReactNode, options?: ToastOptions) => show(\"success\", title, options),\n  error: (title: ReactNode, options?: ToastOptions) => show(\"error\", title, options),\n  loading: (title: ReactNode, options?: ToastOptions) => show(\"loading\", title, options),\n  promise,\n  dismiss,\n});\n\n/** The plain text of a toast's content, for the announcement when it changes */\nfunction textOf(node: ReactNode): string {\n  if (node == null || typeof node === \"boolean\") return \"\";\n  if (typeof node === \"string\" || typeof node === \"number\") return String(node);\n  if (Array.isArray(node)) return node.map(textOf).join(\"\");\n  if (isValidElement<{ children?: ReactNode }>(node)) return textOf(node.props.children);\n  return \"\";\n}\n\n/** The same check and cross as Loading Button, drawing themselves in (pathLength, a 16px stroke) */\nconst CHECK = \"M5 12.5l4.5 4.5L19 7.5\";\nconst CROSS = \"M7 7l10 10M17 7L7 17\";\n\nfunction Mark({ d, reduce }: { d: string; reduce: boolean }) {\n  return (\n    <svg viewBox=\"0 0 24 24\" fill=\"none\" aria-hidden className=\"size-(--size-icon-md)\">\n      <motion.path\n        d={d}\n        stroke=\"currentColor\"\n        strokeWidth=\"2.5\"\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n        initial={{ pathLength: reduce ? 1 : 0 }}\n        animate={{ pathLength: 1 }}\n        transition={{ duration: duration.slow, ease: ease.out, delay: reduce ? 0 : duration.instant }}\n      />\n    </svg>\n  );\n}\n\nconst fade = { initial: { opacity: 0 }, animate: { opacity: 1 }, exit: { opacity: 0 } };\n\nfunction ToasterToast({ record, onUpdate }: { record: ToastRecord; onUpdate: (text: string) => void }) {\n  const reduce = useReducedMotion() ?? false;\n  const { kind, version } = record;\n\n  // Radix reads a toast out once, as it opens. An update (toast.promise settling) is read out here instead.\n  // biome-ignore lint/correctness/useExhaustiveDependencies: only an update is read out\n  useEffect(() => {\n    if (version > 0) onUpdate([textOf(record.title), textOf(record.description)].filter(Boolean).join(\". \"));\n  }, [version]);\n\n  const icon =\n    kind === \"loading\" ? (\n      <Spinner aria-hidden />\n    ) : kind === \"success\" ? (\n      <Mark d={CHECK} reduce={reduce} />\n    ) : kind === \"error\" ? (\n      <span className=\"flex text-destructive\">\n        <Mark d={CROSS} reduce={reduce} />\n      </span>\n    ) : null;\n  const motionProps = reduce ? fade : swap;\n\n  return (\n    <Toast\n      open={record.open}\n      onOpenChange={(open) => {\n        if (!open) dismiss(record.id);\n      }}\n      onExitComplete={() => drop(record.id)}\n      variant={kind === \"error\" ? \"destructive\" : \"default\"}\n      duration={kind === \"loading\" ? Number.POSITIVE_INFINITY : record.duration}\n      data-type={kind}\n    >\n      {/* Updated content swaps in the same cell: the old lifts away blurring as the new rises in */}\n      <div className=\"grid min-w-0 flex-1\">\n        <AnimatePresence>\n          <motion.div\n            key={version}\n            initial={version === 0 ? false : motionProps.initial}\n            animate={motionProps.animate}\n            exit={motionProps.exit}\n            transition={\n              reduce\n                ? { duration: duration.fast }\n                : { duration: duration.base, ease: ease.out, y: spring.snappy }\n            }\n            className=\"col-start-1 row-start-1 flex items-start gap-3\"\n          >\n            {/* The icon sits on the title's first line */}\n            {icon ? <span className=\"flex h-5 shrink-0 items-center\">{icon}</span> : null}\n            <div className=\"grid min-w-0 gap-0.5\">\n              <ToastTitle>{record.title}</ToastTitle>\n              {record.description ? <ToastDescription>{record.description}</ToastDescription> : null}\n            </div>\n          </motion.div>\n        </AnimatePresence>\n      </div>\n      {record.action ? (\n        <ToastAction altText={record.action.altText ?? record.action.label} onClick={record.action.onClick}>\n          {record.action.label}\n        </ToastAction>\n      ) : null}\n      <ToastClose />\n    </Toast>\n  );\n}\n\n/** Mounted Toasters, in mount order. Only the first shows toasts, so placing two never doubles them. */\nconst toasters: ((live: boolean) => void)[] = [];\n\nfunction syncToasters() {\n  toasters.forEach((setLive, index) => {\n    setLive(index === 0);\n  });\n}\n\nexport type ToasterProps = ToastViewportProps & {\n  /** Milliseconds each toast stays open, unless it sets its own duration */\n  duration?: number;\n};\n\n/**\n * Shows the toasts from `toast()`. Place it once, for example in your root layout; it takes the\n * viewport's props (position, expand, visibleToasts).\n */\nfunction Toaster({ duration: stay, ...props }: ToasterProps) {\n  const items = useSyncExternalStore(subscribe, getRecords, getNoRecords);\n  const [live, setLive] = useState(false);\n  const [announcement, setAnnouncement] = useState(\"\");\n\n  useEffect(() => {\n    toasters.push(setLive);\n    syncToasters();\n    return () => {\n      toasters.splice(toasters.indexOf(setLive), 1);\n      syncToasters();\n    };\n  }, []);\n\n  // Toasts that closed while no Toaster could play their exit are gone already\n  useEffect(() => {\n    if (live && records.some((record) => !record.open)) commit(records.filter((record) => record.open));\n  }, [live]);\n\n  if (!live) return null;\n  return (\n    <ToastProvider duration={stay}>\n      {items.map((record) => (\n        <ToasterToast key={record.id} record={record} onUpdate={setAnnouncement} />\n      ))}\n      <ToastViewport {...props} />\n      <span aria-live=\"polite\" className=\"sr-only\">\n        {announcement}\n      </span>\n    </ToastProvider>\n  );\n}\n\nexport {\n  Toast,\n  ToastAction,\n  ToastClose,\n  ToastDescription,\n  Toaster,\n  ToastProvider,\n  ToastTitle,\n  ToastViewport,\n  toast,\n  toastVariants,\n  toastViewportVariants,\n};\n"
    }
  ],
  "categories": [
    "feedback"
  ],
  "docs": "Usage and examples: https://ui.fewtone.com/components/toast"
}
