signal-desktop/ts/hooks/useEscapeHandling.ts

27 lines
604 B
TypeScript
Raw Normal View History

2021-09-17 22:24:21 +00:00
// Copyright 2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
import { useEffect } from 'react';
export function useEscapeHandling(handleEscape?: () => unknown): void {
useEffect(() => {
if (!handleEscape) {
return;
}
const handler = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
handleEscape();
event.preventDefault();
event.stopPropagation();
}
};
2023-03-23 22:35:15 +00:00
document.addEventListener('keydown', handler);
2021-09-17 22:24:21 +00:00
return () => {
2023-03-23 22:35:15 +00:00
document.removeEventListener('keydown', handler);
2021-09-17 22:24:21 +00:00
};
}, [handleEscape]);
}