use super::state::FilterTail;
use ratatui::buffer::CellWidth;
use reedline::LineBuffer;
use unicode_segmentation::UnicodeSegmentation;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Edit {
Insert(char),
DeleteBefore,
DeleteAfter,
DeleteWordBefore,
DeleteToStart,
Left,
Right,
Start,
End,
}
const FILTER_HISTORY_LIMIT: usize = 100;
#[derive(Debug, Default)]
pub struct FilterHistory(Vec<FilterTail>);
impl FilterHistory {
pub fn add(&mut self, filter: &FilterTail) {
if filter.is_empty() {
return;
}
self.0.retain(|kept| kept != filter);
self.0.push(filter.clone());
if self.0.len() > FILTER_HISTORY_LIMIT {
self.0.remove(0);
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Recall {
Older,
Newer,
}
#[derive(Debug)]
pub struct FilterEditor {
line: LineBuffer,
recalled: Option<Recalled>,
}
#[derive(Debug)]
struct Recalled {
back: usize,
draft: String,
}
impl FilterEditor {
pub fn recall(&mut self, recall: Recall, history: &FilterHistory) {
let Some(oldest) = history.0.len().checked_sub(1) else {
return;
};
let back = match (self.recalled.as_ref().map(|recalled| recalled.back), recall) {
(None, Recall::Older) => Some(0),
(None, Recall::Newer) => return,
(Some(back), Recall::Older) => Some((back + 1).min(oldest)),
(Some(back), Recall::Newer) => back.checked_sub(1),
};
let draft = match self.recalled.take() {
Some(recalled) => recalled.draft,
None => self.text().to_string(),
};
let text = match back {
Some(back) => {
let filter = history.0[oldest - back].to_string();
self.recalled = Some(Recalled { back, draft });
filter
}
None => draft,
};
self.line = LineBuffer::from(text.as_str());
}
pub fn apply(&mut self, edit: Edit) {
match edit {
Edit::Insert(typed) => self.line.insert_char(typed),
Edit::DeleteBefore => self.line.delete_left_grapheme(),
Edit::DeleteAfter => self.line.delete_right_grapheme(),
Edit::DeleteWordBefore => self.line.delete_word_left(),
Edit::DeleteToStart => self.line.clear_to_insertion_point(),
Edit::Left => self.line.move_left(),
Edit::Right => self.line.move_right(),
Edit::Start => self.line.move_to_start(),
Edit::End => self.line.move_to_end(),
}
}
pub fn paste(&mut self, pasted: &str) {
let line = pasted.replace("\r\n", " ").replace(char::is_control, " ");
self.line.insert_str(&line);
}
pub fn text(&self) -> &str {
self.line.get_buffer()
}
pub fn cursor(&self) -> usize {
self.line.insertion_point()
}
pub fn window(&self, width: usize, from: usize) -> Window {
let stops = Stops::of(self.text());
let cursor = stops.at_or_after(self.cursor());
let mut start = stops.at_or_before(from).min(cursor);
while start < cursor && !stops.shows(start, cursor, width) {
start += 1;
}
while start > 0
&& stops.end(start, width) == stops.last()
&& stops.need(start - 1, stops.last()) <= width
{
start -= 1;
}
Window {
start: stops.byte(start),
end: stops.byte(stops.end(start, width)),
cursor_column: usize::from(start > 0) + stops.column(cursor) - stops.column(start),
}
}
}
struct Stops(Vec<Stop>);
struct Stop {
byte: usize,
column: usize,
}
impl Stops {
fn of(text: &str) -> Self {
let mut stops = Vec::new();
let mut column = 0;
for (byte, grapheme) in text.grapheme_indices(true) {
let width = if grapheme.contains(char::is_control) {
0
} else {
usize::from(grapheme.cell_width())
};
if width > 0 {
stops.push(Stop { byte, column });
}
column += width;
}
stops.push(Stop {
byte: text.len(),
column,
});
Self(stops)
}
fn last(&self) -> usize {
self.0.len() - 1
}
fn byte(&self, stop: usize) -> usize {
self.0[stop].byte
}
fn column(&self, stop: usize) -> usize {
self.0[stop].column
}
fn at_or_after(&self, byte: usize) -> usize {
self.0
.partition_point(|stop| stop.byte < byte)
.min(self.last())
}
fn at_or_before(&self, byte: usize) -> usize {
self.0
.partition_point(|stop| stop.byte <= byte)
.saturating_sub(1)
}
fn need(&self, start: usize, end: usize) -> usize {
usize::from(start > 0) + self.column(end) - self.column(start) + 1
}
fn end(&self, start: usize, width: usize) -> usize {
(start + 1..=self.last())
.take_while(|&end| self.need(start, end) <= width)
.last()
.unwrap_or(start)
}
fn shows(&self, start: usize, cursor: usize, width: usize) -> bool {
let end = self.end(start, width);
cursor < end || cursor == self.last() && end == self.last()
}
}
impl From<&FilterTail> for FilterEditor {
fn from(filter: &FilterTail) -> Self {
Self {
line: LineBuffer::from(filter.to_string().as_str()),
recalled: None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Window {
pub start: usize,
pub end: usize,
pub cursor_column: usize,
}
#[cfg(test)]
mod tests {
use super::*;
const LONG_FILTER: &str =
"WHERE genre = 'Science fiction' AND pages BETWEEN 200 AND 900 ORDER BY rating DESC";
fn editor(text: &str) -> FilterEditor {
FilterEditor::from(&FilterTail::from(text))
}
fn edited(text: &str, edits: &[Edit]) -> FilterEditor {
let mut editor = editor(text);
for edit in edits {
editor.apply(*edit);
}
editor
}
fn shown(editor: &FilterEditor, window: Window) -> &str {
&editor.text()[window.start..window.end]
}
#[test]
fn a_wide_character_takes_two_columns_of_the_window() {
let editor = editor(&"名前".repeat(20));
let window = editor.window(21, 0);
assert_eq!(
shown(&editor, window),
"名前".repeat(5).chars().skip(1).collect::<String>()
);
assert_eq!(window.cursor_column, 19);
}
#[test]
fn the_cursor_column_counts_each_grapheme_as_wide_as_it_is_drawn() {
for emoji in ["👍🏽", "👨👩👧", "❤️"] {
let editor = editor(&format!("WHERE t = '{emoji}'"));
let window = editor.window(40, 0);
assert_eq!(window.cursor_column, "WHERE t = ''".len() + 2, "{emoji}");
}
}
#[test]
fn a_paste_goes_in_at_the_cursor_as_one_line() {
let mut editor = edited("WHERE ORDER BY title", &[Edit::Start]);
for _ in 0.."WHERE ".len() {
editor.apply(Edit::Right);
}
editor.paste("genre = 'sf'\r\nAND\tpages > 100\n");
assert_eq!(
editor.text(),
"WHERE genre = 'sf' AND pages > 100 ORDER BY title"
);
}
#[test]
fn a_text_that_fits_shows_whole() {
let editor = editor("WHERE pages > 100");
let window = editor.window(40, 0);
assert_eq!(shown(&editor, window), "WHERE pages > 100");
assert_eq!(window.cursor_column, "WHERE pages > 100".len());
}
#[test]
fn a_long_text_shows_its_end_with_the_cursor_at_the_end() {
let editor = editor(LONG_FILTER);
let window = editor.window(40, 0);
assert_eq!(window.end, LONG_FILTER.len());
assert!(LONG_FILTER.ends_with(shown(&editor, window)));
assert_eq!(window.cursor_column, 39);
assert_eq!(1 + shown(&editor, window).len() + 1, 40);
}
#[test]
fn the_window_scrolls_only_once_the_cursor_reaches_its_edge() {
let mut editor = editor(LONG_FILTER);
let at_end = editor.window(40, 0);
editor.apply(Edit::Left);
let one_left = editor.window(40, at_end.start);
assert_eq!(one_left.start, at_end.start);
assert_eq!(one_left.cursor_column, at_end.cursor_column - 1);
editor.apply(Edit::Start);
let at_start = editor.window(40, one_left.start);
assert_eq!(at_start.start, 0);
assert_eq!(at_start.cursor_column, 0);
assert!(at_start.end < LONG_FILTER.len());
for _ in 0..60 {
editor.apply(Edit::Right);
}
let moved = editor.window(40, at_start.start);
assert!(moved.start > 0);
assert!(moved.start <= editor.cursor() && editor.cursor() < moved.end);
assert_eq!(moved.cursor_column, 38);
}
#[test]
fn a_text_that_shrinks_scrolls_back_to_fill_the_line() {
let mut editor = editor(LONG_FILTER);
let at_end = editor.window(40, 0);
for _ in 0..50 {
editor.apply(Edit::DeleteBefore);
}
let window = editor.window(40, at_end.start);
assert_eq!(window.start, 0);
assert_eq!(
shown(&editor, window),
&LONG_FILTER[..LONG_FILTER.len() - 50]
);
}
}