diff --git a/.changeset/prechat-submit-validation-focus.md b/.changeset/prechat-submit-validation-focus.md new file mode 100644 index 00000000..10860075 --- /dev/null +++ b/.changeset/prechat-submit-validation-focus.md @@ -0,0 +1,5 @@ +--- +"@chatcops/widget": patch +--- + +Keep pre-chat submit button enabled, show all field errors and focus the first invalid field on submit, and hide the required asterisk marker from screen readers. diff --git a/e2e/screenshots/visual.spec.ts/s5-prechat-dark.png b/e2e/screenshots/visual.spec.ts/s5-prechat-dark.png index f5e429b6..ce428b2c 100644 Binary files a/e2e/screenshots/visual.spec.ts/s5-prechat-dark.png and b/e2e/screenshots/visual.spec.ts/s5-prechat-dark.png differ diff --git a/e2e/screenshots/visual.spec.ts/s5-prechat-light.png b/e2e/screenshots/visual.spec.ts/s5-prechat-light.png index 706128ff..a13cab03 100644 Binary files a/e2e/screenshots/visual.spec.ts/s5-prechat-light.png and b/e2e/screenshots/visual.spec.ts/s5-prechat-light.png differ diff --git a/e2e/screenshots/visual.spec.ts/s5-prechat-rtl.png b/e2e/screenshots/visual.spec.ts/s5-prechat-rtl.png index 1d8b37cb..95d9d153 100644 Binary files a/e2e/screenshots/visual.spec.ts/s5-prechat-rtl.png and b/e2e/screenshots/visual.spec.ts/s5-prechat-rtl.png differ diff --git a/e2e/tests/states.spec.ts b/e2e/tests/states.spec.ts index 0d62b6d7..d4375bc1 100644 --- a/e2e/tests/states.spec.ts +++ b/e2e/tests/states.spec.ts @@ -144,6 +144,10 @@ for (const look of looks) { await openChat(page); await expect(page.locator('.cc-prechat')).toBeVisible(); await expectAccessible(page); + // Press Start Chat on empty form, check focus and run axe. + await page.locator('.cc-prechat button[type="submit"]').click(); + await expect(page.getByRole('textbox', { name: 'Name' })).toBeFocused(); + await expectAccessible(page); // A wrong email: the error shows next to the field, and is still accessible. await page.getByRole('textbox', { name: 'Name' }).fill('Sam'); await page.getByRole('textbox', { name: 'Email' }).fill('not an email'); diff --git a/packages/widget/mangle.ts b/packages/widget/mangle.ts index b689b22f..2fb360ee 100644 --- a/packages/widget/mangle.ts +++ b/packages/widget/mangle.ts @@ -28,7 +28,7 @@ export const CHECKED = [ 'markFailed', 'nearBottom', 'pageData', 'panelLabels', 'renderDisclosure', 'renderHeader', 'renderMessageElement', 'renderStream', 'renderSuggestions', 'resolveContainer', 'resolveErrorType', 'restoreScroll', 'saveHistory', 'scrollToBottom', 'sendToServer', 'sessionKey', 'setHidden', 'showChatView', 'showError', - 'showLatestRegenerateButton', 'streams', 'submitBtn', 'ttlMs', 'updateSubmitState', 'userDataSentWith', 'userFromSite', + 'showLatestRegenerateButton', 'streams', 'submitBtn', 'ttlMs', 'userDataSentWith', 'userFromSite', ]; export const MANGLED_PROPERTIES = new RegExp(`^(?:${[...EARLIER, ...CHECKED].join('|')})$`); diff --git a/packages/widget/src/dom/prechat-form.ts b/packages/widget/src/dom/prechat-form.ts index 90eff2e2..48acadf9 100644 --- a/packages/widget/src/dom/prechat-form.ts +++ b/packages/widget/src/dom/prechat-form.ts @@ -68,8 +68,6 @@ export class PreChatForm { parent.appendChild(this.container); addStyles(parent.getRootNode(), options.nonce); - this.updateSubmitState(); - const firstInput = this.fieldElements.values().next().value; if (firstInput && options.autoFocus !== false) { setTimeout(() => firstInput.focus(), 100); @@ -90,6 +88,7 @@ export class PreChatForm { if (field.required) { const req = document.createElement('span'); req.className = 'cc-required'; + req.setAttribute('aria-hidden', 'true'); req.textContent = '*'; label.appendChild(req); } @@ -137,12 +136,10 @@ export class PreChatForm { } input.addEventListener('input', () => { this.clearError(field.name); - this.updateSubmitState(); }); if (input instanceof HTMLSelectElement) { input.addEventListener('change', () => { this.clearError(field.name); - this.updateSubmitState(); }); } wrapper.appendChild(input); @@ -157,18 +154,10 @@ export class PreChatForm { return wrapper; } - private updateSubmitState(): void { - const allRequiredFilled = this.options.fields.every((field) => { - if (!field.required) return true; - const el = this.fieldElements.get(field.name); - return el ? el.value.trim().length > 0 : false; - }); - this.submitBtn.disabled = !allRequiredFilled; - } - private handleSubmit(): void { const data: Record = {}; let valid = true; + let firstInvalid: HTMLElement | null = null; for (const field of this.options.fields) { const el = this.fieldElements.get(field.name); @@ -179,18 +168,23 @@ export class PreChatForm { if (field.required && !value) { this.showError(field.name, this.options.locale.preChatRequired); valid = false; + firstInvalid ??= el; continue; } if (field.type === 'email' && value && !this.isValidEmail(value)) { this.showError(field.name, this.options.locale.preChatInvalidEmail); valid = false; + firstInvalid ??= el; } } - if (valid) { - this.options.onSubmit(data); + if (!valid) { + firstInvalid?.focus(); + return; } + + this.options.onSubmit(data); } private showError(fieldName: string, message: string): void { diff --git a/packages/widget/src/styles/prechat.css b/packages/widget/src/styles/prechat.css index 97547973..854a7d42 100644 --- a/packages/widget/src/styles/prechat.css +++ b/packages/widget/src/styles/prechat.css @@ -100,11 +100,6 @@ background: var(--cc-accent-hover); } -.cc-prechat-submit:disabled { - opacity: 0.5; - cursor: not-allowed; -} - .cc-prechat-input:focus-visible, .cc-prechat-select:focus-visible, .cc-prechat-textarea:focus-visible, diff --git a/packages/widget/tests/dom/prechat-form.test.ts b/packages/widget/tests/dom/prechat-form.test.ts index 8de77ccc..883c28a0 100644 --- a/packages/widget/tests/dom/prechat-form.test.ts +++ b/packages/widget/tests/dom/prechat-form.test.ts @@ -81,7 +81,9 @@ describe('PreChatForm', () => { const emailLabel = labels[1]; const topicLabel = labels[2]; - expect(nameLabel.querySelector('.cc-required')).toBeTruthy(); + const nameReq = nameLabel.querySelector('.cc-required'); + expect(nameReq).toBeTruthy(); + expect(nameReq?.getAttribute('aria-hidden')).toBe('true'); expect(emailLabel.querySelector('.cc-required')).toBeTruthy(); expect(topicLabel.querySelector('.cc-required')).toBeNull(); }); @@ -133,25 +135,45 @@ describe('PreChatForm', () => { expect(nameError.textContent).toBe(''); }); - it('disables submit when required fields are empty', () => { - createForm(parent); + it('keeps submit enabled and focuses the first invalid field on submit', () => { + const onSubmit = vi.fn(); + createForm(parent, [], onSubmit); + const btn = parent.querySelector('.cc-prechat-submit') as HTMLButtonElement; - expect(btn.disabled).toBe(true); + expect(btn.disabled).toBe(false); + + const form = parent.querySelector('form') as HTMLFormElement; + form.dispatchEvent(new Event('submit', { cancelable: true })); + + const errors = parent.querySelectorAll('.cc-prechat-error'); + expect(errors[0].textContent).toBe('This field is required'); + expect(errors[1].textContent).toBe('This field is required'); + + const nameInput = parent.querySelector('input[name="name"]') as HTMLInputElement; + expect(document.activeElement).toBe(nameInput); + expect(onSubmit).not.toHaveBeenCalled(); }); - it('enables submit when all required fields are filled', () => { - createForm(parent); + it('focuses the first empty required field when an earlier field is filled', () => { + const onSubmit = vi.fn(); + createForm(parent, [], onSubmit); const nameInput = parent.querySelector('input[name="name"]') as HTMLInputElement; const emailInput = parent.querySelector('input[name="email"]') as HTMLInputElement; nameInput.value = 'Alice'; nameInput.dispatchEvent(new Event('input')); - expect((parent.querySelector('.cc-prechat-submit') as HTMLButtonElement).disabled).toBe(true); - - emailInput.value = 'alice@example.com'; - emailInput.dispatchEvent(new Event('input')); expect((parent.querySelector('.cc-prechat-submit') as HTMLButtonElement).disabled).toBe(false); + + const form = parent.querySelector('form') as HTMLFormElement; + form.dispatchEvent(new Event('submit', { cancelable: true })); + + const errors = parent.querySelectorAll('.cc-prechat-error'); + expect(errors[0].textContent).toBe(''); + expect(errors[1].textContent).toBe('This field is required'); + + expect(document.activeElement).toBe(emailInput); + expect(onSubmit).not.toHaveBeenCalled(); }); }); @@ -174,6 +196,7 @@ describe('PreChatForm', () => { const errors = parent.querySelectorAll('.cc-prechat-error'); const emailError = errors[1]; expect(emailError.textContent).toBe('Please enter a valid email'); + expect(document.activeElement).toBe(emailInput); expect(onSubmit).not.toHaveBeenCalled(); }); diff --git a/website/src/content/docs/widget/pre-chat-form.mdx b/website/src/content/docs/widget/pre-chat-form.mdx index 4bcf4156..e8a75ad5 100644 --- a/website/src/content/docs/widget/pre-chat-form.mdx +++ b/website/src/content/docs/widget/pre-chat-form.mdx @@ -53,10 +53,10 @@ The form appears when there is no saved conversation with messages and the visit | `type` | `'text' \| 'email' \| 'select' \| 'textarea'` | Required input type. Email fields are checked for a valid email format. | | `label` | `string` | Required text label displayed above the field. | | `placeholder` | `string` | Optional placeholder. For a select, this replaces the default prompt. If omitted, the select prompt comes from `strings.selectPlaceholder` (English default: `Select {label}...`). | -| `required` | `boolean` | Optional. When `true`, the visitor must enter or select a non-empty value before submitting. Defaults to `false`. | +| `required` | `boolean` | Optional. When `true`, submitting with an empty value shows an error and focuses the field. Defaults to `false`. | | `options` | `string[]` | Optional choices for a `select` field. | -Required fields are checked for non-empty values, and non-empty `email` fields are checked for email format. Invalid fields show an error and the form stays open until corrected. Values are trimmed before they are submitted. +On submit, required fields are checked for non-empty values, and non-empty `email` fields are checked for email format. Invalid fields show an error, focus moves to the first invalid field, and the form stays open until corrected. Values are trimmed before they are submitted. ## What happens to answers