Skip to content

Commit

Permalink
Prevent scrolling when activating ActionMenu items via space (#2326)
Browse files Browse the repository at this point in the history
  • Loading branch information
camertron authored Oct 23, 2023
1 parent cc44952 commit 4e05b7e
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/dry-cameras-attend.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@primer/view-components': patch
---

Prevent scrolling when activating ActionMenu items via space
2 changes: 2 additions & 0 deletions app/components/primer/alpha/action_bar_element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ class ActionBarElement extends HTMLElement {

#isVisible(element: HTMLElement): boolean {
// Safari doesn't support `checkVisibility` yet.
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
if (typeof element.checkVisibility === 'function') return element.checkVisibility()

return Boolean(element.offsetParent || element.offsetWidth || element.offsetHeight)
Expand Down
25 changes: 24 additions & 1 deletion app/components/primer/alpha/action_menu/action_menu_element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,11 +134,24 @@ export class ActionMenuElement extends HTMLElement {
}

#isKeyboardActivation(event: Event): boolean {
return this.#isKeyboardActivationViaEnter(event) || this.#isKeyboardActivationViaSpace(event)
}

#isKeyboardActivationViaEnter(event: Event): boolean {
return (
event instanceof KeyboardEvent &&
event.type === 'keydown' &&
!(event.ctrlKey || event.altKey || event.metaKey || event.shiftKey) &&
event.key === 'Enter'
)
}

#isKeyboardActivationViaSpace(event: Event): boolean {
return (
event instanceof KeyboardEvent &&
event.type === 'keydown' &&
!(event.ctrlKey || event.altKey || event.metaKey || event.shiftKey) &&
(event.key === 'Enter' || event.key === ' ')
event.key === ' '
)
}

Expand Down Expand Up @@ -202,6 +215,16 @@ export class ActionMenuElement extends HTMLElement {

this.#activateItem(event, item)
this.#handleItemActivated(event, item)

// Pressing the space key on a button will cause the page to scroll unless preventDefault()
// is called. Unfortunately, calling preventDefault() will also skip form submission. The
// code below therefore only calls preventDefault() if the button submits a form and the
// button is being activated by the space key.
if (item.getAttribute('type') === 'submit' && this.#isKeyboardActivationViaSpace(event)) {
event.preventDefault()
item.closest('form')?.submit()
}

return
}

Expand Down

0 comments on commit 4e05b7e

Please sign in to comment.