Skip to main content

teksilo_data/
list_model.rs

1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4//! `ListModel<T>` — concrete reactive list backed by a `Vec<T>`.
5//!
6//! `ListModel<T>` stores items in a heap-allocated `Vec<T>` behind
7//! `Rc<RefCell<…>>`. Cloning a handle shares the same underlying data — there
8//! is no deep copy. Every mutation method (`push`, `insert`, `remove`, `set`,
9//! `move_item`, `replace_all`, `clear`) drops the internal borrow before
10//! notifying observers, so observer callbacks may safely call read methods
11//! (`len`, `with_item`) without a re-entrant borrow.
12//!
13//! `ListModel<T>` implements [`ListDataSource`] directly, so it can be handed
14//! to any `ListView` / `TableView` without adaption. For lists too large to
15//! hold in memory, implement [`ListDataSource`] directly on your own type
16//! (paged database cursor, windowed feed, etc.).
17//!
18//! ## When to use
19//!
20//! Use `ListModel<T>` when the full list fits in memory and you want automatic
21//! change notifications with no extra setup. Use a custom [`ListDataSource`]
22//! when the source is external, huge, or lazy-loaded.
23//!
24//! ## Notifications
25//!
26//! Observers registered via [`ListModel::observe_changes`] receive a
27//! [`DataChange`] describing the minimal change: `ItemsInserted`,
28//! `ItemsRemoved`, `ItemUpdated`, `ItemsMoved`, or `Reset`. The
29//! [`ObserverHandle`] returned is RAII — dropping
30//! it unregisters the callback immediately.
31//!
32//! ```rust
33//! # use teksilo_data::ListModel;
34//! let model: ListModel<&str> = ListModel::new();
35//! model.push("alpha");
36//! model.push("beta");
37//! model.push("gamma");
38//! assert_eq!(model.len(), 3);
39//! let second = model.with_item(1, |s| *s);
40//! assert_eq!(second, Some("beta"));
41//! model.set(0, "ALPHA");
42//! model.remove(2);
43//! assert_eq!(model.len(), 2);
44//! ```
45
46use std::cell::RefCell;
47use std::collections::HashSet;
48use std::hash::Hash;
49use std::ops::Range;
50use std::rc::Rc;
51
52use teksilo_core::ObserverHandle;
53
54use crate::data_change::DataChange;
55use crate::dnd_types::{
56    DragEligibility, DragSource, DropCommit, DropPosition, DropQuery, DropResponse,
57};
58use crate::list_data_source::ListDataSource;
59
60struct ObserverEntry {
61    id: u64,
62    callback: Rc<dyn Fn(&DataChange)>,
63}
64
65struct ListModelInner<T> {
66    items: Vec<T>,
67    observers: Vec<ObserverEntry>,
68    next_observer_id: u64,
69    /// Strong handle to the debug-registry adapter for this model.
70    /// Owned here so that the registration drops automatically when
71    /// the inner is freed (the adapter holds only a `Weak` to inner,
72    /// breaking the cycle). `None` until `.debug_named()` is called.
73    /// Compiled out in release.
74    #[cfg(debug_assertions)]
75    debug_adapter: Option<Rc<dyn crate::debug_registry::ModelDebug>>,
76}
77
78/// A concrete reactive list that stores items in a `Vec<T>`.
79///
80/// `ListModel<T>` is `Clone` — cloning produces a second handle to the same
81/// data. Multiple widgets can hold clones and all see the same items.
82///
83/// Every mutation method modifies the internal Vec, drops the mutable borrow,
84/// then notifies observers. By the time any observer runs, the borrow is
85/// released and shared borrows (`len()`, `with_item()`) are safe.
86pub struct ListModel<T: 'static> {
87    inner: Rc<RefCell<ListModelInner<T>>>,
88}
89
90impl<T: 'static> ListModel<T> {
91    /// Create an empty list model.
92    pub fn new() -> Self {
93        Self {
94            inner: Rc::new(RefCell::new(ListModelInner {
95                items: Vec::new(),
96                observers: Vec::new(),
97                next_observer_id: 1,
98                #[cfg(debug_assertions)]
99                debug_adapter: None,
100            })),
101        }
102    }
103
104    /// Create a list model from an existing vector.
105    pub fn from_vec(items: Vec<T>) -> Self {
106        Self {
107            inner: Rc::new(RefCell::new(ListModelInner {
108                items,
109                observers: Vec::new(),
110                next_observer_id: 1,
111                #[cfg(debug_assertions)]
112                debug_adapter: None,
113            })),
114        }
115    }
116
117    /// Number of items in the list.
118    pub fn len(&self) -> usize {
119        self.inner.borrow().items.len()
120    }
121
122    /// Whether the list is empty.
123    pub fn is_empty(&self) -> bool {
124        self.inner.borrow().items.is_empty()
125    }
126
127    /// Access an item by index via a callback. Returns `None` if out of bounds.
128    ///
129    /// The callback pattern avoids returning a reference that would need to
130    /// outlive the `RefCell` borrow guard.
131    pub fn with_item<R>(&self, index: usize, f: impl FnOnce(&T) -> R) -> Option<R> {
132        let guard = self.inner.borrow();
133        guard.items.get(index).map(f)
134    }
135
136    /// Append an item to the end of the list.
137    pub fn push(&self, item: T) {
138        let index = {
139            let mut guard = self.inner.borrow_mut();
140            let index = guard.items.len();
141            guard.items.push(item);
142            index
143        };
144        self.notify(DataChange::ItemsInserted {
145            range: index..index + 1,
146        });
147    }
148
149    /// Insert an item at the given index.
150    ///
151    /// # Panics
152    /// Panics if `index > len()`.
153    pub fn insert(&self, index: usize, item: T) {
154        {
155            let mut guard = self.inner.borrow_mut();
156            guard.items.insert(index, item);
157        }
158        self.notify(DataChange::ItemsInserted {
159            range: index..index + 1,
160        });
161    }
162
163    /// Remove and return the item at the given index.
164    ///
165    /// # Panics
166    /// Panics if `index >= len()`.
167    pub fn remove(&self, index: usize) -> T {
168        let item = {
169            let mut guard = self.inner.borrow_mut();
170            guard.items.remove(index)
171        };
172        self.notify(DataChange::ItemsRemoved {
173            range: index..index + 1,
174        });
175        item
176    }
177
178    /// Replace the item at the given index.
179    ///
180    /// # Panics
181    /// Panics if `index >= len()`.
182    pub fn set(&self, index: usize, item: T) {
183        {
184            let mut guard = self.inner.borrow_mut();
185            guard.items[index] = item;
186        }
187        self.notify(DataChange::ItemUpdated { index });
188    }
189
190    /// Move an item from one index to another.
191    ///
192    /// The item at `from` is removed, then inserted at `to` (post-removal index).
193    ///
194    /// # Panics
195    /// Panics if either index is out of bounds.
196    pub fn move_item(&self, from: usize, to: usize) {
197        if from == to {
198            return;
199        }
200        {
201            let mut guard = self.inner.borrow_mut();
202            let item = guard.items.remove(from);
203            guard.items.insert(to, item);
204        }
205        self.notify(DataChange::ItemsMoved { from, to, count: 1 });
206    }
207
208    /// Move a set of items so they land **contiguously** at a drop gap,
209    /// preserving their relative order — the multi-row same-view reorder
210    /// commit. `indices` are the items' current positions (any order;
211    /// out-of-range entries are ignored); `insert_gap` is the destination in
212    /// `0..=len` expressed in the pre-move indexing (i.e. "land before the item
213    /// currently at `insert_gap`"; `len` = at the end).
214    ///
215    /// Returns whether anything moved (`false` if `indices` held no in-range
216    /// entry). A **contiguous** source block emits a single
217    /// [`DataChange::ItemsMoved`] — so index-based selection follows the moved
218    /// rows; a non-contiguous set emits [`DataChange::Reset`] (that permutation
219    /// is not expressible as one `ItemsMoved`, and selection is dropped). For a
220    /// single index prefer [`move_item`](Self::move_item).
221    pub fn move_items(&self, indices: &[usize], insert_gap: usize) -> bool {
222        let len = self.len();
223        let mut idx: Vec<usize> = indices.iter().copied().filter(|&i| i < len).collect();
224        idx.sort_unstable();
225        idx.dedup();
226        if idx.is_empty() {
227            return false;
228        }
229        let contiguous = idx.windows(2).all(|w| w[1] == w[0] + 1);
230        let from0 = idx[0];
231        let count = idx.len();
232        let at;
233        {
234            let mut guard = self.inner.borrow_mut();
235            // Remove from the back so earlier indices stay valid, then restore
236            // ascending (original) order.
237            let mut block: Vec<T> = idx.iter().rev().map(|&i| guard.items.remove(i)).collect();
238            block.reverse();
239            let removed_before = idx.iter().filter(|&&i| i < insert_gap).count();
240            at = insert_gap
241                .saturating_sub(removed_before)
242                .min(guard.items.len());
243            for (off, item) in block.into_iter().enumerate() {
244                guard.items.insert(at + off, item);
245            }
246        }
247        if contiguous && from0 != at {
248            self.notify(DataChange::ItemsMoved {
249                from: from0,
250                to: at,
251                count,
252            });
253        } else if contiguous {
254            // No net movement (block landed where it started).
255        } else {
256            self.notify(DataChange::Reset);
257        }
258        true
259    }
260
261    /// Replace the entire list contents.
262    pub fn replace_all(&self, items: Vec<T>) {
263        {
264            let mut guard = self.inner.borrow_mut();
265            guard.items = items;
266        }
267        self.notify(DataChange::Reset);
268    }
269
270    /// Remove all items from the list.
271    pub fn clear(&self) {
272        {
273            let mut guard = self.inner.borrow_mut();
274            guard.items.clear();
275        }
276        self.notify(DataChange::Reset);
277    }
278
279    /// Register an observer that is called on every mutation.
280    /// Returns an `ObserverHandle` — dropping it removes the callback.
281    pub fn observe_changes(&self, f: impl Fn(&DataChange) + 'static) -> ObserverHandle {
282        let mut guard = self.inner.borrow_mut();
283        let id = guard.next_observer_id;
284        guard.next_observer_id += 1;
285        guard.observers.push(ObserverEntry {
286            id,
287            callback: Rc::new(f),
288        });
289        let inner = self.inner.clone();
290        ObserverHandle::new(
291            self.inner.clone(),
292            id,
293            Rc::new(move |observer_id| {
294                // A callback may own the last reference to another observer of
295                // this model: it is dropped only once the borrow is released.
296                let removed = {
297                    let mut guard = inner.borrow_mut();
298                    let index = guard.observers.iter().position(|e| e.id == observer_id);
299                    index.map(|i| guard.observers.remove(i))
300                };
301                drop(removed);
302            }),
303        )
304    }
305
306    fn notify(&self, change: DataChange) {
307        let callbacks: Vec<Rc<dyn Fn(&DataChange)>> = self
308            .inner
309            .borrow()
310            .observers
311            .iter()
312            .map(|e| e.callback.clone())
313            .collect();
314        for cb in &callbacks {
315            cb(&change);
316        }
317    }
318}
319
320impl<T: PartialEq + 'static> ListModel<T> {
321    /// Reconcile the list's contents with `new_items`, matching old and new
322    /// rows **by key** (`key_fn`) instead of wholesale-replacing them, and
323    /// emitting the minimal set of granular [`DataChange`]s needed to reach
324    /// that state — never [`DataChange::Reset`].
325    ///
326    /// This is the primitive a live view needs when a peer process (or any
327    /// other out-of-band writer) reloads a backing file and the merged
328    /// result must land in a `ListModel` that a `ListView` is *currently
329    /// displaying*, without wiping the user's selection or keyboard focus
330    /// mid-interaction. `replace_all`/`clear` always emit `Reset`, and a
331    /// `Reset` unconditionally clears a positional `SelectionModel`
332    /// (`RowSelection::from_index`) — `reconcile_by_key` is how a caller
333    /// avoids that.
334    ///
335    /// # Change order
336    ///
337    /// The changes are emitted in two stages, coalescing contiguous runs into
338    /// a single event each:
339    ///
340    /// 1. **Removals first.** One [`DataChange::ItemsRemoved`] per contiguous
341    ///    run of keys present in the old list but absent from `new_items`,
342    ///    emitted back to front so every range is still valid, in the old
343    ///    indices, at the moment it is removed.
344    /// 2. **One left-to-right walk over the target order.** Each surviving
345    ///    row is handled when the walk reaches it: a [`DataChange::ItemsMoved`]
346    ///    (a single-row block) if it is not yet in its target slot — skipped
347    ///    for rows already in place, so an append-only or remove-only reload
348    ///    emits **no** moves — then a [`DataChange::ItemUpdated`] if its
349    ///    content differs (`T: PartialEq`; the stored value is replaced with
350    ///    the incoming one). Brand-new keys are buffered and flushed as one
351    ///    [`DataChange::ItemsInserted`] run just before the next survivor, or
352    ///    at the end of the walk.
353    ///
354    /// So after the removals, moves, updates and inserts are **interleaved in
355    /// walk order**, not grouped by kind: reconciling `[(1,"a"),(2,"b")]`
356    /// into `[(1,"a"),(2,"B"),(3,"c")]` emits `ItemUpdated { index: 1 }` and
357    /// then `ItemsInserted { range: 2..3 }`.
358    ///
359    /// Every change's indices are valid against the list **as it stands
360    /// after the previous change** (a sequential index space), not against
361    /// the list before `reconcile_by_key` or after it. A consumer that
362    /// applies the changes one at a time, in the order delivered, stays
363    /// correct; one that batches them by kind (all removals, then all moves,
364    /// …) or replays them out of order does not.
365    ///
366    /// If `new_items` is identical (same keys, same order, same content, by
367    /// `PartialEq`) to the current contents, **no** change is emitted and no
368    /// observer runs — reconciling with unchanged data is silent.
369    ///
370    /// # Preconditions
371    /// `key_fn` must be a pure, stable function of an item's identity (not
372    /// its content) and keys must be **unique** within both the current list
373    /// and `new_items`. See `# Panics` below — an unstable `key_fn` or a
374    /// duplicate within `new_items` panics; a duplicate within the current
375    /// list is silently tolerated and leaves the extra copies behind, which
376    /// is worse.
377    ///
378    /// # Panics
379    /// Panics (via an internal `.expect`) if `key_fn` is not stable — it
380    /// returns a different key for the same item across the two calls this
381    /// method makes to it (once while snapshotting the current list's keys,
382    /// once while re-deriving a key during the write pass) — or if a key is
383    /// **duplicated** within the current list or within `new_items`. Both
384    /// break the same invariant the write pass relies on: "the item that
385    /// was accounted for under this key is still findable at or after the
386    /// write cursor." A duplicate key means two different items raced to
387    /// claim one key slot, so by the time the second one is processed the
388    /// slot the accounting expected is already gone. This is this crate's
389    /// usual documented-panic-on-contract-violation style (see e.g.
390    /// [`TreeModel::remove`](crate::TreeModel::remove)) — a caller-side bug
391    /// surfaced immediately as a panic, not silently wrong data.
392    ///
393    /// # Complexity
394    /// Re-ordering is a straightforward left-to-right pass that moves each
395    /// out-of-place survivor into its target slot; it is correct and always
396    /// granular, but is not guaranteed to emit the mathematically fewest
397    /// possible `ItemsMoved` events for an adversarial permutation (an
398    /// LIS-based scheme could do slightly better there). For the common
399    /// case this primitive targets — a peer append/remove/edit merged back
400    /// in — the existing relative order of untouched rows is preserved
401    /// as-is, so no moves are emitted at all.
402    pub fn reconcile_by_key<K: Eq + Hash>(&self, new_items: Vec<T>, key_fn: impl Fn(&T) -> K) {
403        let mut changes: Vec<DataChange> = Vec::new();
404        {
405            let mut guard = self.inner.borrow_mut();
406            reconcile_vec(&mut guard.items, new_items, &key_fn, &mut changes);
407        }
408        for change in changes {
409            self.notify(change);
410        }
411    }
412}
413
414/// Diff `items` (current contents) against `new_items` by key, mutating
415/// `items` in place to match `new_items` exactly and pushing one
416/// [`DataChange`] per atomic step taken. Kept as a free function (rather
417/// than inlined into `reconcile_by_key`) so it can be exercised directly —
418/// and so it operates on the bare `Vec<T>` while the caller still holds the
419/// `RefCell` borrow, before any observer notification fires.
420fn reconcile_vec<T: PartialEq, K: Eq + Hash>(
421    items: &mut Vec<T>,
422    new_items: Vec<T>,
423    key_fn: &impl Fn(&T) -> K,
424    out: &mut Vec<DataChange>,
425) {
426    // Pair every incoming item with its key up front: we need the key
427    // before we decide anything, and this avoids re-deriving ownership of
428    // the item later.
429    let new_pairs: Vec<(K, T)> = new_items.into_iter().map(|it| (key_fn(&it), it)).collect();
430    let new_key_set: HashSet<&K> = new_pairs.iter().map(|(k, _)| k).collect();
431
432    // ---- Phase 1: drop old items whose key no longer exists in the
433    // incoming list. Computed against a pre-removal key snapshot so later
434    // removals don't perturb earlier indices; applied back-to-front so
435    // each removed range's indices stay valid at the point it's removed. ----
436    let old_keys: Vec<K> = items.iter().map(key_fn).collect();
437    let remove_idxs: Vec<usize> = (0..items.len())
438        .filter(|&i| !new_key_set.contains(&old_keys[i]))
439        .collect();
440    for range in coalesce_ranges(&remove_idxs).into_iter().rev() {
441        items.drain(range.clone());
442        out.push(DataChange::ItemsRemoved { range });
443    }
444
445    // From here on, `items` holds exactly the surviving ("common") rows, in
446    // their original relative order.
447    let remaining_keys: HashSet<K> = items.iter().map(key_fn).collect();
448
449    // ---- Phase 2/3: walk the target order left to right. A common key is
450    // moved into place (if it isn't already there) and its content updated
451    // in place if it changed; a brand-new key is buffered and flushed as a
452    // single contiguous `ItemsInserted` run as soon as a common key (or the
453    // end of the list) is reached. ----
454    let mut cursor = 0usize;
455    let mut pending_inserts: Vec<T> = Vec::new();
456
457    for (key, new_item) in new_pairs {
458        if remaining_keys.contains(&key) {
459            flush_inserts(items, &mut cursor, &mut pending_inserts, out);
460
461            // Invariant: items[0..cursor] already matches the target
462            // prefix, so this key — being common and not yet placed — must
463            // sit somewhere at or after `cursor`.
464            let pos = items
465                .iter()
466                .skip(cursor)
467                .position(|it| key_fn(it) == key)
468                .expect(
469                    "reconcile_by_key: key reported common but not found — \
470                     key_fn must be stable and keys unique",
471                );
472            let actual = cursor + pos;
473            if actual != cursor {
474                let val = items.remove(actual);
475                items.insert(cursor, val);
476                out.push(DataChange::ItemsMoved {
477                    from: actual,
478                    to: cursor,
479                    count: 1,
480                });
481            }
482            if items[cursor] != new_item {
483                items[cursor] = new_item;
484                out.push(DataChange::ItemUpdated { index: cursor });
485            }
486            cursor += 1;
487        } else {
488            pending_inserts.push(new_item);
489        }
490    }
491    flush_inserts(items, &mut cursor, &mut pending_inserts, out);
492}
493
494/// Splice any buffered new rows into `items` at `*cursor` as one contiguous
495/// block, emit the single `ItemsInserted` covering them, and advance the
496/// cursor past them. No-op (no event) if nothing is pending.
497fn flush_inserts<T>(
498    items: &mut Vec<T>,
499    cursor: &mut usize,
500    pending: &mut Vec<T>,
501    out: &mut Vec<DataChange>,
502) {
503    if pending.is_empty() {
504        return;
505    }
506    let start = *cursor;
507    let n = pending.len();
508    items.splice(start..start, pending.drain(..));
509    out.push(DataChange::ItemsInserted {
510        range: start..start + n,
511    });
512    *cursor += n;
513}
514
515/// Group a sorted, deduplicated slice of indices into maximal contiguous
516/// ranges, e.g. `[1, 2, 3, 7, 8]` → `[1..4, 7..9]`.
517fn coalesce_ranges(sorted_idxs: &[usize]) -> Vec<Range<usize>> {
518    let mut ranges = Vec::new();
519    let mut iter = sorted_idxs.iter().peekable();
520    while let Some(&start) = iter.next() {
521        let mut end = start + 1;
522        while iter.peek().is_some_and(|&&n| n == end) {
523            end += 1;
524            iter.next();
525        }
526        ranges.push(start..end);
527    }
528    ranges
529}
530
531impl<T: std::fmt::Debug + 'static> ListModel<T> {
532    /// Register this model with the debug inspector under `name`. In
533    /// release builds (`!cfg(debug_assertions)`) this is a no-op
534    /// pass-through so call sites stay free of `#[cfg]` lines.
535    ///
536    /// Idempotent on repeated calls — the latest registration wins.
537    /// The registration drops automatically when the last `ListModel`
538    /// handle is freed (the adapter the registry holds is `Weak`).
539    pub fn debug_named(self, _name: impl Into<String>) -> Self {
540        #[cfg(debug_assertions)]
541        {
542            let weak = Rc::downgrade(&self.inner);
543            let adapter: Rc<dyn crate::debug_registry::ModelDebug> =
544                Rc::new(ListModelDebug::<T> { weak });
545            let name = _name.into();
546            crate::debug_registry::register(name, Rc::downgrade(&adapter));
547            self.inner.borrow_mut().debug_adapter = Some(adapter);
548        }
549        self
550    }
551}
552
553#[cfg(debug_assertions)]
554struct ListModelDebug<T> {
555    weak: std::rc::Weak<RefCell<ListModelInner<T>>>,
556}
557
558#[cfg(debug_assertions)]
559impl<T: std::fmt::Debug + 'static> crate::debug_registry::ModelDebug for ListModelDebug<T> {
560    fn kind(&self) -> &'static str {
561        "ListModel"
562    }
563    fn len(&self) -> usize {
564        self.weak
565            .upgrade()
566            .map(|inner| inner.borrow().items.len())
567            .unwrap_or(0)
568    }
569    fn debug_dump(&self, out: &mut dyn std::fmt::Write) {
570        let Some(inner) = self.weak.upgrade() else {
571            return;
572        };
573        let guard = inner.borrow();
574        for (i, item) in guard.items.iter().enumerate() {
575            let _ = writeln!(out, "[{}] {:?}", i, item);
576        }
577    }
578}
579
580impl<T: 'static> Default for ListModel<T> {
581    fn default() -> Self {
582        Self::new()
583    }
584}
585
586impl<T: 'static> Clone for ListModel<T> {
587    fn clone(&self) -> Self {
588        Self {
589            inner: self.inner.clone(),
590        }
591    }
592}
593
594impl<T: std::fmt::Debug + 'static> std::fmt::Debug for ListModel<T> {
595    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
596        f.debug_struct("ListModel")
597            .field("len", &self.inner.borrow().items.len())
598            .finish()
599    }
600}
601
602/// `ListModel` is the built-in fully-resident, in-memory `ListDataSource`.
603/// Identity is positional (`Key = usize`); a `SameView` drop reorders via
604/// `move_item`. `Into` and `Foreign` drops are rejected (a flat list does not
605/// nest, and a bare model knows no foreign payloads).
606impl<T: 'static> ListDataSource for ListModel<T> {
607    type Item = T;
608    type Key = usize;
609
610    fn len(&self) -> usize {
611        ListModel::len(self)
612    }
613
614    fn with_item<R>(&self, index: usize, f: impl FnOnce(&T) -> R) -> Option<R> {
615        ListModel::with_item(self, index, f)
616    }
617
618    fn key_at(&self, index: usize) -> Option<usize> {
619        (index < ListModel::len(self)).then_some(index)
620    }
621
622    fn index_of(&self, key: &usize) -> Option<usize> {
623        (*key < ListModel::len(self)).then_some(*key)
624    }
625
626    fn observe_changes(&self, f: impl Fn(&DataChange) + 'static) -> ObserverHandle {
627        ListModel::observe_changes(self, f)
628    }
629
630    fn drag(&self, _key: &usize) -> DragEligibility {
631        DragEligibility::CanDrag
632    }
633
634    fn can_accept(&self, query: &DropQuery<'_, usize>) -> DropResponse {
635        match &query.source {
636            DragSource::SameView { .. } => match query.position {
637                DropPosition::Into => DropResponse::Reject,
638                DropPosition::Before | DropPosition::After => DropResponse::Accept,
639            },
640            DragSource::Foreign { .. } => DropResponse::Reject,
641        }
642    }
643
644    fn accept_drop(&self, commit: DropCommit<'_, usize>) -> bool {
645        let DragSource::SameView { key: from } = commit.source else {
646            return false;
647        };
648        let len = ListModel::len(self);
649        if from >= len {
650            return false;
651        }
652        let target = commit.target;
653        // move_item removes `from` before inserting, so an insertion point above
654        // the source's old slot shifts down by one.
655        let shift = if from < target { 1 } else { 0 };
656        let to = match commit.position {
657            DropPosition::Before => target.saturating_sub(shift),
658            DropPosition::After => (target + 1).saturating_sub(shift),
659            DropPosition::Into => return false,
660        };
661        let to = to.min(len.saturating_sub(1));
662        self.move_item(from, to);
663        true
664    }
665
666    fn reorder_within(&self, sources: &[usize], target: &usize, position: DropPosition) -> bool {
667        // A `ListModel`'s key IS the index, so the stable-key default (which
668        // re-anchors on a just-moved key) would corrupt after the first move —
669        // route the multi-row case through the index-safe block move instead.
670        // A single row keeps the finer-grained `accept_drop`/`move_item` path.
671        if sources.len() <= 1 {
672            let Some(&from) = sources.first() else {
673                return false;
674            };
675            return self.accept_drop(DropCommit {
676                source: DragSource::SameView { key: from },
677                target: *target,
678                position,
679            });
680        }
681        let gap = match position {
682            DropPosition::Before => *target,
683            DropPosition::After => *target + 1,
684            DropPosition::Into => return false,
685        };
686        self.move_items(sources, gap)
687    }
688
689    fn on_drag_out(&self, key: &usize) {
690        // Source-side completion for a foreign move: drop the row that was
691        // accepted elsewhere. Callers remove in descending index order so
692        // earlier keys stay valid across a multi-row transfer.
693        if *key < ListModel::len(self) {
694            let _ = self.remove(*key);
695        }
696    }
697}
698
699#[cfg(test)]
700mod tests {
701    use std::cell::Cell;
702
703    use super::*;
704
705    #[test]
706    fn new_is_empty() {
707        let model: ListModel<String> = ListModel::new();
708        assert!(model.is_empty());
709        assert_eq!(model.len(), 0);
710    }
711
712    /// A model that observes its own list, kept alive only by another
713    /// observer's callback: removing that observer drops the model, whose
714    /// own handle then removes itself from the same list.
715    #[test]
716    fn removing_an_observer_that_owns_the_last_reference_to_another_does_not_panic() {
717        struct Owner {
718            items: ListModel<u8>,
719            own: RefCell<Vec<ObserverHandle>>,
720        }
721        let owner = Rc::new(Owner {
722            items: ListModel::new(),
723            own: RefCell::new(Vec::new()),
724        });
725        owner
726            .own
727            .borrow_mut()
728            .push(owner.items.observe_changes(|_| {}));
729        let items = owner.items.clone();
730        let held = Rc::clone(&owner);
731        let handle = owner.items.observe_changes(move |_| {
732            let _ = &held;
733        });
734        drop(owner);
735
736        drop(handle);
737        let fired = Rc::new(Cell::new(false));
738        let f = fired.clone();
739        let _h = items.observe_changes(move |_| f.set(true));
740        items.push(1);
741        assert!(fired.get(), "the model still notifies after the removal");
742    }
743
744    #[test]
745    fn from_vec() {
746        let model = ListModel::from_vec(vec![10, 20, 30]);
747        assert_eq!(model.len(), 3);
748        assert_eq!(model.with_item(1, |v| *v), Some(20));
749    }
750
751    #[test]
752    fn push_emits_inserted() {
753        let model = ListModel::new();
754        let changes: Rc<RefCell<Vec<DataChange>>> = Rc::new(RefCell::new(Vec::new()));
755        let c = changes.clone();
756        let _handle = model.observe_changes(move |change| {
757            c.borrow_mut().push(change.clone());
758        });
759
760        model.push("a");
761        model.push("b");
762
763        let log = changes.borrow();
764        assert_eq!(log.len(), 2);
765        assert_eq!(log[0], DataChange::ItemsInserted { range: 0..1 });
766        assert_eq!(log[1], DataChange::ItemsInserted { range: 1..2 });
767    }
768
769    #[test]
770    fn insert_emits_inserted() {
771        let model = ListModel::from_vec(vec![1, 2, 3]);
772        let changes: Rc<RefCell<Vec<DataChange>>> = Rc::new(RefCell::new(Vec::new()));
773        let c = changes.clone();
774        let _handle = model.observe_changes(move |change| {
775            c.borrow_mut().push(change.clone());
776        });
777
778        model.insert(1, 99);
779
780        assert_eq!(model.len(), 4);
781        assert_eq!(model.with_item(1, |v| *v), Some(99));
782        let log = changes.borrow();
783        assert_eq!(log.len(), 1, "insert should emit exactly one change");
784        assert_eq!(log[0], DataChange::ItemsInserted { range: 1..2 });
785    }
786
787    #[test]
788    fn remove_emits_removed() {
789        let model = ListModel::from_vec(vec!["a", "b", "c"]);
790        let changes: Rc<RefCell<Vec<DataChange>>> = Rc::new(RefCell::new(Vec::new()));
791        let c = changes.clone();
792        let _handle = model.observe_changes(move |change| {
793            c.borrow_mut().push(change.clone());
794        });
795
796        let removed = model.remove(1);
797        assert_eq!(removed, "b");
798        assert_eq!(model.len(), 2);
799        let log = changes.borrow();
800        assert_eq!(log.len(), 1, "remove should emit exactly one change");
801        assert_eq!(log[0], DataChange::ItemsRemoved { range: 1..2 });
802    }
803
804    #[test]
805    fn set_emits_updated() {
806        let model = ListModel::from_vec(vec![10, 20, 30]);
807        let changes: Rc<RefCell<Vec<DataChange>>> = Rc::new(RefCell::new(Vec::new()));
808        let c = changes.clone();
809        let _handle = model.observe_changes(move |change| {
810            c.borrow_mut().push(change.clone());
811        });
812
813        model.set(2, 99);
814        assert_eq!(model.with_item(2, |v| *v), Some(99));
815        let log = changes.borrow();
816        assert_eq!(log.len(), 1, "set should emit exactly one change");
817        assert_eq!(log[0], DataChange::ItemUpdated { index: 2 });
818    }
819
820    #[test]
821    fn move_item_emits_moved() {
822        let model = ListModel::from_vec(vec!["a", "b", "c", "d"]);
823        let changes: Rc<RefCell<Vec<DataChange>>> = Rc::new(RefCell::new(Vec::new()));
824        let c = changes.clone();
825        let _handle = model.observe_changes(move |change| {
826            c.borrow_mut().push(change.clone());
827        });
828
829        model.move_item(0, 2);
830        // After: ["b", "c", "a", "d"]
831        assert_eq!(model.with_item(0, |v| *v), Some("b"));
832        assert_eq!(model.with_item(2, |v| *v), Some("a"));
833        let log = changes.borrow();
834        assert_eq!(log.len(), 1, "move_item should emit exactly one change");
835        assert_eq!(
836            log[0],
837            DataChange::ItemsMoved {
838                from: 0,
839                to: 2,
840                count: 1
841            }
842        );
843    }
844
845    #[test]
846    fn move_item_same_index_is_noop() {
847        let model = ListModel::from_vec(vec![1, 2, 3]);
848        let count = Rc::new(Cell::new(0));
849        let c = count.clone();
850        let _handle = model.observe_changes(move |_| {
851            c.set(c.get() + 1);
852        });
853
854        model.move_item(1, 1);
855        assert_eq!(count.get(), 0);
856    }
857
858    #[test]
859    fn replace_all_emits_reset() {
860        let model = ListModel::from_vec(vec![1, 2]);
861        let changes: Rc<RefCell<Vec<DataChange>>> = Rc::new(RefCell::new(Vec::new()));
862        let c = changes.clone();
863        let _handle = model.observe_changes(move |change| {
864            c.borrow_mut().push(change.clone());
865        });
866
867        model.replace_all(vec![10, 20, 30]);
868        assert_eq!(model.len(), 3);
869        let log = changes.borrow();
870        assert_eq!(log[0], DataChange::Reset);
871    }
872
873    #[test]
874    fn clear_emits_reset() {
875        let model = ListModel::from_vec(vec![1, 2, 3]);
876        let changes: Rc<RefCell<Vec<DataChange>>> = Rc::new(RefCell::new(Vec::new()));
877        let c = changes.clone();
878        let _handle = model.observe_changes(move |change| {
879            c.borrow_mut().push(change.clone());
880        });
881
882        model.clear();
883        assert!(model.is_empty());
884        let log = changes.borrow();
885        assert_eq!(log[0], DataChange::Reset);
886    }
887
888    #[test]
889    fn observer_removed_on_handle_drop() {
890        let model = ListModel::new();
891        let count = Rc::new(Cell::new(0));
892        let c = count.clone();
893        let handle = model.observe_changes(move |_| {
894            c.set(c.get() + 1);
895        });
896
897        model.push(1);
898        assert_eq!(count.get(), 1);
899
900        drop(handle);
901        model.push(2);
902        assert_eq!(count.get(), 1); // Not called again
903    }
904
905    #[test]
906    fn multiple_observers() {
907        let model = ListModel::new();
908        let count = Rc::new(Cell::new(0));
909        let c1 = count.clone();
910        let c2 = count.clone();
911        let _h1 = model.observe_changes(move |_| c1.set(c1.get() + 1));
912        let _h2 = model.observe_changes(move |_| c2.set(c2.get() + 1));
913
914        model.push(42);
915        assert_eq!(count.get(), 2);
916    }
917
918    #[test]
919    fn clone_shares_data() {
920        let model = ListModel::from_vec(vec![1, 2, 3]);
921        let clone = model.clone();
922
923        model.push(4);
924        assert_eq!(clone.len(), 4);
925        assert_eq!(clone.with_item(3, |v| *v), Some(4));
926    }
927
928    #[test]
929    fn clone_shares_observers() {
930        let model = ListModel::from_vec(vec![1, 2]);
931        let count = Rc::new(Cell::new(0));
932        let c = count.clone();
933        let _handle = model.observe_changes(move |_| c.set(c.get() + 1));
934
935        let clone = model.clone();
936        clone.push(3); // mutation on clone triggers observer registered on original
937        assert_eq!(count.get(), 1);
938    }
939
940    #[test]
941    fn with_item_out_of_bounds_returns_none() {
942        let model = ListModel::from_vec(vec![1, 2]);
943        assert_eq!(model.with_item(5, |v| *v), None);
944    }
945
946    #[test]
947    #[should_panic]
948    fn remove_out_of_bounds_panics() {
949        let model = ListModel::from_vec(vec![1]);
950        model.remove(5);
951    }
952
953    // ── ListDataSource capability protocol ──────────────────────────────
954
955    fn order<T: Clone>(model: &ListModel<T>) -> Vec<T> {
956        (0..model.len())
957            .map(|i| model.with_item(i, |v| v.clone()).unwrap())
958            .collect()
959    }
960
961    #[test]
962    fn list_source_accept_drop_after_reorders() {
963        // [a,b,c,d]; drag index 0 (a) After index 2 (c) → [b,c,a,d]
964        let model = ListModel::from_vec(vec!["a", "b", "c", "d"]);
965        assert!(model.accept_drop(DropCommit {
966            source: DragSource::SameView { key: 0 },
967            target: 2,
968            position: DropPosition::After,
969        }));
970        assert_eq!(order(&model), vec!["b", "c", "a", "d"]);
971    }
972
973    #[test]
974    fn list_source_accept_drop_before_reorders() {
975        // [a,b,c,d]; drag index 3 (d) Before index 1 (b) → [a,d,b,c]
976        let model = ListModel::from_vec(vec!["a", "b", "c", "d"]);
977        assert!(model.accept_drop(DropCommit {
978            source: DragSource::SameView { key: 3 },
979            target: 1,
980            position: DropPosition::Before,
981        }));
982        assert_eq!(order(&model), vec!["a", "d", "b", "c"]);
983    }
984
985    #[test]
986    fn list_source_can_accept_rejects_into_accepts_sibling() {
987        let model = ListModel::from_vec(vec![1, 2, 3]);
988        // A flat list does not nest → Into is forbidden.
989        assert_eq!(
990            model.can_accept(&DropQuery {
991                source: DragSource::SameView { key: 0 },
992                target: 1,
993                position: DropPosition::Into,
994            }),
995            DropResponse::Reject
996        );
997        // Sibling reorder is allowed.
998        assert_eq!(
999            model.can_accept(&DropQuery {
1000                source: DragSource::SameView { key: 0 },
1001                target: 1,
1002                position: DropPosition::After,
1003            }),
1004            DropResponse::Accept
1005        );
1006    }
1007
1008    #[test]
1009    fn list_source_key_is_positional_identity() {
1010        let model = ListModel::from_vec(vec![10, 20, 30]);
1011        assert_eq!(model.key_at(1), Some(1));
1012        assert_eq!(model.index_of(&2), Some(2));
1013        assert_eq!(model.key_at(5), None);
1014        assert_eq!(model.index_of(&9), None);
1015    }
1016
1017    fn snapshot<T: Clone>(model: &ListModel<T>) -> Vec<T> {
1018        (0..model.len())
1019            .filter_map(|i| model.with_item(i, |v| v.clone()))
1020            .collect()
1021    }
1022
1023    #[test]
1024    fn move_items_block_move_contiguous_and_ordered() {
1025        // Move a non-contiguous set {A(0), C(2), E(4)} to land at gap 3
1026        // (before the item originally at index 3, i.e. D).
1027        let model = ListModel::from_vec(vec!['A', 'B', 'C', 'D', 'E', 'F']);
1028        model.move_items(&[0, 2, 4], 3);
1029        // gap 3 = "before the original item at index 3" (D). Remove A,C,E →
1030        // [B,D,F]; two removed before the gap → insert the block before D.
1031        assert_eq!(snapshot(&model), vec!['B', 'A', 'C', 'E', 'D', 'F']);
1032    }
1033
1034    #[test]
1035    fn move_items_to_end() {
1036        let model = ListModel::from_vec(vec![1, 2, 3, 4]);
1037        model.move_items(&[0, 1], 4);
1038        assert_eq!(snapshot(&model), vec![3, 4, 1, 2]);
1039    }
1040
1041    #[test]
1042    fn move_items_ignores_out_of_range_and_dedups() {
1043        let model = ListModel::from_vec(vec![1, 2, 3]);
1044        model.move_items(&[1, 1, 9], 3);
1045        assert_eq!(snapshot(&model), vec![1, 3, 2]);
1046    }
1047
1048    #[test]
1049    fn move_items_single_matches_move_item() {
1050        let a = ListModel::from_vec(vec![1, 2, 3, 4, 5]);
1051        let b = ListModel::from_vec(vec![1, 2, 3, 4, 5]);
1052        // move_items([1], gap 4) == move a block of one from 1 to before-4.
1053        a.move_items(&[1], 4);
1054        // Equivalent single move: remove index 1, insert at post-removal index 3.
1055        b.move_item(1, 3);
1056        assert_eq!(snapshot(&a), snapshot(&b));
1057    }
1058
1059    #[test]
1060    fn reorder_within_multi_row_lands_contiguously() {
1061        // Exercise the ListModel `reorder_within` override (multi → block move).
1062        let model = ListModel::from_vec(vec![0, 1, 2, 3, 4, 5]);
1063        // Drag rows {0,1} to drop After index 4.
1064        assert!(model.reorder_within(&[0, 1], &4, DropPosition::After));
1065        assert_eq!(snapshot(&model), vec![2, 3, 4, 0, 1, 5]);
1066    }
1067
1068    #[test]
1069    fn reorder_within_single_row_uses_accept_drop() {
1070        let model = ListModel::from_vec(vec![10, 20, 30]);
1071        assert!(model.reorder_within(&[0], &2, DropPosition::After));
1072        assert_eq!(snapshot(&model), vec![20, 30, 10]);
1073    }
1074
1075    #[test]
1076    fn reorder_within_into_is_rejected_for_flat_list() {
1077        let model = ListModel::from_vec(vec![1, 2, 3]);
1078        assert!(!model.reorder_within(&[0, 1], &2, DropPosition::Into));
1079        assert_eq!(snapshot(&model), vec![1, 2, 3]);
1080    }
1081
1082    #[test]
1083    fn on_drag_out_removes_the_moved_row() {
1084        let model = ListModel::from_vec(vec!['a', 'b', 'c']);
1085        model.on_drag_out(&1);
1086        assert_eq!(snapshot(&model), vec!['a', 'c']);
1087    }
1088
1089    #[test]
1090    fn move_items_contiguous_emits_moved_non_contiguous_resets() {
1091        let model = ListModel::from_vec(vec![0, 1, 2, 3, 4]);
1092        let log: Rc<RefCell<Vec<DataChange>>> = Rc::new(RefCell::new(Vec::new()));
1093        let l = log.clone();
1094        let _h = model.observe_changes(move |c| l.borrow_mut().push(c.clone()));
1095        // Contiguous block → ItemsMoved (so index selection can follow).
1096        assert!(model.move_items(&[1, 2], 5));
1097        assert!(matches!(
1098            log.borrow().last(),
1099            Some(DataChange::ItemsMoved { .. })
1100        ));
1101        log.borrow_mut().clear();
1102        // Non-contiguous set → Reset.
1103        assert!(model.move_items(&[0, 2], 0));
1104        assert!(matches!(log.borrow().last(), Some(DataChange::Reset)));
1105    }
1106
1107    #[test]
1108    fn reorder_within_and_move_items_report_no_move_for_out_of_range() {
1109        let model = ListModel::from_vec(vec![1, 2, 3]);
1110        assert!(!model.reorder_within(&[99, 100], &0, DropPosition::Before));
1111        assert!(!model.move_items(&[99, 100], 0));
1112        assert_eq!(snapshot(&model), vec![1, 2, 3]);
1113    }
1114
1115    // ── reconcile_by_key ─────────────────────────────────────────────────
1116
1117    #[derive(Debug, Clone, PartialEq, Eq)]
1118    struct Row {
1119        id: u64,
1120        val: &'static str,
1121    }
1122
1123    fn row(id: u64, val: &'static str) -> Row {
1124        Row { id, val }
1125    }
1126
1127    fn key(r: &Row) -> u64 {
1128        r.id
1129    }
1130
1131    fn ids(model: &ListModel<Row>) -> Vec<u64> {
1132        (0..model.len())
1133            .map(|i| model.with_item(i, |r| r.id).unwrap())
1134            .collect()
1135    }
1136
1137    fn vals(model: &ListModel<Row>) -> Vec<&'static str> {
1138        (0..model.len())
1139            .map(|i| model.with_item(i, |r| r.val).unwrap())
1140            .collect()
1141    }
1142
1143    fn record_changes(model: &ListModel<Row>) -> (Rc<RefCell<Vec<DataChange>>>, ObserverHandle) {
1144        let log: Rc<RefCell<Vec<DataChange>>> = Rc::new(RefCell::new(Vec::new()));
1145        let l = log.clone();
1146        let handle = model.observe_changes(move |c| l.borrow_mut().push(c.clone()));
1147        (log, handle)
1148    }
1149
1150    #[test]
1151    fn reconcile_pure_insert_emits_one_coalesced_range() {
1152        let model = ListModel::from_vec(vec![row(1, "a"), row(2, "b")]);
1153        let (log, _h) = record_changes(&model);
1154
1155        model.reconcile_by_key(
1156            vec![row(1, "a"), row(2, "b"), row(3, "c"), row(4, "d")],
1157            key,
1158        );
1159
1160        assert_eq!(ids(&model), vec![1, 2, 3, 4]);
1161        assert_eq!(vals(&model), vec!["a", "b", "c", "d"]);
1162        let entries = log.borrow();
1163        assert_eq!(entries.len(), 1, "contiguous inserts coalesce: {entries:?}");
1164        assert_eq!(entries[0], DataChange::ItemsInserted { range: 2..4 });
1165    }
1166
1167    #[test]
1168    fn reconcile_insert_at_front_and_middle() {
1169        let model = ListModel::from_vec(vec![row(1, "a"), row(2, "b")]);
1170        let (log, _h) = record_changes(&model);
1171
1172        // 0 is new (front), 1 stays, 5 is new (middle), 2 stays.
1173        model.reconcile_by_key(
1174            vec![row(0, "z"), row(1, "a"), row(5, "m"), row(2, "b")],
1175            key,
1176        );
1177
1178        assert_eq!(ids(&model), vec![0, 1, 5, 2]);
1179        let entries = log.borrow();
1180        // Two non-adjacent insert runs, no move needed (1 and 2 already in
1181        // relative order).
1182        assert_eq!(entries.len(), 2, "{entries:?}");
1183        assert_eq!(entries[0], DataChange::ItemsInserted { range: 0..1 });
1184        assert_eq!(entries[1], DataChange::ItemsInserted { range: 2..3 });
1185    }
1186
1187    #[test]
1188    fn reconcile_pure_remove_emits_one_coalesced_range() {
1189        let model = ListModel::from_vec(vec![row(1, "a"), row(2, "b"), row(3, "c"), row(4, "d")]);
1190        let (log, _h) = record_changes(&model);
1191
1192        model.reconcile_by_key(vec![row(1, "a"), row(4, "d")], key);
1193
1194        assert_eq!(ids(&model), vec![1, 4]);
1195        let entries = log.borrow();
1196        assert_eq!(entries.len(), 1, "contiguous removes coalesce: {entries:?}");
1197        assert_eq!(entries[0], DataChange::ItemsRemoved { range: 1..3 });
1198    }
1199
1200    #[test]
1201    fn reconcile_remove_scattered_emits_separate_ranges() {
1202        let model = ListModel::from_vec(vec![row(1, "a"), row(2, "b"), row(3, "c"), row(4, "d")]);
1203        let (log, _h) = record_changes(&model);
1204
1205        model.reconcile_by_key(vec![row(1, "a"), row(3, "c")], key);
1206
1207        assert_eq!(ids(&model), vec![1, 3]);
1208        let entries = log.borrow();
1209        assert_eq!(entries.len(), 2, "{entries:?}");
1210        // Emitted back-to-front so earlier indices stay valid at removal time.
1211        assert_eq!(entries[0], DataChange::ItemsRemoved { range: 3..4 });
1212        assert_eq!(entries[1], DataChange::ItemsRemoved { range: 1..2 });
1213    }
1214
1215    #[test]
1216    fn reconcile_reorder_emits_only_moves() {
1217        let model = ListModel::from_vec(vec![row(1, "a"), row(2, "b"), row(3, "c")]);
1218        let (log, _h) = record_changes(&model);
1219
1220        model.reconcile_by_key(vec![row(3, "c"), row(2, "b"), row(1, "a")], key);
1221
1222        assert_eq!(ids(&model), vec![3, 2, 1]);
1223        let entries = log.borrow();
1224        assert!(
1225            entries
1226                .iter()
1227                .all(|c| matches!(c, DataChange::ItemsMoved { .. })),
1228            "a pure reorder must only emit moves: {entries:?}"
1229        );
1230        assert!(!entries.is_empty());
1231    }
1232
1233    #[test]
1234    fn reconcile_no_reorder_when_relative_order_already_matches() {
1235        // Peer removed the middle row but didn't touch the order of the rest —
1236        // this must NOT emit any ItemsMoved, only the removal.
1237        let model = ListModel::from_vec(vec![row(1, "a"), row(2, "b"), row(3, "c"), row(4, "d")]);
1238        let (log, _h) = record_changes(&model);
1239
1240        model.reconcile_by_key(vec![row(1, "a"), row(3, "c"), row(4, "d")], key);
1241
1242        assert_eq!(ids(&model), vec![1, 3, 4]);
1243        let entries = log.borrow();
1244        assert!(
1245            entries
1246                .iter()
1247                .all(|c| !matches!(c, DataChange::ItemsMoved { .. })),
1248            "untouched relative order must not emit moves: {entries:?}"
1249        );
1250    }
1251
1252    #[test]
1253    fn reconcile_in_place_update_emits_item_updated() {
1254        let model = ListModel::from_vec(vec![row(1, "a"), row(2, "b"), row(3, "c")]);
1255        let (log, _h) = record_changes(&model);
1256
1257        model.reconcile_by_key(vec![row(1, "a"), row(2, "CHANGED"), row(3, "c")], key);
1258
1259        assert_eq!(vals(&model), vec!["a", "CHANGED", "c"]);
1260        let entries = log.borrow();
1261        assert_eq!(entries.len(), 1, "{entries:?}");
1262        assert_eq!(entries[0], DataChange::ItemUpdated { index: 1 });
1263    }
1264
1265    #[test]
1266    fn reconcile_combined_insert_remove_reorder_update() {
1267        // old: [1,2,3,4] -> new: [4, 2*, 5, 1]
1268        //  - 3 removed
1269        //  - 4 moves to front
1270        //  - 2's content changes in place
1271        //  - 5 is inserted
1272        //  - 1 stays last (relative order of 1 vs 2 vs 4 reshuffled)
1273        let model = ListModel::from_vec(vec![row(1, "a"), row(2, "b"), row(3, "c"), row(4, "d")]);
1274        let (log, _h) = record_changes(&model);
1275
1276        model.reconcile_by_key(
1277            vec![row(4, "d"), row(2, "B!"), row(5, "e"), row(1, "a")],
1278            key,
1279        );
1280
1281        assert_eq!(ids(&model), vec![4, 2, 5, 1]);
1282        assert_eq!(vals(&model), vec!["d", "B!", "e", "a"]);
1283        let entries = log.borrow();
1284        assert!(!entries.is_empty());
1285        assert!(
1286            entries
1287                .iter()
1288                .any(|c| matches!(c, DataChange::ItemsMoved { .. })),
1289            "{entries:?}"
1290        );
1291        assert!(
1292            entries
1293                .iter()
1294                .any(|c| matches!(c, DataChange::ItemsInserted { .. })),
1295            "{entries:?}"
1296        );
1297        assert!(
1298            entries
1299                .iter()
1300                .any(|c| matches!(c, DataChange::ItemsRemoved { .. })),
1301            "{entries:?}"
1302        );
1303        assert!(
1304            entries
1305                .iter()
1306                .any(|c| matches!(c, DataChange::ItemUpdated { .. })),
1307            "{entries:?}"
1308        );
1309        assert!(
1310            !entries.iter().any(|c| matches!(c, DataChange::Reset)),
1311            "{entries:?}"
1312        );
1313    }
1314
1315    #[test]
1316    fn reconcile_emits_in_walk_order_with_sequential_indices() {
1317        // Update then insert, interleaved in walk order (not grouped by kind).
1318        let model = ListModel::from_vec(vec![row(1, "a"), row(2, "b")]);
1319        let (log, _h) = record_changes(&model);
1320        model.reconcile_by_key(vec![row(1, "a"), row(2, "B"), row(3, "c")], key);
1321        assert_eq!(
1322            *log.borrow(),
1323            vec![
1324                DataChange::ItemUpdated { index: 1 },
1325                DataChange::ItemsInserted { range: 2..3 },
1326            ]
1327        );
1328
1329        // Remove first (old indices), then per survivor: move, update, with a
1330        // pending insert flushed ahead of the next survivor.
1331        // old [1,2,3,4] -> new [4, 9(new), 2*, 1]
1332        let model = ListModel::from_vec(vec![row(1, "a"), row(2, "b"), row(3, "c"), row(4, "d")]);
1333        let (log, _h) = record_changes(&model);
1334        model.reconcile_by_key(
1335            vec![row(4, "d"), row(9, "n"), row(2, "B"), row(1, "a")],
1336            key,
1337        );
1338        assert_eq!(ids(&model), vec![4, 9, 2, 1]);
1339        assert_eq!(
1340            *log.borrow(),
1341            vec![
1342                // 3 leaves: [1,2,4]
1343                DataChange::ItemsRemoved { range: 2..3 },
1344                // 4 walks to slot 0: [4,1,2]
1345                DataChange::ItemsMoved {
1346                    from: 2,
1347                    to: 0,
1348                    count: 1
1349                },
1350                // 9 is flushed before the next survivor: [4,9,1,2]
1351                DataChange::ItemsInserted { range: 1..2 },
1352                // 2 walks to slot 2: [4,9,2,1]
1353                DataChange::ItemsMoved {
1354                    from: 3,
1355                    to: 2,
1356                    count: 1
1357                },
1358                DataChange::ItemUpdated { index: 2 },
1359            ]
1360        );
1361    }
1362
1363    #[test]
1364    fn reconcile_empty_to_full() {
1365        let model: ListModel<Row> = ListModel::new();
1366        let (log, _h) = record_changes(&model);
1367
1368        model.reconcile_by_key(vec![row(1, "a"), row(2, "b"), row(3, "c")], key);
1369
1370        assert_eq!(ids(&model), vec![1, 2, 3]);
1371        let entries = log.borrow();
1372        assert_eq!(entries.len(), 1, "{entries:?}");
1373        assert_eq!(entries[0], DataChange::ItemsInserted { range: 0..3 });
1374    }
1375
1376    #[test]
1377    fn reconcile_full_to_empty() {
1378        let model = ListModel::from_vec(vec![row(1, "a"), row(2, "b"), row(3, "c")]);
1379        let (log, _h) = record_changes(&model);
1380
1381        model.reconcile_by_key(vec![], key);
1382
1383        assert!(model.is_empty());
1384        let entries = log.borrow();
1385        assert_eq!(entries.len(), 1, "{entries:?}");
1386        assert_eq!(entries[0], DataChange::ItemsRemoved { range: 0..3 });
1387    }
1388
1389    #[test]
1390    fn reconcile_identical_input_emits_nothing() {
1391        let model = ListModel::from_vec(vec![row(1, "a"), row(2, "b"), row(3, "c")]);
1392        let (log, _h) = record_changes(&model);
1393
1394        model.reconcile_by_key(vec![row(1, "a"), row(2, "b"), row(3, "c")], key);
1395
1396        assert_eq!(ids(&model), vec![1, 2, 3]);
1397        assert!(
1398            log.borrow().is_empty(),
1399            "identical reconcile must not notify: {:?}",
1400            log.borrow()
1401        );
1402    }
1403
1404    #[test]
1405    fn reconcile_never_emits_reset() {
1406        // Exercise every scenario above (plus a full rewrite / total
1407        // replacement, the case most tempted to fall back to `Reset`) and
1408        // assert `Reset` is never among the emitted changes.
1409        let scenarios: Vec<(Vec<Row>, Vec<Row>)> = vec![
1410            (
1411                vec![row(1, "a"), row(2, "b")],
1412                vec![row(1, "a"), row(2, "b"), row(3, "c")],
1413            ),
1414            (
1415                vec![row(1, "a"), row(2, "b"), row(3, "c")],
1416                vec![row(1, "a")],
1417            ),
1418            (
1419                vec![row(1, "a"), row(2, "b"), row(3, "c")],
1420                vec![row(3, "c"), row(1, "a"), row(2, "b")],
1421            ),
1422            (vec![], vec![row(1, "a"), row(2, "b")]),
1423            (vec![row(1, "a"), row(2, "b")], vec![]),
1424            (
1425                vec![row(1, "a"), row(2, "b"), row(3, "c"), row(4, "d")],
1426                vec![row(9, "x"), row(8, "y"), row(7, "z")],
1427            ),
1428        ];
1429        for (before, after) in scenarios {
1430            let model = ListModel::from_vec(before.clone());
1431            let (log, _h) = record_changes(&model);
1432            model.reconcile_by_key(after.clone(), key);
1433            assert!(
1434                !log.borrow().iter().any(|c| matches!(c, DataChange::Reset)),
1435                "reconcile must never emit Reset — before {before:?}, after {after:?}, got {:?}",
1436                log.borrow()
1437            );
1438        }
1439    }
1440
1441    #[test]
1442    #[should_panic(expected = "reconcile_by_key")]
1443    fn reconcile_duplicate_key_in_new_items_panics() {
1444        let model = ListModel::from_vec(vec![row(1, "a"), row(2, "b")]);
1445        // Two incoming rows both claim key 1 — the second can't be found at
1446        // or after the write cursor once the first has already consumed
1447        // that key's slot (see `# Panics` on `reconcile_by_key`).
1448        model.reconcile_by_key(vec![row(1, "a"), row(1, "a-dup"), row(2, "b")], key);
1449    }
1450}