/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { useEffect, useMemo, useRef, useState, type CSSProperties } from 'react'; import { Layout, Menu, Breadcrumb, Avatar, Dropdown, Empty, Modal, message } from 'antd'; import { Outlet, useNavigate, useLocation } from 'react-router-dom'; import { House, Database, Monitor, Sparkle, GearSix, ChatCircleText, Key, MagnifyingGlass, ListDashes, UserGear, ChartBar, Sun, Moon, ShieldCheck, TrashSimple, PlugsConnected, BellRinging, Siren, PaperPlaneTilt, Notebook, Warning, } from '@phosphor-icons/react'; import { useLang } from '../i18n/LangContext'; import { useTheme } from '../theme/useTheme'; import { logout as requestLogout } from '../api/auth'; import useAuthStore from '../stores/authStore'; import { filterNavigationEntries, isNavigationSearchShortcut, type NavigationSearchEntry, } from './navigationSearch'; import { useDataModeStore } from '../stores/dataModeStore'; import { getInstanceCapabilities } from '../services/instanceService'; import type { InstanceCapability } from '../api/instance'; const { Sider, Content } = Layout; const iconSize = 18; function hasInstanceCapability( capabilities: Set | null, capability: InstanceCapability, ) { return capabilities === null || capabilities.has(capability); } const MainLayout = () => { const navigate = useNavigate(); const location = useLocation(); const { darkMode, toggleTheme } = useTheme(); const [searchOpen, setSearchOpen] = useState(false); const [searchText, setSearchText] = useState(''); const [activeIndex, setActiveIndex] = useState(0); const [collapsed, setCollapsed] = useState(false); const searchInputRef = useRef(null); const { lang, setLang, t } = useLang(); const clearAuth = useAuthStore((state) => state.logout); const admin = useAuthStore((state) => state.admin); const username = useAuthStore((state) => state.user); const useMock = useDataModeStore((state) => state.useMock); const toggleDataMode = useDataModeStore((state) => state.toggle); const [capabilityState, setCapabilityState] = useState<{ instanceId: string; capabilities: Set; } | null>(null); // Pages fetch on mount, so reload to re-request everything from the new data source. const handleDataModeToggle = () => { toggleDataMode(); window.location.reload(); }; const handleUserMenuClick = async ({ key }: { key: string }) => { if (key === 'dataMode') { handleDataModeToggle(); return; } if (key === 'profile') { navigate('/settings'); return; } if (key === 'users') { navigate('/studio/users'); return; } if (key !== 'logout') return; try { await requestLogout(); } catch { message.warning(t('user.logoutFailed')); } finally { clearAuth(); navigate('/login', { replace: true }); } }; useEffect(() => { const openSearchWithShortcut = (event: KeyboardEvent) => { if (!isNavigationSearchShortcut(event)) return; event.preventDefault(); setSearchOpen(true); }; window.addEventListener('keydown', openSearchWithShortcut); return () => window.removeEventListener('keydown', openSearchWithShortcut); }, []); const instanceScopedMatch = useMemo( // 与 useInstanceFilter 的 INSTANCE_SCOPED_PATH 保持同一口径:尾斜杠路由 // (/instance//topic/)同样算实例维度页,否则菜单高亮与面包屑末级标题会降级。 () => location.pathname.match(/^\/instance\/[^/]+\/(topic|consumer|message|acl|dlq)\/*$/), [location.pathname], ); const selectedInstanceId = useMemo(() => { const match = location.pathname.match(/^\/instance\/([^/]+)\//); if (!match) return null; try { const value = decodeURIComponent(match[1]); return value || null; } catch { return null; } }, [location.pathname]); useEffect(() => { if (!selectedInstanceId) return; let active = true; void getInstanceCapabilities(selectedInstanceId) .then((result) => { if (active) { setCapabilityState({ instanceId: selectedInstanceId, capabilities: new Set(result.capabilities), }); } }) .catch(() => { // Preserve existing navigation when capability discovery is unavailable. }); return () => { active = false; }; }, [selectedInstanceId]); const instanceCapabilities = capabilityState?.instanceId === selectedInstanceId ? capabilityState.capabilities : null; const selectedMenuKey = instanceScopedMatch ? `/instance/${instanceScopedMatch[1]}` : location.pathname; const menuItems = useMemo( () => [ { key: '/', icon: , label: t('nav.home') }, { key: 'instance-group', icon: , label: t('nav.instance'), children: [ { key: '/instance', icon: , label: t('nav.instanceList') }, ...(hasInstanceCapability(instanceCapabilities, 'TOPIC_MANAGEMENT') ? [{ key: '/instance/topic', icon: , label: t('nav.topic') }] : []), ...(hasInstanceCapability(instanceCapabilities, 'CONSUMER_GROUP_MANAGEMENT') ? [ { key: '/instance/consumer', icon: , label: t('nav.group'), }, ] : []), ...(hasInstanceCapability(instanceCapabilities, 'ACL_MANAGEMENT') ? [{ key: '/instance/acl', icon: , label: t('nav.acl') }] : []), ...(hasInstanceCapability(instanceCapabilities, 'MESSAGE_QUERY') ? [ { key: '/instance/message', icon: , label: t('nav.message'), }, ] : []), ...(hasInstanceCapability(instanceCapabilities, 'DLQ_MANAGEMENT') ? [{ key: '/instance/dlq', icon: , label: t('nav.dlq') }] : []), { key: '/ops/business-alerts', icon: , label: t('nav.alertRuleAssets'), }, ], }, { key: 'cluster-ops-group', icon: , label: t('nav.clusterOps'), children: [ { key: '/cluster/certs', icon: , label: t('nav.certs') }, { key: '/cluster', icon: , label: t('nav.rocketmqCluster') }, { key: '/cluster/clients', icon: , label: t('nav.clients') }, { key: '/ops/alerts', icon: , label: t('nav.alertRules') }, { key: '/ops/system-alerts', icon: , label: t('nav.alertEvents'), }, { key: '/ops/alert-deliveries', icon: , label: t('nav.alertDeliveries'), }, { key: '/ops/dashboard', icon: , label: t('nav.dashboard') }, ], }, { key: '/ops/audit', icon: , label: t('nav.audit'), }, { key: '/ai', icon: , label: t('nav.ai') }, { key: '/settings', icon: , label: t('nav.settings'), }, ], [t, instanceCapabilities], ); const breadcrumbMap: Record = useMemo( () => ({ '/': t('nav.home'), '/ops': t('nav.clusterOps'), '/instance': t('nav.instanceList'), '/instance/topic': t('nav.topic'), '/instance/consumer': t('nav.group'), '/instance/message': t('nav.message'), '/instance/acl': t('nav.acl'), '/instance/dlq': t('nav.dlq'), '/instance/alerts': t('nav.alertRuleAssets'), '/cluster': t('nav.rocketmqCluster'), '/cluster/certs': t('nav.certs'), '/cluster/clients': t('nav.clients'), '/ops/dashboard': t('nav.dashboard'), '/ops/grafana': t('nav.grafanaDashboards'), '/ops/system-alerts': t('nav.alertEvents'), '/ops/alert-deliveries': t('nav.alertDeliveries'), '/ops/business-alerts': t('nav.alertRuleAssets'), '/ops/alerts': t('nav.alertRules'), '/ops/audit': t('nav.audit'), '/ai': t('nav.ai'), '/settings': t('nav.settings'), '/studio/users': t('userMgmt.title'), }), [t], ); const breadcrumbItems = useMemo(() => { const pathSnippets = location.pathname.split('/').filter((segment) => segment); return [ { title: ( ), key: 'home', }, ...pathSnippets .map((_, index) => { const path = '/' + pathSnippets.slice(0, index + 1).join('/'); // The instance ID path segment (/instance/) is an identifier, not a // navigation level — keep it out of the breadcrumb trail. const isInstanceIdSegment = index === 1 && pathSnippets[0] === 'instance' && !breadcrumbMap[path]; if (isInstanceIdSegment) { return null; } // Same for the AI conversation path (/ai/c/): everything after /ai is // conversation identity, not a navigation level. const isAiConversationSegment = index >= 1 && pathSnippets[0] === 'ai'; if (isAiConversationSegment) { return null; } const isSectionLeaf = instanceScopedMatch && index === pathSnippets.length - 1; const leafTitle = isSectionLeaf ? breadcrumbMap[`/instance/${instanceScopedMatch[1]}`] : undefined; return { title: breadcrumbMap[path] || leafTitle || path, key: path, }; }) .filter((item): item is NonNullable => item !== null), ]; }, [location.pathname, navigate, breadcrumbMap, instanceScopedMatch, t]); const userMenu = { onClick: handleUserMenuClick, items: [ { key: 'profile', icon: , label: t('user.profile') }, ...(admin ? [{ key: 'users', icon: , label: t('userMgmt.title') }] : []), { key: 'dataMode', icon: ( ), label: `${t('layout.dataMode')}: ${useMock ? 'Mock' : 'Real'}`, title: useMock ? t('layout.switchToRealData') : t('layout.switchToMockData'), }, { type: 'divider' as const }, { key: 'logout', label: t('user.logout'), danger: true }, ], }; const borderColor = darkMode ? '#3a3a3e' : '#f0f0f0'; const siderBg = darkMode ? '#2a2a2e' : '#ffffff'; const topBarBg = darkMode ? 'rgba(42,42,46,0.85)' : 'rgba(255,255,255,0.7)'; const logoColor = darkMode ? '#e5e5e5' : '#1b1b1a'; const kbdStyle: CSSProperties = { fontSize: 12, lineHeight: '18px', padding: '0 6px', borderRadius: 6, background: darkMode ? '#333' : '#f5f5f5', border: `1px solid ${borderColor}`, color: darkMode ? '#a1a1aa' : '#9CA3AF', fontFamily: 'inherit', whiteSpace: 'nowrap', }; const navigationEntries: NavigationSearchEntry[] = useMemo( () => menuItems .flatMap((item) => ('children' in item && item.children ? item.children : [item])) .map((item) => ({ key: String(item.key), label: String(item.label), icon: item.icon })), [menuItems], ); const filteredEntries = filterNavigationEntries(navigationEntries, searchText); // Group filtered results by their navigation section for the grid layout; the // top-level pages (home / audit / AI / settings) share a single "general" bucket. const resultSections = useMemo(() => { const matched = new Set(filteredEntries.map((entry) => entry.key)); const sections: { title: string; entries: NavigationSearchEntry[] }[] = []; const general: NavigationSearchEntry[] = []; for (const item of menuItems) { if ('children' in item && item.children) { const entries = item.children .map((child) => ({ key: String(child.key), label: String(child.label), icon: child.icon, })) .filter((entry) => matched.has(entry.key)); if (entries.length > 0) sections.push({ title: String(item.label), entries }); } else { const entry = { key: String(item.key), label: String(item.label), icon: item.icon }; if (matched.has(entry.key)) general.push(entry); } } if (general.length > 0) sections.unshift({ title: t('layout.searchGeneral'), entries: general }); return sections; }, [menuItems, filteredEntries, t]); // Keyboard navigation follows the visual (grouped) order. const searchResults = useMemo( () => resultSections.flatMap((section) => section.entries), [resultSections], ); const isAiRoute = location.pathname === '/ai'; return ( <> { event.currentTarget.style.transform = 'translateY(0)'; }} onBlur={(event) => { event.currentTarget.style.transform = 'translateY(-150%)'; }} > {t('layout.skipToMain')} {/* Logo */}
🚀 {!collapsed && RocketMQ Studio}
{/* Navigation Menu */} navigate(key)} style={{ borderRight: 'none', background: 'transparent' }} /> {/* Top bar */}
{/* Left: Breadcrumb */} {/* Right: Search + Lang + Theme + User */}
{/* Search button */} {/* Language toggle */} {/* Theme toggle */} {/* User avatar */}
{/* Search Modal (command palette) */} { setSearchOpen(false); setSearchText(''); setActiveIndex(0); }} footer={null} closable={false} styles={{ body: { padding: 0 }, content: { padding: 0, overflow: 'hidden', borderRadius: 16, border: `1px solid ${borderColor}`, boxShadow: '0 24px 80px -24px rgba(0, 0, 0, 0.35)', }, }} width={640} style={{ top: '14vh' }} afterOpenChange={(open) => { if (open) searchInputRef.current?.focus(); }} >
{ setSearchText(e.target.value); setActiveIndex(0); }} onKeyDown={(e) => { // Composition keys select or confirm IME text, not navigation results. if (e.nativeEvent.isComposing || e.nativeEvent.keyCode === 229) return; if (e.key === 'ArrowDown') { e.preventDefault(); setActiveIndex((i) => Math.min(i + 1, Math.max(searchResults.length - 1, 0))); } else if (e.key === 'ArrowUp') { e.preventDefault(); setActiveIndex((i) => Math.max(i - 1, 0)); } else if (e.key === 'Enter') { const target = searchResults[Math.min(activeIndex, searchResults.length - 1)]; if (!target) return; navigate(target.key as string); setSearchOpen(false); setSearchText(''); setActiveIndex(0); } }} autoFocus style={{ flex: 1, border: 'none', outline: 'none', fontSize: 15, background: 'transparent', color: 'inherit', }} /> ESC
{resultSections.length ? ( resultSections.map((section) => (
{section.title}
{section.entries.map((item) => { const active = searchResults[activeIndex]?.key === item.key; return ( ); })}
)) ) : ( )}
↑ ↓ {t('layout.shortcutNavigate')} ↵ {t('common.open')} ESC {t('common.close')}
); }; export default MainLayout;