on 2158366 help sign in
326 lines 10 kB history raw
1use crate::compositor::{Component, Compositor, Context, EventResult};
2use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
3use tui::{buffer::Buffer as Surface, widgets::Table};
5pub use tui::widgets::{Cell, Row};
7use fuzzy_matcher::skim::SkimMatcherV2 as Matcher;
8use fuzzy_matcher::FuzzyMatcher;
10use helix_view::{graphics::Rect, Editor};
11use tui::layout::Constraint;
13pub trait Item {
14 fn sort_text(&self) -> &str;
15 fn filter_text(&self) -> &str;
17 fn label(&self) -> &str;
18 fn row(&self) -> Row;
21pub struct Menu<T: Item> {
22 options: Vec<T>,
24 cursor: Option<usize>,
26 matcher: Box<Matcher>,
27 /// (index, score)
28 matches: Vec<(usize, i64)>,
30 widths: Vec<Constraint>,
32 callback_fn: Box<dyn Fn(&mut Editor, Option<&T>, MenuEvent)>,
34 scroll: usize,
35 size: (u16, u16),
38impl<T: Item> Menu<T> {
39 // TODO: it's like a slimmed down picker, share code? (picker = menu + prompt with different
40 // rendering)
41 pub fn new(
42 options: Vec<T>,
43 callback_fn: impl Fn(&mut Editor, Option<&T>, MenuEvent) + 'static,
44 ) -> Self {
45 let mut menu = Self {
46 options,
47 matcher: Box::new(Matcher::default()),
48 matches: Vec::new(),
49 cursor: None,
50 widths: Vec::new(),
51 callback_fn: Box::new(callback_fn),
52 scroll: 0,
53 size: (0, 0),
54 };
56 // TODO: scoring on empty input should just use a fastpath
57 menu.score("");
59 menu
60 }
62 pub fn score(&mut self, pattern: &str) {
63 // need to borrow via pattern match otherwise it complains about simultaneous borrow
64 let Self {
65 ref mut matcher,
66 ref mut matches,
67 ref options,
68 ..
69 } = *self;
71 // reuse the matches allocation
72 matches.clear();
73 matches.extend(options.iter().enumerate().filter_map(|(index, option)| {
74 let text = option.filter_text();
75 // TODO: using fuzzy_indices could give us the char idx for match highlighting
76 matcher
77 .fuzzy_match(text, pattern)
78 .map(|score| (index, score))
79 }));
80 // matches.sort_unstable_by_key(|(_, score)| -score);
81 matches.sort_unstable_by_key(|(index, _score)| options[*index].sort_text());
83 // reset cursor position
84 self.cursor = None;
85 self.scroll = 0;
86 }
88 pub fn move_up(&mut self) {
89 let len = self.matches.len();
90 let pos = self.cursor.map_or(0, |i| (i + len.saturating_sub(1)) % len) % len;
91 self.cursor = Some(pos);
92 self.adjust_scroll();
93 }
95 pub fn move_down(&mut self) {
96 let len = self.matches.len();
97 let pos = self.cursor.map_or(0, |i| i + 1) % len;
98 self.cursor = Some(pos);
99 self.adjust_scroll();
100 }
102 fn adjust_scroll(&mut self) {
103 let win_height = self.size.1 as usize;
104 if let Some(cursor) = self.cursor {
105 let mut scroll = self.scroll;
106 if cursor > (win_height + scroll).saturating_sub(1) {
107 // scroll down
108 scroll += cursor - (win_height + scroll).saturating_sub(1)
109 } else if cursor < scroll {
110 // scroll up
111 scroll = cursor
112 }
113 self.scroll = scroll;
114 }
115 }
117 pub fn selection(&self) -> Option<&T> {
118 self.cursor.and_then(|cursor| {
119 self.matches
120 .get(cursor)
121 .map(|(index, _score)| &self.options[*index])
122 })
123 }
125 pub fn is_empty(&self) -> bool {
126 self.matches.is_empty()
127 }
129 pub fn len(&self) -> usize {
130 self.matches.len()
131 }
134use super::PromptEvent as MenuEvent;
136impl<T: Item + 'static> Component for Menu<T> {
137 fn handle_event(&mut self, event: Event, cx: &mut Context) -> EventResult {
138 let event = match event {
139 Event::Key(event) => event,
140 _ => return EventResult::Ignored,
141 };
143 let close_fn = EventResult::Consumed(Some(Box::new(|compositor: &mut Compositor| {
144 // remove the layer
145 compositor.pop();
146 })));
148 match event {
149 // esc or ctrl-c aborts the completion and closes the menu
150 KeyEvent {
151 code: KeyCode::Esc, ..
152 }
153 | KeyEvent {
154 code: KeyCode::Char('c'),
155 modifiers: KeyModifiers::CONTROL,
156 } => {
157 (self.callback_fn)(cx.editor, self.selection(), MenuEvent::Abort);
158 return close_fn;
159 }
160 // arrow up/ctrl-p/shift-tab prev completion choice (including updating the doc)
161 KeyEvent {
162 code: KeyCode::BackTab,
163 ..
164 }
165 | KeyEvent {
166 code: KeyCode::Up, ..
167 }
168 | KeyEvent {
169 code: KeyCode::Char('p'),
170 modifiers: KeyModifiers::CONTROL,
171 } => {
172 self.move_up();
173 (self.callback_fn)(cx.editor, self.selection(), MenuEvent::Update);
174 return EventResult::Consumed(None);
175 }
176 // arrow down/ctrl-n/tab advances completion choice (including updating the doc)
177 KeyEvent {
178 code: KeyCode::Tab,
179 modifiers: KeyModifiers::NONE,
180 }
181 | KeyEvent {
182 code: KeyCode::Down,
183 ..
184 }
185 | KeyEvent {
186 code: KeyCode::Char('n'),
187 modifiers: KeyModifiers::CONTROL,
188 } => {
189 self.move_down();
190 (self.callback_fn)(cx.editor, self.selection(), MenuEvent::Update);
191 return EventResult::Consumed(None);
192 }
193 KeyEvent {
194 code: KeyCode::Enter,
195 ..
196 } => {
197 if let Some(selection) = self.selection() {
198 (self.callback_fn)(cx.editor, Some(selection), MenuEvent::Validate);
199 }
200 return close_fn;
201 }
202 // KeyEvent {
203 // code: KeyCode::Char(c),
204 // modifiers: KeyModifiers::NONE,
205 // } => {
206 // self.insert_char(c);
207 // (self.callback_fn)(cx.editor, &self.line, MenuEvent::Update);
208 // }
210 // / -> edit_filter?
211 //
212 // enter confirms the match and closes the menu
213 // typing filters the menu
214 // if we run out of options the menu closes itself
215 _ => (),
216 }
217 // for some events, we want to process them but send ignore, specifically all input except
218 // tab/enter/ctrl-k or whatever will confirm the selection/ ctrl-n/ctrl-p for scroll.
219 // EventResult::Consumed(None)
220 EventResult::Ignored
221 }
223 fn required_size(&mut self, viewport: (u16, u16)) -> Option<(u16, u16)> {
224 let n = self
225 .options
226 .first()
227 .map(|option| option.row().cells.len())
228 .unwrap_or_default();
229 let max_lens = self.options.iter().fold(vec![0; n], |mut acc, option| {
230 let row = option.row();
231 // maintain max for each column
232 for (acc, cell) in acc.iter_mut().zip(row.cells.iter()) {
233 let width = cell.content.width();
234 if width > *acc {
235 *acc = width;
236 }
237 }
239 acc
240 });
241 let len = max_lens.iter().sum::<usize>() + n + 1; // +1: reserve some space for scrollbar
242 let width = len.min(viewport.0 as usize);
244 self.widths = max_lens
245 .into_iter()
246 .map(|len| Constraint::Length(len as u16))
247 .collect();
249 let height = self.options.len().min(10).min(viewport.1 as usize);
251 self.size = (width as u16, height as u16);
253 // adjust scroll offsets if size changed
254 self.adjust_scroll();
256 Some(self.size)
257 }
259 // TODO: required size should re-trigger when we filter items so we can draw a smaller menu
261 fn render(&mut self, area: Rect, surface: &mut Surface, cx: &mut Context) {
262 let style = cx.editor.theme.get("ui.text");
263 let selected = cx.editor.theme.get("ui.menu.selected");
265 let scroll = self.scroll;
267 let options: Vec<_> = self
268 .matches
269 .iter()
270 .map(|(index, _score)| {
271 // (index, self.options.get(*index).unwrap()) // get_unchecked
272 &self.options[*index] // get_unchecked
273 })
274 .collect();
276 let len = options.len();
278 let win_height = area.height as usize;
280 const fn div_ceil(a: usize, b: usize) -> usize {
281 (a + b - 1) / a
282 }
284 let scroll_height = std::cmp::min(div_ceil(win_height.pow(2), len), win_height as usize);
286 let scroll_line = (win_height - scroll_height) * scroll
287 / std::cmp::max(1, len.saturating_sub(win_height));
289 let rows = options.iter().map(|option| option.row());
290 let table = Table::new(rows)
291 .style(style)
292 .highlight_style(selected)
293 .column_spacing(1)
294 .widths(&self.widths);
296 use tui::widgets::TableState;
298 table.render_table(
299 area,
300 surface,
301 &mut TableState {
302 offset: scroll,
303 selected: self.cursor,
304 },
305 );
307 // // TODO: set bg for the whole row if selected
308 // if line == self.cursor {
309 // surface.set_style(
310 // Rect::new(area.x, area.y + i as u16, area.width - 1, 1),
311 // selected,
312 // )
313 // }
315 for (i, _) in (scroll..(scroll + win_height).min(len)).enumerate() {
316 let is_marked = i >= scroll_line && i < scroll_line + scroll_height;
318 if is_marked {
319 let cell = surface.get_mut(area.x + area.width - 2, area.y + i as u16);
320 cell.set_symbol("▐ ");
321 // cell.set_style(selected);
322 // cell.set_style(if is_marked { selected } else { style });
323 }
324 }
325 }