-
Notifications
You must be signed in to change notification settings - Fork 18
/
index.tsx
68 lines (62 loc) · 1.68 KB
/
index.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { Wrapper, LoadingWrapperProps } from './Wrapper';
import { createPortalDOM } from '../utils/dom';
import isPlainObject from 'lodash/isPlainObject';
/**
* 显示loading
* @param hint 提示文字
* @param option
* @returns
*/
export function showLoading(hint?: string, option?: LoadingWrapperProps) {
const { mount, unmount } = createPortalDOM();
let props: LoadingWrapperProps = { hint, status: 'show' };
if (isPlainObject(option)) {
delete option!.status;
props = { ...props, ...option };
}
// 关闭loading
const closeLoading = async () => {
props.status = 'hide';
props.onHide = unmount;
await mount(<Wrapper {...props} />);
};
// 显示loading
const mountShow = mount(<Wrapper {...props} />);
// 关闭loading
return async () => {
await mountShow;
await closeLoading();
};
}
/**
* 显示loading,至少展示atLeast毫秒
* @param atLeast 最小展示时间
* @param hint 提示文字
* @param option 各种可定制的选项
* @returns
*/
export function showLoadingAtLeast(
atLeast = 300,
hint?: string,
option?: LoadingWrapperProps
) {
const closeLoading = showLoading(hint, option);
// 记录开始展示的时间
const start = Date.now();
// 返回一个可关闭的函数
return async () => {
const now = Date.now();
const diff = now - start;
// 如果当前关闭的时间已经超过最小允许的时间,直接关闭
if (diff >= atLeast) {
await closeLoading();
return;
}
// 等待剩余的差时间差
await new Promise<void>((resolve) => {
window.setTimeout(resolve, atLeast - diff);
});
// 时间够了,直接关闭
await closeLoading();
};
}