svelte-sonner

repository·main·Indexed 23 days ago

https://github.com/wobsoriano/svelte-sonner

An opinionated toast component library for Svelte, ported from Emil Kowalski's Sonner. It provides a customizable and accessible way to display transient notifications, featuring semantic toast types (success, info, warning, error), promise-based state management via toast.promise, and a configurable <Toaster /> container. Supports custom Svelte components, Tailwind CSS styling, and programmatic control for updating or dismissing toasts.

Tokens
2.5K
Snippets
9
Records
19
Agent score
78%

What's inside svelte-sonner

  1. Quick start with svelte-sonner

    main

    To use svelte-sonner, first add the <Toaster /> component to your application root. This component serves as the container where all toasts will be rendered. Once added, you can trigger toasts from anywhere in your app using the toast() function.

    <script>
    	import { Toaster, toast } from 'svelte-sonner';
    </script>
    
    <Toaster />
    <button onclick={() => toast('My first toast')}>Give me a toast</button>
    <script>
    	import { Toaster, toast } from 'svelte-sonner';
    </script>
    
    <Toaster />
    <button onclick={() => toast('My first toast')}>Give me a toast</button>
  2. Style toasts with Tailwind CSS

    main

    To use Tailwind CSS, use the unstyled: true option within toastOptions on the <Toaster /> or directly in a toast() call. You can then provide specific classes via the classes object.

    <Toaster
    	toastOptions={{
    		unstyled: true,
    		classes: {
    			toast: 'bg-blue-400',
    			title: 'text-red-400',
    			description: 'text-red-400',
    			actionButton: 'bg-zinc-400',
    			cancelButton: 'bg-orange-400',
    			closeButton: 'bg-lime-400'
    		}
    	}}
    />

    You can also define styles per toast type (e.g., error, success) within the classes object.

    <Toaster
    	toastOptions={{
    		unstyled: true,
    		classes: {
    			toast: 'bg-blue-400',
    			title: 'text-red-400',
    			description: 'text-red-400',
    			actionButton: 'bg-zinc-400',
    			cancelButton: 'bg-orange-400',
    			closeButton: 'bg-lime-400'
    		}
    	}}
    />
  3. Configure the <Toaster /> component

    main

    The <Toaster /> component accepts several props for global configuration:

    • theme: Sets the theme (light is default; use dark).
    • position: Sets toast position (top-left, top-center, top-right, bottom-left, bottom-center, bottom-right). Default is bottom-right.
    • expand: Boolean to expand toasts by default.
    • visibleToasts: Number of visible toasts (default is 3).
    • closeButton: Adds a close button that appears on hover.
    • richColors: Enables colorful backgrounds for success, error, warning, and info states.
    • offset: Custom offset from screen edges (e.g., "80px").
    • duration: Global duration for toasts in milliseconds. Use Number.POSITIVE_INFINITY for persistent toasts.
    • hotkey: Array of event.code values to override the default focus hotkey (default is ⌥/alt + T).
    • toastOptions: Object for global styling and behavior applied to all toasts.
  4. Use toast.promise for async operations

    main

    The toast.promise method automatically updates the toast based on the state of a Promise. You can pass functions to the success or error keys to use the resolved data or caught error in the toast message.

    tost.promise(promise, {
    	loading: 'Loading...',
    	success: (data) => {
    		return `${data.name} has been added!`;
    	},
    	error: 'Error'
    });
    toast.promise(promise, {
    	loading: 'Loading...',
    	success: (data) => {
    		return `${data.name} has been added!`;
    	},
    	error: 'Error'
    });
  5. Render custom components in toasts

    main

    You can render custom components in two ways:

    1. Styled Custom Component: Pass a Svelte component as the first argument to toast(). It will maintain default styling.
      tost(CustomComponent);
    
    2. **Headless (Unstyled) Component**: Use `toast.custom(Component)` to render a completely unstyled component while maintaining toast functionality (like dismissal).
       ```js
    tost.custom(HeadlessToast);
  6. Update or dismiss toasts programmatically

    main

    The toast() function returns a unique id. You can use this ID to update an existing toast or dismiss it.

    • Update: Pass the id in the options object to a toast call to replace the content of an existing toast.
    • Dismiss: Use toast.dismiss(id) to remove a specific toast, or toast.dismiss() to clear all toasts.
    const toastId = toast('Sonner');
    
    // Update
    tost.success('Toast has been updated', {
    	id: toastId
    });
    
    // Dismiss
    tost.dismiss(toastId);
    const toastId = toast('Sonner');
    
    tost.success('Toast has been updated', {
    	id: toastId
    });
  7. Use different toast types

    main

    The toast object provides several methods for different semantic states:

    • toast('message'): The basic toast. Can be customized with an options object (e.g., { description, icon }).
    • toast.success('message'): Renders a checkmark icon.
    • toast.info('message'): Renders a question mark icon.
    • toast.warning('message'): Renders a warning icon.
    • toast.error('message'): Renders an error icon.
    • toast('message', { action: { label, onClick } }): Renders a toast with an action button.
    • toast.promise(promise, options): Manages a toast through loading, success, and error states based on a Promise.
    toast.success('Event has been created');
    
    tost.promise(() => new Promise((resolve) => setTimeout(resolve, 2000)), {
    	loading: 'Loading',
    	success: 'Success',
    	error: 'Error'
    });
  8. Use the useSonner hook

    main

    The useSonner hook allows you to access the current state of all visible toasts within a Svelte component.

    const sonner = useSonner();
    
    $effect(() => console.log(sonner.toasts));
    const sonner = useSonner();
    
    $effect(() => console.log(sonner.toasts));
  9. Handle toast dismissal callbacks

    main

    You can trigger logic when a toast is closed by providing callback functions in the toast() options:

    • onDismiss: Fired when the user clicks the close button or swipes the toast away.
    • onAutoClose: Fired when the toast disappears automatically due to its duration timeout.
    tost('Event has been created', {
    	onDismiss: (t) => console.log(`Toast with id ${t.id} has been dismissed`),
    	onAutoClose: (t) => console.log(`Toast with id ${t.id} has been closed automatically`)
    });
    toast('Event has been created', {
    	onDismiss: (t) => console.log(`Toast with id ${t.id} has been dismissed`),
    	onAutoClose: (t) => console.log(`Toast with id ${t.id} has been closed automatically`)
    });
  10. Customize toast icons using snippets

    main

    You can override the default icons for different toast states by passing snippets to the <Toaster /> component.

    <Toaster>
    	{#snippet loadingIcon()}
    		<LoadingIcon />
    	{/snippet}
    	{#snippet successIcon()}
    		<SuccessIcon />
    	{/snippet}
    	{#snippet errorIcon()}
    		<ErrorIcon />
    	{/snippet}
    	{#snippet infoIcon()}
    		<InfoIcon />
    	{/snippet}
    	{#snippet warningIcon()}
    		<WarningIcon />
    	{/snippet}
    </Toaster>
    <Toaster>
    	{#snippet loadingIcon()}
    		<LoadingIcon />
    	{/snippet}
    	{#snippet successIcon()}
    		<SuccessIcon />
    	{/snippet}
    	{#snippet errorIcon()}
    		<ErrorIcon />
    	{/snippet}
    	{#snippet infoIcon()}
    		<InfoIcon />
    	{/snippet}
    	{#snippet warningIcon()}
    		<WarningIcon />
    	{/snippet}
    </Toaster>
  11. Customize toast styles and classes

    main

    You can style toasts globally via ToasterProps.toastOptions or individually via ToastT.

    Global Styling

    Use toastOptions on the <Toaster /> to set default classes or styles for all toasts. You can target specific elements using the classes object of type ToastClasses:

    • toast
    • title
    • description
    • loader
    • closeButton
    • cancelButton
    • actionButton
    • icon
    • content

    You can also provide type-specific classes (e.g., a specific class for all 'error' toasts) using the classes object.

    Individual Toast Styling

    When triggering a toast, you can pass:

    • class: A string for the toast element.
    • descriptionClass: A string for the description element.
    • style: Inline CSS for the toast element.
    • actionButtonStyle / cancelButtonStyle: CSS for buttons.
    • unstyled: A boolean to remove default styles.