-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
31 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
import {Dispatch, Middleware, MiddlewareAPI} from "redux"; | ||
import {ACTION_TYPE} from "../services/constants"; | ||
|
||
let lastFocusedStack: Element[] = []; | ||
|
||
// When a modal is closed, this tries to focus the last element that was focused before it opened. If no element exists, | ||
// we try to focus the page title. This is for accessibility, mostly to help when navigating the site with a screen-reader. | ||
export const modalFocusMiddleware: Middleware = (api: MiddlewareAPI) => (next: Dispatch) => action => { | ||
const state = api.getState(); | ||
|
||
switch (action.type) { | ||
case ACTION_TYPE.ACTIVE_MODAL_OPEN: | ||
// Before modal open, record the element that is currently focused | ||
if (document.activeElement) lastFocusedStack.push(document.activeElement); | ||
break; | ||
case ACTION_TYPE.ACTIVE_MODAL_CLOSE: { | ||
const lastFocusedElement = lastFocusedStack.pop() as HTMLElement; | ||
// Before modal close, try to focus the last focused element, otherwise focus the main heading (if it exists) | ||
if (lastFocusedElement && lastFocusedElement.isConnected && typeof lastFocusedElement.focus === "function") { | ||
lastFocusedElement.focus(); | ||
} else { | ||
lastFocusedStack = []; | ||
document.getElementById(state?.mainContentId || "main")?.focus(); | ||
} | ||
} | ||
} | ||
|
||
return next(action); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters