slider-captcha-sdk 1.0.19 → 1.0.21
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.
- package/README.md +254 -37
- package/dist/README.md +254 -37
- package/dist/index.esm.js +1 -1309
- package/dist/index.min.js +1 -1
- package/dist/password-validator.d.ts +13 -17
- package/dist/password-validator.esm.js +1 -368
- package/dist/password-validator.min.js +1 -1
- package/dist/slider-captcha.esm.js +1 -917
- package/dist/slider-captcha.min.js +1 -1
- package/package.json +10 -3
|
@@ -1,917 +1 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 纯JavaScript弹窗滑块验证码组件
|
|
3
|
-
*/
|
|
4
|
-
class PopupSliderCaptcha {
|
|
5
|
-
static DEFAULTS = {
|
|
6
|
-
width: 320,
|
|
7
|
-
height: 155,
|
|
8
|
-
sliderSize: 38,
|
|
9
|
-
maxRetries: 3,
|
|
10
|
-
timeout: 30000,
|
|
11
|
-
apiUrl: '/api/captcha',
|
|
12
|
-
verifyUrl: '/api/captcha/verify',
|
|
13
|
-
throttleDelay: 16,
|
|
14
|
-
clickMaskClose: false,
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
static CSS_CLASSES = {
|
|
18
|
-
overlay: 'slider-captcha-overlay',
|
|
19
|
-
modal: 'slider-captcha-modal',
|
|
20
|
-
header: 'slider-captcha-header',
|
|
21
|
-
container: 'slider-captcha-container',
|
|
22
|
-
track: 'slider-captcha-track',
|
|
23
|
-
btn: 'slider-captcha-btn',
|
|
24
|
-
hint: 'slider-captcha-hint',
|
|
25
|
-
loading: 'slider-captcha-loading',
|
|
26
|
-
error: 'slider-captcha-error',
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
// 优化:提取CSS样式为独立方法,减少主体代码长度
|
|
30
|
-
static getStyles() {
|
|
31
|
-
return `:root{--sc-primary:#409eff;--sc-success:#67c23a;--sc-danger:#f56c6c;--sc-border:#e4e7eb;--sc-bg:linear-gradient(90deg, #f7f9fa 0%, #e8f4fd 100%);--sc-text:#333;--sc-text-light:#999;--sc-shadow:0 4px 20px rgba(0,0,0,.3);--sc-radius:8px;--sc-transition:.3s ease}.slider-captcha-overlay{position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,.5);z-index:9999;display:none;justify-content:center;align-items:center;opacity:0;transition:opacity var(--sc-transition)}.slider-captcha-overlay.show{opacity:1}.slider-captcha-modal{background:#fff;border-radius:var(--sc-radius);padding:20px;box-shadow:var(--sc-shadow);position:relative;max-width:90vw;max-height:90vh;transform:scale(.8) translateY(-20px);opacity:0;transition:all var(--sc-transition)}.slider-captcha-modal.show{transform:scale(1) translateY(0);opacity:1}.slider-captcha-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:15px;padding-bottom:10px;border-bottom:1px solid var(--sc-border)}.slider-captcha-container{display:flex;align-items:center;position:relative;border-radius:4px;overflow:hidden;margin-bottom:15px;background:#837a7a;justify-content:center}.slider-captcha-track{width:100%;height:40px;line-height:40px;background:var(--sc-bg);border:1px solid var(--sc-border);border-radius:20px;position:relative;margin-bottom:15px;overflow:hidden}.slider-captcha-btn{width:38px;height:38px;background:#fff;border:1px solid #ccc;border-radius:50%;position:absolute;top:0;left:0;cursor:pointer;display:flex;align-items:center;justify-content:center;box-shadow:0 2px 4px rgba(0,0,0,.1);transition:all var(--sc-transition);user-select:none;z-index:1}.slider-captcha-loading{position:absolute;top:0;left:0;width:100%;height:100%;background:rgba(255,255,255,.6);display:flex;align-items:center;justify-content:center;flex-direction:column;color:#666;font-size:14px;z-index:10;border-radius:4px}.slider-captcha-error{color:var(--sc-danger);font-size:12px;text-align:center;margin-top:10px;display:none}.slider-captcha-title{margin:0;font-size:16px;color:var(--sc-text)}.slider-captcha-close,.slider-captcha-refresh{background:none;border:none;cursor:pointer;color:var(--sc-text-light);padding:0;width:30px;height:30px;display:flex;align-items:center;justify-content:center;border-radius:50%;transition:all var(--sc-transition);position:relative;font-size:0}.slider-captcha-close::before,.slider-captcha-close::after{content:'';position:absolute;width:16px;height:2px;background-color:var(--sc-text-light);border-radius:1px;transition:all var(--sc-transition)}.slider-captcha-close::before{transform:rotate(45deg)}.slider-captcha-close::after{transform:rotate(-45deg)}.slider-captcha-close:hover{background:#f5f5f5;transform:scale(1.1)}.slider-captcha-close:hover::before,.slider-captcha-close:hover::after{background-color:var(--sc-danger)}.slider-captcha-refresh{margin-left:10px}.slider-captcha-refresh svg{width:20px;height:20px;fill:var(--sc-text-light);transition:all var(--sc-transition)}.slider-captcha-refresh:hover{background:#f5f5f5;transform:scale(1.1)}.slider-captcha-refresh:hover svg{fill:var(--sc-primary);transform:rotate(180deg)}.slider-captcha-floating-time{position:absolute;bottom:-40px;left:50%;transform:translateX(-50%);color:#fff;font-size:12px;white-space:nowrap;opacity:0;pointer-events:none;z-index:10;transition:all var(--sc-transition);background:#fff;padding:2px 15px;border-radius:10px}.slider-captcha-floating-time.show{opacity:1;transform:translateX(-50%) translateY(-45px)}.slider-captcha-floating-time.success{color:var(--sc-success)}.slider-captcha-floating-time.fail{color:var(--sc-danger)}.slider-captcha-bg{width:100%;height:100%;object-fit:cover;display:block}.slider-captcha-piece{position:absolute;top:0;left:0;cursor:pointer;transition:none;z-index:2}.slider-captcha-finger{position:absolute;top:50%;left:10px;transform:translateY(-50%);font-size:20px;animation:fingerSlide 2s ease-in-out infinite;pointer-events:none;z-index:1;opacity:.6}.slider-captcha-hint{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);color:var(--sc-text-light);font-size:14px;pointer-events:none;z-index:1;transition:all var(--sc-transition)}.slider-captcha-header-buttons{display:flex;align-items:center}@keyframes fingerSlide{0%{left:10px;opacity:.6}50%{opacity:1}100%{left:calc(50% - 10px);opacity:.6}}`
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
// 优化:添加常量定义,提高可维护性
|
|
35
|
-
static CONSTANTS = {
|
|
36
|
-
CACHE_DURATION: 5 * 60 * 1000, // 5分钟缓存
|
|
37
|
-
MAX_RETRY_ATTEMPTS: 3,
|
|
38
|
-
DEFAULT_TIMEOUT: 30000,
|
|
39
|
-
FLOATING_TIME_DURATION: 2500,
|
|
40
|
-
THROTTLE_DELAY: 16,
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
static ERROR_TYPES = {
|
|
44
|
-
NETWORK_ERROR: 'NETWORK_ERROR',
|
|
45
|
-
TIMEOUT_ERROR: 'TIMEOUT_ERROR',
|
|
46
|
-
VALIDATION_ERROR: 'VALIDATION_ERROR',
|
|
47
|
-
IMAGE_LOAD_ERROR: 'IMAGE_LOAD_ERROR',
|
|
48
|
-
CAPTCHA_DATA_ERROR: 'CAPTCHA_DATA_ERROR',
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
constructor(options = {}) {
|
|
52
|
-
this.options = {
|
|
53
|
-
...PopupSliderCaptcha.DEFAULTS,
|
|
54
|
-
...options,
|
|
55
|
-
timeout: options.timeout || PopupSliderCaptcha.CONSTANTS.DEFAULT_TIMEOUT,
|
|
56
|
-
maxRetries: options.maxRetries || PopupSliderCaptcha.CONSTANTS.MAX_RETRY_ATTEMPTS,
|
|
57
|
-
throttleDelay: options.throttleDelay || PopupSliderCaptcha.CONSTANTS.THROTTLE_DELAY,
|
|
58
|
-
};
|
|
59
|
-
|
|
60
|
-
this.elements = {};
|
|
61
|
-
this.state = this.createInitialState();
|
|
62
|
-
this.captchaData = null;
|
|
63
|
-
this.times = [];
|
|
64
|
-
this.startTime = null;
|
|
65
|
-
this.eventListeners = [];
|
|
66
|
-
this.timers = new Set();
|
|
67
|
-
this.rafId = null;
|
|
68
|
-
this.cachedDimensions = null;
|
|
69
|
-
this.imageCache = new Map();
|
|
70
|
-
this.abortController = null;
|
|
71
|
-
|
|
72
|
-
this.throttledHandleMove = this.throttle((e) => this.handleMove(e), this.options.throttleDelay);
|
|
73
|
-
|
|
74
|
-
try {
|
|
75
|
-
this.init();
|
|
76
|
-
} catch (error) {
|
|
77
|
-
console.error('滑块验证码初始化失败:', error);
|
|
78
|
-
this.handleError(PopupSliderCaptcha.ERROR_TYPES.VALIDATION_ERROR, error.message);
|
|
79
|
-
}
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
createInitialState() {
|
|
83
|
-
return {
|
|
84
|
-
isVisible: false,
|
|
85
|
-
isDragging: false,
|
|
86
|
-
currentX: 0,
|
|
87
|
-
startX: 0,
|
|
88
|
-
retryCount: 0,
|
|
89
|
-
isLoading: false,
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
init() {
|
|
94
|
-
this.injectStyles();
|
|
95
|
-
this.createElements();
|
|
96
|
-
this.bindEvents();
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
injectStyles() {
|
|
100
|
-
if (document.querySelector('#slider-captcha-styles')) return
|
|
101
|
-
|
|
102
|
-
const style = document.createElement('style');
|
|
103
|
-
style.id = 'slider-captcha-styles';
|
|
104
|
-
style.textContent = PopupSliderCaptcha.getStyles();
|
|
105
|
-
document.head.appendChild(style);
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
createElements() {
|
|
109
|
-
const { elements, options } = this;
|
|
110
|
-
|
|
111
|
-
// 批量创建元素配置
|
|
112
|
-
const elementConfigs = [
|
|
113
|
-
['overlay', 'div', PopupSliderCaptcha.CSS_CLASSES.overlay],
|
|
114
|
-
['modal', 'div', PopupSliderCaptcha.CSS_CLASSES.modal],
|
|
115
|
-
['header', 'div', PopupSliderCaptcha.CSS_CLASSES.header],
|
|
116
|
-
['title', 'h3', 'slider-captcha-title', '安全验证'],
|
|
117
|
-
['closeBtn', 'button', 'slider-captcha-close'],
|
|
118
|
-
['refreshBtn', 'button', 'slider-captcha-refresh'],
|
|
119
|
-
['container', 'div', PopupSliderCaptcha.CSS_CLASSES.container],
|
|
120
|
-
['backgroundImg', 'img', 'slider-captcha-bg'],
|
|
121
|
-
['sliderImg', 'img', 'slider-captcha-piece'],
|
|
122
|
-
['loadingText', 'div', PopupSliderCaptcha.CSS_CLASSES.loading, '加载中...'],
|
|
123
|
-
['floatingTime', 'div', 'slider-captcha-floating-time'],
|
|
124
|
-
['track', 'div', PopupSliderCaptcha.CSS_CLASSES.track],
|
|
125
|
-
['fingerAnimation', 'div', 'slider-captcha-finger', '👉'],
|
|
126
|
-
['btn', 'div', PopupSliderCaptcha.CSS_CLASSES.btn],
|
|
127
|
-
['icon', 'div', '', '→'],
|
|
128
|
-
['hint', 'div', PopupSliderCaptcha.CSS_CLASSES.hint, '向右滑动完成验证'],
|
|
129
|
-
['error', 'div', PopupSliderCaptcha.CSS_CLASSES.error],
|
|
130
|
-
];
|
|
131
|
-
|
|
132
|
-
// 批量创建元素
|
|
133
|
-
elementConfigs.forEach(([key, tag, className, textContent]) => {
|
|
134
|
-
elements[key] = this.createElement(tag, className, textContent);
|
|
135
|
-
});
|
|
136
|
-
|
|
137
|
-
// 设置容器尺寸
|
|
138
|
-
elements.container.style.cssText = `width:${options.width}px;height:${options.height}px`;
|
|
139
|
-
|
|
140
|
-
// 添加刷新按钮图标
|
|
141
|
-
elements.refreshBtn.innerHTML = `<svg viewBox="0 0 24 24"><path d="M17.65,6.35C16.2,4.9 14.21,4 12,4A8,8 0 0,0 4,12A8,8 0 0,0 12,20C15.73,20 18.84,17.45 19.73,14H17.65C16.83,16.33 14.61,18 12,18A6,6 0 0,1 6,12A6,6 0 0,1 12,6C13.66,6 15.14,6.69 16.22,7.78L13,11H20V4L17.65,6.35Z"/></svg>`;
|
|
142
|
-
|
|
143
|
-
this.assembleDOM();
|
|
144
|
-
this.setInitialState();
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
createElement(tag, className = '', textContent = '') {
|
|
148
|
-
const element = document.createElement(tag);
|
|
149
|
-
if (className) element.className = className;
|
|
150
|
-
if (textContent) element.textContent = textContent;
|
|
151
|
-
return element
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
assembleDOM() {
|
|
155
|
-
const { elements } = this;
|
|
156
|
-
|
|
157
|
-
// 组装头部
|
|
158
|
-
const headerButtons = this.createElement('div', 'slider-captcha-header-buttons');
|
|
159
|
-
headerButtons.append(elements.refreshBtn, elements.closeBtn);
|
|
160
|
-
elements.header.append(elements.title, headerButtons);
|
|
161
|
-
|
|
162
|
-
// 组装验证码容器
|
|
163
|
-
elements.container.append(
|
|
164
|
-
elements.backgroundImg,
|
|
165
|
-
elements.sliderImg,
|
|
166
|
-
elements.loadingText,
|
|
167
|
-
elements.floatingTime,
|
|
168
|
-
);
|
|
169
|
-
|
|
170
|
-
// 组装滑块轨道
|
|
171
|
-
elements.btn.appendChild(elements.icon);
|
|
172
|
-
elements.track.append(elements.fingerAnimation, elements.btn, elements.hint);
|
|
173
|
-
|
|
174
|
-
// 组装模态框
|
|
175
|
-
elements.modal.append(elements.header, elements.container, elements.track, elements.error);
|
|
176
|
-
|
|
177
|
-
// 组装到覆盖层
|
|
178
|
-
elements.overlay.appendChild(elements.modal);
|
|
179
|
-
document.body.appendChild(elements.overlay);
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
setInitialState() {
|
|
183
|
-
// 批量设置初始状态
|
|
184
|
-
Object.assign(this.elements.container.style, { display: 'none' });
|
|
185
|
-
Object.assign(this.elements.track.style, { display: 'none' });
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
bindEvents() {
|
|
189
|
-
const { elements } = this;
|
|
190
|
-
|
|
191
|
-
// 基础事件
|
|
192
|
-
this.addEventListener(elements.closeBtn, 'click', () => this.hide());
|
|
193
|
-
this.addEventListener(elements.refreshBtn, 'click', () => this.refresh());
|
|
194
|
-
this.addEventListener(elements.overlay, 'click', (e) => {
|
|
195
|
-
if (e.target === elements.overlay && this.options.clickMaskClose) this.hide();
|
|
196
|
-
});
|
|
197
|
-
this.addEventListener(document, 'keydown', (e) => {
|
|
198
|
-
if (e.key === 'Escape' && this.state.isVisible) this.hide();
|
|
199
|
-
});
|
|
200
|
-
this.addEventListener(document, 'visibilitychange', () => this.handleVisibilityChange());
|
|
201
|
-
|
|
202
|
-
this.bindSliderEvents();
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
bindSliderEvents() {
|
|
206
|
-
const { elements } = this;
|
|
207
|
-
const handlers = {
|
|
208
|
-
start: (e) => this.handleStart(e),
|
|
209
|
-
move: this.throttledHandleMove,
|
|
210
|
-
end: () => this.handleEnd(),
|
|
211
|
-
};
|
|
212
|
-
|
|
213
|
-
// 滑块事件
|
|
214
|
-
this.addEventListener(elements.btn, 'mousedown', handlers.start);
|
|
215
|
-
this.addEventListener(elements.btn, 'touchstart', handlers.start);
|
|
216
|
-
this.addEventListener(elements.sliderImg, 'mousedown', handlers.start);
|
|
217
|
-
this.addEventListener(elements.sliderImg, 'touchstart', handlers.start);
|
|
218
|
-
this.addEventListener(document, 'mousemove', handlers.move, { passive: false });
|
|
219
|
-
this.addEventListener(document, 'touchmove', handlers.move, { passive: false });
|
|
220
|
-
this.addEventListener(document, 'mouseup', handlers.end);
|
|
221
|
-
this.addEventListener(document, 'touchend', handlers.end);
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
addEventListener(element, event, handler, options = {}) {
|
|
225
|
-
if (!element || typeof handler !== 'function') return
|
|
226
|
-
|
|
227
|
-
element.addEventListener(event, handler, options);
|
|
228
|
-
this.eventListeners.push({ element, event, handler, options });
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
removeAllEventListeners() {
|
|
232
|
-
this.eventListeners.forEach(({ element, event, handler, options }) => {
|
|
233
|
-
try {
|
|
234
|
-
element?.removeEventListener?.(event, handler, options);
|
|
235
|
-
} catch (error) {
|
|
236
|
-
console.warn('Failed to remove event listener:', error);
|
|
237
|
-
}
|
|
238
|
-
});
|
|
239
|
-
this.eventListeners.length = 0;
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
getDimensions() {
|
|
243
|
-
if (!this.cachedDimensions) {
|
|
244
|
-
const trackWidth = this.elements.track.offsetWidth;
|
|
245
|
-
const btnWidth = this.elements.btn.offsetWidth;
|
|
246
|
-
this.cachedDimensions = {
|
|
247
|
-
trackWidth,
|
|
248
|
-
btnWidth,
|
|
249
|
-
maxX: trackWidth - btnWidth,
|
|
250
|
-
};
|
|
251
|
-
}
|
|
252
|
-
return this.cachedDimensions
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
getPosition() {
|
|
256
|
-
const { maxX } = this.getDimensions();
|
|
257
|
-
const percentage = this.state.currentX / maxX;
|
|
258
|
-
return Math.round(percentage * (this.options.width - this.options.sliderSize))
|
|
259
|
-
}
|
|
260
|
-
|
|
261
|
-
handleStart(e) {
|
|
262
|
-
if (!this.captchaData || this.state.isDragging || this.state.isLoading) return
|
|
263
|
-
|
|
264
|
-
e.preventDefault();
|
|
265
|
-
this.state.isDragging = true;
|
|
266
|
-
this.state.startX = this.getClientX(e) - this.state.currentX;
|
|
267
|
-
this.dragStartTime = Date.now();
|
|
268
|
-
this.times = [{ time: Date.now(), position: this.getPosition() }];
|
|
269
|
-
|
|
270
|
-
this.setTransition(false);
|
|
271
|
-
this.updateUIState('dragging');
|
|
272
|
-
this.cachedDimensions = null; // 清除缓存
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
handleMove(e) {
|
|
276
|
-
if (!this.state.isDragging) return
|
|
277
|
-
e.preventDefault();
|
|
278
|
-
|
|
279
|
-
const clientX = this.getClientX(e);
|
|
280
|
-
const deltaX = clientX - this.state.startX;
|
|
281
|
-
const { maxX } = this.getDimensions();
|
|
282
|
-
|
|
283
|
-
this.state.currentX = Math.max(0, Math.min(deltaX, maxX));
|
|
284
|
-
this.times.push({ time: Date.now(), position: this.getPosition() });
|
|
285
|
-
|
|
286
|
-
// 优化:使用RAF批量更新
|
|
287
|
-
this.rafId && cancelAnimationFrame(this.rafId);
|
|
288
|
-
this.rafId = requestAnimationFrame(() => this.updateSliderPosition());
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
handleEnd() {
|
|
292
|
-
if (!this.state.isDragging) return
|
|
293
|
-
|
|
294
|
-
this.times.push({ time: Date.now(), position: this.getPosition() });
|
|
295
|
-
this.state.isDragging = false;
|
|
296
|
-
|
|
297
|
-
if (this.rafId) {
|
|
298
|
-
cancelAnimationFrame(this.rafId);
|
|
299
|
-
this.rafId = null;
|
|
300
|
-
}
|
|
301
|
-
|
|
302
|
-
this.verify();
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
handleVisibilityChange() {
|
|
306
|
-
const animationState = document.hidden ? 'paused' : 'running';
|
|
307
|
-
if (this.elements.fingerAnimation) {
|
|
308
|
-
this.elements.fingerAnimation.style.animationPlayState = animationState;
|
|
309
|
-
}
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
getClientX(e) {
|
|
313
|
-
return e.type.includes('touch') ? e.touches[0].clientX : e.clientX
|
|
314
|
-
}
|
|
315
|
-
|
|
316
|
-
setTransition(enabled) {
|
|
317
|
-
const transition = enabled ? 'all 0.3s ease' : 'none';
|
|
318
|
-
requestAnimationFrame(() => {
|
|
319
|
-
this.elements.btn.style.transition = transition;
|
|
320
|
-
this.elements.sliderImg.style.transition = transition;
|
|
321
|
-
});
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
// 优化:简化UI状态更新
|
|
325
|
-
updateUIState(state) {
|
|
326
|
-
const { elements } = this;
|
|
327
|
-
const updates = {
|
|
328
|
-
dragging: () => {
|
|
329
|
-
elements.hint.style.opacity = '0';
|
|
330
|
-
elements.fingerAnimation.style.display = 'none';
|
|
331
|
-
},
|
|
332
|
-
success: () => {
|
|
333
|
-
Object.assign(elements.btn.style, { background: 'var(--sc-success)' });
|
|
334
|
-
Object.assign(elements.icon.style, { innerHTML: '✓', color: 'white' });
|
|
335
|
-
elements.icon.innerHTML = '✓';
|
|
336
|
-
},
|
|
337
|
-
fail: () => {
|
|
338
|
-
Object.assign(elements.btn.style, { background: 'var(--sc-danger)' });
|
|
339
|
-
Object.assign(elements.icon.style, { innerHTML: '✗', color: 'white' });
|
|
340
|
-
elements.icon.innerHTML = '✗';
|
|
341
|
-
},
|
|
342
|
-
reset: () => {
|
|
343
|
-
Object.assign(elements.btn.style, { background: 'white' });
|
|
344
|
-
Object.assign(elements.icon.style, { color: '#666' });
|
|
345
|
-
elements.icon.innerHTML = '→';
|
|
346
|
-
elements.fingerAnimation.style.display = 'block';
|
|
347
|
-
this.updateHintText('向右滑动完成验证', 'var(--sc-text-light)');
|
|
348
|
-
},
|
|
349
|
-
loading: () => {
|
|
350
|
-
elements.hint.style.opacity = '0';
|
|
351
|
-
elements.fingerAnimation.style.display = 'none';
|
|
352
|
-
Object.assign(elements.track.style, { pointerEvents: 'none', opacity: '0.6' });
|
|
353
|
-
},
|
|
354
|
-
};
|
|
355
|
-
|
|
356
|
-
if (updates[state]) {
|
|
357
|
-
requestAnimationFrame(() => {
|
|
358
|
-
updates[state]();
|
|
359
|
-
if (state !== 'loading') {
|
|
360
|
-
Object.assign(elements.track.style, { pointerEvents: 'auto', opacity: '1' });
|
|
361
|
-
}
|
|
362
|
-
});
|
|
363
|
-
}
|
|
364
|
-
}
|
|
365
|
-
|
|
366
|
-
updateHintText(text, color) {
|
|
367
|
-
requestAnimationFrame(() => {
|
|
368
|
-
Object.assign(this.elements.hint, { textContent: text });
|
|
369
|
-
Object.assign(this.elements.hint.style, { color, opacity: '1' });
|
|
370
|
-
});
|
|
371
|
-
}
|
|
372
|
-
|
|
373
|
-
updateSliderPosition() {
|
|
374
|
-
const { elements, options, state } = this;
|
|
375
|
-
const { maxX } = this.getDimensions();
|
|
376
|
-
const pieceX = (state.currentX / maxX) * (options.width - options.sliderSize);
|
|
377
|
-
const progress = state.currentX / maxX;
|
|
378
|
-
|
|
379
|
-
requestAnimationFrame(() => {
|
|
380
|
-
elements.btn.style.transform = `translateX(${state.currentX}px)`;
|
|
381
|
-
elements.sliderImg.style.transform = `translateX(${pieceX}px)`;
|
|
382
|
-
elements.fingerAnimation.style.opacity = progress >= 0.8 ? '0' : '0.6';
|
|
383
|
-
});
|
|
384
|
-
}
|
|
385
|
-
|
|
386
|
-
// 优化:简化显示/隐藏逻辑
|
|
387
|
-
show() {
|
|
388
|
-
this.state.isVisible = true;
|
|
389
|
-
this.elements.overlay.style.display = 'flex';
|
|
390
|
-
|
|
391
|
-
requestAnimationFrame(() => {
|
|
392
|
-
this.elements.overlay.classList.add('show');
|
|
393
|
-
this.elements.modal.classList.add('show');
|
|
394
|
-
});
|
|
395
|
-
|
|
396
|
-
this.loadCaptcha();
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
hide() {
|
|
400
|
-
this.state.isVisible = false;
|
|
401
|
-
this.elements.overlay.classList.remove('show');
|
|
402
|
-
this.elements.modal.classList.remove('show');
|
|
403
|
-
|
|
404
|
-
this.safeSetTimeout(() => {
|
|
405
|
-
this.elements.overlay.style.display = 'none';
|
|
406
|
-
document.body.removeChild(this.elements.overlay);
|
|
407
|
-
this.reset();
|
|
408
|
-
this.options.onClose?.();
|
|
409
|
-
this.elements.overlay = null;
|
|
410
|
-
}, 300);
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
// 优化:添加统一错误处理方法
|
|
414
|
-
handleError(errorType, message, originalError = null) {
|
|
415
|
-
const errorMessages = {
|
|
416
|
-
[PopupSliderCaptcha.ERROR_TYPES.NETWORK_ERROR]: '网络连接失败,请检查网络设置',
|
|
417
|
-
[PopupSliderCaptcha.ERROR_TYPES.TIMEOUT_ERROR]: '请求超时,请重试',
|
|
418
|
-
[PopupSliderCaptcha.ERROR_TYPES.VALIDATION_ERROR]: '验证失败,请重试',
|
|
419
|
-
[PopupSliderCaptcha.ERROR_TYPES.IMAGE_LOAD_ERROR]: '图片加载失败,请刷新重试',
|
|
420
|
-
[PopupSliderCaptcha.ERROR_TYPES.CAPTCHA_DATA_ERROR]: '验证码数据错误,请刷新重试',
|
|
421
|
-
};
|
|
422
|
-
|
|
423
|
-
const errorMessage = errorMessages[errorType] || message || '未知错误';
|
|
424
|
-
|
|
425
|
-
// 调用用户自定义错误处理
|
|
426
|
-
if (this.options.onError) {
|
|
427
|
-
this.options.onError({
|
|
428
|
-
type: errorType,
|
|
429
|
-
message: errorMessage,
|
|
430
|
-
originalError,
|
|
431
|
-
});
|
|
432
|
-
}
|
|
433
|
-
|
|
434
|
-
this.showError(errorMessage);
|
|
435
|
-
console.error(`滑块验证码错误 [${errorType}]:`, errorMessage, originalError);
|
|
436
|
-
}
|
|
437
|
-
|
|
438
|
-
// 优化:简化加载逻辑,增强错误处理
|
|
439
|
-
async loadCaptcha() {
|
|
440
|
-
try {
|
|
441
|
-
this.showLoading();
|
|
442
|
-
this.startTime = Date.now();
|
|
443
|
-
|
|
444
|
-
// 取消之前的请求
|
|
445
|
-
if (this.abortController) {
|
|
446
|
-
this.abortController.abort();
|
|
447
|
-
}
|
|
448
|
-
this.abortController = new AbortController();
|
|
449
|
-
|
|
450
|
-
const response = await fetch(this.options.apiUrl, {
|
|
451
|
-
method: 'POST',
|
|
452
|
-
headers: {
|
|
453
|
-
'Content-Type': 'application/json',
|
|
454
|
-
...this.options.headers,
|
|
455
|
-
},
|
|
456
|
-
body: JSON.stringify({
|
|
457
|
-
timestamp: Date.now(),
|
|
458
|
-
...this.options.requestData,
|
|
459
|
-
}),
|
|
460
|
-
signal: this.abortController.signal,
|
|
461
|
-
});
|
|
462
|
-
|
|
463
|
-
if (!response.ok) {
|
|
464
|
-
throw new Error(`HTTP ${response.status}: ${response.statusText}`)
|
|
465
|
-
}
|
|
466
|
-
|
|
467
|
-
const data = await response.json();
|
|
468
|
-
|
|
469
|
-
// 优化:更严格的数据验证
|
|
470
|
-
if (!this.validateCaptchaData(data)) {
|
|
471
|
-
throw new Error('验证码数据格式错误')
|
|
472
|
-
}
|
|
473
|
-
|
|
474
|
-
this.captchaData = data.data;
|
|
475
|
-
this.showCaptcha();
|
|
476
|
-
await this.renderCaptcha();
|
|
477
|
-
} catch (error) {
|
|
478
|
-
if (error.name === 'AbortError') {
|
|
479
|
-
this.handleError(PopupSliderCaptcha.ERROR_TYPES.TIMEOUT_ERROR, '请求被取消');
|
|
480
|
-
} else if (
|
|
481
|
-
error.message.includes('Failed to fetch') ||
|
|
482
|
-
error.message.includes('NetworkError')
|
|
483
|
-
) {
|
|
484
|
-
this.handleError(PopupSliderCaptcha.ERROR_TYPES.NETWORK_ERROR, '网络连接失败');
|
|
485
|
-
} else {
|
|
486
|
-
this.handleError(PopupSliderCaptcha.ERROR_TYPES.CAPTCHA_DATA_ERROR, error.message, error);
|
|
487
|
-
}
|
|
488
|
-
}
|
|
489
|
-
}
|
|
490
|
-
|
|
491
|
-
// 优化:添加验证码数据验证方法
|
|
492
|
-
validateCaptchaData(data) {
|
|
493
|
-
if (!data || typeof data !== 'object') return false
|
|
494
|
-
|
|
495
|
-
const requiredFields = [
|
|
496
|
-
'canvasSrc',
|
|
497
|
-
'blockSrc',
|
|
498
|
-
'canvasWidth',
|
|
499
|
-
'canvasHeight',
|
|
500
|
-
'blockWidth',
|
|
501
|
-
'blockHeight',
|
|
502
|
-
'blockY',
|
|
503
|
-
'nonceStr',
|
|
504
|
-
];
|
|
505
|
-
const dataObj = data.data || data;
|
|
506
|
-
|
|
507
|
-
return requiredFields.every((field) => {
|
|
508
|
-
const value = dataObj[field];
|
|
509
|
-
return value !== null && value !== undefined && value !== ''
|
|
510
|
-
})
|
|
511
|
-
}
|
|
512
|
-
|
|
513
|
-
async renderCaptcha() {
|
|
514
|
-
return new Promise((resolve, reject) => {
|
|
515
|
-
let hasError = false;
|
|
516
|
-
|
|
517
|
-
// 优化:并行加载图片,提高性能
|
|
518
|
-
const loadPromises = [
|
|
519
|
-
this.loadImageAsync(this.elements.backgroundImg, this.captchaData.canvasSrc, {
|
|
520
|
-
width: this.captchaData.canvasWidth,
|
|
521
|
-
height: this.captchaData.canvasHeight,
|
|
522
|
-
}),
|
|
523
|
-
this.loadImageAsync(this.elements.sliderImg, this.captchaData.blockSrc, {
|
|
524
|
-
width: this.captchaData.blockWidth,
|
|
525
|
-
height: this.captchaData.blockHeight,
|
|
526
|
-
top: this.captchaData.blockY,
|
|
527
|
-
}),
|
|
528
|
-
];
|
|
529
|
-
|
|
530
|
-
Promise.all(loadPromises)
|
|
531
|
-
.then(() => {
|
|
532
|
-
if (!hasError) {
|
|
533
|
-
this.hideLoading();
|
|
534
|
-
resolve();
|
|
535
|
-
}
|
|
536
|
-
})
|
|
537
|
-
.catch((error) => {
|
|
538
|
-
if (!hasError) {
|
|
539
|
-
hasError = true;
|
|
540
|
-
this.handleError(PopupSliderCaptcha.ERROR_TYPES.IMAGE_LOAD_ERROR, '图片加载失败', error);
|
|
541
|
-
reject(error);
|
|
542
|
-
}
|
|
543
|
-
});
|
|
544
|
-
})
|
|
545
|
-
}
|
|
546
|
-
|
|
547
|
-
// 优化:添加异步图片加载方法
|
|
548
|
-
async loadImageAsync(imgElement, src, styles) {
|
|
549
|
-
return new Promise((resolve, reject) => {
|
|
550
|
-
// 检查缓存
|
|
551
|
-
if (this.imageCache.has(src)) {
|
|
552
|
-
const cachedImg = this.imageCache.get(src);
|
|
553
|
-
imgElement.src = cachedImg.src;
|
|
554
|
-
this.applyStyles(imgElement, styles);
|
|
555
|
-
resolve();
|
|
556
|
-
return
|
|
557
|
-
}
|
|
558
|
-
|
|
559
|
-
const timeoutId = this.safeSetTimeout(() => {
|
|
560
|
-
reject(new Error('图片加载超时'));
|
|
561
|
-
}, 10000); // 10秒超时
|
|
562
|
-
|
|
563
|
-
imgElement.onload = () => {
|
|
564
|
-
this.safeClearTimeout(timeoutId);
|
|
565
|
-
this.imageCache.set(src, imgElement.cloneNode());
|
|
566
|
-
resolve();
|
|
567
|
-
};
|
|
568
|
-
|
|
569
|
-
imgElement.onerror = (error) => {
|
|
570
|
-
this.safeClearTimeout(timeoutId);
|
|
571
|
-
reject(error);
|
|
572
|
-
};
|
|
573
|
-
|
|
574
|
-
imgElement.src = src;
|
|
575
|
-
this.applyStyles(imgElement, styles);
|
|
576
|
-
})
|
|
577
|
-
}
|
|
578
|
-
|
|
579
|
-
// 优化:提取样式应用逻辑
|
|
580
|
-
applyStyles(element, styles) {
|
|
581
|
-
Object.entries(styles).forEach(([key, value]) => {
|
|
582
|
-
element.style[key] = typeof value === 'number' ? value + 'px' : value;
|
|
583
|
-
});
|
|
584
|
-
}
|
|
585
|
-
|
|
586
|
-
// 优化:简化状态显示方法
|
|
587
|
-
showLoading() {
|
|
588
|
-
this.state.isLoading = true;
|
|
589
|
-
this.batchUpdateStyles({
|
|
590
|
-
container: { display: 'block' },
|
|
591
|
-
loadingText: { display: 'flex' },
|
|
592
|
-
error: { display: 'none' },
|
|
593
|
-
});
|
|
594
|
-
this.updateUIState('loading');
|
|
595
|
-
}
|
|
596
|
-
|
|
597
|
-
hideLoading() {
|
|
598
|
-
this.state.isLoading = false;
|
|
599
|
-
this.batchUpdateStyles({ loadingText: { display: 'none' } });
|
|
600
|
-
this.updateUIState('reset');
|
|
601
|
-
}
|
|
602
|
-
|
|
603
|
-
showCaptcha() {
|
|
604
|
-
this.batchUpdateStyles({
|
|
605
|
-
container: { display: 'block' },
|
|
606
|
-
track: { display: 'block' },
|
|
607
|
-
error: { display: 'none' },
|
|
608
|
-
});
|
|
609
|
-
}
|
|
610
|
-
|
|
611
|
-
showError(message) {
|
|
612
|
-
this.hideLoading();
|
|
613
|
-
this.batchUpdateStyles({
|
|
614
|
-
error: { display: 'block', textContent: message },
|
|
615
|
-
});
|
|
616
|
-
}
|
|
617
|
-
|
|
618
|
-
// 优化:批量样式更新
|
|
619
|
-
batchUpdateStyles(updates) {
|
|
620
|
-
requestAnimationFrame(() => {
|
|
621
|
-
Object.entries(updates).forEach(([elementKey, styles]) => {
|
|
622
|
-
const element = this.elements[elementKey];
|
|
623
|
-
if (element) {
|
|
624
|
-
Object.entries(styles).forEach(([prop, value]) => {
|
|
625
|
-
if (prop === 'textContent') {
|
|
626
|
-
element.textContent = value;
|
|
627
|
-
} else {
|
|
628
|
-
element.style[prop] = value;
|
|
629
|
-
}
|
|
630
|
-
});
|
|
631
|
-
}
|
|
632
|
-
});
|
|
633
|
-
});
|
|
634
|
-
}
|
|
635
|
-
|
|
636
|
-
async verify() {
|
|
637
|
-
if (!this.captchaData) {
|
|
638
|
-
this.onVerifyFail('验证码数据丢失');
|
|
639
|
-
return
|
|
640
|
-
}
|
|
641
|
-
|
|
642
|
-
try {
|
|
643
|
-
// 取消之前的验证请求
|
|
644
|
-
if (this.abortController) {
|
|
645
|
-
this.abortController.abort();
|
|
646
|
-
}
|
|
647
|
-
this.abortController = new AbortController();
|
|
648
|
-
|
|
649
|
-
const response = await fetch(this.options.verifyUrl, {
|
|
650
|
-
method: 'POST',
|
|
651
|
-
headers: {
|
|
652
|
-
'Content-Type': 'application/json',
|
|
653
|
-
...this.options.headers,
|
|
654
|
-
},
|
|
655
|
-
body: JSON.stringify({
|
|
656
|
-
loginVo: {
|
|
657
|
-
nonceStr: this.captchaData.nonceStr,
|
|
658
|
-
value: this.getPosition(),
|
|
659
|
-
},
|
|
660
|
-
dragEventList: [...this.times],
|
|
661
|
-
...this.options.verifyData,
|
|
662
|
-
}),
|
|
663
|
-
signal: this.abortController.signal,
|
|
664
|
-
});
|
|
665
|
-
|
|
666
|
-
if (!response.ok) {
|
|
667
|
-
throw new Error(`HTTP ${response.status}: ${response.statusText}`)
|
|
668
|
-
}
|
|
669
|
-
|
|
670
|
-
const data = await response.json();
|
|
671
|
-
|
|
672
|
-
// 优化:更灵活的验证结果判断
|
|
673
|
-
if (this.isVerifySuccess(data)) {
|
|
674
|
-
this.onVerifySuccess(data.data || data.result);
|
|
675
|
-
} else {
|
|
676
|
-
this.onVerifyFail(data.message || data.msg || '验证失败,请重试!');
|
|
677
|
-
}
|
|
678
|
-
} catch (error) {
|
|
679
|
-
if (error.name === 'AbortError') {
|
|
680
|
-
this.handleError(PopupSliderCaptcha.ERROR_TYPES.TIMEOUT_ERROR, '验证请求被取消');
|
|
681
|
-
} else if (
|
|
682
|
-
error.message.includes('Failed to fetch') ||
|
|
683
|
-
error.message.includes('NetworkError')
|
|
684
|
-
) {
|
|
685
|
-
this.handleError(PopupSliderCaptcha.ERROR_TYPES.NETWORK_ERROR, '网络连接失败');
|
|
686
|
-
} else {
|
|
687
|
-
this.handleError(PopupSliderCaptcha.ERROR_TYPES.VALIDATION_ERROR, error.message, error);
|
|
688
|
-
}
|
|
689
|
-
}
|
|
690
|
-
}
|
|
691
|
-
|
|
692
|
-
// 优化:添加验证成功判断方法
|
|
693
|
-
isVerifySuccess(data) {
|
|
694
|
-
if (!data || typeof data !== 'object') return false
|
|
695
|
-
|
|
696
|
-
// 支持多种成功标识
|
|
697
|
-
const successIndicators = [
|
|
698
|
-
data.code === '0',
|
|
699
|
-
data.code === 0,
|
|
700
|
-
data.success === true,
|
|
701
|
-
data.status === 'success',
|
|
702
|
-
data.result === true,
|
|
703
|
-
];
|
|
704
|
-
|
|
705
|
-
return successIndicators.some((indicator) => indicator === true)
|
|
706
|
-
}
|
|
707
|
-
|
|
708
|
-
onVerifySuccess(ticket) {
|
|
709
|
-
const duration = this.dragStartTime
|
|
710
|
-
? Date.now() - this.dragStartTime
|
|
711
|
-
: Date.now() - this.startTime;
|
|
712
|
-
const durationText = `验证成功!耗时:${(duration / 1000).toFixed(2)}s`;
|
|
713
|
-
|
|
714
|
-
this.updateUIState('success');
|
|
715
|
-
this.showFloatingTime(durationText, 'success');
|
|
716
|
-
|
|
717
|
-
this.safeSetTimeout(() => {
|
|
718
|
-
this.options.onSuccess?.({
|
|
719
|
-
ticket: ticket,
|
|
720
|
-
timestamp: Date.now(),
|
|
721
|
-
duration,
|
|
722
|
-
});
|
|
723
|
-
this.hide();
|
|
724
|
-
}, 2000);
|
|
725
|
-
}
|
|
726
|
-
|
|
727
|
-
showFloatingTime(text, type = 'success') {
|
|
728
|
-
const { elements } = this;
|
|
729
|
-
elements.floatingTime.textContent = text;
|
|
730
|
-
elements.floatingTime.className = `slider-captcha-floating-time ${type}`;
|
|
731
|
-
|
|
732
|
-
this.safeSetTimeout(() => elements.floatingTime.classList.add('show'), 100);
|
|
733
|
-
this.safeSetTimeout(() => {
|
|
734
|
-
elements.floatingTime.className = 'slider-captcha-floating-time';
|
|
735
|
-
}, 2500); // 优化:延长显示时间,避免被reset清除
|
|
736
|
-
}
|
|
737
|
-
|
|
738
|
-
onVerifyFail(message) {
|
|
739
|
-
this.state.retryCount++;
|
|
740
|
-
this.updateUIState('fail');
|
|
741
|
-
this.showFloatingTime(message, 'fail');
|
|
742
|
-
|
|
743
|
-
this.safeSetTimeout(() => {
|
|
744
|
-
if (this.state.retryCount >= this.options.maxRetries) {
|
|
745
|
-
this.refresh();
|
|
746
|
-
} else {
|
|
747
|
-
this.reset();
|
|
748
|
-
}
|
|
749
|
-
}, 2500); // 优化:延长等待时间,确保浮动提示完整显示
|
|
750
|
-
}
|
|
751
|
-
|
|
752
|
-
reset() {
|
|
753
|
-
this.clearAllTimers();
|
|
754
|
-
|
|
755
|
-
// 重置状态
|
|
756
|
-
Object.assign(this.state, {
|
|
757
|
-
isDragging: false,
|
|
758
|
-
currentX: 0,
|
|
759
|
-
startX: 0,
|
|
760
|
-
isLoading: false,
|
|
761
|
-
});
|
|
762
|
-
|
|
763
|
-
this.times = [];
|
|
764
|
-
this.startTime = null;
|
|
765
|
-
this.dragStartTime = null; // 优化:重置拖拽开始时间
|
|
766
|
-
this.cachedDimensions = null;
|
|
767
|
-
|
|
768
|
-
// 重置UI
|
|
769
|
-
requestAnimationFrame(() => {
|
|
770
|
-
this.setTransition(true);
|
|
771
|
-
this.elements.btn.style.transform = 'translateX(0px)';
|
|
772
|
-
this.elements.sliderImg.style.transform = 'translateX(0px)';
|
|
773
|
-
this.updateUIState('reset');
|
|
774
|
-
this.elements.error.style.display = 'none';
|
|
775
|
-
});
|
|
776
|
-
}
|
|
777
|
-
|
|
778
|
-
refresh() {
|
|
779
|
-
this.reset();
|
|
780
|
-
this.state.retryCount = 0;
|
|
781
|
-
this.loadCaptcha();
|
|
782
|
-
}
|
|
783
|
-
|
|
784
|
-
// 安全的定时器管理
|
|
785
|
-
safeSetTimeout(callback, delay) {
|
|
786
|
-
const timerId = setTimeout(() => {
|
|
787
|
-
this.timers.delete(timerId);
|
|
788
|
-
callback();
|
|
789
|
-
}, delay);
|
|
790
|
-
this.timers.add(timerId);
|
|
791
|
-
return timerId
|
|
792
|
-
}
|
|
793
|
-
|
|
794
|
-
safeClearTimeout(timerId) {
|
|
795
|
-
if (timerId) {
|
|
796
|
-
clearTimeout(timerId);
|
|
797
|
-
this.timers.delete(timerId);
|
|
798
|
-
}
|
|
799
|
-
}
|
|
800
|
-
|
|
801
|
-
clearAllTimers() {
|
|
802
|
-
this.timers.forEach((timer) => {
|
|
803
|
-
clearTimeout(timer);
|
|
804
|
-
clearInterval(timer);
|
|
805
|
-
});
|
|
806
|
-
this.timers.clear();
|
|
807
|
-
|
|
808
|
-
if (this.rafId) {
|
|
809
|
-
cancelAnimationFrame(this.rafId);
|
|
810
|
-
this.rafId = null;
|
|
811
|
-
}
|
|
812
|
-
}
|
|
813
|
-
|
|
814
|
-
// 清理图片资源
|
|
815
|
-
cleanupImages() {
|
|
816
|
-
if (this.elements.backgroundImg) {
|
|
817
|
-
this.elements.backgroundImg.src = '';
|
|
818
|
-
this.elements.backgroundImg.onload = null;
|
|
819
|
-
this.elements.backgroundImg.onerror = null;
|
|
820
|
-
}
|
|
821
|
-
if (this.elements.sliderImg) {
|
|
822
|
-
this.elements.sliderImg.src = '';
|
|
823
|
-
this.elements.sliderImg.onload = null;
|
|
824
|
-
this.elements.sliderImg.onerror = null;
|
|
825
|
-
}
|
|
826
|
-
this.imageCache.clear();
|
|
827
|
-
}
|
|
828
|
-
|
|
829
|
-
// 工具函数:节流
|
|
830
|
-
throttle(func, delay) {
|
|
831
|
-
let lastCall = 0;
|
|
832
|
-
return function (...args) {
|
|
833
|
-
const now = Date.now();
|
|
834
|
-
if (now - lastCall >= delay) {
|
|
835
|
-
lastCall = now;
|
|
836
|
-
return func.apply(this, args)
|
|
837
|
-
}
|
|
838
|
-
}
|
|
839
|
-
}
|
|
840
|
-
|
|
841
|
-
destroy() {
|
|
842
|
-
try {
|
|
843
|
-
// 取消所有进行中的请求
|
|
844
|
-
if (this.abortController) {
|
|
845
|
-
this.abortController.abort();
|
|
846
|
-
this.abortController = null;
|
|
847
|
-
}
|
|
848
|
-
|
|
849
|
-
// 恢复body样式
|
|
850
|
-
if (document.body) {
|
|
851
|
-
document.body.style.userSelect = '';
|
|
852
|
-
document.body.style.cursor = '';
|
|
853
|
-
}
|
|
854
|
-
|
|
855
|
-
// 清理所有定时器
|
|
856
|
-
this.clearAllTimers();
|
|
857
|
-
|
|
858
|
-
// 移除所有事件监听器
|
|
859
|
-
this.removeAllEventListeners();
|
|
860
|
-
|
|
861
|
-
// 清理图片资源
|
|
862
|
-
this.cleanupImages();
|
|
863
|
-
|
|
864
|
-
// 移除DOM元素
|
|
865
|
-
if (this.elements?.overlay?.parentNode) {
|
|
866
|
-
this.elements.overlay.parentNode.removeChild(this.elements.overlay);
|
|
867
|
-
}
|
|
868
|
-
|
|
869
|
-
// 清理样式表
|
|
870
|
-
const styleElement = document.getElementById('slider-captcha-styles');
|
|
871
|
-
if (styleElement) {
|
|
872
|
-
styleElement.remove();
|
|
873
|
-
}
|
|
874
|
-
|
|
875
|
-
// 清空缓存
|
|
876
|
-
this.imageCache.clear();
|
|
877
|
-
this.cachedDimensions = null;
|
|
878
|
-
|
|
879
|
-
// 清空所有属性
|
|
880
|
-
Object.keys(this).forEach((key) => {
|
|
881
|
-
if (key !== 'constructor') {
|
|
882
|
-
this[key] = null;
|
|
883
|
-
}
|
|
884
|
-
});
|
|
885
|
-
|
|
886
|
-
// 调用销毁回调
|
|
887
|
-
if (this.options.onDestroy) {
|
|
888
|
-
this.options.onDestroy();
|
|
889
|
-
}
|
|
890
|
-
} catch (error) {
|
|
891
|
-
console.error('销毁滑块验证码时出错:', error);
|
|
892
|
-
}
|
|
893
|
-
}
|
|
894
|
-
|
|
895
|
-
static create(options) {
|
|
896
|
-
return new PopupSliderCaptcha(options)
|
|
897
|
-
}
|
|
898
|
-
|
|
899
|
-
static show(options) {
|
|
900
|
-
const instance = new PopupSliderCaptcha(options);
|
|
901
|
-
instance.show();
|
|
902
|
-
return instance
|
|
903
|
-
}
|
|
904
|
-
}
|
|
905
|
-
|
|
906
|
-
// 模块导出
|
|
907
|
-
if (typeof module !== 'undefined' && module.exports) {
|
|
908
|
-
module.exports = PopupSliderCaptcha;
|
|
909
|
-
module.exports.default = PopupSliderCaptcha;
|
|
910
|
-
} else if (typeof define === 'function' && define.amd) {
|
|
911
|
-
define([], () => PopupSliderCaptcha);
|
|
912
|
-
} else if (typeof window !== 'undefined') {
|
|
913
|
-
window.PopupSliderCaptcha = PopupSliderCaptcha;
|
|
914
|
-
window.SliderCaptcha = PopupSliderCaptcha;
|
|
915
|
-
}
|
|
916
|
-
|
|
917
|
-
export { PopupSliderCaptcha as default };
|
|
1
|
+
class PopupSliderCaptcha{static DEFAULTS={width:320,height:155,sliderSize:38,maxRetries:3,timeout:3e4,apiUrl:"/externalapi/commonservice/captcha/get",verifyUrl:"/externalapi/commonservice/captcha/check",baseUrl:"",throttleDelay:16,clickMaskClose:!1};static CSS_CLASSES={overlay:"slider-captcha-overlay",modal:"slider-captcha-modal",header:"slider-captcha-header",container:"slider-captcha-container",track:"slider-captcha-track",btn:"slider-captcha-btn",hint:"slider-captcha-hint",loading:"slider-captcha-loading",error:"slider-captcha-error"};static getStyles(){return":root{--sc-primary:#409eff;--sc-success:#67c23a;--sc-danger:#f56c6c;--sc-border:#e4e7eb;--sc-bg:linear-gradient(90deg, #f7f9fa 0%, #e8f4fd 100%);--sc-text:#333;--sc-text-light:#999;--sc-shadow:0 4px 20px rgba(0,0,0,.3);--sc-radius:8px;--sc-transition:.3s ease}.slider-captcha-overlay{position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,.5);z-index:9999;display:none;justify-content:center;align-items:center;opacity:0;transition:opacity var(--sc-transition)}.slider-captcha-overlay.show{opacity:1}.slider-captcha-modal{background:#fff;border-radius:var(--sc-radius);padding:20px;box-shadow:var(--sc-shadow);position:relative;max-width:90vw;max-height:90vh;transform:scale(.8) translateY(-20px);opacity:0;transition:all var(--sc-transition)}.slider-captcha-modal.show{transform:scale(1) translateY(0);opacity:1}.slider-captcha-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:15px;padding-bottom:10px;border-bottom:1px solid var(--sc-border)}.slider-captcha-container{display:flex;align-items:center;position:relative;border-radius:4px;overflow:hidden;margin-bottom:15px;background:#837a7a;justify-content:center}.slider-captcha-track{width:100%;height:40px;line-height:40px;background:var(--sc-bg);border:1px solid var(--sc-border);border-radius:20px;position:relative;margin-bottom:15px;overflow:hidden}.slider-captcha-btn{width:38px;height:38px;background:#fff;border:1px solid #ccc;border-radius:50%;position:absolute;top:0;left:0;cursor:pointer;display:flex;align-items:center;justify-content:center;box-shadow:0 2px 4px rgba(0,0,0,.1);transition:all var(--sc-transition);user-select:none;z-index:1}.slider-captcha-loading{position:absolute;top:0;left:0;width:100%;height:100%;background:rgba(255,255,255,.6);display:flex;align-items:center;justify-content:center;flex-direction:column;color:#666;font-size:14px;z-index:10;border-radius:4px}.slider-captcha-error{color:var(--sc-danger);font-size:12px;text-align:center;margin-top:10px;display:none}.slider-captcha-title{margin:0;font-size:16px;color:var(--sc-text)}.slider-captcha-close,.slider-captcha-refresh{background:none;border:none;cursor:pointer;color:var(--sc-text-light);padding:0;width:30px;height:30px;display:flex;align-items:center;justify-content:center;border-radius:50%;transition:all var(--sc-transition);position:relative;font-size:0}.slider-captcha-close::before,.slider-captcha-close::after{content:'';position:absolute;width:16px;height:2px;background-color:var(--sc-text-light);border-radius:1px;transition:all var(--sc-transition)}.slider-captcha-close::before{transform:rotate(45deg)}.slider-captcha-close::after{transform:rotate(-45deg)}.slider-captcha-close:hover{background:#f5f5f5;transform:scale(1.1)}.slider-captcha-close:hover::before,.slider-captcha-close:hover::after{background-color:var(--sc-danger)}.slider-captcha-refresh{margin-left:10px}.slider-captcha-refresh svg{width:20px;height:20px;fill:var(--sc-text-light);transition:all var(--sc-transition)}.slider-captcha-refresh:hover{background:#f5f5f5;transform:scale(1.1)}.slider-captcha-refresh:hover svg{fill:var(--sc-primary);transform:rotate(180deg)}.slider-captcha-floating-time{position:absolute;bottom:-40px;left:50%;transform:translateX(-50%);color:#fff;font-size:12px;white-space:nowrap;opacity:0;pointer-events:none;z-index:10;transition:all var(--sc-transition);background:#fff;padding:2px 15px;border-radius:10px}.slider-captcha-floating-time.show{opacity:1;transform:translateX(-50%) translateY(-45px)}.slider-captcha-floating-time.success{color:var(--sc-success)}.slider-captcha-floating-time.fail{color:var(--sc-danger)}.slider-captcha-bg{width:100%;height:100%;object-fit:cover;display:block}.slider-captcha-piece{position:absolute;top:0;left:0;cursor:pointer;transition:none;z-index:2}.slider-captcha-finger{position:absolute;top:50%;left:10px;transform:translateY(-50%);font-size:20px;animation:fingerSlide 2s ease-in-out infinite;pointer-events:none;z-index:1;opacity:.6}.slider-captcha-hint{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);color:var(--sc-text-light);font-size:14px;pointer-events:none;z-index:1;transition:all var(--sc-transition)}.slider-captcha-header-buttons{display:flex;align-items:center}@keyframes fingerSlide{0%{left:10px;opacity:.6}50%{opacity:1}100%{left:calc(50% - 10px);opacity:.6}}"}static ERROR_TYPES={NETWORK_ERROR:"NETWORK_ERROR",TIMEOUT_ERROR:"TIMEOUT_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",IMAGE_LOAD_ERROR:"IMAGE_LOAD_ERROR",CAPTCHA_DATA_ERROR:"CAPTCHA_DATA_ERROR"};constructor(t={}){this.options={...PopupSliderCaptcha.DEFAULTS,...t},this.options.apiUrl=this.normalizeUrl(this.options.apiUrl,this.options.baseUrl),this.options.verifyUrl=this.normalizeUrl(this.options.verifyUrl,this.options.baseUrl);const{elements:e={},state:i=this.createInitialState(),captchaData:s=null,times:a=[],startTime:r=null,eventListeners:n=[],timers:o=new Set,rafId:c=null,cachedDimensions:h=null,imageCache:l=new Map,abortController:d=null}=this;Object.assign(this,{elements:e,state:i,captchaData:s,times:a,startTime:r,eventListeners:n,timers:o,rafId:c,cachedDimensions:h,imageCache:l,abortController:d}),this.throttledHandleMove=this.throttle(t=>this.handleMove(t),this.options.throttleDelay);try{this.init()}catch(t){this.handleError(PopupSliderCaptcha.ERROR_TYPES.VALIDATION_ERROR,t.message)}}createInitialState(){return{isVisible:!1,isDragging:!1,currentX:0,startX:0,retryCount:0,isLoading:!1}}normalizeUrl(t,e){return t?/^https?:\/\//.test(t)||!e?t:(e.endsWith("/")?e:e+"/")+(t.startsWith("/")?t.substring(1):t):t}init(){this.injectStyles(),this.createElements(),this.bindEvents()}injectStyles(){if(document.querySelector("#slider-captcha-styles"))return;const t=Object.assign(document.createElement("style"),{id:"slider-captcha-styles",textContent:PopupSliderCaptcha.getStyles()});document.head.appendChild(t)}createElements(){const{elements:t,options:e}=this,i={overlay:["div",PopupSliderCaptcha.CSS_CLASSES.overlay],modal:["div",PopupSliderCaptcha.CSS_CLASSES.modal],header:["div",PopupSliderCaptcha.CSS_CLASSES.header],title:["h3","slider-captcha-title","安全验证"],closeBtn:["button","slider-captcha-close"],refreshBtn:["button","slider-captcha-refresh"],container:["div",PopupSliderCaptcha.CSS_CLASSES.container],backgroundImg:["img","slider-captcha-bg"],sliderImg:["img","slider-captcha-piece"],loadingText:["div",PopupSliderCaptcha.CSS_CLASSES.loading,"加载中..."],floatingTime:["div","slider-captcha-floating-time"],track:["div",PopupSliderCaptcha.CSS_CLASSES.track],fingerAnimation:["div","slider-captcha-finger","👉"],btn:["div",PopupSliderCaptcha.CSS_CLASSES.btn],icon:["div","","→"],hint:["div",PopupSliderCaptcha.CSS_CLASSES.hint,"向右滑动完成验证"],error:["div",PopupSliderCaptcha.CSS_CLASSES.error]};Object.entries(i).forEach(([e,[i,s,a]])=>{t[e]=this.createElement(i,s,a)}),t.container.style.cssText=`width:${e.width}px;height:${e.height}px`,t.refreshBtn.innerHTML='\n <svg viewBox="0 0 24 24">\n <path d="M17.65,6.35C16.2,4.9 14.21,4 12,4A8,8 0 0,0 4,12A8,8 0 0,0 12,20C15.73,20 18.84,17.45 19.73,14H17.65C16.83,16.33 14.61,18 12,18A6,6 0 0,1 6,12A6,6 0 0,1 12,6C13.66,6 15.14,6.69 16.22,7.78L13,11H20V4L17.65,6.35Z"/>\n </svg>\n ',this.assembleDOM(),this.setInitialState()}createElement(t,e="",i=""){return Object.assign(document.createElement(t),{className:e,textContent:i})}assembleDOM(){const{elements:t}=this,e=this.createElement("div","slider-captcha-header-buttons");e.append(t.refreshBtn,t.closeBtn),t.header.append(t.title,e),t.container.append(t.backgroundImg,t.sliderImg,t.loadingText,t.floatingTime),t.btn.appendChild(t.icon),t.track.append(t.fingerAnimation,t.btn,t.hint),t.modal.append(t.header,t.container,t.track,t.error),t.overlay.appendChild(t.modal),document.body.appendChild(t.overlay)}setInitialState(){Object.assign(this.elements.container.style,{display:"none"}),Object.assign(this.elements.track.style,{display:"none"})}bindEvents(){const{elements:t}=this;[[t.closeBtn,"click",()=>this.hide()],[t.refreshBtn,"click",()=>this.refresh()],[t.overlay,"click",e=>{e.target===t.overlay&&this.options.clickMaskClose&&this.hide()}],[document,"keydown",t=>{"Escape"===t.key&&this.state.isVisible&&this.hide()}],[document,"visibilitychange",()=>this.handleVisibilityChange()]].forEach(([t,e,i])=>{this.addEventListener(t,e,i)}),this.bindSliderEvents()}bindSliderEvents(){const{elements:t}=this,e={start:t=>this.handleStart(t),move:this.throttledHandleMove,end:()=>this.handleEnd()};[[t.btn,"mousedown",e.start],[t.btn,"touchstart",e.start],[t.sliderImg,"mousedown",e.start],[t.sliderImg,"touchstart",e.start],[document,"mousemove",e.move,{passive:!1}],[document,"touchmove",e.move,{passive:!1}],[document,"mouseup",e.end],[document,"touchend",e.end]].forEach(([t,e,i,s])=>{this.addEventListener(t,e,i,s)})}addEventListener(t,e,i,s={}){t&&"function"==typeof i&&(t.addEventListener(e,i,s),this.eventListeners.push({element:t,event:e,handler:i,options:s}))}removeAllEventListeners(){this.eventListeners.forEach(({element:t,event:e,handler:i,options:s})=>{try{t?.removeEventListener?.(e,i,s)}catch(t){}}),this.eventListeners.length=0}getDimensions(){if(!this.cachedDimensions){const{track:t,btn:e}=this.elements;this.cachedDimensions={trackWidth:t.offsetWidth,btnWidth:e.offsetWidth,get maxX(){return this.trackWidth-this.btnWidth}}}return this.cachedDimensions}getPosition(){const{maxX:t}=this.getDimensions(),e=this.state.currentX/t;return Math.round(e*(this.options.width-this.options.sliderSize))}handleStart(t){!this.captchaData||this.state.isDragging||this.state.isLoading||(t.preventDefault(),Object.assign(this.state,{isDragging:!0,startX:this.getClientX(t)-this.state.currentX}),this.dragStartTime=Date.now(),this.times=[{time:Date.now(),position:this.getPosition()}],this.setTransition(!1),this.updateUIState("dragging"),this.cachedDimensions=null)}handleMove(t){if(!this.state.isDragging)return;t.preventDefault();const e=this.getClientX(t)-this.state.startX,{maxX:i}=this.getDimensions();this.state.currentX=Math.max(0,Math.min(e,i)),this.times.push({time:Date.now(),position:this.getPosition()}),this.rafId&&cancelAnimationFrame(this.rafId),this.rafId=requestAnimationFrame(()=>this.updateSliderPosition())}handleEnd(){this.state.isDragging&&(this.times.push({time:Date.now(),position:this.getPosition()}),this.state.isDragging=!1,this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null),this.verify())}handleVisibilityChange(){const t=document.hidden?"paused":"running";this.elements.fingerAnimation?.style&&(this.elements.fingerAnimation.style.animationPlayState=t)}getClientX=t=>t.type.includes("touch")?t.touches[0].clientX:t.clientX;setTransition(t){const e=t?"all 0.3s ease":"none";requestAnimationFrame(()=>{const{btn:t,sliderImg:i}=this.elements;t.style.transition=i.style.transition=e})}updateUIState(t){const{elements:e}=this,i={dragging:()=>{e.hint.style.opacity="0",e.fingerAnimation.style.display="none"},success:()=>{Object.assign(e.btn.style,{background:"var(--sc-success)"}),Object.assign(e.icon.style,{color:"white"}),e.icon.textContent="✓"},fail:()=>{Object.assign(e.btn.style,{background:"var(--sc-danger)"}),Object.assign(e.icon.style,{color:"white"}),e.icon.textContent="✗"},reset:()=>{Object.assign(e.btn.style,{background:"white"}),Object.assign(e.icon.style,{color:"#666"}),e.icon.textContent="→",e.fingerAnimation.style.display="block",this.updateHintText("向右滑动完成验证","var(--sc-text-light)")},loading:()=>{e.hint.style.opacity="0",e.fingerAnimation.style.display="none",Object.assign(e.track.style,{pointerEvents:"none",opacity:"0.6"})}};i[t]&&requestAnimationFrame(()=>{i[t](),"loading"!==t&&Object.assign(e.track.style,{pointerEvents:"auto",opacity:"1"})})}updateHintText(t,e){requestAnimationFrame(()=>{Object.assign(this.elements.hint,{textContent:t}),Object.assign(this.elements.hint.style,{color:e,opacity:"1"})})}updateSliderPosition(){const{elements:t,options:e,state:i}=this,{maxX:s}=this.getDimensions(),a=i.currentX/s*(e.width-e.sliderSize),r=i.currentX/s;requestAnimationFrame(()=>{t.btn.style.transform=`translateX(${i.currentX}px)`,t.sliderImg.style.transform=`translateX(${a}px)`,t.fingerAnimation.style.opacity=.8>r?"0.6":"0"})}show(){this.state.isVisible=!0,this.elements.overlay.style.display="flex",requestAnimationFrame(()=>{this.elements.overlay.classList.add("show"),this.elements.modal.classList.add("show")}),this.loadCaptcha()}hide(){this.state.isVisible=!1,this.elements.overlay.classList.remove("show"),this.elements.modal.classList.remove("show"),this.safeSetTimeout(()=>{this.elements.overlay.style.display="none",document.body.removeChild(this.elements.overlay),this.reset(),this.options.onClose?.(),this.elements.overlay=null},300)}handleError(t,e,i=null){const s={[PopupSliderCaptcha.ERROR_TYPES.NETWORK_ERROR]:"网络连接失败,请检查网络设置",[PopupSliderCaptcha.ERROR_TYPES.TIMEOUT_ERROR]:"请求超时,请重试",[PopupSliderCaptcha.ERROR_TYPES.VALIDATION_ERROR]:"验证失败,请重试",[PopupSliderCaptcha.ERROR_TYPES.IMAGE_LOAD_ERROR]:"图片加载失败,请刷新重试",[PopupSliderCaptcha.ERROR_TYPES.CAPTCHA_DATA_ERROR]:"验证码数据错误,请刷新重试"}[t]||e||"未知错误";this.options.onError&&this.options.onError({type:t,message:s,originalError:i}),this.showError(s)}async loadCaptcha(){try{this.showLoading(),this.startTime=Date.now(),this.abortController&&this.abortController.abort(),this.abortController=new AbortController;const t=await fetch(this.options.apiUrl,{method:"POST",headers:{"Content-Type":"application/json",...this.options.headers},body:JSON.stringify({timestamp:Date.now(),...this.options.requestData}),signal:this.abortController.signal});if(!t.ok)throw Error(`HTTP ${t.status}: ${t.statusText}`);const e=await t.json();if(!this.validateCaptchaData(e))throw Error("验证码数据格式错误");this.captchaData=e.data,this.showCaptcha(),await this.renderCaptcha()}catch(t){"AbortError"===t.name?this.handleError(PopupSliderCaptcha.ERROR_TYPES.TIMEOUT_ERROR,"请求被取消"):t.message.includes("Failed to fetch")||t.message.includes("NetworkError")?this.handleError(PopupSliderCaptcha.ERROR_TYPES.NETWORK_ERROR,"网络连接失败"):this.handleError(PopupSliderCaptcha.ERROR_TYPES.CAPTCHA_DATA_ERROR,t.message,t)}}validateCaptchaData(t){if(!t||"object"!=typeof t)return!1;const e=t.data||t;return["canvasSrc","blockSrc","canvasWidth","canvasHeight","blockWidth","blockHeight","blockY","nonceStr"].every(t=>{const i=e[t];return null!=i&&""!==i})}renderCaptcha(){return new Promise((t,e)=>{let i=!1;const s=[this.loadImageAsync(this.elements.backgroundImg,this.captchaData.canvasSrc,{width:this.captchaData.canvasWidth,height:this.captchaData.canvasHeight}),this.loadImageAsync(this.elements.sliderImg,this.captchaData.blockSrc,{width:this.captchaData.blockWidth,height:this.captchaData.blockHeight,top:this.captchaData.blockY})];Promise.all(s).then(()=>{i||(this.hideLoading(),t())}).catch(t=>{i||(i=!0,this.handleError(PopupSliderCaptcha.ERROR_TYPES.IMAGE_LOAD_ERROR,"图片加载失败",t),e(t))})})}loadImageAsync(t,e,i){return new Promise((s,a)=>{if(this.imageCache.has(e)){const a=this.imageCache.get(e);return t.src=a.src,this.applyStyles(t,i),void s()}const r=this.safeSetTimeout(()=>{a(Error("图片加载超时"))},1e4);t.onload=function(){this.safeClearTimeout(r),this.imageCache.set(e,t.cloneNode()),s()}.bind(this),t.onerror=function(t){this.safeClearTimeout(r),a(t)}.bind(this),t.src=e,this.applyStyles(t,i)})}applyStyles(t,e){Object.entries(e).forEach(([e,i])=>{t.style[e]="number"==typeof i?i+"px":i})}showLoading(){this.state.isLoading=!0,this.batchUpdateStyles({container:{display:"block"},loadingText:{display:"flex"},error:{display:"none"}}),this.updateUIState("loading")}hideLoading(){this.state.isLoading=!1,this.batchUpdateStyles({loadingText:{display:"none"}}),this.updateUIState("reset")}showCaptcha(){this.batchUpdateStyles({container:{display:"block"},track:{display:"block"},error:{display:"none"}})}showError(t){this.hideLoading(),this.batchUpdateStyles({error:{display:"block",textContent:t}})}batchUpdateStyles(t){requestAnimationFrame(()=>{Object.entries(t).forEach(([t,e])=>{const i=this.elements[t];i&&Object.entries(e).forEach(([t,e])=>{"textContent"===t?i.textContent=e:i.style[t]=e})})})}async verify(){if(this.captchaData)try{this.abortController&&this.abortController.abort(),this.abortController=new AbortController;const t=await fetch(this.options.verifyUrl,{method:"POST",headers:{"Content-Type":"application/json",...this.options.headers},body:JSON.stringify({loginVo:{nonceStr:this.captchaData.nonceStr,value:this.getPosition()},dragEventList:[...this.times],...this.options.verifyData}),signal:this.abortController.signal});if(!t.ok)throw Error(`HTTP ${t.status}: ${t.statusText}`);const e=await t.json();this.isVerifySuccess(e)?this.onVerifySuccess(e.data||e.result):this.onVerifyFail(e.message||e.msg||"验证失败,请重试!")}catch(t){"AbortError"===t.name?this.handleError(PopupSliderCaptcha.ERROR_TYPES.TIMEOUT_ERROR,"验证请求被取消"):t.message.includes("Failed to fetch")||t.message.includes("NetworkError")?this.handleError(PopupSliderCaptcha.ERROR_TYPES.NETWORK_ERROR,"网络连接失败"):this.handleError(PopupSliderCaptcha.ERROR_TYPES.VALIDATION_ERROR,t.message,t)}else this.onVerifyFail("验证码数据丢失")}isVerifySuccess(t){return!(!t||"object"!=typeof t)&&["0"===t.code,0===t.code,!0===t.success,"success"===t.status,!0===t.result].some(t=>!0===t)}onVerifySuccess(t){const e=this.dragStartTime?Date.now()-this.dragStartTime:Date.now()-this.startTime,i=`验证成功!耗时:${(e/1e3).toFixed(2)}s`;this.updateUIState("success"),this.showFloatingTime(i,"success"),this.safeSetTimeout(()=>{this.options.onSuccess?.({ticket:t,timestamp:Date.now(),duration:e}),this.hide()},2e3)}showFloatingTime(t,e="success"){const{elements:i}=this;i.floatingTime.textContent=t,i.floatingTime.className="slider-captcha-floating-time "+e,this.safeSetTimeout(()=>i.floatingTime.classList.add("show"),100),this.safeSetTimeout(()=>{i.floatingTime.className="slider-captcha-floating-time"},2500)}onVerifyFail(t){this.state.retryCount++,this.updateUIState("fail"),this.showFloatingTime(t,"fail"),this.safeSetTimeout(()=>{this.state.retryCount<this.options.maxRetries?this.reset():this.refresh()},2500)}reset(){this.clearAllTimers(),Object.assign(this.state,{isDragging:!1,currentX:0,startX:0,isLoading:!1}),this.times=[],this.startTime=null,this.dragStartTime=null,this.cachedDimensions=null,requestAnimationFrame(()=>{this.setTransition(!0),this.elements.btn.style.transform="translateX(0px)",this.elements.sliderImg.style.transform="translateX(0px)",this.updateUIState("reset"),this.elements.error.style.display="none"})}refresh(){try{this.reset(),this.state.retryCount=0,this.loadCaptcha()}catch(t){}}safeSetTimeout(t,e){const i=setTimeout(()=>{this.timers.delete(i),t()},e);return this.timers.add(i),i}safeClearTimeout(t){t&&(clearTimeout(t),this.timers.delete(t))}clearAllTimers(){this.timers.forEach(t=>{clearTimeout(t),clearInterval(t)}),this.timers.clear(),this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null)}cleanupImages(){this.elements.backgroundImg&&(this.elements.backgroundImg.src="",this.elements.backgroundImg.onload=null,this.elements.backgroundImg.onerror=null),this.elements.sliderImg&&(this.elements.sliderImg.src="",this.elements.sliderImg.onload=null,this.elements.sliderImg.onerror=null),this.imageCache.clear()}throttle(t,e){let i=0;return(...s)=>{const a=Date.now();if(a-i>=e)return i=a,t.apply(this,s)}}destroy(){try{this.abortController&&(this.abortController.abort(),this.abortController=null),document.body&&(document.body.style.userSelect="",document.body.style.cursor=""),this.clearAllTimers(),this.removeAllEventListeners(),this.cleanupImages(),this.elements?.overlay?.parentNode&&this.elements.overlay.parentNode.removeChild(this.elements.overlay);const t=document.getElementById("slider-captcha-styles");t&&t.remove(),this.imageCache.clear(),this.cachedDimensions=null,Object.keys(this).forEach(t=>{"constructor"!==t&&(this[t]=null)}),this.options.onDestroy&&this.options.onDestroy()}catch(t){}}static create(t){return new PopupSliderCaptcha(t)}static show(t){const e=new PopupSliderCaptcha(t);return e.show(),e}}"undefined"!=typeof module&&module.exports?(module.exports=PopupSliderCaptcha,module.exports.default=PopupSliderCaptcha):"function"==typeof define&&define.amd?define([],()=>PopupSliderCaptcha):"undefined"!=typeof window&&(window.PopupSliderCaptcha=PopupSliderCaptcha,window.SliderCaptcha=PopupSliderCaptcha);export{PopupSliderCaptcha as default};
|