Lines
100 %
Functions
50 %
Branches
//! Completions a rows list offers to its tag name and value cells.
use std::collections::HashMap;
use forms::Suggest;
use super::RowsWidget;
/// A lookup the sub-list wants answered; a value lookup names its tag.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Hint {
Names(Suggest),
Values(Suggest, String),
}
impl Hint {
/// The `form-options` source that serves the lookup.
#[must_use]
pub fn source(&self) -> String {
match self {
Self::Names(suggest) => suggest.name().to_string(),
Self::Values(suggest, tag) => format!("{}:{tag}", suggest.name()),
/// The lookup the focused cell of `rows` needs, if it suggests anything.
pub fn of_focused(rows: &RowsWidget) -> Option<Self> {
let suggest = rows.focused_suggest()?;
match suggest {
Suggest::TagNames(_) => Some(Self::Names(suggest)),
Suggest::TagValues(_) => match rows.focused_text("name") {
"" => None,
name => Some(Self::Values(suggest, name.to_string())),
},
/// The answers so far per source and the `seq` of each request; a reply of
/// any other `seq` is stale.
#[derive(Debug, Default)]
pub struct Hints {
answers: HashMap<String, (u64, Vec<String>)>,
impl Hints {
/// Whether `hint` has not been asked yet.
pub fn wants(&self, hint: &Hint) -> bool {
!self.answers.contains_key(&hint.source())
pub fn asked(&mut self, hint: &Hint, seq: u64) {
self.answers.insert(hint.source(), (seq, Vec::new()));
pub fn arrived(&mut self, hint: &Hint, seq: u64, strings: Vec<String>) {
if let Some(answer) = self.answers.get_mut(&hint.source())
&& answer.0 == seq
{
answer.1 = strings;
/// The answer to `hint`, empty until it arrives.
pub fn answer(&self, hint: &Hint) -> &[String] {
self.answers
.get(&hint.source())
.map_or(&[], |(_, strings)| strings)
/// The candidates that start with `typed`, ignoring case.
pub fn matching<'a>(all: &'a [String], typed: &str) -> Vec<&'a str> {
let typed = typed.to_lowercase();
all.iter()
.map(String::as_str)
.filter(|candidate| candidate.to_lowercase().starts_with(&typed))
.collect()
/// What completing `typed` yields: the candidate after the one typed in full,
/// else the first.
pub fn completion<'a>(candidates: &[&'a str], typed: &str) -> Option<&'a str> {
match candidates.iter().position(|candidate| *candidate == typed) {
Some(at) => candidates.get((at + 1) % candidates.len()).copied(),
None => candidates.first().copied(),