added use_web_notification

This commit is contained in:
Maccesch 2023-10-23 23:49:11 -05:00
parent b8421f2186
commit cd67ca5542
16 changed files with 860 additions and 0 deletions

View file

@ -7,6 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### New Functions 🚀
- `use_web_notification` - thanks for the help @centershocks44
- `use_infinite_scroll`
### Breaking Changes 🛠

View file

@ -25,6 +25,7 @@ paste = "1"
serde = { version = "1", optional = true }
serde_json = { version = "1", optional = true }
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
[dependencies.web-sys]
version = "0.3"
@ -60,6 +61,10 @@ features = [
"MutationRecord",
"Navigator",
"NodeList",
"Notification",
"NotificationDirection",
"NotificationOptions",
"NotificationPermission",
"PointerEvent",
"Position",
"PositionError",

View file

@ -38,6 +38,7 @@
- [use_media_query](browser/use_media_query.md)
- [use_preferred_contrast](browser/use_preferred_contrast.md)
- [use_preferred_dark](browser/use_preferred_dark.md)
- [use_web_notification](browser/use_web_notification.md)
# Sensors

View file

@ -0,0 +1,3 @@
# use_web_notification
<!-- cmdrun python3 ../extract_doc_comment.py use_web_notification -->

View file

@ -40,6 +40,7 @@ members = [
"use_storage",
"use_throttle_fn",
"use_timestamp",
"use_web_notification",
"use_websocket",
"use_window_focus",
"use_window_scroll",

View file

@ -0,0 +1,16 @@
[package]
name = "use_web_notification"
version = "0.1.0"
edition = "2021"
[dependencies]
leptos = { version = "0.5", features = ["nightly", "csr"] }
console_error_panic_hook = "0.1"
console_log = "1"
log = "0.4"
leptos-use = { path = "../..", features = ["docs"] }
web-sys = "0.3"
[dev-dependencies]
wasm-bindgen = "0.2"
wasm-bindgen-test = "0.3.0"

View file

@ -0,0 +1,23 @@
A simple example for `use_web_notification`.
If you don't have it installed already, install [Trunk](https://trunkrs.dev/) and [Tailwind](https://tailwindcss.com/docs/installation)
as well as the nightly toolchain for Rust and the wasm32-unknown-unknown target:
```bash
cargo install trunk
npm install -D tailwindcss @tailwindcss/forms
rustup toolchain install nightly
rustup target add wasm32-unknown-unknown
```
Then, open two terminals. In the first one, run:
```
npx tailwindcss -i ./input.css -o ./style/output.css --watch
```
In the second one, run:
```bash
trunk serve --open
```

View file

@ -0,0 +1,2 @@
[build]
public_url = "/demo/"

View file

@ -0,0 +1,7 @@
<!DOCTYPE html>
<html>
<head>
<link data-trunk rel="css" href="style/output.css">
</head>
<body></body>
</html>

View file

@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;

View file

@ -0,0 +1,2 @@
[toolchain]
channel = "nightly"

View file

@ -0,0 +1,55 @@
use leptos::*;
use leptos_use::docs::{demo_or_body, BooleanDisplay};
use leptos_use::{
use_web_notification_with_options, NotificationDirection, ShowOptions,
UseWebNotificationOptions, UseWebNotificationReturn,
};
#[component]
fn Demo() -> impl IntoView {
let UseWebNotificationReturn {
is_supported, show, ..
} = use_web_notification_with_options(
UseWebNotificationOptions::default()
.title("Hello World from leptos-use")
.direction(NotificationDirection::Auto)
.language("en")
// .renotify(true)
.tag("test"),
);
let show = move || {
show(ShowOptions::default());
};
view! {
<div>
<p>
Supported: <BooleanDisplay value=is_supported />
</p>
</div>
<Show
when=is_supported
fallback=|| view! {
<div>The Notification Web API is not supported in your browser.</div>
}
>
<button on:click={
let show = show.clone();
move |_| show()
}>
Show Notification
</button>
</Show>
}
}
fn main() {
_ = console_log::init_with_level(log::Level::Debug);
console_error_panic_hook::set_once();
mount_to(demo_or_body(), || {
view! { <Demo/> }
})
}

View file

@ -0,0 +1,289 @@
[type='text'],[type='email'],[type='url'],[type='password'],[type='number'],[type='date'],[type='datetime-local'],[type='month'],[type='search'],[type='tel'],[type='time'],[type='week'],[multiple],textarea,select {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background-color: #fff;
border-color: #6b7280;
border-width: 1px;
border-radius: 0px;
padding-top: 0.5rem;
padding-right: 0.75rem;
padding-bottom: 0.5rem;
padding-left: 0.75rem;
font-size: 1rem;
line-height: 1.5rem;
--tw-shadow: 0 0 #0000;
}
[type='text']:focus, [type='email']:focus, [type='url']:focus, [type='password']:focus, [type='number']:focus, [type='date']:focus, [type='datetime-local']:focus, [type='month']:focus, [type='search']:focus, [type='tel']:focus, [type='time']:focus, [type='week']:focus, [multiple]:focus, textarea:focus, select:focus {
outline: 2px solid transparent;
outline-offset: 2px;
--tw-ring-inset: var(--tw-empty,/*!*/ /*!*/);
--tw-ring-offset-width: 0px;
--tw-ring-offset-color: #fff;
--tw-ring-color: #2563eb;
--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);
--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);
box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);
border-color: #2563eb;
}
input::-moz-placeholder, textarea::-moz-placeholder {
color: #6b7280;
opacity: 1;
}
input::placeholder,textarea::placeholder {
color: #6b7280;
opacity: 1;
}
::-webkit-datetime-edit-fields-wrapper {
padding: 0;
}
::-webkit-date-and-time-value {
min-height: 1.5em;
}
::-webkit-datetime-edit,::-webkit-datetime-edit-year-field,::-webkit-datetime-edit-month-field,::-webkit-datetime-edit-day-field,::-webkit-datetime-edit-hour-field,::-webkit-datetime-edit-minute-field,::-webkit-datetime-edit-second-field,::-webkit-datetime-edit-millisecond-field,::-webkit-datetime-edit-meridiem-field {
padding-top: 0;
padding-bottom: 0;
}
select {
background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e");
background-position: right 0.5rem center;
background-repeat: no-repeat;
background-size: 1.5em 1.5em;
padding-right: 2.5rem;
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
[multiple] {
background-image: initial;
background-position: initial;
background-repeat: unset;
background-size: initial;
padding-right: 0.75rem;
-webkit-print-color-adjust: unset;
print-color-adjust: unset;
}
[type='checkbox'],[type='radio'] {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
padding: 0;
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
display: inline-block;
vertical-align: middle;
background-origin: border-box;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
flex-shrink: 0;
height: 1rem;
width: 1rem;
color: #2563eb;
background-color: #fff;
border-color: #6b7280;
border-width: 1px;
--tw-shadow: 0 0 #0000;
}
[type='checkbox'] {
border-radius: 0px;
}
[type='radio'] {
border-radius: 100%;
}
[type='checkbox']:focus,[type='radio']:focus {
outline: 2px solid transparent;
outline-offset: 2px;
--tw-ring-inset: var(--tw-empty,/*!*/ /*!*/);
--tw-ring-offset-width: 2px;
--tw-ring-offset-color: #fff;
--tw-ring-color: #2563eb;
--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);
--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);
box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);
}
[type='checkbox']:checked,[type='radio']:checked {
border-color: transparent;
background-color: currentColor;
background-size: 100% 100%;
background-position: center;
background-repeat: no-repeat;
}
[type='checkbox']:checked {
background-image: url("data:image/svg+xml,%3csvg viewBox='0 0 16 16' fill='white' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='M12.207 4.793a1 1 0 010 1.414l-5 5a1 1 0 01-1.414 0l-2-2a1 1 0 011.414-1.414L6.5 9.086l4.293-4.293a1 1 0 011.414 0z'/%3e%3c/svg%3e");
}
[type='radio']:checked {
background-image: url("data:image/svg+xml,%3csvg viewBox='0 0 16 16' fill='white' xmlns='http://www.w3.org/2000/svg'%3e%3ccircle cx='8' cy='8' r='3'/%3e%3c/svg%3e");
}
[type='checkbox']:checked:hover,[type='checkbox']:checked:focus,[type='radio']:checked:hover,[type='radio']:checked:focus {
border-color: transparent;
background-color: currentColor;
}
[type='checkbox']:indeterminate {
background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 16 16'%3e%3cpath stroke='white' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M4 8h8'/%3e%3c/svg%3e");
border-color: transparent;
background-color: currentColor;
background-size: 100% 100%;
background-position: center;
background-repeat: no-repeat;
}
[type='checkbox']:indeterminate:hover,[type='checkbox']:indeterminate:focus {
border-color: transparent;
background-color: currentColor;
}
[type='file'] {
background: unset;
border-color: inherit;
border-width: 0;
border-radius: 0;
padding: 0;
font-size: unset;
line-height: inherit;
}
[type='file']:focus {
outline: 1px solid ButtonText;
outline: 1px auto -webkit-focus-ring-color;
}
*, ::before, ::after {
--tw-border-spacing-x: 0;
--tw-border-spacing-y: 0;
--tw-translate-x: 0;
--tw-translate-y: 0;
--tw-rotate: 0;
--tw-skew-x: 0;
--tw-skew-y: 0;
--tw-scale-x: 1;
--tw-scale-y: 1;
--tw-pan-x: ;
--tw-pan-y: ;
--tw-pinch-zoom: ;
--tw-scroll-snap-strictness: proximity;
--tw-gradient-from-position: ;
--tw-gradient-via-position: ;
--tw-gradient-to-position: ;
--tw-ordinal: ;
--tw-slashed-zero: ;
--tw-numeric-figure: ;
--tw-numeric-spacing: ;
--tw-numeric-fraction: ;
--tw-ring-inset: ;
--tw-ring-offset-width: 0px;
--tw-ring-offset-color: #fff;
--tw-ring-color: rgb(59 130 246 / 0.5);
--tw-ring-offset-shadow: 0 0 #0000;
--tw-ring-shadow: 0 0 #0000;
--tw-shadow: 0 0 #0000;
--tw-shadow-colored: 0 0 #0000;
--tw-blur: ;
--tw-brightness: ;
--tw-contrast: ;
--tw-grayscale: ;
--tw-hue-rotate: ;
--tw-invert: ;
--tw-saturate: ;
--tw-sepia: ;
--tw-drop-shadow: ;
--tw-backdrop-blur: ;
--tw-backdrop-brightness: ;
--tw-backdrop-contrast: ;
--tw-backdrop-grayscale: ;
--tw-backdrop-hue-rotate: ;
--tw-backdrop-invert: ;
--tw-backdrop-opacity: ;
--tw-backdrop-saturate: ;
--tw-backdrop-sepia: ;
}
::backdrop {
--tw-border-spacing-x: 0;
--tw-border-spacing-y: 0;
--tw-translate-x: 0;
--tw-translate-y: 0;
--tw-rotate: 0;
--tw-skew-x: 0;
--tw-skew-y: 0;
--tw-scale-x: 1;
--tw-scale-y: 1;
--tw-pan-x: ;
--tw-pan-y: ;
--tw-pinch-zoom: ;
--tw-scroll-snap-strictness: proximity;
--tw-gradient-from-position: ;
--tw-gradient-via-position: ;
--tw-gradient-to-position: ;
--tw-ordinal: ;
--tw-slashed-zero: ;
--tw-numeric-figure: ;
--tw-numeric-spacing: ;
--tw-numeric-fraction: ;
--tw-ring-inset: ;
--tw-ring-offset-width: 0px;
--tw-ring-offset-color: #fff;
--tw-ring-color: rgb(59 130 246 / 0.5);
--tw-ring-offset-shadow: 0 0 #0000;
--tw-ring-shadow: 0 0 #0000;
--tw-shadow: 0 0 #0000;
--tw-shadow-colored: 0 0 #0000;
--tw-blur: ;
--tw-brightness: ;
--tw-contrast: ;
--tw-grayscale: ;
--tw-hue-rotate: ;
--tw-invert: ;
--tw-saturate: ;
--tw-sepia: ;
--tw-drop-shadow: ;
--tw-backdrop-blur: ;
--tw-backdrop-brightness: ;
--tw-backdrop-contrast: ;
--tw-backdrop-grayscale: ;
--tw-backdrop-hue-rotate: ;
--tw-backdrop-invert: ;
--tw-backdrop-opacity: ;
--tw-backdrop-saturate: ;
--tw-backdrop-sepia: ;
}
.block {
display: block;
}
.text-\[--brand-color\] {
color: var(--brand-color);
}
.text-green-600 {
--tw-text-opacity: 1;
color: rgb(22 163 74 / var(--tw-text-opacity));
}
.opacity-75 {
opacity: 0.75;
}
@media (prefers-color-scheme: dark) {
.dark\:text-green-500 {
--tw-text-opacity: 1;
color: rgb(34 197 94 / var(--tw-text-opacity));
}
}

View file

@ -0,0 +1,15 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
content: {
files: ["*.html", "./src/**/*.rs", "../../src/docs/**/*.rs"],
},
theme: {
extend: {},
},
corePlugins: {
preflight: false,
},
plugins: [
require('@tailwindcss/forms'),
],
}

View file

@ -25,6 +25,7 @@ mod is_none;
mod is_ok;
mod is_some;
mod on_click_outside;
mod use_web_notification;
mod signal_debounced;
mod signal_throttled;
mod use_active_element;
@ -75,6 +76,7 @@ pub use is_none::*;
pub use is_ok::*;
pub use is_some::*;
pub use on_click_outside::*;
pub use use_web_notification::*;
pub use signal_debounced::*;
pub use signal_throttled::*;
pub use use_active_element::*;

435
src/use_web_notification.rs Normal file
View file

@ -0,0 +1,435 @@
use crate::{use_event_listener, use_supported, use_window};
use default_struct_builder::DefaultBuilder;
use leptos::ev::visibilitychange;
use leptos::*;
use std::rc::Rc;
use wasm_bindgen::closure::Closure;
use wasm_bindgen::JsCast;
/// 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")
/// .tag("test"),
/// );
///
/// show(ShowOptions::default().title("Hello World from leptos-use"));
/// #
/// # view! { }
/// # }
/// ```
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());
let on_click_closure = Closure::<dyn Fn(web_sys::Event)>::new({
let on_click = Rc::clone(&options.on_click);
move |e: web_sys::Event| {
on_click(e);
}
})
.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| {
on_close(e);
}
})
.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| {
on_error(e);
}
})
.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| {
on_show(e);
}
})
.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),
&notification_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.clone());
// 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: is_supported.into(),
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:
/// - `renotify`
/// - `vibrate`
/// - `silent`
/// - `image`
#[derive(DefaultBuilder, Clone)]
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>,
/// 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,
/// 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,
require_interaction: false,
// renotify: false,
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 mut web_sys_options = Self::new();
web_sys_options
.dir(options.direction.into())
.require_interaction(options.require_interaction);
// .renotify(options.renotify);
if let Some(body) = &options.body {
web_sys_options.body(&body);
}
if let Some(icon) = &options.icon {
web_sys_options.icon(&icon);
}
if let Some(language) = &options.language {
web_sys_options.lang(&language);
}
if let Some(tag) = &options.tag {
web_sys_options.tag(&tag);
}
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:
/// - `vibrate`
/// - `silent`
/// - `image`
#[derive(DefaultBuilder, Default)]
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>,
/// 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>,
}
impl ShowOptions {
fn override_notification_options(&self, options: &mut web_sys::NotificationOptions) {
if let Some(direction) = self.direction {
options.dir(direction.into());
}
if let Some(require_interaction) = self.require_interaction {
options.require_interaction(require_interaction);
}
if let Some(body) = &self.body {
options.body(body);
}
if let Some(icon) = &self.icon {
options.icon(icon);
}
if let Some(language) = &self.language {
options.lang(language);
}
if let Some(tag) = &self.tag {
options.tag(tag);
}
// if let Some(renotify) = &self.renotify {
// options.renotify(renotify);
// }
}
}
/// 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
}
#[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,
web_sys::NotificationPermission::__Nonexhaustive => 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.
async fn request_web_notification_permission() -> NotificationPermission {
if let Ok(notification_permission) = web_sys::Notification::request_permission() {
let _ = wasm_bindgen_futures::JsFuture::from(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>,
}