lurq 0.65.1

A Rust UI toolkit with typed components, retained state, reactive signals, GPU rendering, and DevTools.
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
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
//! A sheet: content that comes up from the bottom of the window over everything in it, as a phone's apps
//! show a choice or a short task.
//!
//! - It comes up when its signal is set, and goes down when the signal is cleared, by Escape, by a tap beside it, or by
//!   a finger that drags it down far enough or fast enough.
//! - It stands at one of its [`SheetDetent`]s, and a finger moves it between them.
//! - Content that scrolls, named with [`SheetProps::scroll`], scrolls under a finger once the sheet is at its highest
//!   and gives the finger to the sheet when it is at its top.

use std::{sync::Arc, time::Duration};

use parking_lot::Mutex;

use crate::{
  animation::{Easing, Transition},
  app::{
    component::Component,
    ctx::{Ctx, Modal, Root, Timeout},
    events::{GesturePhase, PanEvent},
  },
  components::{Column, Row, Stack},
  core::{ElementRef, Signal},
  layout::{StackAlignment, layout_kind::ScrollState},
  node::{Element, color::Color, dimension::Dimension, transform::Transform2D},
  ui::{Recipe, Themed, engine_look::EngineLook, names},
};

const FILL: Dimension = Dimension::Pct(100.0);
/// How long after a sheet is first laid out, out of view, it sets off.
const BEGIN: Duration = Duration::from_millis(1);
/// How long after a move's duration the sheet is taken to be at rest.
const SETTLE_AFTER: Duration = Duration::from_millis(50);
/// How much of the sheet reaches under the window's bottom edge: what is seen under its content when a finger
/// has it higher than it stands.
const UNDER: f32 = 400.0;
/// How much of a pull past the sheet's highest place is given to it.
const RESISTANCE: f32 = 0.55;

/// A height a sheet stands at.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SheetDetent {
  /// Half the window.
  Medium,
  /// The whole window under [`SheetStyle::top_margin`].
  Large,
  /// A share of [`SheetDetent::Large`], from 0 to 1.
  Fraction(f32),
  /// So many logical pixels, over the room the home indicator takes.
  Height(f32),
  /// As high as the content is.
  Content,
}

/// How a [`Sheet`] looks and moves. Its sizes and its motion were set by eye beside the platform's. Its colors
/// come from the theme, through the recipe it keeps under the name `phone_sheet` ([`SheetNode`] names the parts):
/// the design's roles, light or dark as the theme is, and the colors of 0.62 in
/// [`ThemeDefinition::legacy`](crate::app::theme::ThemeDefinition::legacy). They are read where the style is made,
/// in the theme of what is being built.
///
/// ```
/// use lurq::{app::theme::{PaletteColor, ThemeDefinition}, components::{SheetNode, SheetStyle}};
///
/// // Every sheet of the app on the card's color.
/// let mut theme = ThemeDefinition::neutral();
/// theme.ui.patch::<SheetStyle>(|rules| rules.base(SheetNode::Panel, |s| s.background(PaletteColor::Card)));
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SheetStyle {
  /// The sheet's own color. A sheet that draws all of itself has a clear one and no radius.
  pub background: Color,
  /// How round the sheet's top corners are.
  pub corner_radius: f32,
  /// What is drawn over the window behind the sheet, and how much of it shows when the sheet is up: 0 leaves
  /// the window as it is.
  pub backdrop: Color,
  pub dim: f32,
  /// The bar at the sheet's top that says it can be dragged.
  pub grabber: bool,
  pub grabber_color: Color,
  pub grabber_width: f32,
  pub grabber_height: f32,
  /// How far under the sheet's top edge the grabber is.
  pub grabber_top: f32,
  /// How far under the status bar's room the highest sheet stops.
  pub top_margin: f32,
  /// The widest the sheet is; in a wider window it stands in the middle.
  pub max_width: f32,
  /// How long the sheet takes to come up, go down or move between heights. It follows a spring, which starts
  /// at the speed a finger let the sheet go with. Taken when the sheet is made.
  pub duration: Duration,
  /// How far ahead of where a finger let the sheet go it is taken to be going, in seconds of the finger's
  /// speed: the height nearest to there is where it goes.
  pub throw: f32,
}

/// The colors of 0.62's sheet: what the legacy theme gives, and what a theme with no recipe for the sheet keeps.
const LEGACY_BACKGROUND: Color = Color::new(255, 255, 255, 255);
const LEGACY_BACKDROP: Color = Color::new(0, 0, 0, 255);
const LEGACY_DIM: f32 = 0.3;
const LEGACY_GRABBER: Color = Color::new(60, 60, 67, 77);

impl Default for SheetStyle {
  fn default() -> Self {
    let look = EngineLook::of::<Self>(&[]);
    Self {
      background: look.background(SheetNode::Panel, LEGACY_BACKGROUND),
      corner_radius: 20.0,
      backdrop: look.background(SheetNode::Backdrop, LEGACY_BACKDROP),
      dim: look.opacity(SheetNode::Backdrop, LEGACY_DIM),
      grabber: false,
      grabber_color: look.background(SheetNode::Grabber, LEGACY_GRABBER),
      grabber_width: 36.0,
      grabber_height: 5.0,
      grabber_top: 5.0,
      top_margin: 10.0,
      max_width: f32::INFINITY,
      duration: Duration::from_millis(500),
      throw: 0.15,
    }
  }
}

impl Themed for SheetStyle {
  const NAME: &'static str = "phone_sheet";
  type Renderer = ();

  /// The design's colors (`pencil/lurq-design-system.pen`, Mobile/Bottom Sheet): the panel on the background,
  /// its grabber in the color of an input's edge, and the window behind under the scrim, which carries its own
  /// alpha, all of it shown.
  fn recipe() -> Recipe {
    use crate::app::theme::PaletteColor::{Background, Input, Scrim};
    Recipe::new()
      .base(SheetNode::Panel, |s| s.background(Background))
      .base(SheetNode::Grabber, |s| s.background(Input))
      .base(SheetNode::Backdrop, |s| s.background(Scrim).opacity(1.0))
  }
}

impl SheetStyle {
  /// The sheet in the colors of the theme of what is being built.
  pub fn new() -> Self {
    Self::default()
  }

  /// 0.62's colors: the recipe [`UiDefinition::legacy`](crate::ui::UiDefinition::legacy) gives the sheet.
  pub(crate) fn legacy_recipe() -> Recipe {
    Recipe::new()
      .base(SheetNode::Panel, |s| s.background(LEGACY_BACKGROUND))
      .base(SheetNode::Grabber, |s| s.background(LEGACY_GRABBER))
      .base(SheetNode::Backdrop, |s| {
        s.background(LEGACY_BACKDROP).opacity(LEGACY_DIM)
      })
  }

  /// The platform's dark colors of 0.62.
  #[deprecated(
    since = "0.63.0",
    note = "the theme's appearance gives the dark colors: `SheetStyle::new()` built in a dark theme is dark"
  )]
  pub fn dark() -> Self {
    Self {
      background: Color::from_hex("#1C1C1E"),
      grabber_color: Color::new(235, 235, 245, 77),
      backdrop: LEGACY_BACKDROP,
      dim: 0.5,
      ..Self::default()
    }
  }

  /// The platform's sheet of 0.62 for an appearance.
  #[deprecated(
    since = "0.63.0",
    note = "the theme's appearance gives the colors: `SheetStyle::new()` is light or dark as the theme is"
  )]
  #[allow(deprecated)]
  pub fn for_appearance(appearance: crate::app::window::Appearance) -> Self {
    match appearance {
      crate::app::window::Appearance::Light => Self {
        background: LEGACY_BACKGROUND,
        grabber_color: LEGACY_GRABBER,
        backdrop: LEGACY_BACKDROP,
        dim: LEGACY_DIM,
        ..Self::default()
      },
      crate::app::window::Appearance::Dark => Self::dark(),
    }
  }

  pub fn background(mut self, color: Color) -> Self {
    self.background = color;
    self
  }

  pub fn corner_radius(mut self, radius: f32) -> Self {
    self.corner_radius = radius;
    self
  }

  pub fn dim(mut self, dim: f32) -> Self {
    self.dim = dim;
    self
  }

  pub fn grabber(mut self, grabber: bool) -> Self {
    self.grabber = grabber;
    self
  }
}

/// What makes a sheet's content when the sheet builds it itself.
type SheetContent = Arc<dyn Fn(&mut Ctx) -> Element + Send + Sync>;

/// A node a sheet draws itself, which [`SheetProps::dress`] is given, and a part of the recipe of
/// [`SheetStyle`]'s colors.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SheetNode {
  /// What is drawn over the window behind the sheet. The sheet sets how much of it shows: in the recipe, the
  /// part's opacity.
  Backdrop,
  /// The sheet itself: what is behind its content, reaching under the window's bottom edge.
  Panel,
  /// The bar at the sheet's top that says it can be dragged.
  Grabber,
}

names!(SheetNode {
  Backdrop => "backdrop",
  Panel => "panel",
  Grabber => "grabber",
});

/// What dresses the nodes a sheet draws itself: the look of a design system's sheet in place of the colors of
/// [`SheetStyle`].
pub type SheetDress = Arc<dyn Fn(SheetNode, Column) -> Column + Send + Sync>;

#[derive(Clone)]
pub struct SheetProps {
  open: Signal<bool>,
  detents: Vec<SheetDetent>,
  detent: Option<Signal<usize>>,
  style: SheetStyle,
  dismissable: bool,
  /// Whether Escape puts the sheet away, where it is not as [`SheetProps::dismissable`] says.
  escape: Option<bool>,
  takes_focus: bool,
  dress: Option<SheetDress>,
  scroll: Option<ScrollState>,
  /// What makes the content, for a sheet whose content is made in it ([`Sheet::mount_with`]).
  content: Option<SheetContent>,
  /// What a person putting the sheet away calls, in order: see [`SheetProps::on_dismiss`].
  on_dismiss: Vec<Arc<dyn Fn() + Send + Sync>>,
}

impl PartialEq for SheetProps {
  fn eq(&self, other: &Self) -> bool {
    let same_scroll = match (&self.scroll, &other.scroll) {
      (None, None) => true,
      (Some(a), Some(b)) => a.same(b),
      _ => false,
    };
    self.open.id() == other.open.id()
      && self.detents == other.detents
      && self.detent.as_ref().map(Signal::id) == other.detent.as_ref().map(Signal::id)
      && self.style == other.style
      && self.dismissable == other.dismissable
      && self.escape == other.escape
      && self.takes_focus == other.takes_focus
      && match (&self.dress, &other.dress) {
        (None, None) => true,
        (Some(a), Some(b)) => Arc::ptr_eq(a, b),
        _ => false,
      }
      && same_scroll
      && match (&self.content, &other.content) {
        (None, None) => true,
        (Some(a), Some(b)) => Arc::ptr_eq(a, b),
        _ => false,
      }
      && self.on_dismiss.len() == other.on_dismiss.len()
      && self
        .on_dismiss
        .iter()
        .zip(&other.on_dismiss)
        .all(|(a, b)| Arc::ptr_eq(a, b))
  }
}

#[cfg(feature = "devtools")]
impl crate::app::component::DevtoolsInspectable for SheetProps {
  fn write_info(&self, _buffer: &mut Vec<crate::app::component::ComponentInfo>) {}
}

impl SheetProps {
  /// A sheet that is up while `open` is set, as high as its content.
  pub fn new(open: Signal<bool>) -> Self {
    Self {
      open,
      detents: vec![SheetDetent::Content],
      detent: None,
      style: SheetStyle::default(),
      dismissable: true,
      escape: None,
      takes_focus: false,
      dress: None,
      scroll: None,
      content: None,
      on_dismiss: Vec::new(),
    }
  }

  /// The heights the sheet stands at. It comes up at the first; a finger moves it between them.
  pub fn detents(mut self, detents: impl IntoIterator<Item = SheetDetent>) -> Self {
    let detents: Vec<SheetDetent> = detents.into_iter().collect();
    if !detents.is_empty() {
      self.detents = detents;
    }
    self
  }

  /// Which of [`SheetProps::detents`] the sheet is at, by its place in them: the sheet goes where the signal
  /// says, and says here where a finger put it.
  pub fn detent(mut self, detent: Signal<usize>) -> Self {
    self.detent = Some(detent);
    self
  }

  pub fn style(mut self, style: SheetStyle) -> Self {
    self.style = style;
    self
  }

  /// Whether a tap beside the sheet, a drag down and Escape put it away. A sheet that is not dismissable goes
  /// down only when its signal is cleared.
  pub fn dismissable(mut self, dismissable: bool) -> Self {
    self.dismissable = dismissable;
    self
  }

  /// Whether Escape puts the sheet away, over what [`SheetProps::dismissable`] says of it.
  pub fn dismiss_on_escape(mut self, dismiss: bool) -> Self {
    self.escape = Some(dismiss);
    self
  }

  /// Whether the focus goes into the sheet as it comes up, to its first stop of Tab, and back to what had it
  /// as it goes down, as `Modal::takes_focus` has it. Off by default.
  pub fn takes_focus(mut self, takes: bool) -> Self {
    self.takes_focus = takes;
    self
  }

  /// What dresses the nodes the sheet draws itself, the backdrop, the panel and the grabber, after the sheet
  /// has given them their place and the colors of its style: a design system's edge, corners, colors and
  /// shadow. The sheet still says how much of the backdrop shows and where the panel is.
  pub fn dress(mut self, dress: impl Fn(SheetNode, Column) -> Column + Send + Sync + 'static) -> Self {
    self.dress = Some(Arc::new(dress));
    self
  }

  /// What runs after a person put the sheet away, its signal set to `false` first: a finger dragging it down
  /// and away, a tap beside it, Escape wherever the focus is. Not when the app clears the signal. A second
  /// handler is called after the first.
  pub fn on_dismiss(mut self, handler: impl Fn() + Send + Sync + 'static) -> Self {
    self.on_dismiss.push(Arc::new(handler));
    self
  }

  /// The state of the list the sheet's content scrolls in. With it a finger that goes down on the list drags
  /// the sheet only when the list is at its top, and one that goes up scrolls the list only when the sheet is
  /// at its highest.
  pub fn scroll(mut self, scroll: ScrollState) -> Self {
    self.scroll = Some(scroll);
    self
  }
}

#[derive(Clone, Copy, PartialEq, Debug)]
enum Phase {
  /// Down, and not in the tree.
  Closed,
  /// Coming up; `started` once a frame was laid out with it under the window.
  Entering { started: bool },
  /// At rest at a detent, or under a finger.
  Open,
  /// On its way to a detent.
  Moving,
  /// Going down.
  Leaving,
}

struct State {
  phase: Phase,
  /// The sheet was first rendered and waits for its frame to set off.
  begin_due: bool,
  /// The speed a finger let the sheet go with, towards where it is going, as a share of the way left per the
  /// move's duration.
  velocity: f64,
  /// The detent last rendered.
  at: usize,
  /// How far the fingers had gone when they took the sheet, and where the sheet was then; `None` when no
  /// finger has it.
  held: Option<f32>,
  /// How high the content was last laid out, when the sheet is as high as its content, less what it was
  /// padded by at the bottom then: the padding changes with the keyboard, frame by frame, and the sheet with
  /// it in the same frame.
  content_height: f32,
  padded_by: f32,
  /// Where the sheet's top is at each detent, and where it is when down, as last rendered.
  tops: Vec<f32>,
  room: f32,
  /// How far the window behind draws back for this sheet, as rendered and as last told to the host.
  receded: Receded,
  told: Receded,
  host: Option<Behind>,
}

/// How far the content of a [`SheetHost`] is drawn back, from 0 to 1, and how it gets there.
#[derive(Clone, Copy, PartialEq, Debug)]
struct Receded {
  share: f32,
  pace: Duration,
  curve: Easing,
}

#[cfg(feature = "devtools")]
impl crate::app::component::DevtoolsInspectable for Receded {
  fn write_info(&self, _buffer: &mut Vec<crate::app::component::ComponentInfo>) {}
}

impl Receded {
  const NONE: Self = Self {
    share: 0.0,
    pace: Duration::ZERO,
    curve: Easing::Linear,
  };
}

/// What a [`SheetHost`] gives the sheets under it: where they say how far its content draws back.
#[derive(Clone)]
struct Behind {
  receded: Signal<Receded>,
}

/// The list a sheet's own content scrolls in, for a sheet that was not told it: a stack of screens in the
/// sheet says which list its top screen has, and a finger at that list's top is the sheet's.
#[derive(Clone, Default)]
pub(crate) struct SheetScroll(pub(crate) Arc<Mutex<Option<ScrollState>>>);

/// No finger has the sheet.
const NO_DRAG: f32 = f32::MIN;

/// The engine's phone sheet: a panel that comes up from the bottom over the window, stands at its detents and
/// follows a finger. It is what [`ui::Sheet`](crate::ui::Sheet) builds its bottom sheet on; an app normally wants
/// that, or [`ui::Drawer`](crate::ui::Drawer), which are drawn in the design system's recipes. This one draws
/// itself in [`SheetStyle`]'s colors, or in what [`SheetProps::dress`] makes of its nodes.
pub struct Sheet {
  state: Arc<Mutex<State>>,
  changed: Signal<u64>,
  /// How far a finger has the sheet from where it stands, down being more, or [`NO_DRAG`].
  drag: Signal<f32>,
  /// The detent of a sheet whose props name no signal for it.
  detent: Signal<usize>,
  begin: Timeout,
  settle: Timeout,
  content: ElementRef,
  scroll: SheetScroll,
}

impl Sheet {
  /// A sheet with `content`. It takes no room where it is mounted: it is laid over the window.
  pub fn mount(ctx: &mut Ctx, props: SheetProps, content: impl Into<Element>) -> Element {
    ctx.mount_with::<Self>(props, vec![content.into()])
  }

  /// A sheet whose content is made in it, as a route's is in its outlet. It is the way to put a stack of
  /// screens in a sheet: what `content` mounts is the sheet's own, so a `StackOutlet` there has its bar at the
  /// sheet's top, with nothing of the window's edges to keep clear of (`ctx.safe_area()` is nothing inside a
  /// sheet).
  pub fn mount_with(
    ctx: &mut Ctx,
    mut props: SheetProps,
    content: impl Fn(&mut Ctx) -> Element + Send + Sync + 'static,
  ) -> Element {
    props.content = Some(Arc::new(content));
    ctx.mount::<Self>(props)
  }

  /// [`Sheet::mount_with`], told apart from its siblings by `key`.
  pub fn mount_keyed_with(
    ctx: &mut Ctx,
    key: &str,
    mut props: SheetProps,
    content: impl Fn(&mut Ctx) -> Element + Send + Sync + 'static,
  ) -> Element {
    props.content = Some(Arc::new(content));
    ctx.mount_keyed::<Self>(key, props)
  }

  /// [`Sheet::mount`], told apart from its siblings by `key`.
  pub fn mount_keyed(ctx: &mut Ctx, key: &str, props: SheetProps, content: impl Into<Element>) -> Element {
    ctx.mount_keyed_with::<Self>(key, props, vec![content.into()])
  }
}

/// How high the sheet stands at `detent`, in a window `room` high whose highest sheet is `large` high.
/// The on-screen keyboard is under the sheet: a sheet rises by the `keyboard`'s height, as far as it can.
fn height_of(detent: SheetDetent, room: f32, large: f32, bottom: f32, keyboard: f32, content: f32) -> f32 {
  let height = match detent {
    SheetDetent::Medium => room * 0.5 + keyboard,
    SheetDetent::Large => large,
    SheetDetent::Fraction(share) => large * share.clamp(0.0, 1.0) + keyboard,
    SheetDetent::Height(height) => height + bottom,
    SheetDetent::Content => content + bottom,
  };
  height.clamp(0.0, large.max(0.0))
}

impl Component for Sheet {
  type Props = SheetProps;

  fn create(ctx: &mut Ctx) -> Self {
    // The sheet keeps its content clear of the window's edges itself.
    ctx.provide(crate::app::ctx::SafeAreaTaken);
    let scroll = SheetScroll::default();
    ctx.provide(scroll.clone());
    let state = Arc::new(Mutex::new(State {
      phase: Phase::Closed,
      begin_due: false,
      velocity: 0.0,
      at: 0,
      held: None,
      content_height: 0.0,
      padded_by: 0.0,
      tops: Vec::new(),
      room: 0.0,
      receded: Receded::NONE,
      told: Receded::NONE,
      host: None,
    }));
    let changed = Signal::new(0u64);
    let begin = ctx.create_timeout(BEGIN, {
      let (state, changed) = (state.clone(), changed.clone());
      move || {
        if let Phase::Entering { started } = &mut state.lock().phase {
          *started = true;
        }
        changed.update(|version| *version += 1);
      }
    });
    let duration = ctx.props::<SheetProps>().style.duration;
    let settle = ctx.create_timeout(duration + SETTLE_AFTER, {
      let (state, changed) = (state.clone(), changed.clone());
      move || {
        {
          let mut state = state.lock();
          state.phase = match state.phase {
            Phase::Leaving | Phase::Closed => Phase::Closed,
            _ => Phase::Open,
          };
          state.velocity = 0.0;
        }
        changed.update(|version| *version += 1);
      }
    });
    Self {
      state,
      changed,
      drag: Signal::new(NO_DRAG),
      detent: Signal::new(0),
      begin,
      settle,
      content: ElementRef::default(),
      scroll,
    }
  }

  fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
    let props = ctx.props::<SheetProps>().clone();
    let style = props.style;
    let open = props.open.get();
    let _ = self.changed.get();
    let drag = self.drag.get();
    let detent = props.detent.clone().unwrap_or_else(|| self.detent.clone());
    let at = detent.get().min(props.detents.len() - 1);

    let window = ctx.window();
    // A sheet over the whole window is laid out under the title bar the app draws, as every modal is.
    let room = (window.logical_height() - window.title_bar_inset()).max(0.0);
    let safe_area = window.safe_area;
    let large = room - safe_area.top - style.top_margin;

    let mut state = self.state.lock();
    match (open, state.phase) {
      (true, Phase::Closed) => {
        state.phase = Phase::Entering { started: false };
        state.velocity = 0.0;
        state.held = None;
        // It sets off once this frame, with the sheet under the window, is laid out: `after_layout`.
        state.begin_due = true;
        self.settle.restart();
      }
      (true, Phase::Leaving) => {
        state.phase = Phase::Moving;
        self.settle.restart();
      }
      (false, Phase::Entering { .. } | Phase::Open | Phase::Moving) => {
        state.phase = Phase::Leaving;
        state.held = None;
        // What was typed into in the sheet is no longer: the keyboard goes down with the sheet.
        ctx.blur();
        self.begin.cancel();
        self.settle.restart();
      }
      _ => {}
    }
    if state.phase == Phase::Open && state.at != at {
      // Sent to another height by the signal.
      state.phase = Phase::Moving;
      self.settle.restart();
    }
    state.at = at;
    state.host = ctx.use_context::<Behind>();
    if state.phase == Phase::Closed {
      state.receded = Receded::NONE;
      return Element::from(Modal::new(Element::new()).open_when(false));
    }

    let heights: Vec<f32> = props
      .detents
      .iter()
      .map(|detent| {
        height_of(
          *detent,
          room,
          large,
          safe_area.bottom,
          safe_area.keyboard,
          state.content_height,
        )
      })
      .collect();
    state.tops = heights.iter().map(|height| room - height).collect();
    state.room = room;
    let height = heights[at];
    let highest = heights.iter().copied().fold(0.0, f32::max);
    let lowest = heights.iter().copied().fold(f32::INFINITY, f32::min);

    // Where the sheet's top is: under the window before it sets off and when it goes, at its height
    // otherwise, and as far from there as a finger has it. Past its highest place it gives way less and less.
    let dragged = drag != NO_DRAG;
    // With motion reduced the sheet does not cross the window: it fades in where it stands, and out.
    let reduce_motion = window.system.reduce_motion;
    let away = matches!(state.phase, Phase::Entering { started: false } | Phase::Leaving);
    let top = match state.phase {
      Phase::Entering { started: false } | Phase::Leaving if !reduce_motion => room,
      _ if dragged => {
        let top = room - height + drag;
        let limit = room - highest;
        if top < limit {
          let over = limit - top;
          limit - over * RESISTANCE * room / (room + RESISTANCE * over)
        } else if !props.dismissable && top > room - lowest {
          let (limit, over) = (room - lowest, top - (room - lowest));
          limit + over * RESISTANCE * room / (room + RESISTANCE * over)
        } else {
          top
        }
      }
      _ => room - height,
    };
    let moving = !dragged
      && matches!(
        state.phase,
        Phase::Entering { started: true } | Phase::Moving | Phase::Leaving
      );
    // Every node that moves has its transition from its first frame; put where a finger has it, or where it
    // sets off from, the transition takes no time.
    let pace = if moving { style.duration } else { Duration::ZERO };
    let curve = Easing::Spring {
      velocity: state.velocity,
    };
    // How much of the lowest height is in view: the window behind dims by as much.
    let up = if reduce_motion && away {
      0.0
    } else if lowest > 0.0 {
      ((room - top) / lowest).clamp(0.0, 1.0)
    } else {
      0.0
    };
    let fits_content = props.detents[at] == SheetDetent::Content;
    state.padded_by = safe_area.bottom;
    // A sheet that takes all the room sends the window behind back, by as much of the way from its next
    // height down, or from the bottom, as it has come.
    let reaches = highest >= large - 1.0 && large > 0.0;
    let under = heights
      .iter()
      .copied()
      .filter(|height| *height < highest - 1.0)
      .fold(0.0, f32::max);
    state.receded = Receded {
      share: if reaches {
        ((room - top - under) / (highest - under)).clamp(0.0, 1.0)
      } else {
        0.0
      },
      pace,
      curve,
    };
    drop(state);

    let dress = |node: SheetNode, column: Column| match &props.dress {
      Some(dress) => dress(node, column),
      None => column,
    };
    let backdrop = Column::new().size(FILL, FILL).background(style.backdrop);
    let backdrop = dress(SheetNode::Backdrop, backdrop)
      .opacity(style.dim * up)
      .transition(Transition::opacity().duration(pace).easing(curve))
      .on_click({
        let (open, dismissable, told) = (props.open.clone(), props.dismissable, props.on_dismiss.clone());
        move |_| {
          if dismissable {
            open.set(false);
            for handler in &told {
              handler();
            }
          }
        }
      });

    // The content, in the room the sheet has at its height, clear of the home indicator and the keyboard. A
    // sheet as high as its content lets the content say how high that is.
    let mut content = Column::new()
      .ref_element(self.content.clone())
      .width(FILL)
      .padding_bottom(safe_area.bottom)
      .padding_left(safe_area.left)
      .padding_right(safe_area.right);
    content = if fits_content {
      content.max_height(large.max(0.0))
    } else {
      // Between two of its heights the content is as high as what of the sheet is in the window, so that what
      // stands at its bottom stays at the window's bottom: under a finger at once, and on the way to a height
      // as the sheet's top goes there, by the same curve. Never higher than its highest place, past which a
      // finger only pulls the sheet a little, nor lower than its lowest, under which it is on its way out.
      let shown = if dragged && !away {
        (room - top).clamp(lowest, highest)
      } else {
        height
      };
      content
        .height(shown)
        .transition(Transition::height().duration(pace).easing(curve))
    };
    if let Some(build) = &props.content {
      content = content.child(build(ctx));
    }
    for child in ctx.children() {
      content = content.child(child.clone());
    }
    let mut body = Stack::new().width(FILL).child(content.clip());
    if style.grabber {
      body = body.child(
        Row::new()
          .width(FILL)
          .padding_top(style.grabber_top)
          .justify(crate::layout::layout_kind::Justify::Center)
          .pointer_events_none()
          .child(dress(
            SheetNode::Grabber,
            Column::new()
              .width(style.grabber_width)
              .height(style.grabber_height)
              .rounded(style.grabber_height / 2.0)
              .background(style.grabber_color),
          )),
      );
    }

    let panel = Column::new()
      .id("sheet")
      .width(FILL)
      .max_width(style.max_width)
      .height(room + UNDER)
      .background(style.background)
      .rounded(style.corner_radius)
      .clip();
    let panel = dress(SheetNode::Panel, panel)
      .child(body)
      .opacity(if reduce_motion && away { 0.0 } else { 1.0 })
      .transform(Transform2D::translate(0.0, top))
      .transition(Transition::transform().duration(pace).easing(curve))
      .transition(Transition::opacity().duration(pace).easing(curve))
      // A press on the sheet is the sheet's: it is not a tap beside it.
      .on_click(|_| {})
      .on_pan({
        let (state, drag, changed) = (self.state.clone(), self.drag.clone(), self.changed.clone());
        let (open, detent, settle) = (props.open.clone(), detent.clone(), self.settle.clone());
        let (told, found, dismissable) = (props.scroll.clone(), self.scroll.clone(), props.dismissable);
        let dismissed = props.on_dismiss.clone();
        move |event: PanEvent| {
          let mut state = state.lock();
          match event.phase {
            GesturePhase::Start => {
              if state.phase != Phase::Open || event.fingers != 1 {
                return;
              }
              if event.translation_y.abs() <= event.translation_x.abs() {
                return;
              }
              let top = state.tops.get(state.at).copied().unwrap_or(state.room);
              let highest = state.tops.iter().copied().fold(f32::INFINITY, f32::min);
              let at_highest = top <= highest + 0.5;
              let takes = if event.translation_y > 0.0 {
                // Down: the content's while it has something above to show.
                let scroll = told.clone().or_else(|| found.0.lock().clone());
                scroll.is_none_or(|scroll| scroll.scroll_y() <= 0.0)
              } else {
                !at_highest
              };
              if !takes {
                return;
              }
              // The sheet's: the fingers neither scroll nor click.
              event.prevent_default();
              event.stop_propagation();
              state.held = Some(event.translation_y);
              drop(state);
              drag.set(0.0);
            }
            GesturePhase::Change => {
              if let Some(from) = state.held {
                event.stop_propagation();
                drop(state);
                drag.set(event.translation_y - from);
              }
            }
            GesturePhase::End => {
              let Some(from) = state.held.take() else {
                return;
              };
              event.stop_propagation();
              let stands = state.tops.get(state.at).copied().unwrap_or(state.room);
              let highest = state.tops.iter().copied().fold(f32::INFINITY, f32::min);
              let now = (stands + event.translation_y - from).max(highest);
              // Where it is going: the height, or the way down, nearest to where the finger threw it.
              let thrown = now + event.velocity_y * style.throw;
              let mut goes = (None, state.room);
              let mut nearest = if dismissable {
                (thrown - state.room).abs()
              } else {
                f32::INFINITY
              };
              for (index, top) in state.tops.iter().enumerate() {
                if (thrown - top).abs() < nearest {
                  nearest = (thrown - top).abs();
                  goes = (Some(index), *top);
                }
              }
              let left = goes.1 - now;
              state.velocity = if left.abs() > 1.0 {
                f64::from((event.velocity_y * style.duration.as_secs_f32() / left).max(0.0))
              } else {
                0.0
              };
              state.phase = Phase::Moving;
              let at = state.at;
              drop(state);
              drag.set(NO_DRAG);
              settle.restart();
              match goes.0 {
                Some(index) if index != at => detent.set(index),
                Some(_) => changed.update(|version| *version += 1),
                None => {
                  open.set(false);
                  for handler in &dismissed {
                    handler();
                  }
                }
              }
            }
          }
        }
      });

    let layer = Stack::new()
      .size(FILL, FILL)
      .stack_align(StackAlignment::TopCenter)
      .child(backdrop)
      .child(panel);
    let mut modal = Modal::new(layer)
      .open_when(true)
      .target(Root)
      .takes_focus(props.takes_focus);
    modal = if props.escape.unwrap_or(props.dismissable) {
      let told = props.on_dismiss.clone();
      let modal = modal.dismisses(props.open.clone());
      if told.is_empty() {
        modal
      } else {
        modal.on_dismiss(move || {
          for handler in &told {
            handler();
          }
        })
      }
    } else {
      modal.dismiss_on_escape(false)
    };
    modal.into()
  }

  fn after_layout(&self) {
    let mut state = self.state.lock();
    if state.receded != state.told {
      state.told = state.receded;
      if let Some(host) = &state.host {
        host.receded.set(state.receded);
      }
    }
    if state.phase == Phase::Closed {
      return;
    }
    let mut changed = false;
    if self.content.is_attached() {
      let height = (self.content.rect().3 - state.padded_by).max(0.0);
      if (state.content_height - height).abs() > 0.25 {
        state.content_height = height;
        changed = true;
      }
    }
    if std::mem::take(&mut state.begin_due) {
      self.begin.restart();
    }
    drop(state);
    if changed {
      self.changed.update(|version| *version += 1);
    }
  }
}

/// How the content of a [`SheetHost`] draws back behind a sheet that takes all the room. Its color comes from the
/// theme, through the recipe it keeps under the name `phone_sheet_host` ([`SheetHostPart`]).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SheetHostStyle {
  /// How small the content gets: a share of its size. 1 leaves it as it is.
  pub scale: f32,
  /// How round its corners get.
  pub corner_radius: f32,
  /// What is seen around it.
  pub background: Color,
}

/// The parts of the recipe of [`SheetHostStyle`]'s colors.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SheetHostPart {
  /// What is seen around the content as it draws back.
  Root,
}

names!(SheetHostPart { Root => "root" });

/// What is seen around a window's content drawn back behind a sheet, in 0.62 and in the design alike.
const HOST_BLACK: Color = Color::new(0, 0, 0, 255);

impl Themed for SheetHostStyle {
  const NAME: &'static str = "phone_sheet_host";
  type Renderer = ();

  /// Black around the content in the light look and in the dark one, as the platform's: the board draws no
  /// host, and no role is the color of a screen with nothing lit.
  fn recipe() -> Recipe {
    Recipe::new().base(SheetHostPart::Root, |s| s.background(HOST_BLACK))
  }
}

impl SheetHostStyle {
  /// 0.62's color: the recipe [`UiDefinition::legacy`](crate::ui::UiDefinition::legacy) gives the host.
  pub(crate) fn legacy_recipe() -> Recipe {
    Self::recipe()
  }
}

impl Default for SheetHostStyle {
  fn default() -> Self {
    let look = EngineLook::of::<Self>(&[]);
    Self {
      scale: 0.92,
      corner_radius: 12.0,
      background: look.background(SheetHostPart::Root, HOST_BLACK),
    }
  }
}

/// What a [`SheetHost`] is made with: how it looks, and what makes its content.
#[derive(Clone)]
pub struct SheetHostProps {
  style: SheetHostStyle,
  content: SheetContent,
}

impl PartialEq for SheetHostProps {
  fn eq(&self, other: &Self) -> bool {
    self.style == other.style && Arc::ptr_eq(&self.content, &other.content)
  }
}

#[cfg(feature = "devtools")]
impl crate::app::component::DevtoolsInspectable for SheetHostProps {
  fn write_info(&self, _buffer: &mut Vec<crate::app::component::ComponentInfo>) {}
}

/// The content of a window that draws back behind a sheet at its full height, as a phone's apps do: it gets
/// smaller, its top goes under the status bar's room and its corners round. Put it around the whole of the
/// app's content; the sheets mounted in that content tell it how far they are up. Without it a sheet only dims
/// what is behind.
pub struct SheetHost {
  receded: Signal<Receded>,
}

impl SheetHost {
  /// The host around what `content` makes. The content is made in the host, as a route's is in its outlet:
  /// that is what lets the sheets in it find the host.
  pub fn mount(ctx: &mut Ctx, content: impl Fn(&mut Ctx) -> Element + Send + Sync + 'static) -> Element {
    Self::mount_with(ctx, SheetHostStyle::default(), content)
  }

  pub fn mount_with(
    ctx: &mut Ctx,
    style: SheetHostStyle,
    content: impl Fn(&mut Ctx) -> Element + Send + Sync + 'static,
  ) -> Element {
    ctx.mount::<Self>(SheetHostProps {
      style,
      content: Arc::new(content),
    })
  }
}

impl Component for SheetHost {
  type Props = SheetHostProps;

  fn create(ctx: &mut Ctx) -> Self {
    let receded = Signal::new(Receded::NONE);
    ctx.provide(Behind {
      receded: receded.clone(),
    });
    Self { receded }
  }

  fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
    let props = ctx.props::<SheetHostProps>().clone();
    let style = props.style;
    let receded = self.receded.get();
    let window = ctx.window();
    let (room, top) = (window.logical_height(), window.safe_area.top);
    // Smaller about its middle, and up or down so that its top is where the status bar's room ends.
    let scale = 1.0 - (1.0 - style.scale) * receded.share;
    let down = receded.share * (top - room * (1.0 - style.scale) / 2.0);
    let content = Stack::new()
      .size(FILL, FILL)
      .rounded(style.corner_radius * receded.share)
      .clip()
      .transform(Transform2D::translate(0.0, down).then(&Transform2D::scale_uniform(scale)))
      .transition(Transition::transform().duration(receded.pace).easing(receded.curve))
      .child((props.content)(ctx));
    Stack::new()
      .size(FILL, FILL)
      .background(style.background)
      .child(content)
  }
}