use crate::theme::MacTheme;
use egui::{vec2, Align, IdSalt, Layout, Response, Ui, Vec2, WidgetText};
pub struct MacForm<'a> {
id_salt: IdSalt,
theme: Option<&'a MacTheme>,
spacing: Option<Vec2>,
min_col_width: Option<f32>,
}
impl<'a> MacForm<'a> {
pub fn new(id_salt: impl egui::AsIdSalt) -> Self {
Self {
id_salt: IdSalt::new(id_salt),
theme: None,
spacing: None,
min_col_width: None,
}
}
pub fn theme(mut self, theme: &'a MacTheme) -> Self {
self.theme = Some(theme);
self
}
pub fn spacing(mut self, spacing: impl Into<Vec2>) -> Self {
self.spacing = Some(spacing.into());
self
}
pub fn min_col_width(mut self, min_col_width: f32) -> Self {
self.min_col_width = Some(min_col_width);
self
}
pub fn show<R>(self, ui: &mut Ui, add_contents: impl FnOnce(&mut MacFormUi<'_>) -> R) -> R {
let spacing = self.spacing.unwrap_or_else(|| {
let s = self
.theme
.map(|t| t.stack_view().default_spacing.points())
.unwrap_or_else(|| ui.spacing().item_spacing.x);
vec2(s, s)
});
let mut result = None;
let mut grid = egui::Grid::new(self.id_salt)
.num_columns(2)
.spacing(spacing);
if let Some(min_w) = self.min_col_width {
grid = grid.min_col_width(min_w);
}
grid.show(ui, |grid_ui| {
let mut form_ui = MacFormUi { ui: grid_ui };
result = Some(add_contents(&mut form_ui));
});
result.expect("MacForm grid rendered")
}
}
pub struct MacFormUi<'a> {
pub ui: &'a mut Ui,
}
impl<'a> MacFormUi<'a> {
pub fn row<R1, R2>(
&mut self,
label: impl FnOnce(&mut Ui) -> R1,
control: impl FnOnce(&mut Ui) -> R2,
) -> (R1, R2) {
let r1 = self
.ui
.with_layout(Layout::right_to_left(Align::Center), label)
.inner;
let r2 = self
.ui
.with_layout(Layout::left_to_right(Align::Center), control)
.inner;
self.ui.end_row();
(r1, r2)
}
pub fn row_label<R>(
&mut self,
label_text: impl Into<WidgetText>,
control: impl FnOnce(&mut Ui) -> R,
) -> (Response, R) {
let text = label_text.into();
self.row(|ui| ui.label(text), control)
}
}