egui_macview/layout/
form.rs1use crate::theme::MacTheme;
7use egui::{vec2, Align, IdSalt, Layout, Response, Ui, Vec2, WidgetText};
8
9pub struct MacForm<'a> {
11 id_salt: IdSalt,
12 theme: Option<&'a MacTheme>,
13 spacing: Option<Vec2>,
14 min_col_width: Option<f32>,
15}
16
17impl<'a> MacForm<'a> {
18 pub fn new(id_salt: impl egui::AsIdSalt) -> Self {
20 Self {
21 id_salt: IdSalt::new(id_salt),
22 theme: None,
23 spacing: None,
24 min_col_width: None,
25 }
26 }
27
28 pub fn theme(mut self, theme: &'a MacTheme) -> Self {
30 self.theme = Some(theme);
31 self
32 }
33
34 pub fn spacing(mut self, spacing: impl Into<Vec2>) -> Self {
36 self.spacing = Some(spacing.into());
37 self
38 }
39
40 pub fn min_col_width(mut self, min_col_width: f32) -> Self {
42 self.min_col_width = Some(min_col_width);
43 self
44 }
45
46 pub fn show<R>(self, ui: &mut Ui, add_contents: impl FnOnce(&mut MacFormUi<'_>) -> R) -> R {
48 let spacing = self.spacing.unwrap_or_else(|| {
49 let s = self
50 .theme
51 .map(|t| t.stack_view().default_spacing.points())
52 .unwrap_or_else(|| ui.spacing().item_spacing.x);
53 vec2(s, s)
54 });
55
56 let mut result = None;
57 let mut grid = egui::Grid::new(self.id_salt)
58 .num_columns(2)
59 .spacing(spacing);
60 if let Some(min_w) = self.min_col_width {
61 grid = grid.min_col_width(min_w);
62 }
63 grid.show(ui, |grid_ui| {
64 let mut form_ui = MacFormUi { ui: grid_ui };
65 result = Some(add_contents(&mut form_ui));
66 });
67 result.expect("MacForm grid rendered")
68 }
69}
70
71pub struct MacFormUi<'a> {
73 pub ui: &'a mut Ui,
75}
76
77impl<'a> MacFormUi<'a> {
78 pub fn row<R1, R2>(
80 &mut self,
81 label: impl FnOnce(&mut Ui) -> R1,
82 control: impl FnOnce(&mut Ui) -> R2,
83 ) -> (R1, R2) {
84 let r1 = self
85 .ui
86 .with_layout(Layout::right_to_left(Align::Center), label)
87 .inner;
88 let r2 = self
89 .ui
90 .with_layout(Layout::left_to_right(Align::Center), control)
91 .inner;
92 self.ui.end_row();
93 (r1, r2)
94 }
95
96 pub fn row_label<R>(
98 &mut self,
99 label_text: impl Into<WidgetText>,
100 control: impl FnOnce(&mut Ui) -> R,
101 ) -> (Response, R) {
102 let text = label_text.into();
103 self.row(|ui| ui.label(text), control)
104 }
105}