Files
chaos-api/web/default/src/features/usage-logs/index.tsx
T
t0ng7u 92a0959448 refactor(web/default): adopt drill-in sidebar pattern for System Settings
Replace the ad-hoc "workspace" abstraction with a focused, URL-driven
"sidebar view" registry that implements the modern Vercel / Cloudflare
drill-in pattern: clicking a top-level entry (e.g. System Settings)
swaps the sidebar to a contextual workspace, with a `← Back to
Dashboard` affordance, instead of stacking sub-navigation in the root.

Architecture
------------
- types.ts
    + SidebarView           — declarative nested view config
                              (id, pathPattern, parent, getNavGroups)
    + SidebarViewParent     — back-navigation descriptor
    + ResolvedSidebarView   — { key, view, navGroups } returned by hook
    + SidebarData           — slimmed to { navGroups } only
    - Workspace             — removed (logo/plan never rendered)

- lib/sidebar-view-registry.ts (new, replaces workspace-registry.ts)
    + SIDEBAR_VIEWS array — single source of truth for nested views
    + resolveSidebarView(pathname)
    + getNavGroupsForPath(pathname, t) — back-compat helper for the
      command palette

- config/system-settings.config.ts
    Refactored to export a single SYSTEM_SETTINGS_VIEW (SidebarView)
    with parent `/dashboard/overview` + label `Back to Dashboard`.

- components/sidebar-view-header.tsx (new)
    Renders only the back affordance (chevron + label). Uses the
    default SidebarMenuButton size so its typography matches the
    nav items below; collapses gracefully into icon mode via the
    existing tooltip behavior. The redundant "title + icon" row was
    removed — workspace context is already carried by the nav groups.

- hooks/use-sidebar-view.ts (new)
    Encapsulates view resolution and root-nav filtering:
      · matched view  → returns its nav groups verbatim (route-level
                        beforeLoad guards already enforce access);
      · no match      → returns root nav groups, narrowed by user
                        role (admin gate) and useSidebarConfig
                        (admin × user sidebar_modules overlay).

- components/app-sidebar.tsx
    Now a thin presentation layer: reads { key, view, navGroups }
    from useSidebarView() and orchestrates the view transition via
    AnimatePresence + MOTION_VARIANTS.sidebarSlide (respects
    prefers-reduced-motion). No logic, no role checks, no path
    matching — those live in the hook.

- components/command-menu.tsx
    Switched to the new getNavGroupsForPath() API; behavior preserved.

Cleanup
-------
- Deleted layout/context/workspace-context.tsx (zero consumers).
- Deleted layout/lib/workspace-registry.ts and its
  workspace-registry.example.ts companion (over-abstracted: name/id
  metadata, isInWorkspace / getAllWorkspaces / WORKSPACE_IDS were
  registered but never read).
- Removed `workspaces` field from useSidebarData (never consumed
  after the top-switcher was dropped).
- Dropped WorkspaceProvider from authenticated-layout.tsx.
- Trimmed dead `Manage and configure` translation key from all six
  locale files and from static-keys.ts.

i18n
----
Added the `Back to Dashboard` key to en, zh, fr, ja, ru, vi, and
registered it in static-keys.ts under "Sidebar views".

Verification
------------
- bun run typecheck: passes
- Lint: no new warnings/errors on the touched files
- Adding a new drill-in workspace now only requires registering a
  SidebarView in SIDEBAR_VIEWS — no changes to AppSidebar required.
2026-05-24 22:09:05 +08:00

178 lines
5.4 KiB
TypeScript
Vendored

/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useCallback, useMemo } from 'react'
import { getRouteApi, useNavigate } from '@tanstack/react-router'
import { useTranslation } from 'react-i18next'
import { useSidebarConfig } from '@/hooks/use-sidebar-config'
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { SectionPageLayout } from '@/components/layout'
import type { NavGroup } from '@/components/layout/types'
import { CacheStatsDialog } from '@/features/system-settings/general/channel-affinity/cache-stats-dialog'
import { UserInfoDialog } from './components/dialogs/user-info-dialog'
import {
UsageLogsProvider,
useUsageLogsContext,
} from './components/usage-logs-provider'
import { UsageLogsTable } from './components/usage-logs-table'
import {
isUsageLogsSectionId,
USAGE_LOGS_DEFAULT_SECTION,
type UsageLogsSectionId,
} from './section-registry'
const route = getRouteApi('/_authenticated/usage-logs/$section')
const TASK_LOG_SECTIONS = ['drawing', 'task'] as const
const SECTION_META: Record<
UsageLogsSectionId,
{ titleKey: string; descriptionKey: string }
> = {
common: {
titleKey: 'Common Logs',
descriptionKey: 'View and manage your API usage logs',
},
drawing: {
titleKey: 'Drawing Logs',
descriptionKey: 'View and manage your drawing logs',
},
task: {
titleKey: 'Task Logs',
descriptionKey: 'View and manage your task logs',
},
}
function UsageLogsContent() {
const { t } = useTranslation()
const navigate = useNavigate()
const params = route.useParams()
const activeCategory: UsageLogsSectionId =
params.section && isUsageLogsSectionId(params.section)
? params.section
: USAGE_LOGS_DEFAULT_SECTION
const {
selectedUserId,
userInfoDialogOpen,
setUserInfoDialogOpen,
affinityTarget,
affinityDialogOpen,
setAffinityDialogOpen,
} = useUsageLogsContext()
const tabNavGroups = useMemo<NavGroup[]>(
() => [
{
title: 'Task Logs',
items: TASK_LOG_SECTIONS.map((section) => ({
title: SECTION_META[section].titleKey,
url: `/usage-logs/${section}`,
})),
},
],
[]
)
const filteredTabGroups = useSidebarConfig(tabNavGroups)
const visibleSections = useMemo(
() =>
(filteredTabGroups[0]?.items ?? [])
.map((item) => {
if (!('url' in item) || typeof item.url !== 'string') return null
return item.url.split('/').pop() ?? null
})
.filter((section): section is UsageLogsSectionId =>
Boolean(section && isUsageLogsSectionId(section))
),
[filteredTabGroups]
)
const handleSectionChange = useCallback(
(section: string) => {
void navigate({
to: '/usage-logs/$section',
params: { section: section as UsageLogsSectionId },
})
},
[navigate]
)
const pageMeta =
activeCategory === 'common' ? SECTION_META.common : SECTION_META.task
const showTaskSwitcher =
activeCategory !== 'common' && visibleSections.length > 1
return (
<>
<SectionPageLayout>
<SectionPageLayout.Title>
{t(pageMeta.titleKey)}
</SectionPageLayout.Title>
<SectionPageLayout.Description>
{t(pageMeta.descriptionKey)}
</SectionPageLayout.Description>
<SectionPageLayout.Content>
<div className='space-y-4'>
{showTaskSwitcher && (
<Tabs value={activeCategory} onValueChange={handleSectionChange}>
<TabsList className='max-w-full flex-wrap justify-start group-data-horizontal/tabs:h-auto'>
{visibleSections.map((section) => (
<TabsTrigger key={section} value={section}>
{t(SECTION_META[section].titleKey)}
</TabsTrigger>
))}
</TabsList>
</Tabs>
)}
<UsageLogsTable logCategory={activeCategory} />
</div>
</SectionPageLayout.Content>
</SectionPageLayout>
<UserInfoDialog
userId={selectedUserId}
open={userInfoDialogOpen}
onOpenChange={setUserInfoDialogOpen}
/>
<CacheStatsDialog
open={affinityDialogOpen}
onOpenChange={setAffinityDialogOpen}
target={
affinityTarget
? {
rule_name: affinityTarget.rule_name || '',
using_group:
affinityTarget.using_group ||
affinityTarget.selected_group ||
'',
key_hint: affinityTarget.key_hint || '',
key_fp: affinityTarget.key_fp || '',
}
: null
}
/>
</>
)
}
export function UsageLogs() {
return (
<UsageLogsProvider>
<UsageLogsContent />
</UsageLogsProvider>
)
}