Skip to content

Commit

Permalink
feat(json-crdt): 馃幐 add Model.create() method
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich committed May 1, 2024
1 parent 692a626 commit 8fc8fc0
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
6 changes: 2 additions & 4 deletions src/json-crdt-extensions/peritext/Peritext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,10 @@ export class Peritext implements Printable {
) {
this.savedSlices = new Slices(this.model, slices, this.str);

const extraModel = Model.withLogicalClock(SESSION.GLOBAL)
.setSchema(s.vec(s.arr([])))
.fork(this.model.clock.sid + 1);
const extraModel = Model.create(s.vec(s.arr([])), this.model.clock.sid - 1);
this.extraSlices = new Slices(extraModel, extraModel.root.node().get(0)!, this.str);

const localModel = Model.withLogicalClock(SESSION.LOCAL).setSchema(s.vec(s.arr([])));
const localModel = Model.create(s.vec(s.arr([])), SESSION.LOCAL);
const localApi = localModel.api;
localApi.onLocalChange.listen(() => {
localApi.flush();
Expand Down
14 changes: 14 additions & 0 deletions src/json-crdt/model/Model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,20 @@ export class Model<N extends JsonNode = JsonNode<any>> implements Printable {
return new Model(clockVector);
}

/**
* Create a new strictly typed JSON CRDT model.
*
* @param schema The schema (typing and default value) to set for this model.
* @param sid Session ID to use for local operations. Defaults to a random
* session ID.
* @returns A strictly typed model.
*/
public static create<S extends NodeBuilder>(schema?: S, sid: number = randomSessionId()): Model<SchemaToJsonNode<S>> {
const model = Model.withLogicalClock(sid) as unknown as Model<SchemaToJsonNode<S>>;
if (schema) model.setSchema(schema, true);
return model as Model<SchemaToJsonNode<S>>;
}

/**
* Un-serializes a model from "binary" structural encoding.
* @param data Binary blob of a model encoded using "binary" structural
Expand Down

0 comments on commit 8fc8fc0

Please sign in to comment.