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
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT
//! NavigationDrawer widget — an Android-style slide-out side navigation drawer.
//!
//! The NavigationDrawer presents a semi-transparent overlay behind a side panel
//! that lists navigation items (icon + label). It supports open/close state,
//! item selection, and emits signals for opened, closed, and item_selected events.
use crate::core::{Color, Font, HorizontalAlignment, Point, Rect};
use crate::event::{Event, EventHandler};
use crate::render::RenderContext;
use crate::signal::{GenericSignal, Signal1};
use crate::style::{MotionSlot, PropertyDriver};
use crate::widget::capability::coercion::{expect_bool, expect_f32};
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};
/// A single item in the navigation drawer, consisting of an icon and a label.
#[derive(Clone, Debug)]
pub struct DrawerItem {
/// Icon displayed as text (emoji or character).
pub icon: String,
/// Display label text.
pub label: String,
}
/// Navigation Drawer widget — an Android-style slide-out side navigation drawer.
///
/// The drawer can be opened and closed programmatically or by user interaction.
/// When open, it renders a semi-transparent overlay covering the full geometry
/// with a side panel on the left containing navigation items. Clicking an item
/// selects it and emits `item_selected`. Clicking the overlay closes the drawer.
pub struct NavigationDrawer {
base: BaseWidget,
/// Whether the drawer is currently open.
open: bool,
/// List of drawer items to display.
items: Vec<DrawerItem>,
/// Index of the currently selected item.
selected_index: usize,
/// Panel width in pixels.
panel_width: u32,
/// How far the panel has slid in, `0.0` fully closed and `1.0` fully open.
///
/// # Why this is separate from `open`
///
/// `open` is the logical state a caller reads the instant it changes; `slide` is what the draw
/// path positions the panel with. Drawing straight from `open` put the panel at its final place
/// on the first frame and removed it on the last, so a navigation drawer — which on every
/// platform that has one *slides* — appeared and vanished. Same split, same reason, as
/// `Switch`'s `checked`/`travel` and `BottomSheet`'s `open`/`rise`.
slide: PropertyDriver,
/// Emitted when the drawer opens.
pub opened: GenericSignal,
/// Emitted when the drawer closes.
pub closed: GenericSignal,
/// Emitted when an item is selected, with the index of the selected item.
pub item_selected: Signal1<usize>,
}
impl NavigationDrawer {
/// Creates a new NavigationDrawer widget with the given geometry.
///
/// The geometry should cover the full screen/overlay area. The side panel
/// defaults to 280px wide.
pub fn new(geometry: Rect) -> Self {
Self {
base: BaseWidget::new(WidgetKind::NavigationDrawer, geometry, "NavigationDrawer"),
open: false,
items: Vec::new(),
selected_index: 0,
panel_width: 280,
// At rest at the closed end: a freshly built drawer is closed, so it must not animate
// its panel away on the first frame.
slide: PropertyDriver::at(0.0, MotionSlot::Normal),
opened: GenericSignal::new(),
closed: GenericSignal::new(),
item_selected: Signal1::new(),
}
}
/// Opens the navigation drawer. Emits `opened` signal.
pub fn open(&mut self) {
if !self.open {
self.open = true;
// Aim the slide; the frames that follow carry the panel in. No redraw is requested,
// because a redraw is not what makes the motion visible -- `tick_animations` reports the
// movement itself, which is what keeps the loop painting.
self.slide.set_target(1.0);
self.opened.emit();
}
}
/// Closes the navigation drawer. Emits `closed` signal.
pub fn close(&mut self) {
if self.open {
self.open = false;
self.slide.set_target(0.0);
self.closed.emit();
self.base.request_redraw();
}
}
/// How far the panel has slid in, `0.0` closed and `1.0` fully open.
///
/// This is the *drawn* fraction: the panel's width and offset are both functions of it, so a
/// test can assert the drawer slid rather than appeared by sampling it per frame.
pub fn slide_progress(&self) -> f32 {
self.slide.value()
}
/// Advances the slide by `delta_ms`; `true` while it is still moving.
pub fn tick(&mut self, delta_ms: u32) -> bool {
self.slide.tick(delta_ms)
}
/// Whether the panel is between two positions -- answers only, never advances.
pub fn is_animating(&self) -> bool {
self.slide.is_moving()
}
/// Toggles the open/close state of the drawer.
pub fn toggle(&mut self) {
if self.open {
self.close();
} else {
self.open();
}
}
/// Returns whether the drawer is currently open.
pub fn is_open(&self) -> bool {
self.open
}
/// Adds a new item to the navigation drawer.
///
/// `icon` is a text/emoji character displayed to the left of the label.
pub fn add_item(&mut self, icon: &str, label: &str) {
self.items.push(DrawerItem { icon: icon.to_string(), label: label.to_string() });
self.base.request_redraw();
}
/// Sets the selected item index. Emits `item_selected` if changed.
pub fn set_selected_index(&mut self, index: usize) {
if index < self.items.len() && self.selected_index != index {
self.selected_index = index;
self.item_selected.emit(index);
self.base.request_redraw();
}
}
/// Returns the currently selected item index.
pub fn selected_index(&self) -> usize {
self.selected_index
}
/// Returns a reference to the items list.
pub fn items(&self) -> &[DrawerItem] {
&self.items
}
/// Returns the panel width in pixels.
pub fn panel_width(&self) -> u32 {
self.panel_width
}
/// Sets the panel width in pixels.
pub fn set_panel_width(&mut self, width: u32) {
self.panel_width = width;
self.base.request_redraw();
}
}
impl Widget for NavigationDrawer {
fn base(&self) -> &BaseWidget {
&self.base
}
fn base_mut(&mut self) -> &mut BaseWidget {
&mut self.base
}
fn size_hint(&self) -> crate::core::Size {
crate::core::Size::new(300, 400)
}
// The slide is the control's own animation; the trait spelling is what the frame bus reaches
// through `&mut dyn Widget`, which is the only way the panel actually travels.
fn tick(&mut self, delta_ms: u32) -> bool {
NavigationDrawer::tick(self, delta_ms)
}
fn is_animating(&self) -> bool {
NavigationDrawer::is_animating(self)
}
impl_draw_bridge!();
impl_widget_property_hooks!();
}
/// `NavigationDrawer`'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. `width` reports the panel
/// width, which is a `u32` internally and published as a `Float` to match the
/// legacy shape.
impl WidgetProperties for NavigationDrawer {
fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
match name {
"open" => Ok(CapabilityValue::Bool(self.is_open())),
"width" => Ok(CapabilityValue::Float(f64::from(self.panel_width()))),
_ => base_property_get(self, name),
}
}
fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
match name {
"open" => {
if expect_bool(value)? {
self.open();
} else {
self.close();
}
Ok(())
}
"width" => {
self.set_panel_width(expect_f32(value)? as u32);
Ok(())
}
_ => base_property_set(self, name, value),
}
}
fn property_names(&self) -> &'static [&'static str] {
property_names_of!["open", "width", BASE_PROPERTY_NAMES]
}
}
impl Draw for NavigationDrawer {
fn draw(&mut self, context: &mut RenderContext) {
let rect = self.geometry();
let is_enabled = self.base.is_enabled();
// Chrome colours resolve explicit style first, then the theme's resolved style for
// this control, and only then a literal. The theme step is what makes an appearance
// switch visible; the overlay, panel, header, items and divider used to be hardcoded
// literals, so light and dark rendered identically.
//
// 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("navigation_drawer");
// `navigation_drawer` 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 panel 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 = crate::style::theme_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(30, 30, 30));
// The selected item and the scrim are the accent: the hue a theme is expected to vary
// most, so selection follows the appearance rather than a literal blue.
let accent = crate::style::theme_manager()
.current_theme()
.map(|active| active.colors.primary)
.unwrap_or(Color::rgb(30, 100, 200));
let panel = 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 panel = if is_enabled { panel } else { panel.blend(&ink, 0.5) };
let border = style
.border_color
.or_else(|| theme.as_ref().and_then(|t| t.border_color))
.unwrap_or_else(|| panel.blend(&ink, 0.25));
// The header band and the selected row are chrome states derived from the panel, and
// the item separators are dimmer than the ink, so all three move with the appearance.
let header_color = panel.blend(&ink, 0.06);
let highlight_color = panel.blend(&accent, 0.2);
let divider_color = ink.with_alpha_f32(0.1);
// Draw the closed-state affordance and the sliding panel.
//
// # The two states, and why the closing state needs the panel too
//
// A fully closed drawer paints only its edge affordance — a drawer in its default state has
// to be visible, or the host cannot show that anything can be opened. Once the slide begins
// the panel is *partially* in, so the panel is drawn for every non-zero `slide`, at the width
// the slide calls for. The old code branched on the boolean, so the panel was either absent
// or complete and the closing animation would have had nothing to draw.
let slide = self.slide.value();
let full_width = self.panel_width.min(rect.width);
let panel_width = (full_width as f32 * slide) as u32;
if panel_width == 0 {
let handle_width = full_width.max(1);
let handle_rect = Rect::new(rect.x, rect.y, handle_width, rect.height);
context.fill_rect(handle_rect, panel.blend(&ink, 0.04));
// Leading edge stripe: the affordance that says "this opens".
context.fill_rect(Rect::new(rect.x, rect.y, 4.min(handle_width), rect.height), accent);
context.draw_rect_stroke(handle_rect, border, 1);
return;
}
// Draw the modal scrim covering the full geometry, fading in with the panel. Read from the
// `Scrim` role rather than built from the accent at a literal alpha: the role is what lets a
// theme express the dimming once (and what keeps a dark appearance from being *lit* by a
// scrim), which is the same reason every other modal in this crate reads it.
//
// A partially-open drawer dims partially, so the scrim's alpha scales with the slide — one
// form that works whether the theme authored a black veil or a translucent white wash.
let scrim = crate::style::layer_color(crate::style::LayerColor::Scrim)
.unwrap_or_else(|| ink.with_alpha(82));
if slide > 0.0 {
let scrim = scrim.with_alpha((scrim.a as f32 * slide) as u8);
context.fill_rect(rect, scrim);
}
// Draw side panel on the left, at the width the slide calls for.
let panel_rect = Rect::new(rect.x, rect.y, panel_width, rect.height);
context.fill_rect(panel_rect, panel);
// Draw a subtle right border on the panel
context.draw_rect_stroke(panel_rect, border.with_alpha_f32(0.2), 1);
// Draw header area
let header_height: u32 = 60;
let header_rect = Rect::new(rect.x, rect.y, panel_width, header_height);
context.fill_rect(header_rect, header_color);
// Draw header title text
let font = Font::new("sans-serif", 16.0, true, false);
let header_text = "Navigation";
let metrics = context.measure_text(header_text, &font);
let header_text_x = rect.x + 16;
// The origin is the glyph box's top edge, so centring on the header is half the line
// box; the old `+ ascent/2` sat the title half a line below the header's middle.
let header_text_y = rect.y + (header_height as i32 - metrics.height as i32) / 2;
context.draw_text(
Point::new(header_text_x, header_text_y),
header_text,
&font,
ink,
HorizontalAlignment::Left,
);
// Draw items vertically
let item_height: u32 = 48;
let item_font = Font::new("sans-serif", 14.0, false, false);
let icon_font = Font::new("sans-serif", 16.0, false, false);
let item_metrics = context.measure_text("A", &item_font);
let start_y = rect.y + header_height as i32;
for (i, item) in self.items.iter().enumerate() {
let y_offset = start_y + (i as i32 * item_height as i32);
let item_rect = Rect::new(rect.x, y_offset, panel_width, item_height);
// Highlight selected item
if i == self.selected_index {
context.fill_rect(item_rect, highlight_color);
} else {
// Resting rows keep the panel's own surface, so the selected row is the only
// one that reads as raised in either appearance.
context.fill_rect(item_rect, panel);
}
// Vertical center position for text: the origin is the glyph box's top edge, so
// the centre of the 48px row is `y_offset + (row - line box)/2`. The old
// `row/2 + ascent/2` sat the icon and label half a line below the row's middle.
let text_center_y = y_offset + (item_height as i32 - item_metrics.height as i32) / 2;
// Draw icon
let icon_x = rect.x + 16;
let icon_color = if i == self.selected_index { accent } else { ink };
context.draw_text(
Point::new(icon_x, text_center_y),
&item.icon,
&icon_font,
icon_color,
HorizontalAlignment::Left,
);
// Draw label
let icon_width: u32 = 24;
let label_x = rect.x + 16 + icon_width as i32 + 8;
let label_color = if i == self.selected_index { accent } else { ink };
context.draw_text(
Point::new(label_x, text_center_y),
&item.label,
&item_font,
label_color,
HorizontalAlignment::Left,
);
// Draw divider line between items
if i > 0 {
let divider_y = y_offset;
context.fill_rect(
Rect::new(rect.x + 16, divider_y, panel_width.saturating_sub(32), 1),
divider_color,
);
}
}
}
}
impl EventHandler for NavigationDrawer {
fn handle_event(&mut self, event: &Event) {
if !self.base.is_enabled() || !self.open {
self.base.handle_event(event);
return;
}
match event {
Event::MousePress { pos, button } | Event::MouseRelease { pos, button } => {
if *button != 1 {
return;
}
let rect = self.geometry();
let panel_width = self.panel_width.min(rect.width);
// Check if click is on the overlay (outside the side panel)
if pos.x > rect.x + panel_width as i32 {
if let Event::MouseRelease { .. } = event {
self.close();
}
return;
}
// Check if click is inside the panel on an item
let header_height: u32 = 60;
let item_height: u32 = 48;
let start_y = rect.y + header_height as i32;
// Exclusive far edge, matching `Rect::contains_point`. A `<=` here put
// the panel's boundary column inside it, so a click one pixel past the
// panel still selected an item.
if pos.x >= rect.x && pos.x < rect.x + panel_width as i32 {
let relative_y = pos.y - start_y;
if relative_y >= 0 {
let item_index = (relative_y as u32) / item_height;
if (item_index as usize) < self.items.len() {
if let Event::MouseRelease { .. } = event {
self.set_selected_index(item_index as usize);
}
return;
}
}
}
// Fall through to base handler for other events
self.base.handle_event(event);
}
_ => {
self.base.handle_event(event);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::widget::svg::render_to_svg;
use std::sync::{
atomic::{AtomicBool, AtomicUsize, Ordering},
Arc,
};
fn make_drawer() -> NavigationDrawer {
let mut drawer = NavigationDrawer::new(Rect::new(0, 0, 400, 600));
drawer.add_item("🏠", "Home");
drawer.add_item("🔍", "Search");
drawer.add_item("⚙️", "Settings");
drawer.add_item("👤", "Profile");
drawer
}
#[test]
fn drawer_default_is_closed() {
let drawer = NavigationDrawer::new(Rect::new(0, 0, 400, 600));
assert!(!drawer.is_open());
assert_eq!(drawer.kind(), WidgetKind::NavigationDrawer);
assert_eq!(drawer.selected_index(), 0);
assert!(drawer.items().is_empty());
}
#[test]
fn drawer_open_signal_emits() {
let mut drawer = NavigationDrawer::new(Rect::new(0, 0, 400, 600));
let opened = Arc::new(AtomicBool::new(false));
let o = opened.clone();
drawer.opened.connect(move || {
o.store(true, Ordering::SeqCst);
});
drawer.open();
assert!(drawer.is_open());
assert!(opened.load(Ordering::SeqCst));
}
#[test]
fn drawer_close_signal_emits() {
let mut drawer = NavigationDrawer::new(Rect::new(0, 0, 400, 600));
drawer.open();
assert!(drawer.is_open());
let closed = Arc::new(AtomicBool::new(false));
let c = closed.clone();
drawer.closed.connect(move || {
c.store(true, Ordering::SeqCst);
});
drawer.close();
assert!(!drawer.is_open());
assert!(closed.load(Ordering::SeqCst));
}
#[test]
fn drawer_toggle_flips_state() {
let mut drawer = NavigationDrawer::new(Rect::new(0, 0, 400, 600));
assert!(!drawer.is_open());
drawer.toggle();
assert!(drawer.is_open());
drawer.toggle();
assert!(!drawer.is_open());
}
#[test]
fn drawer_add_item() {
let mut drawer = NavigationDrawer::new(Rect::new(0, 0, 400, 600));
assert_eq!(drawer.items().len(), 0);
drawer.add_item("📁", "Files");
assert_eq!(drawer.items().len(), 1);
assert_eq!(drawer.items()[0].icon, "📁");
assert_eq!(drawer.items()[0].label, "Files");
drawer.add_item("📧", "Mail");
assert_eq!(drawer.items().len(), 2);
}
#[test]
fn drawer_set_selected_index_emits_signal() {
let mut drawer = make_drawer();
let selected = Arc::new(AtomicUsize::new(usize::MAX));
let s = selected.clone();
drawer.item_selected.connect(move |index: Arc<usize>| {
s.store(*index, Ordering::SeqCst);
});
drawer.set_selected_index(2);
assert_eq!(drawer.selected_index(), 2);
assert_eq!(selected.load(Ordering::SeqCst), 2);
}
#[test]
fn drawer_set_selected_index_out_of_bounds_noop() {
let mut drawer = make_drawer();
drawer.set_selected_index(99);
// Should not change because index is out of bounds
assert_eq!(drawer.selected_index(), 0);
}
#[test]
fn drawer_set_selected_index_same_value_no_reemit() {
let mut drawer = make_drawer();
let count = Arc::new(AtomicUsize::new(0));
let c = count.clone();
drawer.item_selected.connect(move |_: Arc<usize>| {
c.fetch_add(1, Ordering::SeqCst);
});
drawer.set_selected_index(0);
// Should not emit because it's already 0
assert_eq!(count.load(Ordering::SeqCst), 0);
}
#[test]
fn drawer_mouse_press_on_overlay_closes() {
let mut drawer = make_drawer();
drawer.open();
assert!(drawer.is_open());
// Click on overlay (outside panel, at x=350)
drawer.handle_event(&Event::MousePress { pos: Point::new(350, 300), button: 1 });
// Press alone does not close; release does
assert!(drawer.is_open());
drawer.handle_event(&Event::MouseRelease { pos: Point::new(350, 300), button: 1 });
assert!(!drawer.is_open());
}
#[test]
fn drawer_mouse_release_on_item_selects() {
let mut drawer = make_drawer();
drawer.open();
// Click on item at index 1 ("Search") - header=60, item_height=48, item 1 starts at y=108
let target_y = 60 + 48 + 24;
drawer.handle_event(&Event::MousePress { pos: Point::new(20, target_y), button: 1 });
// Not yet selected on press
assert_eq!(drawer.selected_index(), 0);
drawer.handle_event(&Event::MouseRelease { pos: Point::new(20, target_y), button: 1 });
assert_eq!(drawer.selected_index(), 1);
}
#[test]
fn drawer_mouse_click_other_button_noop() {
let mut drawer = make_drawer();
drawer.open();
// Right-click on overlay
drawer.handle_event(&Event::MousePress { pos: Point::new(350, 300), button: 2 });
drawer.handle_event(&Event::MouseRelease { pos: Point::new(350, 300), button: 2 });
assert!(drawer.is_open());
assert_eq!(drawer.selected_index(), 0);
}
#[test]
fn drawer_disabled_blocks_events() {
let mut drawer = make_drawer();
drawer.set_enabled(false);
drawer.open();
// Click release on overlay - should NOT close because disabled
drawer.handle_event(&Event::MousePress { pos: Point::new(350, 300), button: 1 });
drawer.handle_event(&Event::MouseRelease { pos: Point::new(350, 300), button: 1 });
assert!(drawer.is_open());
}
#[test]
fn drawer_closed_ignores_events() {
let mut drawer = make_drawer();
assert!(!drawer.is_open());
// Events while closed should be ignored for drawer-specific behavior
drawer.handle_event(&Event::MousePress { pos: Point::new(20, 100), button: 1 });
drawer.handle_event(&Event::MouseRelease { pos: Point::new(20, 100), button: 1 });
assert_eq!(drawer.selected_index(), 0);
}
#[test]
fn drawer_panel_width_customization() {
let mut drawer = NavigationDrawer::new(Rect::new(0, 0, 400, 600));
assert_eq!(drawer.panel_width(), 280);
drawer.set_panel_width(320);
assert_eq!(drawer.panel_width(), 320);
}
#[test]
fn drawer_svg_output_closed() {
let mut drawer = make_drawer();
// Closed drawer produces an empty SVG (just background / no content)
let svg = render_to_svg(&mut drawer);
assert!(svg.starts_with("<svg"));
assert!(svg.ends_with("</svg>"));
}
#[test]
fn drawer_svg_output_open() {
let mut drawer = make_drawer();
drawer.open();
let svg = render_to_svg(&mut drawer);
assert!(svg.starts_with("<svg"));
assert!(svg.ends_with("</svg>"));
assert!(svg.contains("width=\"400\""));
assert!(svg.contains("height=\"600\""));
}
#[test]
fn drawer_open_close_signals_not_reemitted() {
let mut drawer = NavigationDrawer::new(Rect::new(0, 0, 400, 600));
let open_count = Arc::new(AtomicUsize::new(0));
let close_count = Arc::new(AtomicUsize::new(0));
let oc = open_count.clone();
let cc = close_count.clone();
drawer.opened.connect(move || {
oc.fetch_add(1, Ordering::SeqCst);
});
drawer.closed.connect(move || {
cc.fetch_add(1, Ordering::SeqCst);
});
// Open twice - should only emit once
drawer.open();
drawer.open();
assert_eq!(open_count.load(Ordering::SeqCst), 1);
// Close twice - should only emit once
drawer.close();
drawer.close();
assert_eq!(close_count.load(Ordering::SeqCst), 1);
}
#[test]
fn drawer_item_selected_signal_is_typed() {
let mut drawer = make_drawer();
let captured = Arc::new(std::sync::Mutex::new(None));
let c = captured.clone();
drawer.item_selected.connect(move |val: Arc<usize>| {
*c.lock().unwrap() = Some(*val);
});
drawer.set_selected_index(3);
assert_eq!(*captured.lock().unwrap(), Some(3));
}
#[test]
fn drawer_drawer_item_struct() {
let item = DrawerItem { icon: "📁".to_string(), label: "Documents".to_string() };
assert_eq!(item.icon, "📁");
assert_eq!(item.label, "Documents");
}
/// Opening the drawer slides the panel in rather than placing it there.
///
/// # The defect this pins
///
/// The draw branched on the boolean `open`, so the panel was either absent or complete: a drawer
/// — which slides on every platform that has one — appeared and vanished. The assertions are in
/// two halves, because a progress nothing reads is not a slide: the model must take an interior
/// value, and the *painted* panel must be narrower at that moment than when settled.
#[test]
fn opening_the_drawer_slides_the_panel_in() {
use crate::widget::svg::render_to_svg;
let mut drawer = NavigationDrawer::new(Rect::new(0, 0, 300, 400));
assert_eq!(drawer.slide_progress(), 0.0, "a fresh drawer is closed");
assert!(!drawer.is_animating(), "and owes no frames");
drawer.open();
assert!(drawer.is_open(), "the logical state answers at once");
assert!(drawer.is_animating(), "while the drawn position owes frames");
assert_eq!(drawer.slide_progress(), 0.0, "the slide starts where the panel was");
assert!(drawer.tick(60), "still moving after one step");
let mid = drawer.slide_progress();
assert!(
mid > 0.0 && mid < 1.0,
"the drawer must pass through an interior position (got {mid})"
);
while drawer.tick(60) {}
assert_eq!(drawer.slide_progress(), 1.0, "and settle fully open");
assert!(!drawer.is_animating(), "a settled drawer owes no more frames");
// The painted panel's width, read from the emitted document: the panel and the scrim are both
// full height, so the *widest* rectangle narrower than the control is the panel.
fn panel_width(svg: &str) -> u32 {
svg.split("<rect ")
.filter_map(|chunk| {
let w = chunk.split("width=\"").nth(1)?;
w.split('"').next()?.parse::<u32>().ok()
})
.filter(|w| *w < 300)
.max()
.unwrap_or(0)
}
let closed = NavigationDrawer::new(Rect::new(0, 0, 300, 400));
let closed_width = panel_width(&render_to_svg(&mut { closed }));
let mut mid_drawer = NavigationDrawer::new(Rect::new(0, 0, 300, 400));
mid_drawer.open();
assert!(mid_drawer.tick(60));
let mid_width = panel_width(&render_to_svg(&mut mid_drawer));
let mut open_drawer = NavigationDrawer::new(Rect::new(0, 0, 300, 400));
open_drawer.open();
while open_drawer.tick(60) {}
let open_width = panel_width(&render_to_svg(&mut open_drawer));
assert!(
mid_width > 0 && mid_width < open_width,
"a mid-slide panel must be narrower than a settled one: closed={closed_width} \
mid={mid_width} open={open_width}"
);
// Closing is the same movement in reverse, so the panel does not vanish on the last frame.
drawer.close();
assert!(!drawer.is_open());
assert!(drawer.is_animating(), "closing is also a slide");
while drawer.tick(60) {}
assert_eq!(drawer.slide_progress(), 0.0, "back to closed");
}
}