diff --git a/CHANGELOG.md b/CHANGELOG.md index 23dd824..e7a84dd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 🛠 diff --git a/Cargo.toml b/Cargo.toml index 582fa0a..9545c23 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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", diff --git a/docs/book/src/SUMMARY.md b/docs/book/src/SUMMARY.md index ea74e15..d33f60d 100644 --- a/docs/book/src/SUMMARY.md +++ b/docs/book/src/SUMMARY.md @@ -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 diff --git a/docs/book/src/browser/use_web_notification.md b/docs/book/src/browser/use_web_notification.md new file mode 100644 index 0000000..ceef60c --- /dev/null +++ b/docs/book/src/browser/use_web_notification.md @@ -0,0 +1,3 @@ +# use_web_notification + + diff --git a/examples/Cargo.toml b/examples/Cargo.toml index d367ba8..c5dbe1a 100644 --- a/examples/Cargo.toml +++ b/examples/Cargo.toml @@ -40,6 +40,7 @@ members = [ "use_storage", "use_throttle_fn", "use_timestamp", + "use_web_notification", "use_websocket", "use_window_focus", "use_window_scroll", diff --git a/examples/use_web_notification/Cargo.toml b/examples/use_web_notification/Cargo.toml new file mode 100644 index 0000000..26ee6c9 --- /dev/null +++ b/examples/use_web_notification/Cargo.toml @@ -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" diff --git a/examples/use_web_notification/README.md b/examples/use_web_notification/README.md new file mode 100644 index 0000000..aa9d332 --- /dev/null +++ b/examples/use_web_notification/README.md @@ -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 +``` \ No newline at end of file diff --git a/examples/use_web_notification/Trunk.toml b/examples/use_web_notification/Trunk.toml new file mode 100644 index 0000000..3e4be08 --- /dev/null +++ b/examples/use_web_notification/Trunk.toml @@ -0,0 +1,2 @@ +[build] +public_url = "/demo/" \ No newline at end of file diff --git a/examples/use_web_notification/index.html b/examples/use_web_notification/index.html new file mode 100644 index 0000000..ae249a6 --- /dev/null +++ b/examples/use_web_notification/index.html @@ -0,0 +1,7 @@ + + + + + + + diff --git a/examples/use_web_notification/input.css b/examples/use_web_notification/input.css new file mode 100644 index 0000000..bd6213e --- /dev/null +++ b/examples/use_web_notification/input.css @@ -0,0 +1,3 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; \ No newline at end of file diff --git a/examples/use_web_notification/rust-toolchain.toml b/examples/use_web_notification/rust-toolchain.toml new file mode 100644 index 0000000..271800c --- /dev/null +++ b/examples/use_web_notification/rust-toolchain.toml @@ -0,0 +1,2 @@ +[toolchain] +channel = "nightly" \ No newline at end of file diff --git a/examples/use_web_notification/src/main.rs b/examples/use_web_notification/src/main.rs new file mode 100644 index 0000000..b9045bc --- /dev/null +++ b/examples/use_web_notification/src/main.rs @@ -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! { +
+

+ Supported: +

+
+ + The Notification Web API is not supported in your browser. + } + > + + + } +} + +fn main() { + _ = console_log::init_with_level(log::Level::Debug); + console_error_panic_hook::set_once(); + + mount_to(demo_or_body(), || { + view! { } + }) +} diff --git a/examples/use_web_notification/style/output.css b/examples/use_web_notification/style/output.css new file mode 100644 index 0000000..ab5191f --- /dev/null +++ b/examples/use_web_notification/style/output.css @@ -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)); + } +} \ No newline at end of file diff --git a/examples/use_web_notification/tailwind.config.js b/examples/use_web_notification/tailwind.config.js new file mode 100644 index 0000000..bc09f5e --- /dev/null +++ b/examples/use_web_notification/tailwind.config.js @@ -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'), + ], +} \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs index aaea588..8530bca 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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::*; diff --git a/src/use_web_notification.rs b/src/use_web_notification.rs new file mode 100644 index 0000000..92a7024 --- /dev/null +++ b/src/use_web_notification.rs @@ -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 { + 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 { + let is_supported = use_supported(browser_supports_notifications); + + let (notification, set_notification) = create_signal(None::); + + let (permission, set_permission) = create_signal(NotificationPermission::default()); + + let on_click_closure = Closure::::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::::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::::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::::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), + ¬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.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 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, + + /// 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, + + /// The ID of the notification(if any) as specified in the constructor's options + /// parameter. + #[builder(into)] + tag: Option, + + /// The URL of the image used as an icon of the notification as specified + /// in the constructor's options parameter. + #[builder(into)] + icon: Option, + + /// 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, + + /// Called when the user closes a `Notification`. + on_close: Rc, + + /// Called when something goes wrong with a `Notification` + /// (in many cases an error preventing the notification from being displayed.) + on_error: Rc, + + /// Called when a `Notification` is displayed + on_show: Rc, +} + +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, + + /// The body string of the notification as specified in the constructor's + /// options parameter. + #[builder(into)] + body: Option, + + /// 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, + + /// The language code of the notification as specified in the constructor's + /// options parameter. + #[builder(into)] + language: Option, + + /// The ID of the notification(if any) as specified in the constructor's options + /// parameter. + #[builder(into)] + tag: Option, + + /// The URL of the image used as an icon of the notification as specified + /// in the constructor's options parameter. + #[builder(into)] + icon: Option, + + /// 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, + // /// 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, +} + +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 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 +where + ShowFn: Fn(ShowOptions) + Clone, + CloseFn: Fn() + Clone, +{ + pub is_supported: Signal, + pub notification: Signal>, + pub show: ShowFn, + pub close: CloseFn, + pub permission: Signal, +}