1use aylis_core::{ComponentId, PropKind, PropValue, Ui, read_prop};
4use serde_json::{Map, Value};
5
6use crate::value::{describe, from_prop, object, to_prop};
7use crate::{Error, FORMAT_VERSION, Result};
8
9pub(crate) const RESERVED: [&str; 6] = ["class", "name", "children", "uses", "bindings", "views"];
12
13const LIMITS: [&str; 6] = ["min", "max", "minimum", "maximum", "min_value", "max_value"];
15
16pub fn load(ui: &mut Ui, json: &str, parent: Option<ComponentId>) -> Result<ComponentId> {
21 let value: Value = serde_json::from_str(json.trim_start_matches('\u{feff}'))?;
22 load_value(ui, &value, parent)
23}
24
25pub fn load_value(ui: &mut Ui, document: &Value, parent: Option<ComponentId>) -> Result<ComponentId> {
29 ui.without_change_events(|ui| load_document(ui, document, parent))
30}
31
32fn load_document(ui: &mut Ui, document: &Value, parent: Option<ComponentId>) -> Result<ComponentId> {
33 let doc = object(document, "o documento").map_err(structure(""))?;
34 if let Some(version) = doc.get("aylis") {
35 let version = version.as_u64().ok_or_else(|| structure("")("\"aylis\" deve ser o número da versão".into()))?;
36 if version != FORMAT_VERSION {
38 return Err(Error::Version(version));
39 }
40 }
41 for key in doc.keys() {
42 if !matches!(key.as_str(), "aylis" | "root" | "$schema") {
43 return Err(structure("")(format!("chave desconhecida no documento: '{key}' (use \"aylis\" e \"root\")")));
44 }
45 }
46 let root = doc.get("root").ok_or_else(|| structure("")("falta \"root\"".into()))?;
47
48 let mut loader = Loader { ui, created: None, deferred: Vec::new(), bindings: Vec::new(), views: Vec::new(), errors: None };
49 let result = loader.node(root, parent, &mut Vec::new()).and_then(|id| loader.fixup().map(|_| id));
50 if result.is_err() {
51 if let Some(created) = loader.created {
52 loader.ui.free(created);
53 }
54 }
55 result
56}
57
58pub(crate) struct Loader<'a> {
59 pub(crate) ui: &'a mut Ui,
60 pub(crate) created: Option<ComponentId>,
62 pub(crate) deferred: Vec<(ComponentId, String, String, String)>,
64 pub(crate) bindings: Vec<(ComponentId, String, String, String)>,
66 pub(crate) views: Vec<(ComponentId, Value)>,
68 pub(crate) errors: Option<Vec<Error>>,
71}
72
73pub fn validate(ui: &mut Ui, json: &str) -> Vec<Error> {
77 let doc: Value = match serde_json::from_str(json.trim_start_matches('\u{feff}')) {
78 Ok(v) => v,
79 Err(e) => return vec![Error::Structure { path: String::new(), message: format!("JSON inválido: {e}") }],
80 };
81 let Some(root) = doc.get("root") else { return vec![structure("")("falta \"root\"".into())] };
82 let mut loader = Loader { ui, created: None, deferred: Vec::new(), bindings: Vec::new(), views: Vec::new(), errors: Some(Vec::new()) };
83 let result = loader.node(root, None, &mut Vec::new()).and_then(|_| loader.fixup());
84 let mut errors = loader.errors.take().unwrap_or_default();
85 if let Err(e) = result {
86 errors.push(e);
87 }
88 if let Some(created) = loader.created {
89 loader.ui.free(created);
90 }
91 errors
92}
93
94impl Loader<'_> {
95 fn soft(&mut self, error: Error) -> Result<()> {
97 match self.errors.as_mut() {
98 Some(list) => {
99 list.push(error);
100 Ok(())
101 }
102 None => Err(error),
103 }
104 }
105
106 pub(crate) fn node(&mut self, value: &Value, parent: Option<ComponentId>, path: &mut Vec<String>) -> Result<ComponentId> {
107 let obj = object(value, "cada componente").map_err(|e| structure(&path.join(" > "))(e))?;
110 let class = obj
111 .get("class")
112 .and_then(Value::as_str)
113 .ok_or_else(|| structure(&path.join(" > "))("falta \"class\" (o nome da classe do componente)".into()))?;
114 let name = match obj.get("name") {
115 None | Some(Value::Null) => None,
116 Some(Value::String(s)) => Some(s.as_str()),
117 Some(other) => return Err(structure(&path.join(" > "))(format!("\"name\" deve ser texto, recebido {}", describe(other)))),
118 };
119 path.push(name.unwrap_or(class).to_string());
120 let here = |path: &[String]| path.join(" > ");
121
122 let id = match self.ui.create(class, parent) {
123 Ok(id) => id,
124 Err(source) => {
126 let error = Error::Component { path: here(path), source };
127 match parent {
128 Some(p) if self.errors.is_some() => {
129 self.soft(error)?;
130 path.pop();
131 return Ok(p);
132 }
133 _ => return Err(error),
134 }
135 }
136 };
137 if self.created.is_none() && parent.is_some() && class == "Form" {
138 self.ui.set_name_scope(id, true);
141 }
142 self.created.get_or_insert(id);
143 if let Some(name) = name {
144 if let Err(source) = self.ui.set_name(id, name) {
145 self.soft(Error::Component { path: here(path), source })?;
146 }
147 }
148
149 let first = |key: &str| LIMITS.contains(&key) || key == "translate";
155 let entries = obj.iter().filter(|(key, _)| first(key)).chain(obj.iter().filter(|(key, _)| !first(key)));
156 for (key, value) in entries {
157 if RESERVED.contains(&key.as_str()) && !(key == "bindings" && value.is_string()) {
161 continue;
162 }
163 if let Err(e) = self.property(id, class, key, value, path) {
164 self.soft(e)?;
165 }
166 }
167
168 if let Some(Value::Object(list)) = obj.get("bindings") {
170 for (property, b) in list {
171 let source = b.get("source").and_then(Value::as_str).unwrap_or("").to_string();
172 let field = b.get("field").and_then(Value::as_str).unwrap_or("").to_string();
173 self.bindings.push((id, property.clone(), source, field));
174 }
175 }
176 if let Some(views) = obj.get("views").filter(|v| v.is_array()) {
178 self.views.push((id, views.clone()));
179 }
180
181 if class == "Frame" && obj.get("children").and_then(Value::as_array).is_some_and(|c| !c.is_empty()) {
184 self.soft(structure(&here(path))("o Frame mostra o form da propriedade `form` e não tem filhos: ponha os componentes no form dele".into()))?;
185 path.pop();
186 return Ok(id);
187 }
188 match obj.get("children") {
189 None | Some(Value::Null) => {}
190 Some(Value::Array(children)) => {
191 for child in children {
192 self.node(child, Some(id), path)?;
193 }
194 }
195 Some(other) => {
196 return Err(structure(&here(path))(format!("\"children\" deve ser uma lista, recebido {}", describe(other))));
197 }
198 }
199 path.pop();
200 Ok(id)
201 }
202
203 fn property(&mut self, id: ComponentId, class: &str, key: &str, value: &Value, path: &[String]) -> Result<()> {
205 let fail = |message: String| Error::Property { path: path.join(" > "), property: key.to_string(), message };
206 if key.contains('.') {
208 let v = value.as_f64().ok_or_else(|| fail(format!("esperado número, recebido {}", describe(value))))?;
209 return self.ui.set_prop(id, key, v).map_err(|e| fail(e.to_string()));
210 }
211 let info = self.ui.prop_info(id, key).ok_or_else(|| fail(format!("a classe {class} não tem esta propriedade")))?;
212 let prop = to_prop(value, info.kind, self.ui.theme()).map_err(fail)?;
213 if info.kind == PropKind::Component {
214 if let PropValue::String(target) = prop {
215 self.deferred.push((id, key.to_string(), target, path.join(" > ")));
216 }
217 return Ok(());
218 }
219 if let (PropValue::String(text), true) = (&prop, aylis_core::i18n::TRANSLATABLE.contains(&key)) {
221 let text = text.clone();
222 return self.ui.set_translated(id, key, &text).map_err(|e| fail(strip_property(e)));
223 }
224 self.ui.set_prop(id, key, prop).map_err(|e| fail(strip_property(e)))
225 }
226
227 pub(crate) fn fixup(&mut self) -> Result<()> {
229 for (id, property, target, path) in std::mem::take(&mut self.deferred) {
230 if let Err(e) = self.ui.set_prop(id, &property, target.as_str()) {
231 self.soft(Error::Property { path, property, message: strip_property(e) })?;
232 }
233 }
234 for (id, property, source, field) in std::mem::take(&mut self.bindings) {
235 let source = self.ui.resolve_reference(id, &source);
236 self.ui.set_binding(id, &property, source, &field);
237 }
238 for (form, list) in std::mem::take(&mut self.views) {
239 let views = load_views(self.ui, form, &list);
240 self.ui.set_views(form, views);
241 }
242 Ok(())
243 }
244}
245
246fn load_views(ui: &Ui, form: ComponentId, list: &Value) -> Vec<aylis_core::FormView> {
252 use aylis_core::views::{INDEX, PARENT};
253 let mut views = Vec::new();
254 for v in list.as_array().into_iter().flatten() {
255 let Some(name) = v.get("name").and_then(Value::as_str) else { continue };
256 let number = |key: &str, default: f64| v.get(key).and_then(Value::as_f64).unwrap_or(default) as f32;
257 let mut view = aylis_core::FormView::new(name, number("max_width", 0.0));
258 view.min_width = number("min_width", 0.0);
259 view.min_height = number("min_height", 0.0);
260 view.max_height = number("max_height", 0.0);
261 view.font_scale = number("font_scale", 1.0);
262 view.spacing_scale = number("spacing_scale", 1.0);
263 if let Some(o) = v.get("orientation").and_then(Value::as_str) {
264 view.orientation = <aylis_core::ViewOrientation as aylis_core::PropEnum>::from_name(o).unwrap_or_default();
265 }
266 view.platforms = v.get("platforms").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();
267 for (component, props) in v.get("changes").and_then(Value::as_object).into_iter().flatten() {
268 let Some(id) = (if component.is_empty() { Some(form) } else { ui.find_in(form, component) }) else { continue };
269 for (property, value) in props.as_object().into_iter().flatten() {
270 let value = match property.as_str() {
271 PARENT => value.as_str().map(|s| PropValue::String(s.to_string())),
272 INDEX => value.as_i64().map(PropValue::Int),
273 _ => crate::prop_from_json(ui, id, property, value).ok(),
274 };
275 if let Some(value) = value {
276 view.changes.push(aylis_core::ViewChange { component: component.clone(), property: property.clone(), value });
277 }
278 }
279 }
280 views.push(view);
281 }
282 views
283}
284
285fn save_views(views: &[aylis_core::FormView]) -> Value {
287 let list: Vec<Value> = views
288 .iter()
289 .map(|v| {
290 let mut changes = Map::new();
291 for c in &v.changes {
292 let entry = changes.entry(c.component.clone()).or_insert_with(|| Value::Object(Map::new()));
293 if let Value::Object(props) = entry {
294 props.insert(c.property.clone(), from_prop(&c.value));
295 }
296 }
297 let mut map = Map::new();
298 map.insert("name".into(), Value::from(v.name.clone()));
299 map.insert("max_width".into(), crate::value::number(v.max_width as f64));
300 for (key, value, default) in [
301 ("min_width", v.min_width, 0.0),
302 ("min_height", v.min_height, 0.0),
303 ("max_height", v.max_height, 0.0),
304 ("font_scale", v.font_scale, 1.0),
305 ("spacing_scale", v.spacing_scale, 1.0),
306 ] {
307 if value != default {
308 map.insert(key.into(), crate::value::number(value as f64));
309 }
310 }
311 if v.orientation != aylis_core::ViewOrientation::Any {
312 map.insert("orientation".into(), Value::from(aylis_core::PropEnum::name(v.orientation)));
313 }
314 if !v.platforms.is_empty() {
315 map.insert("platforms".into(), Value::from(v.platforms.clone()));
316 }
317 map.insert("changes".into(), Value::Object(changes));
318 Value::Object(map)
319 })
320 .collect();
321 Value::Array(list)
322}
323
324fn structure(path: &str) -> impl Fn(String) -> Error + '_ {
325 move |message| Error::Structure { path: path.to_string(), message }
326}
327
328fn strip_property(e: aylis_core::Error) -> String {
330 match e {
331 aylis_core::Error::TypeMismatch { expected, got, .. } => format!("esperado {expected}, recebido {got}"),
332 aylis_core::Error::InvalidValue { message, .. } => message,
333 other => other.to_string(),
334 }
335}
336
337pub fn save(ui: &Ui, root: ComponentId) -> Result<String> {
344 let value = save_value(ui, root)?;
345 Ok(crate::format::to_form_text(&value))
346}
347
348pub fn save_value(ui: &Ui, root: ComponentId) -> Result<Value> {
350 let mut doc = Map::new();
351 doc.insert("aylis".into(), Value::from(FORMAT_VERSION));
352 doc.insert("root".into(), save_node(ui, root, &mut Vec::new())?);
353 Ok(Value::Object(doc))
354}
355
356fn save_node(ui: &Ui, id: ComponentId, path: &mut Vec<String>) -> Result<Value> {
357 let component = ui.component(id).ok_or_else(|| structure(&path.join(" > "))("componente inexistente".into()))?;
358 let class = component.class_name();
359 let name = ui.name(id).unwrap_or_default();
360 path.push(if name.is_empty() { class.to_string() } else { name.to_string() });
361 let here = path.join(" > ");
362
363 let create = ui
365 .registry()
366 .get(class)
367 .ok_or_else(|| structure(&here)(format!("a classe {class} não está registrada; registre-a para poder salvar")))?
368 .create;
369 let defaults = create();
370
371 let mut map = Map::new();
372 map.insert("class".into(), Value::String(class.to_string()));
373 if !name.is_empty() {
374 map.insert("name".into(), Value::String(name.to_string()));
375 }
376 for info in ui.prop_infos(id) {
377 if info.read_only || info.runtime {
378 continue;
379 }
380 if ui.binding(id, info.name).is_some() {
382 continue;
383 }
384 let value = match ui.view_base(id, info.name) {
386 Some(base) => base.clone(),
387 None => ui.get_declared_prop(id, info.name).map_err(|source| Error::Component { path: here.clone(), source })?,
388 };
389 let json = match (&value, info.kind) {
390 (PropValue::Event(None), _) => continue,
391 (PropValue::Component(target), PropKind::Component) => {
392 match target.and_then(|t| ui.reference_name(id, t)) {
393 Some(target_name) => Value::String(target_name),
394 None => continue,
395 }
396 }
397 (PropValue::Event(Some(_)), _) => from_prop(&value),
398 _ => {
399 if read_prop(defaults.as_ref(), info.name).as_ref() == Some(&value) {
400 continue;
401 }
402 from_prop(&value)
403 }
404 };
405 map.insert(info.name.to_string(), json);
406 }
407
408 if !ui.bindings(id).is_empty() {
409 let mut list = Map::new();
410 for b in ui.bindings(id) {
411 let mut item = Map::new();
412 if let Some(name) = b.source.and_then(|s| ui.reference_name(id, s)) {
413 item.insert("source".into(), Value::String(name));
414 }
415 item.insert("field".into(), Value::String(b.path.clone()));
416 list.insert(b.property.clone(), Value::Object(item));
417 }
418 map.insert("bindings".into(), Value::Object(list));
419 }
420 if !ui.views(id).is_empty() {
421 map.insert("views".into(), save_views(ui.views(id)));
422 }
423
424 let own: Vec<ComponentId> = if class == "Frame" { Vec::new() } else { ui.base_children(id) };
427 let children: Vec<Value> = own.iter().map(|&c| save_node(ui, c, path)).collect::<Result<_>>()?;
428 if !children.is_empty() {
429 map.insert("children".into(), Value::Array(children));
430 }
431 path.pop();
432 Ok(Value::Object(map))
433}