Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
83 changes: 83 additions & 0 deletions __tests__/api/popups_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -165,4 +165,87 @@ describe('PopupsAPI', () => {
})
expect(response.succeeded).toBe(true)
})

it('resolves the active popup for a path while skipping finished ids', async () => {
global.fetch.mockResolvedValue({
ok: true,
json: async () => ({
eligible: true,
popup: { id: 'general-popup' },
html: '<article data-controller="hellotext--popup" data-hellotext--popup-id-value="general-popup"></article>',
business: { id: 'xy76ks' },
locale: 'en',
}),
})

const resolved = await PopupsAPI.resolve({
path: '/electrohogar',
finishedIds: ['telefonia-popup'],
})

const requestedUrl = new URL(global.fetch.mock.calls[0][0])
expect(requestedUrl.pathname).toBe('/v1/public/popups/resolve')
expect(requestedUrl.searchParams.get('path')).toBe('/electrohogar')
expect(requestedUrl.searchParams.getAll('finished_ids[]')).toEqual(['telefonia-popup'])
expect(resolved.id).toBe('general-popup')
expect(resolved.html.getAttribute('data-hellotext--popup-id-value')).toBe('general-popup')
})

it('returns null from resolve when no popup is eligible', async () => {
global.fetch.mockResolvedValue({
ok: true,
json: async () => ({
eligible: false,
locale: 'en',
}),
})

const warn = jest.spyOn(console, 'warn').mockImplementation(() => {})
try {
await expect(PopupsAPI.resolve({ path: '/electrohogar' })).resolves.toBeNull()
expect(warn).not.toHaveBeenCalled()
} finally {
warn.mockRestore()
}
})

it.each([
[{ ok: false, status: 503 }, 'HTTP 503'],
[{ ok: true, json: async () => { throw new SyntaxError() } }, 'invalid response'],
[{
ok: true,
json: async () => ({
eligible: true,
popup: { id: 'winner' },
html: '<article data-hellotext--popup-id-value="different"></article>',
}),
}, 'invalid popup identity'],
])('reports resolver failures without including the request URL', async (response, reason) => {
const warn = jest.spyOn(console, 'warn').mockImplementation(() => {})
global.fetch.mockResolvedValue(response)
try {
await expect(PopupsAPI.resolve({ path: '/private-path' })).resolves.toBeNull()
expect(warn).toHaveBeenCalledWith('Hellotext popup resolution failed:', reason)
} finally {
warn.mockRestore()
}
})

it('times out an unresponsive resolver', async () => {
jest.useFakeTimers()
const warn = jest.spyOn(console, 'warn').mockImplementation(() => {})
global.fetch.mockImplementation((_url, { signal }) => new Promise((_, reject) => {
signal.addEventListener('abort', () => reject(new Error('aborted')), { once: true })
}))
try {
const pending = PopupsAPI.resolve()
jest.advanceTimersByTime(10_000)
await expect(pending).resolves.toBeNull()
expect(warn).toHaveBeenCalledTimes(1)
expect(warn).toHaveBeenCalledWith('Hellotext popup resolution failed:', 'timeout')
} finally {
warn.mockRestore()
jest.useRealTimers()
}
})
})
129 changes: 129 additions & 0 deletions __tests__/hellotext_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1342,3 +1342,132 @@ describe('when initializing Push', () => {
expect(Hellotext.push).toBeNull()
})
})

describe('when resolving multiple popups', () => {
beforeAll(() => jest.spyOn(global, 'window', 'get').mockRestore())

it('resolves active popups on the server when multiple popups are pending', async () => {
const pathSpy = jest.spyOn(Hellotext, 'currentPopupPath').mockReturnValue('/electrohogar')
localStorage.setItem('hello_popup_submitted_finished-popup', '1')

mockBusinessFetch(defaultBusiness({
popup: { id: 'finished-popup' },
popups: [{ id: 'finished-popup' }, { id: 'popup-a' }, { id: 'popup-b' }],
}))

const resolveSpy = jest.spyOn(Popup, 'resolve').mockResolvedValue({
id: 'popup-b',
mounted: true,
data: { html: document.createElement('article') },
rendered: Promise.resolve(true),
unmount: jest.fn(),
})

await Hellotext.initialize('xy76ks')

expect(resolveSpy).toHaveBeenCalledWith(
expect.objectContaining({
path: '/electrohogar',
finishedIds: ['finished-popup'],
}),
)
expect(Hellotext.popup.id).toBe('popup-b')

resolveSpy.mockRestore()
pathSpy.mockRestore()
localStorage.removeItem('hello_popup_submitted_finished-popup')
})

it('still resolves by route when only one active popup is unfinished', async () => {
localStorage.setItem('hello_popup_submitted_popup-a', '1')

mockBusinessFetch(defaultBusiness({
popup: { id: 'popup-a' },
popups: [{ id: 'popup-a' }, { id: 'popup-b' }],
}))

const resolveSpy = jest.spyOn(Popup, 'resolve').mockResolvedValue({
id: 'popup-b',
mounted: true,
data: { html: document.createElement('article') },
rendered: Promise.resolve(true),
unmount: jest.fn(),
})

await Hellotext.initialize('xy76ks')

expect(resolveSpy).toHaveBeenCalledWith(expect.objectContaining({ finishedIds: ['popup-a'] }))
resolveSpy.mockRestore()
localStorage.removeItem('hello_popup_submitted_popup-a')
})

it('releases initialization when a new route cancels the pending initial popup', async () => {
const path = window.location.href
window.history.replaceState({}, '', '/')
mockBusinessFetch(defaultBusiness({ popups: [{ id: 'general' }, { id: 'category' }] }))
const resolve = jest.spyOn(API.popups, 'resolve').mockImplementation(({ signal }) =>
new Promise(complete => signal.addEventListener('abort', () => complete(null), { once: true })),
)
try {
const initialized = Hellotext.initialize('xy76ks')
await new Promise(complete => setTimeout(complete, 0))
const initialSignal = resolve.mock.calls[0][0].signal
window.history.pushState({}, '', '/electrohogar')
await initialized
expect(initialSignal.aborted).toBe(true)
expect(resolve.mock.calls[1][0].signal.aborted).toBe(false)
await Hellotext.initialize('xy76ks', { popup: false })
expect(resolve.mock.calls[1][0].signal.aborted).toBe(true)
} finally {
resolve.mockRestore()
await Hellotext.initialize('xy76ks', { popup: false })
window.history.replaceState({}, '', path)
}
})

it('replaces the mounted popup on SPA navigation and ignores an out-of-order response', async () => {
await Hellotext.initialize('xy76ks', { popup: false })
const originalPath = window.location.href
window.history.replaceState({}, '', '/')
mockBusinessFetch(defaultBusiness({
popup: { id: 'general' },
popups: [{ id: 'general' }, { id: 'category' }],
}))
const requests = []
const resolve = jest.spyOn(API.popups, 'resolve').mockImplementation(
options => new Promise(complete => requests.push({ ...options, complete })),
)
const respond = (index, id) => {
const html = document.createElement('article')
html.id = id
requests[index].complete({ id, html })
}
const tick = () => new Promise(complete => setTimeout(complete, 0))

try {
const init = Hellotext.initialize('xy76ks')
await tick()
respond(0, 'general')
await init
expect(document.getElementById('general')).not.toBeNull()

window.history.pushState({}, '', '/electrohogar')
expect(document.getElementById('general')).toBeNull()
window.history.pushState({}, '', '/#/ofertas?utm_source=email')
window.history.replaceState({}, '', '/#!/ofertas?utm_source=sms')
expect(requests.map(({ path }) => path)).toEqual(['/', '/electrohogar', '/#/ofertas'])
expect(Hellotext.visitCampaign).toEqual({ source: 'sms' })

respond(2, 'offers')
await tick()
respond(1, 'category')
await tick()
expect(document.getElementById('category')).toBeNull()
expect(document.getElementById('offers')).toBe(Hellotext.popup.data.html)
} finally {
resolve.mockRestore()
await Hellotext.initialize('xy76ks', { popup: false })
window.history.replaceState({}, '', originalPath)
}
})
})
2 changes: 1 addition & 1 deletion dist/hellotext.js

Large diffs are not rendered by default.

4 changes: 1 addition & 3 deletions dist/hellotext.js.LICENSE.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1 @@
/*! @license DOMPurify 3.4.17 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.17/LICENSE */

/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
/*! @license DOMPurify 3.4.15 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.15/LICENSE */
97 changes: 87 additions & 10 deletions lib/api/popups.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -22,26 +22,97 @@ class PopupsAPI {
static async get(id, {
linked = false
} = {}) {
const url = new URL(`${this.endpoint}/${id}`);
const url = this.buildUrl(`${this.endpoint}/${id}`);
if (linked) url.searchParams.append('linked', 'true');
const result = await this.fetchAndParse(url);
return result ? result.html : null;
}

/**
* Ask the server to select the first eligible popup for the current path,
* skipping popups already finished in this browser.
*
* @param {Object} [options]
* @param {String} [options.path]
* @param {Array<String>} [options.finishedIds]
* @returns {Promise<{ id: String|null, html: Element }|null>}
*/
static async resolve({
path = '',
finishedIds = [],
signal
} = {}) {
const url = this.buildUrl(`${this.endpoint}/resolve`);
url.searchParams.append('viewport', this.viewportDevice);
if (path) url.searchParams.append('path', path);
finishedIds.forEach(id => {
if (id) url.searchParams.append('finished_ids[]', id);
});
const controller = new AbortController();
const cancel = () => controller.abort();
const reportFailure = reason => {
if (!signal?.aborted) console.warn('Hellotext popup resolution failed:', reason);
};
if (signal?.aborted) return null;
signal?.addEventListener('abort', cancel, {
once: true
});
const timeout = setTimeout(() => {
reportFailure('timeout');
cancel();
}, 10_000);
try {
return await this.fetchAndParse(url, {
signal: controller.signal,
reportFailure
});
} finally {
clearTimeout(timeout);
signal?.removeEventListener('abort', cancel);
}
}
static buildUrl(endpointUrl) {
const url = new URL(endpointUrl);
url.searchParams.append('session', _hellotext.default.session);
url.searchParams.append('locale', _core.Locale.toString());
url.searchParams.append('device', this.runtimeDevice);
if (linked) url.searchParams.append('linked', 'true');
const response = await this.fetchPopup(url);
if (!response.ok) return null;
return url;
}
static async fetchAndParse(url, {
signal,
reportFailure
} = {}) {
const fail = reason => {
if (!signal?.aborted) reportFailure?.(reason);
return null;
};
const response = await this.fetchPopup(url, signal);
if (signal?.aborted) return null;
if (!response.ok) return fail(response.status ? `HTTP ${response.status}` : 'network error');
const data = await this.parsePopupResponse(response);
if (!data) return null;
if (signal?.aborted) return null;
if (!data || typeof data !== 'object') return fail('invalid response');

// The server evaluates the profile half of the display rules and answers
// `eligible: false` with no markup when this visitor does not qualify. That is a
// deliberate outcome rather than an error, so it is treated the same as "nothing to
// render" instead of surfacing as a failure.
if (data.eligible === false || !data.html) return null;
if (data.eligible === false) return null;
if (typeof data.html !== 'string') return fail('missing markup');
const html = new DOMParser().parseFromString(data.html, 'text/html').querySelector('article');
if (!html) return fail('missing popup article');
const articleId = html.getAttribute('data-hellotext--popup-id-value');
if (reportFailure && (data.eligible !== true || !articleId || data.popup?.id !== articleId)) {
return fail('invalid popup identity');
}
if (!_hellotext.default.business.data) {
_hellotext.default.business.setData(data.business);
_hellotext.default.business.setLocale(data.locale);
}
return new DOMParser().parseFromString(data.html, 'text/html').querySelector('article');
return {
id: data.popup?.id || articleId || null,
html
};
}
static async submit(id, data, idempotencyKey = this.idempotencyKey()) {
const response = await fetch(`${this.endpoint}/${id}/submissions`, {
Expand Down Expand Up @@ -83,11 +154,14 @@ class PopupsAPI {
}
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
}
static async fetchPopup(url) {
static async fetchPopup(url, signal) {
try {
return await fetch(url, {
method: 'GET',
headers: _hellotext.default.headers
headers: _hellotext.default.headers,
...(signal && {
signal
})
});
} catch (_) {
return {
Expand All @@ -97,7 +171,10 @@ class PopupsAPI {
}
static get runtimeDevice() {
if (_core.Configuration.popup.device !== 'auto') return _core.Configuration.popup.device;
return window.innerWidth <= 767 ? 'mobile' : 'desktop';
return this.viewportDevice;
}
static get viewportDevice() {
return window.innerWidth < 768 ? 'mobile' : 'desktop';
}
static async parsePopupResponse(response) {
try {
Expand Down
Loading