It's time to use CloseWatcher

It shipped since Chrome 120 https://chromestatus.com/feature/4722261258928128
pull/373/head
Lim Chee Aun 2023-12-20 21:02:22 +08:00
rodzic dfe727b702
commit 7b246fc660
3 zmienionych plików z 28 dodań i 1 usunięć

Wyświetl plik

@ -28,6 +28,7 @@ import {
getCurrentInstanceConfiguration,
} from '../utils/store-utils';
import supports from '../utils/supports';
import useCloseWatcher from '../utils/useCloseWatcher';
import useInterval from '../utils/useInterval';
import visibilityIconsMap from '../utils/visibility-icons-map';
@ -416,6 +417,7 @@ function Compose({
};
useEffect(updateCharCount, []);
const supportsCloseWatcher = window.CloseWatcher;
const escDownRef = useRef(false);
useHotkeys(
'esc',
@ -424,6 +426,7 @@ function Compose({
// This won't be true if this event is already handled and not propagated 🤞
},
{
enabled: !supportsCloseWatcher,
enableOnFormTags: true,
},
);
@ -436,6 +439,7 @@ function Compose({
escDownRef.current = false;
},
{
enabled: !supportsCloseWatcher,
enableOnFormTags: true,
// Use keyup because Esc keydown will close the confirm dialog on Safari
keyup: true,
@ -448,6 +452,11 @@ function Compose({
},
},
);
useCloseWatcher(() => {
if (!standalone && confirmClose()) {
onClose();
}
}, [standalone, confirmClose, onClose]);
const prevBackgroundDraft = useRef({});
const draftKey = () => {

Wyświetl plik

@ -4,6 +4,8 @@ import { createPortal } from 'preact/compat';
import { useEffect, useRef } from 'preact/hooks';
import { useHotkeys } from 'react-hotkeys-hook';
import useCloseWatcher from '../utils/useCloseWatcher';
const $modalContainer = document.getElementById('modal-container');
function Modal({ children, onClose, onClick, class: className }) {
@ -20,6 +22,7 @@ function Modal({ children, onClose, onClick, class: className }) {
return () => clearTimeout(timer);
}, []);
const supportsCloseWatcher = window.CloseWatcher;
const escRef = useHotkeys(
'esc',
() => {
@ -28,7 +31,7 @@ function Modal({ children, onClose, onClick, class: className }) {
}, 0);
},
{
enabled: !!onClose,
enabled: !supportsCloseWatcher && !!onClose,
// Using keyup and setTimeout above
// This will run "later" to prevent clash with esc handlers from other components
keydown: false,
@ -36,6 +39,7 @@ function Modal({ children, onClose, onClick, class: className }) {
},
[onClose],
);
useCloseWatcher(onClose, [onClose]);
const Modal = (
<div

Wyświetl plik

@ -0,0 +1,14 @@
import { useEffect } from 'preact/hooks';
function useCloseWatcher(fn, deps = []) {
if (!fn || typeof fn !== 'function') return;
useEffect(() => {
const watcher = new CloseWatcher();
watcher.addEventListener('close', fn);
return () => {
watcher.destroy();
};
}, deps);
}
export default window.CloseWatcher ? useCloseWatcher : () => {};