nsh-core 0.3.0

Platform-independent core: shadow tree, styles, layout and mount instructions.
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
//! What components that run once read of the surface and ask of the
//! platform, as free functions (TS: `nsh`'s accessors and modules).
//!
//! The environment, the design tokens, globals and screens' insets are signals the
//! core writes: reading one in a binding subscribes it, so a change reaches
//! only what read it. Services (dialogs, the clipboard) are actions
//! for the core; tasks and timers belong to the current owner and end with
//! it.

use std::{
    any::{Any, TypeId},
    future::Future,
    rc::Rc,
    sync::Arc,
    time::Duration,
};

use rustc_hash::FxHashMap;

use super::{
    AdaptiveColor, Environment, Memo, Owner, Signal, SignalEquals, Tokens, cleanup, computed,
    reactive::with_data,
    signal_with,
    task::{self, Action, Answer, ClipboardImage, DialogAnswer, Executor, ImageSize},
};
use crate::{
    Command, Dialog, EdgeInsets, LayoutAnimation, NodeId, Points, Size,
    canvas::CanvasFont,
    color::Hsla,
    platform::{Appearance, Idiom, Locale, Os},
    time::Instant,
};

/// How text is measured on one line, in a canvas font.
pub(crate) type MeasureFn = Rc<dyn Fn(&CanvasFont, &str) -> crate::canvas::TextMetrics>;

/// What the core gives components that run once.
#[derive(Default)]
pub(crate) struct Ambient {
    executor: Option<Rc<Executor>>,
    env: Option<EnvSignals>,
    tokens: Option<Signal<Arc<Tokens>>>,
    globals: FxHashMap<TypeId, Box<dyn Any>>,
    /// The insets of the screens or modals components are on, by host.
    insets: FxHashMap<NodeId, Signal<EdgeInsets>>,
    measure: Option<MeasureFn>,
    /// The app's key-value storage (`nsh/storage`).
    storage: Option<crate::storage::Store>,
}

impl Ambient {
    /// The hosts whose insets components read.
    pub(crate) fn inset_hosts(&self) -> Vec<NodeId> {
        self.insets.keys().copied().collect()
    }
}

/// The environment as a signal, and a memo per part (a change notifies only
/// the readers of the parts that changed).
struct EnvSignals {
    env: Signal<Environment>,
    window: Memo<Size<Points>>,
    safe_area: Memo<EdgeInsets>,
    title_bar: Memo<crate::geometry::Edges<crate::geometry::Points>>,
    keyboard_height: Memo<Points>,
    keyboard_duration: Memo<f32>,
    dark: Memo<bool>,
    font_scale: Memo<f32>,
    reduce_motion: Memo<bool>,
    screen_reader: Memo<bool>,
    pixel_ratio: Memo<f32>,
    locale: Memo<Locale>,
}

impl EnvSignals {
    fn new(env: Environment) -> Self {
        Owner::detached().run(|| {
            let signal = super::signal(env);
            macro_rules! part {
                ($field:ident) => {
                    computed(move || signal.with(|e| e.$field))
                };
            }
            Self {
                env: signal,
                window: part!(window),
                safe_area: part!(safe_area),
                title_bar: part!(title_bar),
                keyboard_height: part!(keyboard_height),
                keyboard_duration: part!(keyboard_duration),
                dark: part!(dark),
                font_scale: part!(font_scale),
                reduce_motion: part!(reduce_motion),
                screen_reader: part!(screen_reader),
                pixel_ratio: part!(pixel_ratio),
                locale: part!(locale),
            }
        })
    }
}

// --- What the core sets ------------------------------------------------------

impl super::Runtime {
    /// The executor of tasks and actions.
    pub(crate) fn set_services(&self, executor: Rc<Executor>) {
        let _entered = self.enter();
        with_data(|d| d.ambient.executor = Some(executor));
    }

    /// Where the app's storage is kept.
    pub(crate) fn set_storage(&self, storage: crate::storage::Store) {
        let _entered = self.enter();
        with_data(|d| d.ambient.storage = Some(storage));
    }

    /// How text is measured (the core's text engine).
    pub(crate) fn set_measure(&self, measure: MeasureFn) {
        let _entered = self.enter();
        with_data(|d| d.ambient.measure = Some(measure));
    }

    /// The environment now: what read a part that changed runs again.
    pub(crate) fn set_environment(&self, env: Environment) {
        let _entered = self.enter();
        let signal = with_data(|d| d.ambient.env.as_ref().map(|e| e.env));
        match signal {
            Some(signal) => signal.set(env),
            None => {
                let signals = EnvSignals::new(env);
                with_data(|d| d.ambient.env = Some(signals));
            }
        }
    }

    /// The design tokens now: what read them runs again.
    pub(crate) fn set_tokens(&self, tokens: Arc<Tokens>) {
        let _entered = self.enter();
        let signal = with_data(|d| d.ambient.tokens);
        match signal {
            Some(signal) => signal.set(tokens),
            None => {
                let signal = Owner::detached().run(|| signal_with(tokens, SignalEquals::Never));
                with_data(|d| d.ambient.tokens = Some(signal));
            }
        }
    }

    /// The hosts whose insets components read.
    pub(crate) fn inset_hosts(&self) -> Vec<NodeId> {
        let _entered = self.enter();
        with_data(|d| d.ambient.inset_hosts())
    }

    /// The insets of the screen or modal `host` is on.
    pub(crate) fn set_insets(&self, host: NodeId, insets: EdgeInsets) {
        let _entered = self.enter();
        if let Some(signal) = with_data(|d| d.ambient.insets.get(&host).copied()) {
            signal.set(insets);
        }
    }

    /// `host` goes: its insets are no longer read.
    pub(crate) fn forget_host(&self, host: NodeId) {
        let _entered = self.enter();
        with_data(|d| d.ambient.insets.remove(&host));
    }
}

fn env<T: Clone + 'static>(part: impl FnOnce(&EnvSignals) -> Memo<T>) -> T {
    let memo = with_data(|d| d.ambient.env.as_ref().map(part));
    memo.expect("the core sets the environment before components run")
        .get()
}

fn executor() -> Rc<Executor> {
    with_data(|d| d.ambient.executor.clone()).expect("the core sets the executor")
}

fn act(action: Action) {
    executor().act(action);
}

// --- The environment ---------------------------------------------------------

/// The surface's size in points (TS: `windowSize()`).
pub fn window() -> Size<Points> {
    env(|e| e.window)
}

/// The edges system UI covers: notch, home indicator (TS: `safeArea()`).
pub fn safe_area() -> EdgeInsets {
    env(|e| e.safe_area)
}

/// The software keyboard's height over the surface, 0 when hidden (TS:
/// `keyboardFrame().height`).
pub fn keyboard_height() -> Points {
    env(|e| e.keyboard_height)
}

/// How long the keyboard's show / hide animation takes, in seconds.
pub fn keyboard_duration() -> f32 {
    env(|e| e.keyboard_duration)
}

/// Dark appearance (TS: `colorScheme() === "dark"`). Theme colors follow
/// it without this; read it for anything else.
pub fn dark() -> bool {
    env(|e| e.dark)
}

/// `color` for the appearance now (props that take one color, such as an
/// input's placeholder color; styles take theme colors as they are).
pub fn color(color: impl Into<AdaptiveColor>) -> Hsla {
    let color = color.into();
    if dark() { color.dark } else { color.light }
}

/// The user's text size relative to the default (TS: `fontScale()`).
pub fn font_scale() -> f32 {
    env(|e| e.font_scale)
}

/// The user asked for less motion (TS: `reduceMotion()`).
pub fn reduce_motion() -> bool {
    env(|e| e.reduce_motion)
}

/// A screen reader runs (TS: `screenReaderEnabled()`).
pub fn screen_reader() -> bool {
    env(|e| e.screen_reader)
}

/// Device pixels per point (TS: `pixelRatio()`).
pub fn pixel_ratio() -> f32 {
    env(|e| e.pixel_ratio)
}

/// `points` rounded to whole device pixels (TS:
/// `Math.round(x * pixelRatio()) / pixelRatio()`).
pub fn round_to_nearest_pixel(points: Points) -> Points {
    let ratio = pixel_ratio().max(f32::MIN_POSITIVE);
    Points((points.0 * ratio).round() / ratio)
}

/// The user's locale (TS: what `Intl` formats for by default).
pub fn locale() -> Locale {
    env(|e| e.locale)
}

/// The operating system (TS: `platform.os`); it does not change.
pub fn os() -> Os {
    with_data(|d| d.ambient.env.as_ref().map(|e| e.env))
        .expect("the core sets the environment")
        .with_untracked(|e| e.os)
}

/// The OS version: major and minor on iOS, the API level and 0 on Android
/// (TS: `platform.version`).
pub fn os_version() -> (u16, u16) {
    with_data(|d| d.ambient.env.as_ref().map(|e| e.env))
        .expect("the core sets the environment")
        .with_untracked(|e| e.os_version)
}

/// The kind of device (TS: `platform.idiom`, `platform.catalyst`).
pub fn idiom() -> Idiom {
    with_data(|d| d.ambient.env.as_ref().map(|e| e.env))
        .expect("the core sets the environment")
        .with_untracked(|e| e.idiom)
}

/// Whether desktop behavior applies: a desktop OS, or a browser in the
/// desktop idiom (TS: `platform.idiom` `"desktop"`); it does not change.
pub fn is_desktop() -> bool {
    with_data(|d| d.ambient.env.as_ref().map(|e| e.env))
        .expect("the core sets the environment")
        .with_untracked(|e| e.idiom.desktop_on(e.os))
}

/// The design tokens the app is drawn with (reading them subscribes: new
/// tokens reach what read them).
pub fn tokens() -> Arc<Tokens> {
    with_data(|d| d.ambient.tokens)
        .expect("the core sets the tokens")
        .get()
}

/// The width of `text` on one line in `font` (the CSS `font` shorthand; an
/// invalid one measures in `10px sans-serif`), by the platform's text engine
/// (TS: a canvas's `measureText(text).width`).
pub fn measure_text(font: &str, text: &str) -> Points {
    text_metrics(font, text).width
}

/// How `text` sits on one line in `font` (the CSS `font` shorthand; an
/// invalid one measures in `10px sans-serif`), by the platform's text
/// engine: its width and the font's ascent, descent and line height, to
/// place text a canvas draws (a cell's baseline, a caret over it).
pub fn text_metrics(font: &str, text: &str) -> crate::canvas::TextMetrics {
    let font = CanvasFont::parse(font).unwrap_or_default();
    let measure = with_data(|d| d.ambient.measure.clone()).expect("the core sets the text engine");
    measure(&font, text)
}

/// The surface's `G`: one signal per type, made with `Default` the first
/// time (TS: a signal at module level). Every write notifies.
pub fn global<G: Default + 'static>() -> Signal<G> {
    let id = TypeId::of::<G>();
    if let Some(signal) = with_data(|d| {
        d.ambient
            .globals
            .get(&id)
            .and_then(|g| g.downcast_ref::<Signal<G>>().copied())
    }) {
        return signal;
    }
    let signal = Owner::detached().run(|| signal_with(G::default(), SignalEquals::Never));
    with_data(|d| d.ambient.globals.insert(id, Box::new(signal)));
    signal
}

/// [`global`] where a reactive runtime is entered (the engine's thread,
/// while it runs Rust code), else `None`: for code that also runs outside
/// an engine (a unit test of a component's model).
pub fn try_global<G: Default + 'static>() -> Option<Signal<G>> {
    super::reactive::try_with_data(|_| ())?;
    Some(global::<G>())
}

/// The insets of the screen or modal the component on `host` is on, below
/// its header, else the safe area (TS: `safeAreaInsets()`).
pub(crate) fn insets_of(host: NodeId) -> EdgeInsets {
    let existing = with_data(|d| d.ambient.insets.get(&host).copied());
    let signal = existing.unwrap_or_else(|| {
        // The core fills it in before the commit ends.
        let signal = Owner::detached().run(|| super::signal(safe_area()));
        with_data(|d| d.ambient.insets.insert(host, signal));
        signal
    });
    signal.get()
}

// --- Services ----------------------------------------------------------------

/// Shows `dialog` (an alert, or with `sheet` an action sheet); await the
/// answer in a task.
///
/// The core's part of `nsh_base::alert_dialog`, which apps use.
#[doc(hidden)]
pub fn dialog(dialog: Dialog) -> DialogAnswer {
    let (answer, slot) = DialogAnswer::new();
    act(Action::Dialog(dialog, slot));
    answer
}

/// Unfocuses the focused input, hiding the software keyboard.
pub fn dismiss_keyboard() {
    act(Action::Command(crate::ROOT_ID, Command::Blur));
}

/// Animates the layout changes of the next commit (React Native's
/// `LayoutAnimation.configureNext`).
pub fn animate_layout(animation: LayoutAnimation) {
    act(Action::Command(
        crate::ROOT_ID,
        Command::LayoutAnimation(animation),
    ));
}

/// The screen reader reads `message` (TS:
/// `announce`).
pub fn announce_for_accessibility(message: impl Into<String>) {
    act(super::services::announce(message.into()));
}

/// Runs `f` with the app's storage (`nsh/storage`, [`crate::storage::Storage`]):
/// the one the engine was given, or one in memory when it was given none.
pub(crate) fn with_storage<R>(f: impl FnOnce(&crate::storage::Store) -> R) -> R {
    let storage = with_data(|d| {
        d.ambient
            .storage
            .get_or_insert_with(|| crate::storage::Store::new(None))
            .clone()
    });
    f(&storage)
}

/// Opens `url` outside the app (TS: `openUrl` of `nsh/device`): a web page
/// in the browser, a `mailto:` or `tel:` link in its app, any scheme
/// another app registered. The embedding app may take it first (its host
/// channel's URL handler, which routes it through the host's router).
/// Resolves to whether it opened: `false` for a URL
/// [`crate::open_url::check_url`] refuses, when the app's `openUrl`
/// capability is not granted, or when no app handles it. Await it in a
/// task, or drop it when the answer does not matter.
pub fn open_url(url: impl Into<String>) -> Answer<bool> {
    let (answer, action) = super::services::open_url(url.into());
    act(action);
    answer
}

/// Puts `text` on the system clipboard (TS: `Clipboard.writeText`).
pub fn set_clipboard(text: impl Into<String>) {
    act(super::services::set_clipboard(text.into()));
}

/// The text on the system clipboard, `""` when it holds none (TS:
/// `Clipboard.readText`), to await in a task.
pub fn clipboard_string() -> Answer<String> {
    let (answer, action) = super::services::clipboard_string();
    act(action);
    answer
}

/// Whether the system clipboard holds text (TS: `Clipboard.hasText`).
pub fn clipboard_has_string() -> Answer<bool> {
    let (answer, action) = super::services::clipboard_has_string();
    act(action);
    answer
}

/// Puts the image of a `data:` URI (as [`clipboard_image`] gives) on the
/// system clipboard (TS: `Clipboard.writeImage`).
pub fn set_clipboard_image(uri: impl Into<String>) {
    act(super::services::set_clipboard_image(uri.into()));
}

/// The image on the system clipboard, `None` when it holds none (TS:
/// `Clipboard.readImage`), to await in a task.
pub fn clipboard_image() -> Answer<Option<ClipboardImage>> {
    let (answer, action) = super::services::clipboard_image();
    act(action);
    answer
}

/// Whether the system clipboard holds an image, without reading it (TS:
/// `Clipboard.hasImage`).
pub fn clipboard_has_image() -> Answer<bool> {
    let (answer, action) = super::services::clipboard_has_image();
    act(action);
    answer
}

/// The `file:` URLs of the local files on the system clipboard (files
/// copied in a file manager; TS: `Clipboard.readFiles`), to await in a task.
pub fn clipboard_files() -> Answer<Vec<String>> {
    let (answer, action) = super::services::clipboard_files();
    act(action);
    answer
}

/// Shows the system's picker for images and gives the ones the user picked,
/// prepared as `request` says, none when cancelled (TS:
/// `Picker.pickImages`), to await in a task.
pub fn pick_images(request: crate::picker::PickRequest) -> Answer<Vec<crate::picker::PickedFile>> {
    let (answer, action) = super::services::pick_images(request);
    act(action);
    answer
}

/// The value function `name` of the embedding app returns for `args`
/// (TS: `host.call`), to await in a task.
pub(crate) fn host_call(
    name: String,
    args: crate::JsonValue,
) -> Answer<Result<crate::JsonValue, String>> {
    let (answer, action) = super::services::host_call(name, args);
    act(action);
    answer
}

/// Forgets the host calls whose answers were dropped (they timed out).
pub(crate) fn forget_host_calls() {
    act(Action::ForgetHostCalls);
}

/// The size in pixels of the image at `src` (TS: `Image.getSize`).
pub fn image_size(src: impl Into<String>) -> Answer<Result<ImageSize, String>> {
    let (answer, action) = super::services::image_size(src.into());
    act(action);
    answer
}

/// Loads the image at `src` ahead of showing it (TS: `Image.prefetch`).
pub fn prefetch_image(src: impl Into<String>) -> super::Prefetch {
    let (answer, action) = super::services::prefetch(src.into());
    act(action);
    answer
}

/// Makes an HTTP request (in a task: await its response; TS: `fetch`) with
/// the engine's network stack, the one JS's `fetch` uses: the platform's
/// on native targets and the browser's on the web, under the app's
/// `capabilities.network`. `request` is a URL (`GET`) or an
/// [`HttpRequest`](crate::platform::HttpRequest); the URL is absolute.
/// The whole body arrives with the response.
pub fn fetch(request: impl Into<crate::platform::HttpRequest>) -> super::Fetch {
    let (answer, action) = super::services::fetch(request.into());
    act(action);
    answer
}

/// Shows the surface in `appearance` whatever the system's (TS:
/// `setColorScheme`).
pub fn set_color_scheme(appearance: Appearance) {
    act(Action::Appearance(appearance));
}

// --- Tasks and timers --------------------------------------------------------

/// A running task ([`spawn`]): it ends with the owner it was made under, or
/// when [`Spawned::cancel`] is called. Awaiting it gives its output.
pub struct Spawned<T>(task::Task<T>);

impl<T> Spawned<T> {
    /// Ends the task now.
    pub fn cancel(self) {
        self.0.handle().cancel();
    }
}

impl<T> Future for Spawned<T> {
    type Output = T;

    fn poll(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<T> {
        std::pin::Pin::new(&mut self.0).poll(cx)
    }
}

/// Runs `future` on the engine thread (TS: an `async` function): it changes
/// what it wants by writing signals, and ends with the current owner. It
/// runs under that owner: what it makes is the owner's.
pub fn spawn<T: 'static>(future: impl Future<Output = T> + 'static) -> Spawned<T> {
    let executor = executor();
    let owner = Owner::current();
    let task = task::spawn_future(
        &executor,
        Owned {
            owner,
            future: Box::pin(future),
        },
    );
    let handle = task.handle();
    cleanup(move || handle.cancel());
    Spawned(task)
}

/// A future polled under `owner` ([`Owner::scope`]).
struct Owned<F> {
    owner: Owner,
    future: std::pin::Pin<Box<F>>,
}

impl<F: Future> Future for Owned<F> {
    type Output = F::Output;

    fn poll(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<F::Output> {
        let this = self.get_mut();
        this.owner.scope(|| this.future.as_mut().poll(cx))
    }
}

/// Runs `f` once after `delay` (TS: `setTimeout`; cancelling the task is
/// `clearTimeout`), while the current owner lives.
pub fn set_timeout(delay: Duration, f: impl FnOnce() + 'static) -> Spawned<()> {
    let owner = Owner::current();
    spawn(async move {
        timer(delay).await;
        owner.run(f);
    })
}

/// Runs `f` every `period` (TS: `setInterval`), while the current owner
/// lives. Late wakes do not pile up runs.
pub fn set_interval(period: Duration, f: impl Fn() + 'static) -> Spawned<()> {
    let owner = Owner::current();
    spawn(async move {
        let mut next = crate::time::now() + period;
        loop {
            timer_until(next).await;
            next = (next + period).max(crate::time::now());
            owner.run(&f);
        }
    })
}

/// Runs `f` when the next display frame starts, with its time (TS:
/// `requestAnimationFrame`).
pub fn request_animation_frame(f: impl FnOnce(Instant) + 'static) -> Spawned<()> {
    let owner = Owner::current();
    spawn(async move {
        let at = next_frame().await;
        owner.run(move || f(at));
    })
}

/// Waits `delay` (in a task; TS: what `setTimeout` waits for).
pub fn timer(delay: Duration) -> Delay {
    timer_until(crate::time::now() + delay)
}

/// Waits until `at` (in a task).
pub fn timer_until(at: Instant) -> Delay {
    Delay {
        at,
        registered: false,
        #[cfg(not(target_arch = "wasm32"))]
        elsewhere: None,
    }
}

/// What [`timer`] and [`timer_until`] wait for. In the engine's tasks the
/// core keeps it and the engine's loop wakes for it, as for JS's timers
/// (on time, with no other thread involved); awaited off the engine's
/// thread (in [`background`]), it is tokio's.
#[derive(Debug)]
pub struct Delay {
    at: Instant,
    /// The core keeps it.
    registered: bool,
    #[cfg(not(target_arch = "wasm32"))]
    elsewhere: Option<std::pin::Pin<Box<tokio::time::Sleep>>>,
}

impl Future for Delay {
    type Output = ();

    fn poll(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<()> {
        #[cfg(not(target_arch = "wasm32"))]
        if let Some(sleep) = &mut self.elsewhere {
            return sleep.as_mut().poll(cx);
        }
        if crate::time::now() >= self.at {
            return std::task::Poll::Ready(());
        }
        if self.registered {
            return std::task::Poll::Pending;
        }
        match super::reactive::try_with_data(|d| d.ambient.executor.clone()).flatten() {
            Some(executor) => {
                executor.add_timer(self.at, cx.waker().clone());
                self.registered = true;
                std::task::Poll::Pending
            }
            #[cfg(not(target_arch = "wasm32"))]
            None => {
                let at = self.at;
                let sleep = self
                    .elsewhere
                    .insert(Box::pin(tokio::time::sleep_until(at.into())));
                sleep.as_mut().poll(cx)
            }
            // WebAssembly runs everything on the engine's thread.
            #[cfg(target_arch = "wasm32")]
            None => std::task::Poll::Pending,
        }
    }
}

/// The next display frame's start (in a task; TS: what
/// `requestAnimationFrame` waits for). Awaited in a loop, it runs once per
/// frame.
pub fn next_frame() -> Answer<Instant> {
    let (answer, action) = super::services::frame();
    act(action);
    answer
}

/// Runs blocking `f` on the runtime's blocking threads (in a task: await
/// its result; `tokio::task::spawn_blocking`). Not in WebAssembly: code
/// that should also run on the web uses the engine's services instead
/// ([`fetch`], [`timer`]).
#[cfg(not(target_arch = "wasm32"))]
pub fn blocking<R: Send + 'static>(
    f: impl FnOnce() -> R + Send + 'static,
) -> tokio::task::JoinHandle<R> {
    tokio::task::spawn_blocking(f)
}

/// Runs `future` on the runtime's threads (in a task: await its result;
/// `tokio::spawn`): `Send` work that should not hold the engine thread.
/// Not in WebAssembly, which has no threads.
#[cfg(not(target_arch = "wasm32"))]
pub fn background<F>(future: F) -> tokio::task::JoinHandle<F::Output>
where
    F: Future + Send + 'static,
    F::Output: Send + 'static,
{
    tokio::spawn(future)
}

// --- Handles -----------------------------------------------------------------

/// An animated value starting at `value` (TS: `createAnimatedValue`): bind
/// it to styles, drags, scroll offsets or drawings, animate it from handlers
/// and tasks. A `Copy` handle the current owner keeps, as a signal is (with
/// no owner, it lives as long as the surface).
pub fn animated_value(value: f32) -> super::AnimatedValue {
    super::AnimatedValue::new(&executor(), value)
}

/// Animated values for a view's opacity and transform, and motions to
/// play on them (TS: `createMotion`): bind it with
/// [`super::Styled::bind_motion`]. A `Copy` handle the current owner keeps.
pub fn motion() -> super::Motion {
    super::Motion::new(&executor())
}

/// A handle for an element (TS: `ref`): put it on the element with
/// [`super::Element::element_ref`], call its commands from handlers and
/// tasks. A `Copy` handle the current owner keeps, as a signal is.
pub fn element_ref() -> super::ElementRef {
    super::ElementRef::new(&executor())
}

/// A handle for a component this view renders (TS: a `ref` to a
/// component): put it on the component's element with
/// [`super::ComponentElement::component_ref`]; [`super::ComponentRef::api`]
/// is the API its view registered. A `Copy` handle the current owner keeps.
pub fn component_ref<C: super::Component>() -> super::ComponentRef<C> {
    super::ComponentRef::new(&executor())
}

/// How a keyboard shortcut fires ([`on_key_with`]; TS: `keymap.bind`'s
/// options).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct KeyOptions {
    /// While a text input (or a web view) has the keyboard focus: by
    /// default unless the input uses the keystroke itself.
    pub when: crate::keymap::When,
    /// Fires again on the auto-repeats of a held key (default: once until
    /// the key is released).
    pub repeat: bool,
}

/// Whether shortcuts follow Apple's conventions here (`mod` is Command):
/// the OS, or for a browser the platform it runs on.
fn apple_keys() -> bool {
    let (os, apple) = with_data(|d| d.ambient.env.as_ref().map(|e| e.env))
        .expect("the core sets the environment")
        .with_untracked(|e| (e.os, e.apple_keyboard));
    crate::keymap::apple_keys(os, apple)
}

/// Runs `handler` when `keystroke` is pressed while the current owner
/// lives (TS: `keymap.bind`): `"mod+k"` (`mod` is Command on Apple
/// platforms, Control elsewhere), `"shift+mod+l"`, `"escape"`, ... (the
/// keystrokes of `nsh/keymap`). The handler gets the keystroke as written.
/// Desktop platforms fire them; elsewhere they are kept but no key does.
///
/// # Panics
///
/// On a keystroke that is not one, or one the platform keeps (Command+Q
/// on Apple platforms, Alt+F4 elsewhere, ...), as TS's `bind` throws.
#[track_caller]
pub fn on_key(keystroke: &str, handler: impl Fn(&str) + 'static) {
    on_key_with(keystroke, KeyOptions::default(), handler);
}

/// [`on_key`] that fires as `options` say.
///
/// # Panics
///
/// As [`on_key`].
#[track_caller]
pub fn on_key_with(keystroke: &str, options: KeyOptions, handler: impl Fn(&str) + 'static) {
    let os = os();
    let parsed = crate::keymap::Keystroke::parse_with(keystroke, apple_keys())
        .unwrap_or_else(|e| panic!("on_key: {e}"));
    if let Some(why) = parsed.reserved(os) {
        panic!("on_key: {keystroke:?} cannot be bound: {why}");
    }
    let owner = Owner::current();
    let handler: super::keys::KeyHandler = Rc::new(move |k: &str| owner.run(|| handler(k)));
    let keys = executor().keys.clone();
    let id = keys.borrow_mut().add(
        |id| crate::keymap::KeyBinding::new(id, parsed, options.when, options.repeat),
        keystroke.into(),
        handler,
    );
    let weak = Rc::downgrade(&keys);
    cleanup(move || {
        if let Some(keys) = weak.upgrade() {
            let removed = keys.borrow_mut().remove(id);
            drop(removed);
        }
    });
}

/// `keystroke` as menus and hints show it here (TS: `keymap.label`):
/// `"⇧⌘L"` on Apple platforms (and in a browser on one), `"Ctrl+Shift+L"`
/// elsewhere, for `"mod+shift+l"`.
///
/// # Panics
///
/// On a keystroke that is not one.
#[track_caller]
pub fn key_label(keystroke: &str) -> String {
    let apple = apple_keys();
    crate::keymap::Keystroke::parse_with(keystroke, apple)
        .unwrap_or_else(|e| panic!("key_label: {e}"))
        .label(os(), apple)
}

/// Listens to the Android back button while the current owner lives (TS:
/// `BackHandler.onBackPress(f)`): when no modal is
/// shown, `f` runs before the stack pops, newest listener first, and returns
/// true when it handled the press. While one listens, a back gesture does
/// not preview the pop.
pub fn on_back_press(f: impl Fn() -> bool + 'static) {
    let owner = Owner::current();
    let listener: super::back::BackListener = Rc::new(move || owner.run(&f));
    let back = &executor().back;
    let id = back.borrow_mut().add(listener);
    let subscription = super::back::BackSubscription::new(back, id);
    cleanup(move || drop(subscription));
}

pub(crate) fn title_bar() -> crate::geometry::Edges<crate::geometry::Points> {
    env(|e| e.title_bar)
}

pub(crate) fn desktop_command(command: crate::desktop::DesktopCommand) {
    act(Action::Command(
        crate::ROOT_ID,
        Command::Desktop(Box::new(command)),
    ));
}