"use client"; import { useEffect, useState } from "react"; import { remark } from 'remark'; import html from 'remark-html'; import matter from 'gray-matter'; import "github-markdown-css/github-markdown.css"; import "../styles/custom.css"; // Adjust the path as necessary import { MarkdownRenderer } from "../../components/MarkdownRenderer"; interface FilePreviewProps { fileId: string; fileType: string; // Pass the file type as a prop } export function FilePreview({ fileId, fileType, share }: FilePreviewProps & { share: boolean }) { const [mediaSrc, setMediaSrc] = useState(null); const [error, setError] = useState(null); const [markdownContent, setMarkdownContent] = useState(null); console.log("File Type:", fileType); useEffect(() => { if (!fileId) { setError("File ID is required."); return; } let objectUrl: string | null = null; const fetchMedia = async () => { try { const response = await fetch(`/api/files/serv?id=${encodeURIComponent(fileId)}`); if (!response.ok) { throw new Error("Failed to fetch media"); } const blob = await response.blob(); objectUrl = URL.createObjectURL(blob); setMediaSrc(objectUrl); } catch (err) { console.error(err); setError("Failed to load media."); } }; fetchMedia(); return () => { if (objectUrl) { URL.revokeObjectURL(objectUrl); } }; }, [fileId]); useEffect(() => { if (fileType.startsWith("markdown")) { const fetchMarkdown = async () => { try { const result = await renderMarkdown({ id: fileId }); setMarkdownContent(result.props.postData.contentHtml); } catch (err) { console.error("Failed to fetch markdown content:", err); } }; fetchMarkdown(); } }, [fileId, fileType]); if (error) { return
{error}
; } if (!mediaSrc && !markdownContent) { return
Loading...
; } if (fileType.startsWith("markdown")) { if (share) { return (
{markdownContent ? ( ) : (
Loading markdown...
)}
); } return ( Code file preview ); } if (fileType.startsWith("video")) { return ( ); } if (fileType.startsWith("audio")) { return ( ); } if (fileType.startsWith("image")) { return Media preview; } if (fileType.startsWith("text")) { return ( Text file preview ); } if (fileType.startsWith("archive")) { return ( Archive file preview ); } if (fileType.startsWith("code")) { return ( Code file preview ); } console.log("Unsupported file type:", fileType); return null; } export async function rendererMarkdown(id: string) { const fileContents = await fetch(`/api/files/serv?id=${encodeURIComponent(id)}`) .then((res) => res.text()) .catch((err) => { console.error("Failed to fetch file contents:", err); return null; }); if (!fileContents) { throw new Error("File contents could not be fetched."); } const matterResult = matter(fileContents); const processedContent = await remark() .use(html) .process(matterResult.content); const contentHtml = processedContent.toString(); return { id, contentHtml, ...matterResult.data, }; } export async function renderMarkdown({ id }: { id: string }) { const postData = await rendererMarkdown(id); return { props: { postData, }, }; }