1use crate::{ChangeSignal, RowKey, TableRowPatch, Value, VecModel, model::RowObserver};
2use std::{
3 cell::RefCell,
4 collections::BTreeMap,
5 fmt,
6 rc::{Rc, Weak},
7};
8
9#[derive(Clone, Debug)]
10pub struct RecordValue {
11 name: Rc<str>,
12 fields: Rc<BTreeMap<String, Value>>,
13}
14
15impl PartialEq for RecordValue {
16 fn eq(&self, other: &Self) -> bool {
17 self.name == other.name
18 && self.fields.len() == other.fields.len()
19 && self.fields.iter().zip(other.fields.iter()).all(
20 |((left_name, left), (right_name, right))| {
21 left_name == right_name && left.eq_with_image_assets(right)
22 },
23 )
24 }
25}
26
27impl RecordValue {
28 pub fn new(name: impl Into<Rc<str>>, fields: BTreeMap<String, Value>) -> Self {
29 Self {
30 name: name.into(),
31 fields: Rc::new(fields),
32 }
33 }
34
35 pub fn name(&self) -> &str {
36 &self.name
37 }
38
39 pub fn field(&self, name: &str) -> Option<&Value> {
40 self.fields.get(name)
41 }
42
43 pub fn fields(&self) -> impl ExactSizeIterator<Item = (&str, &Value)> {
44 self.fields
45 .iter()
46 .map(|(name, value)| (name.as_str(), value))
47 }
48
49 pub fn field_path(&self, path: &[String]) -> Option<&Value> {
50 let (name, rest) = path.split_first()?;
51 let field = self.field(name)?;
52 if rest.is_empty() {
53 Some(field)
54 } else if let Value::Record(record) = field {
55 record.field_path(rest)
56 } else {
57 None
58 }
59 }
60
61 pub fn with_field(&self, path: &[String], value: Value) -> Option<Self> {
62 let (name, rest) = path.split_first()?;
63 let mut record = self.clone();
64 let target = Rc::make_mut(&mut record.fields).get_mut(name)?;
65 if rest.is_empty() {
66 *target = value;
67 } else if let Value::Record(nested) = target {
68 *nested = nested.with_field(rest, value)?;
69 } else {
70 return None;
71 }
72 Some(record)
73 }
74}
75
76impl TableRowPatch<RecordValue> {
77 pub fn record_changes(&mut self, before: &RecordValue, after: &RecordValue) {
79 self.record_record(before, after, &mut Vec::new());
80 }
81
82 fn record_record(&mut self, before: &RecordValue, after: &RecordValue, path: &mut Vec<String>) {
83 if Rc::ptr_eq(&before.fields, &after.fields) {
84 return;
85 }
86 for (name, before) in before.fields.iter() {
87 let Some(after) = after.field(name) else {
88 continue;
89 };
90 path.push(name.clone());
91 if let (Value::Record(before), Value::Record(after)) = (before, after) {
92 self.record_record(before, after, path);
93 } else if !same_field(before, after) {
94 let field = path.clone();
95 let metadata_bytes = field
96 .iter()
97 .fold(std::mem::size_of_val(field.as_slice()), |bytes, name| {
98 bytes.saturating_add(name.len())
99 });
100 self.record_with(
101 before,
102 after,
103 same_field,
104 field_bytes,
105 metadata_bytes,
106 move |row, expected, value| {
107 if !row
108 .field_path(&field)
109 .is_some_and(|current| same_field(current, expected))
110 {
111 return false;
112 }
113 let Some(next) = row.with_field(&field, value.clone()) else {
114 return false;
115 };
116 *row = next;
117 true
118 },
119 );
120 }
121 path.pop();
122 }
123 }
124}
125
126fn same_field(before: &Value, after: &Value) -> bool {
127 before.eq_with_image_assets(after)
128 || match (before, after) {
129 (Value::Float(before), Value::Float(after)) => before.to_bits() == after.to_bits(),
130 (Value::Length(before), Value::Length(after)) => {
131 before.0.to_bits() == after.0.to_bits()
132 }
133 _ => false,
134 }
135}
136
137fn field_bytes(value: &Value) -> usize {
138 match value {
139 Value::String(value) => value.len(),
140 Value::StyledText(value) => value.links().iter().fold(
141 value
142 .text()
143 .len()
144 .saturating_add(std::mem::size_of_val(value.runs()))
145 .saturating_add(std::mem::size_of_val(value.links())),
146 |bytes, link| bytes.saturating_add(link.href.len()),
147 ),
148 Value::Brush(crate::Brush::Linear { stops, .. } | crate::Brush::Radial { stops, .. }) => {
149 std::mem::size_of_val(stops.as_ref())
150 }
151 _ => 0,
152 }
153}
154
155#[doc(hidden)]
156pub type RecordRowValidator = dyn Fn(&str, &RecordValue) -> Result<(), String>;
157
158#[derive(Default)]
159struct ValidationState {
160 failures: RefCell<BTreeMap<RowKey, String>>,
161 changed: ChangeSignal,
162}
163
164struct RecordValidation {
165 validator: Weak<RecordRowValidator>,
166 state: Rc<ValidationState>,
167 _observer: Rc<RowObserver<RecordValue>>,
168}
169
170impl RecordValidation {
171 fn new(list: &RecordList, validator: &Rc<RecordRowValidator>) -> Self {
172 let state = Rc::new(ValidationState::default());
173 let mut failures = state.failures.borrow_mut();
174 list.model.visit_rows_untracked(usize::MAX, |_, key, row| {
175 if let Err(error) = validator(&list.name, row) {
176 failures.insert(key, error);
177 }
178 });
179 drop(failures);
180
181 let validator = Rc::downgrade(validator);
182 let observer: Rc<RowObserver<RecordValue>> = Rc::new({
183 let state = state.clone();
184 let validator = validator.clone();
185 let name = list.name.clone();
186 move |key, row| {
187 let Some(validator) = validator.upgrade() else {
188 return;
189 };
190 let error = row.and_then(|row| validator(&name, row).err());
191 let mut failures = state.failures.borrow_mut();
192 if failures.get(&key) != error.as_ref() {
193 if let Some(error) = error {
194 failures.insert(key, error);
195 } else {
196 failures.remove(&key);
197 }
198 state.changed.notify();
199 }
200 }
201 });
202 list.model.observe_rows(&observer);
203 Self {
204 validator,
205 state,
206 _observer: observer,
207 }
208 }
209}
210
211#[derive(Clone)]
212pub struct RecordList {
213 name: Rc<str>,
214 model: VecModel<RecordValue>,
215 validations: Rc<RefCell<Vec<RecordValidation>>>,
216}
217
218impl PartialEq for RecordList {
219 fn eq(&self, other: &Self) -> bool {
220 self.name == other.name && self.model == other.model
221 }
222}
223
224impl RecordList {
225 pub fn new(name: impl Into<Rc<str>>, rows: Vec<RecordValue>) -> Self {
226 Self::from_model(name, VecModel::from(rows))
227 }
228
229 pub fn from_model(name: impl Into<Rc<str>>, model: VecModel<RecordValue>) -> Self {
231 Self {
232 name: name.into(),
233 model,
234 validations: Rc::default(),
235 }
236 }
237
238 pub fn name(&self) -> &str {
239 &self.name
240 }
241
242 pub fn model(&self) -> &VecModel<RecordValue> {
243 &self.model
244 }
245
246 #[doc(hidden)]
247 pub fn into_snapshot(self) -> (Rc<str>, Vec<RecordValue>) {
248 (self.name, self.model.into_snapshot())
249 }
250
251 #[doc(hidden)]
252 pub fn values_eq_owned(
253 self,
254 other: Self,
255 validator: &Rc<RecordRowValidator>,
256 ) -> Result<bool, String> {
257 for list in [&self, &other] {
258 list.check_rows(validator, list.model.is_shared())
259 .map_err(|error| format!("model {}{error}", list.name))?;
260 }
261 Ok(self.name == other.name && self.model.values_eq_owned(other.model))
262 }
263
264 #[doc(hidden)]
266 pub fn validate_rows(&self, validator: &Rc<RecordRowValidator>) -> Result<(), String> {
267 self.check_rows(validator, true)
268 }
269
270 #[doc(hidden)]
271 pub fn validate_rows_untracked(
272 &self,
273 validator: &Rc<RecordRowValidator>,
274 ) -> Result<(), String> {
275 self.check_rows(validator, false)
276 }
277
278 fn check_rows(&self, validator: &Rc<RecordRowValidator>, tracked: bool) -> Result<(), String> {
279 let mut validations = self.validations.borrow_mut();
280 validations.retain(|entry| entry.validator.strong_count() != 0);
281 let key = Rc::downgrade(validator);
282 let index = validations
283 .iter()
284 .position(|entry| entry.validator.ptr_eq(&key))
285 .unwrap_or_else(|| {
286 validations.push(RecordValidation::new(self, validator));
287 validations.len() - 1
288 });
289 let state = &validations[index].state;
290 if tracked {
291 state.changed.track();
292 }
293 let failures = state.failures.borrow();
294 let Some((&row, error)) = failures.first_key_value() else {
295 return Ok(());
296 };
297 let index = if tracked {
298 self.model.row_index(row)
299 } else {
300 self.model.row_index_untracked(row)
301 };
302 Err(index.map_or_else(|| error.clone(), |index| format!("[{index}]{error}")))
303 }
304}
305
306impl fmt::Debug for RecordList {
307 fn fmt(&self, output: &mut fmt::Formatter<'_>) -> fmt::Result {
308 output
309 .debug_struct("RecordList")
310 .field("name", &self.name)
311 .finish_non_exhaustive()
312 }
313}