|
| 1 | +import { useState, useRef, useEffect, useCallback, useMemo } from 'react' |
| 2 | +import { useBlocker } from 'react-router-dom' |
| 3 | + |
| 4 | +/** |
| 5 | + * This hook is similar to react-router's useBlocker, but it also handles the case where the app is closing. |
| 6 | + * It returns a boolean indicating if the view is blocked, and two functions to cancel or confirm the blocking. |
| 7 | + */ |
| 8 | +export function useViewBlocker(block: boolean) { |
| 9 | + const [isAppClosing, setIsAppClosing] = useState(false) |
| 10 | + |
| 11 | + const isBlockingRef = useRef(block) |
| 12 | + const isConfirmedRef = useRef(false) |
| 13 | + |
| 14 | + const blocker = useBlocker(block) |
| 15 | + |
| 16 | + useEffect(() => { |
| 17 | + isBlockingRef.current = block |
| 18 | + }, [block]) |
| 19 | + |
| 20 | + // After confirm(), `isConfirmedRef` prevents double submission until the block condition |
| 21 | + // clears (e.g. debugging stopped). Reset so a later blocking session can confirm again. |
| 22 | + useEffect(() => { |
| 23 | + if (!block) { |
| 24 | + isConfirmedRef.current = false |
| 25 | + } |
| 26 | + }, [block]) |
| 27 | + |
| 28 | + useEffect(() => { |
| 29 | + return window.studio.app.onApplicationClose(() => { |
| 30 | + if (isBlockingRef.current) { |
| 31 | + setIsAppClosing(true) |
| 32 | + |
| 33 | + return |
| 34 | + } |
| 35 | + |
| 36 | + window.studio.app.closeApplication() |
| 37 | + }) |
| 38 | + }, []) |
| 39 | + |
| 40 | + const cancel = useCallback(() => { |
| 41 | + setIsAppClosing(false) |
| 42 | + |
| 43 | + blocker.reset?.() |
| 44 | + }, [blocker.reset]) |
| 45 | + |
| 46 | + const confirm = useCallback(() => { |
| 47 | + if (isConfirmedRef.current) { |
| 48 | + return |
| 49 | + } |
| 50 | + |
| 51 | + isConfirmedRef.current = true |
| 52 | + |
| 53 | + if (isAppClosing) { |
| 54 | + window.studio.app.closeApplication() |
| 55 | + |
| 56 | + return |
| 57 | + } |
| 58 | + |
| 59 | + blocker.proceed?.() |
| 60 | + }, [blocker.proceed, isAppClosing]) |
| 61 | + |
| 62 | + const blocked = blocker.state === 'blocked' || isAppClosing |
| 63 | + |
| 64 | + return useMemo(() => { |
| 65 | + return { |
| 66 | + blocked, |
| 67 | + cancel, |
| 68 | + confirm, |
| 69 | + } |
| 70 | + }, [blocked, cancel, confirm]) |
| 71 | +} |
0 commit comments