plugin.js
2.38 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
import Vue from "vue";
import GlobalLoading from "./index.vue";
const LoadingConstructor = Vue.extend(GlobalLoading);
const DEFAULT_OPTIONS = {
delay: 250,
minDuration: 300,
};
let instance = null;
let pendingCount = 0;
let showTimer = null;
let hideTimer = null;
let latestOptions = { ...DEFAULT_OPTIONS };
let shownAt = 0;
function getInstance() {
if (instance)
return instance;
instance = new LoadingConstructor({
el: document.createElement("div"),
});
document.body.appendChild(instance.$el);
return instance;
}
function normalizeOptions(options = {}) {
const config = typeof options === "string" ? { text: options } : options;
return {
...DEFAULT_OPTIONS,
...config,
};
}
function clearShowTimer() {
if (!showTimer)
return;
clearTimeout(showTimer);
showTimer = null;
}
function clearHideTimer() {
if (!hideTimer)
return;
clearTimeout(hideTimer);
hideTimer = null;
}
function openLoading(options) {
const loadingInstance = getInstance();
loadingInstance.open(options);
shownAt = Date.now();
return loadingInstance;
}
export const loading = {
show(options = {}) {
pendingCount += 1;
const config = normalizeOptions(options);
latestOptions = config;
clearHideTimer();
const loadingInstance = getInstance();
if (loadingInstance.visible) {
loadingInstance.open(config);
return loadingInstance;
}
clearShowTimer();
if (config.delay <= 0)
return openLoading(config);
showTimer = setTimeout(() => {
showTimer = null;
if (pendingCount <= 0)
return;
openLoading(latestOptions);
}, config.delay);
return loadingInstance;
},
hide(force = false) {
if (force) {
pendingCount = 0;
} else {
pendingCount = Math.max(pendingCount - 1, 0);
}
if (pendingCount > 0)
return;
clearShowTimer();
if (!instance || !instance.visible)
return;
clearHideTimer();
const minDuration = Number(latestOptions.minDuration) || 0;
const visibleDuration = Date.now() - shownAt;
const remainingDuration = Math.max(minDuration - visibleDuration, 0);
if (remainingDuration === 0) {
instance.close();
return;
}
hideTimer = setTimeout(() => {
hideTimer = null;
if (pendingCount === 0 && instance)
instance.close();
}, remainingDuration);
},
clear() {
this.hide(true);
},
};
export default {
install(VueInstance) {
if (VueInstance.prototype.$loading)
return;
VueInstance.prototype.$loading = loading;
},
};