-
Notifications
You must be signed in to change notification settings - Fork 12
Select active GPT responsive slots #978
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
base: fix/duplicate-gpt-slots
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -52,15 +52,50 @@ interface SlotRenderEndedEvent { | |
| slot: GoogleTagSlot; | ||
| } | ||
|
|
||
| function isElementVisible(element: HTMLElement): boolean { | ||
| const style = window.getComputedStyle(element); | ||
| return ( | ||
| style.display !== 'none' && style.visibility !== 'hidden' && style.visibility !== 'collapse' | ||
| ); | ||
| } | ||
|
|
||
| function slotElementHasLayout(element: HTMLElement): boolean { | ||
| if (!isElementVisible(element)) return false; | ||
| const elementRect = element.getBoundingClientRect(); | ||
| if (elementRect.width > 0 && elementRect.height > 0) return true; | ||
|
|
||
| const container = document.getElementById(`${element.id}-container`); | ||
| if (!container || !isElementVisible(container)) return false; | ||
| const containerRect = container.getBoundingClientRect(); | ||
| return containerRect.width > 0 && containerRect.height > 0; | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ❓ question — Fail-closed drops the impression entirely when no candidate has reserved height.
Is total no-fill acceptable for publishers that don't reserve slot heights? A width-only container check would disambiguate without requiring reserved height, since a const containerRect = container.getBoundingClientRect();
return containerRect.width > 0;Same applies to the mirrored |
||
| } | ||
|
|
||
| function findSlotElementByDivId(divId: string): HTMLElement | null { | ||
| if (!divId) return null; | ||
|
ChristianPavilonis marked this conversation as resolved.
|
||
| const exact = document.getElementById(divId); | ||
| if (exact) return exact; | ||
|
|
||
| return ( | ||
| Array.from(document.querySelectorAll<HTMLElement>('[id]')).find( | ||
| (el) => el.id.startsWith(divId) && !el.id.endsWith('-container') | ||
| ) ?? null | ||
| const prefixMatches = Array.from(document.querySelectorAll<HTMLElement>('[id]')).filter( | ||
| (element) => element.id.startsWith(divId) && !element.id.endsWith('-container') | ||
| ); | ||
| // A unique prefix match may be a lazy slot that has not been sized yet. | ||
| // Geometry is only needed to disambiguate multiple responsive siblings. | ||
| if (prefixMatches.length === 1) return prefixMatches[0] ?? null; | ||
|
|
||
| const visibleMatches = prefixMatches.filter(isElementVisible); | ||
| if (visibleMatches.length === 1) return visibleMatches[0] ?? null; | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🤔 thinking — Element-level visibility can't see container-hidden siblings.
function isElementVisible(element: HTMLElement): boolean {
if (typeof element.checkVisibility === 'function') return element.checkVisibility();
const style = window.getComputedStyle(element);
// existing checks…
} |
||
|
|
||
| const activeMatches = visibleMatches.filter(slotElementHasLayout); | ||
| if (activeMatches.length === 1) return activeMatches[0] ?? null; | ||
|
|
||
| if (prefixMatches.length > 1) { | ||
| log.warn('GPT slot prefix did not resolve to one active element', { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ♻️ refactor — Ambiguity warning fires on every animation frame during the SPA slot wait.
|
||
| divId, | ||
| prefixMatchCount: prefixMatches.length, | ||
| activeMatchCount: activeMatches.length, | ||
| }); | ||
| } | ||
| return null; | ||
| } | ||
|
|
||
| function candidateSlotRoots(divId: string): HTMLElement[] { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🤔 thinking — Render bridge re-resolves the prefix at message time and can disagree with adInit.
|
||
|
|
@@ -869,16 +904,26 @@ function waitForSlotElements(slots: AuctionSlot[], signal: AbortSignal): Promise | |
|
|
||
| return new Promise<void>((resolve) => { | ||
| let settled = false; | ||
| let animationFrame: number | undefined; | ||
| const finish = (): void => { | ||
| if (settled) return; | ||
| settled = true; | ||
| if (animationFrame !== undefined) cancelAnimationFrame(animationFrame); | ||
| observer.disconnect(); | ||
| clearTimeout(timer); | ||
| signal.removeEventListener('abort', finish); | ||
| resolve(); | ||
| }; | ||
| const observer = new MutationObserver(() => { | ||
| if (allPresent()) finish(); | ||
| if (animationFrame !== undefined) return; | ||
| if (typeof requestAnimationFrame === 'undefined') { | ||
| if (allPresent()) finish(); | ||
| return; | ||
| } | ||
| animationFrame = requestAnimationFrame(() => { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🤔 thinking — rAF gating always costs the full 2 s in background tabs.
|
||
| animationFrame = undefined; | ||
| if (allPresent()) finish(); | ||
| }); | ||
| }); | ||
| observer.observe(document.documentElement, { childList: true, subtree: true }); | ||
| const timer = setTimeout(finish, SPA_SLOT_WAIT_MS); | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -53,6 +53,44 @@ type TestWindow = Window & { | |
| tsjs?: any; | ||
| }; | ||
|
|
||
| function appendResponsiveSlotElement( | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ⛏ nitpick — Call sites like |
||
| id: string, | ||
| containerHasLayout: boolean, | ||
| elementHidden = false, | ||
| elementHasLayout = false, | ||
| containerVisible = containerHasLayout | ||
| ): HTMLDivElement { | ||
| const container = document.createElement('div'); | ||
| container.id = `${id}-container`; | ||
| container.dataset.responsiveSlotTest = 'true'; | ||
| container.style.display = containerVisible ? 'block' : 'none'; | ||
| container.getBoundingClientRect = () => | ||
| ({ | ||
| width: containerHasLayout ? 320 : 0, | ||
| height: containerHasLayout ? 100 : 0, | ||
| }) as DOMRect; | ||
|
|
||
| const element = document.createElement('div'); | ||
| element.id = id; | ||
| element.style.display = elementHidden ? 'none' : 'block'; | ||
| element.getBoundingClientRect = () => | ||
| ({ | ||
| width: elementHasLayout ? 300 : 0, | ||
| height: elementHasLayout ? 250 : 0, | ||
| }) as DOMRect; | ||
| container.appendChild(element); | ||
| document.body.appendChild(container); | ||
| return element; | ||
| } | ||
|
|
||
| function runGptBootstrap(): void { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🏕 camp site — Reuse this helper in the older bootstrap test. The pre-existing handoff test ('runs the embedded bootstrap handoff for a hydrated publisher ID', ~line 516) still inlines the identical |
||
| const bootstrap = readFileSync( | ||
| resolve(process.cwd(), '../../trusted-server-core/src/integrations/gpt_bootstrap.js'), | ||
| 'utf8' | ||
| ); | ||
| window.eval(bootstrap); | ||
| } | ||
|
|
||
| describe('installTsAdInit', () => { | ||
| beforeEach(() => { | ||
| vi.resetModules(); | ||
|
|
@@ -79,6 +117,7 @@ describe('installTsAdInit', () => { | |
| document.getElementById('div-atf-sidebar')?.remove(); | ||
| document.getElementById('ad-header-0-_r_1_')?.remove(); | ||
| document.getElementById("ad'prefix-real")?.remove(); | ||
| document.querySelectorAll('[data-responsive-slot-test]').forEach((element) => element.remove()); | ||
| }); | ||
|
|
||
| it('reads window.tsjs.bids synchronously and applies bid targeting before refresh', async () => { | ||
|
|
@@ -1257,6 +1296,130 @@ describe('installTsAdInit', () => { | |
| expect(mockPubads.refresh).toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it.each([ | ||
|
ChristianPavilonis marked this conversation as resolved.
|
||
| { implementation: 'runtime', activeIndexes: [2], publisherOwned: true, selectedIndex: 2 }, | ||
| { implementation: 'runtime', activeIndexes: [], selectedIndex: null }, | ||
| { implementation: 'runtime', activeIndexes: [], elementLayoutIndexes: [1], selectedIndex: 1 }, | ||
| { implementation: 'runtime', activeIndexes: [0, 2], selectedIndex: null }, | ||
| { | ||
| implementation: 'runtime', | ||
| activeIndexes: [2, 3], | ||
| hiddenElementIndexes: [2], | ||
| selectedIndex: 3, | ||
| }, | ||
| { | ||
| implementation: 'runtime', | ||
| activeIndexes: [], | ||
| hiddenElementIndexes: [0, 1, 3], | ||
| visibleContainerIndexes: [2], | ||
| selectedIndex: 2, | ||
| }, | ||
| { implementation: 'runtime', activeIndexes: [2], divId: '', selectedIndex: null }, | ||
| { implementation: 'bootstrap', activeIndexes: [2], publisherOwned: true, selectedIndex: 2 }, | ||
| { implementation: 'bootstrap', activeIndexes: [], selectedIndex: null }, | ||
| { implementation: 'bootstrap', activeIndexes: [], elementLayoutIndexes: [1], selectedIndex: 1 }, | ||
| { implementation: 'bootstrap', activeIndexes: [0, 2], selectedIndex: null }, | ||
| { | ||
| implementation: 'bootstrap', | ||
| activeIndexes: [2, 3], | ||
| hiddenElementIndexes: [2], | ||
| selectedIndex: 3, | ||
| }, | ||
| { | ||
| implementation: 'bootstrap', | ||
| activeIndexes: [], | ||
| hiddenElementIndexes: [0, 1, 3], | ||
| visibleContainerIndexes: [2], | ||
| selectedIndex: 2, | ||
| }, | ||
| { implementation: 'bootstrap', activeIndexes: [2], divId: '', selectedIndex: null }, | ||
| ] as const)( | ||
| '$implementation resolves responsive matches $activeIndexes to $selectedIndex', | ||
| async (testCase) => { | ||
| const { implementation, activeIndexes, selectedIndex } = testCase; | ||
| const hiddenElementIndexes = | ||
| 'hiddenElementIndexes' in testCase ? testCase.hiddenElementIndexes : []; | ||
| const elementLayoutIndexes = | ||
| 'elementLayoutIndexes' in testCase ? testCase.elementLayoutIndexes : []; | ||
| const visibleContainerIndexes = | ||
| 'visibleContainerIndexes' in testCase ? testCase.visibleContainerIndexes : activeIndexes; | ||
| const divId = 'divId' in testCase ? testCase.divId : 'ad-responsive-'; | ||
| const publisherOwned = 'publisherOwned' in testCase && testCase.publisherOwned; | ||
| const elements = ['a', 'b', 'c', 'd'].map((suffix, index) => | ||
| appendResponsiveSlotElement( | ||
| `ad-responsive-${suffix}`, | ||
| (activeIndexes as readonly number[]).includes(index), | ||
| (hiddenElementIndexes as readonly number[]).includes(index), | ||
| (elementLayoutIndexes as readonly number[]).includes(index), | ||
| (visibleContainerIndexes as readonly number[]).includes(index) | ||
| ) | ||
| ); | ||
| const selectedElement = selectedIndex === null ? undefined : elements[selectedIndex]; | ||
| const mockSlot = { | ||
| addService: vi.fn().mockReturnThis(), | ||
| setTargeting: vi.fn().mockReturnThis(), | ||
| getSlotElementId: vi.fn().mockReturnValue(selectedElement?.id ?? elements[0]!.id), | ||
| getTargeting: vi.fn().mockReturnValue([]), | ||
| }; | ||
| const nativeRefresh = vi.fn(); | ||
| const mockPubads = { | ||
| enableSingleRequest: vi.fn(), | ||
| getSlots: vi.fn().mockReturnValue(publisherOwned ? [mockSlot] : []), | ||
| addEventListener: vi.fn(), | ||
| refresh: nativeRefresh, | ||
| }; | ||
| const defineSlot = vi.fn().mockReturnValue(mockSlot); | ||
| const nativeDisplay = vi.fn(); | ||
| (window as TestWindow).googletag = { | ||
| cmd: { push: vi.fn((fn: () => void) => fn()) }, | ||
| defineSlot, | ||
| display: nativeDisplay, | ||
| pubads: vi.fn().mockReturnValue(mockPubads), | ||
| enableServices: vi.fn(), | ||
| }; | ||
| (window as TestWindow).tsjs = { | ||
| adSlots: [ | ||
| { | ||
| id: 'responsive_slot', | ||
| gam_unit_path: '/123/responsive', | ||
| div_id: divId, | ||
| formats: [[300, 250]], | ||
| targeting: {}, | ||
| }, | ||
| ], | ||
| bids: {}, | ||
| }; | ||
|
|
||
| if (implementation === 'runtime') { | ||
| const { installTsAdInit } = await import('../../../src/integrations/gpt/index'); | ||
| installTsAdInit(); | ||
| } else { | ||
| runGptBootstrap(); | ||
| } | ||
| (window as TestWindow).tsjs!.adInit!(); | ||
|
|
||
| if (selectedElement) { | ||
| if (publisherOwned) { | ||
| expect(defineSlot).not.toHaveBeenCalled(); | ||
| expect(nativeRefresh).toHaveBeenCalledWith([mockSlot]); | ||
| } else { | ||
| expect(defineSlot).toHaveBeenCalledWith( | ||
| '/123/responsive', | ||
| [[300, 250]], | ||
| selectedElement.id | ||
| ); | ||
| expect(nativeDisplay).toHaveBeenCalledWith(selectedElement.id); | ||
| } | ||
| expect((window as TestWindow).tsjs!.divToSlotId).toEqual({ | ||
| [selectedElement.id]: 'responsive_slot', | ||
| }); | ||
| } else { | ||
| expect(defineSlot).not.toHaveBeenCalled(); | ||
| expect((window as TestWindow).tsjs!.divToSlotId).toEqual({}); | ||
| } | ||
| } | ||
| ); | ||
|
|
||
| it('resolves dynamic div prefixes without interpolating div_id into a CSS selector', async () => { | ||
| const dynamicDiv = document.createElement('div'); | ||
| dynamicDiv.id = "ad'prefix-real"; | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.