Giter Club home page Giter Club logo

notyf's Introduction

Notyf

npm version Cypress.io tests npm downloads size jsdelivr

Notyf is a minimalistic JavaScript library for toast notifications. It's responsive, A11Y compatible, dependency-free and tiny (~3KB). Easy integration with React, Angular, Aurelia, Vue, and Svelte.

demo gif

Features

  • πŸ“± Responsive
  • πŸ‘“ A11Y compatible
  • πŸ”₯ Strongly typed codebase (TypeScript Typings readily available)
  • ⚑️ 4 types of bundles exposed: ES6, CommonJS, UMD, and IIFE (for vanilla, framework-free usage).
  • 🎯 End-to-end testing with Cypress
  • 🎸 Easily plugable to modern frameworks. Recipes available to integrate with React, Angular, Aurelia, Vue, and Svelte.
  • ✨ Optional ripple-like fancy revealing effect
  • 😈 Simple but highly extensible API. Create your own toast types and customize them.
  • πŸŽƒ Support to render custom HTML content within the toasts
  • 🐣 Tiny footprint (<3K gzipped)
  • πŸ‘΄πŸ½ Works on IE11

Demo: carlosroso.com/notyf

Installation

npm i notyf

Usage

This section explains the base case using the minified bundle. See the quick recipes section for instructions to plug Notyf into Angular, React, Aurelia, Vue, or Svelte.

Add the css and js files to your main document:

<html>
  <head>
    ...
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/notyf@3/notyf.min.css">
  </head>
  <body>
    ...
    <script src="https://cdn.jsdelivr.net/npm/notyf@3/notyf.min.js"></script>
  </body>
</html>

Files are delivered via CDN by jsdeliver

Basic

// Create an instance of Notyf
var notyf = new Notyf();

// Display an error notification
notyf.error('You must fill out the form before moving forward');

// Display a success notification
notyf.success('Your changes have been successfully saved!');

With module bundlers

Notyf ships with an ES6 bundle referenced from the module key of its package.json. This is the file that module bundlers like Webpack will use when using the package. Notyf is exported as a class under the notyf namespace. Typings are also available.

import { Notyf } from 'notyf';
import 'notyf/notyf.min.css'; // for React, Vue and Svelte

// Create an instance of Notyf
const notyf = new Notyf();

// Display an error notification 
notyf.error('Please fill out the form');

API

You can set some options when creating a Notyf instance.

new Notyf(options: INotyfOptions)

Param Type Default Details
duration number 2000 Number of miliseconds before hiding the notification. Use 0 for infinite duration.
ripple boolean true Whether to show the notification with a ripple effect
position INotyfPosition {x:'right',y:'bottom'} Viewport location where notifications are rendered
dismissible boolean Β false Whether to allow users to dismiss the notification with a button
types INotyfNotificationOptions[] Success and error toasts Array with individual configurations for each type of toast

dismiss(notification: NotyfNotification)

Dismiss a specific notification.

const notyf = new Notyf();
const notification = notyf.success('Address updated');
notyf.dismiss(notification);

dismissAll()

Dismiss all the active notifications.

const notyf = new Notyf();
notyf.success('Address updated');
notyf.error('Please fill out the form');
notyf.dismissAll();

Events

Every individual notification emits events. You can register listeners using the on method.

'click'

Triggers when the notification is clicked

const notyf = new Notyf();
const notification = notyf.success('Address updated. Click here to continue');
notification.on('click', ({target, event}) => {
  // target: the notification being clicked
  // event: the mouseevent
  window.location.href = '/';
});

'dismiss'

Triggers when the notification is manually (not programatically) dismissed.

const notyf = new Notyf();
notyf
  .error({
    message: 'There has been an error. Dismiss to retry.',
    dismissible: true
  })
  .on('dismiss', ({target, event}) => foobar.retry());

Interfaces

INotyfPosition

Viewport location where notifications are rendered.

Param Type Details
x left | center | right x-position
y top | center | bottom y-position

INotyfNotificationOptions

Configuration interface for each individual toast.

Param Type Details
type string Notification type for which this configuration will be applied
className string Custom class name to be set in the toast wrapper element
duration number 2000
icon string INotyfIcon false Either a string with HTML markup, an object with the properties of the icon, or 'false' to hide the icon
background string Background color of the toast
message string Message to be rendered inside of the toast. Becomes the default message when used in the global config.
ripple boolean Whether or not to render the ripple at revealing
dismissible boolean Whether to allow users to dismiss the notification with a button

INotyfIcon

Icon configuration

Param Type Details
className string Custom class name to be set in the icon element
tagName string HTML5 tag used to render the icon
text string Inner text rendered within the icon (useful when using ligature icons)
color string Icon color. It must be a valid CSS color value. Defaults to background color.

Examples

Global configuration

The following example configures Notyf with the following settings:

  • 1s duration
  • Render notifications in the top-right corner
  • New custom notification called 'warning' with a ligature material icon
  • Error notification with custom duration, color and dismiss button
const notyf = new Notyf({
  duration: 1000,
  position: {
    x: 'right',
    y: 'top',
  },
  types: [
    {
      type: 'warning',
      background: 'orange',
      icon: {
        className: 'material-icons',
        tagName: 'i',
        text: 'warning'
      }
    },
    {
      type: 'error',
      background: 'indianred',
      duration: 2000,
      dismissible: true
    }
  ]
});

Custom toast type

Register a new toast type and use it by referencing its type name:

const notyf = new Notyf({
  types: [
    {
      type: 'info',
      background: 'blue',
      icon: false
    }
  ]
});

notyf.open({
  type: 'info',
  message: 'Send us <b>an email</b> to get support'
});

Warning: Notyf doesn't sanitize the content when rendering your message. To avoid injection attacks, you should either sanitize your HTML messages or make sure you don't render user generated content on the notifications.

Default types with custom configurations

The default types are 'success' and 'error'. You can use them simply by passing a message as its argument, or you can pass a settings object in case you want to modify its behaviour.

const notyf = new Notyf();

notyf.error({
  message: 'Accept the terms before moving forward',
  duration: 9000,
  icon: false
})

Recipes

Notyf is well supported in all of the modern frameworks such as Angular, React, Aurelia, Vue, or Svelte. Check out the recipes and learn how to integrate the library to your application.

Contributing

Please see the contributing document and read the contribution guidelines. Thanks in advance for all the help!

Licence

Notyf is under MIT licence

notyf's People

Contributors

abrahemalhofe avatar aitongoldman avatar avrahamcool avatar axyxnz avatar bharatramnani94 avatar caroso1222 avatar dependabot[bot] avatar jdjuan avatar miguelcobain avatar roquie avatar strajk avatar stramel avatar xlanex6 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

notyf's Issues

Will a UMD be released with the library?

Hi. Thanks for building this great lib. It's an integral part of one of our libs so we'd love to have a UMD for it since it'll be used in multiple projects that come together at runtime. We're using webpack externals for the libs that are commonly used and I guess other people would do so for sure.

Will a UMD file be released with the library? Again thanks for the work.

[Feature Suggestion] Passing HTML element to icon option

Provide a possibility of passing HTML element to icon option as a shorthand of their config to increase a possibility of customization beside the traditional way

const IconOptions = {
 tagName: 'svg',
 className: '.notyf__icon',
 text: ' . . . ',
 color: 'red'
}

const IconElement = document.createElement('svg')
IconElement.classList.add('notyf__icon')
IconElement.innerHTML = ' . . . '
IconElement.style.color = 'red'

const notyf = new Notyf({
 icon: IconElement // or IconOptions
});

Script Injection possible

Hi! Thanks for this nice toast plugin!

Just wanted to let you know that i is possible to inject malicious code due to the usage of innerHTML. It's easy to test on the demo site as well by entering a message like:
They see me rolling <img src=x onerror='alert("hi");' />
or
They see me rolling <img src=x onerror='alert(document.cookie)' />

Please consider escaping message in some way or replace innerHTML with textContent.

Thanks!

Fix support for Webpack

I am using Notyf with Webpack. Here's how I installed Notyf:

npm install notyf --save

Then I used this code in my VueJS component to initialize (require) Notyf:

var Notyf = require('notyf')
var notyf = new Notyf()
notyf.alert('You must fill out the form before moving forward')

I got the following error:

Uncaught ReferenceError: Notyf is not defined

I have also tried:

import Notyf from 'notyf'

Which didn't work either.

Can anyone help me getting this to work with VueJS and Webpack? I have used other libraries this way too, and they work just fine. This one isn't working. Any help would be appreciated.

Idea for 3.0 API

Hey @caroso1222! Thanks for the project ❀️

I have been thinking about the API and a way to extend the API so it's easier to add more notification types than just success and error.

Seeing that the code that makes the two "types" is nearly identical, it should be pretty "easy" to turn it into a loop:

Instead of using

var notyf = new Notyf({
  delay: 1000,
  alertIcon: 'fa fa-exclamation-circle',
  confirmIcon: 'fa fa-check-circle'  
})

I propose moving to:

const notyf = new Notyf({
  types: {
    success: {
      delay: 1000, // #7
      duration: 2000, // #6
      icon: 'fa-foo-fi-fu'
    },
    error: {} // use all defaults
  }
});

const errorNotification = notyf.error({
  title: 'Something went wrong..',
  message: 'We had some trouble while processing your request'
});

errorNotification.close(); // #20
errorNotification.on('close', () => console.log('Notification closed'));

notyf.success({
  html: "<p>Hooray! <code>image-124.jpg</code> has been uploaded!</p>" // #17
});

By nesting the types in the types key, we keep the "root" level open for global options, for example
position: bottom left|bottom right or classPrefix: noty__.

By using an object instead of a string for the individual

This API change should take care of #6, #7, (half) #13, #17, and #20. Oh, and #21 of course πŸ˜‰

Material Icons?

Hi! Thanks for awesome plugin! :) I'm glad to use it with Vue.js.
I have a next question: what if I want use Material Icons instead of FontAwesome? How can I do this? :)

Problem when using with React 16.2.0

Hello, your bookstore is great! I love it!
I have a problem using it with react in version 16.2.0
At the creation of new toasts, this one will recreate each time new div parent. What is hugely cluttering the DOM and is not really clean ... Do you have a solution? Thank you in advance!

image

CDN version

Please, add a CDN link version, so we can use this package with only vanilla js.

Adjust notification size with javascript

As you can see from the photo below, large content doesn't play well with notyf because the notification container's width is limited to 400px.
chrome_0uhLcWWhFY

Which is fixable using the className option, but now the ripple effect is broken because it's also set to 400px

Can we add an option to specify the max-width of the container which would also be applied to the ripple element?
Something like this:

notyf.error({
                duration: duration,
                position: position,
                dismissible: dismissible,
                message: ErrorMessage,
                max_width: '50em'
            });

The code below (scss) fixes the problem by overriding default styles:

//A custom class applied via className option.
.toast-custom-notyf {
    max-width: 50em !important;

    .notyf__ripple {
        height: 50em;
        width: 50em;
    }
}

And renders the following result:
8HnVttDoLF

And great job on this library, i love it!

Custom notification types

Hi, thanks for such a great library.

For now, there are only two types of notification: alert and confirm with notyf--alert and notyf--confirm css classes respectively.
It would be better, if there was a way to add another type of notification or css class. For example, type warning (with another class).

Example API:

const notyf = new Notyf();

notyf.custom('We had some trouble', { className : 'warning' });

Or based on issue #22:

const notyf = new Notyf({
  types: {
    warning: {
      delay: 1000, // #7
      duration: 2000, // #6
      icon: 'fa-foo-fi-fu',
      notificationClass: 'notyf--warning',
    },
  },
});

const errorNotification = notyf.custom({
  type: 'warning'
  title: 'Some uncritical issue',
  message: 'We had some trouble',
});

Add support for Bower

Hey,

Cool nifty plugin. Some JavaScript frameworks still rely on Bower package manager to manage and import plugins in the project. I would love to see support for Bower.

Feature request

This is a great library and I use it on my site, however, it would be nice to change the configuration dynamically. For example, after a Notyf object is created with dismiss disabled, I want to enable dismiss feature on the fly base on some conditions, or change duration. This is currently not possible. It would be nice to be able to configure these configurations.

Thanks for your works

Custom background colors not accepting gradients

The following config won't properly work:

const notyf = new Notyf({
  types: [
    {
      type: 'custom',
      backgroundColor: 'linear-gradient(45deg, #e541f9, #0aa0ce)'
    }
  ]
});

This is because we're setting the CSS property backgroundColor instead of setting background. Linear gradients are considered to be images and, as such, should be rendered with background-image or the shorthand background.

I think the right way to do this is to introduce a new prop background and deprecate backgroundColor.

This won't be considered as a breaking change as background-color is contained within background

background: [  <background-color>    ||  <background-image>       ||
               <background-repeat>   ||  <background-attachment>  ||
               <background-position>
            ]   |   inherit ;

allow adding of data attributes (for Turbo/Stimulus Reflex)

When notfy is used with modern Multi page applications e.g. Rails, using Stimulus, Stimulus Reflex or Turbo - it is often required to have elements persist throughout page refreshes or DOM diff replacements.
Currently NotyfView adds the .notyf container dynamically when first instantiated, and only once, however this does not survive page reloads even through a memoized instance of Notyf would.
Therefore it's beneficial that the notyf element is able to survive DOM replacements by turbo or otherwise, this is accomplished with data-reflex-permanent, or data-turbo-permanent respectively. While these attributes can be added dynamically Notyf adds/removes this element seemingly at will

Would you be open to a PR that allows data attributes to be passed to the .notyf and .notyf-announcer container elements?

Programmatically close the notyf?

Hi, great work on this. Is there a way to close programmatically the notyf?

ex. var notyf = new Notyf();
// NoTe: should return some id
var theID = notyf.confirm();

after some time...
notyf.close(theID);

Positioning of the toast, how?

How would I change the position of the toast? Will it be included in the future release? I am using Angular 8.2.11. Thanks :)

Inability to wait for NotyfNotification to be removed

Usecase: Run another method once a NotyfNotification is added, dismissed or the timeout expires.

I assumed that with the NotyfNotification class now including on and triggerEvent methods, an event would now be triggered when a notification was removed/added. It appears that triggerEvent is only used to trigger user input events.

Do you have anything against calling NotyfNotification.prototype.triggerEvent in NotyfArray.prototype.push and NotyfArray.prototype.splice?

Feature Request

Would be great if we could have additional default methods for :

Info (Light Blue Background)
notyf.info({......});

Warning (Orange Background)
notyf.warning({......});

The plugin needs an option to setup position

The plugin needs an option to setup position (top-left, top-center, top-right, bottom-left, bottom-center, bottom-right, middle-left, middle-center, middle-right).
Currently, it's stuck to the bottom right.

Btw, it's a great plugin!
Thanks for all the effort you've put into it.

z-index

the z-index in notyf.min.css is 1 I think this should be above any element.

I was using leafletjs and the map is in 999, for obvious reasons the notification did not appear to me and I came to think that it was problems of the api.

I have placed this in 1005 on my fork

.notyf {
    position: fixed;
    bottom: 20px;
    right: 30px;
    width: 20%;
    color: #fff;
    z-index: 1005 /*Here*/
}

unsafe HTML?

Curious to know if there's a way to allow notyf.alert(message_with_html) to be displayed properly?

@caroso1222 Your module allowed us to finally toss jQuery from our entire app.. so thanks!!

[Feature Suggestion] SVG Icons

First of all, I love this notification library, great job!

An improvement to this library would be to allow the use of SVG icons, this change would lessen dependencies on font icon kits and expand the number of icons that can be used with this library.

How to change font of the notification

Hello,
I would like to change the font of the notification to a sans serif one but this is not mentioned in the documentation.
Using the code example I get a serif font:
Screenshot from 2021-02-15 09-18-00

Thanks!

Add yes and no callbacks

Hi,

First of all, thank you for this dead simple lib.

I just have one request, is it possible to add buttons et callback options to confirm and alert methods?

Thank you

Julien

Notification delay

hello! The delay option should be renamed to duration in my opinion, and a new simple "delay" should be added to prevent overlapping, for example; if you add 3 notifications at the same time (alert for example) they all appear and dissapear at the same time, when in fact, setting up a diferent duration or delay to dissapear to each one, should fix it.

It can be done creating multiple instances in your example; but that is not how it should be because if i have 10 alerts, i must have 10 different instances to avoid overlapping!

Popup Modal Library

Because this is such a beautifully well-written toaster lib, I'd be remiss not to ask if you have any recommendations for similar modal/popup libs. Maybe not the place in which place close it but this lib is fantastic so well done.

Ripple effect is broken on long messages.

Screenshot from 2020-08-06 14-45-57

...
off-topic personal opinion follows: The ripple effect is cool and all, but I would consider turning it off by default. The non-ripple animation seems more mature to me.

Alert conflicting with Bootstrap alert

When an alert is created, a classname notyf alert is assigned to the element. The class alert is a special class in Bootstrap so it's setting an additional padding making the card look pretty big.

Fix this by either changing the class name or manually setting padding:0 to the alert element.

Error if trying to use library before body is found

Hi,

I just noticed that this library doesn't work if it's used in a script included in the head section of the page (before the body is in place). It also requires script tag to not have defer attribute.

It boils down to this line

document.body.appendChild(docFrag);

It will give the following error: Cannot read property 'appendChild' of null which basically means that the body is not there yet and can't append to it. It works if I move script tag to bottom or use defer attribute, but in my case I can't use neither.

Is there a way to fix this?

Make interface properties optional

It would be great if the interface properties would be optional so I can type them without implementing all members.

Currently this leads to a typescript compiler error:

 private types: INotyfNotificationOptions[] = [
    {
      type: 'my-custom-type',
      className: 'my-custom-classname',
    }
  ];

I can make a PR if appreciated.

Sorry for being such an irresponsible maintainer

I know there are quite several folks out there using this package and I've been such an irresponsible maintainer to abandon my dear Notyf. This was my first open source package and I've been through a lot these last 2 years.

I'm happy to take the lead on the project again, resolve the issues, close/merge the PRs and set a roadmap for Notyf 3.0 with better animations, more features, better API and more.

Sorry again to all of you who have opened issues or PRs that I have simply ignore or overlooked :(.

[Bug] `duration` option to `0` don't make it infinite

Hello :-)

Describtion

When setting duration option to 0, notification should be visible until the user close/click it (with dismissible or not) following the documentation.

Expected behavior

Setting duration option to 0, notification must be visible until the user close/click it.

Actual behavior

Setting duration option to 0, notification is visible only for a fraction of ms.

How to reproduce & Context

Using https://carlosroso.com/notyf/ under Windows 10 Pro 2004 with:

  • Chromium Version 83.0.4103.61 (Official Build) (64-bit)
  • Google Chrome Version 84.0.4147.105 (Official Build) (64-bit)
  • Firefox 79.0 (64 bits)

Thanks,
Herve-M

large monitor css issue

kapture 2017-05-01 at 21 11 27

I'm emulating a wide monitor here with dev tools, but it also didn't display correctly on my ultrawide windows setup. Its not reaching the side and then on the .disappear it stretches. Hope that makes sense, cool library!

Styles are broken in case of long message

Hi Carlos.
Toasts style are broken in case of long message.

Screen Shot 2019-10-01 at 5 31 18 PM

Repro steps:

const message = `
Unless required by applicable law or agreed to in writing, software distributed under the License
Unless required by applicable law or agreed to in writing, software distributed under the License
Unless required by applicable law or agreed to in writing, software distributed under the License
Unless required by applicable law or agreed to in writing, software distributed under the License
Unless required by applicable law or agreed to in writing, software distributed under the License
Unless required by applicable law or agreed to in writing, software distributed under the License
Unless required by applicable law or agreed to in writing, software distributed under the License

new Notyf().error({
  message: message,
  duration: 20000,
});
`

macOS
Safari Version 12.1 (14607.1.40.1.3)
Google Chrome Version 77.0.3865.90 (Official Build) (64-bit)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.