Skip to content

Commit

Permalink
✨ set return focus on focusable clicked element
Browse files Browse the repository at this point in the history
  • Loading branch information
far-fetched committed Nov 1, 2021
1 parent 39abdee commit 0550e59
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
11 changes: 7 additions & 4 deletions addon/components/dialog.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,26 @@
aria-modal='true'
...attributes
{{headlessui-focus-trap
focusTrapOptions=(hash initialFocus=@initialFocus)
focusTrapOptions=(hash
initialFocus=@initialFocus
allowOutsideClick=this.allowOutsideClick
setReturnFocus=this.setReturnFocus
)
}}
{{click-outside this.onClose event='mouseup'}}
{{this.handleEscapeKey @isOpen this.onClose}}
{{did-insert (fn this.dialogStackProvider.push this)}}
{{will-destroy (fn this.dialogStackProvider.remove this)}}
>
{{yield
(hash
isOpen=@isOpen
onClose=@onClose
onClose=this.onClose
Overlay=(component
'dialog/-overlay'
guid=this.overlayGuid
dialogGuid=this.guid
isOpen=@isOpen
onClose=@onClose
onClose=this.onClose
)
Title=(component
'dialog/-title'
Expand Down
16 changes: 16 additions & 0 deletions addon/components/dialog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export default class DialogComponent extends Component<Args> {

guid = `${guidFor(this)}-headlessui-dialog`;
$portalRoot = getPortalRoot();
outsideClickedElement: HTMLElement | null = null;

handleEscapeKey = modifier(
(_element, [isOpen, onClose]: [boolean, () => void]) => {
Expand Down Expand Up @@ -103,6 +104,21 @@ export default class DialogComponent extends Component<Args> {
return `${this.guid}-description`;
}

@action
setReturnFocus(trigger: HTMLElement) {
return this.outsideClickedElement ? this.outsideClickedElement : trigger;
}

@action
allowOutsideClick(e: MouseEvent) {
let target = e.target as HTMLElement;
if (target && target.tagName !== 'BODY') {
this.outsideClickedElement = target;
}
this.onClose();
return true
}

@action
onClose() {
if (this.dialogStackProvider.hasOpenChild(this)) return;
Expand Down

0 comments on commit 0550e59

Please sign in to comment.