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
use freya_core::{
integration::ScopeId,
layers::Layer,
prelude::*,
};
use torin::prelude::{
CursorPoint,
Position,
};
use crate::menu::Menu;
/// Closing is only allowed once a new click starts after the menu opened.
#[derive(Clone, Copy, PartialEq)]
pub(crate) enum ClosePhase {
/// A down event just happened, now waiting for its press.
PendingPress,
/// Waiting for a new click.
Idle,
/// A new click started, it may close the menu.
CloseAllowed,
}
/// Global context menu state.
///
/// Requires a [`ContextMenuViewer`] in an ancestor scope.
///
/// # Example
///
/// ```rust
/// # use freya::prelude::*;
/// fn app() -> impl IntoElement {
/// rect().child(ContextMenuViewer::new()).child(
/// rect()
/// .on_secondary_down(move |_| {
/// ContextMenu::open_from_down(
/// Menu::new().child(MenuButton::new().child("Option 1")),
/// );
/// })
/// .child("Right click to open menu"),
/// )
/// }
/// ```
#[derive(Clone, Copy, PartialEq)]
pub struct ContextMenu {
pub(crate) location: State<CursorPoint>,
pub(crate) menu: State<Option<(CursorPoint, Menu)>>,
pub(crate) close_phase: State<ClosePhase>,
}
impl ContextMenu {
/// Returns whether the context menu is open, or `false` if no viewer is mounted.
///
/// # Example
///
/// ```rust
/// # use freya::prelude::*;
/// fn app() -> impl IntoElement {
/// rect()
/// .child(ContextMenuViewer::new())
/// .child(if ContextMenu::is_open() {
/// "Menu open"
/// } else {
/// "Menu closed"
/// })
/// }
/// ```
pub fn is_open() -> bool {
try_consume_root_context::<Self>().is_some_and(|c| c.menu.read().is_some())
}
/// Open the context menu, from a press event or programmatically.
///
/// # Example
///
/// ```rust
/// # use freya::prelude::*;
/// fn app() -> impl IntoElement {
/// rect()
/// .child(ContextMenuViewer::new())
/// .child(Button::new().child("Open menu").on_press(|_| {
/// ContextMenu::open(Menu::new().child(MenuButton::new().child("Copy")));
/// }))
/// }
/// ```
pub fn open(menu: Menu) {
Self::open_with_phase(menu, ClosePhase::Idle);
}
/// Open the context menu from a pointer down event, like `on_secondary_down`.
///
/// # Example
///
/// ```rust
/// # use freya::prelude::*;
/// fn app() -> impl IntoElement {
/// rect().child(ContextMenuViewer::new()).child(
/// rect().child("Right click here").on_secondary_down(|_| {
/// ContextMenu::open_from_down(Menu::new().child(MenuButton::new().child("Copy")));
/// }),
/// )
/// }
/// ```
pub fn open_from_down(menu: Menu) {
Self::open_with_phase(menu, ClosePhase::PendingPress);
}
/// Opens the menu at the current pointer location with the given closing phase.
fn open_with_phase(menu: Menu, phase: ClosePhase) {
let mut this = try_consume_root_context::<Self>()
.expect("ContextMenu requires a `ContextMenuViewer` in an ancestor scope");
this.menu.set(Some(((this.location)(), menu)));
this.close_phase.set(phase);
}
/// Closes the context menu, doing nothing if no viewer is mounted.
///
/// # Example
///
/// ```rust
/// # use freya::prelude::*;
/// fn app() -> impl IntoElement {
/// rect().child(ContextMenuViewer::new()).child(
/// Button::new()
/// .child("Close menu")
/// .on_press(|_| ContextMenu::close()),
/// )
/// }
/// ```
pub fn close() {
if let Some(mut this) = try_consume_root_context::<Self>() {
this.menu.set(None);
}
}
}
/// Provides the [`ContextMenu`] state and renders the floating menu overlay.
///
/// Mount this as high up in your tree as possible (typically in your `app`
/// component) so the rendered menu inherits styling like `font_size` from
/// the app's root element.
///
/// # Example
///
/// ```rust
/// # use freya::prelude::*;
/// fn app() -> impl IntoElement {
/// rect()
/// .font_size(18.)
/// .child(ContextMenuViewer::new())
/// .child("Your app content here")
/// }
/// ```
#[derive(Default, Clone, PartialEq)]
pub struct ContextMenuViewer {
key: DiffKey,
}
impl KeyExt for ContextMenuViewer {
fn key_mut(&mut self) -> &mut DiffKey {
&mut self.key
}
}
impl ContextMenuViewer {
pub fn new() -> Self {
Self::default()
}
}
impl ComponentOwned for ContextMenuViewer {
fn render(self) -> impl IntoElement {
let mut context = use_hook(|| {
try_consume_root_context::<ContextMenu>().unwrap_or_else(|| {
let state = ContextMenu {
location: State::create_in_scope(CursorPoint::default(), ScopeId::ROOT),
menu: State::create_in_scope(None, ScopeId::ROOT),
close_phase: State::create_in_scope(ClosePhase::Idle, ScopeId::ROOT),
};
provide_context_for_scope_id(state, ScopeId::ROOT);
state
})
});
use_side_effect(move || {
if !*Platform::get().current_window().is_app_focused.read() {
context.menu.set(None);
}
});
rect()
.on_global_pointer_move(move |e: Event<PointerEventData>| {
context.location.set(e.global_location());
})
.on_global_pointer_down(move |_: Event<PointerEventData>| {
if context.menu.read().is_some() {
let phase = match (context.close_phase)() {
ClosePhase::PendingPress => ClosePhase::Idle,
_ => ClosePhase::CloseAllowed,
};
context.close_phase.set(phase);
}
})
.maybe_child(context.menu.read().clone().map(|(location, menu)| {
let location = location.to_f32();
rect()
.layer(Layer::Overlay)
.position(
Position::new_global()
.left(location.x.round())
.top(location.y.round()),
)
.child(
menu.on_close(move |_| {
if (context.close_phase)() == ClosePhase::CloseAllowed {
context.menu.set(None);
}
})
.on_escape(move |_| {
context.menu.set(None);
}),
)
}))
}
fn render_key(&self) -> DiffKey {
self.key.clone().or(self.default_key())
}
}