frus-shell 0.3.0

frus — the platform layer: window + event loop (Milestone 0)
Documentation
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
//! [`Command`]: the **effects** `Application::update` returns.
//!
//! A command describes work to be done **outside** the `update` cycle — a file
//! write, a load, a network `fetch`, a long computation — whose result comes back as
//! a **message** fed into `update`. There are three shapes:
//!
//! - **synchronous** ([`Command::perform`] / [`Command::run`]): a closure that
//!   blocks. It gets a background thread natively, or a microtask on the Web.
//! - **asynchronous** ([`Command::perform_async`] / [`Command::run_async`]): a
//!   **future** that can `await`. Natively it goes to the shell's executor, which
//!   has a reactor, so a future may wait on a timer or on I/O without holding a
//!   thread. On the **Web**, which is single-threaded, the browser drives it
//!   (`spawn_local`) and always did.
//! - **delayed** ([`Command::after`]): a message on a real timer.
//!
//! The distinction that matters is the first against the second, and it is about
//! **what the work does while it is not finished**. Something that blocks — a
//! synchronous file read, a CPU-bound computation — must be a `perform`, because
//! occupying a thread is exactly what a thread is for. Something that *waits* should
//! be a `perform_async`, because waiting no longer costs a thread. Putting a blocking
//! call inside `perform_async` is the one mistake worth naming here: it parks one of
//! the executor's few workers and starves every other effect.
//!
//! Until milestone 303 the asynchronous side was a thread and a `block_on` with no
//! reactor underneath it — `frus-shell`'s own `runtime` module records what that
//! could and could not do.

use std::future::Future;
use std::pin::Pin;
use std::time::Duration;

use frus_widgets::{ScrollTo, SheetTo};

/// A command taken apart, for the shell to run. A struct rather than a tuple: there
/// are several kinds of effect, and a tuple at a call site says nothing about which is
/// which.
pub(crate) struct Parts<Msg> {
    pub(crate) tasks: Vec<Task<Msg>>,
    pub(crate) async_tasks: Vec<AsyncTask<Msg>>,
    pub(crate) timers: Vec<(Duration, Msg)>,
    pub(crate) focus: Vec<u64>,
    pub(crate) scrolls: Vec<(u64, ScrollTo)>,
    pub(crate) sheets: Vec<(u64, SheetTo)>,
}

/// A **synchronous** task: work that may produce a message.
type Task<Msg> = Box<dyn FnOnce() -> Option<Msg> + Send + 'static>;

/// An **asynchronous** task: a future that may produce a message.
///
/// **Natively** it crosses a thread (`block_on`), hence the `Send` bound. On the
/// **Web**, which is single-threaded, the browser's futures (`JsFuture`/`fetch`) are
/// **not** `Send` and do not need to be — hence the relaxed bound.
#[cfg(not(web))]
type AsyncTask<Msg> = Pin<Box<dyn Future<Output = Option<Msg>> + Send + 'static>>;
#[cfg(web)]
type AsyncTask<Msg> = Pin<Box<dyn Future<Output = Option<Msg>> + 'static>>;

/// A batch of effects to run, possibly empty: background **tasks**, synchronous or
/// asynchronous, and **focus** and **scroll** requests addressed by widget key.
pub struct Command<Msg> {
    tasks: Vec<Task<Msg>>,
    async_tasks: Vec<AsyncTask<Msg>>,
    /// Messages to deliver after a delay. Kept as data rather than as a future, so
    /// that the one piece of platform knowledge — how this machine waits — stays in
    /// the shell with all the other platform knowledge.
    timers: Vec<(Duration, Msg)>,
    /// The keys of widgets to focus — the key's hash, as in [`crate::Subscription`]
    /// and the widgets' `keyed(...)`. The shell resolves them after the next build.
    focus: Vec<u64>,
    /// The scroll regions to move, by the same kind of key. Resolved against the frame
    /// the request is returned into.
    scrolls: Vec<(u64, ScrollTo)>,
    /// The sheets to move, by the same kind of key and on the same terms.
    sheets: Vec<(u64, SheetTo)>,
}

/// A key's hash — **identical** to the hash the widgets' `keyed(key, …)` uses, so that
/// `Command::focus(k)` and `Command::scroll(k, …)` both target the `keyed(k, …)` widget.
fn focus_key(key: impl std::hash::Hash) -> u64 {
    use std::hash::Hasher;
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    key.hash(&mut hasher);
    hasher.finish()
}

impl<Msg: Send + 'static> Command<Msg> {
    /// No effect at all.
    pub fn none() -> Self {
        Self {
            tasks: Vec::new(),
            async_tasks: Vec::new(),
            timers: Vec::new(),
            focus: Vec::new(),
            scrolls: Vec::new(),
            sheets: Vec::new(),
        }
    }

    /// Groups several commands into one.
    pub fn batch(commands: impl IntoIterator<Item = Command<Msg>>) -> Self {
        let mut tasks = Vec::new();
        let mut async_tasks = Vec::new();
        let mut timers = Vec::new();
        let mut focus = Vec::new();
        let mut scrolls = Vec::new();
        let mut sheets = Vec::new();
        for command in commands {
            tasks.extend(command.tasks);
            async_tasks.extend(command.async_tasks);
            timers.extend(command.timers);
            focus.extend(command.focus);
            scrolls.extend(command.scrolls);
            sheets.extend(command.sheets);
        }
        Self {
            tasks,
            async_tasks,
            timers,
            focus,
            scrolls,
            sheets,
        }
    }

    /// Delivers `message` once, after `delay`.
    ///
    /// This waits without occupying anything: natively it is a task on the shell's
    /// executor parked on the reactor's timer wheel, and on the Web a `setTimeout`.
    /// A hundred pending timers are a hundred entries in a queue, not a hundred
    /// threads.
    ///
    /// For a message that repeats, declare a [`Subscription::every`](crate::Subscription::every)
    /// instead — a subscription is a function of the state and stops when the state
    /// says so, where a chain of `after`s has to be stopped by hand.
    pub fn after(delay: Duration, message: Msg) -> Self {
        Self {
            timers: vec![(delay, message)],
            ..Self::none()
        }
    }

    /// Runs a **synchronous** task in the background; its result becomes a message.
    pub fn perform(task: impl FnOnce() -> Msg + Send + 'static) -> Self {
        Self {
            tasks: vec![Box::new(move || Some(task()))],
            ..Self::none()
        }
    }

    /// Runs a **synchronous** side effect; it may return a message (`None` for none).
    pub fn run(task: impl FnOnce() -> Option<Msg> + Send + 'static) -> Self {
        Self {
            tasks: vec![Box::new(task)],
            ..Self::none()
        }
    }

    /// Runs an asynchronous **future**; its value becomes a message.
    ///
    /// On the **Web**, which is single-threaded, the browser drives the future
    /// (`spawn_local`), so a real `fetch` can `await` without blocking. **Natively**
    /// it runs on the shell's executor (the `runtime` module), which has a reactor: a
    /// future may wait on a timer or on a socket and costs nothing while it does.
    ///
    /// Do not put a **blocking** call in here — that is what [`Command::perform`] is
    /// for. The executor has four worker threads, and a blocking call holds one of
    /// them for its whole duration.
    #[cfg(not(web))]
    pub fn perform_async<F>(future: F) -> Self
    where
        F: Future<Output = Msg> + Send + 'static,
    {
        Self {
            async_tasks: vec![Box::pin(async move { Some(future.await) })],
            ..Self::none()
        }
    }

    /// Runs an asynchronous **future**; its value becomes a message. See the native
    /// version for the full semantics; the `Send` bounds are relaxed on the Web.
    #[cfg(web)]
    pub fn perform_async<F>(future: F) -> Self
    where
        F: Future<Output = Msg> + 'static,
    {
        Self {
            async_tasks: vec![Box::pin(async move { Some(future.await) })],
            ..Self::none()
        }
    }

    /// Runs an asynchronous **future** for its side effect; it may return a message
    /// (`None` for none). The asynchronous counterpart of [`Command::run`].
    #[cfg(not(web))]
    pub fn run_async<F>(future: F) -> Self
    where
        F: Future<Output = Option<Msg>> + Send + 'static,
    {
        Self {
            async_tasks: vec![Box::pin(future)],
            ..Self::none()
        }
    }

    /// Runs an asynchronous **future** for its side effect (`None` for no message).
    /// The Web version, with the `Send` bound relaxed.
    #[cfg(web)]
    pub fn run_async<F>(future: F) -> Self
    where
        F: Future<Output = Option<Msg>> + 'static,
    {
        Self {
            async_tasks: vec![Box::pin(future)],
            ..Self::none()
        }
    }

    /// Requests **focus** for the widget carrying `key` — the field wrapped in
    /// `keyed(key, …)`. The shell resolves it after the view is next built; it is
    /// typically returned when a form submission fails, to jump to the first invalid
    /// field (`Form::first_invalid`).
    pub fn focus(key: impl std::hash::Hash) -> Self {
        Self {
            focus: vec![focus_key(key)],
            ..Self::none()
        }
    }

    /// **Moves a scroll region**: the one named `key` goes where `to` says.
    ///
    /// A scroll is not a function of the state — the same list, the same offset, and yet
    /// "go back to the top" happens once — so it is an effect and belongs here rather
    /// than on a widget. The offset it changes *is* state, and it stays where it was: in
    /// the runtime, beside every other offset, written by the frame this request is
    /// resolved into.
    ///
    /// Named the way a focus request is named: the region is wrapped in `keyed(k, …)`
    /// and addressed by `k`. The framework's own identities are hashes of a position in
    /// a tree, which an application cannot know and should not have to.
    ///
    /// Resolved against the **frame that follows**, once and once only — the same rule
    /// as [`Command::focus`]. A request naming a region that frame has not got is
    /// dropped rather than kept waiting: an effect that outlived the state it was
    /// written for would arrive at a list that had since become somebody else's.
    ///
    /// ```no_run
    /// # use frus_shell::Command;
    /// # use frus_widgets::ScrollTo;
    /// # fn f() -> Command<()> {
    /// Command::scroll("journal", ScrollTo::start())
    /// # }
    /// ```
    pub fn scroll(key: impl std::hash::Hash, to: ScrollTo) -> Self {
        Self {
            scrolls: vec![(focus_key(key), to)],
            ..Self::none()
        }
    }

    /// **Moves a sheet**: the one named `key` goes where `to` says — the reference's
    /// `DraggableScrollableController`, as an effect.
    ///
    /// For the reason a scroll is one: "raise the sheet" happens once, and the height it
    /// leaves behind is state that stays where every other sheet height is, in the
    /// runtime. Named the same way — the sheet, or anything around it, wrapped in
    /// `keyed(k, …)` — and resolved on the same terms: against the frame that follows, a
    /// sheet that has only just appeared included, and dropped if that frame has not got
    /// it. A finger on the sheet refuses it.
    ///
    /// ```no_run
    /// # use frus_shell::Command;
    /// # use frus_widgets::{Curve, SheetTo};
    /// # fn f() -> Command<()> {
    /// Command::sheet("places", SheetTo::size(1.0).animate(0.3, Curve::ease()))
    /// # }
    /// ```
    pub fn sheet(key: impl std::hash::Hash, to: SheetTo) -> Self {
        Self {
            sheets: vec![(focus_key(key), to)],
            ..Self::none()
        }
    }

    /// A focus request whose key is already a hash — what a component's effect carries.
    pub(crate) fn focus_hashed(key: u64) -> Self {
        Self {
            focus: vec![key],
            ..Self::none()
        }
    }

    /// A scroll request whose key is already a hash.
    pub(crate) fn scroll_hashed(key: u64, to: ScrollTo) -> Self {
        Self {
            scrolls: vec![(key, to)],
            ..Self::none()
        }
    }

    /// A sheet request whose key is already a hash.
    pub(crate) fn sheet_hashed(key: u64, to: SheetTo) -> Self {
        Self {
            sheets: vec![(key, to)],
            ..Self::none()
        }
    }

    /// `true` when the command has no effect and no request of any kind.
    pub fn is_empty(&self) -> bool {
        self.tasks.is_empty()
            && self.async_tasks.is_empty()
            && self.timers.is_empty()
            && self.focus.is_empty()
            && self.scrolls.is_empty()
            && self.sheets.is_empty()
    }

    /// Takes the command apart for the framework to run.
    pub(crate) fn into_parts(self) -> Parts<Msg> {
        Parts {
            tasks: self.tasks,
            async_tasks: self.async_tasks,
            timers: self.timers,
            focus: self.focus,
            scrolls: self.scrolls,
            sheets: self.sheets,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn none_is_empty() {
        assert!(Command::<u32>::none().is_empty());
    }

    #[test]
    fn a_batch_keeps_its_sheet_requests() {
        let sheet = Command::<u32>::sheet("places", SheetTo::size(1.0));
        assert!(!sheet.is_empty());
        let batch = Command::batch([
            sheet,
            Command::none(),
            Command::sheet("other", SheetTo::initial()),
        ]);
        assert_eq!(batch.into_parts().sheets.len(), 2);
    }

    #[test]
    fn perform_yields_a_message() {
        let command = Command::perform(|| 42u32);
        let tasks = command.into_parts().tasks;
        assert_eq!(tasks.len(), 1);
        let produced = (tasks.into_iter().next().unwrap())();
        assert_eq!(produced, Some(42));
    }

    #[test]
    fn run_may_produce_nothing() {
        let command = Command::run(|| -> Option<u32> { None });
        let tasks = command.into_parts().tasks;
        assert_eq!((tasks.into_iter().next().unwrap())(), None);
    }

    #[test]
    fn batch_flattens_and_drops_empties() {
        let command = Command::batch([
            Command::perform(|| 1u32),
            Command::none(),
            Command::run(|| Some(2u32)),
        ]);
        assert_eq!(command.into_parts().tasks.len(), 2);
    }

    #[test]
    fn focus_carries_a_key_and_no_task() {
        // A focus command carries no task, yet it is not "empty".
        let f = Command::<u32>::focus("email");
        assert!(!f.is_empty());
        let parts = f.into_parts();
        assert!(parts.tasks.is_empty());
        assert!(parts.async_tasks.is_empty());
        assert_eq!(parts.focus, vec![focus_key("email")]);
    }

    #[cfg(not(web))]
    #[test]
    fn perform_async_yields_a_message() {
        // The future is driven to completion (`block_on`) and its value becomes a message.
        let command = Command::perform_async(async { 7u32 });
        let mut parts = command.into_parts();
        assert!(parts.tasks.is_empty());
        assert_eq!(parts.async_tasks.len(), 1);
        let produced = pollster::block_on(parts.async_tasks.remove(0));
        assert_eq!(produced, Some(7));
    }

    #[cfg(not(web))]
    #[test]
    fn run_async_may_produce_nothing() {
        let command = Command::run_async(async { None::<u32> });
        let mut parts = command.into_parts();
        assert_eq!(pollster::block_on(parts.async_tasks.remove(0)), None);
    }

    #[cfg(not(web))]
    #[test]
    fn batch_combines_sync_and_async_tasks() {
        let command = Command::batch([
            Command::perform(|| 1u32),
            Command::perform_async(async { 2u32 }),
        ]);
        let parts = command.into_parts();
        assert_eq!(parts.tasks.len(), 1);
        assert_eq!(parts.async_tasks.len(), 1);
    }

    #[test]
    fn after_carries_its_delay_and_is_not_empty() {
        let command = Command::after(Duration::from_millis(250), 9u32);
        assert!(!command.is_empty(), "a pending timer is an effect");
        let parts = command.into_parts();
        assert!(parts.tasks.is_empty() && parts.async_tasks.is_empty());
        assert_eq!(parts.timers, vec![(Duration::from_millis(250), 9u32)]);
    }

    #[test]
    fn batch_carries_timers_through() {
        let command = Command::batch([
            Command::after(Duration::from_millis(10), 1u32),
            Command::perform(|| 2u32),
            Command::after(Duration::from_millis(20), 3u32),
        ]);
        let parts = command.into_parts();
        assert_eq!(parts.tasks.len(), 1);
        assert_eq!(parts.timers.len(), 2, "a batch must not swallow a timer");
    }
}