Skip to main content

tilo_render_protocol/patch/
diff.rs

1//! The patches that bring one tree to another, by key.
2//!
3//! A tree sent over [`super`] is diffed against the copy the window holds, and the patches
4//! alone are sent: a node kept by key keeps its widget, and with it focus, scroll position and
5//! text state. Keyed by `Node::key`, which is stable for as long as the node shows the same
6//! thing.
7//!
8//! Both sides of the protocol use this: a tilolang view's tree ([`crate::patch::Node`]) is
9//! diffed by the runtime, and so is a Rust app's — a view is a function of a resource whichever
10//! language wrote it, and the window draws both the same way (one-app-model.md §2).
11
12use std::collections::HashSet;
13
14use super::{Node, Patch};
15
16/// The patches that bring `old`, the tree the window holds, to `new`, appended to `out`.
17///
18/// The whole tree is sent (`SetRoot`) when the root changed kind or key, or when the keys of
19/// some node's children are not unique: patches by key need both to hold.
20pub fn diff(old: &Node, new: &Node, out: &mut Vec<Patch>) {
21    if old.kind != new.kind || old.key != new.key || !unique(old) || !unique(new) {
22        out.push(Patch::SetRoot(new.clone()));
23        return;
24    }
25    diff_node(old, new, &mut Vec::new(), out);
26}
27
28/// The node at `path` (keys below the root) of `node`, when each key on the way names one child.
29#[must_use]
30pub fn at<'a>(node: &'a Node, path: &[String]) -> Option<&'a Node> {
31    path.iter().try_fold(node, |node, key| {
32        let mut named = node.children.iter().filter(|child| child.key == *key);
33        let child = named.next()?;
34        named.next().is_none().then_some(child)
35    })
36}
37
38/// The node at `path` (keys below the root) of `node`.
39pub fn at_mut<'a>(node: &'a mut Node, path: &[String]) -> Option<&'a mut Node> {
40    path.iter().try_fold(node, |node, key| {
41        node.children.iter_mut().find(|child| child.key == *key)
42    })
43}
44
45/// The patches that bring `old`, the node at `path` of the tree the window holds, to `new`,
46/// appended to `out`; `false`, and nothing appended, when `new` is another node (another kind
47/// or key) or its children's keys are not unique: then the tree is diffed whole.
48pub fn diff_at(old: &Node, new: &Node, path: &[String], out: &mut Vec<Patch>) -> bool {
49    if old.kind != new.kind || old.key != new.key || !unique(old) || !unique(new) {
50        return false;
51    }
52    diff_node(old, new, &mut path.to_vec(), out);
53    true
54}
55
56/// Whether the keys of each node's children are unique, all the way down: what patches by key
57/// need.
58fn unique(node: &Node) -> bool {
59    let mut seen = HashSet::with_capacity(node.children.len());
60    node.children.iter().all(|child| seen.insert(&child.key)) && node.children.iter().all(unique)
61}
62
63fn diff_node(old: &Node, new: &Node, path: &mut Vec<String>, out: &mut Vec<Patch>) {
64    for (name, value) in &new.props {
65        if old.props.get(name) != Some(value) {
66            out.push(Patch::SetProp {
67                path: path.clone(),
68                name: name.clone(),
69                value: Some(value.clone()),
70            });
71        }
72    }
73    for name in old
74        .props
75        .keys()
76        .filter(|name| !new.props.contains_key(*name))
77    {
78        out.push(Patch::SetProp {
79            path: path.clone(),
80            name: name.clone(),
81            value: None,
82        });
83    }
84    if old.binding != new.binding {
85        out.push(Patch::SetBinding {
86            path: path.clone(),
87            binding: new.binding.clone(),
88        });
89    }
90    for (event, action) in &new.events {
91        if old.events.get(event) != Some(action) {
92            out.push(Patch::SetEvent {
93                path: path.clone(),
94                event: event.clone(),
95                action: Some(action.clone()),
96            });
97        }
98    }
99    for event in old
100        .events
101        .keys()
102        .filter(|event| !new.events.contains_key(*event))
103    {
104        out.push(Patch::SetEvent {
105            path: path.clone(),
106            event: event.clone(),
107            action: None,
108        });
109    }
110    if old.anchor != new.anchor {
111        out.push(Patch::SetAnchor {
112            path: path.clone(),
113            anchor: new.anchor.clone(),
114        });
115    }
116    diff_children(old, new, path, out);
117}
118
119/// The children of `old` brought to `new`'s by key: those gone removed, those kept moved to
120/// their place and brought up to date there, those new inserted.
121fn diff_children(old: &Node, new: &Node, path: &mut Vec<String>, out: &mut Vec<Patch>) {
122    let wanted: HashSet<&str> = new
123        .children
124        .iter()
125        .map(|child| child.key.as_str())
126        .collect();
127    let mut held: Vec<&Node> = Vec::with_capacity(old.children.len());
128    for child in &old.children {
129        if wanted.contains(child.key.as_str()) {
130            held.push(child);
131        } else {
132            out.push(Patch::Remove {
133                parent: path.clone(),
134                key: child.key.clone(),
135            });
136        }
137    }
138    for (index, child) in new.children.iter().enumerate() {
139        let at = held.iter().position(|old| old.key == child.key);
140        let Some(at) = at else {
141            out.push(Patch::Insert {
142                parent: path.clone(),
143                index: u32::try_from(index).unwrap_or(u32::MAX),
144                node: child.clone(),
145            });
146            held.insert(index.min(held.len()), child);
147            continue;
148        };
149        if at != index {
150            out.push(Patch::Move {
151                parent: path.clone(),
152                key: child.key.clone(),
153                to: u32::try_from(index).unwrap_or(u32::MAX),
154            });
155            let moved = held.remove(at);
156            held.insert(index.min(held.len()), moved);
157        }
158        let before = held.get(index).copied();
159        if let Some(before) = before
160            && before != child
161        {
162            if before.kind == child.kind {
163                path.push(child.key.clone());
164                diff_node(before, child, path, out);
165                path.pop();
166            } else {
167                out.push(Patch::Remove {
168                    parent: path.clone(),
169                    key: child.key.clone(),
170                });
171                out.push(Patch::Insert {
172                    parent: path.clone(),
173                    index: u32::try_from(index).unwrap_or(u32::MAX),
174                    node: child.clone(),
175                });
176            }
177        }
178    }
179}
180
181#[cfg(test)]
182mod tests {
183    use super::*;
184    use crate::patch::Value;
185
186    fn text(key: &str, value: &str) -> Node {
187        let mut node = Node::empty("ui.Text", key);
188        node.props.insert("value".to_owned(), Value::text(value));
189        node
190    }
191
192    fn stack(key: &str, children: Vec<Node>) -> Node {
193        Node {
194            children,
195            ..Node::empty("stack", key)
196        }
197    }
198
199    /// `old` patched by the diff to `new` is `new`.
200    fn round_trip(old: &Node, new: &Node) -> Vec<Patch> {
201        let mut patches = Vec::new();
202        diff(old, new, &mut patches);
203        let mut applied = old.clone();
204        for patch in patches.clone() {
205            patch.apply(&mut applied).expect("the diff's patches apply");
206        }
207        assert_eq!(&applied, new, "{patches:#?}");
208        patches
209    }
210
211    #[test]
212    fn the_diff_brings_the_windows_tree_to_the_views_by_key() {
213        let old = stack(
214            "s",
215            vec![
216                text("a", "a"),
217                text("b", "b"),
218                stack("c", vec![text("c1", "1")]),
219            ],
220        );
221        let new = stack(
222            "s",
223            vec![
224                text("n", "n"),
225                stack("c", vec![text("c1", "2"), text("c2", "3")]),
226                text("a", "a"),
227            ],
228        );
229        let patches = round_trip(&old, &new);
230        assert!(
231            !patches
232                .iter()
233                .any(|patch| matches!(patch, Patch::SetRoot(_))),
234            "a change by key, not the tree anew: {patches:#?}"
235        );
236        assert!(round_trip(&new, &new).is_empty(), "no change, no patch");
237        // A child that changes kind under the same key is replaced.
238        let swapped = stack("s", vec![Node::empty("divider", "a")]);
239        round_trip(&old, &swapped);
240        // A root of another kind is the tree anew.
241        let other = Node::empty("page", "s");
242        assert_eq!(
243            round_trip(&old, &other),
244            vec![Patch::SetRoot(other.clone())]
245        );
246    }
247
248    #[test]
249    fn siblings_sharing_a_key_are_sent_whole() {
250        let old = stack("s", vec![text("a", "1"), text("a", "2")]);
251        let new = stack("s", vec![text("a", "3")]);
252        assert_eq!(round_trip(&old, &new), vec![Patch::SetRoot(new.clone())]);
253    }
254}