1use super::Form;
5use crate::widgets::{Hint, RowsWidget, Widget, completion, matching};
6
7const MAX_SHOWN: usize = 8;
8
9impl Form {
10 fn focused_rows(&self) -> Option<&RowsWidget> {
11 match &self.fields.get(self.focus)?.widget {
12 Widget::Rows(rows) => Some(rows),
13 Widget::Splits(splits) => splits.tags(),
14 _ => None,
15 }
16 }
17
18 pub(super) fn focused_rows_mut(&mut self) -> Option<&mut RowsWidget> {
19 match &mut self.fields.get_mut(self.focus)?.widget {
20 Widget::Rows(rows) => Some(rows),
21 Widget::Splits(splits) => splits.tags_mut(),
22 _ => None,
23 }
24 }
25
26 #[must_use]
28 pub fn wanted_hint(&self) -> Option<Hint> {
29 let hint = Hint::of_focused(self.focused_rows()?)?;
30 self.hints.wants(&hint).then_some(hint)
31 }
32
33 pub fn hint_asked(&mut self, hint: &Hint, seq: u64) {
34 self.hints.asked(hint, seq);
35 }
36
37 pub fn hint_arrived(&mut self, hint: &Hint, seq: u64, strings: Vec<String>) {
39 self.hints.arrived(hint, seq, strings);
40 }
41
42 fn focused_typed(&self) -> String {
43 let text = self
44 .focused_rows()
45 .and_then(|rows| Some(rows.focused_text(rows.focused_key()?)));
46 text.unwrap_or_default().to_string()
47 }
48
49 fn candidates_for(&self, typed: &str) -> Vec<&str> {
50 let hint = self.focused_rows().and_then(Hint::of_focused);
51 hint.map_or_else(Vec::new, |hint| matching(self.hints.answer(&hint), typed))
52 }
53
54 #[must_use]
56 pub fn candidates(&self) -> Vec<&str> {
57 self.candidates_for(&self.focused_typed())
58 }
59
60 #[must_use]
62 pub fn suggestion_line(&self, key: Option<String>) -> Option<String> {
63 let shown: Vec<&str> = self.candidates().into_iter().take(MAX_SHOWN).collect();
64 let label = key.map_or_else(|| "suggest".to_string(), |key| format!("suggest ({key})"));
65 (!shown.is_empty()).then(|| format!("{label}: {}", shown.join(", ")))
66 }
67
68 pub fn complete_hint(&mut self) {
71 let typed = self.focused_typed();
72 let prefix = match &self.completing {
73 Some((prefix, filled)) if *filled == typed => prefix.clone(),
74 _ => typed.clone(),
75 };
76 let next = completion(&self.candidates_for(&prefix), &typed).map(str::to_string);
77 if let Some(next) = next
78 && let Some(rows) = self.focused_rows_mut()
79 {
80 rows.set_focused_text(&next);
81 self.completing = Some((prefix, next));
82 }
83 }
84}