1use crate::{Date, Node, Orientation, Property, TableRows, Time, Value, VecModel};
2use std::{
3 cell::Cell,
4 collections::HashMap,
5 fmt,
6 ops::Range,
7 rc::{Rc, Weak},
8 sync::atomic::{AtomicU64, Ordering},
9};
10
11pub(crate) const MAX_ROWS: usize = 1_000_000;
12
13#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
14pub struct RowKey {
15 pub(crate) model: u64,
16 pub(crate) row: u64,
17 pub(crate) scope: u64,
18}
19
20#[derive(Clone, Copy, Debug)]
22#[doc(hidden)]
23pub enum ViewIndex {
24 FromSource,
25 ToSource,
26}
27
28impl ViewIndex {
29 pub fn parse(name: &str) -> Option<Self> {
30 match name {
31 "view-index-for-source" => Some(Self::FromSource),
32 "source-index-for-view" => Some(Self::ToSource),
33 _ => None,
34 }
35 }
36
37 pub fn try_query<E>(
38 self,
39 index: i64,
40 lookup: impl FnOnce(usize, Self) -> Result<Option<usize>, E>,
41 ) -> Result<i64, E> {
42 let Ok(index) = usize::try_from(index) else {
43 return Ok(-1);
44 };
45 Ok(lookup(index, self)?
46 .and_then(|index| i64::try_from(index).ok())
47 .unwrap_or(-1))
48 }
49
50 pub fn query(self, index: i64, lookup: impl FnOnce(usize, Self) -> Option<usize>) -> i64 {
51 self.try_query(index, |index, direction| {
52 Ok::<_, std::convert::Infallible>(lookup(index, direction))
53 })
54 .unwrap_or_else(|error| match error {})
55 }
56}
57
58impl RowKey {
59 pub(crate) fn in_view(self, scope: u64) -> Self {
60 Self { scope, ..self }
61 }
62
63 #[doc(hidden)]
64 pub fn has_view_scope(self) -> bool {
65 self.scope != 0
66 }
67}
68
69type RenderRows = dyn Fn(Range<usize>, &TableColumnWindow) -> Vec<Node>;
70
71struct RowRenderer {
72 scope: u64,
73 rows: Box<RenderRows>,
74 offsets: [Property<Option<f32>>; 2],
75 selection: Cell<Option<(Option<usize>, usize)>>,
76 tree_root: Cell<Option<(i64, Option<RowKey>)>>,
77}
78
79#[doc(hidden)]
81#[derive(Clone)]
82pub struct ListRowRenderer(Rc<RowRenderer>);
83
84impl Node {
85 #[doc(hidden)]
87 pub fn list_rows_at(&self, path: &[usize], rows: Range<usize>) -> Vec<Node> {
88 let Some(node) = self.at_path(path) else {
89 return Vec::new();
90 };
91 let end = node
92 .list
93 .map_or(rows.end, |list| rows.end.min(list.row_count));
94 node.list_row_renderer
95 .as_ref()
96 .map_or_else(Vec::new, |renderer| renderer.render(rows.start..end))
97 }
98
99 #[doc(hidden)]
101 pub fn list_event_row(&self, slot: usize) -> Option<(usize, RowKey, &Node)> {
102 let index = self.list?.first_row.checked_add(slot)?;
103 let row = self.child_at(slot)?;
104 Some((index, row.row_key?, row.child_at(0)?))
105 }
106}
107
108impl ListRowRenderer {
109 pub fn new(rows: impl Fn(Range<usize>) -> Vec<Node> + 'static) -> Self {
110 Self::with_columns(move |range, _| rows(range))
111 }
112
113 pub fn with_columns(
114 rows: impl Fn(Range<usize>, &TableColumnWindow) -> Vec<Node> + 'static,
115 ) -> Self {
116 static NEXT_VIEW: AtomicU64 = AtomicU64::new(1);
117 let scope = NEXT_VIEW
118 .try_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
119 .expect("virtual view identities exhausted");
120 Self(Rc::new(RowRenderer {
121 scope,
122 rows: Box::new(rows),
123 offsets: Default::default(),
124 selection: Cell::default(),
125 tree_root: Cell::default(),
126 }))
127 }
128
129 pub fn render(&self, rows: Range<usize>) -> Vec<Node> {
130 self.render_in_columns(rows, &TableColumnWindow::default())
131 }
132
133 pub fn render_in_columns(&self, rows: Range<usize>, columns: &TableColumnWindow) -> Vec<Node> {
134 (self.0.rows)(rows, columns)
135 }
136
137 pub fn scope(&self) -> u64 {
138 self.0.scope
139 }
140
141 pub fn offset(&self, axis: Orientation) -> Option<f32> {
142 self.0.offsets[usize::from(axis == Orientation::Vertical)].get(|| None)
143 }
144
145 pub fn set_offset(&self, axis: Orientation, offset: f32) {
146 self.0.offsets[usize::from(axis == Orientation::Vertical)].set_if_changed(Some(offset));
147 }
148
149 pub fn selection_changed(&self, selected: Option<usize>, columns: usize) -> bool {
150 self.0
151 .selection
152 .get()
153 .is_some_and(|previous| previous != (selected, columns))
154 }
155
156 pub fn remember_selection(&self, selected: Option<usize>, columns: usize) {
157 self.0.selection.set(Some((selected, columns)));
158 }
159
160 pub fn tree_root_changed(&self, root: (i64, Option<RowKey>)) -> bool {
161 self.0
162 .tree_root
163 .get()
164 .is_some_and(|previous| previous != root)
165 }
166
167 pub fn remember_tree_root(&self, root: (i64, Option<RowKey>)) {
168 self.0.tree_root.set(Some(root));
169 }
170}
171
172#[doc(hidden)]
174#[derive(Clone, Debug, Default, PartialEq, Eq)]
175pub struct TableColumnWindow(Option<Rc<VisibleColumns>>);
176
177#[derive(Debug, PartialEq, Eq)]
178struct VisibleColumns {
179 indices: Box<[usize]>,
180 count: usize,
181}
182
183impl TableColumnWindow {
184 pub fn new(visible: impl IntoIterator<Item = bool>) -> Self {
185 let mut indices = Vec::new();
186 let mut count = 0;
187 for (index, visible) in visible.into_iter().enumerate() {
188 if visible {
189 indices.push(index);
190 }
191 count = index + 1;
192 }
193 Self((indices.len() != count).then(|| {
194 Rc::new(VisibleColumns {
195 indices: indices.into_boxed_slice(),
196 count,
197 })
198 }))
199 }
200
201 pub fn includes(&self, column: usize) -> bool {
202 self.dense_index(column).is_some()
203 }
204
205 pub fn dense_index(&self, column: usize) -> Option<usize> {
206 self.0.as_ref().map_or(Some(column), |visible| {
207 visible.indices.binary_search(&column).ok()
208 })
209 }
210
211 pub fn logical_index(&self, index: usize) -> usize {
212 self.0
213 .as_ref()
214 .map_or(index, |visible| visible.indices[index])
215 }
216
217 pub fn logical_len(&self, materialized: usize) -> usize {
218 self.0
219 .as_ref()
220 .map_or(materialized, |visible| visible.count)
221 }
222
223 pub fn columns(&self, count: usize) -> impl Iterator<Item = usize> + '_ {
224 self.0
225 .iter()
226 .flat_map(move |visible| {
227 visible
228 .indices
229 .iter()
230 .copied()
231 .take_while(move |&index| index < count)
232 })
233 .chain(0..if self.0.is_none() { count } else { 0 })
234 }
235}
236
237impl PartialEq for ListRowRenderer {
238 fn eq(&self, other: &Self) -> bool {
239 Rc::ptr_eq(&self.0, &other.0)
240 }
241}
242
243impl fmt::Debug for ListRowRenderer {
244 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
245 formatter
246 .debug_struct("ListRowRenderer")
247 .finish_non_exhaustive()
248 }
249}
250
251pub struct RowLifetime(pub(crate) Option<Weak<()>>);
252
253impl RowLifetime {
254 pub(crate) fn is_live(&self, key: RowKey, model: u64, count: usize) -> bool {
255 key.model == model
256 && match &self.0 {
257 Some(lifetime) => lifetime.strong_count() != 0,
258 None => key.row < count as u64,
259 }
260 }
261}
262
263#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
264pub struct ListMetrics {
265 pub row_count: usize,
266 pub first_row: usize,
267}
268
269impl ListMetrics {
270 pub fn row_height(node: &Node) -> f32 {
271 Self::clamp_row_height(node.length("row-height").unwrap_or(32.0))
272 }
273
274 pub fn clamp_row_height(height: f32) -> f32 {
275 height.clamp(12.0, 512.0)
276 }
277
278 pub fn row_height_at(node: &Node, index: usize) -> f32 {
279 node.row_heights
280 .as_ref()
281 .map_or_else(|| Self::row_height(node), |heights| heights.height(index))
282 }
283
284 pub fn selection(node: &Node) -> Option<i64> {
285 if let Some(tree) = &node.tree {
286 return tree
287 .visible_index(node.int("current-key")?)
288 .map(|index| index as i64);
289 }
290 node.int(if node.kind == "TableView" {
291 "current-row"
292 } else {
293 "current-index"
294 })
295 }
296
297 #[doc(hidden)]
299 pub fn has_row_in_model(node: &Node, index: usize, live_stamp: Option<(u64, u64)>) -> bool {
300 node.standard_list_stamp == live_stamp
301 && node.list.is_some_and(|list| index < list.row_count)
302 }
303}
304
305#[derive(Clone)]
307#[doc(hidden)]
308pub struct ListRowLocator(Rc<dyn RowPositions>);
309
310trait RowPositions {
311 fn first_position(&self, candidates: &[(RowKey, usize)]) -> Option<(usize, usize)>;
312 fn key_at(&self, index: usize) -> Option<RowKey>;
313 fn position_of_source_key(&self, key: RowKey, source_index: usize) -> Option<usize>;
314}
315
316impl<M: ListModel> RowPositions for M {
317 fn position_of_source_key(&self, key: RowKey, source_index: usize) -> Option<usize> {
318 self.index_of_source_key(key, source_index)
319 }
320
321 fn key_at(&self, index: usize) -> Option<RowKey> {
322 ListModel::key_at(self, index)
323 }
324
325 fn first_position(&self, candidates: &[(RowKey, usize)]) -> Option<(usize, usize)> {
326 let &(first, hint) = candidates.first()?;
327 let count = self.row_count();
328 if count == 0 || self.row_key(0).model != first.model {
329 return None;
330 }
331 if hint < count && self.row_key(hint) == first {
332 return Some((0, hint));
333 }
334 let nearby = hint.saturating_sub(4)..count.min(hint.saturating_add(5));
336 if let Some(index) = nearby
337 .into_iter()
338 .find(|&index| self.row_key(index) == first)
339 {
340 return Some((0, index));
341 }
342
343 let priorities: HashMap<_, _> = candidates
345 .iter()
346 .enumerate()
347 .map(|(priority, &(key, _))| (key, priority))
348 .collect();
349 let mut best = None;
350 let mut index = 0;
351 self.visit_row_keys(0..count, |key| {
352 if let Some(&priority) = priorities.get(&key)
353 && best.is_none_or(|(previous, _)| priority < previous)
354 {
355 best = Some((priority, index));
356 }
357 index += 1;
358 });
359 best
360 }
361}
362
363impl ListRowLocator {
364 pub fn new(model: Rc<impl ListModel + 'static>) -> Self {
365 Self(model)
366 }
367
368 pub fn first_position(&self, candidates: &[(RowKey, usize)]) -> Option<(usize, usize)> {
369 self.0.first_position(candidates)
370 }
371
372 pub fn key_at(&self, index: usize) -> Option<RowKey> {
373 self.0.key_at(index)
374 }
375
376 pub(crate) fn position_of_source_key(&self, key: RowKey, source_index: usize) -> Option<usize> {
377 self.0.position_of_source_key(key, source_index)
378 }
379}
380
381impl PartialEq for ListRowLocator {
382 fn eq(&self, other: &Self) -> bool {
383 Rc::ptr_eq(&self.0, &other.0)
384 }
385}
386
387impl fmt::Debug for ListRowLocator {
388 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
389 formatter
390 .debug_struct("ListRowLocator")
391 .finish_non_exhaustive()
392 }
393}
394
395#[doc(hidden)]
396pub fn standard_list_rows<T: Clone + PartialEq>(
397 model: &VecModel<T>,
398 range: Range<usize>,
399 label: impl FnMut(T) -> String,
400) -> Vec<Node> {
401 standard_list_rows_at(model, range, label)
402}
403
404#[doc(hidden)]
405pub fn standard_list_rows_in_view<T: Clone + PartialEq>(
406 rows: &TableRows<VecModel<T>>,
407 range: Range<usize>,
408 label: impl FnMut(T) -> String,
409) -> Vec<Node> {
410 standard_list_rows_at(
411 rows.source(),
412 range.filter_map(|row| rows.positions().source_index(row)),
413 label,
414 )
415}
416
417fn standard_list_rows_at<T: Clone + PartialEq>(
418 model: &VecModel<T>,
419 indices: impl Iterator<Item = usize>,
420 mut label: impl FnMut(T) -> String,
421) -> Vec<Node> {
422 indices
423 .filter_map(|index| {
424 let value = model.row(index)?;
425 let key = model.row_key(index)?;
426 let mut item = Node::new("StandardListItem", None);
427 item.set_row_key(Some(key));
428 item.properties.insert("text", label(value).into());
429 Some(item)
430 })
431 .collect()
432}
433
434#[doc(hidden)]
435pub fn standard_table_rows<T, const COLUMNS: usize>(
436 model: &VecModel<T>,
437 range: Range<usize>,
438 project: impl Fn(&T) -> [String; COLUMNS],
439) -> Vec<Node> {
440 standard_table_rows_with_header(model, range, |item| (None, project(item)))
441}
442
443#[doc(hidden)]
444pub fn standard_table_rows_with_header<T, const COLUMNS: usize>(
445 model: &VecModel<T>,
446 range: Range<usize>,
447 project: impl Fn(&T) -> (Option<String>, [String; COLUMNS]),
448) -> Vec<Node> {
449 standard_table_rows_at(model, range, [None; COLUMNS], project)
450}
451
452#[doc(hidden)]
453pub fn standard_table_rows_in_order<T, const COLUMNS: usize>(
454 rows: &TableRows<VecModel<T>>,
455 range: Range<usize>,
456 project: impl Fn(&T) -> (Option<String>, [String; COLUMNS]),
457) -> Vec<Node> {
458 standard_table_rows_with_editors_in_order(rows, range, [None; COLUMNS], project)
459}
460
461#[doc(hidden)]
462pub fn standard_table_rows_with_editors_in_order<T, const COLUMNS: usize>(
463 rows: &TableRows<VecModel<T>>,
464 range: Range<usize>,
465 editors: [Option<TableCellEditor>; COLUMNS],
466 project: impl Fn(&T) -> (Option<String>, [String; COLUMNS]),
467) -> Vec<Node> {
468 standard_table_rows_at(
469 rows.source(),
470 range.filter_map(|index| rows.positions().source_index(index)),
471 editors,
472 project,
473 )
474}
475
476#[doc(hidden)]
478pub fn project_standard_table_rows<T>(
479 rows: &TableRows<VecModel<T>>,
480 range: Range<usize>,
481 columns: &TableColumnWindow,
482 column_count: usize,
483 header: impl Fn(&T) -> Option<String>,
484 cell: impl Fn(&T, usize) -> String,
485 editor: impl Fn(usize) -> Option<TableCellEditor>,
486) -> Vec<Node> {
487 try_project_standard_table_rows(rows, range, columns, column_count, header, cell, |column| {
488 Ok::<_, std::convert::Infallible>(editor(column))
489 })
490 .unwrap_or_else(|error| match error {})
491}
492
493#[doc(hidden)]
494pub fn try_project_standard_table_rows<T, E>(
495 rows: &TableRows<VecModel<T>>,
496 range: Range<usize>,
497 columns: &TableColumnWindow,
498 column_count: usize,
499 header: impl Fn(&T) -> Option<String>,
500 cell: impl Fn(&T, usize) -> String,
501 editor: impl Fn(usize) -> Result<Option<TableCellEditor>, E>,
502) -> Result<Vec<Node>, E> {
503 let model = rows.source();
504 let visible: Vec<_> = columns
505 .columns(column_count)
506 .map(|column| editor(column).map(|editor| (column, editor)))
507 .collect::<Result<_, E>>()?;
508 Ok(range
509 .filter_map(|index| {
510 let index = rows.positions().source_index(index)?;
511 let key = model.row_key(index)?;
512 model.project_row(index, |item| {
513 let mut row = projected_table_row(key, header(item));
514 row.table_column_window = columns.clone();
515 row.children.extend(
516 visible
517 .iter()
518 .map(|&(column, editor)| projected_table_cell(cell(item, column), editor)),
519 );
520 row
521 })
522 })
523 .collect())
524}
525
526#[doc(hidden)]
528#[derive(Clone, Copy, Debug, PartialEq, Eq)]
529pub enum TableCellEditor {
530 String,
531 Int,
532 Float,
533 Bool,
534 Date,
535 Time,
536}
537
538impl TableCellEditor {
539 pub fn parse(self, text: &str) -> Option<Value> {
540 let trimmed = text.trim();
541 match self {
542 Self::String => Some(Value::String(text.into())),
543 Self::Int => trimmed.parse().ok().map(Value::Int),
544 Self::Float => trimmed
545 .parse::<f64>()
546 .ok()
547 .filter(|number| number.is_finite())
548 .map(Value::Float),
549 Self::Bool => crate::table_paste_bool(text).map(Value::Bool),
550 Self::Date => {
551 let [year, month, day] = parse_cell_parts(trimmed, '-')?;
552 Date::new(year, month, day).map(Value::Date)
553 }
554 Self::Time => {
555 let [hour, minute, second] = parse_cell_parts(trimmed, ':')?;
556 Time::new(hour, minute, second).map(Value::Time)
557 }
558 }
559 }
560
561 pub fn accepts(self, text: &str) -> bool {
562 self == Self::String || self.parse(text).is_some()
563 }
564}
565
566fn parse_cell_parts(text: &str, separator: char) -> Option<[i64; 3]> {
567 let mut parts = text.split(separator);
568 let values = [
569 parts.next()?.parse().ok()?,
570 parts.next()?.parse().ok()?,
571 parts.next()?.parse().ok()?,
572 ];
573 parts.next().is_none().then_some(values)
574}
575
576fn standard_table_rows_at<T, const COLUMNS: usize>(
577 model: &VecModel<T>,
578 indices: impl Iterator<Item = usize>,
579 editors: [Option<TableCellEditor>; COLUMNS],
580 project: impl Fn(&T) -> (Option<String>, [String; COLUMNS]),
581) -> Vec<Node> {
582 indices
583 .filter_map(|index| {
584 let key = model.row_key(index)?;
585 let (header, cells) = model.project_row(index, &project)?;
586 let mut row = projected_table_row(key, header);
587 row.children.extend(
588 cells
589 .into_iter()
590 .zip(editors)
591 .map(|(text, editor)| projected_table_cell(text, editor)),
592 );
593 Some(row)
594 })
595 .collect()
596}
597
598fn projected_table_row(key: RowKey, header: Option<String>) -> Node {
599 let mut row = Node::new("TableRow", None);
600 row.set_row_key(Some(key));
601 if let Some(header) = header {
602 row.properties.insert("row-header-text", header.into());
603 }
604 row
605}
606
607fn projected_table_cell(text: String, editor: Option<TableCellEditor>) -> Node {
608 let mut cell = Node::new("TableCell", None);
609 cell.properties.insert("text", text.into());
610 if editor.is_some() {
611 cell.properties.insert("editable", true.into());
612 cell.table_cell_editor = editor;
613 }
614 cell
615}
616
617pub trait ListModel {
618 type Item: Clone + PartialEq;
619
620 fn row_count(&self) -> usize;
621 fn item(&self, row: usize) -> Self::Item;
622 fn row_key(&self, row: usize) -> RowKey;
623 #[doc(hidden)]
624 fn key_at(&self, index: usize) -> Option<RowKey> {
625 (index < self.row_count()).then(|| self.row_key(index))
626 }
627 fn visit_items(&self, mut visit: impl FnMut(usize, RowKey, &Self::Item)) {
628 for index in 0..self.row_count() {
629 visit(index, self.row_key(index), &self.item(index));
630 }
631 }
632 fn visit_row_keys(&self, range: Range<usize>, mut visit: impl FnMut(RowKey)) {
633 for index in range {
634 visit(self.row_key(index));
635 }
636 }
637 fn index_of_key(&self, key: RowKey) -> Option<usize> {
638 (0..self.row_count()).find(|&index| self.row_key(index) == key)
639 }
640 #[doc(hidden)]
641 fn index_of_source_key(&self, key: RowKey, source_index: usize) -> Option<usize> {
642 if source_index < self.row_count() && self.row_key(source_index) == key {
643 Some(source_index)
644 } else {
645 self.index_of_key(key)
646 }
647 }
648 fn row_lifetime(&self, key: RowKey) -> RowLifetime;
649 fn structure_stamp(&self) -> (u64, u64);
650 #[doc(hidden)]
652 fn contents_stamp(&self) -> (u64, u64) {
653 self.structure_stamp()
654 }
655 #[doc(hidden)]
656 fn source_structure_stamp(&self) -> (u64, u64) {
657 self.structure_stamp()
658 }
659 #[doc(hidden)]
660 fn visit_source_row_keys(&self, visit: impl FnMut(RowKey)) {
661 self.visit_row_keys(0..self.row_count(), visit);
662 }
663}
664
665impl ListModel for i64 {
666 type Item = i64;
667
668 fn row_count(&self) -> usize {
669 (*self).clamp(0, MAX_ROWS as i64) as usize
670 }
671
672 fn item(&self, row: usize) -> Self::Item {
673 row as i64
674 }
675
676 fn row_key(&self, row: usize) -> RowKey {
677 RowKey {
678 model: 0,
679 row: row as u64,
680 scope: 0,
681 }
682 }
683 fn row_lifetime(&self, _: RowKey) -> RowLifetime {
684 RowLifetime(None)
685 }
686 fn index_of_key(&self, key: RowKey) -> Option<usize> {
687 let index = usize::try_from(key.row).ok()?;
688 (key.model == 0 && index < self.row_count()).then_some(index)
689 }
690 fn structure_stamp(&self) -> (u64, u64) {
691 (0, self.row_count() as u64)
692 }
693}
694
695impl<T: Clone + PartialEq> ListModel for VecModel<T> {
696 type Item = T;
697
698 fn row_count(&self) -> usize {
699 self.len().min(MAX_ROWS)
700 }
701 fn visit_items(&self, visit: impl FnMut(usize, RowKey, &Self::Item)) {
702 self.visit_row_data(self.row_count(), visit);
703 }
704
705 fn item(&self, row: usize) -> Self::Item {
706 self.row(row).expect("row is inside the model range")
707 }
708
709 fn row_key(&self, row: usize) -> RowKey {
710 self.row_key(row).expect("row is inside the model range")
711 }
712
713 fn row_lifetime(&self, key: RowKey) -> RowLifetime {
714 self.row_lifetime(key)
715 }
716 fn index_of_key(&self, key: RowKey) -> Option<usize> {
717 self.row_index(key).filter(|&index| index < MAX_ROWS)
718 }
719 fn visit_row_keys(&self, range: Range<usize>, visit: impl FnMut(RowKey)) {
720 self.visit_row_keys(range, visit);
721 }
722 fn structure_stamp(&self) -> (u64, u64) {
723 self.structure_stamp()
724 }
725 fn contents_stamp(&self) -> (u64, u64) {
726 self.contents_stamp()
727 }
728}
729
730#[cfg(test)]
731mod tests {
732 use super::*;
733
734 #[test]
735 fn standard_table_projects_values_and_editor_flags_only_for_requested_columns() {
736 use std::cell::RefCell;
737
738 let model = Rc::new(VecModel::from(vec!["A".to_owned(), "B".to_owned()]));
739 let rows = crate::TableRowOrder::default().rows(model.clone());
740 let values = RefCell::new(Vec::new());
741 let flags = RefCell::new(Vec::new());
742 let view = project_standard_table_rows(
743 &rows,
744 0..2,
745 &TableColumnWindow::new(vec![true, false, true, false]),
746 4,
747 |item| Some(item.clone()),
748 |item, column| {
749 values.borrow_mut().push((item.clone(), column));
750 format!("{item}:{column}")
751 },
752 |column| {
753 flags.borrow_mut().push(column);
754 Some(TableCellEditor::String)
755 },
756 );
757 assert_eq!(*flags.borrow(), [0, 2]);
758 assert_eq!(
759 values
760 .borrow()
761 .iter()
762 .map(|(_, column)| *column)
763 .collect::<Vec<_>>(),
764 [0, 2, 0, 2]
765 );
766 assert_eq!(view[1].row_key, model.row_key(1));
767 assert_eq!(view[1].text("row-header-text"), Some("B"));
768 assert_eq!(view[1].child_at(2).unwrap().text("text"), Some("B:2"));
769 assert_eq!(
770 view[1].child_at(2).unwrap().table_cell_editor,
771 Some(TableCellEditor::String)
772 );
773 assert!(view[1].child_at(1).is_none());
774 assert_eq!(view[1].children.len(), 2);
775 }
776
777 #[test]
778 fn projected_cell_values_validate_scalar_ranges_and_preserve_strings() {
779 use TableCellEditor::*;
780 assert_eq!(
781 String.parse(" device "),
782 Some(Value::String(" device ".into()))
783 );
784 assert_eq!(Int.parse(" -42 "), Some(Value::Int(-42)));
785 assert!(!Int.accepts("9223372036854775808"));
786 assert_eq!(Float.parse("1.25e2"), Some(Value::Float(125.0)));
787 for text in ["NaN", "inf", "1e500"] {
788 assert!(!Float.accepts(text));
789 }
790 assert_eq!(Bool.parse("true"), Some(Value::Bool(true)));
791 assert_eq!(Bool.parse("0"), Some(Value::Bool(false)));
792 assert!(!Bool.accepts("2"));
793 assert_eq!(
794 Date.parse("2000-02-29"),
795 crate::Date::new(2000, 2, 29).map(Value::Date)
796 );
797 assert!(!Date.accepts("1900-02-29"));
798 assert!(!Date.accepts("2000-02-29-01"));
799 assert_eq!(
800 Time.parse("23:59:59"),
801 crate::Time::new(23, 59, 59).map(Value::Time)
802 );
803 assert!(!Time.accepts("24:00:00"));
804 assert!(!Time.accepts("12:34"));
805 }
806}