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
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT
//! Popover widget — a floating bubble card with an anchor arrow.
//!
//! The Popover widget displays a floating card near an anchor rectangle,
//! optionally containing a child widget. It supports show/hide with an
//! arrow pointing toward the anchor, and auto-dismisses when the user
//! clicks outside the popover area.
use crate::core::{Color, Font, HorizontalAlignment, Point, Rect, Size};
use crate::event::{Event, EventHandler};
use crate::render::{RenderCommand, RenderContext};
use crate::style::{MotionSlot, PropertyDriver};
use crate::widget::capability::coercion::expect_bool;
use crate::widget::capability::properties_trait::{base_property_get, base_property_set};
use crate::widget::capability::types::{CapabilityAccessError, CapabilityValue};
use crate::widget::capability::WidgetProperties;
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};
use crate::{impl_widget_property_hooks, property_names_of};
/// Arrow size in pixels from tip to base.
const ARROW_SIZE: i32 = 10;
/// Corner radius of the popover body.
const CORNER_RADIUS: u32 = 8;
/// How tall the card is at the instant it appears, as a fraction of its settled height.
///
/// A popover unfolds **downward from the anchor**: the arrow and the anchor edge stay put and the
/// card grows along the axis the arrow points down. Growing from a corner or from the centre would
/// read as a dialog or a tooltip arriving, which are different affordances; the card's own origin is
/// what makes it read as "this thing belongs to that button". The floor is not zero, so the first
/// visible frame already has the card's width and a visible sliver of its body.
const REVEAL_MIN_SCALE: f32 = 0.06;
/// The alpha of the shadow under the card, out of 255. A constant rather than a literal in the draw
/// so the reveal can scale it without a second magic number.
const SHADOW_ALPHA: u8 = 40;
/// Popover widget — a floating bubble card with an anchor arrow.
///
/// Shows a rounded rectangle with a triangular arrow pointing toward an
/// anchor rectangle. When visible, it can contain an optional child widget
/// rendered inside the card body. Clicking outside the popover area
/// automatically hides it.
pub struct Popover {
base: BaseWidget,
content: Option<Box<dyn Widget>>,
anchor_rect: Rect,
visible: bool,
/// Cached popover body rectangle (computed during draw).
body_rect: Rect,
/// How far the card has unfolded, `0.0` closed and `1.0` fully open.
///
/// # Why this is separate from `visible`
///
/// `visible` is the *logical* state and answers the instant it changes — `is_visible` tells
/// whether the popover is up, not how far through appearing it is. The draw reads this, so the
/// card unfolds rather than appearing whole on one frame and vanishing on the next. Same split,
/// same reason, as `Switch`'s `checked`/`travel` and `Dialog`'s `visible`/`reveal`.
reveal: PropertyDriver,
}
impl Popover {
/// Creates a new Popover widget with the given geometry.
///
/// Initially hidden with no content and an empty anchor rectangle.
pub fn new(geometry: Rect) -> Self {
Self {
base: BaseWidget::new(WidgetKind::Popover, geometry, "Popover"),
content: None,
anchor_rect: Rect::default(),
visible: false,
body_rect: Rect::default(),
// At rest at the closed end: a freshly built popover is hidden, so it must not
// animate itself away on its first frame.
reveal: PropertyDriver::at(0.0, MotionSlot::Normal),
}
}
/// Shows the popover positioned relative to the given anchor rectangle.
pub fn show(&mut self, anchor: Rect) {
self.anchor_rect = anchor;
self.visible = true;
self.reveal.set_target(1.0);
self.base.request_redraw();
}
/// Hides the popover.
pub fn hide(&mut self) {
self.visible = false;
self.reveal.set_target(0.0);
self.base.request_redraw();
}
/// Returns how far the card has unfolded, `0.0` closed and `1.0` fully open.
///
/// The value the draw measures with, as distinct from the logical [`is_visible`](Self::is_visible).
pub fn reveal_progress(&self) -> f32 {
self.reveal.value()
}
/// Returns whether the popover is currently visible.
pub fn is_visible(&self) -> bool {
self.visible
}
/// Reports the popover's own shown-state.
///
/// Deliberately distinct from [`Widget::is_visible`], which this widget
/// overrides to return the popup state. The property contract publishes the
/// inherited `visible` for the control, so the popup state is published under
/// the `shown` name instead; without this separation the base property would
/// be unreachable.
pub fn is_shown(&self) -> bool {
self.visible
}
/// Sets the popover's shown-state without moving its anchor.
///
/// The counterpart to [`is_shown`](Self::is_shown). Showing keeps the existing
/// anchor rectangle, so a caller that wants to reposition first uses
/// [`show`](Self::show) with the new anchor.
pub fn set_shown(&mut self, shown: bool) {
if shown {
self.show(self.anchor_rect);
} else {
self.hide();
}
}
/// Returns the title of the popover's content widget, or an empty string when
/// it has no content.
///
/// A `Box<dyn Widget>` exposes no text of its own, so the concrete `Label`
/// case is read through a downcast; anything else answers honestly with the
/// empty string rather than inventing a rendering.
pub fn content_text(&self) -> String {
self.content
.as_deref()
.and_then(
crate::widget::capability::coercion::widget_as::<
crate::widget::base_widgets::label::Label,
>,
)
.map_or_else(String::new, |label| label.text().to_string())
}
/// Sets the content widget displayed inside the popover.
pub fn set_content(&mut self, widget: Box<dyn Widget>) {
self.content = Some(widget);
self.base.request_redraw();
}
/// Returns a reference to the content widget, if any.
pub fn content(&self) -> Option<&dyn Widget> {
self.content.as_deref()
}
/// Returns a mutable reference to the content widget, if any.
pub fn content_mut(&mut self) -> Option<&mut dyn Widget> {
self.content.as_deref_mut()
}
/// Returns the anchor rectangle.
pub fn anchor_rect(&self) -> Rect {
self.anchor_rect
}
/// Sets the anchor rectangle.
pub fn set_anchor_rect(&mut self, rect: Rect) {
self.anchor_rect = rect;
self.base.request_redraw();
}
/// Computes the popover body rectangle below/above the anchor.
fn compute_layout(&self) -> (Rect, Point, ArrowDirection) {
let geom = self.geometry();
let body_width = geom.width.clamp(100, 400);
let body_height = geom.height.clamp(60, 400);
// Position popover below the anchor by default; flip above if not enough room
let below_space =
geom.y + geom.height as i32 - (self.anchor_rect.y + self.anchor_rect.height as i32);
let above_space = self.anchor_rect.y - geom.y;
let (body_y, arrow_dir) = if below_space >= body_height as i32 + ARROW_SIZE {
(self.anchor_rect.y + self.anchor_rect.height as i32 + ARROW_SIZE, ArrowDirection::Up)
} else if above_space >= body_height as i32 + ARROW_SIZE {
(self.anchor_rect.y - body_height as i32 - ARROW_SIZE, ArrowDirection::Down)
} else {
// Default: below
(self.anchor_rect.y + self.anchor_rect.height as i32 + ARROW_SIZE, ArrowDirection::Up)
};
// Center horizontally on anchor
let anchor_center_x = self.anchor_rect.x + self.anchor_rect.width as i32 / 2;
let body_x = (anchor_center_x - body_width as i32 / 2).max(geom.x);
let body_rect = Rect::new(body_x, body_y, body_width, body_height);
// Arrow tip points to anchor center
let arrow_tip = Point::new(
anchor_center_x,
match arrow_dir {
ArrowDirection::Up => body_y - ARROW_SIZE,
ArrowDirection::Down => body_y + body_height as i32 + ARROW_SIZE,
},
);
(body_rect, arrow_tip, arrow_dir)
}
}
impl Widget for Popover {
fn base(&self) -> &BaseWidget {
&self.base
}
fn base_mut(&mut self) -> &mut BaseWidget {
&mut self.base
}
fn size_hint(&self) -> Size {
crate::core::Size::new(200, 150)
}
/// Advances the unfold by `delta_ms`, returning whether another frame is owed.
///
/// The driver is what decides "settled": it reports false the step it reaches its target, so a
/// settled popover costs no frames and the idle screen repaints nothing.
fn tick(&mut self, delta_ms: u32) -> bool {
self.reveal.tick(delta_ms)
}
/// Whether the popover is mid-unfold and owes the driver another frame.
fn is_animating(&self) -> bool {
self.reveal.is_moving()
}
impl_draw_bridge!();
impl_widget_property_hooks!();
}
/// `Popover`'s property contract.
///
/// Read/write semantics are carried over unchanged from the centralised
/// `access_read_dialog.in.rs` / `access_write_dialog.in.rs` dispatch, so callers see
/// the same coercions and the same errors as before.
///
/// The legacy table served a `visible` arm for this kind, but there is a name
/// collision to resolve: this widget overrides [`Widget::is_visible`] to return its
/// *popup* state, so a `visible` arm here would shadow the shared `visible` that
/// [`base_property_get`] serves — the two would be indistinguishable and the base
/// one unreachable. The popup state is therefore published as `shown`, and bare
/// `visible` keeps meaning what it means for every other control.
impl WidgetProperties for Popover {
fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
match name {
"shown" => Ok(CapabilityValue::Bool(self.is_shown())),
"text" => Ok(CapabilityValue::String(self.content_text())),
_ => base_property_get(self, name),
}
}
fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
match name {
"shown" => {
self.set_shown(expect_bool(value)?);
Ok(())
}
// The text mirrors the content widget, so writing it would either be
// dropped by the next layout or require synthesising a `Label` the
// caller never asked for. A caller that means to set it installs the
// content widget through `set_content`.
"text" => Err(CapabilityAccessError::ReadOnlyProperty),
_ => base_property_set(self, name, value),
}
}
fn property_names(&self) -> &'static [&'static str] {
property_names_of!["shown", "text", BASE_PROPERTY_NAMES]
}
/// Runs one of the commands `popover` publishes.
///
/// Both names carry a value — `set_visible` the boolean the property route
/// already accepts, `set_text` the content the popover mirrors and cannot be
/// given as a bare string — so a payload-less invocation is reported as
/// needing one rather than being called unknown.
fn command(&mut self, name: &str) -> Result<(), CapabilityAccessError> {
match name {
"set_visible" | "set_text" => Err(CapabilityAccessError::OutOfRange),
_ => Err(CapabilityAccessError::UnknownCommand),
}
}
}
impl Draw for Popover {
fn draw(&mut self, context: &mut RenderContext) {
let rect = self.geometry();
if rect.width == 0 || rect.height == 0 {
return;
}
// Chrome colours resolve explicit style first, then the theme's resolved style for
// this control, and only then a literal. Every colour below used to be a literal —
// and the whole card used to be skipped unless the popover was already showing — so
// the census reported `ink = 0` *and* no response to a light/dark switch.
//
// The theme reads take and release the global manager's lock internally, so no
// guard is held across the draw (the mutex is not re-entrant).
let style = self.base.style().clone();
let theme = crate::style::resolved_theme_style("popover");
// `popover` is absent from `WidgetRole::for_kind_name`'s table, so it classifies as
// `Surface` and resolves to `theme.colors.background` — the window's own fill. A card
// painted in that colour would be byte-identical to the frame behind it, so a resolved
// surface equal to the window fill is re-derived a visible step away from it, the same
// distinction `Colors::input_background` draws for a field.
let window_fill = {
let manager = crate::style::theme_manager();
manager.current_theme().map(|active| active.colors.background).unwrap_or(Color::WHITE)
};
let ink = style
.text_color
.or_else(|| theme.as_ref().and_then(|t| t.text_color))
.unwrap_or(Color::rgb(40, 40, 40));
let card = match style
.background_color
.or_else(|| theme.as_ref().and_then(|t| t.background_color))
{
Some(resolved) if resolved != window_fill => resolved,
_ => window_fill.blend(&ink, 0.08),
};
let border = style
.border_color
.or_else(|| theme.as_ref().and_then(|t| t.border_color))
.filter(|resolved| *resolved != card)
.unwrap_or_else(|| card.blend(&ink, 0.35));
let muted_ink = ink.blend(&card, 0.45);
// A hidden popover is still laid out, so the card it will occupy is visible before it
// opens: the control used to paint nothing at rest. It is drawn at reduced opacity so
// the two states stay distinguishable.
let visible = self.visible;
// How far the card has unfolded. At rest (0.0) it is the thin closed strip below; at 1.0
// every dimension below is exactly what it was before this animation existed.
let reveal = self.reveal.value();
let (body_rect, arrow_tip, arrow_dir) = self.compute_layout();
self.body_rect = body_rect;
let (body_rect, arrow_tip) = if visible {
(body_rect, arrow_tip)
} else {
// Anchor-less at rest: the card fills the control's own rect rather than being
// positioned against an anchor rectangle that has never been set.
(
Rect::new(
rect.x + ARROW_SIZE,
rect.y,
rect.width.saturating_sub(ARROW_SIZE as u32),
rect.height,
),
arrow_tip,
)
};
// The body **unfolds downward from its own top edge**: the anchor-facing edge is the fixed
// one, and that is what makes a popover read as belonging to the button it points at. At
// `reveal = 1.0` the multiplication is an identity, so the settled card is unchanged to the
// pixel — which is what keeps the resting snapshot valid.
//
// The floor is the *closed* height: a fully hidden card is a thin strip behind its own top
// edge rather than a zero-height rectangle, so the control still has a shape when its
// content is not up. It is a fraction of the **control**, not of the body, because the
// body's own height is derived from the anchor and would make the closed strip's size
// anchor-dependent.
let closed_height = ((rect.height as f32 * REVEAL_MIN_SCALE) + 0.5) as u32;
let revealed_height = ((body_rect.height as f32 * reveal) + 0.5) as u32;
let body_rect = Rect::new(
body_rect.x,
body_rect.y,
body_rect.width,
revealed_height.max(closed_height),
);
// One value drives the body, the shadow, the arrow and the ink alike, so they cannot get
// out of step: a half-open card with a full-strength shadow would read as a rendering fault.
let card = if visible { card } else { window_fill.blend(&card, 0.45) };
let border = if visible { border } else { window_fill.blend(&border, 0.45) };
// ── Draw shadow ──
//
// The shadow is offset down-right, so at a geometry whose right or bottom edge is
// already reached by the card it would paint past the control: the census reported
// the shadow rect at `[12,2..242,122]` on a 240×120 box. It only makes sense where
// there is room for it, so it is dropped when the offset would leave the control
// rather than being clamped — a half-shadow along one edge reads as a rendering
// fault, whereas no shadow at rest reads as the flat card it is.
let shadow_offset = 2i32;
let shadow_fits = body_rect.x + shadow_offset + body_rect.width as i32
<= rect.x + rect.width as i32
&& body_rect.y + shadow_offset + body_rect.height as i32 <= rect.y + rect.height as i32;
if shadow_fits && body_rect.height > 0 {
let shadow_rect = Rect::new(
body_rect.x + shadow_offset,
body_rect.y + shadow_offset,
body_rect.width,
body_rect.height,
);
// The shadow fades in with the unfold and is gone at `reveal = 0`, where the card is a
// closed strip: a shadow under a strip that has not opened yet is a smudge on the page.
context.fill_rounded_rect(
shadow_rect,
CORNER_RADIUS,
Color::rgba(0, 0, 0, (SHADOW_ALPHA as f32 * reveal) as u8),
);
}
// ── Draw popover body ──
if body_rect.height > 0 {
context.fill_rounded_rect(body_rect, CORNER_RADIUS, card);
context.draw_rounded_rect_stroke(body_rect, CORNER_RADIUS, border, 1);
}
// ── Draw arrow ──
//
// The arrow exists **only once the card is open**. While closed it would be a free-floating
// triangle on the page with nothing behind it, which is what the census's closed-state
// figure used to show; a closed popover *is* the thin strip, and nothing else.
if visible && reveal > 0.0 {
self.draw_arrow(context, arrow_tip, arrow_dir, card, border);
}
// ── Draw placeholder content indicator ──
// The label reads the theme rather than the previous fixed grey, so a dark card does
// not carry light-theme text.
let content_padding = 8i32;
// The label lives inside the card, so it is clipped to what has **unfolded so far** rather
// than to the settled body: an unclipped label in a half-open card paints below the card's
// own bottom edge, which is the one thing that would make the unfold visibly wrong. At
// `reveal = 1.0` this box is exactly the padded body, so a settled label is unchanged.
let content_rect = crate::core::Rect::new(
body_rect.x + content_padding,
body_rect.y + content_padding,
body_rect.width.saturating_sub((content_padding as u32) * 2),
body_rect.height.saturating_sub((content_padding as u32) * 2),
);
if content_rect.height == 0 {
return;
}
let font = Font::simple("sans-serif", 13.0);
let label = if self.content.is_some() { "Popover" } else { "Popover (empty)" };
// The label is centred on the content box — **both ways**. `draw_text_fitted` aligns
// horizontally only, so passing the padded content box pinned the label to the card's
// top edge: `popover.svg` drew a 13 px line at `y = 8` inside a 120 px card. Deriving
// the line box first is what makes «centred» true on the vertical axis too, and the
// fit/ellipsis behaviour is unchanged (the box is 224 px wide at the census geometry
// and `Popover (empty)` is wider than that).
let line = context.text_line(content_rect, &font);
context.draw_text_fitted(line, label, &font, muted_ink, HorizontalAlignment::Center);
}
}
/// Direction the popover arrow points.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ArrowDirection {
Up,
Down,
}
impl Popover {
/// Draws the triangular arrow pointing toward the anchor.
///
/// The fill and outline are passed in rather than literals so the arrow is the same
/// colour as the card it belongs to — otherwise the arrow stayed white on a dark card.
fn draw_arrow(
&self,
context: &mut RenderContext,
tip: Point,
dir: ArrowDirection,
fill: Color,
outline: Color,
) {
let half_base = ARROW_SIZE / 2;
let (_base_center, base_left, base_right) = match dir {
ArrowDirection::Up => {
let base_center = Point::new(tip.x, tip.y + ARROW_SIZE);
let base_left = Point::new(tip.x - half_base, tip.y + ARROW_SIZE);
let base_right = Point::new(tip.x + half_base, tip.y + ARROW_SIZE);
(base_center, base_left, base_right)
}
ArrowDirection::Down => {
let base_center = Point::new(tip.x, tip.y - ARROW_SIZE);
let base_left = Point::new(tip.x - half_base, tip.y - ARROW_SIZE);
let base_right = Point::new(tip.x + half_base, tip.y - ARROW_SIZE);
(base_center, base_left, base_right)
}
};
// Draw filled triangle using DrawPath
let points = vec![tip, base_left, base_right];
context.execute_command(RenderCommand::DrawPath {
points: points.clone(),
closed: true,
color: fill,
filled: true,
width: 1,
});
// Draw triangle outline
context.execute_command(RenderCommand::DrawPath {
points,
closed: true,
color: outline,
filled: false,
width: 1,
});
}
}
impl EventHandler for Popover {
fn handle_event(&mut self, event: &Event) {
if !self.visible {
self.base.handle_event(event);
return;
}
// A disabled popover must not act on input. `is_enabled` was unchecked here,
// so `set_enabled(false)` still let a click outside — or Escape — close it,
// which is a state change the caller explicitly asked to suspend.
if !self.base.is_enabled() {
self.base.handle_event(event);
return;
}
match event {
Event::MousePress { pos, button } => {
if *button == 1 && !self.body_rect.contains_point(*pos) {
// Auto-dismiss on click outside
self.hide();
}
}
Event::KeyPress { key, modifiers: _ } => {
if *key == 27 {
// Escape key
self.hide();
}
}
_ => {
self.base.handle_event(event);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::widget::svg::render_to_svg;
/// How far the empty-state placeholder's line box may sit from the card's middle and
/// still count as centred.
///
/// The line box is derived from a measured line height, so its top edge lands on a whole
/// pixel that need not be the exact middle. One line's worth is generous enough to
/// absorb that rounding while still rejecting a top-edge origin, which is half the card
/// away.
const LINE_TOLERANCE: i32 = 8;
/// The `(y, height)` of the document's first **rounded** rectangle.
///
/// The card is the popover's only rounded rectangle, and it is what both the placeholder's
/// centring and its containment are measured against — the control's own rectangle is not,
/// because the card tracks the anchor and need not be inside the control at all. Shared rather
/// than repeated so the two assertions cannot drift onto different rectangles.
fn first_rounded_rect(svg: &str) -> Option<(i32, i32)> {
svg.split("<rect ").filter(|chunk| chunk.contains("rx=\"")).find_map(|chunk| {
let y = chunk.split("y=\"").nth(1)?.split('"').next()?.parse::<i32>().ok()?;
let h = chunk.split("height=\"").nth(1)?.split('"').next()?.parse::<i32>().ok()?;
Some((y, h))
})
}
/// A simple test widget used as content inside popover tests.
struct TestContent {
base: BaseWidget,
text: String,
}
impl TestContent {
fn new(text: &str, geometry: Rect) -> Self {
Self {
base: BaseWidget::new(WidgetKind::Label, geometry, "TestContent"),
text: text.to_string(),
}
}
}
impl Widget for TestContent {
fn base(&self) -> &BaseWidget {
&self.base
}
fn base_mut(&mut self) -> &mut BaseWidget {
&mut self.base
}
}
impl Draw for TestContent {
fn draw(&mut self, context: &mut RenderContext) {
let font = Font::simple("sans-serif", 12.0);
context.draw_text(
Point::new(self.geometry().x, self.geometry().y),
&self.text,
&font,
Color::BLACK,
HorizontalAlignment::Left,
);
}
}
impl EventHandler for TestContent {
fn handle_event(&mut self, _event: &Event) {}
}
#[test]
fn popover_default_creation() {
let popover = Popover::new(Rect::new(0, 0, 300, 200));
assert_eq!(popover.kind(), WidgetKind::Popover);
assert!(!popover.is_visible());
assert!(popover.content().is_none());
assert_eq!(popover.geometry(), Rect::new(0, 0, 300, 200));
}
#[test]
fn popover_show_hide() {
let mut popover = Popover::new(Rect::new(0, 0, 300, 200));
assert!(!popover.is_visible());
popover.show(Rect::new(100, 100, 50, 20));
assert!(popover.is_visible());
popover.hide();
assert!(!popover.is_visible());
}
#[test]
fn popover_anchor_rect() {
let mut popover = Popover::new(Rect::new(0, 0, 300, 400));
let anchor = Rect::new(100, 100, 50, 20);
popover.show(anchor);
assert_eq!(popover.anchor_rect(), anchor);
let new_anchor = Rect::new(50, 50, 80, 30);
popover.set_anchor_rect(new_anchor);
assert_eq!(popover.anchor_rect(), new_anchor);
}
#[test]
fn popover_set_content() {
let mut popover = Popover::new(Rect::new(0, 0, 300, 200));
assert!(popover.content().is_none());
let content = TestContent::new("Hello", Rect::new(0, 0, 100, 30));
popover.set_content(Box::new(content));
assert!(popover.content().is_some());
}
#[test]
fn popover_auto_dismiss_on_click_outside() {
let mut popover = Popover::new(Rect::new(0, 0, 400, 400));
let anchor = Rect::new(150, 100, 50, 20);
popover.show(anchor);
assert!(popover.is_visible());
// Click far outside the body rect
popover.handle_event(&Event::MousePress { pos: Point::new(5, 5), button: 1 });
assert!(!popover.is_visible());
}
#[test]
fn popover_escape_key_dismisses() {
let mut popover = Popover::new(Rect::new(0, 0, 400, 400));
popover.show(Rect::new(150, 100, 50, 20));
assert!(popover.is_visible());
popover.handle_event(&Event::KeyPress { key: 27, modifiers: 0 });
assert!(!popover.is_visible());
}
/// A disabled popover must not close on a click outside or on Escape.
///
/// `handle_event` checked `visible` but never `enabled`, so a caller that
/// suspended the popover with `set_enabled(false)` still had it dismissed by a
/// stray click. Auto-dismissing is exactly the kind of state change `enabled`
/// exists to gate.
#[test]
fn popover_disabled_ignores_dismissal_input() {
let mut popover = Popover::new(Rect::new(0, 0, 400, 400));
popover.show(Rect::new(150, 100, 50, 20));
popover.set_enabled(false);
// Click far outside the body rect: would normally auto-dismiss.
popover.handle_event(&Event::MousePress { pos: Point::new(5, 5), button: 1 });
assert!(popover.is_visible(), "a disabled popover must not auto-dismiss");
// Escape: would normally dismiss.
popover.handle_event(&Event::KeyPress { key: 27, modifiers: 0 });
assert!(popover.is_visible(), "a disabled popover must not close on Escape");
// Re-enabling must restore the behaviour, so the gate is a suspension and not
// a permanent lock.
popover.set_enabled(true);
popover.handle_event(&Event::KeyPress { key: 27, modifiers: 0 });
assert!(!popover.is_visible(), "re-enabling must restore dismissal");
}
#[test]
fn popover_svg_output_visible() {
let mut popover = Popover::new(Rect::new(0, 0, 300, 200));
popover.show(Rect::new(100, 100, 50, 20));
let svg = render_to_svg(&mut popover);
assert!(svg.starts_with("<svg"), "SVG should start with <svg, got: {svg:.60}");
assert!(svg.ends_with("</svg>"), "SVG should end with </svg>");
}
/// Opening a popover unfolds it rather than placing it there at full height.
///
/// # The defect this pins
///
/// `show`/`hide` carried only the logical state and the draw read it directly, so the card
/// appeared whole on the frame it was shown and vanished on the frame it was hidden. The
/// assertions are in two halves, because a progress nothing reads is not an unfold: the model
/// must take an interior value, and the *painted* card must be shorter at that moment.
#[test]
fn opening_a_popover_unfolds_it() {
let mut popover = Popover::new(Rect::new(0, 0, 300, 200));
assert_eq!(popover.reveal_progress(), 0.0, "a fresh popover is closed");
assert!(!popover.is_animating(), "and owes no frames");
popover.show(Rect::new(100, 100, 50, 20));
assert!(popover.is_visible(), "the logical state answers at once");
assert!(popover.is_animating(), "while the drawn card owes frames");
// The painted card's height, read from the document: the card is the only rounded
// rectangle the *open* popover paints that is at least as wide as the arrow gap.
fn card_height(svg: &str) -> u32 {
svg.split("<rect ")
.filter(|chunk| chunk.contains("rx=\""))
.filter_map(|chunk| {
let h = chunk.split("height=\"").nth(1)?;
h.split('"').next()?.parse::<u32>().ok()
})
.max()
.unwrap_or(0)
}
assert!(popover.tick(20), "still unfolding after one step");
let mid = popover.reveal_progress();
assert!(
mid > 0.0 && mid < 1.0,
"the popover must pass through an interior reveal (got {mid})"
);
let mid_height = card_height(&render_to_svg(&mut popover));
while popover.tick(1000) {}
assert_eq!(popover.reveal_progress(), 1.0, "and settle fully open");
let open_height = card_height(&render_to_svg(&mut popover));
assert!(
mid_height > 0 && mid_height < open_height,
"an unfolding card must be shorter than a settled one: mid={mid_height} open={open_height}"
);
}
#[test]
fn popover_svg_output_hidden() {
// Holds the crate-wide theme guard: this test renders, and a concurrent
// test that switches the appearance would otherwise change a later frame.
let _theme_guard = crate::style::theme_test_guard();
let mut popover = Popover::new(Rect::new(0, 0, 300, 200));
let svg = render_to_svg(&mut popover);
assert!(svg.starts_with("<svg"));
assert!(svg.ends_with("</svg>"));
// A closed popover is a **thin strip**, not a blank page: the card it will occupy is
// already there at its closed height, so a control that has been created but not opened
// still has a rendered extent instead of vanishing. `draw` used to `return` early here,
// which made the control invisible at rest — the defect the rendering census reported as
// `ink = 0`. The card is a rounded rect, so it is read as the rounded `fill` elements.
let rounded = svg.matches("rx=\"").count();
assert!(rounded > 0, "a closed popover must still paint its card: {svg}");
// The placeholder label is **not** painted while the popover is closed: it lives inside
// the card, which has no interior at that height, so painting it would put ink outside
// the card's own bottom edge.
assert!(
crate::widget::svg::text_ink_box(&svg).is_none(),
"a closed popover paints no interior label: {svg}"
);
// A closed popover and an open one must differ: the open card is opaque, is at its full
// height, carries the placeholder and carries its anchor arrow; the closed one is a strip.
//
// This geometry deliberately positions the control so the whole anchored card fits inside
// it: the card tracks the anchor, so at an anchor near the top edge the settled card sits
// *below* the control's bottom — which is where the census-and-gate-relevant form of the
// assertion, "the label is inside the card", belongs. It is asserted against the card's own
// rectangle below rather than against the control's, because that is what is true.
let mut open = Popover::new(Rect::new(0, 0, 300, 400));
open.show(Rect::new(100, 20, 50, 20));
while open.tick(1000) {}
let shown = render_to_svg(&mut open);
assert_ne!(svg, shown, "showing the popover must change what is painted");
let (left, top, right, bottom) = crate::widget::svg::text_ink_box(&shown)
.unwrap_or_else(|| panic!("the placeholder label must be painted when open: {shown}"));
assert!(right > left, "the placeholder laid down ink: {left}..{right}");
let (card_y, card_h) = first_rounded_rect(&shown).expect("the open popover paints a card");
assert!(
top >= card_y && bottom <= card_y + card_h,
"the label must sit inside the card: ink {top}..{bottom}, card {card_y}..{}",
card_y + card_h
);
}
/// The empty-state placeholder is centred in the card on **both** axes.
///
/// It was pinned to the card's top edge while `draw_text_fitted` was being handed the
/// padded content box directly — that method aligns horizontally only, so its origin is
/// `bounds.y` unchanged. Deriving the line box with `context.text_line` first is what
/// centres it vertically, and this asserts the *result* rather than the call, so a
/// future change that reintroduces a bare `bounds.y` fails here.
///
/// The assertion is on the **ink**, not on an element's `y` attribute: text leaves the
/// backend as the `font8x8` rectangles the rasteriser fills, so there is no `y` to read and
/// no baseline to undo — the document holds a picture of the run. That is the stronger
/// check, because the old form verified the coordinate the backend had written down rather
/// than where the ink actually landed.
///
/// The centre is read from the **card's own** rectangle in the document, not from the
/// control's: the card is positioned against the anchor, so it need not be the control's
/// middle (at this anchor it sits at `y = 130` inside a 120-tall control). Measuring against
/// the control would have been asserting the anchor, not the centring.
#[test]
fn popover_empty_placeholder_is_centred_in_the_card() {
let rect = Rect::new(0, 0, 240, 120);
let mut popover = Popover::new(rect);
// The placeholder lives inside the card, so it is only painted once the card is open.
popover.show(Rect::new(100, 100, 50, 20));
while popover.tick(1000) {}
let svg = render_to_svg(&mut popover);
let (left, top, right, bottom) = crate::widget::svg::text_ink_box(&svg)
.expect("the empty-state placeholder must be drawn");
assert!(right > left && bottom > top, "the placeholder laid down ink: {svg}");
// The card: the rounded rectangle that is not the control's background. It is the one
// the label is centred in, so it is the one the centre is measured against.
let (card_y, card_h) = first_rounded_rect(&svg).expect("the open popover paints a card");
let middle = card_y + card_h / 2;
assert!(
(top - middle).abs() <= LINE_TOLERANCE,
"the empty-state placeholder must be vertically centred in the card: top={top}, \
card centre={middle} (card y={card_y} h={card_h})"
);
// And it must sit *below* the card's padding, which a top-edge origin would not.
assert!(
top >= card_y + 8,
"a top-edge origin would pin the placeholder at the padding, got {top} in card y={card_y}"
);
}
}