Skip to main content

tilo_resource/
ordered.rs

1//! A list someone arranges, of items that carry their own ids: [`Ordered`].
2//!
3//! [`Collection`](crate::Collection) keeps each item's id beside it, which
4//! is right when the id is only the collection's business. Items that carry
5//! their id themselves ([`Identified`]) — an effect in a clip's stack, a step
6//! in a recipe — read best as a plain vector, so `Ordered<T>` holds them as a
7//! `Vec<T>` in memory and stores them exactly as a `Collection` is stored:
8//! a map from id to `{ k: order key, v: value }`. Editing an item writes only
9//! that item, a move rewrites one order key, concurrent inserts interleave
10//! deterministically and a delete never disturbs another item's identity —
11//! none of which a list stored by position can promise.
12
13use std::collections::HashSet;
14
15use automerge::ObjId;
16
17use crate::collection::{Id, VALUE, store_in_order, stored_entries};
18use crate::keyed::{Identified, ItemStorage, Items, removed_and_changed_in};
19use crate::model::LocatedAt as _;
20use crate::model::{Doc, Model, ModelError, Slot};
21use crate::path::{Edit, EditOp, Path, Segment};
22
23/// Items in the order they were arranged, stored under the ids they carry.
24/// See the module docs.
25pub type Ordered<T> = Items<T, Arranged>;
26
27/// [`Ordered`] storage: a map from id to `{ k: order key, v: value }`, as a
28/// [`Collection`](crate::Collection) is stored.
29#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
30pub struct Arranged;
31
32impl<R, T: Model + Identified> Path<R, Ordered<T>> {
33    /// Add `item` under its own id at position `at`.
34    #[must_use]
35    pub fn insert(&self, at: usize, item: &T) -> Edit<R> {
36        self.edit(EditOp::InsertItem {
37            id: Some(item.id()),
38            at: crate::At::Index(at),
39            value: item.to_json(),
40        })
41    }
42
43    /// Move the item `id` to position `at`.
44    #[must_use]
45    pub fn move_to(&self, id: &Id, at: usize) -> Edit<R> {
46        self.edit(EditOp::MoveTo {
47            id: id.clone(),
48            at: crate::At::Index(at),
49        })
50    }
51}
52
53impl ItemStorage for Arranged {
54    const ARRANGED: bool = true;
55    const NAME: &'static str = "arranged items";
56
57    #[inline(never)]
58    fn load<T: Model + Identified>(doc: &Doc, map: &ObjId) -> Result<Vec<T>, ModelError> {
59        stored_entries(doc, map)
60            .into_iter()
61            .map(|stored| {
62                crate::model::load_slot::<T>(doc, stored.value, VALUE).located(stored.id.as_str())
63            })
64            .collect()
65    }
66
67    #[inline(never)]
68    fn store<T: Model + Identified>(
69        items: &[T],
70        doc: &mut Doc,
71        slot: Slot<'_>,
72    ) -> Result<(), ModelError> {
73        let ids: Vec<Id> = items.iter().map(Identified::id).collect();
74        let items: Vec<(&Id, &dyn crate::model::Stores)> = ids
75            .iter()
76            .zip(items)
77            .map(|(id, item)| (id, item as &dyn crate::model::Stores))
78            .collect();
79        store_in_order(doc, slot, &items, (false, &|_, _, _| None), &|_| false)
80    }
81
82    const DIFF: crate::keyed::ErasedDiff = arranged_diff_in;
83}
84
85/// [`Arranged`]'s [`ItemStorage::diff`] over items whose type `table`
86/// describes, compiled once for every item type.
87#[inline(never)]
88fn arranged_diff_in(
89    table: &'static crate::table::ModelTable,
90    (before, after): (
91        &dyn crate::collection::ItemList,
92        &dyn crate::collection::ItemList,
93    ),
94    path: &[Segment],
95    out: &mut Vec<Edit<()>>,
96) {
97    let after_ids: Vec<Id> = (0..after.count())
98        .filter_map(|at| Some(after.item(at)?.0))
99        .collect();
100    let before_ids = removed_and_changed_in(table, (before, after), &after_ids, path, out);
101    let present: HashSet<&Id> = after_ids.iter().collect();
102    // Walk `after` against the order the edits so far leave: what
103    // survived of `before`, then each item put where `after` has it.
104    let mut order: Vec<Id> = before_ids
105        .into_iter()
106        .filter(|id| present.contains(id))
107        .collect();
108    for (index, id) in after_ids.iter().cloned().enumerate() {
109        match order.iter().position(|candidate| candidate == &id) {
110            Some(now) if now == index => {}
111            Some(now) => {
112                order.remove(now);
113                order.insert(index.min(order.len()), id.clone());
114                out.push(Edit::new(
115                    path.to_vec(),
116                    EditOp::MoveTo {
117                        id,
118                        at: crate::At::Index(index),
119                    },
120                ));
121            }
122            None => {
123                let Some((_, item)) = after.item(index) else {
124                    continue;
125                };
126                order.insert(index.min(order.len()), id.clone());
127                out.push(Edit::new(
128                    path.to_vec(),
129                    EditOp::InsertItem {
130                        id: Some(id),
131                        at: crate::At::Index(index),
132                        value: (table.ops.to_json)(table, item),
133                    },
134                ));
135            }
136        }
137    }
138}