diff --git a/src/patching.spec.ts b/src/patching.spec.ts index 1d8c8df..d3c9961 100644 --- a/src/patching.spec.ts +++ b/src/patching.spec.ts @@ -295,6 +295,34 @@ describe("patchSharedType", () => expect(ymap.get("text").toString()).toBe("bc"); }); + + it("Converts strings to YText in objects", () => + { + ymap.set("state", objectToYMap({ "foo": null, })); + patchSharedType( + ymap.get("state"), + { + "foo": "bar", + } + ); + + expect(ymap.get("state").get("foo")).toBeInstanceOf(Y.Text); + expect(ymap.get("state").get("foo") + .toString()).toBe("bar"); + }); + + it("Converts strings to YText in arrays", () => + { + ymap.set("state", arrayToYArray([])); + patchSharedType( + ymap.get("state"), + [ "bar" ] + ); + + expect(ymap.get("state").get(0)).toBeInstanceOf(Y.Text); + expect(ymap.get("state").get(0) + .toString()).toBe("bar"); + }); }); describe("patchStore", () => diff --git a/src/patching.ts b/src/patching.ts index 1523b5f..54a1fdc 100644 --- a/src/patching.ts +++ b/src/patching.ts @@ -1,7 +1,7 @@ import * as Y from "yjs"; import { ChangeType, Change, } from "./types"; import { getChanges, } from "./diff"; -import { arrayToYArray, objectToYMap, } from "./mapping"; +import { arrayToYArray, objectToYMap, stringToYText, } from "./mapping"; import { State, StoreApi, } from "zustand/vanilla"; /** @@ -31,12 +31,12 @@ export const patchSharedType = ( { if (sharedType instanceof Y.Map) { - if (value instanceof Array) + if (typeof value === "string") + sharedType.set(property as string, stringToYText(value)); + else if (value instanceof Array) sharedType.set(property as string, arrayToYArray(value)); - else if (value instanceof Object) sharedType.set(property as string, objectToYMap(value)); - else sharedType.set(property as string, value); } @@ -48,7 +48,9 @@ export const patchSharedType = ( if (type === ChangeType.UPDATE) sharedType.delete(index); - if (value instanceof Array) + if (typeof value === "string") + sharedType.insert(index, [ stringToYText(value) ]); + else if (value instanceof Array) sharedType.insert(index, [ arrayToYArray(value) ]); else if (value instanceof Object) sharedType.insert(index, [ objectToYMap(value) ]);