@adstage/web-sdk 2.1.0 → 2.1.3

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/dist/index.cjs.js CHANGED
@@ -2217,8 +2217,14 @@ class AdsModule {
2217
2217
  const adElement = document.createElement('div');
2218
2218
  adElement.id = slotId;
2219
2219
  adElement.className = `adstage-slot adstage-${type.toLowerCase()}`;
2220
- adElement.style.width = typeof options.width === 'number' ? `${options.width}px` : (options.width || '100%');
2221
- adElement.style.height = typeof options.height === 'number' ? `${options.height}px` : (options.height || '250px');
2220
+ // 확실한 컨테이너 식별을 위한 데이터 속성 추가
2221
+ adElement.setAttribute('data-adstage-container', 'true');
2222
+ adElement.setAttribute('data-adstage-type', type);
2223
+ adElement.setAttribute('data-adstage-slot', slotId);
2224
+ // 스마트한 크기 설정
2225
+ const { width, height } = this.calculateAdSize(container, type, options);
2226
+ adElement.style.width = width;
2227
+ adElement.style.height = height;
2222
2228
  adElement.style.border = '1px dashed #ccc';
2223
2229
  adElement.style.display = 'flex';
2224
2230
  adElement.style.alignItems = 'center';
@@ -2228,7 +2234,266 @@ class AdsModule {
2228
2234
  adElement.innerHTML = `<span>Loading ${type} ad...</span>`;
2229
2235
  container.appendChild(adElement);
2230
2236
  if (this._config?.debug) {
2231
- console.log(`📦 Placeholder created for slot: ${slotId}`);
2237
+ console.log(`📦 Placeholder created for slot: ${slotId} (${width} x ${height})`);
2238
+ }
2239
+ }
2240
+ /**
2241
+ * 컨테이너와 광고 타입에 따른 스마트한 크기 계산
2242
+ */
2243
+ calculateAdSize(container, type, options) {
2244
+ // 사용자가 명시적으로 크기를 지정한 경우
2245
+ const explicitWidth = options.width;
2246
+ const explicitHeight = options.height;
2247
+ // 너비 처리
2248
+ let width;
2249
+ if (typeof explicitWidth === 'number') {
2250
+ width = `${explicitWidth}px`;
2251
+ }
2252
+ else if (typeof explicitWidth === 'string') {
2253
+ width = explicitWidth;
2254
+ }
2255
+ else {
2256
+ width = '100%'; // 기본값은 100%
2257
+ }
2258
+ // 높이 처리 - 핵심 로직
2259
+ let height;
2260
+ if (typeof explicitHeight === 'number') {
2261
+ height = `${explicitHeight}px`;
2262
+ }
2263
+ else if (typeof explicitHeight === 'string' && explicitHeight !== '100%') {
2264
+ height = explicitHeight;
2265
+ }
2266
+ else {
2267
+ // 100%이거나 높이가 지정되지 않은 경우 스마트 계산
2268
+ const containerHeight = this.getContainerHeight(container);
2269
+ if (containerHeight > 0) {
2270
+ // 컨테이너에 높이가 있으면 100% 사용
2271
+ height = '100%';
2272
+ if (this._config?.debug) {
2273
+ console.log(`📏 Using 100% height (container: ${containerHeight}px)`);
2274
+ }
2275
+ }
2276
+ else {
2277
+ // 컨테이너에 높이가 없으면 타입별 기본값 사용
2278
+ height = this.getDefaultHeightForAdType(type);
2279
+ if (this._config?.debug) {
2280
+ console.log(`📏 Using default height ${height} (no container height)`);
2281
+ }
2282
+ }
2283
+ }
2284
+ return { width, height };
2285
+ }
2286
+ /**
2287
+ * 컨테이너의 실제 높이 계산
2288
+ */
2289
+ getContainerHeight(container) {
2290
+ // 현재 계산된 스타일에서 높이 확인
2291
+ const computedStyle = window.getComputedStyle(container);
2292
+ const height = parseFloat(computedStyle.height);
2293
+ // height가 auto이거나 0이면 다른 방법들 시도
2294
+ if (!height || height === 0) {
2295
+ // min-height 확인
2296
+ const minHeight = parseFloat(computedStyle.minHeight);
2297
+ if (minHeight > 0)
2298
+ return minHeight;
2299
+ // CSS로 설정된 고정 높이 확인
2300
+ if (container.style.height && container.style.height !== 'auto') {
2301
+ const styleHeight = parseFloat(container.style.height);
2302
+ if (styleHeight > 0)
2303
+ return styleHeight;
2304
+ }
2305
+ // 속성으로 설정된 높이 확인
2306
+ const heightAttr = container.getAttribute('height');
2307
+ if (heightAttr) {
2308
+ const attrHeight = parseFloat(heightAttr);
2309
+ if (attrHeight > 0)
2310
+ return attrHeight;
2311
+ }
2312
+ }
2313
+ return height || 0;
2314
+ }
2315
+ /**
2316
+ * 광고 타입별 기본 높이 반환
2317
+ */
2318
+ getDefaultHeightForAdType(type) {
2319
+ switch (type) {
2320
+ case AdType.BANNER:
2321
+ return '250px'; // 일반 배너
2322
+ case AdType.TEXT:
2323
+ return '120px'; // 텍스트는 좀 더 작게
2324
+ case AdType.VIDEO:
2325
+ return '360px'; // 비디오는 16:9 비율 고려
2326
+ case AdType.NATIVE:
2327
+ return '200px'; // 네이티브는 중간 크기
2328
+ case AdType.INTERSTITIAL:
2329
+ return '400px'; // 전면광고는 크게
2330
+ default:
2331
+ return '250px';
2332
+ }
2333
+ }
2334
+ /**
2335
+ * 이미지 크기 정보 로드 (프리로딩)
2336
+ */
2337
+ async loadImageDimensions(imageUrl) {
2338
+ return new Promise((resolve, reject) => {
2339
+ const img = new Image();
2340
+ img.onload = () => {
2341
+ resolve({ width: img.naturalWidth, height: img.naturalHeight });
2342
+ };
2343
+ img.onerror = () => {
2344
+ reject(new Error(`Failed to load image: ${imageUrl}`));
2345
+ };
2346
+ img.src = imageUrl;
2347
+ });
2348
+ }
2349
+ /**
2350
+ * 여러 광고의 최적 컨테이너 크기 계산 (동적 크기 조정)
2351
+ */
2352
+ async calculateOptimalContainerSize(advertisements, containerWidth, adType) {
2353
+ if (!advertisements.length || adType !== AdType.BANNER) {
2354
+ // 배너가 아니거나 광고가 없으면 기본값
2355
+ return {
2356
+ width: '100%',
2357
+ height: this.getDefaultHeightForAdType(adType),
2358
+ aspectRatio: 16 / 9
2359
+ };
2360
+ }
2361
+ try {
2362
+ // 모든 배너 이미지의 크기 정보 로드
2363
+ const imageDimensions = await Promise.allSettled(advertisements
2364
+ .filter(ad => ad.imageUrl)
2365
+ .map(ad => this.loadImageDimensions(ad.imageUrl)));
2366
+ const validDimensions = imageDimensions
2367
+ .filter((result) => result.status === 'fulfilled')
2368
+ .map(result => result.value);
2369
+ if (validDimensions.length === 0) {
2370
+ // 이미지 로드 실패시 기본값
2371
+ return {
2372
+ width: '100%',
2373
+ height: this.getDefaultHeightForAdType(adType),
2374
+ aspectRatio: 16 / 9
2375
+ };
2376
+ }
2377
+ // 최적 전략 선택
2378
+ const strategy = this.selectOptimalSizeStrategy(validDimensions);
2379
+ const optimalHeight = this.calculateOptimalHeight(validDimensions, containerWidth, strategy);
2380
+ if (this._config?.debug) {
2381
+ console.log(`📐 Optimal container calculated: ${containerWidth}x${optimalHeight} (strategy: ${strategy})`);
2382
+ }
2383
+ return {
2384
+ width: '100%',
2385
+ height: `${optimalHeight}px`,
2386
+ aspectRatio: containerWidth / optimalHeight
2387
+ };
2388
+ }
2389
+ catch (error) {
2390
+ console.warn('Failed to calculate optimal size, using defaults:', error);
2391
+ return {
2392
+ width: '100%',
2393
+ height: this.getDefaultHeightForAdType(adType),
2394
+ aspectRatio: 16 / 9
2395
+ };
2396
+ }
2397
+ }
2398
+ /**
2399
+ * 최적 크기 조정 전략 선택
2400
+ */
2401
+ selectOptimalSizeStrategy(dimensions) {
2402
+ const aspectRatios = dimensions.map(d => d.width / d.height);
2403
+ // 1. 공통 비율이 있는지 확인 (±0.1 허용)
2404
+ const ratioGroups = new Map();
2405
+ aspectRatios.forEach(ratio => {
2406
+ const roundedRatio = Math.round(ratio * 10) / 10;
2407
+ const key = roundedRatio.toString();
2408
+ ratioGroups.set(key, (ratioGroups.get(key) || 0) + 1);
2409
+ });
2410
+ const maxGroup = Math.max(...ratioGroups.values());
2411
+ const totalImages = dimensions.length;
2412
+ // 70% 이상이 비슷한 비율이면 dominant 전략
2413
+ if (maxGroup / totalImages >= 0.7) {
2414
+ return 'dominant';
2415
+ }
2416
+ // 표준 비율들이 많으면 common 전략
2417
+ const standardRatios = [16 / 9, 4 / 3, 1 / 1, 3 / 2];
2418
+ const standardCount = aspectRatios.filter(ratio => standardRatios.some(standard => Math.abs(ratio - standard) < 0.1)).length;
2419
+ if (standardCount / totalImages >= 0.5) {
2420
+ return 'common';
2421
+ }
2422
+ // 기본은 평균 전략
2423
+ return 'average';
2424
+ }
2425
+ /**
2426
+ * 전략에 따른 최적 높이 계산
2427
+ */
2428
+ calculateOptimalHeight(dimensions, containerWidth, strategy) {
2429
+ const aspectRatios = dimensions.map(d => d.width / d.height);
2430
+ switch (strategy) {
2431
+ case 'dominant':
2432
+ // 가장 많은 비율을 기준으로
2433
+ const ratioGroups = new Map();
2434
+ aspectRatios.forEach(ratio => {
2435
+ const roundedRatio = Math.round(ratio * 10) / 10;
2436
+ const key = roundedRatio.toString();
2437
+ const existing = ratioGroups.get(key);
2438
+ if (existing) {
2439
+ existing.count++;
2440
+ }
2441
+ else {
2442
+ ratioGroups.set(key, { ratio: roundedRatio, count: 1 });
2443
+ }
2444
+ });
2445
+ const dominantGroup = Array.from(ratioGroups.values())
2446
+ .reduce((max, current) => current.count > max.count ? current : max);
2447
+ return Math.round(containerWidth / dominantGroup.ratio);
2448
+ case 'common':
2449
+ // 표준 비율 중 가장 적합한 것 선택
2450
+ const standardRatios = [
2451
+ { ratio: 16 / 9, name: '16:9' },
2452
+ { ratio: 4 / 3, name: '4:3' },
2453
+ { ratio: 1 / 1, name: '1:1' },
2454
+ { ratio: 3 / 2, name: '3:2' }
2455
+ ];
2456
+ const avgRatio = aspectRatios.reduce((sum, ratio) => sum + ratio, 0) / aspectRatios.length;
2457
+ const bestStandard = standardRatios.reduce((best, current) => Math.abs(current.ratio - avgRatio) < Math.abs(best.ratio - avgRatio) ? current : best);
2458
+ if (this._config?.debug) {
2459
+ console.log(`📊 Using standard ratio: ${bestStandard.name} (avg: ${avgRatio.toFixed(2)})`);
2460
+ }
2461
+ return Math.round(containerWidth / bestStandard.ratio);
2462
+ case 'average':
2463
+ default:
2464
+ // 평균 비율 사용
2465
+ const averageRatio = aspectRatios.reduce((sum, ratio) => sum + ratio, 0) / aspectRatios.length;
2466
+ return Math.round(containerWidth / averageRatio);
2467
+ }
2468
+ }
2469
+ /**
2470
+ * 개별 이미지에 최적화된 렌더링 스타일 적용
2471
+ */
2472
+ applyOptimizedImageStyle(img, imageAspectRatio, containerAspectRatio) {
2473
+ const ratio = imageAspectRatio / containerAspectRatio;
2474
+ if (Math.abs(ratio - 1) < 0.1) {
2475
+ // 비율이 거의 같으면 cover 사용
2476
+ img.style.objectFit = 'cover';
2477
+ img.style.objectPosition = 'center';
2478
+ }
2479
+ else if (ratio > 1.3) {
2480
+ // 이미지가 훨씬 가로형이면 contain으로 전체 보이기
2481
+ img.style.objectFit = 'contain';
2482
+ img.style.objectPosition = 'center';
2483
+ img.style.backgroundColor = '#f0f0f0'; // 빈 공간 배경색
2484
+ }
2485
+ else if (ratio < 0.7) {
2486
+ // 이미지가 훨씬 세로형이면 cover로 채우기
2487
+ img.style.objectFit = 'cover';
2488
+ img.style.objectPosition = 'center';
2489
+ }
2490
+ else {
2491
+ // 적당한 차이면 스마트 cover
2492
+ img.style.objectFit = 'cover';
2493
+ img.style.objectPosition = 'center';
2494
+ }
2495
+ if (this._config?.debug) {
2496
+ console.log(`🎨 Image style applied: objectFit=${img.style.objectFit}, ratio=${ratio.toFixed(2)}`);
2232
2497
  }
2233
2498
  }
2234
2499
  /**
@@ -2242,6 +2507,10 @@ class AdsModule {
2242
2507
  this.renderFallback(slot);
2243
2508
  return;
2244
2509
  }
2510
+ // 🆕 동적 크기 조정: 배너 광고의 경우 이미지 크기 기반으로 컨테이너 최적화
2511
+ if (slot.adType === AdType.BANNER && adstageData.length > 0) {
2512
+ await this.optimizeContainerForBannerAds(slot, adstageData);
2513
+ }
2245
2514
  // 광고가 여러 개이거나 autoSlide 옵션이 있으면 슬라이더로 렌더링
2246
2515
  if (adstageData.length > 1 || slot.config?.autoSlide) {
2247
2516
  await this.renderAdSlider(slot, adstageData);
@@ -2263,6 +2532,32 @@ class AdsModule {
2263
2532
  this.renderFallback(slot);
2264
2533
  }
2265
2534
  }
2535
+ /**
2536
+ * 배너 광고를 위한 컨테이너 최적화
2537
+ */
2538
+ async optimizeContainerForBannerAds(slot, advertisements) {
2539
+ try {
2540
+ const container = document.getElementById(slot.containerId);
2541
+ const adElement = document.getElementById(slot.id);
2542
+ if (!container || !adElement)
2543
+ return;
2544
+ // 현재 컨테이너 너비 확인
2545
+ const containerWidth = container.getBoundingClientRect().width || 300;
2546
+ // 최적 크기 계산
2547
+ const optimalSize = await this.calculateOptimalContainerSize(advertisements, containerWidth, slot.adType);
2548
+ // 컨테이너 크기 동적 조정
2549
+ adElement.style.height = optimalSize.height;
2550
+ // 슬롯 정보 업데이트
2551
+ slot.optimizedHeight = optimalSize.height;
2552
+ slot.aspectRatio = optimalSize.aspectRatio;
2553
+ if (this._config?.debug) {
2554
+ console.log(`🔧 Container optimized for ${advertisements.length} banner ads: ${optimalSize.height}`);
2555
+ }
2556
+ }
2557
+ catch (error) {
2558
+ console.warn('Container optimization failed, using default size:', error);
2559
+ }
2560
+ }
2266
2561
  /**
2267
2562
  * 기본 viewability 추적 시작
2268
2563
  */
@@ -2314,22 +2609,110 @@ class AdsModule {
2314
2609
  }
2315
2610
  }
2316
2611
  /**
2317
- * Fallback 광고 렌더링 - DOM에서 완전 제거
2612
+ * Fallback 광고 렌더링 - AdStage 확실한 컨테이너 우선 탐지
2318
2613
  */
2319
2614
  renderFallback(slot) {
2320
2615
  const element = document.getElementById(slot.id);
2321
2616
  if (element) {
2322
- // 부모 컨테이너에서 광고 슬롯을 완전히 제거
2323
- const parentContainer = element.parentNode;
2324
- if (parentContainer) {
2325
- parentContainer.removeChild(element);
2617
+ // 1순위: AdStage가 생성한 확실한 컨테이너들 (데이터 속성 기반)
2618
+ const adstageContainers = [
2619
+ element.querySelector('[data-adstage-container="true"]'), // 내부 AdStage 컨테이너
2620
+ element.closest('[data-adstage-container="true"]'), // 상위 AdStage 컨테이너
2621
+ element, // 자기 자신이 AdStage 컨테이너인 경우
2622
+ ].filter(el => el && el.hasAttribute('data-adstage-container'));
2623
+ // 2순위: AdStage 클래스 기반 컨테이너들
2624
+ const classBasedContainers = [
2625
+ element.closest('.adstage-slot'),
2626
+ element.closest('.adstage-banner'),
2627
+ element.closest('.adstage-text'),
2628
+ element.closest('.adstage-video'),
2629
+ element.closest('.adstage-native'),
2630
+ element.closest('.adstage-interstitial'),
2631
+ ].filter(Boolean);
2632
+ // 3순위: 일반적인 광고 컨테이너 패턴들 (fallback)
2633
+ const generalContainers = [
2634
+ element.closest('[class*="ad"]'),
2635
+ element.closest('[class*="banner"]'),
2636
+ element.closest('[class*="container"]'),
2637
+ element.closest('div[style*="height"]'),
2638
+ element.closest('div[style*="min-height"]'),
2639
+ element.parentElement
2640
+ ].filter(Boolean);
2641
+ // 우선순위에 따라 컨테이너 선택
2642
+ const possibleContainers = [
2643
+ ...adstageContainers,
2644
+ ...classBasedContainers,
2645
+ ...generalContainers
2646
+ ];
2647
+ // 가장 적절한 컨테이너 선택
2648
+ const targetContainer = possibleContainers[0];
2649
+ if (targetContainer) {
2650
+ // 컨테이너 타입 로깅
2651
+ let containerType = 'unknown';
2652
+ if (targetContainer.hasAttribute('data-adstage-container')) {
2653
+ containerType = 'adstage-official';
2654
+ }
2655
+ else if (targetContainer.classList.contains('adstage-slot')) {
2656
+ containerType = 'adstage-class';
2657
+ }
2658
+ else {
2659
+ containerType = 'generic';
2660
+ }
2661
+ targetContainer.style.cssText += `
2662
+ height: 0px !important;
2663
+ min-height: 0px !important;
2664
+ padding: 0px !important;
2665
+ margin: 0px !important;
2666
+ border: none !important;
2667
+ overflow: hidden !important;
2668
+ display: block !important;
2669
+ `;
2670
+ // 내부 모든 요소 제거
2671
+ targetContainer.innerHTML = '';
2672
+ // 빈 상태임을 표시하는 속성 추가
2673
+ targetContainer.setAttribute('data-adstage-empty', 'true');
2326
2674
  if (this._config?.debug) {
2327
- console.warn(`⚠️ Ad slot completely removed from DOM: ${slot.id}`);
2675
+ console.warn(`⚠️ Ad container collapsed (${containerType}): ${slot.id}`, targetContainer);
2328
2676
  }
2329
2677
  }
2678
+ else {
2679
+ // 컨테이너를 찾지 못한 경우 새로운 빈 컨테이너 생성
2680
+ this.createEmptyContainer(slot);
2681
+ }
2682
+ }
2683
+ // 슬롯 상태 업데이트 (제거하지 않고 빈 상태로 마킹)
2684
+ slot.advertisement = undefined;
2685
+ slot.isEmpty = true;
2686
+ }
2687
+ /**
2688
+ * 빈 컨테이너 생성 (컨테이너를 찾지 못한 경우)
2689
+ */
2690
+ createEmptyContainer(slot) {
2691
+ const originalContainer = document.getElementById(slot.containerId);
2692
+ if (originalContainer) {
2693
+ // 기존 내용 제거
2694
+ originalContainer.innerHTML = '';
2695
+ // 빈 AdStage 컨테이너 생성
2696
+ const emptyElement = document.createElement('div');
2697
+ emptyElement.id = slot.id;
2698
+ emptyElement.className = 'adstage-slot adstage-empty';
2699
+ emptyElement.setAttribute('data-adstage-container', 'true');
2700
+ emptyElement.setAttribute('data-adstage-empty', 'true');
2701
+ emptyElement.setAttribute('data-adstage-slot', slot.id);
2702
+ emptyElement.style.cssText = `
2703
+ height: 0px !important;
2704
+ min-height: 0px !important;
2705
+ padding: 0px !important;
2706
+ margin: 0px !important;
2707
+ border: none !important;
2708
+ overflow: hidden !important;
2709
+ display: block !important;
2710
+ `;
2711
+ originalContainer.appendChild(emptyElement);
2712
+ if (this._config?.debug) {
2713
+ console.warn(`⚠️ Created empty AdStage container: ${slot.id}`);
2714
+ }
2330
2715
  }
2331
- // 슬롯 맵에서도 제거
2332
- this.slots.delete(slot.id);
2333
2716
  }
2334
2717
  /**
2335
2718
  * 광고 데이터 가져오기
@@ -2397,23 +2780,25 @@ class AdsModule {
2397
2780
  }
2398
2781
  };
2399
2782
  let sliderElement;
2783
+ // 최적화된 슬라이더 옵션 준비
2784
+ const optimizedSliderOptions = {
2785
+ autoSlideInterval: (slot.config?.slideInterval || 5000) / 1000,
2786
+ ...slot.config,
2787
+ // 🆕 동적 크기 정보 전달
2788
+ optimizedHeight: slot.optimizedHeight,
2789
+ aspectRatio: slot.aspectRatio
2790
+ };
2400
2791
  // 텍스트 광고는 TextTransitionManager 사용, 그 외는 CarouselSliderManager 사용
2401
2792
  if (slot.adType === AdType.TEXT) {
2402
- sliderElement = TextTransitionManager.createTextTransitionContainer(slot, advertisements, {
2403
- autoSlideInterval: (slot.config?.slideInterval || 5000) / 1000,
2404
- ...slot.config
2405
- }, trackEventCallback);
2793
+ sliderElement = TextTransitionManager.createTextTransitionContainer(slot, advertisements, optimizedSliderOptions, trackEventCallback);
2406
2794
  if (this._config?.debug) {
2407
2795
  console.log(`✨ Text transition created for TEXT slot: ${slot.id} with ${advertisements.length} ads`);
2408
2796
  }
2409
2797
  }
2410
2798
  else {
2411
- sliderElement = CarouselSliderManager.createSliderContainer(slot, advertisements, {
2412
- autoSlideInterval: (slot.config?.slideInterval || 5000) / 1000,
2413
- ...slot.config
2414
- }, trackEventCallback);
2799
+ sliderElement = CarouselSliderManager.createSliderContainer(slot, advertisements, optimizedSliderOptions, trackEventCallback);
2415
2800
  if (this._config?.debug) {
2416
- console.log(`🎠 Carousel slider created for ${slot.adType} slot: ${slot.id} with ${advertisements.length} ads`);
2801
+ console.log(`🎠 Carousel slider created for ${slot.adType} slot: ${slot.id} with ${advertisements.length} ads (optimized: ${slot.optimizedHeight || 'default'})`);
2417
2802
  }
2418
2803
  }
2419
2804
  // 기존 내용 제거하고 슬라이더 추가
@@ -2440,19 +2825,23 @@ class AdsModule {
2440
2825
  // 기본 HTML 구조 생성
2441
2826
  const adElement = document.createElement('div');
2442
2827
  adElement.className = 'adstage-ad';
2443
- adElement.style.width = typeof slot.width === 'string' ? slot.width : `${slot.width}px`;
2444
- adElement.style.height = typeof slot.height === 'string' ? slot.height : `${slot.height}px`;
2828
+ // 스마트한 크기 설정 - 최적화된 크기가 있으면 사용
2829
+ const optimizedHeight = slot.optimizedHeight;
2830
+ const containerElement = container.parentElement || container;
2831
+ if (optimizedHeight) {
2832
+ adElement.style.width = '100%';
2833
+ adElement.style.height = optimizedHeight;
2834
+ }
2835
+ else {
2836
+ const { width, height } = this.calculateAdSize(containerElement, slot.adType, slot.config || {});
2837
+ adElement.style.width = width;
2838
+ adElement.style.height = height;
2839
+ }
2445
2840
  // 광고 타입별 렌더링
2446
2841
  switch (slot.adType) {
2447
2842
  case AdType.BANNER:
2448
2843
  if (ad.imageUrl) {
2449
- const img = document.createElement('img');
2450
- img.src = ad.imageUrl;
2451
- img.alt = ad.title;
2452
- img.style.width = '100%';
2453
- img.style.height = '100%';
2454
- img.style.objectFit = 'cover';
2455
- adElement.appendChild(img);
2844
+ await this.renderOptimizedBannerImage(adElement, ad, slot);
2456
2845
  }
2457
2846
  break;
2458
2847
  case AdType.TEXT:
@@ -2487,6 +2876,50 @@ class AdsModule {
2487
2876
  container.innerHTML = '';
2488
2877
  container.appendChild(adElement);
2489
2878
  }
2879
+ /**
2880
+ * 최적화된 배너 이미지 렌더링
2881
+ */
2882
+ async renderOptimizedBannerImage(adElement, ad, slot) {
2883
+ try {
2884
+ // 이미지 크기 정보 로드
2885
+ const imageDimensions = await this.loadImageDimensions(ad.imageUrl);
2886
+ const imageAspectRatio = imageDimensions.width / imageDimensions.height;
2887
+ // 컨테이너 비율 계산
2888
+ const containerAspectRatio = slot.aspectRatio || 16 / 9;
2889
+ // 이미지 요소 생성
2890
+ const img = document.createElement('img');
2891
+ img.src = ad.imageUrl;
2892
+ img.alt = ad.title;
2893
+ img.style.width = '100%';
2894
+ img.style.height = '100%';
2895
+ // 🎨 최적화된 스타일 적용
2896
+ this.applyOptimizedImageStyle(img, imageAspectRatio, containerAspectRatio);
2897
+ // 이미지 로드 완료 처리
2898
+ img.onload = () => {
2899
+ if (this._config?.debug) {
2900
+ console.log(`🖼️ Optimized banner image loaded: ${imageDimensions.width}x${imageDimensions.height} (ratio: ${imageAspectRatio.toFixed(2)})`);
2901
+ }
2902
+ };
2903
+ // 에러 처리
2904
+ img.onerror = () => {
2905
+ console.warn(`Failed to load banner image: ${ad.imageUrl}`);
2906
+ // 폴백 텍스트 표시
2907
+ adElement.innerHTML = `<div style="display: flex; align-items: center; justify-content: center; background: #f0f0f0; color: #666;">${ad.title}</div>`;
2908
+ };
2909
+ adElement.appendChild(img);
2910
+ }
2911
+ catch (error) {
2912
+ console.warn('Failed to optimize banner image, using fallback:', error);
2913
+ // 기본 이미지 렌더링 (폴백)
2914
+ const img = document.createElement('img');
2915
+ img.src = ad.imageUrl;
2916
+ img.alt = ad.title;
2917
+ img.style.width = '100%';
2918
+ img.style.height = '100%';
2919
+ img.style.objectFit = 'cover';
2920
+ adElement.appendChild(img);
2921
+ }
2922
+ }
2490
2923
  /**
2491
2924
  * 광고 슬롯 새로고침
2492
2925
  */
package/dist/index.d.ts CHANGED
@@ -282,10 +282,46 @@ declare class AdsModule implements BaseModule {
282
282
  * 즉시 광고 슬롯 생성 (placeholder)
283
283
  */
284
284
  private createAdSlot;
285
+ /**
286
+ * 컨테이너와 광고 타입에 따른 스마트한 크기 계산
287
+ */
288
+ private calculateAdSize;
289
+ /**
290
+ * 컨테이너의 실제 높이 계산
291
+ */
292
+ private getContainerHeight;
293
+ /**
294
+ * 광고 타입별 기본 높이 반환
295
+ */
296
+ private getDefaultHeightForAdType;
297
+ /**
298
+ * 이미지 크기 정보 로드 (프리로딩)
299
+ */
300
+ private loadImageDimensions;
301
+ /**
302
+ * 여러 광고의 최적 컨테이너 크기 계산 (동적 크기 조정)
303
+ */
304
+ private calculateOptimalContainerSize;
305
+ /**
306
+ * 최적 크기 조정 전략 선택
307
+ */
308
+ private selectOptimalSizeStrategy;
309
+ /**
310
+ * 전략에 따른 최적 높이 계산
311
+ */
312
+ private calculateOptimalHeight;
313
+ /**
314
+ * 개별 이미지에 최적화된 렌더링 스타일 적용
315
+ */
316
+ private applyOptimizedImageStyle;
285
317
  /**
286
318
  * 백그라운드에서 광고 콘텐츠 로드
287
319
  */
288
320
  private loadAdContentInBackground;
321
+ /**
322
+ * 배너 광고를 위한 컨테이너 최적화
323
+ */
324
+ private optimizeContainerForBannerAds;
289
325
  /**
290
326
  * 기본 viewability 추적 시작
291
327
  */
@@ -295,9 +331,13 @@ declare class AdsModule implements BaseModule {
295
331
  */
296
332
  private handleViewableEvent;
297
333
  /**
298
- * Fallback 광고 렌더링 - DOM에서 완전 제거
334
+ * Fallback 광고 렌더링 - AdStage 확실한 컨테이너 우선 탐지
299
335
  */
300
336
  private renderFallback;
337
+ /**
338
+ * 빈 컨테이너 생성 (컨테이너를 찾지 못한 경우)
339
+ */
340
+ private createEmptyContainer;
301
341
  /**
302
342
  * 광고 데이터 가져오기
303
343
  */
@@ -314,6 +354,10 @@ declare class AdsModule implements BaseModule {
314
354
  * 광고 요소 렌더링 (기본 구현)
315
355
  */
316
356
  private renderAdElement;
357
+ /**
358
+ * 최적화된 배너 이미지 렌더링
359
+ */
360
+ private renderOptimizedBannerImage;
317
361
  /**
318
362
  * 광고 슬롯 새로고침
319
363
  */