Skip to content

Commit

Permalink
fix: strings properly mapped to YText
Browse files Browse the repository at this point in the history
  • Loading branch information
joebobmiles committed Jun 9, 2023
1 parent 6cab94b commit be0abe6
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
35 changes: 35 additions & 0 deletions src/index.spec.ts
Expand Up @@ -619,6 +619,41 @@ describe("Yjs middleware", () =>
}).not.toThrow();
});
});

// See issue #49
describe("When nesting strings into arrays and objects", () =>
{
it("Does not crash", () =>
{
type Store =
{
foo: { bar: string }
updateFoo: (s: string) => void
};

const doc = new Y.Doc();

const api = createVanilla<Store>(yjs(
doc,
"hello",
(set) =>
({
"foo": {
"bar": "baz",
},
"updateFoo": (s: string) =>
set((state) =>
({ ...state, "foo": { "bar": s, }, })),
})
));

expect(() =>
{
api.getState().updateFoo("bingo");
api.getState().updateFoo("bango"); // Always on subsequent update
}).not.toThrow();
});
});
});

describe("Yjs middleware with network provider", () =>
Expand Down
21 changes: 21 additions & 0 deletions src/mapping.spec.ts
Expand Up @@ -67,6 +67,16 @@ describe("arrayToYArray", () =>
expect(ymap.get("array").get(0)
.get("foo")).toBe(1);
});

it("Creates YText nested in YArrays from strings nested in arrays.", () =>
{
ymap.set("array", arrayToYArray([ "hello" ]));

expect(ymap.get("array").toJSON()).toEqual([ "hello" ]);
expect(ymap.get("array").get(0)).toBeInstanceOf(Y.Text);
expect(ymap.get("array").get(0)
.toString()).toBe("hello");
});
});

describe("yArrayToArray", () =>
Expand Down Expand Up @@ -167,6 +177,17 @@ describe("objectToYMap", () =>
expect((ymap.get("map") as Y.Map<any>).get("foo").get(0)).toBe(1);
expect((ymap.get("map") as Y.Map<any>).get("foo").get(1)).toBe(2);
});

it("Converts strings into YText.", () =>
{
const ydoc = new Y.Doc();
const ymap = ydoc.getMap("tmp");

ymap.set("map", objectToYMap({ "foo": "bar", }));

expect((ymap.get("map") as Y.Map<any>).get("foo")).toBeInstanceOf(Y.Text);
expect((ymap.get("map") as Y.Map<any>).get("foo").toString()).toBe("bar");
});
});

describe("yMapToObject", () =>
Expand Down
6 changes: 6 additions & 0 deletions src/mapping.ts
Expand Up @@ -28,6 +28,9 @@ export const arrayToYArray = (array: any[]): Y.Array<any> =>
else if (value instanceof Object)
yarray.push([ objectToYMap(value) ]);

else if (typeof value === "string")
yarray.push([ stringToYText(value) ]);

else
yarray.push([ value ]);
});
Expand Down Expand Up @@ -102,6 +105,9 @@ export const objectToYMap = (object: any): Y.Map<any> =>
else if (value instanceof Object)
ymap.set(property, objectToYMap(value));

else if (typeof value === "string")
ymap.set(property, stringToYText(value));

else
ymap.set(property, value);
});
Expand Down

0 comments on commit be0abe6

Please sign in to comment.