-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
24 lines (20 loc) · 854 Bytes
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import {useRef} from 'react';
const useNonNullRef = <T>() => useRef<T>(null!);
function show(modal: HTMLDialogElement, initialValue = '') {
modal.showModal();
modal.returnValue = initialValue;
}
export function useModal() {
const ref = useNonNullRef<HTMLDialogElement>();
return [ref, {
show: (initialValue = '') => show(ref.current, initialValue),
showAsync: (initialValue = '') => new Promise<string>(resolve => {
const {current} = ref;
show(current, initialValue);
current.addEventListener('close', () => resolve(current.returnValue), {passive: true, once: true});
}),
hide: (value?: string) => ref.current.close(value),
}] as const;
}
export type ModalHandle = ReturnType<typeof useModal>[1];
export const useModalHandle = () => useNonNullRef<ModalHandle>();