egui_stack 0.32.0

Docking system for egui, continuing egui_dock
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
//! Folded zones: their strips, the zones lying over their neighbour, and
//! the flyout.

use std::f32::consts::FRAC_PI_2;

use egui::{
    Color32, CursorIcon, FontId, Id, Key, LayerId, Order, Painter, Pos2, Rect, Sense, Ui,
    UiBuilder, WidgetInfo,
    accesskit::Role,
    epaint::TextShape,
    text::{LayoutJob, TextWrapping},
};

use super::area::{
    LayoutPainter, LayoutStyle, Names, SashPaint, SnapGuidePaint, SnapKind, ZoneViewer,
    paint_guide, zone_ui_at,
};
use super::solve::{along, span};
use super::{Dir, Laid, LaidZone, Layout, LayoutEvent, Shown, Zone, ZoneName};
use crate::{PartState, SeparatorAxis};

/// A flyout: one item of a folded zone, shown over the neighbouring zone
/// next to the zone's strip, without moving the layout. The application
/// says what it is ([`ZoneViewer::flyout`]) and when to open it
/// ([`LayoutArea::flyout`](super::LayoutArea::flyout)).
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Flyout {
    /// The application's key (a panel), under which its breadth is kept
    /// ([`Layout::flyouts`]).
    pub key: String,
    /// The folded zone whose strip it opens from.
    pub zone: ZoneName,
}

impl Flyout {
    /// The flyout `key` of the folded zone `zone`.
    pub fn new(key: impl Into<String>, zone: impl Into<ZoneName>) -> Self {
        Self {
            key: key.into(),
            zone: zone.into(),
        }
    }
}

/// What a click on a folded zone's strip does, as
/// [`ZoneViewer::on_strip`] returns it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum StripAction {
    /// What the strip does by itself: a zone the user folded
    /// ([`Shown::Folded`]) unfolds; a zone the solver folded short of room
    /// ([`Shown::AutoFolded`]) opens over its neighbour ([`Self::Over`]),
    /// and goes back to its automatic state once closed; a zone lying over
    /// ([`Shown::Over`]) closes ([`Self::Fold`]). When the zone's flyout is
    /// open, the flyout closes instead.
    #[default]
    Default,
    /// The zone unfolds, back in the flow. On an auto-folded zone, nothing:
    /// the room decides.
    Unfold,
    /// The zone opens over its neighbour, next to its strip, without
    /// taking room, as [`Layout::set_over`] does. Opened from an
    /// auto-folded strip, closing it (its strip, Escape or a press outside,
    /// as [`LayoutArea::over_dismiss`](super::LayoutArea::over_dismiss)
    /// says) puts it back in its automatic state; opened from a strip the
    /// user folded, it folds back. On a zone already lying over, nothing.
    Over,
    /// A zone lying over closes, as above. On a folded strip, nothing.
    Fold,
    /// Nothing: the application handles the click itself, from the
    /// response or [`LayoutEvent::StripClicked`].
    Nothing,
}

/// A folded zone's strip to paint.
#[derive(Debug)]
#[non_exhaustive]
pub struct StripPaint<'a> {
    /// The strip.
    pub rect: Rect,
    /// Its grip, the button at its start that unfolds (or folds back) its
    /// zone.
    pub grip: Rect,
    /// Which way the strip runs: [`SeparatorAxis::Vertical`] for a column
    /// in a row of zones.
    pub axis: SeparatorAxis,
    /// The grip's state.
    pub grip_state: PartState,
    /// The zone.
    pub zone: &'a ZoneName,
    /// How the zone is shown: folded, or lying over its neighbour.
    pub shown: Shown,
    /// The layout's style.
    pub style: &'a LayoutStyle,
}

/// Which way a strip's title reads ([`ZoneViewer::strip_title`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum StripOrientation {
    /// Left to right, upright: the strip of a zone in a column of zones
    /// (a top or bottom strip).
    Horizontal,
    /// Turned a quarter turn anticlockwise, read from the bottom up: a side
    /// strip.
    BottomToTop,
    /// Turned a quarter turn clockwise, read from the top down: a side
    /// strip.
    TopToBottom,
}

/// Which way the title reads on a side strip (a zone in a row of zones),
/// left and right strips alike ([`StripTitle::vertical`]).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum VerticalReading {
    /// From the bottom up, the text's top towards the left.
    #[default]
    BottomToTop,
    /// From the top down, the text's top towards the right.
    TopToBottom,
}

impl From<VerticalReading> for StripOrientation {
    fn from(reading: VerticalReading) -> Self {
        match reading {
            VerticalReading::BottomToTop => Self::BottomToTop,
            VerticalReading::TopToBottom => Self::TopToBottom,
        }
    }
}

/// The title a folded zone's strip shows ([`LayoutStyle::strip_title`]):
/// the zone's title ([`ZoneViewer::title`]) after its grip, with its icon
/// ([`ZoneViewer::strip_icon`]) first, if any. A title longer than the
/// strip is cut with an ellipsis and shown whole in a tooltip when the
/// strip is hovered. The strip is made broad enough for a line of
/// [`font`](Self::font), or the widest icon, and the padding on both sides;
/// it is never narrower than [`LayoutStyle::strip`]. An application draws
/// its own title with [`ZoneViewer::strip_title`], in the same room.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct StripTitle {
    /// Which way side strips read. By default from the bottom up.
    pub vertical: VerticalReading,
    /// The font of the title and the icon. By default egui's body font.
    pub font: FontId,
    /// Their colour. By default the colour of non-interactive text.
    pub color: Color32,
    /// The room around the title, inside the strip, after the grip. By
    /// default 4 points.
    pub padding: f32,
    /// The room between the icon and the title. By default 4 points.
    pub gap: f32,
}

impl Default for StripTitle {
    fn default() -> Self {
        Self::from_egui(&egui::Style::default())
    }
}

impl StripTitle {
    /// A title drawn from egui's style: its body font, its text colour.
    pub fn from_egui(style: &egui::Style) -> Self {
        Self {
            vertical: VerticalReading::default(),
            font: egui::TextStyle::Body.resolve(style),
            color: style.visuals.widgets.noninteractive.fg_stroke.color,
            padding: 4.0,
            gap: 4.0,
        }
    }

    /// The breadth a strip needs for this title: a line of its font, or the
    /// widest of `icons`, and the padding on both sides.
    pub(super) fn breadth(&self, painter: &Painter, icons: &[String]) -> f32 {
        let line = painter.fonts_mut(|fonts| fonts.row_height(&self.font));
        let icon = icons
            .iter()
            .map(|icon| {
                painter
                    .layout_no_wrap(icon.clone(), self.font.clone(), self.color)
                    .size()
                    .x
            })
            .fold(0.0, f32::max);
        line.max(icon) + 2.0 * self.padding
    }
}

/// Paints the built-in title in `rect`: the icon upright next to the grip,
/// then the title, cut with an ellipsis when too long. Returns whether it
/// was cut.
fn paint_title(
    painter: &Painter,
    rect: Rect,
    orientation: StripOrientation,
    title: &str,
    icon: Option<&str>,
    style: &StripTitle,
) -> bool {
    let vertical = orientation != StripOrientation::Horizontal;
    let length = if vertical {
        rect.height()
    } else {
        rect.width()
    };
    let mut start = 0.0;
    if let Some(icon) = icon {
        let galley = painter.layout_no_wrap(icon.to_owned(), style.font.clone(), style.color);
        let size = galley.size();
        let pos = if vertical {
            egui::pos2(rect.center().x - size.x * 0.5, rect.top())
        } else {
            egui::pos2(rect.left(), rect.center().y - size.y * 0.5)
        };
        start = if vertical { size.y } else { size.x } + style.gap;
        painter.galley(pos, galley, style.color);
    }
    let room = length - start;
    if title.is_empty() {
        return false;
    }
    if room <= 0.0 {
        return true;
    }
    let mut job = LayoutJob::simple_singleline(title.to_owned(), style.font.clone(), style.color);
    job.wrap = TextWrapping {
        max_width: room,
        max_rows: 1,
        break_anywhere: true,
        overflow_character: Some('\u{2026}'),
    };
    let galley = painter.layout_job(job);
    let elided = galley.elided;
    let size = galley.size();
    // The galley turns about its top-left corner: placed so that the text
    // starts `start` past the grip side and sits centred across the strip.
    let (pos, angle) = match orientation {
        StripOrientation::BottomToTop => (
            egui::pos2(rect.center().x - size.y * 0.5, rect.top() + start + size.x),
            -FRAC_PI_2,
        ),
        StripOrientation::TopToBottom => (
            egui::pos2(rect.center().x + size.y * 0.5, rect.top() + start),
            FRAC_PI_2,
        ),
        StripOrientation::Horizontal => (
            egui::pos2(rect.left() + start, rect.center().y - size.y * 0.5),
            0.0,
        ),
    };
    painter.add(TextShape::new(pos, galley, style.color).with_angle(angle));
    elided
}

/// The frame of a zone lying over its neighbour, or of a flyout.
#[derive(Debug)]
#[non_exhaustive]
pub struct FlyoutPaint<'a> {
    /// Its rect.
    pub rect: Rect,
    /// The zone it opens from.
    pub zone: &'a ZoneName,
    /// The flyout's key, for a flyout; `None` for a zone lying over.
    pub key: Option<&'a str>,
    /// The layout's style.
    pub style: &'a LayoutStyle,
}

/// The direction of the split holding the zone named `name`.
fn parent_dir(root: &Zone, name: &str) -> Option<Dir> {
    let mut found = None;
    root.visit(&mut |zone| {
        if let super::ZoneKind::Split { dir, children } = &zone.kind
            && children.iter().any(|c| c.name == *name)
        {
            found = Some(*dir);
        }
    });
    found
}

/// The name of the split holding the zone named `name`.
fn parent_name(root: &Zone, name: &str) -> Option<ZoneName> {
    let mut found = None;
    root.visit(&mut |zone| {
        if zone.children().iter().any(|c| c.name == *name) {
            found = Some(zone.name.clone());
        }
    });
    found
}

/// What dismisses a flyout ([`LayoutArea::flyout_dismiss`]), or folds
/// back a zone lying over its neighbour ([`LayoutArea::over_dismiss`]).
/// By default both: [`Dismiss::ANY`].
///
/// [`LayoutArea::flyout_dismiss`]: super::LayoutArea::flyout_dismiss
/// [`LayoutArea::over_dismiss`]: super::LayoutArea::over_dismiss
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Dismiss {
    /// A press outside it and its strip, unless the host counts the press
    /// as inside ([`LayoutArea::inside`](super::LayoutArea::inside)).
    pub outside_press: bool,
    /// Escape. A host that closes its own overlays first consumes the
    /// key before the area is drawn (`egui::InputState::consume_key`), or
    /// turns this off while one is open.
    pub escape: bool,
}

impl Dismiss {
    /// A press outside, or Escape.
    pub const ANY: Self = Self {
        outside_press: true,
        escape: true,
    };
    /// Neither: only its strip's grip, or the application, closes it.
    pub const NEVER: Self = Self {
        outside_press: false,
        escape: false,
    };
    /// A press outside only.
    pub const OUTSIDE_PRESS: Self = Self {
        outside_press: true,
        escape: false,
    };
    /// Escape only.
    pub const ESCAPE: Self = Self {
        outside_press: false,
        escape: true,
    };
}

impl Default for Dismiss {
    fn default() -> Self {
        Self::ANY
    }
}

/// The host's say on whether a press counts as inside a flyout or a zone
/// lying over: given the press and the egui layer on top there.
pub type Inside<'a> = &'a dyn Fn(Pos2, Option<LayerId>) -> bool;

/// Whether `dismiss` closes this frame: Escape, or a press outside every
/// rect of `inside` that the host does not count as inside.
fn dismissed(ui: &Ui, dismiss: Dismiss, inside: &[Rect], host: Option<Inside<'_>>) -> bool {
    if dismiss.escape && ui.input(|i| i.key_pressed(Key::Escape)) {
        return true;
    }
    if !dismiss.outside_press {
        return false;
    }
    let press = ui.input(|i| {
        i.pointer
            .any_pressed()
            .then(|| i.pointer.press_origin())
            .flatten()
    });
    let Some(pos) = press else {
        return false;
    };
    if inside.iter().any(|rect| rect.contains(pos)) {
        return false;
    }
    host.is_none_or(|host| !host(pos, ui.ctx().layer_id_at(pos)))
}

#[expect(
    clippy::too_many_arguments,
    reason = "the area's parts, borrowed apart"
)]
pub(super) fn strips(
    ui: &mut Ui,
    id: Id,
    layout: &mut Layout,
    laid: &Laid,
    style: &LayoutStyle,
    painter: &dyn LayoutPainter,
    viewer: &mut dyn ZoneViewer,
    names: &Names<'_>,
    flyout: Option<&Flyout>,
    events: &mut Vec<LayoutEvent>,
) {
    for at in &laid.zones {
        let Some(strip) = at.strip else {
            continue;
        };
        let dir = parent_dir(&layout.root, &at.name.0).unwrap_or_default();
        let breadth = along(dir, strip.size());
        let grip = Rect::from_min_size(strip.min, egui::vec2(breadth, breadth)).intersect(strip);
        // The whole strip clicks like its grip, under the grip and the
        // viewer's own widgets (drawn after it, so on top): on a bare strip,
        // the whole strip is the button. Not a keyboard stop: the grip is.
        let body = ui.interact(strip, id.with(("strip_body", &at.name.0)), Sense::CLICK);
        let response = ui.interact(grip, id.with(("grip", &at.name.0)), Sense::click());
        let label = match at.shown {
            Shown::Over => names.fold(&at.name),
            _ => names.unfold(&at.name),
        };
        response.widget_info(|| WidgetInfo::labeled(Role::Button, true, &label));
        let axis = match dir {
            Dir::Horizontal => SeparatorAxis::Vertical,
            Dir::Vertical => SeparatorAxis::Horizontal,
        };
        painter.strip(
            ui.painter(),
            &StripPaint {
                rect: strip,
                grip,
                axis,
                grip_state: PartState::NONE
                    .with(PartState::HOVERED, response.hovered() || body.hovered())
                    .with(
                        PartState::PRESSED,
                        response.is_pointer_button_down_on() || body.is_pointer_button_down_on(),
                    )
                    .with(PartState::FOCUSED, response.has_focus()),
                zone: &at.name,
                shown: at.shown,
                style,
            },
        );
        let rest = match dir {
            Dir::Horizontal => Rect::from_min_max(egui::pos2(strip.min.x, grip.max.y), strip.max),
            Dir::Vertical => Rect::from_min_max(egui::pos2(grip.max.x, strip.min.y), strip.max),
        };
        let mut child = ui.new_child(
            UiBuilder::new()
                .id_salt(id.with(("strip", &at.name.0)))
                .max_rect(rest)
                .layout(match dir {
                    Dir::Horizontal => egui::Layout::top_down(egui::Align::Center),
                    Dir::Vertical => egui::Layout::left_to_right(egui::Align::Center),
                }),
        );
        child.set_clip_rect(rest.intersect(ui.clip_rect()));
        if let Some(title) = &style.strip_title {
            let room = rest.shrink(title.padding);
            let orientation = match dir {
                Dir::Horizontal => title.vertical.into(),
                Dir::Vertical => StripOrientation::Horizontal,
            };
            if room.is_positive() {
                let mut title_ui = ui.new_child(
                    UiBuilder::new()
                        .id_salt(id.with(("strip_title", &at.name.0)))
                        .max_rect(room),
                );
                title_ui.set_clip_rect(room.intersect(ui.clip_rect()));
                if !viewer.strip_title(&mut title_ui, &at.name, room, orientation) {
                    let icon = viewer.strip_icon(&at.name);
                    let text = names.title(&at.name);
                    let cut = paint_title(
                        title_ui.painter(),
                        room,
                        orientation,
                        text,
                        icon.as_deref(),
                        title,
                    );
                    if cut {
                        body.clone().on_hover_text(text);
                    }
                }
            }
        }
        viewer.strip(&mut child, &at.name);
        let action = viewer.on_strip(&at.name, at.shown, &response.union(body.clone()));

        let mut band_clicked = false;
        if at.shown == Shown::Folded && style.strip_drag {
            match drag_out(ui, id, layout, laid, at, strip, dir, style, painter) {
                DragOut::Unfolded => {
                    events.push(LayoutEvent::Unfolded {
                        zone: at.name.clone(),
                    });
                    continue;
                }
                DragOut::Clicked => band_clicked = true,
                DragOut::None => {}
            }
        }

        if response.clicked() || body.clicked() || band_clicked {
            events.push(LayoutEvent::StripClicked {
                zone: at.name.clone(),
                shown: at.shown,
            });
            if let Some(flyout) = flyout
                && flyout.zone == at.name
                && action == StripAction::Default
            {
                events.push(LayoutEvent::FlyoutClosed {
                    key: flyout.key.clone(),
                });
                continue;
            }
            if let Some(event) = act(layout, &at.name, at.shown, action) {
                events.push(event);
            }
        }
    }
}

/// Applies `action` to the zone `name`, shown as `shown`, whose strip was
/// clicked; returns the event that reports it, if it did anything.
fn act(
    layout: &mut Layout,
    name: &ZoneName,
    shown: Shown,
    action: StripAction,
) -> Option<LayoutEvent> {
    let action = match (action, shown) {
        (StripAction::Default, Shown::Folded) => StripAction::Unfold,
        (StripAction::Default, Shown::AutoFolded) => StripAction::Over,
        (StripAction::Default, Shown::Over) => StripAction::Fold,
        (action, _) => action,
    };
    let zone = name.clone();
    match (action, shown) {
        (StripAction::Unfold, Shown::Folded | Shown::Over) => {
            layout.set_folded(&name.0, false);
            Some(LayoutEvent::Unfolded { zone })
        }
        (StripAction::Over, Shown::Folded) => {
            layout.set_over(&name.0, true);
            Some(LayoutEvent::OpenedOver { zone })
        }
        (StripAction::Over, Shown::AutoFolded) => {
            layout.open_over_from_auto(&name.0);
            Some(LayoutEvent::OpenedOver { zone })
        }
        (StripAction::Fold, Shown::Over) => layout.close_over(name),
        _ => None,
    }
}

/// Draws the zones lying over their neighbour, in front of the others,
/// each with its free edge that resizes it; what `dismiss` says (by default a press outside one, or Escape) folds
/// it back, or puts it back in its automatic state when it was opened from
/// its auto-folded strip.
#[expect(
    clippy::too_many_arguments,
    reason = "the area's parts, borrowed apart"
)]
pub(super) fn overs(
    ui: &mut Ui,
    id: Id,
    layout: &mut Layout,
    laid: &Laid,
    style: &LayoutStyle,
    painter: &dyn LayoutPainter,
    viewer: &mut dyn ZoneViewer,
    names: &Names<'_>,
    (dismiss, host): (Dismiss, Option<Inside<'_>>),
    sublayer_of: Option<LayerId>,
    events: &mut Vec<LayoutEvent>,
) {
    for at in laid.zones.iter().filter(|at| at.shown == Shown::Over) {
        let Some(zone) = layout.zone(&at.name.0).cloned() else {
            continue;
        };
        let rect = at.rect;
        let strip = at.strip.unwrap_or(Rect::NOTHING);
        let dir = parent_dir(&layout.root, &at.name.0).unwrap_or_default();
        let towards_end =
            along(dir, rect.center().to_vec2()) > along(dir, strip.center().to_vec2());
        let free_edge = if towards_end {
            along(dir, rect.max.to_vec2())
        } else {
            along(dir, rect.min.to_vec2())
        };
        let edge = span(
            dir,
            rect,
            free_edge - style.sash_grab * 0.5,
            free_edge + style.sash_grab * 0.5,
        );
        let size = along(dir, rect.size());
        let parent = parent_name(&layout.root, &at.name.0)
            .and_then(|name| laid.rect(&name.0))
            .unwrap_or_else(|| ui.max_rect());
        let room = along(dir, parent.size()) - along(dir, strip.size());
        let label = names.resize(&at.name);
        let area_id = id.with(("over", &at.name.0));
        pin(ui, sublayer_of, area_id);
        let mut resized = None;
        egui::Area::new(area_id)
            .order(Order::Foreground)
            .fixed_pos(rect.min)
            .constrain(false)
            .movable(false)
            .show(ui.ctx(), |ui| {
                ui.allocate_rect(rect, Sense::click());
                painter.flyout_frame(
                    ui.painter(),
                    &FlyoutPaint {
                        rect,
                        zone: &at.name,
                        key: None,
                        style,
                    },
                );
                zone_ui_at(ui, id, &zone, laid, names, viewer);

                // Its free edge resizes it, within its least and largest
                // sizes and the room past its strip.
                if at.least >= at.most {
                    return;
                }
                let cursor = match dir {
                    Dir::Horizontal => egui::CursorIcon::ResizeHorizontal,
                    Dir::Vertical => egui::CursorIcon::ResizeVertical,
                };
                let response = ui
                    .interact(edge, area_id.with("edge"), Sense::drag())
                    .on_hover_and_drag_cursor(cursor);
                response.widget_info(|| WidgetInfo::labeled(Role::Splitter, true, &label));
                painter.over_edge(
                    ui.painter(),
                    &SashPaint {
                        rect: span(
                            dir,
                            rect,
                            free_edge - style.sash_width * 0.5,
                            free_edge + style.sash_width * 0.5,
                        ),
                        axis: match dir {
                            Dir::Horizontal => SeparatorAxis::Vertical,
                            Dir::Vertical => SeparatorAxis::Horizontal,
                        },
                        state: PartState::NONE
                            .with(PartState::HOVERED, response.hovered())
                            .with(PartState::PRESSED, response.is_pointer_button_down_on())
                            .with(PartState::DRAGGED, response.dragged()),
                        zone: &at.name,
                        style,
                    },
                );
                let delta = along(dir, response.drag_delta());
                if delta != 0.0 {
                    let sign = if towards_end { 1.0 } else { -1.0 };
                    let most = at.most.min(room).max(at.least);
                    let new = (size + sign * delta).clamp(at.least, most);
                    if new != size {
                        resized = Some(new);
                    }
                }
            });
        if let Some(size) = resized
            && let Some(zone) = layout.zone_mut(&at.name.0)
        {
            zone.state.size = Some(size);
            events.push(LayoutEvent::Resized {
                zone: at.name.clone(),
                size,
            });
        }
        let inside = [rect, strip, edge];
        if dismissed(ui, dismiss, &inside, host)
            && let Some(event) = layout.close_over(&at.name)
        {
            events.push(event);
        }
    }
}

/// Makes the area `area_id`'s layer a sublayer of `parent`, when the host
/// gave one ([`LayoutArea::sublayer_of`](super::LayoutArea::sublayer_of)).
fn pin(ui: &Ui, parent: Option<LayerId>, area_id: Id) {
    if let Some(parent) = parent {
        ui.ctx()
            .set_sublayer(parent, LayerId::new(Order::Foreground, area_id));
    }
}

/// Draws the flyout next to its zone's strip, in front of the others, with
/// its free edge that resizes it; returns its rect. What `dismiss` says
/// (by default a press outside it, or Escape), or its zone no longer
/// folded, asks to close it.
#[expect(
    clippy::too_many_arguments,
    reason = "the area's parts, borrowed apart"
)]
pub(super) fn flyout(
    ui: &mut Ui,
    id: Id,
    layout: &mut Layout,
    laid: &Laid,
    flyout: &Flyout,
    style: &LayoutStyle,
    painter: &dyn LayoutPainter,
    viewer: &mut dyn ZoneViewer,
    names: &Names<'_>,
    (dismiss, host): (Dismiss, Option<Inside<'_>>),
    sublayer_of: Option<LayerId>,
    events: &mut Vec<LayoutEvent>,
) -> Option<Rect> {
    let closed = || LayoutEvent::FlyoutClosed {
        key: flyout.key.clone(),
    };
    let at = laid.get(&flyout.zone.0);
    let Some((at, strip)) = at.and_then(|at| {
        matches!(at.shown, Shown::Folded | Shown::AutoFolded)
            .then_some(at)
            .zip(at.strip)
    }) else {
        events.push(closed());
        return None;
    };
    let dir = parent_dir(&layout.root, &at.name.0).unwrap_or_default();
    let parent = parent_name(&layout.root, &at.name.0)
        .and_then(|name| laid.rect(&name.0))
        .unwrap_or_else(|| ui.max_rect());
    let (start, end) = (
        along(dir, parent.min.to_vec2()),
        along(dir, parent.max.to_vec2()),
    );
    let towards_end = along(dir, strip.center().to_vec2()) < (start + end) * 0.5;
    let size = layout
        .flyouts
        .get(&flyout.key)
        .copied()
        .or_else(|| layout.zone(&at.name.0).and_then(|zone| zone.state.size))
        .unwrap_or(style.flyout_size);
    let rect_of = |size: f32| {
        if towards_end {
            let from = along(dir, strip.max.to_vec2());
            span(dir, parent, from, (from + size).min(end))
        } else {
            let to = along(dir, strip.min.to_vec2());
            span(dir, parent, (to - size).max(start), to)
        }
    };
    let rect = rect_of(size);
    let free_edge = if towards_end {
        along(dir, rect.max.to_vec2())
    } else {
        along(dir, rect.min.to_vec2())
    };
    let edge = span(
        dir,
        rect,
        free_edge - style.sash_grab * 0.5,
        free_edge + style.sash_grab * 0.5,
    );
    let area_id = id.with(("flyout", &flyout.key));
    pin(ui, sublayer_of, area_id);
    let title = viewer.flyout_title(flyout);
    let label = names.resize_flyout(&title);
    let mut resized = None;
    egui::Area::new(area_id)
        .order(Order::Foreground)
        .fixed_pos(rect.min)
        .constrain(false)
        .movable(false)
        .show(ui.ctx(), |ui| {
            ui.allocate_rect(rect, Sense::click());
            painter.flyout_frame(
                ui.painter(),
                &FlyoutPaint {
                    rect,
                    zone: &at.name,
                    key: Some(&flyout.key),
                    style,
                },
            );
            // The content is a pane named after the flyout, as a zone's is.
            let mut child = ui.new_child(
                UiBuilder::new()
                    .id_salt(area_id.with("content"))
                    .max_rect(rect)
                    .accessibility_role(Role::Pane)
                    .accessibility_label(title),
            );
            child.set_clip_rect(rect);
            super::area::set_bounds(ui.ctx(), child.unique_id(), rect);
            viewer.flyout(&mut child, flyout);

            let cursor = match dir {
                Dir::Horizontal => egui::CursorIcon::ResizeHorizontal,
                Dir::Vertical => egui::CursorIcon::ResizeVertical,
            };
            let response = ui
                .interact(edge, area_id.with("edge"), Sense::drag())
                .on_hover_and_drag_cursor(cursor);
            response.widget_info(|| WidgetInfo::labeled(Role::Splitter, true, &label));
            let delta = along(dir, response.drag_delta());
            if delta != 0.0 {
                let sign = if towards_end { 1.0 } else { -1.0 };
                let least = style.strip * 2.0;
                let new = (size + sign * delta).clamp(least, (end - start).max(least));
                if new != size {
                    resized = Some(new);
                }
            }
        });
    if let Some(size) = resized {
        layout.flyouts.insert(flyout.key.clone(), size);
        events.push(LayoutEvent::FlyoutResized {
            key: flyout.key.clone(),
            size,
        });
    }
    if dismissed(ui, dismiss, &[rect, strip, edge], host) {
        events.push(closed());
    }
    Some(rect)
}

/// Whether the folded zone `at`'s strip opens towards the end of its parent
/// split (a column on the left opens rightwards).
fn towards_end(
    layout: &Layout,
    laid: &Laid,
    ui: &Ui,
    at: &LaidZone,
    strip: Rect,
    dir: Dir,
) -> bool {
    let parent = parent_name(&layout.root, &at.name.0)
        .and_then(|name| laid.rect(&name.0))
        .unwrap_or_else(|| ui.max_rect());
    let (start, end) = (
        along(dir, parent.min.to_vec2()),
        along(dir, parent.max.to_vec2()),
    );
    along(dir, strip.center().to_vec2()) < (start + end) * 0.5
}

/// What the edge band of a folded zone's strip did this frame.
enum DragOut {
    /// Nothing that changes the zone.
    None,
    /// Pressed and released without moving: a click, which the strip takes
    /// like its grip's.
    Clicked,
    /// Dragged out and released: the zone unfolded.
    Unfolded,
}

/// The edge of a folded zone's strip facing its neighbour, dragged: past
/// half the zone's least size, the zone unfolds on release, at the size
/// dragged to, with a guide line meanwhile. The band lies across the edge,
/// or, on a strip narrower than twice the band, just outside it so that
/// the strip stays a button; a press there without motion is a click.
#[expect(
    clippy::too_many_arguments,
    reason = "the area's parts, borrowed apart"
)]
fn drag_out(
    ui: &mut Ui,
    id: Id,
    layout: &mut Layout,
    laid: &Laid,
    at: &LaidZone,
    strip: Rect,
    dir: Dir,
    style: &LayoutStyle,
    painter: &dyn LayoutPainter,
) -> DragOut {
    let towards_end = towards_end(layout, laid, ui, at, strip, dir);
    let edge = if towards_end {
        along(dir, strip.max.to_vec2())
    } else {
        along(dir, strip.min.to_vec2())
    };
    let sign = if towards_end { 1.0 } else { -1.0 };
    let breadth = along(dir, strip.size());
    let grab = style.sash_grab;
    let band = if breadth < 2.0 * grab {
        // Outside a narrow strip, which it would otherwise mostly cover.
        let (a, b) = (edge, edge + sign * grab);
        span(dir, strip, a.min(b), a.max(b))
    } else {
        span(dir, strip, edge - grab * 0.5, edge + grab * 0.5)
    };
    let edge_id = id.with(("strip_edge", &at.name.0));
    // Not a keyboard stop: the grip is the strip's.
    let cursor = match dir {
        Dir::Horizontal => CursorIcon::ResizeHorizontal,
        Dir::Vertical => CursorIcon::ResizeVertical,
    };
    let response = ui
        .interact(band, edge_id, Sense::CLICK | Sense::DRAG)
        .on_hover_and_drag_cursor(cursor);
    if response.clicked() {
        return DragOut::Clicked;
    }
    let delta = along(dir, response.drag_delta());
    let total_id = edge_id.with("total");
    let mut total = None;
    if response.dragged() || delta != 0.0 {
        total = Some(ui.ctx().data_mut(|d| {
            let total = d.get_temp_mut_or_insert_with(total_id, || 0.0_f32);
            *total += sign * delta;
            *total
        }));
    }
    if !response.dragged()
        && let Some(done) = ui.ctx().data_mut(|d| d.remove_temp::<f32>(total_id))
    {
        total = Some(done);
    }
    let Some(total) = total else {
        return DragOut::None;
    };
    // The zone's size were it unfolded at the pointer: from the strip's far
    // edge to it.
    let extent = breadth + total;
    let unfolds = total > 0.0 && extent >= at.least * 0.5;
    let size = extent.clamp(at.least, at.most.max(at.least));
    if response.dragged() && unfolds {
        // Across the strip's breadth, the split's.
        let at_size = edge - sign * breadth + sign * size;
        let line = span(dir, strip, at_size, at_size);
        paint_guide(
            ui,
            id,
            painter,
            &SnapGuidePaint {
                line: [line.min, line.max],
                axis: match dir {
                    Dir::Horizontal => SeparatorAxis::Vertical,
                    Dir::Vertical => SeparatorAxis::Horizontal,
                },
                kind: SnapKind::Unfold,
                zone: &at.name,
                style,
            },
        );
    }
    if response.drag_stopped() && unfolds {
        if let Some(zone) = layout.zone_mut(&at.name.0) {
            zone.state.size = Some(size);
        }
        layout.set_folded(&at.name.0, false);
        return DragOut::Unfolded;
    }
    DragOut::None
}