Lines
97.78 %
Functions
50 %
Branches
100 %
//! Generic input form used by all overlay modals that collect user input.
//!
//! Replaces the per-modal `ConfigSetModal` duplicates.
//! [`Form`] is a list of [`Field`]s with a focused index and a [`FormKind`]
//! that identifies the submit target.
mod descriptor;
mod filter_field;
mod filter_row;
mod options;
mod pointer;
mod suggest;
use forms::FormValues;
pub use filter_row::RowShape;
pub use options::OPTIONS_BUTTONS;
use crate::event::Intent;
use crate::modal::Spec;
use crate::overlay::Placement;
use crate::tabs::reports::ReportKind;
use crate::widgets::{Editor, Hints, SelectOption, SelectWidget, Widget, WidgetKind};
use crate::window::Origin;
#[cfg(test)]
mod tests;
/// The buttons of a form dialog, in focus order, and the intent each presses.
pub const BUTTONS: [Spec; 2] = [("~O~K", Intent::Submit), ("~C~lose", Intent::CloseTopmost)];
/// A single labelled input field.
#[derive(Debug)]
pub struct Field {
/// Descriptor key for descriptor-backed forms; `None` for hand-built ones.
pub key: Option<&'static str>,
pub label: &'static str,
pub widget: Widget,
}
/// What to do when the form is submitted.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FormKind {
ConfigSet,
/// The Options dialog: theme, keymap and colour depth.
Options,
/// Register a public key for the SSH keys tab.
SshKeyAdd,
/// Ask for the path the shown CSV is saved to.
CsvSave,
Report(ReportKind),
TagCreate,
/// Edit an existing tag; its id and revision are hidden values.
TagEdit,
TemplateCreate,
/// Edit an existing template; its id and revision are hidden values.
TemplateEdit,
ScriptCreate,
/// Edit an existing script; its id and revision are hidden values.
ScriptEdit,
/// Pick the template a new transaction starts from.
TemplatePick,
CommodityCreate,
CommodityConvert,
AccountCreate,
TransactionCreate,
/// Edit an existing transaction; its id and revision are hidden values.
TransactionEdit,
/// Edit an existing account; its id and revision are hidden values.
AccountEdit,
/// Edit an existing commodity; its id and revision are hidden values.
CommodityEdit,
/// Merge one account into another, after a confirmation.
AccountMerge,
/// The Transactions tab filter: the `transaction-query` fields minus paging.
TransactionFilter,
/// Pick the kind of a new filter builder row.
FilterAdd,
/// Fill one filter builder row.
FilterRow(RowShape),
/// A generic multi-field input form.
pub struct Form {
pub fields: Vec<Field>,
/// The stop of the focus ring: a field, or past the last field one of the form's buttons.
pub focus: usize,
pub kind: FormKind,
/// Descriptor `hidden` fields: carried to the submit, never rendered.
pub hidden: Vec<(&'static str, String)>,
/// Server rejection messages shown below the fields after an unlock.
pub errors: Vec<String>,
/// Server notes about the loaded entity, shown above the fields.
pub notices: Vec<String>,
/// Values the form was opened with, taken when it joins the overlay stack.
pub baseline: Option<FormValues>,
/// Answers to the tag name and value lookups, kept for the form's lifetime.
pub hints: Hints,
/// The text typed before the current run of completions, and the last one filled.
pub completing: Option<(String, String)>,
/// The window the form's dialog started from; it travels with the form while the stack is
/// empty, between submit and reply.
pub origin: Option<Origin>,
/// Where the user moved or sized the dialog; it travels with the form through submit and
/// reopen.
pub placement: Placement,
impl Form {
/// The `config-set` form: a key and a value.
#[must_use]
pub fn config_set() -> Self {
Self::from_descriptor(&forms::CONFIG_SET, FormKind::ConfigSet)
/// The `ssh-key-add` form: a public key line and an optional label.
pub fn ssh_key_add() -> Self {
Self::from_descriptor(&forms::SSH_KEY_ADD, FormKind::SshKeyAdd)
/// The save-path prompt of the CSV pane, offering `path`.
pub fn csv_save(path: &str) -> Self {
let mut form = Self::from_descriptor(&descriptor::CSV_SAVE, FormKind::CsvSave);
for field in &mut form.fields {
field.widget.set_text(path);
form
/// A report's setup form from its descriptor: dates blank and the other
/// fields at their defaults unless `prefill` holds them.
pub fn report(kind: ReportKind, prefill: &forms::FormValues) -> Self {
let mut form = Self::from_descriptor(kind.descriptor(), FormKind::Report(kind));
if matches!(field.widget, Widget::Date(_)) {
field.widget.set_text("");
form.load(prefill);
/// The `commodity-create` form: symbol and name.
pub fn commodity_create() -> Self {
Self::from_descriptor(&forms::COMMODITY_CREATE, FormKind::CommodityCreate)
/// The `convert` form: amount and two commodity selects, filled from `form-options`.
pub fn commodity_convert() -> Self {
Self::from_descriptor(&forms::CONVERT, FormKind::CommodityConvert)
/// The `account-create` form: a name and a parent select.
pub fn account_create() -> Self {
Self::from_descriptor(&forms::ACCOUNT_CREATE, FormKind::AccountCreate)
/// Transaction create form built from the shared descriptor: date, note, splits.
pub fn transaction_create() -> Self {
Self::from_descriptor(&forms::TRANSACTION_CREATE, FormKind::TransactionCreate)
/// The `account-merge` form: two account selects.
pub fn account_merge() -> Self {
Self::from_descriptor(&forms::ACCOUNT_MERGE, FormKind::AccountMerge)
/// The Transactions tab filter form, prefilled with the active `filter`.
pub fn transaction_filter(filter: &FormValues) -> Self {
let mut form = Self::from_fields(
forms::TRANSACTION_QUERY.filter_fields(),
FormKind::TransactionFilter,
);
form.load(filter);
/// The label the select field `key` shows.
pub fn select_label(&self, key: &str) -> Option<&str> {
self.fields
.iter()
.find(|field| field.key == Some(key))
.and_then(|field| match &field.widget {
Widget::Select(sw) => Some(sw.display()),
_ => None,
})
/// The `tag-create` form from the shared descriptor.
pub fn tag_create() -> Self {
Self::from_descriptor(&forms::TAG_CREATE, FormKind::TagCreate)
/// Tag edit form built from the shared descriptor and the values
/// `load-form` returned. Hidden values ride along unrendered.
pub fn tag_edit(loaded: &forms::FormValues) -> Self {
let mut form = Self::from_descriptor(&forms::TAG_EDIT, FormKind::TagEdit);
form.load(loaded);
/// The `template-create` form from the shared descriptor.
pub fn template_create() -> Self {
Self::from_descriptor(&forms::TEMPLATE_CREATE, FormKind::TemplateCreate)
/// Template edit form built from the shared descriptor and the values
pub fn template_edit(loaded: &forms::FormValues) -> Self {
let mut form = Self::from_descriptor(&forms::TEMPLATE_EDIT, FormKind::TemplateEdit);
/// The template picker over `options`.
pub fn template_pick(options: &[SelectOption]) -> Self {
let mut form = Self::from_descriptor(&descriptor::TEMPLATE_PICK, FormKind::TemplatePick);
if let Widget::Select(select) = &mut field.widget {
select.set_options(options.to_vec());
/// Transaction create form filled from the `load-form` draft of a template.
pub fn transaction_from_template(loaded: &forms::FormValues) -> Self {
let mut form = Self::transaction_create();
/// The `script-create` form from the shared descriptor.
pub fn script_create() -> Self {
Self::from_descriptor(&forms::SCRIPT_CREATE, FormKind::ScriptCreate)
/// Script edit form built from the shared descriptor and the values
pub fn script_edit(loaded: &forms::FormValues) -> Self {
let mut form = Self::from_descriptor(&forms::SCRIPT_EDIT, FormKind::ScriptEdit);
/// Transaction edit form built from the shared descriptor and the values
pub fn transaction_edit(loaded: &forms::FormValues) -> Self {
let mut form = Self::from_descriptor(&forms::TRANSACTION_EDIT, FormKind::TransactionEdit);
/// Account edit form built from the shared descriptor and the values
pub fn account_edit(loaded: &forms::FormValues) -> Self {
let mut form = Self::from_descriptor(&forms::ACCOUNT_EDIT, FormKind::AccountEdit);
/// Commodity edit form built from the shared descriptor and the values
pub fn commodity_edit(loaded: &forms::FormValues) -> Self {
let mut form = Self::from_descriptor(&forms::COMMODITY_EDIT, FormKind::CommodityEdit);
/// Closes the open split tag list; `false` when none was open.
pub fn close_tags(&mut self) -> bool {
self.fields.iter_mut().any(|field| match &mut field.widget {
Widget::Splits(sw) => sw.close_tags(),
_ => false,
/// Closes the focused select's open list; `false` when none was open.
pub fn close_select(&mut self) -> bool {
match self.focused_select_mut() {
Some(select) if select.open => {
select.close();
true
/// The select the focus is on: the field itself or the focused cell of a grid.
pub fn focused_select(&self) -> Option<&SelectWidget> {
match &self.fields.get(self.focus)?.widget {
Widget::Select(select) => Some(select),
Widget::Splits(sw) => sw.focused_select(),
Widget::Rows(rw) => rw.focused_select(),
pub fn focused_select_mut(&mut self) -> Option<&mut SelectWidget> {
match &mut self.fields.get_mut(self.focus)?.widget {
Widget::Splits(sw) => sw.focused_select_mut(),
Widget::Rows(rw) => rw.focused_select_mut(),
/// Advance or retreat focus by one step through the fields, then the buttons, wrapping.
pub fn cycle(&mut self, forward: bool) {
self.close_select();
let len = self.fields.len() + self.buttons().len();
self.focus = if forward {
(self.focus + 1) % len
} else {
(self.focus + len - 1) % len
};
/// Focuses field `index`; an index past the fields changes nothing.
pub fn focus_field(&mut self, index: usize) {
if index < self.fields.len() {
self.focus = index;
/// The index of the focused button when the focus is on the buttons.
pub fn focused_button(&self) -> Option<usize> {
self.focus.checked_sub(self.fields.len())
/// Mutable reference to the currently focused field, if any.
pub fn focused_field_mut(&mut self) -> Option<&mut Field> {
self.fields.get_mut(self.focus)
/// Mutable reference to the inner [`Editor`] of the focused field.
///
/// Returns `None` when the form is empty or the focused widget is not
/// `Text`, `Amount`, or `Date` (i.e. a `Select` or `Splits`).
pub fn focused_editor_mut(&mut self) -> Option<&mut Editor> {
self.focused_field_mut()
.and_then(|f| f.widget.as_text_mut())
/// Widget kind of the focused field, or `None` when the form is empty.
pub fn focused_widget_kind(&self) -> Option<WidgetKind> {
self.fields.get(self.focus).map(|f| f.widget.kind())
/// When the focused field is a Splits or Rows widget, returns `(at_first_cell,
/// at_last_cell)`; Tab/BackTab yield to the field cycle at those edges.
pub fn focused_cells_boundary(&self) -> Option<(bool, bool)> {
match self.fields.get(self.focus)?.widget {
Widget::Splits(ref sw) if sw.tags_open() => Some((false, false)),
Widget::Splits(ref sw) => Some((sw.at_first_cell(), sw.at_last_cell())),
Widget::Rows(ref rw) => Some((rw.at_first_cell(), rw.at_last_cell())),
/// `(at_first_row, at_last_row)` of the focused grid or text area, where Up/Down yield
/// to the field cycle; `None` where Up/Down step nothing of the form (a field, a button).
pub fn focused_vertical_boundary(&self) -> Option<(bool, bool)> {
Widget::Splits(ref sw) if sw.tags_open() => sw
.tags()
.map(|tags| (tags.at_first_row(), tags.at_last_row())),
Widget::Splits(ref sw) => Some((sw.at_first_row(), sw.at_last_row())),
Widget::Rows(ref rw) => Some((rw.at_first_row(), rw.at_last_row())),
Widget::Text(ref ed) if ed.is_multiline() => {
Some((ed.at_first_line(), ed.at_last_line()))