serpl 0.3.10

A simple terminal UI for search and replace, ala VS Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
use std::{
  collections::{HashMap, HashSet},
  default,
  time::Duration,
};

use color_eyre::{eyre::Result, owo_colors::OwoColorize};
use crossterm::event::{KeyCode, KeyEvent};
use ratatui::{prelude::*, style::Stylize, widgets::*};
use serde::{Deserialize, Serialize};
use tokio::sync::mpsc::UnboundedSender;
use tui_input::{backend::crossterm::EventHandler, Input};

use super::{Component, Frame};
use crate::{
  action::AppAction,
  components::search_result,
  config::{Config, KeyBindings},
  layout::get_layout,
  redux::{
    action::Action,
    state::{FocusedScreen, SearchResultState, State},
    thunk::ThunkAction,
  },
  tabs::Tab,
};

const DEBOUNCE_DURATION: Duration = Duration::from_millis(300);

#[derive(Default)]
pub struct SearchResult {
  command_tx: Option<UnboundedSender<AppAction>>,
  config: Config,
  state: ListState,
  match_counts: Vec<String>,
  search_input: Input,
  is_searching: bool,
  search_matches: Vec<usize>,
  current_match_index: usize,
  selected_files: HashSet<String>,
}

impl SearchResult {
  pub fn new() -> Self {
    Self::default()
  }

  fn toggle_select(&mut self, state: &State) {
    if let Some(file) = self.state.selected().and_then(|i| state.search_result.list.get(i)) {
      if !self.selected_files.remove(&file.path) {
        self.selected_files.insert(file.path.clone());
      }
    }
  }

  fn toggle_select_all(&mut self, state: &State) {
    if self.selected_files.len() == state.search_result.list.len() {
      self.selected_files.clear();
    } else {
      self.selected_files = state.search_result.list.iter().map(|f| f.path.clone()).collect();
    }
  }

  /// Indices of the marked files in descending order, so removing them one by one keeps the rest valid.
  fn marked_indices(&self, state: &State) -> Vec<usize> {
    let mut indices: Vec<usize> = state
      .search_result
      .list
      .iter()
      .enumerate()
      .filter(|(_, f)| self.selected_files.contains(&f.path))
      .map(|(i, _)| i)
      .collect();
    indices.reverse();
    indices
  }

  fn replace_selected_files(&mut self, state: &State) {
    let indices = self.marked_indices(state);
    self
      .command_tx
      .as_ref()
      .unwrap()
      .send(AppAction::Thunk(ThunkAction::ProcessSelectedFilesReplace(indices)))
      .unwrap();
    self.selected_files.clear();
  }

  fn delete_file(&mut self, state: &State) {
    if let Some(selected_index) = self.state.selected() {
      if selected_index < state.search_result.list.len() {
        let remove_file_from_list_thunk = AppAction::Thunk(ThunkAction::RemoveFileFromList(selected_index));
        self.command_tx.as_ref().unwrap().send(remove_file_from_list_thunk).unwrap();

        if state.search_result.list.len() > 1 {
          if selected_index >= state.search_result.list.len() - 1 {
            self.state.select(Some(state.search_result.list.len() - 2));
          } else {
            self.state.select(Some(selected_index));
          }
        } else {
          self.state.select(None);
        }

        self.update_selected_result(state);
      }
    }
  }

  fn next(&mut self, state: &State) {
    if state.search_result.list.is_empty() {
      return;
    }

    let new_index = match self.state.selected() {
      Some(i) => {
        if i >= state.search_result.list.len() - 1 {
          0
        } else {
          i + 1
        }
      },
      None => 0,
    };
    self.state.select(Some(new_index));
    self.update_selected_result(state);
  }

  fn previous(&mut self, state: &State) {
    if state.search_result.list.is_empty() {
      return;
    }

    let new_index = match self.state.selected() {
      Some(i) => {
        if i == 0 {
          state.search_result.list.len() - 1
        } else {
          i - 1
        }
      },
      None => state.search_result.list.len() - 1,
    };
    self.state.select(Some(new_index));
    self.update_selected_result(state);
  }

  fn update_selected_result(&mut self, state: &State) {
    if let Some(selected_index) = self.state.selected() {
      if let Some(selected_result) = state.search_result.list.get(selected_index) {
        let action = AppAction::Action(Action::SetSelectedResult {
          result: SearchResultState {
            index: Some(selected_index),
            path: selected_result.path.clone(),
            matches: selected_result.matches.clone(),
            total_matches: selected_result.total_matches,
          },
        });
        self.command_tx.as_ref().unwrap().send(action).unwrap();
      } else {
        let action = AppAction::Action(Action::SetSelectedResult { result: SearchResultState::default() });
        self.command_tx.as_ref().unwrap().send(action).unwrap();
        self.state.select(None);
      }
    } else {
      let action = AppAction::Action(Action::SetSelectedResult { result: SearchResultState::default() });
      self.command_tx.as_ref().unwrap().send(action).unwrap();
    }
  }

  fn set_selected_result(&mut self, state: &State) {
    if state.search_result.list.is_empty() {
      self.state.select(None);
      return;
    }

    if let Some(selected_index) = self.state.selected() {
      if selected_index >= state.search_result.list.len() {
        self.state.select(Some(state.search_result.list.len() - 1));
      }
    } else {
      self.state.select(Some(0));
    }

    self.update_selected_result(state);
  }

  fn top(&mut self, state: &State) {
    if state.search_result.list.is_empty() {
      return;
    }

    self.state.select(Some(0));
    let selected_result = state.search_result.list.first().unwrap();
    let action = AppAction::Action(Action::SetSelectedResult {
      result: SearchResultState {
        index: selected_result.index,
        path: selected_result.path.clone(),
        matches: selected_result.matches.clone(),
        total_matches: selected_result.total_matches,
      },
    });
    self.command_tx.as_ref().unwrap().send(action).unwrap();
  }

  fn bottom(&mut self, state: &State) {
    if state.search_result.list.is_empty() {
      return;
    }

    let i = state.search_result.list.len() - 1;
    self.state.select(Some(i));
    let selected_result = state.search_result.list.get(i).unwrap();
    let action = AppAction::Action(Action::SetSelectedResult {
      result: SearchResultState {
        index: selected_result.index,
        path: selected_result.path.clone(),
        matches: selected_result.matches.clone(),
        total_matches: selected_result.total_matches,
      },
    });
    self.command_tx.as_ref().unwrap().send(action).unwrap();
  }

  fn calculate_total_matches(&mut self, search_result_state: &SearchResultState) -> &str {
    let total_matches: usize = search_result_state.matches.iter().map(|m| m.submatches.len()).sum();
    let total_matches_str = total_matches.to_string();
    self.match_counts.push(total_matches_str);
    self.match_counts.last().unwrap()
  }

  fn replace_single_file(&mut self, state: &State) {
    if !self.selected_files.is_empty() {
      self.replace_selected_files(state);
      return;
    }
    if let Some(selected_index) = self.state.selected() {
      if selected_index < state.search_result.list.len() {
        let process_single_file_replace_thunk = AppAction::Thunk(ThunkAction::ProcessSingleFileReplace(selected_index));
        self.command_tx.as_ref().unwrap().send(process_single_file_replace_thunk).unwrap();
      }
    }
  }

  fn handle_local_key_events(&mut self, key: KeyEvent, state: &State) {
    match (key.code, key.modifiers) {
      (KeyCode::Char(' '), _) => {
        self.toggle_select(state);
      },
      (KeyCode::Char('a'), _) => {
        self.toggle_select_all(state);
      },
      (KeyCode::Char('d'), _) => {
        self.delete_file(state);
      },
      (KeyCode::Char('g') | KeyCode::Char('h') | KeyCode::Left, _) => {
        self.top(state);
      },
      (KeyCode::Char('G') | KeyCode::Char('l') | KeyCode::Right, _) => {
        self.bottom(state);
      },
      (KeyCode::Char('j') | KeyCode::Down, _) => {
        self.next(state);
      },
      (KeyCode::Char('k') | KeyCode::Up, _) => {
        self.previous(state);
      },
      (KeyCode::Char('r'), _) => {
        self.replace_single_file(state);
      },
      (KeyCode::Esc, _) => {
        self.is_searching = false;
        self.search_matches.clear();
        self.search_input.reset();
        self.current_match_index = 0;
      },
      (KeyCode::Enter, _) => {
        let action = AppAction::Action(Action::SetActiveTab { tab: Tab::Preview });
        self.command_tx.as_ref().unwrap().send(action).unwrap();
      },
      (KeyCode::Char('n'), _) => {
        self.next_match(state);
      },
      (KeyCode::Char('p'), _) => {
        self.previous_match(state);
      },
      _ => {},
    }
  }

  fn handle_search_input(&mut self, key: KeyEvent, state: &State) {
    match key.code {
      KeyCode::Esc | KeyCode::Enter => {
        self.is_searching = false;
      },
      _ => {
        self.search_input.handle_event(&crossterm::event::Event::Key(key));
        self.perform_search(state);
      },
    }
  }

  fn perform_search(&mut self, state: &State) {
    let search_term = self.search_input.value().to_lowercase();
    self.search_matches.clear();
    self.current_match_index = 0;

    for (index, result) in state.search_result.list.iter().enumerate() {
      if result.path.to_lowercase().contains(&search_term) {
        let result_index = result.index.unwrap();
        self.search_matches.push(result_index);
      }
    }
    log::info!("111Search matches: {:?}", self.search_matches);

    if !self.search_matches.is_empty() {
      self.state.select(Some(self.search_matches[0]));
      self.update_selected_result(state);
    }
  }

  fn next_match(&mut self, state: &State) {
    log::info!("Next match");
    log::info!("Search matches: {:?}", self.search_matches);
    if !self.search_matches.is_empty() {
      self.current_match_index = (self.current_match_index + 1) % self.search_matches.len();
      let next_index = self.search_matches[self.current_match_index];
      self.state.select(Some(next_index));
      self.update_selected_result(state);
    }
  }

  fn previous_match(&mut self, state: &State) {
    if !self.search_matches.is_empty() {
      self.current_match_index = (self.current_match_index + self.search_matches.len() - 1) % self.search_matches.len();
      let prev_index = self.search_matches[self.current_match_index];
      self.state.select(Some(prev_index));
      self.update_selected_result(state);
    }
  }
}

impl Component for SearchResult {
  fn register_action_handler(&mut self, tx: UnboundedSender<AppAction>) -> Result<()> {
    self.command_tx = Some(tx);
    Ok(())
  }

  fn register_config_handler(&mut self, config: Config) -> Result<()> {
    self.config = config;
    Ok(())
  }

  fn handle_key_events(&mut self, key: KeyEvent, state: &State) -> Result<Option<AppAction>> {
    if state.focused_screen == FocusedScreen::SearchResultList {
      match key.code {
        KeyCode::Char('/') => {
          self.is_searching = true;
          self.search_input.reset();
          Ok(None)
        },
        _ if self.is_searching => {
          self.handle_search_input(key, state);
          Ok(None)
        },
        _ => {
          self.handle_local_key_events(key, state);
          Ok(None)
        },
      }
    } else {
      Ok(None)
    }
  }

  fn draw(&mut self, f: &mut Frame<'_>, area: Rect, state: &State) -> Result<()> {
    let layout = get_layout(area);

    let block = Block::bordered().border_type(BorderType::Rounded).title(Line::from("Result List").left_aligned());
    let block = if state.focused_screen == FocusedScreen::SearchResultList {
      block.border_style(Style::default().fg(Color::Green).add_modifier(Modifier::BOLD))
    } else {
      block
    };

    let project_root = state.project_root.to_string_lossy();
    let results_to_display = &state.search_result.list;
    let search_term = self.search_input.value().to_lowercase();

    self.selected_files.retain(|p| results_to_display.iter().any(|f| &f.path == p));

    let list_items: Vec<ListItem> = results_to_display
      .iter()
      .enumerate()
      .map(|(index, s)| {
        let path = s.path.strip_prefix(format!("{project_root}/").as_str()).unwrap_or(&s.path);
        let mut spans = Vec::new();
        let mut start = 0;

        if self.selected_files.contains(&s.path) {
          spans.push(Span::styled("[x] ", Style::default().fg(Color::Green)));
        } else {
          spans.push(Span::raw("[ ] "));
        }

        if !search_term.is_empty() {
          for (idx, _) in path.to_lowercase().match_indices(&search_term) {
            if start < idx {
              spans.push(Span::raw(&path[start..idx]));
            }
            spans.push(Span::styled(
              &path[idx..idx + search_term.len()],
              Style::default().bg(Color::Yellow).fg(Color::Black),
            ));
            start = idx + search_term.len();
          }
        }

        if start < path.len() {
          spans.push(Span::raw(&path[start..]));
        }

        spans.push(Span::raw(" ("));
        spans.push(Span::styled(s.total_matches.to_string(), Style::default().fg(Color::Yellow)));
        spans.push(Span::raw(")"));

        ListItem::new(Line::from(spans))
      })
      .collect();

    let internal_selected = self.state.selected().unwrap_or(0);

    let details_widget = List::new(list_items)
      .style(Style::default().fg(Color::White))
      .highlight_style(Style::default().bg(Color::Blue))
      .block(block);
    f.render_stateful_widget(details_widget, layout.search_details, &mut self.state);

    if self.is_searching {
      let search_input = Paragraph::new(self.search_input.value())
        .style(Style::default().fg(Color::White))
        .block(Block::default().borders(Borders::ALL).title("Search"));
      let input_area = Rect::new(
        layout.search_details.x,
        layout.search_details.y + layout.search_details.height - 3,
        layout.search_details.width,
        3,
      );
      f.render_widget(search_input, input_area);
      f.set_cursor_position(Position { x: input_area.x + self.search_input.cursor() as u16 + 1, y: input_area.y + 1 });
    }

    Ok(())
  }
}