Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
dai-shi committed May 24, 2024
1 parent 640f4ad commit 1044dfa
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 59 deletions.
104 changes: 46 additions & 58 deletions src/vanilla/utils/atomWithStorage.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
import type { WritableAtom } from '../../vanilla.ts'
import { atom } from '../../vanilla.ts'
import type { WritableAtom } from '../../vanilla.ts'
import { RESET } from './constants.ts'

const isPromiseLike = (x: unknown): x is PromiseLike<unknown> =>
typeof (x as any)?.then === 'function'

type Unsubscribe = () => void

type Subscribe<Value> = (
key: string,
callback: (value: Value) => void,
initialValue: Value,
) => Unsubscribe

type Unsubscribe = () => void
type StringSubscribe = (
key: string,
callback: (value: string | null) => void,
) => Unsubscribe

type SetStateActionWithReset<Value> =
| Value
Expand All @@ -22,36 +27,28 @@ export interface AsyncStorage<Value> {
getItem: (key: string, initialValue: Value) => PromiseLike<Value>
setItem: (key: string, newValue: Value) => PromiseLike<void>
removeItem: (key: string) => PromiseLike<void>
subscribe?: (
key: string,
callback: (value: Value) => void,
initialValue: Value,
) => Unsubscribe
subscribe?: Subscribe<Value>
}

export interface SyncStorage<Value> {
getItem: (key: string, initialValue: Value) => Value
setItem: (key: string, newValue: Value) => void
removeItem: (key: string) => void
subscribe?: (
key: string,
callback: (value: Value) => void,
initialValue: Value,
) => Unsubscribe
subscribe?: Subscribe<Value>
}

export interface AsyncStringStorage {
getItem: (key: string) => PromiseLike<string | null>
setItem: (key: string, newValue: string) => PromiseLike<void>
removeItem: (key: string) => PromiseLike<void>
subscribe?: Subscribe<string | null>
subscribe?: StringSubscribe
}

export interface SyncStringStorage {
getItem: (key: string) => string | null
setItem: (key: string, newValue: string) => void
removeItem: (key: string) => void
subscribe?: Subscribe<string | null>
subscribe?: StringSubscribe
}

export function withStorageValidator<Value>(
Expand Down Expand Up @@ -123,39 +120,6 @@ export function createJSONStorage<Value>(
let lastStr: string | undefined
let lastValue: Value

const webStorageSubscribe: Subscribe<Value> = (key, callback) => {
if (!(getStringStorage() instanceof window.Storage)) {
return () => {}
}
const storageEventCallback = (e: StorageEvent) => {
if (e.storageArea === getStringStorage() && e.key === key) {
callback((e.newValue || '') as Value)
}
}
window.addEventListener('storage', storageEventCallback)
return () => {
window.removeEventListener('storage', storageEventCallback)
}
}

const createHandleSubscribe =
(subscriber: Subscribe<Value>) =>
(...params: Parameters<Subscribe<Value>>) => {
const [key, callback, initialValue] = params
function callbackWithParser(v: Value) {
let newValue: Value
try {
newValue = JSON.parse((v as string) || '')
} catch {
newValue = initialValue
}

callback(newValue as Value)
}

return subscriber(key, callbackWithParser, initialValue)
}

const storage: AsyncStorage<Value> | SyncStorage<Value> = {
getItem: (key, initialValue) => {
const parse = (str: string | null) => {
Expand Down Expand Up @@ -184,17 +148,41 @@ export function createJSONStorage<Value>(
removeItem: (key) => getStringStorage()?.removeItem(key),
}

if (
typeof window !== 'undefined' &&
typeof window.addEventListener === 'function'
) {
if (getStringStorage()?.subscribe) {
storage.subscribe = createHandleSubscribe(
getStringStorage()!.subscribe as unknown as Subscribe<Value>,
)
} else if (window.Storage) {
storage.subscribe = createHandleSubscribe(webStorageSubscribe)
}
const createHandleSubscribe =
(subscriber: StringSubscribe): Subscribe<Value> =>
(key, callback, initialValue) =>
subscriber(key, (v) => {
let newValue: Value
try {
newValue = JSON.parse(v || '')
} catch {
newValue = initialValue
}
callback(newValue)
})

const subscriber: StringSubscribe | undefined =
getStringStorage()?.subscribe ||
(typeof window !== 'undefined' &&
typeof window.addEventListener === 'function' &&
((key, callback) => {
if (!(getStringStorage() instanceof window.Storage)) {
return () => {}
}
const storageEventCallback = (e: StorageEvent) => {
if (e.storageArea === getStringStorage() && e.key === key) {
callback(e.newValue)
}
}
window.addEventListener('storage', storageEventCallback)
return () => {
window.removeEventListener('storage', storageEventCallback)
}
})) ||
undefined

if (subscriber) {
storage.subscribe = createHandleSubscribe(subscriber)
}
return storage
}
Expand Down
2 changes: 1 addition & 1 deletion tests/react/vanilla-utils/atomWithStorage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -636,7 +636,7 @@ describe('with subscribe method in string storage', () => {
</StrictMode>,
)

expect(subscribe).toHaveBeenCalledWith('dummy', expect.any(Function), 1)
expect(subscribe).toHaveBeenCalledWith('dummy', expect.any(Function))
})

it('createJSONStorage subscriber responds to events correctly', async () => {
Expand Down

0 comments on commit 1044dfa

Please sign in to comment.