Skip to content

Commit

Permalink
fix: tested string to YText conversion
Browse files Browse the repository at this point in the history
Last thing we needed to test was that we were converting strings
to YText objects whenever we went to patch shared types.
  • Loading branch information
joebobmiles committed Mar 14, 2023
1 parent d65f5a0 commit 8f60467
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 5 deletions.
28 changes: 28 additions & 0 deletions src/patching.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () =>
Expand Down
12 changes: 7 additions & 5 deletions src/patching.ts
Original file line number Diff line number Diff line change
@@ -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";

/**
Expand Down Expand Up @@ -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);
}
Expand All @@ -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) ]);
Expand Down

0 comments on commit 8f60467

Please sign in to comment.