use super::Viewport;
use crate::browse::editor::{FilterEditor, LineEditor, ValueEditor};
use crate::browse::new_field::{NewField, NewFieldStep};
use crate::browse::state::{
Browser, Copied, EditorChoice, Failure, FilterTail, Load, Mode, Pane, BROWSE_DOCUMENT_LIMIT,
};
use crate::browse::tree::{FieldParent, Row};
use crate::browse::write::Edit;
use crate::errors::FsqError;
use crate::field_path::FieldPath;
use crate::render::cut_middle;
use ratatui::layout::{Constraint, Layout, Position, Rect};
use ratatui::style::Stylize;
use ratatui::text::{Line, Span};
use ratatui::Frame;
use std::borrow::Cow;
const BROWSE_ERROR_LINES: usize = 4;
const FILTER_PROMPT: &str = "/ ";
const FILTER_PLACEHOLDER: &str = "WHERE … ORDER BY … LIMIT …";
const NEW_FIELD_PROMPT: &str = "new field ";
const NEW_FIELD_PLACEHOLDER: &str = "name";
const HINT_SEPARATOR: &str = " · ";
impl Browser {
pub(super) fn draw_footer(&self, frame: &mut Frame, area: Rect, viewport: &mut Viewport) {
let boxed = matches!(
self.mode(),
Mode::Popup | Mode::Confirmation | Mode::ExternalEditor | Mode::FieldType
);
if let Some(editor) = self.edit().and_then(Edit::value_editor) {
let hints = Hints(vec![
Hint::new("Enter", "confirm", 2),
Hint::new("Esc", "cancel", 1),
]);
let prompt = format!("{} = ", FieldPath::from(editor.path()));
let decorations = Decorations {
prompt: &prompt,
placeholder: None,
ghost: None,
};
let cursor = editor
.line()
.draw(frame, area, viewport, decorations, hints);
if !boxed {
frame.set_cursor_position(cursor);
}
return;
}
if let Some(new_field) = self.new_field() {
if let NewFieldStep::Naming { line, .. } = new_field.step() {
let hints = Hints(vec![
Hint::new("Enter", "next", 2),
Hint::new("Esc", "cancel", 1),
]);
let prompt = match new_field.parent() {
FieldParent::Document => NEW_FIELD_PROMPT.to_string(),
FieldParent::Map(map) => {
format!("{NEW_FIELD_PROMPT}{}.", FieldPath::from(map))
}
};
let decorations = Decorations {
prompt: &prompt,
placeholder: Some(NEW_FIELD_PLACEHOLDER),
ghost: None,
};
let cursor = line.draw(frame, area, viewport, decorations, hints);
if !boxed {
frame.set_cursor_position(cursor);
}
return;
}
}
match (self.filter_editor(), boxed) {
(Some(editor), _) => {
let mut hints = vec![Hint::new("Enter", "run", 2), Hint::new("Esc", "cancel", 1)];
if self.failure() == Some(Failure::Query) {
hints.push(Hint::new("Ctrl-G", "error", 3));
}
let cursor = editor.draw(frame, area, viewport, Hints(hints));
if !boxed {
frame.set_cursor_position(cursor);
}
}
(None, true) => {
let mut hints = Vec::new();
if self.is_waiting() {
hints.push(Hint::new("Ctrl-C", "stop", 0));
}
let width = usize::from(area.width);
frame.render_widget(Hints(hints).after_note(viewport.copied, width), area);
}
(None, false) => self.draw_key_hints(frame, area, viewport.copied),
}
}
fn draw_key_hints(&self, frame: &mut Frame, area: Rect, copied: Option<Copied>) {
let mut hints = vec![
Hint::new("↑↓", "move", 1),
Hint::new("→", "open", 5),
Hint::new("Tab", "pane", 4),
Hint::new("/", "filter", 6),
];
if self.filter_on_cursor().is_some() {
hints.push(Hint::new("f", "where", 3));
}
if matches!(self.tree_cursor(), Some((_, Row::Field { .. }))) {
hints.push(Hint::new("y", "copy", 2));
}
if self.edits_at_cursor(EditorChoice::Fitting) {
hints.push(Hint::new("e", "edit", 3));
}
if self.deletion_at_cursor().is_some() {
hints.push(Hint::new("d", "delete", 2));
}
if self.new_field_parent().is_some() {
hints.push(Hint::new("a", "add", 2));
}
if self.focus() == Pane::Documents {
hints.push(Hint::new("n", "new", 2));
if self.level().selected_document().is_some() {
hints.push(Hint::new("D", "copy", 1));
}
}
if self.has_parent() {
hints.push(Hint::new("Esc", "back", 7));
}
if self.failure().is_some() {
hints.push(Hint::new("Ctrl-G", "error", 9));
}
if self.is_waiting() {
hints.push(Hint::new("Ctrl-C", "stop", 8));
}
let pinned = Hints(vec![Hint::new("?", "help", 0), Hint::new("q", "quit", 0)]);
let [left, right] =
Layout::horizontal([Constraint::Fill(1), Constraint::Length(pinned.columns())])
.spacing(2)
.areas(area);
let hints = Hints(hints).after_note(copied, usize::from(left.width));
frame.render_widget(hints, left);
frame.render_widget(pinned.line(), right);
}
pub(super) fn footer_error(&self, width: usize) -> Vec<Line<'static>> {
let rejected = self
.edit()
.and_then(Edit::value_editor)
.and_then(ValueEditor::error)
.or_else(|| self.new_field().and_then(NewField::error));
if let Some(error) = rejected {
return error.footer_lines(width);
}
let level = self.level();
let new_filter_failed =
matches!(level.load(), Load::Failed { filter, .. } if filter != level.filter());
let failure = match self.failure() {
Some(Failure::Query) if new_filter_failed && self.filter_editor().is_none() => None,
failure => failure,
};
failure
.and_then(|failure| self.error(failure))
.map(|error| error.footer_lines(width))
.unwrap_or_default()
}
}
impl FilterEditor {
fn draw(
&self,
frame: &mut Frame,
area: Rect,
viewport: &mut Viewport,
hints: Hints,
) -> Position {
let line = self.line();
let ghost = format!(" LIMIT {BROWSE_DOCUMENT_LIMIT}");
let has_limit = FilterTail::from(line.text()).has_limit();
let decorations = Decorations {
prompt: FILTER_PROMPT,
placeholder: Some(FILTER_PLACEHOLDER),
ghost: (!has_limit).then_some(ghost.as_str()),
};
line.draw(frame, area, viewport, decorations, hints)
}
}
struct Decorations<'a> {
prompt: &'a str,
placeholder: Option<&'static str>,
ghost: Option<&'a str>,
}
impl LineEditor {
fn draw(
&self,
frame: &mut Frame,
area: Rect,
viewport: &mut Viewport,
decorations: Decorations,
hints: Hints,
) -> Position {
let hints = hints.fitted(usize::from(area.width) / 2);
let [line_area, hints_area] =
Layout::horizontal([Constraint::Fill(1), Constraint::Length(hints.columns())])
.spacing(2)
.areas(area);
frame.render_widget(hints.line(), hints_area);
let text = self.text();
let prompt = cut_middle(decorations.prompt, usize::from(line_area.width) / 2);
let prompt_width = Span::from(prompt.as_str()).width();
let room = usize::from(line_area.width).saturating_sub(prompt_width);
let mut window = self.window(room, viewport.editor_start);
let ghost = decorations.ghost.filter(|ghost| {
!text.is_empty() && window.end == text.len() && room >= 2 * ghost.len()
});
if let Some(ghost) = ghost {
window = self.window(room - (ghost.len() - 1), viewport.editor_start);
}
viewport.editor_start = window.start;
let mut spans = vec![Span::from(prompt)];
if let (true, Some(placeholder)) = (text.is_empty(), decorations.placeholder) {
spans.push(Span::from(placeholder).dim());
}
if window.start > 0 {
spans.push(Span::from("…").dim());
}
spans.push(Span::from(text[window.start..window.end].to_string()));
match ghost {
_ if window.end < text.len() => spans.push(Span::from("…").dim()),
Some(ghost) => spans.push(Span::from(ghost.to_string()).dim()),
None => {}
}
frame.render_widget(Line::from(spans), line_area);
let column = u16::try_from(prompt_width + window.cursor_column).unwrap_or(u16::MAX);
Position::new(line_area.x.saturating_add(column), line_area.y)
}
}
impl FsqError {
fn footer_lines(&self, width: usize) -> Vec<Line<'static>> {
let text = format!("error: {self}");
let mut lines: Vec<String> = textwrap::wrap(&text, width.max(1))
.into_iter()
.map(Cow::into_owned)
.collect();
if lines.len() > BROWSE_ERROR_LINES {
lines.truncate(BROWSE_ERROR_LINES);
if let Some(last) = lines.last_mut() {
*last = format!(
"{}…",
console::truncate_str(last, width.saturating_sub(1), "")
);
}
}
lines
.into_iter()
.map(|line| Line::from(line).red())
.collect()
}
}
#[derive(Debug, Clone, Copy)]
pub(super) struct Hint {
key: &'static str,
action: &'static str,
priority: u8,
}
impl Hint {
pub(super) fn new(key: &'static str, action: &'static str, priority: u8) -> Self {
Self {
key,
action,
priority,
}
}
fn width(&self) -> usize {
Span::from(self.key).width() + 1 + Span::from(self.action).width()
}
}
pub(super) struct Hints(pub(super) Vec<Hint>);
impl Hints {
pub(super) fn fitted(mut self, width: usize) -> Self {
while self.width() > width {
let Some(lowest) = (0..self.0.len()).min_by_key(|&position| self.0[position].priority)
else {
break;
};
self.0.remove(lowest);
}
self
}
fn width(&self) -> usize {
let separators = self.0.len().saturating_sub(1) * Span::from(HINT_SEPARATOR).width();
self.0.iter().map(Hint::width).sum::<usize>() + separators
}
pub(super) fn columns(&self) -> u16 {
u16::try_from(self.width()).unwrap_or(u16::MAX)
}
fn after_note(self, copied: Option<Copied>, width: usize) -> Line<'static> {
let Some(copied) = copied else {
return self.fitted(width).line();
};
let note = match copied {
Copied::Value => "copied value",
Copied::Path => "copied path",
};
let separator = Span::from(HINT_SEPARATOR).dim();
let hints = self.fitted(width.saturating_sub(Span::from(note).width() + separator.width()));
let mut spans = vec![Span::from(note).dim()];
if !hints.0.is_empty() {
spans.push(separator);
}
spans.extend(hints.line().spans);
Line::from(spans)
}
pub(super) fn line(&self) -> Line<'static> {
let mut spans = Vec::new();
for (position, hint) in self.0.iter().enumerate() {
if position > 0 {
spans.push(Span::from(HINT_SEPARATOR).dim());
}
spans.push(Span::from(hint.key));
spans.push(Span::from(format!(" {}", hint.action)).dim());
}
Line::from(spans)
}
}