Skip to content

Commit

Permalink
fix: new users no longer nuke existing shared state
Browse files Browse the repository at this point in the history
  • Loading branch information
joebobmiles committed Jul 20, 2021
1 parent f87e118 commit 9701c5b
Show file tree
Hide file tree
Showing 5 changed files with 323 additions and 101 deletions.
5 changes: 5 additions & 0 deletions examples/counter/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

192 changes: 188 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

27 changes: 27 additions & 0 deletions src/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -426,4 +426,31 @@ describe("Yjs middleware (vanilla)", () =>
{ "name": "bob", "status": "online", }
]);
});

it("Does not reset state on join.", () =>
{
type Store =
{
count: number,
increment: () => void,
};

const doc = new Y.Doc();
doc.getMap("hello").set("count", 12);

const api =
create<Store>(yjs(
doc,
"hello",
(set) =>
({
"count": 0,
"increment": () =>
set((state) =>
({ "count": state.count + 1, })),
})
));

expect(api.getState().count).toBe(12);
});
});
10 changes: 7 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
StoreApi,
} from "zustand/vanilla";
import * as Y from "yjs";
import { patchSharedType, patchStore, } from "./patching";
import { patchObject, patchSharedType, patchStore, } from "./patching";

/**
* This function is the middleware the sets up the Zustand store to mirror state
Expand Down Expand Up @@ -45,7 +45,7 @@ const yjs = <S extends State>(
* Capture the initial state so that we can initialize the Yjs store to the
* same values as the initial values of the Zustand store.
*/
const initialState = config(
let initialState = config(
/*
* Create a new set function that defers to the original and then passes
* the new state to patchSharedType.
Expand All @@ -68,7 +68,11 @@ const yjs = <S extends State>(
);

// Initialize the Yjs store.
patchSharedType(map, initialState);
if (Array.from(map.keys()).length === 0)
patchSharedType(map, initialState);

else
initialState = patchObject(initialState, map.toJSON());

/*
* Whenever the Yjs store changes, we perform a set operation on the local
Expand Down
Loading

0 comments on commit 9701c5b

Please sign in to comment.