mirror of
https://github.com/allankoechke/mantisbase-admin.git
synced 2026-11-29 09:16:42 +00:00
feat: implement routing, fix theme toggle, enhance error handling
Add hash-based routing, fix theme toggle, improve error handling, and add requested features #VERCEL_SKIP Co-authored-by: Allan K. Koech <44490960+allankoechke@users.noreply.github.com>
This commit is contained in:
28
app/page.tsx
28
app/page.tsx
@@ -5,25 +5,47 @@ import { LoginForm } from "@/components/login-form"
|
||||
import { AdminDashboard } from "@/components/admin-dashboard"
|
||||
import { Toaster } from "@/components/ui/toaster"
|
||||
import { ThemeProvider } from "@/components/theme-provider"
|
||||
import { useRouter } from "@/lib/router"
|
||||
|
||||
export default function Page() {
|
||||
const [token, setToken] = React.useState<string | null>(null)
|
||||
const [mounted, setMounted] = React.useState(false)
|
||||
const { route, navigate } = useRouter()
|
||||
|
||||
React.useEffect(() => {
|
||||
setMounted(true)
|
||||
const savedToken = localStorage.getItem("admin_token")
|
||||
if (savedToken) {
|
||||
setToken(savedToken)
|
||||
// If we have a token but we're on login route, redirect to tables
|
||||
if (route.path === "/login") {
|
||||
navigate("/tables")
|
||||
}
|
||||
} else {
|
||||
// No token, redirect to login
|
||||
navigate("/login")
|
||||
}
|
||||
}, [])
|
||||
|
||||
React.useEffect(() => {
|
||||
if (mounted) {
|
||||
if (!token && route.path !== "/login") {
|
||||
navigate("/login")
|
||||
} else if (token && route.path === "/login") {
|
||||
navigate("/tables")
|
||||
}
|
||||
}
|
||||
}, [token, route.path, mounted, navigate])
|
||||
|
||||
const handleLogin = (newToken: string) => {
|
||||
setToken(newToken)
|
||||
navigate("/tables")
|
||||
}
|
||||
|
||||
const handleLogout = () => {
|
||||
setToken(null)
|
||||
localStorage.removeItem("admin_token")
|
||||
navigate("/login")
|
||||
}
|
||||
|
||||
if (!mounted) {
|
||||
@@ -39,7 +61,11 @@ export default function Page() {
|
||||
|
||||
return (
|
||||
<ThemeProvider attribute="class" defaultTheme="system" enableSystem disableTransitionOnChange>
|
||||
{!token ? <LoginForm onLogin={handleLogin} /> : <AdminDashboard token={token} onLogout={handleLogout} />}
|
||||
{route.path === "/login" || !token ? (
|
||||
<LoginForm onLogin={handleLogin} />
|
||||
) : (
|
||||
<AdminDashboard token={token} onLogout={handleLogout} />
|
||||
)}
|
||||
<Toaster />
|
||||
</ThemeProvider>
|
||||
)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Table, Settings, Shield, LogOut, FileText, RefreshCw, ExternalLink } from "lucide-react"
|
||||
import { Table, Settings, Shield, LogOut, FileText, RefreshCw, ExternalLink, AlertTriangle } from "lucide-react"
|
||||
import {
|
||||
Sidebar,
|
||||
SidebarContent,
|
||||
@@ -15,6 +15,15 @@ import {
|
||||
SidebarMenuItem,
|
||||
SidebarProvider,
|
||||
} from "@/components/ui/sidebar"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import { ApiClient, type TableMetadata, type Admin, type AppSettings } from "@/lib/api"
|
||||
import { DatabaseSection } from "./database/database-section"
|
||||
import { AdminsSection } from "./admins/admins-section"
|
||||
@@ -23,6 +32,7 @@ import { LogsSection } from "./logs/logs-section"
|
||||
import { SyncSection } from "./sync/sync-section"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
import { ThemeToggle } from "./theme-toggle"
|
||||
import { useRouter } from "@/lib/router"
|
||||
|
||||
interface AdminDashboardProps {
|
||||
token: string
|
||||
@@ -31,15 +41,21 @@ interface AdminDashboardProps {
|
||||
|
||||
export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
const [mounted, setMounted] = React.useState(false)
|
||||
const [activeSection, setActiveSection] = React.useState("tables")
|
||||
const [tables, setTables] = React.useState<TableMetadata[]>([])
|
||||
const [admins, setAdmins] = React.useState<Admin[]>([])
|
||||
const [loading, setLoading] = React.useState(true)
|
||||
const { toast } = useToast()
|
||||
const [settings, setSettings] = React.useState<AppSettings | null>(null)
|
||||
const [authErrorDialog, setAuthErrorDialog] = React.useState(false)
|
||||
const { toast } = useToast()
|
||||
const { route, navigate } = useRouter()
|
||||
|
||||
const showError = React.useCallback(
|
||||
(error: string, type: "error" | "warning" = "error") => {
|
||||
// Prevent error loops by checking if error is already being shown
|
||||
if (error.includes("Unauthorized") || error.includes("auth")) {
|
||||
return // Don't show toast for auth errors, handle with dialog
|
||||
}
|
||||
|
||||
toast({
|
||||
variant: type === "error" ? "destructive" : "default",
|
||||
title: type === "error" ? "Error" : "Warning",
|
||||
@@ -49,7 +65,14 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
[toast],
|
||||
)
|
||||
|
||||
const apiClient = React.useMemo(() => new ApiClient(token, onLogout, showError), [token, onLogout, showError])
|
||||
const handleUnauthorized = React.useCallback(() => {
|
||||
setAuthErrorDialog(true)
|
||||
}, [])
|
||||
|
||||
const apiClient = React.useMemo(
|
||||
() => new ApiClient(token, handleUnauthorized, showError),
|
||||
[token, handleUnauthorized, showError],
|
||||
)
|
||||
|
||||
React.useEffect(() => {
|
||||
setMounted(true)
|
||||
@@ -80,34 +103,46 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
onLogout()
|
||||
}
|
||||
|
||||
const handleAuthErrorLogin = () => {
|
||||
setAuthErrorDialog(false)
|
||||
handleLogout()
|
||||
}
|
||||
|
||||
const sidebarItems = [
|
||||
{
|
||||
title: "Tables",
|
||||
icon: Table,
|
||||
id: "tables",
|
||||
path: "/tables",
|
||||
},
|
||||
{
|
||||
title: "Admins",
|
||||
icon: Shield,
|
||||
id: "admins",
|
||||
path: "/admins",
|
||||
},
|
||||
{
|
||||
title: "Logs",
|
||||
icon: FileText,
|
||||
id: "logs",
|
||||
path: "/logs",
|
||||
},
|
||||
{
|
||||
title: "Sync",
|
||||
icon: RefreshCw,
|
||||
id: "sync",
|
||||
path: "/sync",
|
||||
},
|
||||
{
|
||||
title: "Settings",
|
||||
icon: Settings,
|
||||
id: "settings",
|
||||
path: "/settings",
|
||||
},
|
||||
]
|
||||
|
||||
const currentSection = route.path.split("/")[1] || "tables"
|
||||
|
||||
if (!mounted) {
|
||||
return (
|
||||
<div className="flex min-h-screen w-full items-center justify-center">
|
||||
@@ -137,9 +172,9 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
{sidebarItems.map((item) => (
|
||||
<SidebarMenuItem key={item.id}>
|
||||
<SidebarMenuButton
|
||||
onClick={() => setActiveSection(item.id)}
|
||||
isActive={activeSection === item.id}
|
||||
className={activeSection === item.id ? "bg-accent text-accent-foreground" : ""}
|
||||
onClick={() => navigate(item.path)}
|
||||
isActive={currentSection === item.id}
|
||||
className={currentSection === item.id ? "bg-accent text-accent-foreground" : ""}
|
||||
>
|
||||
<item.icon className="h-4 w-4" />
|
||||
<span>{item.title}</span>
|
||||
@@ -189,15 +224,15 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{activeSection === "tables" && (
|
||||
{currentSection === "tables" && (
|
||||
<DatabaseSection apiClient={apiClient} tables={tables} onTablesUpdate={setTables} />
|
||||
)}
|
||||
{activeSection === "admins" && (
|
||||
{currentSection === "admins" && (
|
||||
<AdminsSection admins={admins} apiClient={apiClient} onAdminsUpdate={setAdmins} />
|
||||
)}
|
||||
{activeSection === "logs" && <LogsSection />}
|
||||
{activeSection === "sync" && <SyncSection />}
|
||||
{activeSection === "settings" && (
|
||||
{currentSection === "logs" && <LogsSection />}
|
||||
{currentSection === "sync" && <SyncSection />}
|
||||
{currentSection === "settings" && (
|
||||
<SettingsSection apiClient={apiClient} settings={settings} onSettingsUpdate={setSettings} />
|
||||
)}
|
||||
</>
|
||||
@@ -205,6 +240,28 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Auth Error Dialog */}
|
||||
<Dialog open={authErrorDialog} onOpenChange={setAuthErrorDialog}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<AlertTriangle className="h-5 w-5 text-destructive" />
|
||||
Authentication Error
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Your session has expired or you don't have permission to access this resource. Please log in again to
|
||||
continue.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setAuthErrorDialog(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleAuthErrorLogin}>Login Again</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</SidebarProvider>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -23,9 +23,10 @@ import type { ApiClient, TableMetadata } from "@/lib/api"
|
||||
interface AddTableDialogProps {
|
||||
apiClient: ApiClient
|
||||
onTablesUpdate: (tables: TableMetadata[]) => void
|
||||
children?: React.ReactNode
|
||||
}
|
||||
|
||||
export function AddTableDialog({ apiClient, onTablesUpdate }: AddTableDialogProps) {
|
||||
export function AddTableDialog({ apiClient, onTablesUpdate, children }: AddTableDialogProps) {
|
||||
const [tableType, setTableType] = React.useState<"base" | "auth" | "view">("base")
|
||||
const [tableName, setTableName] = React.useState("")
|
||||
const [columns, setColumns] = React.useState<
|
||||
@@ -144,10 +145,12 @@ export function AddTableDialog({ apiClient, onTablesUpdate }: AddTableDialogProp
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Add Table
|
||||
</Button>
|
||||
{children || (
|
||||
<Button>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Add Table
|
||||
</Button>
|
||||
)}
|
||||
</DialogTrigger>
|
||||
<DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Search, Table, Eye, Edit, Trash2, MoreHorizontal } from "lucide-react"
|
||||
import { Search, Table, Eye, Edit, Trash2, MoreHorizontal, RefreshCw, Plus, ExternalLink } from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
@@ -13,6 +13,7 @@ import { AddTableDialog } from "./add-table-dialog"
|
||||
import { TableDetailView } from "./table-detail-view"
|
||||
import { EditSchemaDialog } from "./edit-schema-dialog"
|
||||
import { SidebarTrigger } from "@/components/ui/sidebar"
|
||||
import { useRouter } from "@/lib/router"
|
||||
|
||||
interface DatabaseSectionProps {
|
||||
apiClient: ApiClient
|
||||
@@ -21,11 +22,13 @@ interface DatabaseSectionProps {
|
||||
}
|
||||
|
||||
export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseSectionProps) {
|
||||
const [selectedTable, setSelectedTable] = React.useState<string | null>(null)
|
||||
const [searchTerm, setSearchTerm] = React.useState("")
|
||||
const [editingTable, setEditingTable] = React.useState<TableMetadata | null>(null)
|
||||
const [searchExpanded, setSearchExpanded] = React.useState(false)
|
||||
const [isRefreshing, setIsRefreshing] = React.useState(false)
|
||||
const { route, navigate } = useRouter()
|
||||
|
||||
const selectedTableName = route.path.startsWith("/tables/") ? route.path.split("/")[2] : null
|
||||
const filteredTables = tables.filter((table) => table.name.toLowerCase().includes(searchTerm.toLowerCase()))
|
||||
|
||||
const handleDeleteTable = async (tableId: string) => {
|
||||
@@ -39,16 +42,28 @@ export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseS
|
||||
}
|
||||
|
||||
const handleTableClick = (tableName: string) => {
|
||||
setSelectedTable(tableName)
|
||||
navigate(`/tables/${tableName}`)
|
||||
}
|
||||
|
||||
if (selectedTable) {
|
||||
const tableInfo = tables.find((t) => t.name === selectedTable)
|
||||
const handleRefresh = async () => {
|
||||
setIsRefreshing(true)
|
||||
try {
|
||||
const updatedTables = await apiClient.call<TableMetadata[]>("/api/v1/tables")
|
||||
onTablesUpdate(updatedTables)
|
||||
} catch (error) {
|
||||
console.error("Failed to refresh tables:", error)
|
||||
} finally {
|
||||
setIsRefreshing(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (selectedTableName) {
|
||||
const tableInfo = tables.find((t) => t.name === selectedTableName)
|
||||
if (tableInfo) {
|
||||
return (
|
||||
<TableDetailView
|
||||
table={tableInfo}
|
||||
onBack={() => setSelectedTable(null)}
|
||||
onBack={() => navigate("/tables")}
|
||||
apiClient={apiClient}
|
||||
onTableUpdate={(updatedTable) => {
|
||||
const updatedTables = tables.map((t) => (t.id === updatedTable.id ? updatedTable : t))
|
||||
@@ -82,88 +97,117 @@ export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseS
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="ml-auto">
|
||||
<div className="ml-auto flex gap-2">
|
||||
<Button variant="outline" size="sm" onClick={handleRefresh} disabled={isRefreshing}>
|
||||
<RefreshCw className={`h-4 w-4 ${isRefreshing ? "animate-spin" : ""}`} />
|
||||
</Button>
|
||||
<AddTableDialog apiClient={apiClient} onTablesUpdate={onTablesUpdate} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
|
||||
{filteredTables.map((table) => (
|
||||
<Card
|
||||
key={table.id}
|
||||
className="cursor-pointer hover:shadow-md transition-shadow"
|
||||
onClick={() => handleTableClick(table.name)}
|
||||
>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">
|
||||
<div className="flex items-center gap-2">
|
||||
<Table className="h-4 w-4" />
|
||||
{table.name}
|
||||
<Badge
|
||||
variant={table.type === "auth" ? "default" : table.type === "view" ? "secondary" : "outline"}
|
||||
className="text-xs"
|
||||
>
|
||||
{table.type}
|
||||
</Badge>
|
||||
{tables.length === 0 && !isRefreshing ? (
|
||||
<Card>
|
||||
<CardContent className="flex flex-col items-center justify-center py-16">
|
||||
<Table className="h-12 w-12 text-muted-foreground mb-4" />
|
||||
<h3 className="text-lg font-semibold mb-2">No Tables Found</h3>
|
||||
<p className="text-muted-foreground text-center mb-6 max-w-md">
|
||||
Get started by creating your first table. Tables are used to store and organize your data.
|
||||
</p>
|
||||
<div className="flex gap-3">
|
||||
<AddTableDialog apiClient={apiClient} onTablesUpdate={onTablesUpdate}>
|
||||
<Button>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Create Table
|
||||
</Button>
|
||||
</AddTableDialog>
|
||||
<Button variant="outline" asChild>
|
||||
<a href="https://docs.example.com/tables" target="_blank" rel="noopener noreferrer">
|
||||
<ExternalLink className="h-4 w-4 mr-2" />
|
||||
View Documentation
|
||||
</a>
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
|
||||
{filteredTables.map((table) => (
|
||||
<Card
|
||||
key={table.id}
|
||||
className="cursor-pointer hover:shadow-md transition-shadow"
|
||||
onClick={() => handleTableClick(table.name)}
|
||||
>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">
|
||||
<div className="flex items-center gap-2">
|
||||
<Table className="h-4 w-4" />
|
||||
{table.name}
|
||||
<Badge
|
||||
variant={table.type === "auth" ? "default" : table.type === "view" ? "secondary" : "outline"}
|
||||
className="text-xs"
|
||||
>
|
||||
{table.type}
|
||||
</Badge>
|
||||
</div>
|
||||
</CardTitle>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild onClick={(e) => e.stopPropagation()}>
|
||||
<Button variant="ghost" size="sm">
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
handleTableClick(table.name)
|
||||
}}
|
||||
>
|
||||
<Eye className="h-4 w-4 mr-2" />
|
||||
View Details
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
setEditingTable(table)
|
||||
}}
|
||||
>
|
||||
<Edit className="h-4 w-4 mr-2" />
|
||||
Edit Schema
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
className="text-destructive"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
handleDeleteTable(table.id)
|
||||
}}
|
||||
>
|
||||
<Trash2 className="h-4 w-4 mr-2" />
|
||||
Delete Table
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Type:</span>
|
||||
<span className="font-medium capitalize">{table.type}</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Fields:</span>
|
||||
<span className="font-medium">{table.fields?.length || 0}</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Created:</span>
|
||||
<span className="font-medium">{new Date(table.created).toLocaleDateString()}</span>
|
||||
</div>
|
||||
</div>
|
||||
</CardTitle>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild onClick={(e) => e.stopPropagation()}>
|
||||
<Button variant="ghost" size="sm">
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
setSelectedTable(table.name)
|
||||
}}
|
||||
>
|
||||
<Eye className="h-4 w-4 mr-2" />
|
||||
View Details
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
setEditingTable(table)
|
||||
}}
|
||||
>
|
||||
<Edit className="h-4 w-4 mr-2" />
|
||||
Edit Schema
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
className="text-destructive"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
handleDeleteTable(table.id)
|
||||
}}
|
||||
>
|
||||
<Trash2 className="h-4 w-4 mr-2" />
|
||||
Delete Table
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Type:</span>
|
||||
<span className="font-medium capitalize">{table.type}</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Fields:</span>
|
||||
<span className="font-medium">{table.fields?.length || 0}</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Created:</span>
|
||||
<span className="font-medium">{new Date(table.created).toLocaleDateString()}</span>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{editingTable && (
|
||||
<EditSchemaDialog
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { RefreshCw, Cog, FileText, Trash2, Search } from "lucide-react"
|
||||
import { RefreshCw, Cog, FileText, Trash2, Search, Plus, ExternalLink } from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
@@ -166,8 +166,7 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate }: Tab
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" size="sm" onClick={handleReload} disabled={isLoading}>
|
||||
<RefreshCw className={`h-4 w-4 mr-2 ${isLoading ? "animate-spin" : ""}`} />
|
||||
Reload
|
||||
<RefreshCw className={`h-4 w-4 ${isLoading ? "animate-spin" : ""}`} />
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={() => setConfigOpen(true)}>
|
||||
<Cog className="h-4 w-4 mr-2" />
|
||||
@@ -238,54 +237,76 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate }: Tab
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-12">
|
||||
<Checkbox
|
||||
checked={selectedItems.length === tableData.length && tableData.length > 0}
|
||||
onCheckedChange={handleSelectAll}
|
||||
aria-label="Select all"
|
||||
/>
|
||||
</TableHead>
|
||||
{filteredFields.map((field) => (
|
||||
<TableHead key={field.name} className="capitalize">
|
||||
{field.name}
|
||||
</TableHead>
|
||||
))}
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{tableData.length > 0 ? (
|
||||
tableData.map((row, index) => (
|
||||
<TableRow
|
||||
key={index}
|
||||
className="cursor-pointer hover:bg-muted/50"
|
||||
onClick={(e) => handleRowClick(row, e)}
|
||||
>
|
||||
<TableCell onClick={(e) => e.stopPropagation()}>
|
||||
<Checkbox
|
||||
checked={selectedItems.includes(row.id)}
|
||||
onCheckedChange={(checked) => handleSelectItem(row.id, checked as boolean)}
|
||||
aria-label={`Select row ${index + 1}`}
|
||||
/>
|
||||
</TableCell>
|
||||
{filteredFields.map((field) => (
|
||||
<TableCell key={field.name}>{row[field.name] || "-"}</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
))
|
||||
) : (
|
||||
{tableData.length === 0 && !isLoading ? (
|
||||
<div className="flex flex-col items-center justify-center py-16">
|
||||
<FileText className="h-12 w-12 text-muted-foreground mb-4" />
|
||||
<h3 className="text-lg font-semibold mb-2">No Records Found</h3>
|
||||
<p className="text-muted-foreground text-center mb-6 max-w-md">
|
||||
This table doesn't have any records yet. Add some data to get started.
|
||||
</p>
|
||||
<div className="flex gap-3">
|
||||
<Button>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Add Record
|
||||
</Button>
|
||||
<Button variant="outline" asChild>
|
||||
<a href="https://docs.example.com/records" target="_blank" rel="noopener noreferrer">
|
||||
<ExternalLink className="h-4 w-4 mr-2" />
|
||||
View Documentation
|
||||
</a>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableCell colSpan={filteredFields.length + 1} className="text-center text-muted-foreground">
|
||||
{isLoading ? "Loading..." : "No data available"}
|
||||
</TableCell>
|
||||
<TableHead className="w-12">
|
||||
<Checkbox
|
||||
checked={selectedItems.length === tableData.length && tableData.length > 0}
|
||||
onCheckedChange={handleSelectAll}
|
||||
aria-label="Select all"
|
||||
/>
|
||||
</TableHead>
|
||||
{filteredFields.map((field) => (
|
||||
<TableHead key={field.name} className="capitalize">
|
||||
{field.name}
|
||||
</TableHead>
|
||||
))}
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{tableData.length > 0 ? (
|
||||
tableData.map((row, index) => (
|
||||
<TableRow
|
||||
key={index}
|
||||
className="cursor-pointer hover:bg-muted/50"
|
||||
onClick={(e) => handleRowClick(row, e)}
|
||||
>
|
||||
<TableCell onClick={(e) => e.stopPropagation()}>
|
||||
<Checkbox
|
||||
checked={selectedItems.includes(row.id)}
|
||||
onCheckedChange={(checked) => handleSelectItem(row.id, checked as boolean)}
|
||||
aria-label={`Select row ${index + 1}`}
|
||||
/>
|
||||
</TableCell>
|
||||
{filteredFields.map((field) => (
|
||||
<TableCell key={field.name}>{row[field.name] || "-"}</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
))
|
||||
) : (
|
||||
<TableRow>
|
||||
<TableCell colSpan={filteredFields.length + 1} className="text-center text-muted-foreground">
|
||||
{isLoading ? "Loading..." : "No data available"}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{totalPages > 1 && (
|
||||
<div className="flex items-center justify-between mt-4">
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { RefreshCw } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Input } from "@/components/ui/input"
|
||||
@@ -19,6 +20,7 @@ export function SettingsSection({ apiClient, settings, onSettingsUpdate }: Setti
|
||||
const [formData, setFormData] = React.useState<AppSettings | null>(null)
|
||||
const [isLoading, setIsLoading] = React.useState(false)
|
||||
const [hasChanges, setHasChanges] = React.useState(false)
|
||||
const [isRefreshing, setIsRefreshing] = React.useState(false)
|
||||
|
||||
React.useEffect(() => {
|
||||
if (settings) {
|
||||
@@ -55,6 +57,18 @@ export function SettingsSection({ apiClient, settings, onSettingsUpdate }: Setti
|
||||
}
|
||||
}
|
||||
|
||||
const handleRefresh = async () => {
|
||||
setIsRefreshing(true)
|
||||
try {
|
||||
const updatedSettings = await apiClient.call<AppSettings>("/api/v1/settings")
|
||||
onSettingsUpdate(updatedSettings)
|
||||
} catch (error) {
|
||||
console.error("Failed to refresh settings:", error)
|
||||
} finally {
|
||||
setIsRefreshing(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (!formData) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-64">
|
||||
@@ -68,12 +82,17 @@ export function SettingsSection({ apiClient, settings, onSettingsUpdate }: Setti
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<SidebarTrigger />
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold">Application Settings</h2>
|
||||
<p className="text-muted-foreground">Configure global application settings</p>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-4">
|
||||
<SidebarTrigger />
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold">Application Settings</h2>
|
||||
<p className="text-muted-foreground">Configure global application settings</p>
|
||||
</div>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" onClick={handleRefresh} disabled={isRefreshing}>
|
||||
<RefreshCw className={`h-4 w-4 ${isRefreshing ? "animate-spin" : ""}`} />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
|
||||
@@ -6,7 +6,7 @@ import { useTheme } from "next-themes"
|
||||
import { SidebarMenuButton } from "@/components/ui/sidebar"
|
||||
|
||||
export function ThemeToggle() {
|
||||
const { theme, setTheme } = useTheme()
|
||||
const { theme, setTheme, resolvedTheme } = useTheme()
|
||||
const [mounted, setMounted] = React.useState(false)
|
||||
|
||||
React.useEffect(() => {
|
||||
@@ -22,10 +22,14 @@ export function ThemeToggle() {
|
||||
)
|
||||
}
|
||||
|
||||
const toggleTheme = () => {
|
||||
setTheme(resolvedTheme === "dark" ? "light" : "dark")
|
||||
}
|
||||
|
||||
return (
|
||||
<SidebarMenuButton onClick={() => setTheme(theme === "dark" ? "light" : "dark")}>
|
||||
{theme === "dark" ? <Sun className="h-4 w-4" /> : <Moon className="h-4 w-4" />}
|
||||
<span>{theme === "dark" ? "Light Mode" : "Dark Mode"}</span>
|
||||
<SidebarMenuButton onClick={toggleTheme}>
|
||||
{resolvedTheme === "dark" ? <Sun className="h-4 w-4" /> : <Moon className="h-4 w-4" />}
|
||||
<span>{resolvedTheme === "dark" ? "Light Mode" : "Dark Mode"}</span>
|
||||
</SidebarMenuButton>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -4,9 +4,8 @@ import * as React from "react"
|
||||
|
||||
import type { ToastActionElement, ToastProps } from "@/components/ui/toast"
|
||||
|
||||
const TOAST_LIMIT = 1
|
||||
// Update the TOAST_REMOVE_DELAY to show toasts longer
|
||||
const TOAST_REMOVE_DELAY = 5000
|
||||
const TOAST_LIMIT = 5 // Allow multiple toasts
|
||||
const TOAST_REMOVE_DELAY = 300000 // 5 minutes
|
||||
|
||||
type ToasterToast = ToastProps & {
|
||||
id: string
|
||||
|
||||
64
lib/api.ts
64
lib/api.ts
@@ -137,6 +137,8 @@ export class ApiClient {
|
||||
private token: string
|
||||
private onUnauthorized: () => void
|
||||
private onError?: (error: string, type?: "error" | "warning") => void
|
||||
private requestCount = 0
|
||||
private maxRequests = 100
|
||||
|
||||
constructor(
|
||||
token: string,
|
||||
@@ -149,21 +151,32 @@ export class ApiClient {
|
||||
}
|
||||
|
||||
private async mockApiCall<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
|
||||
// Prevent infinite loops
|
||||
this.requestCount++
|
||||
if (this.requestCount > this.maxRequests) {
|
||||
throw new Error("Too many API requests - possible infinite loop detected")
|
||||
}
|
||||
|
||||
// Reset counter after a delay
|
||||
setTimeout(() => {
|
||||
this.requestCount = Math.max(0, this.requestCount - 1)
|
||||
}, 1000)
|
||||
|
||||
// Simulate network delay
|
||||
await delay(300 + Math.random() * 200)
|
||||
|
||||
// Simulate occasional errors for testing
|
||||
if (Math.random() < 0.05) {
|
||||
// Simulate occasional errors for testing (reduced frequency)
|
||||
if (Math.random() < 0.02) {
|
||||
const error = "Network error occurred"
|
||||
this.onError?.(error, "error")
|
||||
throw new Error(error)
|
||||
}
|
||||
|
||||
// Simulate 401 for invalid tokens (uncomment to test)
|
||||
// if (Math.random() < 0.1) {
|
||||
// this.onUnauthorized()
|
||||
// throw new Error('Unauthorized')
|
||||
// }
|
||||
if (Math.random() < 0.01) {
|
||||
const error = new Error("Unauthorized - Session expired")
|
||||
;(error as any).status = 401
|
||||
throw error
|
||||
}
|
||||
|
||||
const method = options.method || "GET"
|
||||
const url = new URL(endpoint, "http://localhost")
|
||||
@@ -260,32 +273,21 @@ export class ApiClient {
|
||||
|
||||
async call<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
|
||||
try {
|
||||
// In production, this would be a real fetch call:
|
||||
// const response = await fetch(endpoint, {
|
||||
// ...options,
|
||||
// headers: {
|
||||
// ...options.headers,
|
||||
// Authorization: `Bearer ${this.token}`,
|
||||
// 'Content-Type': 'application/json',
|
||||
// },
|
||||
// })
|
||||
//
|
||||
// if (response.status === 401) {
|
||||
// this.onUnauthorized()
|
||||
// throw new Error('Unauthorized')
|
||||
// }
|
||||
//
|
||||
// if (!response.ok) {
|
||||
// throw new Error(`API call failed: ${response.statusText}`)
|
||||
// }
|
||||
//
|
||||
// return response.json()
|
||||
|
||||
// For now, use mock API
|
||||
return this.mockApiCall<T>(endpoint, options)
|
||||
return await this.mockApiCall<T>(endpoint, options)
|
||||
} catch (error: any) {
|
||||
console.error("API call failed:", error)
|
||||
this.onError?.(error.message, "error")
|
||||
|
||||
// Handle auth errors specifically
|
||||
if (error.status === 401 || error.status === 403 || error.message.includes("Unauthorized")) {
|
||||
this.onUnauthorized()
|
||||
throw error
|
||||
}
|
||||
|
||||
// Only call onError for non-auth errors to prevent loops
|
||||
if (this.onError && !error.message.includes("Unauthorized")) {
|
||||
this.onError(error.message, "error")
|
||||
}
|
||||
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
78
lib/router.ts
Normal file
78
lib/router.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
|
||||
export interface RouteParams {
|
||||
[key: string]: string
|
||||
}
|
||||
|
||||
export interface ParsedRoute {
|
||||
path: string
|
||||
params: RouteParams
|
||||
}
|
||||
|
||||
export function parseRoute(hash: string): ParsedRoute {
|
||||
// Remove the # if present
|
||||
const cleanHash = hash.startsWith("#") ? hash.slice(1) : hash
|
||||
|
||||
// Split path and query string
|
||||
const [pathPart, queryPart] = cleanHash.split("?")
|
||||
|
||||
// Parse query parameters
|
||||
const params: RouteParams = {}
|
||||
if (queryPart) {
|
||||
const searchParams = new URLSearchParams(queryPart)
|
||||
for (const [key, value] of searchParams.entries()) {
|
||||
params[key] = value
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
path: pathPart || "/tables",
|
||||
params,
|
||||
}
|
||||
}
|
||||
|
||||
export function buildRoute(path: string, params?: RouteParams): string {
|
||||
let route = `#${path}`
|
||||
|
||||
if (params && Object.keys(params).length > 0) {
|
||||
const searchParams = new URLSearchParams()
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
if (value) {
|
||||
searchParams.set(key, value)
|
||||
}
|
||||
}
|
||||
const queryString = searchParams.toString()
|
||||
if (queryString) {
|
||||
route += `?${queryString}`
|
||||
}
|
||||
}
|
||||
|
||||
return route
|
||||
}
|
||||
|
||||
export function useRouter() {
|
||||
const [route, setRoute] = React.useState<ParsedRoute>(() => {
|
||||
if (typeof window !== "undefined") {
|
||||
return parseRoute(window.location.hash)
|
||||
}
|
||||
return { path: "/tables", params: {} }
|
||||
})
|
||||
|
||||
React.useEffect(() => {
|
||||
const handleHashChange = () => {
|
||||
setRoute(parseRoute(window.location.hash))
|
||||
}
|
||||
|
||||
window.addEventListener("hashchange", handleHashChange)
|
||||
return () => window.removeEventListener("hashchange", handleHashChange)
|
||||
}, [])
|
||||
|
||||
const navigate = React.useCallback((path: string, params?: RouteParams) => {
|
||||
const newRoute = buildRoute(path, params)
|
||||
window.location.hash = newRoute
|
||||
}, [])
|
||||
|
||||
return { route, navigate }
|
||||
}
|
||||
Reference in New Issue
Block a user