loro/crates/loro-internal/examples/event.rs
Zixuan Chen 9ecc0a90b1
refactor!: Add prelim support, making creating sub container easier (#300)
This PR includes a BREAKING CHANGE.

It enables you to create containers before attaching them to the document, making the API more intuitive and straightforward.

A container can be either attached to a document or detached. When it's detached, its history/state does not persist. You can attach a container to a document by inserting it into an attached container. Once a container is attached, its state, along with all of its descendants's states, will be recreated in the document. After attaching, the container and its descendants, will each have their corresponding "attached" version of themselves?

When a detached container x is attached to a document, you can use x.getAttached() to obtain the corresponding attached container.
2024-03-30 11:38:24 +08:00

70 lines
2.6 KiB
Rust

use std::sync::Arc;
use loro_internal::{
delta::DeltaItem,
event::Diff,
handler::{Handler, ValueOrHandler},
ListHandler, LoroDoc, MapHandler, TextHandler, ToJson, TreeHandler,
};
fn main() {
let mut doc = LoroDoc::new();
doc.start_auto_commit();
let list = doc.get_list("list");
doc.subscribe_root(Arc::new(|e| {
for container_diff in e.events {
match &container_diff.diff {
Diff::List(list) => {
for item in list.iter() {
if let DeltaItem::Insert {
insert,
attributes: _,
} = item
{
for v in insert {
match v {
ValueOrHandler::Handler(h) => {
// You can directly obtain the handler and perform some operations.
if matches!(h, Handler::Map(_)) {
let text = h
.as_map()
.unwrap()
.insert_container(
"text",
TextHandler::new_detached(),
)
.unwrap();
text.insert(0, "created from event").unwrap();
}
}
ValueOrHandler::Value(value) => {
println!("insert value {:?}", value);
}
}
}
}
}
}
Diff::Map(map) => {
println!("map container updates {:?}", map.updated);
}
_ => {}
}
}
}));
list.insert(0, "abc").unwrap();
list.insert_container(1, ListHandler::new_detached())
.unwrap();
list.insert_container(2, MapHandler::new_detached())
.unwrap();
list.insert_container(3, TextHandler::new_detached())
.unwrap();
list.insert_container(4, TreeHandler::new_detached())
.unwrap();
doc.commit_then_renew();
assert_eq!(
doc.get_deep_value().to_json(),
r#"{"list":["abc",[],{"text":"created from event"},"",[]]}"#
);
}