signal-desktop/ts/util/hooks.ts

47 lines
1.2 KiB
TypeScript
Raw Normal View History

2020-10-30 20:34:04 +00:00
// Copyright 2020 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
2020-01-17 22:23:19 +00:00
import * as React from 'react';
import { ActionCreatorsMapObject, bindActionCreators } from 'redux';
import { useDispatch } from 'react-redux';
2020-01-17 22:23:19 +00:00
// Restore focus on teardown
export const useRestoreFocus = (
// The ref for the element to receive initial focus
focusRef: React.RefObject<HTMLElement>,
2020-01-17 22:23:19 +00:00
// Allow for an optional root element that must exist
root: boolean | HTMLElement | null = true
): void => {
2020-01-17 22:23:19 +00:00
React.useEffect(() => {
if (!root) {
return undefined;
2020-01-17 22:23:19 +00:00
}
const lastFocused = document.activeElement as HTMLElement;
2020-01-17 22:23:19 +00:00
if (focusRef.current) {
focusRef.current.focus();
}
return () => {
2020-02-27 02:09:19 +00:00
// This ensures that the focus is returned to
// previous element
setTimeout(() => {
if (lastFocused && lastFocused.focus) {
lastFocused.focus();
}
});
2020-01-17 22:23:19 +00:00
};
}, [focusRef, root]);
};
export const useBoundActions = <T extends ActionCreatorsMapObject>(
actions: T
): T => {
const dispatch = useDispatch();
return React.useMemo(() => {
return bindActionCreators(actions, dispatch);
}, [actions, dispatch]);
};