1
//! Activity report groups editor. Each row is a name, a filter builder and a
2
//! flip box, written under the `groups.N.*` field names the form reads.
3

            
4
use forms::filter::{Entity, Item, item_sexpr};
5
use wasm_bindgen::JsCast;
6
use wasm_bindgen::prelude::*;
7
use web_sys::{Element, HtmlElement, HtmlInputElement, HtmlTextAreaElement};
8

            
9
use super::tag_filter::{clone_template, find, init_all_filters};
10
use crate::autocomplete;
11

            
12
const CONTAINER: &str = ".activity-groups-container";
13
const ROWS: &str = ".activity-groups-rows";
14
const ROW: &str = ".activity-group-row";
15
const TEMPLATE: &str = "activity-group-row-template";
16
const READY: &str = "data-groups-ready";
17

            
18
const NAME: &str = ".activity-group-name";
19
const FILTER: &str = ".tag-filter-sexpr";
20
const FLIP: &str = ".activity-group-flip";
21
const CELLS: [(&str, &str); 3] = [(NAME, "name"), (FILTER, "filter"), (FLIP, "flip")];
22

            
23
struct Group {
24
    name: &'static str,
25
    value: &'static str,
26
    flip: bool,
27
}
28

            
29
const DEFAULTS: [Group; 2] = [
30
    Group {
31
        name: "Income",
32
        value: "income",
33
        flip: true,
34
    },
35
    Group {
36
        name: "Expense",
37
        value: "expense",
38
        flip: false,
39
    },
40
];
41

            
42
fn type_filter(value: &str) -> String {
43
    let item = Item::Tag {
44
        entities: vec![Entity::Account],
45
        name: "type".to_owned(),
46
        values: vec![value.to_owned()],
47
    };
48
    item_sexpr(&item).unwrap_or_default()
49
}
50

            
51
fn rows_of(rows: &Element) -> Vec<Element> {
52
    let children = rows.children();
53
    (0..children.length())
54
        .filter_map(|i| children.item(i))
55
        .filter(|child| child.matches(ROW).unwrap_or(false))
56
        .collect()
57
}
58

            
59
/// Keeps the row numbers gapless: the form reader refuses a missing row.
60
fn renumber(rows: &Element) {
61
    for (index, row) in rows_of(rows).iter().enumerate() {
62
        for (selector, cell) in CELLS {
63
            if let Some(field) = find::<Element>(row, selector) {
64
                let _ = field.set_attribute("name", &format!("groups.{index}.{cell}"));
65
            }
66
        }
67
    }
68
}
69

            
70
fn append_row(rows: &Element, group: &Group) {
71
    let Some(row) = clone_template(TEMPLATE) else {
72
        return;
73
    };
74
    if let Some(input) = find::<HtmlInputElement>(&row, NAME) {
75
        input.set_value(group.name);
76
    }
77
    if let Some(field) = find::<HtmlTextAreaElement>(&row, FILTER) {
78
        field.set_value(&type_filter(group.value));
79
    }
80
    if let Some(checkbox) = find::<HtmlInputElement>(&row, FLIP) {
81
        checkbox.set_checked(group.flip);
82
    }
83
    let _ = rows.append_child(&row);
84
}
85

            
86
fn blank_row(rows: &Element) {
87
    if let Some(row) = clone_template(TEMPLATE) {
88
        let _ = rows.append_child(&row);
89
    }
90
}
91

            
92
/// Runs once per rendered editor: a page that came without rows gets the
93
/// default groups, a page that came with rows keeps them.
94
fn init_container(container: &Element) {
95
    let Some(rows) = find::<Element>(container, ROWS) else {
96
        return;
97
    };
98
    if rows.has_attribute(READY) {
99
        return;
100
    }
101
    let _ = rows.set_attribute(READY, "");
102
    if rows_of(&rows).is_empty() {
103
        DEFAULTS.iter().for_each(|group| append_row(&rows, group));
104
    }
105
    renumber(&rows);
106
}
107

            
108
pub fn init_activity_groups() {
109
    let Some(document) = web_sys::window().and_then(|w| w.document()) else {
110
        return;
111
    };
112
    let Ok(containers) = document.query_selector_all(CONTAINER) else {
113
        return;
114
    };
115
    for i in 0..containers.length() {
116
        if let Some(container) = containers.get(i).and_then(|n| n.dyn_into::<Element>().ok()) {
117
            init_container(&container);
118
        }
119
    }
120
}
121

            
122
#[wasm_bindgen(js_name = addActivityGroup)]
123
pub fn add_activity_group(button: &HtmlElement) {
124
    let Some(rows) = button
125
        .closest(CONTAINER)
126
        .ok()
127
        .flatten()
128
        .and_then(|container| find::<Element>(&container, ROWS))
129
    else {
130
        return;
131
    };
132
    blank_row(&rows);
133
    renumber(&rows);
134
    init_all_filters();
135
    autocomplete::init_all();
136
}
137

            
138
#[wasm_bindgen(js_name = removeActivityGroup)]
139
pub fn remove_activity_group(button: &HtmlElement) {
140
    let Some(rows) = button.closest(ROWS).ok().flatten() else {
141
        return;
142
    };
143
    if let Some(row) = button.closest(ROW).ok().flatten() {
144
        row.remove();
145
    }
146
    renumber(&rows);
147
}