1use aylis_core::{ComponentId, EventArg, EventArgs, EventValue, PropKind, PropValue, RecordInfo, Ui};
26use serde_json::Value as Json;
27
28use crate::field::{Field, FieldType};
29use crate::handle::data_set;
30use crate::value::Value;
31
32pub const GET_TEXT_REQUEST_RECORD: RecordInfo =
35 RecordInfo { name: "GetTextRequest", fields: &[("field", PropKind::String), ("values", PropKind::List)] };
36
37pub const SET_TEXT_REQUEST_RECORD: RecordInfo =
39 RecordInfo { name: "SetTextRequest", fields: &[("field", PropKind::String), ("text", PropKind::String)] };
40
41pub const FIELD_VALUE_RECORD: RecordInfo =
43 RecordInfo { name: "FieldValue", fields: &[("field", PropKind::String), ("value", PropKind::String)] };
44
45pub const MASTER_CHANGE_RECORD: RecordInfo =
48 RecordInfo { name: "MasterChange", fields: &[("values", PropKind::RecordList(&FIELD_VALUE_RECORD))] };
49
50pub const SERVER_QUERY_RECORD: RecordInfo = RecordInfo {
52 name: "ServerQuery",
53 fields: &[
54 ("kind", PropKind::Enum(&["filter", "sort", "locate"])),
55 ("index", PropKind::String),
56 ("filter", PropKind::String),
57 ("loaded", PropKind::Int),
58 ("field", PropKind::String),
59 ("value", PropKind::String),
60 ],
61};
62
63pub fn value_text(value: &Value) -> String {
67 value.to_string()
68}
69
70fn json_of(args: &EventArgs) -> Option<Json> {
72 let text = match args {
73 EventArgs::Text(t) => t.as_str(),
74 EventArgs::Value(PropValue::String(t)) => t.as_str(),
75 _ => return None,
76 };
77 serde_json::from_str(text).ok()
78}
79
80fn text(json: &Json, key: &str) -> String {
81 match &json[key] {
82 Json::String(s) => s.clone(),
83 Json::Null => String::new(),
84 other => other.to_string(),
85 }
86}
87
88#[derive(Clone, Debug, Default, PartialEq)]
90pub struct GetTextRequest {
91 pub field: String,
92 pub values: Vec<String>,
93}
94
95impl GetTextRequest {
96 pub fn to_json(&self) -> String {
97 serde_json::json!({ "field": self.field, "values": self.values }).to_string()
98 }
99}
100
101impl EventValue for GetTextRequest {
102 const ARG: EventArg = EventArg::Value(PropKind::Record(&GET_TEXT_REQUEST_RECORD));
103 fn from_args(args: &EventArgs) -> Option<Self> {
104 let json = json_of(args)?;
105 let values = json["values"].as_array().map(|a| a.iter().map(|v| if let Json::String(s) = v { s.clone() } else { v.to_string() }).collect());
106 Some(GetTextRequest { field: text(&json, "field"), values: values.unwrap_or_default() })
107 }
108}
109
110#[derive(Clone, Debug, Default, PartialEq)]
112pub struct SetTextRequest {
113 pub field: String,
114 pub text: String,
115}
116
117impl SetTextRequest {
118 pub fn to_json(&self) -> String {
119 serde_json::json!({ "field": self.field, "text": self.text }).to_string()
120 }
121}
122
123impl EventValue for SetTextRequest {
124 const ARG: EventArg = EventArg::Value(PropKind::Record(&SET_TEXT_REQUEST_RECORD));
125 fn from_args(args: &EventArgs) -> Option<Self> {
126 let json = json_of(args)?;
127 Some(SetTextRequest { field: text(&json, "field"), text: text(&json, "text") })
128 }
129}
130
131#[derive(Clone, Debug, Default, PartialEq)]
133pub struct FieldValue {
134 pub field: String,
135 pub value: String,
136}
137
138#[derive(Clone, Debug, Default, PartialEq)]
141pub struct MasterChange {
142 pub values: Vec<FieldValue>,
143}
144
145impl MasterChange {
146 pub fn get(&self, field: &str) -> Option<&str> {
148 self.values.iter().find(|v| v.field.eq_ignore_ascii_case(field)).map(|v| v.value.as_str())
149 }
150
151 pub fn to_json(&self) -> String {
152 let values: Vec<Json> = self.values.iter().map(|v| serde_json::json!({ "field": v.field, "value": v.value })).collect();
153 serde_json::json!({ "values": values }).to_string()
154 }
155}
156
157impl EventValue for MasterChange {
158 const ARG: EventArg = EventArg::Value(PropKind::Record(&MASTER_CHANGE_RECORD));
159 fn from_args(args: &EventArgs) -> Option<Self> {
160 let json = json_of(args)?;
161 let values = json["values"]
162 .as_array()
163 .into_iter()
164 .flatten()
165 .map(|v| FieldValue { field: text(v, "field"), value: text(v, "value") })
166 .collect();
167 Some(MasterChange { values })
168 }
169}
170
171#[derive(Clone, Debug, Default, PartialEq)]
174pub struct ServerQuery {
175 pub kind: String,
177 pub index: String,
179 pub filter: String,
181 pub loaded: i64,
183 pub field: String,
185 pub value: String,
186}
187
188impl ServerQuery {
189 pub fn to_json(&self) -> String {
190 serde_json::json!({
191 "kind": self.kind,
192 "index": self.index,
193 "filter": self.filter,
194 "loaded": self.loaded,
195 "field": self.field,
196 "value": self.value,
197 })
198 .to_string()
199 }
200}
201
202impl EventValue for ServerQuery {
203 const ARG: EventArg = EventArg::Value(PropKind::Record(&SERVER_QUERY_RECORD));
204 fn from_args(args: &EventArgs) -> Option<Self> {
205 let json = json_of(args)?;
206 Some(ServerQuery {
207 kind: text(&json, "kind"),
208 index: text(&json, "index"),
209 filter: text(&json, "filter"),
210 loaded: json["loaded"].as_i64().unwrap_or_default(),
211 field: text(&json, "field"),
212 value: text(&json, "value"),
213 })
214 }
215}
216
217pub(crate) fn value_from_text(text: &str, field: &Field) -> Result<Value, String> {
219 let json = match field.field_type {
220 FieldType::Integer | FieldType::AutoInc | FieldType::Boolean | FieldType::Blob => {
222 serde_json::from_str(text).unwrap_or_else(|_| Json::String(text.to_string()))
223 }
224 _ => Json::String(text.to_string()),
225 };
226 if text.is_empty() && field.field_type != FieldType::String && field.field_type != FieldType::Memo {
227 return Ok(Value::Null);
228 }
229 crate::json::json_to_value(&json, field)
230}
231
232pub fn get_text(ui: &mut Ui, field: ComponentId, args: &EventArgs, text: impl Fn(&Value) -> String) {
235 let Some(request) = GetTextRequest::from_args(args) else { return };
236 let Some(cds) = ui.parent(field) else { return };
237 let Some(f) = ui.get::<Field>(field) else { return };
238 let texts: Vec<(Value, String)> = request
239 .values
240 .iter()
241 .filter_map(|v| value_from_text(v, f).ok())
242 .map(|v| {
243 let t = text(&v);
244 (v, t)
245 })
246 .collect();
247 let _ = data_set(ui, cds).set_field_texts(&request.field, texts);
248}
249
250pub fn set_text(ui: &mut Ui, field: ComponentId, args: &EventArgs, value: impl Fn(&str) -> Result<Value, String>) {
253 let Some(request) = SetTextRequest::from_args(args) else { return };
254 let Some(cds) = ui.parent(field) else { return };
255 let mut ds = data_set(ui, cds);
256 match value(&request.text) {
257 Ok(v) => {
258 let _ = ds.set_value(&request.field, v);
259 }
260 Err(message) => {
261 let _ = ds.set_field_error(&request.field, Some(message));
262 }
263 }
264}