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
82 changes: 82 additions & 0 deletions __tests__/controllers/form_controller_test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { Application } from '@hotwired/stimulus'
import FormController from '../../src/controllers/form_controller'
import Hellotext from '../../src/hellotext'

const flush = () => new Promise(resolve => setTimeout(resolve, 0))

describe('Form start tracking', () => {
let application
let element

const input = () => element.querySelector('input')
const type = () => input().dispatchEvent(new Event('input', { bubbles: true }))

beforeEach(async () => {
localStorage.clear()
jest.spyOn(Hellotext, 'session', 'get').mockReturnValue('session-id')
jest.spyOn(Hellotext, 'track').mockResolvedValue({ succeeded: true })
jest.useFakeTimers({ doNotFake: ['setTimeout', 'nextTick', 'setImmediate', 'queueMicrotask'] })
jest.setSystemTime(new Date(2026, 10, 6, 12))

document.body.innerHTML = `
<form data-controller="hellotext--form" data-hellotext--form-data-value='{"id":"form-id","steps":[]}'>
<input data-hellotext--form-target="input" name="email">
</form>
`
element = document.querySelector('form')

application = Application.start()
application.register('hellotext--form', FormController)
await flush()
})

afterEach(() => {
application.stop()
jest.useRealTimers()
jest.restoreAllMocks()
document.body.innerHTML = ''
})

it('reports the first input, not the focus the form gives its first field', async () => {
expect(Hellotext.track).not.toHaveBeenCalled()

type()
await flush()

expect(Hellotext.track).toHaveBeenCalledWith('form.started', { form_id: 'form-id', tracked_at: expect.any(String) })
})

it('reports once per session, form and day', async () => {
type()
type()
await flush()
type()
await flush()

expect(Hellotext.track).toHaveBeenCalledTimes(1)

jest.setSystemTime(new Date(2026, 10, 7, 12))
type()
await flush()

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

it('reports again on the next input after a failed report', async () => {
Hellotext.track.mockResolvedValueOnce({ succeeded: false })

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

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

it('keeps the form working when reporting throws', async () => {
Hellotext.track.mockRejectedValueOnce(new Error('Offline'))

expect(() => type()).not.toThrow()
await flush()
})
})
2 changes: 1 addition & 1 deletion dist/hellotext.js

Large diffs are not rendered by default.

32 changes: 32 additions & 0 deletions lib/controllers/form_controller.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,46 @@ class _default extends _stimulus.Controller {
static targets = ['inputContainer', 'input', 'button', 'otpContainer'];
initialize() {
this.form = new _models.Form(this.dataValue, this.element);
this.onInput = this.trackStart.bind(this);
}
connect() {
super.connect();
this.element.addEventListener('submit', this.submit.bind(this));
this.element.addEventListener('input', this.onInput);
if (document.activeElement.tagName !== 'INPUT') {
this.inputTargets[0].focus();
}
}
disconnect() {
this.element.removeEventListener('input', this.onInput);
}

// Reports the first input once per session, form and day, which is how the
// website form report counts the visitors who started filling it in. Focus
// alone doesn't count: the form focuses its first input when it connects. A
// failed report is sent again on the next input.
async trackStart() {
if (this.trackingStart) return;
const key = `hellotext--form--${this.form.id}--tracked-start`;
const marker = `${_hellotext.default.session}:${this.localDate}`;
if (_hellotext.default.readStorage('localStorage', key) === marker) return;
this.trackingStart = true;
try {
const response = await _hellotext.default.track('form.started', {
form_id: this.form.id,
tracked_at: new Date().toISOString()
});
if (response?.succeeded) _hellotext.default.writeStorage('localStorage', key, marker);
} catch (_) {
// Tracking must never break the form.
} finally {
this.trackingStart = false;
}
}
get localDate() {
const now = new Date();
return [now.getFullYear(), now.getMonth() + 1, now.getDate()].map(part => String(part).padStart(2, '0')).join('-');
}
async submit(e) {
e.preventDefault();
if (this.invalid) {
Expand Down
32 changes: 32 additions & 0 deletions lib/controllers/form_controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,46 @@ export default class extends Controller {
static targets = ['inputContainer', 'input', 'button', 'otpContainer'];
initialize() {
this.form = new Form(this.dataValue, this.element);
this.onInput = this.trackStart.bind(this);
}
connect() {
super.connect();
this.element.addEventListener('submit', this.submit.bind(this));
this.element.addEventListener('input', this.onInput);
if (document.activeElement.tagName !== 'INPUT') {
this.inputTargets[0].focus();
}
}
disconnect() {
this.element.removeEventListener('input', this.onInput);
}

// Reports the first input once per session, form and day, which is how the
// website form report counts the visitors who started filling it in. Focus
// alone doesn't count: the form focuses its first input when it connects. A
// failed report is sent again on the next input.
async trackStart() {
if (this.trackingStart) return;
const key = `hellotext--form--${this.form.id}--tracked-start`;
const marker = `${Hellotext.session}:${this.localDate}`;
if (Hellotext.readStorage('localStorage', key) === marker) return;
this.trackingStart = true;
try {
const response = await Hellotext.track('form.started', {
form_id: this.form.id,
tracked_at: new Date().toISOString()
});
if (response?.succeeded) Hellotext.writeStorage('localStorage', key, marker);
} catch (_) {
// Tracking must never break the form.
} finally {
this.trackingStart = false;
}
}
get localDate() {
const now = new Date();
return [now.getFullYear(), now.getMonth() + 1, now.getDate()].map(part => String(part).padStart(2, '0')).join('-');
}
async submit(e) {
e.preventDefault();
if (this.invalid) {
Expand Down
41 changes: 41 additions & 0 deletions src/controllers/form_controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,58 @@ export default class extends Controller {

initialize() {
this.form = new Form(this.dataValue, this.element)
this.onInput = this.trackStart.bind(this)
}

connect() {
super.connect()
this.element.addEventListener('submit', this.submit.bind(this))
this.element.addEventListener('input', this.onInput)

if (document.activeElement.tagName !== 'INPUT') {
this.inputTargets[0].focus()
}
}

disconnect() {
this.element.removeEventListener('input', this.onInput)
}

// Reports the first input once per session, form and day, which is how the
// website form report counts the visitors who started filling it in. Focus
// alone doesn't count: the form focuses its first input when it connects. A
// failed report is sent again on the next input.
async trackStart() {
if (this.trackingStart) return

const key = `hellotext--form--${this.form.id}--tracked-start`
const marker = `${Hellotext.session}:${this.localDate}`
if (Hellotext.readStorage('localStorage', key) === marker) return

this.trackingStart = true
Comment thread
rockwellll marked this conversation as resolved.
Resolved

try {
const response = await Hellotext.track('form.started', {
form_id: this.form.id,
tracked_at: new Date().toISOString(),
})

if (response?.succeeded) Hellotext.writeStorage('localStorage', key, marker)
} catch (_) {
// Tracking must never break the form.
} finally {
this.trackingStart = false
}
}

get localDate() {
const now = new Date()

return [now.getFullYear(), now.getMonth() + 1, now.getDate()]
.map(part => String(part).padStart(2, '0'))
.join('-')
}

async submit(e) {
e.preventDefault()

Expand Down
Loading