mirror of
https://github.com/allankoechke/mantisbase-admin.git
synced 2026-12-01 01:15:36 +00:00
Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 97f1139abb | |||
| 5f5b7260ec | |||
| d213b760e0 | |||
| 783b7818f8 | |||
| 0b1ee7c76f | |||
| 3ef1afecdf | |||
| ba2bbe38eb | |||
| 230b3b8889 | |||
| 6966cd190b |
26
README.md
26
README.md
@@ -4,7 +4,7 @@ A modern, web-based admin dashboard for managing your MantisBase backend. This d
|
||||
|
||||

|
||||
|
||||
## 📋 Table of Contents
|
||||
## Table of Contents
|
||||
|
||||
- [About](#about)
|
||||
- [Getting Started](#getting-started)
|
||||
@@ -14,7 +14,7 @@ A modern, web-based admin dashboard for managing your MantisBase backend. This d
|
||||
- [Features](#features)
|
||||
- [Links](#links)
|
||||
|
||||
## 🎯 About
|
||||
## About
|
||||
|
||||
MantisBase Admin Dashboard is the official administrative interface for [MantisBase](https://github.com/allankoechke/mantisbase), a lightweight Backend-as-a-Service (BaaS) written in C++. This dashboard allows you to:
|
||||
|
||||
@@ -25,7 +25,7 @@ MantisBase Admin Dashboard is the official administrative interface for [MantisB
|
||||
- Configure application settings
|
||||
- And much more!
|
||||
|
||||
## 🚀 Getting Started
|
||||
## Getting Started
|
||||
|
||||
### Prerequisites
|
||||
|
||||
@@ -65,7 +65,7 @@ Before you begin, ensure you have the following installed:
|
||||
|
||||
2. Log in with your admin credentials at `/mb/login`
|
||||
|
||||
## 💻 Development
|
||||
## Development
|
||||
|
||||
### Available Scripts
|
||||
|
||||
@@ -86,9 +86,11 @@ In development mode, the dashboard will:
|
||||
You can customize the development setup using environment variables:
|
||||
|
||||
- `MANTIS_PORT` - Port for the MantisBase API (default: 7070)
|
||||
- `NEXT_PUBLIC_BASE_PATH` - Base path for the application (default: `/mb` in production)
|
||||
- `NEXT_PUBLIC_BASE_PATH` - Base path for the app (default: `/mb` in production, empty in dev). Set to empty string for no prefix; overrides at both build and runtime.
|
||||
- `NEXT_PUBLIC_MANTIS_BASE_URL` - Backend API base URL. When set (e.g. `https://api.example.com`), all API and login requests use this URL instead of same-origin or localhost. Omit trailing slash.
|
||||
- `NEXT_PUBLIC_MB_IS_DEMO_MODE` - Set to `true` or `1` to enable demo mode: prefills login with test credentials and shows a banner that data is cleared every 30 minutes
|
||||
|
||||
## 🏗️ Building for Production
|
||||
## Building for Production
|
||||
|
||||
To build the dashboard for production:
|
||||
|
||||
@@ -133,7 +135,7 @@ This repository includes a special branch called `mb-admins` that is automatical
|
||||
|
||||
This integration ensures that MantisBase always includes the latest stable version of the admin dashboard without requiring manual updates.
|
||||
|
||||
## ✨ Features
|
||||
## Features
|
||||
|
||||
### Entity Management
|
||||
- Create, read, update, and delete database entities
|
||||
@@ -169,18 +171,14 @@ This integration ensures that MantisBase always includes the latest stable versi
|
||||
- **Documentation**: [https://docs.mantisbase.com](https://docs.mantisbase.com)
|
||||
- **This Repository**: [https://github.com/allankoechke/mantisbase-admin](https://github.com/allankoechke/mantisbase-admin)
|
||||
|
||||
## 📝 Notes
|
||||
## Notes
|
||||
|
||||
> **Note**: This project is still in active development. Some features may be incomplete or subject to change.
|
||||
|
||||
## 🤝 Contributing
|
||||
## Contributing
|
||||
|
||||
Contributions are welcome! Please feel free to submit a Pull Request.
|
||||
|
||||
## 📄 License
|
||||
## License
|
||||
|
||||
This project is part of the MantisBase ecosystem. Please refer to the main MantisBase repository for license information.
|
||||
|
||||
---
|
||||
|
||||
**Made with ❤️ for the MantisBase community**
|
||||
|
||||
@@ -33,6 +33,11 @@ interface AddTableDialogProps {
|
||||
onTablesUpdate: (tables: TableMetadata[]) => void
|
||||
tables?: TableMetadata[] // List of existing tables for foreign key entity selection
|
||||
children?: React.ReactNode
|
||||
/** When set, drawer opens in "clone" mode with fields pre-filled from this entity */
|
||||
sourceTable?: TableMetadata | null
|
||||
/** Controlled open state (e.g. for opening from Clone action) */
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
}
|
||||
|
||||
interface Field {
|
||||
@@ -53,13 +58,37 @@ interface Field {
|
||||
foreign_key?: ForeignKeyConfig // Optional foreign key configuration
|
||||
}
|
||||
|
||||
export function AddTableDialog({ apiClient, onTablesUpdate, tables = [], children }: AddTableDialogProps) {
|
||||
function tableFieldToField(tf: TableField): Field {
|
||||
return {
|
||||
id: tf.id,
|
||||
name: tf.name,
|
||||
type: tf.type,
|
||||
primary_key: tf.primary_key,
|
||||
nullable: !tf.required,
|
||||
unique: tf.unique ?? false,
|
||||
system: tf.system ?? false,
|
||||
required: tf.required,
|
||||
constraints: tf.constraints ?? {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: null,
|
||||
},
|
||||
foreign_key: tf.foreign_key,
|
||||
}
|
||||
}
|
||||
|
||||
export function AddTableDialog({ apiClient, onTablesUpdate, tables = [], children, sourceTable, open: controlledOpen, onOpenChange: controlledOnOpenChange }: AddTableDialogProps) {
|
||||
const [internalOpen, setInternalOpen] = React.useState(false)
|
||||
const isControlled = controlledOpen !== undefined && controlledOnOpenChange !== undefined
|
||||
const open = isControlled ? controlledOpen : internalOpen
|
||||
const setOpen = isControlled ? controlledOnOpenChange! : setInternalOpen
|
||||
|
||||
const [tableType, setTableType] = React.useState<"base" | "auth" | "view">("base")
|
||||
const [tableName, setTableName] = React.useState("")
|
||||
const [fields, setFields] = React.useState<Field[]>([])
|
||||
const [sqlQuery, setSqlQuery] = React.useState("")
|
||||
const [isLoading, setIsLoading] = React.useState(false)
|
||||
const [open, setOpen] = React.useState(false)
|
||||
const [draggedIndex, setDraggedIndex] = React.useState<number | null>(null)
|
||||
const [expandedFields, setExpandedFields] = React.useState<Set<string>>(new Set())
|
||||
const { toast } = useToast()
|
||||
@@ -67,17 +96,28 @@ export function AddTableDialog({ apiClient, onTablesUpdate, tables = [], childre
|
||||
// Get unique key for field (use id if exists, otherwise generate one)
|
||||
const getFieldKey = (field: Field, index: number) => field.id || `temp-${index}`
|
||||
|
||||
// When drawer opens, reset and add base fields
|
||||
// When drawer opens: either populate from sourceTable (clone) or reset
|
||||
React.useEffect(() => {
|
||||
if (open) {
|
||||
if (!open) return
|
||||
setExpandedFields(new Set())
|
||||
setIsLoading(false)
|
||||
if (sourceTable?.schema) {
|
||||
const schema = sourceTable.schema
|
||||
setTableName(`${schema.name}_copy`)
|
||||
setTableType(schema.type)
|
||||
setSqlQuery(schema.sql ?? "")
|
||||
setFields((schema.fields ?? []).map(tableFieldToField))
|
||||
} else {
|
||||
setTableName("")
|
||||
setSqlQuery("")
|
||||
setIsLoading(false)
|
||||
setTableType("base")
|
||||
setExpandedFields(new Set())
|
||||
addBaseFields()
|
||||
setFields([
|
||||
{ id: "mbf_14258576900392064537", name: "id", type: "string", primary_key: true, nullable: false, system: true, required: true, unique: false, constraints: { min_value: 6, max_value: null, default_value: null, validator: "@password" } },
|
||||
{ id: "mbf_13735287961322938256", name: "created", type: "date", primary_key: false, nullable: false, system: true, required: true, unique: false, constraints: { min_value: null, max_value: null, default_value: null, validator: null } },
|
||||
{ id: "mbf_9124719522053273721", name: "updated", type: "date", primary_key: false, nullable: false, system: true, required: true, unique: false, constraints: { min_value: null, max_value: null, default_value: null, validator: null } },
|
||||
])
|
||||
}
|
||||
}, [open])
|
||||
}, [open, sourceTable?.id])
|
||||
|
||||
function addBaseFields() {
|
||||
if (tableType === "view") {
|
||||
@@ -192,11 +232,12 @@ export function AddTableDialog({ apiClient, onTablesUpdate, tables = [], childre
|
||||
}
|
||||
}
|
||||
|
||||
// When user changes entity type in the form, reset fields (but not when opening for clone)
|
||||
React.useEffect(() => {
|
||||
if (open) {
|
||||
if (open && !sourceTable) {
|
||||
addBaseFields()
|
||||
}
|
||||
}, [tableType, open])
|
||||
}, [tableType, open, sourceTable?.id])
|
||||
|
||||
const addField = () => {
|
||||
setFields([
|
||||
@@ -448,14 +489,16 @@ export function AddTableDialog({ apiClient, onTablesUpdate, tables = [], childre
|
||||
|
||||
return (
|
||||
<Drawer open={open} onOpenChange={setOpen}>
|
||||
<DrawerTrigger asChild>
|
||||
{children || (
|
||||
<Button size="sm">
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Add Table
|
||||
</Button>
|
||||
)}
|
||||
</DrawerTrigger>
|
||||
{!isControlled && (
|
||||
<DrawerTrigger asChild>
|
||||
{children || (
|
||||
<Button size="sm">
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Add Table
|
||||
</Button>
|
||||
)}
|
||||
</DrawerTrigger>
|
||||
)}
|
||||
<DrawerContent side="right" className="w-full sm:w-[600px]">
|
||||
<DrawerHeader>
|
||||
<DrawerTitle>Create New Entity</DrawerTitle>
|
||||
|
||||
@@ -1,17 +1,40 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Search, Table, RefreshCw, Plus, ExternalLink, FileText, Database } from "lucide-react"
|
||||
import { Search, Table, RefreshCw, Plus, ExternalLink, FileText, Database, MoreHorizontal, Copy, Pencil, Trash2, User, LayoutDashboard } from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent } from "@/components/ui/card"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog"
|
||||
import type { ApiClient, TableMetadata } from "@/lib/api"
|
||||
import { AddTableDialog } from "./add-table-dialog"
|
||||
import { TableDetailView } from "./table-detail-view"
|
||||
import { SidebarTrigger } from "@/components/ui/sidebar"
|
||||
import { TableDocsDrawer } from "./table-docs-drawer"
|
||||
import { useRouter } from "@/lib/router"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
@@ -26,7 +49,7 @@ interface DatabaseSectionProps {
|
||||
export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseSectionProps) {
|
||||
const { route, navigate } = useRouter()
|
||||
const { toast } = useToast()
|
||||
|
||||
|
||||
// Initialize search term from query params
|
||||
const initialFilter = route.queryParams.filter || ""
|
||||
const [searchTerm, setSearchTerm] = React.useState(initialFilter)
|
||||
@@ -35,6 +58,19 @@ export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseS
|
||||
const [isRefreshing, setIsRefreshing] = React.useState(false)
|
||||
const [docsOpen, setDocsOpen] = React.useState(false)
|
||||
|
||||
// Clone: open create-entity drawer with schema pre-filled
|
||||
const [addDrawerOpen, setAddDrawerOpen] = React.useState(false)
|
||||
const [cloneSourceTable, setCloneSourceTable] = React.useState<TableMetadata | null>(null)
|
||||
|
||||
// Rename entity dialog
|
||||
const [renameTable, setRenameTable] = React.useState<TableMetadata | null>(null)
|
||||
const [renameNewName, setRenameNewName] = React.useState("")
|
||||
const [isRenaming, setIsRenaming] = React.useState(false)
|
||||
|
||||
// Delete entity confirmation
|
||||
const [deleteTable, setDeleteTable] = React.useState<TableMetadata | null>(null)
|
||||
const [isDeleting, setIsDeleting] = React.useState(false)
|
||||
|
||||
// Sync search term with query params
|
||||
React.useEffect(() => {
|
||||
const filterFromQuery = route.queryParams.filter || ""
|
||||
@@ -65,41 +101,80 @@ export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseS
|
||||
const filteredTables = Array.isArray(tables) ? tables?.filter((table) => table?.schema?.name?.toLowerCase().includes(searchTerm.toLowerCase())) : []
|
||||
|
||||
const handleDeleteTable = async (tableId: string) => {
|
||||
setIsDeleting(true)
|
||||
try {
|
||||
const res: any = await apiClient.call(`/api/v1/schemas/${tableId}`, { method: "DELETE" })
|
||||
|
||||
// If the request failed, throw the error here
|
||||
if (res?.error?.length > 0) throw res.error
|
||||
|
||||
// Fetch new tables
|
||||
const response: any = await apiClient.call("/api/v1/schemas")
|
||||
|
||||
// If the request failed, throw the error here
|
||||
if (response?.error?.length > 0) throw response.error
|
||||
|
||||
// Handle different response structures
|
||||
let updatedTables: TableMetadata[] = []
|
||||
if (Array.isArray(response)) {
|
||||
updatedTables = response
|
||||
} else if (response?.data && Array.isArray(response.data)) {
|
||||
updatedTables = response.data
|
||||
}
|
||||
|
||||
// Set the new tables
|
||||
onTablesUpdate(updatedTables)
|
||||
|
||||
setDeleteTable(null)
|
||||
toast({
|
||||
title: "Table Deleted",
|
||||
description: "Table deleted successfully!",
|
||||
title: "Entity deleted",
|
||||
description: "The entity has been deleted successfully.",
|
||||
duration: 3000,
|
||||
})
|
||||
} catch (error) {
|
||||
} catch (error: unknown) {
|
||||
console.error("Failed to delete table:", error)
|
||||
// toast({
|
||||
// title: "Error Deleted",
|
||||
// description: "Table deleted successfully!",
|
||||
// duration: 3000,
|
||||
// })
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: error instanceof Error ? error.message : "Failed to delete entity",
|
||||
})
|
||||
} finally {
|
||||
setIsDeleting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleRenameSubmit = async () => {
|
||||
if (!renameTable || !renameNewName.trim()) return
|
||||
const trimmed = renameNewName.trim()
|
||||
if (trimmed === renameTable.schema.name) {
|
||||
setRenameTable(null)
|
||||
setRenameNewName("")
|
||||
return
|
||||
}
|
||||
setIsRenaming(true)
|
||||
try {
|
||||
const res: any = await apiClient.call(`/api/v1/schemas/${renameTable.id}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({ name: trimmed }),
|
||||
})
|
||||
if (res?.error?.length > 0) throw res.error
|
||||
|
||||
const response: any = await apiClient.call("/api/v1/schemas")
|
||||
if (response?.error?.length > 0) throw response.error
|
||||
|
||||
let updatedTables: TableMetadata[] = []
|
||||
if (Array.isArray(response)) {
|
||||
updatedTables = response
|
||||
} else if (response?.data && Array.isArray(response.data)) {
|
||||
updatedTables = response.data
|
||||
}
|
||||
onTablesUpdate(updatedTables)
|
||||
setRenameTable(null)
|
||||
setRenameNewName("")
|
||||
toast({
|
||||
title: "Entity renamed",
|
||||
description: `Renamed to "${trimmed}".`,
|
||||
})
|
||||
} catch (error: unknown) {
|
||||
console.error("Failed to rename entity:", error)
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: error instanceof Error ? error.message : "Failed to rename entity",
|
||||
})
|
||||
} finally {
|
||||
setIsRenaming(false)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -185,32 +260,77 @@ export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseS
|
||||
{searchTerm ? "No entities found matching the search term" : "No entities, add some to get started"}
|
||||
</div>
|
||||
) : (
|
||||
filteredTables.map((table) => (
|
||||
<button
|
||||
filteredTables.map((table) => {
|
||||
const TypeIcon = table.schema.type === "auth" ? User : table.schema.type === "view" ? LayoutDashboard : Database
|
||||
return (
|
||||
<div
|
||||
key={table.id}
|
||||
onClick={() => handleEntityClick(table.schema.name)}
|
||||
className={cn(
|
||||
"w-full text-left p-3 rounded-lg transition-colors hover:bg-accent",
|
||||
"group grid grid-cols-[1fr_auto] items-stretch gap-0 rounded-lg transition-colors pr-2 min-w-0 overflow-hidden",
|
||||
selectedEntityName === table.schema.name && "bg-accent text-accent-foreground"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2 flex-1 min-w-0">
|
||||
<Table className="h-4 w-4 flex-shrink-0" />
|
||||
<span className="font-medium truncate">{table.schema.name}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleEntityClick(table.schema.name)}
|
||||
className={cn(
|
||||
"min-w-0 text-left p-3 rounded-lg transition-colors hover:bg-accent overflow-hidden",
|
||||
selectedEntityName === table.schema.name && "bg-accent text-accent-foreground"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2 min-w-0 overflow-hidden">
|
||||
<TypeIcon className="h-4 w-4 flex-shrink-0 text-muted-foreground" />
|
||||
<span className="font-medium truncate block min-w-0" title={table.schema.name}>
|
||||
{table.schema.name}
|
||||
</span>
|
||||
</div>
|
||||
<Badge
|
||||
variant={table.schema.type === "auth" ? "default" : table.schema.type === "view" ? "secondary" : "outline"}
|
||||
className="text-xs flex-shrink-0 ml-2"
|
||||
>
|
||||
{table.schema.type}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground mt-1">
|
||||
{table.schema.fields?.length || 0} fields
|
||||
</div>
|
||||
</button>
|
||||
))
|
||||
<div className="text-xs text-muted-foreground mt-1 truncate">
|
||||
{table.schema.fields?.length || 0} fields
|
||||
</div>
|
||||
</button>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-auto self-stretch flex-shrink-0 rounded-lg opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100 px-2"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
<span className="sr-only">Entity actions</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" onClick={(e) => e.stopPropagation()}>
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
setCloneSourceTable(table)
|
||||
setAddDrawerOpen(true)
|
||||
}}
|
||||
>
|
||||
<Copy className="h-4 w-4 mr-2" />
|
||||
Clone
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
setRenameTable(table)
|
||||
setRenameNewName(table.schema.name)
|
||||
}}
|
||||
>
|
||||
<Pencil className="h-4 w-4 mr-2" />
|
||||
Rename
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
className="text-destructive focus:text-destructive"
|
||||
onClick={() => setDeleteTable(table)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4 mr-2" />
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
@@ -278,6 +398,73 @@ export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseS
|
||||
|
||||
{/* Entity Schema API Documentation */}
|
||||
<TableDocsDrawer open={docsOpen} onClose={() => setDocsOpen(false)} />
|
||||
|
||||
{/* Clone entity: create drawer with schema pre-filled */}
|
||||
<AddTableDialog
|
||||
apiClient={apiClient}
|
||||
onTablesUpdate={onTablesUpdate}
|
||||
tables={tables}
|
||||
open={addDrawerOpen}
|
||||
onOpenChange={(open) => {
|
||||
setAddDrawerOpen(open)
|
||||
if (!open) setCloneSourceTable(null)
|
||||
}}
|
||||
sourceTable={cloneSourceTable}
|
||||
/>
|
||||
|
||||
{/* Rename entity dialog */}
|
||||
<Dialog open={!!renameTable} onOpenChange={(open) => { if (!open) { setRenameTable(null); setRenameNewName("") } }}>
|
||||
<DialogContent className="sm:max-w-md" onClick={(e) => e.stopPropagation()}>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Rename entity</DialogTitle>
|
||||
<DialogDescription>
|
||||
Enter a new name for the entity. This does not affect existing data.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="grid gap-4 py-4">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="rename-entity-name">New name</Label>
|
||||
<Input
|
||||
id="rename-entity-name"
|
||||
value={renameNewName}
|
||||
onChange={(e) => setRenameNewName(e.target.value)}
|
||||
placeholder="Entity name"
|
||||
onKeyDown={(e) => e.key === "Enter" && handleRenameSubmit()}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => { setRenameTable(null); setRenameNewName("") }}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleRenameSubmit} disabled={!renameNewName.trim() || isRenaming}>
|
||||
{isRenaming ? "Renaming..." : "Rename"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Delete entity confirmation */}
|
||||
<AlertDialog open={!!deleteTable} onOpenChange={(open) => { if (!open) setDeleteTable(null) }}>
|
||||
<AlertDialogContent onClick={(e) => e.stopPropagation()}>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete entity</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Are you sure you want to delete the entity <strong>"{deleteTable?.schema.name}"</strong>? This action cannot be undone and will permanently delete all data associated with this entity.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={isDeleting}>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
disabled={isDeleting}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
onClick={() => deleteTable && handleDeleteTable(deleteTable.id)}
|
||||
>
|
||||
{isDeleting ? "Deleting..." : "Delete"}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -400,8 +400,10 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate, onTab
|
||||
/>
|
||||
</TableCell>
|
||||
{filteredFields.map((field) => (
|
||||
<TableCell key={field.name}>
|
||||
{renderCellContent(field, row[field.name])}
|
||||
<TableCell key={field.name} className="max-w-0">
|
||||
<div className="min-w-0 max-w-full line-clamp-2 break-words overflow-hidden text-ellipsis" title={typeof row[field.name] === "string" ? row[field.name] : undefined}>
|
||||
{renderCellContent(field, row[field.name])}
|
||||
</div>
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
|
||||
@@ -9,6 +9,7 @@ import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle } f
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import type { TableMetadata } from "@/lib/api"
|
||||
import { getApiBaseUrl } from "@/lib/api"
|
||||
|
||||
interface TableDocsDrawerProps {
|
||||
open: boolean
|
||||
@@ -124,7 +125,7 @@ function ApiEndpointCard({
|
||||
}
|
||||
|
||||
const generateRequestExample = () => {
|
||||
const baseUrl = "{{MANTISBASE_BASE_URL}}"
|
||||
const baseUrl = getApiBaseUrl()
|
||||
let example = `curl -X ${method} "${baseUrl}${endpoint}"`
|
||||
|
||||
example += ` \\\n -H "Content-Type: application/json"`
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { FileText, ChevronDown, ChevronRight, X, Copy } from "lucide-react"
|
||||
import { FileText, ChevronDown, ChevronRight, X, Copy, Radio } from "lucide-react"
|
||||
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Button } from "@/components/ui/button"
|
||||
@@ -9,6 +9,7 @@ import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle } f
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import type { TableMetadata } from "@/lib/api"
|
||||
import { getApiBaseUrl } from "@/lib/api"
|
||||
|
||||
interface TableDocsDrawerProps {
|
||||
table: TableMetadata
|
||||
@@ -84,6 +85,8 @@ export function TableRecordDocsDrawer({ table, open, onClose }: TableDocsDrawerP
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<RealtimeDocCard table={table} />
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
@@ -92,6 +95,121 @@ export function TableRecordDocsDrawer({ table, open, onClose }: TableDocsDrawerP
|
||||
)
|
||||
}
|
||||
|
||||
// Realtime (SSE) documentation: connect and update topics for this entity
|
||||
function RealtimeDocCard({ table }: { table: TableMetadata }) {
|
||||
const [isOpen, setIsOpen] = React.useState(false)
|
||||
const entityName = table.schema.name
|
||||
const baseUrl = getApiBaseUrl()
|
||||
const sampleRowId = "019c1b81-364b-7000-8120-b5416b2c42c2"
|
||||
|
||||
const connectExample = `# Connect to SSE: subscribe to this entity (all rows) and/or a specific row
|
||||
# Topics: entity name only, or entity:row_id for a single row
|
||||
curl -N -H "Authorization: Bearer YOUR_TOKEN" \\
|
||||
"${baseUrl}/api/v1/realtime?topics=${entityName}"
|
||||
|
||||
# Subscribe to entity + a specific row (comma-separated)
|
||||
curl -N -H "Authorization: Bearer YOUR_TOKEN" \\
|
||||
"${baseUrl}/api/v1/realtime?topics=${entityName},${entityName}:${sampleRowId}"`
|
||||
|
||||
const updateTopicsExample = `# Update topics for an existing SSE session (from the "connected" event client_id)
|
||||
curl -X POST "${baseUrl}/api/v1/realtime" \\
|
||||
-H "Authorization: Bearer YOUR_TOKEN" \\
|
||||
-H "Content-Type: application/json" \\
|
||||
-d '{
|
||||
"client_id": "sse_1769987962000_0abc1",
|
||||
"topics": ["${entityName}", "${entityName}:${sampleRowId}"]
|
||||
}'
|
||||
|
||||
# Clear topics to disconnect
|
||||
curl -X POST "${baseUrl}/api/v1/realtime" \\
|
||||
-H "Authorization: Bearer YOUR_TOKEN" \\
|
||||
-H "Content-Type: application/json" \\
|
||||
-d '{"client_id": "sse_1769987962000_0abc1", "topics": []}'`
|
||||
|
||||
const copyToClipboard = (text: string) => {
|
||||
navigator.clipboard.writeText(text)
|
||||
}
|
||||
|
||||
return (
|
||||
<Collapsible open={isOpen} onOpenChange={setIsOpen}>
|
||||
<CollapsibleTrigger asChild>
|
||||
<div className="p-4 border rounded-lg cursor-pointer hover:bg-muted/50 transition-colors">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<Radio className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="font-medium">Realtime (SSE)</span>
|
||||
{isOpen ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground mt-2">
|
||||
Subscribe to database changes for this entity (all rows) or a specific row. Connect via GET, then update topics via POST.
|
||||
</p>
|
||||
</div>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent>
|
||||
<div className="border-l-2 border-muted ml-4 pl-6 space-y-6 mt-4">
|
||||
<div>
|
||||
<h5 className="font-medium mb-1">Connect to SSE</h5>
|
||||
<p className="text-sm text-muted-foreground mb-2">
|
||||
Open a long-lived SSE stream. Use <code className="bg-muted px-1 rounded">topics</code> query param: entity name (e.g. <code className="bg-muted px-1 rounded">{entityName}</code>) for all rows, or <code className="bg-muted px-1 rounded">{entityName}:row_id</code> for a single row. Multiple topics are comma-separated.
|
||||
</p>
|
||||
<div className="flex justify-end mb-2">
|
||||
<Button variant="outline" size="sm" onClick={() => copyToClipboard(connectExample)} className="h-8">
|
||||
<Copy className="h-3 w-3 mr-1" />
|
||||
Copy
|
||||
</Button>
|
||||
</div>
|
||||
<ScrollArea className="h-40">
|
||||
<pre className="bg-muted p-4 rounded text-sm border whitespace-pre">
|
||||
<code>{connectExample}</code>
|
||||
</pre>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
<div>
|
||||
<h5 className="font-medium mb-1">Update topics to monitor</h5>
|
||||
<p className="text-sm text-muted-foreground mb-2">
|
||||
POST with <code className="bg-muted px-1 rounded">client_id</code> from the <code className="bg-muted px-1 rounded">connected</code> event and a new <code className="bg-muted px-1 rounded">topics</code> array. Send <code className="bg-muted px-1 rounded">topics: []</code> to disconnect.
|
||||
</p>
|
||||
<div className="flex justify-end mb-2">
|
||||
<Button variant="outline" size="sm" onClick={() => copyToClipboard(updateTopicsExample)} className="h-8">
|
||||
<Copy className="h-3 w-3 mr-1" />
|
||||
Copy
|
||||
</Button>
|
||||
</div>
|
||||
<ScrollArea className="h-48">
|
||||
<pre className="bg-muted p-4 rounded text-sm border whitespace-pre">
|
||||
<code>{updateTopicsExample}</code>
|
||||
</pre>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
<div>
|
||||
<h5 className="font-medium mb-2">SSE event types</h5>
|
||||
<div className="grid grid-cols-1 gap-2 text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="secondary" className="text-xs">connected</Badge>
|
||||
<span>Sent once when the stream opens; includes <code className="bg-muted px-1 rounded">client_id</code> and <code className="bg-muted px-1 rounded">topics</code>.</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="secondary" className="text-xs">ping</Badge>
|
||||
<span>Keep-alive sent periodically.</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="secondary" className="text-xs">change</Badge>
|
||||
<span>Database change: <code className="bg-muted px-1 rounded">action</code> (insert/update/delete), <code className="bg-muted px-1 rounded">entity</code>, <code className="bg-muted px-1 rounded">row_id</code>, <code className="bg-muted px-1 rounded">data</code> (row payload or null for delete).</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
<p>
|
||||
Access uses the same rules as entity <strong>list</strong> (topic = entity name) and <strong>get</strong> (topic = entity:row_id). In browsers, <code className="bg-muted px-1 rounded">EventSource</code> cannot send <code className="bg-muted px-1 rounded">Authorization</code>; use <code className="bg-muted px-1 rounded">fetch()</code> with the same URL and headers, then read the body as a stream to process SSE events.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
)
|
||||
}
|
||||
|
||||
function ApiEndpointCard({
|
||||
method,
|
||||
endpoint,
|
||||
@@ -127,7 +245,7 @@ function ApiEndpointCard({
|
||||
}
|
||||
|
||||
const generateRequestExample = () => {
|
||||
const baseUrl = "https://your-api.com"
|
||||
const baseUrl = getApiBaseUrl()
|
||||
let example = `curl -X ${method} "${baseUrl}${endpoint}"`
|
||||
|
||||
if (method !== "GET") {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Eye, EyeOff } from "lucide-react"
|
||||
import { Eye, EyeOff, Info } from "lucide-react"
|
||||
import { Logo } from "./logo"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
@@ -11,13 +11,24 @@ import { Label } from "@/components/ui/label"
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert"
|
||||
import { loginWithPassword } from "@/lib/api"
|
||||
|
||||
const DEMO_EMAIL = "test@test.com"
|
||||
const DEMO_PASSWORD = "123456789"
|
||||
|
||||
function isDemoMode(): boolean {
|
||||
if (typeof window === "undefined") {
|
||||
return process.env.NEXT_PUBLIC_MB_IS_DEMO_MODE === "true" || process.env.NEXT_PUBLIC_MB_IS_DEMO_MODE === "1"
|
||||
}
|
||||
return process.env.NEXT_PUBLIC_MB_IS_DEMO_MODE === "true" || process.env.NEXT_PUBLIC_MB_IS_DEMO_MODE === "1"
|
||||
}
|
||||
|
||||
interface LoginFormProps {
|
||||
onLogin: (token: string) => void
|
||||
}
|
||||
|
||||
export function LoginForm({ onLogin }: LoginFormProps) {
|
||||
const [email, setEmail] = React.useState("")
|
||||
const [password, setPassword] = React.useState("")
|
||||
const isDemo = isDemoMode()
|
||||
const [email, setEmail] = React.useState(isDemo ? DEMO_EMAIL : "")
|
||||
const [password, setPassword] = React.useState(isDemo ? DEMO_PASSWORD : "")
|
||||
const [showPassword, setShowPassword] = React.useState(false)
|
||||
const [isLoading, setIsLoading] = React.useState(false)
|
||||
const [error, setError] = React.useState("")
|
||||
@@ -39,7 +50,16 @@ export function LoginForm({ onLogin }: LoginFormProps) {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-background">
|
||||
<div className="min-h-screen flex flex-col bg-background">
|
||||
{isDemo && (
|
||||
<Alert className="rounded-none border-x-0 border-t-0 bg-amber-500/10 text-amber-900 dark:bg-amber-500/10 dark:text-amber-200 border-amber-500/30">
|
||||
<Info className="h-4 w-4" />
|
||||
<AlertDescription className="font-medium">
|
||||
This is a demo site. Data is cleared every 30 minutes. Default login: {DEMO_EMAIL} / {DEMO_PASSWORD}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
<div className="flex-1 flex items-center justify-center p-4">
|
||||
<Card className="w-full max-w-md">
|
||||
<CardHeader className="text-center">
|
||||
<div className="flex justify-center mb-4">
|
||||
@@ -98,6 +118,7 @@ export function LoginForm({ onLogin }: LoginFormProps) {
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -57,7 +57,7 @@ export function LogsSection({ apiClient }: LogsSectionProps) {
|
||||
const [totalCount, setTotalCount] = React.useState<number>(-1) // -1 means unknown
|
||||
const [searchTerm, setSearchTerm] = React.useState("")
|
||||
const [levelFilter, setLevelFilter] = React.useState<string>("all") // Exact level filter
|
||||
const [minLevelFilter, setMinLevelFilter] = React.useState<string>("trace") // Minimum level filter (default)
|
||||
const [minLevelFilter, setMinLevelFilter] = React.useState<string>("info") // Minimum level filter (default: info+)
|
||||
const [useMinLevel, setUseMinLevel] = React.useState<boolean>(true) // Use minimum level by default
|
||||
const [selectedLog, setSelectedLog] = React.useState<LogEntry | null>(null)
|
||||
const [drawerOpen, setDrawerOpen] = React.useState(false)
|
||||
|
||||
17
lib/api.ts
17
lib/api.ts
@@ -68,22 +68,25 @@ export interface Admin {
|
||||
updated: string
|
||||
}
|
||||
|
||||
/** Backend API base URL. Override with NEXT_PUBLIC_MANTIS_BASE_URL (e.g. https://api.example.com) to use an external backend. */
|
||||
export function getApiBaseUrl(): string {
|
||||
const override = process.env.NEXT_PUBLIC_MANTIS_BASE_URL
|
||||
if (override !== undefined && override !== "") {
|
||||
return override.replace(/\/+$/, "")
|
||||
}
|
||||
|
||||
const mode = process?.env?.NODE_ENV || "production";
|
||||
const port = process?.env?.MANTIS_PORT || 7070;
|
||||
const mode = process?.env?.NODE_ENV || "production"
|
||||
const port = process?.env?.MANTIS_PORT || 7070
|
||||
|
||||
if (mode === "development") {
|
||||
// For debug mode, or non window sessions, pick port from env
|
||||
return `http://localhost:${port}`;
|
||||
return `http://localhost:${port}`
|
||||
}
|
||||
|
||||
if (typeof window !== "undefined") {
|
||||
const { origin } = window.location;
|
||||
return `${origin}`;
|
||||
return window.location.origin
|
||||
}
|
||||
|
||||
return `http://localhost:${port}`;
|
||||
return `http://localhost:${port}`
|
||||
}
|
||||
|
||||
export interface AppSettings {
|
||||
|
||||
@@ -17,29 +17,31 @@ const ROUTE_CHANGE_EVENT = "custom-route-change"
|
||||
|
||||
let currentRoute: ParsedRoute = { path: "/entities", pathParams: {}, queryParams: {} }
|
||||
|
||||
// Get the base path for the application
|
||||
// In production, this should be '/mb', in development it might be empty
|
||||
// Resolve default base path when env is not set (shared for server and client fallback)
|
||||
function getDefaultBasePath(): string {
|
||||
return process.env.NODE_ENV === "production" ? "/mb" : ""
|
||||
}
|
||||
|
||||
// Get the base path for the application. Env var overrides for both build and runtime; empty string = no base path.
|
||||
export function getBasePath(): string {
|
||||
if (typeof window === "undefined") {
|
||||
// Server-side: use env var or default to /mb for production
|
||||
return process.env.NEXT_PUBLIC_BASE_PATH || (process.env.NODE_ENV === 'production' ? '/mb' : '')
|
||||
return typeof process.env.NEXT_PUBLIC_BASE_PATH !== "undefined"
|
||||
? process.env.NEXT_PUBLIC_BASE_PATH
|
||||
: getDefaultBasePath()
|
||||
}
|
||||
|
||||
// Client-side: try to detect base path from current location
|
||||
// If we're at /mb/* or exactly /mb, the base path is /mb
|
||||
|
||||
// Client-side: env var wins when set (including empty string)
|
||||
if (typeof process.env.NEXT_PUBLIC_BASE_PATH !== "undefined") {
|
||||
return process.env.NEXT_PUBLIC_BASE_PATH
|
||||
}
|
||||
|
||||
// Infer from current location when env not set: if we're under /mb, use /mb
|
||||
const pathname = window.location.pathname
|
||||
if (pathname === "/mb" || pathname.startsWith("/mb/")) {
|
||||
return "/mb"
|
||||
}
|
||||
|
||||
// Fallback: check if we're in production mode
|
||||
// In development, base path might be empty
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
return process.env.NEXT_PUBLIC_BASE_PATH || "/mb"
|
||||
}
|
||||
|
||||
// Development: no base path
|
||||
return process.env.NEXT_PUBLIC_BASE_PATH || ""
|
||||
|
||||
return getDefaultBasePath()
|
||||
}
|
||||
|
||||
// Strip base path from a full pathname
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 179 KiB After Width: | Height: | Size: 511 KiB |
@@ -4,8 +4,12 @@ const { version } = require('./package.json');
|
||||
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
// Use basePath in production, or if explicitly set via env var
|
||||
basePath: process.env.NEXT_PUBLIC_BASE_PATH || (process.env.NODE_ENV === 'production' ? '/mb' : ''),
|
||||
// Env var overrides for both build and runtime: empty string = no base path
|
||||
basePath: typeof process.env.NEXT_PUBLIC_BASE_PATH !== "undefined"
|
||||
? process.env.NEXT_PUBLIC_BASE_PATH
|
||||
: process.env.NODE_ENV === "production"
|
||||
? "/mb"
|
||||
: "",
|
||||
env: {
|
||||
MANTIS_ADMIN_VERSION: version,
|
||||
},
|
||||
|
||||
2
package-lock.json
generated
2
package-lock.json
generated
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "mantisbase-admin",
|
||||
"version": "0.3.6",
|
||||
"version": "0.3.8",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "mantisbase-admin",
|
||||
"version": "0.3.6",
|
||||
"version": "0.3.8",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"export": "next build && next export",
|
||||
|
||||
Reference in New Issue
Block a user