Skip to content

Commit

Permalink
refactor again
Browse files Browse the repository at this point in the history
  • Loading branch information
dai-shi committed Oct 6, 2023
1 parent 2e71d8c commit f6e65fc
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 16 deletions.
19 changes: 5 additions & 14 deletions src/mutableAtom/index.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,23 @@
import { atom } from 'jotai'
import type { PrimitiveAtom } from 'jotai'
import { proxy, snapshot, subscribe } from 'valtio'
import type {
Action,
ActionWithPayload,
Options,
ProxyState,
Store,
Wrapped,
} from './types'

export function mutableAtom<Value>(
value: Value,
initialValue: Value,
options: Options<Value> = defaultOptions
) {
const valueAtom = atom({ value })
const valueAtom = atom({ value: initialValue })

if (process.env.NODE_ENV !== 'production') {
valueAtom.debugPrivate = true
}
return makeMutableAtom(valueAtom, options)
}

export function makeMutableAtom<Value>(
valueAtom: PrimitiveAtom<Wrapped<Value>>,
options: Options<Value> = defaultOptions
) {
const { proxyFn } = { ...defaultOptions, ...options }

const storeAtom = atom<
Expand All @@ -34,10 +26,9 @@ export function makeMutableAtom<Value>(
void | Value
>(
(_get, { setSelf }) => {
const getValue = () => setSelf({ type: 'getValue' }) as Value
const store: Store<Value> = {
proxyState: createProxyState(getValue(), () => store),
getValue,
proxyState: createProxyState(() => store),
getValue: () => setSelf({ type: 'getValue' }) as Value,
setValue: (value: Value) =>
setSelf({ type: 'setValue', payload: value }) as void,
}
Expand Down Expand Up @@ -72,7 +63,7 @@ export function makeMutableAtom<Value>(
/**
* create the proxy state and subscribe to it
*/
function createProxyState(initialValue: Value, getStore: () => Store<Value>) {
function createProxyState(getStore: () => Store<Value>) {
const proxyState = proxyFn({ value: initialValue })
// We never unsubscribe, but it's garbage collectable.
subscribe(proxyState, onChange(getStore), true)
Expand Down
2 changes: 0 additions & 2 deletions src/mutableAtom/types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
export type Wrapped<T> = { value: T }

type ProxyFn<T> = (obj: Wrapped<T>) => Wrapped<T>

export type Store<Value> = {
Expand Down

0 comments on commit f6e65fc

Please sign in to comment.