slider-captcha-sdk 1.0.26 → 1.0.27

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