@adstage/web-sdk 2.3.7 → 2.4.1
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 +1 -1
- package/dist/index.cjs.js +1880 -2001
- package/dist/index.d.ts +2 -68
- package/dist/index.esm.js +1881 -1999
- package/dist/index.standalone.js +2206 -2396
- package/package.json +1 -1
- package/src/core/AdStage.ts +0 -9
- package/src/index.ts +0 -3
- package/src/managers/ads/advertisement-event-tracker.ts +8 -15
- package/src/managers/ads/carousel-slider-manager.ts +4 -35
- package/src/managers/ads/text-transition-manager.ts +1 -2
- package/src/managers/ads/viewable-event-tracker.ts +1 -5
- package/src/modules/ads/AdRenderer.ts +730 -0
- package/src/modules/ads/AdsModule.ts +27 -737
- package/src/renderers/base-renderer.ts +6 -10
package/dist/index.cjs.js
CHANGED
|
@@ -1,8 +1,5 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var jsxRuntime = require('react/jsx-runtime');
|
|
4
|
-
var react = require('react');
|
|
5
|
-
|
|
6
3
|
// 광고 타입 정의
|
|
7
4
|
var AdType;
|
|
8
5
|
(function (AdType) {
|
|
@@ -33,6 +30,86 @@ var DeviceType;
|
|
|
33
30
|
DeviceType["TABLET"] = "TABLET";
|
|
34
31
|
})(DeviceType || (DeviceType = {}));
|
|
35
32
|
|
|
33
|
+
/**
|
|
34
|
+
* VIEWABLE 이벤트 추적 및 중복 방지 관리 클래스
|
|
35
|
+
* - 메모리 기반 중복 확인
|
|
36
|
+
* - 세션 스토리지 기반 영구 추적
|
|
37
|
+
* - 자동 정리 기능
|
|
38
|
+
* - ViewabilityTracker와 함께 사용하여 중복 viewable 이벤트 방지
|
|
39
|
+
*/
|
|
40
|
+
class ViewableEventTracker {
|
|
41
|
+
/**
|
|
42
|
+
* 중복 viewable 이벤트 여부 확인
|
|
43
|
+
*/
|
|
44
|
+
static isDuplicateViewable(adId, slotId, debug = false) {
|
|
45
|
+
const key = `${adId}_${slotId}`;
|
|
46
|
+
const now = Date.now();
|
|
47
|
+
// 메모리 기반 중복 확인 (새로고침 시 초기화됨)
|
|
48
|
+
const lastViewable = ViewableEventTracker.viewableTracker.get(key);
|
|
49
|
+
if (lastViewable && (now - lastViewable) < ViewableEventTracker.VIEWABLE_COOLDOWN) {
|
|
50
|
+
if (debug) {
|
|
51
|
+
console.log(`Duplicate viewable blocked for ad ${adId} in slot ${slotId}. Cooldown: ${Math.round((ViewableEventTracker.VIEWABLE_COOLDOWN - (now - lastViewable)) / 1000)}s remaining`);
|
|
52
|
+
}
|
|
53
|
+
return true;
|
|
54
|
+
}
|
|
55
|
+
// 세션 스토리지 기반 중복 확인 (새로고침 시에도 유지)
|
|
56
|
+
const sessionKey = `adstage_viewable_${key}`;
|
|
57
|
+
const sessionViewable = sessionStorage.getItem(sessionKey);
|
|
58
|
+
if (sessionViewable) {
|
|
59
|
+
const sessionTime = parseInt(sessionViewable, 10);
|
|
60
|
+
if (!isNaN(sessionTime) && (now - sessionTime) < ViewableEventTracker.VIEWABLE_COOLDOWN) {
|
|
61
|
+
if (debug) {
|
|
62
|
+
console.log(`Session-based duplicate viewable blocked for ad ${adId} in slot ${slotId}. Cooldown: ${Math.round((ViewableEventTracker.VIEWABLE_COOLDOWN - (now - sessionTime)) / 1000)}s remaining`);
|
|
63
|
+
}
|
|
64
|
+
// 메모리에도 기록하여 이후 요청 최적화
|
|
65
|
+
ViewableEventTracker.viewableTracker.set(key, sessionTime);
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
// viewable 이벤트 시점 기록 (메모리 + 세션 스토리지)
|
|
70
|
+
ViewableEventTracker.viewableTracker.set(key, now);
|
|
71
|
+
sessionStorage.setItem(sessionKey, now.toString());
|
|
72
|
+
// 오래된 세션 스토리지 데이터 정리 (선택적)
|
|
73
|
+
ViewableEventTracker.cleanupOldViewables();
|
|
74
|
+
return false;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* 오래된 viewable 추적 데이터 정리
|
|
78
|
+
*/
|
|
79
|
+
static cleanupOldViewables() {
|
|
80
|
+
const now = Date.now();
|
|
81
|
+
const cleanupThreshold = ViewableEventTracker.VIEWABLE_COOLDOWN * 2; // 쿨다운의 2배 시간이 지난 데이터 정리
|
|
82
|
+
// 세션 스토리지 정리
|
|
83
|
+
for (let i = 0; i < sessionStorage.length; i++) {
|
|
84
|
+
const key = sessionStorage.key(i);
|
|
85
|
+
if (key && key.startsWith('adstage_viewable_')) {
|
|
86
|
+
const timestamp = sessionStorage.getItem(key);
|
|
87
|
+
if (timestamp) {
|
|
88
|
+
const time = parseInt(timestamp, 10);
|
|
89
|
+
if (!isNaN(time) && (now - time) > cleanupThreshold) {
|
|
90
|
+
sessionStorage.removeItem(key);
|
|
91
|
+
i--; // 인덱스 조정
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
// 메모리 정리
|
|
97
|
+
for (const [key, timestamp] of ViewableEventTracker.viewableTracker.entries()) {
|
|
98
|
+
if ((now - timestamp) > cleanupThreshold) {
|
|
99
|
+
ViewableEventTracker.viewableTracker.delete(key);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* 모든 추적 데이터 정리
|
|
105
|
+
*/
|
|
106
|
+
static clear() {
|
|
107
|
+
ViewableEventTracker.viewableTracker.clear();
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
ViewableEventTracker.viewableTracker = new Map();
|
|
111
|
+
ViewableEventTracker.VIEWABLE_COOLDOWN = 300000; // 5분 쿨다운
|
|
112
|
+
|
|
36
113
|
/**
|
|
37
114
|
* SSR 안전한 DOM API 래퍼 클래스
|
|
38
115
|
* 서버사이드 렌더링 환경에서 DOM API 접근 시 오류를 방지합니다.
|
|
@@ -320,454 +397,1053 @@ class DOMUtils {
|
|
|
320
397
|
}
|
|
321
398
|
|
|
322
399
|
/**
|
|
323
|
-
*
|
|
400
|
+
* 디바이스 정보 수집 클래스
|
|
401
|
+
* - 브라우저 환경 정보 수집
|
|
402
|
+
* - 디바이스 ID 생성 및 관리
|
|
403
|
+
* - 세션 ID 생성 및 관리
|
|
324
404
|
*/
|
|
325
|
-
class
|
|
326
|
-
constructor(trackEvent) {
|
|
327
|
-
this.trackEvent = trackEvent;
|
|
328
|
-
}
|
|
405
|
+
class DeviceInfoCollector {
|
|
329
406
|
/**
|
|
330
|
-
*
|
|
407
|
+
* 디바이스 ID 생성 및 반환 (SSR 안전)
|
|
331
408
|
*/
|
|
332
|
-
|
|
333
|
-
DOMUtils.
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
409
|
+
static generateDeviceId() {
|
|
410
|
+
if (!DOMUtils.isBrowser())
|
|
411
|
+
return 'ssr_device_' + Date.now();
|
|
412
|
+
const stored = localStorage.getItem('adstage_device_id');
|
|
413
|
+
if (stored)
|
|
414
|
+
return stored;
|
|
415
|
+
const deviceId = 'device_' + Math.random().toString(36).substr(2, 9) + '_' + Date.now();
|
|
416
|
+
localStorage.setItem('adstage_device_id', deviceId);
|
|
417
|
+
return deviceId;
|
|
339
418
|
}
|
|
340
419
|
/**
|
|
341
|
-
*
|
|
420
|
+
* 세션 ID 생성 및 반환 (SSR 안전)
|
|
342
421
|
*/
|
|
343
|
-
|
|
344
|
-
DOMUtils.
|
|
422
|
+
static generateSessionId() {
|
|
423
|
+
if (!DOMUtils.isBrowser())
|
|
424
|
+
return 'ssr_session_' + Date.now();
|
|
425
|
+
const stored = sessionStorage.getItem('adstage_session_id');
|
|
426
|
+
if (stored)
|
|
427
|
+
return stored;
|
|
428
|
+
const sessionId = 'session_' + Math.random().toString(36).substr(2, 9) + '_' + Date.now();
|
|
429
|
+
sessionStorage.setItem('adstage_session_id', sessionId);
|
|
430
|
+
return sessionId;
|
|
345
431
|
}
|
|
346
432
|
/**
|
|
347
|
-
*
|
|
433
|
+
* 모바일 디바이스 여부 확인
|
|
348
434
|
*/
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
return undefined;
|
|
352
|
-
if (typeof value === 'number') {
|
|
353
|
-
return value > 0 ? `${value}px` : undefined;
|
|
354
|
-
}
|
|
355
|
-
if (typeof value === 'string') {
|
|
356
|
-
const trimmed = value.trim();
|
|
357
|
-
if (!trimmed)
|
|
358
|
-
return undefined;
|
|
359
|
-
// 퍼센트 값 처리
|
|
360
|
-
if (trimmed.endsWith('%')) {
|
|
361
|
-
const percent = parseFloat(trimmed);
|
|
362
|
-
return !isNaN(percent) && percent > 0 ? trimmed : undefined;
|
|
363
|
-
}
|
|
364
|
-
// px 값 처리 (px 단위 포함/미포함 모두 지원)
|
|
365
|
-
const numValue = trimmed.endsWith('px')
|
|
366
|
-
? parseFloat(trimmed.slice(0, -2))
|
|
367
|
-
: parseFloat(trimmed);
|
|
368
|
-
return !isNaN(numValue) && numValue > 0 ? `${numValue}px` : undefined;
|
|
369
|
-
}
|
|
370
|
-
return undefined;
|
|
435
|
+
static isMobile() {
|
|
436
|
+
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
|
|
371
437
|
}
|
|
372
438
|
/**
|
|
373
|
-
*
|
|
439
|
+
* 플랫폼 타입 반환 (서버 enum에 맞춤)
|
|
374
440
|
*/
|
|
375
|
-
|
|
376
|
-
const
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
overflow: 'hidden',
|
|
380
|
-
};
|
|
381
|
-
// 사용자가 지정한 크기가 있을 때만 적용
|
|
382
|
-
const parsedWidth = this.parseSizeValue(slot.width);
|
|
383
|
-
const parsedHeight = this.parseSizeValue(slot.height);
|
|
384
|
-
if (parsedWidth) {
|
|
385
|
-
styles.width = parsedWidth;
|
|
386
|
-
}
|
|
387
|
-
if (parsedHeight) {
|
|
388
|
-
styles.height = parsedHeight;
|
|
441
|
+
static getPlatform() {
|
|
442
|
+
const userAgent = navigator.userAgent.toLowerCase();
|
|
443
|
+
if (/iphone|ipad|ipod/.test(userAgent)) {
|
|
444
|
+
return 'ios';
|
|
389
445
|
}
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
/**
|
|
393
|
-
* 이미지 스타일 (고유 사이즈 유지, 사용자 지정 크기 우선)
|
|
394
|
-
*/
|
|
395
|
-
getImageStyles(slot) {
|
|
396
|
-
const styles = {
|
|
397
|
-
display: 'block',
|
|
398
|
-
'object-position': 'center', // 🎯 이미지 항상 중앙 정렬
|
|
399
|
-
};
|
|
400
|
-
// 사용자가 컨테이너 크기를 지정했는지 확인
|
|
401
|
-
const parsedWidth = this.parseSizeValue(slot?.width);
|
|
402
|
-
const parsedHeight = this.parseSizeValue(slot?.height);
|
|
403
|
-
const hasUserDefinedSize = parsedWidth || parsedHeight;
|
|
404
|
-
if (hasUserDefinedSize) {
|
|
405
|
-
// 🎯 사용자가 크기를 지정한 경우: 컨테이너에 꽉 차도록 설정
|
|
406
|
-
styles.width = '100%';
|
|
407
|
-
styles.height = '100%';
|
|
408
|
-
styles['object-fit'] = 'cover'; // 컨테이너에 꽉 찬 상태로 비율 유지
|
|
409
|
-
styles['object-position'] = 'center';
|
|
446
|
+
if (/android/.test(userAgent)) {
|
|
447
|
+
return 'android';
|
|
410
448
|
}
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
styles['max-width'] = '100%';
|
|
414
|
-
styles.height = 'auto';
|
|
449
|
+
if (DeviceInfoCollector.isMobile()) {
|
|
450
|
+
return 'web'; // 모바일 웹
|
|
415
451
|
}
|
|
416
|
-
return
|
|
452
|
+
return 'desktop'; // 데스크톱 웹
|
|
417
453
|
}
|
|
418
454
|
/**
|
|
419
|
-
*
|
|
455
|
+
* 완전한 디바이스 정보 수집
|
|
420
456
|
*/
|
|
421
|
-
|
|
457
|
+
static collectDeviceInfo() {
|
|
458
|
+
const viewportInfo = DOMUtils.getViewportInfo();
|
|
422
459
|
return {
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
460
|
+
deviceId: DeviceInfoCollector.generateDeviceId(),
|
|
461
|
+
sessionId: DeviceInfoCollector.generateSessionId(),
|
|
462
|
+
osVersion: DOMUtils.isBrowser() ? navigator.platform : 'SSR',
|
|
463
|
+
deviceModel: DOMUtils.isBrowser() ? navigator.platform : 'SSR',
|
|
464
|
+
appVersion: '1.0.0',
|
|
465
|
+
sdkVersion: '1.0.0',
|
|
466
|
+
language: DOMUtils.isBrowser() ? (navigator.language || 'ko') : 'ko',
|
|
467
|
+
country: 'KR', // 기본값
|
|
468
|
+
ipAddress: '', // 서버에서 자동으로 설정됨
|
|
469
|
+
userAgent: DOMUtils.isBrowser() ? navigator.userAgent : 'SSR',
|
|
470
|
+
timezone: DOMUtils.isBrowser() ? Intl.DateTimeFormat().resolvedOptions().timeZone : 'UTC',
|
|
471
|
+
viewportWidth: viewportInfo.width,
|
|
472
|
+
viewportHeight: viewportInfo.height,
|
|
473
|
+
screenWidth: DOMUtils.isBrowser() ? screen.width : 0,
|
|
474
|
+
screenHeight: DOMUtils.isBrowser() ? screen.height : 0,
|
|
475
|
+
colorDepth: DOMUtils.isBrowser() ? screen.colorDepth : 24,
|
|
476
|
+
pixelRatio: viewportInfo.pixelRatio,
|
|
477
|
+
connectionType: DOMUtils.isBrowser() ? (navigator.connection?.effectiveType || 'unknown') : 'unknown',
|
|
478
|
+
platform: DeviceInfoCollector.getPlatform(),
|
|
426
479
|
};
|
|
427
480
|
}
|
|
428
481
|
/**
|
|
429
|
-
*
|
|
430
|
-
*/
|
|
431
|
-
createImageElement(imageUrl, alt = '', slot) {
|
|
432
|
-
const img = DOMUtils.safeCreateElement('img');
|
|
433
|
-
if (!img)
|
|
434
|
-
return null;
|
|
435
|
-
img.src = imageUrl;
|
|
436
|
-
img.alt = alt;
|
|
437
|
-
this.applyStyles(img, this.getImageStyles(slot));
|
|
438
|
-
return img;
|
|
439
|
-
}
|
|
440
|
-
/**
|
|
441
|
-
* 텍스트 요소 생성 (SSR 안전)
|
|
482
|
+
* 슬롯 위치 정보 가져오기 (SSR 안전)
|
|
442
483
|
*/
|
|
443
|
-
|
|
444
|
-
const element = DOMUtils.
|
|
484
|
+
static getSlotPosition(containerId) {
|
|
485
|
+
const element = DOMUtils.safeGetElementById(containerId);
|
|
445
486
|
if (!element)
|
|
446
|
-
return
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
...additionalStyles,
|
|
451
|
-
});
|
|
452
|
-
return element;
|
|
487
|
+
return 'unknown';
|
|
488
|
+
const rect = element.getBoundingClientRect();
|
|
489
|
+
const scrollInfo = DOMUtils.getScrollInfo();
|
|
490
|
+
return `x:${Math.round(rect.left)},y:${Math.round(rect.top + scrollInfo.scrollTop)}`;
|
|
453
491
|
}
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/**
|
|
495
|
+
* AdStage SDK - API 헤더 유틸리티
|
|
496
|
+
* 공통 헤더 생성 로직
|
|
497
|
+
*/
|
|
498
|
+
class ApiHeaders {
|
|
454
499
|
/**
|
|
455
|
-
*
|
|
500
|
+
* 표준 API 헤더 생성
|
|
456
501
|
*/
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
if (!placeholder) {
|
|
461
|
-
// SSR에서는 빈 div를 반환하되, 브라우저에서는 제대로 작동하도록 함
|
|
462
|
-
if (typeof document !== 'undefined') {
|
|
463
|
-
placeholder = document.createElement('div');
|
|
464
|
-
}
|
|
465
|
-
else {
|
|
466
|
-
// SSR 환경에서는 더미 객체 반환 (타입 단언 사용)
|
|
467
|
-
placeholder = {};
|
|
468
|
-
}
|
|
502
|
+
static create(apiKey, options) {
|
|
503
|
+
if (!apiKey) {
|
|
504
|
+
throw new Error('API key is required');
|
|
469
505
|
}
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
'justify-content': 'center',
|
|
478
|
-
color: '#6c757d',
|
|
479
|
-
...this.getBaseFontStyles(),
|
|
480
|
-
// 플레이스홀더는 최소 크기 보장
|
|
481
|
-
'min-width': '100px',
|
|
482
|
-
'min-height': '100px',
|
|
483
|
-
});
|
|
484
|
-
DOMUtils.safeSetTextContent(placeholder, text);
|
|
506
|
+
const headers = {
|
|
507
|
+
'x-api-key': apiKey,
|
|
508
|
+
'Content-Type': options?.contentType || 'application/json'
|
|
509
|
+
};
|
|
510
|
+
// User-Agent는 이벤트 추적에서 실제로 사용됨
|
|
511
|
+
if (typeof navigator !== 'undefined') {
|
|
512
|
+
headers['User-Agent'] = options?.userAgent || navigator.userAgent;
|
|
485
513
|
}
|
|
486
|
-
|
|
514
|
+
// X-Current-URL은 현재 서버에서 사용하지 않으므로 제거
|
|
515
|
+
// 필요시 이벤트 데이터 body에 포함
|
|
516
|
+
return headers;
|
|
487
517
|
}
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
// SSR 환경에서는 기본 div 반환
|
|
498
|
-
return document.createElement('div');
|
|
499
|
-
}
|
|
500
|
-
// 기본 컨테이너 스타일 적용 (불필요한 스타일 제거)
|
|
501
|
-
this.applyStyles(adElement, this.getBaseContainerStyles(slot));
|
|
502
|
-
// 배너 광고는 이미지만 표시
|
|
503
|
-
if (!ad.imageUrl) {
|
|
504
|
-
// 이미지가 없는 경우 플레이스홀더 반환
|
|
505
|
-
const placeholder = this.createPlaceholder(slot, '배너 광고');
|
|
506
|
-
return placeholder || adElement;
|
|
507
|
-
}
|
|
508
|
-
const img = this.createImageElement(ad.imageUrl, '', slot);
|
|
509
|
-
if (img) {
|
|
510
|
-
DOMUtils.safeAppendChild(adElement, img);
|
|
511
|
-
// 클릭 이벤트 추가
|
|
512
|
-
this.addClickHandler(adElement, ad, slot);
|
|
518
|
+
/**
|
|
519
|
+
* 이벤트 추적용 헤더 생성
|
|
520
|
+
* User-Agent는 서버에서 실제로 사용됨
|
|
521
|
+
*/
|
|
522
|
+
static createForEvents(apiKey, eventData) {
|
|
523
|
+
const baseHeaders = ApiHeaders.create(apiKey);
|
|
524
|
+
// User-Agent 오버라이드 (서버에서 실제 사용)
|
|
525
|
+
if (eventData?.userAgent) {
|
|
526
|
+
baseHeaders['User-Agent'] = eventData.userAgent;
|
|
513
527
|
}
|
|
514
|
-
|
|
528
|
+
// 다른 정보들은 HTTP 헤더가 아닌 이벤트 데이터 body에 포함하는 것이 적절
|
|
529
|
+
// (currentUrl, referrer 등은 POST body로 전송)
|
|
530
|
+
return baseHeaders;
|
|
515
531
|
}
|
|
516
532
|
}
|
|
517
533
|
|
|
518
534
|
/**
|
|
519
|
-
*
|
|
535
|
+
* 광고 이벤트 추적 관리 클래스
|
|
536
|
+
* - 광고 전용 이벤트 추적 및 전송
|
|
537
|
+
* - Viewable 이벤트 중복 방지 통합
|
|
538
|
+
* - 광고 서버 API 통신
|
|
520
539
|
*/
|
|
521
|
-
class
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
};
|
|
538
|
-
// 사용자가 크기를 지정하지 않은 경우 컨텐츠에 맞춤
|
|
539
|
-
if (!slot.width || slot.width === 0) {
|
|
540
|
-
containerStyles.display = 'inline-flex';
|
|
541
|
-
containerStyles['white-space'] = 'nowrap';
|
|
542
|
-
containerStyles['justify-content'] = 'flex-start'; // 좌측 정렬로 변경
|
|
543
|
-
}
|
|
544
|
-
// height만 자동인 경우 줄바꿈 허용
|
|
545
|
-
if ((slot.width && slot.width !== 0) && (!slot.height || slot.height === 0)) {
|
|
546
|
-
containerStyles['white-space'] = 'normal';
|
|
547
|
-
containerStyles['min-height'] = 'auto';
|
|
548
|
-
containerStyles['justify-content'] = 'flex-start'; // 좌측 정렬로 변경
|
|
549
|
-
}
|
|
550
|
-
this.applyStyles(adElement, containerStyles);
|
|
551
|
-
// 텍스트 광고는 textContent만 표시
|
|
552
|
-
if (!ad.textContent) {
|
|
553
|
-
// 텍스트가 없는 경우 플레이스홀더 반환
|
|
554
|
-
return this.createPlaceholder(slot, '텍스트 광고');
|
|
555
|
-
}
|
|
556
|
-
// 텍스트 콘텐츠 생성
|
|
557
|
-
const textContent = this.createTextElement(ad.textContent, 'div', {
|
|
558
|
-
'font-size': '16px',
|
|
559
|
-
'font-weight': '500',
|
|
560
|
-
color: '#212529',
|
|
561
|
-
width: '100%', // 전체 너비 사용하여 텍스트 정렬이 적용되도록 함
|
|
562
|
-
});
|
|
563
|
-
if (textContent) {
|
|
564
|
-
adElement.appendChild(textContent);
|
|
565
|
-
}
|
|
566
|
-
// 사용자가 text-align을 지정했는지 확인하고 레이아웃 조정
|
|
567
|
-
setTimeout(() => {
|
|
568
|
-
if (!adElement || typeof window === 'undefined')
|
|
569
|
-
return;
|
|
570
|
-
const computedStyle = window.getComputedStyle(adElement);
|
|
571
|
-
const textAlign = computedStyle.textAlign;
|
|
572
|
-
// 사용자가 text-align을 설정했고, width가 없는 경우
|
|
573
|
-
if (textAlign && textAlign !== 'start' && textAlign !== 'left' && (!slot.width || slot.width === 0)) {
|
|
574
|
-
// 블록 레벨로 변경하여 text-align이 제대로 작동하도록 함
|
|
575
|
-
adElement.style.display = 'block';
|
|
576
|
-
adElement.style.whiteSpace = 'normal';
|
|
577
|
-
// 최소 너비 설정 (텍스트가 한 줄일 때를 위해)
|
|
578
|
-
if (textContent) {
|
|
579
|
-
const textRect = textContent.getBoundingClientRect();
|
|
580
|
-
if (textRect.width > 0) {
|
|
581
|
-
adElement.style.minWidth = `${textRect.width}px`;
|
|
582
|
-
}
|
|
540
|
+
class AdvertisementEventTracker {
|
|
541
|
+
constructor(baseUrl, apiKey, debug, slots) {
|
|
542
|
+
this.baseUrl = baseUrl;
|
|
543
|
+
this.apiKey = apiKey;
|
|
544
|
+
this.debug = debug;
|
|
545
|
+
this.slots = slots;
|
|
546
|
+
}
|
|
547
|
+
/**
|
|
548
|
+
* 광고 이벤트 추적 - viewability 데이터 지원
|
|
549
|
+
*/
|
|
550
|
+
async trackAdvertisementEvent(adId, slotId, eventType, additionalData) {
|
|
551
|
+
try {
|
|
552
|
+
// VIEWABLE 이벤트의 경우 중복 확인
|
|
553
|
+
if (eventType === AdEventType.VIEWABLE) {
|
|
554
|
+
if (ViewableEventTracker.isDuplicateViewable(adId, slotId, this.debug)) {
|
|
555
|
+
return; // 중복 viewable 이벤트이므로 추적하지 않음
|
|
583
556
|
}
|
|
584
557
|
}
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
558
|
+
// 현재 슬롯 정보 가져오기
|
|
559
|
+
const slot = this.slots.get(slotId);
|
|
560
|
+
// 디바이스 정보 수집
|
|
561
|
+
const deviceInfo = DeviceInfoCollector.collectDeviceInfo();
|
|
562
|
+
// 광고 이벤트 데이터 구성 (DTO 구조에 맞춤)
|
|
563
|
+
const eventData = {
|
|
564
|
+
// 서버에서 자동 설정: orgId, advertisementId, action
|
|
565
|
+
// 하지만 DTO 검증을 위해 임시값 제공
|
|
566
|
+
orgId: 'temp', // 서버에서 API 키로부터 덮어씀
|
|
567
|
+
advertisementId: adId, // 서버에서 URL 파라미터로부터 덮어씀
|
|
568
|
+
action: eventType, // 서버에서 URL 파라미터로부터 덮어씀
|
|
569
|
+
// 필수 필드들
|
|
570
|
+
adType: slot?.adType || 'BANNER',
|
|
571
|
+
platform: deviceInfo.platform,
|
|
572
|
+
// 디바이스 정보는 deviceInfo 객체로 래핑
|
|
573
|
+
deviceInfo: deviceInfo,
|
|
574
|
+
// 페이지 및 슬롯 정보
|
|
575
|
+
pageUrl: DOMUtils.getPageInfo().url,
|
|
576
|
+
pageTitle: DOMUtils.getPageInfo().title,
|
|
577
|
+
referrer: DOMUtils.getPageInfo().referrer,
|
|
578
|
+
slotId,
|
|
579
|
+
slotPosition: DeviceInfoCollector.getSlotPosition(slot?.containerId || ''),
|
|
580
|
+
slotWidth: AdvertisementEventTracker.parseNumericValue(slot?.width),
|
|
581
|
+
slotHeight: AdvertisementEventTracker.parseNumericValue(slot?.height),
|
|
582
|
+
sessionId: deviceInfo.sessionId,
|
|
583
|
+
// 성능 메트릭
|
|
584
|
+
pageLoadTime: performance.now(),
|
|
585
|
+
// 추가 메타데이터
|
|
586
|
+
metadata: {
|
|
587
|
+
eventType,
|
|
588
|
+
sdkVersion: '1.0.0',
|
|
589
|
+
timestamp: Date.now(),
|
|
590
|
+
},
|
|
591
|
+
// viewable 관련 추가 데이터 (DTO 필드명과 매칭)
|
|
592
|
+
...(additionalData?.viewabilityMetrics && {
|
|
593
|
+
isViewable: additionalData.viewabilityMetrics.isViewable,
|
|
594
|
+
exposureTime: additionalData.viewabilityMetrics.exposureTime,
|
|
595
|
+
maxVisibilityRatio: additionalData.viewabilityMetrics.maxVisibilityRatio,
|
|
596
|
+
firstViewableTime: additionalData.viewabilityMetrics.firstViewableTime,
|
|
597
|
+
// IAB 표준 준수 여부
|
|
598
|
+
iabCompliant: additionalData.viewabilityMetrics.isViewable,
|
|
599
|
+
}),
|
|
600
|
+
// fraud 관련 데이터 (DTO 필드명과 매칭)
|
|
601
|
+
...(additionalData?.fraudScore !== undefined && {
|
|
602
|
+
fraudScore: additionalData.fraudScore,
|
|
603
|
+
fraudReasons: additionalData.fraudReasons,
|
|
604
|
+
riskLevel: additionalData.riskLevel,
|
|
605
|
+
}),
|
|
606
|
+
};
|
|
607
|
+
await fetch(`${this.baseUrl}/advertisements/events/${adId}/${eventType}`, {
|
|
608
|
+
method: 'POST',
|
|
609
|
+
headers: ApiHeaders.createForEvents(this.apiKey, eventData),
|
|
610
|
+
body: JSON.stringify(eventData),
|
|
611
|
+
});
|
|
612
|
+
if (this.debug) {
|
|
613
|
+
console.log(`Tracked advertisement event: ${eventType} for ad ${adId}`, eventData);
|
|
614
|
+
}
|
|
600
615
|
}
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
// 네이티브 광고는 이미지만 표시
|
|
604
|
-
if (!ad.imageUrl) {
|
|
605
|
-
// 이미지가 없는 경우 플레이스홀더 반환
|
|
606
|
-
const placeholder = this.createPlaceholder(slot, '네이티브 광고');
|
|
607
|
-
return placeholder || adElement;
|
|
616
|
+
catch (error) {
|
|
617
|
+
console.error('Failed to track advertisement event:', error);
|
|
608
618
|
}
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
619
|
+
}
|
|
620
|
+
/**
|
|
621
|
+
* 크기 값을 숫자로 변환 (서버 API용)
|
|
622
|
+
*/
|
|
623
|
+
static parseNumericValue(value) {
|
|
624
|
+
if (typeof value === 'number') {
|
|
625
|
+
return value;
|
|
615
626
|
}
|
|
616
|
-
|
|
627
|
+
if (typeof value === 'string') {
|
|
628
|
+
// px 단위 제거하고 숫자만 추출
|
|
629
|
+
const numericValue = parseFloat(value.replace(/px$/, ''));
|
|
630
|
+
return isNaN(numericValue) ? 0 : numericValue;
|
|
631
|
+
}
|
|
632
|
+
return 0; // 기본값
|
|
617
633
|
}
|
|
618
634
|
}
|
|
619
635
|
|
|
620
636
|
/**
|
|
621
|
-
*
|
|
637
|
+
* IAB 표준 준수 viewable impression 측정
|
|
622
638
|
*/
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
639
|
+
// 광고 타입별 IAB 표준 설정
|
|
640
|
+
const VIEWABILITY_STANDARDS = {
|
|
641
|
+
BANNER: {
|
|
642
|
+
threshold: 0.5,
|
|
643
|
+
minDuration: 1000,
|
|
644
|
+
maxMeasureTime: 30000
|
|
645
|
+
},
|
|
646
|
+
VIDEO: {
|
|
647
|
+
threshold: 0.5,
|
|
648
|
+
minDuration: 2000,
|
|
649
|
+
maxMeasureTime: 60000
|
|
650
|
+
},
|
|
651
|
+
NATIVE: {
|
|
652
|
+
threshold: 0.5,
|
|
653
|
+
minDuration: 1000,
|
|
654
|
+
maxMeasureTime: 30000
|
|
655
|
+
},
|
|
656
|
+
INTERSTITIAL: {
|
|
657
|
+
threshold: 0.5,
|
|
658
|
+
minDuration: 1000,
|
|
659
|
+
maxMeasureTime: 10000
|
|
660
|
+
},
|
|
661
|
+
TEXT: {
|
|
662
|
+
threshold: 0.5,
|
|
663
|
+
minDuration: 1000,
|
|
664
|
+
maxMeasureTime: 30000
|
|
665
|
+
},
|
|
666
|
+
POPUP: {
|
|
667
|
+
threshold: 0.5,
|
|
668
|
+
minDuration: 1000,
|
|
669
|
+
maxMeasureTime: 10000
|
|
646
670
|
}
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
this.
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
this.trackEvent?.(ad._id, slot.id, 'VIDEO_COMPLETE');
|
|
664
|
-
});
|
|
665
|
-
return video;
|
|
671
|
+
};
|
|
672
|
+
class ViewabilityTracker {
|
|
673
|
+
constructor(element, adType, onViewable) {
|
|
674
|
+
this.observer = null;
|
|
675
|
+
this.viewabilityTimer = null;
|
|
676
|
+
this.maxVisibilityTimer = null;
|
|
677
|
+
this.startTime = 0;
|
|
678
|
+
this.maxVisibilityRatio = 0;
|
|
679
|
+
this.firstViewableTime = null;
|
|
680
|
+
this.isViewableAchieved = false;
|
|
681
|
+
this.element = element;
|
|
682
|
+
this.config = VIEWABILITY_STANDARDS[adType] || VIEWABILITY_STANDARDS.BANNER;
|
|
683
|
+
this.onViewableCallback = onViewable;
|
|
684
|
+
this.startTime = performance.now();
|
|
685
|
+
this.initIntersectionObserver();
|
|
686
|
+
this.initMaxMeasureTimer();
|
|
666
687
|
}
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
class InterstitialAdRenderer extends BaseAdRenderer {
|
|
673
|
-
render(ad, slot) {
|
|
674
|
-
let adElement = DOMUtils.safeCreateElement('div');
|
|
675
|
-
if (!adElement) {
|
|
676
|
-
return this.createPlaceholder(slot, '전면 광고');
|
|
688
|
+
initIntersectionObserver() {
|
|
689
|
+
// IntersectionObserver 지원 확인
|
|
690
|
+
if (!('IntersectionObserver' in window)) {
|
|
691
|
+
console.warn('IntersectionObserver not supported, viewability tracking disabled');
|
|
692
|
+
return;
|
|
677
693
|
}
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
display: 'flex',
|
|
682
|
-
'flex-direction': 'column',
|
|
694
|
+
this.observer = new IntersectionObserver((entries) => this.handleIntersection(entries), {
|
|
695
|
+
threshold: [0, 0.1, 0.25, 0.5, 0.75, 1.0],
|
|
696
|
+
rootMargin: '0px'
|
|
683
697
|
});
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
698
|
+
this.observer.observe(this.element);
|
|
699
|
+
}
|
|
700
|
+
handleIntersection(entries) {
|
|
701
|
+
entries.forEach(entry => {
|
|
702
|
+
const visibilityRatio = entry.intersectionRatio;
|
|
703
|
+
const isVisible = this.isDocumentVisible();
|
|
704
|
+
// 최대 가시성 비율 추적
|
|
705
|
+
this.maxVisibilityRatio = Math.max(this.maxVisibilityRatio, visibilityRatio);
|
|
706
|
+
// Viewable 조건 확인 (50% 이상 + 문서 가시성)
|
|
707
|
+
if (visibilityRatio >= this.config.threshold && isVisible) {
|
|
708
|
+
this.startViewabilityTimer();
|
|
689
709
|
}
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
// 이미지가 없고 비디오가 있는 경우
|
|
693
|
-
const video = this.createVideoElement(ad.videoUrl, ad, slot);
|
|
694
|
-
if (video) {
|
|
695
|
-
adElement.appendChild(video);
|
|
710
|
+
else {
|
|
711
|
+
this.stopViewabilityTimer();
|
|
696
712
|
}
|
|
713
|
+
});
|
|
714
|
+
}
|
|
715
|
+
isDocumentVisible() {
|
|
716
|
+
// 단순한 문서 가시성 확인
|
|
717
|
+
return !document.hidden && document.visibilityState === 'visible';
|
|
718
|
+
}
|
|
719
|
+
startViewabilityTimer() {
|
|
720
|
+
if (this.viewabilityTimer || this.isViewableAchieved)
|
|
721
|
+
return;
|
|
722
|
+
if (this.firstViewableTime === null) {
|
|
723
|
+
this.firstViewableTime = performance.now();
|
|
697
724
|
}
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
725
|
+
this.viewabilityTimer = setTimeout(() => {
|
|
726
|
+
this.onViewabilityAchieved();
|
|
727
|
+
}, this.config.minDuration);
|
|
728
|
+
}
|
|
729
|
+
stopViewabilityTimer() {
|
|
730
|
+
if (this.viewabilityTimer) {
|
|
731
|
+
clearTimeout(this.viewabilityTimer);
|
|
732
|
+
this.viewabilityTimer = null;
|
|
701
733
|
}
|
|
702
|
-
// 클릭 이벤트 추가
|
|
703
|
-
this.addClickHandler(adElement, ad, slot);
|
|
704
|
-
return adElement;
|
|
705
734
|
}
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
if (!video)
|
|
712
|
-
return null;
|
|
713
|
-
video.src = videoUrl;
|
|
714
|
-
video.controls = true;
|
|
715
|
-
// 비디오도 이미지와 같은 스타일 적용
|
|
716
|
-
this.applyStyles(video, this.getImageStyles(slot));
|
|
717
|
-
// 비디오 이벤트 추적
|
|
718
|
-
video.addEventListener('play', () => {
|
|
719
|
-
this.trackEvent?.(ad._id, slot.id, 'VIDEO_START');
|
|
720
|
-
});
|
|
721
|
-
video.addEventListener('ended', () => {
|
|
722
|
-
this.trackEvent?.(ad._id, slot.id, 'VIDEO_COMPLETE');
|
|
723
|
-
});
|
|
724
|
-
return video;
|
|
735
|
+
initMaxMeasureTimer() {
|
|
736
|
+
// 최대 측정 시간 후 자동 종료
|
|
737
|
+
this.maxVisibilityTimer = setTimeout(() => {
|
|
738
|
+
this.destroy();
|
|
739
|
+
}, this.config.maxMeasureTime);
|
|
725
740
|
}
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
class AdRendererFactory {
|
|
734
|
-
/**
|
|
735
|
-
* 광고 타입에 맞는 렌더러 생성
|
|
736
|
-
*/
|
|
737
|
-
static createRenderer(adType, trackEvent) {
|
|
738
|
-
const RendererClass = this.renderers.get(adType);
|
|
739
|
-
if (!RendererClass) {
|
|
740
|
-
console.warn(`No renderer found for ad type: ${adType}, falling back to Banner renderer`);
|
|
741
|
-
return new BannerAdRenderer(trackEvent);
|
|
741
|
+
onViewabilityAchieved() {
|
|
742
|
+
if (this.isViewableAchieved)
|
|
743
|
+
return;
|
|
744
|
+
this.isViewableAchieved = true;
|
|
745
|
+
const metrics = this.calculateMetrics();
|
|
746
|
+
if (this.onViewableCallback) {
|
|
747
|
+
this.onViewableCallback(metrics);
|
|
742
748
|
}
|
|
743
|
-
return new RendererClass(trackEvent);
|
|
744
749
|
}
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
return
|
|
750
|
+
calculateMetrics() {
|
|
751
|
+
const currentTime = performance.now();
|
|
752
|
+
const exposureTime = this.firstViewableTime
|
|
753
|
+
? currentTime - this.firstViewableTime
|
|
754
|
+
: 0;
|
|
755
|
+
return {
|
|
756
|
+
isViewable: this.isViewableAchieved,
|
|
757
|
+
exposureTime,
|
|
758
|
+
maxVisibilityRatio: this.maxVisibilityRatio,
|
|
759
|
+
firstViewableTime: this.firstViewableTime,
|
|
760
|
+
measureStartTime: this.startTime,
|
|
761
|
+
};
|
|
751
762
|
}
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
*/
|
|
755
|
-
static getSupportedAdTypes() {
|
|
756
|
-
return Array.from(this.renderers.keys());
|
|
763
|
+
getMetrics() {
|
|
764
|
+
return this.calculateMetrics();
|
|
757
765
|
}
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
766
|
+
destroy() {
|
|
767
|
+
this.stopViewabilityTimer();
|
|
768
|
+
if (this.maxVisibilityTimer) {
|
|
769
|
+
clearTimeout(this.maxVisibilityTimer);
|
|
770
|
+
this.maxVisibilityTimer = null;
|
|
771
|
+
}
|
|
772
|
+
if (this.observer) {
|
|
773
|
+
this.observer.disconnect();
|
|
774
|
+
this.observer = null;
|
|
775
|
+
}
|
|
763
776
|
}
|
|
764
777
|
}
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
778
|
+
|
|
779
|
+
/**
|
|
780
|
+
* BasicFraudDetector - 현실적 구현 버전
|
|
781
|
+
* 기본적인 봇 탐지 및 간단한 행동 패턴 분석
|
|
782
|
+
*/
|
|
783
|
+
class BasicFraudDetector {
|
|
784
|
+
constructor() {
|
|
785
|
+
this.mouseEvents = 0;
|
|
786
|
+
this.keyboardEvents = 0;
|
|
787
|
+
this.scrollEvents = 0;
|
|
788
|
+
this.startTime = Date.now();
|
|
789
|
+
this.initBasicTracking();
|
|
790
|
+
}
|
|
791
|
+
initBasicTracking() {
|
|
792
|
+
// 기본적인 사용자 상호작용 추적
|
|
793
|
+
document.addEventListener('mousemove', () => this.mouseEvents++, { passive: true });
|
|
794
|
+
document.addEventListener('keydown', () => this.keyboardEvents++, { passive: true });
|
|
795
|
+
document.addEventListener('scroll', () => this.scrollEvents++, { passive: true });
|
|
796
|
+
}
|
|
797
|
+
calculateFraudScore() {
|
|
798
|
+
let score = 0;
|
|
799
|
+
const reasons = [];
|
|
800
|
+
// 1. 웹드라이버 탐지 (기본)
|
|
801
|
+
if (this.detectWebDriver()) {
|
|
802
|
+
score += 50;
|
|
803
|
+
reasons.push('WebDriver detected');
|
|
804
|
+
}
|
|
805
|
+
// 2. 헤드리스 브라우저 기본 탐지
|
|
806
|
+
if (this.detectBasicHeadless()) {
|
|
807
|
+
score += 40;
|
|
808
|
+
reasons.push('Headless browser signatures');
|
|
809
|
+
}
|
|
810
|
+
// 3. 사용자 상호작용 부족
|
|
811
|
+
const sessionTime = Date.now() - this.startTime;
|
|
812
|
+
if (sessionTime > 5000) { // 5초 이상 경과
|
|
813
|
+
if (this.mouseEvents === 0) {
|
|
814
|
+
score += 20;
|
|
815
|
+
reasons.push('No mouse interaction');
|
|
816
|
+
}
|
|
817
|
+
if (this.scrollEvents === 0 && sessionTime > 10000) {
|
|
818
|
+
score += 15;
|
|
819
|
+
reasons.push('No scroll activity');
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
// 4. 브라우저 환경 이상 징후
|
|
823
|
+
const browserCheck = this.checkBrowserEnvironment();
|
|
824
|
+
score += browserCheck.score;
|
|
825
|
+
reasons.push(...browserCheck.reasons);
|
|
826
|
+
// 5. 시간 패턴 이상 (너무 빠른 페이지 로드 후 즉시 클릭)
|
|
827
|
+
if (sessionTime < 1000) {
|
|
828
|
+
score += 25;
|
|
829
|
+
reasons.push('Suspiciously fast interaction');
|
|
830
|
+
}
|
|
831
|
+
const finalScore = Math.min(score, 100);
|
|
832
|
+
return {
|
|
833
|
+
score: finalScore,
|
|
834
|
+
riskLevel: this.getRiskLevel(finalScore),
|
|
835
|
+
reasons: reasons
|
|
836
|
+
};
|
|
837
|
+
}
|
|
838
|
+
detectWebDriver() {
|
|
839
|
+
// 기본적인 웹드라이버 탐지
|
|
840
|
+
return !!(window.webdriver ||
|
|
841
|
+
navigator.webdriver ||
|
|
842
|
+
window.__webdriver_evaluate ||
|
|
843
|
+
window.__selenium_evaluate ||
|
|
844
|
+
window.__webdriver_script_function ||
|
|
845
|
+
window.__webdriver_script_func ||
|
|
846
|
+
window.__webdriver_script_fn ||
|
|
847
|
+
window.__fxdriver_evaluate ||
|
|
848
|
+
window.__driver_unwrapped ||
|
|
849
|
+
window.__webdriver_unwrapped ||
|
|
850
|
+
window.__driver_evaluate ||
|
|
851
|
+
window.__selenium_unwrapped ||
|
|
852
|
+
window.__fxdriver_unwrapped);
|
|
853
|
+
}
|
|
854
|
+
detectBasicHeadless() {
|
|
855
|
+
const signatures = [];
|
|
856
|
+
// PhantomJS 탐지
|
|
857
|
+
if (window._phantom || window.phantom) {
|
|
858
|
+
signatures.push('PhantomJS');
|
|
859
|
+
}
|
|
860
|
+
// Chrome headless 기본 탐지
|
|
861
|
+
if (navigator.userAgent.includes('HeadlessChrome')) {
|
|
862
|
+
signatures.push('Chrome Headless');
|
|
863
|
+
}
|
|
864
|
+
// 플러그인 없음 (일반적이지 않음)
|
|
865
|
+
if (navigator.plugins.length === 0) {
|
|
866
|
+
signatures.push('No plugins');
|
|
867
|
+
}
|
|
868
|
+
return signatures.length > 0;
|
|
869
|
+
}
|
|
870
|
+
checkBrowserEnvironment() {
|
|
871
|
+
let score = 0;
|
|
872
|
+
const reasons = [];
|
|
873
|
+
// 언어 설정 이상
|
|
874
|
+
if (!navigator.language || navigator.language === 'C') {
|
|
875
|
+
score += 10;
|
|
876
|
+
reasons.push('Unusual language setting');
|
|
877
|
+
}
|
|
878
|
+
// 쿠키 비활성화
|
|
879
|
+
if (!navigator.cookieEnabled) {
|
|
880
|
+
score += 15;
|
|
881
|
+
reasons.push('Cookies disabled');
|
|
882
|
+
}
|
|
883
|
+
// 화면 해상도 이상
|
|
884
|
+
if (screen.width === 0 || screen.height === 0) {
|
|
885
|
+
score += 20;
|
|
886
|
+
reasons.push('Invalid screen resolution');
|
|
887
|
+
}
|
|
888
|
+
// 시간대 정보 없음
|
|
889
|
+
try {
|
|
890
|
+
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
891
|
+
if (!timezone || timezone === 'UTC') {
|
|
892
|
+
score += 5;
|
|
893
|
+
reasons.push('No timezone info');
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
catch (e) {
|
|
897
|
+
score += 10;
|
|
898
|
+
reasons.push('Timezone detection failed');
|
|
899
|
+
}
|
|
900
|
+
return { score, reasons };
|
|
901
|
+
}
|
|
902
|
+
getRiskLevel(score) {
|
|
903
|
+
if (score >= 70)
|
|
904
|
+
return 'CRITICAL';
|
|
905
|
+
if (score >= 50)
|
|
906
|
+
return 'HIGH';
|
|
907
|
+
if (score >= 30)
|
|
908
|
+
return 'MEDIUM';
|
|
909
|
+
return 'LOW';
|
|
910
|
+
}
|
|
911
|
+
getBrowserInfo() {
|
|
912
|
+
return {
|
|
913
|
+
userAgent: navigator.userAgent,
|
|
914
|
+
language: navigator.language,
|
|
915
|
+
platform: navigator.platform,
|
|
916
|
+
cookieEnabled: navigator.cookieEnabled,
|
|
917
|
+
doNotTrack: navigator.doNotTrack,
|
|
918
|
+
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
919
|
+
screenResolution: `${screen.width}x${screen.height}`,
|
|
920
|
+
viewportSize: `${window.innerWidth}x${window.innerHeight}`
|
|
921
|
+
};
|
|
922
|
+
}
|
|
923
|
+
destroy() {
|
|
924
|
+
// 이벤트 리스너 정리는 생략 (메모리 누수 방지를 위해 필요시 구현)
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
/**
|
|
929
|
+
* AdStage SDK 엔드포인트 상수 관리
|
|
930
|
+
* 모든 API URL을 중앙에서 관리
|
|
931
|
+
*/
|
|
932
|
+
/**
|
|
933
|
+
* 환경별 API 엔드포인트 (읽기 전용)
|
|
934
|
+
*/
|
|
935
|
+
const API_ENDPOINTS = {
|
|
936
|
+
/** 프로덕션 환경 */
|
|
937
|
+
production: 'https://api.adstage.io',
|
|
938
|
+
/** 베타 환경 (기본값) */
|
|
939
|
+
beta: 'https://beta-api.adstage.app'
|
|
940
|
+
};
|
|
941
|
+
/**
|
|
942
|
+
* API 경로 상수
|
|
943
|
+
*/
|
|
944
|
+
const API_PATHS = {
|
|
945
|
+
/** 광고 관련 */
|
|
946
|
+
advertisements: {
|
|
947
|
+
list: '/advertisements/list',
|
|
948
|
+
events: '/advertisements/events'
|
|
949
|
+
},
|
|
950
|
+
/** 이벤트 관련 */
|
|
951
|
+
events: {
|
|
952
|
+
track: '/events/track',
|
|
953
|
+
batch: '/events/batch'
|
|
954
|
+
}
|
|
955
|
+
};
|
|
956
|
+
/**
|
|
957
|
+
* 완전한 API URL 생성 헬퍼
|
|
958
|
+
*/
|
|
959
|
+
class EndpointBuilder {
|
|
960
|
+
constructor(baseUrl) {
|
|
961
|
+
/**
|
|
962
|
+
* 광고 엔드포인트
|
|
963
|
+
*/
|
|
964
|
+
this.advertisements = {
|
|
965
|
+
list: () => `${this.baseUrl}${API_PATHS.advertisements.list}`,
|
|
966
|
+
events: (adId, eventType) => `${this.baseUrl}${API_PATHS.advertisements.events}/${adId}/${eventType}`
|
|
967
|
+
};
|
|
968
|
+
/**
|
|
969
|
+
* 이벤트 엔드포인트
|
|
970
|
+
*/
|
|
971
|
+
this.events = {
|
|
972
|
+
track: () => `${this.baseUrl}${API_PATHS.events.track}`,
|
|
973
|
+
batch: () => `${this.baseUrl}${API_PATHS.events.batch}`
|
|
974
|
+
};
|
|
975
|
+
// 기본값은 베타 환경 사용
|
|
976
|
+
this.baseUrl = baseUrl || API_ENDPOINTS.beta;
|
|
977
|
+
}
|
|
978
|
+
/**
|
|
979
|
+
* 기본 URL 변경
|
|
980
|
+
*/
|
|
981
|
+
setBaseUrl(url) {
|
|
982
|
+
this.baseUrl = url;
|
|
983
|
+
console.log('🔄 API endpoint changed:', url);
|
|
984
|
+
}
|
|
985
|
+
/**
|
|
986
|
+
* 기본 URL 반환
|
|
987
|
+
*/
|
|
988
|
+
getBaseUrl() {
|
|
989
|
+
return this.baseUrl;
|
|
990
|
+
}
|
|
991
|
+
/**
|
|
992
|
+
* 커스텀 경로 생성
|
|
993
|
+
*/
|
|
994
|
+
custom(path) {
|
|
995
|
+
return `${this.baseUrl}${path.startsWith('/') ? path : `/${path}`}`;
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
/**
|
|
999
|
+
* 전역 엔드포인트 빌더 인스턴스 (기본: 베타 환경)
|
|
1000
|
+
*/
|
|
1001
|
+
const endpoints = new EndpointBuilder();
|
|
1002
|
+
|
|
1003
|
+
/**
|
|
1004
|
+
* 기본 광고 렌더러 추상 클래스
|
|
1005
|
+
*/
|
|
1006
|
+
class BaseAdRenderer {
|
|
1007
|
+
constructor(trackEvent) {
|
|
1008
|
+
this.trackEvent = trackEvent;
|
|
1009
|
+
}
|
|
1010
|
+
/**
|
|
1011
|
+
* 공통 클릭 이벤트 핸들러 (SSR 안전)
|
|
1012
|
+
*/
|
|
1013
|
+
addClickHandler(element, ad, slot) {
|
|
1014
|
+
DOMUtils.safeAddEventListener(element, 'click', () => {
|
|
1015
|
+
this.trackEvent?.(ad._id, slot.id, 'CLICK');
|
|
1016
|
+
if (ad.linkUrl) {
|
|
1017
|
+
DOMUtils.safeWindowOpen(ad.linkUrl, '_blank');
|
|
1018
|
+
}
|
|
1019
|
+
});
|
|
1020
|
+
}
|
|
1021
|
+
/**
|
|
1022
|
+
* 공통 스타일 적용 유틸리티 (SSR 안전)
|
|
1023
|
+
*/
|
|
1024
|
+
applyStyles(element, styles) {
|
|
1025
|
+
DOMUtils.safeApplyStyles(element, styles);
|
|
1026
|
+
}
|
|
1027
|
+
/**
|
|
1028
|
+
* 크기 값 파싱 유틸리티 (px, %, number 지원)
|
|
1029
|
+
*/
|
|
1030
|
+
parseSizeValue(value) {
|
|
1031
|
+
if (!value)
|
|
1032
|
+
return undefined;
|
|
1033
|
+
if (typeof value === 'number') {
|
|
1034
|
+
return value > 0 ? `${value}px` : undefined;
|
|
1035
|
+
}
|
|
1036
|
+
if (typeof value === 'string') {
|
|
1037
|
+
const trimmed = value.trim();
|
|
1038
|
+
if (!trimmed)
|
|
1039
|
+
return undefined;
|
|
1040
|
+
// 퍼센트 값 처리
|
|
1041
|
+
if (trimmed.endsWith('%')) {
|
|
1042
|
+
const percent = parseFloat(trimmed);
|
|
1043
|
+
return !isNaN(percent) && percent > 0 ? trimmed : undefined;
|
|
1044
|
+
}
|
|
1045
|
+
// px 값 처리 (px 단위 포함/미포함 모두 지원)
|
|
1046
|
+
const numValue = trimmed.endsWith('px')
|
|
1047
|
+
? parseFloat(trimmed.slice(0, -2))
|
|
1048
|
+
: parseFloat(trimmed);
|
|
1049
|
+
return !isNaN(numValue) && numValue > 0 ? `${numValue}px` : undefined;
|
|
1050
|
+
}
|
|
1051
|
+
return undefined;
|
|
1052
|
+
}
|
|
1053
|
+
/**
|
|
1054
|
+
* 기본 컨테이너 스타일 (사용자 지정 크기만 적용)
|
|
1055
|
+
*/
|
|
1056
|
+
getBaseContainerStyles(slot) {
|
|
1057
|
+
const styles = {
|
|
1058
|
+
cursor: 'pointer',
|
|
1059
|
+
position: 'relative',
|
|
1060
|
+
overflow: 'hidden',
|
|
1061
|
+
};
|
|
1062
|
+
// 사용자가 지정한 크기가 있을 때만 적용
|
|
1063
|
+
const parsedWidth = this.parseSizeValue(slot.width);
|
|
1064
|
+
const parsedHeight = this.parseSizeValue(slot.height);
|
|
1065
|
+
if (parsedWidth) {
|
|
1066
|
+
styles.width = parsedWidth;
|
|
1067
|
+
}
|
|
1068
|
+
if (parsedHeight) {
|
|
1069
|
+
styles.height = parsedHeight;
|
|
1070
|
+
}
|
|
1071
|
+
return styles;
|
|
1072
|
+
}
|
|
1073
|
+
/**
|
|
1074
|
+
* 이미지 스타일 (고유 사이즈 유지, 사용자 지정 크기 우선)
|
|
1075
|
+
*/
|
|
1076
|
+
getImageStyles(slot) {
|
|
1077
|
+
const styles = {
|
|
1078
|
+
display: 'block',
|
|
1079
|
+
'max-width': '100%',
|
|
1080
|
+
height: 'auto',
|
|
1081
|
+
'object-position': 'center', // 🎯 이미지 항상 중앙 정렬
|
|
1082
|
+
};
|
|
1083
|
+
// 사용자가 컨테이너 크기를 지정한 경우에만 크기 제한
|
|
1084
|
+
const parsedWidth = this.parseSizeValue(slot?.width);
|
|
1085
|
+
const parsedHeight = this.parseSizeValue(slot?.height);
|
|
1086
|
+
if (parsedWidth && parsedHeight) {
|
|
1087
|
+
styles.width = '100%';
|
|
1088
|
+
styles.height = '100%';
|
|
1089
|
+
styles['object-fit'] = 'cover';
|
|
1090
|
+
styles['object-position'] = 'center'; // 🎯 크기 조정 시에도 중앙 정렬
|
|
1091
|
+
}
|
|
1092
|
+
return styles;
|
|
1093
|
+
}
|
|
1094
|
+
/**
|
|
1095
|
+
* 기본 폰트 스타일
|
|
1096
|
+
*/
|
|
1097
|
+
getBaseFontStyles() {
|
|
1098
|
+
return {
|
|
1099
|
+
'font-family': 'Arial, sans-serif',
|
|
1100
|
+
'line-height': '1.4',
|
|
1101
|
+
'word-break': 'keep-all',
|
|
1102
|
+
};
|
|
1103
|
+
}
|
|
1104
|
+
/**
|
|
1105
|
+
* 이미지 요소 생성 (SSR 안전)
|
|
1106
|
+
*/
|
|
1107
|
+
createImageElement(imageUrl, alt = '', slot) {
|
|
1108
|
+
const img = DOMUtils.safeCreateElement('img');
|
|
1109
|
+
if (!img)
|
|
1110
|
+
return null;
|
|
1111
|
+
img.src = imageUrl;
|
|
1112
|
+
img.alt = alt;
|
|
1113
|
+
this.applyStyles(img, this.getImageStyles(slot));
|
|
1114
|
+
return img;
|
|
1115
|
+
}
|
|
1116
|
+
/**
|
|
1117
|
+
* 텍스트 요소 생성 (SSR 안전)
|
|
1118
|
+
*/
|
|
1119
|
+
createTextElement(text, tag = 'div', additionalStyles = {}) {
|
|
1120
|
+
const element = DOMUtils.safeCreateElement(tag);
|
|
1121
|
+
if (!element)
|
|
1122
|
+
return null;
|
|
1123
|
+
DOMUtils.safeSetTextContent(element, text);
|
|
1124
|
+
this.applyStyles(element, {
|
|
1125
|
+
...this.getBaseFontStyles(),
|
|
1126
|
+
...additionalStyles,
|
|
1127
|
+
});
|
|
1128
|
+
return element;
|
|
1129
|
+
}
|
|
1130
|
+
/**
|
|
1131
|
+
* 플레이스홀더 요소 생성
|
|
1132
|
+
*/
|
|
1133
|
+
createPlaceholder(slot, text = '광고') {
|
|
1134
|
+
let placeholder = DOMUtils.safeCreateElement('div');
|
|
1135
|
+
// SSR 환경에서 DOM을 사용할 수 없는 경우, 런타임에 생성되도록 함
|
|
1136
|
+
if (!placeholder) {
|
|
1137
|
+
// SSR에서는 빈 div를 반환하되, 브라우저에서는 제대로 작동하도록 함
|
|
1138
|
+
if (typeof document !== 'undefined') {
|
|
1139
|
+
placeholder = document.createElement('div');
|
|
1140
|
+
}
|
|
1141
|
+
else {
|
|
1142
|
+
// SSR 환경에서는 더미 객체 반환 (타입 단언 사용)
|
|
1143
|
+
placeholder = {};
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
// DOM이 사용 가능한 경우에만 스타일 적용
|
|
1147
|
+
if (DOMUtils.canUseDOM() && placeholder) {
|
|
1148
|
+
this.applyStyles(placeholder, {
|
|
1149
|
+
...this.getBaseContainerStyles(slot),
|
|
1150
|
+
background: '#f8f9fa',
|
|
1151
|
+
display: 'flex',
|
|
1152
|
+
'align-items': 'center',
|
|
1153
|
+
'justify-content': 'center',
|
|
1154
|
+
color: '#6c757d',
|
|
1155
|
+
...this.getBaseFontStyles(),
|
|
1156
|
+
// 플레이스홀더는 최소 크기 보장
|
|
1157
|
+
'min-width': '100px',
|
|
1158
|
+
'min-height': '100px',
|
|
1159
|
+
});
|
|
1160
|
+
DOMUtils.safeSetTextContent(placeholder, text);
|
|
1161
|
+
}
|
|
1162
|
+
return placeholder;
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
/**
|
|
1167
|
+
* 배너 광고 렌더러 - 이미지만 표시
|
|
1168
|
+
*/
|
|
1169
|
+
class BannerAdRenderer extends BaseAdRenderer {
|
|
1170
|
+
render(ad, slot) {
|
|
1171
|
+
const adElement = DOMUtils.safeCreateElement('div');
|
|
1172
|
+
if (!adElement) {
|
|
1173
|
+
// SSR 환경에서는 기본 div 반환
|
|
1174
|
+
return document.createElement('div');
|
|
1175
|
+
}
|
|
1176
|
+
// 기본 컨테이너 스타일 적용 (불필요한 스타일 제거)
|
|
1177
|
+
this.applyStyles(adElement, this.getBaseContainerStyles(slot));
|
|
1178
|
+
// 배너 광고는 이미지만 표시
|
|
1179
|
+
if (!ad.imageUrl) {
|
|
1180
|
+
// 이미지가 없는 경우 플레이스홀더 반환
|
|
1181
|
+
const placeholder = this.createPlaceholder(slot, '배너 광고');
|
|
1182
|
+
return placeholder || adElement;
|
|
1183
|
+
}
|
|
1184
|
+
const img = this.createImageElement(ad.imageUrl, '', slot);
|
|
1185
|
+
if (img) {
|
|
1186
|
+
DOMUtils.safeAppendChild(adElement, img);
|
|
1187
|
+
// 클릭 이벤트 추가
|
|
1188
|
+
this.addClickHandler(adElement, ad, slot);
|
|
1189
|
+
}
|
|
1190
|
+
return adElement;
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
/**
|
|
1195
|
+
* 텍스트 광고 렌더러 - textContent만 표시
|
|
1196
|
+
*/
|
|
1197
|
+
class TextAdRenderer extends BaseAdRenderer {
|
|
1198
|
+
render(ad, slot) {
|
|
1199
|
+
let adElement = DOMUtils.safeCreateElement('div');
|
|
1200
|
+
if (!adElement) {
|
|
1201
|
+
return this.createPlaceholder(slot, '텍스트 광고');
|
|
1202
|
+
}
|
|
1203
|
+
// 기본 컨테이너 스타일
|
|
1204
|
+
const containerStyles = {
|
|
1205
|
+
...this.getBaseContainerStyles(slot),
|
|
1206
|
+
padding: '20px',
|
|
1207
|
+
background: 'transparent',
|
|
1208
|
+
display: 'flex',
|
|
1209
|
+
'align-items': 'center',
|
|
1210
|
+
'justify-content': 'center',
|
|
1211
|
+
// text-align은 사용자가 설정할 수 있도록 기본값에서 제외
|
|
1212
|
+
...this.getBaseFontStyles(),
|
|
1213
|
+
};
|
|
1214
|
+
// 사용자가 크기를 지정하지 않은 경우 컨텐츠에 맞춤
|
|
1215
|
+
if (!slot.width || slot.width === 0) {
|
|
1216
|
+
containerStyles.display = 'inline-flex';
|
|
1217
|
+
containerStyles['white-space'] = 'nowrap';
|
|
1218
|
+
containerStyles['justify-content'] = 'flex-start'; // 좌측 정렬로 변경
|
|
1219
|
+
}
|
|
1220
|
+
// height만 자동인 경우 줄바꿈 허용
|
|
1221
|
+
if ((slot.width && slot.width !== 0) && (!slot.height || slot.height === 0)) {
|
|
1222
|
+
containerStyles['white-space'] = 'normal';
|
|
1223
|
+
containerStyles['min-height'] = 'auto';
|
|
1224
|
+
containerStyles['justify-content'] = 'flex-start'; // 좌측 정렬로 변경
|
|
1225
|
+
}
|
|
1226
|
+
this.applyStyles(adElement, containerStyles);
|
|
1227
|
+
// 텍스트 광고는 textContent만 표시
|
|
1228
|
+
if (!ad.textContent) {
|
|
1229
|
+
// 텍스트가 없는 경우 플레이스홀더 반환
|
|
1230
|
+
return this.createPlaceholder(slot, '텍스트 광고');
|
|
1231
|
+
}
|
|
1232
|
+
// 텍스트 콘텐츠 생성
|
|
1233
|
+
const textContent = this.createTextElement(ad.textContent, 'div', {
|
|
1234
|
+
'font-size': '16px',
|
|
1235
|
+
'font-weight': '500',
|
|
1236
|
+
color: '#212529',
|
|
1237
|
+
width: '100%', // 전체 너비 사용하여 텍스트 정렬이 적용되도록 함
|
|
1238
|
+
});
|
|
1239
|
+
if (textContent) {
|
|
1240
|
+
adElement.appendChild(textContent);
|
|
1241
|
+
}
|
|
1242
|
+
// 사용자가 text-align을 지정했는지 확인하고 레이아웃 조정
|
|
1243
|
+
setTimeout(() => {
|
|
1244
|
+
if (!adElement || typeof window === 'undefined')
|
|
1245
|
+
return;
|
|
1246
|
+
const computedStyle = window.getComputedStyle(adElement);
|
|
1247
|
+
const textAlign = computedStyle.textAlign;
|
|
1248
|
+
// 사용자가 text-align을 설정했고, width가 없는 경우
|
|
1249
|
+
if (textAlign && textAlign !== 'start' && textAlign !== 'left' && (!slot.width || slot.width === 0)) {
|
|
1250
|
+
// 블록 레벨로 변경하여 text-align이 제대로 작동하도록 함
|
|
1251
|
+
adElement.style.display = 'block';
|
|
1252
|
+
adElement.style.whiteSpace = 'normal';
|
|
1253
|
+
// 최소 너비 설정 (텍스트가 한 줄일 때를 위해)
|
|
1254
|
+
if (textContent) {
|
|
1255
|
+
const textRect = textContent.getBoundingClientRect();
|
|
1256
|
+
if (textRect.width > 0) {
|
|
1257
|
+
adElement.style.minWidth = `${textRect.width}px`;
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
}
|
|
1261
|
+
}, 0);
|
|
1262
|
+
// 클릭 이벤트 추가
|
|
1263
|
+
this.addClickHandler(adElement, ad, slot);
|
|
1264
|
+
return adElement;
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1268
|
+
/**
|
|
1269
|
+
* 네이티브 광고 렌더러 - 이미지 + textContent 표시
|
|
1270
|
+
*/
|
|
1271
|
+
class NativeAdRenderer extends BaseAdRenderer {
|
|
1272
|
+
render(ad, slot) {
|
|
1273
|
+
const adElement = DOMUtils.safeCreateElement('div');
|
|
1274
|
+
if (!adElement) {
|
|
1275
|
+
return document.createElement('div');
|
|
1276
|
+
}
|
|
1277
|
+
// 컨테이너 스타일 적용 (불필요한 스타일 제거)
|
|
1278
|
+
this.applyStyles(adElement, this.getBaseContainerStyles(slot));
|
|
1279
|
+
// 네이티브 광고는 이미지만 표시
|
|
1280
|
+
if (!ad.imageUrl) {
|
|
1281
|
+
// 이미지가 없는 경우 플레이스홀더 반환
|
|
1282
|
+
const placeholder = this.createPlaceholder(slot, '네이티브 광고');
|
|
1283
|
+
return placeholder || adElement;
|
|
1284
|
+
}
|
|
1285
|
+
// 이미지 생성 (고유 사이즈 또는 사용자 지정 크기)
|
|
1286
|
+
const img = this.createImageElement(ad.imageUrl, '', slot);
|
|
1287
|
+
if (img) {
|
|
1288
|
+
DOMUtils.safeAppendChild(adElement, img);
|
|
1289
|
+
// 클릭 이벤트 추가
|
|
1290
|
+
this.addClickHandler(adElement, ad, slot);
|
|
1291
|
+
}
|
|
1292
|
+
return adElement;
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
|
|
1296
|
+
/**
|
|
1297
|
+
* 비디오 광고 렌더러 - 비디오 또는 이미지 표시
|
|
1298
|
+
*/
|
|
1299
|
+
class VideoAdRenderer extends BaseAdRenderer {
|
|
1300
|
+
render(ad, slot) {
|
|
1301
|
+
let adElement = DOMUtils.safeCreateElement('div');
|
|
1302
|
+
if (!adElement) {
|
|
1303
|
+
return this.createPlaceholder(slot, '비디오 광고');
|
|
1304
|
+
}
|
|
1305
|
+
// 컨테이너 스타일 적용 (불필요한 스타일 제거)
|
|
1306
|
+
this.applyStyles(adElement, {
|
|
1307
|
+
...this.getBaseContainerStyles(slot),
|
|
1308
|
+
background: '#000',
|
|
1309
|
+
});
|
|
1310
|
+
// 비디오 광고는 비디오만 표시
|
|
1311
|
+
if (!ad.videoUrl) {
|
|
1312
|
+
// 비디오가 없는 경우 플레이스홀더 반환
|
|
1313
|
+
return this.createPlaceholder(slot, '비디오 광고');
|
|
1314
|
+
}
|
|
1315
|
+
const video = this.createVideoElement(ad.videoUrl, ad, slot);
|
|
1316
|
+
if (video) {
|
|
1317
|
+
adElement.appendChild(video);
|
|
1318
|
+
}
|
|
1319
|
+
// 클릭 이벤트 추가
|
|
1320
|
+
this.addClickHandler(adElement, ad, slot);
|
|
1321
|
+
return adElement;
|
|
1322
|
+
}
|
|
1323
|
+
/**
|
|
1324
|
+
* 비디오 요소 생성
|
|
1325
|
+
*/
|
|
1326
|
+
createVideoElement(videoUrl, ad, slot) {
|
|
1327
|
+
const video = DOMUtils.safeCreateElement('video');
|
|
1328
|
+
if (!video)
|
|
1329
|
+
return null;
|
|
1330
|
+
video.src = videoUrl;
|
|
1331
|
+
video.controls = true;
|
|
1332
|
+
// 비디오도 이미지와 같은 스타일 적용
|
|
1333
|
+
this.applyStyles(video, this.getImageStyles(slot));
|
|
1334
|
+
// 비디오 이벤트 추적
|
|
1335
|
+
video.addEventListener('play', () => {
|
|
1336
|
+
this.trackEvent?.(ad._id, slot.id, 'VIDEO_START');
|
|
1337
|
+
});
|
|
1338
|
+
video.addEventListener('ended', () => {
|
|
1339
|
+
this.trackEvent?.(ad._id, slot.id, 'VIDEO_COMPLETE');
|
|
1340
|
+
});
|
|
1341
|
+
return video;
|
|
1342
|
+
}
|
|
1343
|
+
}
|
|
1344
|
+
|
|
1345
|
+
/**
|
|
1346
|
+
* 전면/팝업 광고 렌더러 - 핵심 콘텐츠만 표시
|
|
1347
|
+
*/
|
|
1348
|
+
class InterstitialAdRenderer extends BaseAdRenderer {
|
|
1349
|
+
render(ad, slot) {
|
|
1350
|
+
let adElement = DOMUtils.safeCreateElement('div');
|
|
1351
|
+
if (!adElement) {
|
|
1352
|
+
return this.createPlaceholder(slot, '전면 광고');
|
|
1353
|
+
}
|
|
1354
|
+
// 컨테이너 스타일 적용 (불필요한 스타일 제거)
|
|
1355
|
+
this.applyStyles(adElement, {
|
|
1356
|
+
...this.getBaseContainerStyles(slot),
|
|
1357
|
+
display: 'flex',
|
|
1358
|
+
'flex-direction': 'column',
|
|
1359
|
+
});
|
|
1360
|
+
// 우선순위: 1. 이미지, 2. 비디오, 3. 텍스트
|
|
1361
|
+
if (ad.imageUrl) {
|
|
1362
|
+
const img = this.createImageElement(ad.imageUrl, '', slot);
|
|
1363
|
+
if (img) {
|
|
1364
|
+
adElement.appendChild(img);
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
1367
|
+
else if (ad.videoUrl) {
|
|
1368
|
+
// 이미지가 없고 비디오가 있는 경우
|
|
1369
|
+
const video = this.createVideoElement(ad.videoUrl, ad, slot);
|
|
1370
|
+
if (video) {
|
|
1371
|
+
adElement.appendChild(video);
|
|
1372
|
+
}
|
|
1373
|
+
}
|
|
1374
|
+
else {
|
|
1375
|
+
// 모든 콘텐츠가 없는 경우
|
|
1376
|
+
return this.createPlaceholder(slot, '전면 광고');
|
|
1377
|
+
}
|
|
1378
|
+
// 클릭 이벤트 추가
|
|
1379
|
+
this.addClickHandler(adElement, ad, slot);
|
|
1380
|
+
return adElement;
|
|
1381
|
+
}
|
|
1382
|
+
/**
|
|
1383
|
+
* 비디오 요소 생성
|
|
1384
|
+
*/
|
|
1385
|
+
createVideoElement(videoUrl, ad, slot) {
|
|
1386
|
+
const video = DOMUtils.safeCreateElement('video');
|
|
1387
|
+
if (!video)
|
|
1388
|
+
return null;
|
|
1389
|
+
video.src = videoUrl;
|
|
1390
|
+
video.controls = true;
|
|
1391
|
+
// 비디오도 이미지와 같은 스타일 적용
|
|
1392
|
+
this.applyStyles(video, this.getImageStyles(slot));
|
|
1393
|
+
// 비디오 이벤트 추적
|
|
1394
|
+
video.addEventListener('play', () => {
|
|
1395
|
+
this.trackEvent?.(ad._id, slot.id, 'VIDEO_START');
|
|
1396
|
+
});
|
|
1397
|
+
video.addEventListener('ended', () => {
|
|
1398
|
+
this.trackEvent?.(ad._id, slot.id, 'VIDEO_COMPLETE');
|
|
1399
|
+
});
|
|
1400
|
+
return video;
|
|
1401
|
+
}
|
|
1402
|
+
}
|
|
1403
|
+
|
|
1404
|
+
var _a;
|
|
1405
|
+
/**
|
|
1406
|
+
* 광고 렌더러 팩토리
|
|
1407
|
+
* - 광고 타입에 따라 적절한 렌더러 인스턴스를 반환
|
|
1408
|
+
*/
|
|
1409
|
+
class AdRendererFactory {
|
|
1410
|
+
/**
|
|
1411
|
+
* 광고 타입에 맞는 렌더러 생성
|
|
1412
|
+
*/
|
|
1413
|
+
static createRenderer(adType, trackEvent) {
|
|
1414
|
+
const RendererClass = this.renderers.get(adType);
|
|
1415
|
+
if (!RendererClass) {
|
|
1416
|
+
console.warn(`No renderer found for ad type: ${adType}, falling back to Banner renderer`);
|
|
1417
|
+
return new BannerAdRenderer(trackEvent);
|
|
1418
|
+
}
|
|
1419
|
+
return new RendererClass(trackEvent);
|
|
1420
|
+
}
|
|
1421
|
+
/**
|
|
1422
|
+
* 광고 렌더링 (편의 메서드)
|
|
1423
|
+
*/
|
|
1424
|
+
static render(ad, slot, trackEvent) {
|
|
1425
|
+
const renderer = this.createRenderer(slot.adType, trackEvent);
|
|
1426
|
+
return renderer.render(ad, slot);
|
|
1427
|
+
}
|
|
1428
|
+
/**
|
|
1429
|
+
* 사용 가능한 렌더러 타입 목록
|
|
1430
|
+
*/
|
|
1431
|
+
static getSupportedAdTypes() {
|
|
1432
|
+
return Array.from(this.renderers.keys());
|
|
1433
|
+
}
|
|
1434
|
+
/**
|
|
1435
|
+
* 커스텀 렌더러 등록
|
|
1436
|
+
*/
|
|
1437
|
+
static registerRenderer(adType, RendererClass) {
|
|
1438
|
+
this.renderers.set(adType, RendererClass);
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
_a = AdRendererFactory;
|
|
1442
|
+
AdRendererFactory.renderers = new Map();
|
|
1443
|
+
(() => {
|
|
1444
|
+
// 렌더러 등록
|
|
1445
|
+
_a.renderers.set(AdType.BANNER, BannerAdRenderer);
|
|
1446
|
+
_a.renderers.set(AdType.TEXT, TextAdRenderer);
|
|
771
1447
|
_a.renderers.set(AdType.NATIVE, NativeAdRenderer);
|
|
772
1448
|
_a.renderers.set(AdType.VIDEO, VideoAdRenderer);
|
|
773
1449
|
_a.renderers.set(AdType.INTERSTITIAL, InterstitialAdRenderer);
|
|
@@ -805,12 +1481,11 @@ class CarouselSliderManager {
|
|
|
805
1481
|
width = `${slot.width}px`;
|
|
806
1482
|
}
|
|
807
1483
|
containerStyles.width = width;
|
|
808
|
-
containerStyles.display = 'block'; //
|
|
1484
|
+
containerStyles.display = 'inline-block'; // 지정된 크기에 맞춤 (좌측 정렬)
|
|
809
1485
|
}
|
|
810
1486
|
else {
|
|
811
|
-
// 컨텐츠 크기에 맞춤
|
|
812
|
-
containerStyles.display = 'block';
|
|
813
|
-
containerStyles.width = 'fit-content'; // 컨텐츠 크기에 맞춤
|
|
1487
|
+
// 컨텐츠 크기에 맞춤
|
|
1488
|
+
containerStyles.display = 'inline-block';
|
|
814
1489
|
}
|
|
815
1490
|
if (slot.height && slot.height !== 0) {
|
|
816
1491
|
const height = typeof slot.height === 'string' ? slot.height : `${slot.height}px`;
|
|
@@ -919,7 +1594,7 @@ class CarouselSliderManager {
|
|
|
919
1594
|
let currentSlide = 0;
|
|
920
1595
|
const totalSlides = advertisements.length;
|
|
921
1596
|
const autoSlideInterval = (options?.autoSlideInterval || 3) * 1000; // 기본 3초
|
|
922
|
-
// 슬라이드 이동 함수 (무한 루프 지원
|
|
1597
|
+
// 슬라이드 이동 함수 (무한 루프 지원)
|
|
923
1598
|
const moveToSlide = (index, instant = false) => {
|
|
924
1599
|
currentSlide = index;
|
|
925
1600
|
// 애니메이션 임시 비활성화 (무한 루프용)
|
|
@@ -931,33 +1606,6 @@ class CarouselSliderManager {
|
|
|
931
1606
|
}
|
|
932
1607
|
// 항상 퍼센트 기반으로 이동
|
|
933
1608
|
slideContainer.style.transform = `translateX(-${(100 / extendedAds.length) * currentSlide}%)`;
|
|
934
|
-
// 🆕 동적 높이 조정: 현재 슬라이드의 이미지 높이에 맞춰 컨테이너 높이 조정
|
|
935
|
-
if (!instant && !slot.height && !slot.width) { // 사용자가 크기를 지정하지 않은 경우에만
|
|
936
|
-
const currentSlideElement = slideContainer.children[currentSlide];
|
|
937
|
-
if (currentSlideElement) {
|
|
938
|
-
const currentAdElement = currentSlideElement.children[0];
|
|
939
|
-
if (currentAdElement) {
|
|
940
|
-
// 이미지 요소 찾기
|
|
941
|
-
const imgElement = currentAdElement.querySelector('img');
|
|
942
|
-
if (imgElement) {
|
|
943
|
-
// 이미지 로드 완료 후 높이 조정
|
|
944
|
-
const adjustHeight = () => {
|
|
945
|
-
const imgHeight = imgElement.getBoundingClientRect().height;
|
|
946
|
-
if (imgHeight > 0) {
|
|
947
|
-
sliderWrapper.style.height = `${imgHeight}px`;
|
|
948
|
-
sliderWrapper.style.transition = instant ? 'none' : 'height 0.4s ease-out';
|
|
949
|
-
}
|
|
950
|
-
};
|
|
951
|
-
if (imgElement.complete && imgElement.naturalHeight > 0) {
|
|
952
|
-
adjustHeight();
|
|
953
|
-
}
|
|
954
|
-
else {
|
|
955
|
-
imgElement.addEventListener('load', adjustHeight, { once: true });
|
|
956
|
-
}
|
|
957
|
-
}
|
|
958
|
-
}
|
|
959
|
-
}
|
|
960
|
-
}
|
|
961
1609
|
// 도트 업데이트 (무채색 스타일) - 실제 광고 인덱스 기준, 텍스트 광고가 아닐 때만
|
|
962
1610
|
const actualIndex = currentSlide === totalSlides ? 0 : currentSlide;
|
|
963
1611
|
if (dotContainer) {
|
|
@@ -1089,252 +1737,24 @@ class CarouselSliderManager {
|
|
|
1089
1737
|
dot.style.opacity = '0.9';
|
|
1090
1738
|
}
|
|
1091
1739
|
});
|
|
1092
|
-
dot.addEventListener('mouseleave', () => {
|
|
1093
|
-
if (!dot.classList.contains('active')) {
|
|
1094
|
-
dot.style.borderColor = '#cccccc';
|
|
1095
|
-
dot.style.opacity = '0.7';
|
|
1096
|
-
}
|
|
1097
|
-
});
|
|
1098
|
-
dotContainer.appendChild(dot);
|
|
1099
|
-
}
|
|
1100
|
-
return dotContainer;
|
|
1101
|
-
}
|
|
1102
|
-
/**
|
|
1103
|
-
* 터치 제스처 지원 추가
|
|
1104
|
-
*/
|
|
1105
|
-
static addTouchSupport(container, moveToSlide, getCurrentSlide, totalSlides, handleInfiniteLoop) {
|
|
1106
|
-
let startX = 0;
|
|
1107
|
-
let isDragging = false;
|
|
1108
|
-
container.addEventListener('touchstart', (e) => {
|
|
1109
|
-
startX = e.touches[0].clientX;
|
|
1110
|
-
isDragging = true;
|
|
1111
|
-
});
|
|
1112
|
-
container.addEventListener('touchmove', (e) => {
|
|
1113
|
-
if (!isDragging)
|
|
1114
|
-
return;
|
|
1115
|
-
e.preventDefault();
|
|
1116
|
-
});
|
|
1117
|
-
container.addEventListener('touchend', (e) => {
|
|
1118
|
-
if (!isDragging)
|
|
1119
|
-
return;
|
|
1120
|
-
isDragging = false;
|
|
1121
|
-
const endX = e.changedTouches[0].clientX;
|
|
1122
|
-
const diff = startX - endX;
|
|
1123
|
-
if (Math.abs(diff) > 50) { // 50px 이상 스와이프 시
|
|
1124
|
-
const currentSlide = getCurrentSlide();
|
|
1125
|
-
if (diff > 0) {
|
|
1126
|
-
// 왼쪽으로 스와이프 (다음 슬라이드)
|
|
1127
|
-
const nextIndex = currentSlide + 1;
|
|
1128
|
-
moveToSlide(nextIndex);
|
|
1129
|
-
if (handleInfiniteLoop) {
|
|
1130
|
-
handleInfiniteLoop();
|
|
1131
|
-
}
|
|
1132
|
-
}
|
|
1133
|
-
else {
|
|
1134
|
-
// 오른쪽으로 스와이프 (이전 슬라이드)
|
|
1135
|
-
const prevIndex = currentSlide > 0 ? currentSlide - 1 : totalSlides - 1;
|
|
1136
|
-
moveToSlide(prevIndex);
|
|
1137
|
-
}
|
|
1138
|
-
}
|
|
1139
|
-
});
|
|
1140
|
-
}
|
|
1141
|
-
}
|
|
1142
|
-
|
|
1143
|
-
/**
|
|
1144
|
-
* 텍스트 전환 효과 관리 클래스
|
|
1145
|
-
* - 텍스트 광고 전용 페이드 인/아웃 + 상하 움직임 효과
|
|
1146
|
-
* - 부드러운 전환 애니메이션 (vertical transition)
|
|
1147
|
-
* - 무한 루프 지원
|
|
1148
|
-
*/
|
|
1149
|
-
class TextTransitionManager {
|
|
1150
|
-
/**
|
|
1151
|
-
* 텍스트 전환 슬라이더 컨테이너 생성
|
|
1152
|
-
*/
|
|
1153
|
-
static createTextTransitionContainer(slot, advertisements, options, trackEventCallback) {
|
|
1154
|
-
const sliderWrapper = document.createElement('div');
|
|
1155
|
-
sliderWrapper.className = 'adstage-fade-slider-wrapper';
|
|
1156
|
-
// 래퍼 스타일 설정
|
|
1157
|
-
const containerStyles = {
|
|
1158
|
-
position: 'relative',
|
|
1159
|
-
overflow: 'hidden',
|
|
1160
|
-
display: 'block', // ✅ 하단 공백 제거를 위해 block 사용
|
|
1161
|
-
width: 'fit-content', // 컨텐츠 크기에 맞춤
|
|
1162
|
-
};
|
|
1163
|
-
// 사용자가 크기를 지정한 경우
|
|
1164
|
-
if (slot.width && slot.width !== 0) {
|
|
1165
|
-
let width;
|
|
1166
|
-
if (typeof slot.width === 'string') {
|
|
1167
|
-
width = slot.width.includes('px') || slot.width.includes('%') ? slot.width : `${slot.width}px`;
|
|
1168
|
-
}
|
|
1169
|
-
else {
|
|
1170
|
-
width = `${slot.width}px`;
|
|
1171
|
-
}
|
|
1172
|
-
containerStyles.width = width;
|
|
1173
|
-
}
|
|
1174
|
-
if (slot.height && slot.height !== 0) {
|
|
1175
|
-
let height;
|
|
1176
|
-
if (typeof slot.height === 'string') {
|
|
1177
|
-
height = slot.height.includes('px') || slot.height.includes('%') ? slot.height : `${slot.height}px`;
|
|
1178
|
-
}
|
|
1179
|
-
else {
|
|
1180
|
-
height = `${slot.height}px`;
|
|
1181
|
-
}
|
|
1182
|
-
containerStyles.height = height;
|
|
1183
|
-
}
|
|
1184
|
-
// 스타일 적용
|
|
1185
|
-
Object.entries(containerStyles).forEach(([key, value]) => {
|
|
1186
|
-
sliderWrapper.style.setProperty(key, value);
|
|
1187
|
-
});
|
|
1188
|
-
// 슬라이드 컨테이너
|
|
1189
|
-
const slideContainer = document.createElement('div');
|
|
1190
|
-
slideContainer.className = 'adstage-fade-slide-container';
|
|
1191
|
-
slideContainer.style.cssText = `
|
|
1192
|
-
position: relative;
|
|
1193
|
-
width: 100%;
|
|
1194
|
-
height: 100%;
|
|
1195
|
-
`;
|
|
1196
|
-
// 크기 측정을 위한 임시 컨테이너 (자동 크기 계산이 필요한 경우)
|
|
1197
|
-
let measureContainer = null;
|
|
1198
|
-
const needsWidthMeasurement = !slot.width || slot.width === 0;
|
|
1199
|
-
const needsHeightMeasurement = !slot.height || slot.height === 0;
|
|
1200
|
-
if (needsWidthMeasurement || needsHeightMeasurement) {
|
|
1201
|
-
measureContainer = document.createElement('div');
|
|
1202
|
-
measureContainer.style.cssText = `
|
|
1203
|
-
position: absolute;
|
|
1204
|
-
visibility: hidden;
|
|
1205
|
-
white-space: nowrap;
|
|
1206
|
-
top: -9999px;
|
|
1207
|
-
left: -9999px;
|
|
1208
|
-
`;
|
|
1209
|
-
// width가 설정되어 있으면 측정 컨테이너에도 적용
|
|
1210
|
-
if (!needsWidthMeasurement && slot.width) {
|
|
1211
|
-
let width;
|
|
1212
|
-
if (typeof slot.width === 'string') {
|
|
1213
|
-
width = slot.width.includes('px') || slot.width.includes('%') ? slot.width : `${slot.width}px`;
|
|
1214
|
-
}
|
|
1215
|
-
else {
|
|
1216
|
-
width = `${slot.width}px`;
|
|
1217
|
-
}
|
|
1218
|
-
measureContainer.style.width = width;
|
|
1219
|
-
measureContainer.style.whiteSpace = 'normal'; // width가 있으면 줄바꿈 허용
|
|
1220
|
-
}
|
|
1221
|
-
document.body.appendChild(measureContainer);
|
|
1222
|
-
let maxWidth = 0;
|
|
1223
|
-
let maxHeight = 0;
|
|
1224
|
-
// 모든 광고의 크기를 측정하여 최대 크기 찾기
|
|
1225
|
-
advertisements.forEach(ad => {
|
|
1226
|
-
const measureAdElement = AdRendererFactory.render(ad, slot, trackEventCallback);
|
|
1227
|
-
measureContainer.appendChild(measureAdElement);
|
|
1228
|
-
const rect = measureAdElement.getBoundingClientRect();
|
|
1229
|
-
if (rect.width > maxWidth)
|
|
1230
|
-
maxWidth = rect.width;
|
|
1231
|
-
if (rect.height > maxHeight)
|
|
1232
|
-
maxHeight = rect.height;
|
|
1233
|
-
// 측정 후 요소 제거
|
|
1234
|
-
measureContainer.removeChild(measureAdElement);
|
|
1235
|
-
});
|
|
1236
|
-
// 측정된 최대 크기로 래퍼 크기 설정
|
|
1237
|
-
if (needsWidthMeasurement && maxWidth > 0) {
|
|
1238
|
-
sliderWrapper.style.width = `${maxWidth}px`;
|
|
1239
|
-
}
|
|
1240
|
-
if (needsHeightMeasurement && maxHeight > 0) {
|
|
1241
|
-
sliderWrapper.style.height = `${maxHeight}px`;
|
|
1242
|
-
}
|
|
1243
|
-
// 측정 컨테이너 제거
|
|
1244
|
-
document.body.removeChild(measureContainer);
|
|
1245
|
-
}
|
|
1246
|
-
// 각 광고를 슬라이드로 생성
|
|
1247
|
-
const slideElements = [];
|
|
1248
|
-
advertisements.forEach((ad, index) => {
|
|
1249
|
-
const slideElement = document.createElement('div');
|
|
1250
|
-
slideElement.className = 'adstage-fade-slide';
|
|
1251
|
-
slideElement.style.cssText = `
|
|
1252
|
-
position: absolute;
|
|
1253
|
-
top: 0;
|
|
1254
|
-
left: 0;
|
|
1255
|
-
width: 100%;
|
|
1256
|
-
height: 100%;
|
|
1257
|
-
display: flex;
|
|
1258
|
-
align-items: center;
|
|
1259
|
-
justify-content: center;
|
|
1260
|
-
opacity: ${index === 0 ? '1' : '0'};
|
|
1261
|
-
transform: translateY(${index === 0 ? '0' : '20px'});
|
|
1262
|
-
transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1);
|
|
1263
|
-
z-index: ${index === 0 ? '2' : '1'};
|
|
1264
|
-
`;
|
|
1265
|
-
// 광고 렌더링
|
|
1266
|
-
const adElement = AdRendererFactory.render(ad, slot, trackEventCallback);
|
|
1267
|
-
slideElement.appendChild(adElement);
|
|
1268
|
-
slideContainer.appendChild(slideElement);
|
|
1269
|
-
slideElements.push(slideElement);
|
|
1270
|
-
});
|
|
1271
|
-
// 슬라이더 상태 관리
|
|
1272
|
-
let currentSlide = 0;
|
|
1273
|
-
const totalSlides = advertisements.length;
|
|
1274
|
-
const autoSlideInterval = (options?.autoSlideInterval || 4) * 1000; // 기본 4초 (페이드는 조금 더 길게)
|
|
1275
|
-
// 슬라이드 이동 함수 (페이드 효과)
|
|
1276
|
-
const moveToSlide = (index) => {
|
|
1277
|
-
if (index >= totalSlides) {
|
|
1278
|
-
index = 0; // 무한 루프
|
|
1279
|
-
}
|
|
1280
|
-
else if (index < 0) {
|
|
1281
|
-
index = totalSlides - 1;
|
|
1282
|
-
}
|
|
1283
|
-
const previousSlide = slideElements[currentSlide];
|
|
1284
|
-
const nextSlide = slideElements[index];
|
|
1285
|
-
// 이전 슬라이드 페이드 아웃 (아래로)
|
|
1286
|
-
previousSlide.style.opacity = '0';
|
|
1287
|
-
previousSlide.style.transform = 'translateY(-20px)';
|
|
1288
|
-
previousSlide.style.zIndex = '1';
|
|
1289
|
-
// 다음 슬라이드 페이드 인 (위에서)
|
|
1290
|
-
nextSlide.style.opacity = '1';
|
|
1291
|
-
nextSlide.style.transform = 'translateY(0)';
|
|
1292
|
-
nextSlide.style.zIndex = '2';
|
|
1293
|
-
// 다른 슬라이드들은 숨김
|
|
1294
|
-
slideElements.forEach((slide, i) => {
|
|
1295
|
-
if (i !== index && i !== currentSlide) {
|
|
1296
|
-
slide.style.opacity = '0';
|
|
1297
|
-
slide.style.transform = 'translateY(20px)';
|
|
1298
|
-
slide.style.zIndex = '1';
|
|
1299
|
-
}
|
|
1300
|
-
});
|
|
1301
|
-
currentSlide = index;
|
|
1302
|
-
// 현재 슬라이드의 광고에 대해 노출 이벤트 추적
|
|
1303
|
-
if (currentSlide > 0) { // 첫 번째는 이미 loadSlot에서 추적됨
|
|
1304
|
-
trackEventCallback(advertisements[currentSlide]._id, slot.id, AdEventType.VIEWABLE);
|
|
1305
|
-
}
|
|
1306
|
-
};
|
|
1307
|
-
// 자동 슬라이드
|
|
1308
|
-
let autoSlideTimer = setInterval(() => {
|
|
1309
|
-
const nextIndex = currentSlide + 1;
|
|
1310
|
-
moveToSlide(nextIndex);
|
|
1311
|
-
}, autoSlideInterval);
|
|
1312
|
-
// 마우스 호버 시 자동 슬라이드 일시정지
|
|
1313
|
-
sliderWrapper.addEventListener('mouseenter', () => {
|
|
1314
|
-
clearInterval(autoSlideTimer);
|
|
1315
|
-
});
|
|
1316
|
-
sliderWrapper.addEventListener('mouseleave', () => {
|
|
1317
|
-
autoSlideTimer = setInterval(() => {
|
|
1318
|
-
const nextIndex = currentSlide + 1;
|
|
1319
|
-
moveToSlide(nextIndex);
|
|
1320
|
-
}, autoSlideInterval);
|
|
1321
|
-
});
|
|
1322
|
-
// 터치 제스처 지원
|
|
1323
|
-
TextTransitionManager.addTouchSupport(sliderWrapper, moveToSlide, () => currentSlide, totalSlides);
|
|
1324
|
-
// 요소들 조립
|
|
1325
|
-
sliderWrapper.appendChild(slideContainer);
|
|
1326
|
-
return sliderWrapper;
|
|
1740
|
+
dot.addEventListener('mouseleave', () => {
|
|
1741
|
+
if (!dot.classList.contains('active')) {
|
|
1742
|
+
dot.style.borderColor = '#cccccc';
|
|
1743
|
+
dot.style.opacity = '0.7';
|
|
1744
|
+
}
|
|
1745
|
+
});
|
|
1746
|
+
dotContainer.appendChild(dot);
|
|
1747
|
+
}
|
|
1748
|
+
return dotContainer;
|
|
1327
1749
|
}
|
|
1328
1750
|
/**
|
|
1329
1751
|
* 터치 제스처 지원 추가
|
|
1330
1752
|
*/
|
|
1331
|
-
static addTouchSupport(container, moveToSlide, getCurrentSlide, totalSlides) {
|
|
1753
|
+
static addTouchSupport(container, moveToSlide, getCurrentSlide, totalSlides, handleInfiniteLoop) {
|
|
1332
1754
|
let startX = 0;
|
|
1333
|
-
let startY = 0;
|
|
1334
1755
|
let isDragging = false;
|
|
1335
1756
|
container.addEventListener('touchstart', (e) => {
|
|
1336
1757
|
startX = e.touches[0].clientX;
|
|
1337
|
-
startY = e.touches[0].clientY;
|
|
1338
1758
|
isDragging = true;
|
|
1339
1759
|
});
|
|
1340
1760
|
container.addEventListener('touchmove', (e) => {
|
|
@@ -1347,19 +1767,21 @@ class TextTransitionManager {
|
|
|
1347
1767
|
return;
|
|
1348
1768
|
isDragging = false;
|
|
1349
1769
|
const endX = e.changedTouches[0].clientX;
|
|
1350
|
-
const
|
|
1351
|
-
|
|
1352
|
-
const diffY = startY - endY;
|
|
1353
|
-
// 가로 스와이프가 세로 스와이프보다 클 때만 처리
|
|
1354
|
-
if (Math.abs(diffX) > Math.abs(diffY) && Math.abs(diffX) > 50) {
|
|
1770
|
+
const diff = startX - endX;
|
|
1771
|
+
if (Math.abs(diff) > 50) { // 50px 이상 스와이프 시
|
|
1355
1772
|
const currentSlide = getCurrentSlide();
|
|
1356
|
-
if (
|
|
1773
|
+
if (diff > 0) {
|
|
1357
1774
|
// 왼쪽으로 스와이프 (다음 슬라이드)
|
|
1358
|
-
|
|
1775
|
+
const nextIndex = currentSlide + 1;
|
|
1776
|
+
moveToSlide(nextIndex);
|
|
1777
|
+
if (handleInfiniteLoop) {
|
|
1778
|
+
handleInfiniteLoop();
|
|
1779
|
+
}
|
|
1359
1780
|
}
|
|
1360
1781
|
else {
|
|
1361
1782
|
// 오른쪽으로 스와이프 (이전 슬라이드)
|
|
1362
|
-
|
|
1783
|
+
const prevIndex = currentSlide > 0 ? currentSlide - 1 : totalSlides - 1;
|
|
1784
|
+
moveToSlide(prevIndex);
|
|
1363
1785
|
}
|
|
1364
1786
|
}
|
|
1365
1787
|
});
|
|
@@ -1367,698 +1789,844 @@ class TextTransitionManager {
|
|
|
1367
1789
|
}
|
|
1368
1790
|
|
|
1369
1791
|
/**
|
|
1370
|
-
*
|
|
1371
|
-
* -
|
|
1372
|
-
* -
|
|
1373
|
-
* -
|
|
1374
|
-
* - ViewabilityTracker와 함께 사용하여 중복 viewable 이벤트 방지
|
|
1792
|
+
* 텍스트 전환 효과 관리 클래스
|
|
1793
|
+
* - 텍스트 광고 전용 페이드 인/아웃 + 상하 움직임 효과
|
|
1794
|
+
* - 부드러운 전환 애니메이션 (vertical transition)
|
|
1795
|
+
* - 무한 루프 지원
|
|
1375
1796
|
*/
|
|
1376
|
-
class
|
|
1797
|
+
class TextTransitionManager {
|
|
1377
1798
|
/**
|
|
1378
|
-
*
|
|
1799
|
+
* 텍스트 전환 슬라이더 컨테이너 생성
|
|
1379
1800
|
*/
|
|
1380
|
-
static
|
|
1381
|
-
const
|
|
1382
|
-
|
|
1383
|
-
//
|
|
1384
|
-
const
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1801
|
+
static createTextTransitionContainer(slot, advertisements, options, trackEventCallback) {
|
|
1802
|
+
const sliderWrapper = document.createElement('div');
|
|
1803
|
+
sliderWrapper.className = 'adstage-fade-slider-wrapper';
|
|
1804
|
+
// 래퍼 스타일 설정
|
|
1805
|
+
const containerStyles = {
|
|
1806
|
+
position: 'relative',
|
|
1807
|
+
overflow: 'hidden',
|
|
1808
|
+
display: 'inline-block',
|
|
1809
|
+
};
|
|
1810
|
+
// 사용자가 크기를 지정한 경우
|
|
1811
|
+
if (slot.width && slot.width !== 0) {
|
|
1812
|
+
let width;
|
|
1813
|
+
if (typeof slot.width === 'string') {
|
|
1814
|
+
width = slot.width.includes('px') || slot.width.includes('%') ? slot.width : `${slot.width}px`;
|
|
1388
1815
|
}
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
// 세션 스토리지 기반 중복 확인 (새로고침 시에도 유지)
|
|
1392
|
-
const sessionKey = `adstage_viewable_${key}`;
|
|
1393
|
-
const sessionViewable = sessionStorage.getItem(sessionKey);
|
|
1394
|
-
if (sessionViewable) {
|
|
1395
|
-
const sessionTime = parseInt(sessionViewable, 10);
|
|
1396
|
-
if (!isNaN(sessionTime) && (now - sessionTime) < ViewableEventTracker.VIEWABLE_COOLDOWN) {
|
|
1397
|
-
if (debug) {
|
|
1398
|
-
console.log(`Session-based duplicate viewable blocked for ad ${adId} in slot ${slotId}. Cooldown: ${Math.round((ViewableEventTracker.VIEWABLE_COOLDOWN - (now - sessionTime)) / 1000)}s remaining`);
|
|
1399
|
-
}
|
|
1400
|
-
// 메모리에도 기록하여 이후 요청 최적화
|
|
1401
|
-
ViewableEventTracker.viewableTracker.set(key, sessionTime);
|
|
1402
|
-
return true;
|
|
1816
|
+
else {
|
|
1817
|
+
width = `${slot.width}px`;
|
|
1403
1818
|
}
|
|
1819
|
+
containerStyles.width = width;
|
|
1404
1820
|
}
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
console.log(`🎯 New viewable event allowed for ad ${adId} in slot ${slotId}`);
|
|
1410
|
-
}
|
|
1411
|
-
// 오래된 세션 스토리지 데이터 정리 (선택적)
|
|
1412
|
-
ViewableEventTracker.cleanupOldViewables();
|
|
1413
|
-
return false;
|
|
1414
|
-
}
|
|
1415
|
-
/**
|
|
1416
|
-
* 오래된 viewable 추적 데이터 정리
|
|
1417
|
-
*/
|
|
1418
|
-
static cleanupOldViewables() {
|
|
1419
|
-
const now = Date.now();
|
|
1420
|
-
const cleanupThreshold = ViewableEventTracker.VIEWABLE_COOLDOWN * 2; // 쿨다운의 2배 시간이 지난 데이터 정리
|
|
1421
|
-
// 세션 스토리지 정리
|
|
1422
|
-
for (let i = 0; i < sessionStorage.length; i++) {
|
|
1423
|
-
const key = sessionStorage.key(i);
|
|
1424
|
-
if (key && key.startsWith('adstage_viewable_')) {
|
|
1425
|
-
const timestamp = sessionStorage.getItem(key);
|
|
1426
|
-
if (timestamp) {
|
|
1427
|
-
const time = parseInt(timestamp, 10);
|
|
1428
|
-
if (!isNaN(time) && (now - time) > cleanupThreshold) {
|
|
1429
|
-
sessionStorage.removeItem(key);
|
|
1430
|
-
i--; // 인덱스 조정
|
|
1431
|
-
}
|
|
1432
|
-
}
|
|
1821
|
+
if (slot.height && slot.height !== 0) {
|
|
1822
|
+
let height;
|
|
1823
|
+
if (typeof slot.height === 'string') {
|
|
1824
|
+
height = slot.height.includes('px') || slot.height.includes('%') ? slot.height : `${slot.height}px`;
|
|
1433
1825
|
}
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
for (const [key, timestamp] of ViewableEventTracker.viewableTracker.entries()) {
|
|
1437
|
-
if ((now - timestamp) > cleanupThreshold) {
|
|
1438
|
-
ViewableEventTracker.viewableTracker.delete(key);
|
|
1826
|
+
else {
|
|
1827
|
+
height = `${slot.height}px`;
|
|
1439
1828
|
}
|
|
1829
|
+
containerStyles.height = height;
|
|
1440
1830
|
}
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1831
|
+
// 스타일 적용
|
|
1832
|
+
Object.entries(containerStyles).forEach(([key, value]) => {
|
|
1833
|
+
sliderWrapper.style.setProperty(key, value);
|
|
1834
|
+
});
|
|
1835
|
+
// 슬라이드 컨테이너
|
|
1836
|
+
const slideContainer = document.createElement('div');
|
|
1837
|
+
slideContainer.className = 'adstage-fade-slide-container';
|
|
1838
|
+
slideContainer.style.cssText = `
|
|
1839
|
+
position: relative;
|
|
1840
|
+
width: 100%;
|
|
1841
|
+
height: 100%;
|
|
1842
|
+
`;
|
|
1843
|
+
// 크기 측정을 위한 임시 컨테이너 (자동 크기 계산이 필요한 경우)
|
|
1844
|
+
let measureContainer = null;
|
|
1845
|
+
const needsWidthMeasurement = !slot.width || slot.width === 0;
|
|
1846
|
+
const needsHeightMeasurement = !slot.height || slot.height === 0;
|
|
1847
|
+
if (needsWidthMeasurement || needsHeightMeasurement) {
|
|
1848
|
+
measureContainer = document.createElement('div');
|
|
1849
|
+
measureContainer.style.cssText = `
|
|
1850
|
+
position: absolute;
|
|
1851
|
+
visibility: hidden;
|
|
1852
|
+
white-space: nowrap;
|
|
1853
|
+
top: -9999px;
|
|
1854
|
+
left: -9999px;
|
|
1855
|
+
`;
|
|
1856
|
+
// width가 설정되어 있으면 측정 컨테이너에도 적용
|
|
1857
|
+
if (!needsWidthMeasurement && slot.width) {
|
|
1858
|
+
let width;
|
|
1859
|
+
if (typeof slot.width === 'string') {
|
|
1860
|
+
width = slot.width.includes('px') || slot.width.includes('%') ? slot.width : `${slot.width}px`;
|
|
1861
|
+
}
|
|
1862
|
+
else {
|
|
1863
|
+
width = `${slot.width}px`;
|
|
1864
|
+
}
|
|
1865
|
+
measureContainer.style.width = width;
|
|
1866
|
+
measureContainer.style.whiteSpace = 'normal'; // width가 있으면 줄바꿈 허용
|
|
1867
|
+
}
|
|
1868
|
+
document.body.appendChild(measureContainer);
|
|
1869
|
+
let maxWidth = 0;
|
|
1870
|
+
let maxHeight = 0;
|
|
1871
|
+
// 모든 광고의 크기를 측정하여 최대 크기 찾기
|
|
1872
|
+
advertisements.forEach(ad => {
|
|
1873
|
+
const measureAdElement = AdRendererFactory.render(ad, slot, trackEventCallback);
|
|
1874
|
+
measureContainer.appendChild(measureAdElement);
|
|
1875
|
+
const rect = measureAdElement.getBoundingClientRect();
|
|
1876
|
+
if (rect.width > maxWidth)
|
|
1877
|
+
maxWidth = rect.width;
|
|
1878
|
+
if (rect.height > maxHeight)
|
|
1879
|
+
maxHeight = rect.height;
|
|
1880
|
+
// 측정 후 요소 제거
|
|
1881
|
+
measureContainer.removeChild(measureAdElement);
|
|
1882
|
+
});
|
|
1883
|
+
// 측정된 최대 크기로 래퍼 크기 설정
|
|
1884
|
+
if (needsWidthMeasurement && maxWidth > 0) {
|
|
1885
|
+
sliderWrapper.style.width = `${maxWidth}px`;
|
|
1886
|
+
}
|
|
1887
|
+
if (needsHeightMeasurement && maxHeight > 0) {
|
|
1888
|
+
sliderWrapper.style.height = `${maxHeight}px`;
|
|
1889
|
+
}
|
|
1890
|
+
// 측정 컨테이너 제거
|
|
1891
|
+
document.body.removeChild(measureContainer);
|
|
1892
|
+
}
|
|
1893
|
+
// 각 광고를 슬라이드로 생성
|
|
1894
|
+
const slideElements = [];
|
|
1895
|
+
advertisements.forEach((ad, index) => {
|
|
1896
|
+
const slideElement = document.createElement('div');
|
|
1897
|
+
slideElement.className = 'adstage-fade-slide';
|
|
1898
|
+
slideElement.style.cssText = `
|
|
1899
|
+
position: absolute;
|
|
1900
|
+
top: 0;
|
|
1901
|
+
left: 0;
|
|
1902
|
+
width: 100%;
|
|
1903
|
+
height: 100%;
|
|
1904
|
+
display: flex;
|
|
1905
|
+
align-items: center;
|
|
1906
|
+
justify-content: center;
|
|
1907
|
+
opacity: ${index === 0 ? '1' : '0'};
|
|
1908
|
+
transform: translateY(${index === 0 ? '0' : '20px'});
|
|
1909
|
+
transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1);
|
|
1910
|
+
z-index: ${index === 0 ? '2' : '1'};
|
|
1911
|
+
`;
|
|
1912
|
+
// 광고 렌더링
|
|
1913
|
+
const adElement = AdRendererFactory.render(ad, slot, trackEventCallback);
|
|
1914
|
+
slideElement.appendChild(adElement);
|
|
1915
|
+
slideContainer.appendChild(slideElement);
|
|
1916
|
+
slideElements.push(slideElement);
|
|
1917
|
+
});
|
|
1918
|
+
// 슬라이더 상태 관리
|
|
1919
|
+
let currentSlide = 0;
|
|
1920
|
+
const totalSlides = advertisements.length;
|
|
1921
|
+
const autoSlideInterval = (options?.autoSlideInterval || 4) * 1000; // 기본 4초 (페이드는 조금 더 길게)
|
|
1922
|
+
// 슬라이드 이동 함수 (페이드 효과)
|
|
1923
|
+
const moveToSlide = (index) => {
|
|
1924
|
+
if (index >= totalSlides) {
|
|
1925
|
+
index = 0; // 무한 루프
|
|
1926
|
+
}
|
|
1927
|
+
else if (index < 0) {
|
|
1928
|
+
index = totalSlides - 1;
|
|
1929
|
+
}
|
|
1930
|
+
const previousSlide = slideElements[currentSlide];
|
|
1931
|
+
const nextSlide = slideElements[index];
|
|
1932
|
+
// 이전 슬라이드 페이드 아웃 (아래로)
|
|
1933
|
+
previousSlide.style.opacity = '0';
|
|
1934
|
+
previousSlide.style.transform = 'translateY(-20px)';
|
|
1935
|
+
previousSlide.style.zIndex = '1';
|
|
1936
|
+
// 다음 슬라이드 페이드 인 (위에서)
|
|
1937
|
+
nextSlide.style.opacity = '1';
|
|
1938
|
+
nextSlide.style.transform = 'translateY(0)';
|
|
1939
|
+
nextSlide.style.zIndex = '2';
|
|
1940
|
+
// 다른 슬라이드들은 숨김
|
|
1941
|
+
slideElements.forEach((slide, i) => {
|
|
1942
|
+
if (i !== index && i !== currentSlide) {
|
|
1943
|
+
slide.style.opacity = '0';
|
|
1944
|
+
slide.style.transform = 'translateY(20px)';
|
|
1945
|
+
slide.style.zIndex = '1';
|
|
1946
|
+
}
|
|
1947
|
+
});
|
|
1948
|
+
currentSlide = index;
|
|
1949
|
+
// 현재 슬라이드의 광고에 대해 노출 이벤트 추적
|
|
1950
|
+
if (currentSlide > 0) { // 첫 번째는 이미 loadSlot에서 추적됨
|
|
1951
|
+
trackEventCallback(advertisements[currentSlide]._id, slot.id, AdEventType.VIEWABLE);
|
|
1952
|
+
}
|
|
1532
1953
|
};
|
|
1954
|
+
// 자동 슬라이드
|
|
1955
|
+
let autoSlideTimer = setInterval(() => {
|
|
1956
|
+
const nextIndex = currentSlide + 1;
|
|
1957
|
+
moveToSlide(nextIndex);
|
|
1958
|
+
}, autoSlideInterval);
|
|
1959
|
+
// 마우스 호버 시 자동 슬라이드 일시정지
|
|
1960
|
+
sliderWrapper.addEventListener('mouseenter', () => {
|
|
1961
|
+
clearInterval(autoSlideTimer);
|
|
1962
|
+
});
|
|
1963
|
+
sliderWrapper.addEventListener('mouseleave', () => {
|
|
1964
|
+
autoSlideTimer = setInterval(() => {
|
|
1965
|
+
const nextIndex = currentSlide + 1;
|
|
1966
|
+
moveToSlide(nextIndex);
|
|
1967
|
+
}, autoSlideInterval);
|
|
1968
|
+
});
|
|
1969
|
+
// 터치 제스처 지원
|
|
1970
|
+
TextTransitionManager.addTouchSupport(sliderWrapper, moveToSlide, () => currentSlide, totalSlides);
|
|
1971
|
+
// 요소들 조립
|
|
1972
|
+
sliderWrapper.appendChild(slideContainer);
|
|
1973
|
+
return sliderWrapper;
|
|
1533
1974
|
}
|
|
1534
1975
|
/**
|
|
1535
|
-
*
|
|
1976
|
+
* 터치 제스처 지원 추가
|
|
1536
1977
|
*/
|
|
1537
|
-
static
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1978
|
+
static addTouchSupport(container, moveToSlide, getCurrentSlide, totalSlides) {
|
|
1979
|
+
let startX = 0;
|
|
1980
|
+
let startY = 0;
|
|
1981
|
+
let isDragging = false;
|
|
1982
|
+
container.addEventListener('touchstart', (e) => {
|
|
1983
|
+
startX = e.touches[0].clientX;
|
|
1984
|
+
startY = e.touches[0].clientY;
|
|
1985
|
+
isDragging = true;
|
|
1986
|
+
});
|
|
1987
|
+
container.addEventListener('touchmove', (e) => {
|
|
1988
|
+
if (!isDragging)
|
|
1989
|
+
return;
|
|
1990
|
+
e.preventDefault();
|
|
1991
|
+
});
|
|
1992
|
+
container.addEventListener('touchend', (e) => {
|
|
1993
|
+
if (!isDragging)
|
|
1994
|
+
return;
|
|
1995
|
+
isDragging = false;
|
|
1996
|
+
const endX = e.changedTouches[0].clientX;
|
|
1997
|
+
const endY = e.changedTouches[0].clientY;
|
|
1998
|
+
const diffX = startX - endX;
|
|
1999
|
+
const diffY = startY - endY;
|
|
2000
|
+
// 가로 스와이프가 세로 스와이프보다 클 때만 처리
|
|
2001
|
+
if (Math.abs(diffX) > Math.abs(diffY) && Math.abs(diffX) > 50) {
|
|
2002
|
+
const currentSlide = getCurrentSlide();
|
|
2003
|
+
if (diffX > 0) {
|
|
2004
|
+
// 왼쪽으로 스와이프 (다음 슬라이드)
|
|
2005
|
+
moveToSlide(currentSlide + 1);
|
|
2006
|
+
}
|
|
2007
|
+
else {
|
|
2008
|
+
// 오른쪽으로 스와이프 (이전 슬라이드)
|
|
2009
|
+
moveToSlide(currentSlide - 1);
|
|
2010
|
+
}
|
|
2011
|
+
}
|
|
2012
|
+
});
|
|
1544
2013
|
}
|
|
1545
2014
|
}
|
|
1546
2015
|
|
|
1547
2016
|
/**
|
|
1548
|
-
*
|
|
1549
|
-
*
|
|
2017
|
+
* AdRenderer - 광고 렌더링 전용 클래스
|
|
2018
|
+
* AdsModule에서 렌더링 관련 기능을 분리
|
|
1550
2019
|
*/
|
|
1551
|
-
class
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
static create(apiKey, options) {
|
|
1556
|
-
if (!apiKey) {
|
|
1557
|
-
throw new Error('API key is required');
|
|
1558
|
-
}
|
|
1559
|
-
const headers = {
|
|
1560
|
-
'x-api-key': apiKey,
|
|
1561
|
-
'Content-Type': options?.contentType || 'application/json'
|
|
1562
|
-
};
|
|
1563
|
-
// User-Agent는 이벤트 추적에서 실제로 사용됨
|
|
1564
|
-
if (typeof navigator !== 'undefined') {
|
|
1565
|
-
headers['User-Agent'] = options?.userAgent || navigator.userAgent;
|
|
1566
|
-
}
|
|
1567
|
-
// X-Current-URL은 현재 서버에서 사용하지 않으므로 제거
|
|
1568
|
-
// 필요시 이벤트 데이터 body에 포함
|
|
1569
|
-
return headers;
|
|
2020
|
+
class AdRenderer {
|
|
2021
|
+
constructor(debug = false, advertisementEventTracker) {
|
|
2022
|
+
this.debug = debug;
|
|
2023
|
+
this.advertisementEventTracker = advertisementEventTracker || null;
|
|
1570
2024
|
}
|
|
1571
2025
|
/**
|
|
1572
|
-
*
|
|
1573
|
-
* User-Agent는 서버에서 실제로 사용됨
|
|
2026
|
+
* Placeholder(슬롯 컨테이너) 생성
|
|
1574
2027
|
*/
|
|
1575
|
-
|
|
1576
|
-
const
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
2028
|
+
createPlaceholder(container, slotId, type, options, _config) {
|
|
2029
|
+
const adElement = document.createElement('div');
|
|
2030
|
+
adElement.id = slotId;
|
|
2031
|
+
adElement.className = `adstage-slot adstage-${String(type).toLowerCase()}`;
|
|
2032
|
+
adElement.setAttribute('data-adstage-container', 'true');
|
|
2033
|
+
adElement.setAttribute('data-adstage-type', String(type));
|
|
2034
|
+
adElement.setAttribute('data-adstage-slot', slotId);
|
|
2035
|
+
const { width, height } = this.calculateAdSize(container, type, options, _config) || {
|
|
2036
|
+
width: '100%',
|
|
2037
|
+
height: '250px'
|
|
2038
|
+
};
|
|
2039
|
+
adElement.style.width = width;
|
|
2040
|
+
adElement.style.height = height;
|
|
2041
|
+
adElement.style.border = '1px dashed #ccc';
|
|
2042
|
+
adElement.style.display = 'flex';
|
|
2043
|
+
adElement.style.alignItems = 'center';
|
|
2044
|
+
adElement.style.justifyContent = 'center';
|
|
2045
|
+
adElement.style.backgroundColor = '#f9f9f9';
|
|
2046
|
+
adElement.style.color = '#666';
|
|
2047
|
+
adElement.innerHTML = `<span>Loading ${type} ad...</span>`;
|
|
2048
|
+
container.appendChild(adElement);
|
|
2049
|
+
if (this.debug) {
|
|
2050
|
+
console.log(`📦 Placeholder created for slot: ${slotId} (${width} x ${height})`);
|
|
1580
2051
|
}
|
|
1581
|
-
// 다른 정보들은 HTTP 헤더가 아닌 이벤트 데이터 body에 포함하는 것이 적절
|
|
1582
|
-
// (currentUrl, referrer 등은 POST body로 전송)
|
|
1583
|
-
return baseHeaders;
|
|
1584
|
-
}
|
|
1585
|
-
}
|
|
1586
|
-
|
|
1587
|
-
/**
|
|
1588
|
-
* 광고 이벤트 추적 관리 클래스
|
|
1589
|
-
* - 광고 전용 이벤트 추적 및 전송
|
|
1590
|
-
* - Viewable 이벤트 중복 방지 통합
|
|
1591
|
-
* - 광고 서버 API 통신
|
|
1592
|
-
*/
|
|
1593
|
-
class AdvertisementEventTracker {
|
|
1594
|
-
constructor(baseUrl, apiKey, debug, slots) {
|
|
1595
|
-
this.baseUrl = baseUrl;
|
|
1596
|
-
this.apiKey = apiKey;
|
|
1597
|
-
this.debug = debug;
|
|
1598
|
-
this.slots = slots;
|
|
1599
2052
|
}
|
|
1600
2053
|
/**
|
|
1601
|
-
*
|
|
2054
|
+
* 여러 광고의 최적 컨테이너 크기 계산 (동적 크기 조정)
|
|
1602
2055
|
*/
|
|
1603
|
-
async
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
const deviceInfo = DeviceInfoCollector.collectDeviceInfo();
|
|
1610
|
-
// 광고 이벤트 데이터 구성 (DTO 구조에 맞춤)
|
|
1611
|
-
const eventData = {
|
|
1612
|
-
// 서버에서 자동 설정: orgId, advertisementId, action
|
|
1613
|
-
// 하지만 DTO 검증을 위해 임시값 제공
|
|
1614
|
-
orgId: 'temp', // 서버에서 API 키로부터 덮어씀
|
|
1615
|
-
advertisementId: adId, // 서버에서 URL 파라미터로부터 덮어씀
|
|
1616
|
-
action: eventType, // 서버에서 URL 파라미터로부터 덮어씀
|
|
1617
|
-
// 필수 필드들
|
|
1618
|
-
adType: slot?.adType || 'BANNER',
|
|
1619
|
-
platform: deviceInfo.platform,
|
|
1620
|
-
// 디바이스 정보 - 스키마에 맞게 최상위 레벨로 추출
|
|
1621
|
-
deviceId: deviceInfo.deviceId,
|
|
1622
|
-
osVersion: deviceInfo.osVersion,
|
|
1623
|
-
deviceModel: deviceInfo.deviceModel,
|
|
1624
|
-
appVersion: deviceInfo.appVersion,
|
|
1625
|
-
sdkVersion: deviceInfo.sdkVersion,
|
|
1626
|
-
language: deviceInfo.language,
|
|
1627
|
-
country: deviceInfo.country,
|
|
1628
|
-
timezone: deviceInfo.timezone,
|
|
1629
|
-
viewportWidth: deviceInfo.viewportWidth,
|
|
1630
|
-
viewportHeight: deviceInfo.viewportHeight,
|
|
1631
|
-
screenWidth: deviceInfo.screenWidth,
|
|
1632
|
-
screenHeight: deviceInfo.screenHeight,
|
|
1633
|
-
connectionType: deviceInfo.connectionType,
|
|
1634
|
-
// 페이지 및 슬롯 정보
|
|
1635
|
-
pageUrl: DOMUtils.getPageInfo().url,
|
|
1636
|
-
pageTitle: DOMUtils.getPageInfo().title,
|
|
1637
|
-
referrer: DOMUtils.getPageInfo().referrer,
|
|
1638
|
-
slotId,
|
|
1639
|
-
slotPosition: DeviceInfoCollector.getSlotPosition(slot?.containerId || ''),
|
|
1640
|
-
slotWidth: AdvertisementEventTracker.parseNumericValue(slot?.width),
|
|
1641
|
-
slotHeight: AdvertisementEventTracker.parseNumericValue(slot?.height),
|
|
1642
|
-
sessionId: deviceInfo.sessionId,
|
|
1643
|
-
// 성능 메트릭
|
|
1644
|
-
pageLoadTime: performance.now(),
|
|
1645
|
-
// 추가 메타데이터
|
|
1646
|
-
metadata: {
|
|
1647
|
-
eventType,
|
|
1648
|
-
sdkVersion: '1.0.0',
|
|
1649
|
-
timestamp: Date.now(),
|
|
1650
|
-
},
|
|
1651
|
-
// viewable 관련 추가 데이터 (DTO 필드명과 매칭)
|
|
1652
|
-
...(additionalData?.viewabilityMetrics && {
|
|
1653
|
-
isViewable: additionalData.viewabilityMetrics.isViewable,
|
|
1654
|
-
exposureTime: additionalData.viewabilityMetrics.exposureTime,
|
|
1655
|
-
maxVisibilityRatio: additionalData.viewabilityMetrics.maxVisibilityRatio,
|
|
1656
|
-
firstViewableTime: additionalData.viewabilityMetrics.firstViewableTime,
|
|
1657
|
-
// IAB 표준 준수 여부
|
|
1658
|
-
iabCompliant: additionalData.viewabilityMetrics.isViewable,
|
|
1659
|
-
}),
|
|
1660
|
-
// fraud 관련 데이터 (DTO 필드명과 매칭)
|
|
1661
|
-
...(additionalData?.fraudScore !== undefined && {
|
|
1662
|
-
fraudScore: additionalData.fraudScore,
|
|
1663
|
-
fraudReasons: additionalData.fraudReasons,
|
|
1664
|
-
riskLevel: additionalData.riskLevel,
|
|
1665
|
-
}),
|
|
2056
|
+
async calculateOptimalContainerSize(advertisements, containerWidth, adType) {
|
|
2057
|
+
if (!advertisements.length || adType !== AdType.BANNER) {
|
|
2058
|
+
return {
|
|
2059
|
+
width: '100%',
|
|
2060
|
+
height: this.getDefaultHeightForAdType(adType) || '250px',
|
|
2061
|
+
aspectRatio: 16 / 9
|
|
1666
2062
|
};
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
2063
|
+
}
|
|
2064
|
+
try {
|
|
2065
|
+
const imageDimensions = await Promise.allSettled(advertisements
|
|
2066
|
+
.filter(ad => ad.imageUrl)
|
|
2067
|
+
.map(ad => this.loadImageDimensions(ad.imageUrl)));
|
|
2068
|
+
const validDimensions = imageDimensions
|
|
2069
|
+
.filter((result) => result.status === 'fulfilled')
|
|
2070
|
+
.map(result => result.value);
|
|
2071
|
+
if (validDimensions.length === 0) {
|
|
2072
|
+
return {
|
|
2073
|
+
width: '100%',
|
|
2074
|
+
height: this.getDefaultHeightForAdType(adType) || '250px',
|
|
2075
|
+
aspectRatio: 16 / 9
|
|
2076
|
+
};
|
|
2077
|
+
}
|
|
2078
|
+
const strategy = this.selectOptimalSizeStrategy(validDimensions);
|
|
2079
|
+
const optimalHeight = this.calculateOptimalHeight(validDimensions, containerWidth, strategy);
|
|
1672
2080
|
if (this.debug) {
|
|
1673
|
-
console.log(
|
|
2081
|
+
console.log(`📐 Optimal container calculated: ${containerWidth}x${optimalHeight} (strategy: ${strategy})`);
|
|
1674
2082
|
}
|
|
2083
|
+
return {
|
|
2084
|
+
width: '100%',
|
|
2085
|
+
height: `${optimalHeight}px`,
|
|
2086
|
+
aspectRatio: containerWidth / optimalHeight
|
|
2087
|
+
};
|
|
1675
2088
|
}
|
|
1676
2089
|
catch (error) {
|
|
1677
|
-
console.
|
|
2090
|
+
console.warn('Failed to calculate optimal size, using defaults:', error);
|
|
2091
|
+
return {
|
|
2092
|
+
width: '100%',
|
|
2093
|
+
height: this.getDefaultHeightForAdType(adType) || '250px',
|
|
2094
|
+
aspectRatio: 16 / 9
|
|
2095
|
+
};
|
|
1678
2096
|
}
|
|
1679
2097
|
}
|
|
1680
2098
|
/**
|
|
1681
|
-
* 크기
|
|
2099
|
+
* 최적 크기 조정 전략 선택
|
|
1682
2100
|
*/
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
2101
|
+
selectOptimalSizeStrategy(dimensions) {
|
|
2102
|
+
const aspectRatios = dimensions.map(d => d.width / d.height);
|
|
2103
|
+
const ratioGroups = new Map();
|
|
2104
|
+
aspectRatios.forEach(ratio => {
|
|
2105
|
+
const roundedRatio = Math.round(ratio * 10) / 10;
|
|
2106
|
+
const key = roundedRatio.toString();
|
|
2107
|
+
ratioGroups.set(key, (ratioGroups.get(key) || 0) + 1);
|
|
2108
|
+
});
|
|
2109
|
+
const maxGroup = Math.max(...ratioGroups.values());
|
|
2110
|
+
const totalImages = dimensions.length;
|
|
2111
|
+
if (maxGroup / totalImages >= 0.7) {
|
|
2112
|
+
return 'dominant';
|
|
1691
2113
|
}
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
/**
|
|
1697
|
-
* IAB 표준 준수 viewable impression 측정
|
|
1698
|
-
*/
|
|
1699
|
-
// 광고 타입별 IAB 표준 설정
|
|
1700
|
-
const VIEWABILITY_STANDARDS = {
|
|
1701
|
-
BANNER: {
|
|
1702
|
-
threshold: 0.5,
|
|
1703
|
-
minDuration: 1000,
|
|
1704
|
-
maxMeasureTime: 30000
|
|
1705
|
-
},
|
|
1706
|
-
VIDEO: {
|
|
1707
|
-
threshold: 0.5,
|
|
1708
|
-
minDuration: 2000,
|
|
1709
|
-
maxMeasureTime: 60000
|
|
1710
|
-
},
|
|
1711
|
-
NATIVE: {
|
|
1712
|
-
threshold: 0.5,
|
|
1713
|
-
minDuration: 1000,
|
|
1714
|
-
maxMeasureTime: 30000
|
|
1715
|
-
},
|
|
1716
|
-
INTERSTITIAL: {
|
|
1717
|
-
threshold: 0.5,
|
|
1718
|
-
minDuration: 1000,
|
|
1719
|
-
maxMeasureTime: 10000
|
|
1720
|
-
},
|
|
1721
|
-
TEXT: {
|
|
1722
|
-
threshold: 0.5,
|
|
1723
|
-
minDuration: 1000,
|
|
1724
|
-
maxMeasureTime: 30000
|
|
1725
|
-
},
|
|
1726
|
-
POPUP: {
|
|
1727
|
-
threshold: 0.5,
|
|
1728
|
-
minDuration: 1000,
|
|
1729
|
-
maxMeasureTime: 10000
|
|
1730
|
-
}
|
|
1731
|
-
};
|
|
1732
|
-
class ViewabilityTracker {
|
|
1733
|
-
constructor(element, adType, onViewable) {
|
|
1734
|
-
this.observer = null;
|
|
1735
|
-
this.viewabilityTimer = null;
|
|
1736
|
-
this.maxVisibilityTimer = null;
|
|
1737
|
-
this.startTime = 0;
|
|
1738
|
-
this.maxVisibilityRatio = 0;
|
|
1739
|
-
this.firstViewableTime = null;
|
|
1740
|
-
this.isViewableAchieved = false;
|
|
1741
|
-
this.element = element;
|
|
1742
|
-
this.config = VIEWABILITY_STANDARDS[adType] || VIEWABILITY_STANDARDS.BANNER;
|
|
1743
|
-
this.onViewableCallback = onViewable;
|
|
1744
|
-
this.startTime = performance.now();
|
|
1745
|
-
this.initIntersectionObserver();
|
|
1746
|
-
this.initMaxMeasureTimer();
|
|
1747
|
-
}
|
|
1748
|
-
initIntersectionObserver() {
|
|
1749
|
-
// IntersectionObserver 지원 확인
|
|
1750
|
-
if (!('IntersectionObserver' in window)) {
|
|
1751
|
-
console.warn('IntersectionObserver not supported, viewability tracking disabled');
|
|
1752
|
-
return;
|
|
2114
|
+
const standardRatios = [16 / 9, 4 / 3, 1 / 1, 3 / 2];
|
|
2115
|
+
const standardCount = aspectRatios.filter(ratio => standardRatios.some(standard => Math.abs(ratio - standard) < 0.1)).length;
|
|
2116
|
+
if (standardCount / totalImages >= 0.5) {
|
|
2117
|
+
return 'common';
|
|
1753
2118
|
}
|
|
1754
|
-
|
|
1755
|
-
threshold: [0, 0.1, 0.25, 0.5, 0.75, 1.0],
|
|
1756
|
-
rootMargin: '0px'
|
|
1757
|
-
});
|
|
1758
|
-
this.observer.observe(this.element);
|
|
2119
|
+
return 'average';
|
|
1759
2120
|
}
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
2121
|
+
/**
|
|
2122
|
+
* 전략에 따른 최적 높이 계산
|
|
2123
|
+
*/
|
|
2124
|
+
calculateOptimalHeight(dimensions, containerWidth, strategy) {
|
|
2125
|
+
const aspectRatios = dimensions.map(d => d.width / d.height);
|
|
2126
|
+
switch (strategy) {
|
|
2127
|
+
case 'dominant': {
|
|
2128
|
+
const ratioGroups = new Map();
|
|
2129
|
+
aspectRatios.forEach(ratio => {
|
|
2130
|
+
const roundedRatio = Math.round(ratio * 10) / 10;
|
|
2131
|
+
const key = roundedRatio.toString();
|
|
2132
|
+
const existing = ratioGroups.get(key);
|
|
2133
|
+
if (existing) {
|
|
2134
|
+
existing.count++;
|
|
2135
|
+
}
|
|
2136
|
+
else {
|
|
2137
|
+
ratioGroups.set(key, { ratio: roundedRatio, count: 1 });
|
|
2138
|
+
}
|
|
2139
|
+
});
|
|
2140
|
+
const dominantGroup = Array.from(ratioGroups.values()).reduce((max, current) => current.count > max.count ? current : max);
|
|
2141
|
+
return Math.round(containerWidth / dominantGroup.ratio);
|
|
1769
2142
|
}
|
|
1770
|
-
|
|
1771
|
-
|
|
2143
|
+
case 'common': {
|
|
2144
|
+
const standardRatios = [
|
|
2145
|
+
{ ratio: 16 / 9, name: '16:9' },
|
|
2146
|
+
{ ratio: 4 / 3, name: '4:3' },
|
|
2147
|
+
{ ratio: 1 / 1, name: '1:1' },
|
|
2148
|
+
{ ratio: 3 / 2, name: '3:2' }
|
|
2149
|
+
];
|
|
2150
|
+
const avgRatio = aspectRatios.reduce((sum, ratio) => sum + ratio, 0) / aspectRatios.length;
|
|
2151
|
+
const bestStandard = standardRatios.reduce((best, current) => Math.abs(current.ratio - avgRatio) < Math.abs(best.ratio - avgRatio) ? current : best);
|
|
2152
|
+
if (this.debug) {
|
|
2153
|
+
console.log(`📊 Using standard ratio: ${bestStandard.name} (avg: ${avgRatio.toFixed(2)})`);
|
|
2154
|
+
}
|
|
2155
|
+
return Math.round(containerWidth / bestStandard.ratio);
|
|
2156
|
+
}
|
|
2157
|
+
case 'average':
|
|
2158
|
+
default: {
|
|
2159
|
+
const averageRatio = aspectRatios.reduce((sum, ratio) => sum + ratio, 0) / aspectRatios.length;
|
|
2160
|
+
return Math.round(containerWidth / averageRatio);
|
|
1772
2161
|
}
|
|
1773
|
-
});
|
|
1774
|
-
}
|
|
1775
|
-
isDocumentVisible() {
|
|
1776
|
-
// 단순한 문서 가시성 확인
|
|
1777
|
-
return !document.hidden && document.visibilityState === 'visible';
|
|
1778
|
-
}
|
|
1779
|
-
startViewabilityTimer() {
|
|
1780
|
-
if (this.viewabilityTimer || this.isViewableAchieved)
|
|
1781
|
-
return;
|
|
1782
|
-
if (this.firstViewableTime === null) {
|
|
1783
|
-
this.firstViewableTime = performance.now();
|
|
1784
2162
|
}
|
|
1785
|
-
this.viewabilityTimer = setTimeout(() => {
|
|
1786
|
-
this.onViewabilityAchieved();
|
|
1787
|
-
}, this.config.minDuration);
|
|
1788
2163
|
}
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
2164
|
+
/**
|
|
2165
|
+
* 배너 광고를 위한 컨테이너 최적화
|
|
2166
|
+
*/
|
|
2167
|
+
async optimizeContainerForBannerAds(slot, advertisements) {
|
|
2168
|
+
try {
|
|
2169
|
+
const container = document.getElementById(slot.containerId);
|
|
2170
|
+
const adElement = document.getElementById(slot.id);
|
|
2171
|
+
if (!container || !adElement)
|
|
2172
|
+
return;
|
|
2173
|
+
const containerWidth = container.getBoundingClientRect().width || 300;
|
|
2174
|
+
const optimalSize = await this.calculateOptimalContainerSize(advertisements, containerWidth, slot.adType);
|
|
2175
|
+
adElement.style.height = optimalSize.height;
|
|
2176
|
+
slot.optimizedHeight = optimalSize.height;
|
|
2177
|
+
slot.aspectRatio = optimalSize.aspectRatio;
|
|
2178
|
+
if (this.debug) {
|
|
2179
|
+
console.log(`🔧 Container optimized for ${advertisements.length} banner ads: ${optimalSize.height}`);
|
|
2180
|
+
}
|
|
1793
2181
|
}
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
// 최대 측정 시간 후 자동 종료
|
|
1797
|
-
this.maxVisibilityTimer = setTimeout(() => {
|
|
1798
|
-
this.destroy();
|
|
1799
|
-
}, this.config.maxMeasureTime);
|
|
1800
|
-
}
|
|
1801
|
-
onViewabilityAchieved() {
|
|
1802
|
-
if (this.isViewableAchieved)
|
|
1803
|
-
return;
|
|
1804
|
-
this.isViewableAchieved = true;
|
|
1805
|
-
const metrics = this.calculateMetrics();
|
|
1806
|
-
if (this.onViewableCallback) {
|
|
1807
|
-
this.onViewableCallback(metrics);
|
|
2182
|
+
catch (error) {
|
|
2183
|
+
console.warn('Container optimization failed, using default size:', error);
|
|
1808
2184
|
}
|
|
1809
2185
|
}
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
2186
|
+
/**
|
|
2187
|
+
* 광고 슬라이더 렌더링 (여러 광고 또는 autoSlide 옵션)
|
|
2188
|
+
*/
|
|
2189
|
+
async renderAdSlider(slot, advertisements) {
|
|
2190
|
+
const container = document.getElementById(slot.containerId);
|
|
2191
|
+
if (!container) {
|
|
2192
|
+
throw new Error(`Container not found: ${slot.containerId}`);
|
|
2193
|
+
}
|
|
2194
|
+
const trackEventCallback = async (adId, slotId, eventType) => {
|
|
2195
|
+
if (eventType === AdEventType.VIEWABLE) {
|
|
2196
|
+
if (ViewableEventTracker.isDuplicateViewable(adId, slotId, this.debug)) {
|
|
2197
|
+
if (this.debug) {
|
|
2198
|
+
console.log(`🚫 Duplicate viewable blocked for ad ${adId} in slot ${slotId}`);
|
|
2199
|
+
}
|
|
2200
|
+
return;
|
|
2201
|
+
}
|
|
2202
|
+
if (this.debug) {
|
|
2203
|
+
console.log(`✅ New viewable recorded for ad ${adId} in slot ${slotId}`);
|
|
2204
|
+
}
|
|
2205
|
+
}
|
|
2206
|
+
if (this.advertisementEventTracker) {
|
|
2207
|
+
try {
|
|
2208
|
+
await this.advertisementEventTracker.trackAdvertisementEvent(adId, slotId, eventType, {});
|
|
2209
|
+
if (this.debug) {
|
|
2210
|
+
console.log(`📊 Advertisement event tracked: ${eventType} for ad ${adId} in slot ${slotId}`);
|
|
2211
|
+
}
|
|
2212
|
+
}
|
|
2213
|
+
catch (error) {
|
|
2214
|
+
if (this.debug) {
|
|
2215
|
+
console.error(`❌ Failed to track ${eventType} event for ad ${adId}:`, error);
|
|
2216
|
+
}
|
|
2217
|
+
}
|
|
2218
|
+
}
|
|
1821
2219
|
};
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
2220
|
+
let sliderElement;
|
|
2221
|
+
const optimizedSliderOptions = {
|
|
2222
|
+
autoSlideInterval: (slot.config?.slideInterval || 5000) / 1000,
|
|
2223
|
+
...slot.config,
|
|
2224
|
+
optimizedHeight: slot.optimizedHeight,
|
|
2225
|
+
aspectRatio: slot.aspectRatio
|
|
2226
|
+
};
|
|
2227
|
+
if (slot.adType === AdType.TEXT) {
|
|
2228
|
+
sliderElement = TextTransitionManager.createTextTransitionContainer(slot, advertisements, optimizedSliderOptions, trackEventCallback);
|
|
2229
|
+
if (this.debug) {
|
|
2230
|
+
console.log(`✨ Text transition created for TEXT slot: ${slot.id} with ${advertisements.length} ads`);
|
|
2231
|
+
}
|
|
1831
2232
|
}
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
this.
|
|
2233
|
+
else {
|
|
2234
|
+
sliderElement = CarouselSliderManager.createSliderContainer(slot, advertisements, optimizedSliderOptions, trackEventCallback);
|
|
2235
|
+
if (this.debug) {
|
|
2236
|
+
console.log(`🎠 Carousel slider created for ${slot.adType} slot: ${slot.id} with ${advertisements.length} ads (optimized: ${slot.optimizedHeight || 'default'})`);
|
|
2237
|
+
}
|
|
2238
|
+
}
|
|
2239
|
+
container.innerHTML = '';
|
|
2240
|
+
container.appendChild(sliderElement);
|
|
2241
|
+
if (this.debug) {
|
|
2242
|
+
console.log(`� Slider uses manual VIEWABLE event tracking for ${advertisements.length} ads`);
|
|
1835
2243
|
}
|
|
1836
2244
|
}
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
this.keyboardEvents = 0;
|
|
1847
|
-
this.scrollEvents = 0;
|
|
1848
|
-
this.startTime = Date.now();
|
|
1849
|
-
this.initBasicTracking();
|
|
1850
|
-
}
|
|
1851
|
-
initBasicTracking() {
|
|
1852
|
-
// 기본적인 사용자 상호작용 추적
|
|
1853
|
-
document.addEventListener('mousemove', () => this.mouseEvents++, { passive: true });
|
|
1854
|
-
document.addEventListener('keydown', () => this.keyboardEvents++, { passive: true });
|
|
1855
|
-
document.addEventListener('scroll', () => this.scrollEvents++, { passive: true });
|
|
2245
|
+
/**
|
|
2246
|
+
* 광고 렌더링 (단일 광고용)
|
|
2247
|
+
*/
|
|
2248
|
+
async renderAd(slot) {
|
|
2249
|
+
if (!slot.advertisement) {
|
|
2250
|
+
throw new Error('No advertisement to render');
|
|
2251
|
+
}
|
|
2252
|
+
await this.renderAdElement(slot, slot.advertisement);
|
|
2253
|
+
slot.isLoaded = true;
|
|
1856
2254
|
}
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
2255
|
+
/**
|
|
2256
|
+
* 광고 요소 렌더링 (기본 구현)
|
|
2257
|
+
*/
|
|
2258
|
+
async renderAdElement(slot, ad) {
|
|
2259
|
+
const container = document.getElementById(slot.containerId);
|
|
2260
|
+
if (!container)
|
|
2261
|
+
return;
|
|
2262
|
+
const adElement = document.createElement('div');
|
|
2263
|
+
adElement.className = 'adstage-ad';
|
|
2264
|
+
const optimizedHeight = slot.optimizedHeight;
|
|
2265
|
+
const containerElement = container.parentElement || container;
|
|
2266
|
+
if (optimizedHeight) {
|
|
2267
|
+
adElement.style.width = '100%';
|
|
2268
|
+
adElement.style.height = String(optimizedHeight);
|
|
1864
2269
|
}
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
2270
|
+
else {
|
|
2271
|
+
const { width, height } = this.calculateAdSize(containerElement, slot.adType, slot.config || {}, { debug: this.debug }) ||
|
|
2272
|
+
{ width: '100%', height: '250px' };
|
|
2273
|
+
adElement.style.width = width;
|
|
2274
|
+
adElement.style.height = height;
|
|
1869
2275
|
}
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
2276
|
+
switch (slot.adType) {
|
|
2277
|
+
case AdType.BANNER:
|
|
2278
|
+
if (ad.imageUrl) {
|
|
2279
|
+
await this.renderOptimizedBannerImage(adElement, ad, slot);
|
|
2280
|
+
}
|
|
2281
|
+
break;
|
|
2282
|
+
case AdType.TEXT: {
|
|
2283
|
+
const textDiv = document.createElement('div');
|
|
2284
|
+
textDiv.innerHTML = `
|
|
2285
|
+
<h3>${ad.title}</h3>
|
|
2286
|
+
${ad.description ? `<p>${ad.description}</p>` : ''}
|
|
2287
|
+
${ad.textContent ? `<div>${ad.textContent}</div>` : ''}
|
|
2288
|
+
`;
|
|
2289
|
+
adElement.appendChild(textDiv);
|
|
2290
|
+
break;
|
|
1880
2291
|
}
|
|
2292
|
+
case AdType.VIDEO:
|
|
2293
|
+
if (ad.videoUrl) {
|
|
2294
|
+
const video = document.createElement('video');
|
|
2295
|
+
video.src = ad.videoUrl;
|
|
2296
|
+
video.controls = true;
|
|
2297
|
+
video.style.width = '100%';
|
|
2298
|
+
video.style.height = '100%';
|
|
2299
|
+
adElement.appendChild(video);
|
|
2300
|
+
}
|
|
2301
|
+
break;
|
|
2302
|
+
default:
|
|
2303
|
+
adElement.innerHTML = `<div>${ad.title}</div>`;
|
|
1881
2304
|
}
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
if (sessionTime < 1000) {
|
|
1888
|
-
score += 25;
|
|
1889
|
-
reasons.push('Suspiciously fast interaction');
|
|
2305
|
+
if (ad.linkUrl) {
|
|
2306
|
+
adElement.style.cursor = 'pointer';
|
|
2307
|
+
adElement.addEventListener('click', () => {
|
|
2308
|
+
window.open(ad.linkUrl, '_blank');
|
|
2309
|
+
});
|
|
1890
2310
|
}
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
score: finalScore,
|
|
1894
|
-
riskLevel: this.getRiskLevel(finalScore),
|
|
1895
|
-
reasons: reasons
|
|
1896
|
-
};
|
|
1897
|
-
}
|
|
1898
|
-
detectWebDriver() {
|
|
1899
|
-
// 기본적인 웹드라이버 탐지
|
|
1900
|
-
return !!(window.webdriver ||
|
|
1901
|
-
navigator.webdriver ||
|
|
1902
|
-
window.__webdriver_evaluate ||
|
|
1903
|
-
window.__selenium_evaluate ||
|
|
1904
|
-
window.__webdriver_script_function ||
|
|
1905
|
-
window.__webdriver_script_func ||
|
|
1906
|
-
window.__webdriver_script_fn ||
|
|
1907
|
-
window.__fxdriver_evaluate ||
|
|
1908
|
-
window.__driver_unwrapped ||
|
|
1909
|
-
window.__webdriver_unwrapped ||
|
|
1910
|
-
window.__driver_evaluate ||
|
|
1911
|
-
window.__selenium_unwrapped ||
|
|
1912
|
-
window.__fxdriver_unwrapped);
|
|
2311
|
+
container.innerHTML = '';
|
|
2312
|
+
container.appendChild(adElement);
|
|
1913
2313
|
}
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
|
|
2314
|
+
/**
|
|
2315
|
+
* Fallback 광고 렌더링 - 컨테이너 접기/생성
|
|
2316
|
+
*/
|
|
2317
|
+
renderFallback(slot) {
|
|
2318
|
+
const element = document.getElementById(slot.id);
|
|
2319
|
+
if (element) {
|
|
2320
|
+
const adstageContainers = [
|
|
2321
|
+
element.querySelector('[data-adstage-container="true"]'),
|
|
2322
|
+
element.closest('[data-adstage-container="true"]'),
|
|
2323
|
+
element
|
|
2324
|
+
].filter(el => el && el.hasAttribute('data-adstage-container'));
|
|
2325
|
+
const classBasedContainers = [
|
|
2326
|
+
element.closest('.adstage-slot'),
|
|
2327
|
+
element.closest('.adstage-banner'),
|
|
2328
|
+
element.closest('.adstage-text'),
|
|
2329
|
+
element.closest('.adstage-video'),
|
|
2330
|
+
element.closest('.adstage-native'),
|
|
2331
|
+
element.closest('.adstage-interstitial')
|
|
2332
|
+
].filter(Boolean);
|
|
2333
|
+
const generalContainers = [
|
|
2334
|
+
element.closest('[class*="ad"]'),
|
|
2335
|
+
element.closest('[class*="banner"]'),
|
|
2336
|
+
element.closest('[class*="container"]'),
|
|
2337
|
+
element.closest('div[style*="height"]'),
|
|
2338
|
+
element.closest('div[style*="min-height"]'),
|
|
2339
|
+
element.parentElement
|
|
2340
|
+
].filter(Boolean);
|
|
2341
|
+
const possibleContainers = [...adstageContainers, ...classBasedContainers, ...generalContainers];
|
|
2342
|
+
const targetContainer = possibleContainers[0];
|
|
2343
|
+
if (targetContainer) {
|
|
2344
|
+
let containerType = 'unknown';
|
|
2345
|
+
if (targetContainer.hasAttribute('data-adstage-container')) {
|
|
2346
|
+
containerType = 'adstage-official';
|
|
2347
|
+
}
|
|
2348
|
+
else if (targetContainer.classList.contains('adstage-slot')) {
|
|
2349
|
+
containerType = 'adstage-class';
|
|
2350
|
+
}
|
|
2351
|
+
else {
|
|
2352
|
+
containerType = 'generic';
|
|
2353
|
+
}
|
|
2354
|
+
targetContainer.style.cssText += `
|
|
2355
|
+
height: 0px !important;
|
|
2356
|
+
min-height: 0px !important;
|
|
2357
|
+
padding: 0px !important;
|
|
2358
|
+
margin: 0px !important;
|
|
2359
|
+
border: none !important;
|
|
2360
|
+
overflow: hidden !important;
|
|
2361
|
+
display: block !important;
|
|
2362
|
+
`;
|
|
2363
|
+
targetContainer.innerHTML = '';
|
|
2364
|
+
targetContainer.setAttribute('data-adstage-empty', 'true');
|
|
2365
|
+
if (this.debug) {
|
|
2366
|
+
console.warn(`⚠️ Ad container collapsed (${containerType}): ${slot.id}`, targetContainer);
|
|
2367
|
+
}
|
|
2368
|
+
}
|
|
2369
|
+
else {
|
|
2370
|
+
this.createEmptyContainer(slot);
|
|
2371
|
+
}
|
|
1919
2372
|
}
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
2373
|
+
slot.advertisement = undefined;
|
|
2374
|
+
slot.isEmpty = true;
|
|
2375
|
+
}
|
|
2376
|
+
/**
|
|
2377
|
+
* 빈 컨테이너 생성 (컨테이너를 찾지 못한 경우)
|
|
2378
|
+
*/
|
|
2379
|
+
createEmptyContainer(slot) {
|
|
2380
|
+
const originalContainer = document.getElementById(slot.containerId);
|
|
2381
|
+
if (originalContainer) {
|
|
2382
|
+
originalContainer.innerHTML = '';
|
|
2383
|
+
const emptyElement = document.createElement('div');
|
|
2384
|
+
emptyElement.id = slot.id;
|
|
2385
|
+
emptyElement.className = 'adstage-slot adstage-empty';
|
|
2386
|
+
emptyElement.setAttribute('data-adstage-container', 'true');
|
|
2387
|
+
emptyElement.setAttribute('data-adstage-empty', 'true');
|
|
2388
|
+
emptyElement.setAttribute('data-adstage-slot', slot.id);
|
|
2389
|
+
emptyElement.style.cssText = `
|
|
2390
|
+
height: 0px !important;
|
|
2391
|
+
min-height: 0px !important;
|
|
2392
|
+
padding: 0px !important;
|
|
2393
|
+
margin: 0px !important;
|
|
2394
|
+
border: none !important;
|
|
2395
|
+
overflow: hidden !important;
|
|
2396
|
+
display: block !important;
|
|
2397
|
+
`;
|
|
2398
|
+
originalContainer.appendChild(emptyElement);
|
|
2399
|
+
if (this.debug) {
|
|
2400
|
+
console.warn(`⚠️ Created empty AdStage container: ${slot.id}`);
|
|
2401
|
+
}
|
|
1923
2402
|
}
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
2403
|
+
}
|
|
2404
|
+
/**
|
|
2405
|
+
* 광고 타입별 기본 높이 반환
|
|
2406
|
+
*/
|
|
2407
|
+
getDefaultHeightForAdType(type) {
|
|
2408
|
+
switch (type) {
|
|
2409
|
+
case AdType.BANNER:
|
|
2410
|
+
return '250px'; // 일반 배너
|
|
2411
|
+
case AdType.TEXT:
|
|
2412
|
+
return '120px'; // 텍스트는 좀 더 작게
|
|
2413
|
+
case AdType.VIDEO:
|
|
2414
|
+
return '360px'; // 비디오는 16:9 비율 고려
|
|
2415
|
+
case AdType.NATIVE:
|
|
2416
|
+
return '200px'; // 네이티브는 중간 크기
|
|
2417
|
+
case AdType.INTERSTITIAL:
|
|
2418
|
+
return '400px'; // 전면광고는 크게
|
|
2419
|
+
default:
|
|
2420
|
+
return '250px';
|
|
1927
2421
|
}
|
|
1928
|
-
return signatures.length > 0;
|
|
1929
2422
|
}
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
2423
|
+
/**
|
|
2424
|
+
* 컨테이너와 광고 타입에 따른 스마트한 크기 계산
|
|
2425
|
+
*/
|
|
2426
|
+
calculateAdSize(container, type, options, config) {
|
|
2427
|
+
// 사용자가 명시적으로 크기를 지정한 경우
|
|
2428
|
+
const explicitWidth = options.width;
|
|
2429
|
+
const explicitHeight = options.height;
|
|
2430
|
+
// 너비 처리
|
|
2431
|
+
let width;
|
|
2432
|
+
if (typeof explicitWidth === 'number') {
|
|
2433
|
+
width = `${explicitWidth}px`;
|
|
1937
2434
|
}
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
score += 15;
|
|
1941
|
-
reasons.push('Cookies disabled');
|
|
2435
|
+
else if (typeof explicitWidth === 'string') {
|
|
2436
|
+
width = explicitWidth;
|
|
1942
2437
|
}
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
score += 20;
|
|
1946
|
-
reasons.push('Invalid screen resolution');
|
|
2438
|
+
else {
|
|
2439
|
+
width = '100%'; // 기본값은 100%
|
|
1947
2440
|
}
|
|
1948
|
-
//
|
|
1949
|
-
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
score += 5;
|
|
1953
|
-
reasons.push('No timezone info');
|
|
1954
|
-
}
|
|
2441
|
+
// 높이 처리 - 핵심 로직
|
|
2442
|
+
let height;
|
|
2443
|
+
if (typeof explicitHeight === 'number') {
|
|
2444
|
+
height = `${explicitHeight}px`;
|
|
1955
2445
|
}
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
2446
|
+
else if (typeof explicitHeight === 'string' && explicitHeight !== '100%' && explicitHeight !== 'auto') {
|
|
2447
|
+
// 명시적인 크기 문자열 (예: '200px', '50vh' 등)
|
|
2448
|
+
height = explicitHeight;
|
|
1959
2449
|
}
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
screenResolution: `${screen.width}x${screen.height}`,
|
|
1980
|
-
viewportSize: `${window.innerWidth}x${window.innerHeight}`
|
|
1981
|
-
};
|
|
1982
|
-
}
|
|
1983
|
-
destroy() {
|
|
1984
|
-
// 이벤트 리스너 정리는 생략 (메모리 누수 방지를 위해 필요시 구현)
|
|
2450
|
+
else {
|
|
2451
|
+
// 100%, auto이거나 높이가 지정되지 않은 경우 스마트 계산
|
|
2452
|
+
const containerHeight = this.getContainerHeight(container);
|
|
2453
|
+
if (containerHeight > 0) {
|
|
2454
|
+
// 컨테이너에 높이가 있으면 100% 사용
|
|
2455
|
+
height = '100%';
|
|
2456
|
+
if (config?.debug) {
|
|
2457
|
+
console.log(`📏 Using 100% height (container: ${containerHeight}px)`);
|
|
2458
|
+
}
|
|
2459
|
+
}
|
|
2460
|
+
else {
|
|
2461
|
+
// 컨테이너에 높이가 없으면 타입별 기본값 사용 (나중에 동적 조정됨)
|
|
2462
|
+
height = this.getDefaultHeightForAdType(type);
|
|
2463
|
+
if (config?.debug) {
|
|
2464
|
+
console.log(`📏 Using default height ${height} (will be optimized for ${type})`);
|
|
2465
|
+
}
|
|
2466
|
+
}
|
|
2467
|
+
}
|
|
2468
|
+
return { width, height };
|
|
1985
2469
|
}
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2470
|
+
/**
|
|
2471
|
+
* 컨테이너의 실제 높이 계산
|
|
2472
|
+
*/
|
|
2473
|
+
getContainerHeight(container) {
|
|
2474
|
+
// 현재 계산된 스타일에서 높이 확인
|
|
2475
|
+
const computedStyle = window.getComputedStyle(container);
|
|
2476
|
+
const height = parseFloat(computedStyle.height);
|
|
2477
|
+
// height가 auto이거나 0이면 다른 방법들 시도
|
|
2478
|
+
if (!height || height === 0) {
|
|
2479
|
+
// min-height 확인
|
|
2480
|
+
const minHeight = parseFloat(computedStyle.minHeight);
|
|
2481
|
+
if (minHeight > 0)
|
|
2482
|
+
return minHeight;
|
|
2483
|
+
// CSS로 설정된 고정 높이 확인
|
|
2484
|
+
if (container.style.height && container.style.height !== 'auto') {
|
|
2485
|
+
const styleHeight = parseFloat(container.style.height);
|
|
2486
|
+
if (styleHeight > 0)
|
|
2487
|
+
return styleHeight;
|
|
2488
|
+
}
|
|
2489
|
+
// 속성으로 설정된 높이 확인
|
|
2490
|
+
const heightAttr = container.getAttribute('height');
|
|
2491
|
+
if (heightAttr) {
|
|
2492
|
+
const attrHeight = parseFloat(heightAttr);
|
|
2493
|
+
if (attrHeight > 0)
|
|
2494
|
+
return attrHeight;
|
|
2495
|
+
}
|
|
2496
|
+
}
|
|
2497
|
+
return height || 0;
|
|
2014
2498
|
}
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
* 이벤트 엔드포인트
|
|
2030
|
-
*/
|
|
2031
|
-
this.events = {
|
|
2032
|
-
track: () => `${this.baseUrl}${API_PATHS.events.track}`,
|
|
2033
|
-
batch: () => `${this.baseUrl}${API_PATHS.events.batch}`
|
|
2034
|
-
};
|
|
2035
|
-
// 기본값은 베타 환경 사용
|
|
2036
|
-
this.baseUrl = baseUrl || API_ENDPOINTS.beta;
|
|
2499
|
+
/**
|
|
2500
|
+
* 이미지 로드 및 실제 크기 획득 (Promise 기반)
|
|
2501
|
+
*/
|
|
2502
|
+
loadImageDimensions(imageUrl) {
|
|
2503
|
+
return new Promise((resolve, reject) => {
|
|
2504
|
+
const img = new Image();
|
|
2505
|
+
img.onload = () => {
|
|
2506
|
+
resolve({ width: img.naturalWidth, height: img.naturalHeight });
|
|
2507
|
+
};
|
|
2508
|
+
img.onerror = () => {
|
|
2509
|
+
reject(new Error(`Failed to load image: ${imageUrl}`));
|
|
2510
|
+
};
|
|
2511
|
+
img.src = imageUrl;
|
|
2512
|
+
});
|
|
2037
2513
|
}
|
|
2038
2514
|
/**
|
|
2039
|
-
*
|
|
2515
|
+
* 이미지와 컨테이너 비율을 고려한 최적화 스타일 적용
|
|
2040
2516
|
*/
|
|
2041
|
-
|
|
2042
|
-
|
|
2043
|
-
|
|
2517
|
+
applyOptimizedImageStyle(img, imageAspectRatio, containerAspectRatio) {
|
|
2518
|
+
const ratio = imageAspectRatio / containerAspectRatio;
|
|
2519
|
+
if (Math.abs(ratio - 1) < 0.1) {
|
|
2520
|
+
// 비율이 거의 같으면 cover 사용
|
|
2521
|
+
img.style.objectFit = 'cover';
|
|
2522
|
+
img.style.objectPosition = 'center';
|
|
2523
|
+
}
|
|
2524
|
+
else if (ratio > 1.3) {
|
|
2525
|
+
// 이미지가 훨씬 가로형이면 contain으로 전체 보이기
|
|
2526
|
+
img.style.objectFit = 'contain';
|
|
2527
|
+
img.style.objectPosition = 'center';
|
|
2528
|
+
img.style.backgroundColor = '#f0f0f0'; // 빈 공간 배경색
|
|
2529
|
+
}
|
|
2530
|
+
else if (ratio < 0.7) {
|
|
2531
|
+
// 이미지가 훨씬 세로형이면 cover로 채우기
|
|
2532
|
+
img.style.objectFit = 'cover';
|
|
2533
|
+
img.style.objectPosition = 'center';
|
|
2534
|
+
}
|
|
2535
|
+
else {
|
|
2536
|
+
// 적당한 차이면 스마트 cover
|
|
2537
|
+
img.style.objectFit = 'cover';
|
|
2538
|
+
img.style.objectPosition = 'center';
|
|
2539
|
+
}
|
|
2540
|
+
if (this.debug) {
|
|
2541
|
+
console.log(`🎨 Image style applied: objectFit=${img.style.objectFit}, ratio=${ratio.toFixed(2)}`);
|
|
2542
|
+
}
|
|
2044
2543
|
}
|
|
2045
2544
|
/**
|
|
2046
|
-
*
|
|
2545
|
+
* 배너 이미지 최적화 렌더링
|
|
2546
|
+
* 이미지 실제 크기를 로드한 후 컨테이너와 비율을 맞춤
|
|
2047
2547
|
*/
|
|
2048
|
-
|
|
2049
|
-
|
|
2548
|
+
async renderOptimizedBannerImage(container, advertisement, slot) {
|
|
2549
|
+
const img = document.createElement('img');
|
|
2550
|
+
// 기본 스타일 설정
|
|
2551
|
+
img.style.width = '100%';
|
|
2552
|
+
img.style.height = '100%';
|
|
2553
|
+
img.style.display = 'block';
|
|
2554
|
+
img.style.borderRadius = '8px';
|
|
2555
|
+
img.alt = advertisement.title || 'Advertisement';
|
|
2556
|
+
// 이미지 로딩 상태 표시
|
|
2557
|
+
container.innerHTML = '<div style="display: flex; align-items: center; justify-content: center; height: 100%; color: #999;">Loading...</div>';
|
|
2558
|
+
try {
|
|
2559
|
+
// 이미지 URL 체크
|
|
2560
|
+
if (!advertisement.imageUrl) {
|
|
2561
|
+
throw new Error('Image URL is not provided');
|
|
2562
|
+
}
|
|
2563
|
+
// 🆕 이미지 실제 크기 로드
|
|
2564
|
+
const imageDimensions = await this.loadImageDimensions(advertisement.imageUrl);
|
|
2565
|
+
// 컨테이너 크기 정보
|
|
2566
|
+
const containerRect = container.getBoundingClientRect();
|
|
2567
|
+
const containerWidth = containerRect.width;
|
|
2568
|
+
const containerHeight = containerRect.height;
|
|
2569
|
+
if (this.debug) {
|
|
2570
|
+
console.log(`📸 Image dimensions: ${imageDimensions.width}x${imageDimensions.height}`);
|
|
2571
|
+
console.log(`📦 Container dimensions: ${containerWidth}x${containerHeight}`);
|
|
2572
|
+
}
|
|
2573
|
+
// 비율 계산
|
|
2574
|
+
const imageAspectRatio = imageDimensions.width / imageDimensions.height;
|
|
2575
|
+
const containerAspectRatio = containerWidth / containerHeight;
|
|
2576
|
+
// 🆕 스마트 스타일 적용
|
|
2577
|
+
this.applyOptimizedImageStyle(img, imageAspectRatio, containerAspectRatio);
|
|
2578
|
+
// 이미지 설정 및 추가
|
|
2579
|
+
img.src = advertisement.imageUrl;
|
|
2580
|
+
// 컨테이너 클리어 후 이미지 추가
|
|
2581
|
+
container.innerHTML = '';
|
|
2582
|
+
container.appendChild(img);
|
|
2583
|
+
// 클릭 이벤트 등록
|
|
2584
|
+
if (advertisement.linkUrl) {
|
|
2585
|
+
img.style.cursor = 'pointer';
|
|
2586
|
+
img.addEventListener('click', () => {
|
|
2587
|
+
if (this.advertisementEventTracker) {
|
|
2588
|
+
// AdvertisementEventTracker의 실제 메소드명을 확인해야 함
|
|
2589
|
+
console.log(`Click tracked for ad: ${advertisement._id}`);
|
|
2590
|
+
}
|
|
2591
|
+
window.open(advertisement.linkUrl, '_blank');
|
|
2592
|
+
});
|
|
2593
|
+
}
|
|
2594
|
+
if (this.debug) {
|
|
2595
|
+
console.log(`✅ Optimized banner image rendered for ad: ${advertisement._id}`);
|
|
2596
|
+
}
|
|
2597
|
+
return img;
|
|
2598
|
+
}
|
|
2599
|
+
catch (error) {
|
|
2600
|
+
console.error('❌ Failed to load optimized banner image:', error);
|
|
2601
|
+
// 폴백: 일반 이미지 렌더링
|
|
2602
|
+
if (advertisement.imageUrl) {
|
|
2603
|
+
img.src = advertisement.imageUrl;
|
|
2604
|
+
img.style.objectFit = 'cover';
|
|
2605
|
+
img.style.objectPosition = 'center';
|
|
2606
|
+
container.innerHTML = '';
|
|
2607
|
+
container.appendChild(img);
|
|
2608
|
+
if (advertisement.linkUrl) {
|
|
2609
|
+
img.style.cursor = 'pointer';
|
|
2610
|
+
img.addEventListener('click', () => {
|
|
2611
|
+
if (this.advertisementEventTracker) {
|
|
2612
|
+
console.log(`Click tracked for ad: ${advertisement._id}`);
|
|
2613
|
+
}
|
|
2614
|
+
window.open(advertisement.linkUrl, '_blank');
|
|
2615
|
+
});
|
|
2616
|
+
}
|
|
2617
|
+
}
|
|
2618
|
+
return img;
|
|
2619
|
+
}
|
|
2050
2620
|
}
|
|
2051
2621
|
/**
|
|
2052
|
-
*
|
|
2622
|
+
* 디버그 로그 출력
|
|
2053
2623
|
*/
|
|
2054
|
-
|
|
2055
|
-
|
|
2624
|
+
log(message, ...args) {
|
|
2625
|
+
if (this.debug) {
|
|
2626
|
+
console.log(message, ...args);
|
|
2627
|
+
}
|
|
2056
2628
|
}
|
|
2057
|
-
}
|
|
2058
|
-
/**
|
|
2059
|
-
* 전역 엔드포인트 빌더 인스턴스 (기본: 베타 환경)
|
|
2060
|
-
*/
|
|
2061
|
-
const endpoints = new EndpointBuilder();
|
|
2629
|
+
}
|
|
2062
2630
|
|
|
2063
2631
|
/**
|
|
2064
2632
|
* AdStage SDK - Ads 모듈
|
|
@@ -2071,6 +2639,8 @@ class AdsModule {
|
|
|
2071
2639
|
this.slots = new Map();
|
|
2072
2640
|
// Advertisement 이벤트 추적 관련
|
|
2073
2641
|
this.advertisementEventTracker = null;
|
|
2642
|
+
// 렌더링 관련
|
|
2643
|
+
this.adRenderer = null;
|
|
2074
2644
|
}
|
|
2075
2645
|
/**
|
|
2076
2646
|
* Ads 모듈 초기화 (동기)
|
|
@@ -2079,6 +2649,8 @@ class AdsModule {
|
|
|
2079
2649
|
this._config = config;
|
|
2080
2650
|
// AdvertisementEventTracker 초기화 (환경 자동 감지된 엔드포인트 사용)
|
|
2081
2651
|
this.advertisementEventTracker = new AdvertisementEventTracker(endpoints.getBaseUrl(), config.apiKey, config.debug || false, this.slots);
|
|
2652
|
+
// AdRenderer 초기화
|
|
2653
|
+
this.adRenderer = new AdRenderer(config.debug || false, this.advertisementEventTracker);
|
|
2082
2654
|
this._isReady = true;
|
|
2083
2655
|
if (config.debug) {
|
|
2084
2656
|
console.log('🎯 Ads module initialized (sync mode)');
|
|
@@ -2228,8 +2800,8 @@ class AdsModule {
|
|
|
2228
2800
|
}
|
|
2229
2801
|
// 고유한 슬롯 ID 생성
|
|
2230
2802
|
const slotId = `adstage-${type}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
|
2231
|
-
// 즉시 placeholder 생성
|
|
2232
|
-
this.
|
|
2803
|
+
// 즉시 placeholder 생성 (AdRenderer 위임)
|
|
2804
|
+
this.adRenderer?.createPlaceholder(container, slotId, type, options, this._config);
|
|
2233
2805
|
// 광고 슬롯 정보 저장
|
|
2234
2806
|
const slot = {
|
|
2235
2807
|
id: slotId,
|
|
@@ -2245,7 +2817,7 @@ class AdsModule {
|
|
|
2245
2817
|
advertisement: undefined, // 나중에 로드
|
|
2246
2818
|
config: { type, ...options },
|
|
2247
2819
|
load: async () => this.fetchAdData(type, options).then(ads => ads[0] || null),
|
|
2248
|
-
render: (ad) => this.renderAdElement(slot, ad),
|
|
2820
|
+
render: (ad) => this.adRenderer?.renderAdElement(slot, ad),
|
|
2249
2821
|
refresh: async () => this.refreshAdSlot(slot),
|
|
2250
2822
|
destroy: () => this.destroy(slotId)
|
|
2251
2823
|
};
|
|
@@ -2259,293 +2831,19 @@ class AdsModule {
|
|
|
2259
2831
|
}
|
|
2260
2832
|
return slotId;
|
|
2261
2833
|
}
|
|
2262
|
-
|
|
2263
|
-
* 즉시 광고 슬롯 생성 (placeholder)
|
|
2264
|
-
*/
|
|
2265
|
-
createAdSlot(container, slotId, type, options) {
|
|
2266
|
-
const adElement = document.createElement('div');
|
|
2267
|
-
adElement.id = slotId;
|
|
2268
|
-
adElement.className = `adstage-slot adstage-${type.toLowerCase()}`;
|
|
2269
|
-
// 확실한 컨테이너 식별을 위한 데이터 속성 추가
|
|
2270
|
-
adElement.setAttribute('data-adstage-container', 'true');
|
|
2271
|
-
adElement.setAttribute('data-adstage-type', type);
|
|
2272
|
-
adElement.setAttribute('data-adstage-slot', slotId);
|
|
2273
|
-
// 스마트한 크기 설정
|
|
2274
|
-
const { width, height } = this.calculateAdSize(container, type, options);
|
|
2275
|
-
adElement.style.width = width;
|
|
2276
|
-
adElement.style.height = height;
|
|
2277
|
-
adElement.style.border = '1px dashed #ccc';
|
|
2278
|
-
adElement.style.display = 'flex';
|
|
2279
|
-
adElement.style.alignItems = 'center';
|
|
2280
|
-
adElement.style.justifyContent = 'center';
|
|
2281
|
-
adElement.style.backgroundColor = '#f9f9f9';
|
|
2282
|
-
adElement.style.color = '#666';
|
|
2283
|
-
adElement.innerHTML = `<span>Loading ${type} ad...</span>`;
|
|
2284
|
-
container.appendChild(adElement);
|
|
2285
|
-
if (this._config?.debug) {
|
|
2286
|
-
console.log(`📦 Placeholder created for slot: ${slotId} (${width} x ${height})`);
|
|
2287
|
-
}
|
|
2288
|
-
}
|
|
2289
|
-
/**
|
|
2290
|
-
* 컨테이너와 광고 타입에 따른 스마트한 크기 계산
|
|
2291
|
-
*/
|
|
2292
|
-
calculateAdSize(container, type, options) {
|
|
2293
|
-
// 사용자가 명시적으로 크기를 지정한 경우
|
|
2294
|
-
const explicitWidth = options.width;
|
|
2295
|
-
const explicitHeight = options.height;
|
|
2296
|
-
// 너비 처리
|
|
2297
|
-
let width;
|
|
2298
|
-
if (typeof explicitWidth === 'number') {
|
|
2299
|
-
width = `${explicitWidth}px`;
|
|
2300
|
-
}
|
|
2301
|
-
else if (typeof explicitWidth === 'string') {
|
|
2302
|
-
width = explicitWidth;
|
|
2303
|
-
}
|
|
2304
|
-
else {
|
|
2305
|
-
width = '100%'; // 기본값은 100%
|
|
2306
|
-
}
|
|
2307
|
-
// 높이 처리 - 핵심 로직
|
|
2308
|
-
let height;
|
|
2309
|
-
if (typeof explicitHeight === 'number') {
|
|
2310
|
-
height = `${explicitHeight}px`;
|
|
2311
|
-
}
|
|
2312
|
-
else if (typeof explicitHeight === 'string' && explicitHeight !== '100%' && explicitHeight !== 'auto') {
|
|
2313
|
-
// 명시적인 크기 문자열 (예: '200px', '50vh' 등)
|
|
2314
|
-
height = explicitHeight;
|
|
2315
|
-
}
|
|
2316
|
-
else {
|
|
2317
|
-
// 100%, auto이거나 높이가 지정되지 않은 경우 스마트 계산
|
|
2318
|
-
const containerHeight = this.getContainerHeight(container);
|
|
2319
|
-
if (containerHeight > 0) {
|
|
2320
|
-
// 컨테이너에 높이가 있으면 100% 사용
|
|
2321
|
-
height = '100%';
|
|
2322
|
-
if (this._config?.debug) {
|
|
2323
|
-
console.log(`📏 Using 100% height (container: ${containerHeight}px)`);
|
|
2324
|
-
}
|
|
2325
|
-
}
|
|
2326
|
-
else {
|
|
2327
|
-
// 컨테이너에 높이가 없으면 타입별 기본값 사용 (나중에 동적 조정됨)
|
|
2328
|
-
height = this.getDefaultHeightForAdType(type);
|
|
2329
|
-
if (this._config?.debug) {
|
|
2330
|
-
console.log(`📏 Using default height ${height} (will be optimized for ${type})`);
|
|
2331
|
-
}
|
|
2332
|
-
}
|
|
2333
|
-
}
|
|
2334
|
-
return { width, height };
|
|
2335
|
-
}
|
|
2336
|
-
/**
|
|
2337
|
-
* 컨테이너의 실제 높이 계산
|
|
2338
|
-
*/
|
|
2339
|
-
getContainerHeight(container) {
|
|
2340
|
-
// 현재 계산된 스타일에서 높이 확인
|
|
2341
|
-
const computedStyle = window.getComputedStyle(container);
|
|
2342
|
-
const height = parseFloat(computedStyle.height);
|
|
2343
|
-
// height가 auto이거나 0이면 다른 방법들 시도
|
|
2344
|
-
if (!height || height === 0) {
|
|
2345
|
-
// min-height 확인
|
|
2346
|
-
const minHeight = parseFloat(computedStyle.minHeight);
|
|
2347
|
-
if (minHeight > 0)
|
|
2348
|
-
return minHeight;
|
|
2349
|
-
// CSS로 설정된 고정 높이 확인
|
|
2350
|
-
if (container.style.height && container.style.height !== 'auto') {
|
|
2351
|
-
const styleHeight = parseFloat(container.style.height);
|
|
2352
|
-
if (styleHeight > 0)
|
|
2353
|
-
return styleHeight;
|
|
2354
|
-
}
|
|
2355
|
-
// 속성으로 설정된 높이 확인
|
|
2356
|
-
const heightAttr = container.getAttribute('height');
|
|
2357
|
-
if (heightAttr) {
|
|
2358
|
-
const attrHeight = parseFloat(heightAttr);
|
|
2359
|
-
if (attrHeight > 0)
|
|
2360
|
-
return attrHeight;
|
|
2361
|
-
}
|
|
2362
|
-
}
|
|
2363
|
-
return height || 0;
|
|
2364
|
-
}
|
|
2365
|
-
/**
|
|
2366
|
-
* 광고 타입별 기본 높이 반환
|
|
2367
|
-
*/
|
|
2368
|
-
getDefaultHeightForAdType(type) {
|
|
2369
|
-
switch (type) {
|
|
2370
|
-
case AdType.BANNER:
|
|
2371
|
-
return '250px'; // 일반 배너
|
|
2372
|
-
case AdType.TEXT:
|
|
2373
|
-
return '120px'; // 텍스트는 좀 더 작게
|
|
2374
|
-
case AdType.VIDEO:
|
|
2375
|
-
return '360px'; // 비디오는 16:9 비율 고려
|
|
2376
|
-
case AdType.NATIVE:
|
|
2377
|
-
return '200px'; // 네이티브는 중간 크기
|
|
2378
|
-
case AdType.INTERSTITIAL:
|
|
2379
|
-
return '400px'; // 전면광고는 크게
|
|
2380
|
-
default:
|
|
2381
|
-
return '250px';
|
|
2382
|
-
}
|
|
2383
|
-
}
|
|
2384
|
-
/**
|
|
2385
|
-
* 이미지 크기 정보 로드 (프리로딩)
|
|
2386
|
-
*/
|
|
2387
|
-
async loadImageDimensions(imageUrl) {
|
|
2388
|
-
return new Promise((resolve, reject) => {
|
|
2389
|
-
const img = new Image();
|
|
2390
|
-
img.onload = () => {
|
|
2391
|
-
resolve({ width: img.naturalWidth, height: img.naturalHeight });
|
|
2392
|
-
};
|
|
2393
|
-
img.onerror = () => {
|
|
2394
|
-
reject(new Error(`Failed to load image: ${imageUrl}`));
|
|
2395
|
-
};
|
|
2396
|
-
img.src = imageUrl;
|
|
2397
|
-
});
|
|
2398
|
-
}
|
|
2834
|
+
// createAdSlot 제거: AdRenderer.createPlaceholder 사용
|
|
2399
2835
|
/**
|
|
2400
2836
|
* 여러 광고의 최적 컨테이너 크기 계산 (동적 크기 조정)
|
|
2401
2837
|
*/
|
|
2402
|
-
|
|
2403
|
-
|
|
2404
|
-
|
|
2405
|
-
|
|
2406
|
-
|
|
2407
|
-
|
|
2408
|
-
|
|
2409
|
-
|
|
2410
|
-
|
|
2411
|
-
try {
|
|
2412
|
-
// 모든 배너 이미지의 크기 정보 로드
|
|
2413
|
-
const imageDimensions = await Promise.allSettled(advertisements
|
|
2414
|
-
.filter(ad => ad.imageUrl)
|
|
2415
|
-
.map(ad => this.loadImageDimensions(ad.imageUrl)));
|
|
2416
|
-
const validDimensions = imageDimensions
|
|
2417
|
-
.filter((result) => result.status === 'fulfilled')
|
|
2418
|
-
.map(result => result.value);
|
|
2419
|
-
if (validDimensions.length === 0) {
|
|
2420
|
-
// 이미지 로드 실패시 기본값
|
|
2421
|
-
return {
|
|
2422
|
-
width: '100%',
|
|
2423
|
-
height: this.getDefaultHeightForAdType(adType),
|
|
2424
|
-
aspectRatio: 16 / 9
|
|
2425
|
-
};
|
|
2426
|
-
}
|
|
2427
|
-
// 최적 전략 선택
|
|
2428
|
-
const strategy = this.selectOptimalSizeStrategy(validDimensions);
|
|
2429
|
-
const optimalHeight = this.calculateOptimalHeight(validDimensions, containerWidth, strategy);
|
|
2430
|
-
if (this._config?.debug) {
|
|
2431
|
-
console.log(`📐 Optimal container calculated: ${containerWidth}x${optimalHeight} (strategy: ${strategy})`);
|
|
2432
|
-
}
|
|
2433
|
-
return {
|
|
2434
|
-
width: '100%',
|
|
2435
|
-
height: `${optimalHeight}px`,
|
|
2436
|
-
aspectRatio: containerWidth / optimalHeight
|
|
2437
|
-
};
|
|
2438
|
-
}
|
|
2439
|
-
catch (error) {
|
|
2440
|
-
console.warn('Failed to calculate optimal size, using defaults:', error);
|
|
2441
|
-
return {
|
|
2442
|
-
width: '100%',
|
|
2443
|
-
height: this.getDefaultHeightForAdType(adType),
|
|
2444
|
-
aspectRatio: 16 / 9
|
|
2445
|
-
};
|
|
2446
|
-
}
|
|
2447
|
-
}
|
|
2448
|
-
/**
|
|
2449
|
-
* 최적 크기 조정 전략 선택
|
|
2450
|
-
*/
|
|
2451
|
-
selectOptimalSizeStrategy(dimensions) {
|
|
2452
|
-
const aspectRatios = dimensions.map(d => d.width / d.height);
|
|
2453
|
-
// 1. 공통 비율이 있는지 확인 (±0.1 허용)
|
|
2454
|
-
const ratioGroups = new Map();
|
|
2455
|
-
aspectRatios.forEach(ratio => {
|
|
2456
|
-
const roundedRatio = Math.round(ratio * 10) / 10;
|
|
2457
|
-
const key = roundedRatio.toString();
|
|
2458
|
-
ratioGroups.set(key, (ratioGroups.get(key) || 0) + 1);
|
|
2459
|
-
});
|
|
2460
|
-
const maxGroup = Math.max(...ratioGroups.values());
|
|
2461
|
-
const totalImages = dimensions.length;
|
|
2462
|
-
// 70% 이상이 비슷한 비율이면 dominant 전략
|
|
2463
|
-
if (maxGroup / totalImages >= 0.7) {
|
|
2464
|
-
return 'dominant';
|
|
2465
|
-
}
|
|
2466
|
-
// 표준 비율들이 많으면 common 전략
|
|
2467
|
-
const standardRatios = [16 / 9, 4 / 3, 1 / 1, 3 / 2];
|
|
2468
|
-
const standardCount = aspectRatios.filter(ratio => standardRatios.some(standard => Math.abs(ratio - standard) < 0.1)).length;
|
|
2469
|
-
if (standardCount / totalImages >= 0.5) {
|
|
2470
|
-
return 'common';
|
|
2471
|
-
}
|
|
2472
|
-
// 기본은 평균 전략
|
|
2473
|
-
return 'average';
|
|
2474
|
-
}
|
|
2475
|
-
/**
|
|
2476
|
-
* 전략에 따른 최적 높이 계산
|
|
2477
|
-
*/
|
|
2478
|
-
calculateOptimalHeight(dimensions, containerWidth, strategy) {
|
|
2479
|
-
const aspectRatios = dimensions.map(d => d.width / d.height);
|
|
2480
|
-
switch (strategy) {
|
|
2481
|
-
case 'dominant':
|
|
2482
|
-
// 가장 많은 비율을 기준으로
|
|
2483
|
-
const ratioGroups = new Map();
|
|
2484
|
-
aspectRatios.forEach(ratio => {
|
|
2485
|
-
const roundedRatio = Math.round(ratio * 10) / 10;
|
|
2486
|
-
const key = roundedRatio.toString();
|
|
2487
|
-
const existing = ratioGroups.get(key);
|
|
2488
|
-
if (existing) {
|
|
2489
|
-
existing.count++;
|
|
2490
|
-
}
|
|
2491
|
-
else {
|
|
2492
|
-
ratioGroups.set(key, { ratio: roundedRatio, count: 1 });
|
|
2493
|
-
}
|
|
2494
|
-
});
|
|
2495
|
-
const dominantGroup = Array.from(ratioGroups.values())
|
|
2496
|
-
.reduce((max, current) => current.count > max.count ? current : max);
|
|
2497
|
-
return Math.round(containerWidth / dominantGroup.ratio);
|
|
2498
|
-
case 'common':
|
|
2499
|
-
// 표준 비율 중 가장 적합한 것 선택
|
|
2500
|
-
const standardRatios = [
|
|
2501
|
-
{ ratio: 16 / 9, name: '16:9' },
|
|
2502
|
-
{ ratio: 4 / 3, name: '4:3' },
|
|
2503
|
-
{ ratio: 1 / 1, name: '1:1' },
|
|
2504
|
-
{ ratio: 3 / 2, name: '3:2' }
|
|
2505
|
-
];
|
|
2506
|
-
const avgRatio = aspectRatios.reduce((sum, ratio) => sum + ratio, 0) / aspectRatios.length;
|
|
2507
|
-
const bestStandard = standardRatios.reduce((best, current) => Math.abs(current.ratio - avgRatio) < Math.abs(best.ratio - avgRatio) ? current : best);
|
|
2508
|
-
if (this._config?.debug) {
|
|
2509
|
-
console.log(`📊 Using standard ratio: ${bestStandard.name} (avg: ${avgRatio.toFixed(2)})`);
|
|
2510
|
-
}
|
|
2511
|
-
return Math.round(containerWidth / bestStandard.ratio);
|
|
2512
|
-
case 'average':
|
|
2513
|
-
default:
|
|
2514
|
-
// 평균 비율 사용
|
|
2515
|
-
const averageRatio = aspectRatios.reduce((sum, ratio) => sum + ratio, 0) / aspectRatios.length;
|
|
2516
|
-
return Math.round(containerWidth / averageRatio);
|
|
2517
|
-
}
|
|
2518
|
-
}
|
|
2519
|
-
/**
|
|
2520
|
-
* 개별 이미지에 최적화된 렌더링 스타일 적용
|
|
2521
|
-
*/
|
|
2522
|
-
applyOptimizedImageStyle(img, imageAspectRatio, containerAspectRatio) {
|
|
2523
|
-
const ratio = imageAspectRatio / containerAspectRatio;
|
|
2524
|
-
if (Math.abs(ratio - 1) < 0.1) {
|
|
2525
|
-
// 비율이 거의 같으면 cover 사용
|
|
2526
|
-
img.style.objectFit = 'cover';
|
|
2527
|
-
img.style.objectPosition = 'center';
|
|
2528
|
-
}
|
|
2529
|
-
else if (ratio > 1.3) {
|
|
2530
|
-
// 이미지가 훨씬 가로형이면 contain으로 전체 보이기
|
|
2531
|
-
img.style.objectFit = 'contain';
|
|
2532
|
-
img.style.objectPosition = 'center';
|
|
2533
|
-
img.style.backgroundColor = '#f0f0f0'; // 빈 공간 배경색
|
|
2534
|
-
}
|
|
2535
|
-
else if (ratio < 0.7) {
|
|
2536
|
-
// 이미지가 훨씬 세로형이면 cover로 채우기
|
|
2537
|
-
img.style.objectFit = 'cover';
|
|
2538
|
-
img.style.objectPosition = 'center';
|
|
2539
|
-
}
|
|
2540
|
-
else {
|
|
2541
|
-
// 적당한 차이면 스마트 cover
|
|
2542
|
-
img.style.objectFit = 'cover';
|
|
2543
|
-
img.style.objectPosition = 'center';
|
|
2544
|
-
}
|
|
2545
|
-
if (this._config?.debug) {
|
|
2546
|
-
console.log(`🎨 Image style applied: objectFit=${img.style.objectFit}, ratio=${ratio.toFixed(2)}`);
|
|
2547
|
-
}
|
|
2548
|
-
}
|
|
2838
|
+
// calculateOptimalContainerSize 제거: AdRenderer.calculateOptimalContainerSize 사용
|
|
2839
|
+
/**
|
|
2840
|
+
* 최적 크기 조정 전략 선택
|
|
2841
|
+
*/
|
|
2842
|
+
// selectOptimalSizeStrategy 제거: AdRenderer 내부 구현 사용
|
|
2843
|
+
/**
|
|
2844
|
+
* 전략에 따른 최적 높이 계산
|
|
2845
|
+
*/
|
|
2846
|
+
// calculateOptimalHeight 제거: AdRenderer 내부 구현 사용
|
|
2549
2847
|
/**
|
|
2550
2848
|
* 백그라운드에서 광고 콘텐츠 로드
|
|
2551
2849
|
*/
|
|
@@ -2554,21 +2852,21 @@ class AdsModule {
|
|
|
2554
2852
|
// 광고 데이터 가져오기 - 여러 개 로드
|
|
2555
2853
|
const adstageData = await this.fetchAdData(slot.adType, slot.config);
|
|
2556
2854
|
if (!adstageData || adstageData.length === 0) {
|
|
2557
|
-
this.renderFallback(slot);
|
|
2855
|
+
this.adRenderer?.renderFallback(slot);
|
|
2558
2856
|
return;
|
|
2559
2857
|
}
|
|
2560
2858
|
// 🆕 동적 크기 조정: 배너 광고의 경우 이미지 크기 기반으로 컨테이너 최적화
|
|
2561
2859
|
if (slot.adType === AdType.BANNER && adstageData.length > 0) {
|
|
2562
|
-
await this.optimizeContainerForBannerAds(slot, adstageData);
|
|
2860
|
+
await this.adRenderer?.optimizeContainerForBannerAds(slot, adstageData);
|
|
2563
2861
|
}
|
|
2564
2862
|
// 광고가 여러 개이거나 autoSlide 옵션이 있으면 슬라이더로 렌더링
|
|
2565
2863
|
if (adstageData.length > 1 || slot.config?.autoSlide) {
|
|
2566
|
-
await this.renderAdSlider(slot, adstageData);
|
|
2864
|
+
await this.adRenderer?.renderAdSlider(slot, adstageData);
|
|
2567
2865
|
}
|
|
2568
2866
|
else {
|
|
2569
2867
|
// 광고가 1개면 일반 렌더링
|
|
2570
2868
|
slot.advertisement = adstageData[0];
|
|
2571
|
-
await this.renderAdElement(slot, adstageData[0]);
|
|
2869
|
+
await this.adRenderer?.renderAdElement(slot, adstageData[0]);
|
|
2572
2870
|
// ✅ 신규: Viewable impression 추적 시작 (기존 즉시 추적 대신)
|
|
2573
2871
|
this.startBasicViewabilityTracking(slot, adstageData[0]);
|
|
2574
2872
|
}
|
|
@@ -2579,35 +2877,13 @@ class AdsModule {
|
|
|
2579
2877
|
}
|
|
2580
2878
|
catch (error) {
|
|
2581
2879
|
console.error(`❌ Failed to load ad for slot: ${slot.id}`, error);
|
|
2582
|
-
this.renderFallback(slot);
|
|
2880
|
+
this.adRenderer?.renderFallback(slot);
|
|
2583
2881
|
}
|
|
2584
2882
|
}
|
|
2585
2883
|
/**
|
|
2586
2884
|
* 배너 광고를 위한 컨테이너 최적화
|
|
2587
2885
|
*/
|
|
2588
|
-
|
|
2589
|
-
try {
|
|
2590
|
-
const container = document.getElementById(slot.containerId);
|
|
2591
|
-
const adElement = document.getElementById(slot.id);
|
|
2592
|
-
if (!container || !adElement)
|
|
2593
|
-
return;
|
|
2594
|
-
// 현재 컨테이너 너비 확인
|
|
2595
|
-
const containerWidth = container.getBoundingClientRect().width || 300;
|
|
2596
|
-
// 최적 크기 계산
|
|
2597
|
-
const optimalSize = await this.calculateOptimalContainerSize(advertisements, containerWidth, slot.adType);
|
|
2598
|
-
// 컨테이너 크기 동적 조정
|
|
2599
|
-
adElement.style.height = optimalSize.height;
|
|
2600
|
-
// 슬롯 정보 업데이트
|
|
2601
|
-
slot.optimizedHeight = optimalSize.height;
|
|
2602
|
-
slot.aspectRatio = optimalSize.aspectRatio;
|
|
2603
|
-
if (this._config?.debug) {
|
|
2604
|
-
console.log(`🔧 Container optimized for ${advertisements.length} banner ads: ${optimalSize.height}`);
|
|
2605
|
-
}
|
|
2606
|
-
}
|
|
2607
|
-
catch (error) {
|
|
2608
|
-
console.warn('Container optimization failed, using default size:', error);
|
|
2609
|
-
}
|
|
2610
|
-
}
|
|
2886
|
+
// optimizeContainerForBannerAds 제거: AdRenderer.optimizeContainerForBannerAds 사용
|
|
2611
2887
|
/**
|
|
2612
2888
|
* 기본 viewability 추적 시작
|
|
2613
2889
|
*/
|
|
@@ -2661,109 +2937,11 @@ class AdsModule {
|
|
|
2661
2937
|
/**
|
|
2662
2938
|
* Fallback 광고 렌더링 - AdStage 확실한 컨테이너 우선 탐지
|
|
2663
2939
|
*/
|
|
2664
|
-
renderFallback
|
|
2665
|
-
const element = document.getElementById(slot.id);
|
|
2666
|
-
if (element) {
|
|
2667
|
-
// 1순위: AdStage가 생성한 확실한 컨테이너들 (데이터 속성 기반)
|
|
2668
|
-
const adstageContainers = [
|
|
2669
|
-
element.querySelector('[data-adstage-container="true"]'), // 내부 AdStage 컨테이너
|
|
2670
|
-
element.closest('[data-adstage-container="true"]'), // 상위 AdStage 컨테이너
|
|
2671
|
-
element, // 자기 자신이 AdStage 컨테이너인 경우
|
|
2672
|
-
].filter(el => el && el.hasAttribute('data-adstage-container'));
|
|
2673
|
-
// 2순위: AdStage 클래스 기반 컨테이너들
|
|
2674
|
-
const classBasedContainers = [
|
|
2675
|
-
element.closest('.adstage-slot'),
|
|
2676
|
-
element.closest('.adstage-banner'),
|
|
2677
|
-
element.closest('.adstage-text'),
|
|
2678
|
-
element.closest('.adstage-video'),
|
|
2679
|
-
element.closest('.adstage-native'),
|
|
2680
|
-
element.closest('.adstage-interstitial'),
|
|
2681
|
-
].filter(Boolean);
|
|
2682
|
-
// 3순위: 일반적인 광고 컨테이너 패턴들 (fallback)
|
|
2683
|
-
const generalContainers = [
|
|
2684
|
-
element.closest('[class*="ad"]'),
|
|
2685
|
-
element.closest('[class*="banner"]'),
|
|
2686
|
-
element.closest('[class*="container"]'),
|
|
2687
|
-
element.closest('div[style*="height"]'),
|
|
2688
|
-
element.closest('div[style*="min-height"]'),
|
|
2689
|
-
element.parentElement
|
|
2690
|
-
].filter(Boolean);
|
|
2691
|
-
// 우선순위에 따라 컨테이너 선택
|
|
2692
|
-
const possibleContainers = [
|
|
2693
|
-
...adstageContainers,
|
|
2694
|
-
...classBasedContainers,
|
|
2695
|
-
...generalContainers
|
|
2696
|
-
];
|
|
2697
|
-
// 가장 적절한 컨테이너 선택
|
|
2698
|
-
const targetContainer = possibleContainers[0];
|
|
2699
|
-
if (targetContainer) {
|
|
2700
|
-
// 컨테이너 타입 로깅
|
|
2701
|
-
let containerType = 'unknown';
|
|
2702
|
-
if (targetContainer.hasAttribute('data-adstage-container')) {
|
|
2703
|
-
containerType = 'adstage-official';
|
|
2704
|
-
}
|
|
2705
|
-
else if (targetContainer.classList.contains('adstage-slot')) {
|
|
2706
|
-
containerType = 'adstage-class';
|
|
2707
|
-
}
|
|
2708
|
-
else {
|
|
2709
|
-
containerType = 'generic';
|
|
2710
|
-
}
|
|
2711
|
-
targetContainer.style.cssText += `
|
|
2712
|
-
height: 0px !important;
|
|
2713
|
-
min-height: 0px !important;
|
|
2714
|
-
padding: 0px !important;
|
|
2715
|
-
margin: 0px !important;
|
|
2716
|
-
border: none !important;
|
|
2717
|
-
overflow: hidden !important;
|
|
2718
|
-
display: block !important;
|
|
2719
|
-
`;
|
|
2720
|
-
// 내부 모든 요소 제거
|
|
2721
|
-
targetContainer.innerHTML = '';
|
|
2722
|
-
// 빈 상태임을 표시하는 속성 추가
|
|
2723
|
-
targetContainer.setAttribute('data-adstage-empty', 'true');
|
|
2724
|
-
if (this._config?.debug) {
|
|
2725
|
-
console.warn(`⚠️ Ad container collapsed (${containerType}): ${slot.id}`, targetContainer);
|
|
2726
|
-
}
|
|
2727
|
-
}
|
|
2728
|
-
else {
|
|
2729
|
-
// 컨테이너를 찾지 못한 경우 새로운 빈 컨테이너 생성
|
|
2730
|
-
this.createEmptyContainer(slot);
|
|
2731
|
-
}
|
|
2732
|
-
}
|
|
2733
|
-
// 슬롯 상태 업데이트 (제거하지 않고 빈 상태로 마킹)
|
|
2734
|
-
slot.advertisement = undefined;
|
|
2735
|
-
slot.isEmpty = true;
|
|
2736
|
-
}
|
|
2940
|
+
// renderFallback 제거: AdRenderer.renderFallback 사용
|
|
2737
2941
|
/**
|
|
2738
2942
|
* 빈 컨테이너 생성 (컨테이너를 찾지 못한 경우)
|
|
2739
2943
|
*/
|
|
2740
|
-
createEmptyContainer
|
|
2741
|
-
const originalContainer = document.getElementById(slot.containerId);
|
|
2742
|
-
if (originalContainer) {
|
|
2743
|
-
// 기존 내용 제거
|
|
2744
|
-
originalContainer.innerHTML = '';
|
|
2745
|
-
// 빈 AdStage 컨테이너 생성
|
|
2746
|
-
const emptyElement = document.createElement('div');
|
|
2747
|
-
emptyElement.id = slot.id;
|
|
2748
|
-
emptyElement.className = 'adstage-slot adstage-empty';
|
|
2749
|
-
emptyElement.setAttribute('data-adstage-container', 'true');
|
|
2750
|
-
emptyElement.setAttribute('data-adstage-empty', 'true');
|
|
2751
|
-
emptyElement.setAttribute('data-adstage-slot', slot.id);
|
|
2752
|
-
emptyElement.style.cssText = `
|
|
2753
|
-
height: 0px !important;
|
|
2754
|
-
min-height: 0px !important;
|
|
2755
|
-
padding: 0px !important;
|
|
2756
|
-
margin: 0px !important;
|
|
2757
|
-
border: none !important;
|
|
2758
|
-
overflow: hidden !important;
|
|
2759
|
-
display: block !important;
|
|
2760
|
-
`;
|
|
2761
|
-
originalContainer.appendChild(emptyElement);
|
|
2762
|
-
if (this._config?.debug) {
|
|
2763
|
-
console.warn(`⚠️ Created empty AdStage container: ${slot.id}`);
|
|
2764
|
-
}
|
|
2765
|
-
}
|
|
2766
|
-
}
|
|
2944
|
+
// createEmptyContainer 제거: AdRenderer 내부 구현 사용
|
|
2767
2945
|
/**
|
|
2768
2946
|
* 광고 데이터 가져오기
|
|
2769
2947
|
*/
|
|
@@ -2806,228 +2984,15 @@ class AdsModule {
|
|
|
2806
2984
|
/**
|
|
2807
2985
|
* 광고 슬라이더 렌더링 (여러 광고 또는 autoSlide 옵션)
|
|
2808
2986
|
*/
|
|
2809
|
-
|
|
2810
|
-
const container = document.getElementById(slot.containerId);
|
|
2811
|
-
if (!container) {
|
|
2812
|
-
throw new Error(`Container not found: ${slot.containerId}`);
|
|
2813
|
-
}
|
|
2814
|
-
// 이벤트 추적 콜백 함수 (중복 노출 방지 포함)
|
|
2815
|
-
const trackEventCallback = async (adId, slotId, eventType) => {
|
|
2816
|
-
// 노출 이벤트인 경우 중복 확인
|
|
2817
|
-
if (eventType === AdEventType.VIEWABLE) {
|
|
2818
|
-
if (ViewableEventTracker.isDuplicateViewable(adId, slotId, this._config?.debug)) {
|
|
2819
|
-
if (this._config?.debug) {
|
|
2820
|
-
console.log(`🚫 Duplicate viewable blocked for ad ${adId} in slot ${slotId}`);
|
|
2821
|
-
}
|
|
2822
|
-
return; // 중복 노출이면 추적하지 않음
|
|
2823
|
-
}
|
|
2824
|
-
if (this._config?.debug) {
|
|
2825
|
-
console.log(`✅ New viewable recorded for ad ${adId} in slot ${slotId}`);
|
|
2826
|
-
}
|
|
2827
|
-
}
|
|
2828
|
-
// 실제 API 호출로 이벤트 전송
|
|
2829
|
-
if (this.advertisementEventTracker) {
|
|
2830
|
-
try {
|
|
2831
|
-
await this.advertisementEventTracker.trackAdvertisementEvent(adId, slotId, eventType, {} // 기본 메타데이터
|
|
2832
|
-
);
|
|
2833
|
-
if (this._config?.debug) {
|
|
2834
|
-
console.log(`📊 Advertisement event tracked: ${eventType} for ad ${adId} in slot ${slotId}`);
|
|
2835
|
-
}
|
|
2836
|
-
}
|
|
2837
|
-
catch (error) {
|
|
2838
|
-
if (this._config?.debug) {
|
|
2839
|
-
console.error(`❌ Failed to track ${eventType} event for ad ${adId}:`, error);
|
|
2840
|
-
}
|
|
2841
|
-
}
|
|
2842
|
-
}
|
|
2843
|
-
// 🆕 슬라이더에서 VIEWABLE 이벤트 발생 시 해당 광고로 ViewabilityTracker 교체
|
|
2844
|
-
if (eventType === AdEventType.VIEWABLE && advertisements.length > 1) {
|
|
2845
|
-
const currentAd = advertisements.find(ad => ad._id === adId);
|
|
2846
|
-
if (currentAd) {
|
|
2847
|
-
// 기존 ViewabilityTracker 정리
|
|
2848
|
-
if (slot.viewabilityTracker) {
|
|
2849
|
-
slot.viewabilityTracker.destroy();
|
|
2850
|
-
slot.viewabilityTracker = null;
|
|
2851
|
-
}
|
|
2852
|
-
// 현재 광고에 대해 새로운 ViewabilityTracker 시작
|
|
2853
|
-
this.startBasicViewabilityTracking(slot, currentAd);
|
|
2854
|
-
if (this._config?.debug) {
|
|
2855
|
-
console.log(`🔄 ViewabilityTracker switched to ad ${adId} in slider: ${slot.id}`);
|
|
2856
|
-
}
|
|
2857
|
-
}
|
|
2858
|
-
}
|
|
2859
|
-
};
|
|
2860
|
-
let sliderElement;
|
|
2861
|
-
// 최적화된 슬라이더 옵션 준비
|
|
2862
|
-
const optimizedSliderOptions = {
|
|
2863
|
-
autoSlideInterval: (slot.config?.slideInterval || 5000) / 1000,
|
|
2864
|
-
...slot.config,
|
|
2865
|
-
// 🆕 동적 크기 정보 전달
|
|
2866
|
-
optimizedHeight: slot.optimizedHeight,
|
|
2867
|
-
aspectRatio: slot.aspectRatio
|
|
2868
|
-
};
|
|
2869
|
-
// 텍스트 광고는 TextTransitionManager 사용, 그 외는 CarouselSliderManager 사용
|
|
2870
|
-
if (slot.adType === AdType.TEXT) {
|
|
2871
|
-
sliderElement = TextTransitionManager.createTextTransitionContainer(slot, advertisements, optimizedSliderOptions, trackEventCallback);
|
|
2872
|
-
if (this._config?.debug) {
|
|
2873
|
-
console.log(`✨ Text transition created for TEXT slot: ${slot.id} with ${advertisements.length} ads`);
|
|
2874
|
-
}
|
|
2875
|
-
}
|
|
2876
|
-
else {
|
|
2877
|
-
sliderElement = CarouselSliderManager.createSliderContainer(slot, advertisements, optimizedSliderOptions, trackEventCallback);
|
|
2878
|
-
if (this._config?.debug) {
|
|
2879
|
-
console.log(`🎠 Carousel slider created for ${slot.adType} slot: ${slot.id} with ${advertisements.length} ads (optimized: ${slot.optimizedHeight || 'default'})`);
|
|
2880
|
-
}
|
|
2881
|
-
}
|
|
2882
|
-
// 기존 내용 제거하고 슬라이더 추가
|
|
2883
|
-
container.innerHTML = '';
|
|
2884
|
-
container.appendChild(sliderElement);
|
|
2885
|
-
// ✅ 신규: 슬라이더에서도 첫 번째 광고에 대해 ViewabilityTracker 시작
|
|
2886
|
-
if (advertisements.length > 0) {
|
|
2887
|
-
this.startBasicViewabilityTracking(slot, advertisements[0]);
|
|
2888
|
-
if (this._config?.debug) {
|
|
2889
|
-
console.log(`🎯 Viewability tracking started for first ad in slider: ${slot.id}`);
|
|
2890
|
-
}
|
|
2891
|
-
}
|
|
2892
|
-
}
|
|
2987
|
+
// renderAdSlider 제거: AdRenderer.renderAdSlider 사용
|
|
2893
2988
|
/**
|
|
2894
2989
|
* 광고 렌더링 (단일 광고용)
|
|
2895
2990
|
*/
|
|
2896
|
-
|
|
2897
|
-
if (!slot.advertisement) {
|
|
2898
|
-
throw new Error('No advertisement to render');
|
|
2899
|
-
}
|
|
2900
|
-
await this.renderAdElement(slot, slot.advertisement);
|
|
2901
|
-
slot.isLoaded = true;
|
|
2902
|
-
}
|
|
2991
|
+
// renderAd 제거: AdRenderer.renderAd 사용
|
|
2903
2992
|
/**
|
|
2904
2993
|
* 광고 요소 렌더링 (기본 구현)
|
|
2905
2994
|
*/
|
|
2906
|
-
|
|
2907
|
-
const container = document.getElementById(slot.containerId);
|
|
2908
|
-
if (!container)
|
|
2909
|
-
return;
|
|
2910
|
-
// 기본 HTML 구조 생성
|
|
2911
|
-
const adElement = document.createElement('div');
|
|
2912
|
-
adElement.className = 'adstage-ad';
|
|
2913
|
-
// 스마트한 크기 설정 - 최적화된 크기가 있으면 사용
|
|
2914
|
-
const optimizedHeight = slot.optimizedHeight;
|
|
2915
|
-
const containerElement = container.parentElement || container;
|
|
2916
|
-
if (optimizedHeight) {
|
|
2917
|
-
adElement.style.width = '100%';
|
|
2918
|
-
adElement.style.height = optimizedHeight;
|
|
2919
|
-
}
|
|
2920
|
-
else {
|
|
2921
|
-
const { width, height } = this.calculateAdSize(containerElement, slot.adType, slot.config || {});
|
|
2922
|
-
adElement.style.width = width;
|
|
2923
|
-
adElement.style.height = height;
|
|
2924
|
-
}
|
|
2925
|
-
// 광고 타입별 렌더링
|
|
2926
|
-
switch (slot.adType) {
|
|
2927
|
-
case AdType.BANNER:
|
|
2928
|
-
if (ad.imageUrl) {
|
|
2929
|
-
await this.renderOptimizedBannerImage(adElement, ad, slot);
|
|
2930
|
-
}
|
|
2931
|
-
break;
|
|
2932
|
-
case AdType.TEXT:
|
|
2933
|
-
const textDiv = document.createElement('div');
|
|
2934
|
-
textDiv.innerHTML = `
|
|
2935
|
-
<h3>${ad.title}</h3>
|
|
2936
|
-
${ad.description ? `<p>${ad.description}</p>` : ''}
|
|
2937
|
-
${ad.textContent ? `<div>${ad.textContent}</div>` : ''}
|
|
2938
|
-
`;
|
|
2939
|
-
adElement.appendChild(textDiv);
|
|
2940
|
-
break;
|
|
2941
|
-
case AdType.VIDEO:
|
|
2942
|
-
if (ad.videoUrl) {
|
|
2943
|
-
const video = document.createElement('video');
|
|
2944
|
-
video.src = ad.videoUrl;
|
|
2945
|
-
video.controls = true;
|
|
2946
|
-
video.style.width = '100%';
|
|
2947
|
-
video.style.height = '100%';
|
|
2948
|
-
adElement.appendChild(video);
|
|
2949
|
-
}
|
|
2950
|
-
break;
|
|
2951
|
-
default:
|
|
2952
|
-
adElement.innerHTML = `<div>${ad.title}</div>`;
|
|
2953
|
-
}
|
|
2954
|
-
// 클릭 이벤트 추가
|
|
2955
|
-
if (ad.linkUrl) {
|
|
2956
|
-
adElement.style.cursor = 'pointer';
|
|
2957
|
-
adElement.addEventListener('click', () => {
|
|
2958
|
-
window.open(ad.linkUrl, '_blank');
|
|
2959
|
-
});
|
|
2960
|
-
}
|
|
2961
|
-
container.innerHTML = '';
|
|
2962
|
-
container.appendChild(adElement);
|
|
2963
|
-
}
|
|
2964
|
-
/**
|
|
2965
|
-
* 최적화된 배너 이미지 렌더링
|
|
2966
|
-
*/
|
|
2967
|
-
async renderOptimizedBannerImage(adElement, ad, slot) {
|
|
2968
|
-
try {
|
|
2969
|
-
// 사용자가 크기를 지정했는지 확인
|
|
2970
|
-
const configWidth = slot.config?.width;
|
|
2971
|
-
const configHeight = slot.config?.height;
|
|
2972
|
-
const hasUserDefinedWidth = configWidth &&
|
|
2973
|
-
(typeof configWidth === 'number' || (typeof configWidth === 'string' && configWidth !== '100%'));
|
|
2974
|
-
const hasUserDefinedHeight = configHeight &&
|
|
2975
|
-
(typeof configHeight === 'number' || (typeof configHeight === 'string' && configHeight !== 'auto'));
|
|
2976
|
-
const hasUserDefinedSize = hasUserDefinedWidth || hasUserDefinedHeight;
|
|
2977
|
-
// 이미지 요소 생성
|
|
2978
|
-
const img = document.createElement('img');
|
|
2979
|
-
img.src = ad.imageUrl;
|
|
2980
|
-
img.alt = ad.title;
|
|
2981
|
-
if (hasUserDefinedSize) {
|
|
2982
|
-
// 🎯 사용자가 크기를 지정한 경우: 컨테이너에 꽉 차도록 설정
|
|
2983
|
-
img.style.width = '100%';
|
|
2984
|
-
img.style.height = '100%';
|
|
2985
|
-
img.style.objectFit = 'cover'; // 컨테이너에 꽉 찬 상태로 비율 유지
|
|
2986
|
-
img.style.objectPosition = 'center';
|
|
2987
|
-
if (this._config?.debug) {
|
|
2988
|
-
console.log(`🎯 User-defined size detected: filling container completely`);
|
|
2989
|
-
}
|
|
2990
|
-
}
|
|
2991
|
-
else {
|
|
2992
|
-
// 사용자가 크기를 지정하지 않은 경우: 동적 최적화 적용
|
|
2993
|
-
const imageDimensions = await this.loadImageDimensions(ad.imageUrl);
|
|
2994
|
-
const imageAspectRatio = imageDimensions.width / imageDimensions.height;
|
|
2995
|
-
const containerAspectRatio = slot.aspectRatio || 16 / 9;
|
|
2996
|
-
img.style.width = '100%';
|
|
2997
|
-
img.style.height = '100%';
|
|
2998
|
-
// 🎨 최적화된 스타일 적용
|
|
2999
|
-
this.applyOptimizedImageStyle(img, imageAspectRatio, containerAspectRatio);
|
|
3000
|
-
if (this._config?.debug) {
|
|
3001
|
-
console.log(`🖼️ Optimized banner image loaded: ${imageDimensions.width}x${imageDimensions.height} (ratio: ${imageAspectRatio.toFixed(2)})`);
|
|
3002
|
-
}
|
|
3003
|
-
}
|
|
3004
|
-
// 이미지 로드 완료 처리
|
|
3005
|
-
img.onload = () => {
|
|
3006
|
-
if (this._config?.debug) {
|
|
3007
|
-
console.log(`✅ Banner image loaded successfully`);
|
|
3008
|
-
}
|
|
3009
|
-
};
|
|
3010
|
-
// 에러 처리
|
|
3011
|
-
img.onerror = () => {
|
|
3012
|
-
console.warn(`Failed to load banner image: ${ad.imageUrl}`);
|
|
3013
|
-
// 폴백 텍스트 표시
|
|
3014
|
-
adElement.innerHTML = `<div style="display: flex; align-items: center; justify-content: center; background: #f0f0f0; color: #666;">${ad.title}</div>`;
|
|
3015
|
-
};
|
|
3016
|
-
adElement.appendChild(img);
|
|
3017
|
-
}
|
|
3018
|
-
catch (error) {
|
|
3019
|
-
console.warn('Failed to optimize banner image, using fallback:', error);
|
|
3020
|
-
// 기본 이미지 렌더링 (폴백)
|
|
3021
|
-
const img = document.createElement('img');
|
|
3022
|
-
img.src = ad.imageUrl;
|
|
3023
|
-
img.alt = ad.title;
|
|
3024
|
-
img.style.width = '100%';
|
|
3025
|
-
img.style.height = '100%';
|
|
3026
|
-
img.style.objectFit = 'cover';
|
|
3027
|
-
img.style.objectPosition = 'center'; // 🎯 폴백 이미지도 중앙 정렬
|
|
3028
|
-
adElement.appendChild(img);
|
|
3029
|
-
}
|
|
3030
|
-
}
|
|
2995
|
+
// renderAdElement 제거: AdRenderer.renderAdElement 사용
|
|
3031
2996
|
/**
|
|
3032
2997
|
* 광고 슬롯 새로고침
|
|
3033
2998
|
*/
|
|
@@ -3037,7 +3002,7 @@ class AdsModule {
|
|
|
3037
3002
|
const newAdData = await this.fetchAdData(slot.adType, slot.config || {});
|
|
3038
3003
|
if (newAdData && newAdData.length > 0) {
|
|
3039
3004
|
slot.advertisement = newAdData[0]; // 첫 번째 광고로 업데이트
|
|
3040
|
-
await this.renderAd(slot);
|
|
3005
|
+
await this.adRenderer?.renderAd(slot);
|
|
3041
3006
|
// 새로운 노출 추적
|
|
3042
3007
|
if (this.advertisementEventTracker) {
|
|
3043
3008
|
console.log('New advertisement viewable tracked for slot:', slot.id);
|
|
@@ -3284,13 +3249,6 @@ class AdStage {
|
|
|
3284
3249
|
productionMode: false,
|
|
3285
3250
|
...config
|
|
3286
3251
|
};
|
|
3287
|
-
// baseUrl이 설정되었으면 endpoints에 적용
|
|
3288
|
-
if (config.baseUrl) {
|
|
3289
|
-
endpoints.setBaseUrl(config.baseUrl);
|
|
3290
|
-
if (config.debug) {
|
|
3291
|
-
console.log('🔄 API base URL set to:', config.baseUrl);
|
|
3292
|
-
}
|
|
3293
|
-
}
|
|
3294
3252
|
// 모듈 동기 초기화
|
|
3295
3253
|
const enabledModules = instance._config.modules || ['ads', 'events', 'config'];
|
|
3296
3254
|
for (const moduleName of enabledModules) {
|
|
@@ -3353,82 +3311,6 @@ class AdStage {
|
|
|
3353
3311
|
}
|
|
3354
3312
|
}
|
|
3355
3313
|
|
|
3356
|
-
const AdStageContext = react.createContext(null);
|
|
3357
|
-
function AdStageProvider({ children, config }) {
|
|
3358
|
-
const [isInitialized, setIsInitialized] = react.useState(false);
|
|
3359
|
-
const [currentConfig, setCurrentConfig] = react.useState(null);
|
|
3360
|
-
const [error, setError] = react.useState(null);
|
|
3361
|
-
const initialize = (newConfig) => {
|
|
3362
|
-
try {
|
|
3363
|
-
setError(null);
|
|
3364
|
-
// 기존 인스턴스가 있으면 리셋
|
|
3365
|
-
if (isInitialized) {
|
|
3366
|
-
AdStage.reset();
|
|
3367
|
-
}
|
|
3368
|
-
AdStage.init(newConfig);
|
|
3369
|
-
setCurrentConfig(newConfig);
|
|
3370
|
-
setIsInitialized(true);
|
|
3371
|
-
if (newConfig.debug) {
|
|
3372
|
-
console.log('✅ AdStage SDK initialized successfully via React Provider');
|
|
3373
|
-
}
|
|
3374
|
-
}
|
|
3375
|
-
catch (err) {
|
|
3376
|
-
const errorMessage = err instanceof Error ? err.message : 'Unknown error';
|
|
3377
|
-
setError(errorMessage);
|
|
3378
|
-
console.error('❌ AdStage SDK initialization failed:', err);
|
|
3379
|
-
setIsInitialized(false);
|
|
3380
|
-
setCurrentConfig(null);
|
|
3381
|
-
}
|
|
3382
|
-
};
|
|
3383
|
-
const reset = () => {
|
|
3384
|
-
try {
|
|
3385
|
-
AdStage.reset();
|
|
3386
|
-
setIsInitialized(false);
|
|
3387
|
-
setCurrentConfig(null);
|
|
3388
|
-
setError(null);
|
|
3389
|
-
}
|
|
3390
|
-
catch (err) {
|
|
3391
|
-
console.error('❌ AdStage SDK reset failed:', err);
|
|
3392
|
-
}
|
|
3393
|
-
};
|
|
3394
|
-
// 자동 초기화
|
|
3395
|
-
react.useEffect(() => {
|
|
3396
|
-
if (config && !isInitialized) {
|
|
3397
|
-
initialize(config);
|
|
3398
|
-
}
|
|
3399
|
-
}, [config, isInitialized]);
|
|
3400
|
-
const contextValue = {
|
|
3401
|
-
isInitialized,
|
|
3402
|
-
config: currentConfig,
|
|
3403
|
-
initialize,
|
|
3404
|
-
reset,
|
|
3405
|
-
error
|
|
3406
|
-
};
|
|
3407
|
-
return (jsxRuntime.jsx(AdStageContext.Provider, { value: contextValue, children: children }));
|
|
3408
|
-
}
|
|
3409
|
-
/**
|
|
3410
|
-
* AdStage Context Hook
|
|
3411
|
-
* AdStageProvider 내에서 SDK 상태에 접근할 수 있습니다.
|
|
3412
|
-
*/
|
|
3413
|
-
function useAdStage() {
|
|
3414
|
-
const context = react.useContext(AdStageContext);
|
|
3415
|
-
if (!context) {
|
|
3416
|
-
throw new Error('useAdStage must be used within an AdStageProvider');
|
|
3417
|
-
}
|
|
3418
|
-
return context;
|
|
3419
|
-
}
|
|
3420
|
-
/**
|
|
3421
|
-
* AdStage SDK Hook
|
|
3422
|
-
* 초기화된 AdStage 인스턴스에 직접 접근할 수 있습니다.
|
|
3423
|
-
*/
|
|
3424
|
-
function useAdStageSDK() {
|
|
3425
|
-
const { isInitialized } = useAdStage();
|
|
3426
|
-
if (!isInitialized) {
|
|
3427
|
-
throw new Error('AdStage SDK is not initialized. Please call initialize() first or provide config to AdStageProvider.');
|
|
3428
|
-
}
|
|
3429
|
-
return AdStage;
|
|
3430
|
-
}
|
|
3431
|
-
|
|
3432
3314
|
/**
|
|
3433
3315
|
* AdStage Web SDK
|
|
3434
3316
|
* 네임스페이스 아키텍처 기반 SDK
|
|
@@ -3439,8 +3321,5 @@ const SDK_VERSION = '2.0.0';
|
|
|
3439
3321
|
const SUPPORTED_MODULES = ['ads', 'events', 'config'];
|
|
3440
3322
|
|
|
3441
3323
|
exports.AdStage = AdStage;
|
|
3442
|
-
exports.AdStageProvider = AdStageProvider;
|
|
3443
3324
|
exports.SDK_VERSION = SDK_VERSION;
|
|
3444
3325
|
exports.SUPPORTED_MODULES = SUPPORTED_MODULES;
|
|
3445
|
-
exports.useAdStage = useAdStage;
|
|
3446
|
-
exports.useAdStageSDK = useAdStageSDK;
|