1use std::cell::RefCell;
6
7use aylis_core::messages::{t, tf};
8use aylis_core::platform::LocaleInfo;
9use aylis_core::{Component, ComponentId, Error, PropEnum, PropInfo, PropKind, PropValue, Result, TextAlign};
10
11use crate::expr::Expr;
12use crate::mask::Mask;
13
14use crate::format::{date_time_pattern, format_date_time, format_number, parse_date_time, parse_number, plain_number, split};
15use crate::value::{Date, DateTime, Decimal, Rounding, Time, Timestamp, Value};
16
17#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
19pub enum FieldType {
20 #[default]
21 String,
22 Memo,
24 Integer,
25 Float,
26 Currency,
28 Boolean,
29 Date,
30 Time,
31 DateTime,
32 Blob,
33 AutoInc,
36 Timestamp,
39}
40
41impl FieldType {
42 pub const ALL: [FieldType; 12] = [
43 FieldType::String,
44 FieldType::Memo,
45 FieldType::Integer,
46 FieldType::Float,
47 FieldType::Currency,
48 FieldType::Boolean,
49 FieldType::Date,
50 FieldType::Time,
51 FieldType::DateTime,
52 FieldType::Blob,
53 FieldType::AutoInc,
54 FieldType::Timestamp,
55 ];
56
57 pub fn is_numeric(self) -> bool {
58 matches!(self, FieldType::Integer | FieldType::Float | FieldType::Currency | FieldType::AutoInc)
59 }
60}
61
62impl PropEnum for FieldType {
63 const NAMES: &'static [&'static str] =
64 &["string", "memo", "integer", "float", "currency", "boolean", "date", "time", "datetime", "blob", "auto_inc", "timestamp"];
65
66 fn from_index(index: usize) -> Option<Self> {
67 FieldType::ALL.get(index).copied()
68 }
69
70 fn index(self) -> usize {
71 self as usize
72 }
73}
74
75#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
77pub enum FieldKind {
78 #[default]
80 Data,
81 Calculated,
84 Lookup,
87}
88
89impl PropEnum for FieldKind {
90 const NAMES: &'static [&'static str] = &["data", "calculated", "lookup"];
91
92 fn from_index(index: usize) -> Option<Self> {
93 [FieldKind::Data, FieldKind::Calculated, FieldKind::Lookup].get(index).copied()
94 }
95
96 fn index(self) -> usize {
97 self as usize
98 }
99}
100
101#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
103pub enum CharCase {
104 #[default]
105 Normal,
106 Upper,
107 Lower,
108}
109
110impl PropEnum for CharCase {
111 const NAMES: &'static [&'static str] = &["normal", "upper", "lower"];
112
113 fn from_index(index: usize) -> Option<Self> {
114 [CharCase::Normal, CharCase::Upper, CharCase::Lower].get(index).copied()
115 }
116
117 fn index(self) -> usize {
118 self as usize
119 }
120}
121
122pub type GetTextFn = dyn Fn(&Value, bool) -> String;
123pub type SetTextFn = dyn Fn(&str) -> std::result::Result<Value, String>;
124pub type ValidateFn = dyn Fn(&Value) -> std::result::Result<(), String>;
125pub type CalculateFn = dyn Fn(&dyn Fn(&str) -> Value) -> Value;
127
128pub struct Field {
134 pub field_name: String,
136 pub field_type: FieldType,
139 pub size: usize,
141 pub scale: u8,
143 pub rounding: Rounding,
147 pub display_label: String,
149 pub display_width: f32,
151 pub display_format: String,
153 pub edit_format: String,
155 pub alignment: Option<TextAlign>,
157 pub required: bool,
159 pub read_only: bool,
161 pub visible: bool,
163 pub min: Option<f64>,
165 pub max: Option<f64>,
167 pub default_value: String,
169 pub display_values: String,
171 pub char_case: CharCase,
173 pub kind: FieldKind,
176 pub expression: String,
178 pub lookup_data_set: Option<ComponentId>,
180 pub key_fields: String,
182 pub lookup_key_fields: String,
184 pub lookup_result_field: String,
186 pub edit_mask: String,
188 pub sensitive: bool,
191 parsed: RefCell<Option<std::result::Result<Expr, String>>>,
192 calculate: Option<Box<CalculateFn>>,
193 get_text: Option<Box<GetTextFn>>,
194 set_text: Option<Box<SetTextFn>>,
195 validate: Option<Box<ValidateFn>>,
196 remote_texts: RefCell<std::collections::HashMap<String, String>>,
198 pending_texts: RefCell<Vec<Value>>,
200}
201
202impl Default for Field {
203 fn default() -> Self {
204 Self {
205 field_name: String::new(),
206 field_type: FieldType::String,
207 size: 0,
208 scale: 2,
209 rounding: Rounding::HalfUp,
210 display_label: String::new(),
211 display_width: 0.0,
212 display_format: String::new(),
213 edit_format: String::new(),
214 alignment: None,
215 required: false,
216 read_only: false,
217 visible: true,
218 min: None,
219 max: None,
220 default_value: String::new(),
221 display_values: String::new(),
222 char_case: CharCase::Normal,
223 kind: FieldKind::Data,
224 expression: String::new(),
225 lookup_data_set: None,
226 key_fields: String::new(),
227 lookup_key_fields: String::new(),
228 lookup_result_field: String::new(),
229 edit_mask: String::new(),
230 sensitive: false,
231 parsed: RefCell::new(None),
232 calculate: None,
233 get_text: None,
234 set_text: None,
235 validate: None,
236 remote_texts: RefCell::default(),
237 pending_texts: RefCell::default(),
238 }
239 }
240}
241
242impl Field {
243 pub fn new(name: impl Into<String>, field_type: FieldType) -> Self {
244 Self { field_name: name.into(), field_type, ..Default::default() }
245 }
246
247 pub fn label(mut self, label: impl Into<String>) -> Self {
248 self.display_label = label.into();
249 self
250 }
251
252 pub fn size(mut self, size: usize) -> Self {
253 self.size = size;
254 self
255 }
256
257 pub fn format(mut self, display_format: impl Into<String>) -> Self {
258 self.display_format = display_format.into();
259 self
260 }
261
262 pub fn align(mut self, alignment: TextAlign) -> Self {
264 self.alignment = Some(alignment);
265 self
266 }
267
268 pub fn width(mut self, display_width: f32) -> Self {
270 self.display_width = display_width;
271 self
272 }
273
274 pub fn required(mut self) -> Self {
275 self.required = true;
276 self
277 }
278
279 pub fn read_only(mut self) -> Self {
280 self.read_only = true;
281 self
282 }
283
284 pub fn min(mut self, min: f64) -> Self {
285 self.min = Some(min);
286 self
287 }
288
289 pub fn max(mut self, max: f64) -> Self {
290 self.max = Some(max);
291 self
292 }
293
294 pub fn default_value(mut self, text: impl Into<String>) -> Self {
295 self.default_value = text.into();
296 self
297 }
298
299 pub fn display_values(mut self, values: impl Into<String>) -> Self {
300 self.display_values = values.into();
301 self
302 }
303
304 pub fn char_case(mut self, char_case: CharCase) -> Self {
305 self.char_case = char_case;
306 self
307 }
308
309 pub fn on_get_text(mut self, f: impl Fn(&Value, bool) -> String + 'static) -> Self {
312 self.get_text = Some(Box::new(f));
313 self
314 }
315
316 pub fn on_set_text(mut self, f: impl Fn(&str) -> std::result::Result<Value, String> + 'static) -> Self {
318 self.set_text = Some(Box::new(f));
319 self
320 }
321
322 pub(crate) fn has_set_text(&self) -> bool {
324 self.set_text.is_some()
325 }
326
327 pub fn on_validate(mut self, f: impl Fn(&Value) -> std::result::Result<(), String> + 'static) -> Self {
329 self.validate = Some(Box::new(f));
330 self
331 }
332
333 pub fn calculated(mut self, expression: impl Into<String>) -> Self {
336 self.kind = FieldKind::Calculated;
337 self.expression = expression.into();
338 self
339 }
340
341 pub fn on_calculate(mut self, f: impl Fn(&dyn Fn(&str) -> Value) -> Value + 'static) -> Self {
343 self.kind = FieldKind::Calculated;
344 self.calculate = Some(Box::new(f));
345 self
346 }
347
348 pub fn lookup(mut self, data_set: ComponentId, key_field: &str, lookup_key: &str, result: &str) -> Self {
351 self.kind = FieldKind::Lookup;
352 self.lookup_data_set = Some(data_set);
353 self.key_fields = key_field.into();
354 self.lookup_key_fields = lookup_key.into();
355 self.lookup_result_field = result.into();
356 self
357 }
358
359 pub fn mask(mut self, mask: impl Into<String>) -> Self {
361 self.edit_mask = mask.into();
362 self
363 }
364
365 pub fn compute(&self, get: &dyn Fn(&str) -> Option<Value>) -> Value {
367 if let Some(f) = &self.calculate {
368 return f(&|name| get(name).unwrap_or_default());
369 }
370 if self.expression.trim().is_empty() {
371 return Value::Null;
372 }
373 let mut cache = self.parsed.borrow_mut();
374 let parsed = cache.get_or_insert_with(|| Expr::parse(&self.expression));
375 match parsed {
376 Ok(expr) => expr.eval(get).ok().and_then(|v| self.coerce(v).ok()).unwrap_or_default(),
377 Err(_) => Value::Null,
378 }
379 }
380
381 pub fn expression_error(&self) -> Option<String> {
383 if self.kind != FieldKind::Calculated || self.calculate.is_some() || self.expression.trim().is_empty() {
384 return None;
385 }
386 Expr::parse(&self.expression).err()
387 }
388
389 pub fn caption(&self) -> &str {
390 if self.display_label.is_empty() { &self.field_name } else { &self.display_label }
391 }
392
393 pub fn alignment(&self) -> TextAlign {
394 self.alignment.unwrap_or(if self.field_type.is_numeric() { TextAlign::Trailing } else { TextAlign::Leading })
395 }
396
397 pub fn is_read_only(&self) -> bool {
398 self.read_only || self.field_type == FieldType::AutoInc || self.kind != FieldKind::Data
399 }
400
401 fn bool_texts(&self) -> (String, String) {
402 let default = t("Sim;Não");
403 let values = if self.display_values.is_empty() { &default } else { &self.display_values };
404 let (t, f) = values.split_once(';').unwrap_or((values, ""));
405 (t.to_string(), f.to_string())
406 }
407
408 pub(crate) fn remote_text(&self, value: &Value) -> (Option<String>, bool) {
412 let key = crate::value_text(value);
413 if let Some(text) = self.remote_texts.borrow().get(&key) {
414 return (Some(text.clone()), false);
415 }
416 let mut pending = self.pending_texts.borrow_mut();
417 let first = pending.is_empty();
418 if !pending.contains(value) {
419 pending.push(value.clone());
420 }
421 (None, first)
422 }
423
424 pub(crate) fn take_pending_texts(&self) -> Vec<Value> {
426 std::mem::take(&mut *self.pending_texts.borrow_mut())
427 }
428
429 pub(crate) fn store_texts(&self, texts: impl IntoIterator<Item = (Value, String)>) {
431 let mut cache = self.remote_texts.borrow_mut();
432 for (value, text) in texts {
433 cache.insert(crate::value_text(&value), text);
434 }
435 }
436
437 pub fn clear_texts(&self) {
439 self.remote_texts.borrow_mut().clear();
440 }
441
442 pub fn text_of(&self, value: &Value, display: bool, locale: &LocaleInfo) -> String {
444 if let Some(f) = &self.get_text {
445 return f(value, display);
446 }
447 let format = if display || self.edit_format.is_empty() { &self.display_format } else { &self.edit_format };
448 if let (Some(mask), Value::String(s)) = (Mask::parse(&self.edit_mask), value) {
449 return mask.display(s);
450 }
451 match value {
452 Value::Null => String::new(),
453 Value::Bool(b) => {
454 let (t, f) = self.bool_texts();
455 if *b { t } else { f }
456 }
457 Value::String(s) => s.clone(),
458 Value::Int(_) | Value::Float(_) | Value::Decimal(_) => {
459 let number = match (value, self.field_type) {
460 (_, FieldType::Currency) => value.as_decimal().and_then(|d| d.round(self.scale, self.rounding)),
461 (Value::Float(f), _) => Decimal::from_f64(*f, 10).map(trim),
462 _ => value.as_decimal(),
463 };
464 let Some(number) = number else { return value.to_string() };
465 if display && !format.is_empty() {
466 format_number(number, format, locale)
467 } else if display && self.field_type == FieldType::Currency {
468 format_number(number, &format!("#,##0.{}", "0".repeat(self.scale as usize)), locale)
469 } else if !display && !self.edit_format.is_empty() {
470 format_number(number, &self.edit_format, locale)
471 } else {
472 plain_number(number, locale)
473 }
474 }
475 Value::Date(d) => format_date_time(Some(*d), None, self.pattern(format, &locale.short_date_format)),
476 Value::Time(t) => format_date_time(None, Some(*t), self.pattern(format, &locale.long_time_format)),
477 Value::DateTime(dt) => {
478 let (d, t) = split(*dt);
479 format_date_time(d, t, self.pattern(format, &date_time_pattern(locale)))
480 }
481 Value::Timestamp(ts) => {
483 let (d, t) = split(ts.to_local());
484 format_date_time(d, t, self.pattern(format, &date_time_pattern(locale)))
485 }
486 Value::Blob(b) => format!("({} bytes)", b.len()),
487 }
488 }
489
490 fn pattern<'a>(&self, format: &'a str, fallback: &'a str) -> &'a str {
491 if format.is_empty() { fallback } else { format }
492 }
493
494 fn to_scale(&self, value: Decimal) -> std::result::Result<Decimal, String> {
497 value.round(self.scale, self.rounding).ok_or_else(|| tf("{0}: o valor {1} não cabe", &[&self.caption(), &value.to_string()]))
498 }
499
500 pub fn parse_text(&self, text: &str, locale: &LocaleInfo) -> std::result::Result<Value, String> {
502 if let Some(f) = &self.set_text {
503 return f(text);
504 }
505 let trimmed = text.trim();
506 if trimmed.is_empty() && self.field_type != FieldType::String && self.field_type != FieldType::Memo {
507 return Ok(Value::Null);
508 }
509 let caption = self.caption();
510 if let Some(mask) = Mask::parse(&self.edit_mask) {
511 let stored = mask.stored(text);
512 if stored.is_empty() {
513 return Ok(Value::Null);
514 }
515 if !mask.is_complete(text) {
516 return Err(tf("{0} incompleto: '{1}'", &[&caption, &mask.apply(text)]));
517 }
518 return Ok(Value::String(stored));
519 }
520 match self.field_type {
521 FieldType::String | FieldType::Memo => {
522 if text.is_empty() {
523 return Ok(Value::Null);
524 }
525 Ok(Value::String(match self.char_case {
526 CharCase::Normal => text.to_string(),
527 CharCase::Upper => text.to_uppercase(),
528 CharCase::Lower => text.to_lowercase(),
529 }))
530 }
531 FieldType::Integer | FieldType::AutoInc => parse_number(trimmed, locale)
532 .filter(|d| d.rescale(0) == *d)
533 .and_then(|d| d.to_i64())
534 .map(Value::Int)
535 .ok_or_else(|| tf("'{0}' não é um número inteiro válido para {1}", &[&text, &caption])),
536 FieldType::Float => parse_number(trimmed, locale)
537 .map(|d| Value::Float(d.to_f64()))
538 .ok_or_else(|| tf("'{0}' não é um número válido para {1}", &[&text, &caption])),
539 FieldType::Currency => parse_number(trimmed, locale)
540 .ok_or_else(|| tf("'{0}' não é um valor válido para {1}", &[&text, &caption]))
541 .and_then(|d| self.to_scale(d).map(Value::Decimal)),
542 FieldType::Boolean => {
543 let (t, f) = self.bool_texts();
544 let lower = trimmed.to_lowercase();
545 if lower == t.to_lowercase() || ["true", "1", "sim", "s", "yes"].contains(&lower.as_str()) {
546 Ok(Value::Bool(true))
547 } else if lower == f.to_lowercase() || ["false", "0", "não", "nao", "n", "no"].contains(&lower.as_str()) {
548 Ok(Value::Bool(false))
549 } else {
550 Err(tf("'{0}' não é {1} nem {2}", &[&text, &t, &f]))
551 }
552 }
553 FieldType::Date => {
554 let pattern = self.pattern(&self.display_format, &locale.short_date_format);
555 parse_date_time(trimmed, pattern)
556 .and_then(|(d, _)| d)
557 .map(Value::Date)
558 .ok_or_else(|| tf("'{0}' não é uma data válida ({1})", &[&text, &pattern]))
559 }
560 FieldType::Time => {
561 let pattern = self.pattern(&self.display_format, &locale.long_time_format);
562 parse_date_time(trimmed, pattern)
563 .and_then(|(_, t)| t)
564 .or_else(|| Time::parse_iso(trimmed))
565 .map(Value::Time)
566 .ok_or_else(|| tf("'{0}' não é uma hora válida ({1})", &[&text, &pattern]))
567 }
568 FieldType::DateTime | FieldType::Timestamp => {
569 let full = date_time_pattern(locale);
570 let pattern = self.pattern(&self.display_format, &full);
571 let typed = parse_date_time(trimmed, pattern)
572 .and_then(|(d, t)| Some(DateTime::new(d?, t.unwrap_or_default())))
573 .or_else(|| {
574 let date_only = parse_date_time(trimmed, &locale.short_date_format)?.0?;
575 Some(DateTime::new(date_only, Time::default()))
576 })
577 .ok_or_else(|| tf("'{0}' não é uma data/hora válida ({1})", &[&text, &pattern]))?;
578 Ok(if self.field_type == FieldType::Timestamp { Value::Timestamp(Timestamp::from_local(typed)) } else { Value::DateTime(typed) })
580 }
581 FieldType::Blob => Err(tf("{0} não pode ser digitado", &[&caption])),
582 }
583 }
584
585 pub fn coerce(&self, value: Value) -> std::result::Result<Value, String> {
588 let wrong = |v: &Value| format!("{} não aceita valor do tipo {}", self.caption(), v.kind_name());
590 Ok(match (self.field_type, value) {
591 (FieldType::Integer | FieldType::AutoInc, Value::Int(i)) => Value::Int(i),
592 (FieldType::Float, Value::Float(f)) => Value::Float(f),
593 (_, Value::Null) => Value::Null,
594 (FieldType::String | FieldType::Memo, Value::String(s)) => Value::String(s),
595 (FieldType::Integer | FieldType::AutoInc, v) => Value::Int(v.as_i64().ok_or_else(|| wrong(&v))?),
596 (FieldType::Float, v) => Value::Float(v.as_f64().ok_or_else(|| wrong(&v))?),
597 (FieldType::Currency, v) => Value::Decimal(self.to_scale(v.as_decimal().ok_or_else(|| wrong(&v))?)?),
598 (FieldType::Boolean, Value::Bool(b)) => Value::Bool(b),
599 (FieldType::Date, v) => Value::Date(v.as_date().ok_or_else(|| wrong(&v))?),
600 (FieldType::Time, Value::Time(t)) => Value::Time(t),
601 (FieldType::DateTime, Value::DateTime(dt)) => Value::DateTime(dt),
602 (FieldType::DateTime, Value::Date(d)) => Value::DateTime(DateTime::new(d, Time::default())),
603 (FieldType::DateTime, Value::Timestamp(ts)) => Value::DateTime(ts.to_local()),
604 (FieldType::Timestamp, Value::Timestamp(ts)) => Value::Timestamp(ts),
605 (FieldType::Timestamp, Value::DateTime(dt)) => Value::Timestamp(Timestamp::from_local(dt)),
607 (FieldType::Timestamp, Value::Date(d)) => Value::Timestamp(Timestamp::from_local(DateTime::new(d, Time::default()))),
608 (FieldType::Blob, Value::Blob(b)) => Value::Blob(b),
609 (_, v) => return Err(wrong(&v)),
610 })
611 }
612
613 pub fn check(&self, value: &Value) -> std::result::Result<(), String> {
616 let caption = self.caption();
617 if let Value::String(s) = value {
618 if self.size > 0 && s.chars().count() > self.size {
619 return Err(tf("{0}: no máximo {1} caracteres", &[&caption, &self.size]));
620 }
621 }
622 if let Some(number) = value.as_f64().filter(|_| self.field_type.is_numeric()) {
623 if self.min.is_some_and(|min| number < min) {
624 return Err(tf("{0}: o mínimo é {1}", &[&caption, &self.min.unwrap_or_default()]));
625 }
626 if self.max.is_some_and(|max| number > max) {
627 return Err(tf("{0}: o máximo é {1}", &[&caption, &self.max.unwrap_or_default()]));
628 }
629 }
630 match &self.validate {
631 Some(f) => f(value),
632 None => Ok(()),
633 }
634 }
635
636 pub fn initial_value(&self, locale: &LocaleInfo) -> Value {
638 if self.default_value.is_empty() {
639 return Value::Null;
640 }
641 let v = match self.field_type {
642 FieldType::Date => Date::parse_iso(&self.default_value).map(Value::Date),
643 FieldType::Time => Time::parse_iso(&self.default_value).map(Value::Time),
644 FieldType::DateTime => DateTime::parse_iso(&self.default_value).map(Value::DateTime),
645 FieldType::Timestamp => Timestamp::parse_iso(&self.default_value).map(Value::Timestamp),
646 FieldType::Float | FieldType::Currency | FieldType::Integer => {
647 Decimal::parse(&self.default_value).map(Value::Decimal).and_then(|v| self.coerce(v).ok())
648 }
649 FieldType::Boolean => Some(Value::Bool(matches!(self.default_value.to_lowercase().as_str(), "true" | "1" | "sim"))),
650 _ => None,
651 };
652 v.or_else(|| self.parse_text(&self.default_value, locale).ok()).unwrap_or(Value::Null)
653 }
654}
655
656fn trim(d: Decimal) -> Decimal {
658 let mut d = d;
659 while d.scale() > 0 && d.mantissa() % 10 == 0 {
660 d = Decimal::new(d.mantissa() / 10, d.scale() - 1);
661 }
662 d
663}
664
665const FIELD_PROPS: &[PropInfo] = &[
666 PropInfo::new("field_name", PropKind::String, "Data"),
667 PropInfo::new("type", PropKind::Enum(FieldType::NAMES), "Data").rust_type("FieldType"),
668 PropInfo::new("size", PropKind::Int, "Data"),
669 PropInfo::new("scale", PropKind::Int, "Data"),
670 PropInfo::new("rounding", PropKind::Enum(Rounding::NAMES), "Data").rust_type("Rounding"),
671 PropInfo::new("display_label", PropKind::String, "Appearance"),
672 PropInfo::new("display_width", PropKind::Float, "Appearance"),
673 PropInfo::new("display_format", PropKind::String, "Appearance"),
674 PropInfo::new("edit_format", PropKind::String, "Appearance"),
675 PropInfo::new("alignment", PropKind::Enum(<TextAlign as PropEnum>::NAMES), "Appearance").rust_type("TextAlign"),
676 PropInfo::new("required", PropKind::Bool, "Behavior"),
677 PropInfo::new("read_only", PropKind::Bool, "Behavior"),
678 PropInfo::new("visible", PropKind::Bool, "Behavior"),
679 PropInfo::new("min", PropKind::Float, "Behavior"),
680 PropInfo::new("max", PropKind::Float, "Behavior"),
681 PropInfo::new("default_value", PropKind::String, "Data"),
682 PropInfo::new("display_values", PropKind::String, "Appearance"),
683 PropInfo::new("char_case", PropKind::Enum(CharCase::NAMES), "Behavior").rust_type("CharCase"),
684 PropInfo::new("edit_mask", PropKind::String, "Behavior"),
685 PropInfo::new("sensitive", PropKind::Bool, "Behavior"),
686 PropInfo::new("kind", PropKind::Enum(FieldKind::NAMES), "Data").rust_type("FieldKind"),
687 PropInfo::new("expression", PropKind::String, "Data"),
688 PropInfo::new("lookup_data_set", PropKind::Component, "Lookup"),
689 PropInfo::new("key_fields", PropKind::String, "Lookup"),
690 PropInfo::new("lookup_key_fields", PropKind::String, "Lookup"),
691 PropInfo::new("lookup_result_field", PropKind::String, "Lookup"),
692 PropInfo::new("on_change", PropKind::Event, "Events").event_arg(aylis_core::EventArg::Value(PropKind::String)),
693 PropInfo::new("on_get_text", PropKind::Event, "Events")
696 .event_arg(aylis_core::EventArg::Value(PropKind::Record(&crate::events::GET_TEXT_REQUEST_RECORD)))
697 .rust_type("GetTextRequest"),
698 PropInfo::new("on_set_text", PropKind::Event, "Events")
700 .event_arg(aylis_core::EventArg::Value(PropKind::Record(&crate::events::SET_TEXT_REQUEST_RECORD)))
701 .rust_type("SetTextRequest"),
702 PropInfo::new("on_validate", PropKind::Event, "Events"),
703];
704
705impl Component for Field {
706 fn class_name(&self) -> &'static str {
707 "Field"
708 }
709
710 fn notification(&mut self, freed: ComponentId) {
711 if self.lookup_data_set == Some(freed) {
712 self.lookup_data_set = None;
713 }
714 }
715
716 fn property_changed(&mut self, ctx: &mut aylis_core::EventCtx<'_>, name: &str) {
721 const SHOWN: &[&str] =
722 &["display_width", "display_label", "visible", "alignment", "display_format", "display_values", "scale", "rounding", "kind"];
723 if !SHOWN.contains(&name) {
724 return;
725 }
726 let Some(ds) = ctx.ui.parent(ctx.id).filter(|&p| ctx.ui.get::<crate::ClientDataSet>(p).is_some()) else { return };
727 let field = if self.field_name.is_empty() { ctx.ui.name(ctx.id).unwrap_or_default().to_string() } else { self.field_name.clone() };
728 ctx.ui.poster().post(move |ui| crate::handle::data_set(ui, ds).notify(crate::DataEvent::FieldChanged(field)));
729 }
730
731 fn props(&self) -> &'static [PropInfo] {
732 FIELD_PROPS
733 }
734
735 fn get_prop(&self, name: &str) -> Option<PropValue> {
736 let opt = |v: Option<f64>| v.map_or(PropValue::Null, PropValue::Float);
737 Some(match name {
738 "field_name" => self.field_name.clone().into(),
739 "type" => PropValue::enum_value(self.field_type),
740 "size" => PropValue::Int(self.size as i64),
741 "scale" => PropValue::Int(self.scale as i64),
742 "rounding" => PropValue::enum_value(self.rounding),
743 "display_label" => self.display_label.clone().into(),
744 "display_width" => self.display_width.into(),
745 "display_format" => self.display_format.clone().into(),
746 "edit_format" => self.edit_format.clone().into(),
747 "alignment" => self.alignment.map_or(PropValue::Null, PropValue::enum_value),
748 "required" => self.required.into(),
749 "read_only" => self.read_only.into(),
750 "sensitive" => self.sensitive.into(),
751 "visible" => self.visible.into(),
752 "min" => opt(self.min),
753 "max" => opt(self.max),
754 "default_value" => self.default_value.clone().into(),
755 "display_values" => self.display_values.clone().into(),
756 "char_case" => PropValue::enum_value(self.char_case),
757 "edit_mask" => self.edit_mask.clone().into(),
758 "kind" => PropValue::enum_value(self.kind),
759 "expression" => self.expression.clone().into(),
760 "lookup_data_set" => PropValue::Component(self.lookup_data_set),
761 "key_fields" => self.key_fields.clone().into(),
762 "lookup_key_fields" => self.lookup_key_fields.clone().into(),
763 "lookup_result_field" => self.lookup_result_field.clone().into(),
764 _ => return None,
765 })
766 }
767
768 fn set_prop(&mut self, name: &str, value: PropValue) -> Result<()> {
769 let opt = |v: &PropValue| -> Result<Option<f64>> {
770 match v {
771 PropValue::Null => Ok(None),
772 v => v.to_f64().map(Some),
773 }
774 };
775 match name {
776 "field_name" => self.field_name = value.to_str()?.to_string(),
777 "type" => self.field_type = value.to_enum()?,
778 "size" => self.size = value.to_i64()?.max(0) as usize,
779 "scale" => self.scale = value.to_i64()?.clamp(0, 18) as u8,
780 "rounding" => self.rounding = value.to_enum()?,
781 "display_label" => self.display_label = value.to_str()?.to_string(),
782 "display_width" => self.display_width = value.to_f32()?,
783 "display_format" => self.display_format = value.to_str()?.to_string(),
784 "edit_format" => self.edit_format = value.to_str()?.to_string(),
785 "alignment" => {
786 self.alignment = match value {
787 PropValue::Null => None,
788 v => Some(v.to_enum()?),
789 }
790 }
791 "required" => self.required = value.to_bool()?,
792 "read_only" => self.read_only = value.to_bool()?,
793 "sensitive" => self.sensitive = value.to_bool()?,
794 "visible" => self.visible = value.to_bool()?,
795 "min" => self.min = opt(&value)?,
796 "max" => self.max = opt(&value)?,
797 "default_value" => self.default_value = value.to_str()?.to_string(),
798 "display_values" => self.display_values = value.to_str()?.to_string(),
799 "char_case" => self.char_case = value.to_enum()?,
800 "edit_mask" => self.edit_mask = value.to_str()?.to_string(),
801 "kind" => self.kind = value.to_enum()?,
802 "expression" => {
803 self.expression = value.to_str()?.to_string();
804 *self.parsed.borrow_mut() = None;
805 }
806 "lookup_data_set" => self.lookup_data_set = value.to_component()?,
807 "key_fields" => self.key_fields = value.to_str()?.to_string(),
808 "lookup_key_fields" => self.lookup_key_fields = value.to_str()?.to_string(),
809 "lookup_result_field" => self.lookup_result_field = value.to_str()?.to_string(),
810 _ => return Err(Error::UnknownProperty(name.to_string())),
811 }
812 Ok(())
813 }
814}