diff --git a/.editorconfig b/.editorconfig index d5ca7cabe0..92b7b4bec2 100644 --- a/.editorconfig +++ b/.editorconfig @@ -8,7 +8,7 @@ indent_size = 2 indent_style = space insert_final_newline = true trim_trailing_whitespace = true -max_line_length = 120 +max_line_length = 100 [*.{ts, tsx}] ij_typescript_enforce_trailing_comma = keep @@ -24,7 +24,7 @@ ij_typescript_catch_on_new_line = false ij_typescript_spaces_within_interpolation_expressions = false [*.md] -max_line_length = 120 +max_line_length = 100 trim_trailing_whitespace = false [COMMIT_EDITMSG] diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 0000000000..bc52136957 --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,22 @@ +module.exports = { + extends: ['prettier/@typescript-eslint', 'react-app', 'plugin:prettier/recommended'], + plugins: ['prettier'], + rules: { + 'prettier/prettier': [ + 'error', + { + singleQuote: true, + trailingComma: 'es5', + tabWidth: 2, + printWidth: 100, + semicolons: true, + quoteProps: 'as-needed', + jsxSingleQuote: false, + bracketSpacing: true, + jsxBracketSameLine: true, + arrowParens: 'always', + endOfLine: 'lf', + }, + ], + }, +}; diff --git a/.eslintrc.json b/.eslintrc.json deleted file mode 100644 index 4bed466c11..0000000000 --- a/.eslintrc.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": "react-app" -} \ No newline at end of file diff --git a/.prettierrc b/.prettierrc deleted file mode 100644 index b854f157bd..0000000000 --- a/.prettierrc +++ /dev/null @@ -1,6 +0,0 @@ -{ - "trailingComma": "es5", - "singleQuote": true, - "printWidth": 120, - "tabWidth": 2 -} diff --git a/package.json b/package.json index d05f827143..82e801710f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "react-use", - "version": "17.0.2", + "version": "17.0.0", "description": "Collection of React Hooks", "main": "lib/index.js", "module": "esm/index.js", @@ -17,10 +17,9 @@ "test:ssr": "jest --maxWorkers 2 --config ./jest.config.node.ts", "test:watch": "jest --watch", "test:coverage": "jest --coverage", - "lint": "eslint {src,tests}/**/*.{ts,tsx}", + "lint": "eslint {src,tests,stories}/**/*.{ts,tsx}", "lint:fix": "yarn lint --fix", - "lint:types": "tsc --noEmit ", - "lint:prettier": "prettier --write src/**/**/*.{ts,tsx}", + "lint:types": "tsc --noEmit", "build:cjs": "tsc", "build:es": "tsc -m esNext --outDir esm", "build": "yarn build:cjs && yarn build:es", @@ -33,7 +32,7 @@ }, "husky": { "hooks": { - "pre-commit": "yarn lint:types && lint-staged", + "pre-commit": "lint-staged", "pre-push": "yarn lint && yarn clean && yarn build && yarn test" } }, @@ -93,10 +92,12 @@ "babel-loader": "8.2.2", "babel-plugin-dynamic-import-node": "2.3.3", "eslint": "7.19.0", + "eslint-config-prettier": "^7.2.0", "eslint-config-react-app": "6.0.0", "eslint-plugin-flowtype": "5.2.0", "eslint-plugin-import": "2.22.1", "eslint-plugin-jsx-a11y": "6.4.1", + "eslint-plugin-prettier": "^3.3.1", "eslint-plugin-react": "7.22.0", "eslint-plugin-react-hooks": "4.2.0", "fork-ts-checker-webpack-plugin": "6.1.0", @@ -107,7 +108,7 @@ "keyboardjs": "2.6.4", "lint-staged": "10.5.3", "markdown-loader": "6.0.0", - "prettier": "2.2.1", + "prettier": "^2.2.1", "raf-stub": "3.0.0", "react": "17.0.1", "react-dom": "17.0.1", @@ -152,7 +153,6 @@ "lint-staged": { "src/**/**/*.{ts,tsx}": [ "eslint --fix", - "prettier --write", "git add" ] }, diff --git a/src/component/UseKey.tsx b/src/component/UseKey.tsx index 0cf069c4a6..7420475582 100644 --- a/src/component/UseKey.tsx +++ b/src/component/UseKey.tsx @@ -1,6 +1,11 @@ import useKey from '../useKey'; import createRenderProp from '../factory/createRenderProp'; -const UseKey = createRenderProp(useKey, ({ filter, fn, deps, ...rest }) => [filter, fn, rest, deps]); +const UseKey = createRenderProp(useKey, ({ filter, fn, deps, ...rest }) => [ + filter, + fn, + rest, + deps, +]); export default UseKey; diff --git a/src/factory/createBreakpoint.ts b/src/factory/createBreakpoint.ts index 92f5c301cb..e5003ee5e3 100644 --- a/src/factory/createBreakpoint.ts +++ b/src/factory/createBreakpoint.ts @@ -16,9 +16,10 @@ const createBreakpoint = ( off(window, 'resize', setSideScreen); }; }); - const sortedBreakpoints = useMemo(() => Object.entries(breakpoints).sort((a, b) => (a[1] >= b[1] ? 1 : -1)), [ - breakpoints, - ]); + const sortedBreakpoints = useMemo( + () => Object.entries(breakpoints).sort((a, b) => (a[1] >= b[1] ? 1 : -1)), + [breakpoints] + ); const result = sortedBreakpoints.reduce((acc, [name, width]) => { if (screen >= width) { return name; diff --git a/src/factory/createHTMLMediaHook.ts b/src/factory/createHTMLMediaHook.ts index fbea71b3a1..bd384f5037 100644 --- a/src/factory/createHTMLMediaHook.ts +++ b/src/factory/createHTMLMediaHook.ts @@ -3,7 +3,9 @@ import { useEffect, useRef } from 'react'; import useSetState from '../useSetState'; import parseTimeRanges from '../misc/parseTimeRanges'; -export interface HTMLMediaProps extends React.AudioHTMLAttributes, React.VideoHTMLAttributes { +export interface HTMLMediaProps + extends React.AudioHTMLAttributes, + React.VideoHTMLAttributes { src: string; } @@ -33,7 +35,9 @@ type createHTMLMediaHookReturn = [ ]; export default function createHTMLMediaHook(tag: 'audio' | 'video') { - return (elOrProps: HTMLMediaProps | React.ReactElement): createHTMLMediaHookReturn => { + return ( + elOrProps: HTMLMediaProps | React.ReactElement + ): createHTMLMediaHookReturn => { let element: React.ReactElement | undefined; let props: HTMLMediaProps; diff --git a/src/factory/createReducer.ts b/src/factory/createReducer.ts index 16cde29084..ef2af42efc 100644 --- a/src/factory/createReducer.ts +++ b/src/factory/createReducer.ts @@ -8,7 +8,9 @@ interface Store { dispatch: Dispatch; } -type Middleware = (store: Store) => (next: Dispatch) => (action: Action) => void; +type Middleware = ( + store: Store +) => (next: Dispatch) => (action: Action) => void; function composeMiddleware(chain: Middleware[]) { return (context: Store, dispatch: Dispatch) => { diff --git a/src/factory/createReducerContext.ts b/src/factory/createReducerContext.ts index 2bd3605b9e..f07a0165ab 100644 --- a/src/factory/createReducerContext.ts +++ b/src/factory/createReducerContext.ts @@ -4,11 +4,19 @@ const createReducerContext = >( reducer: R, defaultInitialState: React.ReducerState ) => { - const context = createContext<[React.ReducerState, React.Dispatch>] | undefined>(undefined); + const context = createContext< + [React.ReducerState, React.Dispatch>] | undefined + >(undefined); const providerFactory = (props, children) => createElement(context.Provider, props, children); - const ReducerProvider: React.FC<{ initialState?: React.ReducerState }> = ({ children, initialState }) => { - const state = useReducer(reducer, initialState !== undefined ? initialState : defaultInitialState); + const ReducerProvider: React.FC<{ initialState?: React.ReducerState }> = ({ + children, + initialState, + }) => { + const state = useReducer( + reducer, + initialState !== undefined ? initialState : defaultInitialState + ); return providerFactory({ value: state }, children); }; diff --git a/src/factory/createStateContext.ts b/src/factory/createStateContext.ts index 263a8a3ce6..3e73ef93e6 100644 --- a/src/factory/createStateContext.ts +++ b/src/factory/createStateContext.ts @@ -1,7 +1,9 @@ import { createContext, createElement, useContext, useState } from 'react'; const createStateContext = (defaultInitialValue: T) => { - const context = createContext<[T, React.Dispatch>] | undefined>(undefined); + const context = createContext<[T, React.Dispatch>] | undefined>( + undefined + ); const providerFactory = (props, children) => createElement(context.Provider, props, children); const StateProvider: React.FC<{ initialValue?: T }> = ({ children, initialValue }) => { diff --git a/src/misc/hookState.ts b/src/misc/hookState.ts index e89ae165ba..8d163e683f 100644 --- a/src/misc/hookState.ts +++ b/src/misc/hookState.ts @@ -7,9 +7,18 @@ export type IHookStateSetAction = S | IHookStateSetter; export type IHookStateResolvable = S | IHookStateInitialSetter | IHookStateSetter; export function resolveHookState(nextState: IHookStateInitAction): S; -export function resolveHookState(nextState: IHookStateSetAction, currentState?: C): S; -export function resolveHookState(nextState: IHookStateResolvable, currentState?: C): S; -export function resolveHookState(nextState: IHookStateResolvable, currentState?: C): S { +export function resolveHookState( + nextState: IHookStateSetAction, + currentState?: C +): S; +export function resolveHookState( + nextState: IHookStateResolvable, + currentState?: C +): S; +export function resolveHookState( + nextState: IHookStateResolvable, + currentState?: C +): S { if (typeof nextState === 'function') { return nextState.length ? (nextState as Function)(currentState) : (nextState as Function)(); } diff --git a/src/useAsync.ts b/src/useAsync.ts index e5e710b659..f30c85caa9 100644 --- a/src/useAsync.ts +++ b/src/useAsync.ts @@ -4,7 +4,10 @@ import { FunctionReturningPromise } from './misc/types'; export { AsyncState, AsyncFnReturn } from './useAsyncFn'; -export default function useAsync(fn: T, deps: DependencyList = []) { +export default function useAsync( + fn: T, + deps: DependencyList = [] +) { const [state, callback] = useAsyncFn(fn, deps, { loading: true, }); diff --git a/src/useAsyncFn.ts b/src/useAsyncFn.ts index 3f3885fd62..c085536b01 100644 --- a/src/useAsyncFn.ts +++ b/src/useAsyncFn.ts @@ -24,7 +24,9 @@ export type AsyncState = value: T; }; -type StateFromFunctionReturningPromise = AsyncState>>; +type StateFromFunctionReturningPromise = AsyncState< + PromiseType> +>; export type AsyncFnReturn = [ StateFromFunctionReturningPromise, diff --git a/src/useAsyncRetry.ts b/src/useAsyncRetry.ts index a51c18b09d..04119d957f 100644 --- a/src/useAsyncRetry.ts +++ b/src/useAsyncRetry.ts @@ -13,7 +13,9 @@ const useAsyncRetry = (fn: () => Promise, deps: DependencyList = []) => { const retry = useCallback(() => { if (stateLoading) { if (process.env.NODE_ENV === 'development') { - console.log('You are calling useAsyncRetry hook retry() method while loading in progress, this is a no-op.'); + console.log( + 'You are calling useAsyncRetry hook retry() method while loading in progress, this is a no-op.' + ); } return; diff --git a/src/useCopyToClipboard.ts b/src/useCopyToClipboard.ts index 783ba0effd..9656d9efd7 100644 --- a/src/useCopyToClipboard.ts +++ b/src/useCopyToClipboard.ts @@ -26,7 +26,9 @@ const useCopyToClipboard = (): [CopyToClipboardState, (value: string) => void] = try { // only strings and numbers casted to strings can be copied to clipboard if (typeof value !== 'string' && typeof value !== 'number') { - const error = new Error(`Cannot copy typeof ${typeof value} to clipboard, must be a string`); + const error = new Error( + `Cannot copy typeof ${typeof value} to clipboard, must be a string` + ); if (process.env.NODE_ENV === 'development') console.error(error); setState({ value, diff --git a/src/useCounter.ts b/src/useCounter.ts index 7878dcb30c..cb4a3b830a 100644 --- a/src/useCounter.ts +++ b/src/useCounter.ts @@ -17,7 +17,8 @@ export default function useCounter( ): [number, CounterActions] { let init = resolveHookState(initialValue); - typeof init !== 'number' && console.error('initialValue has to be a number, got ' + typeof initialValue); + typeof init !== 'number' && + console.error('initialValue has to be a number, got ' + typeof initialValue); if (typeof min === 'number') { init = Math.max(init, min); @@ -59,7 +60,9 @@ export default function useCounter( const rDelta = resolveHookState(delta, get()); if (typeof rDelta !== 'number') { - console.error('delta has to be a number or function returning a number, got ' + typeof rDelta); + console.error( + 'delta has to be a number or function returning a number, got ' + typeof rDelta + ); } set((num: number) => num + rDelta); @@ -68,7 +71,9 @@ export default function useCounter( const rDelta = resolveHookState(delta, get()); if (typeof rDelta !== 'number') { - console.error('delta has to be a number or function returning a number, got ' + typeof rDelta); + console.error( + 'delta has to be a number or function returning a number, got ' + typeof rDelta + ); } set((num: number) => num - rDelta); @@ -77,7 +82,9 @@ export default function useCounter( const rValue = resolveHookState(value, get()); if (typeof rValue !== 'number') { - console.error('value has to be a number or function returning a number, got ' + typeof rValue); + console.error( + 'value has to be a number or function returning a number, got ' + typeof rValue + ); } // eslint-disable-next-line react-hooks/exhaustive-deps diff --git a/src/useCustomCompareEffect.ts b/src/useCustomCompareEffect.ts index b5c7314292..0ac38bb1c4 100644 --- a/src/useCustomCompareEffect.ts +++ b/src/useCustomCompareEffect.ts @@ -11,7 +11,9 @@ const useCustomCompareEffect = ( ) => { if (process.env.NODE_ENV !== 'production') { if (!(deps instanceof Array) || !deps.length) { - console.warn('`useCustomCompareEffect` should not be used with no dependencies. Use React.useEffect instead.'); + console.warn( + '`useCustomCompareEffect` should not be used with no dependencies. Use React.useEffect instead.' + ); } if (deps.every(isPrimitive)) { @@ -21,7 +23,9 @@ const useCustomCompareEffect = ( } if (typeof depsEqual !== 'function') { - console.warn('`useCustomCompareEffect` should be used with depsEqual callback for comparing deps list'); + console.warn( + '`useCustomCompareEffect` should be used with depsEqual callback for comparing deps list' + ); } } diff --git a/src/useDebounce.ts b/src/useDebounce.ts index 3043eecd60..70956d82a1 100644 --- a/src/useDebounce.ts +++ b/src/useDebounce.ts @@ -3,7 +3,11 @@ import useTimeoutFn from './useTimeoutFn'; export type UseDebounceReturn = [() => boolean | null, () => void]; -export default function useDebounce(fn: Function, ms: number = 0, deps: DependencyList = []): UseDebounceReturn { +export default function useDebounce( + fn: Function, + ms: number = 0, + deps: DependencyList = [] +): UseDebounceReturn { const [isReady, cancel, reset] = useTimeoutFn(fn, ms); useEffect(reset, deps); diff --git a/src/useDeepCompareEffect.ts b/src/useDeepCompareEffect.ts index aec61b23e3..14c08c4ff0 100644 --- a/src/useDeepCompareEffect.ts +++ b/src/useDeepCompareEffect.ts @@ -7,7 +7,9 @@ const isPrimitive = (val: any) => val !== Object(val); const useDeepCompareEffect = (effect: EffectCallback, deps: DependencyList) => { if (process.env.NODE_ENV !== 'production') { if (!(deps instanceof Array) || !deps.length) { - console.warn('`useDeepCompareEffect` should not be used with no dependencies. Use React.useEffect instead.'); + console.warn( + '`useDeepCompareEffect` should not be used with no dependencies. Use React.useEffect instead.' + ); } if (deps.every(isPrimitive)) { diff --git a/src/useDefault.ts b/src/useDefault.ts index 108ac52289..3234e2c4e9 100644 --- a/src/useDefault.ts +++ b/src/useDefault.ts @@ -1,6 +1,9 @@ import { useState } from 'react'; -const useDefault = (defaultValue: TStateType, initialValue: TStateType | (() => TStateType)) => { +const useDefault = ( + defaultValue: TStateType, + initialValue: TStateType | (() => TStateType) +) => { const [value, setValue] = useState(initialValue); if (value === undefined || value === null) { diff --git a/src/useDropArea.ts b/src/useDropArea.ts index 41996dd6e8..76e399ff46 100644 --- a/src/useDropArea.ts +++ b/src/useDropArea.ts @@ -26,7 +26,10 @@ const defaultState: DropAreaState = { }; */ -const createProcess = (options: DropAreaOptions, mounted: boolean) => (dataTransfer: DataTransfer, event) => { +const createProcess = (options: DropAreaOptions, mounted: boolean) => ( + dataTransfer: DataTransfer, + event +) => { const uri = dataTransfer.getData('text/uri-list'); if (uri) { diff --git a/src/useEnsuredForwardedRef.ts b/src/useEnsuredForwardedRef.ts index cc789e6674..ad26fd1a72 100644 --- a/src/useEnsuredForwardedRef.ts +++ b/src/useEnsuredForwardedRef.ts @@ -10,7 +10,9 @@ import { useRef, } from 'react'; -export default function useEnsuredForwardedRef(forwardedRef: MutableRefObject): MutableRefObject { +export default function useEnsuredForwardedRef( + forwardedRef: MutableRefObject +): MutableRefObject { const ensuredRef = useRef(forwardedRef && forwardedRef.current); useEffect(() => { diff --git a/src/useEvent.ts b/src/useEvent.ts index c93e5002a2..24cf4d3f37 100644 --- a/src/useEvent.ts +++ b/src/useEvent.ts @@ -24,7 +24,11 @@ const isListenerType2 = (target: any): target is ListenerType2 => { return !!target.on; }; -type AddEventListener = T extends ListenerType1 ? T['addEventListener'] : T extends ListenerType2 ? T['on'] : never; +type AddEventListener = T extends ListenerType1 + ? T['addEventListener'] + : T extends ListenerType2 + ? T['on'] + : never; const useEvent = ( name: Parameters>[0], diff --git a/src/useFavicon.ts b/src/useFavicon.ts index 8f1b80d997..b470cf223e 100644 --- a/src/useFavicon.ts +++ b/src/useFavicon.ts @@ -2,7 +2,8 @@ import { useEffect } from 'react'; const useFavicon = (href: string) => { useEffect(() => { - const link: HTMLLinkElement = document.querySelector("link[rel*='icon']") || document.createElement('link'); + const link: HTMLLinkElement = + document.querySelector("link[rel*='icon']") || document.createElement('link'); link.type = 'image/x-icon'; link.rel = 'shortcut icon'; link.href = href; diff --git a/src/useFullscreen.ts b/src/useFullscreen.ts index 32c038ee09..f795bb3b14 100644 --- a/src/useFullscreen.ts +++ b/src/useFullscreen.ts @@ -4,11 +4,17 @@ import useIsomorphicLayoutEffect from './useIsomorphicLayoutEffect'; import { noop, off, on } from './misc/util'; export interface FullScreenOptions { - video?: RefObject void; webkitExitFullscreen?: () => void }>; + video?: RefObject< + HTMLVideoElement & { webkitEnterFullscreen?: () => void; webkitExitFullscreen?: () => void } + >; onClose?: (error?: Error) => void; } -const useFullscreen = (ref: RefObject, enabled: boolean, options: FullScreenOptions = {}): boolean => { +const useFullscreen = ( + ref: RefObject, + enabled: boolean, + options: FullScreenOptions = {} +): boolean => { const { video, onClose = noop } = options; const [isFullscreen, setIsFullscreen] = useState(enabled); diff --git a/src/useGetSetState.ts b/src/useGetSetState.ts index 90e70af33e..061c178b7e 100644 --- a/src/useGetSetState.ts +++ b/src/useGetSetState.ts @@ -1,7 +1,9 @@ import { useCallback, useRef } from 'react'; import useUpdate from './useUpdate'; -const useGetSetState = (initialState: T = {} as T): [() => T, (patch: Partial) => void] => { +const useGetSetState = ( + initialState: T = {} as T +): [() => T, (patch: Partial) => void] => { if (process.env.NODE_ENV !== 'production') { if (typeof initialState !== 'object') { console.error('useGetSetState initial state must be an object.'); diff --git a/src/useIdle.ts b/src/useIdle.ts index 0ec1f17151..e5eb9a152f 100644 --- a/src/useIdle.ts +++ b/src/useIdle.ts @@ -5,7 +5,11 @@ import { off, on } from './misc/util'; const defaultEvents = ['mousemove', 'mousedown', 'resize', 'keydown', 'touchstart', 'wheel']; const oneMinute = 60e3; -const useIdle = (ms: number = oneMinute, initialState: boolean = false, events: string[] = defaultEvents): boolean => { +const useIdle = ( + ms: number = oneMinute, + initialState: boolean = false, + events: string[] = defaultEvents +): boolean => { const [state, setState] = useState(initialState); useEffect(() => { diff --git a/src/useIntersection.ts b/src/useIntersection.ts index 7cf9941dd7..8bec1aea38 100644 --- a/src/useIntersection.ts +++ b/src/useIntersection.ts @@ -4,7 +4,10 @@ const useIntersection = ( ref: RefObject, options: IntersectionObserverInit ): IntersectionObserverEntry | null => { - const [intersectionObserverEntry, setIntersectionObserverEntry] = useState(null); + const [ + intersectionObserverEntry, + setIntersectionObserverEntry, + ] = useState(null); useEffect(() => { if (ref.current && typeof IntersectionObserver === 'function') { diff --git a/src/useKey.ts b/src/useKey.ts index 412cbdd443..715b4e6fc1 100644 --- a/src/useKey.ts +++ b/src/useKey.ts @@ -21,7 +21,12 @@ const createKeyPredicate = (keyFilter: KeyFilter): KeyPredicate => ? () => true : () => false; -const useKey = (key: KeyFilter, fn: Handler = noop, opts: UseKeyOptions = {}, deps: DependencyList = [key]) => { +const useKey = ( + key: KeyFilter, + fn: Handler = noop, + opts: UseKeyOptions = {}, + deps: DependencyList = [key] +) => { const { event = 'keydown', target, options } = opts; const useMemoHandler = useMemo(() => { const predicate: KeyPredicate = createKeyPredicate(key); diff --git a/src/useList.ts b/src/useList.ts index c02c7266cb..dd592df30d 100644 --- a/src/useList.ts +++ b/src/useList.ts @@ -117,7 +117,10 @@ function useList(initialList: IHookStateInitAction = []): [T[], ListActi actions.set((curr: T[]) => curr.slice().sort(compareFn)); }, - filter: (callbackFn: (value: T, index: number, array: T[]) => value is S, thisArg?: any) => { + filter: ( + callbackFn: (value: T, index: number, array: T[]) => value is S, + thisArg?: any + ) => { actions.set((curr: T[]) => curr.slice().filter(callbackFn, thisArg)); }, diff --git a/src/useLocalStorage.ts b/src/useLocalStorage.ts index 555b3b3fac..2b77bfa61a 100644 --- a/src/useLocalStorage.ts +++ b/src/useLocalStorage.ts @@ -23,7 +23,11 @@ const useLocalStorage = ( throw new Error('useLocalStorage key may not be falsy'); } - const deserializer = options ? (options.raw ? (value) => value : options.deserializer) : JSON.parse; + const deserializer = options + ? options.raw + ? (value) => value + : options.deserializer + : JSON.parse; // eslint-disable-next-line react-hooks/rules-of-hooks const [state, setState] = useState(() => { @@ -49,7 +53,8 @@ const useLocalStorage = ( const set: Dispatch> = useCallback( (valOrFunc) => { try { - const newState = typeof valOrFunc === 'function' ? (valOrFunc as Function)(state) : valOrFunc; + const newState = + typeof valOrFunc === 'function' ? (valOrFunc as Function)(state) : valOrFunc; if (typeof newState === 'undefined') return; let value: string; diff --git a/src/useLockBodyScroll.ts b/src/useLockBodyScroll.ts index bef76550c5..fd48658917 100644 --- a/src/useLockBodyScroll.ts +++ b/src/useLockBodyScroll.ts @@ -1,7 +1,9 @@ import { RefObject, useEffect, useRef } from 'react'; import { isBrowser, off, on } from './misc/util'; -export function getClosestBody(el: Element | HTMLElement | HTMLIFrameElement | null): HTMLElement | null { +export function getClosestBody( + el: Element | HTMLElement | HTMLIFrameElement | null +): HTMLElement | null { if (!el) { return null; } else if (el.tagName === 'BODY') { @@ -32,7 +34,10 @@ export interface BodyInfoItem { } const isIosDevice = - isBrowser && window.navigator && window.navigator.platform && /iP(ad|hone|od)/.test(window.navigator.platform); + isBrowser && + window.navigator && + window.navigator.platform && + /iP(ad|hone|od)/.test(window.navigator.platform); const bodies: Map = new Map(); @@ -60,7 +65,10 @@ export default !doc body.style.overflow = 'hidden'; } } else { - bodies.set(body, { counter: bodyInfo.counter + 1, initialOverflow: bodyInfo.initialOverflow }); + bodies.set(body, { + counter: bodyInfo.counter + 1, + initialOverflow: bodyInfo.initialOverflow, + }); } }; @@ -80,7 +88,10 @@ export default !doc body.style.overflow = bodyInfo.initialOverflow; } } else { - bodies.set(body, { counter: bodyInfo.counter - 1, initialOverflow: bodyInfo.initialOverflow }); + bodies.set(body, { + counter: bodyInfo.counter - 1, + initialOverflow: bodyInfo.initialOverflow, + }); } } }; diff --git a/src/useMeasure.ts b/src/useMeasure.ts index b51e88707b..2b072a5fa3 100644 --- a/src/useMeasure.ts +++ b/src/useMeasure.ts @@ -7,7 +7,10 @@ export type UseMeasureRect = Pick< 'x' | 'y' | 'top' | 'left' | 'right' | 'bottom' | 'height' | 'width' >; export type UseMeasureRef = (element: E) => void; -export type UseMeasureResult = [UseMeasureRef, UseMeasureRect]; +export type UseMeasureResult = [ + UseMeasureRef, + UseMeasureRect +]; const defaultState: UseMeasureRect = { x: 0, @@ -48,4 +51,4 @@ function useMeasure(): UseMeasureResult export default isBrowser && typeof (window as any).ResizeObserver !== 'undefined' ? useMeasure - : (() => [noop, defaultState]) as typeof useMeasure; + : ((() => [noop, defaultState]) as typeof useMeasure); diff --git a/src/useMedia.ts b/src/useMedia.ts index 8c4b637aad..1cfa737572 100644 --- a/src/useMedia.ts +++ b/src/useMedia.ts @@ -2,7 +2,9 @@ import { useEffect, useState } from 'react'; import { isBrowser } from './misc/util'; const useMedia = (query: string, defaultState: boolean = false) => { - const [state, setState] = useState(isBrowser ? () => window.matchMedia(query).matches : defaultState); + const [state, setState] = useState( + isBrowser ? () => window.matchMedia(query).matches : defaultState + ); useEffect(() => { let mounted = true; diff --git a/src/useMediaDevices.ts b/src/useMediaDevices.ts index 3929d22e8f..50dc53b297 100644 --- a/src/useMediaDevices.ts +++ b/src/useMediaDevices.ts @@ -13,7 +13,12 @@ const useMediaDevices = () => { .then((devices) => { if (mounted) { setState({ - devices: devices.map(({ deviceId, groupId, kind, label }) => ({ deviceId, groupId, kind, label })), + devices: devices.map(({ deviceId, groupId, kind, label }) => ({ + deviceId, + groupId, + kind, + label, + })), }); } }) diff --git a/src/useMediatedState.ts b/src/useMediatedState.ts index 708b2ecf92..6dbb7a4cb1 100644 --- a/src/useMediatedState.ts +++ b/src/useMediatedState.ts @@ -11,9 +11,15 @@ export type UseMediatedStateReturn = [S, Dispatch>]; export function useMediatedState( mediator: StateMediator ): UseMediatedStateReturn; -export function useMediatedState(mediator: StateMediator, initialState: S): UseMediatedStateReturn; +export function useMediatedState( + mediator: StateMediator, + initialState: S +): UseMediatedStateReturn; -export function useMediatedState(mediator: StateMediator, initialState?: S): UseMediatedStateReturn { +export function useMediatedState( + mediator: StateMediator, + initialState?: S +): UseMediatedStateReturn { const mediatorFn = useRef(mediator); const [state, setMediatedState] = useState(initialState!); diff --git a/src/useMethods.ts b/src/useMethods.ts index 2a1675a5a9..5a17c62ae0 100644 --- a/src/useMethods.ts +++ b/src/useMethods.ts @@ -15,7 +15,10 @@ type WrappedMethods = { [P in keyof M]: (...payload: any) => void; }; -const useMethods = (createMethods: CreateMethods, initialState: T): [T, WrappedMethods] => { +const useMethods = ( + createMethods: CreateMethods, + initialState: T +): [T, WrappedMethods] => { const reducer = useMemo>( () => (reducerState: T, action: Action) => { return createMethods(reducerState)[action.type](...action.payload); diff --git a/src/useMultiStateValidator.ts b/src/useMultiStateValidator.ts index 1a545e9958..480d6708ae 100644 --- a/src/useMultiStateValidator.ts +++ b/src/useMultiStateValidator.ts @@ -2,9 +2,15 @@ import { useCallback, useEffect, useRef, useState } from 'react'; import { StateValidator, UseStateValidatorReturn, ValidityState } from './useStateValidator'; export type MultiStateValidatorStates = any[] | { [p: string]: any } | { [p: number]: any }; -export type MultiStateValidator = StateValidator; - -export function useMultiStateValidator( +export type MultiStateValidator< + V extends ValidityState, + S extends MultiStateValidatorStates +> = StateValidator; + +export function useMultiStateValidator< + V extends ValidityState, + S extends MultiStateValidatorStates +>( states: S, validator: MultiStateValidator, initialValidity: V = [undefined] as V diff --git a/src/useNetworkState.ts b/src/useNetworkState.ts index f8d816a6e6..0d48439d19 100644 --- a/src/useNetworkState.ts +++ b/src/useNetworkState.ts @@ -8,7 +8,15 @@ export interface INetworkInformation extends EventTarget { readonly effectiveType: 'slow-2g' | '2g' | '3g' | '4g'; readonly rtt: number; readonly saveData: boolean; - readonly type: 'bluetooth' | 'cellular' | 'ethernet' | 'none' | 'wifi' | 'wimax' | 'other' | 'unknown'; + readonly type: + | 'bluetooth' + | 'cellular' + | 'ethernet' + | 'none' + | 'wifi' + | 'wimax' + | 'other' + | 'unknown'; onChange: (event: Event) => void; } @@ -68,9 +76,11 @@ export interface IUseNetworkState { } const nav: - | (Navigator & Partial>) + | (Navigator & + Partial>) | undefined = isNavigator ? navigator : undefined; -const conn: INetworkInformation | undefined = nav && (nav.connection || nav.mozConnection || nav.webkitConnection); +const conn: INetworkInformation | undefined = + nav && (nav.connection || nav.mozConnection || nav.webkitConnection); function getConnectionState(previousState?: IUseNetworkState): IUseNetworkState { const online = nav?.onLine; @@ -89,7 +99,9 @@ function getConnectionState(previousState?: IUseNetworkState): IUseNetworkState }; } -export default function useNetworkState(initialState?: IHookStateInitAction): IUseNetworkState { +export default function useNetworkState( + initialState?: IHookStateInitAction +): IUseNetworkState { const [state, setState] = useState(initialState ?? getConnectionState); useEffect(() => { diff --git a/src/usePreviousDistinct.ts b/src/usePreviousDistinct.ts index 896afc73fe..10bf5f8293 100644 --- a/src/usePreviousDistinct.ts +++ b/src/usePreviousDistinct.ts @@ -5,7 +5,10 @@ export type Predicate = (prev: T | undefined, next: T) => boolean; const strictEquals = (prev: T | undefined, next: T) => prev === next; -export default function usePreviousDistinct(value: T, compare: Predicate = strictEquals): T | undefined { +export default function usePreviousDistinct( + value: T, + compare: Predicate = strictEquals +): T | undefined { const prevRef = useRef(); const curRef = useRef(value); const isFirstMount = useFirstMountState(); diff --git a/src/useRafLoop.ts b/src/useRafLoop.ts index 5f5b667c2e..23a0807478 100644 --- a/src/useRafLoop.ts +++ b/src/useRafLoop.ts @@ -2,7 +2,10 @@ import { useCallback, useEffect, useMemo, useRef } from 'react'; export type RafLoopReturns = [() => void, () => void, () => boolean]; -export default function useRafLoop(callback: FrameRequestCallback, initiallyActive = true): RafLoopReturns { +export default function useRafLoop( + callback: FrameRequestCallback, + initiallyActive = true +): RafLoopReturns { const raf = useRef(null); const rafActivity = useRef(false); const rafCallback = useRef(callback); diff --git a/src/useScratch.ts b/src/useScratch.ts index 08bb57fc4a..68b793f85c 100644 --- a/src/useScratch.ts +++ b/src/useScratch.ts @@ -28,7 +28,9 @@ export interface ScratchSensorState { elY?: number; } -const useScratch = (params: ScratchSensorParams = {}): [(el: HTMLElement | null) => void, ScratchSensorState] => { +const useScratch = ( + params: ScratchSensorParams = {} +): [(el: HTMLElement | null) => void, ScratchSensorState] => { const { disabled } = params; const paramsRef = useLatest(params); const [state, setState] = useState({ isScratching: false }); @@ -155,7 +157,10 @@ const useScratch = (params: ScratchSensorParams = {}): [(el: HTMLElement | null) }; export interface ScratchSensorProps extends ScratchSensorParams { - children: (state: ScratchSensorState, ref: (el: HTMLElement | null) => void) => React.ReactElement; + children: ( + state: ScratchSensorState, + ref: (el: HTMLElement | null) => void + ) => React.ReactElement; } export const ScratchSensor: FC = (props) => { diff --git a/src/useSessionStorage.ts b/src/useSessionStorage.ts index 988185b0ef..65b9a0e835 100644 --- a/src/useSessionStorage.ts +++ b/src/useSessionStorage.ts @@ -1,7 +1,11 @@ import { useEffect, useState } from 'react'; import { isBrowser } from './misc/util'; -const useSessionStorage = (key: string, initialValue?: T, raw?: boolean): [T, (value: T) => void] => { +const useSessionStorage = ( + key: string, + initialValue?: T, + raw?: boolean +): [T, (value: T) => void] => { if (!isBrowser) { return [initialValue as T, () => {}]; } diff --git a/src/useSet.ts b/src/useSet.ts index 53f7ad3c61..d45c27255d 100644 --- a/src/useSet.ts +++ b/src/useSet.ts @@ -16,7 +16,8 @@ const useSet = (initialSet = new Set()): [Set, Actions] => { const stableActions = useMemo>(() => { const add = (item: K) => setSet((prevSet) => new Set([...Array.from(prevSet), item])); - const remove = (item: K) => setSet((prevSet) => new Set(Array.from(prevSet).filter((i) => i !== item))); + const remove = (item: K) => + setSet((prevSet) => new Set(Array.from(prevSet).filter((i) => i !== item))); const toggle = (item: K) => setSet((prevSet) => prevSet.has(item) diff --git a/src/useSetState.ts b/src/useSetState.ts index d589f46a89..608acc9603 100644 --- a/src/useSetState.ts +++ b/src/useSetState.ts @@ -6,7 +6,9 @@ const useSetState = ( const [state, set] = useState(initialState); const setState = useCallback( (patch) => { - set((prevState) => Object.assign({}, prevState, patch instanceof Function ? patch(prevState) : patch)); + set((prevState) => + Object.assign({}, prevState, patch instanceof Function ? patch(prevState) : patch) + ); }, [set] ); diff --git a/src/useShallowCompareEffect.ts b/src/useShallowCompareEffect.ts index 722668a1f9..2c6e4808c9 100644 --- a/src/useShallowCompareEffect.ts +++ b/src/useShallowCompareEffect.ts @@ -9,7 +9,9 @@ const shallowEqualDepsList = (prevDeps: DependencyList, nextDeps: DependencyList const useShallowCompareEffect = (effect: EffectCallback, deps: DependencyList) => { if (process.env.NODE_ENV !== 'production') { if (!(deps instanceof Array) || !deps.length) { - console.warn('`useShallowCompareEffect` should not be used with no dependencies. Use React.useEffect instead.'); + console.warn( + '`useShallowCompareEffect` should not be used with no dependencies. Use React.useEffect instead.' + ); } if (deps.every(isPrimitive)) { diff --git a/src/useSize.tsx b/src/useSize.tsx index d5d2d6dfbb..4c6271fe59 100644 --- a/src/useSize.tsx +++ b/src/useSize.tsx @@ -17,7 +17,10 @@ const useSize = ( { width = Infinity, height = Infinity }: Partial = {} ): [React.ReactElement, State] => { if (!isBrowser) { - return [typeof element === 'function' ? element({ width, height }) : element, { width, height }]; + return [ + typeof element === 'function' ? element({ width, height }) : element, + { width, height }, + ]; } // eslint-disable-next-line react-hooks/rules-of-hooks diff --git a/src/useSpeech.ts b/src/useSpeech.ts index d71005dac9..b8eaee9791 100644 --- a/src/useSpeech.ts +++ b/src/useSpeech.ts @@ -20,7 +20,8 @@ export interface SpeechOptions { volume?: number; } -const voices = isBrowser && typeof window.speechSynthesis === 'object' ? window.speechSynthesis.getVoices() : []; +const voices = + isBrowser && typeof window.speechSynthesis === 'object' ? window.speechSynthesis.getVoices() : []; const useSpeech = (text: string, opts: SpeechOptions = {}): SpeechState => { const [state, setState] = useSetState({ diff --git a/src/useStateList.ts b/src/useStateList.ts index a0fc355a2a..7e4d605cf6 100644 --- a/src/useStateList.ts +++ b/src/useStateList.ts @@ -42,7 +42,10 @@ export default function useStateList(stateSet: T[] = []): UseStateListReturn< // it gives the ability to travel through the left and right borders. // 4ex: if list contains 5 elements, attempt to set index 9 will bring use to 5th element // in case of negative index it will start counting from the right, so -17 will bring us to 4th element - index.current = newIndex >= 0 ? newIndex % stateSet.length : stateSet.length + (newIndex % stateSet.length); + index.current = + newIndex >= 0 + ? newIndex % stateSet.length + : stateSet.length + (newIndex % stateSet.length); update(); }, setState: (state: T) => { diff --git a/src/useStateWithHistory.ts b/src/useStateWithHistory.ts index db34c7458f..64f1cf7843 100644 --- a/src/useStateWithHistory.ts +++ b/src/useStateWithHistory.ts @@ -104,7 +104,10 @@ export function useStateWithHistory( } innerSetState(() => { - historyPosition.current = Math.min(historyPosition.current + amount, history.current.length - 1); + historyPosition.current = Math.min( + historyPosition.current + amount, + history.current.length - 1 + ); return history.current[historyPosition.current]; }); diff --git a/src/useToggle.ts b/src/useToggle.ts index 5fb41188b2..8e380e19e2 100644 --- a/src/useToggle.ts +++ b/src/useToggle.ts @@ -1,6 +1,7 @@ import { Reducer, useReducer } from 'react'; -const toggleReducer = (state: boolean, nextValue?: any) => (typeof nextValue === 'boolean' ? nextValue : !state); +const toggleReducer = (state: boolean, nextValue?: any) => + typeof nextValue === 'boolean' ? nextValue : !state; const useToggle = (initialValue: boolean): [boolean, (nextValue?: any) => void] => { return useReducer>(toggleReducer, initialValue); diff --git a/src/useVibrate.ts b/src/useVibrate.ts index b3542b3dfb..3481fc1379 100644 --- a/src/useVibrate.ts +++ b/src/useVibrate.ts @@ -5,7 +5,11 @@ export type VibrationPattern = number | number[]; const isVibrationApiSupported = isNavigator && 'vibrate' in navigator; -function useVibrate(enabled: boolean = true, pattern: VibrationPattern = [1000, 1000], loop: boolean = true): void { +function useVibrate( + enabled: boolean = true, + pattern: VibrationPattern = [1000, 1000], + loop: boolean = true +): void { useEffect(() => { let interval; @@ -13,7 +17,8 @@ function useVibrate(enabled: boolean = true, pattern: VibrationPattern = [1000, navigator.vibrate(pattern); if (loop) { - const duration = pattern instanceof Array ? pattern.reduce((a, b) => a + b) : (pattern as number); + const duration = + pattern instanceof Array ? pattern.reduce((a, b) => a + b) : (pattern as number); interval = setInterval(() => { navigator.vibrate(pattern); diff --git a/stories/useBattery.story.tsx b/stories/useBattery.story.tsx index 703046bfb6..b6f688edb0 100644 --- a/stories/useBattery.story.tsx +++ b/stories/useBattery.story.tsx @@ -27,8 +27,10 @@ const Demo = () => {
Battery sensor:   supported
Battery state: fetched
- Charge level:   {(batteryState.level * 100).toFixed(0)}%
- Charging:   {batteryState.charging ? 'yes' : 'no'}
+ Charge level:  {' '} + {(batteryState.level * 100).toFixed(0)}%
+ Charging:   {batteryState.charging ? 'yes' : 'no'}{' '} +
Charging time:   {batteryState.chargingTime ? batteryState.chargingTime : 'finished'}
Discharging time:   {batteryState.dischargingTime} diff --git a/stories/useEvent.story.tsx b/stories/useEvent.story.tsx index 3675ad9dff..360c2468b6 100644 --- a/stories/useEvent.story.tsx +++ b/stories/useEvent.story.tsx @@ -21,7 +21,8 @@ const Demo = () => { return (

- Press some keys on your keyboard, r key resets the list + Press some keys on your keyboard, r key resets the + list

{JSON.stringify(list, null, 4)}
diff --git a/stories/useFullscreen.story.tsx b/stories/useFullscreen.story.tsx index 7b8ee94513..e23db230b7 100644 --- a/stories/useFullscreen.story.tsx +++ b/stories/useFullscreen.story.tsx @@ -32,8 +32,7 @@ const Demo = () => { display: 'flex', justifyContent: 'center', alignItems: 'center', - }} - > + }}>