Code Monkey home page Code Monkey logo

svelte-notifications's Introduction

Beyonk

Svelte Notifications

js-standard-style Svelte v3

Svelte Notifications component

  • Uses SvelteKit ๐ŸŽ‰
  • v3 compatible
  • Uses stores for completely hassle free operation
  • Can persist across full page reloads!

Demo

A Demo of this component is available.

Alternatively, check the project out from github and npm run dev.

Usage

npm i -D @beyonk/svelte-notifications
<NotificationDisplay />

<button on:click={someFunction}>Show message</button>

<script>
import { NotificationDisplay, notifier } from '@beyonk/svelte-notifications'

function someFunction () {
  notifier.success('Notifications work!')
}
</script>

Notification types

You can call multiple types of notification:

const options = {
  timeout: 3000, // milliseconds
  persist: false, // automatic timeout (ignores above)
  showProgess: true, // Show (or Hide) the progress bar
  icon: null // Add svelte component to render an icon
}

notifier.show('danger', message, options)
notifier.danger(message, options),
notifier.warning(message, options),
notifier.info(message, options),
notifier.success(message, options)

Persisting across apps

Your notifications can persist across multiple apps / page reloads, as long as they use this library. This is useful for a scenario where you show a notification and then redirect the browser to a different application, or trigger a full reload of the page.

This is completely automatic and uses session storage.

To ensure that notifications don't persist across apps where they should not, set the sessionKey attribute to something unique to each app.

<NotificationDisplay sessionKey="foo" />

Notification themes

You can customise the themes:

<NotificationDisplay {themes} />

<button on:click={someFunction}>Show message</button>

<script>
import { NotificationDisplay, notifier } from '@beyonk/svelte-notifications'

let themes = { // These are the defaults
  danger: '#bb2124',
  success: '#22bb33',
  warning: '#f0ad4e',
  info: '#5bc0de',
  default: '#aaaaaa' // relates to simply '.show()'
}

function someFunction () {
  notifier.success('Notifications work!')
}
</script>
Custom types
<NotificationDisplay {themes} />

<button on:click={someFunction}>Show message</button>

<script>
import { NotificationDisplay, notifier } from '@beyonk/svelte-notifications'

let themes = {
  myColour: '#ff00bb'
}

function someFunction () {
  notifier.send('myColour', 'Notifications work!')
}
</script>

Timeouts

You can set a default timeout:

<NotificationDisplay {timeout} />

<button on:click={someFunction}>Show message</button>

<script>
import { NotificationDisplay, notifier } from '@beyonk/svelte-notifications'

let timeout = 3000 // The default

function someFunction () {
  notifier.success('Notifications work!')
}
</script>
Custom timeout:

You can set a timeout per message

<NotificationDisplay />

<button on:click={someFunction}>Show message</button>

<script>
import { NotificationDisplay, notifier } from '@beyonk/svelte-notifications'

function someFunction () {
  notifier.success('Notifications work!', { timeout: 5000 }) // built in theme
  notifier.send('custom-theme', 'Notifications work!', { timeout: 5000 }) // custom theme
}
</script>
Show Progress:

You can show or hide the progress bar per message

<NotificationDisplay />

<button on:click={someFunction}>Show message</button>

<script>
import { NotificationDisplay, notifier } from '@beyonk/svelte-notifications'

function someFunction () {
  notifier.success('Notifications work!', { showProgress: false }) // built in theme
  notifier.send('custom-theme', 'Notifications work!', { showProgress: true }) // custom theme
}
</script>
Persist

You can make a message persist and never timeout, having a close button that the user can click to remove it.

<NotificationDisplay />

<button on:click={someFunction}>Show message</button>

<script>
import { NotificationDisplay, notifier } from '@beyonk/svelte-notifications'

function someFunction () {
  notifier.success('Notifications work!', { persist: true }) // built in theme
  notifier.send('custom-theme', 'Notifications work!', { persist: true }) // custom theme
}
</script>
Icons

You can include custom svelte components to render icons (or anything).

<NotificationDisplay />

<button on:click={someFunction}>Show message</button>

<script>
import { NotificationDisplay, notifier } from '@beyonk/svelte-notifications'
impoer Icon from 'somewhere/Icon.svelte'

function someFunction () {
  notifier.success('Notifications work!', { icon: Icon })
}
</script>

// Icon.svelte

<svg width="1em" height="1em" viewBox="0 0 36 36">
  <path
    fill="currentColor"
    d="M18 34a16 16 0 1 1 16-16a16 16 0 0 1-16 16Zm0-30a14 14 0 1 0 14 14A14 14 0 0 0 18 4Z"
  </path>
</svg>

Credits

svelte-notifications's People

Contributors

adamponddesign avatar antony avatar dependabot[bot] avatar fenilli avatar himujjal avatar mcmxcdev avatar paulmaly avatar th3-s1lenc3 avatar thecashewtrader avatar timsully avatar wolfr 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

svelte-notifications's Issues

Timeout parameter for notifications shouldn't be required

The types for TNotifier are e.g. success(message: string, timeout: number): void, which doesn't make sense since timeout has a defined default and user doesn't change it very often on a per-use basis IMO.

Also, most of the basic examples from the README.md don't even conform to these typings, and wouldn't pass TS compilation.

Not working with Svelte 3

Hi! Thanks for this component.

Can you help me to setup it for Svelte 3? I thought that the problem was in #1 but it's not working too. In Devtools I see many items in toasts array but no one showing.

Any ideas?

Wrong number of arguments (4 for 3) for `rgb'

Traceback:

ERROR in ./node_modules/@beyonk/svelte-notifications/src/Notifications.svelte.css
Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js):
ModuleBuildError: Module build failed (from ./node_modules/sass-loader/lib/loader.js):
Wrong number of arguments (4 for 3) for `rgb'
      in ./node_modules/@beyonk/svelte-notifications/src/Notifications.svelte.css (line 1, column 362)
    at runLoaders (./node_modules/webpack/lib/NormalModule.js:313:20)
    at ./node_modules/loader-runner/lib/LoaderRunner.js:367:11
    at ./node_modules/loader-runner/lib/LoaderRunner.js:233:18
    at context.callback (./node_modules/loader-runner/lib/LoaderRunner.js:111:13)
    at Object.render [as callback] (./node_modules/sass-loader/lib/loader.js:90:7)
    at Object.done [as callback] (./node_modules/neo-async/async.js:8067:18)
    at options.error (./node_modules/node-sass/lib/index.js:294:32)
 @ ./node_modules/@beyonk/svelte-notifications/src/Notifications.svelte 297:0-118
[...]

No errors if I change rgb -> rgba in Notifications.svelte

new version tag

Hello,

Latest changes are not reflected on npm. could you create new release tag and publish it on npm?

Variable width

Nice work on this package. Exactly what I needed.

One thing that would be nice would be the ability to control the width. 40vw can be pretty big in some cases, and in other it would be nice to have a fixed size. Of course it can be done with a wrapper component and overriding the CSS, but it can get messy.

SSR | Unknown file extension ".svelte"

Using svelte-notifications with the sveltekit node adapter results in the following error:

Error when evaluating SSR module /src/routes/test.svelte:
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".svelte" for [...]/node_modules/@beyonk/svelte-notifications/Notifications.svelte

Option to disable persisting on page reload

Most notifications I can think of are ephemeral and relevant only for the currently active javascript state (for example errors executing javascript, problems with submitting forms, etc). As such, I do not want to persist them on page reload, because after the reload they are no longer relevant.

Is there a way to disable persisting notifications on reload. If not, could it be added?

Does it support typescript?

I use typescript with Sveltekit and it gives run time error:

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: .../node_modules/@beyonk/svelte-notifications/index.js
require() of ES modules is not supported.

Notification Positioning

Any plans to add positioning functionality to the component?

I know this involves a bit of work to setup containers for each corner of the window, but it would be nice to be able to use the notify function to add a position property.

Hopefully I can fork this when I wrap up a big project in the Spring, and maybe submit a pull request if "beyonk" hasn't had a chance to work on this.

// possible implementations

notifier({
  type: 'info',
  message: 'A top left positioned toast.',
  position: 'top-left',
})

notifier.success('A bottom left positioned toast.', {
  position: 'bottom-left',
  timeout: 3500,
})

With frameworks like Vue.js, you can put a CSS class directly on the component and it gets passed down to the component's outermost element. Svelte.js does not do this, however, so I cannot simply put the class to override positioning directly on the component, which is a hacky way to quickly add a class to the Toast container.

<!-- not possible with Svelte but works with Vue.js -->
<NotificationDisplay class="toast-top-left"/>โ€จ

vite-plug-in warning: resolve config in packaage json can causa problems

17:53:08 [vite-plugin-svelte] WARNING: The following packages use a svelte resolve configuration in package.json that has conflicting results and is going to cause problems future.

@beyonk/[email protected]

Please see https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/faq.md#conflicts-in-svelte-resolve for details.

{
"name": "fs-...",
"version": "2.20.5",
"author": "voscausa",
"repository": {
"type": "git",
"url": "https://github.com/voscausa/..." // not public
},
"license": "MIT",
"type": "module",
"scripts": {
"dev": "vite",
"emu": "vite --mode emu_dev",
"build": "vite build",
"serve": "vite preview"
},
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "^2.4.6",
"@voscausa/svelte-use-validate": "^1.4.3",
"eslint": "^8.46.0",
"eslint-plugin-svelte": "^2.33.2",
"svelte": "^4.2.1",
"vite": "^4.4.9"
},
"dependencies": {
"@beyonk/svelte-notifications": "^4.2.0",
"firebase": "^10.3.1",
"jszip": "^3.7.1",
"lodash.clonedeep": "^4.5.0",
"lodash.isequal": "^4.5.0",
"rxfire": "^6.0.5",
"rxjs": "^7.8.1"
}
}

Toast displays 2 times | SvelteKit

I'm using SvelteKit and this library to display toast notifications.
Making a project I discovered that calling any notifier function from the onMount of Svelte will duplicate the toast.

unknown

Steps to reproduce bug:

npm create svelte@latest 
my-app
cd my-app
npm install
npm i -D @beyonk/svelte-notifications
npm run dev

Paste the following code in the main +page.svelte:

<script>
    import { NotificationDisplay, notifier } from '@beyonk/svelte-notifications'
    import { onMount } from "svelte"
    let n

    onMount(()=>{
        notifier.success('test1', 7000)
        notifier.success('test2', 7000)
        console.log('test1')
        console.log('test2')
    })
</script>

<NotificationDisplay bind:this={n} />

Failed to build error - directive values should not be wrapped

Hi I am trying to integrate your component into Svelte v2 app, and my client keeps crashing during build time with this message:

$ yarn run dev
yarn run v1.16.0
$ set BASEPATH=&&sapper dev
โœ— client
Failed to build โ€” error in C:\Projects\App\node_modules\@beyonk\svelte-notifications\src\Not
ifications.svelte: directive values should not be wrapped โ€” use '() => removeToast(toast.id) ', not '{(
) => removeToast(toast.id) }'
 8:            class="progress"
 9:            style="animation-duration: {toast.timeout}ms;"
10:            on:animationend={() => removeToast(toast.id) }>
                               ^
11:       </div>
12:     </li>
โœ” server (4.0s)

Here is the code:

<div class='wrapper'>
  <Notifications bind:this=notifications />
  <Nav segment={child.segment} path={child.props.path}></Nav>
  <Header></Header>
  <main>
    <svelte:component this={child.component} {...child.props}></svelte:component>
  </main>
</div>

<script>
  import Notifications from '@beyonk/svelte-notifications';
  let notifications;
  export default {
    components: {
      Nav: '../components/Nav.html',
      Notifications,
      Header: '../components/Header.html'
    },
    oncreate() {
      sendMessage();
    },
    data() {
      return {
        notification: null
      }
    },
    methods: {
      sendMessage() {
        notifications.success('Welcome', 10000);
      }
    }
  };
</script>

Toast does not work

The component does not show toast. Tried in sveltekit app and create-vite svelte app.

Steps to reproduce

  1. Create a blank sveltekit app pnpm init svelte@next my-app
  2. Copy example from readme to routes/index.svelte
  3. Run pnpm dev
  4. See error
500

String.prototype.startsWith called on null or undefined

TypeError: String.prototype.startsWith called on null or undefined
    at startsWith (<anonymous>)
    at node:internal/errors:811:19
    at Array.filter (<anonymous>)
    at node:internal/errors:809:16
    at prepareStackTrace (node:internal/errors:96:12)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1138:38)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:94:18)
  1. Refresh and button appears. Clicking button does not show toast.

Code available in https://github.com/supercoww/svelte-notifications-repro

System info

Windows 10
Node 16.6.0
pnpm 6.14.7

Option to close manually.

I liked this work.
What i suggest is an manual close button for user. so this button when enabled will override the time.
use case

  • This is important in case when we want user to know for sure.
  • sometimes if there is long process then if the user is away from desk . this notification will help.

What do you think ?

we can implement it in below way

notifier.success('Notifications work!',9999,True);

if True it will override the time and will show close icon.

Allow custom component

I wonder if we could try to refactor lines 3-17 to allow providing a custom Notification component, so as to allow for more customisations and extensibility.

I would be willing to work on this.

Tweaked animations?

The incoming and outgoing default animation for https://fkhadra.github.io/react-toastify/ is so awesome. Would you consider tweaking the existing animation to support it? If not, would you accept a PR that swaps the current animation with the default react-toastify one?

Thanks!

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.