forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

event.rs66 lines, 2.6 KiBHistoryRawDownload
1use std::sync::Arc;
2
3use loro_internal::{
4 cursor::PosType,
5 event::Diff,
6 handler::{Handler, ValueOrHandler},
7 ListHandler, LoroDoc, MapHandler, TextHandler, ToJson, TreeHandler,
8};
9
10fn main() {
11 let doc = LoroDoc::new();
12 doc.start_auto_commit();
13 let list = doc.get_list("list");
14 let _g = doc.subscribe_root(Arc::new(|e| {
15 for container_diff in e.events {
16 match &container_diff.diff {
17 Diff::List(list) => {
18 for item in list.iter() {
19 if let loro_delta::DeltaItem::Replace { value, .. } = item {
20 for v in value.iter() {
21 match v {
22 ValueOrHandler::Handler(h) => {
23 // You can directly obtain the handler and perform some operations.
24 if matches!(h, Handler::Map(_)) {
25 let text = h
26 .as_map()
27 .unwrap()
28 .insert_container(
29 "text",
30 TextHandler::new_detached(),
31 )
32 .unwrap();
33 text.insert(0, "created from event", PosType::Unicode)
34 .unwrap();
35 }
36 }
37 ValueOrHandler::Value(value) => {
38 println!("insert value {value:?}");
39 }
40 }
41 }
42 }
43 }
44 }
45 Diff::Map(map) => {
46 println!("map container updates {:?}", map.updated);
47 }
48 _ => {}
49 }
50 }
51 }));
52 list.insert(0, "abc").unwrap();
53 list.insert_container(1, ListHandler::new_detached())
54 .unwrap();
55 list.insert_container(2, MapHandler::new_detached())
56 .unwrap();
57 list.insert_container(3, TextHandler::new_detached())
58 .unwrap();
59 list.insert_container(4, TreeHandler::new_detached())
60 .unwrap();
61 doc.commit_then_renew();
62 assert_eq!(
63 doc.get_deep_value().to_json(),
64 r#"{"list":["abc",[],{"text":"created from event"},"",[]]}"#
65 );
66}