gloo_dialogs/lib.rs
1//! This crate provides wrapper for `alert`, `prompt` and `confirm` functions.
2//! `web-sys` provides a raw API which is hard to use. This crate provides an easy-to-use,
3//! idiomatic Rust API for these functions.
4//!
5//! See the documentation for [`alert`], [`prompt`] and [`confirm`] for more information.
6
7use wasm_bindgen::prelude::*;
8
9/// Calls the alert function.
10///
11/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/alert)
12pub fn alert(message: &str) {
13 window().alert_with_message(message).unwrap_throw()
14}
15
16/// Calls the confirm function.
17///
18/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm)
19pub fn confirm(message: &str) -> bool {
20 window().confirm_with_message(message).unwrap_throw()
21}
22
23/// Calls the `prompt` function.
24///
25/// A default value can be supplied which will be returned if the user doesn't input anything.
26/// This function will return `None` if the value of `default` is `None` and the user cancels
27/// the operation.
28///
29/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt)
30pub fn prompt(message: &str, default: Option<&str>) -> Option<String> {
31 match default {
32 Some(default) => window()
33 .prompt_with_message_and_default(message, default)
34 .expect_throw("can't read input"),
35 None => window()
36 .prompt_with_message(message)
37 .expect_throw("can't read input"),
38 }
39}
40
41#[inline]
42fn window() -> web_sys::Window {
43 web_sys::window().expect_throw("can't access window")
44}