Skip to content

Commit

Permalink
better esc key handling in different scenarios
Browse files Browse the repository at this point in the history
  • Loading branch information
schlawg committed Feb 13, 2025
1 parent c4cf795 commit ab533e4
Showing 1 changed file with 22 additions and 16 deletions.
38 changes: 22 additions & 16 deletions ui/common/src/dialog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,10 @@ class DialogWrapper implements Dialog {
view.parentElement?.style.setProperty('---viewport-height', `${window.innerHeight}px`);
this.dialogEvents.addListener(view, 'click', e => e.stopPropagation());

this.dialogEvents.addListener(dialog, 'cancel', () => !this.returnValue && (this.returnValue = 'cancel'));
this.dialogEvents.addListener(dialog, 'cancel', e => {
if (o.noClickAway && o.noCloseButton && o.class !== 'alert') return e.preventDefault();
if (!this.returnValue) this.returnValue = 'cancel';
});
this.dialogEvents.addListener(dialog, 'close', this.onRemove);
if (!o.noCloseButton)
this.dialogEvents.addListener(
Expand All @@ -276,7 +279,7 @@ class DialogWrapper implements Dialog {
else where.appendChild(app.node);
}
this.updateActions();
this.dialogEvents.addListener(this.dialog, 'keydown', onKeydown);
this.dialogEvents.addListener(this.dialog, 'keydown', this.onKeydown);
}

get open(): boolean {
Expand Down Expand Up @@ -322,6 +325,23 @@ class DialogWrapper implements Dialog {
}
};

private onKeydown = (e: KeyboardEvent) => {
if (e.key === 'Escape' && !(this.o.noCloseButton && this.o.noClickAway)) {
this.close('cancel');
e.preventDefault();
} else if (e.key === 'Tab') {
const $focii = $(focusQuery, e.currentTarget as Element),
first = $as<HTMLElement>($focii.first()),
last = $as<HTMLElement>($focii.last()),
focus = document.activeElement as HTMLElement;
if (focus === last && !e.shiftKey) first.focus();
else if (focus === first && e.shiftKey) last.focus();
else return;
e.preventDefault();
}
e.stopPropagation();
};

private autoFocus() {
const focus =
(this.o.focus ? this.view.querySelector(this.o.focus) : this.view.querySelector('input[autofocus]')) ??
Expand Down Expand Up @@ -365,20 +385,6 @@ function escapeHtmlAddBreaks(s: string) {
return escapeHtml(s).replace(/\n/g, '<br>');
}

function onKeydown(e: KeyboardEvent) {
if (e.key === 'Tab') {
const $focii = $(focusQuery, e.currentTarget as Element),
first = $as<HTMLElement>($focii.first()),
last = $as<HTMLElement>($focii.last()),
focus = document.activeElement as HTMLElement;
if (focus === last && !e.shiftKey) first.focus();
else if (focus === first && e.shiftKey) last.focus();
else return;
e.preventDefault();
}
e.stopPropagation();
}

function onResize() {
// ios safari vh behavior workaround
$('dialog > div.scrollable').css('---viewport-height', `${window.innerHeight}px`);
Expand Down

0 comments on commit ab533e4

Please sign in to comment.