Skip to main content

gpui_rhai/
native_collection.rs

1use std::cmp::Ordering;
2use std::collections::{BTreeMap, BTreeSet};
3use std::fmt;
4use std::sync::{Arc, Mutex, OnceLock};
5
6use rhai::{
7    CustomType, Dynamic, EvalAltResult, FuncRegistration, ImmutableString, Map, Position,
8    TypeBuilder,
9};
10use thiserror::Error;
11
12use crate::{ComponentInstancePath, UiValue};
13
14const MAX_TABLE_ORDER_CACHE_ENTRIES: usize = 64;
15const MAX_FUZZY_ORDER_CACHE_ENTRIES: usize = 64;
16
17#[derive(Clone)]
18pub struct NativeCollection {
19    source: Arc<NativeCollectionSource>,
20    order: Arc<Vec<NativeCollectionEntry>>,
21    sticky_headers: Arc<BTreeSet<usize>>,
22    projection: Option<Arc<CollectionProjection>>,
23}
24
25#[derive(Clone, Debug, Eq, PartialEq)]
26enum NativeCollectionEntry {
27    Row(usize),
28    Group(GroupEntry),
29}
30
31#[derive(Clone, Debug, PartialEq)]
32enum CollectionProjection {
33    Table(TableProjection),
34    List(BTreeSet<String>),
35    /// Rows the application draws: each keeps its own fields and gains its
36    /// key, a `selected` flag and a `disabled` default.
37    Selection(BTreeSet<String>),
38    Fuzzy(FuzzyProjection),
39}
40
41#[derive(Clone, Debug, Eq, PartialEq)]
42struct GroupEntry {
43    key: String,
44    value: String,
45    count: usize,
46    collapsed: bool,
47}
48
49#[derive(Clone)]
50struct TableOrder {
51    entries: Arc<Vec<NativeCollectionEntry>>,
52    sticky_headers: Arc<BTreeSet<usize>>,
53}
54
55struct NativeCollectionSource {
56    key_field: String,
57    rows: Vec<UiValue>,
58    keys: Vec<String>,
59    sorted_orders: Mutex<BTreeMap<SortSpec, Arc<Vec<usize>>>>,
60    table_orders: Mutex<BTreeMap<TableOrderSpec, TableOrder>>,
61    fuzzy_orders: Mutex<BTreeMap<FuzzyOrderSpec, Arc<Vec<NativeCollectionEntry>>>>,
62    list_validation: OnceLock<Result<(), NativeCollectionError>>,
63    selection_validation: OnceLock<Result<(), NativeCollectionError>>,
64}
65
66impl fmt::Debug for NativeCollectionSource {
67    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
68        formatter
69            .debug_struct("NativeCollectionSource")
70            .field("key_field", &self.key_field)
71            .field("rows", &self.rows.len())
72            .finish_non_exhaustive()
73    }
74}
75
76impl fmt::Debug for NativeCollection {
77    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
78        formatter
79            .debug_struct("NativeCollection")
80            .field("key_field", &self.source.key_field)
81            .field("len", &self.order.len())
82            .field("projected", &self.projection.is_some())
83            .finish_non_exhaustive()
84    }
85}
86
87impl PartialEq for NativeCollection {
88    fn eq(&self, other: &Self) -> bool {
89        Arc::ptr_eq(&self.source, &other.source)
90            && (Arc::ptr_eq(&self.order, &other.order) || self.order == other.order)
91            && (Arc::ptr_eq(&self.sticky_headers, &other.sticky_headers)
92                || self.sticky_headers == other.sticky_headers)
93            && self.projection == other.projection
94    }
95}
96
97impl NativeCollection {
98    /// Build an immutable Rust-owned keyed collection.
99    ///
100    /// # Errors
101    ///
102    /// Returns an error unless every row contains one unique scalar key.
103    pub fn new(
104        key_field: impl Into<String>,
105        rows: impl IntoIterator<Item = BTreeMap<String, UiValue>>,
106    ) -> Result<Self, NativeCollectionError> {
107        Self::from_values(key_field, rows.into_iter().map(UiValue::Map).collect())
108    }
109
110    /// Build a collection from already-normalized [`UiValue`] maps.
111    ///
112    /// # Errors
113    ///
114    /// Returns an error for an unsafe key field, non-map rows, missing keys,
115    /// unsupported key values, or duplicate keys.
116    pub fn from_values(
117        key_field: impl Into<String>,
118        rows: Vec<UiValue>,
119    ) -> Result<Self, NativeCollectionError> {
120        let key_field = key_field.into();
121        validate_name(&key_field, "key field")?;
122        let mut seen = BTreeSet::new();
123        let keys = rows
124            .iter()
125            .enumerate()
126            .map(|(index, row)| {
127                let UiValue::Map(row) = row else {
128                    return Err(NativeCollectionError::RowNotMap(index));
129                };
130                let key = row
131                    .get(&key_field)
132                    .ok_or_else(|| NativeCollectionError::MissingKey {
133                        index,
134                        field: key_field.clone(),
135                    })?;
136                let key = scalar_text(key).ok_or_else(|| NativeCollectionError::InvalidKey {
137                    index,
138                    field: key_field.clone(),
139                })?;
140                if key.is_empty() {
141                    return Err(NativeCollectionError::InvalidKey {
142                        index,
143                        field: key_field.clone(),
144                    });
145                }
146                if !seen.insert(key.clone()) {
147                    return Err(NativeCollectionError::DuplicateKey(key));
148                }
149                Ok(key)
150            })
151            .collect::<Result<Vec<_>, _>>()?;
152        let order = Arc::new((0..rows.len()).map(NativeCollectionEntry::Row).collect());
153        Ok(Self {
154            source: Arc::new(NativeCollectionSource {
155                key_field,
156                rows,
157                keys,
158                sorted_orders: Mutex::new(BTreeMap::new()),
159                table_orders: Mutex::new(BTreeMap::new()),
160                fuzzy_orders: Mutex::new(BTreeMap::new()),
161                list_validation: OnceLock::new(),
162                selection_validation: OnceLock::new(),
163            }),
164            order,
165            sticky_headers: Arc::new(BTreeSet::new()),
166            projection: None,
167        })
168    }
169
170    #[must_use]
171    pub fn len(&self) -> usize {
172        self.order.len()
173    }
174
175    #[must_use]
176    pub fn is_empty(&self) -> bool {
177        self.order.is_empty()
178    }
179
180    #[must_use]
181    pub fn key_field(&self) -> &str {
182        &self.source.key_field
183    }
184
185    pub(crate) fn key(&self, index: usize) -> Option<&str> {
186        match self.order.get(index)? {
187            NativeCollectionEntry::Row(source) => self.source.keys.get(*source).map(String::as_str),
188            NativeCollectionEntry::Group(group) => Some(group.key.as_str()),
189        }
190    }
191
192    pub(crate) fn item(&self, index: usize) -> Result<Option<UiValue>, NativeCollectionError> {
193        let Some(entry) = self.order.get(index) else {
194            return Ok(None);
195        };
196        match entry {
197            NativeCollectionEntry::Row(source_index) => {
198                let row = self
199                    .source
200                    .rows
201                    .get(*source_index)
202                    .ok_or(NativeCollectionError::CorruptOrder(*source_index))?;
203                self.projection.as_ref().map_or_else(
204                    || Ok(Some(row.clone())),
205                    |projection| {
206                        projection
207                            .project_row(row, index, self.key(index))
208                            .map(Some)
209                    },
210                )
211            }
212            NativeCollectionEntry::Group(group) => self
213                .projection
214                .as_ref()
215                .ok_or(NativeCollectionError::UnexpectedGroupEntry)
216                .map(|projection| Some(projection.project_group(group))),
217        }
218    }
219
220    pub(crate) fn sticky_headers(&self) -> Arc<BTreeSet<usize>> {
221        Arc::clone(&self.sticky_headers)
222    }
223
224    pub(crate) fn table_view(&self, config: Map) -> Result<Self, NativeCollectionError> {
225        let config = UiValue::from_dynamic(Dynamic::from_map(config))
226            .map_err(|error| NativeCollectionError::InvalidTableConfig(error.to_string()))?;
227        let projection = TableProjection::decode(config, self.key_field())?;
228        let order = self.table_order(&projection)?;
229        Ok(Self {
230            source: Arc::clone(&self.source),
231            order: order.entries,
232            sticky_headers: order.sticky_headers,
233            projection: Some(Arc::new(CollectionProjection::Table(projection))),
234        })
235    }
236
237    /// The rows as a selectable collection the application draws itself: any
238    /// map with a key, its `disabled` a bool when present.
239    fn selection_view(&self, selected: BTreeSet<String>) -> Result<Self, NativeCollectionError> {
240        self.source
241            .selection_validation
242            .get_or_init(|| {
243                for row in &self.source.rows {
244                    selection_row(row, "", &BTreeSet::new())?;
245                }
246                Ok(())
247            })
248            .clone()?;
249        Ok(Self {
250            source: Arc::clone(&self.source),
251            order: Arc::clone(&self.order),
252            sticky_headers: Arc::new(BTreeSet::new()),
253            projection: Some(Arc::new(CollectionProjection::Selection(selected))),
254        })
255    }
256
257    fn list_view(&self, selected: BTreeSet<String>) -> Result<Self, NativeCollectionError> {
258        self.source
259            .list_validation
260            .get_or_init(|| {
261                for row in &self.source.rows {
262                    list_row(row, "", &BTreeSet::new())?;
263                }
264                Ok(())
265            })
266            .clone()?;
267        Ok(Self {
268            source: Arc::clone(&self.source),
269            order: Arc::clone(&self.order),
270            sticky_headers: Arc::new(BTreeSet::new()),
271            projection: Some(Arc::new(CollectionProjection::List(selected))),
272        })
273    }
274
275    pub(crate) fn fuzzy_view(&self, config: Map) -> Result<Self, NativeCollectionError> {
276        let projection = FuzzyProjection::decode(config)?;
277        let order = self.fuzzy_order(&projection)?;
278        Ok(Self {
279            source: Arc::clone(&self.source),
280            order,
281            sticky_headers: Arc::new(BTreeSet::new()),
282            projection: Some(Arc::new(CollectionProjection::Fuzzy(projection))),
283        })
284    }
285
286    fn fuzzy_order(
287        &self,
288        projection: &FuzzyProjection,
289    ) -> Result<Arc<Vec<NativeCollectionEntry>>, NativeCollectionError> {
290        let spec = FuzzyOrderSpec::from(projection);
291        if let Some(order) = self
292            .source
293            .fuzzy_orders
294            .lock()
295            .map_err(|_| NativeCollectionError::Poisoned)?
296            .get(&spec)
297            .cloned()
298        {
299            return Ok(order);
300        }
301        let order = Arc::new(projection.grouped_order(&self.source)?);
302        let mut cache = self
303            .source
304            .fuzzy_orders
305            .lock()
306            .map_err(|_| NativeCollectionError::Poisoned)?;
307        if cache.len() >= MAX_FUZZY_ORDER_CACHE_ENTRIES
308            && let Some(victim) = cache.keys().next().cloned()
309        {
310            cache.remove(&victim);
311        }
312        cache.insert(spec, Arc::clone(&order));
313        Ok(order)
314    }
315
316    pub(crate) fn fuzzy_edge(&self, last: bool) -> Result<String, NativeCollectionError> {
317        let projection = self.fuzzy_projection()?;
318        let rows = if last {
319            Box::new(self.order.iter().rev()) as Box<dyn Iterator<Item = &NativeCollectionEntry>>
320        } else {
321            Box::new(self.order.iter()) as Box<dyn Iterator<Item = &NativeCollectionEntry>>
322        };
323        for entry in rows {
324            if let NativeCollectionEntry::Row(index) = entry
325                && !projection.row_disabled(&self.source, *index)?
326            {
327                return self
328                    .source
329                    .keys
330                    .get(*index)
331                    .cloned()
332                    .ok_or(NativeCollectionError::CorruptOrder(*index));
333            }
334        }
335        Ok(String::new())
336    }
337
338    pub(crate) fn fuzzy_adjacent(
339        &self,
340        active: &str,
341        step: i64,
342    ) -> Result<String, NativeCollectionError> {
343        let projection = self.fuzzy_projection()?;
344        let mut enabled = Vec::new();
345        for entry in self.order.iter() {
346            if let NativeCollectionEntry::Row(index) = entry
347                && !projection.row_disabled(&self.source, *index)?
348            {
349                enabled.push(*index);
350            }
351        }
352        if enabled.is_empty() {
353            return Ok(String::new());
354        }
355        let current = enabled.iter().position(|index| {
356            self.source
357                .keys
358                .get(*index)
359                .is_some_and(|key| key == active)
360        });
361        let next = match step.cmp(&0) {
362            Ordering::Equal => current.unwrap_or(0),
363            Ordering::Less => (current.unwrap_or(0) + enabled.len() - 1) % enabled.len(),
364            Ordering::Greater => (current.unwrap_or(0) + 1) % enabled.len(),
365        };
366        self.source
367            .keys
368            .get(enabled[next])
369            .cloned()
370            .ok_or(NativeCollectionError::CorruptOrder(enabled[next]))
371    }
372
373    /// Keyboard targets of a table view, by the same rule as an array Table:
374    /// the current row is the first displayed row in `selected`; Up and Down
375    /// move one row and stop at the ends; with no current row both go to the
376    /// first. Group headers are skipped. One scan in native code, so a key
377    /// press does not enumerate the collection in Rhai.
378    pub(crate) fn table_neighbors(&self, selected: &BTreeSet<String>) -> TableNeighbors {
379        // (display index, key) of each displayed row; group headers take display
380        // indices too.
381        let rows = self
382            .order
383            .iter()
384            .enumerate()
385            .filter_map(|(display, entry)| match entry {
386                NativeCollectionEntry::Row(index) => {
387                    if matches!(
388                        self.projection.as_deref(),
389                        Some(CollectionProjection::List(_) | CollectionProjection::Selection(_))
390                    ) && row_field(&self.source.rows[*index], "disabled")
391                        == Some(&UiValue::Bool(true))
392                    {
393                        return None;
394                    }
395                    self.source.keys.get(*index).map(|key| (display, key))
396                }
397                NativeCollectionEntry::Group(_) => None,
398            })
399            .collect::<Vec<_>>();
400        let current = rows
401            .iter()
402            .position(|(_, key)| selected.contains(key.as_str()));
403        let at = |index: usize| rows.get(index).map(|(_, key)| (*key).clone());
404        let last = rows.len().saturating_sub(1);
405        TableNeighbors {
406            first: at(0),
407            last: at(last),
408            previous: at(current.map_or(0, |current| current.saturating_sub(1))),
409            next: at(current.map_or(0, |current| (current + 1).min(last))),
410            current: current.and_then(at),
411            current_index: current
412                .and_then(|current| rows.get(current).map(|(display, _)| *display)),
413        }
414    }
415
416    fn fuzzy_projection(&self) -> Result<&FuzzyProjection, NativeCollectionError> {
417        match self.projection.as_deref() {
418            Some(CollectionProjection::Fuzzy(projection)) => Ok(projection),
419            _ => Err(NativeCollectionError::NotFuzzyProjection),
420        }
421    }
422
423    fn table_order(
424        &self,
425        projection: &TableProjection,
426    ) -> Result<TableOrder, NativeCollectionError> {
427        if self.projection.is_none()
428            && projection.sort.is_none()
429            && projection.group_by.is_none()
430            && projection.query.is_empty()
431            && projection.page_size.is_none()
432        {
433            return Ok(TableOrder {
434                entries: Arc::clone(&self.order),
435                sticky_headers: Arc::clone(&self.sticky_headers),
436            });
437        }
438        let spec = TableOrderSpec::from(projection);
439        if let Some(order) = self
440            .source
441            .table_orders
442            .lock()
443            .map_err(|_| NativeCollectionError::Poisoned)?
444            .get(&spec)
445            .cloned()
446        {
447            return Ok(order);
448        }
449        let rows = projection.sort.as_ref().map_or_else(
450            || Ok(Arc::new((0..self.source.rows.len()).collect())),
451            |sort| self.sorted_order(sort),
452        )?;
453        let rows = projection.visible_rows(&self.source, rows.as_ref());
454        let entries = Arc::new(projection.grouped_order(&self.source, &rows)?);
455        let sticky_headers = Arc::new(
456            entries
457                .iter()
458                .enumerate()
459                .filter_map(|(index, entry)| {
460                    matches!(entry, NativeCollectionEntry::Group(_)).then_some(index)
461                })
462                .collect(),
463        );
464        let order = TableOrder {
465            entries,
466            sticky_headers,
467        };
468        let mut cache = self
469            .source
470            .table_orders
471            .lock()
472            .map_err(|_| NativeCollectionError::Poisoned)?;
473        if cache.len() >= MAX_TABLE_ORDER_CACHE_ENTRIES
474            && let Some(victim) = cache.keys().next().cloned()
475        {
476            cache.remove(&victim);
477        }
478        cache.insert(spec, order.clone());
479        Ok(order)
480    }
481
482    fn sorted_order(&self, sort: &SortSpec) -> Result<Arc<Vec<usize>>, NativeCollectionError> {
483        if let Some(cached) = self
484            .source
485            .sorted_orders
486            .lock()
487            .map_err(|_| NativeCollectionError::Poisoned)?
488            .get(sort)
489            .cloned()
490        {
491            return Ok(cached);
492        }
493        // Validate even one-row views, before the comparator can short-circuit.
494        let mut sample = None;
495        for row in &self.source.rows {
496            if let Some(value) = row_field(row, &sort.key).filter(|value| **value != UiValue::Null)
497            {
498                let reference = sample.get_or_insert(value);
499                if compare_values(reference, value).is_none() {
500                    return Err(NativeCollectionError::UnsortableField(sort.key.clone()));
501                }
502            }
503        }
504        let mut order = (0..self.source.rows.len()).collect::<Vec<_>>();
505        order.sort_by(|left, right| {
506            let field = |index: usize| {
507                row_field(&self.source.rows[index], &sort.key)
508                    .filter(|value| **value != UiValue::Null)
509            };
510            let ordering = match (field(*left), field(*right)) {
511                (None, None) => Ordering::Equal,
512                (None, Some(_)) => Ordering::Greater,
513                (Some(_), None) => Ordering::Less,
514                (Some(left), Some(right)) => {
515                    let ordering = compare_values(left, right).expect("validated scalar sort type");
516                    if sort.descending {
517                        ordering.reverse()
518                    } else {
519                        ordering
520                    }
521                }
522            };
523            ordering.then_with(|| left.cmp(right))
524        });
525        let order = Arc::new(order);
526        self.source
527            .sorted_orders
528            .lock()
529            .map_err(|_| NativeCollectionError::Poisoned)?
530            .insert(sort.clone(), Arc::clone(&order));
531        Ok(order)
532    }
533}
534
535impl CustomType for NativeCollection {
536    fn build(mut builder: TypeBuilder<Self>) {
537        builder
538            .with_name("NativeCollection")
539            .with_get("len", |collection: &mut Self| {
540                i64::try_from(collection.len()).unwrap_or(i64::MAX)
541            })
542            .with_get("key_field", |collection: &mut Self| {
543                ImmutableString::from(collection.key_field().to_owned())
544            })
545            .with_fn("to_string", |collection: &mut Self| {
546                format!("NativeCollection(len={})", collection.len())
547            });
548    }
549}
550
551fn register_list_collection_api(engine: &mut rhai::Engine) {
552    register_list_navigation_api(engine);
553    FuncRegistration::new("native_list_view")
554        .in_global_namespace()
555        .register_into_engine(
556            engine,
557            |collection: NativeCollection,
558             selected: rhai::Array|
559             -> Result<NativeCollection, Box<EvalAltResult>> {
560                collection
561                    .list_view(
562                        selected
563                            .into_iter()
564                            .filter_map(|value| value.into_string().ok())
565                            .collect(),
566                    )
567                    .map_err(|error| Box::new(native_collection_runtime_error(&error)))
568            },
569        );
570    FuncRegistration::new("native_list_view")
571        .in_global_namespace()
572        .register_into_engine(
573            engine,
574            |rows: rhai::Array,
575             selected: rhai::Array|
576             -> Result<NativeCollection, Box<EvalAltResult>> {
577                let rows = rows
578                    .into_iter()
579                    .map(|value| {
580                        UiValue::from_dynamic(value).map_err(|error| {
581                            Box::new(EvalAltResult::ErrorRuntime(
582                                error.to_string().into(),
583                                Position::NONE,
584                            ))
585                        })
586                    })
587                    .collect::<Result<Vec<_>, _>>()?;
588                NativeCollection::from_values("key", rows)
589                    .and_then(|collection| {
590                        collection.list_view(
591                            selected
592                                .into_iter()
593                                .filter_map(|value| value.into_string().ok())
594                                .collect(),
595                        )
596                    })
597                    .map_err(|error| Box::new(native_collection_runtime_error(&error)))
598            },
599        );
600}
601
602pub(crate) fn register_native_collection_api(engine: &mut rhai::Engine) {
603    engine.build_type::<NativeCollection>();
604    register_list_collection_api(engine);
605    register_selection_collection_api(engine);
606    register_table_collection_api(engine);
607    register_fuzzy_collection_api(engine);
608    FuncRegistration::new("is_native_collection")
609        .in_global_namespace()
610        .register_into_engine(engine, |value: Dynamic| value.is::<NativeCollection>());
611}
612
613fn register_table_collection_api(engine: &mut rhai::Engine) {
614    register_array_table_api(engine);
615    FuncRegistration::new("native_table_view")
616        .in_global_namespace()
617        .register_into_engine(
618            engine,
619            |collection: NativeCollection,
620             config: Map|
621             -> Result<NativeCollection, Box<EvalAltResult>> {
622                collection.table_view(config).map_err(|error| {
623                    Box::new(EvalAltResult::ErrorRuntime(
624                        error.to_string().into(),
625                        Position::NONE,
626                    ))
627                })
628            },
629        );
630    FuncRegistration::new("native_table_neighbors")
631        .in_global_namespace()
632        .register_into_engine(
633            engine,
634            |collection: NativeCollection, selected: rhai::Array| -> Map {
635                let selected = selected
636                    .into_iter()
637                    .filter_map(|key| key.into_string().ok())
638                    .collect::<BTreeSet<_>>();
639                collection.table_neighbors(&selected).into_map()
640            },
641        );
642}
643
644fn selected_keys(selected: rhai::Array) -> BTreeSet<String> {
645    selected
646        .into_iter()
647        .filter_map(|value| value.into_string().ok())
648        .collect()
649}
650
651/// `native_selection_view(items, selected)` and `native_selection_neighbors`:
652/// the rows of a `SelectableList`, an array of maps or a native collection, each
653/// keyed by `key`.
654fn register_selection_collection_api(engine: &mut rhai::Engine) {
655    fn rows(items: Dynamic) -> Result<NativeCollection, Box<EvalAltResult>> {
656        if items.is::<NativeCollection>() {
657            return Ok(items.cast::<NativeCollection>());
658        }
659        let rows = items
660            .try_cast::<rhai::Array>()
661            .ok_or_else(|| {
662                Box::new(EvalAltResult::ErrorRuntime(
663                    "selection items must be an array or a NativeCollection".into(),
664                    Position::NONE,
665                ))
666            })?
667            .into_iter()
668            .map(|value| {
669                UiValue::from_dynamic(value).map_err(|error| {
670                    Box::new(EvalAltResult::ErrorRuntime(
671                        error.to_string().into(),
672                        Position::NONE,
673                    ))
674                })
675            })
676            .collect::<Result<Vec<_>, _>>()?;
677        NativeCollection::from_values("key", rows)
678            .map_err(|error| Box::new(native_collection_runtime_error(&error)))
679    }
680    FuncRegistration::new("native_selection_view")
681        .in_global_namespace()
682        .register_into_engine(
683            engine,
684            |items: Dynamic,
685             selected: rhai::Array|
686             -> Result<NativeCollection, Box<EvalAltResult>> {
687                rows(items)?
688                    .selection_view(selected_keys(selected))
689                    .map_err(|error| Box::new(native_collection_runtime_error(&error)))
690            },
691        );
692    FuncRegistration::new("native_selection_neighbors")
693        .in_global_namespace()
694        .register_into_engine(
695            engine,
696            |items: Dynamic, selected: rhai::Array| -> Result<Map, Box<EvalAltResult>> {
697                let selected = selected_keys(selected);
698                let view = rows(items)?
699                    .selection_view(selected.clone())
700                    .map_err(|error| Box::new(native_collection_runtime_error(&error)))?;
701                Ok(view.table_neighbors(&selected).into_map())
702            },
703        );
704}
705
706fn register_list_navigation_api(engine: &mut rhai::Engine) {
707    FuncRegistration::new("native_list_neighbors")
708        .in_global_namespace()
709        .register_into_engine(
710            engine,
711            |collection: NativeCollection,
712             selected: rhai::Array|
713             -> Result<Map, Box<EvalAltResult>> {
714                let selected: BTreeSet<_> = selected
715                    .into_iter()
716                    .filter_map(|value| value.into_string().ok())
717                    .collect();
718                let collection = collection
719                    .list_view(selected.clone())
720                    .map_err(|error| Box::new(native_collection_runtime_error(&error)))?;
721                let neighbors = collection.table_neighbors(&selected);
722                let children = neighbors
723                    .current_index
724                    .and_then(|index| collection.item(index).ok().flatten())
725                    .is_some_and(|item| {
726                        row_field(&item, "has_children") == Some(&UiValue::Bool(true))
727                    });
728                let mut result = neighbors.into_map();
729                result.insert("has_children".into(), Dynamic::from(children));
730                Ok(result)
731            },
732        );
733}
734
735fn register_array_table_api(engine: &mut rhai::Engine) {
736    FuncRegistration::new("native_table_view")
737        .in_global_namespace()
738        .register_into_engine(
739            engine,
740            |rows: rhai::Array, config: Map| -> Result<NativeCollection, Box<EvalAltResult>> {
741                let key = config
742                    .get("row_key")
743                    .and_then(|value| value.clone().try_cast::<ImmutableString>())
744                    .ok_or_else(|| {
745                        Box::new(native_collection_runtime_error(
746                            &NativeCollectionError::InvalidTableConfig(
747                                "row_key must be a string".into(),
748                            ),
749                        ))
750                    })?;
751                let values = rows
752                    .into_iter()
753                    .map(|value| {
754                        UiValue::from_dynamic(value).map_err(|error| {
755                            Box::new(EvalAltResult::ErrorRuntime(
756                                error.to_string().into(),
757                                Position::NONE,
758                            ))
759                        })
760                    })
761                    .collect::<Result<Vec<_>, _>>()?;
762                NativeCollection::from_values(key.as_str(), values)
763                    .and_then(|rows| rows.table_view(config))
764                    .map_err(|error| Box::new(native_collection_runtime_error(&error)))
765            },
766        );
767}
768
769fn register_fuzzy_collection_api(engine: &mut rhai::Engine) {
770    FuncRegistration::new("native_fuzzy_view")
771        .in_global_namespace()
772        .register_into_engine(
773            engine,
774            |collection: NativeCollection,
775             config: Map|
776             -> Result<NativeCollection, Box<EvalAltResult>> {
777                collection
778                    .fuzzy_view(config)
779                    .map_err(|error| Box::new(native_collection_runtime_error(&error)))
780            },
781        );
782    FuncRegistration::new("native_fuzzy_edge")
783        .in_global_namespace()
784        .register_into_engine(
785            engine,
786            |collection: NativeCollection,
787             last: bool|
788             -> Result<ImmutableString, Box<EvalAltResult>> {
789                collection
790                    .fuzzy_edge(last)
791                    .map(ImmutableString::from)
792                    .map_err(|error| Box::new(native_collection_runtime_error(&error)))
793            },
794        );
795    FuncRegistration::new("native_fuzzy_adjacent")
796        .in_global_namespace()
797        .register_into_engine(
798            engine,
799            |collection: NativeCollection,
800             active: ImmutableString,
801             step: i64|
802             -> Result<ImmutableString, Box<EvalAltResult>> {
803                collection
804                    .fuzzy_adjacent(active.as_str(), step)
805                    .map(ImmutableString::from)
806                    .map_err(|error| Box::new(native_collection_runtime_error(&error)))
807            },
808        );
809}
810
811/// The row keys a Table's navigation keys move to; `None` when the view has
812/// no rows (or no current row).
813#[derive(Debug, Default, PartialEq, Eq)]
814pub(crate) struct TableNeighbors {
815    pub first: Option<String>,
816    pub last: Option<String>,
817    pub previous: Option<String>,
818    pub next: Option<String>,
819    pub current: Option<String>,
820    /// The current row's index among the displayed items.
821    pub current_index: Option<usize>,
822}
823
824impl TableNeighbors {
825    fn into_map(self) -> Map {
826        let key = |value: Option<String>| value.map_or(Dynamic::UNIT, Dynamic::from);
827        Map::from([
828            ("first".into(), key(self.first)),
829            ("last".into(), key(self.last)),
830            ("previous".into(), key(self.previous)),
831            ("next".into(), key(self.next)),
832            ("current".into(), key(self.current)),
833            (
834                "current_index".into(),
835                self.current_index
836                    .and_then(|index| rhai::INT::try_from(index).ok())
837                    .map_or(Dynamic::UNIT, Dynamic::from),
838            ),
839        ])
840    }
841}
842
843fn native_collection_runtime_error(error: &NativeCollectionError) -> EvalAltResult {
844    EvalAltResult::ErrorRuntime(error.to_string().into(), Position::NONE)
845}
846
847// Shared List/ColumnBrowser row normalization. Work remains native for large
848// Host collections; Rhai sees only the realized virtual rows and key targets.
849fn selection_row(
850    row: &UiValue,
851    key: &str,
852    selected: &BTreeSet<String>,
853) -> Result<UiValue, NativeCollectionError> {
854    let UiValue::Map(row) = row else {
855        return Err(NativeCollectionError::RowNotMap(0));
856    };
857    let mut item = row.clone();
858    item.insert("key".into(), UiValue::String(key.into()));
859    let disabled = item
860        .entry("disabled".into())
861        .or_insert(UiValue::Bool(false));
862    if !matches!(disabled, UiValue::Bool(_)) {
863        return Err(NativeCollectionError::InvalidTableConfig(
864            "SelectableList disabled must be a bool".into(),
865        ));
866    }
867    item.insert("selected".into(), UiValue::Bool(selected.contains(key)));
868    Ok(UiValue::Map(item))
869}
870
871fn list_row(
872    row: &UiValue,
873    key: &str,
874    selected: &BTreeSet<String>,
875) -> Result<UiValue, NativeCollectionError> {
876    let UiValue::Map(row) = row else {
877        return Err(NativeCollectionError::RowNotMap(0));
878    };
879    if !matches!(row.get("title"), Some(UiValue::String(_))) {
880        return Err(NativeCollectionError::InvalidTableConfig(
881            "List title must be a string".into(),
882        ));
883    }
884    let mut item = row.clone();
885    item.insert("key".into(), UiValue::String(key.into()));
886    for name in ["secondary", "meta", "badge"] {
887        item.entry(name.into()).or_insert(UiValue::Null);
888    }
889    for name in ["disabled", "has_children"] {
890        let value = item.entry(name.into()).or_insert(UiValue::Bool(false));
891        if !matches!(value, UiValue::Bool(_)) {
892            return Err(NativeCollectionError::InvalidTableConfig(format!(
893                "List {name} must be a bool"
894            )));
895        }
896    }
897    for name in ["secondary", "meta"] {
898        if !matches!(item[name], UiValue::Null | UiValue::String(_)) {
899            return Err(NativeCollectionError::InvalidTableConfig(format!(
900                "List {name} must be a string or null"
901            )));
902        }
903    }
904    if let Some(UiValue::Map(badge)) = item.get_mut("badge") {
905        if !matches!(badge.get("text"), Some(UiValue::String(_))) {
906            return Err(NativeCollectionError::InvalidTableConfig(
907                "List badge.text must be a string".into(),
908            ));
909        }
910        badge
911            .entry("variant".into())
912            .or_insert(UiValue::String("neutral".into()));
913        badge.entry("dot".into()).or_insert(UiValue::Bool(true));
914        let Some(UiValue::String(variant)) = badge.get("variant") else {
915            return Err(NativeCollectionError::InvalidTableConfig(
916                "List badge.variant must be a string".into(),
917            ));
918        };
919        validate_badge_variant(variant)?;
920        if !matches!(badge.get("dot"), Some(UiValue::Bool(_))) {
921            return Err(NativeCollectionError::InvalidTableConfig(
922                "List badge.dot must be a bool".into(),
923            ));
924        }
925    } else if item["badge"] != UiValue::Null {
926        return Err(NativeCollectionError::InvalidTableConfig(
927            "List badge must be a map or null".into(),
928        ));
929    }
930    item.insert("selected".into(), UiValue::Bool(selected.contains(key)));
931    Ok(UiValue::Map(item))
932}
933
934impl CollectionProjection {
935    fn project_row(
936        &self,
937        row: &UiValue,
938        index: usize,
939        key: Option<&str>,
940    ) -> Result<UiValue, NativeCollectionError> {
941        match self {
942            Self::Table(projection) => projection.project_row(row, index),
943            Self::List(selected) => list_row(row, key.unwrap_or_default(), selected),
944            Self::Selection(selected) => selection_row(row, key.unwrap_or_default(), selected),
945            Self::Fuzzy(projection) => projection.project_row(row, index, key),
946        }
947    }
948
949    fn project_group(&self, group: &GroupEntry) -> UiValue {
950        match self {
951            Self::Table(projection) => projection.project_group(group),
952            Self::List(_) | Self::Selection(_) => UiValue::Null,
953            Self::Fuzzy(projection) => projection.project_group(group),
954        }
955    }
956}
957
958#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
959struct FuzzyOrderSpec {
960    query: String,
961    label_field: String,
962    keywords_field: String,
963    group_field: String,
964}
965
966impl From<&FuzzyProjection> for FuzzyOrderSpec {
967    fn from(projection: &FuzzyProjection) -> Self {
968        Self {
969            query: projection.query.clone(),
970            label_field: projection.label_field.clone(),
971            keywords_field: projection.keywords_field.clone(),
972            group_field: projection.group_field.clone(),
973        }
974    }
975}
976
977#[derive(Clone, Debug, PartialEq)]
978struct FuzzyProjection {
979    query: String,
980    label_field: String,
981    keywords_field: String,
982    group_field: String,
983    shortcut_field: String,
984    disabled_field: String,
985    active: String,
986    row_height: f64,
987}
988
989impl FuzzyProjection {
990    fn decode(config: Map) -> Result<Self, NativeCollectionError> {
991        let UiValue::Map(mut config) = UiValue::from_dynamic(Dynamic::from_map(config))
992            .map_err(|error| NativeCollectionError::InvalidFuzzyConfig(error.to_string()))?
993        else {
994            return Err(NativeCollectionError::InvalidFuzzyConfig(
995                "configuration must be a map".to_owned(),
996            ));
997        };
998        let query = fuzzy_take_string(&mut config, "query")?.to_lowercase();
999        let label_field = fuzzy_take_string(&mut config, "label_field")?;
1000        let keywords_field = fuzzy_take_string(&mut config, "keywords_field")?;
1001        let group_field = fuzzy_take_string(&mut config, "group_field")?;
1002        let shortcut_field = fuzzy_take_string(&mut config, "shortcut_field")?;
1003        let disabled_field = fuzzy_take_string(&mut config, "disabled_field")?;
1004        let active = fuzzy_take_string(&mut config, "active")?;
1005        let row_height = fuzzy_take_number(&mut config, "row_height")?;
1006        if !row_height.is_finite() || row_height <= 0.0 {
1007            return Err(NativeCollectionError::InvalidFuzzyConfig(
1008                "row_height must be finite and positive".to_owned(),
1009            ));
1010        }
1011        for (field, label) in [
1012            (&label_field, "label field"),
1013            (&keywords_field, "keywords field"),
1014            (&group_field, "group field"),
1015            (&shortcut_field, "shortcut field"),
1016            (&disabled_field, "disabled field"),
1017        ] {
1018            validate_name(field, label)?;
1019        }
1020        if !config.is_empty() {
1021            return Err(NativeCollectionError::InvalidFuzzyConfig(format!(
1022                "unknown configuration fields: {}",
1023                config.keys().cloned().collect::<Vec<_>>().join(", ")
1024            )));
1025        }
1026        Ok(Self {
1027            query,
1028            label_field,
1029            keywords_field,
1030            group_field,
1031            shortcut_field,
1032            disabled_field,
1033            active,
1034            row_height,
1035        })
1036    }
1037
1038    fn grouped_order(
1039        &self,
1040        source: &NativeCollectionSource,
1041    ) -> Result<Vec<NativeCollectionEntry>, NativeCollectionError> {
1042        let mut grouped = Vec::new();
1043        for (index, row) in source.rows.iter().enumerate() {
1044            let label = Self::row_string(row, index, &self.label_field, true)?;
1045            let keywords = self.row_keywords(row, index)?;
1046            let score = fuzzy_score(&label, &keywords, &self.query);
1047            if score < 0 {
1048                continue;
1049            }
1050            let group = Self::row_string(row, index, &self.group_field, false)?;
1051            grouped.push((group, (index, score)));
1052        }
1053        let source_keys = source
1054            .keys
1055            .iter()
1056            .map(String::as_str)
1057            .collect::<BTreeSet<_>>();
1058        let mut header_keys = BTreeSet::new();
1059        let mut entries = Vec::new();
1060        for (group, mut rows) in crate::collection_projection::stable_groups(grouped) {
1061            rows.sort_by(|(left_index, left_score), (right_index, right_score)| {
1062                right_score
1063                    .cmp(left_score)
1064                    .then_with(|| left_index.cmp(right_index))
1065            });
1066            if !group.is_empty() {
1067                let key =
1068                    unique_group_key(&format!("command:{group}"), &source_keys, &mut header_keys);
1069                entries.push(NativeCollectionEntry::Group(GroupEntry {
1070                    key,
1071                    value: group,
1072                    count: rows.len(),
1073                    collapsed: false,
1074                }));
1075            }
1076            entries.extend(
1077                rows.into_iter()
1078                    .map(|(index, _)| NativeCollectionEntry::Row(index)),
1079            );
1080        }
1081        Ok(entries)
1082    }
1083
1084    fn project_row(
1085        &self,
1086        row: &UiValue,
1087        index: usize,
1088        key: Option<&str>,
1089    ) -> Result<UiValue, NativeCollectionError> {
1090        let key = key.ok_or(NativeCollectionError::CorruptOrder(index))?;
1091        let label = Self::row_string(row, index, &self.label_field, true)?;
1092        let shortcut = Self::row_string(row, index, &self.shortcut_field, false)?;
1093        let disabled = self.row_disabled_value(row, index)?;
1094        Ok(UiValue::Map(BTreeMap::from([
1095            ("kind".to_owned(), UiValue::String("item".to_owned())),
1096            ("key".to_owned(), UiValue::String(format!("item:{key}"))),
1097            ("value".to_owned(), UiValue::String(key.to_owned())),
1098            ("label".to_owned(), UiValue::String(label)),
1099            ("shortcut".to_owned(), UiValue::String(shortcut)),
1100            ("disabled".to_owned(), UiValue::Bool(disabled)),
1101            ("active".to_owned(), UiValue::Bool(self.active == key)),
1102            ("height".to_owned(), UiValue::Float(self.row_height)),
1103        ])))
1104    }
1105
1106    fn project_group(&self, group: &GroupEntry) -> UiValue {
1107        UiValue::Map(BTreeMap::from([
1108            ("kind".to_owned(), UiValue::String("group".to_owned())),
1109            ("key".to_owned(), UiValue::String(group.key.clone())),
1110            ("label".to_owned(), UiValue::String(group.value.clone())),
1111            ("height".to_owned(), UiValue::Float(self.row_height)),
1112        ]))
1113    }
1114
1115    fn row_disabled(
1116        &self,
1117        source: &NativeCollectionSource,
1118        index: usize,
1119    ) -> Result<bool, NativeCollectionError> {
1120        let row = source
1121            .rows
1122            .get(index)
1123            .ok_or(NativeCollectionError::CorruptOrder(index))?;
1124        self.row_disabled_value(row, index)
1125    }
1126
1127    fn row_disabled_value(
1128        &self,
1129        row: &UiValue,
1130        index: usize,
1131    ) -> Result<bool, NativeCollectionError> {
1132        match row_field(row, &self.disabled_field) {
1133            None | Some(UiValue::Null) => Ok(false),
1134            Some(UiValue::Bool(value)) => Ok(*value),
1135            Some(_) => Err(NativeCollectionError::InvalidFuzzyConfig(format!(
1136                "row {index} field `{}` must be bool when present",
1137                self.disabled_field
1138            ))),
1139        }
1140    }
1141
1142    fn row_string(
1143        row: &UiValue,
1144        index: usize,
1145        field: &str,
1146        required: bool,
1147    ) -> Result<String, NativeCollectionError> {
1148        match row_field(row, field) {
1149            Some(UiValue::String(value)) if !required || !value.is_empty() => Ok(value.clone()),
1150            None | Some(UiValue::Null) if !required => Ok(String::new()),
1151            _ => Err(NativeCollectionError::InvalidFuzzyConfig(format!(
1152                "row {index} field `{field}` must be {}string",
1153                if required { "a non-empty " } else { "a " }
1154            ))),
1155        }
1156    }
1157
1158    fn row_keywords(
1159        &self,
1160        row: &UiValue,
1161        index: usize,
1162    ) -> Result<Vec<String>, NativeCollectionError> {
1163        match row_field(row, &self.keywords_field) {
1164            None | Some(UiValue::Null) => Ok(Vec::new()),
1165            Some(UiValue::Array(values)) => values
1166                .iter()
1167                .enumerate()
1168                .map(|(keyword, value)| match value {
1169                    UiValue::String(value) => Ok(value.clone()),
1170                    _ => Err(NativeCollectionError::InvalidFuzzyConfig(format!(
1171                        "row {index} field `{}` item {keyword} must be a string",
1172                        self.keywords_field
1173                    ))),
1174                })
1175                .collect(),
1176            Some(_) => Err(NativeCollectionError::InvalidFuzzyConfig(format!(
1177                "row {index} field `{}` must be an array of strings",
1178                self.keywords_field
1179            ))),
1180        }
1181    }
1182}
1183
1184fn fuzzy_score(label: &str, keywords: &[String], query: &str) -> i64 {
1185    std::iter::once((label, 0))
1186        .chain(keywords.iter().map(|keyword| (keyword.as_str(), -100)))
1187        .map(|(candidate, penalty)| fuzzy_candidate_score(candidate, query) + penalty)
1188        .max()
1189        .unwrap_or(-1)
1190}
1191
1192fn fuzzy_candidate_score(candidate: &str, query: &str) -> i64 {
1193    if query.is_empty() {
1194        return 0;
1195    }
1196    let candidate = candidate.to_lowercase();
1197    if candidate == query {
1198        return 10_000;
1199    }
1200    let length = i64::try_from(candidate.chars().count()).unwrap_or(i64::MAX);
1201    if candidate.starts_with(query) {
1202        return 8_000 - length;
1203    }
1204    if let Some(position) = candidate.find(query) {
1205        let position = i64::try_from(candidate[..position].chars().count()).unwrap_or(i64::MAX);
1206        return 6_000 - position.saturating_mul(8) - length;
1207    }
1208    let chars = candidate.chars().collect::<Vec<_>>();
1209    let mut position = 0usize;
1210    let mut gaps = 0i64;
1211    for needle in query.chars() {
1212        let Some(found) = chars[position..]
1213            .iter()
1214            .position(|candidate| *candidate == needle)
1215        else {
1216            return -1;
1217        };
1218        gaps = gaps.saturating_add(i64::try_from(found).unwrap_or(i64::MAX));
1219        position = position.saturating_add(found).saturating_add(1);
1220    }
1221    4_000 - gaps.saturating_mul(12) - length
1222}
1223
1224fn fuzzy_take_string(
1225    values: &mut BTreeMap<String, UiValue>,
1226    name: &str,
1227) -> Result<String, NativeCollectionError> {
1228    match values.remove(name) {
1229        Some(UiValue::String(value)) => Ok(value),
1230        _ => Err(NativeCollectionError::InvalidFuzzyConfig(format!(
1231            "{name} must be a string"
1232        ))),
1233    }
1234}
1235
1236fn fuzzy_take_number(
1237    values: &mut BTreeMap<String, UiValue>,
1238    name: &str,
1239) -> Result<f64, NativeCollectionError> {
1240    match values.remove(name) {
1241        Some(UiValue::Float(value)) => Ok(value),
1242        Some(UiValue::Integer(value)) => Ok(integer_float(value)),
1243        _ => Err(NativeCollectionError::InvalidFuzzyConfig(format!(
1244            "{name} must be a number"
1245        ))),
1246    }
1247}
1248
1249#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
1250struct SortSpec {
1251    key: String,
1252    descending: bool,
1253}
1254
1255#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
1256struct TableOrderSpec {
1257    sort: Option<SortSpec>,
1258    group_by: Option<String>,
1259    collapsed_groups: BTreeSet<String>,
1260    query: String,
1261    search_fields: Vec<String>,
1262    page: usize,
1263    page_size: Option<usize>,
1264}
1265
1266impl From<&TableProjection> for TableOrderSpec {
1267    fn from(projection: &TableProjection) -> Self {
1268        Self {
1269            sort: projection.sort.clone(),
1270            group_by: projection.group_by.clone(),
1271            collapsed_groups: projection.collapsed_groups.clone(),
1272            query: projection.query.clone(),
1273            search_fields: projection.search_fields.clone(),
1274            page: projection.page,
1275            page_size: projection.page_size,
1276        }
1277    }
1278}
1279
1280#[derive(Clone, Debug, PartialEq)]
1281struct TableProjection {
1282    label: String,
1283    row_key: String,
1284    columns: Vec<TableColumn>,
1285    selected: BTreeSet<String>,
1286    striped: bool,
1287    row_height: f64,
1288    sort: Option<SortSpec>,
1289    group_by: Option<String>,
1290    collapsed_groups: BTreeSet<String>,
1291    group_toggle: bool,
1292    query: String,
1293    search_fields: Vec<String>,
1294    page: usize,
1295    page_size: Option<usize>,
1296}
1297
1298#[derive(Clone, Debug, PartialEq)]
1299struct TableColumn {
1300    key: String,
1301    sort_key: String,
1302    width: UiValue,
1303    align: String,
1304    resize_signal_key: Option<String>,
1305    adornments: Vec<TableAdornment>,
1306}
1307
1308#[derive(Clone, Debug, Eq, PartialEq)]
1309struct TableAdornment {
1310    text_key: String,
1311    variant: String,
1312    variant_key: Option<String>,
1313    dot: bool,
1314}
1315
1316impl TableProjection {
1317    fn decode(config: UiValue, source_key: &str) -> Result<Self, NativeCollectionError> {
1318        let UiValue::Map(mut config) = config else {
1319            return Err(NativeCollectionError::InvalidTableConfig(
1320                "configuration must be a map".to_owned(),
1321            ));
1322        };
1323        let row_key = take_string(&mut config, "row_key")?;
1324        if row_key != source_key {
1325            return Err(NativeCollectionError::KeyFieldMismatch {
1326                source_key: source_key.to_owned(),
1327                requested: row_key,
1328            });
1329        }
1330        let label = take_string(&mut config, "label")?;
1331        let columns = take_array(&mut config, "columns")?
1332            .into_iter()
1333            .map(TableColumn::decode)
1334            .collect::<Result<Vec<_>, _>>()?;
1335        let selected = take_array(&mut config, "selected_keys")?
1336            .into_iter()
1337            .enumerate()
1338            .map(|(index, value)| match value {
1339                UiValue::String(value) => Ok(value),
1340                _ => Err(NativeCollectionError::InvalidTableConfig(format!(
1341                    "selected_keys[{index}] must be a string"
1342                ))),
1343            })
1344            .collect::<Result<BTreeSet<_>, _>>()?;
1345        // A row is drawn from its selected flag; a click builds the next
1346        // selection in Rhai, so the mode is only validated here.
1347        let selection_mode = take_string(&mut config, "selection_mode")?;
1348        if !matches!(selection_mode.as_str(), "none" | "single" | "multiple") {
1349            return Err(NativeCollectionError::InvalidTableConfig(format!(
1350                "unknown selection mode `{selection_mode}`"
1351            )));
1352        }
1353        let striped = take_bool(&mut config, "striped")?;
1354        let row_height = take_number(&mut config, "row_height")?;
1355        if !row_height.is_finite() || row_height <= 0.0 {
1356            return Err(NativeCollectionError::InvalidTableConfig(
1357                "row_height must be finite and positive".to_owned(),
1358            ));
1359        }
1360        let sort = decode_sort(config.remove("sort"))?
1361            .map(|mut sort| {
1362                let column = columns
1363                    .iter()
1364                    .find(|column| column.key == sort.key)
1365                    .ok_or_else(|| {
1366                        NativeCollectionError::InvalidTableConfig(format!(
1367                            "sort key `{}` is not a declared column",
1368                            sort.key
1369                        ))
1370                    })?;
1371                sort.key.clone_from(&column.sort_key);
1372                Ok(sort)
1373            })
1374            .transpose()?;
1375        let (group_by, collapsed_groups, group_toggle) = decode_grouping(&mut config, &columns)?;
1376        let (query, search_fields, page, page_size) =
1377            decode_table_window(&mut config, &row_key, &columns)?;
1378        if !config.is_empty() {
1379            return Err(NativeCollectionError::InvalidTableConfig(format!(
1380                "unknown configuration fields: {}",
1381                config.keys().cloned().collect::<Vec<_>>().join(", ")
1382            )));
1383        }
1384        Ok(Self {
1385            label,
1386            row_key,
1387            columns,
1388            selected,
1389            striped,
1390            row_height,
1391            sort,
1392            group_by,
1393            collapsed_groups,
1394            group_toggle,
1395            query,
1396            search_fields,
1397            page,
1398            page_size,
1399        })
1400    }
1401
1402    fn visible_rows(&self, source: &NativeCollectionSource, rows: &[usize]) -> Vec<usize> {
1403        let mut visible = if self.query.is_empty() {
1404            rows.to_vec()
1405        } else {
1406            rows.iter()
1407                .copied()
1408                .filter(|index| {
1409                    source.rows.get(*index).is_some_and(|row| {
1410                        self.search_fields.iter().any(|field| {
1411                            row_field(row, field)
1412                                .and_then(scalar_text)
1413                                .is_some_and(|value| value.to_lowercase().contains(&self.query))
1414                        })
1415                    })
1416                })
1417                .collect()
1418        };
1419        if let Some(page_size) = self.page_size {
1420            let start = self.page.saturating_sub(1).saturating_mul(page_size);
1421            if start >= visible.len() {
1422                visible.clear();
1423            } else {
1424                let end = start.saturating_add(page_size).min(visible.len());
1425                visible = visible[start..end].to_vec();
1426            }
1427        }
1428        visible
1429    }
1430
1431    fn grouped_order(
1432        &self,
1433        source: &NativeCollectionSource,
1434        rows: &[usize],
1435    ) -> Result<Vec<NativeCollectionEntry>, NativeCollectionError> {
1436        let Some(group_by) = &self.group_by else {
1437            return Ok(rows
1438                .iter()
1439                .copied()
1440                .map(NativeCollectionEntry::Row)
1441                .collect());
1442        };
1443        let mut grouped = Vec::with_capacity(rows.len());
1444        for source_index in rows {
1445            let row = source
1446                .rows
1447                .get(*source_index)
1448                .ok_or(NativeCollectionError::CorruptOrder(*source_index))?;
1449            let value = match row_field(row, group_by) {
1450                Some(UiValue::String(value)) if !value.is_empty() => value.clone(),
1451                _ => {
1452                    return Err(NativeCollectionError::InvalidGroupField {
1453                        index: *source_index,
1454                        field: group_by.clone(),
1455                    });
1456                }
1457            };
1458            grouped.push((value, *source_index));
1459        }
1460        let source_keys = source
1461            .keys
1462            .iter()
1463            .map(String::as_str)
1464            .collect::<BTreeSet<_>>();
1465        let mut header_keys = BTreeSet::new();
1466        let groups = crate::collection_projection::stable_groups(grouped);
1467        let mut entries = Vec::with_capacity(rows.len().saturating_add(groups.len()));
1468        for (value, rows) in groups {
1469            let key = unique_group_key(&value, &source_keys, &mut header_keys);
1470            let collapsed = self.collapsed_groups.contains(&value);
1471            entries.push(NativeCollectionEntry::Group(GroupEntry {
1472                key,
1473                value,
1474                count: rows.len(),
1475                collapsed,
1476            }));
1477            if !collapsed {
1478                entries.extend(rows.into_iter().map(NativeCollectionEntry::Row));
1479            }
1480        }
1481        Ok(entries)
1482    }
1483
1484    fn project_row(&self, row: &UiValue, index: usize) -> Result<UiValue, NativeCollectionError> {
1485        let UiValue::Map(row) = row else {
1486            return Err(NativeCollectionError::RowNotMap(index));
1487        };
1488        let key = row.get(&self.row_key).and_then(scalar_text);
1489        let key = key.ok_or_else(|| {
1490            NativeCollectionError::InvalidTableConfig("projected row key is unavailable".to_owned())
1491        })?;
1492        let selected = self.selected.contains(&key);
1493        let cells = self
1494            .columns
1495            .iter()
1496            .map(|column| {
1497                let text = row
1498                    .get(&column.key)
1499                    .map_or_else(String::new, display_scalar);
1500                let adornments = column
1501                    .adornments
1502                    .iter()
1503                    .map(|adornment| adornment.project(row))
1504                    .collect::<Result<Vec<_>, _>>()?
1505                    .into_iter()
1506                    .flatten()
1507                    .collect();
1508                let mut cell = BTreeMap::from([
1509                    ("key".to_owned(), UiValue::String(column.key.clone())),
1510                    ("text".to_owned(), UiValue::String(text)),
1511                    ("width".to_owned(), column.width.clone()),
1512                    ("align".to_owned(), UiValue::String(column.align.clone())),
1513                    ("adornments".to_owned(), UiValue::Array(adornments)),
1514                ]);
1515                if let Some(signal_key) = &column.resize_signal_key {
1516                    cell.insert(
1517                        "resize_signal_key".to_owned(),
1518                        UiValue::String(signal_key.clone()),
1519                    );
1520                }
1521                Ok(UiValue::Map(cell))
1522            })
1523            .collect::<Result<Vec<_>, NativeCollectionError>>()?;
1524        Ok(UiValue::Map(BTreeMap::from([
1525            ("kind".to_owned(), UiValue::String("row".to_owned())),
1526            ("key".to_owned(), UiValue::String(key)),
1527            (
1528                "label".to_owned(),
1529                UiValue::String(format!("{} row {}", self.label, index + 1)),
1530            ),
1531            ("cells".to_owned(), UiValue::Array(cells)),
1532            ("selected".to_owned(), UiValue::Bool(selected)),
1533            (
1534                "striped".to_owned(),
1535                UiValue::Bool(self.striped && index % 2 == 1),
1536            ),
1537            ("height".to_owned(), UiValue::Float(self.row_height)),
1538        ])))
1539    }
1540
1541    fn project_group(&self, group: &GroupEntry) -> UiValue {
1542        UiValue::Map(BTreeMap::from([
1543            ("kind".to_owned(), UiValue::String("group".to_owned())),
1544            ("key".to_owned(), UiValue::String(group.key.clone())),
1545            ("group".to_owned(), UiValue::String(group.value.clone())),
1546            (
1547                "count".to_owned(),
1548                UiValue::Integer(i64::try_from(group.count).unwrap_or(i64::MAX)),
1549            ),
1550            ("collapsed".to_owned(), UiValue::Bool(group.collapsed)),
1551            ("toggle".to_owned(), UiValue::Bool(self.group_toggle)),
1552            ("height".to_owned(), UiValue::Float(self.row_height)),
1553        ]))
1554    }
1555}
1556
1557fn decode_table_window(
1558    config: &mut BTreeMap<String, UiValue>,
1559    row_key: &str,
1560    columns: &[TableColumn],
1561) -> Result<(String, Vec<String>, usize, Option<usize>), NativeCollectionError> {
1562    let query = match config.remove("query") {
1563        None => String::new(),
1564        Some(UiValue::String(value)) => value.to_lowercase(),
1565        _ => {
1566            return Err(NativeCollectionError::InvalidTableConfig(
1567                "query must be a string".to_owned(),
1568            ));
1569        }
1570    };
1571    let search_fields = match config.remove("search_fields") {
1572        None => Vec::new(),
1573        Some(UiValue::Array(values)) => values,
1574        _ => {
1575            return Err(NativeCollectionError::InvalidTableConfig(
1576                "search_fields must be an array".to_owned(),
1577            ));
1578        }
1579    }
1580    .into_iter()
1581    .enumerate()
1582    .map(|(index, value)| match value {
1583        UiValue::String(value) if !value.is_empty() => Ok(value),
1584        _ => Err(NativeCollectionError::InvalidTableConfig(format!(
1585            "search_fields[{index}] must be a non-empty string"
1586        ))),
1587    })
1588    .collect::<Result<Vec<_>, _>>()?;
1589    if !query.is_empty() && search_fields.is_empty() {
1590        return Err(NativeCollectionError::InvalidTableConfig(
1591            "non-empty query requires search_fields".to_owned(),
1592        ));
1593    }
1594    if let Some(field) = search_fields.iter().find(|field| {
1595        field.as_str() != row_key && !columns.iter().any(|column| column.key == field.as_str())
1596    }) {
1597        return Err(NativeCollectionError::InvalidTableConfig(format!(
1598            "search field `{field}` is not the row key or a declared column"
1599        )));
1600    }
1601    let page = if config.contains_key("page") {
1602        take_positive_usize(config, "page")?
1603    } else {
1604        1
1605    };
1606    let page_size = take_optional_positive_usize(config, "page_size")?;
1607    Ok((query, search_fields, page, page_size))
1608}
1609
1610fn decode_sort(value: Option<UiValue>) -> Result<Option<SortSpec>, NativeCollectionError> {
1611    let Some(value) = value else {
1612        return Ok(None);
1613    };
1614    let UiValue::Map(mut sort) = value else {
1615        if value == UiValue::Null {
1616            return Ok(None);
1617        }
1618        return Err(NativeCollectionError::InvalidTableConfig(
1619            "sort must be null or a map".to_owned(),
1620        ));
1621    };
1622    let key = take_string(&mut sort, "key")?;
1623    let direction = take_string(&mut sort, "direction")?;
1624    if !sort.is_empty() {
1625        return Err(NativeCollectionError::InvalidTableConfig(
1626            "sort contains unknown fields".to_owned(),
1627        ));
1628    }
1629    let descending = match direction.as_str() {
1630        "ascending" => false,
1631        "descending" => true,
1632        _ => {
1633            return Err(NativeCollectionError::InvalidTableConfig(format!(
1634                "unknown sort direction `{direction}`"
1635            )));
1636        }
1637    };
1638    Ok(Some(SortSpec { key, descending }))
1639}
1640
1641fn decode_grouping(
1642    config: &mut BTreeMap<String, UiValue>,
1643    columns: &[TableColumn],
1644) -> Result<(Option<String>, BTreeSet<String>, bool), NativeCollectionError> {
1645    let group_by = take_optional_string(config, "group_by")?;
1646    if let Some(group_by) = &group_by
1647        && !columns.iter().any(|column| &column.key == group_by)
1648    {
1649        return Err(NativeCollectionError::InvalidTableConfig(format!(
1650            "group_by `{group_by}` is not a declared column"
1651        )));
1652    }
1653    let collapsed = if config.contains_key("collapsed_groups") {
1654        take_string_set(config, "collapsed_groups")?
1655    } else {
1656        BTreeSet::new()
1657    };
1658    if group_by.is_none() && !collapsed.is_empty() {
1659        return Err(NativeCollectionError::InvalidTableConfig(
1660            "collapsed_groups requires group_by".to_owned(),
1661        ));
1662    }
1663    let toggle = if config.contains_key("group_toggle") {
1664        take_bool(config, "group_toggle")?
1665    } else {
1666        false
1667    };
1668    Ok((group_by, collapsed, toggle))
1669}
1670
1671fn unique_group_key(
1672    value: &str,
1673    source_keys: &BTreeSet<&str>,
1674    header_keys: &mut BTreeSet<String>,
1675) -> String {
1676    let mut key = format!("__gpui_rhai_group__:{value}");
1677    while source_keys.contains(key.as_str()) || !header_keys.insert(key.clone()) {
1678        key.insert(0, '_');
1679    }
1680    key
1681}
1682
1683impl TableColumn {
1684    fn decode(value: UiValue) -> Result<Self, NativeCollectionError> {
1685        let UiValue::Map(mut column) = value else {
1686            return Err(NativeCollectionError::InvalidTableConfig(
1687                "each column must be a map".to_owned(),
1688            ));
1689        };
1690        let key = take_string(&mut column, "key")?;
1691        let sort_key =
1692            take_optional_string(&mut column, "sort_key")?.unwrap_or_else(|| key.clone());
1693        validate_name(&sort_key, "sort field")?;
1694        let width = column.remove("width").ok_or_else(|| {
1695            NativeCollectionError::InvalidTableConfig("column.width is required".to_owned())
1696        })?;
1697        let align = match column.remove("align") {
1698            None | Some(UiValue::Null) => "start".to_owned(),
1699            Some(UiValue::String(value)) => value,
1700            Some(_) => {
1701                return Err(NativeCollectionError::InvalidTableConfig(
1702                    "column.align must be a string".to_owned(),
1703                ));
1704            }
1705        };
1706        let resize_signal_key = match column.remove("resize_signal_key") {
1707            Some(UiValue::String(value)) => Some(value),
1708            Some(_) => {
1709                return Err(NativeCollectionError::InvalidTableConfig(
1710                    "resize_signal_key must be a string".to_owned(),
1711                ));
1712            }
1713            None => None,
1714        };
1715        let adornments = match column.remove("adornments") {
1716            Some(UiValue::Array(values)) => values
1717                .into_iter()
1718                .map(TableAdornment::decode)
1719                .collect::<Result<Vec<_>, _>>()?,
1720            Some(_) => {
1721                return Err(NativeCollectionError::InvalidTableConfig(
1722                    "column.adornments must be an array".to_owned(),
1723                ));
1724            }
1725            None => Vec::new(),
1726        };
1727        for normalized_only in [
1728            "title",
1729            "numeric",
1730            "typography",
1731            "sortable",
1732            "resizable",
1733            "resize_enabled",
1734            "resize_ref_key",
1735            "min_width",
1736            "max_width",
1737        ] {
1738            column.remove(normalized_only);
1739        }
1740        if !column.is_empty() {
1741            return Err(NativeCollectionError::InvalidTableConfig(format!(
1742                "unknown column fields: {}",
1743                column.keys().cloned().collect::<Vec<_>>().join(", ")
1744            )));
1745        }
1746        Ok(Self {
1747            key,
1748            sort_key,
1749            width,
1750            align,
1751            resize_signal_key,
1752            adornments,
1753        })
1754    }
1755}
1756
1757impl TableAdornment {
1758    fn decode(value: UiValue) -> Result<Self, NativeCollectionError> {
1759        let UiValue::Map(mut value) = value else {
1760            return Err(NativeCollectionError::InvalidTableConfig(
1761                "each column adornment must be a map".to_owned(),
1762            ));
1763        };
1764        let text_key = take_string(&mut value, "text_key")?;
1765        let variant = match value.remove("variant") {
1766            Some(UiValue::String(value)) => value,
1767            Some(_) => {
1768                return Err(NativeCollectionError::InvalidTableConfig(
1769                    "adornment.variant must be a string".to_owned(),
1770                ));
1771            }
1772            None => "neutral".to_owned(),
1773        };
1774        validate_badge_variant(&variant)?;
1775        let variant_key = match value.remove("variant_key") {
1776            Some(UiValue::String(value)) => Some(value),
1777            Some(UiValue::Null) | None => None,
1778            Some(_) => {
1779                return Err(NativeCollectionError::InvalidTableConfig(
1780                    "adornment.variant_key must be a string".to_owned(),
1781                ));
1782            }
1783        };
1784        let dot = match value.remove("dot") {
1785            Some(UiValue::Bool(value)) => value,
1786            Some(_) => {
1787                return Err(NativeCollectionError::InvalidTableConfig(
1788                    "adornment.dot must be a bool".to_owned(),
1789                ));
1790            }
1791            None => false,
1792        };
1793        if !value.is_empty() {
1794            return Err(NativeCollectionError::InvalidTableConfig(format!(
1795                "unknown adornment fields: {}",
1796                value.keys().cloned().collect::<Vec<_>>().join(", ")
1797            )));
1798        }
1799        Ok(Self {
1800            text_key,
1801            variant,
1802            variant_key,
1803            dot,
1804        })
1805    }
1806
1807    fn project(
1808        &self,
1809        row: &BTreeMap<String, UiValue>,
1810    ) -> Result<Option<UiValue>, NativeCollectionError> {
1811        let text = row
1812            .get(&self.text_key)
1813            .map_or_else(String::new, display_scalar);
1814        if text.is_empty() {
1815            return Ok(None);
1816        }
1817        let variant = self.variant_key.as_ref().map_or_else(
1818            || Ok(self.variant.clone()),
1819            |key| match row.get(key) {
1820                Some(UiValue::String(value)) => Ok(value.clone()),
1821                _ => Err(NativeCollectionError::InvalidTableConfig(format!(
1822                    "adornment variant field `{key}` must be a string"
1823                ))),
1824            },
1825        )?;
1826        validate_badge_variant(&variant)?;
1827        Ok(Some(UiValue::Map(BTreeMap::from([
1828            ("text".to_owned(), UiValue::String(text)),
1829            ("variant".to_owned(), UiValue::String(variant)),
1830            ("dot".to_owned(), UiValue::Bool(self.dot)),
1831        ]))))
1832    }
1833}
1834
1835fn validate_badge_variant(value: &str) -> Result<(), NativeCollectionError> {
1836    if matches!(
1837        value,
1838        "neutral" | "accent" | "success" | "warning" | "danger"
1839    ) {
1840        Ok(())
1841    } else {
1842        Err(NativeCollectionError::InvalidTableConfig(format!(
1843            "unknown adornment variant `{value}`"
1844        )))
1845    }
1846}
1847
1848fn row_field<'a>(row: &'a UiValue, key: &str) -> Option<&'a UiValue> {
1849    match row {
1850        UiValue::Map(row) => row.get(key),
1851        _ => None,
1852    }
1853}
1854
1855fn compare_values(left: &UiValue, right: &UiValue) -> Option<Ordering> {
1856    match (left, right) {
1857        (UiValue::Null, UiValue::Null) => Some(Ordering::Equal),
1858        (UiValue::Bool(left), UiValue::Bool(right)) => Some(left.cmp(right)),
1859        (UiValue::Integer(left), UiValue::Integer(right)) => Some(left.cmp(right)),
1860        (UiValue::Float(left), UiValue::Float(right)) if left.is_finite() && right.is_finite() => {
1861            left.partial_cmp(right)
1862        }
1863        (UiValue::Integer(left), UiValue::Float(right)) => compare_integer_float(*left, *right),
1864        (UiValue::Float(left), UiValue::Integer(right)) => {
1865            compare_integer_float(*right, *left).map(Ordering::reverse)
1866        }
1867        (UiValue::String(left), UiValue::String(right)) => Some(left.cmp(right)),
1868        _ => None,
1869    }
1870}
1871
1872#[allow(clippy::cast_possible_truncation)]
1873fn compare_integer_float(integer: i64, float: f64) -> Option<Ordering> {
1874    const I64_END: f64 = 9_223_372_036_854_775_808.0;
1875    if !float.is_finite() {
1876        return None;
1877    }
1878    // The upper endpoint is exclusive: i64::MAX rounds up to 2^63 as f64.
1879    // Converting the integer instead would collapse distinct ranks above 2^53
1880    // and make the stable source-order tie break violate transitivity.
1881    if float >= I64_END {
1882        return Some(Ordering::Less);
1883    }
1884    if float < -I64_END {
1885        return Some(Ordering::Greater);
1886    }
1887    // The range checks make the truncated integral part representable as i64.
1888    let truncated = float as i64;
1889    Some(integer.cmp(&truncated).then_with(|| {
1890        if float.fract() > 0.0 {
1891            Ordering::Less
1892        } else if float.fract() < 0.0 {
1893            Ordering::Greater
1894        } else {
1895            Ordering::Equal
1896        }
1897    }))
1898}
1899
1900fn scalar_text(value: &UiValue) -> Option<String> {
1901    match value {
1902        UiValue::Bool(value) => Some(value.to_string()),
1903        UiValue::Integer(value) => Some(value.to_string()),
1904        UiValue::Float(value) if value.is_finite() => Some(value.to_string()),
1905        UiValue::String(value) => Some(value.clone()),
1906        UiValue::Null
1907        | UiValue::Float(_)
1908        | UiValue::Array(_)
1909        | UiValue::Map(_)
1910        | UiValue::Handle(_) => None,
1911    }
1912}
1913
1914fn display_scalar(value: &UiValue) -> String {
1915    scalar_text(value).unwrap_or_default()
1916}
1917
1918fn take_string(
1919    values: &mut BTreeMap<String, UiValue>,
1920    name: &str,
1921) -> Result<String, NativeCollectionError> {
1922    match values.remove(name) {
1923        Some(UiValue::String(value)) => Ok(value),
1924        _ => Err(NativeCollectionError::InvalidTableConfig(format!(
1925            "{name} must be a string"
1926        ))),
1927    }
1928}
1929
1930fn take_optional_string(
1931    values: &mut BTreeMap<String, UiValue>,
1932    name: &str,
1933) -> Result<Option<String>, NativeCollectionError> {
1934    match values.remove(name) {
1935        None | Some(UiValue::Null) => Ok(None),
1936        Some(UiValue::String(value)) if !value.is_empty() => Ok(Some(value)),
1937        _ => Err(NativeCollectionError::InvalidTableConfig(format!(
1938            "{name} must be null or a non-empty string"
1939        ))),
1940    }
1941}
1942
1943fn take_string_set(
1944    values: &mut BTreeMap<String, UiValue>,
1945    name: &str,
1946) -> Result<BTreeSet<String>, NativeCollectionError> {
1947    take_array(values, name)?
1948        .into_iter()
1949        .enumerate()
1950        .map(|(index, value)| match value {
1951            UiValue::String(value) if !value.is_empty() => Ok(value),
1952            _ => Err(NativeCollectionError::InvalidTableConfig(format!(
1953                "{name}[{index}] must be a non-empty string"
1954            ))),
1955        })
1956        .collect()
1957}
1958
1959fn take_array(
1960    values: &mut BTreeMap<String, UiValue>,
1961    name: &str,
1962) -> Result<Vec<UiValue>, NativeCollectionError> {
1963    match values.remove(name) {
1964        Some(UiValue::Array(value)) => Ok(value),
1965        _ => Err(NativeCollectionError::InvalidTableConfig(format!(
1966            "{name} must be an array"
1967        ))),
1968    }
1969}
1970
1971fn take_bool(
1972    values: &mut BTreeMap<String, UiValue>,
1973    name: &str,
1974) -> Result<bool, NativeCollectionError> {
1975    match values.remove(name) {
1976        Some(UiValue::Bool(value)) => Ok(value),
1977        _ => Err(NativeCollectionError::InvalidTableConfig(format!(
1978            "{name} must be a bool"
1979        ))),
1980    }
1981}
1982
1983fn take_positive_usize(
1984    values: &mut BTreeMap<String, UiValue>,
1985    name: &str,
1986) -> Result<usize, NativeCollectionError> {
1987    match values.remove(name) {
1988        Some(UiValue::Integer(value)) if value > 0 => usize::try_from(value).map_err(|_| {
1989            NativeCollectionError::InvalidTableConfig(format!(
1990                "{name} exceeds the supported platform size"
1991            ))
1992        }),
1993        _ => Err(NativeCollectionError::InvalidTableConfig(format!(
1994            "{name} must be a positive integer"
1995        ))),
1996    }
1997}
1998
1999fn take_optional_positive_usize(
2000    values: &mut BTreeMap<String, UiValue>,
2001    name: &str,
2002) -> Result<Option<usize>, NativeCollectionError> {
2003    match values.remove(name) {
2004        None | Some(UiValue::Null) => Ok(None),
2005        Some(UiValue::Integer(value)) if value > 0 => {
2006            usize::try_from(value).map(Some).map_err(|_| {
2007                NativeCollectionError::InvalidTableConfig(format!(
2008                    "{name} exceeds the supported platform size"
2009                ))
2010            })
2011        }
2012        _ => Err(NativeCollectionError::InvalidTableConfig(format!(
2013            "{name} must be null or a positive integer"
2014        ))),
2015    }
2016}
2017
2018fn take_number(
2019    values: &mut BTreeMap<String, UiValue>,
2020    name: &str,
2021) -> Result<f64, NativeCollectionError> {
2022    match values.remove(name) {
2023        Some(UiValue::Float(value)) => Ok(value),
2024        Some(UiValue::Integer(value)) => Ok(integer_float(value)),
2025        _ => Err(NativeCollectionError::InvalidTableConfig(format!(
2026            "{name} must be a number"
2027        ))),
2028    }
2029}
2030
2031fn integer_float(value: i64) -> f64 {
2032    value.to_string().parse().unwrap_or_else(|_| {
2033        if value.is_negative() {
2034            f64::MIN
2035        } else {
2036            f64::MAX
2037        }
2038    })
2039}
2040
2041fn validate_name(name: &str, label: &'static str) -> Result<(), NativeCollectionError> {
2042    if name.is_empty() || name.len() > 256 || name.chars().any(char::is_control) {
2043        Err(NativeCollectionError::InvalidName(label, name.to_owned()))
2044    } else {
2045        Ok(())
2046    }
2047}
2048
2049#[cfg(test)]
2050use crate::read_dependency::MAX_MISSING_NAMES_PER_READER;
2051
2052#[derive(Clone, Debug, Default)]
2053pub struct NativeCollectionRegistry {
2054    collections: BTreeMap<String, NativeCollection>,
2055    readers: BTreeMap<String, BTreeSet<crate::read_dependency::ReadDependency>>,
2056    missing_readers: BTreeMap<String, BTreeSet<crate::read_dependency::ReadDependency>>,
2057}
2058
2059impl NativeCollectionRegistry {
2060    #[must_use]
2061    pub fn new() -> Self {
2062        Self::default()
2063    }
2064
2065    /// Register one application-owned collection before initial render.
2066    ///
2067    /// # Errors
2068    ///
2069    /// Returns an error for an unsafe or duplicate name.
2070    pub fn register(
2071        &mut self,
2072        name: impl Into<String>,
2073        collection: NativeCollection,
2074    ) -> Result<(), NativeCollectionError> {
2075        self.register_with_invalidated(name.into(), collection)?;
2076        Ok(())
2077    }
2078
2079    pub(crate) fn register_with_invalidated(
2080        &mut self,
2081        name: String,
2082        collection: NativeCollection,
2083    ) -> Result<BTreeSet<ComponentInstancePath>, NativeCollectionError> {
2084        validate_name(&name, "collection name")?;
2085        if self.collections.contains_key(&name) {
2086            return Err(NativeCollectionError::DuplicateCollection(name));
2087        }
2088        self.collections.insert(name.clone(), collection);
2089        Ok(crate::read_dependency::owners(
2090            self.missing_readers.remove(&name).unwrap_or_default(),
2091        ))
2092    }
2093
2094    /// Replace an existing collection and return its exact subscribed readers.
2095    ///
2096    /// # Errors
2097    ///
2098    /// Returns an error when the collection is unknown.
2099    pub fn replace(
2100        &mut self,
2101        name: &str,
2102        collection: NativeCollection,
2103    ) -> Result<BTreeSet<ComponentInstancePath>, NativeCollectionError> {
2104        let current = self
2105            .collections
2106            .get_mut(name)
2107            .ok_or_else(|| NativeCollectionError::UnknownCollection(name.to_owned()))?;
2108        if current == &collection {
2109            return Ok(BTreeSet::new());
2110        }
2111        *current = collection;
2112        Ok(crate::read_dependency::owners(
2113            self.readers.get(name).cloned().unwrap_or_default(),
2114        ))
2115    }
2116
2117    #[cfg(test)]
2118    pub(crate) fn read_tracked(
2119        &mut self,
2120        reader: &ComponentInstancePath,
2121        name: &str,
2122    ) -> Result<NativeCollection, NativeCollectionError> {
2123        self.read_tracked_with_missing(reader, name, true)
2124    }
2125
2126    #[cfg(test)]
2127    pub(crate) fn read_tracked_with_missing(
2128        &mut self,
2129        reader: &ComponentInstancePath,
2130        name: &str,
2131        track_missing: bool,
2132    ) -> Result<NativeCollection, NativeCollectionError> {
2133        self.read_dependency(
2134            Some(&crate::read_dependency::ReadDependency::component(reader)),
2135            name,
2136            track_missing,
2137        )
2138    }
2139
2140    /// Read a collection, subscribing `reader` when there is one.
2141    pub(crate) fn read_dependency(
2142        &mut self,
2143        reader: Option<&crate::read_dependency::ReadDependency>,
2144        name: &str,
2145        track_missing: bool,
2146    ) -> Result<NativeCollection, NativeCollectionError> {
2147        validate_name(name, "collection name")?;
2148        let Some(collection) = self.collections.get(name).cloned() else {
2149            if track_missing && let Some(reader) = reader {
2150                self.track_missing_reader(reader, name)?;
2151            }
2152            return Err(NativeCollectionError::UnknownCollection(name.to_owned()));
2153        };
2154        let Some(reader) = reader else {
2155            return Ok(collection);
2156        };
2157        if let Some(readers) = self.missing_readers.get_mut(name) {
2158            readers.remove(reader);
2159            if readers.is_empty() {
2160                self.missing_readers.remove(name);
2161            }
2162        }
2163        self.readers
2164            .entry(name.to_owned())
2165            .or_default()
2166            .insert(reader.clone());
2167        Ok(collection)
2168    }
2169
2170    fn track_missing_reader(
2171        &mut self,
2172        reader: &crate::read_dependency::ReadDependency,
2173        name: &str,
2174    ) -> Result<(), NativeCollectionError> {
2175        crate::read_dependency::track_missing_reader(&mut self.missing_readers, reader, name)
2176            .map_err(|budget| NativeCollectionError::MissingDependencyBudget {
2177                kind: budget.kind,
2178                limit: budget.limit,
2179            })
2180    }
2181
2182    pub(crate) fn reset_reader(&mut self, reader: &ComponentInstancePath) {
2183        self.reset_contribution(&crate::read_dependency::ReadDependency::component(reader));
2184    }
2185
2186    pub(crate) fn reset_contribution(&mut self, reader: &crate::read_dependency::ReadDependency) {
2187        for readers in self.readers.values_mut() {
2188            readers.remove(reader);
2189        }
2190        self.readers.retain(|_, readers| !readers.is_empty());
2191        for readers in self.missing_readers.values_mut() {
2192            readers.remove(reader);
2193        }
2194        self.missing_readers
2195            .retain(|_, readers| !readers.is_empty());
2196    }
2197
2198    pub(crate) fn retain_reader_scope(
2199        &mut self,
2200        root: &ComponentInstancePath,
2201        active: &BTreeSet<ComponentInstancePath>,
2202    ) {
2203        for readers in self.readers.values_mut() {
2204            readers.retain(|reader| reader.retained_in_owner_scope(root, active));
2205        }
2206        self.readers.retain(|_, readers| !readers.is_empty());
2207        for readers in self.missing_readers.values_mut() {
2208            readers.retain(|reader| reader.retained_in_owner_scope(root, active));
2209        }
2210        self.missing_readers
2211            .retain(|_, readers| !readers.is_empty());
2212    }
2213
2214    pub(crate) fn remove_reader_scope(&mut self, root: &ComponentInstancePath) {
2215        for readers in self.readers.values_mut() {
2216            readers.retain(|reader| !reader.owner.is_within(root));
2217        }
2218        self.readers.retain(|_, readers| !readers.is_empty());
2219        for readers in self.missing_readers.values_mut() {
2220            readers.retain(|reader| !reader.owner.is_within(root));
2221        }
2222        self.missing_readers
2223            .retain(|_, readers| !readers.is_empty());
2224    }
2225
2226    pub(crate) fn retain_contributions(
2227        &mut self,
2228        scope: &ComponentInstancePath,
2229        active: &BTreeSet<crate::read_dependency::ReadContribution>,
2230    ) {
2231        crate::read_dependency::retain_readers(&mut self.readers, |reader| {
2232            reader.retained_in_contribution_scope(scope, active)
2233        });
2234        crate::read_dependency::retain_readers(&mut self.missing_readers, |reader| {
2235            reader.retained_in_contribution_scope(scope, active)
2236        });
2237    }
2238}
2239
2240#[derive(Clone, Debug, PartialEq)]
2241pub enum VirtualCollectionData {
2242    Values(Vec<UiValue>),
2243    Native(NativeCollection),
2244}
2245
2246impl From<Vec<UiValue>> for VirtualCollectionData {
2247    fn from(values: Vec<UiValue>) -> Self {
2248        Self::Values(values)
2249    }
2250}
2251
2252impl From<NativeCollection> for VirtualCollectionData {
2253    fn from(collection: NativeCollection) -> Self {
2254        Self::Native(collection)
2255    }
2256}
2257
2258impl FromIterator<UiValue> for VirtualCollectionData {
2259    fn from_iter<T: IntoIterator<Item = UiValue>>(iter: T) -> Self {
2260        Self::Values(iter.into_iter().collect())
2261    }
2262}
2263
2264impl VirtualCollectionData {
2265    #[must_use]
2266    pub fn len(&self) -> usize {
2267        match self {
2268            Self::Values(values) => values.len(),
2269            Self::Native(collection) => collection.len(),
2270        }
2271    }
2272
2273    #[must_use]
2274    pub fn is_empty(&self) -> bool {
2275        self.len() == 0
2276    }
2277
2278    pub(crate) fn sticky_headers(&self) -> Arc<BTreeSet<usize>> {
2279        match self {
2280            Self::Values(_) => Arc::new(BTreeSet::new()),
2281            Self::Native(collection) => collection.sticky_headers(),
2282        }
2283    }
2284
2285    /// Read one projected row without converting the full native source.
2286    ///
2287    /// # Errors
2288    /// Returns a native projection error for an invalid source/view configuration.
2289    pub fn item(&self, index: usize) -> Result<Option<UiValue>, NativeCollectionError> {
2290        match self {
2291            Self::Values(values) => Ok(values.get(index).cloned()),
2292            Self::Native(collection) => collection.item(index),
2293        }
2294    }
2295
2296    /// Stable key at an ordered collection index, without materializing its row.
2297    #[must_use]
2298    pub fn key(&self, index: usize) -> Option<&str> {
2299        match self {
2300            Self::Values(values) => values.get(index).and_then(|item| match item {
2301                UiValue::Map(item) => match item.get("key") {
2302                    Some(UiValue::String(key)) => Some(key.as_str()),
2303                    _ => None,
2304                },
2305                _ => None,
2306            }),
2307            Self::Native(collection) => collection.key(index),
2308        }
2309    }
2310}
2311
2312#[derive(Clone, Debug, Error, PartialEq)]
2313pub enum NativeCollectionError {
2314    #[error("invalid {0} `{1}`")]
2315    InvalidName(&'static str, String),
2316    #[error("native collection row {0} must be a map")]
2317    RowNotMap(usize),
2318    #[error("native collection row {index} is missing key field `{field}`")]
2319    MissingKey { index: usize, field: String },
2320    #[error("native collection row {index} key field `{field}` must be a non-empty scalar")]
2321    InvalidKey { index: usize, field: String },
2322    #[error("native collection key `{0}` is duplicated")]
2323    DuplicateKey(String),
2324    #[error("native collection `{0}` is already registered")]
2325    DuplicateCollection(String),
2326    #[error("native collection `{0}` is not registered")]
2327    UnknownCollection(String),
2328    #[error("native collection missing-dependency {kind} exceeds limit {limit}")]
2329    MissingDependencyBudget { kind: &'static str, limit: usize },
2330    #[error(
2331        "native collection key field `{source_key}` does not match requested row key `{requested}`"
2332    )]
2333    KeyFieldMismatch {
2334        source_key: String,
2335        requested: String,
2336    },
2337    #[error("native collection sort field `{0}` is missing")]
2338    MissingSortField(String),
2339    #[error("native collection sort field `{0}` is not a consistently comparable scalar")]
2340    UnsortableField(String),
2341    #[error("native collection order references missing source row {0}")]
2342    CorruptOrder(usize),
2343    #[error("native collection contains a group header outside a table projection")]
2344    UnexpectedGroupEntry,
2345    #[error("native collection is not a fuzzy projection")]
2346    NotFuzzyProjection,
2347    #[error("native collection row {index} group field `{field}` must be a non-empty string")]
2348    InvalidGroupField { index: usize, field: String },
2349    #[error("invalid native Table configuration: {0}")]
2350    InvalidTableConfig(String),
2351    #[error("invalid native fuzzy-view configuration: {0}")]
2352    InvalidFuzzyConfig(String),
2353    #[error("native collection cache is poisoned")]
2354    Poisoned,
2355}
2356
2357#[cfg(test)]
2358mod tests {
2359    use super::*;
2360
2361    fn rows() -> NativeCollection {
2362        NativeCollection::new(
2363            "id",
2364            [
2365                BTreeMap::from([
2366                    ("id".to_owned(), UiValue::String("b".to_owned())),
2367                    ("score".to_owned(), UiValue::Integer(2)),
2368                ]),
2369                BTreeMap::from([
2370                    ("id".to_owned(), UiValue::String("a".to_owned())),
2371                    ("score".to_owned(), UiValue::Integer(1)),
2372                ]),
2373            ],
2374        )
2375        .unwrap()
2376    }
2377
2378    fn grouped_rows() -> NativeCollection {
2379        NativeCollection::new(
2380            "id",
2381            [
2382                BTreeMap::from([
2383                    ("id".to_owned(), UiValue::String("b".to_owned())),
2384                    ("track".to_owned(), UiValue::String("track-b".to_owned())),
2385                    ("score".to_owned(), UiValue::Integer(2)),
2386                ]),
2387                BTreeMap::from([
2388                    ("id".to_owned(), UiValue::String("a".to_owned())),
2389                    ("track".to_owned(), UiValue::String("track-a".to_owned())),
2390                    ("score".to_owned(), UiValue::Integer(3)),
2391                ]),
2392                BTreeMap::from([
2393                    ("id".to_owned(), UiValue::String("c".to_owned())),
2394                    ("track".to_owned(), UiValue::String("track-b".to_owned())),
2395                    ("score".to_owned(), UiValue::Integer(1)),
2396                ]),
2397            ],
2398        )
2399        .unwrap()
2400    }
2401
2402    fn table_config(collapsed: &[&str]) -> Map {
2403        let columns = ["id", "track", "score"]
2404            .into_iter()
2405            .map(|key| {
2406                UiValue::Map(BTreeMap::from([
2407                    ("key".to_owned(), UiValue::String(key.to_owned())),
2408                    ("width".to_owned(), UiValue::Integer(80)),
2409                ]))
2410            })
2411            .collect();
2412        UiValue::Map(BTreeMap::from([
2413            ("row_key".to_owned(), UiValue::String("id".to_owned())),
2414            ("label".to_owned(), UiValue::String("Clusters".to_owned())),
2415            ("columns".to_owned(), UiValue::Array(columns)),
2416            ("selected_keys".to_owned(), UiValue::Array(Vec::new())),
2417            (
2418                "selection_mode".to_owned(),
2419                UiValue::String("multiple".to_owned()),
2420            ),
2421            ("striped".to_owned(), UiValue::Bool(true)),
2422            ("row_height".to_owned(), UiValue::Float(30.0)),
2423            (
2424                "sort".to_owned(),
2425                UiValue::Map(BTreeMap::from([
2426                    ("key".to_owned(), UiValue::String("score".to_owned())),
2427                    (
2428                        "direction".to_owned(),
2429                        UiValue::String("ascending".to_owned()),
2430                    ),
2431                ])),
2432            ),
2433            ("group_by".to_owned(), UiValue::String("track".to_owned())),
2434            (
2435                "collapsed_groups".to_owned(),
2436                UiValue::Array(
2437                    collapsed
2438                        .iter()
2439                        .map(|value| UiValue::String((*value).to_owned()))
2440                        .collect(),
2441                ),
2442            ),
2443            ("group_toggle".to_owned(), UiValue::Bool(true)),
2444        ]))
2445        .into_dynamic()
2446        .cast::<Map>()
2447    }
2448
2449    fn fuzzy_rows() -> NativeCollection {
2450        NativeCollection::new(
2451            "id",
2452            [
2453                BTreeMap::from([
2454                    ("id".to_owned(), UiValue::String("new".to_owned())),
2455                    ("label".to_owned(), UiValue::String("New file".to_owned())),
2456                    ("group".to_owned(), UiValue::String("File".to_owned())),
2457                    (
2458                        "keywords".to_owned(),
2459                        UiValue::Array(vec![UiValue::String("create document".to_owned())]),
2460                    ),
2461                    ("shortcut".to_owned(), UiValue::String("⌘N".to_owned())),
2462                    ("disabled".to_owned(), UiValue::Bool(false)),
2463                ]),
2464                BTreeMap::from([
2465                    ("id".to_owned(), UiValue::String("open".to_owned())),
2466                    ("label".to_owned(), UiValue::String("Open file".to_owned())),
2467                    ("group".to_owned(), UiValue::String("File".to_owned())),
2468                    (
2469                        "keywords".to_owned(),
2470                        UiValue::Array(vec![UiValue::String("load document".to_owned())]),
2471                    ),
2472                    ("shortcut".to_owned(), UiValue::String("⌘O".to_owned())),
2473                    ("disabled".to_owned(), UiValue::Bool(false)),
2474                ]),
2475                BTreeMap::from([
2476                    ("id".to_owned(), UiValue::String("close".to_owned())),
2477                    (
2478                        "label".to_owned(),
2479                        UiValue::String("Close window".to_owned()),
2480                    ),
2481                    ("group".to_owned(), UiValue::String("Window".to_owned())),
2482                    ("keywords".to_owned(), UiValue::Array(Vec::new())),
2483                    ("shortcut".to_owned(), UiValue::String("⌘W".to_owned())),
2484                    ("disabled".to_owned(), UiValue::Bool(true)),
2485                ]),
2486            ],
2487        )
2488        .unwrap()
2489    }
2490
2491    fn fuzzy_config(query: &str, active: &str) -> Map {
2492        UiValue::Map(BTreeMap::from([
2493            ("query".to_owned(), UiValue::String(query.to_owned())),
2494            (
2495                "label_field".to_owned(),
2496                UiValue::String("label".to_owned()),
2497            ),
2498            (
2499                "keywords_field".to_owned(),
2500                UiValue::String("keywords".to_owned()),
2501            ),
2502            (
2503                "group_field".to_owned(),
2504                UiValue::String("group".to_owned()),
2505            ),
2506            (
2507                "shortcut_field".to_owned(),
2508                UiValue::String("shortcut".to_owned()),
2509            ),
2510            (
2511                "disabled_field".to_owned(),
2512                UiValue::String("disabled".to_owned()),
2513            ),
2514            ("active".to_owned(), UiValue::String(active.to_owned())),
2515            ("row_height".to_owned(), UiValue::Float(32.0)),
2516        ]))
2517        .into_dynamic()
2518        .cast::<Map>()
2519    }
2520
2521    #[test]
2522    fn fuzzy_projection_filters_groups_projects_and_reuses_structural_order() {
2523        let source = fuzzy_rows();
2524        let view = source.fuzzy_view(fuzzy_config("opn", "")).unwrap();
2525        assert_eq!(view.len(), 2);
2526        assert_eq!(view.fuzzy_edge(false).unwrap(), "open");
2527        assert_eq!(view.fuzzy_adjacent("", 0).unwrap(), "open");
2528        let UiValue::Map(group) = view.item(0).unwrap().unwrap() else {
2529            panic!("first fuzzy entry must be a group");
2530        };
2531        assert_eq!(group["kind"], UiValue::String("group".to_owned()));
2532        let UiValue::Map(item) = view.item(1).unwrap().unwrap() else {
2533            panic!("second fuzzy entry must be a command");
2534        };
2535        assert_eq!(item["value"], UiValue::String("open".to_owned()));
2536        assert_eq!(item["active"], UiValue::Bool(false));
2537
2538        let active = source.fuzzy_view(fuzzy_config("opn", "open")).unwrap();
2539        assert!(Arc::ptr_eq(&view.order, &active.order));
2540        let UiValue::Map(item) = active.item(1).unwrap().unwrap() else {
2541            unreachable!()
2542        };
2543        assert_eq!(item["active"], UiValue::Bool(true));
2544
2545        let all = source.fuzzy_view(fuzzy_config("", "new")).unwrap();
2546        assert_eq!(all.fuzzy_edge(true).unwrap(), "open");
2547        assert_eq!(all.fuzzy_adjacent("new", 1).unwrap(), "open");
2548        assert_eq!(all.fuzzy_adjacent("open", 1).unwrap(), "new");
2549    }
2550
2551    #[test]
2552    fn validates_keys_and_caches_rust_sort_order() {
2553        fn assert_send_sync<T: Send + Sync>() {}
2554        assert_send_sync::<NativeCollection>();
2555        let collection = rows();
2556        let sort = SortSpec {
2557            key: "score".to_owned(),
2558            descending: false,
2559        };
2560        let first = collection.sorted_order(&sort).unwrap();
2561        let second = collection.sorted_order(&sort).unwrap();
2562        assert!(Arc::ptr_eq(&first, &second));
2563        assert_eq!(collection.source.keys[first[0]], "a");
2564    }
2565
2566    fn ranked_config(direction: &str) -> Map {
2567        let mut config = table_config(&[]);
2568        config.insert("group_by".into(), Dynamic::UNIT);
2569        config.insert(
2570            "columns".into(),
2571            Dynamic::from_array(vec![Dynamic::from_map(Map::from([
2572                ("key".into(), Dynamic::from("score")),
2573                ("sort_key".into(), Dynamic::from("rank")),
2574                ("width".into(), Dynamic::from(80_i64)),
2575            ]))]),
2576        );
2577        config.insert(
2578            "sort".into(),
2579            Dynamic::from_map(Map::from([
2580                ("key".into(), Dynamic::from("score")),
2581                ("direction".into(), Dynamic::from(direction.to_owned())),
2582            ])),
2583        );
2584        config
2585    }
2586
2587    #[test]
2588    fn mixed_numeric_comparison_is_exact_at_integer_and_float_boundaries() {
2589        const TWO_TO_53: i64 = 9_007_199_254_740_992;
2590        let float_53 = 9_007_199_254_740_992.0_f64;
2591        let float_63 = 9_223_372_036_854_775_808.0_f64;
2592        let tiny = f64::from_bits(1);
2593        for (integer, float, expected) in [
2594            (TWO_TO_53 - 1, float_53, Ordering::Less),
2595            (TWO_TO_53, float_53, Ordering::Equal),
2596            (TWO_TO_53 + 1, float_53, Ordering::Greater),
2597            (TWO_TO_53 + 1, float_53.next_up(), Ordering::Less),
2598            (-TWO_TO_53 - 1, -float_53, Ordering::Less),
2599            (-TWO_TO_53, -float_53, Ordering::Equal),
2600            (-TWO_TO_53 + 1, -float_53, Ordering::Greater),
2601            (i64::MAX, float_63, Ordering::Less),
2602            (i64::MAX, float_63.next_down(), Ordering::Greater),
2603            (i64::MAX, float_63.next_up(), Ordering::Less),
2604            (i64::MIN, -float_63, Ordering::Equal),
2605            (i64::MIN + 1, -float_63, Ordering::Greater),
2606            (i64::MIN, (-float_63).next_up(), Ordering::Less),
2607            (i64::MIN, (-float_63).next_down(), Ordering::Greater),
2608            (i64::MAX, f64::MAX, Ordering::Less),
2609            (i64::MIN, -f64::MAX, Ordering::Greater),
2610            (1, 1.5, Ordering::Less),
2611            (2, 1.5, Ordering::Greater),
2612            (-1, -1.5, Ordering::Greater),
2613            (-2, -1.5, Ordering::Less),
2614            (0, 0.5, Ordering::Less),
2615            (0, -0.5, Ordering::Greater),
2616            (0, tiny, Ordering::Less),
2617            (0, -tiny, Ordering::Greater),
2618            (0, 0.0, Ordering::Equal),
2619            (0, -0.0, Ordering::Equal),
2620        ] {
2621            let integer = UiValue::Integer(integer);
2622            let float = UiValue::Float(float);
2623            assert_eq!(
2624                compare_values(&integer, &float),
2625                Some(expected),
2626                "{integer:?} versus {float:?}"
2627            );
2628            assert_eq!(compare_values(&float, &integer), Some(expected.reverse()));
2629        }
2630        for float in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
2631            assert_eq!(
2632                compare_values(&UiValue::Integer(0), &UiValue::Float(float)),
2633                None
2634            );
2635            assert_eq!(
2636                compare_values(&UiValue::Float(float), &UiValue::Integer(0)),
2637                None
2638            );
2639        }
2640    }
2641
2642    #[test]
2643    fn mixed_numeric_comparison_is_a_total_order_with_stable_ties() {
2644        let values = [
2645            UiValue::Integer(9_007_199_254_740_993),
2646            UiValue::Float(9_007_199_254_740_992.0),
2647            UiValue::Integer(9_007_199_254_740_992),
2648            UiValue::Integer(9_007_199_254_740_991),
2649            UiValue::Float(9_007_199_254_740_994.0),
2650            UiValue::Integer(-9_007_199_254_740_993),
2651            UiValue::Float(-9_007_199_254_740_992.0),
2652            UiValue::Integer(-9_007_199_254_740_992),
2653            UiValue::Integer(i64::MIN),
2654            UiValue::Integer(i64::MIN + 1),
2655            UiValue::Float(-9_223_372_036_854_775_808.0),
2656            UiValue::Integer(i64::MAX),
2657            UiValue::Float(9_223_372_036_854_775_808.0),
2658            UiValue::Float(f64::MAX),
2659            UiValue::Float(-f64::MAX),
2660            UiValue::Integer(-2),
2661            UiValue::Float(-1.5),
2662            UiValue::Integer(-1),
2663            UiValue::Float(-f64::from_bits(1)),
2664            UiValue::Integer(0),
2665            UiValue::Float(-0.0),
2666            UiValue::Float(0.0),
2667            UiValue::Float(f64::from_bits(1)),
2668            UiValue::Float(0.5),
2669            UiValue::Integer(1),
2670            UiValue::Float(1.5),
2671            UiValue::Integer(2),
2672        ];
2673        // Include the source-position tie break used by sorted_order: rounding
2674        // 2^53 + 1 down to 2^53 previously produced a cycle in the first triple.
2675        for (left_index, left) in values.iter().enumerate() {
2676            assert_eq!(compare_values(left, left), Some(Ordering::Equal));
2677            for (right_index, right) in values.iter().enumerate() {
2678                let forward = compare_values(left, right).unwrap();
2679                assert_eq!(compare_values(right, left), Some(forward.reverse()));
2680                for (last_index, last) in values.iter().enumerate() {
2681                    let middle = compare_values(right, last).unwrap();
2682                    let end = compare_values(left, last).unwrap();
2683                    assert!(
2684                        forward == Ordering::Greater
2685                            || middle == Ordering::Greater
2686                            || end != Ordering::Greater,
2687                        "non-transitive numeric order: {left:?}, {right:?}, {last:?}"
2688                    );
2689                    let forward = forward.then_with(|| left_index.cmp(&right_index));
2690                    let middle = middle.then_with(|| right_index.cmp(&last_index));
2691                    let end = end.then_with(|| left_index.cmp(&last_index));
2692                    assert!(
2693                        forward == Ordering::Greater
2694                            || middle == Ordering::Greater
2695                            || end != Ordering::Greater,
2696                        "non-transitive stable order: {left:?}, {right:?}, {last:?}"
2697                    );
2698                }
2699            }
2700        }
2701    }
2702
2703    fn mixed_numeric_source() -> NativeCollection {
2704        let float_63 = 9_223_372_036_854_775_808.0_f64;
2705        let ranks = [
2706            ("large-int", Some(UiValue::Integer(9_007_199_254_740_993))),
2707            ("large-float", Some(UiValue::Float(9_007_199_254_740_992.0))),
2708            ("same-int", Some(UiValue::Integer(9_007_199_254_740_992))),
2709            ("max-int", Some(UiValue::Integer(i64::MAX))),
2710            ("upper-float", Some(UiValue::Float(float_63))),
2711            ("min-int", Some(UiValue::Integer(i64::MIN))),
2712            ("lower-float", Some(UiValue::Float(-float_63))),
2713            ("below-min", Some(UiValue::Float((-float_63).next_down()))),
2714            ("negative-frac", Some(UiValue::Float(-1.5))),
2715            ("negative-int", Some(UiValue::Integer(-1))),
2716            ("negative-tiny", Some(UiValue::Float(-f64::from_bits(1)))),
2717            ("zero-int", Some(UiValue::Integer(0))),
2718            ("zero-negative", Some(UiValue::Float(-0.0))),
2719            ("zero-positive", Some(UiValue::Float(0.0))),
2720            ("positive-tiny", Some(UiValue::Float(f64::from_bits(1)))),
2721            ("positive-frac", Some(UiValue::Float(0.5))),
2722            ("null", Some(UiValue::Null)),
2723            ("missing", None),
2724        ];
2725        NativeCollection::new(
2726            "id",
2727            ranks.into_iter().map(|(key, rank)| {
2728                let mut row = BTreeMap::from([
2729                    ("id".into(), UiValue::String(key.into())),
2730                    ("score".into(), UiValue::String(format!("formatted {key}"))),
2731                ]);
2732                if let Some(rank) = rank {
2733                    row.insert("rank".into(), rank);
2734                }
2735                row
2736            }),
2737        )
2738        .unwrap()
2739    }
2740
2741    #[test]
2742    fn array_and_native_sort_key_share_exact_mixed_numeric_order() {
2743        let source = mixed_numeric_source();
2744        let array = source
2745            .source
2746            .rows
2747            .iter()
2748            .cloned()
2749            .map(UiValue::into_dynamic)
2750            .collect::<rhai::Array>();
2751        let mut engine = rhai::Engine::new_raw();
2752        register_native_collection_api(&mut engine);
2753        for (direction, expected) in [
2754            (
2755                "ascending",
2756                [
2757                    "below-min",
2758                    "min-int",
2759                    "lower-float",
2760                    "negative-frac",
2761                    "negative-int",
2762                    "negative-tiny",
2763                    "zero-int",
2764                    "zero-negative",
2765                    "zero-positive",
2766                    "positive-tiny",
2767                    "positive-frac",
2768                    "large-float",
2769                    "same-int",
2770                    "large-int",
2771                    "max-int",
2772                    "upper-float",
2773                    "null",
2774                    "missing",
2775                ],
2776            ),
2777            (
2778                "descending",
2779                [
2780                    "upper-float",
2781                    "max-int",
2782                    "large-int",
2783                    "large-float",
2784                    "same-int",
2785                    "positive-frac",
2786                    "positive-tiny",
2787                    "zero-int",
2788                    "zero-negative",
2789                    "zero-positive",
2790                    "negative-tiny",
2791                    "negative-int",
2792                    "negative-frac",
2793                    "min-int",
2794                    "lower-float",
2795                    "below-min",
2796                    "null",
2797                    "missing",
2798                ],
2799            ),
2800        ] {
2801            for input in [
2802                Dynamic::from(source.clone()),
2803                Dynamic::from_array(array.clone()),
2804            ] {
2805                let mut scope = rhai::Scope::new();
2806                scope.push_dynamic("rows", input);
2807                scope.push("config", ranked_config(direction));
2808                let view = engine
2809                    .eval_with_scope::<NativeCollection>(
2810                        &mut scope,
2811                        "native_table_view(rows, config)",
2812                    )
2813                    .unwrap();
2814                assert_eq!(
2815                    (0..view.len())
2816                        .map(|index| view.key(index).unwrap())
2817                        .collect::<Vec<_>>(),
2818                    expected
2819                );
2820            }
2821        }
2822    }
2823
2824    #[test]
2825    fn sort_key_resolves_column_identity_and_nulls_stay_last_with_stable_ties() {
2826        let rows = [
2827            Some(UiValue::Integer(2)),
2828            None,
2829            Some(UiValue::Null),
2830            Some(UiValue::Integer(1)),
2831            Some(UiValue::Integer(2)),
2832        ];
2833        let source = NativeCollection::new(
2834            "id",
2835            rows.into_iter().enumerate().map(|(index, rank)| {
2836                let mut row = BTreeMap::from([
2837                    ("id".into(), UiValue::String(index.to_string())),
2838                    (
2839                        "score".into(),
2840                        UiValue::String(format!("formatted {index}")),
2841                    ),
2842                ]);
2843                if let Some(rank) = rank {
2844                    row.insert("rank".into(), rank);
2845                }
2846                row
2847            }),
2848        )
2849        .unwrap();
2850        for (direction, expected) in [
2851            ("ascending", ["3", "0", "4", "1", "2"]),
2852            ("descending", ["0", "4", "3", "1", "2"]),
2853        ] {
2854            let view = source.table_view(ranked_config(direction)).unwrap();
2855            assert_eq!(
2856                (0..view.len())
2857                    .map(|index| view.key(index).unwrap())
2858                    .collect::<Vec<_>>(),
2859                expected
2860            );
2861            let UiValue::Map(item) = view.item(0).unwrap().unwrap() else {
2862                panic!()
2863            };
2864            assert!(format!("{item:?}").contains("formatted"));
2865        }
2866        let mut invalid = ranked_config("ascending");
2867        invalid.insert(
2868            "sort".into(),
2869            Dynamic::from_map(Map::from([
2870                ("key".into(), Dynamic::from("rank")),
2871                ("direction".into(), Dynamic::from("ascending")),
2872            ])),
2873        );
2874        assert!(
2875            source.table_view(invalid).is_err(),
2876            "sort must name the declared display column"
2877        );
2878    }
2879
2880    #[test]
2881    fn sort_validates_every_non_null_value_before_mutating_or_caching() {
2882        for rank in [
2883            UiValue::Array(vec![]),
2884            UiValue::Float(f64::NAN),
2885            UiValue::Float(f64::INFINITY),
2886        ] {
2887            let source = NativeCollection::new(
2888                "id",
2889                [BTreeMap::from([
2890                    ("id".into(), UiValue::String("only".into())),
2891                    ("rank".into(), rank),
2892                ])],
2893            )
2894            .unwrap();
2895            assert!(matches!(
2896                source.table_view(ranked_config("ascending")),
2897                Err(NativeCollectionError::UnsortableField(_))
2898            ));
2899            assert!(source.source.sorted_orders.lock().unwrap().is_empty());
2900            assert_eq!(source.key(0), Some("only"));
2901        }
2902        let source = NativeCollection::new(
2903            "id",
2904            [UiValue::Integer(1), UiValue::String("bad".into())]
2905                .into_iter()
2906                .enumerate()
2907                .map(|(index, rank)| {
2908                    BTreeMap::from([
2909                        ("id".into(), UiValue::String(index.to_string())),
2910                        ("rank".into(), rank),
2911                    ])
2912                }),
2913        )
2914        .unwrap();
2915        assert!(source.table_view(ranked_config("ascending")).is_err());
2916    }
2917
2918    #[test]
2919    fn thirty_thousand_formatted_native_rows_sort_without_rhai_enumeration() {
2920        let source = NativeCollection::new(
2921            "id",
2922            (0..30_000).map(|index| {
2923                BTreeMap::from([
2924                    ("id".into(), UiValue::String(index.to_string())),
2925                    (
2926                        "score".into(),
2927                        UiValue::String(format!("{} min", 30_000 - index)),
2928                    ),
2929                    ("rank".into(), UiValue::Integer(30_000 - index)),
2930                ])
2931            }),
2932        )
2933        .unwrap();
2934        let view = source.table_view(ranked_config("ascending")).unwrap();
2935        assert_eq!(view.len(), 30_000);
2936        assert_eq!(view.key(0), Some("29999"));
2937        assert_eq!(view.key(29_999), Some("0"));
2938        let cached = source.table_view(ranked_config("ascending")).unwrap();
2939        assert!(Arc::ptr_eq(&view.order, &cached.order));
2940    }
2941
2942    #[test]
2943    fn native_list_neighbors_skip_disabled_and_missing_selections() {
2944        let source = NativeCollection::new(
2945            "id",
2946            ["a", "b", "c"].into_iter().map(|key| {
2947                BTreeMap::from([
2948                    ("id".into(), UiValue::String(key.into())),
2949                    ("title".into(), UiValue::String(key.into())),
2950                    ("disabled".into(), UiValue::Bool(key == "b")),
2951                    ("has_children".into(), UiValue::Bool(key == "a")),
2952                ])
2953            }),
2954        )
2955        .unwrap();
2956        let selected = BTreeSet::from(["a".into()]);
2957        let view = source.list_view(selected.clone()).unwrap();
2958        let neighbors = view.table_neighbors(&selected);
2959        assert_eq!(neighbors.next.as_deref(), Some("c"));
2960        let missing = view.table_neighbors(&BTreeSet::from(["gone".into()]));
2961        assert_eq!(missing.current, None);
2962        assert_eq!(missing.next.as_deref(), Some("a"));
2963    }
2964
2965    #[test]
2966    fn tracked_replacement_invalidates_only_collection_readers() {
2967        let mut registry = NativeCollectionRegistry::new();
2968        registry.register("accounts", rows()).unwrap();
2969        let reader = ComponentInstancePath::root("View", "main");
2970        let _ = registry.read_tracked(&reader, "accounts").unwrap();
2971        let changed = NativeCollection::new(
2972            "id",
2973            [BTreeMap::from([(
2974                "id".to_owned(),
2975                UiValue::String("next".to_owned()),
2976            )])],
2977        )
2978        .unwrap();
2979        assert_eq!(
2980            registry.replace("accounts", changed).unwrap(),
2981            [reader].into()
2982        );
2983    }
2984
2985    #[test]
2986    fn registering_a_missing_name_invalidates_its_exact_readers() {
2987        let mut registry = NativeCollectionRegistry::new();
2988        let reader = ComponentInstancePath::root("View", "late-child");
2989        assert!(registry.read_tracked(&reader, "late").is_err());
2990        assert_eq!(
2991            registry
2992                .register_with_invalidated("late".to_owned(), rows())
2993                .unwrap(),
2994            BTreeSet::from([reader])
2995        );
2996    }
2997
2998    #[test]
2999    fn missing_dependencies_are_render_only_validated_and_bounded() {
3000        let mut registry = NativeCollectionRegistry::new();
3001        let reader = ComponentInstancePath::root("View", "missing-budget");
3002        assert!(matches!(
3003            registry.read_tracked_with_missing(&reader, &"x".repeat(257), true),
3004            Err(NativeCollectionError::InvalidName(_, _))
3005        ));
3006        assert!(registry.missing_readers.is_empty());
3007
3008        for index in 0..128 {
3009            assert!(
3010                registry
3011                    .read_tracked_with_missing(&reader, &format!("event-{index}"), false)
3012                    .is_err()
3013            );
3014        }
3015        assert!(registry.missing_readers.is_empty());
3016
3017        for index in 0..MAX_MISSING_NAMES_PER_READER {
3018            assert!(
3019                registry
3020                    .read_tracked_with_missing(&reader, &format!("render-{index}"), true)
3021                    .is_err()
3022            );
3023        }
3024        assert_eq!(registry.missing_readers.len(), MAX_MISSING_NAMES_PER_READER);
3025        assert!(matches!(
3026            registry.read_tracked_with_missing(&reader, "one-too-many", true),
3027            Err(NativeCollectionError::MissingDependencyBudget { .. })
3028        ));
3029        assert_eq!(registry.missing_readers.len(), MAX_MISSING_NAMES_PER_READER);
3030    }
3031
3032    #[test]
3033    fn grouped_table_projection_flattens_headers_and_sorted_rows() {
3034        let source = grouped_rows();
3035        let grouped = source.table_view(table_config(&[])).unwrap();
3036        let mut selected_config = table_config(&[]);
3037        selected_config.insert(
3038            "selected_keys".into(),
3039            Dynamic::from_array(vec![Dynamic::from("a")]),
3040        );
3041        let reused = source.table_view(selected_config).unwrap();
3042        assert!(Arc::ptr_eq(&grouped.order, &reused.order));
3043        assert_eq!(grouped.len(), 5);
3044        assert_eq!(grouped.sticky_headers().as_ref(), &BTreeSet::from([0, 3]));
3045        let values = (0..grouped.len())
3046            .map(|index| grouped.item(index).unwrap().unwrap())
3047            .collect::<Vec<_>>();
3048        let field = |value: &UiValue, name: &str| match value {
3049            UiValue::Map(value) => value[name].clone(),
3050            _ => panic!("projected table item must be a map"),
3051        };
3052        assert_eq!(field(&values[0], "kind"), UiValue::String("group".into()));
3053        assert_eq!(
3054            field(&values[0], "group"),
3055            UiValue::String("track-b".into())
3056        );
3057        assert_eq!(field(&values[0], "count"), UiValue::Integer(2));
3058        assert_eq!(field(&values[1], "key"), UiValue::String("c".into()));
3059        assert_eq!(field(&values[2], "key"), UiValue::String("b".into()));
3060        assert_eq!(
3061            field(&values[3], "group"),
3062            UiValue::String("track-a".into())
3063        );
3064        assert_eq!(field(&values[4], "key"), UiValue::String("a".into()));
3065    }
3066
3067    #[test]
3068    fn table_rows_carry_their_selected_flag_but_not_the_next_selection() {
3069        let source = grouped_rows();
3070        for (mode, selected) in [
3071            ("multiple", vec!["a", "b"]),
3072            ("single", vec!["a"]),
3073            ("none", vec![]),
3074        ] {
3075            let mut config = table_config(&[]);
3076            config.insert("group_by".into(), Dynamic::UNIT);
3077            config.insert("selection_mode".into(), Dynamic::from(mode));
3078            config.insert(
3079                "selected_keys".into(),
3080                Dynamic::from_array(selected.iter().copied().map(Dynamic::from).collect()),
3081            );
3082            let view = source.table_view(config).unwrap();
3083            for index in 0..view.len() {
3084                let UiValue::Map(row) = view.item(index).unwrap().unwrap() else {
3085                    panic!("projected table row must be a map");
3086                };
3087                let UiValue::String(key) = &row["key"] else {
3088                    panic!("projected table row key must be a string");
3089                };
3090                assert_eq!(
3091                    row["selected"],
3092                    UiValue::Bool(selected.contains(&key.as_str())),
3093                    "{mode} {key}"
3094                );
3095                assert_eq!(
3096                    row.keys().map(String::as_str).collect::<Vec<_>>(),
3097                    [
3098                        "cells", "height", "key", "kind", "label", "selected", "striped"
3099                    ],
3100                    "{mode} {key}"
3101                );
3102            }
3103        }
3104        let mut config = table_config(&[]);
3105        config.insert("selection_mode".into(), Dynamic::from("several"));
3106        assert!(matches!(
3107            source.table_view(config),
3108            Err(NativeCollectionError::InvalidTableConfig(message))
3109                if message == "unknown selection mode `several`"
3110        ));
3111    }
3112
3113    #[test]
3114    fn grouped_table_projection_collapses_rows_but_retains_header_counts() {
3115        let grouped = grouped_rows()
3116            .table_view(table_config(&["track-b"]))
3117            .unwrap();
3118        assert_eq!(grouped.len(), 3);
3119        assert_eq!(grouped.sticky_headers().as_ref(), &BTreeSet::from([0, 1]));
3120        let UiValue::Map(first) = grouped.item(0).unwrap().unwrap() else {
3121            panic!("group header must be a map");
3122        };
3123        assert_eq!(first["group"], UiValue::String("track-b".into()));
3124        assert_eq!(first["count"], UiValue::Integer(2));
3125        assert_eq!(first["collapsed"], UiValue::Bool(true));
3126        assert_eq!(grouped.key(2), Some("a"));
3127    }
3128
3129    #[test]
3130    fn table_projection_filters_then_pages_the_sorted_native_rows() {
3131        let source = grouped_rows();
3132        let page = |number: i64| {
3133            let mut config = table_config(&[]);
3134            config.insert("group_by".into(), Dynamic::UNIT);
3135            config.insert("query".into(), Dynamic::from("track-b"));
3136            config.insert(
3137                "search_fields".into(),
3138                Dynamic::from_array(vec![Dynamic::from("track")]),
3139            );
3140            config.insert("page".into(), Dynamic::from_int(number));
3141            config.insert("page_size".into(), Dynamic::from_int(1));
3142            source.table_view(config).unwrap()
3143        };
3144        let first = page(1);
3145        let second = page(2);
3146        assert_eq!(first.len(), 1);
3147        assert_eq!(second.len(), 1);
3148        assert_eq!(first.key(0), Some("c"));
3149        assert_eq!(second.key(0), Some("b"));
3150        assert!(!Arc::ptr_eq(&first.order, &second.order));
3151    }
3152}