summaryrefslogtreecommitdiff
path: root/packages/doc/src/lib.rs
blob: 93c008a1db6312abaa6b4a75f28e194d59e5ebf1 (plain)
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
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>,
}

#[wasm_bindgen]
impl State {
    #[wasm_bindgen(constructor)]
    pub fn new() -> Self {
        let actor_id = Uuid::now_v7();

        Self {
            actor_id,
            ops: vec![],
        }
    }

    pub fn create_grid(&mut self) {
        self.append_op(OpKind::CreateGrid(CreateGrid {
            rows: 4,
            base_cells_per_row: 16,
        }));
    }

    pub fn to_json(&self) -> Doc {
        self.realize().unwrap()
    }
}

impl State {
    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)
    }
}

#[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);
    }
}