| 52 | >; |
| 53 | |
| 54 | export function useGitState(options: UseGitStateOptions): UseGitStateReturn { |
| 55 | const { |
| 56 | repositoryPath, |
| 57 | isActive = true, |
| 58 | participateInWindowFocusRefresh = true, |
| 59 | selector, |
| 60 | refreshOnMount = true, |
| 61 | refreshOnActive = true, |
| 62 | debugSource = 'use_git_state', |
| 63 | cancelPendingRefreshSources = DEFAULT_CANCEL_PENDING_REFRESH_SOURCES, |
| 64 | layers, |
| 65 | } = options; |
| 66 | |
| 67 | const normalizedPath = useMemo( |
| 68 | () => repositoryPath.replace(/\\/g, '/'), |
| 69 | [repositoryPath] |
| 70 | ); |
| 71 | |
| 72 | const [state, setState] = useState<GitState | null>(() => |
| 73 | gitStateManager.getState(normalizedPath) |
| 74 | ); |
| 75 | |
| 76 | const prevActiveRef = useRef(isActive); |
| 77 | const mountedRef = useRef(true); |
| 78 | const selectorRef = useRef(selector); |
| 79 | const layersRef = useRef(layers); |
| 80 | const suppressedMountRefreshRef = useRef(false); |
| 81 | |
| 82 | useEffect(() => { |
| 83 | selectorRef.current = selector; |
| 84 | }, [selector]); |
| 85 | |
| 86 | useEffect(() => { |
| 87 | layersRef.current = layers; |
| 88 | }, [layers]); |
| 89 | |
| 90 | useEffect(() => { |
| 91 | if (!normalizedPath) return; |
| 92 | |
| 93 | mountedRef.current = true; |
| 94 | |
| 95 | const unsubscribe = gitStateManager.subscribe( |
| 96 | normalizedPath, |
| 97 | (newState, _prevState, _changedLayers) => { |
| 98 | if (!mountedRef.current) return; |
| 99 | if (selectorRef.current) { |
| 100 | const selectedValue = selectorRef.current(newState); |
| 101 | setState((prev) => { |
| 102 | const prevSelected = prev ? selectorRef.current!(prev) : null; |
| 103 | if (shallowEqual(selectedValue, prevSelected)) { |
| 104 | return prev; |
| 105 | } |
| 106 | return newState; |
| 107 | }); |
| 108 | } else { |
| 109 | setState(newState); |
| 110 | } |
| 111 | }, |