Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Core: support for expandable / flex slots #12379

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion creative/renderers/display/renderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,12 @@ export function render({ad, adUrl, width, height}, {mkFrame}, win) {
message: 'Missing ad markup or URL'
};
} else {
if (height == null) {
const body = win.document?.body;
[body, body?.parentElement].filter(elm => elm?.style != null).forEach(elm => elm.style.height = '100%');
}
const doc = win.document;
const attrs = {width, height};
const attrs = {width: width ?? '100%', height: height ?? '100%'};
if (adUrl && !ad) {
attrs.src = adUrl;
} else {
Expand Down
2 changes: 1 addition & 1 deletion integrationExamples/gpt/x-domain/creative.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// creative will be rendered, e.g. GAM delivering a SafeFrame

// this code is autogenerated, also available in 'build/creative/creative.js'
<script>!function(){"use strict";const e="Prebid Event",n=(()=>{const e={frameBorder:0,scrolling:"no",marginHeight:0,marginWidth:0,topMargin:0,leftMargin:0,allowTransparency:"true"};return(n,t)=>{const r=n.createElement("iframe");return Object.entries(Object.assign({},t,e)).forEach((([e,n])=>r.setAttribute(e,n))),r}})();function t(e){return!!e.frames.__pb_locator__}window.pbRender=function(r){let o=r.parent;try{for(;o!==r.top&&!t(o);)o=o.parent;t(o)||(o=r.parent)}catch(e){}return function({adId:t,pubUrl:s,clickUrl:i}){const c=new URL(s,window.location).origin;function a(e,n,r){const s=new MessageChannel;s.port1.onmessage=u(r),o.postMessage(JSON.stringify(Object.assign({message:e,adId:t},n)),c,[s.port2])}function d(n){a(e,{event:"adRenderFailed",info:{reason:n?.reason||"exception",message:n?.message}}),n?.stack&&console.error(n)}function u(e){return function(){try{return e.apply(this,arguments)}catch(e){d(e)}}}a("Prebid Request",{options:{clickUrl:i}},(function(o){let s;try{s=JSON.parse(o.data)}catch(e){return}if("Prebid Response"===s.message&&s.adId===t){const t=n(r.document,{width:0,height:0,style:"display: none",srcdoc:`<script>${s.renderer}<\/script>`});t.onload=u((function(){const o=t.contentWindow;o.Promise.resolve(o.render(s,{sendMessage:a,mkFrame:n},r)).then((()=>a(e,{event:"adRenderSucceeded"})),d)})),r.document.body.appendChild(t)}}))}}(window)}();</script>
<script>(()=>{"use strict";const e="Prebid Event",n=(()=>{const e={frameBorder:0,scrolling:"no",marginHeight:0,marginWidth:0,topMargin:0,leftMargin:0,allowTransparency:"true"};return(n,t)=>{const r=n.createElement("iframe");return Object.entries(Object.assign({},t,e)).forEach((([e,n])=>r.setAttribute(e,n))),r}})();function t(e){return!!e.frames.__pb_locator__}window.pbRender=function(r){let o=r.parent;try{for(;o!==r.top&&!t(o);)o=o.parent;t(o)||(o=r.parent)}catch(e){}return function({adId:t,pubUrl:s,clickUrl:i}){const a=new URL(s,window.location).origin;function c(e,n,r){const s=new MessageChannel;s.port1.onmessage=l(r),o.postMessage(JSON.stringify(Object.assign({message:e,adId:t},n)),a,[s.port2])}function d(n){c(e,{event:"adRenderFailed",info:{reason:n?.reason||"exception",message:n?.message}}),n?.stack&&console.error(n)}function l(e){return function(){try{return e.apply(this,arguments)}catch(e){d(e)}}}c("Prebid Request",{options:{clickUrl:i}},(function(o){let s;try{s=JSON.parse(o.data)}catch(e){return}if("Prebid Response"===s.message&&s.adId===t){const t=n(r.document,{width:0,height:0,style:"display: none",srcdoc:`<script>${s.renderer}<\/script>`});t.onload=l((function(){const o=t.contentWindow;o.Promise.resolve(o.render(s,{sendMessage:c,mkFrame:n},r)).then((()=>c(e,{event:"adRenderSucceeded"})),d)})),r.document.body.appendChild(t)}}))}}(window)})();</script>

<script>
pbRender({
Expand Down
2 changes: 1 addition & 1 deletion libraries/creative-renderer-display/renderer.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion libraries/ortbConverter/processors/banner.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export function fillBannerImp(imp, bidRequest, context) {
const banner = {
topframe: inIframe() === true ? 0 : 1
};
if (bannerParams.sizes) {
if (bannerParams.sizes && bidRequest.ortb2Imp?.banner?.format == null) {
banner.format = sizesToSizeTuples(bannerParams.sizes).map(sizeTupleToRtbSize);
}
if (bannerParams.hasOwnProperty('pos')) {
Expand Down
2 changes: 2 additions & 0 deletions libraries/ortbConverter/processors/default.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,8 @@ export const DEFAULT_PROCESSORS = {
currency: context.ortbResponse.cur || context.currency,
width: bid.w,
height: bid.h,
wratio: bid.wratio,
hratio: bid.hratio,
dealId: bid.dealid,
creative_id: bid.crid,
creativeId: bid.crid,
Expand Down
2 changes: 1 addition & 1 deletion modules/debugging/bidInterceptor.js
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ Object.assign(BidInterceptor.prototype, {
};
},
defaultAd(bid, bidResponse) {
return `<html><head><style>#ad {width: ${bidResponse.width}px;height: ${bidResponse.height}px;background-color: #f6f6ae;color: #85144b;padding: 5px;text-align: center;display: flex;flex-direction: column;align-items: center;justify-content: center;}#bidder {font-family: monospace;font-weight: normal;}#title {font-size: x-large;font-weight: bold;margin-bottom: 5px;}#body {font-size: large;margin-top: 5px;}</style></head><body><div id="ad"><div id="title">Mock ad: <span id="bidder">${bid.bidder}</span></div><div id="body">${bidResponse.width}x${bidResponse.height}</div></div></body></html>`;
return `<html><head><style>html, body {height: 100%} #ad {width: ${bidResponse.width == null ? '100%' : bidResponse.width + 'px'};height: ${bidResponse.height == null ? '100%' : bidResponse.height + 'px'};background-color: #f6f6ae;color: #85144b;padding: 5px;text-align: center;display: flex;flex-direction: column;align-items: center;justify-content: center;}#bidder {font-family: monospace;font-weight: normal;}#title {font-size: x-large;font-weight: bold;margin-bottom: 5px;}#body {font-size: large;margin-top: 5px;}</style></head><body><div id="ad"><div id="title">Mock ad: <span id="bidder">${bid.bidder}</span></div><div id="body">${bidResponse.width ?? bidResponse.wratio}x${bidResponse.height ?? bidResponse.hratio}</div></div></body></html>`;
},
/**
* Match a candidate bid against all registered rules.
Expand Down
6 changes: 6 additions & 0 deletions src/adapters/bidderFactory.js
Original file line number Diff line number Diff line change
Expand Up @@ -551,6 +551,12 @@ function validBidSize(adUnitCode, bid, {index = auctionManager.index} = {}) {
return true;
}

if (bid.wratio != null && bid.hratio != null) {
bid.wratio = parseInt(bid.wratio, 10);
bid.hratio = parseInt(bid.hratio, 10);
return true;
}

const bidRequest = index.getBidRequest(bid);
const mediaTypes = index.getMediaTypes(bid);

Expand Down
39 changes: 34 additions & 5 deletions src/prebid.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ import {
mergeDeep,
transformAdServerTargetingObj,
uniques,
unsupportedBidderMessage
unsupportedBidderMessage,
deepEqual
} from './utils.js';
import {listenMessagesFromCreative} from './secureCreatives.js';
import {userSync} from './userSync.js';
Expand Down Expand Up @@ -119,11 +120,39 @@ export function setBattrForAdUnit(adUnit, mediaType) {
function validateBannerMediaType(adUnit) {
const validatedAdUnit = deepClone(adUnit);
const banner = validatedAdUnit.mediaTypes.banner;
const bannerSizes = validateSizes(banner.sizes);
if (bannerSizes.length > 0) {
banner.sizes = bannerSizes;
const bannerSizes = banner.sizes == null ? null : validateSizes(banner.sizes);
const format = adUnit.ortb2Imp?.banner?.format ?? banner?.format;
let formatSizes;
if (format != null) {
deepSetValue(validatedAdUnit, 'ortb2Imp.banner.format', format);
banner.format = format;
try {
formatSizes = format
.filter(({w, h, wratio, hratio}) => {
if ((w ?? h) != null && (wratio ?? hratio) != null) {
logWarn(`Ad unit banner.format specifies both w/h and wratio/hratio`, adUnit);
return false;
}
return (w ?? h ?? wratio ?? hratio) != null;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shouldn't we check that w AND h aren't null or wratio AND hratio aren't null ? Instead of having just one non null value

})
.map(({w, h, wratio, hratio}) => [w ?? wratio, h ?? hratio]);
} catch (e) {
logError(`Invalid format definition on ad unit ${adUnit.code}`, format);
}
if (formatSizes != null && bannerSizes != null && !deepEqual(bannerSizes, formatSizes)) {
logWarn(`Ad unit ${adUnit.code} has conflicting sizes and format definitions`, adUnit);
}
}
const sizes = formatSizes ?? bannerSizes ?? [];
const expdir = adUnit.ortb2Imp?.banner?.expdir ?? banner.expdir;
if (expdir != null) {
banner.expdir = expdir;
deepSetValue(validatedAdUnit, 'ortb2Imp.banner.expdir', expdir);
}
if (sizes.length > 0) {
banner.sizes = sizes;
// Deprecation Warning: This property will be deprecated in next release in favor of adUnit.mediaTypes.banner.sizes
validatedAdUnit.sizes = bannerSizes;
validatedAdUnit.sizes = sizes;
} else {
logError('Detected a mediaTypes.banner object without a proper sizes field. Please ensure the sizes are listed like: [[300, 250], ...]. Removing invalid mediaTypes.banner object from request.');
delete validatedAdUnit.mediaTypes.banner
Expand Down
28 changes: 26 additions & 2 deletions test/spec/creative/displayRenderer_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {render} from 'creative/renderers/display/renderer.js';
import {ERROR_NO_AD} from '../../../creative/renderers/display/constants.js';

describe('Creative renderer - display', () => {
let doc, mkFrame, sendMessage;
let doc, mkFrame, sendMessage, win;
beforeEach(() => {
mkFrame = sinon.stub().callsFake((doc, attrs) => Object.assign({doc}, attrs));
sendMessage = sinon.stub();
Expand All @@ -11,10 +11,13 @@ describe('Creative renderer - display', () => {
appendChild: sinon.stub()
}
};
win = {
document: doc
}
});

function runRenderer(data) {
return render(data, {sendMessage, mkFrame}, {document: doc});
return render(data, {sendMessage, mkFrame}, win);
}

it('throws when both ad and adUrl are missing', () => {
Expand Down Expand Up @@ -52,4 +55,25 @@ describe('Creative renderer - display', () => {
})
})
})

it('defaults width and height to 100%', () => {
runRenderer({ad: 'mock'});
sinon.assert.calledWith(doc.body.appendChild, sinon.match({
doc,
width: '100%',
height: '100%'
}))
});

it('sets html and body style height: 100% if no height is provided', () => {
Object.assign(doc.body, {
style: {},
parentElement: {
style: {}
}
})
runRenderer({ad: 'mock'});
expect(doc.body.style.height).to.eql('100%');
expect(doc.body.parentElement.style.height).to.eql('100%');
})
})
20 changes: 20 additions & 0 deletions test/spec/ortbConverter/banner_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,26 @@ describe('pbjs -> ortb banner conversion', () => {
}
}
},
{
t: 'banner with format',
request: {
mediaTypes: {
banner: {
sizes: ['should be ignored']
}
},
ortb2Imp: {
banner: {
format: [{w: 123, h: 321}, {wratio: 2, hratio: 1}]
}
},
},
imp: {
banner: {
topframe: 0
}
}
},
{
t: 'multi size banner',
request: {
Expand Down
23 changes: 17 additions & 6 deletions test/spec/unit/core/bidderFactory_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -1610,26 +1610,37 @@ describe('bidderFactory', () => {
}
});

function mkResponse(width, height) {
return {
function mkResponse(props) {
return Object.assign({
requestId: req.bidId,
width,
height,
cpm: 1,
ttl: 60,
creativeId: '123',
netRevenue: true,
currency: 'USD',
mediaType: 'banner',
}
}, props)
}

function checkValid(bid) {
return isValid('au', bid, {index: stubAuctionIndex({bidRequests: [req]})});
}

it('should succeed when response has a size that was in request', () => {
expect(checkValid(mkResponse(3, 4))).to.be.true;
expect(checkValid(mkResponse({width: 3, height: 4}))).to.be.true;
});

describe('using w/hratio', () => {
beforeEach(() => {
req.ortb2Imp = {
banner: {
format: [{wratio: 1, hratio: 2}]
}
}
})
it('should accept wratio/hratio', () => {
expect(checkValid(mkResponse({wratio: 1, hratio: 2}))).to.be.true;
});
});
})
});
Expand Down
62 changes: 61 additions & 1 deletion test/spec/unit/pbjs_api_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import {stubAuctionIndex} from '../../helpers/indexStub.js';
import {createBid} from '../../../src/bidfactory.js';
import {enrichFPD} from '../../../src/fpd/enrichment.js';
import {mockFpdEnrichments} from '../../helpers/fpd.js';
import {generateUUID} from '../../../src/utils.js';
import {deepAccess, deepSetValue, generateUUID} from '../../../src/utils.js';
import {getCreativeRenderer} from '../../../src/creativeRenderers.js';
import {BID_STATUS, EVENTS, GRANULARITY_OPTIONS, PB_LOCATOR, TARGETING_KEYS} from 'src/constants.js';
import {getBidToRender} from '../../../src/adRendering.js';
Expand Down Expand Up @@ -2408,6 +2408,66 @@ describe('Unit: Prebid Module', function () {
});
sinon.assert.match(auctionArgs.adUnits[0], adUnit);
});

describe('banner.format', () => {
let au;
beforeEach(() => {
au = {
code: 'test',
bids: [],
mediaTypes: {
banner: {}
}
};
});
const EXPDIR = ['ortb2Imp.banner.expdir', 'mediaTypes.banner.expdir'];
EXPDIR.forEach(prop => {
it(`should make ${prop} avaliable under both ${EXPDIR.join(' and ')}`, () => {
au.mediaTypes.banner.sizes = [1, 2];
deepSetValue(au, prop, [1, 2]);
$$PREBID_GLOBAL$$.requestBids({
adUnits: [au]
});
EXPDIR.forEach(dest => {
expect(deepAccess(auctionArgs.adUnits[0], dest)).to.eql([1, 2]);
});
})
});
['ortb2Imp.banner.format', 'mediaTypes.banner.format'].forEach(prop => {
it(`should accept ${prop} instead of sizes`, () => {
deepSetValue(au, prop, [{w: 123, h: 321}, {w: 444, h: 555}]);
$$PREBID_GLOBAL$$.requestBids({
adUnits: [au]
});
expect(auctionArgs.adUnits[0].mediaTypes.banner.sizes).to.deep.equal([[123, 321], [444, 555]]);
});

it(`should make ${prop} available under both mediaTypes.banner and ortb2Imp.format`, () => {
const format = [{w: 123, h: 321}];
deepSetValue(au, prop, format);
$$PREBID_GLOBAL$$.requestBids({
adUnits: [au]
});
expect(auctionArgs.adUnits[0].mediaTypes.banner.format).to.deep.equal(format);
expect(auctionArgs.adUnits[0].ortb2Imp.banner.format).to.deep.equal(format);
})

it(`should transform wratio/hratio from ${prop} into placeholder sizes`, () => {
deepSetValue(au, prop, [{w: 123, h: 321}, {wratio: 2, hratio: 1}]);
$$PREBID_GLOBAL$$.requestBids({
adUnits: [au]
});
expect(auctionArgs.adUnits[0].mediaTypes.banner.sizes).to.deep.equal([[123, 321], [2, 1]]);
});
it(`should ignore ${prop} elements that specify both w/h and wratio/hratio`, () => {
deepSetValue(au, prop, [{w: 333, hratio: 2}, {w: 123, h: 321}]);
$$PREBID_GLOBAL$$.requestBids({
adUnits: [au]
});
expect(auctionArgs.adUnits[0].mediaTypes.banner.sizes).to.deep.equal([[123, 321]]);
})
});
})
});

describe('negative tests for validating adUnits', function() {
Expand Down