1use std::fmt;
5
6use aylis_core::{Component, ComponentId, EventCtx, PropEnum, Ui, properties};
7
8use crate::field::FieldKind;
9use crate::store::ColumnStore;
10use crate::value::Value;
11
12#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
14pub enum DataSetState {
15 #[default]
16 Inactive,
17 Browse,
18 Edit,
19 Insert,
20}
21
22impl DataSetState {
23 pub fn is_editing(self) -> bool {
24 matches!(self, DataSetState::Edit | DataSetState::Insert)
25 }
26}
27
28#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
30pub enum ApplyMode {
31 #[default]
33 Cached,
34 OnPost,
36}
37
38impl PropEnum for ApplyMode {
39 const NAMES: &'static [&'static str] = &["cached", "on_post"];
40
41 fn from_index(index: usize) -> Option<Self> {
42 [ApplyMode::Cached, ApplyMode::OnPost].get(index).copied()
43 }
44
45 fn index(self) -> usize {
46 self as usize
47 }
48}
49
50#[derive(Clone, Copy, Debug, PartialEq, Eq)]
52pub enum RowStatus {
53 Unmodified,
54 Modified,
55 Inserted,
56}
57
58#[derive(Clone, Debug, PartialEq)]
60pub struct Row {
61 pub id: u64,
63 pub(crate) data: RowData,
66 pub status: RowStatus,
67 pub original: Option<Box<Vec<Value>>>,
69 pub error: Option<Box<String>>,
71}
72
73#[derive(Clone, Debug, PartialEq)]
75pub(crate) enum RowData {
76 Stored(u32),
78 Owned(Box<Vec<Value>>),
79}
80
81#[derive(Clone, Copy)]
83pub(crate) enum Src<'a> {
84 Slice(&'a [Value]),
85 Store(&'a ColumnStore, u32),
86}
87
88impl Src<'_> {
89 pub(crate) fn get(&self, col: usize) -> Value {
90 match self {
91 Src::Slice(v) => v.get(col).cloned().unwrap_or_default(),
92 Src::Store(s, row) => s.get(*row, col),
93 }
94 }
95}
96
97pub(crate) fn src<'a>(store: &'a ColumnStore, row: &'a Row) -> Src<'a> {
99 match &row.data {
100 RowData::Stored(i) => Src::Store(store, *i),
101 RowData::Owned(v) => Src::Slice(v),
102 }
103}
104
105pub(crate) fn owned<'a>(store: &ColumnStore, row: &'a mut Row) -> &'a mut Vec<Value> {
107 if let RowData::Stored(i) = row.data {
108 row.data = RowData::Owned(Box::new(store.row(i)));
109 }
110 match &mut row.data {
111 RowData::Owned(v) => v,
112 RowData::Stored(_) => unreachable!("convertido acima"),
113 }
114}
115
116#[derive(Clone, Copy, Debug, PartialEq, Eq)]
118pub enum ChangeKind {
119 Insert,
120 Update,
121 Delete,
122}
123
124impl ChangeKind {
125 pub fn name(self) -> &'static str {
126 match self {
127 ChangeKind::Insert => "insert",
128 ChangeKind::Update => "update",
129 ChangeKind::Delete => "delete",
130 }
131 }
132}
133
134#[derive(Clone, Debug, PartialEq)]
136pub struct Change {
137 pub reference: u64,
140 pub kind: ChangeKind,
141 pub data_set: String,
143 pub key: Vec<(String, Value)>,
145 pub old: Vec<(String, Value)>,
147 pub new: Vec<(String, Value)>,
149 pub master: Option<MasterLink>,
152}
153
154#[derive(Clone, Debug, PartialEq)]
156pub struct MasterLink {
157 pub data_set: String,
158 pub reference: u64,
160 pub fields: Vec<(String, String)>,
162}
163
164pub(crate) fn new_row_id() -> u64 {
167 use std::sync::atomic::{AtomicU64, Ordering};
168 static NEXT: AtomicU64 = AtomicU64::new(1);
169 NEXT.fetch_add(1, Ordering::Relaxed)
170}
171
172#[derive(Clone, Debug, Default, PartialEq)]
174pub struct ApplyResult {
175 pub reference: u64,
176 pub error: Option<String>,
178 pub values: Vec<(String, Value)>,
180}
181
182impl ApplyResult {
183 pub fn ok(reference: u64) -> Self {
184 Self { reference, ..Default::default() }
185 }
186
187 pub fn with_value(mut self, field: &str, value: impl Into<Value>) -> Self {
188 self.values.push((field.to_string(), value.into()));
189 self
190 }
191
192 pub fn error(reference: u64, message: impl Into<String>) -> Self {
193 Self { reference, error: Some(message.into()), values: Vec::new() }
194 }
195}
196
197#[derive(Clone, Debug, PartialEq, Eq)]
199pub struct DataError {
200 pub message: String,
201 pub field: Option<String>,
203 pub waiting: bool,
206}
207
208impl DataError {
209 pub fn new(message: impl Into<String>) -> Self {
210 Self { message: message.into(), field: None, waiting: false }
211 }
212
213 pub fn on_field(field: &str, message: impl Into<String>) -> Self {
214 Self { message: message.into(), field: Some(field.to_string()), waiting: false }
215 }
216
217 pub fn waiting() -> Self {
219 Self { message: "a gravação espera a resposta do backend".into(), field: None, waiting: true }
220 }
221}
222
223impl fmt::Display for DataError {
224 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
225 f.write_str(&self.message)
226 }
227}
228
229impl std::error::Error for DataError {}
230
231impl From<String> for DataError {
232 fn from(message: String) -> Self {
233 DataError::new(message)
234 }
235}
236
237impl From<&str> for DataError {
238 fn from(message: &str) -> Self {
239 DataError::new(message)
240 }
241}
242
243pub type DataResult<T = ()> = Result<T, DataError>;
244
245#[derive(Clone, Debug, PartialEq, Eq)]
247pub enum DataEvent {
248 ActiveChanged,
250 DataSetChanged,
252 Scrolled,
254 RecordChanged(Option<String>),
256 StateChanged,
258 UpdateData,
260 FieldChanged(String),
263}
264
265#[derive(Clone, Debug, PartialEq)]
268pub struct DataMessage {
269 pub data_set: ComponentId,
270 pub event: DataEvent,
271}
272
273pub(crate) type DataSetHook = dyn FnMut(&mut Ui, ComponentId) -> Result<(), String>;
274pub(crate) type FetchHook = dyn FnMut(&mut Ui, ComponentId, usize);
275pub(crate) type ApplyHandler = dyn FnMut(&[Change]) -> Vec<ApplyResult>;
276pub(crate) type FilterHook = dyn Fn(&dyn Fn(&str) -> Value) -> bool;
278
279#[derive(Default)]
280pub(crate) struct Hooks {
281 pub(crate) on_new_record: Option<Box<DataSetHook>>,
282 pub(crate) before_post: Option<Box<DataSetHook>>,
283 pub(crate) after_post: Option<Box<DataSetHook>>,
284 pub(crate) before_delete: Option<Box<DataSetHook>>,
285 pub(crate) after_scroll: Option<Box<DataSetHook>>,
286 pub(crate) apply: Option<Box<ApplyHandler>>,
287 pub(crate) fetch: Option<Box<FetchHook>>,
288 pub(crate) filter_record: Option<Box<FilterHook>>,
289}
290
291#[derive(Clone, Debug)]
293pub(crate) struct Column {
294 pub(crate) field: ComponentId,
295 pub(crate) name: String,
296 pub(crate) kind: FieldKind,
297}
298
299#[derive(Default)]
306pub struct ClientDataSet {
307 pub key_fields: String,
309 pub apply_mode: ApplyMode,
312 pub read_only: bool,
314 pub filter: String,
317 pub filtered: bool,
320 pub index_field_names: String,
323 pub indexes: String,
327 pub index_name: String,
330 pub params: String,
336 pub status_filter: String,
339 pub master_source: Option<ComponentId>,
341 pub master_fields: String,
345 pub apply_separately: bool,
348 pub(crate) param_values: Vec<(String, Value)>,
350 pub(crate) hidden: Vec<Row>,
352 pub(crate) needs_refilter: bool,
353 pub(crate) wants_open: bool,
356 pub(crate) columns: Vec<Column>,
357 pub(crate) column_index: std::collections::HashMap<String, usize>,
360 pub(crate) rows: Vec<Row>,
361 pub(crate) store: ColumnStore,
363 pub(crate) deleted: Vec<Row>,
364 pub(crate) cursor: usize,
365 pub(crate) bof: bool,
366 pub(crate) eof: bool,
367 pub(crate) state: DataSetState,
368 pub(crate) buffer: Option<Vec<Value>>,
369 pub(crate) insert_at: usize,
370 pub(crate) next_temp_key: i64,
371 pub(crate) disabled: u32,
372 pub(crate) pending_notify: bool,
373 pub(crate) pending_error: Option<String>,
374 pub(crate) field_errors: Vec<(String, String)>,
376 pub(crate) awaiting_text: Vec<String>,
379 pub(crate) post_deferred: bool,
381 pub(crate) asking: Option<Asking>,
384 pub(crate) answered: Option<Asking>,
385 pub(crate) applying: bool,
388 pub(crate) apply_errors: usize,
389 pub record_total: i64,
392 pub max_records: i64,
395 pub(crate) has_more: bool,
397 pub(crate) fetching: bool,
398 pub(crate) partial_notice: String,
401 pub(crate) querying: bool,
404 pub(crate) inferred_fields: Vec<ComponentId>,
407 pub(crate) hooks: Hooks,
408}
409
410impl ClientDataSet {
411 pub fn new() -> Self {
412 Self::default()
413 }
414
415 pub fn partial_notice(&self) -> &str {
418 &self.partial_notice
419 }
420
421 pub fn with_key(mut self, key_fields: &str) -> Self {
422 self.key_fields = key_fields.to_string();
423 self
424 }
425
426 pub fn with_apply_mode(mut self, mode: ApplyMode) -> Self {
427 self.apply_mode = mode;
428 self
429 }
430
431 pub fn state(&self) -> DataSetState {
432 self.state
433 }
434
435 pub fn is_active(&self) -> bool {
436 self.state != DataSetState::Inactive
437 }
438
439 pub fn rows(&self) -> &[Row] {
440 &self.rows
441 }
442
443 pub fn deleted_rows(&self) -> &[Row] {
444 &self.deleted
445 }
446
447 pub(crate) fn column(&self, name: &str) -> Option<usize> {
448 if let Some(&i) = self.column_index.get(name) {
449 return Some(i);
450 }
451 if name.bytes().any(|b| b.is_ascii_uppercase()) {
452 if let Some(&i) = self.column_index.get(&name.to_ascii_lowercase()) {
453 return Some(i);
454 }
455 }
456 self.columns.iter().position(|c| c.name.eq_ignore_ascii_case(name))
458 }
459
460 pub(crate) fn set_columns(&mut self, columns: Vec<Column>) {
462 self.column_index = columns.iter().enumerate().rev().map(|(i, c)| (c.name.to_ascii_lowercase(), i)).collect();
463 self.columns = columns;
464 }
465
466 pub(crate) fn current(&self) -> Option<Src<'_>> {
468 match &self.buffer {
469 Some(b) => Some(Src::Slice(b)),
470 None => self.rows.get(self.cursor).map(|r| src(&self.store, r)),
471 }
472 }
473
474 pub fn row_values(&self, row: &Row) -> Vec<Value> {
477 match &row.data {
478 RowData::Stored(i) => self.store.row(*i),
479 RowData::Owned(v) => v.as_ref().clone(),
480 }
481 }
482
483 pub fn storage_bytes(&self) -> usize {
485 self.store.approx_bytes()
486 }
487
488 fn active_prop(&self) -> bool {
489 self.is_active() || self.wants_open
490 }
491
492 pub fn effective_index(&self) -> Result<String, String> {
494 if self.index_name.trim().is_empty() {
495 return Ok(self.index_field_names.clone());
496 }
497 crate::records::index_defs(&self.indexes)
498 .into_iter()
499 .find(|(n, _)| n.eq_ignore_ascii_case(self.index_name.trim()))
500 .map(|(_, fields)| fields)
501 .ok_or_else(|| format!("índice '{}' não existe em indexes", self.index_name.trim()))
502 }
503
504 pub fn index_names(&self) -> Vec<String> {
506 crate::records::index_defs(&self.indexes).into_iter().map(|(n, _)| n).collect()
507 }
508
509 pub fn param(&self, name: &str) -> Option<Value> {
512 if let Some((_, v)) = self.param_values.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)) {
513 return Some(v.clone());
514 }
515 let (_, text) = crate::records::filter_params(&self.params).into_iter().find(|(n, _)| n.eq_ignore_ascii_case(name))?;
516 let text = text.trim();
517 Some(if let Ok(i) = text.parse::<i64>() {
518 Value::Int(i)
519 } else if let Ok(x) = text.parse::<f64>() {
520 Value::Float(x)
521 } else if text.eq_ignore_ascii_case("true") || text.eq_ignore_ascii_case("false") {
522 Value::Bool(text.eq_ignore_ascii_case("true"))
523 } else {
524 Value::String(text.to_string())
525 })
526 }
527
528 pub(crate) fn status_allowed(&self) -> Option<Vec<RowStatus>> {
530 let names: Vec<String> = self.status_filter.split(';').map(|s| s.trim().to_ascii_lowercase()).filter(|s| !s.is_empty()).collect();
531 if names.is_empty() {
532 return None;
533 }
534 Some(
535 names
536 .iter()
537 .filter_map(|n| match n.as_str() {
538 "unmodified" => Some(RowStatus::Unmodified),
539 "modified" => Some(RowStatus::Modified),
540 "inserted" => Some(RowStatus::Inserted),
541 _ => None,
542 })
543 .collect(),
544 )
545 }
546}
547
548impl Component for ClientDataSet {
549 fn class_name(&self) -> &'static str {
550 "ClientDataSet"
551 }
552
553 fn props(&self) -> &'static [aylis_core::PropInfo] {
554 use aylis_core::{EventArg, PropInfo, PropKind};
555 const PROPS: &[PropInfo] = &[
556 PropInfo::new("key_fields", PropKind::String, "Data"),
557 PropInfo::new("apply_mode", PropKind::Enum(ApplyMode::NAMES), "Data").rust_type("ApplyMode"),
558 PropInfo::new("read_only", PropKind::Bool, "Data"),
559 PropInfo::new("active", PropKind::Bool, "Data"),
560 PropInfo::new("filter", PropKind::String, "Data"),
561 PropInfo::new("filtered", PropKind::Bool, "Data"),
562 PropInfo::new("index_field_names", PropKind::String, "Data"),
563 PropInfo::new("indexes", PropKind::RecordList(&crate::INDEX_DEF_RECORD), "Data"),
564 PropInfo::new("index_name", PropKind::String, "Data"),
565 PropInfo::new("params", PropKind::RecordList(&crate::FILTER_PARAM_RECORD), "Data"),
566 PropInfo::new("status_filter", PropKind::String, "Data"),
567 PropInfo::new("master_source", PropKind::Component, "Data"),
568 PropInfo::new("master_fields", PropKind::RecordList(&crate::MASTER_FIELD_RECORD), "Data"),
569 PropInfo::new("apply_separately", PropKind::Bool, "Data"),
570 PropInfo::new("record_total", PropKind::Int, "Data"),
571 PropInfo::new("max_records", PropKind::Int, "Data"),
572 PropInfo::new("partial_notice", PropKind::String, "Data").read_only().runtime(),
573 PropInfo::new("on_master_change", PropKind::Event, "Events")
574 .event_arg(EventArg::Value(PropKind::Record(&crate::events::MASTER_CHANGE_RECORD)))
575 .rust_type("MasterChange"),
576 PropInfo::new("after_scroll", PropKind::Event, "Events").event_arg(EventArg::None),
577 PropInfo::new("before_post", PropKind::Event, "Events"),
578 PropInfo::new("after_post", PropKind::Event, "Events").event_arg(EventArg::None),
579 PropInfo::new("before_delete", PropKind::Event, "Events"),
580 PropInfo::new("on_state_change", PropKind::Event, "Events").event_arg(EventArg::None),
581 PropInfo::new("on_apply_updates", PropKind::Event, "Events"),
582 PropInfo::new("on_reconcile_error", PropKind::Event, "Events").event_arg(EventArg::Value(PropKind::String)),
583 PropInfo::new("on_error", PropKind::Event, "Events").event_arg(EventArg::Value(PropKind::String)),
584 PropInfo::new("on_fetch", PropKind::Event, "Events").event_arg(EventArg::Value(PropKind::Int)),
585 PropInfo::new("on_server_query", PropKind::Event, "Events")
586 .event_arg(EventArg::Value(PropKind::Record(&crate::events::SERVER_QUERY_RECORD)))
587 .rust_type("ServerQuery"),
588 ];
589 PROPS
590 }
591
592 fn get_prop(&self, name: &str) -> Option<aylis_core::PropValue> {
593 use aylis_core::PropValue;
594 Some(match name {
595 "key_fields" => self.key_fields.clone().into(),
596 "apply_mode" => PropValue::enum_value(self.apply_mode),
597 "read_only" => self.read_only.into(),
598 "active" => self.active_prop().into(),
599 "filter" => self.filter.clone().into(),
600 "filtered" => self.filtered.into(),
601 "index_field_names" => self.index_field_names.clone().into(),
602 "indexes" => self.indexes.clone().into(),
603 "index_name" => self.index_name.clone().into(),
604 "params" => self.params.clone().into(),
605 "status_filter" => self.status_filter.clone().into(),
606 "master_source" => PropValue::Component(self.master_source),
607 "master_fields" => self.master_fields.clone().into(),
608 "apply_separately" => self.apply_separately.into(),
609 "record_total" => self.record_total.into(),
610 "max_records" => self.max_records.into(),
611 "partial_notice" => self.partial_notice.clone().into(),
612 _ => return None,
613 })
614 }
615
616 fn set_prop(&mut self, name: &str, value: aylis_core::PropValue) -> aylis_core::Result<()> {
617 match name {
618 "key_fields" => self.key_fields = value.to_str()?.to_string(),
619 "apply_mode" => self.apply_mode = value.to_enum()?,
620 "read_only" => self.read_only = value.to_bool()?,
621 "active" => self.wants_open = value.to_bool()?,
623 "filter" => self.filter = value.to_str()?.to_string(),
624 "filtered" => self.filtered = value.to_bool()?,
625 "index_field_names" => {
626 self.index_field_names = value.to_str()?.to_string();
627 self.index_name.clear();
628 }
629 "indexes" => self.indexes = value.to_str()?.to_string(),
630 "index_name" => self.index_name = value.to_str()?.to_string(),
631 "params" => self.params = value.to_str()?.to_string(),
632 "status_filter" => self.status_filter = value.to_str()?.to_string(),
633 "master_source" => self.master_source = value.to_component()?,
634 "master_fields" => self.master_fields = value.to_str()?.to_string(),
635 "apply_separately" => self.apply_separately = value.to_bool()?,
636 "record_total" => self.record_total = value.to_i64()?.max(0),
637 "max_records" => self.max_records = value.to_i64()?.max(0),
638 _ => return Err(aylis_core::Error::UnknownProperty(name.to_string())),
639 }
640 if REFILTER_PROPS.contains(&name) {
641 self.needs_refilter = true;
642 }
643 Ok(())
644 }
645
646 fn property_changed(&mut self, ctx: &mut EventCtx<'_>, name: &str) {
649 if name == "record_total" && self.is_active() {
651 let id = ctx.id;
652 ctx.ui.poster().post(move |ui| crate::handle::data_set(ui, id).notify(DataEvent::DataSetChanged));
653 }
654 if self.needs_refilter && self.is_active() && REFILTER_PROPS.contains(&name) {
655 let id = ctx.id;
656 ctx.ui.poster().post(move |ui| {
657 let _ = crate::handle::data_set(ui, id).refilter();
658 });
659 }
660 }
661
662 fn notification(&mut self, freed: ComponentId) {
663 if self.master_source == Some(freed) {
664 self.master_source = None;
665 }
666 }
667}
668
669const REFILTER_PROPS: &[&str] = &["filter", "filtered", "index_field_names", "indexes", "index_name", "params", "status_filter", "master_source", "master_fields"];
673
674pub struct DataSource {
676 pub data_set: Option<ComponentId>,
678 pub auto_edit: bool,
680 pub enabled: bool,
682}
683
684impl Default for DataSource {
685 fn default() -> Self {
686 Self { data_set: None, auto_edit: true, enabled: true }
687 }
688}
689
690impl DataSource {
691 pub fn new(data_set: ComponentId) -> Self {
692 Self { data_set: Some(data_set), ..Default::default() }
693 }
694}
695
696impl Component for DataSource {
697 fn class_name(&self) -> &'static str {
698 "DataSource"
699 }
700
701 properties! {
702 data_set: Option<ComponentId> => "Data",
703 auto_edit: bool => "Data",
704 enabled: bool => "Data";
705 events: on_data_change: (), on_state_change: ()
706 }
707
708 fn notification(&mut self, freed: ComponentId) {
709 if self.data_set == Some(freed) {
710 self.data_set = None;
711 }
712 }
713}
714
715#[derive(Clone, Copy, Debug, PartialEq, Eq)]
717pub(crate) enum Asking {
718 Post,
719 Delete,
720}