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                inner.borrow_mut().observers.retain(|e| e.id != observer_id);
295            }),
296        )
297    }
298
299    fn notify(&self, change: DataChange) {
300        let callbacks: Vec<Rc<dyn Fn(&DataChange)>> = self
301            .inner
302            .borrow()
303            .observers
304            .iter()
305            .map(|e| e.callback.clone())
306            .collect();
307        for cb in &callbacks {
308            cb(&change);
309        }
310    }
311}
312
313impl<T: PartialEq + 'static> ListModel<T> {
314    /// Reconcile the list's contents with `new_items`, matching old and new
315    /// rows **by key** (`key_fn`) instead of wholesale-replacing them, and
316    /// emitting the minimal set of granular [`DataChange`]s needed to reach
317    /// that state — never [`DataChange::Reset`].
318    ///
319    /// This is the primitive a live view needs when a peer process (or any
320    /// other out-of-band writer) reloads a backing file and the merged
321    /// result must land in a `ListModel` that a `ListView` is *currently
322    /// displaying*, without wiping the user's selection or keyboard focus
323    /// mid-interaction. `replace_all`/`clear` always emit `Reset`, and a
324    /// `Reset` unconditionally clears a positional `SelectionModel`
325    /// (`RowSelection::from_index`) — `reconcile_by_key` is how a caller
326    /// avoids that.
327    ///
328    /// Emits, in this order, coalescing contiguous runs into a single event
329    /// each:
330    /// - [`DataChange::ItemsRemoved`] for keys present in the old list but
331    ///   absent from `new_items`;
332    /// - [`DataChange::ItemsMoved`] (single-row blocks) to re-order the
333    ///   surviving rows into `new_items`'s relative order — skipped
334    ///   entirely for rows already in the right place, so an append-only or
335    ///   remove-only reload emits **no** moves at all;
336    /// - [`DataChange::ItemsInserted`] for keys present in `new_items` but
337    ///   not in the old list;
338    /// - [`DataChange::ItemUpdated`] for a row whose key is unchanged but
339    ///   whose content differs (`T: PartialEq`) — the row's stored value is
340    ///   replaced with the incoming one.
341    ///
342    /// If `new_items` is identical (same keys, same order, same content, by
343    /// `PartialEq`) to the current contents, **no** change is emitted and no
344    /// observer runs — reconciling with unchanged data is silent.
345    ///
346    /// # Preconditions
347    /// `key_fn` must be a pure, stable function of an item's identity (not
348    /// its content) and keys must be **unique** within both the current list
349    /// and `new_items`. See `# Panics` below — an unstable `key_fn` or a
350    /// duplicate within `new_items` panics; a duplicate within the current
351    /// list is silently tolerated and leaves the extra copies behind, which
352    /// is worse.
353    ///
354    /// # Panics
355    /// Panics (via an internal `.expect`) if `key_fn` is not stable — it
356    /// returns a different key for the same item across the two calls this
357    /// method makes to it (once while snapshotting the current list's keys,
358    /// once while re-deriving a key during the write pass) — or if a key is
359    /// **duplicated** within the current list or within `new_items`. Both
360    /// break the same invariant the write pass relies on: "the item that
361    /// was accounted for under this key is still findable at or after the
362    /// write cursor." A duplicate key means two different items raced to
363    /// claim one key slot, so by the time the second one is processed the
364    /// slot the accounting expected is already gone. This is this crate's
365    /// usual documented-panic-on-contract-violation style (see e.g.
366    /// [`TreeModel::remove`](crate::TreeModel::remove)) — a caller-side bug
367    /// surfaced immediately as a panic, not silently wrong data.
368    ///
369    /// # Complexity
370    /// Re-ordering is a straightforward left-to-right pass that moves each
371    /// out-of-place survivor into its target slot; it is correct and always
372    /// granular, but is not guaranteed to emit the mathematically fewest
373    /// possible `ItemsMoved` events for an adversarial permutation (an
374    /// LIS-based scheme could do slightly better there). For the common
375    /// case this primitive targets — a peer append/remove/edit merged back
376    /// in — the existing relative order of untouched rows is preserved
377    /// as-is, so no moves are emitted at all.
378    pub fn reconcile_by_key<K: Eq + Hash>(&self, new_items: Vec<T>, key_fn: impl Fn(&T) -> K) {
379        let mut changes: Vec<DataChange> = Vec::new();
380        {
381            let mut guard = self.inner.borrow_mut();
382            reconcile_vec(&mut guard.items, new_items, &key_fn, &mut changes);
383        }
384        for change in changes {
385            self.notify(change);
386        }
387    }
388}
389
390/// Diff `items` (current contents) against `new_items` by key, mutating
391/// `items` in place to match `new_items` exactly and pushing one
392/// [`DataChange`] per atomic step taken. Kept as a free function (rather
393/// than inlined into `reconcile_by_key`) so it can be exercised directly —
394/// and so it operates on the bare `Vec<T>` while the caller still holds the
395/// `RefCell` borrow, before any observer notification fires.
396fn reconcile_vec<T: PartialEq, K: Eq + Hash>(
397    items: &mut Vec<T>,
398    new_items: Vec<T>,
399    key_fn: &impl Fn(&T) -> K,
400    out: &mut Vec<DataChange>,
401) {
402    // Pair every incoming item with its key up front: we need the key
403    // before we decide anything, and this avoids re-deriving ownership of
404    // the item later.
405    let new_pairs: Vec<(K, T)> = new_items.into_iter().map(|it| (key_fn(&it), it)).collect();
406    let new_key_set: HashSet<&K> = new_pairs.iter().map(|(k, _)| k).collect();
407
408    // ---- Phase 1: drop old items whose key no longer exists in the
409    // incoming list. Computed against a pre-removal key snapshot so later
410    // removals don't perturb earlier indices; applied back-to-front so
411    // each removed range's indices stay valid at the point it's removed. ----
412    let old_keys: Vec<K> = items.iter().map(key_fn).collect();
413    let remove_idxs: Vec<usize> = (0..items.len())
414        .filter(|&i| !new_key_set.contains(&old_keys[i]))
415        .collect();
416    for range in coalesce_ranges(&remove_idxs).into_iter().rev() {
417        items.drain(range.clone());
418        out.push(DataChange::ItemsRemoved { range });
419    }
420
421    // From here on, `items` holds exactly the surviving ("common") rows, in
422    // their original relative order.
423    let remaining_keys: HashSet<K> = items.iter().map(key_fn).collect();
424
425    // ---- Phase 2/3: walk the target order left to right. A common key is
426    // moved into place (if it isn't already there) and its content updated
427    // in place if it changed; a brand-new key is buffered and flushed as a
428    // single contiguous `ItemsInserted` run as soon as a common key (or the
429    // end of the list) is reached. ----
430    let mut cursor = 0usize;
431    let mut pending_inserts: Vec<T> = Vec::new();
432
433    for (key, new_item) in new_pairs {
434        if remaining_keys.contains(&key) {
435            flush_inserts(items, &mut cursor, &mut pending_inserts, out);
436
437            // Invariant: items[0..cursor] already matches the target
438            // prefix, so this key — being common and not yet placed — must
439            // sit somewhere at or after `cursor`.
440            let pos = items
441                .iter()
442                .skip(cursor)
443                .position(|it| key_fn(it) == key)
444                .expect(
445                    "reconcile_by_key: key reported common but not found — \
446                     key_fn must be stable and keys unique",
447                );
448            let actual = cursor + pos;
449            if actual != cursor {
450                let val = items.remove(actual);
451                items.insert(cursor, val);
452                out.push(DataChange::ItemsMoved {
453                    from: actual,
454                    to: cursor,
455                    count: 1,
456                });
457            }
458            if items[cursor] != new_item {
459                items[cursor] = new_item;
460                out.push(DataChange::ItemUpdated { index: cursor });
461            }
462            cursor += 1;
463        } else {
464            pending_inserts.push(new_item);
465        }
466    }
467    flush_inserts(items, &mut cursor, &mut pending_inserts, out);
468}
469
470/// Splice any buffered new rows into `items` at `*cursor` as one contiguous
471/// block, emit the single `ItemsInserted` covering them, and advance the
472/// cursor past them. No-op (no event) if nothing is pending.
473fn flush_inserts<T>(
474    items: &mut Vec<T>,
475    cursor: &mut usize,
476    pending: &mut Vec<T>,
477    out: &mut Vec<DataChange>,
478) {
479    if pending.is_empty() {
480        return;
481    }
482    let start = *cursor;
483    let n = pending.len();
484    items.splice(start..start, pending.drain(..));
485    out.push(DataChange::ItemsInserted {
486        range: start..start + n,
487    });
488    *cursor += n;
489}
490
491/// Group a sorted, deduplicated slice of indices into maximal contiguous
492/// ranges, e.g. `[1, 2, 3, 7, 8]` → `[1..4, 7..9]`.
493fn coalesce_ranges(sorted_idxs: &[usize]) -> Vec<Range<usize>> {
494    let mut ranges = Vec::new();
495    let mut iter = sorted_idxs.iter().peekable();
496    while let Some(&start) = iter.next() {
497        let mut end = start + 1;
498        while iter.peek().is_some_and(|&&n| n == end) {
499            end += 1;
500            iter.next();
501        }
502        ranges.push(start..end);
503    }
504    ranges
505}
506
507impl<T: std::fmt::Debug + 'static> ListModel<T> {
508    /// Register this model with the debug inspector under `name`. In
509    /// release builds (`!cfg(debug_assertions)`) this is a no-op
510    /// pass-through so call sites stay free of `#[cfg]` lines.
511    ///
512    /// Idempotent on repeated calls — the latest registration wins.
513    /// The registration drops automatically when the last `ListModel`
514    /// handle is freed (the adapter the registry holds is `Weak`).
515    pub fn debug_named(self, _name: impl Into<String>) -> Self {
516        #[cfg(debug_assertions)]
517        {
518            let weak = Rc::downgrade(&self.inner);
519            let adapter: Rc<dyn crate::debug_registry::ModelDebug> =
520                Rc::new(ListModelDebug::<T> { weak });
521            let name = _name.into();
522            crate::debug_registry::register(name, Rc::downgrade(&adapter));
523            self.inner.borrow_mut().debug_adapter = Some(adapter);
524        }
525        self
526    }
527}
528
529#[cfg(debug_assertions)]
530struct ListModelDebug<T> {
531    weak: std::rc::Weak<RefCell<ListModelInner<T>>>,
532}
533
534#[cfg(debug_assertions)]
535impl<T: std::fmt::Debug + 'static> crate::debug_registry::ModelDebug for ListModelDebug<T> {
536    fn kind(&self) -> &'static str {
537        "ListModel"
538    }
539    fn len(&self) -> usize {
540        self.weak
541            .upgrade()
542            .map(|inner| inner.borrow().items.len())
543            .unwrap_or(0)
544    }
545    fn debug_dump(&self, out: &mut dyn std::fmt::Write) {
546        let Some(inner) = self.weak.upgrade() else {
547            return;
548        };
549        let guard = inner.borrow();
550        for (i, item) in guard.items.iter().enumerate() {
551            let _ = writeln!(out, "[{}] {:?}", i, item);
552        }
553    }
554}
555
556impl<T: 'static> Default for ListModel<T> {
557    fn default() -> Self {
558        Self::new()
559    }
560}
561
562impl<T: 'static> Clone for ListModel<T> {
563    fn clone(&self) -> Self {
564        Self {
565            inner: self.inner.clone(),
566        }
567    }
568}
569
570impl<T: std::fmt::Debug + 'static> std::fmt::Debug for ListModel<T> {
571    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
572        f.debug_struct("ListModel")
573            .field("len", &self.inner.borrow().items.len())
574            .finish()
575    }
576}
577
578/// `ListModel` is the built-in fully-resident, in-memory `ListDataSource`.
579/// Identity is positional (`Key = usize`); a `SameView` drop reorders via
580/// `move_item`. `Into` and `Foreign` drops are rejected (a flat list does not
581/// nest, and a bare model knows no foreign payloads).
582impl<T: 'static> ListDataSource for ListModel<T> {
583    type Item = T;
584    type Key = usize;
585
586    fn len(&self) -> usize {
587        ListModel::len(self)
588    }
589
590    fn with_item<R>(&self, index: usize, f: impl FnOnce(&T) -> R) -> Option<R> {
591        ListModel::with_item(self, index, f)
592    }
593
594    fn key_at(&self, index: usize) -> Option<usize> {
595        (index < ListModel::len(self)).then_some(index)
596    }
597
598    fn index_of(&self, key: &usize) -> Option<usize> {
599        (*key < ListModel::len(self)).then_some(*key)
600    }
601
602    fn observe_changes(&self, f: impl Fn(&DataChange) + 'static) -> ObserverHandle {
603        ListModel::observe_changes(self, f)
604    }
605
606    fn drag(&self, _key: &usize) -> DragEligibility {
607        DragEligibility::CanDrag
608    }
609
610    fn can_accept(&self, query: &DropQuery<'_, usize>) -> DropResponse {
611        match &query.source {
612            DragSource::SameView { .. } => match query.position {
613                DropPosition::Into => DropResponse::Reject,
614                DropPosition::Before | DropPosition::After => DropResponse::Accept,
615            },
616            DragSource::Foreign { .. } => DropResponse::Reject,
617        }
618    }
619
620    fn accept_drop(&self, commit: DropCommit<'_, usize>) -> bool {
621        let DragSource::SameView { key: from } = commit.source else {
622            return false;
623        };
624        let len = ListModel::len(self);
625        if from >= len {
626            return false;
627        }
628        let target = commit.target;
629        // move_item removes `from` before inserting, so an insertion point above
630        // the source's old slot shifts down by one.
631        let shift = if from < target { 1 } else { 0 };
632        let to = match commit.position {
633            DropPosition::Before => target.saturating_sub(shift),
634            DropPosition::After => (target + 1).saturating_sub(shift),
635            DropPosition::Into => return false,
636        };
637        let to = to.min(len.saturating_sub(1));
638        self.move_item(from, to);
639        true
640    }
641
642    fn reorder_within(&self, sources: &[usize], target: &usize, position: DropPosition) -> bool {
643        // A `ListModel`'s key IS the index, so the stable-key default (which
644        // re-anchors on a just-moved key) would corrupt after the first move —
645        // route the multi-row case through the index-safe block move instead.
646        // A single row keeps the finer-grained `accept_drop`/`move_item` path.
647        if sources.len() <= 1 {
648            let Some(&from) = sources.first() else {
649                return false;
650            };
651            return self.accept_drop(DropCommit {
652                source: DragSource::SameView { key: from },
653                target: *target,
654                position,
655            });
656        }
657        let gap = match position {
658            DropPosition::Before => *target,
659            DropPosition::After => *target + 1,
660            DropPosition::Into => return false,
661        };
662        self.move_items(sources, gap)
663    }
664
665    fn on_drag_out(&self, key: &usize) {
666        // Source-side completion for a foreign move: drop the row that was
667        // accepted elsewhere. Callers remove in descending index order so
668        // earlier keys stay valid across a multi-row transfer.
669        if *key < ListModel::len(self) {
670            let _ = self.remove(*key);
671        }
672    }
673}
674
675#[cfg(test)]
676mod tests {
677    use std::cell::Cell;
678
679    use super::*;
680
681    #[test]
682    fn new_is_empty() {
683        let model: ListModel<String> = ListModel::new();
684        assert!(model.is_empty());
685        assert_eq!(model.len(), 0);
686    }
687
688    #[test]
689    fn from_vec() {
690        let model = ListModel::from_vec(vec![10, 20, 30]);
691        assert_eq!(model.len(), 3);
692        assert_eq!(model.with_item(1, |v| *v), Some(20));
693    }
694
695    #[test]
696    fn push_emits_inserted() {
697        let model = ListModel::new();
698        let changes: Rc<RefCell<Vec<DataChange>>> = Rc::new(RefCell::new(Vec::new()));
699        let c = changes.clone();
700        let _handle = model.observe_changes(move |change| {
701            c.borrow_mut().push(change.clone());
702        });
703
704        model.push("a");
705        model.push("b");
706
707        let log = changes.borrow();
708        assert_eq!(log.len(), 2);
709        assert_eq!(log[0], DataChange::ItemsInserted { range: 0..1 });
710        assert_eq!(log[1], DataChange::ItemsInserted { range: 1..2 });
711    }
712
713    #[test]
714    fn insert_emits_inserted() {
715        let model = ListModel::from_vec(vec![1, 2, 3]);
716        let changes: Rc<RefCell<Vec<DataChange>>> = Rc::new(RefCell::new(Vec::new()));
717        let c = changes.clone();
718        let _handle = model.observe_changes(move |change| {
719            c.borrow_mut().push(change.clone());
720        });
721
722        model.insert(1, 99);
723
724        assert_eq!(model.len(), 4);
725        assert_eq!(model.with_item(1, |v| *v), Some(99));
726        let log = changes.borrow();
727        assert_eq!(log.len(), 1, "insert should emit exactly one change");
728        assert_eq!(log[0], DataChange::ItemsInserted { range: 1..2 });
729    }
730
731    #[test]
732    fn remove_emits_removed() {
733        let model = ListModel::from_vec(vec!["a", "b", "c"]);
734        let changes: Rc<RefCell<Vec<DataChange>>> = Rc::new(RefCell::new(Vec::new()));
735        let c = changes.clone();
736        let _handle = model.observe_changes(move |change| {
737            c.borrow_mut().push(change.clone());
738        });
739
740        let removed = model.remove(1);
741        assert_eq!(removed, "b");
742        assert_eq!(model.len(), 2);
743        let log = changes.borrow();
744        assert_eq!(log.len(), 1, "remove should emit exactly one change");
745        assert_eq!(log[0], DataChange::ItemsRemoved { range: 1..2 });
746    }
747
748    #[test]
749    fn set_emits_updated() {
750        let model = ListModel::from_vec(vec![10, 20, 30]);
751        let changes: Rc<RefCell<Vec<DataChange>>> = Rc::new(RefCell::new(Vec::new()));
752        let c = changes.clone();
753        let _handle = model.observe_changes(move |change| {
754            c.borrow_mut().push(change.clone());
755        });
756
757        model.set(2, 99);
758        assert_eq!(model.with_item(2, |v| *v), Some(99));
759        let log = changes.borrow();
760        assert_eq!(log.len(), 1, "set should emit exactly one change");
761        assert_eq!(log[0], DataChange::ItemUpdated { index: 2 });
762    }
763
764    #[test]
765    fn move_item_emits_moved() {
766        let model = ListModel::from_vec(vec!["a", "b", "c", "d"]);
767        let changes: Rc<RefCell<Vec<DataChange>>> = Rc::new(RefCell::new(Vec::new()));
768        let c = changes.clone();
769        let _handle = model.observe_changes(move |change| {
770            c.borrow_mut().push(change.clone());
771        });
772
773        model.move_item(0, 2);
774        // After: ["b", "c", "a", "d"]
775        assert_eq!(model.with_item(0, |v| *v), Some("b"));
776        assert_eq!(model.with_item(2, |v| *v), Some("a"));
777        let log = changes.borrow();
778        assert_eq!(log.len(), 1, "move_item should emit exactly one change");
779        assert_eq!(
780            log[0],
781            DataChange::ItemsMoved {
782                from: 0,
783                to: 2,
784                count: 1
785            }
786        );
787    }
788
789    #[test]
790    fn move_item_same_index_is_noop() {
791        let model = ListModel::from_vec(vec![1, 2, 3]);
792        let count = Rc::new(Cell::new(0));
793        let c = count.clone();
794        let _handle = model.observe_changes(move |_| {
795            c.set(c.get() + 1);
796        });
797
798        model.move_item(1, 1);
799        assert_eq!(count.get(), 0);
800    }
801
802    #[test]
803    fn replace_all_emits_reset() {
804        let model = ListModel::from_vec(vec![1, 2]);
805        let changes: Rc<RefCell<Vec<DataChange>>> = Rc::new(RefCell::new(Vec::new()));
806        let c = changes.clone();
807        let _handle = model.observe_changes(move |change| {
808            c.borrow_mut().push(change.clone());
809        });
810
811        model.replace_all(vec![10, 20, 30]);
812        assert_eq!(model.len(), 3);
813        let log = changes.borrow();
814        assert_eq!(log[0], DataChange::Reset);
815    }
816
817    #[test]
818    fn clear_emits_reset() {
819        let model = ListModel::from_vec(vec![1, 2, 3]);
820        let changes: Rc<RefCell<Vec<DataChange>>> = Rc::new(RefCell::new(Vec::new()));
821        let c = changes.clone();
822        let _handle = model.observe_changes(move |change| {
823            c.borrow_mut().push(change.clone());
824        });
825
826        model.clear();
827        assert!(model.is_empty());
828        let log = changes.borrow();
829        assert_eq!(log[0], DataChange::Reset);
830    }
831
832    #[test]
833    fn observer_removed_on_handle_drop() {
834        let model = ListModel::new();
835        let count = Rc::new(Cell::new(0));
836        let c = count.clone();
837        let handle = model.observe_changes(move |_| {
838            c.set(c.get() + 1);
839        });
840
841        model.push(1);
842        assert_eq!(count.get(), 1);
843
844        drop(handle);
845        model.push(2);
846        assert_eq!(count.get(), 1); // Not called again
847    }
848
849    #[test]
850    fn multiple_observers() {
851        let model = ListModel::new();
852        let count = Rc::new(Cell::new(0));
853        let c1 = count.clone();
854        let c2 = count.clone();
855        let _h1 = model.observe_changes(move |_| c1.set(c1.get() + 1));
856        let _h2 = model.observe_changes(move |_| c2.set(c2.get() + 1));
857
858        model.push(42);
859        assert_eq!(count.get(), 2);
860    }
861
862    #[test]
863    fn clone_shares_data() {
864        let model = ListModel::from_vec(vec![1, 2, 3]);
865        let clone = model.clone();
866
867        model.push(4);
868        assert_eq!(clone.len(), 4);
869        assert_eq!(clone.with_item(3, |v| *v), Some(4));
870    }
871
872    #[test]
873    fn clone_shares_observers() {
874        let model = ListModel::from_vec(vec![1, 2]);
875        let count = Rc::new(Cell::new(0));
876        let c = count.clone();
877        let _handle = model.observe_changes(move |_| c.set(c.get() + 1));
878
879        let clone = model.clone();
880        clone.push(3); // mutation on clone triggers observer registered on original
881        assert_eq!(count.get(), 1);
882    }
883
884    #[test]
885    fn with_item_out_of_bounds_returns_none() {
886        let model = ListModel::from_vec(vec![1, 2]);
887        assert_eq!(model.with_item(5, |v| *v), None);
888    }
889
890    #[test]
891    #[should_panic]
892    fn remove_out_of_bounds_panics() {
893        let model = ListModel::from_vec(vec![1]);
894        model.remove(5);
895    }
896
897    // ── ListDataSource capability protocol ──────────────────────────────
898
899    fn order<T: Clone>(model: &ListModel<T>) -> Vec<T> {
900        (0..model.len())
901            .map(|i| model.with_item(i, |v| v.clone()).unwrap())
902            .collect()
903    }
904
905    #[test]
906    fn list_source_accept_drop_after_reorders() {
907        // [a,b,c,d]; drag index 0 (a) After index 2 (c) → [b,c,a,d]
908        let model = ListModel::from_vec(vec!["a", "b", "c", "d"]);
909        assert!(model.accept_drop(DropCommit {
910            source: DragSource::SameView { key: 0 },
911            target: 2,
912            position: DropPosition::After,
913        }));
914        assert_eq!(order(&model), vec!["b", "c", "a", "d"]);
915    }
916
917    #[test]
918    fn list_source_accept_drop_before_reorders() {
919        // [a,b,c,d]; drag index 3 (d) Before index 1 (b) → [a,d,b,c]
920        let model = ListModel::from_vec(vec!["a", "b", "c", "d"]);
921        assert!(model.accept_drop(DropCommit {
922            source: DragSource::SameView { key: 3 },
923            target: 1,
924            position: DropPosition::Before,
925        }));
926        assert_eq!(order(&model), vec!["a", "d", "b", "c"]);
927    }
928
929    #[test]
930    fn list_source_can_accept_rejects_into_accepts_sibling() {
931        let model = ListModel::from_vec(vec![1, 2, 3]);
932        // A flat list does not nest → Into is forbidden.
933        assert_eq!(
934            model.can_accept(&DropQuery {
935                source: DragSource::SameView { key: 0 },
936                target: 1,
937                position: DropPosition::Into,
938            }),
939            DropResponse::Reject
940        );
941        // Sibling reorder is allowed.
942        assert_eq!(
943            model.can_accept(&DropQuery {
944                source: DragSource::SameView { key: 0 },
945                target: 1,
946                position: DropPosition::After,
947            }),
948            DropResponse::Accept
949        );
950    }
951
952    #[test]
953    fn list_source_key_is_positional_identity() {
954        let model = ListModel::from_vec(vec![10, 20, 30]);
955        assert_eq!(model.key_at(1), Some(1));
956        assert_eq!(model.index_of(&2), Some(2));
957        assert_eq!(model.key_at(5), None);
958        assert_eq!(model.index_of(&9), None);
959    }
960
961    fn snapshot<T: Clone>(model: &ListModel<T>) -> Vec<T> {
962        (0..model.len())
963            .filter_map(|i| model.with_item(i, |v| v.clone()))
964            .collect()
965    }
966
967    #[test]
968    fn move_items_block_move_contiguous_and_ordered() {
969        // Move a non-contiguous set {A(0), C(2), E(4)} to land at gap 3
970        // (before the item originally at index 3, i.e. D).
971        let model = ListModel::from_vec(vec!['A', 'B', 'C', 'D', 'E', 'F']);
972        model.move_items(&[0, 2, 4], 3);
973        // gap 3 = "before the original item at index 3" (D). Remove A,C,E →
974        // [B,D,F]; two removed before the gap → insert the block before D.
975        assert_eq!(snapshot(&model), vec!['B', 'A', 'C', 'E', 'D', 'F']);
976    }
977
978    #[test]
979    fn move_items_to_end() {
980        let model = ListModel::from_vec(vec![1, 2, 3, 4]);
981        model.move_items(&[0, 1], 4);
982        assert_eq!(snapshot(&model), vec![3, 4, 1, 2]);
983    }
984
985    #[test]
986    fn move_items_ignores_out_of_range_and_dedups() {
987        let model = ListModel::from_vec(vec![1, 2, 3]);
988        model.move_items(&[1, 1, 9], 3);
989        assert_eq!(snapshot(&model), vec![1, 3, 2]);
990    }
991
992    #[test]
993    fn move_items_single_matches_move_item() {
994        let a = ListModel::from_vec(vec![1, 2, 3, 4, 5]);
995        let b = ListModel::from_vec(vec![1, 2, 3, 4, 5]);
996        // move_items([1], gap 4) == move a block of one from 1 to before-4.
997        a.move_items(&[1], 4);
998        // Equivalent single move: remove index 1, insert at post-removal index 3.
999        b.move_item(1, 3);
1000        assert_eq!(snapshot(&a), snapshot(&b));
1001    }
1002
1003    #[test]
1004    fn reorder_within_multi_row_lands_contiguously() {
1005        // Exercise the ListModel `reorder_within` override (multi → block move).
1006        let model = ListModel::from_vec(vec![0, 1, 2, 3, 4, 5]);
1007        // Drag rows {0,1} to drop After index 4.
1008        assert!(model.reorder_within(&[0, 1], &4, DropPosition::After));
1009        assert_eq!(snapshot(&model), vec![2, 3, 4, 0, 1, 5]);
1010    }
1011
1012    #[test]
1013    fn reorder_within_single_row_uses_accept_drop() {
1014        let model = ListModel::from_vec(vec![10, 20, 30]);
1015        assert!(model.reorder_within(&[0], &2, DropPosition::After));
1016        assert_eq!(snapshot(&model), vec![20, 30, 10]);
1017    }
1018
1019    #[test]
1020    fn reorder_within_into_is_rejected_for_flat_list() {
1021        let model = ListModel::from_vec(vec![1, 2, 3]);
1022        assert!(!model.reorder_within(&[0, 1], &2, DropPosition::Into));
1023        assert_eq!(snapshot(&model), vec![1, 2, 3]);
1024    }
1025
1026    #[test]
1027    fn on_drag_out_removes_the_moved_row() {
1028        let model = ListModel::from_vec(vec!['a', 'b', 'c']);
1029        model.on_drag_out(&1);
1030        assert_eq!(snapshot(&model), vec!['a', 'c']);
1031    }
1032
1033    #[test]
1034    fn move_items_contiguous_emits_moved_non_contiguous_resets() {
1035        let model = ListModel::from_vec(vec![0, 1, 2, 3, 4]);
1036        let log: Rc<RefCell<Vec<DataChange>>> = Rc::new(RefCell::new(Vec::new()));
1037        let l = log.clone();
1038        let _h = model.observe_changes(move |c| l.borrow_mut().push(c.clone()));
1039        // Contiguous block → ItemsMoved (so index selection can follow).
1040        assert!(model.move_items(&[1, 2], 5));
1041        assert!(matches!(
1042            log.borrow().last(),
1043            Some(DataChange::ItemsMoved { .. })
1044        ));
1045        log.borrow_mut().clear();
1046        // Non-contiguous set → Reset.
1047        assert!(model.move_items(&[0, 2], 0));
1048        assert!(matches!(log.borrow().last(), Some(DataChange::Reset)));
1049    }
1050
1051    #[test]
1052    fn reorder_within_and_move_items_report_no_move_for_out_of_range() {
1053        let model = ListModel::from_vec(vec![1, 2, 3]);
1054        assert!(!model.reorder_within(&[99, 100], &0, DropPosition::Before));
1055        assert!(!model.move_items(&[99, 100], 0));
1056        assert_eq!(snapshot(&model), vec![1, 2, 3]);
1057    }
1058
1059    // ── reconcile_by_key ─────────────────────────────────────────────────
1060
1061    #[derive(Debug, Clone, PartialEq, Eq)]
1062    struct Row {
1063        id: u64,
1064        val: &'static str,
1065    }
1066
1067    fn row(id: u64, val: &'static str) -> Row {
1068        Row { id, val }
1069    }
1070
1071    fn key(r: &Row) -> u64 {
1072        r.id
1073    }
1074
1075    fn ids(model: &ListModel<Row>) -> Vec<u64> {
1076        (0..model.len())
1077            .map(|i| model.with_item(i, |r| r.id).unwrap())
1078            .collect()
1079    }
1080
1081    fn vals(model: &ListModel<Row>) -> Vec<&'static str> {
1082        (0..model.len())
1083            .map(|i| model.with_item(i, |r| r.val).unwrap())
1084            .collect()
1085    }
1086
1087    fn record_changes(model: &ListModel<Row>) -> (Rc<RefCell<Vec<DataChange>>>, ObserverHandle) {
1088        let log: Rc<RefCell<Vec<DataChange>>> = Rc::new(RefCell::new(Vec::new()));
1089        let l = log.clone();
1090        let handle = model.observe_changes(move |c| l.borrow_mut().push(c.clone()));
1091        (log, handle)
1092    }
1093
1094    #[test]
1095    fn reconcile_pure_insert_emits_one_coalesced_range() {
1096        let model = ListModel::from_vec(vec![row(1, "a"), row(2, "b")]);
1097        let (log, _h) = record_changes(&model);
1098
1099        model.reconcile_by_key(
1100            vec![row(1, "a"), row(2, "b"), row(3, "c"), row(4, "d")],
1101            key,
1102        );
1103
1104        assert_eq!(ids(&model), vec![1, 2, 3, 4]);
1105        assert_eq!(vals(&model), vec!["a", "b", "c", "d"]);
1106        let entries = log.borrow();
1107        assert_eq!(entries.len(), 1, "contiguous inserts coalesce: {entries:?}");
1108        assert_eq!(entries[0], DataChange::ItemsInserted { range: 2..4 });
1109    }
1110
1111    #[test]
1112    fn reconcile_insert_at_front_and_middle() {
1113        let model = ListModel::from_vec(vec![row(1, "a"), row(2, "b")]);
1114        let (log, _h) = record_changes(&model);
1115
1116        // 0 is new (front), 1 stays, 5 is new (middle), 2 stays.
1117        model.reconcile_by_key(
1118            vec![row(0, "z"), row(1, "a"), row(5, "m"), row(2, "b")],
1119            key,
1120        );
1121
1122        assert_eq!(ids(&model), vec![0, 1, 5, 2]);
1123        let entries = log.borrow();
1124        // Two non-adjacent insert runs, no move needed (1 and 2 already in
1125        // relative order).
1126        assert_eq!(entries.len(), 2, "{entries:?}");
1127        assert_eq!(entries[0], DataChange::ItemsInserted { range: 0..1 });
1128        assert_eq!(entries[1], DataChange::ItemsInserted { range: 2..3 });
1129    }
1130
1131    #[test]
1132    fn reconcile_pure_remove_emits_one_coalesced_range() {
1133        let model = ListModel::from_vec(vec![row(1, "a"), row(2, "b"), row(3, "c"), row(4, "d")]);
1134        let (log, _h) = record_changes(&model);
1135
1136        model.reconcile_by_key(vec![row(1, "a"), row(4, "d")], key);
1137
1138        assert_eq!(ids(&model), vec![1, 4]);
1139        let entries = log.borrow();
1140        assert_eq!(entries.len(), 1, "contiguous removes coalesce: {entries:?}");
1141        assert_eq!(entries[0], DataChange::ItemsRemoved { range: 1..3 });
1142    }
1143
1144    #[test]
1145    fn reconcile_remove_scattered_emits_separate_ranges() {
1146        let model = ListModel::from_vec(vec![row(1, "a"), row(2, "b"), row(3, "c"), row(4, "d")]);
1147        let (log, _h) = record_changes(&model);
1148
1149        model.reconcile_by_key(vec![row(1, "a"), row(3, "c")], key);
1150
1151        assert_eq!(ids(&model), vec![1, 3]);
1152        let entries = log.borrow();
1153        assert_eq!(entries.len(), 2, "{entries:?}");
1154        // Emitted back-to-front so earlier indices stay valid at removal time.
1155        assert_eq!(entries[0], DataChange::ItemsRemoved { range: 3..4 });
1156        assert_eq!(entries[1], DataChange::ItemsRemoved { range: 1..2 });
1157    }
1158
1159    #[test]
1160    fn reconcile_reorder_emits_only_moves() {
1161        let model = ListModel::from_vec(vec![row(1, "a"), row(2, "b"), row(3, "c")]);
1162        let (log, _h) = record_changes(&model);
1163
1164        model.reconcile_by_key(vec![row(3, "c"), row(2, "b"), row(1, "a")], key);
1165
1166        assert_eq!(ids(&model), vec![3, 2, 1]);
1167        let entries = log.borrow();
1168        assert!(
1169            entries
1170                .iter()
1171                .all(|c| matches!(c, DataChange::ItemsMoved { .. })),
1172            "a pure reorder must only emit moves: {entries:?}"
1173        );
1174        assert!(!entries.is_empty());
1175    }
1176
1177    #[test]
1178    fn reconcile_no_reorder_when_relative_order_already_matches() {
1179        // Peer removed the middle row but didn't touch the order of the rest —
1180        // this must NOT emit any ItemsMoved, only the removal.
1181        let model = ListModel::from_vec(vec![row(1, "a"), row(2, "b"), row(3, "c"), row(4, "d")]);
1182        let (log, _h) = record_changes(&model);
1183
1184        model.reconcile_by_key(vec![row(1, "a"), row(3, "c"), row(4, "d")], key);
1185
1186        assert_eq!(ids(&model), vec![1, 3, 4]);
1187        let entries = log.borrow();
1188        assert!(
1189            entries
1190                .iter()
1191                .all(|c| !matches!(c, DataChange::ItemsMoved { .. })),
1192            "untouched relative order must not emit moves: {entries:?}"
1193        );
1194    }
1195
1196    #[test]
1197    fn reconcile_in_place_update_emits_item_updated() {
1198        let model = ListModel::from_vec(vec![row(1, "a"), row(2, "b"), row(3, "c")]);
1199        let (log, _h) = record_changes(&model);
1200
1201        model.reconcile_by_key(vec![row(1, "a"), row(2, "CHANGED"), row(3, "c")], key);
1202
1203        assert_eq!(vals(&model), vec!["a", "CHANGED", "c"]);
1204        let entries = log.borrow();
1205        assert_eq!(entries.len(), 1, "{entries:?}");
1206        assert_eq!(entries[0], DataChange::ItemUpdated { index: 1 });
1207    }
1208
1209    #[test]
1210    fn reconcile_combined_insert_remove_reorder_update() {
1211        // old: [1,2,3,4] -> new: [4, 2*, 5, 1]
1212        //  - 3 removed
1213        //  - 4 moves to front
1214        //  - 2's content changes in place
1215        //  - 5 is inserted
1216        //  - 1 stays last (relative order of 1 vs 2 vs 4 reshuffled)
1217        let model = ListModel::from_vec(vec![row(1, "a"), row(2, "b"), row(3, "c"), row(4, "d")]);
1218        let (log, _h) = record_changes(&model);
1219
1220        model.reconcile_by_key(
1221            vec![row(4, "d"), row(2, "B!"), row(5, "e"), row(1, "a")],
1222            key,
1223        );
1224
1225        assert_eq!(ids(&model), vec![4, 2, 5, 1]);
1226        assert_eq!(vals(&model), vec!["d", "B!", "e", "a"]);
1227        let entries = log.borrow();
1228        assert!(!entries.is_empty());
1229        assert!(
1230            entries
1231                .iter()
1232                .any(|c| matches!(c, DataChange::ItemsMoved { .. })),
1233            "{entries:?}"
1234        );
1235        assert!(
1236            entries
1237                .iter()
1238                .any(|c| matches!(c, DataChange::ItemsInserted { .. })),
1239            "{entries:?}"
1240        );
1241        assert!(
1242            entries
1243                .iter()
1244                .any(|c| matches!(c, DataChange::ItemsRemoved { .. })),
1245            "{entries:?}"
1246        );
1247        assert!(
1248            entries
1249                .iter()
1250                .any(|c| matches!(c, DataChange::ItemUpdated { .. })),
1251            "{entries:?}"
1252        );
1253        assert!(
1254            !entries.iter().any(|c| matches!(c, DataChange::Reset)),
1255            "{entries:?}"
1256        );
1257    }
1258
1259    #[test]
1260    fn reconcile_empty_to_full() {
1261        let model: ListModel<Row> = ListModel::new();
1262        let (log, _h) = record_changes(&model);
1263
1264        model.reconcile_by_key(vec![row(1, "a"), row(2, "b"), row(3, "c")], key);
1265
1266        assert_eq!(ids(&model), vec![1, 2, 3]);
1267        let entries = log.borrow();
1268        assert_eq!(entries.len(), 1, "{entries:?}");
1269        assert_eq!(entries[0], DataChange::ItemsInserted { range: 0..3 });
1270    }
1271
1272    #[test]
1273    fn reconcile_full_to_empty() {
1274        let model = ListModel::from_vec(vec![row(1, "a"), row(2, "b"), row(3, "c")]);
1275        let (log, _h) = record_changes(&model);
1276
1277        model.reconcile_by_key(vec![], key);
1278
1279        assert!(model.is_empty());
1280        let entries = log.borrow();
1281        assert_eq!(entries.len(), 1, "{entries:?}");
1282        assert_eq!(entries[0], DataChange::ItemsRemoved { range: 0..3 });
1283    }
1284
1285    #[test]
1286    fn reconcile_identical_input_emits_nothing() {
1287        let model = ListModel::from_vec(vec![row(1, "a"), row(2, "b"), row(3, "c")]);
1288        let (log, _h) = record_changes(&model);
1289
1290        model.reconcile_by_key(vec![row(1, "a"), row(2, "b"), row(3, "c")], key);
1291
1292        assert_eq!(ids(&model), vec![1, 2, 3]);
1293        assert!(
1294            log.borrow().is_empty(),
1295            "identical reconcile must not notify: {:?}",
1296            log.borrow()
1297        );
1298    }
1299
1300    #[test]
1301    fn reconcile_never_emits_reset() {
1302        // Exercise every scenario above (plus a full rewrite / total
1303        // replacement, the case most tempted to fall back to `Reset`) and
1304        // assert `Reset` is never among the emitted changes.
1305        let scenarios: Vec<(Vec<Row>, Vec<Row>)> = vec![
1306            (
1307                vec![row(1, "a"), row(2, "b")],
1308                vec![row(1, "a"), row(2, "b"), row(3, "c")],
1309            ),
1310            (
1311                vec![row(1, "a"), row(2, "b"), row(3, "c")],
1312                vec![row(1, "a")],
1313            ),
1314            (
1315                vec![row(1, "a"), row(2, "b"), row(3, "c")],
1316                vec![row(3, "c"), row(1, "a"), row(2, "b")],
1317            ),
1318            (vec![], vec![row(1, "a"), row(2, "b")]),
1319            (vec![row(1, "a"), row(2, "b")], vec![]),
1320            (
1321                vec![row(1, "a"), row(2, "b"), row(3, "c"), row(4, "d")],
1322                vec![row(9, "x"), row(8, "y"), row(7, "z")],
1323            ),
1324        ];
1325        for (before, after) in scenarios {
1326            let model = ListModel::from_vec(before.clone());
1327            let (log, _h) = record_changes(&model);
1328            model.reconcile_by_key(after.clone(), key);
1329            assert!(
1330                !log.borrow().iter().any(|c| matches!(c, DataChange::Reset)),
1331                "reconcile must never emit Reset — before {before:?}, after {after:?}, got {:?}",
1332                log.borrow()
1333            );
1334        }
1335    }
1336
1337    #[test]
1338    #[should_panic(expected = "reconcile_by_key")]
1339    fn reconcile_duplicate_key_in_new_items_panics() {
1340        let model = ListModel::from_vec(vec![row(1, "a"), row(2, "b")]);
1341        // Two incoming rows both claim key 1 — the second can't be found at
1342        // or after the write cursor once the first has already consumed
1343        // that key's slot (see `# Panics` on `reconcile_by_key`).
1344        model.reconcile_by_key(vec![row(1, "a"), row(1, "a-dup"), row(2, "b")], key);
1345    }
1346}