1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT
//! CupertinoNavigationBar — iOS-style large title navigation bar.
//!
//! An iOS-style navigation bar with optional large title (similar to the
//! iOS 13+ large title nav bar), back button with arrow, and translucent
//! background effect.
use crate::core::{Color, HorizontalAlignment, Point, Rect, Size};
use crate::event::{Event, EventHandler};
use crate::render::RenderContext;
use crate::signal::Signal1;
use crate::style::{MotionSlot, PropertyDriver};
use crate::widget::capability::coercion::{expect_bool, expect_string};
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::metrics::{dimensions, lerp_f32, lerp_i32, lerp_u32, role_font, ControlMetrics};
use crate::widget::{BaseWidget, Draw, IconName, Widget, WidgetKind};
use crate::{impl_widget_property_hooks, property_names_of};
/// The width of a Cupertino navigation bar's leading back-control area.
///
/// The affordance is the arrow plus a short label ("Back"), so it is fixed rather than
/// proportional: a bar twice as wide does not make the back control twice as wide.
const BACK_BUTTON_WIDTH: u32 = 80;
/// The edge length of the back button's arrow icon box, in pixels.
///
/// A square sized to the label's cap height rather than the `←` glyph's 20 px text run, so the
/// affordance reads as an icon beside the text instead of a stray character within it.
const ARROW_ICON_SIZE: u32 = 18;
/// One leading or trailing navigation-bar item.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NavBarItem {
/// Caption; may be empty for an icon-only action.
pub label: String,
/// Optional icon drawn before the caption.
pub icon: Option<IconName>,
}
impl NavBarItem {
/// A text-only item.
pub fn new(label: impl Into<String>) -> Self {
Self { label: label.into(), icon: None }
}
/// The same item with an icon.
pub fn with_icon(mut self, icon: IconName) -> Self {
self.icon = Some(icon);
self
}
/// The width the item's own ink needs at `font`, including its icon slot.
fn ink_width(&self, font: &crate::core::Font) -> u32 {
let icon = if self.icon.is_some() { ICON_ITEM_SIZE + 4 } else { 0 };
icon + crate::widget::metrics::estimate_text_width(&self.label, font, 1.0)
}
}
/// The edge length of an icon inside a bar item.
const ICON_ITEM_SIZE: u32 = 18;
/// What occupies the bar's centre title area.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum NavBarTitleMode {
/// The title string (the historical behaviour).
#[default]
Text,
/// A caller-supplied widget, e.g. a search field or a segmented control.
Widget,
}
/// iOS-style large title navigation bar.
///
/// Renders a translucent background with an optional large title and a
/// back button. Emits `back_pressed` when the back button is clicked.
pub struct CupertinoNavigationBar {
base: BaseWidget,
title: String,
/// Secondary line shown above the title in the large-title state (iOS `prompt`).
prompt: String,
large_title: bool,
/// How far the large title is **shown**, `1.0` full and `0.0` collapsed to the compact bar.
///
/// This is the *drawn* fraction, not a cache of [`Self::large_title`]: the bar's height, the
/// title's point size and the title's x/y are all read off it, so the collapse is a movement
/// through the intermediate sizes rather than a jump between the two ends (the defect this
/// field replaces -- BLUE23 §A.16.4 / §A.18). The target is the logical flag, so setting the
/// flag re-aims the driver and the tick and the "am I moving?" query cannot disagree.
collapse: PropertyDriver,
back_button_visible: bool,
back_button_text: String,
/// Custom leading items drawn after the back affordance.
leading_items: Vec<NavBarItem>,
/// Custom trailing items drawn from the bar's trailing edge inward.
trailing_items: Vec<NavBarItem>,
/// A scroll-driven offset added to the collapse fraction, `-1.0..=1.0`.
///
/// This is a bypass around the animated driver: a host that owns the scroll offset sets it
/// directly, so the title folds continuously with the content instead of waiting for a
/// boolean target to animate.
collapse_offset: f32,
/// The x where an edge-swipe back gesture started.
edge_drag_x: Option<f32>,
/// Emitted when the back button is pressed.
pub back_pressed: Signal1<()>,
/// Emitted with the index of a custom leading item that was tapped.
pub leading_item_pressed: Signal1<usize>,
/// Emitted with the index of a custom trailing item that was tapped.
pub trailing_item_pressed: Signal1<usize>,
/// Whether the title area paints the text or a custom widget.
title_mode: NavBarTitleMode,
/// The custom title-area widget, when [`Self::title_mode`] is `Widget`.
title_widget: Option<crate::compat::Box<dyn Widget>>,
}
impl CupertinoNavigationBar {
/// Creates a new CupertinoNavigationBar with the given geometry.
pub fn new(geometry: Rect) -> Self {
let base =
BaseWidget::new(WidgetKind::CupertinoNavigationBar, geometry, "CupertinoNavigationBar");
Self {
base,
title: String::new(),
prompt: String::new(),
large_title: true,
// Born at the target end, because the default is a bar that is already large. A driver
// built at `0.0` would make a freshly constructed bar animate *away* from its own
// state on the first frame it is drawn -- the defect `PropertyDriver::at` documents.
collapse: PropertyDriver::at(1.0, MotionSlot::Normal),
back_button_visible: false,
back_button_text: "Back".to_string(),
leading_items: Vec::new(),
trailing_items: Vec::new(),
collapse_offset: 0.0,
edge_drag_x: None,
back_pressed: Signal1::new(),
leading_item_pressed: Signal1::new(),
trailing_item_pressed: Signal1::new(),
title_mode: NavBarTitleMode::Text,
title_widget: None,
}
}
/// Sets whether the back button is visible.
pub fn show_back_button(&mut self, visible: bool) {
self.back_button_visible = visible;
self.base.request_redraw();
}
/// Sets the title text.
pub fn set_title(&mut self, title: &str) {
if self.title == title {
return;
}
self.title = title.to_string();
self.base.request_redraw();
}
/// Returns the title text.
pub fn title(&self) -> &str {
&self.title
}
/// Whether the title area paints text or a widget.
pub fn title_mode(&self) -> NavBarTitleMode {
self.title_mode
}
/// Chooses between the text title and the custom widget slot.
pub fn set_title_mode(&mut self, mode: NavBarTitleMode) {
if self.title_mode == mode {
return;
}
self.title_mode = mode;
self.base.request_layout();
self.base.request_redraw();
}
/// Installs the widget drawn in the title area.
///
/// The slot is how a search field, a segmented control or any other in-library control
/// replaces the static title without stacking a second bar on top of this one (MW-17).
/// Passing `None` leaves an empty title area; the mode still has to be set to `Widget`
/// for the slot to be used.
pub fn set_title_widget(&mut self, widget: Option<crate::compat::Box<dyn Widget>>) {
self.title_widget = widget;
if self.title_mode == NavBarTitleMode::Widget {
self.base.request_layout();
self.base.request_redraw();
}
}
/// The region the title slot occupies: the bar's centre, clear of the leading control and
/// the trailing items.
fn title_slot(&self) -> Rect {
let band = self.bar_band();
let left = band.x + if self.back_button_visible { BACK_BUTTON_WIDTH as i32 } else { 8 };
let right = band.right() - 8;
Rect::new(
left,
band.y + 4,
right.saturating_sub(left).max(0) as u32,
band.height.saturating_sub(8),
)
}
/// The secondary line above the title.
pub fn prompt(&self) -> &str {
&self.prompt
}
/// Sets the secondary line shown above the large title.
pub fn set_prompt(&mut self, prompt: &str) {
if self.prompt == prompt {
return;
}
self.prompt = prompt.to_string();
self.base.request_redraw();
}
/// The scroll-driven collapse offset added to the animated fraction.
pub fn collapse_offset(&self) -> f32 {
self.collapse_offset
}
/// Sets a scroll-driven collapse offset, bypassing the animated driver.
///
/// `-1.0` fully collapses a settled large title and `1.0` fully expands a settled compact one;
/// the sum is clamped into `0.0..=1.0`. Nothing is animated, so this is the path for a host
/// that already has the scroll position and wants the title to follow it exactly.
pub fn set_collapse_offset(&mut self, offset: f32) {
if !offset.is_finite() {
return;
}
let offset = offset.clamp(-1.0, 1.0);
if self.collapse_offset == offset {
return;
}
self.collapse_offset = offset;
self.base.request_redraw();
}
/// The collapse fraction after the scroll offset is applied.
pub fn effective_collapse(&self) -> f32 {
(self.collapse.value() + self.collapse_offset).clamp(0.0, 1.0)
}
/// Returns whether large title mode is enabled.
pub fn is_large_title(&self) -> bool {
self.large_title
}
/// Enables or disables large title mode.
///
/// This is the **logical** state; the bar animates to it rather than jumping. A bar being
/// told to collapse therefore owes frames for the duration of the movement, which is what
/// makes iOS's signature large-title collapse continuous instead of a one-frame swap.
///
/// # Why the driver is aimed here and not in `tick`
///
/// The frame bus asks [`Widget::is_animating`] *before* it decides whether to advance
/// anything, so a control that only aims its target inside `tick` reports "still" at the
/// moment it is asked and is never ticked at all -- the movement silently never happens.
/// Aiming here means the state change and the answer to "do I owe frames?" agree from the
/// same instant, which is the property `CollapsiblePane::set_collapsed` establishes for its
/// own disclosure.
pub fn set_large_title(&mut self, enabled: bool) {
if self.large_title == enabled {
return;
}
self.large_title = enabled;
self.collapse.set_target(if enabled { 1.0 } else { 0.0 });
self.base.request_redraw();
}
/// How far the large title is shown, `1.0` full and `0.0` collapsed.
///
/// This is the *drawn* fraction: the bar's height, the title's point size and its x/y are
/// all functions of it, so a test can assert the collapse slid rather than jumped by
/// sampling it at successive frames -- the same reading `CollapsiblePane::open_progress`
/// gives for its own disclosure.
pub fn collapse_progress(&self) -> f32 {
self.collapse.value()
}
/// Advances the large-title collapse by `delta_ms`; `true` while it is still moving.
///
/// The target is re-derived from the logical flag as well as being aimed by
/// [`Self::set_large_title`], so a bar whose flag was set through a path that did not go
/// through the setter still converges, and the tick and the "am I moving?" query cannot
/// disagree about which end the flag means.
pub fn tick(&mut self, delta_ms: u32) -> bool {
self.collapse.set_target(if self.large_title { 1.0 } else { 0.0 });
self.collapse.tick(delta_ms)
}
/// Whether the bar is between two collapse fractions -- answers only, never advances.
pub fn is_animating(&self) -> bool {
self.collapse.is_moving()
}
/// Returns whether the back button is visible.
pub fn is_back_button_visible(&self) -> bool {
self.back_button_visible
}
/// Sets the text for the back button.
pub fn set_back_button_text(&mut self, text: &str) {
if self.back_button_text == text {
return;
}
self.back_button_text = text.to_string();
self.base.request_redraw();
}
/// Returns the back button text.
pub fn back_button_text(&self) -> &str {
&self.back_button_text
}
/// Replaces the custom items shown after the back affordance.
pub fn set_leading_items(&mut self, items: Vec<String>) {
self.set_leading_actions(items.into_iter().map(NavBarItem::new).collect());
}
/// Returns the custom leading items' captions.
pub fn leading_items(&self) -> Vec<String> {
self.leading_items.iter().map(|item| item.label.clone()).collect()
}
/// Replaces the leading items, allowing each to carry an icon.
pub fn set_leading_actions(&mut self, items: Vec<NavBarItem>) {
if self.leading_items == items {
return;
}
self.leading_items = items;
self.base.request_redraw();
}
/// The leading items, including their icons.
pub fn leading_actions(&self) -> &[NavBarItem] {
&self.leading_items
}
/// Replaces the custom items shown at the trailing edge.
pub fn set_trailing_items(&mut self, items: Vec<String>) {
self.set_trailing_actions(items.into_iter().map(NavBarItem::new).collect());
}
/// Returns the custom trailing items' captions.
pub fn trailing_items(&self) -> Vec<String> {
self.trailing_items.iter().map(|item| item.label.clone()).collect()
}
/// Replaces the trailing items, allowing each to carry an icon.
pub fn set_trailing_actions(&mut self, items: Vec<NavBarItem>) {
if self.trailing_items == items {
return;
}
self.trailing_items = items;
self.base.request_redraw();
}
/// The trailing items, including their icons.
pub fn trailing_actions(&self) -> &[NavBarItem] {
&self.trailing_items
}
/// The bar band the control paints: the top strip, sized by the collapse fraction.
fn bar_band(&self) -> Rect {
let height = lerp_u32(
dimensions::NAV_BAR_HEIGHT,
dimensions::NAV_BAR_LARGE_HEIGHT,
self.effective_collapse(),
);
ControlMetrics::top_band(self.geometry(), height)
}
/// The x where each custom leading item starts, given its measured width.
fn leading_item_x(&self, index: usize, widths: &[u32]) -> Option<i32> {
self.leading_items.get(index)?;
let band = self.bar_band();
let mut x = band.x + if self.back_button_visible { BACK_BUTTON_WIDTH as i32 } else { 8 };
for width in widths.iter().take(index) {
x += *width as i32 + 8;
}
Some(x)
}
/// The trailing edge x of each custom trailing item, in right-to-left draw order.
fn trailing_item_x(&self, index: usize, widths: &[u32]) -> Option<i32> {
self.trailing_items.get(index)?;
let band = self.bar_band();
let mut right = band.right() - 8;
for width in widths.iter().take(index) {
right -= *width as i32 + 8;
}
Some(right)
}
}
impl Widget for CupertinoNavigationBar {
fn base(&self) -> &BaseWidget {
&self.base
}
fn set_state_theme_hook(&mut self) {
crate::style::reapply_active_theme_state(self);
}
fn base_mut(&mut self) -> &mut BaseWidget {
&mut self.base
}
fn size_hint(&self) -> Size {
crate::core::Size::new(400, 44)
}
fn kind(&self) -> WidgetKind {
WidgetKind::CupertinoNavigationBar
}
// The collapse is the control's own; the trait spelling is what the frame bus reaches
// through `&mut dyn Widget`, which is the only way the movement actually happens.
fn tick(&mut self, delta_ms: u32) -> bool {
CupertinoNavigationBar::tick(self, delta_ms)
}
fn is_animating(&self) -> bool {
self.collapse.is_moving()
}
impl_draw_bridge!();
impl_widget_property_hooks!();
/// Resolves a published event name to the control's own signal.
///
/// # Why the field is named per arm
///
/// The published name and the Rust field name are not always the same (`find_next` is backed by
/// `find_next_signal`, `dismissed` by a `Signal1<()>` field). `connect_event` validates a name
/// against the capability table and registers a hub slot; only `event_signal_dyn` joins that
/// name to the signal the control actually **emits**. A wrong arm is worse than no arm, because
/// it reports a wire as live and never fires it, so each field is named explicitly here rather
/// than derived from the published name.
fn event_signal_dyn(&self, name: &str) -> Option<crate::signal::EventSignalRef> {
use crate::signal::EventSignalRef;
match name {
"back_pressed" => {
Some(EventSignalRef::mapped("back_pressed", &self.back_pressed, |_| {
CapabilityValue::Null
}))
}
"leading_item_pressed" => Some(EventSignalRef::mapped(
"leading_item_pressed",
&self.leading_item_pressed,
|v| crate::widget::capability::CapabilityValue::UInt(*v as u64),
)),
"trailing_item_pressed" => Some(EventSignalRef::mapped(
"trailing_item_pressed",
&self.trailing_item_pressed,
|v| crate::widget::capability::CapabilityValue::UInt(*v as u64),
)),
_ => None,
}
}
}
/// `CupertinoNavigationBar`'s property contract.
///
/// Read/write semantics are carried over unchanged from the centralised
/// `access_read_other.in.rs` / `access_write_other.in.rs` dispatch, so callers see
/// the same coercions and the same errors as before. Both properties now report
/// the bar's real state instead of the placeholder defaults that dispatch
/// returned.
impl WidgetProperties for CupertinoNavigationBar {
fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
match name {
"title" => Ok(CapabilityValue::String(self.title().to_string())),
"prompt" => Ok(CapabilityValue::String(self.prompt().to_string())),
"large_title" => Ok(CapabilityValue::Bool(self.is_large_title())),
"collapse_offset" => Ok(CapabilityValue::Float(self.collapse_offset() as f64)),
_ => base_property_get(self, name),
}
}
fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
match name {
"title" => {
self.set_title(&expect_string(value)?);
Ok(())
}
"prompt" => {
self.set_prompt(&expect_string(value)?);
Ok(())
}
"large_title" => {
self.set_large_title(expect_bool(value)?);
Ok(())
}
"collapse_offset" => {
let offset = match value {
CapabilityValue::Float(offset) => offset as f32,
_ => return Err(CapabilityAccessError::TypeMismatch),
};
self.set_collapse_offset(offset);
Ok(())
}
_ => base_property_set(self, name, value),
}
}
fn property_names(&self) -> &'static [&'static str] {
property_names_of!["title", "prompt", "large_title", "collapse_offset", BASE_PROPERTY_NAMES]
}
}
impl Draw for CupertinoNavigationBar {
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 fall back to a literal. Every colour below used to be
// a literal, so a light/dark switch left the bar, its rule, its title and its back
// affordance unchanged — the rendering census reported the control as theme-blind.
//
// The theme read is a separate manager lock, taken and released inside
// `resolved_theme_style`, so it is not held across the draw — the global manager's
// mutex is not re-entrant.
let style = self.base.style();
let theme = crate::style::resolved_theme_style_shared("cupertino_navigation_bar");
// Read as its own lock acquisition and copied out as values, so the guard is dropped
// before anything else touches the theme. The bar is not in the role table, so it
// classifies as `Surface` and its resolved background is the window fill itself; the
// bar below therefore derives its own distinct surface rather than painting the
// window's. The back affordance is iOS blue only because it used to be hardcoded — it
// is the bar's action colour, so it reads the theme's primary token.
let (window_fill, foreground, primary) = {
let manager = crate::style::theme_manager();
match manager.current_theme() {
Some(active) => {
(active.colors.background, active.colors.foreground, active.colors.primary)
}
None => (Color::rgb(240, 240, 240), Color::BLACK, Color::rgb(0, 122, 255)),
}
};
let ink = style
.text_color
.or_else(|| theme.as_ref().and_then(|t| t.text_color))
.unwrap_or(foreground);
// A translucent fill cannot tint anything on this surface: `fill_rect` writes raw
// pixels, so `rgba(255, 255, 255, 230)` *replaced* the page with white at alpha 230
// instead of frosting it, and the bar kept that colour through a theme switch. Mixing
// the bar's own surface with the page it covers produces the same translucent
// appearance with an opaque result that follows the appearance.
//
// The filter is on the **resolved** value, not only on the theme's: the active theme
// is applied to every control before it is drawn, so `style.background_color` already
// holds `Surface`'s window fill and letting it through unfiltered is exactly the
// invisible-bar defect this guards against. A caller's own colour still wins.
let bar_from_theme = window_fill.blend(&ink, 0.06);
let bar_surface = match style.background_color {
Some(resolved) if resolved != window_fill => resolved,
_ => bar_from_theme,
};
let bar = bar_surface.blend(&window_fill, 0.10);
// ── The bar actually painted ──
//
// `rect` is the area the control was *given*; a navigation bar is a strip pinned to the
// **top** of that area, [`dimensions::NAV_BAR_HEIGHT`] tall in compact mode and
// [`dimensions::NAV_BAR_LARGE_HEIGHT`] in large-title mode. Filling the whole rectangle
// made a 240x120 census cell a 120 px navigation bar whose compact title sat at `y + 22`
// — a third of the way down a bar three times its proper height — and it put the bottom
// rule on the *canvas* edge rather than on the bar's. `top_band` is the shared
// derivation for "a strip pinned to my top edge", and the hit test below reads the same
// band so the back affordance and its ink cannot part company.
//
// The two modes are the **ends of a movement**, so the height is read off the drawn
// fraction instead of the boolean: at `1.0` this is exactly `NAV_BAR_LARGE_HEIGHT` and at
// `0.0` exactly `NAV_BAR_HEIGHT`, so a settled bar is byte-identical to the un-animated
// one and only the frames in between are new.
let collapse = self.effective_collapse();
let bar_height =
lerp_u32(dimensions::NAV_BAR_HEIGHT, dimensions::NAV_BAR_LARGE_HEIGHT, collapse);
let bar_rect = ControlMetrics::top_band(rect, bar_height);
context.fill_rect(bar_rect, bar);
// ── Bottom border line ──
// A `Surface` role resolves no border colour, so the rule is derived one visible
// step from the bar and a caller's explicit border still wins.
let border = style
.border_color
.or_else(|| theme.as_ref().and_then(|t| t.border_color))
.filter(|resolved| *resolved != bar)
.unwrap_or_else(|| bar.blend(&ink, 0.20));
let border_y = bar_rect.y + bar_rect.height as i32 - 1;
context.draw_line(
Point::new(bar_rect.x, border_y),
Point::new(bar_rect.x + bar_rect.width as i32, border_y),
border,
);
// ── Title ──
//
// The large and compact titles are two ends of one movement, so the point size and the
// x/y are interpolated off the drawn fraction rather than switched:
//
// * **size** `18 -> 34`, so the title grows rather than swapping glyphs;
// * **x** leading `+ 16` -> centred, which is the iOS large-title slide;
// * **y** the text line of whatever band the height currently is, so the title stays on
// the bar's middle line at every intermediate height.
//
// At `1.0` this is the old large-title branch and at `0.0` the old compact one, so a bar
// settled at either end draws exactly what it drew before.
if self.title_mode == NavBarTitleMode::Text && !self.title.is_empty() {
let title_font =
role_font(style, lerp_f32(17.0, 34.0, collapse)).with_bold(collapse > 0.5);
let metrics = crate::widget::base_widgets::measure_cache::measure_text(
context,
&self.title,
&title_font,
);
let leading_x = bar_rect.x + 16;
let centred_x = bar_rect.x + (bar_rect.width as i32 - metrics.width as i32) / 2;
let title_x = lerp_i32(centred_x, leading_x, collapse);
// Centre the title through the shared primitive, so it sits on the bar's middle line
// whatever height the band was clamped to; the `+ 22` this replaces was a literal for
// the 44 px bar and landed elsewhere on any other.
let line = context.text_line(bar_rect, &title_font);
// The prompt is a second, smaller line above the title in the large-title state. It
// fades out with the large title rather than being clipped abruptly; the title is
// nudged down by the line it adds so the two never overlap.
let mut title_top = line.y;
if !self.prompt.is_empty() && collapse > 0.5 {
let prompt_font = role_font(style, 11.0);
let prompt_metrics = crate::widget::base_widgets::measure_cache::measure_text(
context,
&self.prompt,
&prompt_font,
);
let prompt_y = bar_rect.y + 4;
context.draw_text_fitted_cow(
Rect::new(
bar_rect.x + 16,
prompt_y,
bar_rect.width.saturating_sub(32),
prompt_metrics.height,
),
&self.prompt,
&prompt_font,
ink.blend(&bar, 0.25),
HorizontalAlignment::Left,
);
title_top += prompt_metrics.height as i32;
}
context.draw_text(
Point::new(title_x, title_top),
&self.title,
&title_font,
ink,
HorizontalAlignment::Left,
);
}
// ── Back button (left side) ──
if self.back_button_visible {
let label_font = role_font(style, 17.0);
// The affordance sits on the bar, so the theme's primary is contrast-checked
// against it rather than assumed legible.
let action = primary.contrast_color().blend(&primary, 0.85);
// Drawn as an icon rather than the `←` text glyph: no bundled face covers
// U+2190, so it degraded to an 8x8 fallback bitmap and read as a blocky
// blob. The icon is geometry, so both backends agree on the same shape.
let arrow_x = bar_rect.x + 8;
// On the compact bar's own middle line, shared with the title; the removed
// `+ 22` was a literal for the 44 px bar.
let arrow_line = context.text_line(bar_rect, &label_font);
let icon_y = arrow_line.y + (arrow_line.height as i32 - ARROW_ICON_SIZE as i32) / 2;
let icon_rect = Rect::new(arrow_x, icon_y, ARROW_ICON_SIZE, ARROW_ICON_SIZE);
crate::widget::draw_icon_at(context, icon_rect, action, IconName::ArrowLeft);
// Draw text label next to arrow
if !self.back_button_text.is_empty() {
let label_x = arrow_x + ARROW_ICON_SIZE as i32 + 4;
// Reads as a small title and shares the compact bar's middle line with the
// title and the arrow; no literal offset, which had moved it with the bar's
// height rather than its own line.
let label_line = context.text_line(bar_rect, &label_font);
context.draw_text(
Point::new(label_x, label_line.y),
&self.back_button_text,
&label_font,
action,
HorizontalAlignment::Left,
);
}
}
// ── Custom leading and trailing items ──
let item_font = role_font(style, 17.0);
let action = primary.contrast_color().blend(&primary, 0.85);
let leading_widths: Vec<u32> =
self.leading_items.iter().map(|item| item.ink_width(&item_font)).collect();
for (index, item) in self.leading_items.iter().enumerate() {
if let Some(x) = self.leading_item_x(index, &leading_widths) {
let line = context.text_line(bar_rect, &item_font);
let mut ink_x = x;
if let Some(icon) = item.icon {
let icon_y = line.y + (line.height as i32 - ICON_ITEM_SIZE as i32) / 2;
crate::widget::draw_icon_at(
context,
Rect::new(ink_x, icon_y, ICON_ITEM_SIZE, ICON_ITEM_SIZE),
action,
icon,
);
ink_x += ICON_ITEM_SIZE as i32 + 4;
}
if !item.label.is_empty() {
context.draw_text(
Point::new(ink_x, line.y),
&item.label,
&item_font,
action,
HorizontalAlignment::Left,
);
}
}
}
let trailing_widths: Vec<u32> =
self.trailing_items.iter().map(|item| item.ink_width(&item_font)).collect();
for (index, item) in self.trailing_items.iter().enumerate() {
if let Some(right) = self.trailing_item_x(index, &trailing_widths) {
let width = trailing_widths.get(index).copied().unwrap_or(0) as i32;
let line = context.text_line(bar_rect, &item_font);
let mut ink_x = right - width;
if let Some(icon) = item.icon {
let icon_y = line.y + (line.height as i32 - ICON_ITEM_SIZE as i32) / 2;
crate::widget::draw_icon_at(
context,
Rect::new(ink_x, icon_y, ICON_ITEM_SIZE, ICON_ITEM_SIZE),
action,
icon,
);
ink_x += ICON_ITEM_SIZE as i32 + 4;
}
if !item.label.is_empty() {
context.draw_text(
Point::new(ink_x, line.y),
&item.label,
&item_font,
action,
HorizontalAlignment::Left,
);
}
}
}
// ── Custom title slot ──
// Painted after the bar's own chrome so a host control (a search field, a segmented
// picker) reads as the bar's title. The slot gets its own rectangle and every pointer
// event that lands inside it is forwarded to the widget, so it is interactive rather
// than decorative (MW-17).
if self.title_mode == NavBarTitleMode::Widget {
let slot = self.title_slot();
context.push_clip(slot.x, slot.y, slot.width, slot.height);
if let Some(widget) = self.title_widget.as_mut() {
widget.set_geometry(slot);
if let Some(drawable) = crate::widget::draw_bridge::draw_of(widget.as_mut()) {
drawable.draw(context);
}
}
context.pop_clip();
}
}
}
impl EventHandler for CupertinoNavigationBar {
fn handle_event(&mut self, event: &Event) {
if !self.base.is_enabled() {
self.base.handle_event(event);
return;
}
// Pointer events inside the custom title slot belong to that widget, not to the bar's
// back-area or item tests (MW-17).
let pointer = match event {
Event::MousePress { pos, .. }
| Event::MouseRelease { pos, .. }
| Event::MouseMove { pos }
| Event::Drag { pos, .. } => Some(*pos),
_ => None,
};
if self.title_mode == NavBarTitleMode::Widget {
if let Some(pos) = pointer {
if self.title_slot().contains_point(pos) {
if let Some(widget) = self.title_widget.as_mut() {
widget.handle_event(event);
}
return;
}
}
}
match event {
Event::MousePress { pos, button, .. } => {
if *button != 1 {
return;
}
// The leading edge starts an interactive back gesture. The strip is the same
// width on both sides so a right-to-left interface mirrors it.
let bar_rect = self.bar_band();
let edge =
Rect::new(bar_rect.x, bar_rect.y, 20.min(bar_rect.width), bar_rect.height);
self.edge_drag_x = edge.contains_point(*pos).then_some(pos.x as f32);
}
Event::MouseMove { .. } => {}
Event::MouseRelease { pos, button } => {
if *button != 1 {
return;
}
// An edge swipe that travelled far enough is a back gesture.
if let Some(start) = self.edge_drag_x.take() {
if pos.x as f32 - start > 40.0 {
self.back_pressed.emit(());
self.base.request_redraw();
return;
}
}
let bar_rect = self.bar_band();
// The back area is the leading end of the bar itself, so it tracks the band the
// bar is painted in rather than a fixed 80x44 literal: the clickable region and
// the ink the user aims at are the same rectangle by construction.
if self.back_button_visible {
let back_area =
Rect::new(bar_rect.x, bar_rect.y, BACK_BUTTON_WIDTH, bar_rect.height);
if back_area.contains_point(*pos) {
self.back_pressed.emit(());
self.base.request_redraw();
return;
}
}
// Custom items are hit-tested against the boxes they were painted in.
let font = role_font(self.base.style(), 17.0);
let measure = |item: &NavBarItem| -> u32 { item.ink_width(&font) };
let leading_widths: Vec<u32> = self.leading_items.iter().map(measure).collect();
for index in 0..self.leading_items.len() {
if let Some(x) = self.leading_item_x(index, &leading_widths) {
let width = leading_widths[index];
if pos.x >= x && pos.x < x + width as i32 {
self.leading_item_pressed.emit(index);
self.base.request_redraw();
return;
}
}
}
let trailing_widths: Vec<u32> = self.trailing_items.iter().map(measure).collect();
for index in 0..self.trailing_items.len() {
if let Some(right) = self.trailing_item_x(index, &trailing_widths) {
let width = trailing_widths[index] as i32;
if pos.x >= right - width && pos.x < right {
self.trailing_item_pressed.emit(index);
self.base.request_redraw();
return;
}
}
}
}
_ => {
self.base.handle_event(event);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::widget::svg::render_to_svg;
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc,
};
#[test]
fn cupertino_nav_bar_creation() {
let bar = CupertinoNavigationBar::new(Rect::new(0, 0, 375, 96));
assert_eq!(bar.kind(), WidgetKind::CupertinoNavigationBar);
assert!(bar.title().is_empty());
assert!(bar.is_large_title());
assert!(!bar.is_back_button_visible());
}
#[test]
fn cupertino_nav_bar_title_accessors() {
let mut bar = CupertinoNavigationBar::new(Rect::new(0, 0, 375, 96));
bar.set_title("Home");
assert_eq!(bar.title(), "Home");
}
#[test]
fn cupertino_nav_bar_back_button_visibility() {
let mut bar = CupertinoNavigationBar::new(Rect::new(0, 0, 375, 96));
assert!(!bar.is_back_button_visible());
bar.show_back_button(true);
assert!(bar.is_back_button_visible());
bar.show_back_button(false);
assert!(!bar.is_back_button_visible());
}
#[test]
fn cupertino_nav_bar_large_title_toggle() {
let mut bar = CupertinoNavigationBar::new(Rect::new(0, 0, 375, 96));
assert!(bar.is_large_title());
bar.set_large_title(false);
assert!(!bar.is_large_title());
bar.set_large_title(true);
assert!(bar.is_large_title());
}
#[test]
fn cupertino_nav_bar_back_button_text() {
let mut bar = CupertinoNavigationBar::new(Rect::new(0, 0, 375, 96));
assert_eq!(bar.back_button_text(), "Back");
bar.set_back_button_text("Settings");
assert_eq!(bar.back_button_text(), "Settings");
}
#[test]
fn cupertino_nav_bar_back_pressed_signal() {
let mut bar = CupertinoNavigationBar::new(Rect::new(0, 0, 375, 96));
bar.show_back_button(true);
let fired = Arc::new(AtomicBool::new(false));
let f = fired.clone();
bar.back_pressed.connect(move |_: std::sync::Arc<()>| {
f.store(true, Ordering::SeqCst);
});
// Click on back button area
bar.handle_event(&Event::MouseRelease { pos: Point::new(20, 22), button: 1 });
assert!(fired.load(Ordering::SeqCst));
}
/// A disabled nav bar must not emit `back_pressed`.
///
/// `handle_event` went straight to the hit test, so `set_enabled(false)` had no
/// effect on this widget: the back affordance still fired navigation. Every
/// interactive widget in the crate gates on `is_enabled()` first, so a missing
/// gate turns `set_enabled` into a silent no-op rather than a policy choice.
#[test]
fn cupertino_nav_bar_disabled_ignores_back_click() {
let mut bar = CupertinoNavigationBar::new(Rect::new(0, 0, 375, 96));
bar.show_back_button(true);
bar.set_enabled(false);
let fired = Arc::new(AtomicBool::new(false));
let f = fired.clone();
bar.back_pressed.connect(move |_: std::sync::Arc<()>| {
f.store(true, Ordering::SeqCst);
});
bar.handle_event(&Event::MouseRelease { pos: Point::new(20, 22), button: 1 });
assert!(!fired.load(Ordering::SeqCst), "a disabled nav bar must not navigate");
}
#[test]
fn cupertino_nav_bar_back_pressed_not_fired_when_hidden() {
let mut bar = CupertinoNavigationBar::new(Rect::new(0, 0, 375, 96));
// back_button_visible is false by default
let fired = Arc::new(AtomicBool::new(false));
let f = fired.clone();
bar.back_pressed.connect(move |_: std::sync::Arc<()>| {
f.store(true, Ordering::SeqCst);
});
// Click where back button would be
bar.handle_event(&Event::MouseRelease { pos: Point::new(20, 22), button: 1 });
assert!(!fired.load(Ordering::SeqCst));
}
#[test]
fn cupertino_nav_bar_svg_output() {
let mut bar = CupertinoNavigationBar::new(Rect::new(0, 0, 375, 96));
bar.set_title("Settings");
bar.show_back_button(true);
let svg = render_to_svg(&mut bar);
assert!(svg.starts_with("<svg"));
}
/// The bar is a top-anchored strip, and its rule sits on the bar's own bottom edge.
///
/// The defect this pins: the bar filled its whole rectangle, so a 240x120 census cell was
/// a 120 px navigation bar whose compact title sat at a literal `y + 22` — a third of the
/// way down a bar three times its proper height — and whose bottom rule landed on the
/// *canvas* edge rather than the bar's own.
#[test]
fn the_bar_is_a_top_strip_that_keeps_its_own_height() {
use crate::widget::metrics::{dimensions, ControlMetrics};
for height in [96u32, 120, 300] {
let mut bar = CupertinoNavigationBar::new(Rect::new(0, 0, 240, height));
bar.set_title("Settings");
// The large-title bar is the taller of the two modes.
let band = ControlMetrics::top_band(
Rect::new(0, 0, 240, height),
dimensions::NAV_BAR_LARGE_HEIGHT,
);
let svg = render_to_svg(&mut bar);
let fill = format!("x=\"0\" y=\"0\" width=\"240\" height=\"{}\"", band.height);
assert!(
svg.contains(&fill),
"at control height {height} the bar must be {band:?}, in:\n{svg}"
);
// And the rule is on the bar, not on the canvas.
let rule = format!(
"x1=\"0\" y1=\"{}\" x2=\"240\" y2=\"{}\"",
band.y + band.height as i32 - 1,
band.y + band.height as i32 - 1
);
assert!(svg.contains(&rule), "the rule must sit on the bar's bottom edge:\n{svg}");
}
}
#[test]
fn custom_items_report_the_index_that_was_tapped() {
let mut bar = CupertinoNavigationBar::new(Rect::new(0, 0, 375, 96));
bar.set_title("Inbox");
bar.set_leading_items(vec!["Edit".to_string()]);
bar.set_trailing_items(vec!["Done".to_string(), "More".to_string()]);
let fired = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(usize::MAX));
let f = fired.clone();
bar.trailing_item_pressed.connect(move |index: std::sync::Arc<usize>| {
f.store(*index, std::sync::atomic::Ordering::SeqCst);
});
// The trailing-most item is index zero and lives nearest the trailing edge.
bar.handle_event(&Event::MouseRelease { pos: Point::new(360, 30), button: 1 });
assert_eq!(fired.load(std::sync::atomic::Ordering::SeqCst), 0);
}
#[test]
fn an_edge_drag_presses_back() {
let mut bar = CupertinoNavigationBar::new(Rect::new(0, 0, 375, 96));
let fired = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let f = fired.clone();
bar.back_pressed.connect(move |_: std::sync::Arc<()>| {
f.store(true, std::sync::atomic::Ordering::SeqCst);
});
bar.handle_event(&Event::MousePress { pos: Point::new(4, 30), button: 1, modifiers: 0 });
bar.handle_event(&Event::MouseRelease { pos: Point::new(80, 30), button: 1 });
assert!(fired.load(Ordering::SeqCst));
}
#[test]
fn a_scroll_offset_moves_the_collapse_without_animating() {
let mut bar = CupertinoNavigationBar::new(Rect::new(0, 0, 375, 96));
assert!((bar.effective_collapse() - 1.0).abs() < f32::EPSILON);
bar.set_collapse_offset(-0.5);
assert!((bar.effective_collapse() - 0.5).abs() < 1e-6);
assert!(!bar.is_animating(), "a scroll offset bypasses the animated driver");
let svg = render_to_svg(&mut bar);
assert!(svg.starts_with("<svg"));
}
#[test]
fn a_prompt_is_a_second_title_line_and_icons_are_drawn() {
let mut bar = CupertinoNavigationBar::new(Rect::new(0, 0, 375, 120));
bar.set_title("Inbox");
bar.set_prompt("12 unread");
bar.set_leading_actions(vec![NavBarItem::new("Edit").with_icon(IconName::Check)]);
bar.set_trailing_actions(vec![NavBarItem::new("").with_icon(IconName::Cross)]);
assert_eq!(bar.leading_actions().len(), 1);
assert_eq!(bar.trailing_actions()[0].icon, Some(IconName::Cross));
assert_eq!(bar.leading_items(), vec!["Edit".to_string()]);
let svg = render_to_svg(&mut bar);
// Text is emitted as glyph outlines carrying `data-text`, not as literal characters.
let text_runs = svg.matches("data-text=\"1\"").count();
assert!(text_runs >= 2, "the title and the prompt are both painted: {svg}");
}
}