leptos_use/use_web_notification.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
use crate::{use_supported, use_window};
use cfg_if::cfg_if;
use default_struct_builder::DefaultBuilder;
use leptos::*;
use std::rc::Rc;
use wasm_bindgen::JsValue;
/// Reactive [Notification API](https://developer.mozilla.org/en-US/docs/Web/API/Notification).
///
/// The Web Notification interface of the Notifications API is used to configure and display desktop notifications to the user.
///
/// ## Demo
///
/// [Link to Demo](https://github.com/Synphonyte/leptos-use/tree/main/examples/use_web_notification)
///
/// ## Usage
///
/// ```
/// # use leptos::*;
/// # use leptos_use::{use_web_notification_with_options, UseWebNotificationOptions, ShowOptions, UseWebNotificationReturn, NotificationDirection};
/// #
/// # #[component]
/// # fn Demo() -> impl IntoView {
/// let UseWebNotificationReturn {
/// show,
/// close,
/// ..
/// } = use_web_notification_with_options(
/// UseWebNotificationOptions::default()
/// .direction(NotificationDirection::Auto)
/// .language("en")
/// .renotify(true)
/// .tag("test"),
/// );
///
/// show(ShowOptions::default().title("Hello World from leptos-use"));
/// #
/// # view! { }
/// # }
/// ```
///
/// ## Server-Side Rendering
///
/// This function is basically ignored on the server. You can safely call `show` but it will do nothing.
pub fn use_web_notification(
) -> UseWebNotificationReturn<impl Fn(ShowOptions) + Clone, impl Fn() + Clone> {
use_web_notification_with_options(UseWebNotificationOptions::default())
}
/// Version of [`use_web_notification`] which takes an [`UseWebNotificationOptions`].
pub fn use_web_notification_with_options(
options: UseWebNotificationOptions,
) -> UseWebNotificationReturn<impl Fn(ShowOptions) + Clone, impl Fn() + Clone> {
let is_supported = use_supported(browser_supports_notifications);
let (notification, set_notification) = create_signal(None::<web_sys::Notification>);
let (permission, set_permission) = create_signal(NotificationPermission::default());
cfg_if! { if #[cfg(feature = "ssr")] {
let _ = options;
let _ = set_notification;
let _ = set_permission;
let show = move |_: ShowOptions| ();
let close = move || ();
} else {
use crate::use_event_listener;
use leptos::ev::visibilitychange;
use wasm_bindgen::closure::Closure;
use wasm_bindgen::JsCast;
let on_click_closure = Closure::<dyn Fn(web_sys::Event)>::new({
let on_click = Rc::clone(&options.on_click);
move |e: web_sys::Event| {
#[cfg(debug_assertions)]
let prev = SpecialNonReactiveZone::enter();
on_click(e);
#[cfg(debug_assertions)]
SpecialNonReactiveZone::exit(prev);
}
})
.into_js_value();
let on_close_closure = Closure::<dyn Fn(web_sys::Event)>::new({
let on_close = Rc::clone(&options.on_close);
move |e: web_sys::Event| {
#[cfg(debug_assertions)]
let prev = SpecialNonReactiveZone::enter();
on_close(e);
#[cfg(debug_assertions)]
SpecialNonReactiveZone::exit(prev);
}
})
.into_js_value();
let on_error_closure = Closure::<dyn Fn(web_sys::Event)>::new({
let on_error = Rc::clone(&options.on_error);
move |e: web_sys::Event| {
#[cfg(debug_assertions)]
let prev = SpecialNonReactiveZone::enter();
on_error(e);
#[cfg(debug_assertions)]
SpecialNonReactiveZone::exit(prev);
}
})
.into_js_value();
let on_show_closure = Closure::<dyn Fn(web_sys::Event)>::new({
let on_show = Rc::clone(&options.on_show);
move |e: web_sys::Event| {
#[cfg(debug_assertions)]
let prev = SpecialNonReactiveZone::enter();
on_show(e);
#[cfg(debug_assertions)]
SpecialNonReactiveZone::exit(prev);
}
})
.into_js_value();
let show = {
let options = options.clone();
let on_click_closure = on_click_closure.clone();
let on_close_closure = on_close_closure.clone();
let on_error_closure = on_error_closure.clone();
let on_show_closure = on_show_closure.clone();
move |options_override: ShowOptions| {
if !is_supported.get_untracked() {
return;
}
let options = options.clone();
let on_click_closure = on_click_closure.clone();
let on_close_closure = on_close_closure.clone();
let on_error_closure = on_error_closure.clone();
let on_show_closure = on_show_closure.clone();
spawn_local(async move {
set_permission.set(request_web_notification_permission().await);
let mut notification_options = web_sys::NotificationOptions::from(&options);
options_override.override_notification_options(&mut notification_options);
let notification_value = web_sys::Notification::new_with_options(
&options_override.title.unwrap_or(options.title),
¬ification_options,
)
.expect("Notification should be created");
notification_value.set_onclick(Some(on_click_closure.unchecked_ref()));
notification_value.set_onclose(Some(on_close_closure.unchecked_ref()));
notification_value.set_onerror(Some(on_error_closure.unchecked_ref()));
notification_value.set_onshow(Some(on_show_closure.unchecked_ref()));
set_notification.set(Some(notification_value));
});
}
};
let close = {
move || {
notification.with_untracked(|notification| {
if let Some(notification) = notification {
notification.close();
}
});
set_notification.set(None);
}
};
spawn_local(async move {
set_permission.set(request_web_notification_permission().await);
});
on_cleanup(close);
// Use close() to remove a notification that is no longer relevant to to
// the user (e.g.the user already read the notification on the webpage).
// Most modern browsers dismiss notifications automatically after a few
// moments(around four seconds).
if is_supported.get_untracked() {
let _ = use_event_listener(document(), visibilitychange, move |e: web_sys::Event| {
e.prevent_default();
if document().visibility_state() == web_sys::VisibilityState::Visible {
// The tab has become visible so clear the now-stale Notification:
close()
}
});
}
}}
UseWebNotificationReturn {
is_supported,
notification: notification.into(),
show,
close,
permission: permission.into(),
}
}
#[derive(Default, Clone, Copy, Eq, PartialEq, Debug)]
pub enum NotificationDirection {
#[default]
Auto,
LeftToRight,
RightToLeft,
}
impl From<NotificationDirection> for web_sys::NotificationDirection {
fn from(direction: NotificationDirection) -> Self {
match direction {
NotificationDirection::Auto => Self::Auto,
NotificationDirection::LeftToRight => Self::Ltr,
NotificationDirection::RightToLeft => Self::Rtl,
}
}
}
/// Options for [`use_web_notification_with_options`].
/// See [MDN Docs](https://developer.mozilla.org/en-US/docs/Web/API/notification) for more info.
///
/// The following implementations are missing:
#[derive(DefaultBuilder, Clone)]
#[cfg_attr(feature = "ssr", allow(dead_code))]
pub struct UseWebNotificationOptions {
/// The title property of the Notification interface indicates
/// the title of the notification
#[builder(into)]
title: String,
/// The body string of the notification as specified in the constructor's
/// options parameter.
#[builder(into)]
body: Option<String>,
/// The text direction of the notification as specified in the constructor's
/// options parameter. Can be `LeftToRight`, `RightToLeft` or `Auto` (default).
/// See [`web_sys::NotificationDirection`] for more info.
direction: NotificationDirection,
/// The language code of the notification as specified in the constructor's
/// options parameter.
#[builder(into)]
language: Option<String>,
/// The ID of the notification(if any) as specified in the constructor's options
/// parameter.
#[builder(into)]
tag: Option<String>,
/// The URL of the image used as an icon of the notification as specified
/// in the constructor's options parameter.
#[builder(into)]
icon: Option<String>,
/// The URL of the image to be displayed as part of the notification as specified
/// in the constructor's options parameter.
#[builder(into)]
image: Option<String>,
/// A boolean value indicating that a notification should remain active until the
/// user clicks or dismisses it, rather than closing automatically.
require_interaction: bool,
/// A boolean value specifying whether the user should be notified after a new notification replaces an old one.
/// The default is `false`, which means they won't be notified. If `true`, then `tag` also must be set.
#[builder(into)]
renotify: bool,
/// A boolean value specifying whether the notification should be silent, regardless of the device settings.
/// The default is `null`, which means the notification is not silent. If `true`, then the notification will be silent.
#[builder(into)]
silent: Option<bool>,
/// A `Vec<u16>` specifying the vibration pattern in milliseconds for vibrating and not vibrating.
/// The last entry can be a vibration since it stops automatically after each period.
#[builder(into)]
vibrate: Option<Vec<u16>>,
/// Called when the user clicks on displayed `Notification`.
on_click: Rc<dyn Fn(web_sys::Event)>,
/// Called when the user closes a `Notification`.
on_close: Rc<dyn Fn(web_sys::Event)>,
/// Called when something goes wrong with a `Notification`
/// (in many cases an error preventing the notification from being displayed.)
on_error: Rc<dyn Fn(web_sys::Event)>,
/// Called when a `Notification` is displayed
on_show: Rc<dyn Fn(web_sys::Event)>,
}
impl Default for UseWebNotificationOptions {
fn default() -> Self {
Self {
title: "".to_string(),
body: None,
direction: NotificationDirection::default(),
language: None,
tag: None,
icon: None,
image: None,
require_interaction: false,
renotify: false,
silent: None,
vibrate: None,
on_click: Rc::new(|_| {}),
on_close: Rc::new(|_| {}),
on_error: Rc::new(|_| {}),
on_show: Rc::new(|_| {}),
}
}
}
impl From<&UseWebNotificationOptions> for web_sys::NotificationOptions {
fn from(options: &UseWebNotificationOptions) -> Self {
let web_sys_options = Self::new();
web_sys_options.set_dir(options.direction.into());
web_sys_options.set_require_interaction(options.require_interaction);
web_sys_options.set_renotify(options.renotify);
web_sys_options.set_silent(options.silent);
if let Some(body) = &options.body {
web_sys_options.set_body(body);
}
if let Some(icon) = &options.icon {
web_sys_options.set_icon(icon);
}
if let Some(image) = &options.image {
web_sys_options.set_image(image);
}
if let Some(language) = &options.language {
web_sys_options.set_lang(language);
}
if let Some(tag) = &options.tag {
web_sys_options.set_tag(tag);
}
if let Some(vibrate) = &options.vibrate {
web_sys_options.set_vibrate(&vibration_pattern_to_jsvalue(vibrate));
}
web_sys_options
}
}
/// Options for [`UseWebNotificationReturn::show`].
///
/// This can be used to override options passed to [`use_web_notification`].
/// See [MDN Docs](https://developer.mozilla.org/en-US/docs/Web/API/notification) for more info.
///
/// The following implementations are missing:
#[derive(DefaultBuilder, Default)]
#[cfg_attr(feature = "ssr", allow(dead_code))]
pub struct ShowOptions {
/// The title property of the Notification interface indicates
/// the title of the notification
#[builder(into)]
title: Option<String>,
/// The body string of the notification as specified in the constructor's
/// options parameter.
#[builder(into)]
body: Option<String>,
/// The text direction of the notification as specified in the constructor's
/// options parameter. Can be `LeftToRight`, `RightToLeft` or `Auto` (default).
/// See [`web_sys::NotificationDirection`] for more info.
#[builder(into)]
direction: Option<NotificationDirection>,
/// The language code of the notification as specified in the constructor's
/// options parameter.
#[builder(into)]
language: Option<String>,
/// The ID of the notification(if any) as specified in the constructor's options
/// parameter.
#[builder(into)]
tag: Option<String>,
/// The URL of the image used as an icon of the notification as specified
/// in the constructor's options parameter.
#[builder(into)]
icon: Option<String>,
/// The URL of the image to be displayed as part of the notification as specified
/// in the constructor's options parameter.
#[builder(into)]
image: Option<String>,
/// A boolean value indicating that a notification should remain active until the
/// user clicks or dismisses it, rather than closing automatically.
#[builder(into)]
require_interaction: Option<bool>,
/// A boolean value specifying whether the user should be notified after a new notification replaces an old one.
/// The default is `false`, which means they won't be notified. If `true`, then `tag` also must be set.
#[builder(into)]
renotify: Option<bool>,
/// A boolean value specifying whether the notification should be silent, regardless of the device settings.
/// The default is `null`, which means the notification is not silent. If `true`, then the notification will be silent.
#[builder(into)]
silent: Option<bool>,
/// A `Vec<u16>` specifying the vibration pattern in milliseconds for vibrating and not vibrating.
/// The last entry can be a vibration since it stops automatically after each period.
#[builder(into)]
vibrate: Option<Vec<u16>>,
}
#[cfg(not(feature = "ssr"))]
impl ShowOptions {
fn override_notification_options(&self, options: &mut web_sys::NotificationOptions) {
if let Some(direction) = self.direction {
options.set_dir(direction.into());
}
if let Some(require_interaction) = self.require_interaction {
options.set_require_interaction(require_interaction);
}
if let Some(body) = &self.body {
options.set_body(body);
}
if let Some(icon) = &self.icon {
options.set_icon(icon);
}
if let Some(image) = &self.image {
options.set_image(image);
}
if let Some(language) = &self.language {
options.set_lang(language);
}
if let Some(tag) = &self.tag {
options.set_tag(tag);
}
if let Some(renotify) = self.renotify {
options.set_renotify(renotify);
}
if let Some(silent) = self.silent {
options.set_silent(Some(silent));
}
if let Some(vibrate) = &self.vibrate {
options.set_vibrate(&vibration_pattern_to_jsvalue(vibrate));
}
}
}
/// Helper function to determine if browser supports notifications
fn browser_supports_notifications() -> bool {
if let Some(window) = use_window().as_ref() {
if window.has_own_property(&wasm_bindgen::JsValue::from_str("Notification")) {
return true;
}
}
false
}
/// Helper function to convert a slice of `u16` into a `JsValue` array that represents a vibration pattern
fn vibration_pattern_to_jsvalue(pattern: &[u16]) -> JsValue {
let array = js_sys::Array::new();
for &value in pattern.iter() {
array.push(&JsValue::from(value));
}
array.into()
}
#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
/// The permission to send notifications
pub enum NotificationPermission {
/// Notification has not been requested. In effect this is the same as `Denied`.
#[default]
Default,
/// You are allowed to send notifications
Granted,
/// You are *not* allowed to send notifications
Denied,
}
impl From<web_sys::NotificationPermission> for NotificationPermission {
fn from(permission: web_sys::NotificationPermission) -> Self {
match permission {
web_sys::NotificationPermission::Default => Self::Default,
web_sys::NotificationPermission::Granted => Self::Granted,
web_sys::NotificationPermission::Denied => Self::Denied,
_ => Self::Default,
}
}
}
/// Use `window.Notification.requestPosition()`. Returns a future that should be awaited
/// at least once before using [`use_web_notification`] to make sure
/// you have the permission to send notifications.
#[cfg(not(feature = "ssr"))]
async fn request_web_notification_permission() -> NotificationPermission {
if let Ok(notification_permission) = web_sys::Notification::request_permission() {
let _ = crate::js_fut!(notification_permission).await;
}
web_sys::Notification::permission().into()
}
/// Return type for [`use_web_notification`].
pub struct UseWebNotificationReturn<ShowFn, CloseFn>
where
ShowFn: Fn(ShowOptions) + Clone,
CloseFn: Fn() + Clone,
{
pub is_supported: Signal<bool>,
pub notification: Signal<Option<web_sys::Notification>>,
pub show: ShowFn,
pub close: CloseFn,
pub permission: Signal<NotificationPermission>,
}