File size: 3,062 Bytes
67d6774 312ace9 b9515a8 50cf5bb 67d6774 312ace9 67d6774 312ace9 67d6774 312ace9 67d6774 312ace9 67d6774 312ace9 67d6774 312ace9 67d6774 312ace9 67d6774 b9515a8 9f43bd2 312ace9 9f43bd2 50cf5bb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 | import React, { Suspense, useState, useEffect } from "react";
import { Alert, AlertTitle, AlertDescription } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
interface DynamicFileProps {
id: string;
}
const DynamicFileRenderer: React.FC<DynamicFileProps> = ({ id }) => {
const [DynamicComponent, setDynamicComponent] =
useState<React.ComponentType | null>(null);
const [error, setError] = useState(false);
const [loadingText, setLoadingText] = useState("Loading");
useEffect(() => {
let failed = false;
const loadComponent = async (canSetError: boolean) => {
try {
const Component = await import(`@/components/generated/${id}`);
setDynamicComponent(() => Component.default || Component);
setError(false);
} catch (error) {
failed = true;
if (canSetError) {
setDynamicComponent(() => null);
setError(true);
}
}
};
loadComponent(false);
setTimeout(() => {
failed && loadComponent(true);
}, 2000);
}, [id]);
useEffect(() => {
const interval = setInterval(() => {
setLoadingText((prev) => (prev.endsWith("...") ? "Loading" : prev + "."));
}, 500);
return () => clearInterval(interval);
}, []);
if (error) {
return (
<div className="flex flex-col items-center justify-center min-h-screen p-6 bg-background text-foreground">
<div className="max-w-md rounded-lg border p-4 bg-card text-card-foreground border-border">
<Alert variant="destructive">
<AlertTitle className="text-destructive-foreground">
Error Loading Component
</AlertTitle>
<AlertDescription className="text-muted-foreground">
We encountered an issue while loading the component. Please try
the following steps:
<ul className="list-disc list-inside mt-2 text-sm">
<li>Switch between the "Preview" and "Code" tabs.</li>
<li>If the issue persists, refresh the page.</li>
</ul>
</AlertDescription>
</Alert>
<div className="flex justify-center mt-4">
<Button
onClick={() => window.location.reload()}
variant="default"
style={{
backgroundColor: "hsl(var(--primary))",
color: "hsl(var(--primary-foreground))",
}}
>
Refresh Page
</Button>
</div>
</div>
</div>
);
}
if (!DynamicComponent) {
return (
<div className="flex items-center justify-center min-h-screen bg-background text-muted-foreground">
{loadingText}
</div>
);
}
return (
<Suspense
fallback={
<div className="flex items-center justify-center min-h-screen bg-background text-muted-foreground">
{loadingText}
</div>
}
>
<DynamicComponent />
</Suspense>
);
};
export default DynamicFileRenderer;
|