Skip to main content

egui_pop_views/
property.rs

1//! Property rows: a name and a value, their name column aligned.
2//!
3//! <div class="warning">Experimental: may change in any release
4//! (docs/stability.md).</div>
5//!
6//! A [`PropertyRow`] is a [`ListItem`](crate::item::ListItem)'s row (its
7//! height, its box, hovered under the pointer) split in two: the name, in
8//! the row's muted tone, and the value, any widget. The name column is as
9//! wide as the widest name of its rows: the rows sharing a column id
10//! ([`PropertyRow::column`]; by default, the rows of one `Ui`) line their
11//! values up, as a selection panel does. The column never takes more than
12//! [`NAME_SHARE`] of the row.
13//!
14//! A value is editable unless the row is read-only
15//! ([`PropertyRow::read_only`]: its widgets are disabled). A plain value
16//! is text ([`PropertyRow::text`]); a widget given with
17//! [`PropertyRow::widget`] is named by the property for screen readers.
18//!
19//! ```
20//! use egui_pop_views::property::PropertyRow;
21//!
22//! fn entity(ui: &mut egui::Ui, radius: &mut f32, visible: &mut bool) {
23//!     PropertyRow::new("Path").text(ui, "world/points");
24//!     PropertyRow::new("Archetype").text(ui, "Points3D");
25//!     PropertyRow::new("Radius").widget(ui, egui::DragValue::new(radius).speed(0.1));
26//!     PropertyRow::new("Visible").widget(ui, egui::Checkbox::without_text(visible));
27//! }
28//! # let _ = entity;
29//! ```
30
31use egui::{
32    Align, AsIdSalt, FontSelection, Id, InnerResponse, Layout, Rect, Response, Role, Sense, Shape,
33    TextStyle, Ui, UiBuilder, Widget, WidgetInfo, WidgetText, pos2, vec2,
34};
35use egui_pop_core::kit::{Kit, Part, State, Tone};
36use egui_pop_core::theme::Tokens;
37
38use crate::item::row_height;
39
40/// The most of a row's width its name column takes.
41pub const NAME_SHARE: f32 = 0.5;
42
43/// A name and a value: see the [module](self).
44#[derive(Clone, Debug)]
45#[must_use]
46pub struct PropertyRow {
47    name: String,
48    column: Option<Id>,
49    depth: usize,
50    read_only: bool,
51    height: Option<f32>,
52}
53
54impl PropertyRow {
55    /// A row for the property `name`.
56    pub fn new(name: impl Into<String>) -> Self {
57        Self {
58            name: name.into(),
59            column: None,
60            depth: 0,
61            read_only: false,
62            height: None,
63        }
64    }
65
66    /// The rows whose names line up: those given the same id (default:
67    /// the rows of one `Ui`).
68    pub fn column(mut self, id: impl AsIdSalt) -> Self {
69        self.column = Some(Id::unique(id));
70        self
71    }
72
73    /// Nested under another property: its name indented one step per
74    /// level (the value column stays where it is).
75    pub fn depth(mut self, depth: usize) -> Self {
76        self.depth = depth;
77        self
78    }
79
80    /// The value cannot be changed: its widgets are disabled.
81    pub fn read_only(mut self, read_only: bool) -> Self {
82        self.read_only = read_only;
83        self
84    }
85
86    /// Its least height (default: [`row_height`]); a taller value grows
87    /// it.
88    pub fn height(mut self, height: f32) -> Self {
89        self.height = Some(height);
90        self
91    }
92
93    /// A plain value: text, selectable for copying.
94    pub fn text(self, ui: &mut Ui, value: impl Into<WidgetText>) -> Response {
95        let value = value.into();
96        self.show(ui, |ui| {
97            ui.add(egui::Label::new(value).truncate().selectable(true))
98        })
99        .inner
100    }
101
102    /// A widget as the value, named by the property for screen readers.
103    pub fn widget(self, ui: &mut Ui, widget: impl Widget) -> Response {
104        let out = self.show(ui, |ui| ui.add(widget));
105        out.inner.labelled_by(name_id(out.response.id))
106    }
107
108    /// The value drawn by `add`, left to right in the value column. The
109    /// response is the row's; its name's accessible node is
110    /// `response.id.with("name")`, for `Response::labelled_by`.
111    pub fn show<R>(self, ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> InnerResponse<R> {
112        let kit = Kit::of(ui.ctx());
113        let t = Tokens::of(ui.ctx());
114        let h = self.height.unwrap_or_else(|| row_height(ui));
115        let id = ui.next_auto_id();
116        let width = ui.available_width();
117        let top = ui.cursor().min;
118        let indent = ui.spacing().indent;
119        let pad = ui.spacing().item_spacing.x;
120        let font = FontSelection::Style(TextStyle::Body).resolve(ui.style());
121        let name = ui
122            .painter()
123            .layout_no_wrap(self.name.clone(), font, egui::Color32::PLACEHOLDER);
124        let start = self.depth as f32 * indent + pad;
125        let column = self
126            .column
127            .unwrap_or_else(|| ui.scope_id().with("property_column"));
128        let split = name_column(
129            ui,
130            column,
131            start + name.size().x + t.space.l,
132            width * NAME_SHARE,
133        );
134
135        // The box goes under the name and the value once the row's height
136        // is known.
137        let slot = ui.painter().add(Shape::Noop);
138        let value_rect = Rect::from_min_max(
139            pos2(top.x + split, top.y),
140            pos2(top.x + width - pad, top.y + h),
141        );
142        let mut value = ui.new_child(
143            UiBuilder::new()
144                .id_salt(id.with("value"))
145                .max_rect(value_rect)
146                .layout(Layout::left_to_right(Align::Center)),
147        );
148        if self.read_only {
149            value.disable();
150        }
151        let inner = add(&mut value);
152        let height = h.max(value.min_rect().height());
153        let rect = Rect::from_min_size(top, vec2(width, height));
154        let response = ui.allocate_rect(rect, Sense::hover());
155        let state = State::REST.with(State::HOVER, response.contains_pointer());
156        kit.list_item.paint_under(
157            ui,
158            slot,
159            &Part {
160                rect,
161                room: rect,
162                state,
163                label: None,
164            },
165            None,
166        );
167        let color = kit.list_item.style_toned(Tone::Muted, state).text;
168        let name_rect = Rect::from_min_max(
169            pos2(top.x + start, top.y),
170            pos2((top.x + split - pad).max(top.x + start), top.y + h),
171        );
172        let at = pos2(name_rect.left(), name_rect.center().y - name.size().y / 2.0);
173        ui.painter()
174            .with_clip_rect(name_rect.intersect(ui.clip_rect()))
175            .galley(at, name, color);
176        let named = ui.interact(name_rect, name_id(response.id), Sense::hover());
177        let text = self.name;
178        named.widget_info(move || WidgetInfo::labeled(Role::Label, true, &text));
179        InnerResponse { inner, response }
180    }
181}
182
183/// The accessible node of a row's name.
184fn name_id(row: Id) -> Id {
185    row.with("name")
186}
187
188/// Where the value column starts for the rows of `column`: the widest
189/// name they asked for (`wanted`), at most `most`. The widest of the last
190/// pass is used, so names shrink a pass later; a name wider than any
191/// before discards the pass, and every row is drawn again with it.
192fn name_column(ui: &Ui, column: Id, wanted: f32, most: f32) -> f32 {
193    #[derive(Clone, Copy, Default)]
194    struct Widest {
195        pass: u64,
196        last: f32,
197        now: f32,
198    }
199    let pass = ui.ctx().cumulative_pass_nr();
200    let id = column.with("egui_pop_views::property");
201    let (widest, grew) = ui.ctx().data_mut(|d| {
202        let w = d.get_temp_mut_or_default::<Widest>(id);
203        if w.pass != pass {
204            w.last = w.now;
205            w.now = 0.0;
206            w.pass = pass;
207        }
208        w.now = w.now.max(wanted);
209        let grew = wanted > w.last;
210        if grew {
211            w.last = wanted;
212        }
213        (w.last, grew)
214    });
215    if grew {
216        ui.ctx()
217            .request_discard("a property name wider than before");
218    }
219    widest.min(most).max(0.0)
220}