@@ -0,0 +1,258 @@
1+use crate::compositor::{Component, Compositor, Context, EventResult};
2+use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
3+use tui::buffer::Buffer as Surface;
4+use tui::{
5+ layout::Rect,
6+ style::{Color, Style},
7+ widgets::{Block, Borders},
8+};
9+
10+use fuzzy_matcher::skim::SkimMatcherV2 as Matcher;
11+use fuzzy_matcher::FuzzyMatcher;
12+
13+use crate::ui::{Prompt, PromptEvent};
14+use helix_core::Position;
15+use helix_view::Editor;
16+
17+pub struct Picker<T> {
18+ options: Vec<T>,
19+ // filter: String,
20+ matcher: Box<Matcher>,
21+ /// (index, score)
22+ matches: Vec<(usize, i64)>,
23+
24+ cursor: usize,
25+ // pattern: String,
26+ prompt: Prompt,
27+
28+ format_fn: Box<dyn Fn(&T) -> &str>,
29+ callback_fn: Box<dyn Fn(&mut Editor, &T)>,
30+}
31+
32+impl<T> Picker<T> {
33+ pub fn new(
34+ options: Vec<T>,
35+ format_fn: impl Fn(&T) -> &str + 'static,
36+ callback_fn: impl Fn(&mut Editor, &T) + 'static,
37+ ) -> Self {
38+ let prompt = Prompt::new(
39+ "".to_string(),
40+ |pattern: &str| Vec::new(),
41+ |editor: &mut Editor, pattern: &str, event: PromptEvent| {
42+ //
43+ },
44+ );
45+
46+ let mut picker = Self {
47+ options,
48+ matcher: Box::new(Matcher::default()),
49+ matches: Vec::new(),
50+ cursor: 0,
51+ prompt,
52+ format_fn: Box::new(format_fn),
53+ callback_fn: Box::new(callback_fn),
54+ };
55+
56+ // TODO: scoring on empty input should just use a fastpath
57+ picker.score();
58+
59+ picker
60+ }
61+
62+ pub fn score(&mut self) {
63+ // need to borrow via pattern match otherwise it complains about simultaneous borrow
64+ let Self {
65+ ref mut options,
66+ ref mut matcher,
67+ ref mut matches,
68+ ref format_fn,
69+ ..
70+ } = *self;
71+
72+ let pattern = &self.prompt.line;
73+
74+ // reuse the matches allocation
75+ matches.clear();
76+ matches.extend(
77+ self.options
78+ .iter()
79+ .enumerate()
80+ .filter_map(|(index, option)| {
81+ // TODO: maybe using format_fn isn't the best idea here
82+ let text = (format_fn)(option);
83+ // TODO: using fuzzy_indices could give us the char idx for match highlighting
84+ matcher
85+ .fuzzy_match(text, pattern)
86+ .map(|score| (index, score))
87+ }),
88+ );
89+ matches.sort_unstable_by_key(|(_, score)| -score);
90+
91+ // reset cursor position
92+ self.cursor = 0;
93+ }
94+
95+ pub fn move_up(&mut self) {
96+ self.cursor = self.cursor.saturating_sub(1);
97+ }
98+
99+ pub fn move_down(&mut self) {
100+ // TODO: len - 1
101+ if self.cursor < self.options.len() {
102+ self.cursor += 1;
103+ }
104+ }
105+
106+ pub fn selection(&self) -> Option<&T> {
107+ self.matches
108+ .get(self.cursor)
109+ .map(|(index, _score)| &self.options[*index])
110+ }
111+}
112+
113+// process:
114+// - read all the files into a list, maxed out at a large value
115+// - on input change:
116+// - score all the names in relation to input
117+
118+impl<T> Component for Picker<T> {
119+ fn handle_event(&mut self, event: Event, cx: &mut Context) -> EventResult {
120+ let key_event = match event {
121+ Event::Key(event) => event,
122+ Event::Resize(..) => return EventResult::Consumed(None),
123+ _ => return EventResult::Ignored,
124+ };
125+
126+ let close_fn = EventResult::Consumed(Some(Box::new(|compositor: &mut Compositor| {
127+ // remove the layer
128+ compositor.pop();
129+ })));
130+
131+ match key_event {
132+ // KeyEvent {
133+ // code: KeyCode::Char(c),
134+ // modifiers: KeyModifiers::NONE,
135+ // } => {
136+ // self.insert_char(c);
137+ // (self.callback_fn)(cx.editor, &self.line, PromptEvent::Update);
138+ // }
139+ KeyEvent {
140+ code: KeyCode::Up, ..
141+ }
142+ | KeyEvent {
143+ code: KeyCode::Char('k'),
144+ modifiers: KeyModifiers::CONTROL,
145+ } => self.move_up(),
146+ KeyEvent {
147+ code: KeyCode::Down,
148+ ..
149+ }
150+ | KeyEvent {
151+ code: KeyCode::Char('j'),
152+ modifiers: KeyModifiers::CONTROL,
153+ } => self.move_down(),
154+ KeyEvent {
155+ code: KeyCode::Esc, ..
156+ } => {
157+ return close_fn;
158+ }
159+ KeyEvent {
160+ code: KeyCode::Enter,
161+ ..
162+ } => {
163+ if let Some(option) = self.selection() {
164+ (self.callback_fn)(&mut cx.editor, option);
165+ }
166+ return close_fn;
167+ }
168+ _ => {
169+ match self.prompt.handle_event(event, cx) {
170+ EventResult::Consumed(_) => {
171+ // TODO: recalculate only if pattern changed
172+ self.score();
173+ }
174+ _ => (),
175+ }
176+ }
177+ }
178+
179+ EventResult::Consumed(None)
180+ }
181+
182+ fn render(&self, area: Rect, surface: &mut Surface, cx: &mut Context) {
183+ let padding_vertical = area.height * 20 / 100;
184+ let padding_horizontal = area.width * 20 / 100;
185+
186+ let area = Rect::new(
187+ area.x + padding_horizontal,
188+ area.y + padding_vertical,
189+ area.width - padding_horizontal * 2,
190+ area.height - padding_vertical * 2,
191+ );
192+
193+ // -- Render the frame:
194+
195+ // clear area
196+ for y in area.top()..area.bottom() {
197+ for x in area.left()..area.right() {
198+ surface.get_mut(x, y).reset()
199+ }
200+ }
201+
202+ use tui::widgets::Widget;
203+ // don't like this but the lifetime sucks
204+ let block = Block::default().borders(Borders::ALL);
205+
206+ // calculate the inner area inside the box
207+ let inner = block.inner(area);
208+
209+ block.render(area, surface);
210+ // TODO: abstract into a clear(area) fn
211+ // surface.set_style(inner, Style::default().bg(Color::Rgb(150, 50, 0)));
212+
213+ // -- Render the input bar:
214+
215+ let area = Rect::new(inner.x + 1, inner.y, inner.width - 1, 1);
216+ self.prompt.render(area, surface, cx);
217+
218+ // -- Separator
219+ use tui::widgets::BorderType;
220+ let style = Style::default().fg(Color::Rgb(90, 89, 119));
221+ let symbols = BorderType::line_symbols(BorderType::Plain);
222+ for x in inner.left()..inner.right() {
223+ surface
224+ .get_mut(x, inner.y + 1)
225+ .set_symbol(symbols.horizontal)
226+ .set_style(style);
227+ }
228+
229+ // -- Render the contents:
230+
231+ let style = Style::default().fg(Color::Rgb(164, 160, 232)); // lavender
232+ let selected = Style::default().fg(Color::Rgb(255, 255, 255));
233+
234+ let rows = inner.height - 2; // -1 for search bar
235+
236+ let files = self.matches.iter().map(|(index, _score)| {
237+ (index, self.options.get(*index).unwrap()) // get_unchecked
238+ });
239+
240+ for (i, (_index, option)) in files.take(rows as usize).enumerate() {
241+ if i == self.cursor {
242+ surface.set_string(inner.x + 1, inner.y + 2 + i as u16, ">", selected);
243+ }
244+
245+ surface.set_stringn(
246+ inner.x + 3,
247+ inner.y + 2 + i as u16,
248+ (self.format_fn)(option),
249+ inner.width as usize - 1,
250+ if i == self.cursor { selected } else { style },
251+ );
252+ }
253+ }
254+
255+ fn cursor_position(&self, area: Rect, ctx: &mut Context) -> Option<Position> {
256+ self.prompt.cursor_position(area, ctx)
257+ }
258+}