1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
|
use thiserror::Error;
use uuid::Uuid;
use wasm_bindgen::prelude::*;
use crate::{
doc::{ApplyOpError, Doc},
op::{CreateGrid, Op, OpKind},
vector_clock::VectorClock,
};
mod doc;
mod op;
mod vector_clock;
#[derive(Error, Debug)]
pub enum Error {
#[error("error while realizing state")]
RealizeError(#[from] ApplyOpError),
}
#[wasm_bindgen]
pub struct State {
actor_id: Uuid,
ops: Vec<Op>,
}
impl State {
pub fn new() -> Self {
let actor_id = Uuid::now_v7();
Self {
actor_id,
ops: vec![],
}
}
pub fn append_op(&mut self, kind: OpKind) {
let clock = self
.ops
.last()
.map(|op| op.clock.inc(&self.actor_id))
.unwrap_or_else(|| VectorClock::new().inc(&self.actor_id));
self.ops.push(Op {
id: Uuid::now_v7(),
clock,
kind,
});
}
pub fn realize(&self) -> Result<Doc, Error> {
let mut doc = Doc::default();
for op in &self.ops {
doc.apply_op(op)?;
}
Ok(doc)
}
}
#[wasm_bindgen]
pub fn make_state() -> State {
State::new()
}
#[wasm_bindgen]
pub fn create_grid(state: &mut State) {
state.append_op(OpKind::CreateGrid(CreateGrid {
rows: 4,
base_cells_per_row: 16
}));
}
pub fn realize(state: &State) -> JsValue {
let doc = state.realize().unwrap();
serde_wasm_bindgen::to_value(&doc).unwrap()
}
#[cfg(test)]
mod tests {
use crate::op::CreateGrid;
use super::*;
#[test]
fn test() {
let mut state = State::new();
state.append_op(OpKind::CreateGrid(CreateGrid {
rows: 4,
base_cells_per_row: 16,
}));
let doc = state.realize().unwrap();
let grid = doc.grids.first().unwrap();
assert_eq!(grid.rows.len(), 4);
}
}
|