Expression completion: keep longer names visible when the typed word is a unit (#3663) (#3664)

* claim: #3663

* Expression completion: keep longer names listed when the typed word is a unit (#3663)

Typing `rad` into an expression box showed nothing because `rad` is the radians unit and
a word that is itself a known token closed the popup. The popup now stays open on such a
word. A complete name (`width` with `width_extra` defined) opens it unarmed: the longer
names are listed with no row selected, Enter submits what was typed and Tab moves on; Up
or Down picks a row, after which Enter or Tab complete it as before. A unit means
something only after a number, so a unit typed anywhere else (`rad` on the way to
`radius`) is a prefix like any other: the popup is armed and Enter completes `radius`
instead of submitting one radian.

A complete token is extended only by names that start with it (`in` lists `inner`, not
`rounding`), a typed unit offers no other units (`in` does not list `inch`), and a unit
right after a number (`2 in`, the form every dialog starts its sizes in) opens no popup at
all, so nothing sits over a dialog's OK button.

Fixes #3663

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Daniel
2026-10-24 08:01:48 +00:00
committed by GitHub
parent 4dc30c092d
commit 8b65d41b31
9 changed files with 213 additions and 30 deletions
+2 -1
View File
@@ -2394,5 +2394,6 @@
"update.up_to_date": "SolidCraft is up to date.",
"update.update_now": "Update now",
"update.you_have": "You have {version}.",
"↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ choose · Enter / Tab complete · Esc dismiss"
"↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ choose · Enter / Tab complete · Esc dismiss",
"↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ choose · Enter applies what you typed · Esc dismiss"
}
+2 -1
View File
@@ -2394,5 +2394,6 @@
"update.up_to_date": "SolidCraft は最新です。",
"update.update_now": "今すぐ更新",
"update.you_have": "現在のバージョンは {version} です。",
"↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ 選択 · Enter / Tab 補完 · Esc 閉じる"
"↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ 選択 · Enter / Tab 補完 · Esc 閉じる",
"↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ 選択 · Enter 入力どおりに適用 · Esc 閉じる"
}
+2 -1
View File
@@ -2394,5 +2394,6 @@
"update.up_to_date": "SolidCraft 已是最新版本。",
"update.update_now": "立即更新",
"update.you_have": "当前版本为 {version}。",
"↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ 选择 · Enter / Tab 补全 · Esc 关闭"
"↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ 选择 · Enter / Tab 补全 · Esc 关闭",
"↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ 选择 · Enter 按原样应用 · Esc 关闭"
}
+30
View File
@@ -872,6 +872,36 @@ mod tests {
}
}
/// Typing `rad` into a new dimension's value lists `radius` although `rad` is itself the
/// radians unit; the popup is unarmed, so Down then Enter completes the name and the
/// dimension takes it (#3663).
#[test]
fn a_name_that_extends_a_unit_is_offered_and_completes() {
cancel();
let mut h = crate::scenario::Harness::new();
h.app.run("parameters.add", json!({"name":"radius","expression":"10 mm"})).unwrap();
h.app.run("sketch.create", json!({"plane":"XY"})).unwrap();
h.app.run("sketch.line", json!({"points":[[10,10],[40,10]],"infer":false})).unwrap();
h.call("ui.view", json!({"view":"top"}));
h.step(&json!({"start":"sketch.dimension"})).unwrap();
h.step(&json!({"click":{"sketch":[25,10]}})).unwrap();
assert!(editing(), "{:?}", h.app.status);
h.step(&json!({"text":"rad"})).unwrap();
h.frames(2);
assert!(crate::params_dialog::suggestions(&h.ctx, "rad").iter().any(|s| s.text == "radius"));
assert_eq!(crate::expression_complete::popup_state(&h.ctx), Some((1, true)), "a unit with no number before it is a prefix: armed");
h.step(&json!({"key":"Enter"})).unwrap();
assert!(editing(), "Enter completed the name, the editor stays open: {:?}", h.app.status);
assert_eq!(EDIT.with(|e| e.borrow().as_ref().map(|e| e.expr.clone())), Some("radius".to_string()));
h.step(&json!({"key":"Enter"})).unwrap();
assert!(!editing(), "{:?}", h.app.status);
let sk = h.app.session.doc.sketch(h.app.session.active_sketch.unwrap()).unwrap();
let dim = sk.constraints.iter().find_map(|c| c.param.as_deref()).expect("the dimension was added");
assert_eq!(h.app.session.doc.param(dim).map(|p| p.expr.as_str()), Some("radius"));
h.step(&json!({"key":"Escape"})).unwrap();
cancel();
}
#[test]
fn placement_previews_radial_and_angular_dimensions_and_invalidates_on_document_change() {
cancel();
+126 -12
View File
@@ -3,7 +3,7 @@
use crate::ui_kit;
use egui::Key;
use crate::params_dialog::{suggestions_for, word_before};
use crate::params_dialog::{exact_token, suggestions_for, unit_token, word_before};
use crate::theme::Tokens;
#[derive(Clone)]
@@ -19,6 +19,13 @@ struct Popup {
explicit: bool,
/// Where each suggestion was drawn, for a press on one (see [`complete`]).
rows: Vec<egui::Rect>,
/// A row is selected, so Enter and Tab complete it. A popup opened on a word that is
/// itself a complete name (`width`) starts unarmed: it only shows the longer names, Enter
/// and Tab reach the editor as if it were not there, and an arrow key arms it (#3663). A
/// unit means something only after a number, where no popup opens, so a unit typed anywhere
/// else (`rad` on the way to `radius`) is a prefix like any other and the popup is armed.
/// A press on a row inserts it whether or not the list is armed.
armed: bool,
}
fn popup_id() -> egui::Id {
@@ -38,6 +45,7 @@ pub(crate) fn begin_frame(ctx: &egui::Context) {
});
popup.explicit = true;
popup.dismissed = false;
popup.armed = true;
ctx.data_mut(|d| d.insert_temp(popup_id(), popup.clone()));
}
let escape_blurred = ctx.input(|i| i.key_pressed(Key::Escape)) && ctx.memory(|m| m.focused().is_none() && m.had_focus_last_frame(popup.editor));
@@ -65,8 +73,12 @@ pub(crate) fn begin_frame(ctx: &egui::Context) {
&& *modifiers == egui::Modifiers::NONE
{
match key {
Key::ArrowDown if !popup.armed => (popup.armed, popup.selected) = (true, 0),
Key::ArrowUp if !popup.armed => (popup.armed, popup.selected) = (true, popup.count - 1),
Key::ArrowDown => popup.selected = (popup.selected + 1) % popup.count,
Key::ArrowUp => popup.selected = (popup.selected + popup.count - 1) % popup.count,
// Unarmed, the typed word is complete: Enter submits it and Tab moves on.
Key::Enter | Key::Tab if !popup.armed => continue,
Key::Enter | Key::Tab => popup.accept = true,
Key::Escape => {
popup.dismissed = true;
@@ -128,6 +140,9 @@ pub(crate) fn complete(ui: &mut egui::Ui, resp: &egui::Response, text: &mut Stri
// Dismissed suggestions stay closed until this box is typed in: another control rewriting
// its text (a slider dragged while the box keeps the focus) or a moved caret is no reason.
let dismissed = previous.as_ref().is_some_and(|p| p.dismissed) && !resp.changed();
// A word that is already a complete name opens unarmed: Enter submits it as typed. A unit
// without a number before it (`rad`, half-way to `radius`) is a prefix, so it stays armed.
let armed = !exact_token(&ctx, &word) || unit_token(&ctx, &word);
let mut popup = previous.filter(|p| p.word == word && p.cursor == cursor).unwrap_or(Popup {
editor: resp.id,
frame: 0,
@@ -139,12 +154,20 @@ pub(crate) fn complete(ui: &mut egui::Ui, resp: &egui::Response, text: &mut Stri
dismissed,
explicit: false,
rows: Vec::new(),
armed,
});
// Never over a control being dragged: the drag dismisses them.
if ctx.dragged_id().is_some_and(|id| id != resp.id) {
popup.dismissed = true;
}
let list = suggestions_for(&ctx, &popup.word, popup.explicit);
// A unit right after a number (`2 in`, `10 mm`, the form every dialog starts its sizes in)
// is a unit, not the start of a name: no popup there, so nothing sits over the OK button.
let number_before = text.chars().take(start).filter(|c| !c.is_whitespace()).last().is_some_and(|c| c.is_ascii_digit() || c == '.' || c == ')');
let list = if !popup.explicit && number_before && unit_token(&ctx, &popup.word) {
Vec::new()
} else {
suggestions_for(&ctx, &popup.word, popup.explicit)
};
popup.frame = ctx.cumulative_frame_nr();
popup.count = list.len();
popup.selected = popup.selected.min(list.len().saturating_sub(1));
@@ -156,7 +179,7 @@ pub(crate) fn complete(ui: &mut egui::Ui, resp: &egui::Response, text: &mut Stri
}
let mut pick = match pressed_row {
Some(row) => list.get(row).map(|s| s.text.clone()),
None if popup.accept => list.get(popup.selected).map(|s| s.text.clone()),
None if popup.accept && popup.armed => list.get(popup.selected).map(|s| s.text.clone()),
None => None,
};
popup.accept = false;
@@ -185,9 +208,14 @@ pub(crate) fn complete(ui: &mut egui::Ui, resp: &egui::Response, text: &mut Stri
&ctx,
list_id,
resp.rect,
popup.selected,
popup.armed.then_some(popup.selected),
&options,
crate::i18n::tr_label("↑ ↓ choose · Enter / Tab complete · Esc dismiss"),
// Unarmed, the typed word is complete and Enter submits it; an arrow key arms the list.
crate::i18n::tr_label(if popup.armed {
"↑ ↓ choose · Enter / Tab complete · Esc dismiss"
} else {
"↑ ↓ choose · Enter applies what you typed · Esc dismiss"
}),
) && pick.is_none()
&& !released_after_press
{
@@ -212,6 +240,12 @@ pub(crate) fn complete(ui: &mut egui::Ui, resp: &egui::Response, text: &mut Stri
true
}
/// The open popup for tests: (number of rows, armed).
#[cfg(test)]
pub(crate) fn popup_state(ctx: &egui::Context) -> Option<(usize, bool)> {
ctx.data(|d| d.get_temp::<Popup>(popup_id())).filter(|p| p.count > 0 && !p.dismissed).map(|p| (p.count, p.armed))
}
#[cfg(test)]
mod tests {
use super::*;
@@ -232,7 +266,7 @@ mod tests {
fn new(text: &str) -> Self {
let ctx = crate::fonts::test_context();
let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default());
for (name, value) in [("width", 40), ("width_extra", 50), ("wing", 20), ("wire", 10)] {
for (name, value) in [("width", 40), ("width_extra", 50), ("wing", 20), ("wire", 10), ("radius", 10)] {
app.run("parameters.add", json!({"name":name,"expression":format!("{value} mm")})).unwrap();
}
params_dialog::publish(&mut app, &ctx);
@@ -288,6 +322,11 @@ mod tests {
fn selected(&self) -> usize {
self.ctx.data(|d| d.get_temp::<Popup>(popup_id())).unwrap().selected
}
/// (rows, armed) of the open popup.
fn popup(&self) -> Option<(usize, bool)> {
popup_state(&self.ctx)
}
}
#[test]
@@ -387,17 +426,92 @@ mod tests {
assert_eq!(e.text, "1234");
}
/// A word that is itself a complete name submits on Enter and lets Tab move on, whether or
/// not longer names share its prefix. Those names stay listed, unarmed, so `width` shows
/// `width_extra` instead of nothing (#3663).
#[test]
fn exact_tokens_submit_without_completing_longer_names() {
for text in ["width", "2 mm"] {
let mut e = Editor::new(text);
e.key(Key::Enter);
assert_eq!(e.text, text);
assert!(!e.accepted);
assert!(e.leaked.contains(&Key::Enter));
for (text, rows) in [("width", true), ("2 mm", false)] {
for key in [Key::Enter, Key::Tab] {
let mut e = Editor::new(text);
let popup = e.popup();
assert_eq!(popup.is_some(), rows, "{text:?}: {popup:?}");
if let Some((count, armed)) = popup {
assert!(count > 0 && !armed, "{text:?}: {popup:?}");
}
e.key(key);
assert_eq!(e.text, text);
assert!(!e.accepted);
assert!(e.leaked.contains(&key), "{text:?} {key:?}");
}
}
}
/// From the unarmed popup an arrow key picks a row (Down the first, Up the last); Enter or
/// Tab then complete it as usual.
#[test]
fn arrows_arm_the_popup_on_an_exact_token() {
let mut e = Editor::new("width");
assert!(suggestions(&e.ctx, "width").iter().any(|s| s.text == "width_extra"));
assert_eq!(e.popup().map(|(_, armed)| armed), Some(false));
e.key(Key::ArrowDown);
assert_eq!(e.popup().map(|(_, armed)| armed), Some(true));
assert_eq!(e.selected(), 0);
assert!(e.leaked.is_empty());
e.key(Key::Enter);
assert_eq!(e.text, "width_extra");
assert!(e.accepted && e.leaked.is_empty());
let mut e = Editor::new("2 * width");
assert_eq!(e.popup().map(|(_, armed)| armed), Some(false));
e.key(Key::ArrowUp);
let (count, armed) = e.popup().unwrap();
assert!(armed);
assert_eq!(e.selected(), count - 1);
e.key(Key::Tab);
assert!(e.accepted && e.text.starts_with("2 * "));
assert_ne!(e.text, "2 * width");
}
/// A unit right after a number is a unit: `10 mm` opens no popup even with a parameter
/// `mm_wall` defined (a dialog starting on `2 in` otherwise listed names over its OK button),
/// and Enter submits `10 mm`. After an operator the same word is a prefix again: `2 * mm`
/// lists `mm_wall`, armed, so Enter completes it.
#[test]
fn a_unit_after_a_number_opens_no_popup() {
let mut e = Editor::new("10 mm");
assert!(e.popup().is_none());
e.app.run("parameters.add", json!({"name":"mm_wall","expression":"3 mm"})).unwrap();
e.frame(Vec::new());
assert!(e.popup().is_none(), "{:?}", e.popup());
assert!(suggestions(&e.ctx, "mm").iter().any(|s| s.text == "mm_wall"));
e.key(Key::Enter);
assert_eq!(e.text, "10 mm");
assert!(!e.accepted && e.leaked.contains(&Key::Enter));
let mut e = Editor::new("2 * mm");
e.app.run("parameters.add", json!({"name":"mm_wall","expression":"3 mm"})).unwrap();
e.frame(Vec::new());
assert_eq!(e.popup(), Some((1, true)));
e.key(Key::Enter);
assert_eq!(e.text, "2 * mm_wall");
}
/// Typing a name letter by letter passes through words that happen to be units: `ra` lists
/// `radius` selected, and `rad` must keep it selected, so Enter completes the name instead
/// of submitting one radian into a length (found testing #3663).
#[test]
fn a_unit_typed_on_the_way_to_a_name_stays_armed() {
let mut e = Editor::new("ra");
assert_eq!(e.popup().map(|(_, armed)| armed), Some(true));
e.frame(vec![egui::Event::Text("d".into())]);
assert_eq!(e.text, "rad");
assert_eq!(e.popup(), Some((1, true)));
e.key(Key::Enter);
assert_eq!(e.text, "radius");
assert!(e.accepted && e.leaked.is_empty());
}
#[test]
fn typing_and_enter_in_one_batch_does_not_accept_stale_prefix() {
let mut e = Editor::new("wi");
+37 -6
View File
@@ -752,19 +752,33 @@ pub(crate) fn suggestions_for(ctx: &egui::Context, word: &str, explicit: bool) -
return Vec::new();
}
let all = ctx.data(|d| d.get_temp::<Cache>(cache_id())).map(|c| c.all).unwrap_or_default();
// A complete token is ready to submit, even when longer names share its prefix.
if !explicit && all.iter().any(|s| s.text == word) {
return Vec::new();
}
// A complete token stays out of its own list; longer names that start with it are still
// offered (passively: see `expression_complete`, #3663), but only those: `in` lists `inner`,
// not every name with `in` somewhere in it. A typed unit is complete in every sense, so only
// parameters, functions and constants extend it: `in` does not offer `inch`.
let exact = !explicit && all.iter().any(|s| s.text == word);
let w = word.to_ascii_lowercase();
let offered = |s: &&Suggestion| explicit || s.text.trim_end_matches('(') != word;
let offered = |s: &&Suggestion| (explicit || s.text.trim_end_matches('(') != word) && !(exact && s.kind == "unit");
let starts = |s: &&Suggestion| s.text.to_ascii_lowercase().starts_with(&w);
// A parameter is also offered for a word anywhere in its name (`side` finds
// `cab_side_thickness`, #2757), after the names that start with it.
let within = |s: &&Suggestion| s.kind == "parameter" && !starts(s) && s.text.to_ascii_lowercase().contains(&w);
let within = |s: &&Suggestion| !exact && s.kind == "parameter" && !starts(s) && s.text.to_ascii_lowercase().contains(&w);
all.iter().filter(|s| starts(s) && offered(s)).chain(all.iter().filter(|s| within(s) && offered(s))).take(8).cloned().collect()
}
/// Is `word` itself one of the known tokens (a parameter or dimension name, a constant or a
/// unit)? Such a word is ready to submit as typed; the popup then only offers longer names.
pub(crate) fn exact_token(ctx: &egui::Context, word: &str) -> bool {
let all = ctx.data(|d| d.get_temp::<Cache>(cache_id())).map(|c| c.all).unwrap_or_default();
all.iter().any(|s| s.text == word)
}
/// Is `word` a unit (`mm`, `in`, `deg`, ...)?
pub(crate) fn unit_token(ctx: &egui::Context, word: &str) -> bool {
let all = ctx.data(|d| d.get_temp::<Cache>(cache_id())).map(|c| c.all).unwrap_or_default();
all.iter().any(|s| s.kind == "unit" && s.text == word)
}
/// Offer keyboard and pointer completions under a focused expression box.
/// Returns true when a suggestion was accepted; callers must not submit that frame.
pub fn complete(ui: &mut egui::Ui, resp: &egui::Response, text: &mut String) -> bool {
@@ -977,9 +991,26 @@ mod tests {
let ctx = crate::fonts::test_context();
let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default());
let _ = app.run("parameters.add", json!({"name": "width", "expression": "40 mm"}));
let _ = app.run("parameters.add", json!({"name": "radius", "expression": "10 mm"}));
let _ = app.run("parameters.add", json!({"name": "rounding", "expression": "3 mm"}));
publish(&mut app, &ctx);
let s = suggestions(&ctx, "wi");
assert_eq!(s.first().map(|x| x.text.as_str()), Some("width"));
// A name that extends a unit is still offered at the unit's own prefix (#3663); the
// prefix itself is a complete token, so the caller knows Enter should submit it.
assert!(suggestions(&ctx, "rad").iter().any(|x| x.text == "radius"));
assert!(!suggestions(&ctx, "rad").iter().any(|x| x.text == "rad"));
// A typed unit is not extended by other units: `in` offers no `inch` (a popup there sat
// over dialog buttons); a prefix that is not itself a unit still does. A complete token
// is extended only by names that start with it: `in` does not list `rounding` (a fillet
// dialog opening on `2 in` showed it over the OK button), while `und` still does (#2757).
assert!(suggestions(&ctx, "in").is_empty() && suggestions(&ctx, "mm").is_empty());
assert!(suggestions(&ctx, "und").iter().any(|x| x.text == "rounding"));
assert!(unit_token(&ctx, "in") && unit_token(&ctx, "rad") && !unit_token(&ctx, "radius") && !unit_token(&ctx, "i"));
let m: Vec<String> = suggestions(&ctx, "m").into_iter().map(|x| x.kind).collect();
assert!(!m.is_empty() && m.iter().all(|k| k == "function"), "{m:?}");
assert!(suggestions(&ctx, "i").iter().any(|x| x.text == "inch"));
assert!(exact_token(&ctx, "rad") && exact_token(&ctx, "width") && !exact_token(&ctx, "radi") && !exact_token(&ctx, "wi"));
assert!(suggestions(&ctx, "ata").iter().any(|x| x.text == "atan2("));
assert!(suggestions(&ctx, "1").is_empty());
// The dialog's rows come from the engine.
+7 -6
View File
@@ -376,15 +376,16 @@ pub(crate) struct PopupOption<'a> {
pub color: egui::Color32,
}
/// Focus-neutral suggestion popup. The owner handles navigation and completion semantics. Its
/// rows take no focus, and where they were drawn is kept under `id.with("rows")`, so an owner
/// can act on a press before the click lands (#3257).
/// Focus-neutral suggestion popup. The owner handles navigation and completion semantics;
/// `selected` is the highlighted row, or `None` when no row is picked yet (#3663). Its rows
/// take no focus, and where they were drawn is kept under `id.with("rows")`, so an owner can
/// act on a press before the click lands (#3257).
/// Tokens: space_2, form_label_width, control_height, text_dim, scope control/font tokens.
pub(crate) fn popup_list(
ctx: &egui::Context,
id: egui::Id,
anchor: egui::Rect,
selected: usize,
selected: Option<usize>,
options: &[PopupOption<'_>],
hint: &str,
) -> Option<usize> {
@@ -404,7 +405,7 @@ pub(crate) fn popup_list(
for (index, option) in options.iter().enumerate() {
let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), t.control_height), egui::Sense::CLICK);
rows.push(rect);
let picked = index == selected;
let picked = selected == Some(index);
if picked || response.hovered() {
ui.painter().rect_filled(rect, t.control_radius, if picked { t.selected_bg } else { t.hover });
}
@@ -438,7 +439,7 @@ pub(crate) fn popup_list(
}
}
super::divider(ui, "completion_detail");
if let Some(option) = options.get(selected) {
if let Some(option) = selected.and_then(|index| options.get(index)) {
super::text(ui, option.detail, super::Text::Note("completion_detail"));
}
super::text(ui, hint, super::Text::Note("completion_hint"));
+2 -2
View File
@@ -1043,7 +1043,7 @@ const ELEMENTS: &[Element] = &[
ui.ctx(),
ui.id().with("popup"),
anchor,
0,
Some(0),
&[PopupOption { kind: "parameter", text: "Width", detail: "10 mm", color: Tokens::get().text }],
"Choose",
);
@@ -1325,7 +1325,7 @@ fn popup_suggestions_and_selectable_lists_keep_click_selection() {
ui.ctx(),
egui::Id::new("suggestions"),
egui::Rect::from_min_size(egui::pos2(10.0, 10.0), vec2(220.0, 24.0)),
0,
Some(0),
&[
PopupOption { kind: "parameter", text: "width", detail: "Parameter · 10 mm", color: Tokens::get().text },
PopupOption { kind: "parameter", text: "height", detail: "Parameter · 20 mm", color: Tokens::get().text },
+5 -1
View File
@@ -25,7 +25,11 @@ editable. In expression fields, type a parameter or dimension name for autocompl
or press **Ctrl+Space** to open suggestions, including in an empty field.
**Up/Down** selects an autocomplete suggestion,
**Enter/Tab** accepts it, and **Escape** dismisses the suggestions. Accepting a suggestion
does not also submit the parameter.
does not also submit the parameter. When what you typed is already a complete name
(`width`), longer names such as `width_extra` stay listed without a selection: **Enter**
applies what you typed, and **Up/Down** picks one of them first. A unit right after a number
(`10 mm`) is left alone; anywhere else a unit is a prefix like any other, so `rad` followed by
**Enter** gives `radius`.
Expressions are unit-aware: `2 * width + 5 mm`, `angle / 2`, `sqrt(area)`, `1 in + 3 mm`, using
`+ - * / ^`, parentheses, `sin cos tan asin acos atan atan2 sqrt abs min max floor ceil round mod