()
| 17 | } |
| 18 | |
| 19 | export function ConfirmationHost() { |
| 20 | const titleId = useId(); |
| 21 | const messageId = useId(); |
| 22 | const [pending, setPending] = useState<PendingConfirmation | null>(null); |
| 23 | const pendingRef = useRef<PendingConfirmation | null>(null); |
| 24 | const queueRef = useRef<PendingConfirmation[]>([]); |
| 25 | const dialogRef = useRef<HTMLDivElement>(null); |
| 26 | const cancelButtonRef = useRef<HTMLButtonElement>(null); |
| 27 | const previousFocusRef = useRef<HTMLElement | null>(null); |
| 28 | |
| 29 | const restoreFocus = useCallback(() => { |
| 30 | const previousFocus = previousFocusRef.current; |
| 31 | previousFocusRef.current = null; |
| 32 | if (previousFocus?.isConnected) { |
| 33 | previousFocus.focus(); |
| 34 | } |
| 35 | }, []); |
| 36 | |
| 37 | const settle = useCallback((confirmed: boolean) => { |
| 38 | const current = pendingRef.current; |
| 39 | if (!current) return; |
| 40 | |
| 41 | current.resolve(confirmed); |
| 42 | const next = queueRef.current.shift() ?? null; |
| 43 | pendingRef.current = next; |
| 44 | setPending(next); |
| 45 | if (!next) { |
| 46 | restoreFocus(); |
| 47 | } |
| 48 | }, [restoreFocus]); |
| 49 | |
| 50 | const showConfirmation = useCallback((request: ConfirmationRequest) => ( |
| 51 | new Promise<boolean>((resolve) => { |
| 52 | const next = { request, resolve }; |
| 53 | if (pendingRef.current) { |
| 54 | queueRef.current.push(next); |
| 55 | return; |
| 56 | } |
| 57 | |
| 58 | pendingRef.current = next; |
| 59 | setPending(next); |
| 60 | }) |
| 61 | ), []); |
| 62 | |
| 63 | useEffect(() => { |
| 64 | registerConfirmationHandler(showConfirmation); |
| 65 | |
| 66 | return () => { |
| 67 | registerConfirmationHandler(null); |
| 68 | pendingRef.current?.resolve(false); |
| 69 | for (const queued of queueRef.current) { |
| 70 | queued.resolve(false); |
| 71 | } |
| 72 | pendingRef.current = null; |
| 73 | queueRef.current = []; |
| 74 | restoreFocus(); |
| 75 | }; |
| 76 | }, [showConfirmation, restoreFocus]); |
nothing calls this directly
no test coverage detected