Skip to content

Commit

Permalink
support valtio v1
Browse files Browse the repository at this point in the history
  • Loading branch information
dai-shi committed Jul 13, 2024
1 parent 79d422f commit 826f506
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 20 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -75,13 +75,13 @@
"react-dom": "^18.3.1",
"ts-expect": "^1.3.0",
"typescript": "^5.5.3",
"valtio": "^2.0.0-rc.0",
"valtio": "^1.13.2",
"vite": "^5.3.3",
"vitest": "^2.0.2",
"zustand": "^4.5.4",
"zustand-valtio": "link:."
},
"peerDependencies": {
"valtio": ">=2.0.0-rc.0"
"valtio": ">=1.0.0"
}
}
28 changes: 19 additions & 9 deletions pnpm-lock.yaml

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

22 changes: 13 additions & 9 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import type { StateCreator, StoreApi, StoreMutatorIdentifier } from 'zustand';
import { proxy, snapshot, subscribe } from 'valtio/vanilla';
import type { Snapshot } from 'valtio/vanilla';

// TODO replace with Valtio's Snapshot type in v2
type Snapshot<T> = T extends (...args: never[]) => unknown
? T
: T extends object
? { readonly [K in keyof T]: Snapshot<T[K]> }
: T;

type StoreWithProxy<T> = {
setState: never;
Expand All @@ -9,16 +15,14 @@ type StoreWithProxy<T> = {

type Write<T, U> = Omit<T, keyof U> & U;

type DeepWritable<T> = T extends object
? {
-readonly [K in keyof T]: DeepWritable<T[K]>;
}
: T;

type WithWithProxy<S, _A> = S extends { getState: () => Snapshot<infer T> }
? Write<S, StoreWithProxy<DeepWritable<T>>>
: never;

type DeepWritable<T> = T extends object
? { -readonly [K in keyof T]: DeepWritable<T[K]> }
: T;

declare module 'zustand/vanilla' {
interface StoreMutators<S, A> {
'zustand-valtio': WithWithProxy<S, A>;
Expand All @@ -45,7 +49,7 @@ const withProxyImpl: WithProxyImpl = (initialObject) => (set, get, api) => {
const updateState = () => {
if (!mutating) {
++updating;
set(snapshot(proxyState), true);
set(snapshot(proxyState) as Snapshot<typeof proxyState>, true);
--updating;
}
};
Expand Down Expand Up @@ -82,7 +86,7 @@ const withProxyImpl: WithProxyImpl = (initialObject) => (set, get, api) => {
});
}
});
return snapshot(proxyState);
return snapshot(proxyState) as Snapshot<typeof proxyState>;
};

export const withProxy = withProxyImpl as unknown as WithProxy;

0 comments on commit 826f506

Please sign in to comment.