aboutsummaryrefslogtreecommitdiff
path: root/src/core/components/form_builder.rs
blob: 30f25ef9c1a6980e92aab65ef7446b65b3e9a4f5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
use eframe::egui;
use serde_json::Value;
use std::collections::HashMap;

use super::help::{show_help_window, HelpWindowOptions};
use egui_commonmark::CommonMarkCache;
use egui_phosphor::regular as icons;

/// Field types supported by the generic editor
#[derive(Clone)]
pub enum FieldType {
    Text,
    #[allow(dead_code)]
    Dropdown(Vec<(String, String)>), // (value, label)
    MultilineText,
    Checkbox,
    Date, // simple single-line date input (YYYY-MM-DD)
}

/// Definition of an editable field
#[derive(Clone)]
pub struct EditorField {
    pub name: String,
    pub label: String,
    pub field_type: FieldType,
    pub required: bool,
    pub read_only: bool,
}

/// Replacement for FormBuilder that uses egui_form + garde for validation.
/// Maintains compatibility with existing EditorField schema.
pub struct FormBuilder {
    pub title: String,
    pub fields: Vec<EditorField>,
    pub data: HashMap<String, String>, // Store as strings for form editing
    pub original_data: serde_json::Map<String, Value>, // Store original JSON data
    pub show: bool,
    pub item_id: Option<String>,
    pub is_new: bool,
    field_help: HashMap<String, String>,
    pub form_help_text: Option<String>,
    pub show_form_help: bool,
    help_cache: CommonMarkCache,
}

impl FormBuilder {
    pub fn new(title: impl Into<String>, fields: Vec<EditorField>) -> Self {
        Self {
            title: title.into(),
            fields,
            data: HashMap::new(),
            original_data: serde_json::Map::new(),
            show: false,
            item_id: None,
            is_new: false,
            field_help: HashMap::new(),
            form_help_text: None,
            show_form_help: false,
            help_cache: CommonMarkCache::default(),
        }
    }

    #[allow(dead_code)]
    pub fn with_help(mut self, help_text: impl Into<String>) -> Self {
        self.form_help_text = Some(help_text.into());
        self
    }

    pub fn open(&mut self, item: &Value) {
        self.show = true;
        self.data.clear();
        self.original_data.clear();

        // Convert JSON to string map
        if let Some(obj) = item.as_object() {
            self.original_data = obj.clone();
            for (k, v) in obj {
                let value_str = match v {
                    Value::String(s) => s.clone(),
                    Value::Number(n) => n.to_string(),
                    Value::Bool(b) => b.to_string(),
                    Value::Null => String::new(),
                    _ => serde_json::to_string(v).unwrap_or_default(),
                };
                self.data.insert(k.clone(), value_str);
            }

            self.item_id = obj.get("id").and_then(|v| match v {
                Value::String(s) => Some(s.clone()),
                Value::Number(n) => n.as_i64().map(|i| i.to_string()),
                _ => None,
            });
            self.is_new = false;
        }
    }

    pub fn open_new(&mut self, preset: Option<&serde_json::Map<String, Value>>) {
        self.show = true;
        self.data.clear();

        if let Some(p) = preset {
            for (k, v) in p {
                let value_str = match v {
                    Value::String(s) => s.clone(),
                    Value::Number(n) => n.to_string(),
                    Value::Bool(b) => b.to_string(),
                    Value::Null => String::new(),
                    _ => serde_json::to_string(v).unwrap_or_default(),
                };
                self.data.insert(k.clone(), value_str);
            }
        }

        self.item_id = None;
        self.is_new = true;
    }

    pub fn close(&mut self) {
        self.show = false;
        self.data.clear();
        self.original_data.clear();
        self.item_id = None;
        self.is_new = false;
    }

    /// Show the form editor and return Some(data) if saved, None if still open
    pub fn show_editor(
        &mut self,
        ctx: &egui::Context,
    ) -> Option<Option<serde_json::Map<String, Value>>> {
        if !self.show {
            return None;
        }

        let mut result = None;
        let mut close_requested = false;

        // Dynamic sizing
        let root_bounds = ctx.available_rect();
        let screen_bounds = ctx.input(|i| {
            i.viewport().inner_rect.unwrap_or(egui::Rect::from_min_size(
                egui::Pos2::ZERO,
                egui::vec2(800.0, 600.0),
            ))
        });
        let horizontal_margin = 24.0;
        let vertical_margin = 24.0;

        let max_w = (root_bounds.width() - horizontal_margin)
            .min(screen_bounds.width() - horizontal_margin)
            .max(260.0);
        let max_h = (root_bounds.height() - vertical_margin)
            .min(screen_bounds.height() - vertical_margin)
            .max(260.0);

        let default_w = (root_bounds.width() * 0.6).clamp(320.0, max_w);
        let default_h = (root_bounds.height() * 0.7).clamp(300.0, max_h);
        let content_max_h = (max_h - 160.0).max(180.0);
        let _window_response = egui::Window::new(&self.title)
            .collapsible(false)
            .resizable(true)
            .default_width(default_w)
            .default_height(default_h)
            .min_width(f32::min(280.0, max_w))
            .min_height(f32::min(260.0, max_h))
            .max_width(max_w)
            .max_height(max_h)
            .open(&mut self.show)
            .show(ctx, |ui| {
                egui::ScrollArea::vertical()
                    .max_height(content_max_h)
                    .show(ui, |ui| {
                        ui.vertical(|ui| {
                            for field in &self.fields.clone() {
                                let field_value = self
                                    .data
                                    .entry(field.name.clone())
                                    .or_insert_with(String::new);

                                match &field.field_type {
                                    FieldType::Text => {
                                        let label_text = if field.required {
                                            format!("{} *", field.label)
                                        } else {
                                            field.label.clone()
                                        };
                                        ui.label(&label_text);
                                        ui.add(
                                            egui::TextEdit::singleline(field_value)
                                                .desired_width(f32::INFINITY)
                                                .interactive(!field.read_only),
                                        );
                                    }
                                    FieldType::MultilineText => {
                                        let label_text = if field.required {
                                            format!("{} *", field.label)
                                        } else {
                                            field.label.clone()
                                        };
                                        ui.label(&label_text);
                                        ui.add(
                                            egui::TextEdit::multiline(field_value)
                                                .desired_width(f32::INFINITY)
                                                .interactive(!field.read_only),
                                        );
                                    }
                                    FieldType::Checkbox => {
                                        let mut checked =
                                            field_value == "true" || field_value == "1";
                                        ui.add_enabled(
                                            !field.read_only,
                                            egui::Checkbox::new(&mut checked, &field.label),
                                        );
                                        if !field.read_only {
                                            *field_value = if checked {
                                                "true".to_string()
                                            } else {
                                                "false".to_string()
                                            };
                                        }
                                    }
                                    FieldType::Date => {
                                        let label_text = if field.required {
                                            format!("{} *", field.label)
                                        } else {
                                            field.label.clone()
                                        };
                                        ui.label(&label_text);
                                        ui.add(
                                            egui::TextEdit::singleline(field_value)
                                                .hint_text("YYYY-MM-DD")
                                                .desired_width(f32::INFINITY)
                                                .interactive(!field.read_only),
                                        );
                                    }
                                    FieldType::Dropdown(options) => {
                                        let label_text = if field.required {
                                            format!("{} *", field.label)
                                        } else {
                                            field.label.clone()
                                        };
                                        ui.label(&label_text);
                                        ui.add_enabled_ui(!field.read_only, |ui| {
                                            egui::ComboBox::from_id_salt(&field.name)
                                                .width(ui.available_width())
                                                .selected_text(
                                                    options
                                                        .iter()
                                                        .find(|(v, _)| v == field_value)
                                                        .map(|(_, l)| l.as_str())
                                                        .unwrap_or(""),
                                                )
                                                .show_ui(ui, |ui| {
                                                    for (value, label) in options {
                                                        ui.selectable_value(
                                                            field_value,
                                                            value.clone(),
                                                            label,
                                                        );
                                                    }
                                                });
                                        });
                                    }
                                }

                                // Show help text if available
                                if let Some(help) = self.field_help.get(&field.name) {
                                    ui.label(
                                        egui::RichText::new(help)
                                            .small()
                                            .color(ui.visuals().weak_text_color()),
                                    );
                                }

                                ui.add_space(8.0);
                            }
                        });
                    });

                ui.separator();

                ui.horizontal(|ui| {
                    // Help button if help text is available
                    if self.form_help_text.is_some() {
                        if ui.button(format!("{} Help", icons::QUESTION)).clicked() {
                            self.show_form_help = true;
                        }
                        ui.separator();
                    }

                    // Submit button
                    if ui.button(format!("{} Save", icons::CHECK)).clicked() {
                        // Validate required fields
                        let mut missing_fields = Vec::new();
                        for field in &self.fields {
                            if field.required {
                                let value =
                                    self.data.get(&field.name).map(|s| s.as_str()).unwrap_or("");
                                if value.trim().is_empty() {
                                    missing_fields.push(field.label.clone());
                                }
                            }
                        }

                        if !missing_fields.is_empty() {
                            log::warn!("Missing required fields: {}", missing_fields.join(", "));
                            // Show error in UI - for now just log, could add error message field
                        } else {
                            // Convert string map back to JSON
                            let mut json_map = serde_json::Map::new();
                            for (k, v) in &self.data {
                                // Try to preserve types
                                let json_value = if v == "true" {
                                    Value::Bool(true)
                                } else if v == "false" {
                                    Value::Bool(false)
                                } else if let Ok(n) = v.parse::<i64>() {
                                    Value::Number(n.into())
                                } else if let Ok(n) = v.parse::<f64>() {
                                    serde_json::Number::from_f64(n)
                                        .map(Value::Number)
                                        .unwrap_or_else(|| Value::String(v.clone()))
                                } else if v.is_empty() {
                                    Value::Null
                                } else {
                                    Value::String(v.clone())
                                };
                                json_map.insert(k.clone(), json_value);
                            }

                            // CRITICAL: Include the item_id so updates work
                            if let Some(ref id) = self.item_id {
                                json_map.insert(
                                    "__editor_item_id".to_string(),
                                    Value::String(id.clone()),
                                );
                            }

                            result = Some(Some(json_map));
                            close_requested = true;
                        }
                    }

                    if ui.button(format!("{} Cancel", icons::X)).clicked() {
                        result = Some(None);
                        close_requested = true;
                    }
                });
            });
        if close_requested || !self.show {
            self.close();
        }

        // Show help window if requested
        if let Some(help_text) = &self.form_help_text {
            if self.show_form_help {
                show_help_window(
                    ctx,
                    &mut self.help_cache,
                    format!("{}_help", self.title),
                    &format!("{} - Help", self.title),
                    help_text,
                    &mut self.show_form_help,
                    HelpWindowOptions::default(),
                );
            }
        }

        result
    }
}