Skip to main content

armas_basic/ext/
context.rs

1//! Context extension for Armas theme storage
2//!
3//! This extension trait allows storing the Armas theme in egui's context,
4//! eliminating the need to pass theme to every component.
5
6use crate::Theme;
7use egui::Context;
8
9/// Extension trait for storing Armas theme in egui Context
10///
11/// # Example
12///
13/// ```rust,no_run
14/// use armas_basic::ext::ArmasContextExt;
15/// use armas_basic::Theme;
16///
17/// fn setup(ctx: &egui::Context) {
18///     // Set theme once
19///     ctx.set_armas_theme(Theme::dark());
20/// }
21///
22/// fn my_ui(ui: &mut egui::Ui) {
23///     // Components automatically get theme from context
24///     let theme = ui.ctx().armas_theme();
25///     // ...
26/// }
27/// ```
28pub trait ArmasContextExt {
29    /// Get the current Armas theme from context
30    ///
31    /// Returns the theme previously set with `set_armas_theme()`.
32    /// If no theme was set, returns `Theme::dark()` as default.
33    fn armas_theme(&self) -> Theme;
34
35    /// Set the Armas theme in context
36    ///
37    /// This stores the theme globally in egui's context, making it
38    /// available to all components without explicit passing.
39    ///
40    /// # Example
41    ///
42    /// ```rust,no_run
43    /// # use armas_basic::ext::ArmasContextExt;
44    /// # use armas_basic::Theme;
45    /// # let ctx = &egui::Context::default();
46    /// # let user_wants_light_theme = false;
47    /// // Set theme once at startup
48    /// ctx.set_armas_theme(Theme::dark());
49    ///
50    /// // Change theme dynamically
51    /// if user_wants_light_theme {
52    ///     ctx.set_armas_theme(Theme::light());
53    /// }
54    /// ```
55    fn set_armas_theme(&self, theme: Theme);
56}
57
58impl ArmasContextExt for Context {
59    fn armas_theme(&self) -> Theme {
60        self.data(|d| d.get_temp(egui::Id::new("armas_theme")))
61            .unwrap_or_else(Theme::dark)
62    }
63
64    fn set_armas_theme(&self, theme: Theme) {
65        self.data_mut(|d| d.insert_temp(egui::Id::new("armas_theme"), theme));
66    }
67}