Skip to content

Commit

Permalink
Restore reverted PR to branch
Browse files Browse the repository at this point in the history
  • Loading branch information
Morpheu5 committed Mar 21, 2022
1 parent 7456360 commit 866cd75
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/app/state/modalFocusMiddleware.ts
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);
};
2 changes: 2 additions & 0 deletions src/app/state/store.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@ import * as reduxLogger from "redux-logger";
import {AppState, rootReducer} from "./reducers";
import {userConsistencyCheckerMiddleware} from "./userConsistencyChecker";
import {notificationCheckerMiddleware} from "../services/notificationManager";
import {modalFocusMiddleware} from "./modalFocusMiddleware";

// @ts-ignore
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

export const middleware: Middleware[] = [
userConsistencyCheckerMiddleware,
notificationCheckerMiddleware,
modalFocusMiddleware,
thunk,
];

Expand Down

0 comments on commit 866cd75

Please sign in to comment.