Completion list: a mark before each candidate and the highlighted one's description under the list; Enter accepts only where the field completes on Enter (ctl:72, ctl:73)

- Completion carries a mark and a description; the unread detail line goes.
- FocusPolicy::list_enter: a text opener of a KeepAnchor layer keeps Enter when its layer turns it off, and Tab alone
  takes the lead. TextField::complete_on_enter turns it on; the review composer's mentions use it, as before.
This commit is contained in:
aiongg
2026-11-12 14:32:43 +00:00
parent 97bd415a4c
commit 21b71e19d1
9 changed files with 196 additions and 27 deletions
+1
View File
@@ -208,6 +208,7 @@ impl ThreadPopover<'_> {
.lines(COMPOSER_ROWS)
.placeholder(words.reply.clone())
.complete(MentionCompleter { people: people.to_vec(), me: me.to_owned() })
.complete_on_enter()
.submits()
.default_stop()
.show(ui);
@@ -59,6 +59,8 @@ pub struct TextOptions {
pub tab_inserts: bool,
/// Candidates for the text before the caret.
pub complete: Option<Arc<dyn Completer>>,
/// Enter accepts the highlighted candidate, as Tab does; off, Enter stays the field's own (a cell commits on it).
pub complete_on_enter: bool,
/// Text that replaces the selection in the pass it is set (the caret inserts it).
pub replace_selection: Option<String>,
/// Typing one of these characters commits the draft, as Enter does without submitting; the character is not
@@ -102,6 +104,7 @@ impl Default for TextOptions {
ink: None,
tab_inserts: false,
complete: None,
complete_on_enter: false,
replace_selection: None,
commit_on: &[],
enabled: true,
@@ -152,14 +155,30 @@ pub struct Completion {
pub label: Label,
/// The text that replaces the range.
pub insert: String,
/// A second line of the row.
pub detail: Option<Label>,
/// A short mark before the label (GridCraft's "ƒ" for a function).
pub mark: Option<Label>,
/// What the candidate is, shown under the list while its row is highlighted.
pub description: Option<Label>,
}
impl Completion {
/// A candidate shown as `label` that inserts `insert`.
pub fn new(label: impl Into<Label>, insert: impl Into<String>) -> Self {
Completion { label: label.into(), insert: insert.into(), detail: None }
Completion { label: label.into(), insert: insert.into(), mark: None, description: None }
}
/// Sets the mark before the label.
#[must_use]
pub fn mark(mut self, mark: impl Into<Label>) -> Self {
self.mark = Some(mark.into());
self
}
/// Sets the description shown while the candidate is highlighted.
#[must_use]
pub fn description(mut self, description: impl Into<Label>) -> Self {
self.description = Some(description.into());
self
}
}
@@ -50,6 +50,9 @@ pub struct FocusPolicy {
pub cancel: CancelRule,
/// Ctrl+Tab cycles pages.
pub pages: bool,
/// In a `KeepAnchor` layer, Enter on a text opener activates the layer's list; off, the opener keeps Enter and
/// Tab alone takes the list's lead (a completion list that leaves Enter to the field's own commit).
pub list_enter: bool,
}
impl FocusPolicy {
@@ -62,6 +65,7 @@ impl FocusPolicy {
enter: EnterRule::Pass,
cancel: CancelRule::Ignore,
pages: false,
list_enter: true,
};
/// A pane: an F6 stop.
pub const PANE: FocusPolicy = FocusPolicy { kind: ScopeKind::Pane, ..FocusPolicy::NONE };
@@ -74,6 +78,7 @@ impl FocusPolicy {
enter: EnterRule::Submit,
cancel: CancelRule::Close,
pages: false,
list_enter: true,
};
/// A popup: focus moves in, Escape closes and focus returns to the opener.
pub const POPUP: FocusPolicy = FocusPolicy {
@@ -84,6 +89,7 @@ impl FocusPolicy {
enter: EnterRule::Pass,
cancel: CancelRule::Close,
pages: false,
list_enter: true,
};
/// A menu: like a popup.
pub const MENU: FocusPolicy = FocusPolicy { kind: ScopeKind::Menu, ..FocusPolicy::POPUP };
@@ -115,6 +121,12 @@ impl FocusPolicy {
self
}
/// Whether Enter on a text opener activates the layer's list.
pub const fn list_enter(mut self, on: bool) -> Self {
self.list_enter = on;
self
}
/// Whether Ctrl+Tab cycles pages.
pub const fn pages(mut self, on: bool) -> Self {
self.pages = on;
@@ -1,7 +1,7 @@
//! The registrations of the focus service: a stop and a roving group. The types are `pub` so the testing kit can
//! name them; the module is crate-private, so no other path reaches them.
use super::{Initial, KeyUse, Roving, StopKey, with};
use super::{FocusPolicy, Initial, KeyUse, Roving, StopKey, with};
use crate::runtime::egui::memory as store;
use crate::runtime::memory::sub;
use craft_behavior::{KeyRole, PartRef};
@@ -192,10 +192,10 @@ pub(crate) fn part_group(ctx: &Context, parts: Id) -> Option<Id> {
(join.pass.saturating_add(1) >= crate::runtime::pointer::pass_of(ctx)).then_some(join.group)
}
/// The innermost open `KeepAnchor` layer opened from the stop `opener` and the collection its opener hands list
/// keys to: the stop with the collection's key role that is registered inside the layer's focus scope. `None` while
/// no such layer is open or it has no collection.
pub(crate) fn dropdown_target(ctx: &Context, opener: StopKey) -> Option<(Id, Id)> {
/// The innermost open `KeepAnchor` layer opened from the stop `opener`, the collection its opener hands list keys
/// to (the stop with the collection's key role that is registered inside the layer's focus scope) and the layer's
/// policy. `None` while no such layer is open or it has no collection.
pub(crate) fn dropdown_target(ctx: &Context, opener: StopKey) -> Option<(Id, Id, FocusPolicy)> {
with(ctx, |state| {
let layer =
*state.last_scope_order.iter().rev().find(|id| {
@@ -211,7 +211,8 @@ pub(crate) fn dropdown_target(ctx: &Context, opener: StopKey) -> Option<(Id, Id)
}
false
};
state.last_stops.iter().find(|rec| rec.stop.role.type_ahead && inside(rec)).map(|rec| (layer, rec.stop.id))
let policy = state.last_scopes.get(&layer)?.policy;
state.last_stops.iter().find(|rec| rec.stop.role.type_ahead && inside(rec)).map(|rec| (layer, rec.stop.id, policy))
})
}
+9 -6
View File
@@ -266,6 +266,8 @@ struct Driven {
ends: bool,
/// Left and Right go to the list too (a tree): a text stop keeps them for its caret while it holds text.
tree: bool,
/// Enter goes to the list; off, a text opener keeps it (its layer's `FocusPolicy::list_enter`).
enter: bool,
}
/// The collection a text stop inside an open `KeepAnchor` dropdown layer (a search field) or a text field that drives
@@ -289,10 +291,11 @@ fn list_of_field(ctx: &Context, rec: &StopRec) -> Option<Driven> {
text: false,
ends: drive.empty,
tree: drive.empty && focus::registration::is_tree(ctx, drive.list),
enter: true,
}),
(None, Some((_, opener))) => {
let (layer, list) = focus::registration::dropdown_target(ctx, opener)?;
Some(Driven { layer: Some(layer), list, text: false, ends: true, tree: false })
let (layer, list, _) = focus::registration::dropdown_target(ctx, opener)?;
Some(Driven { layer: Some(layer), list, text: false, ends: true, tree: false, enter: true })
}
(None, None) => None,
}
@@ -303,9 +306,9 @@ const LIST_KEYS: [Key; 8] = [Key::Up, Key::Down, Key::PageUp, Key::PageDown, Key
impl Driven {
fn of(ctx: &Context, opener: &StopRec) -> Option<Driven> {
let (layer, list) = focus::registration::dropdown_target(ctx, opener.stop.key())?;
let (layer, list, policy) = focus::registration::dropdown_target(ctx, opener.stop.key())?;
let text = matches!(opener.stop.keys.owner, OwnerClass::Text);
Some(Driven { layer: Some(layer), list, text, ends: !text, tree: false })
Some(Driven { layer: Some(layer), list, text, ends: !text, tree: false, enter: !text || policy.list_enter })
}
/// The intent a claimed chord of the opener becomes for the list.
@@ -314,7 +317,7 @@ impl Driven {
}
/// The list intent of a plain key the focused stop hands on: vertical moves and Page keys, Home and End where
/// `ends` says, Left and Right of a tree, and Enter as the activation. A text opener's Tab accepts the lead too:
/// `ends` says, Left and Right of a tree, and Enter as the activation where `enter` says. A text opener's Tab accepts the lead too:
/// there Tab is not the way to the next stop while the list is open.
fn intent(self, key: Key) -> Option<Intent> {
let moved = |mv| Some(Intent::Move(mv, MoveMods::PLAIN));
@@ -327,7 +330,7 @@ impl Driven {
Key::End if self.ends => moved(NavMove::End),
Key::Left if self.tree => moved(NavMove::Back),
Key::Right if self.tree => moved(NavMove::Forward),
Key::Enter => Some(Intent::Activate),
Key::Enter if self.enter => Some(Intent::Activate),
Key::Tab if self.text => Some(Intent::Activate),
_ => None,
}
+33 -11
View File
@@ -1,10 +1,14 @@
//! The completion list of a text control (18.2): the popup shows the candidates the text adapter holds, and a click
//! on a row hands the pick back to the adapter, which accepts it in its next run.
use crate::contract::{CollectionEvent, Component, Cx, Overlay, OverlayUi, Overlays as _, ShowCollection as _, WordSetCx as _};
use crate::contract::{
CollectionEvent, Component, Cx, Overlay, OverlayUi, Overlays as _, Show as _, ShowCollection as _, WordSetCx as _, lead_position,
};
use crate::display::{Divider, Text};
use crate::list::{List, ListRow};
use crate::primitives::TextKey;
use crate::runtime::env::Label;
use crate::style::TypeRole;
use craft_behavior::{DisplayOrder, ItemSource};
use std::borrow::Cow;
use std::hash::{DefaultHasher, Hash as _, Hasher as _};
@@ -34,14 +38,20 @@ impl DisplayOrder<usize> for Candidates<'_> {
impl ItemSource<usize> for Candidates<'_> {}
/// Shows the `completions` popup of a component whose text part is `key`: one option row per candidate. The popup is
/// a dropdown: the host hands the text part's list keys to the list, whose lead is the highlight, and the opener keeps
/// the key focus. An activation (Enter, Tab or a click) picks the candidate the adapter accepts in its next run. A text
/// control that takes completion calls this from its `overlay` hook.
pub(crate) fn show<C: Component, V: 'static>(ui: &mut OverlayUi<'_>, cx: &mut Cx<'_, C>, key: &TextKey<V>) {
/// Shows the `completions` popup of a component whose text part is `key`: one option row per candidate, its mark before
/// the label, and under the rows, past a divider, the highlighted candidate's description. The popup is a dropdown: the
/// host hands the text part's list keys to the list, whose lead is the highlight, and the opener keeps the key focus.
/// An activation (Tab, a click, and Enter with `enter`) picks the candidate the adapter accepts in its next run; without
/// `enter` the field keeps Enter. A text control that takes completion calls this from its `overlay` hook.
pub(crate) fn show<C: Component, V: 'static>(ui: &mut OverlayUi<'_>, cx: &mut Cx<'_, C>, key: &TextKey<V>, enter: bool) {
let popup = cx.popup("completions");
let candidates = cx.text(key).map_or_else(Vec::new, |text| text.completions.clone());
let labels: Vec<Label> = candidates.iter().map(|candidate| cx.env.resolve(&candidate.label)).collect();
let marks: Vec<Option<Label>> = candidates.iter().map(|candidate| candidate.mark.as_ref().map(|mark| cx.env.resolve(mark))).collect();
let descriptions: Vec<Option<Label>> =
candidates.iter().map(|candidate| candidate.description.as_ref().map(|text| cx.env.resolve(text))).collect();
// The mark slot is as wide as the widest mark, so the labels line up.
let widest = marks.iter().flatten().max_by_key(|mark| mark.as_str().chars().count()).cloned();
let name = cx.label();
// New candidates are new rows: the highlight returns to the first.
let stamp = {
@@ -49,11 +59,23 @@ pub(crate) fn show<C: Component, V: 'static>(ui: &mut OverlayUi<'_>, cx: &mut Cx
labels.iter().for_each(|label| label.as_str().hash(&mut hasher));
hasher.finish()
};
let events = ui.show(popup, Overlay::dropdown(), |ui, _| {
List::options(name.clone())
.rows_stamp(stamp)
.show_items(ui, &Candidates { labels: &labels }, &mut |at, _| ListRow::new(labels[*at].clone()).option())
.events
let focus = Overlay::dropdown().focus.list_enter(enter);
let overlay = Overlay::dropdown().focus(focus);
let events = ui.show(popup, overlay, |ui, _| {
let list = List::options(name.clone()).rows_stamp(stamp).show_items(ui, &Candidates { labels: &labels }, &mut |at, _| {
let row = ListRow::new(labels[*at].clone()).option();
match (&marks[*at], &widest) {
(Some(mark), Some(widest)) => row.lead_text(mark.clone(), widest.clone()),
(None, Some(widest)) => row.lead_text(Label::Empty, widest.clone()),
_ => row,
}
});
let lead = lead_position(ui.ctx(), list.response.id);
if let Some(description) = lead.and_then(|at| descriptions.get(at)).and_then(Option::as_ref) {
Divider::horizontal().show(ui);
Text::new(description.clone()).role(TypeRole::Caption).show(ui);
}
list.events
});
let picked = events.into_iter().flatten().find_map(|event| match event {
CollectionEvent::Activate(at) => Some(at),
+9 -1
View File
@@ -183,6 +183,14 @@ impl<'a, C: Codec + Clone + 'static> TextField<'a, C> {
self
}
/// Enter accepts the highlighted completion, as Tab does. Without it Enter stays the field's own: it commits the
/// text as typed.
#[must_use]
pub fn complete_on_enter(mut self) -> Self {
self.options.complete_on_enter = true;
self
}
/// `text` replaces the selection in this pass: at the caret it inserts. Set it for one pass only.
#[must_use]
pub fn replace_selection(mut self, text: impl Into<String>) -> Self {
@@ -299,7 +307,7 @@ impl<C: Codec + Clone + 'static> Component for TextField<'_, C> {
/// The completion list under the field, over what the text adapter holds.
fn overlay(&mut self, ui: &mut OverlayUi<'_>, cx: &mut Cx<'_, Self>) {
if self.options.complete.is_some() {
completions::show(ui, cx, &text_part::<C::Value>());
completions::show(ui, cx, &text_part::<C::Value>(), self.options.complete_on_enter);
}
}
@@ -133,3 +133,34 @@ fn text_field_adorned(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
.show(ui)
.into()
}
/// Completes spreadsheet functions: each candidate marked "ƒ", with what it does under the list.
struct Functions;
impl Completer for Functions {
fn complete(&self, text: &str, caret: usize, out: &mut Vec<Completion>) -> Option<Range<usize>> {
const FUNCTIONS: [(&str, &str); 3] = [
("SUM", "Adds the numbers in a range."),
("SUMIF", "Adds the numbers in a range that meet a condition."),
("SUBSTITUTE", "Replaces text in a string."),
];
let before = text.get(..caret)?.trim_start_matches('=');
let start = caret - before.len();
let hits: Vec<_> = FUNCTIONS.into_iter().filter(|(name, _)| !before.is_empty() && name.starts_with(&before.to_uppercase())).collect();
out.extend(hits.iter().map(|(name, what)| Completion::new(*name, format!("{name}(")).mark("ƒ").description(*what)));
(!hits.is_empty()).then_some(start..caret)
}
}
/// Focuses the field and types the start of a function name, which opens the marked list.
fn open_functions(fixture: &mut Fixture) {
fixture.key(Key::Tab, Modifiers::NONE);
fixture.type_text("=SU");
fixture.idle(4);
}
/// A formula cell: the marked list with the highlighted function's description; Enter commits the cell, Tab completes.
#[story(TextField<'static, PlainText>, covers = [], drive = Drive::Custom(open_functions))]
fn text_field_formula(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
TextField::new("Formula", Bind::given(String::new())).complete(Functions).show(ui).into()
}
+72
View File
@@ -85,3 +85,75 @@ fn a_value_set_outside_ends_the_typing_run() {
const SET: f64 = 7.0;
assert_eq!(*value.borrow(), Some(SET), "Enter commits the value that was set, not the draft");
}
/// Enter on an open completion list commits the text as typed unless the field completes on Enter; Tab always takes
/// the highlighted candidate.
#[trial]
fn enter_accepts_a_completion_only_where_the_field_completes_on_enter() {
for on_enter in [false, true] {
let mut rig = Rig::new("");
rig.focus();
let frame = |rig: &mut Rig, events: Vec<Event>| {
let (text, seen) = (&mut rig.text, &mut rig.seen);
rig.frames.frame(events, |ui| {
let field = TextField::new("Name", Bind::bound(&mut *text)).complete(Prefixes).id_salt("name");
let out = if on_enter { field.complete_on_enter() } else { field }.show(ui);
seen.rect = out.response.rect;
seen.id = out.response.id;
});
};
frame(&mut rig, vec![Event::Text("al".into())]);
for _ in 0..4 {
frame(&mut rig, vec![]);
}
frame(&mut rig, vec![key_press(Key::Enter, Modifiers::NONE)]);
for _ in 0..4 {
frame(&mut rig, vec![]);
}
let expected = if on_enter { "alpha" } else { "al" };
assert_eq!(rig.text, expected, "Enter with complete_on_enter {on_enter}");
}
}
/// Completes "sum" and "sumif", each marked, with a description.
struct Marked;
impl Completer for Marked {
fn complete(&self, text: &str, caret: usize, out: &mut Vec<Completion>) -> Option<Range<usize>> {
let before = text.get(..caret)?;
let hits: Vec<_> = [("sum", "Adds numbers."), ("sumif", "Adds numbers that meet a condition.")]
.into_iter()
.filter(|(word, _)| !before.is_empty() && word.starts_with(before))
.collect();
out.extend(hits.iter().map(|(word, what)| Completion::new(*word, *word).mark("ƒ").description(*what)));
(!hits.is_empty()).then_some(0..caret)
}
}
/// The list marks each candidate and describes the highlighted one: the description follows the highlight.
#[trial]
fn the_completion_list_describes_the_highlighted_candidate() {
let mut rig = Rig::new("");
rig.focus();
let shown_after = |rig: &mut Rig, events: Vec<Event>| {
let (text, seen) = (&mut rig.text, &mut rig.seen);
let mut show = |ui: &mut egui::Ui| {
let out = TextField::new("Name", Bind::bound(&mut *text)).complete(Marked).id_salt("name").show(ui);
seen.rect = out.response.rect;
seen.id = out.response.id;
};
rig.frames.frame(events, &mut show);
for _ in 0..4 {
rig.frames.frame(vec![], &mut show);
}
painted(&rig.frames.frame_shapes(&mut show))
};
let first = shown_after(&mut rig, vec![Event::Text("su".into())]);
assert!(first.iter().any(|t| t == "ƒ"), "each candidate shows its mark: {first:?}");
assert!(
first.iter().any(|t| t == "Adds numbers.") && !first.iter().any(|t| t == "Adds numbers that meet a condition."),
"the first candidate is described: {first:?}"
);
let second = shown_after(&mut rig, vec![key_press(Key::ArrowDown, Modifiers::NONE)]);
assert!(second.iter().any(|t| t == "Adds numbers that meet a condition."), "the description follows the highlight: {second:?}");
}