From 82ee5d005cb35a93e5ff7b287f884bca4398f8f8 Mon Sep 17 00:00:00 2001 From: Joseph R Miles Date: Fri, 9 Jul 2021 12:25:14 -0700 Subject: [PATCH] :white_check_mark: test: Changes are applied as patches --- src/patching.spec.ts | 29 ++++++++++++++++++++++++++++- src/patching.ts | 26 ++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) diff --git a/src/patching.spec.ts b/src/patching.spec.ts index 5769d61..dcccfb4 100644 --- a/src/patching.spec.ts +++ b/src/patching.spec.ts @@ -1,4 +1,6 @@ -import { getChangeList, } from "./patching"; +import * as Y from "yjs"; +import { objectToYMap, } from "./mapping"; +import { getChangeList, patchSharedType, } from "./patching"; describe("getChangeList", () => { @@ -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); + }); }); \ No newline at end of file diff --git a/src/patching.ts b/src/patching.ts index 29008a2..36ee9b4 100644 --- a/src/patching.ts +++ b/src/patching.ts @@ -1,3 +1,4 @@ +import * as Y from "yjs"; import { diff, } from "json-diff"; export type Change = [ @@ -59,4 +60,29 @@ export const getChangeList = (a: any, b: any): Change[] => } return changes; +}; + +export const patchSharedType = ( + a: any, + b: any, + sharedType: Y.Map | Y.Array +): 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; + } + }); }; \ No newline at end of file