6 Commits

13 changed files with 371 additions and 109 deletions

View File

@@ -4,7 +4,7 @@ A modern, web-based admin dashboard for managing your MantisBase backend. This d
![MantisBase Admin Dashboard](mantisbase-admin.png)
## 📋 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**

View File

@@ -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>

View File

@@ -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>
)
}

View File

@@ -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>

View File

@@ -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"`

View File

@@ -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
@@ -98,7 +99,7 @@ export function TableRecordDocsDrawer({ table, open, onClose }: TableDocsDrawerP
function RealtimeDocCard({ table }: { table: TableMetadata }) {
const [isOpen, setIsOpen] = React.useState(false)
const entityName = table.schema.name
const baseUrl = "https://your-api.com"
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
@@ -244,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") {

View File

@@ -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>
)
}

View File

@@ -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 {

View File

@@ -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

View File

@@ -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
View File

@@ -1,6 +1,6 @@
{
"name": "mantisbase-admin",
"version": "0.3.6",
"version": "0.3.8",
"lockfileVersion": 3,
"requires": true,
"packages": {

View File

@@ -1,6 +1,6 @@
{
"name": "mantisbase-admin",
"version": "0.3.7",
"version": "0.3.8",
"private": true,
"scripts": {
"export": "next build && next export",