Skip to main content

tilo_resource/
children.rs

1//! Resources that contain resources: a container lists its children, each a
2//! record of its own.
3//!
4//! A child that can need its own permissions, sharing or history (a chat's
5//! channel, a category) is its own record, with a minted id that never
6//! changes, living in its parent's workspace. The parent keeps only what
7//! places it: a [`ChildRef`] per child in a [`Children`] field, in order,
8//! naming its kind, the sibling it is grouped under (a channel's category)
9//! and whether it is in the workspace's trash. Moving a child moves its
10//! reference; the child keeps its identity, so every reference to it keeps
11//! working.
12//!
13//! Every container has the same lifecycle (the framework publishes it, the
14//! app writes no verbs for it): `create` a child of a kind at a place with
15//! its first fields, `delete` it to the trash (restorable, its record and id
16//! kept), `restore` it, and `move` it to another place or group.
17
18use crate::{Atom, Collection, Id, Model};
19
20/// The id of the generated action that makes a child.
21pub const CREATE: &str = "create";
22/// The id of the generated action that puts a child in the trash.
23pub const DELETE: &str = "delete";
24/// The id of the generated action that takes a child out of the trash.
25pub const RESTORE: &str = "restore";
26/// The id of the generated action that moves a child.
27pub const MOVE: &str = "move";
28
29/// When a child went to the workspace's trash: in milliseconds since the epoch.
30#[derive(Model, Clone, Copy, Debug, Default, PartialEq, Eq)]
31pub struct Trashed {
32    /// When.
33    pub at: i64,
34}
35
36/// One child a container lists. See the [module docs](self).
37#[derive(Model, Clone, Debug, Default, PartialEq, Eq)]
38pub struct ChildRef {
39    /// Its resource kind: a container may hold several, and a child is
40    /// always read as the kind it was made as.
41    #[model(readonly)]
42    pub kind: Atom,
43    /// The sibling it is listed under (a channel's category), if any.
44    pub group: Option<Id>,
45    /// In the workspace's trash since then: listed nowhere, kept whole.
46    pub trashed: Option<Trashed>,
47}
48
49/// The children a container lists, in order. See the [module docs](self).
50pub type Children = Collection<ChildRef>;
51
52/// Reading a container: what it lists outside the trash, by kind and group.
53pub trait ChildList {
54    /// Every child outside the trash, in order.
55    fn listed(&self) -> Vec<(&Id, &ChildRef)>;
56    /// The children of `kind` outside the trash, in order.
57    fn listed_of(&self, kind: &str) -> Vec<&Id>;
58    /// The children listed under `group` (none: at the top), outside the
59    /// trash, in order.
60    fn under(&self, group: Option<&Id>) -> Vec<&Id>;
61    /// The children in the trash, in order.
62    fn in_trash(&self) -> Vec<&Id>;
63    /// Whether `id` is listed outside the trash.
64    fn lists(&self, id: &Id) -> bool;
65}
66
67impl ChildList for Children {
68    fn listed(&self) -> Vec<(&Id, &ChildRef)> {
69        self.iter()
70            .filter(|(_, child)| child.trashed.is_none())
71            .collect()
72    }
73
74    fn listed_of(&self, kind: &str) -> Vec<&Id> {
75        self.iter()
76            .filter(|(_, child)| child.trashed.is_none() && child.kind.0 == kind)
77            .map(|(id, _)| id)
78            .collect()
79    }
80
81    fn under(&self, group: Option<&Id>) -> Vec<&Id> {
82        self.iter()
83            .filter(|(_, child)| child.trashed.is_none() && child.group.as_ref() == group)
84            .map(|(id, _)| id)
85            .collect()
86    }
87
88    fn in_trash(&self) -> Vec<&Id> {
89        self.iter()
90            .filter(|(_, child)| child.trashed.is_some())
91            .map(|(id, _)| id)
92            .collect()
93    }
94
95    fn lists(&self, id: &Id) -> bool {
96        self.get(id).is_some_and(|child| child.trashed.is_none())
97    }
98}
99
100/// Where a moved or new child goes in the container's order: before the
101/// sibling `before`, else last (and so last among the children of whichever
102/// group it is listed under).
103#[must_use]
104pub fn place(children: &Children, before: Option<&Id>) -> usize {
105    before
106        .and_then(|before| children.position(before))
107        .unwrap_or_else(|| children.len())
108}
109
110/// Why a child cannot be grouped under `group`: it names no listed child,
111/// or the child itself (nothing is listed under itself).
112pub fn check_group(children: &Children, child: &Id, group: Option<&Id>) -> Result<(), String> {
113    match group {
114        Some(group) if group == child => Err("nothing is listed under itself".into()),
115        Some(group) if !children.lists(group) => Err("there is no such group".into()),
116        _ => Ok(()),
117    }
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123
124    fn child(kind: &str, group: Option<&str>) -> ChildRef {
125        ChildRef {
126            kind: Atom(kind.into()),
127            group: group.map(Id::from_raw),
128            trashed: None,
129        }
130    }
131
132    tilo_test_env::scenario! {
133        fn a_container_lists_and_places_its_children;
134
135        phase a_container_lists_its_children_by_group_and_keeps_the_trashed_aside;
136        {
137            let mut children = Children::new();
138            children.push(Id::from_raw("design"), child("chat.category", None));
139            children.push(Id::from_raw("general"), child("chat.channel", None));
140            children.push(Id::from_raw("ui"), child("chat.channel", Some("design")));
141            children.push(Id::from_raw("ux"), child("chat.channel", Some("design")));
142            assert_eq!(
143                children.listed_of("chat.channel"),
144                [
145                    &Id::from_raw("general"),
146                    &Id::from_raw("ui"),
147                    &Id::from_raw("ux")
148                ]
149            );
150            assert_eq!(
151                children.under(Some(&Id::from_raw("design"))),
152                [&Id::from_raw("ui"), &Id::from_raw("ux")]
153            );
154            children.get_mut(&Id::from_raw("ui")).unwrap().trashed = Some(Trashed { at: 5 });
155            assert_eq!(
156                children.under(Some(&Id::from_raw("design"))),
157                [&Id::from_raw("ux")]
158            );
159            assert_eq!(children.in_trash(), [&Id::from_raw("ui")]);
160            assert!(!children.lists(&Id::from_raw("ui")));
161            assert!(children.contains(&Id::from_raw("ui")), "kept whole");
162        }
163
164        phase a_new_child_goes_last_or_before_the_sibling_named;
165        {
166            let mut children = Children::new();
167            children.push(Id::from_raw("design"), child("chat.category", None));
168            children.push(Id::from_raw("ui"), child("chat.channel", Some("design")));
169            children.push(Id::from_raw("general"), child("chat.channel", None));
170            let design = Id::from_raw("design");
171            assert_eq!(place(&children, None), 3);
172            assert_eq!(place(&children, Some(&Id::from_raw("ui"))), 1);
173            assert_eq!(place(&children, Some(&Id::from_raw("absent"))), 3);
174            assert_eq!(place(&Children::new(), None), 0);
175            assert!(check_group(&children, &Id::from_raw("ui"), Some(&design)).is_ok());
176            assert!(check_group(&children, &design, Some(&design)).is_err());
177            assert!(check_group(&children, &design, Some(&Id::from_raw("absent"))).is_err());
178        }
179    }
180}