forked from rustwasm/gloo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.rs
288 lines (251 loc) · 7.43 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
/*!
Working with timers on the Web: `setTimeout` and `setInterval`.
These APIs come in two flavors:
1. a callback style (that more directly mimics the JavaScript APIs), and
2. a `Future`s and `Stream`s API.
## Timeouts
Timeouts fire once after a period of time (measured in milliseconds).
### Timeouts with a Callback Function
```no_run
use gloo_timers::Timeout;
let timeout = Timeout::new(1_000, move || {
// Do something after the one second timeout is up!
});
// Since we don't plan on cancelling the timeout, call `forget`.
timeout.forget();
```
### Timeouts as `Future`s
```no_run
use futures::prelude::*;
use gloo_timers::TimeoutFuture;
use wasm_bindgen_futures::spawn_local;
let timeout = TimeoutFuture::new(1_000).and_then(|_| {
// Do something here after the one second timeout is up!
# Ok(())
});
// Spawn the `timeout` future on the local thread. If we just dropped it, then
// the timeout would be cancelled with `clearTimeout`.
spawn_local(timeout);
```
## Intervals
Intervals fire repeatedly every *n* milliseconds.
### Intervals with a Callback Function
TODO
### Intervals as `Stream`s
TODO
*/
#![deny(missing_docs, missing_debug_implementations)]
use futures::prelude::*;
use std::fmt;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::JsFuture;
fn window() -> web_sys::Window {
web_sys::window().unwrap_throw()
}
/// A scheduled timeout.
///
/// See `Timeout::new` for scheduling new timeouts.
///
/// Once scheduled, you can either `cancel` so that it doesn't run or `forget`
/// it so that it is un-cancel-able.
#[must_use = "timeouts cancel on drop; either call `forget` or `drop` explicitly"]
pub struct Timeout {
id: Option<i32>,
closure: Option<Closure<FnMut()>>,
}
impl Drop for Timeout {
fn drop(&mut self) {
if let Some(id) = self.id {
window().clear_timeout_with_handle(id);
}
}
}
impl fmt::Debug for Timeout {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Timeout").field("id", &self.id).finish()
}
}
impl Timeout {
/// Schedule a timeout to invoke `callback` in `millis` milliseconds from
/// now.
///
/// # Example
///
/// ```no_run
/// use gloo_timers::Timeout;
///
/// let timeout = Timeout::new(1_000, move || {
/// // Do something...
/// });
/// ```
pub fn new<F>(millis: u32, callback: F) -> Timeout
where
F: 'static + FnOnce(),
{
// TODO: Use `FnOnce` here after this merges:
// https://github.com/rustwasm/wasm-bindgen/pull/1281
let mut callback = Some(callback);
let closure = Closure::wrap(Box::new(move || {
let callback = callback.take().unwrap_throw();
callback();
}) as Box<FnMut()>);
let id = window()
.set_timeout_with_callback_and_timeout_and_arguments_0(
closure.as_ref().unchecked_ref::<js_sys::Function>(),
millis as i32,
)
.unwrap_throw();
Timeout {
id: Some(id),
closure: Some(closure),
}
}
/// Make this timeout uncancel-able.
///
/// Returns the identifier returned by the original `setTimeout` call, and
/// therefore you can still cancel the timeout by calling `clearTimeout`
/// directly (perhaps via `web_sys::clear_timeout_with_handle`).
///
/// # Example
///
/// ```no_run
/// use gloo_timers::Timeout;
///
/// // We definitely want to do stuff, and aren't going to ever cancel this
/// // timeout.
/// Timeout::new(1_000, || {
/// // Do stuff...
/// }).forget();
/// ```
pub fn forget(mut self) -> i32 {
let id = self.id.take().unwrap_throw();
self.closure.take().unwrap_throw().forget();
id
}
/// Cancel this timeout so that the callback is not invoked after the time
/// is up.
///
/// The scheduled callback is returned.
///
/// # Example
///
/// ```no_run
/// use gloo_timers::Timeout;
///
/// let timeout = Timeout::new(1_000, || {
/// // Do stuff...
/// });
///
/// // If actually we didn't want to set a timer, then cancel it.
/// if nevermind() {
/// timeout.cancel();
/// }
/// # fn nevermind() -> bool { true }
/// ```
pub fn cancel(mut self) -> Closure<FnMut()> {
self.closure.take().unwrap_throw()
}
}
/// A scheduled timeout as a `Future`.
///
/// See `TimeoutFuture::new` for scheduling new timeouts.
///
/// Once scheduled, if you change your mind and don't want the timeout to fire,
/// you can `drop` the future.
///
/// A timeout future will never resolve to `Err`. Its only failure mode is when
/// the timeout is so long that it is effectively infinite and never fires.
///
/// # Example
///
/// ```no_run
/// use futures::prelude::*;
/// use gloo_timers::TimeoutFuture;
///
/// let timeout_a = TimeoutFuture::new(1_000).map(|_| "a");
/// let timeout_b = TimeoutFuture::new(2_000).map(|_| "b");
///
/// wasm_bindgen_futures::spawn_local(
/// timeout_a
/// .select(timeout_b)
/// .and_then(|(who, other)| {
/// // `timeout_a` should have won this race.
/// assert_eq!(who, "a");
///
/// // Drop `timeout_b` to cancel its timeout.
/// drop(other);
///
/// Ok(())
/// })
/// .map_err(|_| {
/// wasm_bindgen::throw_str(
/// "unreachable -- timeouts never fail, only potentially hang"
/// );
/// })
/// );
/// ```
#[must_use = "futures do nothing unless polled or spawned"]
pub struct TimeoutFuture {
id: Option<i32>,
inner: JsFuture,
}
impl Drop for TimeoutFuture {
fn drop(&mut self) {
if let Some(id) = self.id {
window().clear_timeout_with_handle(id);
}
}
}
impl TimeoutFuture {
/// Create a new timeout future.
///
/// Remember that futures do nothing unless polled or spawned, so either
/// pass this future to `wasm_bindgen_futures::spawn_local` or use it inside
/// another future.
///
/// # Example
///
/// ```no_run
/// use futures::prelude::*;
/// use gloo_timers::TimeoutFuture;
///
/// wasm_bindgen_futures::spawn_local(
/// TimeoutFuture::new(1_000).map(|_| {
/// // Do stuff after one second...
/// })
/// );
/// ```
pub fn new(millis: u32) -> TimeoutFuture {
let mut id = None;
let promise = js_sys::Promise::new(&mut |resolve, _reject| {
id = Some(
window()
.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, millis as i32)
.unwrap_throw(),
);
});
debug_assert!(id.is_some());
let inner = JsFuture::from(promise);
TimeoutFuture { id, inner }
}
}
impl fmt::Debug for TimeoutFuture {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("TimeoutFuture")
.field("id", &self.id)
.finish()
}
}
impl Future for TimeoutFuture {
type Item = ();
type Error = ();
fn poll(&mut self) -> Poll<(), ()> {
match self.inner.poll() {
Ok(Async::Ready(_)) => Ok(Async::Ready(())),
Ok(Async::NotReady) => Ok(Async::NotReady),
// We only ever `resolve` the promise, never reject it.
Err(_) => wasm_bindgen::throw_str("unreachable"),
}
}
}