68 lines
1.4 KiB
TypeScript
Raw Normal View History

2024-02-22 12:14:58 +00:00
import { getFileExt } from "~/lib/utils";
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 Spinner from "~/components/ui/spinner";
2024-02-23 23:57:14 +00:00
import { previewStore } from "../stores/web-preview";
2024-02-20 06:52:39 +00:00
type Props = {
id: number;
};
2024-02-23 23:57:14 +00:00
const FileViewer = ({ id }: 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-23 23:57:14 +00:00
const onFileContentChange = () => {
// refresh preview
previewStore.getState().refresh();
};
2024-02-20 06:52:39 +00:00
const updateFileContent = trpc.file.update.useMutation({
onSuccess: () => {
2024-02-23 23:57:14 +00:00
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 (
2024-02-22 19:49:13 +00:00
<CodeEditor
lang={ext}
value={data?.content || ""}
formatOnSave
onChange={(val) => updateFileContent.mutate({ id, content: val })}
/>
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>
);
};
2024-02-21 02:01:35 +07:00
export default FileViewer;