Lines
96.15 %
Functions
50 %
Branches
100 %
//! Type-ahead for the focused tag cell of any rows list in the form: answers
//! are fetched once per source and kept for the form's lifetime.
use super::Form;
use crate::widgets::{Hint, RowsWidget, Widget, completion, matching};
const MAX_SHOWN: usize = 8;
impl Form {
fn focused_rows(&self) -> Option<&RowsWidget> {
match &self.fields.get(self.focus)?.widget {
Widget::Rows(rows) => Some(rows),
Widget::Splits(splits) => splits.tags(),
_ => None,
}
pub(super) fn focused_rows_mut(&mut self) -> Option<&mut RowsWidget> {
match &mut self.fields.get_mut(self.focus)?.widget {
Widget::Splits(splits) => splits.tags_mut(),
/// The lookup the focused cell needs, if not asked yet.
#[must_use]
pub fn wanted_hint(&self) -> Option<Hint> {
let hint = Hint::of_focused(self.focused_rows()?)?;
self.hints.wants(&hint).then_some(hint)
pub fn hint_asked(&mut self, hint: &Hint, seq: u64) {
self.hints.asked(hint, seq);
/// Keeps the answer unless a newer request for its source superseded `seq`.
pub fn hint_arrived(&mut self, hint: &Hint, seq: u64, strings: Vec<String>) {
self.hints.arrived(hint, seq, strings);
fn focused_typed(&self) -> String {
let text = self
.focused_rows()
.and_then(|rows| Some(rows.focused_text(rows.focused_key()?)));
text.unwrap_or_default().to_string()
fn candidates_for(&self, typed: &str) -> Vec<&str> {
let hint = self.focused_rows().and_then(Hint::of_focused);
hint.map_or_else(Vec::new, |hint| matching(self.hints.answer(&hint), typed))
/// The suggestions that fit the focused cell as typed.
pub fn candidates(&self) -> Vec<&str> {
self.candidates_for(&self.focused_typed())
/// The suggestion line under the focused list, empty when nothing fits; `key` fills the cell.
pub fn suggestion_line(&self, key: Option<String>) -> Option<String> {
let shown: Vec<&str> = self.candidates().into_iter().take(MAX_SHOWN).collect();
let label = key.map_or_else(|| "suggest".to_string(), |key| format!("suggest ({key})"));
(!shown.is_empty()).then(|| format!("{label}: {}", shown.join(", ")))
/// Fills the focused cell with its next suggestion; repeated presses cycle
/// through those matching what was typed before the first.
pub fn complete_hint(&mut self) {
let typed = self.focused_typed();
let prefix = match &self.completing {
Some((prefix, filled)) if *filled == typed => prefix.clone(),
_ => typed.clone(),
};
let next = completion(&self.candidates_for(&prefix), &typed).map(str::to_string);
if let Some(next) = next
&& let Some(rows) = self.focused_rows_mut()
{
rows.set_focused_text(&next);
self.completing = Some((prefix, next));