Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

webbureaucrat
webbureaucrat

Posted on • Originally published atwebbureaucrat.gitlab.io on

     

Displaying Notifications in ReScript

This article will serve to document and demonstrate therescript-notifications npm package, a complete set of bindings for the JavaScript-compiling ReScript language (formerly BuckleScript/ReasonML). At the close of this article, the reader should be able to enable and display notifications in an entirely type safe and functional way.

Be advised that there are some limitations to web notifications, and I encourage the reader to review theJavaScript Notifications API documentation. TL;DR: Notifications require an HTTPS connection, and they are widely butnot universally supported.

How to use this article

This article is meant to beboth a tutorialand a demo. While I've included the code snippets I think are important, I also want to give a tour of the source so that the reader can browse it in context.

  • NotificationsDemo.res is the ReScript source for the scripts on this page. You can read the whole thing in context by reading thesource on GitLab
  • It compiles toNotificationsDemo.bs.js, which is referenced in a script tag at the bottom of this article.
  • For completeness, thesource of this article is also available on GitLab, although there's no magic here and you may not need it.

A word from across the web

I am adapting this article for cross-posting on sites likeDev.to andFunctional Works by stripping out thedemo-ness of it all.

So feel free to read how you want! But if you'd like to see the notifications, visitthe live demo site on my blog.

Setting up the project

You'll need to install therescript-notifications npm package and add it to yourbsconfig.json in the usual way.

I'm also using a local clone ofbs-webapi, although of course you can always just write your own bindings for DOM manipulation.

Lastly, I just want to flag that I'm using twoopen statements like so:

openNotifications;openWebapi.Dom;
Enter fullscreen modeExit fullscreen mode

(I usually try to limit myself to two or three open statements per file.)

Reading and requesting Notifications permissions

The first thing to establish is notification permissions. We do this through theNotification.permission static property and theNotification.requestPermission() static method.

For example:

NotificationsDemo.res

openNotifications;openWebapi.Dom;window|>Window.addEventListener("load",_=>{letspanPermissions:option<Dom.element>=Document.querySelector("#span-permission",document);letsetSpanText=(span:option<Dom.element>,text:string):unit=>{let_=span->Belt.Option.map(span=>Element.setInnerText(span,text));Js.log("Permission text: "|>Js.String.concat(text));};let_=spanPermissions->setSpanText(Notification.permission);letonBtnRequestClick=(event:Dom.event):unit=>{Js.log("button-request clicked.");let_=Notification.requestPermission()|>Js.Promise.then_(str=>{spanPermissions->setSpanText(str)|>Js.Promise.resolve});};let_=Document.querySelector("#button-request",document)->Belt.Option.map(btn=>{btn|>Element.addEventListener("click",onBtnRequestClick);Js.log("button-request event added.");});});
Enter fullscreen modeExit fullscreen mode

As you can see, this demo sets thespan text to the current notification permission state and then wires up an even to the button to ask for permission and update thespan accordingly. You can see the result below:

Demo omitted in cross-post

Go ahead and grant permission if you'd like--I am only using notifications for the purposes of this demo. Ordinarily, I would hide the button after permission has been granted because it only works once, but as a demo this is fine.

Constructing notifications to display them

As long as permissions are granted, notifications are displayed as soon as they're constructed.

Therescript-notifications binding includestwo Notification constructors,makeWithoutOptions andmakeWithOptions.

Notifications are typed with a type parameter because they can include a data object of any datatype. If you don't need it, you can always just use a throwaway object of some sort.

The options object includes a lot of properties that the calling code won't necessarily need (and isn't necessarily widely supported), so the library includes aninit function for convenience.

NotificationsDemo.res continues:

letonBtnNotifyClick=(_:Dom.event):unit=>{Js.log("button-notify clicked.");let_=Notification.makeWithoutOptions("You have been notified.");};letonBtnWithOptionsClick=(_:Dom.event):unit=>{Js.log("button-with-options clicked.");letoptions:NotificationOptions.t<string>={...NotificationOptions.init(Js.Nullable.return("unused data.")),icon:"https://webbureaucrat.gitlab.io/img/icons/192.png",body:"with an icon and additional text."};let_=Notification.makeWithOptions("You have been thoroughly notified",options);};let_=Document.querySelector("#button-notify",document)->Belt.Option.map(btn=>{btn|>Element.addEventListener("click",onBtnNotifyClick);});let_=Document.querySelector("#button-with-options",document)->Belt.Option.map(btn=>{btn|>Element.addEventListener("click",onBtnWithOptionsClick);});
Enter fullscreen modeExit fullscreen mode

As you can see, the click events call themake methods, which, by ReScript convention, bind to the Notification object constructor. The notifications will appear as soon as they are constructed.

The feel free to play with the live demo below:

Demo omitted in cross-post

Happy notifying!

This has been a quick demonstration of using JavaScript notifications in a type-safe way using ReScript. I hope you have found this helpful and informative, and, as always, feel free toreach out with questions or comments.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

functional programming enthusiast and civic tech nerd.
  • Location
    Chicago, IL
  • Education
    Bachelor of Science, Computer Science, DePaul University
  • Work
    Software Developer
  • Joined

More fromwebbureaucrat

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp