Skip to content

Commit

Permalink
feat(shared): use shared methods to judge types (#1591)
Browse files Browse the repository at this point in the history
* feat(shared): add shared util methods

* refactor: use shared methods to judge types
  • Loading branch information
hchlq authored May 9, 2022
1 parent d5a4509 commit c907c7b
Show file tree
Hide file tree
Showing 25 changed files with 144 additions and 47 deletions.
4 changes: 2 additions & 2 deletions packages/hooks/src/createUseStorageState/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import { useState } from 'react';
import useMemoizedFn from '../useMemoizedFn';
import useUpdateEffect from '../useUpdateEffect';
import { isFunction } from '../utils';
import { isFunction, isUndef } from '../utils';

export interface IFuncUpdater<T> {
(previousState?: T): T;
Expand Down Expand Up @@ -76,7 +76,7 @@ export function createUseStorageState(getStorage: () => Storage | undefined) {
}, [key]);

const updateState = (value?: T | IFuncUpdater<T>) => {
if (typeof value === 'undefined') {
if (isUndef(value)) {
setState(undefined);
storage?.removeItem(key);
} else if (isFunction(value)) {
Expand Down
3 changes: 2 additions & 1 deletion packages/hooks/src/useAsyncEffect/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { DependencyList } from 'react';
import { useEffect } from 'react';
import { isFunction } from '../utils';

function useAsyncEffect(
effect: () => AsyncGenerator<void, void, void> | Promise<void>,
Expand All @@ -8,7 +9,7 @@ function useAsyncEffect(
function isAsyncGenerator(
val: AsyncGenerator<void, void, void> | Promise<void>,
): val is AsyncGenerator<void, void, void> {
return typeof val[Symbol.asyncIterator] === 'function';
return isFunction(val[Symbol.asyncIterator]);
}
useEffect(() => {
const e = effect();
Expand Down
4 changes: 2 additions & 2 deletions packages/hooks/src/useCookieState/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import Cookies from 'js-cookie';
import { useState } from 'react';
import useMemoizedFn from '../useMemoizedFn';
import { isFunction } from '../utils';
import { isFunction, isString } from '../utils';

export type State = string | undefined;

Expand All @@ -13,7 +13,7 @@ function useCookieState(cookieKey: string, options: Options = {}) {
const [state, setState] = useState<State>(() => {
const cookieValue = Cookies.get(cookieKey);

if (typeof cookieValue === 'string') return cookieValue;
if (isString(cookieValue)) return cookieValue;

if (isFunction(options.defaultValue)) {
return options.defaultValue();
Expand Down
7 changes: 4 additions & 3 deletions packages/hooks/src/useCounter/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useState } from 'react';
import useMemoizedFn from '../useMemoizedFn';
import { isNumber } from '../utils';

export interface Options {
min?: number;
Expand All @@ -18,10 +19,10 @@ export type ValueParam = number | ((c: number) => number);
function getTargetValue(val: number, options: Options = {}) {
const { min, max } = options;
let target = val;
if (typeof max === 'number') {
if (isNumber(max)) {
target = Math.min(max, target);
}
if (typeof min === 'number') {
if (isNumber(min)) {
target = Math.max(min, target);
}
return target;
Expand All @@ -39,7 +40,7 @@ function useCounter(initialValue: number = 0, options: Options = {}) {

const setValue = (value: ValueParam) => {
setCurrent((c) => {
const target = typeof value === 'number' ? value : value(c);
const target = isNumber(value) ? value : value(c);
return getTargetValue(target, {
max,
min,
Expand Down
7 changes: 4 additions & 3 deletions packages/hooks/src/useDebounceFn/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@ import { useMemo } from 'react';
import type { DebounceOptions } from '../useDebounce/debounceOptions';
import useLatest from '../useLatest';
import useUnmount from '../useUnmount';
import { isFunction } from '../utils';

type noop = (...args: any) => any;

function useDebounceFn<T extends noop>(fn: T, options?: DebounceOptions) {
if (process.env.NODE_ENV === 'development') {
if (typeof fn !== 'function') {
if (!isFunction(fn)) {
console.error(`useDebounceFn expected parameter is a function, got ${typeof fn}`);
}
}
Expand All @@ -20,9 +21,9 @@ function useDebounceFn<T extends noop>(fn: T, options?: DebounceOptions) {
const debounced = useMemo(
() =>
debounce(
((...args: Parameters<T>): ReturnType<T> => {
(...args: Parameters<T>): ReturnType<T> => {
return fnRef.current(...args);
}),
},
wait,
options,
),
Expand Down
3 changes: 2 additions & 1 deletion packages/hooks/src/useEventTarget/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useCallback, useState } from 'react';
import useLatest from '../useLatest';
import { isFunction } from '../utils';

interface EventTarget<U> {
target: {
Expand All @@ -22,7 +23,7 @@ function useEventTarget<T, U = T>(options?: Options<T, U>) {

const onChange = useCallback((e: EventTarget<U>) => {
const _value = e.target.value;
if (typeof transformerRef.current === 'function') {
if (isFunction(transformerRef.current)) {
return setValue(transformerRef.current(_value));
}
// no transformer => U and T should be the same
Expand Down
3 changes: 2 additions & 1 deletion packages/hooks/src/useHistoryTravel/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useRef, useState } from 'react';
import useMemoizedFn from '../useMemoizedFn';
import { isNumber } from '../utils';

interface IData<T> {
present?: T;
Expand Down Expand Up @@ -86,7 +87,7 @@ export default function useHistoryTravel<T>(initialValue?: T) {
};

const go = (step: number) => {
const stepNum = typeof step === 'number' ? step : Number(step);
const stepNum = isNumber(step) ? step : Number(step);
if (stepNum === 0) {
return;
}
Expand Down
5 changes: 3 additions & 2 deletions packages/hooks/src/useKeyPress/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import useLatest from '../useLatest';
import { isNumber, isString } from '../utils';
import type { BasicTarget } from '../utils/domTarget';
import { getTargetElement } from '../utils/domTarget';
import useDeepCompareEffectWithTarget from '../utils/useDeepCompareWithTarget';
Expand Down Expand Up @@ -155,7 +156,7 @@ function genFilterKey(event: KeyboardEvent, keyFilter: keyType, exactMatch: bool
}

// 数字类型直接匹配事件的 keyCode
if (typeof keyFilter === 'number') {
if (isNumber(keyFilter)) {
return event.keyCode === keyFilter;
}

Expand Down Expand Up @@ -195,7 +196,7 @@ function genKeyFormater(keyFilter: KeyFilter, exactMatch: boolean): KeyPredicate
if (typeof keyFilter === 'function') {
return keyFilter;
}
if (typeof keyFilter === 'string' || typeof keyFilter === 'number') {
if (isString(keyFilter) || isNumber(keyFilter)) {
return (event: KeyboardEvent) => genFilterKey(event, keyFilter, exactMatch);
}
if (Array.isArray(keyFilter)) {
Expand Down
3 changes: 2 additions & 1 deletion packages/hooks/src/useMemoizedFn/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useMemo, useRef } from 'react';
import { isFunction } from '../utils';

type noop = (this: any, ...args: any[]) => any;

Expand All @@ -9,7 +10,7 @@ type PickFunction<T extends noop> = (

function useMemoizedFn<T extends noop>(fn: T) {
if (process.env.NODE_ENV === 'development') {
if (typeof fn !== 'function') {
if (!isFunction(fn)) {
console.error(`useMemoizedFn expected parameter is a function, got ${typeof fn}`);
}
}
Expand Down
7 changes: 5 additions & 2 deletions packages/hooks/src/useMount/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { useEffect } from 'react';
import { isFunction } from '../utils';

const useMount = (fn: () => void) => {
if (process.env.NODE_ENV === 'development') {
if (typeof fn !== 'function') {
console.error(`useMount: parameter \`fn\` expected to be a function, but got "${typeof fn}".`);
if (!isFunction(fn)) {
console.error(
`useMount: parameter \`fn\` expected to be a function, but got "${typeof fn}".`,
);
}
}

Expand Down
3 changes: 2 additions & 1 deletion packages/hooks/src/useNetwork/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useEffect, useState } from 'react';
import { isObject } from '../utils';

export interface NetworkState {
since?: Date;
Expand All @@ -19,7 +20,7 @@ enum NetworkEventType {

function getConnection() {
const nav = navigator as any;
if (typeof nav !== 'object') return null;
if (!isObject(nav)) return null;
return nav.connection || nav.mozConnection || nav.webkitConnection;
}

Expand Down
3 changes: 2 additions & 1 deletion packages/hooks/src/useRafInterval/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useEffect } from 'react';
import useLatest from '../useLatest';
import { isNumber } from '../utils';

interface Handle {
id: number | NodeJS.Timer;
Expand Down Expand Up @@ -50,7 +51,7 @@ function useRafInterval(
const fnRef = useLatest(fn);

useEffect(() => {
if (typeof delay !== 'number' || delay < 0) return;
if (!isNumber(delay) || delay < 0) return;
if (immediate) {
fnRef.current();
}
Expand Down
3 changes: 2 additions & 1 deletion packages/hooks/src/useRafTimeout/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useEffect } from 'react';
import useLatest from '../useLatest';
import { isNumber } from '../utils';

interface Handle {
id: number | NodeJS.Timeout;
Expand Down Expand Up @@ -45,7 +46,7 @@ function useRafTimeout(fn: () => void, delay: number | undefined) {
const fnRef = useLatest(fn);

useEffect(() => {
if (typeof delay !== 'number' || delay < 0) return;
if (!isNumber(delay) || delay < 0) return;
const timer = setRafTimeout(() => {
fnRef.current();
}, delay);
Expand Down
5 changes: 1 addition & 4 deletions packages/hooks/src/useReactive/index.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
import { useRef } from 'react';
import useCreation from '../useCreation';
import useUpdate from '../useUpdate';
import { isObject } from '../utils';

// k:v 原对象:代理过的对象
const proxyMap = new WeakMap();
// k:v 代理过的对象:原对象
const rawMap = new WeakMap();

function isObject(val: Record<string, any>): boolean {
return typeof val === 'object' && val !== null;
}

function observer<T extends Record<string, any>>(initialVal: T, cb: () => void): T {
const existingProxy = proxyMap.get(initialVal);

Expand Down
3 changes: 2 additions & 1 deletion packages/hooks/src/useRequest/src/Fetch.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { isFunction } from '../../utils';
import type { MutableRefObject } from 'react';
import type { FetchState, Options, PluginReturn, Service, Subscribe } from './types';

Expand Down Expand Up @@ -154,7 +155,7 @@ export default class Fetch<TData, TParams extends any[]> {

mutate(data?: TData | ((oldData?: TData) => TData | undefined)) {
let targetData: TData | undefined;
if (typeof data === 'function') {
if (isFunction(data)) {
// @ts-ignore
targetData = data(this.state.data);
} else {
Expand Down
3 changes: 2 additions & 1 deletion packages/hooks/src/useRequest/src/utils/isOnline.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { isUndef } from '../../../utils';
import canUseDom from '../../../utils/canUseDom';

export default function isOnline(): boolean {
if (canUseDom() && typeof navigator.onLine !== 'undefined') {
if (canUseDom() && !isUndef(navigator.onLine)) {
return navigator.onLine;
}
return true;
Expand Down
7 changes: 4 additions & 3 deletions packages/hooks/src/useThrottleFn/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@ import { useMemo } from 'react';
import useLatest from '../useLatest';
import type { ThrottleOptions } from '../useThrottle/throttleOptions';
import useUnmount from '../useUnmount';
import { isFunction } from '../utils';

type noop = (...args: any) => any;

function useThrottleFn<T extends noop>(fn: T, options?: ThrottleOptions) {
if (process.env.NODE_ENV === 'development') {
if (typeof fn !== 'function') {
if (!isFunction(fn)) {
console.error(`useThrottleFn expected parameter is a function, got ${typeof fn}`);
}
}
Expand All @@ -20,9 +21,9 @@ function useThrottleFn<T extends noop>(fn: T, options?: ThrottleOptions) {
const throttled = useMemo(
() =>
throttle(
((...args: Parameters<T>): ReturnType<T> => {
(...args: Parameters<T>): ReturnType<T> => {
return fnRef.current(...args);
}),
},
wait,
options,
),
Expand Down
3 changes: 2 additions & 1 deletion packages/hooks/src/useTimeout/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { useEffect } from 'react';
import useLatest from '../useLatest';
import { isNumber } from '../utils';

function useTimeout(fn: () => void, delay: number | undefined): void {
const fnRef = useLatest(fn);

useEffect(() => {
if (typeof delay !== 'number' || delay < 0) return;
if (!isNumber(delay) || delay < 0) return;
const timer = setTimeout(() => {
fnRef.current();
}, delay);
Expand Down
3 changes: 2 additions & 1 deletion packages/hooks/src/useUnmount/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { useEffect } from 'react';
import useLatest from '../useLatest';
import { isFunction } from '../utils';

const useUnmount = (fn: () => void) => {
if (process.env.NODE_ENV === 'development') {
if (typeof fn !== 'function') {
if (!isFunction(fn)) {
console.error(`useUnmount expected parameter is a function, got ${typeof fn}`);
}
}
Expand Down
11 changes: 6 additions & 5 deletions packages/hooks/src/useVirtualList/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import useMemoizedFn from '../useMemoizedFn';
import useSize from '../useSize';
import { getTargetElement } from '../utils/domTarget';
import type { BasicTarget } from '../utils/domTarget';
import { isNumber } from '../utils';

export interface Options<T> {
containerTarget: BasicTarget;
Expand All @@ -25,7 +26,7 @@ const useVirtualList = <T = any>(list: T[], options: Options<T>) => {
const [targetList, setTargetList] = useState<{ index: number; data: T }[]>([]);

const getVisibleCount = (containerHeight: number, fromIndex: number) => {
if (typeof itemHeightRef.current === 'number') {
if (isNumber(itemHeightRef.current)) {
return Math.ceil(containerHeight / itemHeightRef.current);
}

Expand All @@ -36,14 +37,14 @@ const useVirtualList = <T = any>(list: T[], options: Options<T>) => {
sum += height;
endIndex = i;
if (sum >= containerHeight) {
break;
break;
}
}
return endIndex - fromIndex;
};

const getOffset = (scrollTop: number) => {
if (typeof itemHeightRef.current === 'number') {
if (isNumber(itemHeightRef.current)) {
return Math.floor(scrollTop / itemHeightRef.current) + 1;
}
let sum = 0;
Expand All @@ -61,7 +62,7 @@ const useVirtualList = <T = any>(list: T[], options: Options<T>) => {

// 获取上部高度
const getDistanceTop = (index: number) => {
if (typeof itemHeightRef.current === 'number') {
if (isNumber(itemHeightRef.current)) {
const height = index * itemHeightRef.current;
return height;
}
Expand All @@ -73,7 +74,7 @@ const useVirtualList = <T = any>(list: T[], options: Options<T>) => {
};

const totalHeight = useMemo(() => {
if (typeof itemHeightRef.current === 'number') {
if (isNumber(itemHeightRef.current)) {
return list.length * itemHeightRef.current;
}
// @ts-ignore
Expand Down
Loading

0 comments on commit c907c7b

Please sign in to comment.