Skip to main content

egui_pop_views/
list.rs

1//! A list of rows the application draws, virtualised.
2//!
3//! <div class="warning">Experimental: may change in any release
4//! (docs/stability.md).</div>
5//!
6//! The application gives the rows ([`ListRows`]): how many, each one's
7//! key (the selection is kept by key, so it survives the rows being
8//! sorted, filtered or changed) and label (its accessible name and what
9//! type-ahead searches), and draws each row in view. The list does the
10//! selection (single or multiple, Ctrl, Shift), the keyboard (arrows,
11//! Page Up/Down, Home/End, Space, Ctrl+A, type-ahead) and scrolling;
12//! a selection runs the `list.select` step. Enter or a double click on
13//! a row activates it ([`Signal::Activate`]); built with
14//! [`ListView::drag_out`], a drag from a row carries rows out
15//! ([`Signal::DragOut`]).
16//!
17//! ```
18//! use egui_pop_views::list::{ListRows, ListState, ListView};
19//! use egui_pop_views::Mode;
20//!
21//! struct Recent(Vec<(u64, String)>);
22//!
23//! impl ListRows<u64> for Recent {
24//!     fn len(&self) -> usize { self.0.len() }
25//!     fn key(&self, row: usize) -> u64 { self.0[row].0 }
26//!     fn label(&self, row: usize) -> String { self.0[row].1.clone() }
27//! }
28//!
29//! fn ui(ui: &mut egui::Ui, state: &mut ListState<u64>, rows: &mut Recent) {
30//!     let out = ListView::new("recent").mode(Mode::Multiple).show(ui, state, rows);
31//!     let _ = out.signals;
32//! }
33//! ```
34
35use std::collections::HashSet;
36
37use crate::app_link::AppHandle;
38use crate::shared::SelectionService;
39use egui::{Id, Response, Role, Ui, UiBuilder, WidgetInfo};
40use egui_pop_core::icon::Source;
41use egui_pop_core::strings::tr;
42use egui_pop_model::ids::StepId;
43use egui_pop_model::selection::SelectionItem;
44
45use crate::item::{self, Disclosure};
46use crate::nav::{self, TypeAhead};
47use crate::rows::{self, Scroll};
48use crate::select::{self, Key, Mode, Proposal, Selection};
49use crate::shared;
50use crate::steps::LIST_SELECT;
51use crate::strings as s;
52
53/// The rows a list shows; the application owns them.
54pub trait ListRows<K: Key> {
55    fn len(&self) -> usize;
56
57    fn is_empty(&self) -> bool {
58        self.len() == 0
59    }
60
61    /// Row `row`'s key.
62    fn key(&self, row: usize) -> K;
63
64    /// Row `row`'s accessible name, searched by type-ahead.
65    fn label(&self, row: usize) -> String;
66
67    /// Row `row`'s item in the application-wide selection
68    /// ([`ListView::shared`]): by default its key's
69    /// ([`SelectionItem::from_key`]). Give the id other widgets showing
70    /// the same thing use.
71    fn item(&self, row: usize) -> SelectionItem {
72        SelectionItem::from_key(&self.key(row))
73    }
74
75    /// Row `row`'s icon, drawn before what [`ListRows::ui`] draws, in
76    /// the row's text colour (default: none).
77    fn icon(&self, row: usize) -> Option<Source> {
78        let _ = row;
79        None
80    }
81
82    /// Row `row`'s weak text on its right (a count, a type; default:
83    /// none), in the row's muted tone; what [`ListRows::ui`] draws stops
84    /// before it.
85    fn trailing(&self, row: usize) -> Option<String> {
86        let _ = row;
87        None
88    }
89
90    /// Draws row `row` (its background is drawn, with its icon and its
91    /// trailing text, [a list item](crate::item)'s; the row is named by
92    /// its label). By default, its label on one line, elided with "…"
93    /// when it does not fit, the row then showing the full label on hover.
94    fn ui(&mut self, ui: &mut Ui, row: usize, selected: bool) {
95        let _ = selected;
96        let color = ui
97            .visuals()
98            .override_text_color
99            .unwrap_or_else(|| ui.visuals().text_color());
100        item::row_label(ui, &self.label(row), color);
101    }
102}
103
104/// A list's state between passes.
105#[derive(Debug)]
106pub struct ListState<K: Key> {
107    selection: Selection<K>,
108    scroll: Scroll,
109    type_ahead: TypeAhead,
110    len: Option<usize>,
111    /// The shared selection's revision and the row count last followed.
112    seen: Option<(u64, u64)>,
113    /// How many rows a drag out carries, while it lasts.
114    carry: Option<usize>,
115}
116
117impl<K: Key> Default for ListState<K> {
118    fn default() -> Self {
119        Self {
120            selection: Selection::default(),
121            scroll: Scroll::default(),
122            type_ahead: TypeAhead::default(),
123            len: None,
124            seen: None,
125            carry: None,
126        }
127    }
128}
129
130impl<K: Key> ListState<K> {
131    pub fn new() -> Self {
132        Self::default()
133    }
134
135    pub fn selection(&self) -> &Selection<K> {
136        &self.selection
137    }
138
139    /// Sets the selection without running a step.
140    pub fn set_selection(&mut self, keys: impl IntoIterator<Item = K>, cursor: Option<K>) {
141        self.selection.set(keys, cursor);
142    }
143
144    /// Brings a row into view at the next pass.
145    pub fn reveal(&mut self, row: usize) {
146        self.scroll.reveal = Some(row);
147    }
148}
149
150/// What happened in a list (or a table) this pass.
151#[derive(Clone, Debug, PartialEq)]
152#[non_exhaustive]
153pub enum Signal<K> {
154    Select {
155        keys: Vec<K>,
156        cursor: Option<K>,
157    },
158    /// A row opened: Enter on the cursor's row, or a double click.
159    Activate {
160        key: K,
161    },
162    /// A drag started on a row of a view built with `drag_out`
163    /// ([`ListView::drag_out`], `DataTable::drag_out`): these rows go,
164    /// the selection when the row is in it, else that row alone (the
165    /// selection is left as it is). The application sets its drag
166    /// payload (`egui::DragAndDrop::set_payload`).
167    DragOut {
168        keys: Vec<K>,
169    },
170    /// A step was vetoed.
171    Vetoed {
172        step: StepId,
173        reason: String,
174    },
175}
176
177/// What [`ListView::show`] returns.
178#[derive(Debug)]
179pub struct ListOutput<K> {
180    /// The list as one focusable widget.
181    pub response: Response,
182    pub signals: Vec<Signal<K>>,
183}
184
185/// The list widget.
186///
187/// Need (data): a long list, virtualised.
188#[derive(Debug)]
189pub struct ListView<'a> {
190    id: String,
191    label: Option<String>,
192    mode: Mode,
193    app: Option<&'a AppHandle>,
194    height: Option<f32>,
195    row_height: Option<f32>,
196    shared: Option<&'a SelectionService>,
197    drag_out: bool,
198}
199
200impl<'a> ListView<'a> {
201    /// A list named `id` in steps and signals.
202    pub fn new(id: impl Into<String>) -> Self {
203        Self {
204            id: id.into(),
205            label: None,
206            mode: Mode::Single,
207            app: None,
208            height: None,
209            row_height: None,
210            shared: None,
211            drag_out: false,
212        }
213    }
214
215    /// A drag that starts on a row carries rows out (off by default):
216    /// the list signals [`Signal::DragOut`] as it starts, for the
217    /// application to set its payload (`egui::DragAndDrop::set_payload`)
218    /// and its drop targets to take it; while it lasts the cursor shows a
219    /// carry and the pointer how many rows go.
220    pub fn drag_out(mut self, on: bool) -> Self {
221        self.drag_out = on;
222        self
223    }
224
225    /// Its accessible name.
226    pub fn label(mut self, label: impl Into<String>) -> Self {
227        self.label = Some(label.into());
228        self
229    }
230
231    pub fn mode(mut self, mode: Mode) -> Self {
232        self.mode = mode;
233        self
234    }
235
236    /// Runs its moments as steps of this application.
237    #[cfg(feature = "api")]
238    pub fn app(mut self, app: &'a AppHandle) -> Self {
239        self.app = Some(app);
240        self
241    }
242
243    /// Its height (default: what is available).
244    pub fn height(mut self, height: f32) -> Self {
245        self.height = Some(height);
246        self
247    }
248
249    /// Each row's height (default: the theme's interactive height).
250    pub fn row_height(mut self, height: f32) -> Self {
251        self.row_height = Some(height);
252        self
253    }
254
255    /// Binds the list to the application-wide selection
256    /// (`egui_pop_api::selection`, the service under `SELECTION`): its
257    /// rows ([`ListRows::item`]) show selected and hovered when they are
258    /// so anywhere, and what it selects (still through `list.select`)
259    /// goes there: a plain click or move replaces the whole selection,
260    /// Ctrl changes only the list's items. The list is then in the
261    /// selection's focus surface, where Alt+Left and Alt+Right walk its
262    /// history.
263    #[cfg(feature = "api")]
264    pub fn shared(mut self, selection: &'a SelectionService) -> Self {
265        self.shared = Some(selection);
266        self
267    }
268
269    pub fn show<K: Key>(
270        self,
271        ui: &mut Ui,
272        state: &mut ListState<K>,
273        rows: &mut dyn ListRows<K>,
274    ) -> ListOutput<K> {
275        shared::surface(ui, self.shared.is_some(), |ui| self.draw(ui, state, rows))
276    }
277
278    fn draw<K: Key>(
279        self,
280        ui: &mut Ui,
281        state: &mut ListState<K>,
282        rows: &mut dyn ListRows<K>,
283    ) -> ListOutput<K> {
284        let id = Id::unique(("egui_pop_views::list", &self.id));
285        let len = rows.len();
286        retain(&mut state.selection, &mut state.len, len, &|i| rows.key(i));
287        if let Some(service) = self.shared {
288            shared::follow(
289                service,
290                &mut state.selection,
291                &mut state.seen,
292                len as u64,
293                (0..len).map(|i| (rows.key(i), rows.item(i))),
294            );
295        }
296        let row_h = self.row_height.unwrap_or_else(|| rows::height(ui));
297        egui_pop_core::focus::reads_keys(ui.ctx(), id, &nav::READS);
298        let focused = ui.memory(|m| m.has_focus(id));
299        let mut proposals = Vec::new();
300        let mut late = Vec::new();
301        if focused {
302            let (p, reveal, activate) = nav::flat(
303                ui,
304                &state.selection,
305                self.mode,
306                len,
307                &|i| rows.key(i),
308                &|i| rows.label(i),
309                rows::page(&state.scroll, row_h),
310                &mut state.type_ahead,
311            );
312            proposals = p;
313            if reveal.is_some() {
314                state.scroll.reveal = reveal;
315            }
316            late.extend(activate.map(|key| Signal::Activate { key }));
317        }
318        let label = self.label.clone().unwrap_or_else(|| tr(ui.ctx(), &s::LIST));
319        let selection = &state.selection;
320        let mode = self.mode;
321        let mut take_focus = false;
322        let shared = self.shared;
323        let mut hovering: Option<SelectionItem> = None;
324        let drag_out = self.drag_out;
325        let mut carry = state.carry.take();
326        let mut cursor_row = None;
327        let (_, response, _) = rows::show(
328            ui,
329            id,
330            &label,
331            Role::ListBox,
332            &mut state.scroll,
333            len,
334            row_h,
335            self.height,
336            |ui, visible| {
337                for i in visible.range.clone() {
338                    let rect = (visible.rect_of)(i);
339                    let key = rows.key(i);
340                    let r = ui.interact(rect, id.with(("row", &key)), rows::ROW_SENSE);
341                    let selected = selection.contains(&key);
342                    let cursor = focused && selection.cursor() == Some(&key);
343                    if cursor {
344                        cursor_row = Some(r.id);
345                    }
346                    // Hovered here, or the same item hovered elsewhere.
347                    let mut hovered = r.hovered();
348                    if let Some(service) = shared {
349                        let item = rows.item(i);
350                        if hovered {
351                            hovering = Some(item);
352                        } else {
353                            hovered = service.is_hovered(&item);
354                        }
355                    }
356                    let state = rows::state(
357                        selected,
358                        hovered,
359                        cursor && egui_pop_core::focus::ring_shown(ui.ctx()),
360                    );
361                    let icon = rows.icon(i);
362                    let placed = item::Frame {
363                        kit: visible.kit,
364                        state,
365                        depth: 0,
366                        guides: false,
367                        disclosure: Disclosure::None,
368                        handle: false,
369                        icon: icon.as_ref(),
370                    }
371                    .paint(ui, rect, false);
372                    let right = match rows.trailing(i) {
373                        Some(text) => item::paint_trailing(
374                            ui,
375                            visible.kit,
376                            state,
377                            rect,
378                            placed.left,
379                            rect.right(),
380                            &text,
381                        ),
382                        None => rect.right() - ui.spacing().item_spacing.x,
383                    };
384                    let mut child = ui.new_child(
385                        UiBuilder::new()
386                            .max_rect(egui::Rect::from_min_max(
387                                egui::pos2(placed.left, rect.top()),
388                                egui::pos2(right.max(placed.left), rect.bottom()),
389                            ))
390                            .layout(egui::Layout::left_to_right(egui::Align::Center)),
391                    );
392                    if selected {
393                        child.visuals_mut().override_text_color = Some(placed.color);
394                    }
395                    rows.ui(&mut child, i, selected);
396                    let name = rows.label(i);
397                    let full = item::take_elided(&child).then(|| name.clone());
398                    r.widget_info(move || {
399                        WidgetInfo::selected(Role::Button, true, selected, &name)
400                    });
401                    let r = match full {
402                        Some(label) => item::full_label_tip(r, &label),
403                        None => r,
404                    };
405                    if r.double_clicked() {
406                        late.push(Signal::Activate { key: key.clone() });
407                    } else if r.clicked() {
408                        take_focus = true;
409                        let mods = ui.input(|i| i.modifiers);
410                        proposals.push(selection.click(mode, len, &|i| rows.key(i), i, mods));
411                    }
412                    if drag_out && r.drag_started() {
413                        let keys = rows::carried(selection, key);
414                        carry = Some(keys.len());
415                        late.push(Signal::DragOut { keys });
416                    }
417                }
418            },
419        );
420        rows::active_row(ui, response.id, cursor_row);
421        rows::carry(ui, &mut carry);
422        state.carry = carry;
423        if take_focus {
424            response.request_focus();
425        }
426        if let Some(service) = shared {
427            service.hover(&self.id, hovering.as_ref());
428        }
429        let before = state.selection.keys().to_vec();
430        let mut signals = run(
431            self.app,
432            &LIST_SELECT,
433            "list",
434            &self.id,
435            &mut state.selection,
436            proposals,
437        );
438        if let Some(service) = shared
439            && let Some(Signal::Select { keys, .. }) = signals
440                .iter()
441                .rev()
442                .find(|s| matches!(s, Signal::Select { .. }))
443        {
444            let items: std::collections::HashMap<K, SelectionItem> =
445                (0..len).map(|i| (rows.key(i), rows.item(i))).collect();
446            let item_of = |k: &K| {
447                items
448                    .get(k)
449                    .cloned()
450                    .unwrap_or_else(|| SelectionItem::from_key(k))
451            };
452            let keep_others = ui.input(|i| i.modifiers.command);
453            shared::write(service, &self.id, &before, keys, keep_others, &item_of);
454            state.seen = Some((service.revision(), len as u64));
455        }
456        signals.extend(late);
457        if !signals.is_empty() {
458            ui.ctx().request_repaint();
459        }
460        ListOutput { response, signals }
461    }
462}
463
464/// Drops the selected keys no longer among the rows, when their count
465/// changed.
466pub(crate) fn retain<K: Key>(
467    selection: &mut Selection<K>,
468    last: &mut Option<usize>,
469    len: usize,
470    key_at: &dyn Fn(usize) -> K,
471) {
472    if *last == Some(len) {
473        return;
474    }
475    *last = Some(len);
476    if selection.is_empty() && selection.cursor().is_none() {
477        return;
478    }
479    let keys: HashSet<K> = (0..len).map(key_at).collect();
480    selection.retain(|k| keys.contains(k));
481}
482
483/// Runs the selection steps of a flat view; returns its signals.
484pub(crate) fn run<K: Key>(
485    app: Option<&AppHandle>,
486    step: &StepId,
487    field: &str,
488    view: &str,
489    selection: &mut Selection<K>,
490    proposals: Vec<Proposal<K>>,
491) -> Vec<Signal<K>> {
492    let mut out = Vec::new();
493    for p in proposals {
494        if p.keys == selection.keys() && p.cursor.as_ref() == selection.cursor() {
495            continue;
496        }
497        out.push(match select::run(app, step, field, view, selection, p) {
498            Ok(done) => Signal::Select {
499                keys: done.keys,
500                cursor: done.cursor,
501            },
502            Err(reason) => Signal::Vetoed {
503                step: step.clone(),
504                reason,
505            },
506        });
507    }
508    out
509}