iced-cube 0.0.8

Themeable application components for the iced GUI library, with Lucide icons
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
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
//! Floats a panel next to an anchor element: the one layer popovers, menus,
//! the combobox and select lists, and the command list's keys are built on.
//!
//! [`anchored`] wraps an anchor, such as a trigger button or a text field,
//! and while it has content draws that content above everything else.
//! [`place`] is the pure positioning logic: it puts the panel on one
//! [`Side`] of the anchor, aligned by [`Align`], then flips and shifts it to
//! stay inside the window.
//!
//! Every open panel follows the same rules:
//!
//! - Events reach the content first, including panels nested inside it, so
//!   Escape closes the innermost layer.
//! - [`on_key`](Anchored::on_key) sees the key presses the content leaves,
//!   while the panel is open or something in the anchor has focus.
//! - [`on_dismiss`](Anchored::on_dismiss) is sent at most once per event: on
//!   a [dismiss chord](Anchored::dismiss_keys), a press outside the panel and
//!   the anchor, or, with [`dismiss_on_blur`](Anchored::dismiss_on_blur),
//!   when the anchor loses focus.
//! - That outside press is captured, so nothing underneath sees it, unless
//!   the panel [passes it through](Anchored::pass_through).
//! - Presses on the anchor are left to the anchor, so a trigger can toggle
//!   the panel itself. Presses inside the panel never reach the widgets
//!   underneath it.

use iced::advanced::layout::{self, Layout};
use iced::advanced::overlay;
use iced::advanced::renderer;
use iced::advanced::widget::operation::Focusable;
use iced::advanced::widget::{Id, Operation, Tree, Widget, tree};
use iced::advanced::{Clipboard, Shell};
use iced::keyboard::{self, key::Named};
use iced::widget::container;
use iced::{
    Background, Border, Color, Element, Event, Length, Point, Rectangle, Renderer, Shadow, Size,
    Theme, Vector, mouse, touch,
};

use crate::keys::{self, Chord};
use crate::theme::{Tokens, fade, radius};

/// Default space between the anchor and the panel, in logical pixels.
pub const GAP: f32 = 4.0;

/// Space kept between the panel and the edges of the window.
pub const MARGIN: f32 = 8.0;

/// The side of the anchor the panel appears on.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Side {
    Top,
    #[default]
    Bottom,
    Left,
    Right,
}

impl Side {
    pub const ALL: [Side; 4] = [Side::Top, Side::Bottom, Side::Left, Side::Right];

    pub fn opposite(self) -> Side {
        match self {
            Side::Top => Side::Bottom,
            Side::Bottom => Side::Top,
            Side::Left => Side::Right,
            Side::Right => Side::Left,
        }
    }

    fn is_vertical(self) -> bool {
        matches!(self, Side::Top | Side::Bottom)
    }
}

/// How the panel lines up with the anchor along that side.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Align {
    /// Left edges meet (or top edges, on the left and right sides).
    Start,
    #[default]
    Center,
    /// Right edges meet (or bottom edges, on the left and right sides).
    End,
}

impl Align {
    pub const ALL: [Align; 3] = [Align::Start, Align::Center, Align::End];

    fn mirrored(self) -> Align {
        match self {
            Align::Start => Align::End,
            Align::Center => Align::Center,
            Align::End => Align::Start,
        }
    }
}

/// Where a panel sits relative to its anchor.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Placement {
    pub side: Side,
    pub align: Align,
    /// Space between the anchor and the panel.
    pub gap: f32,
    /// Shift along the side, away from the aligned edge.
    pub offset: f32,
}

impl Default for Placement {
    fn default() -> Self {
        Self {
            side: Side::default(),
            align: Align::default(),
            gap: GAP,
            offset: 0.0,
        }
    }
}

impl Placement {
    pub fn new(side: Side, align: Align) -> Self {
        Self {
            side,
            align,
            ..Self::default()
        }
    }

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

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

/// Positions a panel of `size` next to `anchor`, keeping it inside
/// `viewport` less [`MARGIN`].
///
/// The panel moves to the opposite side when it does not fit on the
/// requested one and does fit there, and to the mirrored alignment when it
/// would overflow along the side. A panel on the left or right that fits on
/// neither moves below the anchor, or above it, rather than covering it.
/// Whatever still overflows is shifted back inside, pinned to the top left
/// if the panel is larger than the window.
pub fn place(
    anchor: Rectangle,
    size: Size,
    viewport: Rectangle,
    placement: Placement,
) -> Rectangle {
    let area = viewport.shrink(MARGIN);
    let side = choose_side(anchor, size, area, placement);
    // The offset runs along the requested side, so it does not carry over
    // to a side across it.
    let offset = if side.is_vertical() == placement.side.is_vertical() {
        placement.offset
    } else {
        0.0
    };

    let main = match side {
        Side::Top => anchor.y - placement.gap - size.height,
        Side::Bottom => anchor.y + anchor.height + placement.gap,
        Side::Left => anchor.x - placement.gap - size.width,
        Side::Right => anchor.x + anchor.width + placement.gap,
    };

    let (start, length, extent, low, high) = if side.is_vertical() {
        (
            anchor.x,
            anchor.width,
            size.width,
            area.x,
            area.x + area.width,
        )
    } else {
        (
            anchor.y,
            anchor.height,
            size.height,
            area.y,
            area.y + area.height,
        )
    };
    let cross_at = |align: Align| match align {
        Align::Start => start + offset,
        Align::Center => start + (length - extent) / 2.0 + offset,
        Align::End => start + length - extent - offset,
    };
    let fits = |value: f32| value >= low && value + extent <= high;
    let preferred = cross_at(placement.align);
    let mirrored = cross_at(placement.align.mirrored());
    let cross = if !fits(preferred) && fits(mirrored) {
        mirrored
    } else {
        preferred
    };

    let (x, y) = if side.is_vertical() {
        (cross, main)
    } else {
        (main, cross)
    };
    Rectangle::new(
        Point::new(
            clamp(x, area.x, area.x + area.width - size.width),
            clamp(y, area.y, area.y + area.height - size.height),
        ),
        size,
    )
}

/// The side [`place`] puts the panel on: the requested side, else the
/// opposite one, else (for the left and right) below or above. With no
/// side that fits, the roomier of the requested pair wins, keeping the
/// requested side on a tie.
fn choose_side(anchor: Rectangle, size: Size, area: Rectangle, placement: Placement) -> Side {
    let room = |side: Side| room(anchor, area, placement.gap, side);
    let fits = |side: Side| room(side) >= needed(size, side);
    let roomier = |side: Side| {
        if room(side.opposite()) > room(side) {
            side.opposite()
        } else {
            side
        }
    };

    let requested = placement.side;
    let opposite = requested.opposite();
    if fits(requested) {
        return requested;
    }
    if fits(opposite) {
        return opposite;
    }
    if requested.is_vertical() {
        return roomier(requested);
    }
    [Side::Bottom, Side::Top]
        .into_iter()
        .find(|side| fits(*side))
        .unwrap_or_else(|| roomier(Side::Bottom))
}

/// The panel's extent across `side`, the length that must fit beside it.
fn needed(size: Size, side: Side) -> f32 {
    if side.is_vertical() {
        size.height
    } else {
        size.width
    }
}

/// Space between the anchor and the edge of `area` on one side, less the gap.
fn room(anchor: Rectangle, area: Rectangle, gap: f32, side: Side) -> f32 {
    match side {
        Side::Top => anchor.y - gap - area.y,
        Side::Bottom => area.y + area.height - (anchor.y + anchor.height + gap),
        Side::Left => anchor.x - gap - area.x,
        Side::Right => area.x + area.width - (anchor.x + anchor.width + gap),
    }
}

/// The tallest a panel may be with [`Anchored::fit_height`]: `None` when
/// it fits where [`place`] puts it as it is, otherwise the room on the
/// roomier of above and below, however little, so the panel scrolls rather
/// than covering its anchor. A panel placed on the left or right is only
/// limited once it fits beside the anchor on neither side.
pub fn fitted_height(
    anchor: Rectangle,
    size: Size,
    viewport: Rectangle,
    placement: Placement,
) -> Option<f32> {
    let area = viewport.shrink(MARGIN);
    let side = placement.side;
    let beside = |side: Side| room(anchor, area, placement.gap, side) >= size.width;
    if !side.is_vertical() && (beside(side) || beside(side.opposite())) {
        return None;
    }
    let above = room(anchor, area, placement.gap, Side::Top);
    let below = room(anchor, area, placement.gap, Side::Bottom);
    if above >= size.height || below >= size.height {
        return None;
    }
    Some(above.max(below).max(0.0))
}

/// Keeps `value` within `low..=high`, preferring `low` when the range is empty.
fn clamp(value: f32, low: f32, high: f32) -> f32 {
    value.min(high).max(low)
}

/// The floating surface shared by popovers, menus, lists and dialogs: the
/// popover colour, a subtle border and a restrained shadow.
pub fn surface_style(tokens: &Tokens) -> container::Style {
    container::Style {
        background: Some(Background::Color(tokens.popover)),
        text_color: Some(tokens.foreground),
        border: Border {
            color: tokens.border,
            width: 1.0,
            radius: radius::MD.into(),
        },
        shadow: shadow(tokens),
        snap: true,
    }
}

/// The shadow under every floating surface, stronger on a dark page.
pub fn shadow(tokens: &Tokens) -> Shadow {
    Shadow {
        color: fade(Color::BLACK, if tokens.is_dark { 0.5 } else { 0.1 }),
        offset: Vector::new(0.0, 4.0),
        blur_radius: 12.0,
    }
}

type OnKey<'a, Message> = Box<dyn Fn(&keys::Event) -> Option<Message> + 'a>;

/// How an open panel behaves. Shared with the widgets in this crate that
/// float a panel of their own.
pub(crate) struct Behaviour<'a, Message> {
    pub(crate) placement: Placement,
    pub(crate) point: Option<Point>,
    pub(crate) match_width: bool,
    pub(crate) fit_height: bool,
    pub(crate) on_dismiss: Option<Message>,
    pub(crate) dismiss_keys: Vec<Chord>,
    pub(crate) dismiss_on_anchor_press: bool,
    pub(crate) dismiss_on_blur: bool,
    pub(crate) pass_through: bool,
    /// The panel opens and closes itself through [`State::open`]: a
    /// dismissal or a press the content captured closes it.
    pub(crate) closes_itself: bool,
    pub(crate) on_key: Option<OnKey<'a, Message>>,
    pub(crate) on_anchor_press: Option<Message>,
    pub(crate) on_focus: Option<OnFocus<'a, Message>>,
}

type OnFocus<'a, Message> = Box<dyn Fn(bool) -> Message + 'a>;

impl<Message> Default for Behaviour<'_, Message> {
    fn default() -> Self {
        Self {
            placement: Placement::default(),
            point: None,
            match_width: false,
            fit_height: false,
            on_dismiss: None,
            dismiss_keys: vec![Chord::named(Named::Escape)],
            dismiss_on_anchor_press: false,
            dismiss_on_blur: false,
            pass_through: false,
            closes_itself: false,
            on_key: None,
            on_anchor_press: None,
            on_focus: None,
        }
    }
}

impl<Message> Behaviour<'_, Message> {
    fn can_dismiss(&self) -> bool {
        self.on_dismiss.is_some() || self.closes_itself
    }

    fn watches_focus(&self) -> bool {
        self.on_key.is_some() || self.dismiss_on_blur || self.on_focus.is_some()
    }

    /// The message for a change of focus inside the anchor, if it changed
    /// and anyone listens.
    fn focus_message(&self, was: bool, is: bool) -> Option<Message> {
        if was == is {
            return None;
        }
        self.on_focus.as_ref().map(|on_focus| on_focus(is))
    }
}

/// What an anchor remembers between events.
#[derive(Debug, Default)]
pub(crate) struct State {
    focused: bool,
    /// An outside press dismissed the panel, so the anchor gives up focus
    /// on the next event, without a second dismissal.
    unfocus: bool,
    /// Whether a panel that [closes itself](Behaviour::closes_itself) is open.
    pub(crate) open: bool,
}

/// An anchor with a panel floating next to it. Convert it into an
/// [`Element`] to render.
pub struct Anchored<'a, Message> {
    anchor: Element<'a, Message>,
    content: Option<Element<'a, Message>>,
    behaviour: Behaviour<'a, Message>,
}

impl<Message> std::fmt::Debug for Anchored<'_, Message> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let behaviour = &self.behaviour;
        f.debug_struct("Anchored")
            .field("open", &self.content.is_some())
            .field("placement", &behaviour.placement)
            .field("point", &behaviour.point)
            .field("match_width", &behaviour.match_width)
            .field("fit_height", &behaviour.fit_height)
            .field("dismissable", &behaviour.on_dismiss.is_some())
            .field("dismiss_keys", &behaviour.dismiss_keys)
            .field("pass_through", &behaviour.pass_through)
            .finish_non_exhaustive()
    }
}

/// Wraps `anchor`. Nothing floats until [`content`](Anchored::content) is set.
pub fn anchored<'a, Message>(anchor: impl Into<Element<'a, Message>>) -> Anchored<'a, Message> {
    Anchored {
        anchor: anchor.into(),
        content: None,
        behaviour: Behaviour::default(),
    }
}

impl<'a, Message> Anchored<'a, Message> {
    /// The floating panel. `None` keeps it closed.
    pub fn content(mut self, content: Option<Element<'a, Message>>) -> Self {
        self.content = content;
        self
    }

    pub fn placement(mut self, placement: Placement) -> Self {
        self.behaviour.placement = placement;
        self
    }

    /// Anchors the panel to a point, relative to the anchor's top left
    /// corner, instead of to the anchor's edges.
    pub fn at(mut self, point: Point) -> Self {
        self.behaviour.point = Some(point);
        self
    }

    /// Makes the panel exactly as wide as the anchor, as a list under a
    /// field is.
    pub fn match_width(mut self, match_width: bool) -> Self {
        self.behaviour.match_width = match_width;
        self
    }

    /// When the panel fits on no side of the anchor, limits its height to
    /// the roomier of above and below instead of shifting it over the
    /// anchor; see [`fitted_height`]. For content that scrolls, such as a
    /// long menu.
    pub fn fit_height(mut self, fit: bool) -> Self {
        self.behaviour.fit_height = fit;
        self
    }

    /// Sent once when the panel is dismissed; see the module docs.
    pub fn on_dismiss(self, message: Message) -> Self {
        self.on_dismiss_maybe(Some(message))
    }

    /// Like [`on_dismiss`](Self::on_dismiss); `None` makes the panel
    /// undismissable, so presses outside it pass through.
    pub fn on_dismiss_maybe(mut self, message: Option<Message>) -> Self {
        self.behaviour.on_dismiss = message;
        self
    }

    /// The chords that dismiss the panel when the content and
    /// [`on_key`](Self::on_key) leave them alone. Defaults to Escape. Pass
    /// the chords of a component keymap's close action, so unbinding them
    /// there works.
    pub fn dismiss_keys(mut self, chords: impl IntoIterator<Item = Chord>) -> Self {
        self.behaviour.dismiss_keys = chords.into_iter().collect();
        self
    }

    /// Also dismiss on presses on the anchor itself, for anchors that do
    /// not toggle the panel, such as a context menu area. The press still
    /// reaches the anchor.
    pub fn dismiss_on_anchor_press(mut self, dismiss: bool) -> Self {
        self.behaviour.dismiss_on_anchor_press = dismiss;
        self
    }

    /// Also dismiss when a focused widget inside the anchor, such as a text
    /// field, loses focus.
    pub fn dismiss_on_blur(mut self, dismiss: bool) -> Self {
        self.behaviour.dismiss_on_blur = dismiss;
        self
    }

    /// Lets a press outside the panel reach the widgets underneath after
    /// dismissing it, for panels that are not modal, such as a popover.
    pub fn pass_through(mut self, pass_through: bool) -> Self {
        self.behaviour.pass_through = pass_through;
        self
    }

    /// Resolves key presses the content leaves, while the panel is open or
    /// something in the anchor has focus. Returning a message sends it and
    /// captures the key.
    pub fn on_key(mut self, on_key: impl Fn(&keys::Event) -> Option<Message> + 'a) -> Self {
        self.behaviour.on_key = Some(Box::new(on_key));
        self
    }

    /// Sent with `true` when a widget inside the anchor, such as a text
    /// field, gains focus, and with `false` when it loses it.
    pub fn on_focus(mut self, on_focus: impl Fn(bool) -> Message + 'a) -> Self {
        self.behaviour.on_focus = Some(Box::new(on_focus));
        self
    }

    /// Sent when the pointer is pressed on the anchor, before the anchor
    /// sees the press.
    pub fn on_anchor_press_maybe(mut self, message: Option<Message>) -> Self {
        self.behaviour.on_anchor_press = message;
        self
    }
}

impl<'a, Message: Clone + 'a> From<Anchored<'a, Message>> for Element<'a, Message> {
    fn from(anchored: Anchored<'a, Message>) -> Self {
        Element::new(anchored)
    }
}

impl<Message: Clone> Widget<Message, Theme, Renderer> for Anchored<'_, Message> {
    fn tag(&self) -> tree::Tag {
        tree::Tag::of::<State>()
    }

    fn state(&self) -> tree::State {
        tree::State::new(State::default())
    }

    fn size(&self) -> Size<Length> {
        self.anchor.as_widget().size()
    }

    fn size_hint(&self) -> Size<Length> {
        self.anchor.as_widget().size_hint()
    }

    fn children(&self) -> Vec<Tree> {
        std::iter::once(&self.anchor)
            .chain(&self.content)
            .map(Tree::new)
            .collect()
    }

    fn diff(&self, tree: &mut Tree) {
        match &self.content {
            Some(content) => tree.diff_children(&[&self.anchor, content]),
            None => tree.diff_children(&[&self.anchor]),
        }
    }

    fn layout(
        &mut self,
        tree: &mut Tree,
        renderer: &Renderer,
        limits: &layout::Limits,
    ) -> layout::Node {
        self.anchor
            .as_widget_mut()
            .layout(&mut tree.children[0], renderer, limits)
    }

    fn draw(
        &self,
        tree: &Tree,
        renderer: &mut Renderer,
        theme: &Theme,
        style: &renderer::Style,
        layout: Layout<'_>,
        cursor: mouse::Cursor,
        viewport: &Rectangle,
    ) {
        self.anchor.as_widget().draw(
            &tree.children[0],
            renderer,
            theme,
            style,
            layout,
            cursor,
            viewport,
        );
    }

    fn operate(
        &mut self,
        tree: &mut Tree,
        layout: Layout<'_>,
        renderer: &Renderer,
        operation: &mut dyn Operation,
    ) {
        self.anchor
            .as_widget_mut()
            .operate(&mut tree.children[0], layout, renderer, operation);
    }

    fn update(
        &mut self,
        tree: &mut Tree,
        event: &Event,
        layout: Layout<'_>,
        cursor: mouse::Cursor,
        renderer: &Renderer,
        clipboard: &mut dyn Clipboard,
        shell: &mut Shell<'_, Message>,
        viewport: &Rectangle,
    ) {
        let Tree {
            state, children, ..
        } = tree;
        let state = state.downcast_mut::<State>();
        let Some(anchor_tree) = children.first_mut() else {
            return;
        };
        let behaviour = &self.behaviour;

        if state.unfocus {
            state.unfocus = false;
            if let Some(message) = behaviour.focus_message(state.focused, false) {
                shell.publish(message);
            }
            state.focused = false;
            self.anchor
                .as_widget_mut()
                .operate(anchor_tree, layout, renderer, &mut Unfocus);
            shell.request_redraw();
        }

        if state.focused
            && let Some(message) = key_message(behaviour, event)
        {
            shell.publish(message);
            shell.capture_event();
            return;
        }

        if is_press(event)
            && cursor.is_over(layout.bounds())
            && let Some(message) = &behaviour.on_anchor_press
        {
            shell.publish(message.clone());
        }

        self.anchor.as_widget_mut().update(
            anchor_tree,
            event,
            layout,
            cursor,
            renderer,
            clipboard,
            shell,
            viewport,
        );

        if !behaviour.watches_focus() {
            return;
        }
        let mut focus = FindFocus::default();
        self.anchor
            .as_widget_mut()
            .operate(anchor_tree, layout, renderer, &mut focus);
        if state.focused
            && !focus.0
            && behaviour.dismiss_on_blur
            && let Some(message) = &behaviour.on_dismiss
        {
            shell.publish(message.clone());
        }
        if let Some(message) = behaviour.focus_message(state.focused, focus.0) {
            shell.publish(message);
        }
        state.focused = focus.0;
    }

    fn mouse_interaction(
        &self,
        tree: &Tree,
        layout: Layout<'_>,
        cursor: mouse::Cursor,
        viewport: &Rectangle,
        renderer: &Renderer,
    ) -> mouse::Interaction {
        self.anchor.as_widget().mouse_interaction(
            &tree.children[0],
            layout,
            cursor,
            viewport,
            renderer,
        )
    }

    fn overlay<'b>(
        &'b mut self,
        tree: &'b mut Tree,
        layout: Layout<'b>,
        renderer: &Renderer,
        viewport: &Rectangle,
        translation: Vector,
    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
        let Self {
            anchor,
            content,
            behaviour,
        } = self;
        let Tree {
            state, children, ..
        } = tree;
        let mut trees = children.iter_mut();
        let anchor_tree = trees.next()?;
        let trigger = layout.bounds() + translation;

        // While the panel is open the anchor's own overlays, such as its
        // tooltip, stay hidden.
        let Some((content, tree)) = content.as_mut().zip(trees.next()) else {
            return anchor.as_widget_mut().overlay(
                anchor_tree,
                layout,
                renderer,
                viewport,
                translation,
            );
        };
        Some(floating(
            content,
            tree,
            state.downcast_mut::<State>(),
            behaviour,
            trigger,
        ))
    }
}

/// The overlay drawing a panel for `trigger`, the anchor's bounds in
/// window coordinates.
pub(crate) fn floating<'a, 'b, Message: Clone>(
    content: &'b mut Element<'a, Message>,
    tree: &'b mut Tree,
    state: &'b mut State,
    behaviour: &'b Behaviour<'a, Message>,
    trigger: Rectangle,
) -> overlay::Element<'b, Message, Theme, Renderer> {
    let target = match behaviour.point {
        Some(point) => Rectangle::new(
            trigger.position() + Vector::new(point.x, point.y),
            Size::ZERO,
        ),
        None => trigger,
    };
    overlay::Element::new(Box::new(Floating {
        content,
        tree,
        state,
        behaviour,
        target,
        trigger,
    }))
}

/// The overlay drawing the panel. Its node covers the whole window so the
/// panel's shadow is never clipped; the panel is its only child.
struct Floating<'a, 'b, Message> {
    content: &'b mut Element<'a, Message>,
    tree: &'b mut Tree,
    state: &'b mut State,
    behaviour: &'b Behaviour<'a, Message>,
    target: Rectangle,
    trigger: Rectangle,
}

impl<Message: Clone> Floating<'_, '_, Message> {
    fn dismiss(&mut self, shell: &mut Shell<'_, Message>) {
        if self.behaviour.closes_itself {
            self.state.open = false;
            shell.request_redraw();
        }
        if self.behaviour.dismiss_on_blur {
            self.state.unfocus = true;
        }
        if let Some(message) = &self.behaviour.on_dismiss {
            shell.publish(message.clone());
        }
    }
}

/// The message [`Behaviour::on_key`] sends for a key press, if any.
fn key_message<Message>(behaviour: &Behaviour<'_, Message>, event: &Event) -> Option<Message> {
    let Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, .. }) = event else {
        return None;
    };
    let on_key = behaviour.on_key.as_ref()?;
    on_key(&keys::Event {
        key: key.clone(),
        modifiers: *modifiers,
    })
}

fn is_dismiss_key<Message>(behaviour: &Behaviour<'_, Message>, event: &Event) -> bool {
    let Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, .. }) = event else {
        return false;
    };
    behaviour
        .dismiss_keys
        .iter()
        .any(|chord| chord.matches(key, *modifiers))
}

fn is_press(event: &Event) -> bool {
    matches!(
        event,
        Event::Mouse(mouse::Event::ButtonPressed(_))
            | Event::Touch(touch::Event::FingerPressed { .. })
    )
}

fn is_release(event: &Event) -> bool {
    matches!(
        event,
        Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left))
            | Event::Touch(touch::Event::FingerLifted { .. })
    )
}

/// Where a mouse or touch press landed, if the event is one.
fn press_position(event: &Event, cursor: mouse::Cursor) -> Option<Point> {
    match event {
        Event::Mouse(mouse::Event::ButtonPressed(_)) => cursor.position(),
        Event::Touch(touch::Event::FingerPressed { position, .. }) => Some(*position),
        _ => None,
    }
}

fn is_pointer_input(event: &Event) -> bool {
    matches!(
        event,
        Event::Mouse(
            mouse::Event::ButtonPressed(_)
                | mouse::Event::ButtonReleased(_)
                | mouse::Event::WheelScrolled { .. }
        ) | Event::Touch(_)
    )
}

impl<Message: Clone> overlay::Overlay<Message, Theme, Renderer> for Floating<'_, '_, Message> {
    fn layout(&mut self, renderer: &Renderer, bounds: Size) -> layout::Node {
        let viewport = Rectangle::with_size(bounds);
        let room = viewport.shrink(MARGIN).size();
        let room = Size::new(room.width.max(0.0), room.height.max(0.0));
        let match_width = self.behaviour.match_width;
        let trigger_width = self.trigger.width;
        let limits = |height: f32| {
            if match_width {
                let width = trigger_width.min(room.width);
                layout::Limits::new(Size::new(width, 0.0), Size::new(width, height))
            } else {
                layout::Limits::new(Size::ZERO, Size::new(room.width, height))
            }
        };
        let placement = self.behaviour.placement;
        let mut node =
            self.content
                .as_widget_mut()
                .layout(self.tree, renderer, &limits(room.height));
        let fitted = self
            .behaviour
            .fit_height
            .then(|| fitted_height(self.target, node.size(), viewport, placement))
            .flatten();
        if let Some(height) = fitted {
            node = self
                .content
                .as_widget_mut()
                .layout(self.tree, renderer, &limits(height));
        }
        let panel = place(self.target, node.size(), viewport, placement);
        layout::Node::with_children(bounds, vec![node.move_to(panel.position())])
    }

    fn draw(
        &self,
        renderer: &mut Renderer,
        theme: &Theme,
        style: &renderer::Style,
        layout: Layout<'_>,
        cursor: mouse::Cursor,
    ) {
        let Some(panel) = layout.children().next() else {
            return;
        };
        self.content.as_widget().draw(
            self.tree,
            renderer,
            theme,
            style,
            panel,
            cursor,
            &layout.bounds(),
        );
    }

    fn operate(&mut self, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn Operation) {
        let Some(panel) = layout.children().next() else {
            return;
        };
        self.content
            .as_widget_mut()
            .operate(self.tree, panel, renderer, operation);
    }

    fn update(
        &mut self,
        event: &Event,
        layout: Layout<'_>,
        cursor: mouse::Cursor,
        renderer: &Renderer,
        clipboard: &mut dyn Clipboard,
        shell: &mut Shell<'_, Message>,
    ) {
        let Some(panel) = layout.children().next() else {
            return;
        };

        self.content.as_widget_mut().update(
            self.tree,
            event,
            panel,
            cursor,
            renderer,
            clipboard,
            shell,
            &layout.bounds(),
        );
        if shell.is_event_captured() {
            // A row took the click, so the choice is made.
            if self.behaviour.closes_itself && is_release(event) {
                self.state.open = false;
                shell.request_redraw();
            }
            return;
        }

        if let Some(message) = key_message(self.behaviour, event) {
            shell.publish(message);
            shell.capture_event();
            return;
        }
        if is_dismiss_key(self.behaviour, event) && self.behaviour.can_dismiss() {
            self.dismiss(shell);
            shell.capture_event();
            return;
        }
        if !is_pointer_input(event) {
            return;
        }

        let bounds = panel.bounds();
        if cursor.is_over(bounds) {
            shell.capture_event();
            return;
        }
        let Some(position) = press_position(event, cursor) else {
            return;
        };
        if bounds.contains(position) {
            shell.capture_event();
            return;
        }
        let on_anchor = self.trigger.contains(position);
        if (on_anchor && !self.behaviour.dismiss_on_anchor_press) || !self.behaviour.can_dismiss() {
            return;
        }
        self.dismiss(shell);
        if !on_anchor && !self.behaviour.pass_through {
            shell.capture_event();
        }
    }

    fn mouse_interaction(
        &self,
        layout: Layout<'_>,
        cursor: mouse::Cursor,
        renderer: &Renderer,
    ) -> mouse::Interaction {
        let Some(panel) = layout.children().next() else {
            return mouse::Interaction::None;
        };
        if !cursor.is_over(panel.bounds()) {
            return mouse::Interaction::None;
        }
        self.content
            .as_widget()
            .mouse_interaction(self.tree, panel, cursor, &layout.bounds(), renderer)
            .max(mouse::Interaction::Idle)
    }

    fn overlay<'c>(
        &'c mut self,
        layout: Layout<'c>,
        renderer: &Renderer,
    ) -> Option<overlay::Element<'c, Message, Theme, Renderer>> {
        let panel = layout.children().next()?;
        let viewport = layout.bounds();
        self.content
            .as_widget_mut()
            .overlay(self.tree, panel, renderer, &viewport, Vector::ZERO)
    }
}

/// Whether any focusable widget in a subtree has focus.
#[derive(Default)]
struct FindFocus(bool);

impl Operation for FindFocus {
    fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) {
        operate(self);
    }

    fn focusable(&mut self, _id: Option<&Id>, _bounds: Rectangle, state: &mut dyn Focusable) {
        self.0 |= state.is_focused();
    }
}

/// Takes focus away from every widget in a subtree.
struct Unfocus;

impl Operation for Unfocus {
    fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) {
        operate(self);
    }

    fn focusable(&mut self, _id: Option<&Id>, _bounds: Rectangle, state: &mut dyn Focusable) {
        if state.is_focused() {
            state.unfocus();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::theme::{dark, light};
    use iced::keyboard::{Key, Modifiers};

    const VIEWPORT: Rectangle = Rectangle {
        x: 0.0,
        y: 0.0,
        width: 400.0,
        height: 300.0,
    };

    fn anchor() -> Rectangle {
        Rectangle::new(Point::new(150.0, 100.0), Size::new(100.0, 40.0))
    }

    const PANEL: Size = Size::new(60.0, 50.0);

    fn at(side: Side, align: Align) -> Point {
        place(anchor(), PANEL, VIEWPORT, Placement::new(side, align)).position()
    }

    #[test]
    fn defaults_to_bottom_centre_with_a_small_gap() {
        let placement = Placement::default();
        assert_eq!(placement.side, Side::Bottom);
        assert_eq!(placement.align, Align::Center);
        assert_eq!(placement.gap, GAP);
        assert_eq!(placement.offset, 0.0);
    }

    #[test]
    fn each_side_sits_outside_the_anchor_with_the_gap() {
        assert_eq!(at(Side::Bottom, Align::Start), Point::new(150.0, 144.0));
        assert_eq!(at(Side::Top, Align::Start), Point::new(150.0, 46.0));
        assert_eq!(at(Side::Left, Align::Start), Point::new(86.0, 100.0));
        assert_eq!(at(Side::Right, Align::Start), Point::new(254.0, 100.0));
    }

    #[test]
    fn alignment_moves_along_the_side() {
        assert_eq!(at(Side::Bottom, Align::Center).x, 170.0);
        assert_eq!(at(Side::Bottom, Align::End).x, 190.0);
        assert_eq!(at(Side::Right, Align::Center).y, 95.0);
        assert_eq!(at(Side::Right, Align::End).y, 90.0);
    }

    #[test]
    fn offset_shifts_away_from_the_aligned_edge() {
        let placement = Placement::new(Side::Bottom, Align::Start).offset(5.0);
        let start = place(anchor(), PANEL, VIEWPORT, placement);
        assert_eq!(start.x, 155.0);
        let placement = Placement::new(Side::Bottom, Align::End).offset(5.0);
        let end = place(anchor(), PANEL, VIEWPORT, placement);
        assert_eq!(end.x, 185.0);
    }

    #[test]
    fn flips_to_the_opposite_side_when_there_is_no_room() {
        let low = Rectangle::new(Point::new(150.0, 230.0), Size::new(100.0, 40.0));
        let panel = place(
            low,
            PANEL,
            VIEWPORT,
            Placement::new(Side::Bottom, Align::Start),
        );
        assert_eq!(panel.y, 230.0 - GAP - PANEL.height);

        let left_edge = Rectangle::new(Point::new(20.0, 100.0), Size::new(40.0, 40.0));
        let panel = place(
            left_edge,
            PANEL,
            VIEWPORT,
            Placement::new(Side::Left, Align::Start),
        );
        assert_eq!(panel.x, 60.0 + GAP);
    }

    #[test]
    fn stays_put_when_neither_side_fits_and_the_requested_one_is_larger() {
        let tall = Size::new(60.0, 290.0);
        let panel = place(
            anchor(),
            tall,
            VIEWPORT,
            Placement::new(Side::Bottom, Align::Start),
        );
        assert_eq!(panel.y, MARGIN, "shifted up to fit, pinned at the margin");
    }

    #[test]
    fn fitted_height_keeps_a_tall_panel_off_its_anchor() {
        let below = Placement::new(Side::Bottom, Align::Start);
        assert_eq!(fitted_height(anchor(), PANEL, VIEWPORT, below), None);
        let tall = Size::new(60.0, 290.0);
        let room_below = VIEWPORT.height - MARGIN - (140.0 + GAP);
        assert_eq!(
            fitted_height(anchor(), tall, VIEWPORT, below),
            Some(room_below)
        );
        let panel = place(anchor(), Size::new(60.0, room_below), VIEWPORT, below);
        assert_eq!(panel.y, 140.0 + GAP, "stays below the anchor");

        let low = Rectangle::new(Point::new(150.0, 200.0), Size::new(100.0, 40.0));
        let room_above = 200.0 - GAP - MARGIN;
        assert_eq!(fitted_height(low, tall, VIEWPORT, below), Some(room_above));
        let panel = place(low, Size::new(60.0, room_above), VIEWPORT, below);
        assert_eq!(panel.y + panel.height, 200.0 - GAP, "flips above it");

        let beside = Placement::new(Side::Right, Align::Start);
        assert_eq!(fitted_height(anchor(), tall, VIEWPORT, beside), None);
    }

    #[test]
    fn fitted_height_uses_the_roomier_side_however_little_room_it_has() {
        let below = Placement::new(Side::Bottom, Align::Start);
        let tall = Size::new(60.0, 290.0);
        let squeezed = Rectangle::new(Point::new(150.0, 100.0), Size::new(100.0, 120.0));
        let room_above = 100.0 - GAP - MARGIN;
        assert_eq!(
            fitted_height(squeezed, tall, VIEWPORT, below),
            Some(room_above)
        );
        let panel = place(squeezed, Size::new(60.0, room_above), VIEWPORT, below);
        assert_eq!(panel.y + panel.height, 100.0 - GAP, "clear of the anchor");

        let filling = Rectangle::new(Point::new(0.0, 0.0), Size::new(400.0, 300.0));
        assert_eq!(fitted_height(filling, tall, VIEWPORT, below), Some(0.0));
    }

    #[test]
    fn a_menu_low_in_the_window_opens_above_at_full_height() {
        let point = Rectangle::new(Point::new(100.0, 230.0), Size::ZERO);
        let menu = Size::new(180.0, 200.0);
        let placement = Placement::new(Side::Bottom, Align::Start).gap(0.0);
        assert_eq!(fitted_height(point, menu, VIEWPORT, placement), None);
        let panel = place(point, menu, VIEWPORT, placement);
        assert_eq!(panel.y + panel.height, 230.0, "flipped above the point");
    }

    #[test]
    fn a_side_panel_that_fits_neither_side_moves_below_its_anchor() {
        let narrow = Rectangle::new(Point::new(0.0, 0.0), Size::new(320.0, 300.0));
        let row = Rectangle::new(Point::new(40.0, 100.0), Size::new(216.0, 32.0));
        let submenu = Size::new(224.0, 120.0);
        let placement = Placement::new(Side::Right, Align::Start).gap(4.0);
        let panel = place(row, submenu, narrow, placement);
        assert_eq!(panel.y, 132.0 + 4.0, "below the row, clear of its label");
        assert_eq!(panel.x, 40.0, "lined up with the row");

        let low_row = Rectangle::new(Point::new(40.0, 200.0), Size::new(216.0, 32.0));
        let panel = place(low_row, submenu, narrow, placement);
        assert_eq!(panel.y + panel.height, 200.0 - 4.0, "above the row");

        let wide = Rectangle::new(Point::new(0.0, 0.0), Size::new(600.0, 300.0));
        let panel = place(row, submenu, wide, placement);
        assert_eq!(panel.x, 256.0 + 4.0, "beside the row when it fits");
        assert_eq!(fitted_height(row, submenu, wide, placement), None);
    }

    #[test]
    fn a_tall_side_panel_without_room_beside_scrolls_on_the_roomier_side() {
        let narrow = Rectangle::new(Point::new(0.0, 0.0), Size::new(320.0, 300.0));
        let row = Rectangle::new(Point::new(40.0, 160.0), Size::new(216.0, 32.0));
        let submenu = Size::new(224.0, 180.0);
        let placement = Placement::new(Side::Right, Align::Start).gap(4.0);
        assert_eq!(
            fitted_height(row, submenu, narrow, placement),
            Some(160.0 - 4.0 - MARGIN)
        );
        let fitted = Size::new(224.0, 160.0 - 4.0 - MARGIN);
        let panel = place(row, fitted, narrow, placement);
        assert_eq!(panel.y, MARGIN);
        assert_eq!(panel.y + panel.height, 160.0 - 4.0, "clear of the row");
    }

    #[test]
    fn mirrors_the_alignment_when_it_would_overflow() {
        let right_edge = Rectangle::new(Point::new(360.0, 100.0), Size::new(30.0, 30.0));
        let panel = place(
            right_edge,
            PANEL,
            VIEWPORT,
            Placement::new(Side::Bottom, Align::Start),
        );
        assert_eq!(panel.x, 390.0 - PANEL.width);
    }

    #[test]
    fn shifts_inside_the_margin_when_nothing_else_fits() {
        let corner = Rectangle::new(Point::new(0.0, 0.0), Size::new(10.0, 10.0));
        let panel = place(
            corner,
            PANEL,
            VIEWPORT,
            Placement::new(Side::Left, Align::Center),
        );
        assert_eq!(panel.x, 10.0 + GAP, "flipped to the right");
        assert_eq!(panel.y, MARGIN, "shifted down to the margin");
    }

    #[test]
    fn a_list_near_the_bottom_keeps_the_margin() {
        let field = Rectangle::new(Point::new(20.0, 200.0), Size::new(200.0, 36.0));
        let list = Size::new(200.0, 80.0);
        let placement = Placement::new(Side::Bottom, Align::Start);
        let panel = place(field, list, VIEWPORT, placement);
        assert_eq!(panel.y, 200.0 - GAP - list.height, "flips above the field");

        let wide = Size::new(420.0, 40.0);
        let panel = place(field, wide, VIEWPORT, placement);
        assert_eq!(panel.x, MARGIN, "clamped inside the window");
    }

    #[test]
    fn a_point_anchor_opens_below_and_right_then_flips_near_edges() {
        let point = |x, y| Rectangle::new(Point::new(x, y), Size::ZERO);
        let placement = Placement::new(Side::Bottom, Align::Start).gap(0.0);
        assert_eq!(
            place(point(100.0, 100.0), PANEL, VIEWPORT, placement).position(),
            Point::new(100.0, 100.0)
        );
        assert_eq!(
            place(point(380.0, 280.0), PANEL, VIEWPORT, placement).position(),
            Point::new(320.0, 230.0)
        );
    }

    #[test]
    fn a_panel_larger_than_the_window_is_pinned_top_left() {
        let huge = Size::new(1000.0, 1000.0);
        let panel = place(anchor(), huge, VIEWPORT, Placement::default());
        assert_eq!(panel.position(), Point::new(MARGIN, MARGIN));
        assert_eq!(panel.size(), huge);
    }

    #[test]
    fn sides_and_alignments_mirror() {
        for side in Side::ALL {
            assert_eq!(side.opposite().opposite(), side);
            assert_ne!(side.opposite(), side);
        }
        assert_eq!(Align::Center.mirrored(), Align::Center);
        assert_eq!(Align::Start.mirrored(), Align::End);
    }

    #[test]
    fn surface_uses_the_popover_colour_a_border_and_a_shadow() {
        for theme in [light(), dark()] {
            let tokens = Tokens::of(&theme);
            let style = surface_style(&tokens);
            assert_eq!(style.background, Some(Background::Color(tokens.popover)));
            assert_eq!(style.text_color, Some(tokens.foreground));
            assert_eq!(style.border.color, tokens.border);
            assert_eq!(style.border.width, 1.0);
            assert_eq!(style.border.radius, radius::MD.into());
            assert_eq!(style.shadow, shadow(&tokens));
            assert_eq!(style.shadow.offset, Vector::new(0.0, 4.0));
            assert_eq!(style.shadow.blur_radius, 12.0);
        }
        let light = shadow(&Tokens::of(&light())).color.a;
        let dark = shadow(&Tokens::of(&dark())).color.a;
        assert!((light - 0.1).abs() < 1e-6);
        assert!((dark - 0.5).abs() < 1e-6);
    }

    #[test]
    fn builder_starts_closed_and_undismissable_with_escape_bound() {
        let anchored: Anchored<'_, ()> = anchored(iced::widget::text("Anchor"));
        let behaviour = &anchored.behaviour;
        assert!(anchored.content.is_none());
        assert!(behaviour.on_dismiss.is_none());
        assert!(behaviour.point.is_none());
        assert!(!behaviour.dismiss_on_anchor_press);
        assert!(!behaviour.dismiss_on_blur);
        assert!(!behaviour.pass_through);
        assert!(!behaviour.match_width);
        assert_eq!(behaviour.dismiss_keys, vec![Chord::named(Named::Escape)]);
        assert!(!behaviour.can_dismiss());
        assert!(!behaviour.watches_focus());
    }

    #[test]
    fn builder_sets_every_option() {
        let anchored: Anchored<'_, u8> = anchored(iced::widget::text("Anchor"))
            .at(Point::new(3.0, 4.0))
            .match_width(true)
            .on_dismiss(1)
            .dismiss_keys([Chord::character('q')])
            .dismiss_on_anchor_press(true)
            .dismiss_on_blur(true)
            .pass_through(true)
            .on_anchor_press_maybe(Some(2))
            .on_key(|_| Some(3))
            .on_focus(|focused| if focused { 4 } else { 5 });
        let behaviour = &anchored.behaviour;
        assert_eq!(behaviour.focus_message(false, true), Some(4));
        assert_eq!(behaviour.focus_message(true, false), Some(5));
        assert_eq!(behaviour.focus_message(true, true), None);
        assert_eq!(behaviour.point, Some(Point::new(3.0, 4.0)));
        assert!(behaviour.match_width && behaviour.pass_through);
        assert!(behaviour.dismiss_on_anchor_press && behaviour.dismiss_on_blur);
        assert_eq!(behaviour.on_dismiss, Some(1));
        assert_eq!(behaviour.on_anchor_press, Some(2));
        assert_eq!(behaviour.dismiss_keys, vec![Chord::character('q')]);
        assert!(behaviour.can_dismiss() && behaviour.watches_focus());
    }

    fn key_press(key: Key, modifiers: Modifiers) -> Event {
        Event::Keyboard(keyboard::Event::KeyPressed {
            key: key.clone(),
            modified_key: key,
            physical_key: keyboard::key::Physical::Unidentified(
                keyboard::key::NativeCode::Unidentified,
            ),
            location: keyboard::Location::Standard,
            modifiers,
            text: None,
            repeat: false,
        })
    }

    #[test]
    fn keys_resolve_through_on_key_then_the_dismiss_chords() {
        let behaviour: Behaviour<'_, u8> = Behaviour {
            on_key: Some(Box::new(|key: &keys::Event| {
                (key.key == Key::Named(Named::ArrowDown)).then_some(7)
            })),
            ..Behaviour::default()
        };
        let down = key_press(Key::Named(Named::ArrowDown), Modifiers::empty());
        let escape = key_press(Key::Named(Named::Escape), Modifiers::empty());
        let shift_escape = key_press(Key::Named(Named::Escape), Modifiers::SHIFT);
        assert_eq!(key_message(&behaviour, &down), Some(7));
        assert_eq!(key_message(&behaviour, &escape), None);
        assert!(is_dismiss_key(&behaviour, &escape));
        assert!(!is_dismiss_key(&behaviour, &shift_escape));
        assert!(!is_dismiss_key(&behaviour, &down));

        let unbound: Behaviour<'_, u8> = Behaviour {
            dismiss_keys: Vec::new(),
            ..Behaviour::default()
        };
        assert!(!is_dismiss_key(&unbound, &escape));
    }

    #[test]
    fn press_position_only_reports_presses() {
        let cursor = mouse::Cursor::Available(Point::new(3.0, 4.0));
        let pressed = Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Right));
        let released = Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left));
        assert_eq!(press_position(&pressed, cursor), Some(Point::new(3.0, 4.0)));
        assert_eq!(press_position(&released, cursor), None);
        assert_eq!(press_position(&pressed, mouse::Cursor::Unavailable), None);
        assert!(is_pointer_input(&released));
        assert!(is_release(&released));
        assert!(is_press(&pressed));
        assert!(!is_release(&pressed));
        assert!(!is_pointer_input(&Event::Mouse(mouse::Event::CursorLeft)));
    }
}