Files
gridcraft/crates/ui-egui/src/grid/editor.rs
T
f9af787c7b Dropdown filter (#2119)
* Searchable validation dropdown lists

* double dropdown bug solved

* performance improvements for dropdown list filtering

* docstrings and documentation added

* precisions regarding accented characters for dropdown list search

* Latin extended characters added to accent list in dropdown list search

* formula bar check button handled as enter for highlighted entry

* capping list at 10,000 entries

* Bound the searched validation list's source work

A searched list (data.validationList, and the edit that typing into a list
cell opens) read its whole source first: a whole-column list evaluated every
cell into an array and folded each entry, so a search with few or no matches
could still stall the UI. The search now reads at most LIST_SOURCE_BUDGET
(200,000) cells of the source: a range is walked cell by cell instead of
evaluated, a computed source gets the budget as its formula work, and
`truncated` reports when the source was cut short. The popup says when
entries aren't shown. The validation membership check still reads the
whole list.

* Bound the dropdown arrow's validation list

The full list that the dropdown arrow or Alt+Down opens called list_items
every frame while it was open and drew a button for every entry, so a list
over a huge column reread its source and laid out all of it on each repaint.
It now reads the list once with list_search_source (within
LIST_SOURCE_BUDGET), keeps it while the popup stays open on the same cell of
the same workbook version, and draws only the rows in view, saying when
entries aren't shown. Rows are measured at their real button height, so the
popup shows the eight rows it was meant to (it showed six).

* Dropdown list fixes

1. Row height: the search popup now measures its rows at the real button height, through a helper shared with the arrow picker. It shows eight rows, the highlight stays in view and the end of a long list is reachable.
2. Duplicate call: the second e.update_list() in control.rs is gone.
3. Stale cache: list_picker_items is cleared wherever list_picker is cleared for an edit (start_edit and the editor branch of list_picker).
4. Translation: "More entries not shown" is one constant and goes through lang.tr(...) in both popups. I did not add catalog entries, so it still shows in English in every language until translations are written.
5. Flip above: the search popup opens above the cell when it would run past the bottom of the window, using the same rule as the arrow picker.
6. Width: the popup width is measured once per search and cached in ListSearch::text_width; update_list resets it.

* Validation lists: fixed-height rows, translated cut-short note

The rows of both validation list popups are drawn in slots of exactly the
height the popup scrolls by. A button sizes itself to its laid-out text,
which can be a pixel taller than the font's nominal line height, so the
last visible row ran under the "More entries not shown" note with the
pinned test fonts (the CI gate failure).

The note is translated in all 18 interface catalogs, with a test that no
catalog falls back to English.

The validation-list UI tests move into the shared integration binary and
use the pinned font harness, so they no longer depend on host fonts.

* Validation list note: use each catalog's word for list items

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-authored-by: skylartaylor <skylartaylor@users.noreply.github.com>
2026-11-23 17:32:01 -06:00

302 lines
17 KiB
Rust

use super::cell_paint::ink_on;
use super::geo::Geo;
use super::{
Align2, Arc, CellRef, Color32, FontId, PatternType, Rect, Sheet, SheetApp, Stroke, StrokeKind, Tokens, Workbook, json, pos2, theme, vec2,
};
/// Room the in-cell editor keeps right of its text. It is sized from the text of the last frame, so
/// the next typed character must still fit: a fixed 14 px was less than one glyph at high zoom,
/// and the field scrolled and snapped back on every key (#2336). `size` is the font size in px.
pub(super) fn editor_slack(size: f32) -> f32 {
14.0 + size
}
/// Width of the one-line in-cell editor. While the text fits the cell (with the usual 14 px margin) the
/// editor is exactly the cell wide, as in Excel; once it overflows, the extra `editor_slack` applies.
pub(super) fn editor_width(text_w: f32, cell_w: f32, size: f32) -> f32 {
if text_w + 14.0 <= cell_w { cell_w } else { text_w + editor_slack(size) }
}
/// Draws the in-cell editor, growing and wrapping with its text, mirroring for right-to-left sheets, choosing contrasting caret ink and clipping cells hidden under frozen panes.
pub(super) fn in_cell_editor(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, sh: &Sheet, wb: &Workbook) {
let Some(ed) = app.editor.as_ref() else { return };
if app.view_key() != Some((ed.doc, ed.sheet)) {
return;
}
let cell = ed.cell;
let rect = match sh.merge_at(cell) {
Some(m) => geo.range_rect(sh, m),
None => geo.cell_rect(sh, cell),
};
let st = wb.styles.get(sh.style_id(cell)).clone();
let size = st.font.size * 96.0 / 72.0 * geo.z;
let font = FontId::new(size, theme::cell_family(&st.font.name, st.font.bold, st.font.italic));
let lines = ed.text.lines().count().max(1) as f32 + if ed.text.ends_with('\n') { 1.0 } else { 0.0 };
// Grows with the text: the in-cell editor shows every line and never scrolls (the formula bar
// is the one that stops at five lines).
let shown = lines;
// Wrap Text: the editor keeps the column's width and wraps, growing down as Excel's does.
// Otherwise it widens to the text's one-line width.
let wrap = st.align.wrap;
let (w, h) = if wrap {
// The field wraps at the width it is given (the editor's less its 2 px inset a side): its
// frame is `Frame::NONE`, so no text margin is taken off.
let wrapped = ui.painter().layout(ed.text.clone(), font.clone(), Color32::BLACK, (rect.width() - 4.0).max(1.0));
(rect.width(), (wrapped.size().y.max(size * 1.3 * shown) + 4.0).max(rect.height()))
} else {
let text_w = ui.painter().layout_no_wrap(ed.text.clone(), font.clone(), Color32::BLACK).size().x;
// Excel keeps the cell's height for one line and only grows for extra lines.
let h = if lines > 1.0 { (size * 1.3 * lines + 4.0).max(rect.height()) } else { rect.height() };
(editor_width(text_w, rect.width(), size).min(geo.cells.right() - rect.left()), h)
};
// Grows to the left on a right-to-left sheet.
let erect = geo.mirror_rect(Rect::from_min_size(rect.min, vec2(w, h)));
let fill = match st.fill.pattern {
PatternType::Solid => st.fill.fg.resolve(&wb.theme).map(theme::color32).unwrap_or(Color32::WHITE),
_ => Color32::WHITE,
};
let split = pos2(geo.cells.left() + geo.frozen_w, geo.cells.top() + geo.frozen_h);
let quadrant = Rect::from_min_max(
pos2(if cell.col >= geo.fc { split.x } else { geo.cells.left() }, if cell.row >= geo.fr { split.y } else { geo.cells.top() }),
pos2(if cell.col >= geo.fc { geo.cells.right() } else { split.x }, if cell.row >= geo.fr { geo.cells.bottom() } else { split.y }),
);
// A cell scrolled entirely under a frozen row/column keeps its edit (Escape still works),
// but neither the cell nor its helper may paint. Test the cell's own visible quadrant and
// give the shared editor an empty clip when the cell is hidden: a one-line cell editor's
// field can be larger than the cell (egui 0.37 gives text fields a minimum height), so its
// own max_rect is not a reliable "is the cell on screen" test at the frozen boundary. The
// pre-wrap cell rect must also be positive: a hidden row/column has zero height/width, but
// Wrap Text can expand the editor below/right of it, which must not paint over the next line.
let cell_visible = rect.width() > 0.0 && rect.height() > 0.0;
// `erect` and `ui.clip_rect()` are in screen coordinates; `quadrant` is logical until mirrored.
let screen_quadrant = geo.mirror_rect(quadrant);
let on_screen = cell_visible && erect.intersect(screen_quadrant).is_positive() && !geo.hidden_under_frozen(sh, cell);
let clip = if on_screen { ui.clip_rect().intersect(screen_quadrant) } else { Rect::NOTHING };
let painter = ui.painter().with_clip_rect(clip);
painter.rect_filled(erect, 0.0, fill);
painter.rect_stroke(erect.expand(1.0), 0.0, Stroke::new(2.0, Tokens::get(ui.ctx()).sel_border), StrokeKind::Middle);
let id = egui::Id::unique("gridcraft.cell_editor");
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(erect.shrink2(vec2(2.0, 1.0))));
child.set_clip_rect(clip);
// The theme's caret is meant for the UI chrome and vanishes on some fills (and, in the dark
// theme, on the white paper): pick black or white against the fill, like Excel.
child.visuals_mut().text_cursor.stroke.color = ink_on(fill);
crate::formula_bar::editor_widget(app, &mut child, id, font, wrap, erect.width() - 4.0, erect.height() - 2.0);
ui.ctx().data_mut(|d| d.insert_temp(egui::Id::unique("gridcraft.cell_editor.rect"), erect));
}
/// Test the popup itself, not whether the pointer is over any part of the app.
/// A trigger can sit outside its popup, so its opening click must be ignored.
pub(super) fn popup_dismissed(response: &egui::Response, was_open: bool) -> bool {
response.ctx.input(|i| !i.focused || i.key_pressed(egui::Key::Escape)) || (was_open && response.clicked_elsewhere())
}
/// The dropdown arrow beside a cell with an in-cell list validation.
pub fn validation_arrow(sh: &Sheet, geo: &Geo, c: CellRef) -> Option<Rect> {
let dv = sh.validations.iter().find(|d| d.ranges.iter().any(|r| r.contains(c)))?;
if dv.kind != gridcraft_engine::model::ValidationKind::List || !dv.in_cell_dropdown || geo.hidden_under_frozen(sh, c) {
return None;
}
let r = geo.cell_rect(sh, c);
let s = r.height().clamp(14.0, 22.0);
Some(Rect::from_min_size(pos2(r.right() + 1.0, r.bottom() - s), vec2(s, s)))
}
/// Rows the list-validation dropdown shows before it scrolls (Excel shows 8).
const LIST_PICKER_MAX_ROWS: usize = 8;
const LIST_PICKER_ROW_H: f32 = 18.0;
/// Popup frame around the rows: 2 px inner margin and the window stroke on each side, rounded up.
const LIST_PICKER_CHROME: f32 = 8.0;
/// Shown under a validation list that was cut short (source budget or match cap).
pub(crate) const LIST_MORE_NOTE: &str = "More entries not shown";
/// Height of one row of a validation list popup: its button's real height (text plus padding), at
/// least `LIST_PICKER_ROW_H`. `show_rows` needs the height the rows are drawn at: with a smaller
/// one the popup shows fewer rows than it scrolls by and the last entries can't be reached.
fn list_row_height(ui: &egui::Ui) -> f32 {
LIST_PICKER_ROW_H.max(ui.text_style_height(&egui::TextStyle::Button) + 2.0 * ui.spacing().button_padding.y).ceil()
}
/// Draws one row of a validation list popup in a slot exactly `row_h` tall. A button sizes itself
/// to its text, and text is laid out to the tallest face its glyphs fall back to, rounded to whole
/// pixels, so its height is not always `list_row_height`. `show_rows` places rows by `row_h`: rows
/// that advance by anything else drift out of the popup and under the note below it.
fn list_row(ui: &mut egui::Ui, width: f32, row_h: f32, button: egui::Button<'_>) -> egui::Response {
let (slot, _) = ui.allocate_exact_size(vec2(width, row_h), egui::Sense::hover());
// A child placed on the slot: whatever the button asks for, the popup advances by the slot.
let mut row = ui.new_child(egui::UiBuilder::new().max_rect(slot).layout(egui::Layout::top_down(egui::Align::Min)));
row.add(button.min_size(slot.size()))
}
/// The searched list of a list validation under the cell being typed into (from the cell or the
/// formula bar): the matches of the typed text, the highlighted one is what Enter commits.
pub(super) fn list_search(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, sh: &Sheet) {
let view = app.view_key();
let Some(ed) = app.editor.as_mut() else { return };
if view != Some((ed.doc, ed.sheet)) || !ed.list_open() || geo.hidden_under_frozen(sh, ed.cell) {
return;
}
let r = match sh.merge_at(ed.cell) {
Some(m) => geo.range_rect(sh, m),
None => geo.cell_rect(sh, ed.cell),
};
if !geo.cells.intersects(r) {
return;
}
let Some(list) = ed.list.as_mut() else { return };
// Rows are as tall as their buttons really are, so `show_rows` places them where they are
// drawn: the popup shows `ListSearch::VISIBLE` of them and the highlighted one stays in view.
let row_h = list_row_height(ui);
// Wide enough for the longest of the first matches, within reason. Measured once per search:
// `update_list` clears it when the matches change.
let longest = match list.text_width {
Some(w) => w,
None => {
let font = egui::TextStyle::Button.resolve(ui.style());
let w = list
.matches
.iter()
.take(200)
.filter_map(|&i| list.items.get(i))
.map(|t| ui.painter().layout_no_wrap(t.clone(), font.clone(), Color32::BLACK).size().x)
.fold(0.0_f32, f32::max);
list.text_width = Some(w);
w
}
};
let width = r.width().max(100.0).max((longest + 16.0).min(480.0));
// Not every entry was searched (a huge source) or shown (past the match cap).
let more = list.truncated || list.matches.len() >= gridcraft_engine::cmd::data::LIST_MATCH_CAP;
let height = row_h * list.matches.len().clamp(1, crate::editor::ListSearch::VISIBLE) as f32;
let note = if more { row_h } else { 0.0 };
// Below the cell, or above it when the rows would run past the bottom of the window (as the
// dropdown arrow's list does).
let screen = ui.ctx().content_rect();
let outer = height + note + LIST_PICKER_CHROME;
let above = r.bottom() + outer > screen.bottom() && r.top() - outer >= screen.top();
let (at, pivot) = match (above, geo.rtl) {
(false, false) => (geo.mirror_pos(r.left_bottom()), Align2::LEFT_TOP),
(false, true) => (geo.mirror_pos(r.left_bottom()), Align2::RIGHT_TOP),
(true, false) => (geo.mirror_pos(r.left_top()), Align2::LEFT_BOTTOM),
(true, true) => (geo.mirror_pos(r.left_top()), Align2::RIGHT_BOTTOM),
};
let reveal = std::mem::take(&mut list.reveal).then_some(list.top as f32 * row_h);
let lang = crate::i18n::current(ui.ctx());
let mut pick = None;
let mut top = None;
egui::Area::new(egui::Id::unique("dv_search")).fixed_pos(at).pivot(pivot).order(egui::Order::Foreground).show(ui.ctx(), |ui| {
egui::Frame::popup(ui.style()).inner_margin(2.0).show(ui, |ui| {
ui.set_min_width(width);
ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate);
ui.spacing_mut().item_spacing.y = 0.0;
let mut area = egui::ScrollArea::vertical().max_height(height).auto_shrink([false, true]);
if let Some(y) = reveal {
area = area.vertical_scroll_offset(y);
}
let out = area.show_rows(ui, row_h, list.matches.len(), |ui, rows| {
for row in rows {
let Some(text) = list.matches.get(row).and_then(|&i| list.items.get(i)) else { continue };
if list_row(ui, width, row_h, egui::Button::selectable(row == list.index, text.as_str())).clicked() {
pick = Some(row);
}
}
});
top = Some((out.state.clamped_offset().y / row_h).floor().max(0.0) as usize);
if more {
ui.add_space(2.0);
ui.weak(lang.tr(LIST_MORE_NOTE));
}
});
});
if let Some(top) = top {
list.top = top;
}
if let Some(row) = pick {
list.index = row;
ed.list_accept = true;
app.commit_edit(0, 0, false, false);
}
}
/// Popup height for `n` items: every item up to `LIST_PICKER_MAX_ROWS`, then a scrollbar.
pub(super) fn list_picker_height(n: usize, row_h: f32, gap: f32) -> f32 {
let rows = n.clamp(1, LIST_PICKER_MAX_ROWS) as f32;
rows * row_h + (rows - 1.0) * gap
}
/// Draws the validation list popup, choosing above/below and left/right placement for RTL, and applies the clicked item with `cell.set`.
pub(super) fn list_picker(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, was_open: bool) {
let Some(c) = app.grid.list_picker else { return };
// An edit shows its own searched list; two lists would stack.
if app.editor.is_some() {
app.grid.list_picker = None;
app.grid.list_picker_items = None;
return;
}
let Some(d) = app.session.active() else { return };
let wb = d.wb.clone();
let si = wb.active_sheet();
let Some(sh) = wb.sheet(si) else { return };
let Some(dv) = sh.validations.iter().find(|x| x.ranges.iter().any(|r| r.contains(c))) else {
app.grid.list_picker = None;
app.grid.list_picker_items = None;
return;
};
// Read the list once while it stays open on the same cell of the same workbook version, and
// within the search budget, so a list over a huge column can't stall every frame.
// Taken out while the popup draws (a click runs a command on `app`), put back below.
let list = match app.grid.list_picker_items.take() {
Some(l) if Arc::ptr_eq(&l.wb, &wb) && l.sheet == si && l.cell == c => l,
_ => {
let budget = gridcraft_engine::cmd::data::LIST_SOURCE_BUDGET;
let source = gridcraft_engine::cmd::data::list_search_source(&wb, si, c, dv, budget);
super::ListPickerItems { wb: wb.clone(), sheet: si, cell: c, source }
}
};
let (items, truncated) = (&list.source.items, list.source.truncated);
let r = geo.cell_rect(sh, c);
// Fit the popup to its rows (up to LIST_PICKER_MAX_ROWS); without a minimum the scroll area collapses to its 64 px default.
let gap = ui.spacing().item_spacing.y;
// A row is as tall as its button really is, so the popup shows LIST_PICKER_MAX_ROWS of them.
let row_h = list_row_height(ui);
let height = list_picker_height(items.len(), row_h, gap);
let note = if truncated { row_h + gap } else { 0.0 };
// Open below the cell, or above it when the rows would run past the bottom of the window (as Excel does).
let screen = ui.ctx().content_rect();
let (outer, top_room) = (height + note + LIST_PICKER_CHROME, r.top() - height - note - LIST_PICKER_CHROME);
let above = r.bottom() + outer > screen.bottom() && top_room >= screen.top();
let (at, pivot) = match (above, geo.rtl) {
(false, false) => (geo.mirror_pos(r.left_bottom()), Align2::LEFT_TOP),
(false, true) => (geo.mirror_pos(r.left_bottom()), Align2::RIGHT_TOP),
(true, false) => (geo.mirror_pos(r.left_top()), Align2::LEFT_BOTTOM),
(true, true) => (geo.mirror_pos(r.left_top()), Align2::RIGHT_BOTTOM),
};
let lang = crate::i18n::current(ui.ctx());
let mut close = false;
let response = egui::Area::new(egui::Id::unique("dv_list")).fixed_pos(at).pivot(pivot).order(egui::Order::Foreground).show(ui.ctx(), |ui| {
egui::Frame::popup(ui.style()).inner_margin(2.0).show(ui, |ui| {
ui.set_min_width(r.width().max(100.0));
// Only the rows in view are drawn: a long list costs what eight rows cost.
egui::ScrollArea::vertical().max_height(height).min_scrolled_height(height).show_rows(ui, row_h, items.len(), |ui, rows| {
for it in rows.filter_map(|i| items.get(i)) {
if list_row(ui, r.width().max(100.0), row_h, egui::Button::new(it.as_str()).frame_when_inactive(false)).clicked() {
app.run_or_alert("cell.set", json!({"cell": c.a1(), "input": it}));
close = true;
}
}
});
if truncated {
ui.weak(lang.tr(LIST_MORE_NOTE));
}
});
});
if close || popup_dismissed(&response.response, was_open) {
app.grid.list_picker = None;
} else {
app.grid.list_picker_items = Some(list);
}
}