A simple toaster handler for Nuxt.js

Related tags

Vue.js nuxt-toaster
Overview

@cssninja/nuxt-toaster

A simple toaster handler for Nuxt.js

npm

Features

  • Unstyled by default
  • Render any component as a toast
  • Fully customizable
  • Simple to use

Installation

  1. Add @cssninja/nuxt-toaster dependency to your project
# Using pnpm
pnpm add -D @cssninja/nuxt-toaster

# Using yarn
pnpm add -D @cssninja/nuxt-toaster

# Using npm
npm install --save-dev @cssninja/nuxt-toaster
  1. Add @cssninja/nuxt-toaster to the modules section of nuxt.config.js
export default defineNuxtConfig({
  modules: [
    '@cssninja/nuxt-toaster'
  ]
})

Basic Usage

Show a toast

// get the ninjaToaster instance
const { $nt } = useNuxtApp()

// show a toast with a string as content
$nt.show('Hello world')

Show a toast with a custom component

// define or import a component
const MyToast = defineComponent({
  /* ... */
})

// get the ninjaToaster instance
const { $nt } = useNuxtApp()

// show a toast with render function as content
$nt.show(() => h(MyToast))

Configuration

Using ninjaToaster.show options

// get the ninjaToaster instance
const { $nt } = useNuxtApp()

$nt.show({
  /**
   * The content of the toast, can be a render function
   * 
   * @required
   */
  content: 'Hello world',

  /**
   * The duration of the toast
   * 
   * @default 5000
   */
  duration: 5000,
  

  /**
   * Pause the duration timer on hover, or focus
   * 
   * @default true
   */
  pauseOnHover: true,

  /**
   * Whereas the toast can be closed on click,
   * or on pressing Enter/Space keys when focused
   * 
   * @default true
   */
  dismissible: false,

  /**
   * Maximum number of toasts to show 
   * on the same `theme.containerId`
   * 
   * @default Infinity
   */
  maxToasts: 5,

  /**
   * Transition property for the toast
   * 
   * @see https://vuejs.org/api/built-in-components.html#transition
   */
  transition: {
    name: 'fadeIn',
  },

  /**
   * The theme used for the toast
   */
  theme: {
    containerId: 'nt-container',
    containerClass: 'nt-container-class',
    wrapperClass: 'nt-wrapper-class',
  }
})

This will create a toast with the following HTML structure:

<body>
  <!-- ... -->
  <div id="nt-container" class="nt-container-class">
    <div
      class="nt-wrapper-class"
      role="alert"
      tabindex="0"
    >
      Hello world
    </div>
  </div>
</body>

note: the theme property is used to customize the toaster behavior. Each theme.containerId will have their own context (e.g. the maxToasts will count how many toaster are visible in the container with matching id).

Using toaster app config

To avoid to repeat yourself, you can set defaults values for ninjaToaster.show method in the nuxt app.config.ts at the root of your project.

// app.config.ts
export default defineAppConfig({
  toaster: {
    // default options for ninjaToaster.show
  }
})

Using a custom plugin

By default, the module create an instance of ninjaToaster and inject it in the nuxt context in useNuxtApp().$nt.

You can create your own instance and inject it in the context by using a custom plugin.

  1. Disable default plugin in nuxt.config.ts module options
// nuxt.config.ts
export default defineNuxtConfig({
  modules: [
    '@cssninja/nuxt-toaster'
  ],
  toaster: {
    // disable the default plugin 
    installPlugin: false
  }
})
  1. Create a custom toast component
<script setup lang="ts">
// components/MyToast.vue
const props = defineProps<{
  title: string
  message?: string
  type: 'info' | 'error'
}>()

const {
  isHovered,
  isActive,
  timer,
  duration,
  click,
  close,
} = useNinjaToasterState()

const {
  percent,
  endAt,
  closeIn
} = useNinjaToasterProgress()
</script>

<template>
  <div
    class="rounded p-4"
    :class="[
      props.type === 'info' && 'bg-indigo-600 text-indigo-500'
      props.type === 'error' && 'bg-rose-600 text-rose-500'
    ]"
  >
    <h1>{{ props.title }}</h1>
    <p v-if="props.message">{{ props.message }}</p>
    <button @click="close()">Close</button>
  </div>
</template>
  1. Create a custom plugin
// plugins/toaster.ts
import MyToast from '~/components/MyToast.vue'

interface ToasterOptions {
  message: string
  title?: string
}

export default defineNuxtPlugin(() => {
  // define or import a theme
  const theme = {
    containerId: 'nt-container-bottom-right',
    containerClass: [
      'absolute',
      'inset-0',
      'pointer-events-none',
      'p-4',
      'flex',
      'flex-col-reverse',
      'items-start',
      'gap-2'
    ].join(' '),
    wrapperClass: [
      'pointer-events-auto',
      'cursor-pointer',
    ].join(' '),
  }

  // set default show options here
  const nt = createNinjaToaster({
    theme,
    maxToasts: 5,
    transition: {
      enterActiveClass: 'transition duration-300 ease-out',
      enterFromClass: 'transform translate-x-full opacity-0',
      enterToClass: 'transform translate-x-0 opacity-100',
      leaveActiveClass: 'transition duration-300 ease-in',
      leaveFromClass: 'transform translate-x-0 opacity-100',
      leaveToClass: 'transform translate-x-full opacity-0'
    }
  })

  const toaster = {
    info (options: ToasterOptions) {
      nt.show(() => h(MyToast, {
        ...options,
        type: 'info'
      }))
    },
    async error (options: ToasterOptions) {
      // wait for the toast to be mounted
      const { el, close } = await nt.show(() => h(MyToastError, {
        ...options,
        type: 'error'
      }))

      // focus the toast once it's mounted
      el.focus()
    },
    close() {
      // close all toasts
      nt.closeAll()

      // or close toasts in a specific containerId
      nt.close('nt-container-bottom-right') 

      // or close toasts using a theme
      nt.close(theme)
    },
  }

  return {
    provide {
      toaster
    }
  }
})
  1. Use your toaster instance in your app
// pages/index.vue
const { $toaster } = useNuxtApp()

$toaster.info({
  title: 'Hello world',
  message: 'This is a toaster info message'
})
$toaster.error({
  title: 'Hello world',
  message: 'This is a toaster error message'
})

Development

  • Run npm run dev:prepare to generate type stubs.
  • Use npm run dev to start playground in development mode.
You might also like...

Http-proxy middleware for Nuxt 3.

nuxt-proxy Http-proxy middleware for Nuxt 3. Installation npm install nuxt-proxy Usage export default defineNuxtConfig({ modules: ['nuxt-proxy'],

Dec 30, 2022

Nuxt 3 module for Web3.js

nuxt-web3.js Nuxt 3 module for Web3.js. Installation npm install nuxt-web3.js Usage export default defineNuxtConfig({ modules: ['nuxt-web3.js'], })

Dec 16, 2022

OpenID-Connect(OIDC) integration module for nuxt 3.0.

Nuxt OpenID-Connect OpenID-Connect(OIDC) integration module for nuxt 3.0. Features An Nuxt 3 module. OIDC integration ( implemetation base openid-clie

Dec 24, 2022

๐Ÿ”Ž Meilisearch module for Nuxt 3

๐Ÿ”Ž Meilisearch module for Nuxt 3

nuxt-meilisearch Meilisearch module for Nuxt Features Nuxt 3 Easy integration with MeilisearchJS lib Support for Vue Algolia Vue 3 InstantSearch compo

Dec 26, 2022

A modern, zero-dependency uptime monitoring tool & status page based on GitHub Actions & Nuxt Content v2.

A modern, zero-dependency uptime monitoring tool & status page based on GitHub Actions & Nuxt Content v2.

StatusBase Uptime monitoring tool & beautiful status pages Powered by Nuxt Content v2! Free โ€ข Open Source โ€ข Notification View Demo ยท Report Bug ยท Requ

Jul 5, 2022

Nuxt eureka client

Nuxt eureka client

May 30, 2022

โœ‰๏ธ Nuxt module for first class integration with popular newsletter providers

โœ‰๏ธ Nuxt module for first class integration with popular newsletter providers

nuxt-newsletter Newsletter module for Nuxt 3 โœจ Release Notes ๐Ÿ“– Read the documentation Features Nuxt 3 ready Easy integration with Mailchimp, Revue, B

Jan 5, 2023

๐Ÿ”Ž Algolia module for Nuxt

๐Ÿ”Ž Algolia module for Nuxt

@nuxtjs/algolia Algolia module for Nuxt โœจ Release Notes ๐Ÿ“– Read the documentation Features Nuxt 3 ready Easy integration with Algolia Handy composable

Jul 28, 2022

โšก๏ธ Integrate Nuxt with Twind, The smallest, fastest, most feature complete tailwind-in-js solution in existence!

Nuxt Twind Module Integrate Nuxt with Twind, The smallest, fastest, most feature complete tailwind-in-js solution in existence! Warning ๐Ÿงช This module

Oct 18, 2022
Comments
  • Feat/landing page hero

    Feat/landing page hero

    You can review commits inside, but you can't merge this PR until it is marked as complete.

    • Refactor app.vue
    • Add pages folder
    • Add navigation component [wip]
    • Add hero component [wip]

    @stafyniaksacha can you make tailwind available as a dev dependency for the playground? Working with the CDN is just a pain.

    opened by driss-chelouati 0
  • Configure Renovate

    Configure Renovate

    Mend Renovate

    Welcome to Renovate! This is an onboarding PR to help you understand and configure settings before regular Pull Requests begin.

    ๐Ÿšฆ To activate Renovate, merge this Pull Request. To disable Renovate, simply close this Pull Request unmerged.


    Detected Package Files

    • .github/workflows/release.yml (github-actions)
    • package.json (npm)
    • playground/package.json (npm)

    Configuration

    ๐Ÿ”ก Renovate has detected a custom config for this PR. Feel free to ask for help if you have any doubts and would like it reviewed.

    Important: Now that this branch is edited, Renovate can't rebase it from the base branch any more. If you make changes to the base branch that could impact this onboarding PR, please merge them manually.

    What to Expect

    It looks like your repository dependencies are already up-to-date and no Pull Requests will be necessary right away.


    โ“ Got questions? Check out Renovate's Docs, particularly the Getting Started section. If you need any further assistance then you can also request help here.


    This PR has been generated by Mend Renovate. View repository job log here.

    opened by renovate[bot] 0
Releases(v0.2.1)
Owner
cssninjaStudio
Sleek Themes for Startups
cssninjaStudio
Nuxt.js module to use Unleash toggle feature services

nuxt-unleash Nuxt.js module to use Unleash toggle feature services ?? Release Notes Features Use $unleash to access and handle your Unleash feature fl

Juanjo Conejero 15 Dec 3, 2022
Easy generation of OpenGraph & Twitter meta-tags in Nuxt 3 ๐Ÿ“‹

nuxt-social-tags Easy generation of OpenGraph & Twitter meta-tags in Nuxt 3 โœจ Release Notes ?? Read the documentation Features Nuxt3 ready Composables

Conner 19 Dec 17, 2022
Easily connect your Nuxt 3 application with LogSnag ๐Ÿ“ฐ

Nuxt LogSnag ?? LogSnag integration for Nuxt 3 โœจ Release Notes Features Nuxt 3 ready Easy integration Handy composables TypeScript support Setup Insta

Conner 13 Apr 28, 2022
Nuxt 3 starter with Algolia, Storyblok, and Indexer

Nuxt 3 with Storyblok CMS and Algolia Search (incl. automatic indexing) This is a demo repository for an article in Dev.to. We recommend to look at th

Jakub Andrzejewski 5 May 24, 2022
End-to-end typesafe APIs with tRPC.io in Nuxt applications.

tRPC-Nuxt End-to-end typesafe APIs with tRPC.io in Nuxt applications. The client above is not importing any code from the server, only its type declar

Robert Soriano 231 Dec 30, 2022
A modern, zero-dependency uptime monitoring tool & status page based on GitHub Actions & Nuxt Content v2.

StatusBase Uptime monitoring tool & beautiful status pages Powered by Nuxt Content v2! Free โ€ข Open Source โ€ข Notification View Demo ยท Report Bug ยท Requ

zernonia 208 Dec 27, 2022
๐Ÿ”Ž Algolia module for Nuxt

@nuxtjs/algolia Algolia module for Nuxt โœจ Release Notes ?? Read the documentation Features Nuxt 3 ready Easy integration with Algolia Handy composable

Nuxt Community 128 Jan 7, 2023
Nuxt 3 module for Kirby's Query Language API

nuxt-kql Kirby KQL module for Nuxt 3. This module provides a useKql composable, which under the hood uses useFetch. Thus, KQL query fetching in your N

Johann Schopplich 25 Dec 15, 2022
This repo contains a fully configured nuxt 3 instance supporting TypeScript and several considered as useful libraries, fully configured and ready to use in real world projects!

Nuxt 3 Starter This repo contains a fully configured nuxt 3 instance supporting TypeScript and several considered as useful libraries, fully configure

Ali Soueidan 26 Dec 27, 2022
Batteries-included, zero-config Ionic integration for Nuxt

Nuxt Ionic Ionic integration for Nuxt โœจ Changelog ?? Read the documentation โ–ถ๏ธ Online playground Features โš ๏ธ nuxt-ionic is currently a work in progres

Daniel Roe 211 Dec 28, 2022