Skip to content
Merged
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
103 changes: 103 additions & 0 deletions __tests__/controllers/popup_controller_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ describe('PopupController', () => {
})
jest.spyOn(PopupsAPI, 'cancel').mockResolvedValue({ failed: false, succeeded: true })
jest.spyOn(Hellotext.eventEmitter, 'dispatch')
jest.spyOn(Hellotext, 'track').mockResolvedValue({ succeeded: true })
})

afterEach(() => {
Expand Down Expand Up @@ -1946,4 +1947,106 @@ describe('PopupController', () => {
expect(phoneInput.checkValidity()).toBe(false)
})

describe('step tracking', () => {
const flush = () => new Promise(resolve => setTimeout(resolve, 0))
const type = input => input.dispatchEvent(new Event('input', { bubbles: true }))
const stepReport = (action, stepId) => [
action,
{ popup_id: 'popup-id', step_id: stepId, tracked_at: expect.any(String) },
]

beforeEach(() => {
jest.spyOn(Hellotext, 'session', 'get').mockReturnValue('session-id')
})

afterEach(() => {
controller?.disconnect()
})

it('reports the first step viewed when the dialog opens, not when the bubble shows', async () => {
buildController({ hasBubble: true })

controller.showInitialState()
await flush()

expect(Hellotext.track).not.toHaveBeenCalled()

controller.open()
await flush()

expect(Hellotext.track).toHaveBeenCalledWith(...stepReport('popup.step_viewed', 'step-one'))
})

it('reports the start of a step on the first input in one of its fields', async () => {
const { emailInput } = buildController({ hasBubble: false })

controller.connect()
emailInput.focus()
await flush()

expect(Hellotext.track).not.toHaveBeenCalledWith(...stepReport('popup.step_started', 'step-one'))

type(emailInput)
type(emailInput)
await flush()

expect(
Hellotext.track.mock.calls.filter(([action]) => action === 'popup.step_started'),
).toEqual([stepReport('popup.step_started', 'step-one')])
})

it('reports a step completed when the visitor moves on, and never the last step', async () => {
const { emailInput, phoneInput } = buildController({ hasBubble: false })

controller.connect()
emailInput.value = 'customer@example.com'
await controller.next()
await flush()

expect(Hellotext.track).toHaveBeenCalledWith(...stepReport('popup.step_completed', 'step-one'))
expect(Hellotext.track).toHaveBeenCalledWith(...stepReport('popup.step_viewed', 'step-two'))

phoneInput.value = '+59899123456'
await controller.next()
await flush()

expect(PopupsAPI.submit).toHaveBeenCalled()
expect(Hellotext.track).not.toHaveBeenCalledWith(...stepReport('popup.step_completed', 'step-two'))
})

it('reports a step once per session and day, and again after a failed report', async () => {
jest.useFakeTimers({ doNotFake: ['setTimeout', 'nextTick', 'setImmediate', 'queueMicrotask'] })
jest.setSystemTime(new Date(2026, 10, 6, 12))
Hellotext.track.mockResolvedValueOnce({ succeeded: false })
buildController({ hasBubble: false })

controller.connect()
await flush()
controller.showStep(0)
await flush()
controller.showStep(0)
await flush()

expect(Hellotext.track).toHaveBeenCalledTimes(2)

jest.setSystemTime(new Date(2026, 10, 7, 12))
controller.showStep(0)
await flush()

expect(Hellotext.track).toHaveBeenCalledTimes(3)
})

it('keeps the popup working when the report fails', async () => {
Hellotext.track.mockRejectedValue(new Error('offline'))
const { stepOne, stepTwo, emailInput } = buildController({ hasBubble: false })

controller.connect()
emailInput.value = 'customer@example.com'
await controller.next()
await flush()

expect(stepOne.hidden).toBe(true)
expect(stepTwo.hidden).toBe(false)
})
})
})
2 changes: 1 addition & 1 deletion dist/hellotext.js

Large diffs are not rendered by default.

10 changes: 10 additions & 0 deletions docs/popups.md
Original file line number Diff line number Diff line change
Expand Up @@ -196,3 +196,13 @@ Remove a listener by passing the same callback:
```js
Hellotext.removeEventListener('popup:opened', onPopupOpened)
```

### Step reporting

The popup reports its steps to Hellotext through `Hellotext.track`, with the popup's and the step's public ids, for the popup report:

- `popup.step_viewed` - The dialog shows the step: when it opens, after a bubble click, or when the visitor reaches the step. Showing the bubble alone does not report it.
- `popup.step_started` - The first input in one of the step's fields. Focus alone does not report it.
- `popup.step_completed` - The step passed validation and the visitor moved on to the next one. The last step never reports it: sending the popup completes it, and Hellotext counts the submission.

Each one is sent once per session, popup, step and local day. A report that fails is sent again the next time, and a failed report never stops the popup.
72 changes: 72 additions & 0 deletions lib/controllers/popup_controller.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,13 @@ const PUSH_SUBSCRIPTION_TIMEOUT = 15000;
const PUSH_LOADING_DOT_INTERVAL = 450;
const PUSH_LOADING_LABEL = 'Enable notifications';

// The popup report counts, for each step, the browsers that saw it, started filling it in and
// moved on from it. Sending the last step is the submission, which the server counts as that
// step's completion, so the last step never reports popup.step_completed.
const STEP_VIEWED = 'popup.step_viewed';
const STEP_STARTED = 'popup.step_started';
const STEP_COMPLETED = 'popup.step_completed';

/**
* An input rendered by the popup's server-side field components.
*
Expand Down Expand Up @@ -114,6 +121,7 @@ class _default extends _stimulus.Controller {
*/
initialize() {
this.stepIndex = 0;
this.trackingSteps = new Set();
this.resendLabel = this.hasResendButtonTarget ? this.resendButtonTarget.textContent.trim() : '';
this.rules = new _popup_display_rules.PopupDisplayRules(this.rulesValue);
this.connectedAt = this.pageStartedAt();
Expand All @@ -134,6 +142,8 @@ class _default extends _stimulus.Controller {
if (this.requiredPushUnavailable) this.dismissed = true;
this.syncRequiredPush = this.syncRequiredPush.bind(this);
this.element.addEventListener('change', this.syncRequiredPush);
this.trackStepStart = this.trackStepStart.bind(this);
this.element.addEventListener('input', this.trackStepStart);
this.syncRequiredPush();
this.requireBirthdays();
// Another tab may have sent or closed this popup while its HTML was loading, before the
Expand Down Expand Up @@ -166,6 +176,7 @@ class _default extends _stimulus.Controller {
window.removeEventListener('storage', this.closeIfFinishedElsewhere);
window.removeEventListener('pageshow', this.closeIfFinishedElsewhere);
this.element.removeEventListener('change', this.syncRequiredPush);
this.element.removeEventListener('input', this.trackStepStart);
this.reportActivity(false);
}
pageStartedAt() {
Expand Down Expand Up @@ -331,6 +342,7 @@ class _default extends _stimulus.Controller {
this.dialogTarget.hidden = false;
_hellotext.default.eventEmitter.dispatch('popup:opened');
this.reportActivity();
this.trackStepView();
}

/**
Expand Down Expand Up @@ -386,6 +398,7 @@ class _default extends _stimulus.Controller {
this.clearErrorMessages(this.currentStepInputs);
await this.subscribeForPushOnCurrentStep();
if (this.stepIndex < this.stepTargets.length - 1) {
this.trackStep(STEP_COMPLETED, this.stepTargets[this.stepIndex]);
this.showStep(this.stepIndex + 1);
return;
}
Expand Down Expand Up @@ -844,6 +857,7 @@ class _default extends _stimulus.Controller {
if (this.hasBubbleTarget) this.bubbleTarget.hidden = true;
this.dialogTarget.hidden = false;
_hellotext.default.eventEmitter.dispatch('popup:opened');
this.trackStepView();
}

/**
Expand All @@ -861,6 +875,7 @@ class _default extends _stimulus.Controller {
this.completedTarget.hidden = true;
if (this.hasPushRequiredTarget) this.pushRequiredTarget.hidden = true;
this.reportActivity();
this.trackStepView();
}

/**
Expand All @@ -881,6 +896,63 @@ class _default extends _stimulus.Controller {
this.reportActivity();
}

/**
* Report that the visitor sees the current step: the dialog shows it, not the bubble or the
* completion.
*
* @returns {void}
*/
trackStepView() {
if (this.element.hidden || this.dialogTarget.hidden || !this.completedTarget.hidden) return;
this.trackStep(STEP_VIEWED, this.stepTargets[this.stepIndex]);
}

/**
* Report the visitor's first input in a step. Focus alone doesn't count.
*
* @param {InputEvent} event - Input from one of the popup's fields.
* @returns {void}
*/
trackStepStart(event) {
const stepId = event.target?.dataset?.popupStepId;
if (!stepId) return;
this.trackStep(STEP_STARTED, this.stepTargets.find(step => step.dataset.stepId === stepId));
}

/**
* Report a step's view, start or completion once per session, popup, step and local day. The
* mark is written only when the server received the report, so a failed report is sent again
* the next time. Tracking never breaks the popup.
*
* @param {string} action - popup.step_viewed, popup.step_started or popup.step_completed.
* @param {HTMLElement} [step] - Step carrying a data-step-id attribute.
* @returns {Promise<void>}
*/
async trackStep(action, step) {
const stepId = step?.dataset.stepId;
if (!stepId) return;
const key = `hellotext--popup--${this.idValue}--${stepId}--${action}`;
const marker = `${_hellotext.default.session}:${this.localDate}`;
if (this.trackingSteps.has(key) || _hellotext.default.readStorage('localStorage', key) === marker) return;
this.trackingSteps.add(key);
try {
const response = await _hellotext.default.track(action, {
popup_id: this.idValue,
step_id: stepId,
tracked_at: new Date().toISOString()
});
if (response?.succeeded) _hellotext.default.writeStorage('localStorage', key, marker);
} catch (_) {
// Tracking must never break the popup.
} finally {
this.trackingSteps.delete(key);
}
}
get localDate() {
const now = new Date();
return [now.getFullYear(), now.getMonth() + 1, now.getDate()].map(part => String(part).padStart(2, '0')).join('-');
}

/**
* Tell the SDK whether the visitor is still going through this popup: its dialog shows a
* form step or the Push-required step. The Smart Alert waits for the popup, so the two never
Expand Down
72 changes: 72 additions & 0 deletions lib/controllers/popup_controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,13 @@ const PUSH_SUBSCRIPTION_TIMEOUT = 15000;
const PUSH_LOADING_DOT_INTERVAL = 450;
const PUSH_LOADING_LABEL = 'Enable notifications';

// The popup report counts, for each step, the browsers that saw it, started filling it in and
// moved on from it. Sending the last step is the submission, which the server counts as that
// step's completion, so the last step never reports popup.step_completed.
const STEP_VIEWED = 'popup.step_viewed';
const STEP_STARTED = 'popup.step_started';
const STEP_COMPLETED = 'popup.step_completed';

/**
* An input rendered by the popup's server-side field components.
*
Expand Down Expand Up @@ -108,6 +115,7 @@ export default class extends Controller {
*/
initialize() {
this.stepIndex = 0;
this.trackingSteps = new Set();
this.resendLabel = this.hasResendButtonTarget ? this.resendButtonTarget.textContent.trim() : '';
this.rules = new PopupDisplayRules(this.rulesValue);
this.connectedAt = this.pageStartedAt();
Expand All @@ -128,6 +136,8 @@ export default class extends Controller {
if (this.requiredPushUnavailable) this.dismissed = true;
this.syncRequiredPush = this.syncRequiredPush.bind(this);
this.element.addEventListener('change', this.syncRequiredPush);
this.trackStepStart = this.trackStepStart.bind(this);
this.element.addEventListener('input', this.trackStepStart);
this.syncRequiredPush();
this.requireBirthdays();
// Another tab may have sent or closed this popup while its HTML was loading, before the
Expand Down Expand Up @@ -160,6 +170,7 @@ export default class extends Controller {
window.removeEventListener('storage', this.closeIfFinishedElsewhere);
window.removeEventListener('pageshow', this.closeIfFinishedElsewhere);
this.element.removeEventListener('change', this.syncRequiredPush);
this.element.removeEventListener('input', this.trackStepStart);
this.reportActivity(false);
}
pageStartedAt() {
Expand Down Expand Up @@ -325,6 +336,7 @@ export default class extends Controller {
this.dialogTarget.hidden = false;
Hellotext.eventEmitter.dispatch('popup:opened');
this.reportActivity();
this.trackStepView();
}

/**
Expand Down Expand Up @@ -380,6 +392,7 @@ export default class extends Controller {
this.clearErrorMessages(this.currentStepInputs);
await this.subscribeForPushOnCurrentStep();
if (this.stepIndex < this.stepTargets.length - 1) {
this.trackStep(STEP_COMPLETED, this.stepTargets[this.stepIndex]);
this.showStep(this.stepIndex + 1);
return;
}
Expand Down Expand Up @@ -838,6 +851,7 @@ export default class extends Controller {
if (this.hasBubbleTarget) this.bubbleTarget.hidden = true;
this.dialogTarget.hidden = false;
Hellotext.eventEmitter.dispatch('popup:opened');
this.trackStepView();
}

/**
Expand All @@ -855,6 +869,7 @@ export default class extends Controller {
this.completedTarget.hidden = true;
if (this.hasPushRequiredTarget) this.pushRequiredTarget.hidden = true;
this.reportActivity();
this.trackStepView();
}

/**
Expand All @@ -875,6 +890,63 @@ export default class extends Controller {
this.reportActivity();
}

/**
* Report that the visitor sees the current step: the dialog shows it, not the bubble or the
* completion.
*
* @returns {void}
*/
trackStepView() {
if (this.element.hidden || this.dialogTarget.hidden || !this.completedTarget.hidden) return;
this.trackStep(STEP_VIEWED, this.stepTargets[this.stepIndex]);
}

/**
* Report the visitor's first input in a step. Focus alone doesn't count.
*
* @param {InputEvent} event - Input from one of the popup's fields.
* @returns {void}
*/
trackStepStart(event) {
const stepId = event.target?.dataset?.popupStepId;
if (!stepId) return;
this.trackStep(STEP_STARTED, this.stepTargets.find(step => step.dataset.stepId === stepId));
}

/**
* Report a step's view, start or completion once per session, popup, step and local day. The
* mark is written only when the server received the report, so a failed report is sent again
* the next time. Tracking never breaks the popup.
*
* @param {string} action - popup.step_viewed, popup.step_started or popup.step_completed.
* @param {HTMLElement} [step] - Step carrying a data-step-id attribute.
* @returns {Promise<void>}
*/
async trackStep(action, step) {
const stepId = step?.dataset.stepId;
if (!stepId) return;
const key = `hellotext--popup--${this.idValue}--${stepId}--${action}`;
const marker = `${Hellotext.session}:${this.localDate}`;
if (this.trackingSteps.has(key) || Hellotext.readStorage('localStorage', key) === marker) return;
this.trackingSteps.add(key);
try {
const response = await Hellotext.track(action, {
popup_id: this.idValue,
step_id: stepId,
tracked_at: new Date().toISOString()
});
if (response?.succeeded) Hellotext.writeStorage('localStorage', key, marker);
} catch (_) {
// Tracking must never break the popup.
} finally {
this.trackingSteps.delete(key);
}
}
get localDate() {
const now = new Date();
return [now.getFullYear(), now.getMonth() + 1, now.getDate()].map(part => String(part).padStart(2, '0')).join('-');
}

/**
* Tell the SDK whether the visitor is still going through this popup: its dialog shows a
* form step or the Push-required step. The Smart Alert waits for the popup, so the two never
Expand Down
Loading
Loading