Skip to main content

egui_pop_views/
item.rs

1//! Dense list items: one row look for lists, trees and panels.
2//!
3//! <div class="warning">Experimental: may change in any release
4//! (docs/stability.md).</div>
5//!
6//! A [`ListItem`] is a row of the theme's row height (`size.row.height`,
7//! apart from the controls' `size.control.height`): an optional drag
8//! handle, indent guides down its levels, a collapsing arrow, an icon,
9//! its label, weak text on its right ([`ListItem::trailing`]) and action
10//! buttons ([`ItemAction`]: a visibility eye, remove) shown while the row
11//! is hovered, focused or selected, or always. The tree and the list draw
12//! their rows with the same pieces, so a row looks the same everywhere.
13//! A [`PropertyRow`](crate::property::PropertyRow) is the same row with
14//! a name column and a value.
15//!
16//! Everything is painted through the kit: the row's box is the
17//! `list-item` component (based on `list-row`, so a kit restyling rows
18//! restyles items), its guides `list-guide`, its action buttons
19//! `icon-button`, its arrow the kit's disclosure glyphs.
20//!
21//! ```
22//! use egui_pop_core::icon::Icon;
23//! use egui_pop_views::item::{ItemAction, ListItem};
24//!
25//! fn layer(ui: &mut egui::Ui, shown: &mut bool, selected: bool) -> bool {
26//!     let eye = if *shown { Icon::Visible } else { Icon::Hidden };
27//!     let out = ListItem::new("Ground")
28//!         .icon(Icon::File)
29//!         .trailing("12 points")
30//!         .selected(selected)
31//!         .action(ItemAction::new("visibility", eye, "Hide Ground").pinned(!*shown))
32//!         .show(ui);
33//!     if out.action() == Some("visibility") {
34//!         *shown = !*shown;
35//!     }
36//!     out.response.clicked()
37//! }
38//! # let _ = layer;
39//! ```
40//!
41//! # Keyboard
42//!
43//! A standalone item takes the focus (Tab); Enter or Space clicks it,
44//! Right and Left open and close a collapsing one. Its action buttons
45//! follow it in the Tab order: they show while the item or one of them
46//! has the focus, so Tab walks from the item through its buttons to the
47//! next widget, and Shift+Tab walks back. In the tree, the cursor's row
48//! shows its actions while the tree has the focus, and they come right
49//! after the tree in the Tab order: Tab from the tree reaches the
50//! cursor's buttons, Shift+Tab goes back to the tree. Screen readers also
51//! find each action on the row itself, as a custom action named by its
52//! label.
53//!
54//! A label that does not fit draws on one line, elided with "…" before
55//! the row's trailing text and buttons, which stay whole; hovering the row
56//! then shows the full label. The row's accessible name is always the
57//! full label.
58
59use egui::accesskit::{self, Role};
60use egui::text::{LayoutJob, TextWrapping};
61use egui::{
62    AsIdSalt, Color32, EventFilter, FontSelection, Id, IdSalt, Key, Modifiers, Rect, Response,
63    Sense, TextStyle, Ui, UiBuilder, WidgetInfo, pos2, vec2,
64};
65use egui_pop_core::icon::{Icon, Size, Source};
66use egui_pop_core::kit::{Glyph, Kit, KitCx, Part, State, Tone};
67use egui_pop_core::pointer::{self, DragKind};
68use egui_pop_core::strings::tr_args;
69use egui_pop_core::theme::Tokens;
70
71use crate::strings as s;
72
73/// A row's height: the theme's `size.row.height`, kept apart from the
74/// controls' height, and never under the body text.
75///
76/// It is egui's interact height moved by what the theme's row height
77/// differs from its control height: the token's value once a theme is
78/// installed (which sets egui's interact height to the control height),
79/// egui's interact height in a bare context.
80pub fn row_height(ui: &Ui) -> f32 {
81    let t = Tokens::of(ui.ctx());
82    let shift = t.size.row_height - t.size.control_height;
83    (ui.spacing().interact_size.y + shift).max(ui.text_style_height(&TextStyle::Body) + 4.0)
84}
85
86/// The column on a row's left that holds its collapsing arrow.
87#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
88pub enum Disclosure {
89    /// No column: the content starts after a small padding.
90    #[default]
91    None,
92    /// The column, empty: a leaf among branches, aligned with them.
93    Leaf,
94    /// The column with the open arrow.
95    Open,
96    /// The column with the closed arrow.
97    Closed,
98}
99
100impl Disclosure {
101    /// A branch's arrow, open or closed.
102    pub fn branch(open: bool) -> Self {
103        if open {
104            Disclosure::Open
105        } else {
106            Disclosure::Closed
107        }
108    }
109
110    /// Whether it has the column.
111    pub fn has_column(self) -> bool {
112        self != Disclosure::None
113    }
114
115    /// Whether it draws an arrow (a branch).
116    pub fn is_branch(self) -> bool {
117        matches!(self, Disclosure::Open | Disclosure::Closed)
118    }
119}
120
121/// When a row's action buttons show.
122#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
123pub enum Reveal {
124    /// While the row is hovered, focused (or one of its buttons is) or
125    /// selected; pinned actions always.
126    #[default]
127    Hover,
128    /// Always.
129    Always,
130}
131
132/// An action button at a row's right end: an icon, and its label (its
133/// accessible name and tooltip, and the row's custom action for screen
134/// readers).
135#[derive(Clone, Debug)]
136pub struct ItemAction {
137    id: String,
138    icon: Source,
139    label: String,
140    pinned: bool,
141}
142
143impl ItemAction {
144    /// An action named `id` in the output (and the tree's `tree.action`
145    /// step), drawn as `icon`, named `label`.
146    pub fn new(id: impl Into<String>, icon: impl Into<Source>, label: impl Into<String>) -> Self {
147        Self {
148            id: id.into(),
149            icon: icon.into(),
150            label: label.into(),
151            pinned: false,
152        }
153    }
154
155    /// Shown even when the row's actions are hidden: a state worth seeing
156    /// at a glance (a hidden layer's closed eye).
157    pub fn pinned(mut self, pinned: bool) -> Self {
158        self.pinned = pinned;
159        self
160    }
161
162    pub fn id(&self) -> &str {
163        &self.id
164    }
165
166    pub fn label(&self) -> &str {
167        &self.label
168    }
169
170    pub fn icon(&self) -> &Source {
171        &self.icon
172    }
173
174    pub fn is_pinned(&self) -> bool {
175        self.pinned
176    }
177}
178
179/// What [`ListItem::show`] returns.
180#[derive(Debug)]
181pub struct ItemResponse {
182    /// The row: clicked, double clicked, right clicked, hovered. A click
183    /// on the arrow clicks the row too: look at `toggled` first.
184    pub response: Response,
185    /// The arrow was clicked (or Right, Left, or a screen reader's expand
186    /// or collapse asked for it): the application opens or closes it.
187    pub toggled: bool,
188    /// The action clicked this pass (its id).
189    pub action: Option<String>,
190    /// The drag handle, with [`ListItem::drag_handle`]: drag from it
191    /// (`Response::drag_started`, `dnd_set_drag_payload`).
192    pub handle: Option<Response>,
193}
194
195impl ItemResponse {
196    /// The action clicked this pass.
197    pub fn action(&self) -> Option<&str> {
198        self.action.as_deref()
199    }
200}
201
202/// A dense row: see the [module](self).
203#[derive(Clone, Debug)]
204#[must_use]
205pub struct ListItem {
206    label: String,
207    icon: Option<Source>,
208    trailing: Option<String>,
209    depth: usize,
210    guides: bool,
211    disclosure: Disclosure,
212    handle: bool,
213    selected: bool,
214    active: bool,
215    disabled: bool,
216    actions: Vec<ItemAction>,
217    reveal: Reveal,
218    height: Option<f32>,
219    id_salt: Option<IdSalt>,
220    role: Role,
221}
222
223impl ListItem {
224    /// A row showing `label` (also its accessible name).
225    pub fn new(label: impl Into<String>) -> Self {
226        Self {
227            label: label.into(),
228            icon: None,
229            trailing: None,
230            depth: 0,
231            guides: false,
232            disclosure: Disclosure::None,
233            handle: false,
234            selected: false,
235            active: false,
236            disabled: false,
237            actions: Vec::new(),
238            reveal: Reveal::Hover,
239            height: None,
240            id_salt: None,
241            role: Role::ListItem,
242        }
243    }
244
245    /// An icon before the label, in the row's text colour at the inline
246    /// icon size.
247    pub fn icon(mut self, icon: impl Into<Source>) -> Self {
248        self.icon = Some(icon.into());
249        self
250    }
251
252    /// Weak text at the right end, before the actions (a count, a type).
253    pub fn trailing(mut self, text: impl Into<String>) -> Self {
254        self.trailing = Some(text.into());
255        self
256    }
257
258    /// Its nesting level: one indent (`ui.spacing().indent`) per level.
259    pub fn depth(mut self, depth: usize) -> Self {
260        self.depth = depth;
261        self
262    }
263
264    /// Draws a guide down the row for each of its levels (`list-guide`).
265    pub fn guides(mut self, on: bool) -> Self {
266        self.guides = on;
267        self
268    }
269
270    /// Its arrow column ([`Disclosure`]).
271    pub fn disclosure(mut self, disclosure: Disclosure) -> Self {
272        self.disclosure = disclosure;
273        self
274    }
275
276    /// A collapsing row, open or closed: a click on its arrow, Right or
277    /// Left say [`ItemResponse::toggled`].
278    pub fn collapsing(self, open: bool) -> Self {
279        self.disclosure(Disclosure::branch(open))
280    }
281
282    /// A drag handle at its left end, shown with its actions
283    /// ([`ItemResponse::handle`]).
284    pub fn drag_handle(mut self, on: bool) -> Self {
285        self.handle = on;
286        self
287    }
288
289    pub fn selected(mut self, selected: bool) -> Self {
290        self.selected = selected;
291        self
292    }
293
294    /// Drawn pressed (`active`) though the pointer is not on it: a row
295    /// being dragged, the target of what happens elsewhere.
296    pub fn active(mut self, active: bool) -> Self {
297        self.active = active;
298        self
299    }
300
301    /// Greyed and not interactive.
302    pub fn disabled(mut self, disabled: bool) -> Self {
303        self.disabled = disabled;
304        self
305    }
306
307    /// An action button at the right end (added right to left: the first
308    /// is outermost).
309    pub fn action(mut self, action: ItemAction) -> Self {
310        self.actions.push(action);
311        self
312    }
313
314    /// Several actions ([`ListItem::action`]).
315    pub fn actions(mut self, actions: impl IntoIterator<Item = ItemAction>) -> Self {
316        self.actions.extend(actions);
317        self
318    }
319
320    /// When the actions show (default: [`Reveal::Hover`]).
321    pub fn reveal(mut self, reveal: Reveal) -> Self {
322        self.reveal = reveal;
323        self
324    }
325
326    /// Its height (default: [`row_height`]).
327    pub fn height(mut self, height: f32) -> Self {
328        self.height = Some(height);
329        self
330    }
331
332    /// Its id, stable when rows come and go (default: the next id of the
333    /// `Ui`).
334    pub fn id_salt(mut self, salt: impl AsIdSalt) -> Self {
335        self.id_salt = Some(IdSalt::new(salt));
336        self
337    }
338
339    /// Its accessible role (default: `ListItem`; `TreeItem` in a tree).
340    pub fn role(mut self, role: Role) -> Self {
341        self.role = role;
342        self
343    }
344
345    /// Draws the row across the width available.
346    pub fn show(self, ui: &mut Ui) -> ItemResponse {
347        let h = self.height.unwrap_or_else(|| row_height(ui));
348        let (auto, rect) = ui.allocate_space(vec2(ui.available_width(), h));
349        let id = self
350            .id_salt
351            .map_or(auto, |salt| ui.scope_id().with_salt(salt));
352        let mut row = ui.new_child(UiBuilder::new().max_rect(rect).id_salt(id));
353        if self.disabled {
354            row.disable();
355        }
356        self.draw(&mut row, id, rect)
357    }
358
359    fn draw(self, ui: &mut Ui, id: Id, rect: Rect) -> ItemResponse {
360        let kit = Kit::of(ui.ctx());
361        let enabled = ui.is_enabled();
362        let sense = if enabled {
363            Sense::click()
364        } else {
365            Sense::hover()
366        };
367        // What has the focus before the row takes its place in the Tab
368        // order (which may move it on this pass).
369        let ids: Vec<Id> = (0..self.actions.len()).map(|i| action_id(id, i)).collect();
370        let before = ui.memory(|m| m.focused());
371        let action_focused = before.is_some_and(|f| ids.contains(&f));
372        let row_focused = before == Some(id);
373        let response = ui.interact(rect, id, sense);
374        let hovered = enabled && response.contains_pointer();
375        let state = State::REST
376            .with(State::SELECTED, self.selected)
377            .with(State::HOVER, hovered && !self.selected)
378            .with(State::FOCUS, egui_pop_core::focus::shows_ring(&response))
379            .with(
380                State::ACTIVE,
381                self.active || response.is_pointer_button_down_on(),
382            )
383            .with(State::DISABLED, !enabled);
384        let revealed = self.reveal == Reveal::Always
385            || hovered
386            || self.selected
387            || row_focused
388            || response.has_focus()
389            || action_focused;
390
391        // The keyboard: Right and Left open and close a collapsing row.
392        let mut toggled = false;
393        let branch = self.disclosure.is_branch();
394        if branch && response.has_focus() {
395            ui.memory_mut(|m| {
396                m.set_focus_lock_filter(
397                    id,
398                    EventFilter {
399                        horizontal_arrows: true,
400                        ..Default::default()
401                    },
402                )
403            });
404            let open = self.disclosure == Disclosure::Open;
405            let key = if open {
406                Key::ArrowLeft
407            } else {
408                Key::ArrowRight
409            };
410            toggled |= ui.input_mut(|i| i.consume_key(Modifiers::NONE, key));
411        }
412        if branch {
413            let asked = if self.disclosure == Disclosure::Open {
414                accesskit::Action::Collapse
415            } else {
416                accesskit::Action::Expand
417            };
418            toggled |= ui.input(|i| i.has_accesskit_action_request(id, asked));
419        }
420
421        let frame = Frame {
422            kit: &kit,
423            state,
424            depth: self.depth,
425            guides: self.guides,
426            disclosure: self.disclosure,
427            handle: self.handle,
428            icon: self.icon.as_ref(),
429        };
430        let placed = frame.paint(ui, rect, revealed);
431        if branch
432            && response.clicked()
433            && let (Some(toggle), Some(p)) = (placed.toggle, response.interact_pointer_pos())
434            && toggle.contains(p)
435        {
436            toggled = true;
437        }
438        if let Some(name) = self.icon.as_ref().and_then(Source::icon_name) {
439            egui_pop_core::icon::registry::record(ui.ctx(), "list-item", &self.label, name);
440        }
441
442        // The right end: actions, then the trailing text.
443        let shown: Vec<usize> = (0..self.actions.len())
444            .filter(|&i| revealed || self.actions[i].pinned)
445            .collect();
446        let rects = action_rects(ui, rect, rect.right(), shown.len());
447        let mut right = rects.last().map_or(rect.right(), |r| r.left());
448        if let Some(text) = &self.trailing {
449            right = paint_trailing(ui, &kit, state, rect, placed.left, right, text);
450        } else if rects.is_empty() {
451            right -= ui.spacing().item_spacing.x;
452        }
453        let elided = paint_label(ui, rect, placed.left, right, &self.label, placed.color);
454
455        // The row's accessible node, before its buttons'.
456        let label = self.label.clone();
457        let (selected, role) = (self.selected, self.role);
458        response.widget_info(move || WidgetInfo::selected(role, enabled, selected, &label));
459        let response = if elided {
460            full_label_tip(response, &self.label)
461        } else {
462            response
463        };
464        let open = self.disclosure == Disclosure::Open;
465        let depth = self.depth;
466        let labels: Vec<String> = self.actions.iter().map(|a| a.label.clone()).collect();
467        ui.ctx().accesskit_node_builder(id, |node| {
468            if branch {
469                node.set_expanded(open);
470                node.add_action(if open {
471                    accesskit::Action::Collapse
472                } else {
473                    accesskit::Action::Expand
474                });
475            }
476            if depth > 0 {
477                node.set_level(depth + 1);
478            }
479        });
480        custom_actions(ui, id, &labels);
481        let mut action = requested_action(ui, id)
482            .and_then(|i| self.actions.get(i))
483            .map(|a| a.id.clone());
484
485        let handle = placed.handle.map(|r| {
486            let h = ui.interact(r, id.with("handle"), Sense::DRAG);
487            pointer::drag_cursor(&h, DragKind::Move);
488            let name = tr_args(ui.ctx(), &s::ITEM_MOVE, &[("name", &self.label)]);
489            h.widget_info(move || WidgetInfo::labeled(Role::Button, enabled, &name));
490            h
491        });
492
493        for (&i, r) in shown.iter().zip(&rects) {
494            let a = &self.actions[i];
495            if action_button(ui, &kit, ids[i], *r, a, state).clicked() {
496                action = Some(a.id.clone());
497            }
498        }
499        if toggled || action.is_some() {
500            ui.ctx().request_repaint();
501        }
502        ItemResponse {
503            response,
504            toggled,
505            action,
506            handle,
507        }
508    }
509}
510
511/// The id of a row's action `i`.
512pub(crate) fn action_id(row: Id, i: usize) -> Id {
513    row.with(("item_action", i))
514}
515
516/// The start of a row, as the tree, the list and the items share it.
517pub(crate) struct Frame<'a> {
518    pub kit: &'a Kit,
519    pub state: State,
520    pub depth: usize,
521    pub guides: bool,
522    pub disclosure: Disclosure,
523    pub handle: bool,
524    pub icon: Option<&'a Source>,
525}
526
527/// Where a row's pieces went.
528pub(crate) struct Placed {
529    /// The arrow's column.
530    pub toggle: Option<Rect>,
531    /// The drag handle's column.
532    pub handle: Option<Rect>,
533    /// Where the label starts.
534    pub left: f32,
535    /// The row's text colour.
536    pub color: Color32,
537}
538
539impl Frame<'_> {
540    /// Paints the box (`list-item`), the guides, the handle (when
541    /// `revealed`), the arrow and the icon, left to right.
542    pub fn paint(&self, ui: &Ui, rect: Rect, revealed: bool) -> Placed {
543        let cx = KitCx {
544            painter: ui.painter(),
545            ppp: ui.ctx().pixels_per_point(),
546        };
547        let item = &self.kit.list_item;
548        item.paint(
549            &cx,
550            &Part {
551                rect,
552                room: rect,
553                state: self.state,
554                label: None,
555            },
556        );
557        let color = item.style(self.state).text;
558        let indent = ui.spacing().indent;
559        let mut x = rect.left();
560        let handle = self.handle.then(|| {
561            let r = Rect::from_min_size(pos2(x, rect.top()), vec2(indent, rect.height()));
562            x += indent;
563            r
564        });
565        if let Some(r) = handle
566            && revealed
567        {
568            let side = Size::Inline.points(&Tokens::of(ui.ctx()));
569            let muted = item.style_toned(Tone::Muted, self.state).text;
570            Icon::Grip.paint(
571                ui.painter(),
572                Rect::from_center_size(r.center(), vec2(side, side)),
573                muted,
574            );
575        }
576        if self.guides {
577            for level in 0..self.depth {
578                let gx = x + level as f32 * indent + indent / 2.0;
579                let at = Rect::from_min_max(pos2(gx, rect.top()), pos2(gx, rect.bottom()));
580                self.kit.list_guide.paint(
581                    &cx,
582                    &Part {
583                        rect: at,
584                        room: at,
585                        state: State::REST,
586                        label: None,
587                    },
588                );
589            }
590        }
591        x += self.depth as f32 * indent;
592        let toggle = self
593            .disclosure
594            .has_column()
595            .then(|| Rect::from_min_size(pos2(x, rect.top()), vec2(indent, rect.height())));
596        let mut left = match toggle {
597            Some(t) => {
598                if self.disclosure.is_branch() {
599                    let glyph = if self.disclosure == Disclosure::Open {
600                        Glyph::DisclosureOpen
601                    } else {
602                        Glyph::DisclosureClosed
603                    };
604                    self.kit.glyph(glyph).paint(ui.painter(), t, color);
605                }
606                t.right()
607            }
608            None => x + ui.spacing().item_spacing.x,
609        };
610        if let Some(source) = self.icon {
611            let side = Size::Inline.points(&Tokens::of(ui.ctx()));
612            let at =
613                Rect::from_center_size(pos2(left + side / 2.0, rect.center().y), vec2(side, side));
614            source.paint(ui, at, color);
615            left += side + ui.spacing().icon_spacing;
616        }
617        Placed {
618            toggle,
619            handle,
620            left,
621            color,
622        }
623    }
624}
625
626/// The side of a row's action button.
627fn action_side(ui: &Ui, rect: Rect) -> f32 {
628    let t = Tokens::of(ui.ctx());
629    (t.size.icon_inline + 2.0 * t.space.xs).min(rect.height())
630}
631
632/// The squares of `n` action buttons, right to left from `right`.
633pub(crate) fn action_rects(ui: &Ui, rect: Rect, right: f32, n: usize) -> Vec<Rect> {
634    let side = action_side(ui, rect);
635    (0..n)
636        .map(|k| {
637            Rect::from_center_size(
638                pos2(right - side * (k as f32 + 0.5), rect.center().y),
639                vec2(side, side),
640            )
641        })
642        .collect()
643}
644
645/// An action button: `icon-button`'s box, the icon in the row's muted
646/// text until hovered or focused.
647pub(crate) fn action_button(
648    ui: &Ui,
649    kit: &Kit,
650    id: Id,
651    rect: Rect,
652    action: &ItemAction,
653    row: State,
654) -> Response {
655    let r = ui.interact(rect, id, Sense::click());
656    let state = State::from_response(&r);
657    let cx = KitCx {
658        painter: ui.painter(),
659        ppp: ui.ctx().pixels_per_point(),
660    };
661    let button = &kit.icon_button;
662    button.paint(
663        &cx,
664        &Part {
665            rect,
666            room: rect,
667            state,
668            label: None,
669        },
670    );
671    let lit = state.contains(State::HOVER) || state.contains(State::FOCUS);
672    let color = if lit {
673        button.style(state).text
674    } else {
675        kit.list_item.style_toned(Tone::Muted, row).text
676    };
677    let side = Size::Inline
678        .points(&Tokens::of(ui.ctx()))
679        .min(rect.height());
680    action.icon.paint(
681        ui,
682        Rect::from_center_size(rect.center(), vec2(side, side)),
683        color,
684    );
685    let label = action.label.clone();
686    let enabled = ui.is_enabled();
687    r.widget_info(move || WidgetInfo::labeled(Role::Button, enabled, &label));
688    r.on_hover_text(&action.label)
689}
690
691/// Paints a row's trailing text right-aligned before `right`; returns
692/// where the label must stop.
693pub(crate) fn paint_trailing(
694    ui: &Ui,
695    kit: &Kit,
696    state: State,
697    rect: Rect,
698    left: f32,
699    right: f32,
700    text: &str,
701) -> f32 {
702    let pad = ui.spacing().item_spacing.x;
703    let color = kit.list_item.style_toned(Tone::Muted, state).text;
704    let galley = ui.painter().layout_no_wrap(
705        text.to_string(),
706        FontSelection::Style(TextStyle::Body).resolve(ui.style()),
707        color,
708    );
709    let end = right - pad;
710    let start = (end - galley.size().x).max(left);
711    let clip = Rect::from_min_max(pos2(start, rect.top()), pos2(end, rect.bottom()));
712    ui.painter()
713        .with_clip_rect(clip.intersect(ui.clip_rect()))
714        .galley(
715            pos2(start, rect.center().y - galley.size().y / 2.0),
716            galley,
717            color,
718        );
719    start - pad
720}
721
722/// Paints a row's label from `left` on one line, elided with "…" when it
723/// does not fit before `right`; returns whether it was elided (the row
724/// then shows the full label on hover, [`full_label_tip`]).
725pub(crate) fn paint_label(
726    ui: &Ui,
727    rect: Rect,
728    left: f32,
729    right: f32,
730    text: &str,
731    color: Color32,
732) -> bool {
733    let job = LayoutJob::simple(
734        text.to_owned(),
735        TextStyle::Body.resolve(ui.style()),
736        color,
737        f32::INFINITY,
738    );
739    paint_label_job(ui, rect, left, right, job, color)
740}
741
742/// [`paint_label`] for a label already laid out in sections (a filter's
743/// matches, highlighted).
744pub(crate) fn paint_label_job(
745    ui: &Ui,
746    rect: Rect,
747    left: f32,
748    right: f32,
749    mut job: LayoutJob,
750    color: Color32,
751) -> bool {
752    let width = (right - left).max(0.0);
753    job.wrap = TextWrapping::truncate_at_width(width);
754    let galley = ui.painter().layout_job(job);
755    let elided = galley.elided;
756    let clip = Rect::from_min_max(pos2(left, rect.top()), pos2(right.max(left), rect.bottom()));
757    ui.painter()
758        .with_clip_rect(clip.intersect(ui.clip_rect()))
759        .galley(
760            pos2(left, rect.center().y - galley.size().y / 2.0),
761            galley,
762            color,
763        );
764    elided
765}
766
767/// Shows a row's full label as its tooltip, for a label drawn elided. The
768/// row's accessible node is left as it is (its name is already the full
769/// label; egui's `on_hover_text` would add it again as a description).
770pub(crate) fn full_label_tip(response: Response, label: &str) -> Response {
771    let label = label.to_owned();
772    let tip = move |ui: &mut Ui| {
773        ui.set_max_width(ui.spacing().tooltip_width);
774        ui.add(egui::Label::new(label));
775    };
776    if response.enabled() {
777        response.on_hover_ui(tip)
778    } else {
779        response.on_disabled_hover_ui(tip)
780    }
781}
782
783/// Where a list's default row drawing leaves "its label was elided" for
784/// the list (keyed by the row's `Ui`).
785const ELIDED: &str = "egui_pop_row_label_elided";
786
787/// Draws a row's label in `ui`'s whole rect (a list's default row), elided
788/// as [`paint_label`] does; the list reads [`take_elided`] afterwards.
789pub(crate) fn row_label(ui: &Ui, text: &str, color: Color32) {
790    let rect = ui.max_rect();
791    if paint_label(ui, rect, rect.left(), rect.right(), text, color) {
792        ui.data_mut(|d| d.insert_temp(ui.scope_id().with(ELIDED), true));
793    }
794}
795
796/// Whether [`row_label`] elided the label it drew in `ui` (and forgets
797/// it).
798pub(crate) fn take_elided(ui: &Ui) -> bool {
799    ui.data_mut(|d| d.remove_temp::<bool>(ui.scope_id().with(ELIDED)))
800        .unwrap_or(false)
801}
802
803/// Lists a row's actions on its accessible node, as custom actions
804/// numbered in order.
805pub(crate) fn custom_actions(ui: &Ui, row: Id, labels: &[String]) {
806    if labels.is_empty() {
807        return;
808    }
809    ui.ctx().accesskit_node_builder(row, |node| {
810        for (i, label) in labels.iter().enumerate() {
811            node.push_custom_action(accesskit::CustomAction {
812                id: i as i32,
813                description: label.clone(),
814            });
815        }
816    });
817}
818
819/// The custom action a screen reader asked of a row this pass.
820pub(crate) fn requested_action(ui: &Ui, row: Id) -> Option<usize> {
821    ui.input(|i| {
822        i.accesskit_action_requests(row, accesskit::Action::CustomAction)
823            .find_map(|r| match r.data {
824                Some(accesskit::ActionData::CustomAction(n)) => usize::try_from(n).ok(),
825                _ => None,
826            })
827    })
828}