Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useCodeViewFileReveal.ts

42 lines1.3 KB

1import type { CodeViewScrollTarget } from "@pierre/diffs";
2import { useState } from "react";
3​
4interface FileRevealHandle {
5 getInstance(): object | undefined;
6 getItem(id: string): object | undefined;
7 scrollTo(target: CodeViewScrollTarget): void;
8}
9​
10/**
11 * Scrolls a code view to a file. `attach` is the viewer's ref and `flush` its post-render
12 * handler, so a reveal asked before the viewer mounts, or for a file it does not hold yet, is
13 * positioned once it does. A reveal belongs to the diff it was asked of, so detaching the viewer,
14 * such as remounting it for another diff scope, drops it.
15 */
16export function createCodeViewFileReveal() {
17 let viewer: FileRevealHandle | null = null;
18 let pending: string | null = null;
19 const flush = () => {
20 if (pending === null || viewer === null) return;
21 if (!viewer.getInstance() || viewer.getItem(pending) === undefined) return;
22 viewer.scrollTo({ type: "item", id: pending, align: "start" });
23 pending = null;
24 };
25 return {
26 attach(next: FileRevealHandle | null) {
27 if (viewer !== null && next !== viewer) pending = null;
28 viewer = next;
29 flush();
30 },
31 request(fileKey: string) {
32 pending = fileKey;
33 flush();
34 },
35 flush,
36 };
38​
39export function useCodeViewFileReveal() {
40 const [reveal] = useState(createCodeViewFileReveal);
41 return reveal;