Open History to see the last commit
1import type { CodeViewScrollTarget } from "@pierre/diffs";
2import { useCallback, useEffect, useRef, useState } from "react";
3
4interface FileRevealHandle {
5 getInstance(): object | undefined;
6 scrollTo(target: CodeViewScrollTarget): void;
7}
8
9export function useCodeViewFileReveal<TScope>(
10 viewer: FileRevealHandle | null,
11 scope: TScope,
12 readyFileKeys?: ReadonlyArray<string>,
13) {
14 const [request, setRequest] = useState<{ fileKey: string; scope: TScope } | null>(null);
15 const handledRequest = useRef<typeof request>(null);
16
17 useEffect(() => {
18 if (request === null || handledRequest.current === request) return;
19 if (request.scope !== scope) {
20 handledRequest.current = request;
21 return;
22 }
23 if (!viewer?.getInstance() || (readyFileKeys && !readyFileKeys.includes(request.fileKey)))
24 return;
25
26 viewer.scrollTo({ type: "item", id: request.fileKey, align: "start" });
27 handledRequest.current = request;
28 }, [request, scope, viewer, readyFileKeys]);
29
30 return useCallback((fileKey: string) => setRequest({ fileKey, scope }), [scope]);
31}