diff --git a/crates/loro-internal/src/handler/tree.rs b/crates/loro-internal/src/handler/tree.rs index a29a49f9..dd8749a3 100644 --- a/crates/loro-internal/src/handler/tree.rs +++ b/crates/loro-internal/src/handler/tree.rs @@ -538,7 +538,10 @@ impl TreeHandler { self.move_to(target, parent, index) } MaybeDetached::Attached(a) => { - let index: usize = self.children_num(&parent).unwrap_or(0); + let mut index: usize = self.children_num(&parent).unwrap_or(0); + if self.is_parent(&target, &parent) { + index -= 1; + } a.with_txn(|txn| { self.mov_with_txn(txn, target, parent, index, FiIfNotConfigured::Zero) }) diff --git a/crates/loro-internal/tests/tree.rs b/crates/loro-internal/tests/tree.rs index 54d6ed69..8cdae51f 100644 --- a/crates/loro-internal/tests/tree.rs +++ b/crates/loro-internal/tests/tree.rs @@ -23,3 +23,13 @@ fn tree_index() { assert_eq!(tree.get_index_by_tree_id(&child).unwrap(), 1); assert_eq!(tree.get_index_by_tree_id(&child2).unwrap(), 0); } + +#[test] +fn tree_move_in_parent() { + let doc = LoroDoc::new_auto_commit(); + doc.set_peer_id(0).unwrap(); + let tree = doc.get_tree("tree"); + let root = tree.create(TreeParentId::Root).unwrap(); + let child = tree.create(root.into()).unwrap(); + tree.mov(child, root.into()).unwrap(); +}