/* * Copyright (C) Contributors to the Suwayomi project * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ import { Dispatch, Reducer, SetStateAction, useCallback, useMemo, useReducer, useSyncExternalStore } from 'react'; import { AppStorage, Storage } from '@/util/AppStorage.ts'; const subscribeToStorageUpdates = (callback: () => void) => { window.addEventListener('storage', callback); return () => window.removeEventListener('storage', callback); }; function useStorage(storage: Storage, key: string, defaultValue: T | (() => T)): [T, Dispatch>]; function useStorage( storage: Storage, key: string, ): [T | undefined, Dispatch>]; function useStorage( storage: Storage, key: string, defaultValue?: T | (() => T) | undefined, ): [T | undefined, Dispatch>] { const initialState = defaultValue instanceof Function ? defaultValue() : defaultValue; const storedValueRaw = useSyncExternalStore(subscribeToStorageUpdates, () => storage.getItem(key)); const setValue = useCallback>>( (value) => { // Allow value to be a function so we have same API as useState const valueToStore = value instanceof Function ? value(storage.getItemParsed(key, initialState)) : value; storage.setItem(key, valueToStore); }, [key], ); const storedValue = useMemo( () => (storedValueRaw !== null ? JSON.parse(storedValueRaw) : initialState), [storedValueRaw, key], ); return [storedValue, setValue]; } const useReducerStorage = ( storage: Storage, reducer: Reducer, key: string, defaultState: S | (() => S), ) => { const [storedValue, setValue] = useStorage(storage, key, defaultState); return useReducer((state: S, action: A): S => { const newState = reducer(state, action); setValue(newState); return newState; }, storedValue); }; export function useLocalStorage(key: string, defaultValue: T | (() => T)): [T, Dispatch>]; export function useLocalStorage(key: string): [T | undefined, Dispatch>]; export function useLocalStorage( key: string, defaultValue?: T | undefined | (() => T | undefined), ): [T | undefined, Dispatch>] { return useStorage(AppStorage.local, key, defaultValue); } export function useReducerLocalStorage(reducer: Reducer, key: string, defaultState: S | (() => S)) { return useReducerStorage(AppStorage.local, reducer, key, defaultState); } export function useSessionStorage(key: string, defaultValue: T | (() => T)): [T, Dispatch>]; export function useSessionStorage(key: string): [T | undefined, Dispatch>]; export function useSessionStorage( key: string, defaultValue?: T | (() => T), ): [T | undefined, Dispatch>] { return useStorage(AppStorage.session, key, defaultValue); } export function useReducerSessionStorage(reducer: Reducer, key: string, defaultState: S | (() => S)) { return useReducerStorage(AppStorage.session, reducer, key, defaultState); }