Skip to main content

aylis_json/
reload.rs

1//! Recarregar um layout num form aberto, sem recriá-lo (o "hot reload"): os componentes
2//! que continuam no layout ficam (com dados, foco, posição de rolagem e os handlers
3//! ligados por código), só as propriedades mudam; os novos são criados e os que saíram do
4//! layout são liberados.
5
6use aylis_core::{ComponentId, PropKind, PropValue, Ui, read_prop};
7use serde_json::{Map, Value};
8
9use crate::layout::{Loader, RESERVED};
10use crate::value::{object, to_prop};
11use crate::{Error, Result};
12
13/// O que mudou num [`reload`].
14#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
15pub struct ReloadReport {
16    /// Propriedades alteradas.
17    pub updated: usize,
18    pub created: usize,
19    pub removed: usize,
20}
21
22/// Aplica o layout `json` ao form (ou contêiner) `root` já existente.
23///
24/// Os filhos são casados pelo nome (e, sem nome, pela classe e pela ordem). Só são
25/// liberados os componentes com nome que estavam em `previous` (o layout anterior) e saíram
26/// do novo: os criados pelo código do aplicativo ficam. Como ao carregar, não dispara o
27/// `on_change` dos valores.
28pub fn reload(ui: &mut Ui, root: ComponentId, json: &str, previous: Option<&str>) -> Result<ReloadReport> {
29    ui.without_change_events(|ui| reload_document(ui, root, json, previous))
30}
31
32fn reload_document(ui: &mut Ui, root: ComponentId, json: &str, previous: Option<&str>) -> Result<ReloadReport> {
33    let doc: Value = serde_json::from_str(json.trim_start_matches('\u{feff}'))?;
34    let node = doc.get("root").ok_or_else(|| Error::Structure { path: String::new(), message: "falta \"root\"".into() })?;
35    let old_doc: Option<Value> = previous.and_then(|p| serde_json::from_str::<Value>(p.trim_start_matches('\u{feff}')).ok());
36    let old_root = old_doc.as_ref().map(|v| &v["root"]);
37    let mut before = Vec::new();
38    if let Some(old) = old_root {
39        collect_names(old, &mut before);
40    }
41    let mut now = Vec::new();
42    collect_names(node, &mut now);
43
44    let class = node.get("class").and_then(Value::as_str).unwrap_or_default();
45    let current = ui.component(root).map(|c| c.class_name()).unwrap_or_default();
46    if class != current {
47        return Err(Error::Structure {
48            path: String::new(),
49            message: format!("o layout é de um {class}, mas o componente é um {current}"),
50        });
51    }
52    let mut report = ReloadReport::default();
53    let mut loader = Loader { ui, created: None, deferred: Vec::new(), bindings: Vec::new(), views: Vec::new(), errors: None };
54    apply(&mut loader, root, node, old_root, &mut vec![class.to_string()], &mut report)?;
55    loader.fixup()?;
56    // Saíram do layout: só os que tinham nome e estavam no layout anterior.
57    let gone: Vec<ComponentId> = before
58        .iter()
59        .filter(|n| !now.iter().any(|m| m.eq_ignore_ascii_case(n)))
60        .filter_map(|n| ui.find_in(root, n))
61        .collect();
62    for id in gone {
63        if ui.contains(id) {
64            ui.free(id);
65            report.removed += 1;
66        }
67    }
68    ui.invalidate();
69    Ok(report)
70}
71
72fn collect_names(node: &Value, out: &mut Vec<String>) {
73    if let Some(name) = node.get("name").and_then(Value::as_str) {
74        out.push(name.to_string());
75    }
76    if let Some(children) = node.get("children").and_then(Value::as_array) {
77        children.iter().for_each(|c| collect_names(c, out));
78    }
79}
80
81/// O filho de `old` que corresponde a `children[index]` (pelo nome; sem nome, pela classe
82/// e pela ordem entre os sem nome da mesma classe).
83fn old_child<'a>(old: Option<&'a Value>, children: &[Value], index: usize) -> Option<&'a Value> {
84    let olds = old?.get("children")?.as_array()?;
85    let child = &children[index];
86    let class = child.get("class");
87    match child.get("name").and_then(Value::as_str) {
88        Some(name) => olds.iter().find(|o| o.get("name").and_then(Value::as_str).is_some_and(|n| n.eq_ignore_ascii_case(name))),
89        None => {
90            let nth = children[..index].iter().filter(|c| c.get("name").is_none() && c.get("class") == class).count();
91            olds.iter().filter(|o| o.get("name").is_none() && o.get("class") == class).nth(nth)
92        }
93    }
94}
95
96/// Aplica `node` ao componente `id`. Com o nó do layout anterior (`old`), só o que mudou
97/// nele: o que o usuário fez no app (um texto digitado, uma aba escolhida) fica. Sem ele
98/// (primeira vez, ou componente novo), aplica tudo.
99fn apply(loader: &mut Loader<'_>, id: ComponentId, node: &Value, old: Option<&Value>, path: &mut Vec<String>, report: &mut ReloadReport) -> Result<()> {
100    let here = path.join(" > ");
101    let obj: &Map<String, Value> = object(node, "cada componente").map_err(|m| Error::Structure { path: here.clone(), message: m })?;
102    let ui = &mut *loader.ui;
103    let class = ui.component(id).map(|c| c.class_name()).unwrap_or_default();
104    // Valores padrão da classe: propriedade que saiu do JSON volta ao padrão.
105    let defaults = ui.registry().get(class).map(|c| (c.create)());
106    for info in ui.prop_infos(id) {
107        // A propriedade `bindings` da lista (texto) vale; o objeto `bindings` são as ligações a
108        // campo, aplicadas à parte.
109        let list_bindings = info.name == "bindings" && obj.get("bindings").is_none_or(Value::is_string);
110        if info.read_only || (RESERVED.contains(&info.name) && !list_bindings) {
111            continue;
112        }
113        let fail = |message: String| Error::Property { path: here.clone(), property: info.name.to_string(), message };
114        if old.is_some_and(|old| old.get(info.name) == obj.get(info.name)) {
115            continue; // não mudou no layout
116        }
117        let wanted = match obj.get(info.name) {
118            Some(json) => {
119                let prop = to_prop(json, info.kind, ui.theme()).map_err(fail)?;
120                if info.kind == PropKind::Component {
121                    if let PropValue::String(target) = prop {
122                        loader.deferred.push((id, info.name.to_string(), target, here.clone()));
123                    }
124                    continue;
125                }
126                prop
127            }
128            // Eventos ligados por código (closures) não aparecem no JSON: ficam.
129            None if info.kind == PropKind::Event => continue,
130            None => match defaults.as_ref().and_then(|d| read_prop(d.as_ref(), info.name)) {
131                Some(default) => default,
132                None => continue,
133            },
134        };
135        if let (PropValue::String(text), true) = (&wanted, aylis_core::i18n::TRANSLATABLE.contains(&info.name)) {
136            let text = text.clone();
137            if ui.get_prop(id, info.name).ok() != Some(PropValue::String(ui.translate_prop(info.name, &text))) {
138                ui.set_translated(id, info.name, &text).map_err(|e| fail(e.to_string()))?;
139                report.updated += 1;
140            }
141            continue;
142        }
143        if ui.get_prop(id, info.name).ok().as_ref() != Some(&wanted) {
144            ui.set_prop(id, info.name, wanted).map_err(|e| fail(e.to_string()))?;
145            report.updated += 1;
146        }
147    }
148    // "margins.left": 4
149    for (key, value) in obj.iter().filter(|(k, _)| k.contains('.')) {
150        if let Some(v) = value.as_f64() {
151            let _ = ui.set_prop(id, key, v);
152        }
153    }
154
155    let children: Vec<Value> = match obj.get("children") {
156        Some(Value::Array(c)) => c.clone(),
157        _ => Vec::new(),
158    };
159    let mut used: Vec<ComponentId> = Vec::new();
160    let mut order: Vec<ComponentId> = Vec::new();
161    for (index, child) in children.iter().enumerate() {
162        let class = child.get("class").and_then(Value::as_str).unwrap_or_default();
163        let name = child.get("name").and_then(Value::as_str);
164        let existing = loader.ui.children(id).iter().copied().find(|&c| {
165            let ui = &*loader.ui;
166            !used.contains(&c)
167                && ui.component(c).is_some_and(|x| x.class_name() == class)
168                && match name {
169                    Some(n) => ui.name(c).is_some_and(|m| m.eq_ignore_ascii_case(n)),
170                    None => ui.name(c).is_none_or(str::is_empty),
171                }
172        });
173        let child_id = match existing {
174            Some(c) => {
175                path.push(name.unwrap_or(class).to_string());
176                apply(loader, c, child, old_child(old, &children, index), path, report)?;
177                path.pop();
178                c
179            }
180            None => {
181                let c = loader.node(child, Some(id), path)?;
182                report.created += 1;
183                c
184            }
185        };
186        used.push(child_id);
187        order.push(child_id);
188    }
189    // A ordem dos filhos conta para o alinhamento: segue a do layout.
190    for (i, &c) in order.iter().enumerate() {
191        let _ = loader.ui.set_child_index(c, i);
192    }
193    Ok(())
194}