Skip to content

Commit 151b5b7

Browse files
Add prompt function to the dialogue service. (#1350)
* Add `prompt` function to the dialogue service. * Improve the clarity of some doc comments * Fix a typo in a `map_err` * Fix `cfg_match!` usage. * Add `stdweb` support. * Fix the `prompt` method. * Add different docs for `stdweb` and `web_sys`.
1 parent 142c6b5 commit 151b5b7

File tree

4 files changed

+68
-8
lines changed

4 files changed

+68
-8
lines changed

yew/src/services/dialog.rs

+56
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
//! This module contains the implementation of a service
22
//! 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.
36
47
use cfg_if::cfg_if;
58
use cfg_match::cfg_match;
@@ -41,4 +44,57 @@ impl DialogService {
4144
feature = "web_sys" => utils::window().confirm_with_message(message).unwrap(),
4245
}
4346
}
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+
}
44100
}

yew/src/services/fetch/web_sys.rs

+7-5
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,7 @@ pub struct FetchService {}
164164

165165
impl FetchService {
166166
/// Sends a request to a remote server given a Request object and a callback
167-
/// fuction to convert a Response object into a loop's message.
167+
/// function to convert a Response object into a loop's message.
168168
///
169169
/// You may use a Request builder to build your request declaratively as on the
170170
/// following examples:
@@ -183,7 +183,7 @@ impl FetchService {
183183
/// .expect("Failed to build request.");
184184
/// ```
185185
///
186-
/// The callback function can build a loop message by passing or analizing the
186+
/// The callback function can build a loop message by passing or analyzing the
187187
/// response body and metadata.
188188
///
189189
/// ```
@@ -220,8 +220,8 @@ impl FetchService {
220220
/// ```
221221
///
222222
/// For a full example, you can specify that the response must be in the JSON format,
223-
/// and be a specific serialized data type. If the mesage isn't Json, or isn't the specified
224-
/// data type, then you will get a message indicating failure.
223+
/// and be a specific serialized data type. If the message isn't JSON, or isn't the specified
224+
/// data type, then you will get an error message.
225225
///
226226
/// ```
227227
///# use yew::format::{Json, Nothing, Format};
@@ -555,7 +555,9 @@ impl WindowOrWorker {
555555
} else if !global.worker().is_undefined() {
556556
Self::Worker(global.unchecked_into())
557557
} else {
558-
panic!("Only supported in a browser or web worker");
558+
panic!(
559+
"Yew's `FetchService` only works when a `window` or `worker` object is available."
560+
);
559561
}
560562
}
561563
}

yew/src/services/mod.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,10 @@ pub use self::websocket::WebSocketService;
3737

3838
use std::time::Duration;
3939

40-
/// An universal task of a service.
41-
/// The task must be handled when it is cancelled.
40+
/// A task is an ongoing process which is part of a Yew application.
41+
///
42+
/// All tasks must be handled when they are cancelled, which is why the `Drop` trait is required.
43+
/// Tasks should cancel themselves in their implementation of the `Drop` trait.
4244
pub trait Task: Drop {
4345
/// Returns `true` if task is active.
4446
fn is_active(&self) -> bool;

yew/src/services/reader/web_sys.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ impl ReaderService {
1919

2020
/// Reads all bytes from a file and returns them with a callback.
2121
pub fn read_file(&mut self, file: File, callback: Callback<FileData>) -> Result<ReaderTask> {
22-
let file_reader = FileReader::new().map_err(|_| anyhow!("couldn't aquire file reader"))?;
22+
let file_reader = FileReader::new().map_err(|_| anyhow!("couldn't acquire file reader"))?;
2323
let reader = file_reader.clone();
2424
let name = file.name();
2525
let callback = move |_event: &Event| {

0 commit comments

Comments
 (0)