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
//! Context Menu component for right-click menus
//!
//! A themed context menu that appears at a specific position (usually mouse coordinates).
//! Uses the overlay system for proper positioning and dismissal.
//!
//! # Example
//!
//! ```ignore
//! use blinc_cn::prelude::*;
//!
//! fn build_ui(ctx: &WindowedContext) -> impl ElementBuilder {
//! div()
//! .w(400.0)
//! .h(300.0)
//! .bg(theme.color(ColorToken::Surface))
//! .on_click(|event_ctx| {
//! // Use mouse_x/mouse_y from EventContext for absolute screen position
//! cn::context_menu()
//! .at(event_ctx.mouse_x, event_ctx.mouse_y)
//! .item("Cut", || println!("Cut"))
//! .item("Copy", || println!("Copy"))
//! .item("Paste", || println!("Paste"))
//! .separator()
//! .item("Delete", || println!("Delete"))
//! .show();
//! })
//! }
//!
//! // With keyboard shortcuts displayed
//! cn::context_menu()
//! .at(x, y)
//! .item_with_shortcut("Cut", "Ctrl+X", || {})
//! .item_with_shortcut("Copy", "Ctrl+C", || {})
//! .item_with_shortcut("Paste", "Ctrl+V", || {})
//!
//! // Disabled items
//! cn::context_menu()
//! .at(x, y)
//! .item("Undo", || {})
//! .item_disabled("Redo") // No action available
//!
//! // Submenus (nested menus)
//! cn::context_menu()
//! .at(x, y)
//! .item("Open", || {})
//! .submenu("Recent Files", |sub| {
//! sub.item("file1.rs", || {})
//! .item("file2.rs", || {})
//! })
//! ```
use std::sync::Arc;
use blinc_animation::AnimationPreset;
use blinc_core::context_state::BlincContextState;
use blinc_core::{Color, State};
use blinc_layout::element::CursorStyle;
use blinc_layout::motion::motion_derived;
use blinc_layout::overlay_state::get_overlay_manager;
use blinc_layout::prelude::*;
use blinc_layout::stateful::{stateful_with_key, ButtonState};
use blinc_layout::widgets::hr::hr_with_bg;
use blinc_layout::widgets::overlay::{OverlayHandle, OverlayManagerExt};
use blinc_theme::{ColorToken, RadiusToken, ThemeState};
/// A menu item in the context menu
#[derive(Clone)]
pub struct ContextMenuItem {
/// Display label
label: String,
/// Optional keyboard shortcut display
shortcut: Option<String>,
/// Optional icon SVG
icon: Option<String>,
/// Click handler
on_click: Option<Arc<dyn Fn() + Send + Sync>>,
/// Whether this item is disabled
disabled: bool,
/// Whether this is a separator (ignores other fields)
is_separator: bool,
/// Submenu items (if this is a submenu trigger)
submenu: Option<Vec<ContextMenuItem>>,
}
impl std::fmt::Debug for ContextMenuItem {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ContextMenuItem")
.field("label", &self.label)
.field("shortcut", &self.shortcut)
.field("icon", &self.icon.is_some())
.field("disabled", &self.disabled)
.field("is_separator", &self.is_separator)
.field("submenu", &self.submenu.as_ref().map(|s| s.len()))
.finish()
}
}
impl ContextMenuItem {
/// Create a new menu item
pub fn new(label: impl Into<String>) -> Self {
Self {
label: label.into(),
shortcut: None,
icon: None,
on_click: None,
disabled: false,
is_separator: false,
submenu: None,
}
}
/// Create a separator
pub fn separator() -> Self {
Self {
label: String::new(),
shortcut: None,
icon: None,
on_click: None,
disabled: false,
is_separator: true,
submenu: None,
}
}
/// Set the click handler
pub fn on_click<F>(mut self, f: F) -> Self
where
F: Fn() + Send + Sync + 'static,
{
self.on_click = Some(Arc::new(f));
self
}
/// Set a keyboard shortcut hint
pub fn shortcut(mut self, shortcut: impl Into<String>) -> Self {
self.shortcut = Some(shortcut.into());
self
}
/// Set an icon (SVG string)
pub fn icon(mut self, svg: impl Into<String>) -> Self {
self.icon = Some(svg.into());
self
}
/// Mark as disabled
pub fn disabled(mut self) -> Self {
self.disabled = true;
self
}
/// Set submenu items
pub fn submenu(mut self, items: Vec<ContextMenuItem>) -> Self {
self.submenu = Some(items);
self
}
// =========================================================================
// Accessors for use by other components (like DropdownMenu)
// =========================================================================
/// Get the label
pub fn get_label(&self) -> &str {
&self.label
}
/// Get the shortcut if any
pub fn get_shortcut(&self) -> Option<&str> {
self.shortcut.as_deref()
}
/// Get the icon SVG if any
pub fn get_icon(&self) -> Option<&str> {
self.icon.as_deref()
}
/// Check if this item is disabled
pub fn is_disabled(&self) -> bool {
self.disabled
}
/// Check if this is a separator
pub fn is_separator(&self) -> bool {
self.is_separator
}
/// Check if this item has a submenu
pub fn has_submenu(&self) -> bool {
self.submenu.is_some()
}
/// Get the submenu items if any
pub fn get_submenu(&self) -> Option<&Vec<ContextMenuItem>> {
self.submenu.as_ref()
}
/// Get the click handler (clones the Arc)
pub fn get_on_click(&self) -> Option<Arc<dyn Fn() + Send + Sync>> {
self.on_click.clone()
}
}
/// Builder for creating context menus
pub struct ContextMenuBuilder {
/// Position x coordinate
x: f32,
/// Position y coordinate
y: f32,
/// Menu items
items: Vec<ContextMenuItem>,
/// Minimum width
min_width: f32,
/// User-added CSS classes
classes: Vec<String>,
/// User-set element ID
user_id: Option<String>,
}
impl ContextMenuBuilder {
/// Create a new context menu builder
pub fn new() -> Self {
Self {
x: 0.0,
y: 0.0,
items: Vec::new(),
min_width: 180.0,
classes: Vec::new(),
user_id: None,
}
}
/// Set the position where the menu should appear
pub fn at(mut self, x: f32, y: f32) -> Self {
self.x = x;
self.y = y;
self
}
/// Add a menu item
pub fn item<F>(mut self, label: impl Into<String>, on_click: F) -> Self
where
F: Fn() + Send + Sync + 'static,
{
self.items
.push(ContextMenuItem::new(label).on_click(on_click));
self
}
/// Add a menu item with keyboard shortcut
pub fn item_with_shortcut<F>(
mut self,
label: impl Into<String>,
shortcut: impl Into<String>,
on_click: F,
) -> Self
where
F: Fn() + Send + Sync + 'static,
{
self.items.push(
ContextMenuItem::new(label)
.shortcut(shortcut)
.on_click(on_click),
);
self
}
/// Add a menu item with icon
pub fn item_with_icon<F>(
mut self,
label: impl Into<String>,
icon_svg: impl Into<String>,
on_click: F,
) -> Self
where
F: Fn() + Send + Sync + 'static,
{
self.items.push(
ContextMenuItem::new(label)
.icon(icon_svg)
.on_click(on_click),
);
self
}
/// Add a disabled menu item
pub fn item_disabled(mut self, label: impl Into<String>) -> Self {
self.items.push(ContextMenuItem::new(label).disabled());
self
}
/// Add a separator line
pub fn separator(mut self) -> Self {
self.items.push(ContextMenuItem::separator());
self
}
/// Add a submenu
pub fn submenu<F>(mut self, label: impl Into<String>, builder: F) -> Self
where
F: FnOnce(SubmenuBuilder) -> SubmenuBuilder,
{
let sub = builder(SubmenuBuilder::new());
self.items
.push(ContextMenuItem::new(label).submenu(sub.items));
self
}
/// Add a raw menu item
pub fn add_item(mut self, item: ContextMenuItem) -> Self {
self.items.push(item);
self
}
/// Add a CSS class for selector matching
pub fn class(mut self, name: impl Into<String>) -> Self {
self.classes.push(name.into());
self
}
/// Set the element ID for CSS selector matching
pub fn id(mut self, id: &str) -> Self {
self.user_id = Some(id.to_string());
self
}
/// Set minimum width
pub fn min_width(mut self, width: f32) -> Self {
self.min_width = width;
self
}
/// Show the context menu
pub fn show(self) -> OverlayHandle {
let theme = ThemeState::get();
let bg = theme.color(ColorToken::Surface);
let border = theme.color(ColorToken::Border);
let text_color = theme.color(ColorToken::TextPrimary);
let text_secondary = theme.color(ColorToken::TextSecondary);
let text_tertiary = theme.color(ColorToken::TextTertiary);
let surface_elevated = theme.color(ColorToken::SurfaceElevated);
let radius = theme.radius(RadiusToken::Md);
// Use same sizing as Select dropdown for consistency
let font_size = 14.0; // Medium size font
let padding = 12.0; // Medium size padding
let items = self.items;
let width = self.min_width;
let x = self.x;
let y = self.y;
let classes = self.classes;
let user_id = self.user_id;
// Store overlay handle for closing from menu items
let handle_key = format!("_context_menu_handle_{}_{}", x as i32, y as i32);
let overlay_handle_state: State<Option<u64>> =
BlincContextState::get().use_state_keyed(&handle_key, || None);
let handle_state_for_content = overlay_handle_state.clone();
// Create a key for the menu content
let menu_key = format!("_context_menu_{}_{}", x as i32, y as i32);
let mgr = get_overlay_manager();
// Create a unique motion key for this context menu instance
// The motion is on the child of the wrapper div, so we need ":child:0" suffix
let motion_key_str = format!("ctxmenu_{}", menu_key);
let motion_key_with_child = format!("{}:child:0", motion_key_str);
// Use dropdown() instead of context_menu() to get transparent backdrop
// that dismisses on click outside (same as Select component)
let handle = mgr
.dropdown()
.at(x, y)
.dismiss_on_escape(true)
.motion_key(&motion_key_with_child)
.content(move || {
let mut content = build_menu_content(
&items,
width,
&handle_state_for_content,
&motion_key_str,
bg,
border,
text_color,
text_secondary,
text_tertiary,
surface_elevated,
radius,
font_size,
padding,
);
for c in &classes {
content = content.class(c);
}
if let Some(ref id) = user_id {
content = content.id(id);
}
content
})
.show();
overlay_handle_state.set(Some(handle.id()));
handle
}
}
impl Default for ContextMenuBuilder {
fn default() -> Self {
Self::new()
}
}
/// Builder for submenu items
pub struct SubmenuBuilder {
items: Vec<ContextMenuItem>,
}
impl SubmenuBuilder {
fn new() -> Self {
Self { items: Vec::new() }
}
/// Add a menu item
pub fn item<F>(mut self, label: impl Into<String>, on_click: F) -> Self
where
F: Fn() + Send + Sync + 'static,
{
self.items
.push(ContextMenuItem::new(label).on_click(on_click));
self
}
/// Add a menu item with keyboard shortcut
pub fn item_with_shortcut<F>(
mut self,
label: impl Into<String>,
shortcut: impl Into<String>,
on_click: F,
) -> Self
where
F: Fn() + Send + Sync + 'static,
{
self.items.push(
ContextMenuItem::new(label)
.shortcut(shortcut)
.on_click(on_click),
);
self
}
/// Add a disabled menu item
pub fn item_disabled(mut self, label: impl Into<String>) -> Self {
self.items.push(ContextMenuItem::new(label).disabled());
self
}
/// Add a separator
pub fn separator(mut self) -> Self {
self.items.push(ContextMenuItem::separator());
self
}
/// Get the items from this submenu builder
pub fn items(self) -> Vec<ContextMenuItem> {
self.items
}
}
impl SubmenuBuilder {
/// Create a new submenu builder (public for use by other components)
pub fn new_public() -> Self {
Self::new()
}
}
impl Default for SubmenuBuilder {
fn default() -> Self {
Self::new()
}
}
/// Show a submenu overlay positioned to the right of the parent item
fn show_context_submenu(
x: f32,
y: f32,
items: &[ContextMenuItem],
min_width: f32,
parent_handle_state: State<Option<u64>>,
submenu_handle_state: State<Option<u64>>,
key: String,
) -> OverlayHandle {
let theme = ThemeState::get();
let bg = theme.color(ColorToken::Surface);
let border = theme.color(ColorToken::Border);
let text_color = theme.color(ColorToken::TextPrimary);
let text_secondary = theme.color(ColorToken::TextSecondary);
let text_tertiary = theme.color(ColorToken::TextTertiary);
let surface_elevated = theme.color(ColorToken::SurfaceElevated);
let radius = theme.radius(RadiusToken::Md);
let font_size = 14.0;
let padding = 12.0;
let items = items.to_vec();
let submenu_handle_for_content = submenu_handle_state.clone();
let parent_handle_for_content = parent_handle_state.clone();
let submenu_handle_for_close = submenu_handle_state.clone();
let mgr = get_overlay_manager();
let motion_key_str = format!("ctx_submenu_{}", key);
let motion_key_with_child = format!("{}:child:0", motion_key_str);
mgr.dropdown()
.at(x, y)
.dismiss_on_escape(true)
.motion_key(&motion_key_with_child)
.on_close(move || {
submenu_handle_for_close.set(None);
})
.content(move || {
build_submenu_content(
&items,
min_width,
&parent_handle_for_content,
&submenu_handle_for_content,
&motion_key_str,
bg,
border,
text_color,
text_secondary,
text_tertiary,
surface_elevated,
radius,
font_size,
padding,
)
})
.show()
}
/// Build submenu content (recursive for nested submenus)
#[allow(clippy::too_many_arguments)]
fn build_submenu_content(
items: &[ContextMenuItem],
width: f32,
parent_handle_state: &State<Option<u64>>,
submenu_handle_state: &State<Option<u64>>,
key: &str,
bg: Color,
border: Color,
text_color: Color,
text_secondary: Color,
text_tertiary: Color,
surface_elevated: Color,
radius: f32,
font_size: f32,
padding: f32,
) -> Div {
let menu_id = key;
// State for tracking nested submenus
let nested_submenu_handle: State<Option<u64>> =
BlincContextState::get().use_state_keyed(&format!("{}_nested", key), || None);
let mut menu = div()
.class("cn-context-menu")
.id(menu_id)
.flex_col()
.w(width)
.bg(bg)
.border(1.0, border)
.rounded(radius)
.shadow_lg()
.overflow_clip()
.h_fit();
for (idx, item) in items.iter().enumerate() {
if item.is_separator {
menu = menu.child(hr_with_bg(bg));
} else {
let item_label = item.label.clone();
let item_shortcut = item.shortcut.clone();
let item_icon = item.icon.clone();
let item_disabled = item.disabled;
let item_on_click = item.on_click.clone();
let has_submenu = item.submenu.is_some();
let submenu_items = item.submenu.clone();
let parent_handle_for_click = parent_handle_state.clone();
let submenu_handle_for_click = submenu_handle_state.clone();
let nested_submenu_for_hover = nested_submenu_handle.clone();
let nested_submenu_for_leave = nested_submenu_handle.clone();
let item_key = format!("{}_item-{}", key, idx);
let submenu_key = format!("{}_sub-{}", key, idx);
let item_text_color = if item_disabled {
text_tertiary
} else {
text_color
};
let shortcut_color = text_secondary;
let mut row = stateful_with_key::<ButtonState>(&item_key)
.on_state(move |ctx| {
let state = ctx.state();
let theme = ThemeState::get();
// Background is handled by CSS .cn-context-menu-item:hover
let item_bg = bg;
let text_col = if (state == ButtonState::Hovered || state == ButtonState::Pressed) && !item_disabled {
theme.color(ColorToken::TextSecondary)
} else {
item_text_color
};
let mut left_side = div()
.w_fit()
.h_fit()
.flex_row()
.items_center()
.gap(padding / 4.0);
if let Some(ref icon_svg) = item_icon {
left_side = left_side.child(svg(icon_svg).size(16.0, 16.0).color(item_text_color));
}
left_side = left_side.child(
text(&item_label)
.size(font_size)
.color(text_col)
.no_cursor().pointer_events_none(),
).pointer_events_none();
let right_side: Option<Div> = if let Some(ref shortcut) = item_shortcut {
Some(div().child(
text(shortcut)
.size(font_size - 2.0)
.color(shortcut_color)
.no_cursor(),
))
} else if has_submenu {
let chevron_right = r#"<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m9 18 6-6-6-6"/></svg>"#;
Some(div().child(svg(chevron_right).size(12.0, 12.0).color(text_tertiary)).pointer_events_none())
} else {
None
};
let mut row_content = div()
.class("cn-context-menu-item")
.w_full()
.h_fit()
.py(padding / 4.0)
.px(padding / 2.0)
.bg(item_bg)
.cursor(if item_disabled {
CursorStyle::NotAllowed
} else {
CursorStyle::Pointer
})
.flex_row()
.items_center()
.justify_between()
.child(left_side);
if let Some(right) = right_side {
row_content = row_content.child(right);
}
row_content
})
.on_click(move |_| {
if !item_disabled && !has_submenu {
if let Some(ref cb) = item_on_click {
cb();
}
// Close the submenu
if let Some(handle_id) = submenu_handle_for_click.get() {
let mgr = get_overlay_manager();
mgr.close(OverlayHandle::from_raw(handle_id));
}
// Close the parent menu
if let Some(handle_id) = parent_handle_for_click.get() {
let mgr = get_overlay_manager();
mgr.close(OverlayHandle::from_raw(handle_id));
}
}
});
// Add hover handlers for submenu items
if has_submenu && !item_disabled {
let submenu_items_for_hover = submenu_items.clone();
let parent_handle_for_submenu = parent_handle_state.clone();
let submenu_key_for_hover = submenu_key.clone();
row = row.on_hover_enter(move |ctx| {
// Close any existing nested submenu
if let Some(handle_id) = nested_submenu_for_hover.get() {
let mgr = get_overlay_manager();
let handle = OverlayHandle::from_raw(handle_id);
if !mgr.is_closing(handle) && !mgr.is_pending_close(handle) {
mgr.close(handle);
}
}
// Show new nested submenu
if let Some(ref items) = submenu_items_for_hover {
let x = ctx.bounds_x + ctx.bounds_width + 4.0;
let y = ctx.bounds_y;
let handle = show_context_submenu(
x,
y,
items,
160.0,
parent_handle_for_submenu.clone(),
nested_submenu_for_hover.clone(),
submenu_key_for_hover.clone(),
);
nested_submenu_for_hover.set(Some(handle.id()));
}
});
} else {
// Close nested submenu when hovering non-submenu item
row = row.on_hover_enter(move |_| {
if let Some(handle_id) = nested_submenu_for_leave.get() {
let mgr = get_overlay_manager();
let handle = OverlayHandle::from_raw(handle_id);
if !mgr.is_closing(handle) && !mgr.is_pending_close(handle) {
mgr.close(handle);
}
}
});
}
menu = menu.child(row);
}
}
div().child(
motion_derived(key)
.enter_animation(AnimationPreset::context_menu_in(150))
.exit_animation(AnimationPreset::context_menu_out(100))
.child(menu),
)
}
/// Build the menu content div
///
/// Uses the same layout pattern as the Select dropdown for consistency.
#[allow(clippy::too_many_arguments)]
fn build_menu_content(
items: &[ContextMenuItem],
width: f32,
overlay_handle_state: &State<Option<u64>>,
key: &str,
bg: Color,
border: Color,
text_color: Color,
text_secondary: Color,
text_tertiary: Color,
surface_elevated: Color,
radius: f32,
font_size: f32,
padding: f32,
) -> Div {
// Generate a unique ID for the menu based on the key
let menu_id = key;
// State for tracking open submenu
let submenu_handle: State<Option<u64>> =
BlincContextState::get().use_state_keyed(&format!("{}_submenu", key), || None);
let mut menu = div()
.class("cn-context-menu")
.id(menu_id)
.flex_col()
.w(width)
.bg(bg)
.border(1.0, border)
.rounded(radius)
.shadow_lg()
.overflow_clip()
.h_fit();
// Note: on_ready callback removed - overlay manager now uses initial size estimation
// If accurate sizing is needed, register via ctx.query("context-menu-{handle}").on_ready(...)
for (idx, item) in items.iter().enumerate() {
if item.is_separator {
// Separator line with explicit background to prevent alpha artifacts
// during opacity animations
menu = menu.child(hr_with_bg(bg));
} else {
// Regular menu item
let item_label = item.label.clone();
let item_shortcut = item.shortcut.clone();
let item_icon = item.icon.clone();
let item_disabled = item.disabled;
let item_on_click = item.on_click.clone();
let has_submenu = item.submenu.is_some();
let submenu_items = item.submenu.clone();
let handle_state_for_click = overlay_handle_state.clone();
let submenu_handle_for_hover = submenu_handle.clone();
let submenu_handle_for_leave = submenu_handle.clone();
// Create a stable key for this item's button state
let item_key = format!("{}_item-{}", key, idx);
let submenu_key = format!("{}_sub-{}", key, idx);
let item_text_color = if item_disabled {
text_tertiary
} else {
text_color
};
let shortcut_color = text_secondary;
// Build the stateful menu item row
let mut row = stateful_with_key::<ButtonState>(&item_key)
.on_state(move |ctx| {
let state = ctx.state();
let theme = ThemeState::get();
// Background is handled by CSS .cn-context-menu-item:hover
let item_bg = bg;
let text_col = if (state == ButtonState::Hovered || state == ButtonState::Pressed) && !item_disabled {
theme.color(ColorToken::TextSecondary)
} else {
item_text_color
};
// Left side: icon + label
let mut left_side = div()
.w_fit()
.h_fit()
.flex_row()
.items_center()
.gap(padding / 4.0);
if let Some(ref icon_svg) = item_icon {
left_side = left_side.child(svg(icon_svg).size(16.0, 16.0).color(item_text_color));
}
left_side = left_side.child(
text(&item_label)
.size(font_size)
.color(text_col)
.no_cursor(),
);
// Right side: shortcut or submenu arrow
let right_side: Option<Div> = if let Some(ref shortcut) = item_shortcut {
Some(div().child(
text(shortcut)
.size(font_size - 2.0)
.color(shortcut_color)
.no_cursor(),
))
} else if has_submenu {
let chevron_right = r#"<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m9 18 6-6-6-6"/></svg>"#;
Some(div().child(svg(chevron_right).size(12.0, 12.0).color(text_tertiary)))
} else {
None
};
let mut row_content = div()
.class("cn-context-menu-item")
.w_full()
.h_fit()
.py(padding / 4.0)
.px(padding / 2.0)
.bg(item_bg)
.cursor(if item_disabled {
CursorStyle::NotAllowed
} else {
CursorStyle::Pointer
})
.flex_row()
.items_center()
.justify_between()
.child(left_side);
if let Some(right) = right_side {
row_content = row_content.child(right);
}
row_content
})
.on_click(move |_| {
if !item_disabled && !has_submenu {
// Execute the callback
if let Some(ref cb) = item_on_click {
cb();
}
// Close the menu
if let Some(handle_id) = handle_state_for_click.get() {
let mgr = get_overlay_manager();
mgr.close(OverlayHandle::from_raw(handle_id));
}
}
});
// Add hover handlers for submenu items
if has_submenu && !item_disabled {
let submenu_items_for_hover = submenu_items.clone();
let overlay_handle_for_submenu = overlay_handle_state.clone();
let submenu_key_for_hover = submenu_key.clone();
row = row.on_hover_enter(move |ctx| {
// Close any existing submenu
if let Some(handle_id) = submenu_handle_for_hover.get() {
let mgr = get_overlay_manager();
let handle = OverlayHandle::from_raw(handle_id);
if !mgr.is_closing(handle) && !mgr.is_pending_close(handle) {
mgr.close(handle);
}
}
// Show submenu to the right of this item
if let Some(ref items) = submenu_items_for_hover {
let x = ctx.bounds_x + ctx.bounds_width + 4.0;
let y = ctx.bounds_y;
let handle = show_context_submenu(
x,
y,
items,
160.0,
overlay_handle_for_submenu.clone(),
submenu_handle_for_hover.clone(),
submenu_key_for_hover.clone(),
);
submenu_handle_for_hover.set(Some(handle.id()));
}
});
} else {
// When hovering a non-submenu item, close any open submenu
row = row.on_hover_enter(move |_| {
if let Some(handle_id) = submenu_handle_for_leave.get() {
let mgr = get_overlay_manager();
let handle = OverlayHandle::from_raw(handle_id);
if !mgr.is_closing(handle) && !mgr.is_pending_close(handle) {
mgr.close(handle);
}
}
});
}
menu = menu.child(row);
}
}
// Wrap menu in motion container for enter/exit animations
// Use motion_derived with the key so the overlay can trigger exit animation
div().child(
motion_derived(key)
.enter_animation(AnimationPreset::context_menu_in(150))
.exit_animation(AnimationPreset::context_menu_out(100))
.child(menu),
)
}
/// Create a context menu builder
///
/// # Example
///
/// ```ignore
/// cn::context_menu()
/// .at(event.x, event.y)
/// .item("Cut", || println!("Cut"))
/// .item("Copy", || println!("Copy"))
/// .separator()
/// .item("Paste", || println!("Paste"))
/// .show();
/// ```
pub fn context_menu() -> ContextMenuBuilder {
ContextMenuBuilder::new()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_menu_item_creation() {
let item = ContextMenuItem::new("Test");
assert_eq!(item.label, "Test");
assert!(!item.disabled);
assert!(!item.is_separator);
}
#[test]
fn test_menu_item_with_shortcut() {
let item = ContextMenuItem::new("Copy").shortcut("Ctrl+C");
assert_eq!(item.shortcut, Some("Ctrl+C".to_string()));
}
#[test]
fn test_separator() {
let sep = ContextMenuItem::separator();
assert!(sep.is_separator);
}
#[test]
fn test_disabled_item() {
let item = ContextMenuItem::new("Disabled").disabled();
assert!(item.disabled);
}
#[test]
fn test_builder_items() {
let menu = ContextMenuBuilder::new()
.item("Item 1", || {})
.separator()
.item("Item 2", || {});
assert_eq!(menu.items.len(), 3);
assert!(!menu.items[0].is_separator);
assert!(menu.items[1].is_separator);
assert!(!menu.items[2].is_separator);
}
#[test]
fn test_builder_position() {
let menu = ContextMenuBuilder::new().at(100.0, 200.0);
assert_eq!(menu.x, 100.0);
assert_eq!(menu.y, 200.0);
}
}