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;
14 fn sort_text(&self) -> &str;
15 fn filter_text(&self) -> &str;
17 fn label(&self) -> &str;
21pub struct Menu<T: Item> {
24 cursor: Option<usize>,
26 matcher: Box<Matcher>,
28 matches: Vec<(usize, i64)>,
30 widths: Vec<Constraint>,
32 callback_fn: Box<dyn Fn(&mut Editor, Option<&T>, MenuEvent)>,
38impl<T: Item> Menu<T> {
39 // TODO: it's like a slimmed down picker, share code? (picker = menu + prompt with different
43 callback_fn: impl Fn(&mut Editor, Option<&T>, MenuEvent) + 'static,
47 matcher: Box::new(Matcher::default()),
51 callback_fn: Box::new(callback_fn),
56 // TODO: scoring on empty input should just use a fastpath
62 pub fn score(&mut self, pattern: &str) {
63 // need to borrow via pattern match otherwise it complains about simultaneous borrow
71 // reuse the matches allocation
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
77 .fuzzy_match(text, pattern)
78 .map(|score| (index, score))
80 // matches.sort_unstable_by_key(|(_, score)| -score);
81 matches.sort_unstable_by_key(|(index, _score)| options[*index].sort_text());
83 // reset cursor position
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);
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);
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) {
108 scroll += cursor - (win_height + scroll).saturating_sub(1)
109 } else if cursor < scroll {
113 self.scroll = scroll;
117 pub fn selection(&self) -> Option<&T> {
118 self.cursor.and_then(|cursor| {
121 .map(|(index, _score)| &self.options[*index])
125 pub fn is_empty(&self) -> bool {
126 self.matches.is_empty()
129 pub fn len(&self) -> usize {
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,
143 let close_fn = EventResult::Consumed(Some(Box::new(|compositor: &mut Compositor| {
149 // esc or ctrl-c aborts the completion and closes the menu
151 code: KeyCode::Esc, ..
154 code: KeyCode::Char('c'),
155 modifiers: KeyModifiers::CONTROL,
157 (self.callback_fn)(cx.editor, self.selection(), MenuEvent::Abort);
160 // arrow up/ctrl-p/shift-tab prev completion choice (including updating the doc)
162 code: KeyCode::BackTab,
166 code: KeyCode::Up, ..
169 code: KeyCode::Char('p'),
170 modifiers: KeyModifiers::CONTROL,
173 (self.callback_fn)(cx.editor, self.selection(), MenuEvent::Update);
174 return EventResult::Consumed(None);
176 // arrow down/ctrl-n/tab advances completion choice (including updating the doc)
179 modifiers: KeyModifiers::NONE,
186 code: KeyCode::Char('n'),
187 modifiers: KeyModifiers::CONTROL,
190 (self.callback_fn)(cx.editor, self.selection(), MenuEvent::Update);
191 return EventResult::Consumed(None);
194 code: KeyCode::Enter,
197 if let Some(selection) = self.selection() {
198 (self.callback_fn)(cx.editor, Some(selection), MenuEvent::Validate);
203 // code: KeyCode::Char(c),
204 // modifiers: KeyModifiers::NONE,
206 // self.insert_char(c);
207 // (self.callback_fn)(cx.editor, &self.line, MenuEvent::Update);
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
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)
223 fn required_size(&mut self, viewport: (u16, u16)) -> Option<(u16, u16)> {
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();
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
246 .map(|len| Constraint::Length(len as u16))
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();
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
270 .map(|(index, _score)| {
271 // (index, self.options.get(*index).unwrap()) // get_unchecked
272 &self.options[*index] // get_unchecked
276 let len = options.len();
278 let win_height = area.height as usize;
280 const fn div_ceil(a: usize, b: usize) -> usize {
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)
292 .highlight_style(selected)
294 .widths(&self.widths);
296 use tui::widgets::TableState;
303 selected: self.cursor,
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),
315 for (i, _) in (scroll..(scroll + win_height).min(len)).enumerate() {
316 let is_marked = i >= scroll_line && i < scroll_line + scroll_height;
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 });
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list