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
5 changes: 5 additions & 0 deletions .changeset/prechat-submit-validation-focus.md
Original file line number Diff line number Diff line change
@@ -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.
Binary file modified e2e/screenshots/visual.spec.ts/s5-prechat-dark.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified e2e/screenshots/visual.spec.ts/s5-prechat-light.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified e2e/screenshots/visual.spec.ts/s5-prechat-rtl.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 4 additions & 0 deletions e2e/tests/states.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
2 changes: 1 addition & 1 deletion packages/widget/mangle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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('|')})$`);
24 changes: 9 additions & 15 deletions packages/widget/src/dom/prechat-form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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);
}
Expand Down Expand Up @@ -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);
Expand All @@ -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<string, string> = {};
let valid = true;
let firstInvalid: HTMLElement | null = null;

for (const field of this.options.fields) {
const el = this.fieldElements.get(field.name);
Expand All @@ -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 {
Expand Down
5 changes: 0 additions & 5 deletions packages/widget/src/styles/prechat.css
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
43 changes: 33 additions & 10 deletions packages/widget/tests/dom/prechat-form.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
Expand Down Expand Up @@ -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();
});
});

Expand All @@ -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();
});

Expand Down
4 changes: 2 additions & 2 deletions website/src/content/docs/widget/pre-chat-form.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Loading