Skip to content

Commit

Permalink
Merge pull request #136 from mansona/dialog-fallback-focus
Browse files Browse the repository at this point in the history
Add Fallback Focus to Dialog
  • Loading branch information
GavinJoyce authored Mar 28, 2022
2 parents e9be945 + 26f17fa commit 0eff9d6
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
2 changes: 2 additions & 0 deletions addon/components/dialog.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@
id={{this.guid}}
role='dialog'
aria-modal='true'
tabindex='-1'
...attributes
{{headlessui-focus-trap
focusTrapOptions=(hash
initialFocus=@initialFocus
allowOutsideClick=this.allowOutsideClick
setReturnFocus=this.setReturnFocus
fallbackFocus=this.dialogElementSelector
)
}}
{{this.handleEscapeKey @isOpen this.onClose}}
Expand Down
4 changes: 4 additions & 0 deletions addon/components/dialog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,10 @@ export default class DialogComponent extends Component<Args> {
return this.args.as || this.DEFAULT_TAG_NAME;
}

get dialogElementSelector() {
return `#${this.guid}`;
}

get overlayGuid() {
return `${this.guid}-overlay`;
}
Expand Down
23 changes: 23 additions & 0 deletions tests/integration/components/dialog-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -904,5 +904,28 @@ module('Integration | Component | <Dialog>', function (hooks) {
assertActiveElement(getByText('focused'));
});
});

test('it should fallback to focus the dialog if there are no focusable elements', async function (assert) {
this.set('isOpen', false);

await render(hbs`
<button id='trigger' type="button" {{on "click" (set this "isOpen" true)}}>
Trigger
</button>
<Dialog
@isOpen={{this.isOpen}}
@onClose={{set this "isOpen" false}}
>
<h2>focused the whole dialog</h2>
</Dialog>
`);

await click('#trigger');

await assert.waitFor(() => {
// focus is on the actual dialog as a fallback
return assertActiveElement(getDialog());
});
});
});
});

0 comments on commit 0eff9d6

Please sign in to comment.