Skip to content

Commit 6661ae8

Browse files
committed
Lexical: Improved focus control for popup modal forms
Now moves focus to first field on open, and restores focus back to editor on submit/close.
1 parent 1ee5711 commit 6661ae8

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

resources/js/wysiwyg/ui/framework/forms.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,13 @@ export class EditorForm extends EditorContainerUiElement {
9898
this.definition = definition;
9999
}
100100

101+
focusOnFirst() {
102+
const focusable = this.getDOMElement().querySelector('input,select,textarea');
103+
if (focusable) {
104+
(focusable as HTMLElement).focus();
105+
}
106+
}
107+
101108
setValues(values: Record<string, string>) {
102109
for (const name of Object.keys(values)) {
103110
const field = this.getFieldByName(name);

resources/js/wysiwyg/ui/framework/modals.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ export interface EditorFormModalDefinition extends EditorModalDefinition {
1414
export class EditorFormModal extends EditorContainerUiElement {
1515
protected definition: EditorFormModalDefinition;
1616
protected key: string;
17+
protected originalFocus: Element|null = null;
1718

1819
constructor(definition: EditorFormModalDefinition, key: string) {
1920
super([new EditorForm(definition.form)]);
@@ -22,6 +23,7 @@ export class EditorFormModal extends EditorContainerUiElement {
2223
}
2324

2425
show(defaultValues: Record<string, string>) {
26+
this.originalFocus = document.activeElement as Element;
2527
const dom = this.getDOMElement();
2628
document.body.append(dom);
2729

@@ -31,11 +33,15 @@ export class EditorFormModal extends EditorContainerUiElement {
3133
form.setOnSuccessfulSubmit(this.hide.bind(this));
3234

3335
this.getContext().manager.setModalActive(this.key, this);
36+
form.focusOnFirst();
3437
}
3538

3639
hide() {
3740
this.getContext().manager.setModalInactive(this.key);
3841
this.teardown();
42+
if (this.originalFocus instanceof HTMLElement && this.originalFocus.isConnected) {
43+
this.originalFocus.focus();
44+
}
3945
}
4046

4147
getForm(): EditorForm {
@@ -69,6 +75,12 @@ export class EditorFormModal extends EditorContainerUiElement {
6975
}
7076
});
7177

78+
wrapper.addEventListener('keydown', event => {
79+
if (event.key === 'Escape') {
80+
this.hide();
81+
}
82+
});
83+
7284
return wrapper;
7385
}
7486
}

0 commit comments

Comments
 (0)