reaxes-utils 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/index.js +2 -0
  2. package/index.js.map +1 -0
  3. package/package.json +12 -51
  4. package/types/ConditionRender.utility.d.ts +19 -0
  5. package/types/assert-group.utility.d.ts +6 -0
  6. package/types/checkGenericNull.utility.d.ts +1 -0
  7. package/types/checkType.utility.d.ts +2 -0
  8. package/types/cookie.utility.d.ts +7 -0
  9. package/types/crayon.utility.d.ts +9 -0
  10. package/types/dataflow.utility.d.ts +5 -0
  11. package/types/debounce.utility.d.ts +1 -0
  12. package/types/getNestedValue.utility.d.ts +2 -0
  13. package/types/index.d.ts +22 -0
  14. package/types/isPromise.utility.d.ts +1 -0
  15. package/types/logProxy.utility.d.ts +1 -0
  16. package/types/makePair.utility.d.ts +1 -0
  17. package/types/orzPromise.utility.d.ts +4 -0
  18. package/types/overload.d.ts +1 -0
  19. package/types/queryString.utility.d.ts +6 -0
  20. package/types/random.utility.d.ts +5 -0
  21. package/types/replaceStr.utility.d.ts +1 -0
  22. package/types/runOnlyOnce.utility.d.ts +1 -0
  23. package/types/stringify.utility.d.ts +6 -0
  24. package/types/throttle.utility.d.ts +6 -0
  25. package/types/timer.utility.d.ts +14 -0
  26. package/types/tools.utility.d.ts +3 -0
  27. package/babel.config.js +0 -50
  28. package/src/ConditionRender.utility.tsx +0 -128
  29. package/src/assert-group.utility.ts +0 -70
  30. package/src/checkGenericNull.utility.ts +0 -18
  31. package/src/checkType.utility.ts +0 -44
  32. package/src/cookie.utility.ts +0 -124
  33. package/src/crayon.utility.ts +0 -149
  34. package/src/dataflow.utility.ts +0 -30
  35. package/src/debounce.utility.ts +0 -31
  36. package/src/getNestedValue.utility.ts +0 -47
  37. package/src/hooks/index.ts +0 -4
  38. package/src/hooks/useAsync.utility.ts +0 -129
  39. package/src/hooks/useForceUpdate.tsx +0 -4
  40. package/src/hooks/useMountedRef.utility.ts +0 -20
  41. package/src/hooks/useUndo.utility.ts +0 -103
  42. package/src/index.tsx +0 -55
  43. package/src/isPromise.utility.ts +0 -10
  44. package/src/logProxy.utility.tsx +0 -7
  45. package/src/makePair.utility.ts +0 -18
  46. package/src/orzPromise.utility.ts +0 -24
  47. package/src/overload.ts +0 -17
  48. package/src/queryString.utility.ts +0 -77
  49. package/src/random.utility.ts +0 -73
  50. package/src/replaceStr.utility.ts +0 -15
  51. package/src/runOnlyOnce.utility.ts +0 -13
  52. package/src/stringify.utility.ts +0 -228
  53. package/src/throttle.utility.ts +0 -43
  54. package/src/timer.utility.ts +0 -103
  55. package/src/tools.utility.ts +0 -59
  56. package/src/workspace.d.ts +0 -43
  57. package/tsconfig.json +0 -89
  58. package/webpack.config.mjs +0 -205
@@ -1,129 +0,0 @@
1
- /** @format */
2
-
3
- import {useCallback, useReducer, useState} from 'react';
4
- import {useMountedRef} from './useMountedRef.utility';
5
-
6
- interface State<D> {
7
- error: Error | null;
8
- data: D | null;
9
- stat: 'idle' | 'loading' | 'error' | 'success';
10
- }
11
-
12
- const defaultInitialState: State<null> = {
13
- stat: 'idle',
14
- data: null,
15
- error: null,
16
- };
17
-
18
- const defaultConfig = {
19
- throwOnError: false,
20
- };
21
- /**
22
- * @description 防止组件被卸载后 数据刚请求回来 然后数据挂载的warning
23
- * @param {function} dispatch 用于更新的函数
24
- * @return {function} 处理后的函数
25
- * @example
26
- * const safeDispatch = useSafeDispatch(dispatch);
27
- */
28
- const useSafeDispatch = <T>(dispatch: (...args: T[]) => void) => {
29
- const mountedRef = useMountedRef();
30
- return useCallback((...args: T[]) => (mountedRef.current ? dispatch(...args) : void 0), [dispatch, mountedRef]);
31
- };
32
- /**
33
- * @description 专门用于处理异步的hooks
34
- * @param {State<D>} initialState 初始的state
35
- * @param {} initialConfig 初始的配置 ---现在设置的不抛出错误
36
- * @return {Object}
37
- * isIdle:当前是否处于闲置状态
38
- * isLoading:是否处于loading状态
39
- * isError: 是否有错误,
40
- * isSuccess: 是否成功,
41
- * run: 用来处理异步的方法
42
- * setData: 设置data的方法
43
- * setError: 设置错误的方法
44
- * retry:重新跑一次run的方法用于重新加载
45
- * ...state:剩下的state
46
- * @example
47
- * 登录中的使用
48
- * const { run, isLoading } = useAsync(undefined, { throwOnError: true });
49
- * try {
50
- * await run(login(values));
51
- * } catch (e:any) {
52
- * onError(e);
53
- * }
54
- * 组件中使用
55
- * <Button loading={isLoading} htmlType={"submit"} type={"primary"}>登录</Button>
56
- */
57
- export const useAsync = <D>(initialState?: State<D>, initialConfig?: typeof defaultConfig) => {
58
- const config = {...defaultConfig, ...initialConfig};
59
- const [state, dispatch] = useReducer((state: State<D>, action: Partial<State<D>>) => ({...state, ...action}), {
60
- ...defaultInitialState,
61
- ...initialState,
62
- });
63
- const safeDispatch = useSafeDispatch(dispatch);
64
- const [retry, setRetry] = useState(() => () => {});
65
-
66
- const setData = useCallback(
67
- (data: D) =>
68
- safeDispatch({
69
- data,
70
- stat: 'success',
71
- error: null,
72
- }),
73
- [safeDispatch],
74
- );
75
-
76
- const setError = useCallback(
77
- (error: Error) =>
78
- safeDispatch({
79
- error,
80
- stat: 'error',
81
- data: null,
82
- }),
83
- [safeDispatch],
84
- );
85
-
86
- /**
87
- * @description 用于处理异步操作的方法
88
- * @param {Promise} promise 要被处理的promise
89
- * @param {function} runConfig 可选参数 默认值为刷新方法
90
- * @return {promise}
91
- */
92
- const run = useCallback(
93
- (promise: Promise<D>, runConfig?: {retry: () => Promise<D>}) => {
94
- if (!promise || !promise.then) {
95
- throw new Error('请传入 Promise 类型数据');
96
- }
97
- setRetry(() => () => {
98
- if (runConfig?.retry) {
99
- run(runConfig?.retry(), runConfig);
100
- }
101
- });
102
- safeDispatch({stat: 'loading'});
103
- return promise
104
- .then(data => {
105
- setData(data);
106
- return data;
107
- })
108
- .catch(error => {
109
- // catch会消化异常,如果不主动抛出,外面是接收不到异常的
110
- setError(error);
111
- if (config.throwOnError) return Promise.reject(error);
112
- return error;
113
- });
114
- },
115
- [config.throwOnError, setData, setError, safeDispatch],
116
- );
117
-
118
- return {
119
- isIdle: state.stat === 'idle',
120
- isLoading: state.stat === 'loading',
121
- isError: state.stat === 'error',
122
- isSuccess: state.stat === 'success',
123
- run,
124
- setData,
125
- setError,
126
- retry,
127
- ...state,
128
- };
129
- };
@@ -1,4 +0,0 @@
1
- export const useforceUpdate = () => {
2
- const [state,setState] = useState(true);
3
- return () => setState(!state);
4
- };
@@ -1,20 +0,0 @@
1
- /** @format */
2
-
3
- import {useEffect, useRef} from 'react';
4
- /**
5
- * @description 返回组件的挂载状态,如果还没挂载或者已经卸载,返回false;反之,返回true
6
- * @example
7
- * const mountedRef = useMountedRef();
8
- */
9
- export const useMountedRef = () => {
10
- const mountedRef = useRef(false);
11
-
12
- useEffect(() => {
13
- mountedRef.current = true;
14
- return () => {
15
- mountedRef.current = false;
16
- };
17
- });
18
-
19
- return mountedRef;
20
- };
@@ -1,103 +0,0 @@
1
- /* 实现历史记录的customer hook */
2
- import {useCallback, useReducer} from 'react';
3
-
4
- const UNDO = 'UNDO';
5
- const REDO = 'REDO';
6
- const SET = 'SET';
7
- const RESET = 'RESET';
8
-
9
- type State<T> = {
10
- past: T[];
11
- present: T;
12
- future: T[];
13
- };
14
-
15
- type Action<T> = {
16
- newPresent?: T;
17
- type: typeof UNDO | typeof REDO | typeof SET | typeof RESET;
18
- };
19
-
20
- const undoReducer = <T>(state: State<T>, action: Action<T>) => {
21
- const {past, present, future} = state;
22
- const {newPresent} = action;
23
-
24
- switch (action.type) {
25
- case UNDO: {
26
- if (past.length === 0) return state;
27
-
28
- const previous = past[past.length - 1];
29
- const newPast = past.slice(0, past.length - 1);
30
-
31
- return {
32
- past: newPast,
33
- present: previous,
34
- future: [present, ...future],
35
- };
36
- }
37
-
38
- case REDO: {
39
- if (future.length === 0) return state;
40
-
41
- const next = future[0];
42
- const newFuture = future.slice(1);
43
-
44
- return {
45
- past: [...past, present],
46
- present: next,
47
- future: newFuture,
48
- };
49
- }
50
-
51
- case SET: {
52
- if (newPresent === present) {
53
- return state;
54
- }
55
- return {
56
- past: [...past, present],
57
- present: newPresent,
58
- future: [],
59
- };
60
- }
61
-
62
- case RESET: {
63
- return {
64
- past: [],
65
- present: newPresent,
66
- future: [],
67
- };
68
- }
69
- }
70
- return state;
71
- };
72
- /**
73
- * @description 让操作可回退可前进的一个hook
74
- * @returns
75
- * @state 当前状态
76
- * @Object
77
- * @set ---设置 @param 需要设置的值
78
- * @reset ---重置 @param 将状态重置的值
79
- * @undo ---回退到上一次操作
80
- * @redo ---前进一次操作
81
- * @canUndo ---是否可以后退
82
- * @canRedo ---是否可以前进
83
- */
84
- export const useUndo = <T>(initialPresent: T) => {
85
- const [state, dispatch] = useReducer(undoReducer, {
86
- past: [],
87
- present: initialPresent,
88
- future: [],
89
- } as State<T>);
90
-
91
- const canUndo = state.past.length !== 0;
92
- const canRedo = state.future.length !== 0;
93
-
94
- const undo = useCallback(() => dispatch({type: UNDO}), []);
95
-
96
- const redo = useCallback(() => dispatch({type: REDO}), []);
97
-
98
- const set = useCallback((newPresent: T) => dispatch({type: SET, newPresent}), []);
99
-
100
- const reset = useCallback((newPresent: T) => dispatch({type: RESET, newPresent}), []);
101
-
102
- return [state, {set, reset, undo, redo, canUndo, canRedo}] as const;
103
- };
package/src/index.tsx DELETED
@@ -1,55 +0,0 @@
1
- import shallowequal from 'shallowequal';
2
-
3
- export const {
4
- assignPick,
5
- shallowEqual,
6
- } = new class {
7
- /**
8
- * 从一个对象里挑出需要的键值对,此方法修改源对象
9
- * note: this fn will change original object!
10
- */
11
- assignPick = <O extends {} , K extends Array<keyof O>>(object : O , keys : K) : Pick<O , ArrayElement<K>> => {
12
- Object.keys(object).forEach((k) => {/*@ts-ignore*/
13
- if( !keys.includes(k) ) {
14
- delete object[k];
15
- }
16
- });
17
- return object as Pick<O , ArrayElement<K>>;
18
- };
19
- /**
20
- * 浅比较两个索引对象相等性
21
- * @type {(src, target) => boolean}
22
- */
23
- shallowEqual : (src , target) => boolean = shallowequal;
24
- }();
25
-
26
-
27
- /*无依赖@@utils的放上面*/
28
- export * from './isPromise.utility';
29
- export * from './debounce.utility';
30
- export * from './stringify.utility';
31
- export * from './crayon.utility';
32
- export * from './checkGenericNull.utility';
33
- export * from './runOnlyOnce.utility';
34
- export * from './ConditionRender.utility';
35
- export * from './makePair.utility';
36
- export * from './timer.utility';
37
- export * from './replaceStr.utility';
38
- export * from './queryString.utility';
39
- export * from './orzPromise.utility';
40
-
41
- export * from './assert-group.utility';
42
- export * from './dataflow.utility';
43
-
44
- export * from './logProxy.utility';
45
-
46
- export * from "./hooks";
47
-
48
- export {default as Cookie} from './cookie.utility';
49
- export {default as checkType} from './checkType.utility';
50
- export {default as getNestedValue} from './getNestedValue.utility';
51
- export {default as Random} from './random.utility';
52
- export {default as throttle} from './throttle.utility';
53
-
54
-
55
-
@@ -1,10 +0,0 @@
1
- export const isPromise = <T = any>( target : any ) : target is Promise<T> => {
2
-
3
- if (
4
- _.isObject( target ) &&
5
- target instanceof Promise
6
- ) {
7
- return true;
8
- }
9
- return false;
10
- };
@@ -1,7 +0,0 @@
1
- /**
2
- * console.log a proxy as an normal object to show;
3
- * note: it is
4
- * @param source
5
- */
6
- export const logProxy = ( source:object = {} ) => JSON.parse( stringify( _.cloneDeep( source ) ) );
7
- import { stringify } from './stringify.utility';
@@ -1,18 +0,0 @@
1
- /**
2
- * 成对使用数据
3
- * @param value 也可是callback
4
- */
5
- export const makePair =
6
- <I , F extends (value : I) => any >
7
- (value : I , ...callbacks : F[]) : [ I , ...ReturnType<F>[] ] => {
8
- return [
9
- value ,
10
- ...callbacks.map(callback => {
11
- if( typeof callback === 'function' ) {
12
- return callback(value);
13
- }
14
- }) ,
15
- ];
16
- };
17
-
18
- const [ value , computed ] = makePair({ a : 1 , b : 2 } , (value) => [value.a,'sdad']);
@@ -1,24 +0,0 @@
1
- /**
2
- * @format
3
- * @description 生成一个pending状态的promise
4
- */
5
-
6
- export const orzPromise = <T = any>(
7
- callback?: (resolve: Function, reject: Function) => any,
8
- ): Promise<T> & {
9
- resolve: (value?: any) => void;
10
- reject: (reason?: any) => void;
11
- } => {
12
- let resolve: (value?: any) => void, reject: (reason?: any) => void;
13
- const promise = new Promise<T>(($resolve, $reject) => {
14
- resolve = $resolve;
15
- reject = $reject;
16
- typeof callback === 'function' && callback($resolve, $reject);
17
- });
18
- Object.assign(promise, {
19
- resolve,
20
- reject,
21
- });
22
-
23
- return promise as Promise<T> & {resolve; reject};
24
- };
package/src/overload.ts DELETED
@@ -1,17 +0,0 @@
1
- /**
2
- * 将重载参数匹配转换为对象key-value
3
- * @example
4
- */
5
- export const overload = (params,processer) => {
6
- return params.reduce((accumulator,current) => {
7
- processer.forEach(({
8
- regExp ,
9
- key,
10
- }) => {
11
- if ( regExp.test(current) ) {
12
- accumulator[key] = current;
13
- }
14
- });
15
- return accumulator;
16
- }, {});
17
- };
@@ -1,77 +0,0 @@
1
- /**
2
- * @description 将字符串qs转换为对象(暂不支持多层嵌套)||注意:中文key-value需要decodeURIComponent!!!
3
- * @param str 要转换的字符串,不传默认是获取href query对象
4
- */
5
-
6
- export const decodeQueryString = <result extends string[] = []>( str: string = location.href ): Batch<result , string> => {
7
- type ret = Batch<result , string>;
8
- const empty = {} as ret;
9
- const thr = () : never => {
10
- throw new Error( `非法的queryString , 原字符串为 : ${ str }` );
11
- };
12
- try {
13
- /**
14
- * case1 : 一个不含?的queryString
15
- * 测试用例 :
16
- `csd=123`
17
- `vasd=`
18
- `=`
19
- */
20
- {
21
- if(str.includes('?')){
22
- [,str] = str.split('?');
23
- }
24
- if(str.includes('/')){
25
- [str] = str.split('/');
26
- }
27
-
28
-
29
- if(!str.includes('=')){
30
- return empty;
31
- }
32
-
33
- if(str.includes('&')){
34
- return str.split('&').reduce((accumulator,current) => {
35
- const [key,value] = current.split('=');
36
- accumulator[key] = value;
37
- return accumulator;
38
- },{} as ret);
39
- }else {
40
- const temp = {};
41
- const [ key , value ] = str.split( '=' );
42
- temp[ key ] = value;
43
- return temp as ret;
44
- }
45
- }
46
- } catch ( e ) {
47
- console.error( `decodeQueryString -> 转换失败 , 原始字符串为 : ${ str }` );
48
- console.error( e );
49
- throw '';
50
- }
51
- };
52
-
53
-
54
-
55
- /**
56
- * 将对象转换为queryString不带问号(暂不支持多层嵌套)
57
- * @return {string} a=1&b=2
58
- */
59
- export const encodeQueryString = ( source: object ):string => {
60
- let result = ``;
61
- for ( const key in source ) {
62
- const value = source[ key ];
63
- if ( typeof value === 'object' && value !== null ) {
64
- throw '暂不支持嵌套对象';
65
- }
66
- if ( typeof key === 'symbol' ) {
67
- throw '不支持key为Symbol';
68
- }
69
- result = `${ result }${ result && '&' }${ key }=${ value }`;
70
- }
71
- return result;
72
- };
73
-
74
-
75
-
76
-
77
-
@@ -1,73 +0,0 @@
1
- /**
2
- *
3
- * Random工具方法
4
- *
5
- */
6
-
7
- const Random = {
8
- /**
9
- * color
10
- *
11
- * @description 生成随机颜色
12
- * @function
13
- * @returns {string} 一个随机的HEX格式的颜色
14
- * @example
15
- *
16
- * Random.color() // => '#000000'
17
- */
18
- color() {
19
- return '#' + Math.floor(Math.random() * 0xffffff).toString(16);
20
- },
21
-
22
- /**
23
- * number
24
- *
25
- * @description 生成指定范围[min, max]的随机数
26
- * @param {number} min - 最小值
27
- * @param {number} max - 最大值
28
- * @param {boolean|number} float - 控制小数展示以及小数位数,默认值为false
29
- * @function
30
- * @returns {number} 一个随机范围的数字
31
- * @example
32
- *
33
- * Random.number(1, 100) // => 50
34
- * Random.number(1, 100, true) // => 66.357922312356983
35
- * Random.number(1, 100, 1) // => 29.1
36
- * Random.number(1, 100, 3) // => 61.232
37
- */
38
- number(min: number, max: number, float?: number | boolean) {
39
- if (min === undefined) {
40
- return Math.random();
41
- }
42
-
43
- if (max === undefined) {
44
- max = min;
45
- min = 0;
46
- }
47
-
48
- if (max < min) {
49
- let tmp = max;
50
- max = min;
51
- min = tmp;
52
- }
53
-
54
- if (float) {
55
- let result = Math.random() * (max - min) + min;
56
- if (float === true) {
57
- return result;
58
- } else if (typeof float === 'number') {
59
- let str = result.toString();
60
- let index = str.indexOf('.');
61
- str = str.substr(0, index + 1 + float);
62
- if (str[str.length - 1] === '0') {
63
- str = str.substr(0, str.length - 1) + _.random(1, 9);
64
- }
65
- return parseFloat(str);
66
- }
67
- }
68
-
69
- return Math.floor(Math.random() * (max - min + 1) + min);
70
- },
71
- };
72
-
73
- export default Random;
@@ -1,15 +0,0 @@
1
- /**
2
- * @format
3
- * @description 将sourceText中的coordinate[0] - coordinate[1]替换为paragraph
4
- * @example const str = 'The quick brown fox jumps over the lazy dog.'; replace(str,[0,9],'fuck you ass') -> "fuck you ass brown fox jumps over the lazy dog."
5
- */
6
-
7
- export const replaceStrUtility = (
8
- sourceText: string,
9
- [coordinate0, coordinate1]: [number, number],
10
- paragraph: string,
11
- ) => {
12
- const first = sourceText.slice(0, coordinate0);
13
- const last = sourceText.slice(coordinate1);
14
- return first.concat(paragraph, last);
15
- };
@@ -1,13 +0,0 @@
1
- /**
2
- * /*将callback闭包, 永远只会调用一次, 用于防止重复挂载事件
3
- *
4
- * @format
5
- */
6
-
7
- export const runOnlyOnce = callback => {
8
- let first = true;
9
- return (...args) => {
10
- if (first) callback(...args), (first = false);
11
- else return;
12
- };
13
- };