|
| 1 | +use std::collections::HashMap; |
| 2 | + |
| 3 | +use serde::Serialize; |
| 4 | +use tokio::sync::Notify; |
| 5 | + |
| 6 | +use super::ot::{apply_actions, transform_actions}; |
| 7 | +use super::Action; |
| 8 | + |
| 9 | +#[derive(Debug)] |
| 10 | +pub struct Document { |
| 11 | + pub buffer: String, |
| 12 | + /// Users can subscribe to document events |
| 13 | + pub notify: Notify, |
| 14 | + pub history: Vec<Action>, |
| 15 | + pub cursors: HashMap<String, Vec<(usize, usize)>>, |
| 16 | +} |
| 17 | + |
| 18 | +#[derive(Clone, Debug, Serialize)] |
| 19 | +pub struct DocumentInfo { |
| 20 | + pub text: String, |
| 21 | + pub revision: usize, |
| 22 | +} |
| 23 | + |
| 24 | +impl From<&Document> for DocumentInfo { |
| 25 | + fn from(value: &Document) -> Self { |
| 26 | + Self { |
| 27 | + text: value.buffer.clone(), |
| 28 | + revision: value.history.len(), |
| 29 | + } |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +impl Document { |
| 34 | + pub fn new() -> Self { |
| 35 | + Document { |
| 36 | + buffer: String::new(), |
| 37 | + notify: Notify::new(), |
| 38 | + history: Vec::new(), |
| 39 | + cursors: HashMap::new(), |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + pub fn new_with(buffer: String) -> Self { |
| 44 | + Document { |
| 45 | + buffer, |
| 46 | + notify: Notify::new(), |
| 47 | + history: Vec::new(), |
| 48 | + cursors: HashMap::new(), |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + pub fn fork(&self) -> Self { |
| 53 | + Document { |
| 54 | + buffer: self.buffer.clone(), |
| 55 | + history: self.history.clone(), |
| 56 | + notify: Notify::new(), |
| 57 | + cursors: HashMap::new(), |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + pub fn revision(&self) -> usize { |
| 62 | + self.history.len() |
| 63 | + } |
| 64 | + |
| 65 | + /// Add actions to document history. |
| 66 | + /// - Transform desynchorized actions |
| 67 | + /// - Notify to document listeners |
| 68 | + pub fn compose(&mut self, revision: usize, mut actions: Vec<Action>) -> Vec<Action> { |
| 69 | + if revision == self.revision() { |
| 70 | + self.buffer = apply_actions(&self.buffer, &actions); |
| 71 | + self.history.extend(actions.iter().cloned()); |
| 72 | + self.notify.notify_waiters(); |
| 73 | + return actions; |
| 74 | + } else if revision > self.history.len() { |
| 75 | + log::warn!("Someone comes from the future"); |
| 76 | + return Vec::new(); |
| 77 | + } |
| 78 | + |
| 79 | + let desynchronized_history = &self.history[revision..]; |
| 80 | + |
| 81 | + transform_actions(actions.as_mut_slice(), desynchronized_history); |
| 82 | + |
| 83 | + self.buffer = apply_actions(&self.buffer, &actions); |
| 84 | + self.history.extend_from_slice(&actions); |
| 85 | + self.notify.notify_waiters(); |
| 86 | + |
| 87 | + actions |
| 88 | + } |
| 89 | +} |
0 commit comments