firestore-cli 0.3.0

fsq, a command line client for Google Firestore: a SQL REPL with tables, query plans and index statements, and a scripting mode with JSON output
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;

/// The most lines the footer gives an error, which can be a long message from Firestore.
const BROWSE_ERROR_LINES: usize = 4;

const FILTER_PROMPT: &str = "/ ";

/// What the filter editor shows while it is empty.
const FILTER_PLACEHOLDER: &str = "WHERE … ORDER BY … LIMIT …";

/// What the prompt for the name of a new field starts with, before the path of the map it goes
/// in.
const NEW_FIELD_PROMPT: &str = "new field ";

/// What the prompt for the name of a new field shows while the name is empty.
const NEW_FIELD_PLACEHOLDER: &str = "name";

const HINT_SEPARATOR: &str = " · ";

impl Browser {
    /// Draws the value editor, the prompt for the name of a new field or the filter editor while
    /// one is open, else the keys after the note of a copy. A popup, a list of types or a
    /// confirmation over the panes keeps its own keys, and only the stop of a load shows here,
    /// beside an editor without its cursor.
    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);
    }

    /// The error under the footer, wrapped at words to `width` columns: of the text the value
    /// editor could not read or the name of a new field that was refused, else the one Ctrl-G
    /// shows whole. A new filter that failed shows its error only under the editor: under the
    /// keys, it would sit beside the documents and the header of the filter before.
    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 {
    /// Draws the filter being edited after its prompt, and `hints`, the keys that end the edit, on
    /// the right. Returns where the cursor goes.
    fn draw(
        &self,
        frame: &mut Frame,
        area: Rect,
        viewport: &mut Viewport,
        hints: Hints,
    ) -> Position {
        let line = self.line();
        // The limit the query gets when the filter has none, after the column of the cursor at
        // the end, as the query would run.
        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)
    }
}

/// What the line of an editor shows around its text.
struct Decorations<'a> {
    prompt: &'a str,
    /// What shows dim while the text is empty.
    placeholder: Option<&'static str>,
    /// What shows dim after the end of the text. It takes room from the text only when the end
    /// of the text shows, and only on a line at least twice its width, so that a narrow line
    /// keeps its room for the text.
    ghost: Option<&'a str>,
}

impl LineEditor {
    /// Draws the text after the prompt of `decorations`, scrolled to keep the cursor in view, and
    /// `hints`, the keys that end the edit, on the right. Returns where the cursor goes.
    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();
        // The path of a deep field would leave no room for its value.
        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 {
    /// This error wrapped at words to `width` columns, in at most [`BROWSE_ERROR_LINES`] lines,
    /// the last of which ends in `…` when more of the error remains.
    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()
    }
}

/// A key and what it does, as the footer names it.
#[derive(Debug, Clone, Copy)]
pub(super) struct Hint {
    key: &'static str,
    action: &'static str,
    /// The hints that do not fit go lowest first.
    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()
    }
}

/// Hints in the order they show, their keys bright and what they do dim.
pub(super) struct Hints(pub(super) Vec<Hint>);

impl Hints {
    /// These hints without those of the lowest priority that do not fit in `width` columns.
    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)
    }

    /// These hints fitted to `width` columns after the note of what the last key `copied`, if it
    /// copied anything. The note is never dropped.
    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)
    }
}