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