Doc

Struct Doc 

Source
pub struct Doc { /* private fields */ }
Expand description

A Yrs document type. Documents are the most important units of collaborative resources management. All shared collections live within a scope of their corresponding documents. All updates are generated on per-document basis (rather than individual shared type). All operations on shared collections happen via Transaction, which lifetime is also bound to a document.

Document manages so-called root types, which are top-level shared types definitions (as opposed to recursively nested types).

§Example

use yrs::{Doc, ReadTxn, StateVector, Text, Transact, Update};
use yrs::updates::decoder::Decode;
use yrs::updates::encoder::Encode;

let doc = Doc::new();
let root = doc.get_or_insert_text("root-type-name");
let mut txn = doc.transact_mut(); // all Yrs operations happen in scope of a transaction
root.push(&mut txn, "hello world"); // append text to our collaborative document

// in order to exchange data with other documents we first need to create a state vector
let remote_doc = Doc::new();
let mut remote_txn = remote_doc.transact_mut();
let state_vector = remote_txn.state_vector().encode_v1();

// now compute a differential update based on remote document's state vector
let update = txn.encode_diff_v1(&StateVector::decode_v1(&state_vector).unwrap());

// both update and state vector are serializable, we can pass the over the wire
// now apply update to a remote document
remote_txn.apply_update(Update::decode_v1(update.as_slice()).unwrap());

Implementations§

Source§

impl Doc

Source

pub fn new() -> Doc

Creates a new document with a randomized client identifier.

Examples found in repository?
examples/client.rs (line 19)
10async fn main() -> Result<(), Box<dyn std::error::Error>> {
11    // 初始化日志
12    tracing_subscriber::fmt().with_max_level(tracing::Level::INFO).init();
13
14    // 从 `collaboration.rs` 测试中获取服务器详细信息
15    let server_url = "ws://127.0.0.1:8080/collaboration"; // 确保端口与服务器测试匹配
16    let room_name = "demo-room";
17
18    // 1. 初始化客户端的文档和 awareness 状态
19    let doc = Doc::new();
20    let client_id = doc.client_id();
21    let awareness: AwarenessRef =
22        Arc::new(tokio::sync::RwLock::new(Awareness::new(doc)));
23
24    // 🔍 生成唯一的用户 ID
25    let unique_user_id =
26        format!("client-user-{}-{}", chrono::Utc::now().timestamp(), client_id);
27
28    tracing::info!("🆔 Yrs Client ID: {}", client_id);
29    tracing::info!("👤 User ID: {}", unique_user_id);
30
31    let mut provider = WebsocketProvider::new(
32        server_url.to_string(),
33        room_name.to_string(),
34        awareness.clone(),
35    )
36    .await;
37
38    // 订阅同步事件
39    if let Some(mut receiver) = provider.subscribe_sync_events() {
40        tokio::spawn(async move {
41            while let Ok(event) = receiver.recv().await {
42                match event {
43                    SyncEvent::InitialSyncCompleted {
44                        has_data,
45                        elapsed_ms,
46                    } => {
47                        if has_data {
48                            println!(
49                                "🎉 同步完成,房间有数据!耗时: {elapsed_ms}ms"
50                            );
51                        } else {
52                            println!(
53                                "📭 同步完成,空房间!耗时: {elapsed_ms}ms"
54                            );
55                        }
56                    },
57                    SyncEvent::ProtocolStateChanged(state) => {
58                        println!("📡 协议状态: {state:?}");
59                    },
60                    SyncEvent::DataReceived => {
61                        println!("📥 收到数据更新");
62                    },
63                    SyncEvent::ConnectionFailed(error) => {
64                        println!("🔌 监听: {error:?}");
65                    },
66                    SyncEvent::ConnectionChanged(status) => {
67                        println!("🔌 连接状态: {status:?}");
68                    },
69                }
70            }
71        });
72    }
73
74    // 3. 连接到服务器
75    provider.connect().await;
76    {
77        let nodes_map = awareness.read().await.doc().get_or_insert_map("nodes");
78        // 订阅 nodes变更 浅
79        provider.subscription(nodes_map.observe(move |txn, event| {
80            for (key, change) in event.keys(txn) {
81                match change {
82                    yrs::types::EntryChange::Inserted(value) => {
83                        println!("新增 key: {key}, value: {value:?}");
84                    },
85                    yrs::types::EntryChange::Removed(old_value) => {
86                        println!(
87                            "删除 key: {key}, old value: {old_value:?}"
88                        );
89                    },
90                    yrs::types::EntryChange::Updated(old_value, new_value) => {
91                        println!(
92                            "更新 key: {key}, old: {old_value:?}, new: {new_value:?}"
93                        );
94                    },
95                }
96            }
97        }));
98        provider.subscription(nodes_map.observe_deep(move |_txn, events| {
99            for event in events.iter() {
100                match event {
101                    yrs::types::Event::Array(_array_event) => {
102                        // 更新了 标记数组 需要转换成 step
103                    },
104                    yrs::types::Event::Map(_map_event) => {
105                        // 更新了 节点属性 需要转换成 step 或者 添加节点
106                    },
107                    _ => {},
108                }
109            }
110        }));
111    }
112    {
113        let client_id_ref = client_id;
114        let mut awareness_lock = awareness.write().await;
115        provider.subscription(awareness_lock.on_update(move |event| {
116            println!("📡 awareness update: {:?}", event.awareness_state());
117            let states = event.awareness_state();
118            for client_id in states.all_clients() {
119                let meta: &yrs::sync::awareness::MetaClientState =
120                    states.get_meta(client_id).unwrap();
121                if client_id == client_id_ref {
122                    // 本地客户端
123                    println!(
124                        "🏠 本地客户端 {}: clock={}, last_updated={:?}",
125                        client_id, meta.clock, meta.last_updated
126                    );
127                } else {
128                    // 远程客户端
129                    println!(
130                        "🌐 远程客户端 {}: clock={}, last_updated={:?}",
131                        client_id, meta.clock, meta.last_updated
132                    );
133                }
134            }
135        }));
136
137        // 🎯 使用唯一的用户 ID 避免状态覆盖
138        awareness_lock.set_local_state(
139            serde_json::json!({
140                "user": {
141                    "id": unique_user_id,
142                    "name": "用户李兴栋",
143                    "color": "#FFEAA7",
144                    "online": true,
145                    "client_id": client_id,
146                    "timestamp": chrono::Utc::now().timestamp()
147                },
148                "online": true
149            })
150            .to_string(),
151        );
152
153        tracing::info!("✅ 设置 awareness 状态完成");
154    }
155
156    // 4. 事件循环
157    let mut counter = 0; // 🔄 添加计数器确保状态变化
158
159    loop {
160        tokio::select! {
161
162            // 定期添加本地更改以测试发送更新
163            _ = time::sleep(Duration::from_secs(3)) => {
164                if provider.is_connected() {
165                    counter += 1; // 🔄 递增计数器
166
167                    let mut awareness_lock = awareness.write().await;
168                    awareness_lock.set_local_state(serde_json::json!({
169                        "user": {
170                            "id": unique_user_id,
171                            "name": "用户李兴栋",
172                            "color": "#FFEAA7",
173                            "online": true,
174                            "client_id": client_id,
175                            "timestamp": chrono::Utc::now().timestamp(),
176                            "heartbeat": counter  // 🔄 添加变化的字段
177                        },
178                        "online": true,
179                        "last_activity": chrono::Utc::now().timestamp()  // 🔄 另一个变化字段
180                    }).to_string());
181
182                    let doc = awareness_lock.doc_mut();
183                    let nodes_map = doc.get_or_insert_map("nodes");
184                    let mut txn = doc.transact_mut_with(doc.client_id().to_string());
185                    // 生成新节点 ID
186            let node_id = uuid::Uuid::new_v4().to_string();
187
188            // 简单地插入一个文本值作为节点内容
189            let node_content = format!("{{\"type\": \"DXGC\", \"id\": \"{node_id}\", \"client\": \"rust_client\"}}");
190            nodes_map.insert(&mut txn, node_id.as_str(), node_content.as_str());
191
192            // 事务会在 drop 时自动提交
193            drop(txn);
194                    tracing::info!("📝 已发送本地文档更改,heartbeat: {}", counter);
195             }
196            }
197            // 处理 Ctrl-C 以优雅地断开连接
198            _ = tokio::signal::ctrl_c() => {
199                tracing::info!("🔌 正在断开连接...");
200                provider.disconnect().await;
201                tracing::info!("✅ 已断开连接。");
202                break;
203            }
204        }
205    }
206
207    Ok(())
208}
Source

pub fn with_client_id(client_id: u64) -> Doc

Creates a new document with a specified client_id. It’s up to a caller to guarantee that this identifier is unique across all communicating replicas of that document.

Source

pub fn with_options(options: Options) -> Doc

Creates a new document with a configured set of Options.

Source

pub fn client_id(&self) -> u64

A unique client identifier, that’s also a unique identifier of current document replica and it’s subdocuments.

Examples found in repository?
examples/client.rs (line 20)
10async fn main() -> Result<(), Box<dyn std::error::Error>> {
11    // 初始化日志
12    tracing_subscriber::fmt().with_max_level(tracing::Level::INFO).init();
13
14    // 从 `collaboration.rs` 测试中获取服务器详细信息
15    let server_url = "ws://127.0.0.1:8080/collaboration"; // 确保端口与服务器测试匹配
16    let room_name = "demo-room";
17
18    // 1. 初始化客户端的文档和 awareness 状态
19    let doc = Doc::new();
20    let client_id = doc.client_id();
21    let awareness: AwarenessRef =
22        Arc::new(tokio::sync::RwLock::new(Awareness::new(doc)));
23
24    // 🔍 生成唯一的用户 ID
25    let unique_user_id =
26        format!("client-user-{}-{}", chrono::Utc::now().timestamp(), client_id);
27
28    tracing::info!("🆔 Yrs Client ID: {}", client_id);
29    tracing::info!("👤 User ID: {}", unique_user_id);
30
31    let mut provider = WebsocketProvider::new(
32        server_url.to_string(),
33        room_name.to_string(),
34        awareness.clone(),
35    )
36    .await;
37
38    // 订阅同步事件
39    if let Some(mut receiver) = provider.subscribe_sync_events() {
40        tokio::spawn(async move {
41            while let Ok(event) = receiver.recv().await {
42                match event {
43                    SyncEvent::InitialSyncCompleted {
44                        has_data,
45                        elapsed_ms,
46                    } => {
47                        if has_data {
48                            println!(
49                                "🎉 同步完成,房间有数据!耗时: {elapsed_ms}ms"
50                            );
51                        } else {
52                            println!(
53                                "📭 同步完成,空房间!耗时: {elapsed_ms}ms"
54                            );
55                        }
56                    },
57                    SyncEvent::ProtocolStateChanged(state) => {
58                        println!("📡 协议状态: {state:?}");
59                    },
60                    SyncEvent::DataReceived => {
61                        println!("📥 收到数据更新");
62                    },
63                    SyncEvent::ConnectionFailed(error) => {
64                        println!("🔌 监听: {error:?}");
65                    },
66                    SyncEvent::ConnectionChanged(status) => {
67                        println!("🔌 连接状态: {status:?}");
68                    },
69                }
70            }
71        });
72    }
73
74    // 3. 连接到服务器
75    provider.connect().await;
76    {
77        let nodes_map = awareness.read().await.doc().get_or_insert_map("nodes");
78        // 订阅 nodes变更 浅
79        provider.subscription(nodes_map.observe(move |txn, event| {
80            for (key, change) in event.keys(txn) {
81                match change {
82                    yrs::types::EntryChange::Inserted(value) => {
83                        println!("新增 key: {key}, value: {value:?}");
84                    },
85                    yrs::types::EntryChange::Removed(old_value) => {
86                        println!(
87                            "删除 key: {key}, old value: {old_value:?}"
88                        );
89                    },
90                    yrs::types::EntryChange::Updated(old_value, new_value) => {
91                        println!(
92                            "更新 key: {key}, old: {old_value:?}, new: {new_value:?}"
93                        );
94                    },
95                }
96            }
97        }));
98        provider.subscription(nodes_map.observe_deep(move |_txn, events| {
99            for event in events.iter() {
100                match event {
101                    yrs::types::Event::Array(_array_event) => {
102                        // 更新了 标记数组 需要转换成 step
103                    },
104                    yrs::types::Event::Map(_map_event) => {
105                        // 更新了 节点属性 需要转换成 step 或者 添加节点
106                    },
107                    _ => {},
108                }
109            }
110        }));
111    }
112    {
113        let client_id_ref = client_id;
114        let mut awareness_lock = awareness.write().await;
115        provider.subscription(awareness_lock.on_update(move |event| {
116            println!("📡 awareness update: {:?}", event.awareness_state());
117            let states = event.awareness_state();
118            for client_id in states.all_clients() {
119                let meta: &yrs::sync::awareness::MetaClientState =
120                    states.get_meta(client_id).unwrap();
121                if client_id == client_id_ref {
122                    // 本地客户端
123                    println!(
124                        "🏠 本地客户端 {}: clock={}, last_updated={:?}",
125                        client_id, meta.clock, meta.last_updated
126                    );
127                } else {
128                    // 远程客户端
129                    println!(
130                        "🌐 远程客户端 {}: clock={}, last_updated={:?}",
131                        client_id, meta.clock, meta.last_updated
132                    );
133                }
134            }
135        }));
136
137        // 🎯 使用唯一的用户 ID 避免状态覆盖
138        awareness_lock.set_local_state(
139            serde_json::json!({
140                "user": {
141                    "id": unique_user_id,
142                    "name": "用户李兴栋",
143                    "color": "#FFEAA7",
144                    "online": true,
145                    "client_id": client_id,
146                    "timestamp": chrono::Utc::now().timestamp()
147                },
148                "online": true
149            })
150            .to_string(),
151        );
152
153        tracing::info!("✅ 设置 awareness 状态完成");
154    }
155
156    // 4. 事件循环
157    let mut counter = 0; // 🔄 添加计数器确保状态变化
158
159    loop {
160        tokio::select! {
161
162            // 定期添加本地更改以测试发送更新
163            _ = time::sleep(Duration::from_secs(3)) => {
164                if provider.is_connected() {
165                    counter += 1; // 🔄 递增计数器
166
167                    let mut awareness_lock = awareness.write().await;
168                    awareness_lock.set_local_state(serde_json::json!({
169                        "user": {
170                            "id": unique_user_id,
171                            "name": "用户李兴栋",
172                            "color": "#FFEAA7",
173                            "online": true,
174                            "client_id": client_id,
175                            "timestamp": chrono::Utc::now().timestamp(),
176                            "heartbeat": counter  // 🔄 添加变化的字段
177                        },
178                        "online": true,
179                        "last_activity": chrono::Utc::now().timestamp()  // 🔄 另一个变化字段
180                    }).to_string());
181
182                    let doc = awareness_lock.doc_mut();
183                    let nodes_map = doc.get_or_insert_map("nodes");
184                    let mut txn = doc.transact_mut_with(doc.client_id().to_string());
185                    // 生成新节点 ID
186            let node_id = uuid::Uuid::new_v4().to_string();
187
188            // 简单地插入一个文本值作为节点内容
189            let node_content = format!("{{\"type\": \"DXGC\", \"id\": \"{node_id}\", \"client\": \"rust_client\"}}");
190            nodes_map.insert(&mut txn, node_id.as_str(), node_content.as_str());
191
192            // 事务会在 drop 时自动提交
193            drop(txn);
194                    tracing::info!("📝 已发送本地文档更改,heartbeat: {}", counter);
195             }
196            }
197            // 处理 Ctrl-C 以优雅地断开连接
198            _ = tokio::signal::ctrl_c() => {
199                tracing::info!("🔌 正在断开连接...");
200                provider.disconnect().await;
201                tracing::info!("✅ 已断开连接。");
202                break;
203            }
204        }
205    }
206
207    Ok(())
208}
Source

pub fn guid(&self) -> &Arc<str>

A globally unique identifier, that’s also a unique identifier of current document replica, and unlike Doc::client_id it’s not shared with its subdocuments.

Source

pub fn options(&self) -> &Options

Returns config options of this Doc instance.

Source

pub fn get_or_insert_text<N>(&self, name: N) -> TextRef
where N: Into<Arc<str>>,

Returns a TextRef data structure stored under a given name. Text structures are used for collaborative text editing: they expose operations to append and remove chunks of text, which are free to execute concurrently by multiple peers over remote boundaries.

If no structure under defined name existed before, it will be created and returned instead.

If a structure under defined name already existed, but its type was different it will be reinterpreted as a text (in such case a sequence component of complex data type will be interpreted as a list of text chunks).

§Panics

This method requires exclusive access to an underlying document store. If there is another transaction in process, it will panic. It’s advised to define all root shared types during the document creation.

Source

pub fn get_or_insert_map<N>(&self, name: N) -> MapRef
where N: Into<Arc<str>>,

Returns a MapRef data structure stored under a given name. Maps are used to store key-value pairs associated. These values can be primitive data (similar but not limited to a JavaScript Object Notation) as well as other shared types (Yrs maps, arrays, text structures etc.), enabling to construct a complex recursive tree structures.

If no structure under defined name existed before, it will be created and returned instead.

If a structure under defined name already existed, but its type was different it will be reinterpreted as a map (in such case a map component of complex data type will be interpreted as native map).

§Panics

This method requires exclusive access to an underlying document store. If there is another transaction in process, it will panic. It’s advised to define all root shared types during the document creation.

Examples found in repository?
examples/client.rs (line 77)
10async fn main() -> Result<(), Box<dyn std::error::Error>> {
11    // 初始化日志
12    tracing_subscriber::fmt().with_max_level(tracing::Level::INFO).init();
13
14    // 从 `collaboration.rs` 测试中获取服务器详细信息
15    let server_url = "ws://127.0.0.1:8080/collaboration"; // 确保端口与服务器测试匹配
16    let room_name = "demo-room";
17
18    // 1. 初始化客户端的文档和 awareness 状态
19    let doc = Doc::new();
20    let client_id = doc.client_id();
21    let awareness: AwarenessRef =
22        Arc::new(tokio::sync::RwLock::new(Awareness::new(doc)));
23
24    // 🔍 生成唯一的用户 ID
25    let unique_user_id =
26        format!("client-user-{}-{}", chrono::Utc::now().timestamp(), client_id);
27
28    tracing::info!("🆔 Yrs Client ID: {}", client_id);
29    tracing::info!("👤 User ID: {}", unique_user_id);
30
31    let mut provider = WebsocketProvider::new(
32        server_url.to_string(),
33        room_name.to_string(),
34        awareness.clone(),
35    )
36    .await;
37
38    // 订阅同步事件
39    if let Some(mut receiver) = provider.subscribe_sync_events() {
40        tokio::spawn(async move {
41            while let Ok(event) = receiver.recv().await {
42                match event {
43                    SyncEvent::InitialSyncCompleted {
44                        has_data,
45                        elapsed_ms,
46                    } => {
47                        if has_data {
48                            println!(
49                                "🎉 同步完成,房间有数据!耗时: {elapsed_ms}ms"
50                            );
51                        } else {
52                            println!(
53                                "📭 同步完成,空房间!耗时: {elapsed_ms}ms"
54                            );
55                        }
56                    },
57                    SyncEvent::ProtocolStateChanged(state) => {
58                        println!("📡 协议状态: {state:?}");
59                    },
60                    SyncEvent::DataReceived => {
61                        println!("📥 收到数据更新");
62                    },
63                    SyncEvent::ConnectionFailed(error) => {
64                        println!("🔌 监听: {error:?}");
65                    },
66                    SyncEvent::ConnectionChanged(status) => {
67                        println!("🔌 连接状态: {status:?}");
68                    },
69                }
70            }
71        });
72    }
73
74    // 3. 连接到服务器
75    provider.connect().await;
76    {
77        let nodes_map = awareness.read().await.doc().get_or_insert_map("nodes");
78        // 订阅 nodes变更 浅
79        provider.subscription(nodes_map.observe(move |txn, event| {
80            for (key, change) in event.keys(txn) {
81                match change {
82                    yrs::types::EntryChange::Inserted(value) => {
83                        println!("新增 key: {key}, value: {value:?}");
84                    },
85                    yrs::types::EntryChange::Removed(old_value) => {
86                        println!(
87                            "删除 key: {key}, old value: {old_value:?}"
88                        );
89                    },
90                    yrs::types::EntryChange::Updated(old_value, new_value) => {
91                        println!(
92                            "更新 key: {key}, old: {old_value:?}, new: {new_value:?}"
93                        );
94                    },
95                }
96            }
97        }));
98        provider.subscription(nodes_map.observe_deep(move |_txn, events| {
99            for event in events.iter() {
100                match event {
101                    yrs::types::Event::Array(_array_event) => {
102                        // 更新了 标记数组 需要转换成 step
103                    },
104                    yrs::types::Event::Map(_map_event) => {
105                        // 更新了 节点属性 需要转换成 step 或者 添加节点
106                    },
107                    _ => {},
108                }
109            }
110        }));
111    }
112    {
113        let client_id_ref = client_id;
114        let mut awareness_lock = awareness.write().await;
115        provider.subscription(awareness_lock.on_update(move |event| {
116            println!("📡 awareness update: {:?}", event.awareness_state());
117            let states = event.awareness_state();
118            for client_id in states.all_clients() {
119                let meta: &yrs::sync::awareness::MetaClientState =
120                    states.get_meta(client_id).unwrap();
121                if client_id == client_id_ref {
122                    // 本地客户端
123                    println!(
124                        "🏠 本地客户端 {}: clock={}, last_updated={:?}",
125                        client_id, meta.clock, meta.last_updated
126                    );
127                } else {
128                    // 远程客户端
129                    println!(
130                        "🌐 远程客户端 {}: clock={}, last_updated={:?}",
131                        client_id, meta.clock, meta.last_updated
132                    );
133                }
134            }
135        }));
136
137        // 🎯 使用唯一的用户 ID 避免状态覆盖
138        awareness_lock.set_local_state(
139            serde_json::json!({
140                "user": {
141                    "id": unique_user_id,
142                    "name": "用户李兴栋",
143                    "color": "#FFEAA7",
144                    "online": true,
145                    "client_id": client_id,
146                    "timestamp": chrono::Utc::now().timestamp()
147                },
148                "online": true
149            })
150            .to_string(),
151        );
152
153        tracing::info!("✅ 设置 awareness 状态完成");
154    }
155
156    // 4. 事件循环
157    let mut counter = 0; // 🔄 添加计数器确保状态变化
158
159    loop {
160        tokio::select! {
161
162            // 定期添加本地更改以测试发送更新
163            _ = time::sleep(Duration::from_secs(3)) => {
164                if provider.is_connected() {
165                    counter += 1; // 🔄 递增计数器
166
167                    let mut awareness_lock = awareness.write().await;
168                    awareness_lock.set_local_state(serde_json::json!({
169                        "user": {
170                            "id": unique_user_id,
171                            "name": "用户李兴栋",
172                            "color": "#FFEAA7",
173                            "online": true,
174                            "client_id": client_id,
175                            "timestamp": chrono::Utc::now().timestamp(),
176                            "heartbeat": counter  // 🔄 添加变化的字段
177                        },
178                        "online": true,
179                        "last_activity": chrono::Utc::now().timestamp()  // 🔄 另一个变化字段
180                    }).to_string());
181
182                    let doc = awareness_lock.doc_mut();
183                    let nodes_map = doc.get_or_insert_map("nodes");
184                    let mut txn = doc.transact_mut_with(doc.client_id().to_string());
185                    // 生成新节点 ID
186            let node_id = uuid::Uuid::new_v4().to_string();
187
188            // 简单地插入一个文本值作为节点内容
189            let node_content = format!("{{\"type\": \"DXGC\", \"id\": \"{node_id}\", \"client\": \"rust_client\"}}");
190            nodes_map.insert(&mut txn, node_id.as_str(), node_content.as_str());
191
192            // 事务会在 drop 时自动提交
193            drop(txn);
194                    tracing::info!("📝 已发送本地文档更改,heartbeat: {}", counter);
195             }
196            }
197            // 处理 Ctrl-C 以优雅地断开连接
198            _ = tokio::signal::ctrl_c() => {
199                tracing::info!("🔌 正在断开连接...");
200                provider.disconnect().await;
201                tracing::info!("✅ 已断开连接。");
202                break;
203            }
204        }
205    }
206
207    Ok(())
208}
Source

pub fn get_or_insert_array<N>(&self, name: N) -> ArrayRef
where N: Into<Arc<str>>,

Returns an ArrayRef data structure stored under a given name. Array structures are used for storing a sequences of elements in ordered manner, positioning given element accordingly to its index.

If no structure under defined name existed before, it will be created and returned instead.

If a structure under defined name already existed, but its type was different it will be reinterpreted as an array (in such case a sequence component of complex data type will be interpreted as a list of inserted values).

§Panics

This method requires exclusive access to an underlying document store. If there is another transaction in process, it will panic. It’s advised to define all root shared types during the document creation.

Source

pub fn get_or_insert_xml_fragment<N>(&self, name: N) -> XmlFragmentRef
where N: Into<Arc<str>>,

Returns a XmlFragmentRef data structure stored under a given name. XML elements represent nodes of XML document. They can contain attributes (key-value pairs, both of string type) and other nested XML elements or text values, which are stored in their insertion order.

If no structure under defined name existed before, it will be created and returned instead.

If a structure under defined name already existed, but its type was different it will be reinterpreted as a XML element (in such case a map component of complex data type will be interpreted as map of its attributes, while a sequence component - as a list of its child XML nodes).

§Panics

This method requires exclusive access to an underlying document store. If there is another transaction in process, it will panic. It’s advised to define all root shared types during the document creation.

Source

pub fn observe_update_v1<F>(&self, f: F) -> Result<Subscription, BorrowMutError>
where F: Fn(&TransactionMut<'_>, &UpdateEvent) + 'static,

Subscribe callback function for any changes performed within transaction scope. These changes are encoded using lib0 v1 encoding and can be decoded using [Update::decode_v1] if necessary or passed to remote peers right away. This callback is triggered on function commit.

Returns a subscription, which will unsubscribe function when dropped.

Source

pub fn observe_update_v2<F>(&self, f: F) -> Result<Subscription, BorrowMutError>
where F: Fn(&TransactionMut<'_>, &UpdateEvent) + 'static,

Subscribe callback function for any changes performed within transaction scope. These changes are encoded using lib0 v2 encoding and can be decoded using [Update::decode_v2] if necessary or passed to remote peers right away. This callback is triggered on function commit.

Returns a subscription, which will unsubscribe function when dropped.

Source

pub fn observe_transaction_cleanup<F>( &self, f: F, ) -> Result<Subscription, BorrowMutError>
where F: Fn(&TransactionMut<'_>, &TransactionCleanupEvent) + 'static,

Subscribe callback function to updates on the Doc. The callback will receive state updates and deletions when a document transaction is committed.

Source

pub fn observe_after_transaction<F>( &self, f: F, ) -> Result<Subscription, BorrowMutError>
where F: Fn(&mut TransactionMut<'_>) + 'static,

Source

pub fn observe_subdocs<F>(&self, f: F) -> Result<Subscription, BorrowMutError>
where F: Fn(&TransactionMut<'_>, &SubdocsEvent) + 'static,

Subscribe callback function, that will be called whenever a subdocuments inserted in this Doc will request a load.

Source

pub fn observe_destroy<F>(&self, f: F) -> Result<Subscription, BorrowMutError>
where F: Fn(&TransactionMut<'_>, &Doc) + 'static,

Subscribe callback function, that will be called whenever a [DocRef::destroy] has been called.

Source

pub fn load<T>(&self, parent_txn: &mut T)
where T: WriteTxn,

Sends a load request to a parent document. Works only if current document is a sub-document of an another document.

Source

pub fn destroy<T>(&self, parent_txn: &mut T)
where T: WriteTxn,

Starts destroy procedure for a current document, triggering an “destroy” callback and invalidating all event callback subscriptions.

Source

pub fn parent_doc(&self) -> Option<Doc>

If current document has been inserted as a sub-document, returns a reference to a parent document, which contains it.

Source

pub fn branch_id(&self) -> Option<BranchID>

Source

pub fn ptr_eq(a: &Doc, b: &Doc) -> bool

Trait Implementations§

Source§

impl Clone for Doc

Source§

fn clone(&self) -> Doc

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Doc

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Default for Doc

Source§

fn default() -> Doc

Returns the “default value” for a type. Read more
Source§

impl Display for Doc

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl PartialEq for Doc

Source§

fn eq(&self, other: &Doc) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Prelim for Doc

Source§

type Return = Doc

Type of a value to be returned as a result of inserting this Prelim type instance. Use Unused if none is necessary.
Source§

fn into_content( self, _txn: &mut TransactionMut<'_>, ) -> (ItemContent, Option<Doc>)

This method is used to create initial content required in order to create a block item. A supplied ptr can be used to identify block that is about to be created to store the returned content. Read more
Source§

fn integrate(self, _txn: &mut TransactionMut<'_>, _inner_ref: BranchPtr)

Method called once an original item filled with content from Self::into_content has been added to block store. This method is used by complex types such as maps or arrays to append the original contents of prelim struct into YMap, YArray etc.
Source§

impl ToJson for Doc

Source§

fn to_json<T>(&self, txn: &T) -> Any
where T: ReadTxn,

Converts all contents of a current type into a JSON-like representation.
Source§

impl Transact for Doc

Source§

fn try_transact(&self) -> Result<Transaction<'_>, TransactionAcqError>

Creates and returns a lightweight read-only transaction. Read more
Source§

fn try_transact_mut(&self) -> Result<TransactionMut<'_>, TransactionAcqError>

Creates and returns a read-write capable transaction. This transaction can be used to mutate the contents of underlying document store and upon dropping or committing it may subscription callbacks. Read more
Source§

fn try_transact_mut_with<T>( &self, origin: T, ) -> Result<TransactionMut<'_>, TransactionAcqError>
where T: Into<Origin>,

Creates and returns a read-write capable transaction with an origin classifier attached. This transaction can be used to mutate the contents of underlying document store and upon dropping or committing it may subscription callbacks. Read more
Source§

fn transact_mut_with<T>(&self, origin: T) -> TransactionMut<'_>
where T: Into<Origin>,

Creates and returns a read-write capable transaction with an origin classifier attached. This transaction can be used to mutate the contents of underlying document store and upon dropping or committing it may subscription callbacks. Read more
Source§

fn transact(&self) -> Transaction<'_>

Creates and returns a lightweight read-only transaction. Read more
Source§

fn transact_mut(&self) -> TransactionMut<'_>

Creates and returns a read-write capable transaction. This transaction can be used to mutate the contents of underlying document store and upon dropping or committing it may subscription callbacks. Read more
Source§

impl TryFrom<ItemPtr> for Doc

Source§

type Error = ItemPtr

The type returned in the event of a conversion error.
Source§

fn try_from(item: ItemPtr) -> Result<Doc, <Doc as TryFrom<ItemPtr>>::Error>

Performs the conversion.
Source§

impl TryFrom<Value> for Doc

Source§

type Error = Value

The type returned in the event of a conversion error.
Source§

fn try_from(value: Value) -> Result<Doc, <Doc as TryFrom<Value>>::Error>

Performs the conversion.
Source§

impl Send for Doc

Source§

impl Sync for Doc

Auto Trait Implementations§

§

impl Freeze for Doc

§

impl !RefUnwindSafe for Doc

§

impl Unpin for Doc

§

impl !UnwindSafe for Doc

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T> ToStringFallible for T
where T: Display,

Source§

fn try_to_string(&self) -> Result<String, TryReserveError>

ToString::to_string, but without panic on OOM.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,