Start Magent beta overhaul
This commit is contained in:
@@ -0,0 +1,517 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { authFetch, clearToken, getApiBase, getToken } from '../lib/auth'
|
||||
|
||||
type DiagnosticCatalogItem = {
|
||||
key: string
|
||||
label: string
|
||||
category: string
|
||||
description: string
|
||||
live_safe: boolean
|
||||
target: string | null
|
||||
configured: boolean
|
||||
config_status: string
|
||||
config_detail: string
|
||||
}
|
||||
|
||||
type DiagnosticResult = {
|
||||
key: string
|
||||
label: string
|
||||
category: string
|
||||
description: string
|
||||
target: string | null
|
||||
live_safe: boolean
|
||||
configured: boolean
|
||||
status: string
|
||||
message: string
|
||||
detail?: unknown
|
||||
checked_at?: string
|
||||
duration_ms?: number
|
||||
}
|
||||
|
||||
type DiagnosticsResponse = {
|
||||
checks: DiagnosticCatalogItem[]
|
||||
categories: string[]
|
||||
generated_at: string
|
||||
}
|
||||
|
||||
type RunDiagnosticsResponse = {
|
||||
results: DiagnosticResult[]
|
||||
summary: {
|
||||
total: number
|
||||
up: number
|
||||
down: number
|
||||
degraded: number
|
||||
not_configured: number
|
||||
disabled: number
|
||||
}
|
||||
checked_at: string
|
||||
}
|
||||
|
||||
type RunMode = 'safe' | 'all' | 'single'
|
||||
|
||||
type AdminDiagnosticsPanelProps = {
|
||||
embedded?: boolean
|
||||
}
|
||||
|
||||
type DatabaseDiagnosticDetail = {
|
||||
integrity_check?: string
|
||||
database_path?: string
|
||||
database_size_bytes?: number
|
||||
wal_size_bytes?: number
|
||||
shm_size_bytes?: number
|
||||
page_size_bytes?: number
|
||||
page_count?: number
|
||||
freelist_pages?: number
|
||||
allocated_bytes?: number
|
||||
free_bytes?: number
|
||||
row_counts?: Record<string, number>
|
||||
timings_ms?: Record<string, number>
|
||||
}
|
||||
|
||||
const REFRESH_INTERVAL_MS = 30000
|
||||
|
||||
const STATUS_LABELS: Record<string, string> = {
|
||||
idle: 'Ready',
|
||||
up: 'Up',
|
||||
down: 'Down',
|
||||
degraded: 'Degraded',
|
||||
disabled: 'Disabled',
|
||||
not_configured: 'Not configured',
|
||||
}
|
||||
|
||||
function formatCheckedAt(value?: string) {
|
||||
if (!value) return 'Not yet run'
|
||||
const parsed = new Date(value)
|
||||
if (Number.isNaN(parsed.getTime())) return value
|
||||
return parsed.toLocaleString()
|
||||
}
|
||||
|
||||
function formatDuration(value?: number) {
|
||||
if (typeof value !== 'number' || Number.isNaN(value) || value <= 0) {
|
||||
return 'Pending'
|
||||
}
|
||||
return `${value.toFixed(1)} ms`
|
||||
}
|
||||
|
||||
function statusLabel(status: string) {
|
||||
return STATUS_LABELS[status] ?? status
|
||||
}
|
||||
|
||||
function formatBytes(value?: number) {
|
||||
if (typeof value !== 'number' || Number.isNaN(value) || value < 0) {
|
||||
return '0 B'
|
||||
}
|
||||
if (value >= 1024 * 1024 * 1024) {
|
||||
return `${(value / (1024 * 1024 * 1024)).toFixed(2)} GB`
|
||||
}
|
||||
if (value >= 1024 * 1024) {
|
||||
return `${(value / (1024 * 1024)).toFixed(2)} MB`
|
||||
}
|
||||
if (value >= 1024) {
|
||||
return `${(value / 1024).toFixed(1)} KB`
|
||||
}
|
||||
return `${value} B`
|
||||
}
|
||||
|
||||
function formatDetailLabel(value: string) {
|
||||
return value
|
||||
.replace(/_/g, ' ')
|
||||
.replace(/\b\w/g, (character) => character.toUpperCase())
|
||||
}
|
||||
|
||||
function asDatabaseDiagnosticDetail(detail: unknown): DatabaseDiagnosticDetail | null {
|
||||
if (!detail || typeof detail !== 'object' || Array.isArray(detail)) {
|
||||
return null
|
||||
}
|
||||
return detail as DatabaseDiagnosticDetail
|
||||
}
|
||||
|
||||
function renderDatabaseMetricGroup(title: string, values: Array<[string, string]>) {
|
||||
if (values.length === 0) {
|
||||
return null
|
||||
}
|
||||
return (
|
||||
<div className="diagnostic-detail-group">
|
||||
<h4>{title}</h4>
|
||||
<div className="diagnostic-detail-grid">
|
||||
{values.map(([label, value]) => (
|
||||
<div key={`${title}-${label}`} className="diagnostic-detail-item">
|
||||
<span>{label}</span>
|
||||
<strong>{value}</strong>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function AdminDiagnosticsPanel({ embedded = false }: AdminDiagnosticsPanelProps) {
|
||||
const router = useRouter()
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [authorized, setAuthorized] = useState(false)
|
||||
const [checks, setChecks] = useState<DiagnosticCatalogItem[]>([])
|
||||
const [resultsByKey, setResultsByKey] = useState<Record<string, DiagnosticResult>>({})
|
||||
const [runningKeys, setRunningKeys] = useState<string[]>([])
|
||||
const [autoRefresh, setAutoRefresh] = useState(true)
|
||||
const [pageError, setPageError] = useState('')
|
||||
const [lastRunAt, setLastRunAt] = useState<string | null>(null)
|
||||
const [lastRunMode, setLastRunMode] = useState<RunMode | null>(null)
|
||||
const [emailRecipient, setEmailRecipient] = useState('')
|
||||
|
||||
const liveSafeKeys = checks.filter((check) => check.live_safe).map((check) => check.key)
|
||||
|
||||
async function runDiagnostics(keys?: string[], mode: RunMode = 'single') {
|
||||
const baseUrl = getApiBase()
|
||||
const effectiveKeys = keys && keys.length > 0 ? keys : checks.map((check) => check.key)
|
||||
if (effectiveKeys.length === 0) {
|
||||
return
|
||||
}
|
||||
setRunningKeys((current) => Array.from(new Set([...current, ...effectiveKeys])))
|
||||
setPageError('')
|
||||
try {
|
||||
const response = await authFetch(`${baseUrl}/admin/diagnostics/run`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
keys: effectiveKeys,
|
||||
...(emailRecipient.trim() ? { recipient_email: emailRecipient.trim() } : {}),
|
||||
}),
|
||||
})
|
||||
if (response.status === 401) {
|
||||
clearToken()
|
||||
router.push('/login')
|
||||
return
|
||||
}
|
||||
if (!response.ok) {
|
||||
const text = await response.text()
|
||||
throw new Error(text || `Diagnostics run failed: ${response.status}`)
|
||||
}
|
||||
const data = (await response.json()) as { status: string } & RunDiagnosticsResponse
|
||||
const nextResults: Record<string, DiagnosticResult> = {}
|
||||
for (const result of data.results ?? []) {
|
||||
nextResults[result.key] = result
|
||||
}
|
||||
setResultsByKey((current) => ({ ...current, ...nextResults }))
|
||||
setLastRunAt(data.checked_at ?? new Date().toISOString())
|
||||
setLastRunMode(mode)
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
setPageError(error instanceof Error ? error.message : 'Diagnostics run failed.')
|
||||
} finally {
|
||||
setRunningKeys((current) => current.filter((key) => !effectiveKeys.includes(key)))
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
|
||||
const loadPage = async () => {
|
||||
if (!getToken()) {
|
||||
router.push('/login')
|
||||
return
|
||||
}
|
||||
try {
|
||||
const baseUrl = getApiBase()
|
||||
const authResponse = await authFetch(`${baseUrl}/auth/me`)
|
||||
if (!authResponse.ok) {
|
||||
if (authResponse.status === 401) {
|
||||
clearToken()
|
||||
router.push('/login')
|
||||
return
|
||||
}
|
||||
router.push('/')
|
||||
return
|
||||
}
|
||||
const me = await authResponse.json()
|
||||
if (!active) return
|
||||
if (me?.role !== 'admin') {
|
||||
router.push('/')
|
||||
return
|
||||
}
|
||||
|
||||
const diagnosticsResponse = await authFetch(`${baseUrl}/admin/diagnostics`)
|
||||
if (!diagnosticsResponse.ok) {
|
||||
const text = await diagnosticsResponse.text()
|
||||
throw new Error(text || `Diagnostics load failed: ${diagnosticsResponse.status}`)
|
||||
}
|
||||
const data = (await diagnosticsResponse.json()) as { status: string } & DiagnosticsResponse
|
||||
if (!active) return
|
||||
setChecks(data.checks ?? [])
|
||||
setAuthorized(true)
|
||||
setLoading(false)
|
||||
const safeKeys = (data.checks ?? []).filter((check) => check.live_safe).map((check) => check.key)
|
||||
if (safeKeys.length > 0) {
|
||||
void runDiagnostics(safeKeys, 'safe')
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
if (!active) return
|
||||
setPageError(error instanceof Error ? error.message : 'Unable to load diagnostics.')
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
void loadPage()
|
||||
|
||||
return () => {
|
||||
active = false
|
||||
}
|
||||
}, [router])
|
||||
|
||||
useEffect(() => {
|
||||
if (!authorized || !autoRefresh || liveSafeKeys.length === 0) {
|
||||
return
|
||||
}
|
||||
const interval = window.setInterval(() => {
|
||||
void runDiagnostics(liveSafeKeys, 'safe')
|
||||
}, REFRESH_INTERVAL_MS)
|
||||
return () => {
|
||||
window.clearInterval(interval)
|
||||
}
|
||||
}, [authorized, autoRefresh, liveSafeKeys.join('|')])
|
||||
|
||||
if (loading) {
|
||||
return <div className="admin-panel">Loading diagnostics...</div>
|
||||
}
|
||||
|
||||
if (!authorized) {
|
||||
return null
|
||||
}
|
||||
|
||||
const orderedCategories: string[] = []
|
||||
for (const check of checks) {
|
||||
if (!orderedCategories.includes(check.category)) {
|
||||
orderedCategories.push(check.category)
|
||||
}
|
||||
}
|
||||
|
||||
const mergedResults = checks.map((check) => {
|
||||
const result = resultsByKey[check.key]
|
||||
if (result) {
|
||||
return result
|
||||
}
|
||||
return {
|
||||
key: check.key,
|
||||
label: check.label,
|
||||
category: check.category,
|
||||
description: check.description,
|
||||
target: check.target,
|
||||
live_safe: check.live_safe,
|
||||
configured: check.configured,
|
||||
status: check.configured ? 'idle' : check.config_status,
|
||||
message: check.configured ? 'Ready to test.' : check.config_detail,
|
||||
checked_at: undefined,
|
||||
duration_ms: undefined,
|
||||
} satisfies DiagnosticResult
|
||||
})
|
||||
|
||||
const summary = {
|
||||
total: mergedResults.length,
|
||||
up: 0,
|
||||
down: 0,
|
||||
degraded: 0,
|
||||
disabled: 0,
|
||||
not_configured: 0,
|
||||
idle: 0,
|
||||
}
|
||||
for (const result of mergedResults) {
|
||||
const key = result.status as keyof typeof summary
|
||||
if (key in summary) {
|
||||
summary[key] += 1
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`diagnostics-page${embedded ? ' diagnostics-page-embedded' : ''}`}>
|
||||
<div className="admin-panel diagnostics-control-panel">
|
||||
<div className="diagnostics-control-copy">
|
||||
<h2>{embedded ? 'Connectivity diagnostics' : 'Control center'}</h2>
|
||||
<p className="lede">
|
||||
Use live checks for Magent and service connectivity. Use run all when you want outbound notification
|
||||
channels to send a real ping through the configured provider.
|
||||
</p>
|
||||
</div>
|
||||
<div className="diagnostics-control-actions">
|
||||
<label className="diagnostics-email-recipient">
|
||||
<span>Test email recipient</span>
|
||||
<input
|
||||
type="email"
|
||||
placeholder="Leave blank to use configured sender"
|
||||
value={emailRecipient}
|
||||
onChange={(event) => setEmailRecipient(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
className={autoRefresh ? 'is-active' : ''}
|
||||
onClick={() => setAutoRefresh((current) => !current)}
|
||||
>
|
||||
{autoRefresh ? 'Disable auto refresh' : 'Enable auto refresh'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
void runDiagnostics(liveSafeKeys, 'safe')
|
||||
}}
|
||||
disabled={runningKeys.length > 0 || liveSafeKeys.length === 0}
|
||||
>
|
||||
Run live checks
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
void runDiagnostics(undefined, 'all')
|
||||
}}
|
||||
disabled={runningKeys.length > 0 || checks.length === 0}
|
||||
>
|
||||
Run all tests
|
||||
</button>
|
||||
<span className={`small-pill ${autoRefresh ? 'is-positive' : ''}`}>
|
||||
{autoRefresh ? 'Auto refresh on' : 'Auto refresh off'}
|
||||
</span>
|
||||
<span className="small-pill">{lastRunMode ? `Last run: ${lastRunMode}` : 'No run yet'}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="admin-panel diagnostics-inline-summary">
|
||||
<div className="diagnostics-inline-metric">
|
||||
<span>Total</span>
|
||||
<strong>{summary.total}</strong>
|
||||
</div>
|
||||
<div className="diagnostics-inline-metric">
|
||||
<span>Up</span>
|
||||
<strong>{summary.up}</strong>
|
||||
</div>
|
||||
<div className="diagnostics-inline-metric">
|
||||
<span>Degraded</span>
|
||||
<strong>{summary.degraded}</strong>
|
||||
</div>
|
||||
<div className="diagnostics-inline-metric">
|
||||
<span>Down</span>
|
||||
<strong>{summary.down}</strong>
|
||||
</div>
|
||||
<div className="diagnostics-inline-metric">
|
||||
<span>Disabled</span>
|
||||
<strong>{summary.disabled}</strong>
|
||||
</div>
|
||||
<div className="diagnostics-inline-metric">
|
||||
<span>Not configured</span>
|
||||
<strong>{summary.not_configured}</strong>
|
||||
</div>
|
||||
<div className="diagnostics-inline-last-run">
|
||||
Last completed run: {formatCheckedAt(lastRunAt ?? undefined)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{pageError ? <div className="admin-panel diagnostics-error">{pageError}</div> : null}
|
||||
|
||||
{orderedCategories.map((category) => {
|
||||
const categoryChecks = mergedResults.filter((check) => check.category === category)
|
||||
return (
|
||||
<div key={category} className="admin-panel diagnostics-category-panel">
|
||||
<div className="diagnostics-category-header">
|
||||
<div>
|
||||
<h2>{category}</h2>
|
||||
<p>{category === 'Notifications' ? 'These tests can emit real messages.' : 'Safe live health checks.'}</p>
|
||||
</div>
|
||||
<span className="small-pill">{categoryChecks.length} checks</span>
|
||||
</div>
|
||||
|
||||
<div className="diagnostics-grid">
|
||||
{categoryChecks.map((check) => {
|
||||
const isRunning = runningKeys.includes(check.key)
|
||||
return (
|
||||
<article key={check.key} className={`diagnostic-card diagnostic-card-${check.status}`}>
|
||||
<div className="diagnostic-card-top">
|
||||
<div className="diagnostic-card-copy">
|
||||
<div className="diagnostic-card-title-row">
|
||||
<h3>{check.label}</h3>
|
||||
<span className={`system-pill system-pill-${check.status}`}>{statusLabel(check.status)}</span>
|
||||
</div>
|
||||
<p>{check.description}</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="system-test"
|
||||
onClick={() => {
|
||||
void runDiagnostics([check.key], 'single')
|
||||
}}
|
||||
disabled={isRunning}
|
||||
>
|
||||
{check.live_safe ? 'Ping' : 'Send test'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="diagnostic-meta-grid">
|
||||
<div className="diagnostic-meta-item">
|
||||
<span>Target</span>
|
||||
<strong>{check.target || 'Not set'}</strong>
|
||||
</div>
|
||||
<div className="diagnostic-meta-item">
|
||||
<span>Latency</span>
|
||||
<strong>{formatDuration(check.duration_ms)}</strong>
|
||||
</div>
|
||||
<div className="diagnostic-meta-item">
|
||||
<span>Mode</span>
|
||||
<strong>{check.live_safe ? 'Live safe' : 'Manual only'}</strong>
|
||||
</div>
|
||||
<div className="diagnostic-meta-item">
|
||||
<span>Last checked</span>
|
||||
<strong>{formatCheckedAt(check.checked_at)}</strong>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={`diagnostic-message diagnostic-message-${check.status}`}>
|
||||
<span className="system-dot" />
|
||||
<span>{isRunning ? 'Running diagnostic...' : check.message}</span>
|
||||
</div>
|
||||
|
||||
{check.key === 'database'
|
||||
? (() => {
|
||||
const detail = asDatabaseDiagnosticDetail(check.detail)
|
||||
if (!detail) {
|
||||
return null
|
||||
}
|
||||
return (
|
||||
<div className="diagnostic-detail-panel">
|
||||
{renderDatabaseMetricGroup('Storage', [
|
||||
['Database file', formatBytes(detail.database_size_bytes)],
|
||||
['WAL file', formatBytes(detail.wal_size_bytes)],
|
||||
['Shared memory', formatBytes(detail.shm_size_bytes)],
|
||||
['Allocated bytes', formatBytes(detail.allocated_bytes)],
|
||||
['Free bytes', formatBytes(detail.free_bytes)],
|
||||
['Page size', formatBytes(detail.page_size_bytes)],
|
||||
['Page count', `${detail.page_count?.toLocaleString() ?? 0}`],
|
||||
['Freelist pages', `${detail.freelist_pages?.toLocaleString() ?? 0}`],
|
||||
])}
|
||||
{renderDatabaseMetricGroup(
|
||||
'Tables',
|
||||
Object.entries(detail.row_counts ?? {}).map(([key, value]) => [
|
||||
formatDetailLabel(key),
|
||||
value.toLocaleString(),
|
||||
]),
|
||||
)}
|
||||
{renderDatabaseMetricGroup(
|
||||
'Timings',
|
||||
Object.entries(detail.timings_ms ?? {}).map(([key, value]) => [
|
||||
formatDetailLabel(key),
|
||||
`${value.toFixed(1)} ms`,
|
||||
]),
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})()
|
||||
: null}
|
||||
</article>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
'use client'
|
||||
|
||||
import type { ReactNode } from 'react'
|
||||
import AdminSidebar from './AdminSidebar'
|
||||
|
||||
type AdminShellProps = {
|
||||
title: string
|
||||
subtitle?: string
|
||||
actions?: ReactNode
|
||||
rail?: ReactNode
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
export default function AdminShell({ title, subtitle, actions, rail, children }: AdminShellProps) {
|
||||
const hasRail = Boolean(rail)
|
||||
|
||||
return (
|
||||
<div className={`admin-shell ${hasRail ? 'admin-shell--with-rail' : 'admin-shell--no-rail'}`}>
|
||||
<aside className="admin-shell-nav">
|
||||
<AdminSidebar />
|
||||
</aside>
|
||||
<main className="card admin-card">
|
||||
<div className="admin-header">
|
||||
<div>
|
||||
<span className="section-kicker">Beta stream</span>
|
||||
<h1>{title}</h1>
|
||||
{subtitle && <p className="lede">{subtitle}</p>}
|
||||
</div>
|
||||
{actions}
|
||||
</div>
|
||||
{children}
|
||||
</main>
|
||||
{hasRail ? <aside className="admin-shell-rail">{rail}</aside> : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
'use client'
|
||||
|
||||
import { usePathname } from 'next/navigation'
|
||||
|
||||
const NAV_GROUPS = [
|
||||
{
|
||||
title: 'Operations',
|
||||
items: [
|
||||
{ href: '/admin', label: 'Overview' },
|
||||
{ href: '/', label: 'Health' },
|
||||
{ href: '/portal/requests', label: 'Request portal' },
|
||||
{ href: '/admin/issues', label: 'Issue tracking' },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'Services',
|
||||
items: [
|
||||
{ href: '/admin/general', label: 'General' },
|
||||
{ href: '/admin/seerr', label: 'Seerr' },
|
||||
{ href: '/admin/jellyfin', label: 'Jellyfin' },
|
||||
{ href: '/admin/sonarr', label: 'Sonarr' },
|
||||
{ href: '/admin/radarr', label: 'Radarr' },
|
||||
{ href: '/admin/prowlarr', label: 'Prowlarr' },
|
||||
{ href: '/admin/qbittorrent', label: 'qBittorrent' },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'Requests',
|
||||
items: [
|
||||
{ href: '/admin/requests', label: 'Request sync' },
|
||||
{ href: '/admin/requests-all', label: 'All requests' },
|
||||
{ href: '/admin/cache', label: 'Cache Control' },
|
||||
{ href: '/admin/artwork', label: 'Artwork cache' },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'Admin',
|
||||
items: [
|
||||
{ href: '/admin/notifications', label: 'Notifications' },
|
||||
{ href: '/admin/system', label: 'How it works' },
|
||||
{ href: '/admin/site', label: 'Site' },
|
||||
{ href: '/users', label: 'Users' },
|
||||
{ href: '/admin/invites', label: 'Invite management' },
|
||||
{ href: '/admin/logs', label: 'Activity log' },
|
||||
{ href: '/admin/maintenance', label: 'Maintenance' },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
export default function AdminSidebar() {
|
||||
const pathname = usePathname()
|
||||
return (
|
||||
<nav className="admin-sidebar">
|
||||
<div className="admin-sidebar-title">Settings</div>
|
||||
{NAV_GROUPS.map((group) => (
|
||||
<div key={group.title} className="admin-nav-group">
|
||||
<span className="admin-nav-title">{group.title}</span>
|
||||
<div className="admin-nav-links">
|
||||
{group.items.map((item) => {
|
||||
const isActive =
|
||||
pathname === item.href ||
|
||||
(item.href !== '/' && pathname.startsWith(item.href))
|
||||
return (
|
||||
<a key={item.href} href={item.href} className={isActive ? 'is-active' : ''}>
|
||||
{item.label}
|
||||
</a>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</nav>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect } from 'react'
|
||||
|
||||
export default function BrandingFavicon() {
|
||||
useEffect(() => {
|
||||
const href = '/api/branding/favicon.ico'
|
||||
let link = document.querySelector("link[rel='icon']") as HTMLLinkElement | null
|
||||
if (!link) {
|
||||
link = document.createElement('link')
|
||||
link.rel = 'icon'
|
||||
document.head.appendChild(link)
|
||||
}
|
||||
link.href = href
|
||||
}, [])
|
||||
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
|
||||
type BrandingLogoProps = {
|
||||
className?: string
|
||||
alt?: string
|
||||
}
|
||||
|
||||
export default function BrandingLogo({ className, alt = 'Magent logo' }: BrandingLogoProps) {
|
||||
const [loaded, setLoaded] = useState(false)
|
||||
const [failed, setFailed] = useState(false)
|
||||
|
||||
return (
|
||||
<span className={`${className ?? ''} branding-logo-shell`} role="img" aria-label={alt}>
|
||||
{!failed ? (
|
||||
<img
|
||||
className={loaded ? 'is-loaded' : undefined}
|
||||
src="/api/branding/logo.png"
|
||||
alt=""
|
||||
aria-hidden="true"
|
||||
onLoad={() => setLoaded(true)}
|
||||
onError={() => setFailed(true)}
|
||||
/>
|
||||
) : null}
|
||||
{!loaded ? (
|
||||
<svg aria-hidden="true" viewBox="0 0 64 64" focusable="false">
|
||||
<defs>
|
||||
<linearGradient id="magentLogoGlow" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0%" stopColor="#7ed7ff" />
|
||||
<stop offset="100%" stopColor="#c6c1ff" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect width="64" height="64" rx="12" fill="#0b1328" />
|
||||
<rect x="6" y="6" width="52" height="52" rx="9" fill="#111a33" />
|
||||
<path
|
||||
d="M16 48V16h8l8 13 8-13h8v32h-8V30l-8 12-8-12v18h-8z"
|
||||
fill="url(#magentLogoGlow)"
|
||||
/>
|
||||
</svg>
|
||||
) : null}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { usePathname } from 'next/navigation'
|
||||
import { authFetch, clearToken, getApiBase, getToken } from '../lib/auth'
|
||||
|
||||
export default function HeaderActions() {
|
||||
const [signedIn, setSignedIn] = useState(false)
|
||||
const [role, setRole] = useState<string | null>(null)
|
||||
const [showRequestsNav, setShowRequestsNav] = useState(true)
|
||||
const pathname = usePathname()
|
||||
|
||||
useEffect(() => {
|
||||
const token = getToken()
|
||||
setSignedIn(Boolean(token))
|
||||
if (!token) {
|
||||
setShowRequestsNav(true)
|
||||
return
|
||||
}
|
||||
const load = async () => {
|
||||
try {
|
||||
const baseUrl = getApiBase()
|
||||
const [response, siteResponse] = await Promise.all([
|
||||
authFetch(`${baseUrl}/auth/me`),
|
||||
fetch(`${baseUrl}/site/public`).catch(() => null),
|
||||
])
|
||||
if (!response.ok) {
|
||||
clearToken()
|
||||
setSignedIn(false)
|
||||
setRole(null)
|
||||
return
|
||||
}
|
||||
const data = await response.json()
|
||||
setRole(data?.role ?? null)
|
||||
if (siteResponse?.ok) {
|
||||
const siteData = await siteResponse.json()
|
||||
setShowRequestsNav(siteData?.navigation?.showRequests !== false)
|
||||
} else {
|
||||
setShowRequestsNav(true)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
setShowRequestsNav(true)
|
||||
}
|
||||
}
|
||||
void load()
|
||||
}, [])
|
||||
|
||||
if (!signedIn) {
|
||||
return null
|
||||
}
|
||||
|
||||
const roleItems =
|
||||
role === null
|
||||
? []
|
||||
: role === 'admin'
|
||||
? [
|
||||
{
|
||||
href: '/admin',
|
||||
label: 'Config',
|
||||
match: (path: string) => path.startsWith('/admin'),
|
||||
},
|
||||
]
|
||||
: [
|
||||
{
|
||||
href: '/profile',
|
||||
label: 'Profile',
|
||||
match: (path: string) => path.startsWith('/profile') && !path.startsWith('/profile/invites'),
|
||||
},
|
||||
{
|
||||
href: '/profile/invites',
|
||||
label: 'Invites',
|
||||
match: (path: string) => path.startsWith('/profile/invites'),
|
||||
},
|
||||
]
|
||||
|
||||
const commonItems = [
|
||||
{ href: '/', label: 'Health', match: (path: string) => path === '/' },
|
||||
...(showRequestsNav
|
||||
? [
|
||||
{
|
||||
href: '/portal/requests',
|
||||
label: 'Requests',
|
||||
match: (path: string) => path === '/portal/requests' || path.startsWith('/requests/'),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
{
|
||||
href: '/portal/issues',
|
||||
label: 'Issues',
|
||||
match: (path: string) => path === '/portal/issues' || path === '/admin/issues',
|
||||
},
|
||||
]
|
||||
|
||||
const items = [
|
||||
...commonItems,
|
||||
...roleItems,
|
||||
]
|
||||
|
||||
return (
|
||||
<nav className="header-actions" aria-label="Primary">
|
||||
{items.map((item, index) => {
|
||||
const active = item.match(pathname)
|
||||
return (
|
||||
<a key={item.href} href={item.href} className={active ? 'is-active' : undefined}>
|
||||
<span aria-hidden="true">{String(index + 1).padStart(2, '0')}</span>
|
||||
{item.label}
|
||||
</a>
|
||||
)
|
||||
})}
|
||||
</nav>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { authFetch, clearToken, getApiBase, getToken, logout } from '../lib/auth'
|
||||
|
||||
export default function HeaderIdentity() {
|
||||
const [identity, setIdentity] = useState<{ username: string; role?: string } | null>(null)
|
||||
const [buildNumber, setBuildNumber] = useState<string | null>(null)
|
||||
const [open, setOpen] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
const token = getToken()
|
||||
if (!token) {
|
||||
setIdentity(null)
|
||||
setBuildNumber(null)
|
||||
return
|
||||
}
|
||||
const load = async () => {
|
||||
try {
|
||||
const baseUrl = getApiBase()
|
||||
const response = await authFetch(`${baseUrl}/auth/me`)
|
||||
if (!response.ok) {
|
||||
clearToken()
|
||||
setIdentity(null)
|
||||
return
|
||||
}
|
||||
const data = await response.json()
|
||||
if (data?.username) {
|
||||
setIdentity({ username: data.username, role: data.role })
|
||||
}
|
||||
const siteResponse = await fetch(`${baseUrl}/site/public`)
|
||||
if (siteResponse.ok) {
|
||||
const siteInfo = await siteResponse.json()
|
||||
if (siteInfo?.buildNumber) {
|
||||
setBuildNumber(siteInfo.buildNumber)
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
setIdentity(null)
|
||||
}
|
||||
}
|
||||
void load()
|
||||
}, [])
|
||||
|
||||
if (!identity) {
|
||||
return null
|
||||
}
|
||||
|
||||
const label = `${identity.username}${identity.role ? ` (${identity.role})` : ''}`
|
||||
const initial = identity.username.slice(0, 1).toUpperCase()
|
||||
const signOut = async () => {
|
||||
await logout().catch(() => undefined)
|
||||
clearToken()
|
||||
if (typeof window !== 'undefined') {
|
||||
window.location.href = '/login'
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="signed-in-menu">
|
||||
<button
|
||||
type="button"
|
||||
className="avatar-button"
|
||||
onClick={() => setOpen((prev) => !prev)}
|
||||
aria-haspopup="true"
|
||||
aria-expanded={open}
|
||||
title={label}
|
||||
>
|
||||
{initial}
|
||||
</button>
|
||||
{open && (
|
||||
<div className="signed-in-dropdown">
|
||||
<div className="signed-in-header">Signed in as {label}</div>
|
||||
<div className="signed-in-actions">
|
||||
<a href="/profile" onClick={() => setOpen(false)}>
|
||||
My profile
|
||||
</a>
|
||||
{identity.role === 'admin' ? (
|
||||
<a href="/admin" onClick={() => setOpen(false)}>
|
||||
Settings
|
||||
</a>
|
||||
) : null}
|
||||
<a href="/changelog" onClick={() => setOpen(false)}>
|
||||
Changelog
|
||||
</a>
|
||||
<button type="button" className="signed-in-signout" onClick={() => void signOut()}>
|
||||
Sign out
|
||||
</button>
|
||||
</div>
|
||||
{buildNumber ? <div className="signed-in-build">Build {buildNumber}</div> : null}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { authFetch, clearToken, getApiBase, getToken } from '../lib/auth'
|
||||
|
||||
type BannerInfo = {
|
||||
enabled: boolean
|
||||
message: string
|
||||
tone?: string
|
||||
}
|
||||
|
||||
type SiteInfo = {
|
||||
buildNumber?: string
|
||||
banner?: BannerInfo
|
||||
}
|
||||
|
||||
const buildRequest = () => {
|
||||
const token = getToken()
|
||||
const baseUrl = getApiBase()
|
||||
const url = token ? `${baseUrl}/site/info` : `${baseUrl}/site/public`
|
||||
const fetcher = token ? authFetch : fetch
|
||||
return { token, url, fetcher }
|
||||
}
|
||||
|
||||
export default function SiteStatus() {
|
||||
const [info, setInfo] = useState<SiteInfo | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
const load = async () => {
|
||||
try {
|
||||
const { token, url, fetcher } = buildRequest()
|
||||
const response = await fetcher(url)
|
||||
if (!response.ok) {
|
||||
if (response.status === 401 && token) {
|
||||
clearToken()
|
||||
}
|
||||
return
|
||||
}
|
||||
const data = await response.json()
|
||||
if (!active) return
|
||||
setInfo(data)
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
}
|
||||
}
|
||||
void load()
|
||||
return () => {
|
||||
active = false
|
||||
}
|
||||
}, [])
|
||||
|
||||
const banner = info?.banner
|
||||
const tone = banner?.tone || 'info'
|
||||
return (
|
||||
<>
|
||||
{banner?.enabled && banner.message ? (
|
||||
<div className={`site-banner site-banner--${tone}`}>{banner.message}</div>
|
||||
) : null}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
const STORAGE_KEY = 'magent_theme'
|
||||
|
||||
const getPreferredTheme = () => {
|
||||
if (typeof window === 'undefined') return 'dark'
|
||||
const stored = window.localStorage.getItem(STORAGE_KEY)
|
||||
if (stored === 'light' || stored === 'dark') {
|
||||
return stored
|
||||
}
|
||||
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
|
||||
}
|
||||
|
||||
const applyTheme = (theme: string) => {
|
||||
if (typeof document === 'undefined') return
|
||||
document.documentElement.setAttribute('data-theme', theme)
|
||||
}
|
||||
|
||||
export default function ThemeToggle() {
|
||||
const [theme, setTheme] = useState<'light' | 'dark'>('dark')
|
||||
|
||||
useEffect(() => {
|
||||
const preferred = getPreferredTheme()
|
||||
setTheme(preferred)
|
||||
applyTheme(preferred)
|
||||
}, [])
|
||||
|
||||
const toggle = () => {
|
||||
const next = theme === 'dark' ? 'light' : 'dark'
|
||||
setTheme(next)
|
||||
applyTheme(next)
|
||||
if (typeof window !== 'undefined') {
|
||||
window.localStorage.setItem(STORAGE_KEY, next)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="theme-toggle"
|
||||
onClick={toggle}
|
||||
aria-label={theme === 'dark' ? 'Switch to light mode' : 'Switch to dark mode'}
|
||||
title={theme === 'dark' ? 'Light mode' : 'Dark mode'}
|
||||
>
|
||||
{theme === 'dark' ? (
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||
<circle cx="12" cy="12" r="4" />
|
||||
<path d="M12 2v3M12 19v3M4.22 4.22l2.12 2.12M17.66 17.66l2.12 2.12M2 12h3M19 12h3M4.22 19.78l2.12-2.12M17.66 6.34l2.12-2.12" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||
<path d="M21 14.5A8.5 8.5 0 0 1 9.5 3a8.5 8.5 0 1 0 11.5 11.5z" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user