94 lines · 2.9 KB
"use client";
import { useEffect, useState } from "react";
import { highlight } from "sugar-high";
import { getFileContent } from "~/utils/git";

export type FileViewerProps = {
  path: string;
  gitRef: string;
};

export function FileViewer({ path, gitRef }: FileViewerProps) {
  const [content, setContent] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let active = true;

    setLoading(true);
    setError(null);
    getFileContent({ data: { ref: gitRef, path } })
      .then((nextContent: string) => {
        if (!active) return;
        setContent(nextContent);
      })
      .catch((error: unknown) => {
        if (!active) return;
        setError(error instanceof Error && error.message ? error.message : "Failed to load file");
      })
      .finally(() => {
        if (active) {
          setLoading(false);
        }
      });

    return () => {
      active = false;
    };
  }, [path, gitRef]);