Skip to content

Commit

Permalink
✅ test: Changes are applied as patches
Browse files Browse the repository at this point in the history
  • Loading branch information
joebobmiles committed Jul 9, 2021
1 parent 49adf5e commit 82ee5d0
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
29 changes: 28 additions & 1 deletion src/patching.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { getChangeList, } from "./patching";
import * as Y from "yjs";
import { objectToYMap, } from "./mapping";
import { getChangeList, patchSharedType, } from "./patching";

describe("getChangeList", () =>
{
Expand Down Expand Up @@ -74,4 +76,29 @@ describe("getChangeList", () =>
.toEqual([ change ]);
}
);
});

describe("patchSharedType", () =>
{
it("Applies additions to the given shared type.", () =>
{
const ydoc = new Y.Doc();
const ymap = ydoc.getMap("tmp");

ymap.set("state", objectToYMap({ }));
patchSharedType({ }, { "foo": 1, }, ymap.get("state"));

expect(ymap.get("state").get("foo")).toBe(1);
});

it("Applies updates to the given shared type.", () =>
{
const ydoc = new Y.Doc();
const ymap = ydoc.getMap("tmp");

ymap.set("state", objectToYMap({ "foo": 1, }));
patchSharedType({ "foo": 1, }, { "foo": 2, }, ymap.get("state"));

expect(ymap.get("state").get("foo")).toBe(2);
});
});
26 changes: 26 additions & 0 deletions src/patching.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import * as Y from "yjs";
import { diff, } from "json-diff";

export type Change = [
Expand Down Expand Up @@ -59,4 +60,29 @@ export const getChangeList = (a: any, b: any): Change[] =>
}

return changes;
};

export const patchSharedType = (
a: any,
b: any,
sharedType: Y.Map<any> | Y.Array<any>
): any =>
{
const changes = getChangeList(a, b);

changes.forEach(([ type, property, value ]) =>
{
switch (type)
{
case "add":
case "update":
if (sharedType instanceof Y.Map)
sharedType.set(property as string, value);

break;

default:
break;
}
});
};

0 comments on commit 82ee5d0

Please sign in to comment.