Lines
97.61 %
Functions
49.14 %
Branches
100 %
//! Binds a TUI form to its shared descriptor: widgets, submit values and the
//! focus and wording of server rejections.
use cli_core::render::FieldError;
use forms::{
ACCOUNT_CREATE, ACCOUNT_EDIT, ACCOUNT_MERGE, COMMODITY_CREATE, COMMODITY_EDIT, CONFIG_SET,
CONVERT, Field as Descriptor, FormValues, Kind, Row, TRANSACTION_CREATE, TRANSACTION_EDIT,
TRANSACTION_QUERY, drop_orphans,
};
use super::{Field, Form, FormKind, filter_row, options};
use crate::overlay::Placement;
use crate::widgets::rows::is_text_rows;
use crate::widgets::splits::rows_of;
use crate::widgets::{
AmountWidget, DateWidget, Editor, Hints, RowsWidget, SelectWidget, SplitsWidget, Widget,
/// The CSV save prompt; local only, so it has no server form.
pub(super) const CSV_SAVE: forms::Form = forms::Form {
name: "save-csv",
title: "Save CSV",
fields: &[Descriptor {
key: "path",
label: "File",
kind: Kind::Text {
multiline: false,
suggest: None,
},
required: true,
}],
action: forms::Action::Mutation,
/// The template picker of create-from-template; local only, so it has no server form.
pub(super) const TEMPLATE_PICK: forms::Form = forms::Form {
name: "template-pick",
title: "New from template",
key: "template",
label: "Template",
kind: Kind::Select {
source: forms::Source::Templates,
fills: None,
empty: None,
/// Where a field address points inside the form.
enum Target<'a> {
Field(usize),
Cell {
field: usize,
row: usize,
key: Option<&'a str>,
/// A cell of the `index`th split tag, counted over all splits.
Tag {
index: usize,
}
fn widget_for(descriptor: &Descriptor) -> Option<Widget> {
match descriptor.kind {
Kind::Text { multiline, .. } => Some(Widget::Text(Editor::default().multiline(multiline))),
Kind::Choice { options, default } => {
Some(Widget::Select(SelectWidget::choice(options, default)))
Kind::Select { .. } => Some(Widget::Select(SelectWidget::new())),
Kind::Amount => Some(Widget::Amount(AmountWidget::default())),
Kind::Date { .. } => Some(Widget::Date(DateWidget::default())),
Kind::Rows { .. } if descriptor.is_nested() => None,
Kind::Rows { fields, .. } if is_text_rows(fields) => {
Some(Widget::Rows(RowsWidget::new(fields)))
Kind::Rows { .. } => Some(Widget::Splits(SplitsWidget::default())),
Kind::Hidden => None,
impl Form {
pub(super) fn from_descriptor(form: &forms::Form, kind: FormKind) -> Self {
Self::from_fields(form.fields.iter(), kind)
pub(super) fn from_fields<'a>(
descriptors: impl Iterator<Item = &'a Descriptor>,
kind: FormKind,
) -> Self {
let descriptors: Vec<&Descriptor> = descriptors.collect();
let fields = descriptors
.iter()
.filter_map(|descriptor| {
Some(Field {
key: Some(descriptor.key),
label: descriptor.label,
widget: widget_for(descriptor)?,
})
.collect();
let hidden = descriptors
.filter(|descriptor| descriptor.kind == Kind::Hidden)
.map(|descriptor| (descriptor.key, String::new()))
Self {
fields,
focus: 0,
kind,
hidden,
errors: Vec::new(),
notices: Vec::new(),
baseline: None,
hints: Hints::default(),
completing: None,
origin: None,
placement: Placement::default(),
/// Replaces the widgets' and hidden fields' contents with `loaded`; keys
/// the payload does not hold keep their empty value.
pub fn load(&mut self, loaded: &FormValues) {
let descriptor = self.descriptor();
for field in &mut self.fields {
let Some(key) = field.key else { continue };
match &mut field.widget {
Widget::Splits(sw) => {
sw.load_rows(loaded.rows(key).unwrap_or_default());
if let Some(nested) = nested_key(descriptor, key) {
sw.load_tags(loaded.rows(nested));
Widget::Rows(rw) => rw.load_rows(loaded.rows(key)),
widget => {
if let Some(text) = loaded.text(key) {
widget.set_text(text);
for (key, value) in &mut self.hidden {
*value = loaded.text(key).unwrap_or_default().to_string();
fn descriptor(&self) -> &'static forms::Form {
match self.kind {
FormKind::TransactionCreate => &TRANSACTION_CREATE,
FormKind::TransactionEdit => &TRANSACTION_EDIT,
FormKind::AccountEdit => &ACCOUNT_EDIT,
FormKind::AccountMerge => &ACCOUNT_MERGE,
FormKind::AccountCreate => &ACCOUNT_CREATE,
FormKind::TransactionFilter => &TRANSACTION_QUERY,
FormKind::CommodityCreate => &COMMODITY_CREATE,
FormKind::CommodityEdit => &COMMODITY_EDIT,
FormKind::CommodityConvert => &CONVERT,
FormKind::ConfigSet => &CONFIG_SET,
FormKind::Options => &options::OPTIONS,
FormKind::SshKeyAdd => &forms::SSH_KEY_ADD,
FormKind::CsvSave => &CSV_SAVE,
FormKind::TagCreate => &forms::TAG_CREATE,
FormKind::TagEdit => &forms::TAG_EDIT,
FormKind::TemplateCreate => &forms::TEMPLATE_CREATE,
FormKind::TemplateEdit => &forms::TEMPLATE_EDIT,
FormKind::ScriptCreate => &forms::SCRIPT_CREATE,
FormKind::ScriptEdit => &forms::SCRIPT_EDIT,
FormKind::TemplatePick => &TEMPLATE_PICK,
FormKind::FilterAdd => &filter_row::ADD,
FormKind::FilterRow(shape) => filter_row::shape_descriptor(shape),
FormKind::Report(kind) => kind.descriptor(),
/// Remembers the current values as the clean state, once.
pub fn snapshot(&mut self) {
if self.baseline.is_none() {
self.baseline = Some(self.values());
/// Takes the current values as the clean state.
pub fn rebaseline(&mut self) {
/// Whether the values differ from those the form opened with.
#[must_use]
pub fn is_dirty(&self) -> bool {
self.baseline
.as_ref()
.is_some_and(|baseline| *baseline != self.values())
pub fn is_template(&self) -> bool {
matches!(self.kind, FormKind::TemplateCreate | FormKind::TemplateEdit)
pub fn is_transaction(&self) -> bool {
matches!(
self.kind,
FormKind::TransactionCreate | FormKind::TransactionEdit
)
/// The raw values of a descriptor form, hidden ones included; empty cells
/// are left out so the server reports a missing required value by address.
pub fn values(&self) -> FormValues {
let mut values = FormValues::default();
for (key, value) in &self.hidden {
values.set(key, value);
let row_fields = self.row_fields();
for field in &self.fields {
match &field.widget {
for row in sw.rows() {
values.push_row(key, row_values(row_fields, row));
self.push_nested(key, sw, &mut values);
Widget::Rows(rw) => {
if let Some(rows) = rw.values() {
values.set_rows(key);
rows.into_iter().for_each(|row| values.push_row(key, row));
widget => values.set(key, widget.value()),
drop_orphans(self.descriptor(), &mut values);
values
/// Writes the nested rows; an edit always sends the field, even empty.
fn push_nested(&self, parent: &str, sw: &SplitsWidget, values: &mut FormValues) {
let Some(key) = nested_key(self.descriptor(), parent) else {
return;
let rows = sw.tag_rows();
if self.kind == FormKind::TransactionEdit || sw.tags_present() || !rows.is_empty() {
/// Select `id` in the account select `key`; kept until the options arrive.
pub fn preselect_account(&mut self, key: &str, id: &str) {
for field in self.fields.iter_mut().filter(|f| f.key == Some(key)) {
if let Widget::Select(sw) = &mut field.widget {
sw.select_id(id);
/// Select `id` as the first split row's From account.
pub fn preselect_from_account(&mut self, id: &str) {
if let Widget::Splits(sw) = &mut field.widget {
sw.preselect_from(id);
/// Lists every rejection with its address translated to labels and
/// focuses the first one that points at a field or a cell.
pub fn show_errors(&mut self, errors: &[FieldError]) {
self.errors = errors.iter().map(|e| self.error_line(e)).collect();
let first = errors.iter().find_map(|e| self.target(&e.field));
if let Some(target) = first {
self.focus_target(target);
fn target<'a>(&self, address: &'a str) -> Option<Target<'a>> {
let mut parts = address.split('.');
let key = parts.next()?;
let Some(field) = self.fields.iter().position(|f| f.key == Some(key)) else {
let field = self.nested_field(key)?;
let index = parts.next()?.parse().ok()?;
return Some(Target::Tag {
field,
index,
key: parts.next(),
});
let Some(row) = parts.next() else {
return Some(Target::Field(field));
Some(Target::Cell {
row: row.parse().ok()?,
/// The index of the field holding the editor of the nested rows field `key`.
fn nested_field(&self, key: &str) -> Option<usize> {
self.fields.iter().position(|field| {
let parent = field.key.unwrap_or_default();
nested_key(descriptor, parent) == Some(key) && matches!(field.widget, Widget::Splits(_))
fn error_line(&self, error: &FieldError) -> String {
let message = &error.message;
let label = self.target(&error.field).and_then(|t| self.label(&t));
match (error.field.as_str(), label) {
("", _) => message.clone(),
(address, _) if self.is_hidden(address) => message.clone(),
(_, Some(label)) => format!("{label}: {message}"),
(address, None) => format!("{address}: {message}"),
fn row_fields(&self) -> &'static [Descriptor] {
rows_of(self.descriptor())
fn cell_label(&self, field: usize, key: &str) -> Option<&'static str> {
match &self.fields.get(field)?.widget {
Widget::Rows(rw) => rw.cell_label(key),
_ => self
.row_fields()
.find(|d| d.key == key)
.map(|d| d.label),
fn is_hidden(&self, address: &str) -> bool {
self.hidden.iter().any(|(key, _)| *key == address)
/// Whether a rejection says the loaded entry changed on the server: it is
/// addressed to the hidden `revision` field, which has nothing to focus.
pub fn is_stale(&self, errors: &[FieldError]) -> bool {
errors
.any(|e| e.field == "revision" && self.is_hidden("revision"))
fn label(&self, target: &Target<'_>) -> Option<String> {
match *target {
Target::Field(field) => Some(self.fields.get(field)?.label.to_string()),
Target::Tag { index, key, .. } => {
let label = format!("Tag {}", index + 1);
let cell = key.map(|key| tag_cell_label(key).unwrap_or(key));
Some(match cell {
Some(cell) => format!("{label} \u{b7} {cell}"),
None => label,
Target::Cell { field, row, key } => {
let row_label = format!("Row {}", row + 1);
let cell = key.map(|key| self.cell_label(field, key).unwrap_or(key));
Some(cell) => format!("{row_label} \u{b7} {cell}"),
None => row_label,
fn focus_target(&mut self, target: Target<'_>) {
match target {
Target::Field(field) => self.focus = field,
Target::Tag { field, index, key } => {
self.focus = field;
if let Some(Widget::Splits(sw)) = self.fields.get_mut(field).map(|f| &mut f.widget)
{
sw.focus_tag(index, key.unwrap_or_default());
let key = key.unwrap_or_default();
match self.fields.get_mut(field).map(|f| &mut f.widget) {
Some(Widget::Splits(sw)) => sw.focus_cell(row, key),
Some(Widget::Rows(rw)) => rw.focus_cell(row, key),
_ => {}
/// The key of the rows field `form` nests under `parent`.
fn nested_key(form: &'static forms::Form, parent: &str) -> Option<&'static str> {
let nested = |field: &&Descriptor| field.nested_under() == Some(parent);
form.fields.iter().find(nested).map(|f| f.key)
fn tag_cell_label(key: &str) -> Option<&'static str> {
let mut cell = crate::widgets::splits::tag_fields().iter();
cell.find(|cell| cell.key == key).map(|cell| cell.label)
fn row_values(row_fields: &[Descriptor], row: &crate::widgets::SplitRow) -> Row {
row_fields
.map(|field| (field.key, row.text(field.key)))
.filter(|(_, text)| !text.is_empty())
.map(|(key, text)| (key.to_string(), text.to_string()))
.collect()