tahamajs's picture
download
raw
13.3 kB
// src/components/workspace/PanelManager.tsx
import { lazy, Suspense, Component, ReactNode } from "react";
import { WorkspacePanel, PanelContentType } from "@/types/workspace";
import { Loader2, AlertCircle, RefreshCw } from "lucide-react";
// ============================================
// Error Boundary for panel components
// ============================================
interface PanelErrorBoundaryState {
hasError: boolean;
error: Error | null;
retryCount: number;
}
class PanelErrorBoundary extends Component<{ children: ReactNode; panelTitle: string; onRetry?: () => void }, PanelErrorBoundaryState> {
constructor(props: { children: ReactNode; panelTitle: string; onRetry?: () => void }) {
super(props);
this.state = { hasError: false, error: null, retryCount: 0 };
}
static getDerivedStateFromError(error: Error) {
return { hasError: true, error };
}
componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
console.error(`Panel "${this.props.panelTitle}" crashed:`, error, errorInfo);
}
handleRetry = () => {
this.setState({ hasError: false, error: null, retryCount: this.state.retryCount + 1 });
this.props.onRetry?.();
};
render() {
if (this.state.hasError) {
return (
<div className="flex flex-col items-center justify-center h-full text-gray-400 p-8">
<AlertCircle className="w-12 h-12 text-red-500 mb-3" />
<p className="text-sm font-medium text-red-500">Panel Error</p>
<p className="text-xs text-gray-500 mt-1 max-w-xs text-center">
{this.state.error?.message || "Failed to load panel"}
</p>
<button
onClick={this.handleRetry}
className="mt-3 px-3 py-1 text-xs bg-primary/10 text-primary rounded-lg hover:bg-primary/20 transition flex items-center gap-1"
>
<RefreshCw className="w-3 h-3" />
Reload this panel
</button>
</div>
);
}
return this.props.children;
}
}
// ============================================
// Panel placeholder component
// ============================================
function PanelPlaceholder({ title, type, message }: { title: string; type: PanelContentType; message?: string }) {
const icons: Record<PanelContentType, string> = {
"ai-chat": "💬",
"genui-chat": "✨",
"collaborative-editor": "📝",
"molecule-viewer": "⚛️",
"lab-inventory": "🧪",
"gap-analysis": "🔍",
"grant-assistant": "💰",
"research-assistant": "🤖",
"messages": "💬",
"articles": "📄",
"web-browser": "🌐",
"code-editor": "💻",
"terminal": "🖥️",
"notes": "📓",
"pdf-viewer": "📑",
"data-table": "📊",
"workflow": "⚙️",
"tools": "🛍️",
"installed-tools": "🔌",
"tool-builder": "🛠️",
"custom-tool": "🔧",
};
const descriptions: Record<PanelContentType, string> = {
"ai-chat": "Chat with AI about your research",
"genui-chat": "Generate UI components with AI",
"collaborative-editor": "Real-time collaborative editing",
"molecule-viewer": "Interactive 3D molecular structures",
"lab-inventory": "Manage lab equipment and supplies",
"gap-analysis": "Identify research gaps",
"grant-assistant": "Find and manage grants",
"research-assistant": "AI-powered research help",
"messages": "Direct messages and chats",
"articles": "Browse and manage articles",
"web-browser": "Browse the web",
"code-editor": "Edit code with syntax highlighting",
"terminal": "Command line interface",
"notes": "Take notes",
"pdf-viewer": "View PDF documents",
"data-table": "View and edit tabular data",
"workflow": "Build automation workflows",
"tools": "Browse & install helper apps",
"installed-tools": "Use your installed tools",
"tool-builder": "Build and publish custom tools",
"custom-tool": "Run custom HTML/JS scripts in sandbox",
};
return (
<div className="flex flex-col items-center justify-center h-full text-gray-400 p-8">
<div className="w-16 h-16 rounded-full bg-gray-100 dark:bg-gray-700 flex items-center justify-center text-3xl mb-4">
{icons[type] || "📦"}
</div>
<p className="text-sm font-medium text-gray-600 dark:text-gray-400">{title}</p>
<p className="text-xs text-gray-500 mt-1 text-center max-w-xs">
{message || descriptions[type] || "Panel content will appear here"}
</p>
<p className="text-xs text-gray-400 mt-2">This panel is ready to load when the workspace opens it.</p>
</div>
);
}
// ============================================
// Panel loading component
// ============================================
const PanelLoading = () => (
<div className="flex flex-col items-center justify-center h-full">
<Loader2 className="w-6 h-6 animate-spin text-primary mb-2" />
<p className="text-xs text-gray-400">Loading panel...</p>
</div>
);
// ============================================
// Safe lazy import wrapper
// ============================================
const safeLazy = <T extends React.ComponentType<any>>(
importFn: () => Promise<{ default: T }>,
fallback: T,
componentName: string
) => {
return lazy(() =>
importFn()
.then(module => ({ default: module.default }))
.catch(err => {
console.error(`Failed to load ${componentName}:`, err);
return { default: fallback };
})
);
};
// Create fallback placeholders
const createPlaceholder = (title: string, type: PanelContentType) => {
return function Placeholder() {
return <PanelPlaceholder title={title} type={type} />;
};
};
// ============================================
// Lazy-loaded panel components with error handling
// ============================================
const GenerativeChatArea = lazy(() =>
(async () => {
try {
const m: any = await import("@/components/genui/GenerativeChatArea");
return { default: m.GenerativeChatArea || m.default };
} catch {
return { default: createPlaceholder("AI Chat", "ai-chat") };
}
})()
);
const ScientificEditor = lazy(() =>
(async () => {
try {
const m: any = await import("@/pages/ScientificEditor");
return { default: m.ScientificEditor || m.default };
} catch {
return { default: createPlaceholder("Scientific Editor", "collaborative-editor") };
}
})()
);
const MoleculeViewer = lazy(() =>
(async () => {
try {
const m: any = await import("@/components/genui/MoleculeViewer");
return { default: m.MoleculeViewer || m.default };
} catch {
return { default: createPlaceholder("Molecule Viewer", "molecule-viewer") };
}
})()
);
const LabInventoryDashboard = lazy(() =>
(async () => {
try {
const m: any = await import("@/components/lab/LabInventoryDashboard");
return { default: m.LabInventoryDashboard || m.default };
} catch {
return { default: createPlaceholder("Lab Inventory", "lab-inventory") };
}
})()
);
const GapAnalysisDashboard = lazy(() =>
(async () => {
try {
const m: any = await import("@/components/gap-analysis/GapAnalysisDashboard");
return { default: m.GapAnalysisDashboard || m.default };
} catch {
return { default: createPlaceholder("Gap Analysis", "gap-analysis") };
}
})()
);
const GrantAssistantDashboard = lazy(() =>
(async () => {
try {
const m: any = await import("@/components/grant/GrantAssistantDashboard");
return { default: m.GrantAssistantDashboard || m.default };
} catch {
return { default: createPlaceholder("Grant Assistant", "grant-assistant") };
}
})()
);
const RagAssistantPanel = lazy(() =>
(async () => {
try {
const m: any = await import("@/components/rag/RagAssistantPanel");
return { default: m.RagAssistantPanel || m.default };
} catch {
return { default: createPlaceholder("Research Assistant", "research-assistant") };
}
})()
);
const MessagesPage = lazy(() =>
(async () => {
try {
const m: any = await import("@/pages/MessagesPage");
return { default: m.default };
} catch {
return { default: createPlaceholder("Messages", "messages") };
}
})()
);
const ArticlesPage = lazy(() =>
(async () => {
try {
const m: any = await import("@/pages/ArticlesPage");
return { default: m.default };
} catch {
return { default: createPlaceholder("Articles", "articles") };
}
})()
);
const WebBrowserPanel = lazy(() =>
(async () => {
try {
const m: any = await import("./WebBrowserPanel");
return { default: m.WebBrowserPanel || m.default };
} catch {
return { default: createPlaceholder("Web Browser", "web-browser") };
}
})()
);
const CodeEditor = lazy(() =>
(async () => {
try {
const m: any = await import("@/components/editor/CodeEditor");
return { default: m.default };
} catch {
return { default: createPlaceholder("Code Editor", "code-editor") };
}
})()
);
const Terminal = lazy(() =>
(async () => {
try {
const m: any = await import("@/components/terminal/Terminal");
return { default: m.default };
} catch {
return { default: createPlaceholder("Terminal", "terminal") };
}
})()
);
const NotesPanel = lazy(() =>
(async () => {
try {
const m: any = await import("@/components/notes/NotesPanel");
return { default: m.default };
} catch {
return { default: createPlaceholder("Notes", "notes") };
}
})()
);
const PdfViewer = lazy(() =>
(async () => {
try {
const m: any = await import("@/components/pdf/PdfViewer");
return { default: m.default };
} catch {
return { default: createPlaceholder("PDF Viewer", "pdf-viewer") };
}
})()
);
const DataTable = lazy(() =>
(async () => {
try {
const m: any = await import("@/components/data/DataTable");
return { default: m.default };
} catch {
return { default: createPlaceholder("Data Table", "data-table") };
}
})()
);
const WorkflowBuilder = lazy(() =>
import("@/components/workflow/WorkflowBuilder")
.then(m => ({ default: m.default }))
.catch(() => ({ default: createPlaceholder("Workflow Builder", "workflow") }))
);
const ToolsPage = lazy(() =>
import("@/pages/ToolsPage")
.then(m => ({ default: m.default }))
.catch(() => ({ default: createPlaceholder("Tools Store", "tools") }))
);
const InstalledToolsPage = lazy(() =>
import("@/pages/InstalledToolsPage")
.then(m => ({ default: m.default }))
.catch(() => ({ default: createPlaceholder("Installed Tools", "installed-tools") }))
);
const ToolBuilderPage = lazy(() =>
import("@/pages/ToolBuilderPage")
.then(m => ({ default: m.default }))
.catch(() => ({ default: createPlaceholder("Tool Builder", "tool-builder") }))
);
// ============================================
// Panel Components Registry
// ============================================
const PANEL_COMPONENTS: Partial<Record<PanelContentType, React.ComponentType<any>>> = {
"ai-chat": GenerativeChatArea,
"genui-chat": GenerativeChatArea,
"collaborative-editor": ScientificEditor,
"molecule-viewer": MoleculeViewer,
"lab-inventory": LabInventoryDashboard,
"gap-analysis": GapAnalysisDashboard,
"grant-assistant": GrantAssistantDashboard,
"research-assistant": RagAssistantPanel,
"messages": MessagesPage,
"articles": ArticlesPage,
"web-browser": WebBrowserPanel,
"code-editor": CodeEditor,
"terminal": Terminal,
"notes": NotesPanel,
"pdf-viewer": PdfViewer,
"data-table": DataTable,
"workflow": WorkflowBuilder,
"tools": ToolsPage,
"installed-tools": InstalledToolsPage,
"tool-builder": ToolBuilderPage,
};
// ============================================
// Main PanelManager Component
// ============================================
interface PanelManagerProps {
panel: WorkspacePanel;
onRetry?: (panelId: string) => void;
}
export function PanelManager({ panel, onRetry }: PanelManagerProps) {
if (panel.type === "custom-tool") {
const code = panel.props?.code || "<html><body><p>No tool code loaded.</p></body></html>";
return (
<PanelErrorBoundary panelTitle={panel.title} onRetry={() => onRetry?.(panel.id)}>
<div className="w-full h-full bg-white relative">
<iframe
srcDoc={code}
title={panel.title}
className="absolute inset-0 w-full h-full border-none"
sandbox="allow-scripts allow-modals"
/>
</div>
</PanelErrorBoundary>
);
}
const Component = PANEL_COMPONENTS[panel.type];
const props = { ...panel.props, panelId: panel.id };
if (!Component) {
return (
<PanelPlaceholder
title={panel.title}
type={panel.type}
message="This panel is not mounted yet. Open a preset or add another workspace panel to continue."
/>
);
}
return (
<PanelErrorBoundary panelTitle={panel.title} onRetry={() => onRetry?.(panel.id)}>
<Suspense fallback={<PanelLoading />}>
<Component {...props} />
</Suspense>
</PanelErrorBoundary>
);
}

Xet Storage Details

Size:
13.3 kB
·
Xet hash:
17a34810df721252e6286666642ca0f76b1998e27a20f0d281b643e9d784181a

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.