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()) {
160 continue;
161 }
162 if let Err(e) = self.property(id, class, key, value, path) {
163 self.soft(e)?;
164 }
165 }
166
167 if let Some(Value::Object(list)) = obj.get("bindings") {
169 for (property, b) in list {
170 let source = b.get("source").and_then(Value::as_str).unwrap_or("").to_string();
171 let field = b.get("field").and_then(Value::as_str).unwrap_or("").to_string();
172 self.bindings.push((id, property.clone(), source, field));
173 }
174 }
175 if let Some(views) = obj.get("views").filter(|v| v.is_array()) {
177 self.views.push((id, views.clone()));
178 }
179
180 if class == "Frame" && obj.get("children").and_then(Value::as_array).is_some_and(|c| !c.is_empty()) {
183 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()))?;
184 path.pop();
185 return Ok(id);
186 }
187 match obj.get("children") {
188 None | Some(Value::Null) => {}
189 Some(Value::Array(children)) => {
190 for child in children {
191 self.node(child, Some(id), path)?;
192 }
193 }
194 Some(other) => {
195 return Err(structure(&here(path))(format!("\"children\" deve ser uma lista, recebido {}", describe(other))));
196 }
197 }
198 path.pop();
199 Ok(id)
200 }
201
202 fn property(&mut self, id: ComponentId, class: &str, key: &str, value: &Value, path: &[String]) -> Result<()> {
204 let fail = |message: String| Error::Property { path: path.join(" > "), property: key.to_string(), message };
205 if key.contains('.') {
207 let v = value.as_f64().ok_or_else(|| fail(format!("esperado número, recebido {}", describe(value))))?;
208 return self.ui.set_prop(id, key, v).map_err(|e| fail(e.to_string()));
209 }
210 let info = self.ui.prop_info(id, key).ok_or_else(|| fail(format!("a classe {class} não tem esta propriedade")))?;
211 let prop = to_prop(value, info.kind, self.ui.theme()).map_err(fail)?;
212 if info.kind == PropKind::Component {
213 if let PropValue::String(target) = prop {
214 self.deferred.push((id, key.to_string(), target, path.join(" > ")));
215 }
216 return Ok(());
217 }
218 if let (PropValue::String(text), true) = (&prop, aylis_core::i18n::TRANSLATABLE.contains(&key)) {
220 let text = text.clone();
221 return self.ui.set_translated(id, key, &text).map_err(|e| fail(strip_property(e)));
222 }
223 self.ui.set_prop(id, key, prop).map_err(|e| fail(strip_property(e)))
224 }
225
226 pub(crate) fn fixup(&mut self) -> Result<()> {
228 for (id, property, target, path) in std::mem::take(&mut self.deferred) {
229 if let Err(e) = self.ui.set_prop(id, &property, target.as_str()) {
230 self.soft(Error::Property { path, property, message: strip_property(e) })?;
231 }
232 }
233 for (id, property, source, field) in std::mem::take(&mut self.bindings) {
234 let source = self.ui.resolve_reference(id, &source);
235 self.ui.set_binding(id, &property, source, &field);
236 }
237 for (form, list) in std::mem::take(&mut self.views) {
238 let views = load_views(self.ui, form, &list);
239 self.ui.set_views(form, views);
240 }
241 Ok(())
242 }
243}
244
245fn load_views(ui: &Ui, form: ComponentId, list: &Value) -> Vec<aylis_core::FormView> {
251 use aylis_core::views::{INDEX, PARENT};
252 let mut views = Vec::new();
253 for v in list.as_array().into_iter().flatten() {
254 let Some(name) = v.get("name").and_then(Value::as_str) else { continue };
255 let number = |key: &str, default: f64| v.get(key).and_then(Value::as_f64).unwrap_or(default) as f32;
256 let mut view = aylis_core::FormView::new(name, number("max_width", 0.0));
257 view.min_width = number("min_width", 0.0);
258 view.min_height = number("min_height", 0.0);
259 view.max_height = number("max_height", 0.0);
260 view.font_scale = number("font_scale", 1.0);
261 view.spacing_scale = number("spacing_scale", 1.0);
262 if let Some(o) = v.get("orientation").and_then(Value::as_str) {
263 view.orientation = <aylis_core::ViewOrientation as aylis_core::PropEnum>::from_name(o).unwrap_or_default();
264 }
265 view.platforms = v.get("platforms").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();
266 for (component, props) in v.get("changes").and_then(Value::as_object).into_iter().flatten() {
267 let Some(id) = (if component.is_empty() { Some(form) } else { ui.find_in(form, component) }) else { continue };
268 for (property, value) in props.as_object().into_iter().flatten() {
269 let value = match property.as_str() {
270 PARENT => value.as_str().map(|s| PropValue::String(s.to_string())),
271 INDEX => value.as_i64().map(PropValue::Int),
272 _ => crate::prop_from_json(ui, id, property, value).ok(),
273 };
274 if let Some(value) = value {
275 view.changes.push(aylis_core::ViewChange { component: component.clone(), property: property.clone(), value });
276 }
277 }
278 }
279 views.push(view);
280 }
281 views
282}
283
284fn save_views(views: &[aylis_core::FormView]) -> Value {
286 let list: Vec<Value> = views
287 .iter()
288 .map(|v| {
289 let mut changes = Map::new();
290 for c in &v.changes {
291 let entry = changes.entry(c.component.clone()).or_insert_with(|| Value::Object(Map::new()));
292 if let Value::Object(props) = entry {
293 props.insert(c.property.clone(), from_prop(&c.value));
294 }
295 }
296 let mut map = Map::new();
297 map.insert("name".into(), Value::from(v.name.clone()));
298 map.insert("max_width".into(), crate::value::number(v.max_width as f64));
299 for (key, value, default) in [
300 ("min_width", v.min_width, 0.0),
301 ("min_height", v.min_height, 0.0),
302 ("max_height", v.max_height, 0.0),
303 ("font_scale", v.font_scale, 1.0),
304 ("spacing_scale", v.spacing_scale, 1.0),
305 ] {
306 if value != default {
307 map.insert(key.into(), crate::value::number(value as f64));
308 }
309 }
310 if v.orientation != aylis_core::ViewOrientation::Any {
311 map.insert("orientation".into(), Value::from(aylis_core::PropEnum::name(v.orientation)));
312 }
313 if !v.platforms.is_empty() {
314 map.insert("platforms".into(), Value::from(v.platforms.clone()));
315 }
316 map.insert("changes".into(), Value::Object(changes));
317 Value::Object(map)
318 })
319 .collect();
320 Value::Array(list)
321}
322
323fn structure(path: &str) -> impl Fn(String) -> Error + '_ {
324 move |message| Error::Structure { path: path.to_string(), message }
325}
326
327fn strip_property(e: aylis_core::Error) -> String {
329 match e {
330 aylis_core::Error::TypeMismatch { expected, got, .. } => format!("esperado {expected}, recebido {got}"),
331 aylis_core::Error::InvalidValue { message, .. } => message,
332 other => other.to_string(),
333 }
334}
335
336pub fn save(ui: &Ui, root: ComponentId) -> Result<String> {
343 let value = save_value(ui, root)?;
344 Ok(crate::format::to_form_text(&value))
345}
346
347pub fn save_value(ui: &Ui, root: ComponentId) -> Result<Value> {
349 let mut doc = Map::new();
350 doc.insert("aylis".into(), Value::from(FORMAT_VERSION));
351 doc.insert("root".into(), save_node(ui, root, &mut Vec::new())?);
352 Ok(Value::Object(doc))
353}
354
355fn save_node(ui: &Ui, id: ComponentId, path: &mut Vec<String>) -> Result<Value> {
356 let component = ui.component(id).ok_or_else(|| structure(&path.join(" > "))("componente inexistente".into()))?;
357 let class = component.class_name();
358 let name = ui.name(id).unwrap_or_default();
359 path.push(if name.is_empty() { class.to_string() } else { name.to_string() });
360 let here = path.join(" > ");
361
362 let create = ui
364 .registry()
365 .get(class)
366 .ok_or_else(|| structure(&here)(format!("a classe {class} não está registrada; registre-a para poder salvar")))?
367 .create;
368 let defaults = create();
369
370 let mut map = Map::new();
371 map.insert("class".into(), Value::String(class.to_string()));
372 if !name.is_empty() {
373 map.insert("name".into(), Value::String(name.to_string()));
374 }
375 for info in ui.prop_infos(id) {
376 if info.read_only || info.runtime {
377 continue;
378 }
379 if ui.binding(id, info.name).is_some() {
381 continue;
382 }
383 let value = match ui.view_base(id, info.name) {
385 Some(base) => base.clone(),
386 None => ui.get_declared_prop(id, info.name).map_err(|source| Error::Component { path: here.clone(), source })?,
387 };
388 let json = match (&value, info.kind) {
389 (PropValue::Event(None), _) => continue,
390 (PropValue::Component(target), PropKind::Component) => {
391 match target.and_then(|t| ui.reference_name(id, t)) {
392 Some(target_name) => Value::String(target_name),
393 None => continue,
394 }
395 }
396 (PropValue::Event(Some(_)), _) => from_prop(&value),
397 _ => {
398 if read_prop(defaults.as_ref(), info.name).as_ref() == Some(&value) {
399 continue;
400 }
401 match (&value, info.kind) {
402 (PropValue::String(text), PropKind::Record(_) | PropKind::RecordList(_)) => {
404 match serde_json::from_str::<Value>(text) {
405 Ok(v @ (Value::Array(_) | Value::Object(_))) => v,
406 _ => from_prop(&value),
407 }
408 }
409 _ => from_prop(&value),
410 }
411 }
412 };
413 map.insert(info.name.to_string(), json);
414 }
415
416 if !ui.bindings(id).is_empty() {
417 let mut list = Map::new();
418 for b in ui.bindings(id) {
419 let mut item = Map::new();
420 if let Some(name) = b.source.and_then(|s| ui.reference_name(id, s)) {
421 item.insert("source".into(), Value::String(name));
422 }
423 item.insert("field".into(), Value::String(b.path.clone()));
424 list.insert(b.property.clone(), Value::Object(item));
425 }
426 map.insert("bindings".into(), Value::Object(list));
427 }
428 if !ui.views(id).is_empty() {
429 map.insert("views".into(), save_views(ui.views(id)));
430 }
431
432 let own: Vec<ComponentId> = if class == "Frame" { Vec::new() } else { ui.base_children(id) };
435 let children: Vec<Value> = own.iter().map(|&c| save_node(ui, c, path)).collect::<Result<_>>()?;
436 if !children.is_empty() {
437 map.insert("children".into(), Value::Array(children));
438 }
439 path.pop();
440 Ok(Value::Object(map))
441}