79 lines
1.7 KiB
TypeScript
Raw Normal View History

2024-02-22 12:14:58 +00:00
import { getFileExt } from "~/lib/utils";
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-26 10:48:17 +00:00
import { useProjectContext } from "../context/project";
import { Suspense, lazy } from "react";
const CodeEditor = lazy(() => import("~/components/ui/code-editor"));
2024-02-20 06:52:39 +00:00
type Props = {
id: number;
};
2024-02-23 23:57:14 +00:00
const FileViewer = ({ id }: Props) => {
2024-02-26 10:48:17 +00:00
const { project } = useProjectContext();
2024-02-24 00:27:52 +00:00
const { initialFiles } = useData<Data>();
const initialData = initialFiles.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 (
<Suspense fallback={<LoadingLayout />}>
<CodeEditor
lang={ext}
value={data?.content || ""}
formatOnSave
onChange={(val) =>
updateFileContent.mutate({
projectId: project.id,
id,
content: val,
})
}
/>
</Suspense>
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;