|
1 | 1 | //! This module contains the implementation of a service
|
2 | 2 | //! to show alerts and confirm dialogs in a browser.
|
| 3 | +//! |
| 4 | +//! If you call these methods repeatably browsers tend to disable these options to give users |
| 5 | +//! a better experience. |
3 | 6 |
|
4 | 7 | use cfg_if::cfg_if;
|
5 | 8 | use cfg_match::cfg_match;
|
@@ -41,4 +44,57 @@ impl DialogService {
|
41 | 44 | feature = "web_sys" => utils::window().confirm_with_message(message).unwrap(),
|
42 | 45 | }
|
43 | 46 | }
|
| 47 | + |
| 48 | + /// Prompts the user to input a message. In most browsers this will open an alert box with |
| 49 | + /// an input field where the user can input a message. |
| 50 | + #[cfg_attr( |
| 51 | + feature = "web_sys", |
| 52 | + doc = "A default value can be supplied which will be returned if the user doesn't input anything." |
| 53 | + )] |
| 54 | + /// |
| 55 | + /// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt) |
| 56 | + /// |
| 57 | + /// This method will `panic!` if there is an error in the process of trying to carry out this |
| 58 | + /// operation. |
| 59 | + /// |
| 60 | + /// Note that this function is blocking; no other code can be run on the thread while |
| 61 | + /// the user inputs their message which means that the page will appear to have 'frozen' |
| 62 | + /// while the user types in their message. |
| 63 | + /// |
| 64 | + #[cfg_attr( |
| 65 | + feature = "web_sys", |
| 66 | + doc = "This function will return `None` if the value of `default` is `None` and the user \ |
| 67 | + cancels the operation. (normally a 'cancel' button will be displayed to the user, \ |
| 68 | + clicking which cancels the operation)." |
| 69 | + )] |
| 70 | + #[cfg_attr( |
| 71 | + feature = "std_web", |
| 72 | + doc = "This function will return `None` if the user cancels the operation (normally a \ |
| 73 | + 'cancel' button will be displayed to the user, clicking which cancels the operation)." |
| 74 | + )] |
| 75 | + pub fn prompt( |
| 76 | + message: &str, |
| 77 | + #[cfg(feature = "web_sys")] default: Option<&str>, |
| 78 | + ) -> Option<String> { |
| 79 | + cfg_if! { |
| 80 | + if #[cfg(feature="web_sys")] { |
| 81 | + if let Some(default) = default { |
| 82 | + utils::window() |
| 83 | + .prompt_with_message_and_default(message, default) |
| 84 | + .expect("Couldn't read input.") |
| 85 | + } |
| 86 | + else { |
| 87 | + utils::window() |
| 88 | + .prompt_with_message(message) |
| 89 | + .expect("Couldn't read input.") |
| 90 | + } |
| 91 | + } else if #[cfg(feature="std_web")] { |
| 92 | + let value: Value = js! { return prompt(@{message}); }; |
| 93 | + match value { |
| 94 | + Value::String(result) => Some(result), |
| 95 | + _ => None, |
| 96 | + } |
| 97 | + } |
| 98 | + } |
| 99 | + } |
44 | 100 | }
|
0 commit comments