Skip to main content

tui/modal/
filter_builder.rs

1//! The report filter builder: the rows of the filter grammar, edited one
2//! group at a time. Enter on a group or an `in` row steps into it, `back`
3//! steps out; the whole tree is written back only by [`FilterBuilder::apply`].
4
5use forms::FormValues;
6use forms::filter::{Fault, Item, Logic, Restored, group_sexpr, restore};
7
8use crate::form::RowShape;
9use crate::widgets::SelectOption;
10use describe::{describe, label, logic as logic_label};
11use rows::{blank, id_of, item_of, picks_commodities, shape_of, values_of};
12
13mod describe;
14mod rows;
15
16#[cfg(test)]
17mod tests;
18
19/// The rows or the ids of the group or `in` row being edited.
20enum Level<'a> {
21    Items(&'a [Item]),
22    Ids(&'a [String]),
23}
24
25enum LevelMut<'a> {
26    Items(&'a mut Vec<Item>),
27    Ids(&'a mut Vec<String>),
28}
29
30fn level<'a>(items: &'a [Item], path: &[usize]) -> Option<Level<'a>> {
31    let Some((&first, rest)) = path.split_first() else {
32        return Some(Level::Items(items));
33    };
34    match items.get(first)? {
35        Item::Group { items, .. } => level(items, rest),
36        Item::AccountIn { ids } | Item::CounterpartyIn { ids } | Item::CommodityIn { ids } => {
37            rest.is_empty().then_some(Level::Ids(ids))
38        }
39        _ => None,
40    }
41}
42
43fn level_mut<'a>(items: &'a mut Vec<Item>, path: &[usize]) -> Option<LevelMut<'a>> {
44    let Some((&first, rest)) = path.split_first() else {
45        return Some(LevelMut::Items(items));
46    };
47    match items.get_mut(first)? {
48        Item::Group { items, .. } => level_mut(items, rest),
49        Item::AccountIn { ids } | Item::CounterpartyIn { ids } | Item::CommodityIn { ids } => {
50            rest.is_empty().then_some(LevelMut::Ids(ids))
51        }
52        _ => None,
53    }
54}
55
56/// What the builder shows: the heading, one line per row and the cursor.
57#[derive(Debug, PartialEq, Eq)]
58pub struct View {
59    pub heading: String,
60    pub rows: Vec<String>,
61    pub selected: usize,
62    pub notice: Option<String>,
63}
64
65/// A row form is open: where its values go.
66#[derive(Debug, Clone)]
67enum Pending {
68    /// An id for the `in` row being edited.
69    Id,
70    /// A row of the kind of `template`, replacing the row `at` or appended.
71    Row { at: Option<usize>, template: Item },
72}
73
74/// A row form to open: its shape and the values it starts with.
75#[derive(Debug)]
76pub struct Opened {
77    pub shape: RowShape,
78    pub values: FormValues,
79}
80
81#[derive(Debug)]
82pub struct FilterBuilder {
83    logic: Logic,
84    items: Vec<Item>,
85    original: (Logic, Vec<Item>),
86    /// The filter text rows cannot show; the builder then edits nothing.
87    opaque: Option<String>,
88    path: Vec<usize>,
89    selected: usize,
90    pending: Option<Pending>,
91    /// Why the last apply or edit was refused.
92    pub error: Option<String>,
93    pub accounts: Vec<SelectOption>,
94    pub commodities: Vec<SelectOption>,
95}
96
97impl FilterBuilder {
98    /// A builder holding the rows of the filter `text`.
99    #[must_use]
100    pub fn new(text: &str) -> Self {
101        let (logic, items, opaque) = match restore(text) {
102            Restored::Rows { logic, items } => (logic, items, None),
103            Restored::Opaque => (Logic::And, Vec::new(), Some(text.to_string())),
104        };
105        Self {
106            original: (logic, items.clone()),
107            logic,
108            items,
109            opaque,
110            path: Vec::new(),
111            selected: 0,
112            pending: None,
113            error: None,
114            accounts: Vec::new(),
115            commodities: Vec::new(),
116        }
117    }
118
119    #[must_use]
120    pub fn is_dirty(&self) -> bool {
121        self.original != (self.logic, self.items.clone())
122    }
123
124    #[must_use]
125    pub fn is_opaque(&self) -> bool {
126        self.opaque.is_some()
127    }
128
129    fn len(&self) -> usize {
130        match level(&self.items, &self.path) {
131            Some(Level::Items(items)) => items.len(),
132            Some(Level::Ids(ids)) => ids.len(),
133            None => 0,
134        }
135    }
136
137    pub fn select_next(&mut self) {
138        self.selected = (self.selected + 1).min(self.len().saturating_sub(1));
139    }
140
141    pub fn select_prev(&mut self) {
142        self.selected = self.selected.saturating_sub(1);
143    }
144
145    /// The row under the cursor when this level holds rows.
146    #[must_use]
147    pub fn selected_item(&self) -> Option<&Item> {
148        match level(&self.items, &self.path)? {
149            Level::Items(items) => items.get(self.selected),
150            Level::Ids(_) => None,
151        }
152    }
153
154    /// Whether the level holds ids of an `in` row.
155    #[must_use]
156    pub fn in_ids(&self) -> bool {
157        matches!(level(&self.items, &self.path), Some(Level::Ids(_)))
158    }
159
160    /// Steps into the group or `in` row under the cursor; `false` for any other row.
161    pub fn enter(&mut self) -> bool {
162        let steps = matches!(
163            self.selected_item(),
164            Some(
165                Item::Group { .. }
166                    | Item::AccountIn { .. }
167                    | Item::CounterpartyIn { .. }
168                    | Item::CommodityIn { .. }
169            )
170        );
171        if steps {
172            self.path.push(self.selected);
173            self.selected = 0;
174            self.error = None;
175        }
176        steps
177    }
178
179    /// Steps out to the enclosing level, the cursor on the row left.
180    pub fn back(&mut self) -> bool {
181        let Some(index) = self.path.pop() else {
182            return false;
183        };
184        self.selected = index;
185        self.error = None;
186        true
187    }
188
189    pub fn delete(&mut self) {
190        match level_mut(&mut self.items, &self.path) {
191            Some(LevelMut::Items(items)) if self.selected < items.len() => {
192                items.remove(self.selected);
193            }
194            Some(LevelMut::Ids(ids)) if self.selected < ids.len() => {
195                ids.remove(self.selected);
196            }
197            _ => return,
198        }
199        self.error = None;
200        self.selected = self.selected.min(self.len().saturating_sub(1));
201    }
202
203    /// And, or, not in turn for the group being edited.
204    pub fn cycle_logic(&mut self) {
205        let Some(logic) = self.logic_mut() else {
206            return;
207        };
208        *logic = match *logic {
209            Logic::And => Logic::Or,
210            Logic::Or => Logic::Not,
211            Logic::Not => Logic::And,
212        };
213        self.error = None;
214    }
215
216    fn logic_mut(&mut self) -> Option<&mut Logic> {
217        let Some((&last, parent)) = self.path.split_last() else {
218            return Some(&mut self.logic);
219        };
220        let Some(LevelMut::Items(items)) = level_mut(&mut self.items, parent) else {
221            return None;
222        };
223        match items.get_mut(last)? {
224            Item::Group { logic, .. } => Some(logic),
225            _ => None,
226        }
227    }
228
229    /// The form for adding an id to the `in` row being edited; `None` off an `in` row.
230    pub fn begin_id(&mut self) -> Option<Opened> {
231        let shape = match self.in_row()? {
232            Item::AccountIn { .. } => RowShape::AccountId,
233            Item::CounterpartyIn { .. } => RowShape::Counterparty,
234            Item::CommodityIn { .. } => RowShape::Commodity,
235            _ => return None,
236        };
237        self.pending = Some(Pending::Id);
238        Some(Opened {
239            shape,
240            values: FormValues::default(),
241        })
242    }
243
244    /// The form for the row under the cursor; `None` for a group or an `in` row.
245    pub fn begin_edit(&mut self) -> Option<Opened> {
246        let template = self.selected_item()?.clone();
247        let shape = shape_of(&template)?;
248        let values = values_of(&template);
249        self.pending = Some(Pending::Row {
250            at: Some(self.selected),
251            template,
252        });
253        Some(Opened { shape, values })
254    }
255
256    /// Starts a new row of the named kind. Groups and `in` rows are added at
257    /// once and stepped into; the others come back as a form to fill.
258    pub fn begin_add(&mut self, kind: &str) -> Option<Opened> {
259        let template = blank(kind)?;
260        let Some(shape) = shape_of(&template) else {
261            self.push(template);
262            self.enter();
263            return None;
264        };
265        let values = values_of(&template);
266        self.pending = Some(Pending::Row { at: None, template });
267        Some(Opened { shape, values })
268    }
269
270    /// Takes the values of the open row form.
271    ///
272    /// # Errors
273    /// Why they are not a row; the form stays open and the same values may be retried.
274    pub fn accept(&mut self, values: &FormValues) -> Result<(), String> {
275        match self.pending.clone() {
276            Some(Pending::Id) => {
277                let id = id_of(values)?;
278                if !self.has_id(&id) {
279                    self.push_id(id);
280                }
281            }
282            Some(Pending::Row { at, template }) => {
283                let item = item_of(&template, values)?;
284                match at {
285                    Some(index) => self.replace(index, item),
286                    None => self.push(item),
287                }
288            }
289            None => return Err("no row is being edited".to_string()),
290        }
291        self.pending = None;
292        Ok(())
293    }
294
295    fn has_id(&self, id: &str) -> bool {
296        matches!(level(&self.items, &self.path), Some(Level::Ids(ids)) if ids.iter().any(|have| have == id))
297    }
298
299    /// The names a row form of this shape picks among.
300    #[must_use]
301    pub fn options_for(&self, shape: RowShape) -> &[SelectOption] {
302        match picks_commodities(shape) {
303            true => &self.commodities,
304            false => &self.accounts,
305        }
306    }
307
308    /// Adds `item` to the rows being edited and puts the cursor on it.
309    fn push(&mut self, item: Item) {
310        if let Some(LevelMut::Items(items)) = level_mut(&mut self.items, &self.path) {
311            items.push(item);
312            self.selected = items.len() - 1;
313            self.error = None;
314        }
315    }
316
317    /// Adds `id` to the `in` row being edited.
318    fn push_id(&mut self, id: String) {
319        if let Some(LevelMut::Ids(ids)) = level_mut(&mut self.items, &self.path) {
320            ids.push(id);
321            self.selected = ids.len() - 1;
322            self.error = None;
323        }
324    }
325
326    /// Replaces the row at `index` of the rows being edited.
327    fn replace(&mut self, index: usize, item: Item) {
328        if let Some(LevelMut::Items(items)) = level_mut(&mut self.items, &self.path)
329            && let Some(row) = items.get_mut(index)
330        {
331            *row = item;
332            self.error = None;
333        }
334    }
335
336    /// The filter text of all rows. A row the writer would drop or widen is
337    /// refused: the cursor goes to it and `error` says why.
338    pub fn apply(&mut self) -> Option<String> {
339        if self.is_opaque() {
340            self.error = Some("the filter text is not shown as rows; nothing applied".into());
341            return None;
342        }
343        match group_sexpr(self.logic, &self.items) {
344            Ok(text) => Some(text.unwrap_or_default()),
345            Err(fault) => {
346                self.refuse(fault);
347                None
348            }
349        }
350    }
351
352    fn refuse(&mut self, fault: Fault) {
353        let (selected, parent) = match fault.path.split_last() {
354            Some((&index, parent)) => (index, parent.to_vec()),
355            None => (0, Vec::new()),
356        };
357        self.path = parent;
358        self.selected = selected;
359        self.error = Some(fault.reason.describe());
360    }
361
362    fn heading(&self) -> String {
363        let mut crumbs = vec![logic_label(self.logic).to_string()];
364        let mut items = self.items.as_slice();
365        for &index in &self.path {
366            match items.get(index) {
367                Some(Item::Group {
368                    logic,
369                    items: inner,
370                }) => {
371                    crumbs.push(logic_label(*logic).to_string());
372                    items = inner;
373                }
374                Some(row) => crumbs.push(describe(row, &self.accounts, &self.commodities)),
375                None => break,
376            }
377        }
378        crumbs.join(" > ")
379    }
380
381    fn rows(&self) -> Vec<String> {
382        match level(&self.items, &self.path) {
383            Some(Level::Items(items)) => items
384                .iter()
385                .map(|item| describe(item, &self.accounts, &self.commodities))
386                .collect(),
387            Some(Level::Ids(ids)) => ids.iter().map(|id| self.id_label(id)).collect(),
388            None => Vec::new(),
389        }
390    }
391
392    /// The name of an id of the `in` row being edited.
393    fn id_label(&self, id: &str) -> String {
394        let options = match self.in_row() {
395            Some(Item::CommodityIn { .. }) => &self.commodities,
396            _ => &self.accounts,
397        };
398        label(options, id)
399    }
400
401    fn in_row(&self) -> Option<&Item> {
402        let (&last, parent) = self.path.split_last()?;
403        match level(&self.items, parent)? {
404            Level::Items(items) => items.get(last),
405            Level::Ids(_) => None,
406        }
407    }
408
409    #[must_use]
410    pub fn view(&self) -> View {
411        View {
412            heading: self.heading(),
413            rows: self.rows(),
414            selected: self.selected,
415            notice: self
416                .opaque
417                .as_ref()
418                .map(|text| format!("cannot be shown as rows; the filter is left as is:\n{text}")),
419        }
420    }
421}