78 lines
1.8 KiB
TypeScript
Raw Normal View History

2024-02-20 06:52:39 +00:00
"use client";
2024-02-22 12:14:58 +00:00
import { getFileExt } from "~/lib/utils";
2024-02-20 06:52:39 +00:00
import React from "react";
2024-02-20 18:03:43 +07:00
import CodeEditor from "../../../../components/ui/code-editor";
2024-02-22 12:14:58 +00:00
import trpc from "~/lib/trpc";
import { useData } from "~/renderer/hooks";
import { Data } from "../+data";
import ClientOnly from "~/renderer/client-only";
import Spinner from "~/components/ui/spinner";
2024-02-20 06:52:39 +00:00
type Props = {
id: number;
2024-02-20 18:03:43 +07:00
onFileContentChange?: () => void;
2024-02-20 06:52:39 +00:00
};
2024-02-21 02:01:35 +07:00
const FileViewer = ({ id, onFileContentChange }: Props) => {
const { pinnedFiles } = useData<Data>();
const initialData = pinnedFiles.find((i) => i.id === id);
const { data, isLoading, refetch } = trpc.file.getById.useQuery(id, {
initialData,
});
2024-02-20 06:52:39 +00:00
const updateFileContent = trpc.file.update.useMutation({
onSuccess: () => {
2024-02-20 18:03:43 +07:00
if (onFileContentChange) onFileContentChange();
2024-02-20 06:52:39 +00:00
refetch();
},
});
if (isLoading) {
return <LoadingLayout />;
2024-02-20 06:52:39 +00:00
}
2024-02-21 02:01:35 +07:00
if (!data || data.isDirectory) {
2024-02-20 06:52:39 +00:00
return <p>File not found.</p>;
}
const { filename } = data;
2024-02-21 02:01:35 +07:00
if (!data.isFile) {
2024-02-20 06:52:39 +00:00
const ext = getFileExt(filename);
return (
<ClientOnly fallback={<SSRCodeEditor value={data?.content} />}>
<CodeEditor
lang={ext}
value={data?.content || ""}
formatOnSave
onChange={(val) => updateFileContent.mutate({ id, content: val })}
/>
</ClientOnly>
2024-02-20 06:52:39 +00:00
);
}
return null;
};
const LoadingLayout = () => {
return (
<div className="w-full h-full flex items-center justify-center">
<Spinner />
</div>
);
};
const SSRCodeEditor = ({ value }: { value?: string | null }) => {
return (
<textarea
className="w-full h-full py-3 pl-11 pr-2 overflow-x-auto text-nowrap font-mono text-sm md:text-[16px] md:leading-[22px] bg-[#1a1b26] text-[#787c99]"
value={value || ""}
readOnly
/>
);
};
2024-02-21 02:01:35 +07:00
export default FileViewer;