MPM marketplace and UI updates

This commit is contained in:
leon
2026-10-08 21:13:57 +02:00
parent 7b121fa908
commit fd9de823ea
66 changed files with 5187 additions and 749 deletions

View File

@@ -1,10 +1,13 @@
import { type ReactNode, useEffect, useState } from 'react';
import { NavLink, Outlet } from 'react-router-dom';
import { NavLink, Outlet, useLocation } from 'react-router-dom';
import { useAuth } from '../../features/auth/auth-context';
import { ProfilePage } from '../../features/profile/profile-page';
import { ChevronsUpDown } from 'lucide-react';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from '../ui/dropdown-menu';
import { Icon, type IconName } from '../ui/icon';
import { Sidebar, SidebarContent, SidebarFooter, SidebarGroup, SidebarHeader, SidebarInset, SidebarMenu, SidebarMenuButton, SidebarMenuItem, SidebarProvider, SidebarTrigger, useSidebar } from '../ui/sidebar';
import { Switch } from '../ui/switch';
/** Ein Navigationspunkt der Sidebar. */
interface NavItem {
to: string;
label: string;
@@ -24,10 +27,19 @@ function initialDarkMode(): boolean {
return document.documentElement.dataset.theme === 'dark';
}
/** Responsive App-Shell: Sidebar (Desktop) / Overlay-Menü (Mobil). */
/** MPM-Shell mit shadcn Sidebar; bestehende Breiten, Höhen und Innenabstände bleiben erhalten. */
export function AppLayout(): ReactNode {
return (
<SidebarProvider defaultOpen>
<AppLayoutContent />
</SidebarProvider>
);
}
function AppLayoutContent(): ReactNode {
const { user, logout } = useAuth();
const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
const { setOpenMobile, state: sidebarState } = useSidebar();
const location = useLocation();
const [profileOpen, setProfileOpen] = useState(false);
const [darkMode, setDarkMode] = useState(initialDarkMode);
@@ -36,116 +48,118 @@ export function AppLayout(): ReactNode {
localStorage.setItem('mpm-theme', darkMode ? 'dark' : 'light');
}, [darkMode]);
const visibleItems = NAV_ITEMS.filter(
(item) => !item.adminOnly || user?.role === 'ADMIN',
);
const visibleItems = NAV_ITEMS.filter((item) => !item.adminOnly || user?.role === 'ADMIN');
return (
<div className="flex h-full">
{/* Mobile: Overlay-Hintergrund */}
{mobileMenuOpen && (
<div
className="fixed inset-0 z-30 bg-slate-900/50 lg:hidden"
onClick={() => setMobileMenuOpen(false)}
aria-hidden="true"
/>
)}
{/* Sidebar */}
<aside
className={`fixed inset-y-0 left-0 z-40 flex w-64 flex-col border-r border-slate-200 bg-white transition-transform lg:static lg:translate-x-0
${mobileMenuOpen ? 'translate-x-0' : '-translate-x-full'}`}
aria-label="Hauptnavigation"
>
<div className="flex h-16 items-center gap-2 border-b border-slate-200 px-6">
<span className="flex h-8 w-8 items-center justify-center rounded-lg bg-brand-600 text-sm font-bold text-white">
M
</span>
<span className="text-base font-semibold text-slate-900">MPM</span>
</div>
<nav className="flex-1 space-y-1 overflow-y-auto px-3 py-4">
{visibleItems.map((item) => (
<NavLink
key={item.to}
to={item.to}
end={item.to === '/'}
onClick={() => setMobileMenuOpen(false)}
className={({ isActive }) =>
`flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-colors
${
isActive
? 'bg-brand-50 text-brand-700'
: 'text-slate-600 hover:bg-slate-100 hover:text-slate-900'
}`
}
<>
<Sidebar className="border-r border-slate-200 bg-white" collapsible="icon" variant="sidebar">
<SidebarHeader
className="group/sidebar-header relative h-16 flex-row items-center justify-between gap-2 border-b border-slate-200 px-6 py-0"
style={sidebarState === 'collapsed'
? { display: 'grid', gridTemplateColumns: '1fr', placeItems: 'center', paddingInline: 0 }
: undefined}
>
<div
className="flex min-w-0 items-center gap-2 group-data-[collapsible=icon]:hidden"
style={sidebarState === 'collapsed' ? { display: 'none' } : undefined}
>
<span className="flex h-8 w-8 items-center justify-center rounded-lg bg-brand-600 text-sm font-bold text-white">M</span>
<span className="text-base font-semibold text-slate-900">MPM</span>
</div>
<div
style={sidebarState === 'collapsed'
? { display: 'flex', width: '100%', alignItems: 'center', justifyContent: 'center' }
: { display: 'contents' }}
>
<SidebarTrigger
className="hidden h-9 w-9 shrink-0 rounded-lg p-2 text-slate-600 hover:bg-slate-100 md:flex"
aria-label="Sidebar einklappen oder ausklappen"
>
<Icon name={item.icon} className="h-[18px] w-[18px]" />
{item.label}
</NavLink>
))}
</nav>
<div className="flex h-full w-full items-center justify-center">
<Icon name="menu" className="h-5 w-5" />
</div>
</SidebarTrigger>
</div>
</SidebarHeader>
<div className="border-t border-slate-200 p-4">
<button
type="button"
onClick={() => setProfileOpen(true)}
className="group flex w-full min-w-0 items-center gap-3 rounded-xl border border-slate-200 bg-slate-50 px-3 py-3 text-left transition-colors hover:border-brand-300 hover:bg-brand-50"
aria-haspopup="dialog"
aria-label={`Profileinstellungen für ${user?.displayName ?? 'Benutzer'} öffnen`}
>
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border border-slate-200 bg-white text-slate-600">
<Icon name="user" className="h-[18px] w-[18px]" />
</span>
<span className="min-w-0 flex-1 truncate text-sm font-medium text-slate-900 group-hover:text-brand-700">
{user?.displayName}
</span>
<Icon name="arrow" className="h-4 w-4 shrink-0 text-slate-400 transition-transform group-hover:translate-x-0.5" />
</button>
<button
onClick={() => void logout()}
className="mt-3 w-full rounded-lg px-3 py-2 text-sm font-medium text-slate-600 transition-colors hover:bg-slate-100 hover:text-slate-900"
>
Abmelden
</button>
</div>
</aside>
<SidebarContent className="flex-1 overflow-y-auto px-3 py-4 group-data-[collapsible=icon]:px-0">
<SidebarGroup className="p-0">
<SidebarMenu className="gap-1">
{visibleItems.map((item) => {
const isActive = item.to === '/' ? location.pathname === '/' : location.pathname.startsWith(item.to);
return (
<SidebarMenuItem key={item.to}>
<SidebarMenuButton
asChild
isActive={isActive}
className={`h-auto gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-colors data-[active=true]:bg-brand-50 data-[active=true]:text-brand-700 group-data-[collapsible=icon]:mx-auto ${isActive ? '' : 'text-slate-600 hover:bg-slate-100 hover:text-slate-900'}`}
>
<NavLink to={item.to} end={item.to === '/'} onClick={() => setOpenMobile(false)}>
<Icon name={item.icon} className="h-[18px] w-[18px]" />
<span>{item.label}</span>
</NavLink>
</SidebarMenuButton>
</SidebarMenuItem>
);
})}
</SidebarMenu>
</SidebarGroup>
</SidebarContent>
{/* Hauptbereich */}
<div className="flex min-w-0 flex-1 flex-col">
{/* Topbar (mobil: Menü-Button) */}
<header className="flex h-16 items-center justify-between border-b border-slate-200 bg-white px-4 lg:px-6">
<button
className="rounded-lg p-2 text-slate-600 hover:bg-slate-100 lg:hidden"
onClick={() => setMobileMenuOpen((open) => !open)}
aria-label="Menü öffnen"
aria-expanded={mobileMenuOpen}
>
<SidebarFooter className="border-t border-slate-200 p-3 group-data-[collapsible=icon]:p-1">
<SidebarMenu>
<SidebarMenuItem>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<SidebarMenuButton
size="lg"
className="h-auto min-h-16 gap-3 rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 hover:border-brand-300 hover:bg-brand-50 data-[state=open]:bg-brand-50 group-data-[collapsible=icon]:size-10! group-data-[collapsible=icon]:min-h-10! group-data-[collapsible=icon]:p-1!"
aria-label="Benutzermenü öffnen"
>
<span className="flex size-10 shrink-0 items-center justify-center rounded-full bg-brand-600 text-sm font-semibold text-white">
{(user?.displayName ?? user?.username ?? 'U').trim().charAt(0).toUpperCase()}
</span>
<span className="grid min-w-0 flex-1 text-left leading-tight group-data-[collapsible=icon]:hidden">
<span className="truncate text-sm font-medium text-slate-900">{user?.displayName ?? user?.username}</span>
<span className="truncate text-xs text-slate-500">{user?.email}</span>
</span>
<ChevronsUpDown className="ml-auto size-4 shrink-0 text-slate-500 group-data-[collapsible=icon]:hidden" />
</SidebarMenuButton>
</DropdownMenuTrigger>
<DropdownMenuContent side="right" align="start" sideOffset={8} className="w-56">
<DropdownMenuItem onSelect={() => setProfileOpen(true)}>
<Icon name="user" className="size-4" />
Profileinstellungen
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem onSelect={() => void logout()}>
<Icon name="arrow" className="size-4" />
Abmelden
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</SidebarMenuItem>
</SidebarMenu>
</SidebarFooter>
</Sidebar>
<SidebarInset className="h-full min-w-0 flex-1 flex-col bg-transparent">
<header className="flex h-16 items-center border-b border-slate-200 bg-white px-4 lg:px-6">
<SidebarTrigger className="mr-auto h-9 w-9 rounded-lg p-2 text-slate-600 hover:bg-slate-100 md:hidden" aria-label="Menü öffnen">
<Icon name="menu" className="h-5 w-5" />
</button>
<span className="hidden text-sm text-slate-500 lg:block">Management-Plattform</span>
<span className="text-sm text-slate-500 lg:hidden">MPM</span>
<button
type="button"
role="switch"
aria-checked={darkMode}
aria-label="Darkmode"
onClick={() => setDarkMode((current) => !current)}
className="inline-flex h-9 items-center gap-2 rounded-lg border border-slate-200 px-3 text-sm text-slate-600 transition-colors hover:bg-slate-100"
>
</SidebarTrigger>
<div className="ml-auto inline-flex h-9 items-center gap-2 rounded-lg border border-slate-200 px-3 text-sm text-slate-600 transition-colors hover:bg-slate-100">
<Icon name={darkMode ? 'sun' : 'moon'} className="h-4 w-4" />
<span>{darkMode ? 'Hell' : 'Dunkel'}</span>
<span className={`relative h-5 w-9 rounded-full transition-colors ${darkMode ? 'bg-brand-600' : 'bg-slate-300'}`}>
<span className={`absolute top-0.5 h-4 w-4 rounded-full bg-white transition-transform ${darkMode ? 'translate-x-4' : 'translate-x-0.5'}`} />
</span>
</button>
<Switch checked={darkMode} onCheckedChange={setDarkMode} aria-label="Darkmode" />
</div>
</header>
<main className="flex-1 overflow-y-auto p-4 lg:p-8">
<Outlet />
</main>
</div>
</SidebarInset>
{profileOpen && <ProfilePage onClose={() => setProfileOpen(false)} />}
</div>
</>
);
}

View File

@@ -1,29 +1,26 @@
import { type ReactNode } from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { type HTMLAttributes, type ReactNode } from 'react';
import { cn } from '../../lib/utils';
/** Farbschemata für Badges (Statusanzeigen). */
export type BadgeVariant = 'success' | 'warning' | 'danger' | 'neutral' | 'info';
const badgeVariants = cva('inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ring-1 ring-inset', {
variants: {
variant: {
success: 'bg-emerald-50 text-emerald-700 ring-emerald-600/20',
warning: 'bg-amber-50 text-amber-700 ring-amber-600/20',
danger: 'bg-red-50 text-red-700 ring-red-600/20',
neutral: 'bg-slate-100 text-slate-600 ring-slate-500/20',
info: 'bg-brand-50 text-brand-700 ring-brand-600/20',
},
},
defaultVariants: { variant: 'neutral' },
});
const VARIANT_CLASSES: Record<BadgeVariant, string> = {
success: 'bg-emerald-50 text-emerald-700 ring-emerald-600/20',
warning: 'bg-amber-50 text-amber-700 ring-amber-600/20',
danger: 'bg-red-50 text-red-700 ring-red-600/20',
neutral: 'bg-slate-100 text-slate-600 ring-slate-500/20',
info: 'bg-brand-50 text-brand-700 ring-brand-600/20',
};
export type BadgeVariant = NonNullable<VariantProps<typeof badgeVariants>['variant']>;
export interface BadgeProps extends HTMLAttributes<HTMLSpanElement>, VariantProps<typeof badgeVariants> { children: ReactNode }
export interface BadgeProps {
variant?: BadgeVariant;
children: ReactNode;
/** shadcn/ui Badge mit den bisherigen MPM-Statusvarianten. */
export function Badge({ variant = 'neutral', children, className, ...rest }: BadgeProps): ReactNode {
return <span className={cn(badgeVariants({ variant }), className)} {...rest}>{children}</span>;
}
/** Kleines Status-Label (Design-System). */
export function Badge({ variant = 'neutral', children }: BadgeProps): ReactNode {
return (
<span
className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ring-1 ring-inset
${VARIANT_CLASSES[variant]}`}
>
{children}
</span>
);
}
export { badgeVariants };

View File

@@ -1,58 +1,52 @@
import { Slot } from 'radix-ui';
import { cva, type VariantProps } from 'class-variance-authority';
import { type ButtonHTMLAttributes, type ReactNode } from 'react';
import { cn } from '../../lib/utils';
/** Varianten des Buttons (Design-System). */
export type ButtonVariant = 'primary' | 'secondary' | 'danger' | 'ghost';
export type ButtonSize = 'sm' | 'md' | 'lg';
const buttonVariants = cva(
'inline-flex shrink-0 items-center justify-center gap-2 rounded-lg font-medium transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 disabled:cursor-not-allowed disabled:opacity-50',
{
variants: {
variant: {
default: 'bg-brand-600 text-white hover:bg-brand-700 active:bg-brand-800',
primary: 'bg-brand-600 text-white hover:bg-brand-700 active:bg-brand-800 disabled:bg-slate-300',
secondary: 'border border-slate-300 bg-white text-slate-700 hover:bg-slate-50 active:bg-slate-100 disabled:text-slate-400',
outline: 'border border-slate-300 bg-white text-slate-700 hover:bg-slate-50 active:bg-slate-100',
destructive: 'bg-red-600 text-white hover:bg-red-700 active:bg-red-800',
danger: 'bg-red-600 text-white hover:bg-red-700 active:bg-red-800 disabled:bg-slate-300',
ghost: 'bg-transparent text-slate-600 hover:bg-slate-100 active:bg-slate-200 disabled:text-slate-400',
link: 'text-brand-600 underline-offset-4 hover:underline',
},
size: {
xs: 'h-6 rounded-md px-2 text-xs',
sm: 'h-8 px-3 text-sm',
md: 'h-10 px-4 text-sm',
default: 'h-9 px-4 text-sm',
lg: 'h-11 px-5 text-base',
icon: 'size-9 p-0',
},
},
defaultVariants: { variant: 'primary', size: 'md' },
},
);
const VARIANT_CLASSES: Record<ButtonVariant, string> = {
primary:
'bg-brand-600 text-white hover:bg-brand-700 active:bg-brand-800 disabled:bg-slate-300',
secondary:
'bg-white text-slate-700 border border-slate-300 hover:bg-slate-50 active:bg-slate-100 disabled:text-slate-400',
danger:
'bg-red-600 text-white hover:bg-red-700 active:bg-red-800 disabled:bg-slate-300',
ghost:
'bg-transparent text-slate-600 hover:bg-slate-100 active:bg-slate-200 disabled:text-slate-400',
};
const SIZE_CLASSES: Record<ButtonSize, string> = {
sm: 'h-8 px-3 text-sm',
md: 'h-10 px-4 text-sm',
lg: 'h-11 px-5 text-base',
};
export interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
variant?: ButtonVariant;
size?: ButtonSize;
export type ButtonVariant = NonNullable<VariantProps<typeof buttonVariants>['variant']>;
export type ButtonSize = NonNullable<VariantProps<typeof buttonVariants>['size']>;
export interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement>, VariantProps<typeof buttonVariants> {
loading?: boolean;
asChild?: boolean;
children: ReactNode;
}
/** Standard-Button des Design-Systems. */
export function Button({
variant = 'primary',
size = 'md',
loading = false,
className = '',
disabled,
children,
...rest
}: ButtonProps): ReactNode {
/** shadcn/ui Button mit MPM-Varianten und bestehenden Abmessungen. */
export function Button({ variant = 'primary', size = 'md', loading = false, asChild = false, className, disabled, children, ...rest }: ButtonProps): ReactNode {
const Comp = asChild ? Slot.Root : 'button';
return (
<button
className={`inline-flex items-center justify-center gap-2 rounded-lg font-medium transition-colors
focus-visible:outline-2 focus-visible:outline-offset-2 disabled:cursor-not-allowed
${VARIANT_CLASSES[variant]} ${SIZE_CLASSES[size]} ${className}`}
disabled={disabled || loading}
{...rest}
>
{loading && (
<span
aria-hidden="true"
className="h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"
/>
)}
<Comp data-slot="button" className={cn(buttonVariants({ variant, size }), className)} disabled={disabled || loading} {...rest}>
{loading && <span aria-hidden="true" className="h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent" />}
{children}
</button>
</Comp>
);
}
}
export { buttonVariants };

View File

@@ -1,46 +1,33 @@
import { type ReactNode } from 'react';
import { type ComponentProps, type ReactNode } from 'react';
import { Slot } from 'radix-ui';
import { cn } from '../../lib/utils';
export interface CardProps {
children: ReactNode;
className?: string;
/** shadcn/ui Card primitives; MPM classes preserve the established card geometry. */
export function Card({ asChild = false, className, ...props }: ComponentProps<'div'> & { asChild?: boolean }): ReactNode {
const Comp = asChild ? Slot.Root : 'div';
return <Comp data-slot="card" className={cn('flex flex-col rounded-2xl border border-slate-200 bg-white text-slate-900 shadow-sm', className)} {...props} />;
}
/** Karten-Container des Design-Systems. */
export function Card({ children, className = '' }: CardProps): ReactNode {
return (
<div
className={`rounded-2xl border border-slate-200 bg-white shadow-sm ${className}`}
>
{children}
</div>
);
export function CardHeader({ className, ...props }: ComponentProps<'div'>): ReactNode {
return <div data-slot="card-header" className={cn('flex items-start justify-between gap-4 border-b border-slate-200 px-5 py-4', className)} {...props} />;
}
export interface CardHeaderProps {
title: string;
description?: string;
children?: ReactNode;
export function CardTitle({ className, ...props }: ComponentProps<'h2'>): ReactNode {
return <h2 data-slot="card-title" className={cn('text-base font-semibold text-slate-900', className)} {...props} />;
}
/** Karten-Kopf mit Titel, Beschreibung und optionalen Aktionen. */
export function CardHeader({ title, description, children }: CardHeaderProps): ReactNode {
return (
<div className="flex items-start justify-between gap-4 border-b border-slate-200 px-5 py-4">
<div>
<h2 className="text-base font-semibold text-slate-900">{title}</h2>
{description && <p className="mt-0.5 text-sm text-slate-500">{description}</p>}
</div>
{children}
</div>
);
export function CardDescription({ className, ...props }: ComponentProps<'p'>): ReactNode {
return <p data-slot="card-description" className={cn('mt-0.5 text-sm text-slate-500', className)} {...props} />;
}
export interface CardBodyProps {
children: ReactNode;
className?: string;
export function CardAction({ className, ...props }: ComponentProps<'div'>): ReactNode {
return <div data-slot="card-action" className={cn('shrink-0', className)} {...props} />;
}
/** Karten-Inhalt. */
export function CardBody({ children, className = '' }: CardBodyProps): ReactNode {
return <div className={`px-5 py-5 ${className}`}>{children}</div>;
export function CardContent({ className, ...props }: ComponentProps<'div'>): ReactNode {
return <div data-slot="card-content" className={cn('px-5 py-5', className)} {...props} />;
}
export function CardFooter({ className, ...props }: ComponentProps<'div'>): ReactNode {
return <div data-slot="card-footer" className={cn('flex items-center border-t border-slate-200 px-5 py-4', className)} {...props} />;
}

View File

@@ -0,0 +1,18 @@
import { Checkbox as CheckboxPrimitive } from 'radix-ui';
import { Check } from 'lucide-react';
import { type ComponentProps, type ReactNode } from 'react';
import { cn } from '../../lib/utils';
export type CheckboxProps = ComponentProps<typeof CheckboxPrimitive.Root>;
export function Checkbox({ className, ...props }: CheckboxProps): ReactNode {
return (
<CheckboxPrimitive.Root
className={cn('peer h-4 w-4 shrink-0 rounded-[4px] border border-slate-300 bg-white text-white shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-500 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:border-brand-600 data-[state=checked]:bg-brand-600', className)}
{...props}
>
<CheckboxPrimitive.Indicator className="flex items-center justify-center">
<Check className="h-3 w-3" strokeWidth={3} />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
);
}

View File

@@ -0,0 +1,156 @@
import * as React from "react"
import { cn } from "@/lib/utils"
import { XIcon } from "lucide-react"
import { Dialog as DialogPrimitive } from "radix-ui"
import { Button } from "@/components/ui/button"
function Dialog({
...props
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
}
function DialogTrigger({
...props
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
}
function DialogPortal({
...props
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
}
function DialogClose({
...props
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
}
function DialogOverlay({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
return (
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
"fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",
className
)}
{...props}
/>
)
}
function DialogContent({
className,
children,
showCloseButton = true,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean
}) {
return (
<DialogPortal data-slot="dialog-portal">
<DialogOverlay className="bg-slate-900/50" />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
"fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
className="absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
>
<XIcon />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</DialogPortal>
)
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
)
}
function DialogFooter({
className,
showCloseButton = false,
children,
...props
}: React.ComponentProps<"div"> & {
showCloseButton?: boolean
}) {
return (
<div
data-slot="dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close asChild>
<Button variant="outline">Close</Button>
</DialogPrimitive.Close>
)}
</div>
)
}
function DialogTitle({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn("text-lg leading-none font-semibold", className)}
{...props}
/>
)
}
function DialogDescription({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
)
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
}

View File

@@ -0,0 +1,53 @@
import * as React from 'react';
import { DropdownMenu as DropdownMenuPrimitive } from 'radix-ui';
import { cn } from '../../lib/utils';
const DropdownMenu = DropdownMenuPrimitive.Root;
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger;
const DropdownMenuContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
'z-50 min-w-32 overflow-hidden rounded-md border border-slate-200 bg-white p-1 text-slate-900 shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
className,
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
));
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName;
const DropdownMenuItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.Item
ref={ref}
className={cn(
'relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-slate-100 focus:text-slate-900 data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
className,
)}
{...props}
/>
));
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName;
const DropdownMenuSeparator = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.Separator
ref={ref}
className={cn('-mx-1 my-1 h-px bg-slate-200', className)}
{...props}
/>
));
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName;
export { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger };

View File

@@ -1,36 +1,40 @@
import {
ArrowRight,
Boxes,
Check,
ClipboardList,
Clock3,
LayoutDashboard,
Menu,
Moon,
Plus,
Sun,
UserRound,
UsersRound,
X,
type LucideIcon,
} from 'lucide-react';
import { type ReactNode } from 'react';
export type IconName = 'dashboard' | 'users' | 'modules' | 'system' | 'audit' | 'moon' | 'sun' | 'user' | 'arrow' | 'close' | 'menu' | 'plus' | 'check';
const PATHS: Record<IconName, ReactNode> = {
dashboard: <><rect x="3" y="3" width="7" height="7" rx="1.5" /><rect x="14" y="3" width="7" height="7" rx="1.5" /><rect x="3" y="14" width="7" height="7" rx="1.5" /><rect x="14" y="14" width="7" height="7" rx="1.5" /></>,
users: <><path d="M16 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" /><circle cx="10" cy="7" r="4" /><path d="M20 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75" /></>,
modules: <><rect x="3" y="3" width="8" height="8" rx="2" /><rect x="13" y="3" width="8" height="5" rx="2" /><rect x="13" y="10" width="8" height="11" rx="2" /><rect x="3" y="13" width="8" height="8" rx="2" /></>,
system: <><path d="M12 8v4l2.5 2.5" /><circle cx="12" cy="12" r="9" /><path d="M12 3v2m9 7h-2M5 12H3m9 9v-2" /></>,
audit: <><path d="M8 4h10a2 2 0 0 1 2 2v14H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2Z" /><path d="M8 2v4m0 4h8m-8 4h8m-8 4h5" /></>,
moon: <path d="M20.9 13A9 9 0 0 1 11 3.1 9 9 0 1 0 20.9 13Z" />,
sun: <><circle cx="12" cy="12" r="4" /><path d="M12 2v2m0 16v2M4.93 4.93l1.42 1.42m11.3 11.3 1.42 1.42M2 12h2m16 0h2M4.93 19.07l1.42-1.42m11.3-11.3 1.42-1.42" /></>,
user: <><circle cx="12" cy="8" r="4" /><path d="M5 21a7 7 0 0 1 14 0" /></>,
arrow: <><path d="M5 12h14m-6-6 6 6-6 6" /></>,
close: <><path d="m18 6-12 12M6 6l12 12" /></>,
menu: <><path d="M4 6h16M4 12h16M4 18h16" /></>,
plus: <path d="M12 5v14M5 12h14" />,
check: <path d="m5 12 4 4L19 6" />,
const ICONS: Record<IconName, LucideIcon> = {
dashboard: LayoutDashboard,
users: UsersRound,
modules: Boxes,
system: Clock3,
audit: ClipboardList,
moon: Moon,
sun: Sun,
user: UserRound,
arrow: ArrowRight,
close: X,
menu: Menu,
plus: Plus,
check: Check,
};
/** Lucide-Symbole im bestehenden MPM-Icon-API. */
export function Icon({ name, className = 'h-5 w-5' }: { name: IconName; className?: string }): ReactNode {
return (
<svg
aria-hidden="true"
className={className}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.8"
strokeLinecap="round"
strokeLinejoin="round"
>
{PATHS[name]}
</svg>
);
const Component = ICONS[name];
return <Component aria-hidden="true" className={className} strokeWidth={1.8} />;
}

View File

@@ -1,4 +1,6 @@
import { type InputHTMLAttributes, type ReactNode } from 'react';
import { forwardRef, type InputHTMLAttributes, type ReactNode } from 'react';
import { cn } from '../../lib/utils';
import { Label } from './label';
export interface InputProps extends InputHTMLAttributes<HTMLInputElement> {
label: string;
@@ -6,46 +8,42 @@ export interface InputProps extends InputHTMLAttributes<HTMLInputElement> {
hint?: string;
}
/** Text-Input mit Label, Fehler- und Hinweistext (Design-System). */
export function Input({
label,
error,
hint,
className = '',
id,
...rest
}: InputProps): ReactNode {
/** Basis-Input für Formulare, die ihr Label separat rendern. */
export const InputControl = forwardRef<HTMLInputElement, InputHTMLAttributes<HTMLInputElement>>(
function InputControl({ className, ...rest }, ref) {
return (
<input
ref={ref}
data-slot="input"
className={cn(
'h-10 w-full min-w-0 rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm shadow-sm transition-[color,box-shadow] outline-none placeholder:text-slate-400 selection:bg-brand-600 selection:text-white focus-visible:border-brand-500 focus-visible:ring-2 focus-visible:ring-brand-500/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50',
className,
)}
{...rest}
/>
);
},
);
/** shadcn/ui Input mit MPM-Label und Fehlertext. */
export function Input({ label, error, hint, className, id, ...rest }: InputProps): ReactNode {
const inputId = id ?? `input-${label.toLowerCase().replace(/\s+/g, '-')}`;
const describedBy = error ? `${inputId}-error` : hint ? `${inputId}-hint` : undefined;
return (
<div className="flex flex-col gap-1.5">
<label htmlFor={inputId} className="text-sm font-medium text-slate-700">
{label}
</label>
<input
<Label htmlFor={inputId}>{label}</Label>
<InputControl
id={inputId}
className={`h-10 rounded-lg border px-3 text-sm transition-colors
${
error
? 'border-red-400 focus:border-red-500'
: 'border-slate-300 focus:border-brand-500'
}
${className}`}
className={cn(
error ? 'border-red-400 focus:border-red-500' : 'border-slate-300 focus:border-brand-500',
className,
)}
aria-invalid={error ? true : undefined}
aria-describedby={describedBy}
{...rest}
/>
{hint && !error && (
<p id={`${inputId}-hint`} className="text-xs text-slate-500">
{hint}
</p>
)}
{error && (
<p id={`${inputId}-error`} role="alert" className="text-xs text-red-600">
{error}
</p>
)}
{hint && !error && <p id={`${inputId}-hint`} className="text-xs text-slate-500">{hint}</p>}
{error && <p id={`${inputId}-error`} role="alert" className="text-xs text-red-600">{error}</p>}
</div>
);
}
}

View File

@@ -0,0 +1,7 @@
import { Label as LabelPrimitive } from 'radix-ui';
import { type ComponentProps, type ReactNode } from 'react';
import { cn } from '../../lib/utils';
export function Label({ className, ...props }: ComponentProps<typeof LabelPrimitive.Root>): ReactNode {
return <LabelPrimitive.Root className={cn('text-sm font-medium text-slate-700', className)} {...props} />;
}

View File

@@ -1,4 +1,8 @@
import { type ReactNode, useEffect } from 'react';
import { X } from 'lucide-react';
import { type ReactNode } from 'react';
import { cn } from '../../lib/utils';
import { Button } from './button';
import { Dialog, DialogClose, DialogContent, DialogDescription, DialogTitle } from './dialog';
export interface ModalProps {
open: boolean;
@@ -11,56 +15,35 @@ export interface ModalProps {
hideHeader?: boolean;
}
/** Zugängliches Modal (Design-System): Fokus-Falle, ESC schließt. */
export function Modal({
open,
title,
description,
onClose,
children,
footer,
panelClassName = 'max-w-md',
hideHeader = false,
}: ModalProps): ReactNode {
useEffect(() => {
if (!open) {
return undefined;
}
const handleKeyDown = (event: KeyboardEvent): void => {
if (event.key === 'Escape') {
onClose();
}
};
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}, [open, onClose]);
if (!open) {
return null;
}
/** Kompatibler MPM-Wrapper auf den shadcn/ui Dialog-Komponenten. */
export function Modal({ open, title, description, onClose, children, footer, panelClassName = 'max-w-md', hideHeader = false }: ModalProps): ReactNode {
return (
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4"
onClick={onClose}
role="presentation"
>
<div
role="dialog"
aria-modal="true"
aria-label={title}
className={`w-full rounded-xl bg-white shadow-xl ${panelClassName}`}
onClick={(event) => event.stopPropagation()}
<Dialog open={open} onOpenChange={(nextOpen) => { if (!nextOpen) onClose(); }}>
<DialogContent
showCloseButton={false}
className={cn('w-[calc(100%-2rem)] max-w-none gap-0 rounded-xl border-0 bg-white p-0 shadow-xl', panelClassName)}
>
{!hideHeader && (
<div className="border-b border-slate-200 px-6 py-4">
<h2 className="text-base font-semibold text-slate-900">{title}</h2>
{description && <p className="mt-0.5 text-sm text-slate-500">{description}</p>}
{hideHeader ? (
<>
<DialogTitle className="sr-only">{title}</DialogTitle>
{description && <DialogDescription className="sr-only">{description}</DialogDescription>}
</>
) : (
<div className="flex items-start justify-between gap-4 border-b border-slate-200 px-6 py-4">
<div className="min-w-0">
<DialogTitle className="text-base font-semibold text-slate-900">{title}</DialogTitle>
{description && <DialogDescription className="mt-0.5 text-sm text-slate-500">{description}</DialogDescription>}
</div>
<DialogClose asChild>
<Button variant="ghost" size="icon" aria-label="Dialog schließen" className="-mr-2 -mt-1 h-8 w-8 rounded-full text-slate-500 hover:bg-slate-100 hover:text-slate-900">
<X className="h-4 w-4" aria-hidden="true" />
</Button>
</DialogClose>
</div>
)}
<div className="px-6 py-4">{children}</div>
{footer && <div className="border-t border-slate-200 px-6 py-4">{footer}</div>}
</div>
</div>
</DialogContent>
</Dialog>
);
}

View File

@@ -1,50 +1,62 @@
import { type ReactNode, type SelectHTMLAttributes } from 'react';
import { Select as SelectPrimitive } from 'radix-ui';
import { Check, ChevronDown } from 'lucide-react';
import { type ReactNode } from 'react';
import { cn } from '../../lib/utils';
import { Label } from './label';
export interface SelectProps extends SelectHTMLAttributes<HTMLSelectElement> {
export interface SelectProps {
label: string;
error?: string;
options: ReadonlyArray<{ value: string; label: string }>;
placeholder?: string;
id?: string;
name?: string;
required?: boolean;
disabled?: boolean;
value?: string;
defaultValue?: string;
onValueChange?: (value: string) => void;
}
export type SelectControlProps = Omit<SelectProps, 'label' | 'error' | 'id'> & { id?: string; className?: string; invalid?: boolean };
export function SelectControl({ options, placeholder, id, className, invalid, ...rootProps }: SelectControlProps): ReactNode {
return (
<SelectPrimitive.Root {...rootProps}>
<SelectPrimitive.Trigger
id={id}
aria-invalid={invalid ? true : undefined}
className={cn(
'flex h-10 w-full items-center justify-between rounded-lg border bg-white px-3 text-left text-sm transition-colors focus:outline-none focus:ring-2 focus:ring-brand-500 disabled:cursor-not-allowed disabled:opacity-50',
invalid ? 'border-red-400' : 'border-slate-300',
className,
)}
>
<SelectPrimitive.Value placeholder={placeholder} />
<SelectPrimitive.Icon asChild><ChevronDown className="h-4 w-4 opacity-50" /></SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
<SelectPrimitive.Portal>
<SelectPrimitive.Content position="popper" sideOffset={4} className="z-[60] max-h-60 min-w-[var(--radix-select-trigger-width)] overflow-hidden rounded-lg border border-slate-200 bg-white p-1 text-slate-900 shadow-md">
<SelectPrimitive.Viewport>
{options.map((option) => (
<SelectPrimitive.Item key={option.value} value={option.value} className="relative flex cursor-default select-none items-center rounded-md py-2 pl-8 pr-2 text-sm outline-none focus:bg-slate-100 data-[disabled]:pointer-events-none data-[disabled]:opacity-50">
<span className="absolute left-2 flex h-4 w-4 items-center justify-center"><SelectPrimitive.ItemIndicator><Check className="h-4 w-4" /></SelectPrimitive.ItemIndicator></span>
<SelectPrimitive.ItemText>{option.label}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
))}
</SelectPrimitive.Viewport>
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
</SelectPrimitive.Root>
);
}
/** Select-Dropdown mit Label (Design-System). */
export function Select({
label,
error,
options,
className = '',
id,
...rest
}: SelectProps): ReactNode {
export function Select({ label, error, options, placeholder, id, ...props }: SelectProps): ReactNode {
const selectId = id ?? `select-${label.toLowerCase().replace(/\s+/g, '-')}`;
return (
<div className="flex flex-col gap-1.5">
<label htmlFor={selectId} className="text-sm font-medium text-slate-700">
{label}
</label>
<select
id={selectId}
className={`h-10 rounded-lg border bg-white px-3 text-sm transition-colors
${
error
? 'border-red-400 focus:border-red-500'
: 'border-slate-300 focus:border-brand-500'
}
${className}`}
aria-invalid={error ? true : undefined}
{...rest}
>
{options.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
{error && (
<p role="alert" className="text-xs text-red-600">
{error}
</p>
)}
<Label htmlFor={selectId}>{label}</Label>
<SelectControl id={selectId} options={options} placeholder={placeholder} invalid={Boolean(error)} {...props} />
{error && <p role="alert" className="text-xs text-red-600">{error}</p>}
</div>
);
}
}

View File

@@ -0,0 +1,25 @@
import * as React from "react"
import { cn } from "@/lib/utils"
import { Separator as SeparatorPrimitive } from "radix-ui"
function Separator({
className,
orientation = "horizontal",
decorative = true,
...props
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
return (
<SeparatorPrimitive.Root
data-slot="separator"
decorative={decorative}
orientation={orientation}
className={cn(
"shrink-0 bg-border data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
className
)}
{...props}
/>
)
}
export { Separator }

View File

@@ -0,0 +1,142 @@
"use client"
import * as React from "react"
import { cn } from "@/lib/utils"
import { XIcon } from "lucide-react"
import { Dialog as SheetPrimitive } from "radix-ui"
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
return <SheetPrimitive.Root data-slot="sheet" {...props} />
}
function SheetTrigger({
...props
}: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />
}
function SheetClose({
...props
}: React.ComponentProps<typeof SheetPrimitive.Close>) {
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />
}
function SheetPortal({
...props
}: React.ComponentProps<typeof SheetPrimitive.Portal>) {
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />
}
function SheetOverlay({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Overlay>) {
return (
<SheetPrimitive.Overlay
data-slot="sheet-overlay"
className={cn(
"fixed inset-0 z-50 bg-slate-900/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",
className
)}
{...props}
/>
)
}
function SheetContent({
className,
children,
side = "right",
showCloseButton = true,
...props
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
side?: "top" | "right" | "bottom" | "left"
showCloseButton?: boolean
}) {
return (
<SheetPortal>
<SheetOverlay />
<SheetPrimitive.Content
data-slot="sheet-content"
className={cn(
"fixed z-50 flex flex-col gap-4 bg-background shadow-lg transition ease-in-out data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:animate-in data-[state=open]:duration-500",
side === "right" &&
"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm",
side === "left" &&
"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",
side === "top" &&
"inset-x-0 top-0 h-auto border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",
side === "bottom" &&
"inset-x-0 bottom-0 h-auto border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",
className
)}
{...props}
>
{children}
{showCloseButton && (
<SheetPrimitive.Close className="absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-secondary">
<XIcon className="size-4" />
<span className="sr-only">Close</span>
</SheetPrimitive.Close>
)}
</SheetPrimitive.Content>
</SheetPortal>
)
}
function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sheet-header"
className={cn("flex flex-col gap-1.5 p-4", className)}
{...props}
/>
)
}
function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sheet-footer"
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
{...props}
/>
)
}
function SheetTitle({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Title>) {
return (
<SheetPrimitive.Title
data-slot="sheet-title"
className={cn("font-semibold text-foreground", className)}
{...props}
/>
)
}
function SheetDescription({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Description>) {
return (
<SheetPrimitive.Description
data-slot="sheet-description"
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
)
}
export {
Sheet,
SheetTrigger,
SheetClose,
SheetContent,
SheetHeader,
SheetFooter,
SheetTitle,
SheetDescription,
}

View File

@@ -0,0 +1,727 @@
"use client"
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { PanelLeftIcon } from "lucide-react"
import { Slot } from "radix-ui"
import { useIsMobile } from "@/hooks/use-mobile"
import { Button } from "@/components/ui/button"
import { InputControl as Input } from "@/components/ui/input"
import { Separator } from "@/components/ui/separator"
import {
Sheet,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle,
} from "@/components/ui/sheet"
import { Skeleton } from "@/components/ui/skeleton"
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip"
const SIDEBAR_COOKIE_NAME = "sidebar_state"
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
const SIDEBAR_WIDTH = "16rem"
const SIDEBAR_WIDTH_MOBILE = "16rem"
const SIDEBAR_WIDTH_ICON = "3rem"
const SIDEBAR_KEYBOARD_SHORTCUT = "b"
type SidebarContextProps = {
state: "expanded" | "collapsed"
open: boolean
setOpen: (open: boolean) => void
openMobile: boolean
setOpenMobile: (open: boolean) => void
isMobile: boolean
toggleSidebar: () => void
}
const SidebarContext = React.createContext<SidebarContextProps | null>(null)
function useSidebar() {
const context = React.useContext(SidebarContext)
if (!context) {
throw new Error("useSidebar must be used within a SidebarProvider.")
}
return context
}
function SidebarProvider({
defaultOpen = true,
open: openProp,
onOpenChange: setOpenProp,
className,
style,
children,
...props
}: React.ComponentProps<"div"> & {
defaultOpen?: boolean
open?: boolean
onOpenChange?: (open: boolean) => void
}) {
const isMobile = useIsMobile()
const [openMobile, setOpenMobile] = React.useState(false)
// This is the internal state of the sidebar.
// We use openProp and setOpenProp for control from outside the component.
const [_open, _setOpen] = React.useState(defaultOpen)
const open = openProp ?? _open
const setOpen = React.useCallback(
(value: boolean | ((value: boolean) => boolean)) => {
const openState = typeof value === "function" ? value(open) : value
if (setOpenProp) {
setOpenProp(openState)
} else {
_setOpen(openState)
}
// This sets the cookie to keep the sidebar state.
document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`
},
[setOpenProp, open]
)
// Helper to toggle the sidebar.
const toggleSidebar = React.useCallback(() => {
return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open)
}, [isMobile, setOpen, setOpenMobile])
// Adds a keyboard shortcut to toggle the sidebar.
React.useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (
event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
(event.metaKey || event.ctrlKey)
) {
event.preventDefault()
toggleSidebar()
}
}
window.addEventListener("keydown", handleKeyDown)
return () => window.removeEventListener("keydown", handleKeyDown)
}, [toggleSidebar])
// We add a state so that we can do data-state="expanded" or "collapsed".
// This makes it easier to style the sidebar with Tailwind classes.
const state = open ? "expanded" : "collapsed"
const contextValue = React.useMemo<SidebarContextProps>(
() => ({
state,
open,
setOpen,
isMobile,
openMobile,
setOpenMobile,
toggleSidebar,
}),
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar]
)
return (
<SidebarContext.Provider value={contextValue}>
<TooltipProvider delayDuration={0}>
<div
data-slot="sidebar-wrapper"
style={
{
"--sidebar-width": SIDEBAR_WIDTH,
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
...style,
} as React.CSSProperties
}
className={cn(
"group/sidebar-wrapper flex min-h-svh w-full has-data-[variant=inset]:bg-sidebar",
className
)}
{...props}
>
{children}
</div>
</TooltipProvider>
</SidebarContext.Provider>
)
}
function Sidebar({
side = "left",
variant = "sidebar",
collapsible = "offcanvas",
className,
children,
...props
}: React.ComponentProps<"div"> & {
side?: "left" | "right"
variant?: "sidebar" | "floating" | "inset"
collapsible?: "offcanvas" | "icon" | "none"
}) {
const { isMobile, state, openMobile, setOpenMobile } = useSidebar()
if (collapsible === "none") {
return (
<div
data-slot="sidebar"
className={cn(
"flex h-full w-(--sidebar-width) flex-col bg-sidebar text-sidebar-foreground",
className
)}
{...props}
>
{children}
</div>
)
}
if (isMobile) {
return (
<Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
<SheetContent
data-sidebar="sidebar"
data-slot="sidebar"
data-mobile="true"
className="w-(--sidebar-width) bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden"
style={
{
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
} as React.CSSProperties
}
side={side}
>
<SheetHeader className="sr-only">
<SheetTitle>Sidebar</SheetTitle>
<SheetDescription>Displays the mobile sidebar.</SheetDescription>
</SheetHeader>
<div className="flex h-full w-full flex-col">{children}</div>
</SheetContent>
</Sheet>
)
}
return (
<div
className="group peer hidden text-sidebar-foreground md:block"
data-state={state}
data-collapsible={state === "collapsed" ? collapsible : ""}
data-variant={variant}
data-side={side}
data-slot="sidebar"
>
{/* This is what handles the sidebar gap on desktop */}
<div
data-slot="sidebar-gap"
className={cn(
"relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear",
"group-data-[collapsible=offcanvas]:w-0",
"group-data-[side=right]:rotate-180",
variant === "floating" || variant === "inset"
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon)"
)}
/>
<div
data-slot="sidebar-container"
className={cn(
"fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex",
side === "left"
? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
: "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
// Adjust the padding for floating and inset variants.
variant === "floating" || variant === "inset"
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
className
)}
{...props}
>
<div
data-sidebar="sidebar"
data-slot="sidebar-inner"
className="flex h-full w-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow-sm"
>
{children}
</div>
</div>
</div>
)
}
function SidebarTrigger({
className,
onClick,
children,
...props
}: React.ComponentProps<typeof Button>) {
const { toggleSidebar } = useSidebar()
return (
<Button
data-sidebar="trigger"
data-slot="sidebar-trigger"
variant="ghost"
size="icon"
className={cn("size-7", className)}
onClick={(event) => {
onClick?.(event)
toggleSidebar()
}}
{...props}
>
{children ?? <PanelLeftIcon />}
<span className="sr-only">Toggle Sidebar</span>
</Button>
)
}
function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
const { toggleSidebar } = useSidebar()
return (
<button
data-sidebar="rail"
data-slot="sidebar-rail"
aria-label="Toggle Sidebar"
tabIndex={-1}
onClick={toggleSidebar}
title="Toggle Sidebar"
className={cn(
"absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border sm:flex",
"in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
"group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full hover:group-data-[collapsible=offcanvas]:bg-sidebar",
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
className
)}
{...props}
/>
)
}
function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
return (
<main
data-slot="sidebar-inset"
className={cn(
"relative flex w-full flex-1 flex-col bg-background",
"md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",
className
)}
{...props}
/>
)
}
function SidebarInput({
className,
...props
}: React.ComponentProps<typeof Input>) {
return (
<Input
data-slot="sidebar-input"
data-sidebar="input"
className={cn("h-8 w-full bg-background shadow-none", className)}
{...props}
/>
)
}
function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-header"
data-sidebar="header"
className={cn("flex flex-col gap-2 p-2", className)}
{...props}
/>
)
}
function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-footer"
data-sidebar="footer"
className={cn("flex flex-col gap-2 p-2", className)}
{...props}
/>
)
}
function SidebarSeparator({
className,
...props
}: React.ComponentProps<typeof Separator>) {
return (
<Separator
data-slot="sidebar-separator"
data-sidebar="separator"
className={cn("mx-2 w-auto bg-sidebar-border", className)}
{...props}
/>
)
}
function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-content"
data-sidebar="content"
className={cn(
"flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
className
)}
{...props}
/>
)
}
function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-group"
data-sidebar="group"
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
{...props}
/>
)
}
function SidebarGroupLabel({
className,
asChild = false,
...props
}: React.ComponentProps<"div"> & { asChild?: boolean }) {
const Comp = asChild ? Slot.Root : "div"
return (
<Comp
data-slot="sidebar-group-label"
data-sidebar="group-label"
className={cn(
"flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 ring-sidebar-ring outline-hidden transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
"group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
className
)}
{...props}
/>
)
}
function SidebarGroupAction({
className,
asChild = false,
...props
}: React.ComponentProps<"button"> & { asChild?: boolean }) {
const Comp = asChild ? Slot.Root : "button"
return (
<Comp
data-slot="sidebar-group-action"
data-sidebar="group-action"
className={cn(
"absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground ring-sidebar-ring outline-hidden transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 md:after:hidden",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
)
}
function SidebarGroupContent({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-group-content"
data-sidebar="group-content"
className={cn("w-full text-sm", className)}
{...props}
/>
)
}
function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
return (
<ul
data-slot="sidebar-menu"
data-sidebar="menu"
className={cn("flex w-full min-w-0 flex-col gap-1", className)}
{...props}
/>
)
}
function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
return (
<li
data-slot="sidebar-menu-item"
data-sidebar="menu-item"
className={cn("group/menu-item relative", className)}
{...props}
/>
)
}
const sidebarMenuButtonVariants = cva(
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm ring-sidebar-ring outline-hidden transition-[width,height,padding] group-has-data-[sidebar=menu-action]/menu-item:pr-8 group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
{
variants: {
variant: {
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
outline:
"bg-background shadow-[0_0_0_1px_var(--sidebar-border)] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_var(--sidebar-accent)]",
},
size: {
default: "h-8 text-sm",
sm: "h-7 text-xs",
lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function SidebarMenuButton({
asChild = false,
isActive = false,
variant = "default",
size = "default",
tooltip,
className,
...props
}: React.ComponentProps<"button"> & {
asChild?: boolean
isActive?: boolean
tooltip?: string | React.ComponentProps<typeof TooltipContent>
} & VariantProps<typeof sidebarMenuButtonVariants>) {
const Comp = asChild ? Slot.Root : "button"
const { isMobile, state } = useSidebar()
const button = (
<Comp
data-slot="sidebar-menu-button"
data-sidebar="menu-button"
data-size={size}
data-active={isActive}
className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
{...props}
/>
)
if (!tooltip) {
return button
}
if (typeof tooltip === "string") {
tooltip = {
children: tooltip,
}
}
return (
<Tooltip>
<TooltipTrigger asChild>{button}</TooltipTrigger>
<TooltipContent
side="right"
align="center"
hidden={state !== "collapsed" || isMobile}
{...tooltip}
/>
</Tooltip>
)
}
function SidebarMenuAction({
className,
asChild = false,
showOnHover = false,
...props
}: React.ComponentProps<"button"> & {
asChild?: boolean
showOnHover?: boolean
}) {
const Comp = asChild ? Slot.Root : "button"
return (
<Comp
data-slot="sidebar-menu-action"
data-sidebar="menu-action"
className={cn(
"absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground ring-sidebar-ring outline-hidden transition-transform peer-hover/menu-button:text-sidebar-accent-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 md:after:hidden",
"peer-data-[size=sm]/menu-button:top-1",
"peer-data-[size=default]/menu-button:top-1.5",
"peer-data-[size=lg]/menu-button:top-2.5",
"group-data-[collapsible=icon]:hidden",
showOnHover &&
"group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground data-[state=open]:opacity-100 md:opacity-0",
className
)}
{...props}
/>
)
}
function SidebarMenuBadge({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-menu-badge"
data-sidebar="menu-badge"
className={cn(
"pointer-events-none absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium text-sidebar-foreground tabular-nums select-none",
"peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
"peer-data-[size=sm]/menu-button:top-1",
"peer-data-[size=default]/menu-button:top-1.5",
"peer-data-[size=lg]/menu-button:top-2.5",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
)
}
function SidebarMenuSkeleton({
className,
showIcon = false,
...props
}: React.ComponentProps<"div"> & {
showIcon?: boolean
}) {
// Random width between 50 to 90%.
const width = React.useMemo(() => {
return `${Math.floor(Math.random() * 40) + 50}%`
}, [])
return (
<div
data-slot="sidebar-menu-skeleton"
data-sidebar="menu-skeleton"
className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}
{...props}
>
{showIcon && (
<Skeleton
className="size-4 rounded-md"
data-sidebar="menu-skeleton-icon"
/>
)}
<Skeleton
className="h-4 max-w-(--skeleton-width) flex-1"
data-sidebar="menu-skeleton-text"
style={
{
"--skeleton-width": width,
} as React.CSSProperties
}
/>
</div>
)
}
function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
return (
<ul
data-slot="sidebar-menu-sub"
data-sidebar="menu-sub"
className={cn(
"mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
)
}
function SidebarMenuSubItem({
className,
...props
}: React.ComponentProps<"li">) {
return (
<li
data-slot="sidebar-menu-sub-item"
data-sidebar="menu-sub-item"
className={cn("group/menu-sub-item relative", className)}
{...props}
/>
)
}
function SidebarMenuSubButton({
asChild = false,
size = "md",
isActive = false,
className,
...props
}: React.ComponentProps<"a"> & {
asChild?: boolean
size?: "sm" | "md"
isActive?: boolean
}) {
const Comp = asChild ? Slot.Root : "a"
return (
<Comp
data-slot="sidebar-menu-sub-button"
data-sidebar="menu-sub-button"
data-size={size}
data-active={isActive}
className={cn(
"flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground ring-sidebar-ring outline-hidden hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground",
"data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
size === "sm" && "text-xs",
size === "md" && "text-sm",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
)
}
export {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarGroupAction,
SidebarGroupContent,
SidebarGroupLabel,
SidebarHeader,
SidebarInput,
SidebarInset,
SidebarMenu,
SidebarMenuAction,
SidebarMenuBadge,
SidebarMenuButton,
SidebarMenuItem,
SidebarMenuSkeleton,
SidebarMenuSub,
SidebarMenuSubButton,
SidebarMenuSubItem,
SidebarProvider,
SidebarRail,
SidebarSeparator,
SidebarTrigger,
useSidebar,
}

View File

@@ -0,0 +1,13 @@
import { cn } from "@/lib/utils"
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="skeleton"
className={cn("animate-pulse rounded-md bg-accent", className)}
{...props}
/>
)
}
export { Skeleton }

View File

@@ -0,0 +1,25 @@
import { Switch as SwitchPrimitive } from 'radix-ui';
import { type ComponentProps, type ReactNode } from 'react';
import { cn } from '../../lib/utils';
export type SwitchProps = ComponentProps<typeof SwitchPrimitive.Root> & { size?: 'sm' | 'default' };
/** shadcn/ui Switch, einschließlich unveränderter shadcn-Standardmaße und Zustandsfarben. */
export function Switch({ className, size = 'default', ...props }: SwitchProps): ReactNode {
return (
<SwitchPrimitive.Root
data-slot="switch"
data-size={size}
className={cn(
'peer group/switch inline-flex shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-[1.15rem] data-[size=default]:w-8 data-[size=sm]:h-3.5 data-[size=sm]:w-6 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input dark:data-[state=unchecked]:bg-input/80',
className,
)}
{...props}
>
<SwitchPrimitive.Thumb
data-slot="switch-thumb"
className="pointer-events-none block rounded-full bg-background ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0 dark:data-[state=checked]:bg-primary-foreground dark:data-[state=unchecked]:bg-foreground"
/>
</SwitchPrimitive.Root>
);
}

View File

@@ -0,0 +1,21 @@
import { type ComponentProps, type ReactNode } from 'react';
import { cn } from '../../lib/utils';
export function Table({ className, ...props }: ComponentProps<'table'>): ReactNode {
return <table className={cn('w-full caption-bottom text-sm', className)} {...props} />;
}
export function TableHeader({ className, ...props }: ComponentProps<'thead'>): ReactNode {
return <thead className={cn('[&_tr]:border-b', className)} {...props} />;
}
export function TableBody({ className, ...props }: ComponentProps<'tbody'>): ReactNode {
return <tbody className={cn('[&_tr:last-child]:border-0', className)} {...props} />;
}
export function TableRow({ className, ...props }: ComponentProps<'tr'>): ReactNode {
return <tr className={cn('border-b transition-colors', className)} {...props} />;
}
export function TableHead({ className, ...props }: ComponentProps<'th'>): ReactNode {
return <th className={cn('h-10 px-2 text-left align-middle font-medium text-slate-500', className)} {...props} />;
}
export function TableCell({ className, ...props }: ComponentProps<'td'>): ReactNode {
return <td className={cn('p-2 align-middle', className)} {...props} />;
}

View File

@@ -0,0 +1,16 @@
import { Tabs as TabsPrimitive } from 'radix-ui';
import { type ComponentProps, type ReactNode } from 'react';
import { cn } from '../../lib/utils';
export function Tabs(props: ComponentProps<typeof TabsPrimitive.Root>): ReactNode {
return <TabsPrimitive.Root {...props} />;
}
export function TabsList({ className, ...props }: ComponentProps<typeof TabsPrimitive.List>): ReactNode {
return <TabsPrimitive.List className={cn('inline-flex items-center', className)} {...props} />;
}
export function TabsTrigger({ className, ...props }: ComponentProps<typeof TabsPrimitive.Trigger>): ReactNode {
return <TabsPrimitive.Trigger className={cn('inline-flex items-center justify-center whitespace-nowrap transition-colors disabled:pointer-events-none disabled:opacity-50', className)} {...props} />;
}
export function TabsContent({ className, ...props }: ComponentProps<typeof TabsPrimitive.Content>): ReactNode {
return <TabsPrimitive.Content className={cn('outline-none', className)} {...props} />;
}

View File

@@ -1,84 +1,30 @@
import {
type ReactNode,
createContext,
useCallback,
useContext,
useMemo,
useRef,
useState,
} from 'react';
import { type ReactNode, createContext, useCallback, useContext, useMemo } from 'react';
import { Toaster, toast } from 'sonner';
/** Toast-Varianten. */
export type ToastVariant = 'success' | 'error';
interface ToastEntry {
readonly id: number;
readonly variant: ToastVariant;
readonly message: string;
}
interface ToastContextValue {
showToast: (variant: ToastVariant, message: string) => void;
}
interface ToastContextValue { showToast: (variant: ToastVariant, message: string, description?: ReactNode) => void }
const ToastContext = createContext<ToastContextValue | null>(null);
const VARIANT_CLASSES: Record<ToastVariant, string> = {
success: 'bg-emerald-600 text-white',
error: 'bg-red-600 text-white',
};
const VARIANT_ICONS: Record<ToastVariant, string> = {
success: '✓',
error: '✕',
};
/**
* Toast-Benachrichtigungen (Design-System).
* Meldungen verschwinden automatisch nach 4 Sekunden.
*/
/** shadcn/ui Sonner-Toasts an derselben Position und mit derselben Dauer. */
export function ToastProvider({ children }: { children: ReactNode }): ReactNode {
const [toasts, setToasts] = useState<ToastEntry[]>([]);
const nextId = useRef(1);
const showToast = useCallback((variant: ToastVariant, message: string) => {
const id = nextId.current;
nextId.current += 1;
setToasts((current) => [...current, { id, variant, message }]);
window.setTimeout(() => {
setToasts((current) => current.filter((toast) => toast.id !== id));
}, 4_000);
const showToast = useCallback((variant: ToastVariant, message: string, description?: ReactNode) => {
const className = 'rounded-lg border-0 px-4 py-3 text-sm font-medium shadow-lg';
const options = { description, duration: description ? 12_000 : 4_000 };
if (variant === 'success') toast.success(message, { ...options, className: `${className} !bg-emerald-600 !text-white` });
else toast.error(message, { ...options, className: `${className} !bg-red-600 !text-white` });
}, []);
const value = useMemo<ToastContextValue>(() => ({ showToast }), [showToast]);
return (
<ToastContext.Provider value={value}>
{children}
<div
className="pointer-events-none fixed bottom-4 right-4 z-50 flex flex-col gap-2"
aria-live="polite"
>
{toasts.map((toast) => (
<div
key={toast.id}
className={`pointer-events-auto flex items-center gap-2 rounded-lg px-4 py-3 text-sm font-medium shadow-lg
${VARIANT_CLASSES[toast.variant]}`}
>
<span aria-hidden="true">{VARIANT_ICONS[toast.variant]}</span>
{toast.message}
</div>
))}
</div>
<Toaster position="bottom-right" duration={4000} closeButton={false} richColors={false} />
</ToastContext.Provider>
);
}
/** Zeigt eine Toast-Meldung an (wirft außerhalb des Providers). */
export function useToast(): ToastContextValue {
const context = useContext(ToastContext);
if (!context) {
throw new Error('useToast muss innerhalb von ToastProvider verwendet werden');
}
if (!context) throw new Error('useToast muss innerhalb von ToastProvider verwendet werden');
return context;
}
}

View File

@@ -0,0 +1,54 @@
import * as React from "react"
import { cn } from "@/lib/utils"
import { Tooltip as TooltipPrimitive } from "radix-ui"
function TooltipProvider({
delayDuration = 0,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
return (
<TooltipPrimitive.Provider
data-slot="tooltip-provider"
delayDuration={delayDuration}
{...props}
/>
)
}
function Tooltip({
...props
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
return <TooltipPrimitive.Root data-slot="tooltip" {...props} />
}
function TooltipTrigger({
...props
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
}
function TooltipContent({
className,
sideOffset = 0,
children,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
return (
<TooltipPrimitive.Portal>
<TooltipPrimitive.Content
data-slot="tooltip-content"
sideOffset={sideOffset}
className={cn(
"z-50 w-fit origin-(--radix-tooltip-content-transform-origin) animate-in rounded-md bg-foreground px-3 py-1.5 text-xs text-balance text-background fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",
className
)}
{...props}
>
{children}
<TooltipPrimitive.Arrow className="z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground" />
</TooltipPrimitive.Content>
</TooltipPrimitive.Portal>
)
}
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }

View File

@@ -2,10 +2,11 @@ import { type FormEvent, type ReactNode, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { apiRequest } from '../../lib/api-client';
import { z } from 'zod';
import { Card, CardBody, CardHeader } from '../../components/ui/card';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../../components/ui/card';
import { Input } from '../../components/ui/input';
import { Button } from '../../components/ui/button';
import { ErrorState, Spinner } from '../../components/ui/states';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../../components/ui/table';
/** Audit-Eintrag (API-Vertrag /api/v1/audit). */
const auditEntrySchema = z.object({
@@ -86,7 +87,7 @@ export function AuditPage(): ReactNode {
{/* Filter */}
<Card>
<CardBody>
<CardContent>
<form onSubmit={handleFilterSubmit} className="flex flex-wrap items-end gap-3" noValidate>
<div className="w-48">
<Input
@@ -108,16 +109,15 @@ export function AuditPage(): ReactNode {
Filtern
</Button>
</form>
</CardBody>
</CardContent>
</Card>
{/* Einträge */}
<Card>
<CardHeader
title="Ereignisse"
description={auditQuery.data ? `${auditQuery.data.total} Einträge insgesamt` : undefined}
/>
<CardBody>
<CardHeader>
<div><CardTitle>Ereignisse</CardTitle>{auditQuery.data && <CardDescription>{auditQuery.data.total} Einträge insgesamt</CardDescription>}</div>
</CardHeader>
<CardContent>
{auditQuery.isLoading && <Spinner label="Audit-Log wird geladen…" />}
{auditQuery.isError && <ErrorState message="Audit-Log konnte nicht geladen werden." />}
{auditQuery.data && auditQuery.data.entries.length === 0 && (
@@ -127,36 +127,36 @@ export function AuditPage(): ReactNode {
)}
{auditQuery.data && auditQuery.data.entries.length > 0 && (
<div className="overflow-x-auto">
<table className="w-full min-w-[640px] text-sm">
<thead>
<tr className="border-b border-slate-200 text-left text-xs uppercase tracking-wide text-slate-500">
<th className="px-3 py-2 font-semibold">Zeit</th>
<th className="px-3 py-2 font-semibold">Benutzer</th>
<th className="px-3 py-2 font-semibold">Aktion</th>
<th className="px-3 py-2 font-semibold">Details</th>
</tr>
</thead>
<tbody>
<Table className="w-full min-w-[640px] text-sm">
<TableHeader>
<TableRow className="border-b border-slate-200 text-left text-xs uppercase tracking-wide text-slate-500">
<TableHead className="px-3 py-2 font-semibold">Zeit</TableHead>
<TableHead className="px-3 py-2 font-semibold">Benutzer</TableHead>
<TableHead className="px-3 py-2 font-semibold">Aktion</TableHead>
<TableHead className="px-3 py-2 font-semibold">Details</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{auditQuery.data.entries.map((entry) => (
<tr key={entry.id} className="border-b border-slate-100 last:border-0">
<td className="whitespace-nowrap px-3 py-2 text-slate-500">
<TableRow key={entry.id} className="border-b border-slate-100 last:border-0">
<TableCell className="whitespace-nowrap px-3 py-2 text-slate-500">
{formatTimestamp(entry.createdAt)}
</td>
<td className="px-3 py-2 font-medium text-slate-900">{entry.username}</td>
<td className="px-3 py-2">
</TableCell>
<TableCell className="px-3 py-2 font-medium text-slate-900">{entry.username}</TableCell>
<TableCell className="px-3 py-2">
<code className="rounded bg-slate-100 px-1.5 py-0.5 text-xs text-slate-700">
{entry.action}
</code>
</td>
<td className="px-3 py-2 text-xs text-slate-500">
</TableCell>
<TableCell className="px-3 py-2 text-xs text-slate-500">
{Object.keys(entry.details).length > 0
? JSON.stringify(entry.details)
: '–'}
</td>
</tr>
</TableCell>
</TableRow>
))}
</tbody>
</table>
</TableBody>
</Table>
</div>
)}
@@ -184,8 +184,8 @@ export function AuditPage(): ReactNode {
</Button>
</div>
)}
</CardBody>
</CardContent>
</Card>
</div>
);
}
}

View File

@@ -1,8 +1,15 @@
import { type ReactNode, useRef, useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { type ReactNode, useEffect, useRef, useState } from 'react';
import { useMutation, useQueries, useQuery, useQueryClient } from '@tanstack/react-query';
import { Button } from '../../components/ui/button';
import { Badge } from '../../components/ui/badge';
import { Card } from '../../components/ui/card';
import { Label } from '../../components/ui/label';
import { Icon } from '../../components/ui/icon';
import { InputControl } from '../../components/ui/input';
import { Modal } from '../../components/ui/modal';
import { SelectControl } from '../../components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../../components/ui/tabs';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../../components/ui/table';
import { useToast } from '../../components/ui/toast';
import { ApiError } from '../../lib/api-client';
import {
@@ -12,14 +19,19 @@ import {
fetchMarketplaceRepositories,
fetchMarketplaceProviders,
fetchModules,
fetchModuleConfiguration,
installModule,
installMarketplaceRepository,
fetchMarketplaceUpdates,
updateMarketplaceModule,
removeModule,
restartModule,
setModuleEnabled,
saveModuleConfiguration,
startModule,
stopModule,
type MarketplaceProvider,
type MarketplaceUpdateState,
} from '../../lib/modules-api';
import type { Module, ModuleStatus } from '../../lib/schemas';
@@ -40,22 +52,49 @@ function statusVariant(status: ModuleStatus): 'success' | 'warning' | 'danger' |
}
}
function operationDiagnostic(error: unknown): string | undefined {
if (!(error instanceof ApiError)) return undefined;
const lines = [error.code ? `Fehlercode: ${error.code}` : null, error.diagnostic ?? null]
.filter((line): line is string => Boolean(line));
return lines.length > 0 ? lines.join('\n') : undefined;
}
function operationToastDetails(error: unknown): ReactNode {
const diagnostic = operationDiagnostic(error);
if (!diagnostic) return undefined;
return (
<details className="text-xs">
<summary className="cursor-pointer font-medium">Technische Details</summary>
<pre className="mt-2 max-h-40 overflow-auto whitespace-pre-wrap font-mono">{diagnostic}</pre>
</details>
);
}
/** Bestätigungsdialog: Modul entfernen. */
function RemoveModuleModal({ module, onClose }: { module: Module; onClose: () => void }): ReactNode {
const { showToast } = useToast();
const queryClient = useQueryClient();
const [formError, setFormError] = useState<string | null>(null);
const [formDiagnostic, setFormDiagnostic] = useState<string | null>(null);
const removeMutation = useMutation({
mutationFn: () => removeModule(module.id),
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: ['modules'] });
void queryClient.invalidateQueries({ queryKey: ['marketplace-repositories'] });
showToast('success', `Modul "${module.name}" wurde entfernt`);
onSuccess: async (result) => {
await Promise.all([
queryClient.invalidateQueries({ queryKey: ['modules'] }),
queryClient.invalidateQueries({ queryKey: ['marketplace-repositories'] }),
]);
if (result.cleanupWarning) {
showToast('error', `Modul "${module.name}" wurde entfernt, Dateien blieben zurück`, result.cleanupWarning);
} else {
showToast('success', `Modul "${module.name}" wurde entfernt`);
}
onClose();
},
onError: (error) => {
onError: async (error) => {
setFormError(error instanceof ApiError ? error.message : 'Entfernen fehlgeschlagen');
setFormDiagnostic(operationDiagnostic(error) ?? null);
await queryClient.invalidateQueries({ queryKey: ['modules'] });
},
});
@@ -63,13 +102,14 @@ function RemoveModuleModal({ module, onClose }: { module: Module; onClose: () =>
<Modal
open
title="Modul entfernen"
description={`Möchten Sie "${module.name}" (Version ${module.version}) wirklich entfernen? App- und Datenbankcontainer sowie Dateien und Registrierung werden gelöscht. Datenvolumes bleiben für eine mögliche Neuinstallation erhalten.`}
description={`Möchten Sie "${module.name}" (Version ${module.version}) wirklich entfernen? App- und Datenbankcontainer, alle zugehörigen Datenvolumes, Dateien und Registrierung werden endgültig gelöscht. Gespeicherte Modul- und Kalenderdaten können danach nicht wiederhergestellt werden.`}
onClose={onClose}
>
{formError && (
<p role="alert" className="mb-4 rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700">
{formError}
</p>
<div role="alert" className="mb-4 rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700">
<p>{formError}</p>
{formDiagnostic && <details className="mt-2 text-xs"><summary className="cursor-pointer font-medium">Technische Details</summary><pre className="mt-2 max-h-40 overflow-auto whitespace-pre-wrap font-mono">{formDiagnostic}</pre></details>}
</div>
)}
<div className="flex justify-end gap-2">
<Button variant="secondary" onClick={onClose}>
@@ -87,6 +127,116 @@ function RemoveModuleModal({ module, onClose }: { module: Module; onClose: () =>
);
}
function ModuleConfigurationModal({ module, onClose }: { module: Module; onClose: () => void }): ReactNode {
const { showToast } = useToast();
const queryClient = useQueryClient();
const [values, setValues] = useState<Record<string, string>>({});
const [clearKeys, setClearKeys] = useState<string[]>([]);
const [formError, setFormError] = useState<string | null>(null);
const configQuery = useQuery({
queryKey: ['module-configuration', module.id],
queryFn: () => fetchModuleConfiguration(module.id),
});
useEffect(() => {
if (configQuery.data) {
setValues(Object.fromEntries(configQuery.data.fields.map((field) => [field.key, field.value ?? ''])));
setClearKeys([]);
}
}, [configQuery.data]);
const saveMutation = useMutation({
mutationFn: () => saveModuleConfiguration(module.id, { values, clearKeys }),
onSuccess: async () => {
await queryClient.invalidateQueries({ queryKey: ['modules'] });
await queryClient.invalidateQueries({ queryKey: ['module-configuration', module.id] });
showToast('success', `Konfiguration für „${module.name}“ gespeichert`);
onClose();
},
onError: (error) => setFormError(error instanceof ApiError ? error.message : 'Konfiguration konnte nicht gespeichert werden'),
});
const inputClass = 'mt-1 h-auto w-full rounded-lg border border-slate-300 px-3 py-2 text-sm';
return (
<Modal open title={`Konfiguration: ${module.name}`} description="Werte werden verschlüsselt gespeichert." onClose={onClose} panelClassName="max-w-2xl">
{configQuery.isLoading && <p className="text-sm text-slate-500">Konfiguration wird geladen…</p>}
{configQuery.isError && <p role="alert" className="text-sm text-red-600">Konfiguration konnte nicht geladen werden.</p>}
{configQuery.data && <form onSubmit={(event) => { event.preventDefault(); setFormError(null); saveMutation.mutate(); }}>
{module.status === 'RUNNING' && <p className="mb-4 rounded-lg bg-amber-50 px-3 py-2 text-sm text-amber-800">Das laufende Modul wird nach dem Speichern neu gestartet.</p>}
<div className="max-h-[60vh] space-y-4 overflow-y-auto pr-1">
{configQuery.data.fields.map((field) => <div key={field.key}>
<Label htmlFor={`config-${field.key}`} className="block text-sm font-medium text-slate-800">{field.label}{field.required && <span className="text-red-600"> *</span>}</Label>
{field.description && <p className="mt-0.5 text-xs text-slate-500">{field.description}</p>}
{field.type === 'boolean' ? <SelectControl id={`config-${field.key}`} className={inputClass} required={field.required} value={values[field.key] ?? ''} placeholder="Bitte auswählen" options={[{ value: 'true', label: 'Ja' }, { value: 'false', label: 'Nein' }]} onValueChange={(value) => setValues((current) => ({ ...current, [field.key]: value }))} /> : <InputControl id={`config-${field.key}`} className={inputClass} type={field.secret ? 'password' : field.type === 'url' ? 'url' : 'text'} required={field.required && (!field.secret || !field.isSet || clearKeys.includes(field.key))} value={values[field.key] ?? ''} placeholder={field.secret && field.isSet ? 'Gespeicherter Wert bleibt erhalten' : ''} autoComplete="new-password" onChange={(event) => { setValues((current) => ({ ...current, [field.key]: event.target.value })); setClearKeys((current) => current.filter((key) => key !== field.key)); }} />}
{field.secret && field.isSet && <Button variant="ghost" size="sm" type="button" className="mt-1 h-auto px-0 py-0 text-xs text-red-700 hover:bg-transparent hover:underline" onClick={() => setClearKeys((current) => current.includes(field.key) ? current.filter((key) => key !== field.key) : [...current, field.key])}>{clearKeys.includes(field.key) ? 'Löschen rückgängig machen' : 'Gespeicherten Wert löschen'}</Button>}
{clearKeys.includes(field.key) && <p className="text-xs text-red-700">Wird beim Speichern gelöscht.</p>}
</div>)}
</div>
{formError && <p role="alert" className="mt-4 rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700">{formError}</p>}
<div className="mt-5 flex justify-end gap-2"><Button type="button" variant="secondary" onClick={onClose}>Abbrechen</Button><Button type="submit" loading={saveMutation.isPending}>Speichern</Button></div>
</form>}
</Modal>
);
}
function ModuleUpdateModal({ module, state, onClose }: { module: Module; state: MarketplaceUpdateState; onClose: () => void }): ReactNode {
const queryClient = useQueryClient();
const [branch, setBranch] = useState(state.branches[0]?.name ?? '');
const [formError, setFormError] = useState<string | null>(null);
const [completed, setCompleted] = useState<{ module: Module; branch: string; commit: string | null } | null>(null);
const updateMutation = useMutation({
mutationFn: () => updateMarketplaceModule(module.id, branch),
onSuccess: async (updatedModule) => {
await Promise.all([
queryClient.invalidateQueries({ queryKey: ['modules'] }),
queryClient.invalidateQueries({ queryKey: ['module-updates', module.id] }),
]);
setCompleted({ module: updatedModule, branch, commit: state.branches.find((item) => item.name === branch)?.commit ?? null });
},
onError: (error) => setFormError(error instanceof ApiError ? error.message : 'Modulupdate fehlgeschlagen'),
});
const selected = state.branches.find((item) => item.name === branch);
const handleClose = () => { if (!updateMutation.isPending) onClose(); };
return (
<Modal open title={completed ? 'Update erfolgreich' : `Update verfügbar: ${module.name}`}
description={completed ? `${completed.module.name} wurde erfolgreich aktualisiert.` : 'Wähle die getestete Branch für das Update aus.'}
onClose={handleClose}>
{completed ? <div className="space-y-5">
<div role="status" className="flex items-start gap-3 rounded-lg border border-emerald-200 bg-emerald-50 p-4 text-emerald-900">
<Icon name="check" className="mt-0.5 h-5 w-5 shrink-0" />
<div className="min-w-0">
<p className="font-medium">Installation abgeschlossen</p>
<p className="mt-1 text-sm">Branch <span className="font-medium">{completed.branch}</span> ist jetzt installiert.</p>
{completed.commit && <p className="mt-1 break-all text-xs text-emerald-800">Commit {completed.commit}</p>}
</div>
</div>
<div className="flex justify-end"><Button onClick={handleClose}>Schließen</Button></div>
</div> : <div className="space-y-4">
<div className="rounded-lg border border-slate-200 bg-slate-50 p-3 text-sm">
<p><span className="font-medium">Installierte Branch:</span> {state.installedBranch}</p>
{state.installedCommit && <p className="mt-1 text-xs text-slate-500">Commit {state.installedCommit.slice(0, 12)}</p>}
</div>
<div>
<Label htmlFor="module-update-branch">Neue Branch</Label>
<SelectControl id="module-update-branch" className="mt-1" disabled={updateMutation.isPending} value={branch} onValueChange={(value) => { setBranch(value); setFormError(null); }}
options={state.branches.map((item) => ({ value: item.name, label: item.name }))} />
{selected && <p className="mt-1 text-xs text-slate-500">Commit {selected.commit.slice(0, 12)}</p>}
</div>
<p className="text-xs text-slate-500">Die Konfiguration und persistenten Daten bleiben erhalten. Bei einem fehlgeschlagenen Start stellt MPM die vorherige Modulversion wieder her.</p>
{updateMutation.isPending && <div className="space-y-2" role="status" aria-live="polite">
<div role="progressbar" aria-label="Modulupdate läuft" aria-valuemin={0} aria-valuemax={100} aria-valuetext="Installationsvorgang läuft" className="h-2 overflow-hidden rounded-full bg-brand-100">
<div className="mpm-indeterminate-progress h-full w-2/5 rounded-full bg-brand-600" />
</div>
<p className="text-sm font-medium text-slate-700">Update auf „{branch}“ wird installiert…</p>
<p className="text-xs text-slate-500">MPM aktualisiert das Modul und prüft anschließend den Start. Das kann einige Minuten dauern.</p>
</div>}
{formError && <p role="alert" className="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700">{formError}</p>}
<div className="flex justify-end gap-2">
<Button variant="secondary" disabled={updateMutation.isPending} onClick={handleClose}>Abbrechen</Button>
<Button disabled={!branch} loading={updateMutation.isPending} onClick={() => { setFormError(null); updateMutation.mutate(); }}>Update installieren</Button>
</div>
</div>}
</Modal>
);
}
/** Modul-Verwaltung (nur Admin): Installation, Lifecycle, Healthchecks. */
export function ModulesPage(): ReactNode {
const { showToast } = useToast();
@@ -94,6 +244,8 @@ export function ModulesPage(): ReactNode {
const fileInputRef = useRef<HTMLInputElement>(null);
const [selectedFile, setSelectedFile] = useState<File | null>(null);
const [removeTarget, setRemoveTarget] = useState<Module | null>(null);
const [configurationTarget, setConfigurationTarget] = useState<Module | null>(null);
const [updateTarget, setUpdateTarget] = useState<Module | null>(null);
const [connectTarget, setConnectTarget] = useState<MarketplaceProvider['provider'] | null>(null);
const [connectionTab, setConnectionTab] = useState<'providers' | 'manual'>('providers');
const [healthResults, setHealthResults] = useState<Record<string, { healthy: boolean; detail: string }>>({});
@@ -101,12 +253,20 @@ export function ModulesPage(): ReactNode {
const modulesQuery = useQuery({
queryKey: ['modules'],
queryFn: fetchModules,
refetchInterval: 15_000,
refetchInterval: (query) => query.state.data?.some((module) => module.status === 'STARTING' || module.status === 'STOPPING') ? 2_000 : 15_000,
});
const marketplaceQuery = useQuery({
queryKey: ['marketplace-providers'],
queryFn: fetchMarketplaceProviders,
});
const moduleUpdateQueries = useQueries({
queries: (modulesQuery.data ?? []).map((module) => ({
queryKey: ['module-updates', module.id],
queryFn: () => fetchMarketplaceUpdates(module.id),
refetchInterval: 60 * 1000,
retry: false,
})),
});
const connectedProviders = marketplaceQuery.data?.filter((item) => item.connected) ?? [];
const repositoriesQuery = useQuery({
queryKey: ['marketplace-repositories', connectedProviders.map((item) => item.provider)],
@@ -135,30 +295,36 @@ export function ModulesPage(): ReactNode {
const marketplaceInstallMutation = useMutation({
mutationFn: (input: { provider: MarketplaceProvider['provider']; owner: string; repository: string }) =>
installMarketplaceRepository(input.provider, input.owner, input.repository),
onSuccess: (module) => {
void queryClient.invalidateQueries({ queryKey: ['modules'] });
void queryClient.invalidateQueries({ queryKey: ['marketplace-repositories'] });
onSuccess: async (module) => {
await Promise.all([
queryClient.invalidateQueries({ queryKey: ['modules'] }),
queryClient.invalidateQueries({ queryKey: ['marketplace-repositories'] }),
]);
showToast('success', `Modul "${module.name}" wurde installiert. Zum Starten bitte „Start“ wählen.`);
},
onError: (error) => showToast('error', error instanceof ApiError ? error.message : 'Marketplace-Installation fehlgeschlagen'),
onError: async (error) => {
showToast('error', error instanceof ApiError ? error.message : 'Marketplace-Installation fehlgeschlagen', operationToastDetails(error));
await invalidate();
},
});
const invalidate = (): void => {
void queryClient.invalidateQueries({ queryKey: ['modules'] });
const invalidate = async (): Promise<void> => {
await queryClient.invalidateQueries({ queryKey: ['modules'] });
};
const installMutation = useMutation({
mutationFn: (file: File) => installModule(file),
onSuccess: (module) => {
onSuccess: async (module) => {
showToast('success', `Modul "${module.name}" wurde installiert`);
setSelectedFile(null);
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
invalidate();
await invalidate();
},
onError: (error) => {
showToast('error', error instanceof ApiError ? error.message : 'Installation fehlgeschlagen');
onError: async (error) => {
showToast('error', error instanceof ApiError ? error.message : 'Installation fehlgeschlagen', operationToastDetails(error));
await invalidate();
},
});
@@ -177,13 +343,13 @@ export function ModulesPage(): ReactNode {
return setModuleEnabled(input.module.id, false);
}
},
onSuccess: (module, variables) => {
onSuccess: async (module, variables) => {
showToast('success', `Modul "${module.name}" – Aktion "${variables.action}" erfolgreich`);
invalidate();
await invalidate();
},
onError: (error) => {
showToast('error', error instanceof ApiError ? error.message : 'Aktion fehlgeschlagen');
invalidate();
onError: async (error) => {
showToast('error', error instanceof ApiError ? error.message : 'Aktion fehlgeschlagen', operationToastDetails(error));
await invalidate();
},
});
@@ -242,18 +408,18 @@ export function ModulesPage(): ReactNode {
<div className="space-y-6">
{/* Compact provider connectors */}
<section className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm">
<Card className="p-5">
<h2 className="mb-3 text-lg font-semibold text-slate-900">Verbindungen</h2>
<div role="tablist" aria-label="Verbindungen und manuelle Installation" className="mb-4 flex gap-2 border-b border-slate-200">
<button type="button" role="tab" aria-selected={connectionTab === 'providers'} onClick={() => setConnectionTab('providers')} className={`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${connectionTab === 'providers' ? 'border-brand-600 text-brand-700' : 'border-transparent text-slate-500 hover:text-slate-800'}`}>
<Tabs value={connectionTab} onValueChange={(value) => setConnectionTab(value as 'providers' | 'manual')}>
<TabsList aria-label="Verbindungen und manuelle Installation" className="mb-4 flex gap-2 border-b border-slate-200">
<TabsTrigger value="providers" className="border-b-2 px-3 py-2 text-sm font-medium data-[state=active]:border-brand-600 data-[state=active]:text-brand-700 data-[state=inactive]:border-transparent data-[state=inactive]:text-slate-500 data-[state=inactive]:hover:text-slate-800">
Verbindungen
</button>
<button type="button" role="tab" aria-selected={connectionTab === 'manual'} onClick={() => setConnectionTab('manual')} className={`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${connectionTab === 'manual' ? 'border-brand-600 text-brand-700' : 'border-transparent text-slate-500 hover:text-slate-800'}`}>
</TabsTrigger>
<TabsTrigger value="manual" className="border-b-2 px-3 py-2 text-sm font-medium data-[state=active]:border-brand-600 data-[state=active]:text-brand-700 data-[state=inactive]:border-transparent data-[state=inactive]:text-slate-500 data-[state=inactive]:hover:text-slate-800">
Manuelle Installation
</button>
</div>
{connectionTab === 'providers' ? (
<div className="grid grid-cols-1">
</TabsTrigger>
</TabsList>
<TabsContent value="providers" className="grid grid-cols-1">
{(['github', 'gitea', 'forgejo'] as const).map((provider) => {
const connection = marketplaceQuery.data?.find((item) => item.provider === provider);
const label = connection?.label ?? (provider === 'github' ? 'GitHub' : provider === 'gitea' ? 'Gitea' : 'Forgejo');
@@ -301,68 +467,76 @@ export function ModulesPage(): ReactNode {
</div>
);
})}
</div>
) : (
<div role="tabpanel" className="flex flex-wrap items-center gap-3">
<input
</TabsContent>
<TabsContent value="manual" className="flex flex-wrap items-center gap-3">
<InputControl
ref={fileInputRef}
type="file"
accept=".zip"
onChange={handleFileChange}
className="text-sm text-slate-600 file:mr-3 file:rounded-lg file:border-0 file:bg-brand-50 file:px-3 file:py-2 file:text-sm file:font-medium file:text-brand-700 hover:file:bg-brand-100"
className="h-auto w-auto border-0 bg-transparent px-0 py-0 text-sm text-slate-600 file:mr-3 file:rounded-lg file:border-0 file:bg-brand-50 file:px-3 file:py-2 file:text-sm file:font-medium file:text-brand-700 hover:file:bg-brand-100"
aria-label="Modul-Paket (ZIP) auswählen"
/>
<Button disabled={!selectedFile} loading={installMutation.isPending} onClick={handleInstall}>
Installieren
</Button>
<p className="text-xs text-slate-500">ZIP-Paket mit module.json (Manifest). Maximal 10 MB.</p>
</div>
)}
</section>
</TabsContent>
</Tabs>
</Card>
{/* Modul-Liste */}
<section className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm">
<Card className="p-5">
<h2 className="mb-4 text-lg font-semibold text-slate-900">Installierte Module</h2>
<div className="max-h-[42rem] overflow-auto rounded-xl border border-slate-200">
<table className="w-full min-w-[900px] table-fixed text-sm">
<thead className="sticky top-0 z-10">
<tr className="border-b border-slate-200 bg-slate-50 text-left text-xs uppercase tracking-wide text-slate-500">
<th className="w-[34%] px-4 py-3 font-semibold">Modul</th>
<th className="w-[13%] px-4 py-3 font-semibold">Status</th>
<th className="w-[15%] px-4 py-3 font-semibold">URL</th>
<th className="w-[38%] px-4 py-3 font-semibold">Aktionen</th>
</tr>
</thead>
<tbody>
{modulesQuery.isLoading && <tr><td colSpan={4} className="px-5 py-10 text-center text-slate-500">Module werden geladen…</td></tr>}
{modulesQuery.isError && <tr><td colSpan={4} className="px-5 py-10 text-center text-red-600">Module konnten nicht geladen werden.</td></tr>}
{modulesQuery.data?.map((module) => (
<tr key={module.id} className="border-b border-slate-100 last:border-0">
<td className="px-4 py-3">
<Table className="w-full min-w-[900px] table-fixed text-sm">
<TableHeader className="sticky top-0 z-10">
<TableRow className="border-b border-slate-200 bg-slate-50 text-left text-xs uppercase tracking-wide text-slate-500">
<TableHead className="w-[29%] px-4 py-3 font-semibold">Modul</TableHead>
<TableHead className="w-[12%] px-4 py-3 text-center font-semibold">Status</TableHead>
<TableHead className="w-[13%] px-4 py-3 text-center font-semibold">URL</TableHead>
<TableHead className="w-[22%] px-4 py-3 text-center font-semibold">Konfiguration</TableHead>
<TableHead className="w-[24%] px-4 py-3 font-semibold">Aktionen</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{modulesQuery.isLoading && <TableRow><TableCell colSpan={5} className="px-5 py-10 text-center text-slate-500">Module werden geladen…</TableCell></TableRow>}
{modulesQuery.isError && <TableRow><TableCell colSpan={5} className="px-5 py-10 text-center text-red-600">Module konnten nicht geladen werden.</TableCell></TableRow>}
{modulesQuery.data?.map((module) => {
const actionPending = lifecycleMutation.isPending && lifecycleMutation.variables?.module.id === module.id;
return (
<TableRow key={module.id} className="border-b border-slate-100 last:border-0">
<TableCell className="align-top px-4 py-3">
<div className="font-semibold text-slate-900">{module.name}</div>
<div className="text-xs text-slate-500">{module.moduleId} · Version {module.version}{module.author && ` · ${module.author}`}</div>
{module.description && <div className="mt-0.5 text-xs text-slate-500">{module.description}</div>}
</td>
<td className="px-4 py-3"><span className={`inline-flex rounded-full px-2.5 py-0.5 text-xs font-medium ring-1 ring-inset ${statusVariant(module.status) === 'success' ? 'bg-emerald-50 text-emerald-700 ring-emerald-600/20' : statusVariant(module.status) === 'warning' ? 'bg-amber-50 text-amber-700 ring-amber-600/20' : statusVariant(module.status) === 'danger' ? 'bg-red-50 text-red-700 ring-red-600/20' : statusVariant(module.status) === 'neutral' ? 'bg-slate-100 text-slate-600 ring-slate-500/20' : 'bg-brand-50 text-brand-700 ring-brand-600/20'}`}>{module.status}</span>
{healthResults[module.id] && <div className="mt-1 text-xs text-slate-500">Health: {healthResults[module.id].healthy ? '✓' : '✕'} {healthResults[module.id].detail}</div>}
</td>
<td className="px-4 py-3"><code className="rounded bg-slate-100 px-1.5 py-0.5 text-xs text-slate-700">/{module.slug}</code></td>
<td className="px-4 py-3"><div className="flex flex-wrap gap-1">
{module.status !== 'RUNNING' && module.enabled && <Button size="sm" variant="ghost" loading={lifecycleMutation.isPending && lifecycleMutation.variables?.module.id === module.id && lifecycleMutation.variables?.action === 'start'} onClick={() => lifecycleMutation.mutate({ module, action: 'start' })}>Start</Button>}
{(module.status === 'RUNNING' || module.status === 'STARTING') && <Button size="sm" variant="ghost" loading={lifecycleMutation.isPending && lifecycleMutation.variables?.module.id === module.id && lifecycleMutation.variables?.action === 'stop'} onClick={() => lifecycleMutation.mutate({ module, action: 'stop' })}>Stop</Button>}
<Button size="sm" variant="ghost" loading={lifecycleMutation.isPending && lifecycleMutation.variables?.module.id === module.id && lifecycleMutation.variables?.action === 'restart'} onClick={() => lifecycleMutation.mutate({ module, action: 'restart' })}>Restart</Button>
<Button size="sm" variant="ghost" onClick={() => healthMutation.mutate(module)}>Health</Button>
<Button size="sm" variant="ghost" loading={lifecycleMutation.isPending && lifecycleMutation.variables?.module.id === module.id && (lifecycleMutation.variables?.action === 'enable' || lifecycleMutation.variables?.action === 'disable')} onClick={() => lifecycleMutation.mutate({ module, action: module.enabled ? 'disable' : 'enable' })}>{module.enabled ? 'Disable' : 'Enable'}</Button>
<Button size="sm" variant="ghost" onClick={() => setRemoveTarget(module)}>Remove</Button>
</div></td>
</tr>
))}
</tbody>
</table>
</TableCell>
<TableCell className="align-top px-4 py-3"><div className="flex w-full justify-center"><Badge variant={statusVariant(module.status)}>{module.status}</Badge></div>
{healthResults[module.id] && <div className="mt-1 text-xs text-slate-500">Health: {healthResults[module.id].healthy ? '✓' : '✕'} {healthResults[module.id].detail}</div>}
</TableCell>
<TableCell className="align-top px-4 py-3"><div className="flex justify-center"><code className="whitespace-nowrap rounded bg-slate-100 px-1.5 py-0.5 text-xs text-slate-700">/{module.slug}</code></div></TableCell>
<TableCell className="align-top px-4 py-3">{module.configuration.length > 0 && <div className="flex flex-col items-center gap-1 text-center"><div className={`text-xs font-medium ${module.configurationReady ? 'text-emerald-700' : 'text-amber-700'}`}>{module.configurationReady ? 'Konfig gesetzt' : 'Konfiguration erforderlich'}</div><Button size="sm" variant="ghost" disabled={actionPending} onClick={() => setConfigurationTarget(module)}>{module.configurationReady ? 'Konfiguration ändern' : 'Konfigurieren'}</Button></div>}</TableCell>
<TableCell className="align-top px-4 py-3"><div className="flex flex-wrap gap-1">
{(() => {
const updateState = moduleUpdateQueries[(modulesQuery.data ?? []).findIndex((item) => item.id === module.id)]?.data;
return <Button size="sm" variant="ghost" disabled={!updateState?.branches.length} title={updateState?.branches.length ? 'Neue getestete Branch installieren' : updateState?.installedBranch ? 'Keine neue Branch gefunden' : 'Kein Marketplace-Repository verknüpft'} onClick={() => updateState && setUpdateTarget(module)}>Update verfügbar</Button>;
})()}
{module.status !== 'RUNNING' && module.enabled && <Button size="sm" variant="ghost" disabled={actionPending} loading={actionPending && lifecycleMutation.variables?.action === 'start'} onClick={() => lifecycleMutation.mutate({ module, action: 'start' })}>Start</Button>}
{(module.status === 'RUNNING' || module.status === 'STARTING') && <Button size="sm" variant="ghost" disabled={actionPending} loading={actionPending && lifecycleMutation.variables?.action === 'stop'} onClick={() => lifecycleMutation.mutate({ module, action: 'stop' })}>Stop</Button>}
<Button size="sm" variant="ghost" disabled={actionPending} loading={actionPending && lifecycleMutation.variables?.action === 'restart'} onClick={() => lifecycleMutation.mutate({ module, action: 'restart' })}>Restart</Button>
<Button size="sm" variant="ghost" disabled={actionPending} onClick={() => healthMutation.mutate(module)}>Health</Button>
<Button size="sm" variant="ghost" disabled={actionPending} loading={actionPending && (lifecycleMutation.variables?.action === 'enable' || lifecycleMutation.variables?.action === 'disable')} onClick={() => lifecycleMutation.mutate({ module, action: module.enabled ? 'disable' : 'enable' })}>{module.enabled ? 'Disable' : 'Enable'}</Button>
<Button size="sm" variant="ghost" disabled={actionPending} onClick={() => setRemoveTarget(module)}>Remove</Button>
</div></TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
{modulesQuery.data?.length === 0 && <p className="px-4 py-8 text-center text-slate-500">Noch keine Module installiert.</p>}
</div>
</section>
</Card>
</div>
<section className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm">
<Card className="p-5">
<div className="mb-6">
<h2 className="text-lg font-semibold text-slate-900">Marketplace</h2>
<p className="mt-1 text-base text-slate-500">
@@ -413,10 +587,16 @@ export function ModulesPage(): ReactNode {
</div>
))}
</div>
</section>
</Card>
{removeTarget && (
<RemoveModuleModal module={removeTarget} onClose={() => setRemoveTarget(null)} />
)}
{configurationTarget && <ModuleConfigurationModal module={configurationTarget} onClose={() => setConfigurationTarget(null)} />}
{updateTarget && (() => {
const index = (modulesQuery.data ?? []).findIndex((item) => item.id === updateTarget.id);
const updateState = moduleUpdateQueries[index]?.data;
return updateState?.branches.length ? <ModuleUpdateModal module={updateTarget} state={updateState} onClose={() => setUpdateTarget(null)} /> : null;
})()}
{connectTarget && (
<ConnectProviderModal
provider={connectTarget}
@@ -471,14 +651,15 @@ function ConnectProviderModal({
panelClassName="max-w-xl overflow-hidden rounded-[28px]"
>
<div className="relative max-h-[90vh] overflow-y-auto px-1 pb-1 pt-2">
<button
<Button
variant="ghost"
type="button"
aria-label="Dialog schließen"
onClick={onClose}
className="absolute right-1 top-0 rounded-full p-2 text-slate-500 transition-colors hover:bg-slate-100 hover:text-slate-900"
className="absolute right-1 top-0 h-auto rounded-full p-2 text-slate-500 transition-colors hover:bg-slate-100 hover:text-slate-900"
>
<Icon name="close" className="h-4 w-4" />
</button>
</Button>
<div className="flex items-center justify-center gap-4 pb-5 pt-2">
<span className="flex h-16 w-16 items-center justify-center rounded-2xl bg-slate-900 text-white">

View File

@@ -2,7 +2,7 @@ import { type ReactNode } from 'react';
import { useQuery } from '@tanstack/react-query';
import { apiRequest } from '../../lib/api-client';
import { z } from 'zod';
import { Card, CardBody, CardHeader } from '../../components/ui/card';
import { Card, CardContent, CardHeader, CardTitle } from '../../components/ui/card';
import { Badge } from '../../components/ui/badge';
import { ErrorState, Spinner } from '../../components/ui/states';
@@ -54,8 +54,8 @@ export function SystemStatusPage(): ReactNode {
</div>
<Card>
<CardHeader title="Gesamtstatus" />
<CardBody>
<CardHeader><CardTitle>Gesamtstatus</CardTitle></CardHeader>
<CardContent>
{statusQuery.isLoading && <Spinner />}
{statusQuery.isError && (
<ErrorState message="Der Systemstatus ist nicht erreichbar." />
@@ -78,12 +78,12 @@ export function SystemStatusPage(): ReactNode {
</span>
</div>
)}
</CardBody>
</CardContent>
</Card>
<Card>
<CardHeader title="Komponenten" />
<CardBody>
<CardHeader><CardTitle>Komponenten</CardTitle></CardHeader>
<CardContent>
{statusQuery.data && (
<div className="space-y-3">
{statusQuery.data.components.map((component) => (
@@ -100,8 +100,8 @@ export function SystemStatusPage(): ReactNode {
))}
</div>
)}
</CardBody>
</CardContent>
</Card>
</div>
);
}
}

View File

@@ -1,6 +1,8 @@
import { type ReactNode, useEffect, useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Modal } from '../../components/ui/modal';
import { Checkbox } from '../../components/ui/checkbox';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../../components/ui/table';
import { useToast } from '../../components/ui/toast';
import { ApiError } from '../../lib/api-client';
import {
@@ -102,14 +104,14 @@ export function UserPermissionsModal({
</p>
) : (
<div className="overflow-x-auto rounded-lg border border-slate-200">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-slate-200 bg-slate-50 text-left text-xs uppercase tracking-wide text-slate-500">
<th scope="col" className="px-4 py-3 font-semibold">Modul</th>
<th scope="col" className="w-32 px-4 py-3 text-center font-semibold">Freigeben</th>
</tr>
</thead>
<tbody>
<Table className="w-full text-sm">
<TableHeader>
<TableRow className="border-b border-slate-200 bg-slate-50 text-left text-xs uppercase tracking-wide text-slate-500">
<TableHead scope="col" className="px-4 py-3 font-semibold">Modul</TableHead>
<TableHead scope="col" className="w-32 px-4 py-3 text-center font-semibold">Freigeben</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{modulesQuery.data?.map((module) => {
const isAdmin = user.role === 'ADMIN';
const isGranted = isAdmin || grantedModuleIds.has(module.id);
@@ -117,29 +119,28 @@ export function UserPermissionsModal({
toggleMutation.isPending && toggleMutation.variables?.module.id === module.id;
return (
<tr key={module.id} className="border-b border-slate-100 last:border-0">
<td className="px-4 py-3">
<TableRow key={module.id} className="border-b border-slate-100 last:border-0">
<TableCell className="px-4 py-3">
<p className="font-medium text-slate-900">{module.name}</p>
<p className="text-xs text-slate-500">
/{module.slug} · Version {module.version}
</p>
</td>
<td className="px-4 py-3 text-center">
<input
type="checkbox"
</TableCell>
<TableCell className="px-4 py-3 text-center">
<Checkbox
checked={isGranted}
disabled={isAdmin || isSaving}
aria-label={`${module.name} für ${user.displayName} freigeben`}
title={isAdmin ? 'Administratoren haben automatisch Zugriff' : undefined}
className="h-4 w-4 cursor-pointer accent-brand-600 disabled:cursor-not-allowed disabled:opacity-60"
onChange={() => handleToggle(module)}
className="cursor-pointer disabled:cursor-not-allowed disabled:opacity-60"
onCheckedChange={() => handleToggle(module)}
/>
</td>
</tr>
</TableCell>
</TableRow>
);
})}
</tbody>
</table>
</TableBody>
</Table>
</div>
)}
</Modal>

View File

@@ -2,10 +2,13 @@ import { type FormEvent, type ReactNode, useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useAuth } from '../auth/auth-context';
import { Button } from '../../components/ui/button';
import { Badge } from '../../components/ui/badge';
import { Card } from '../../components/ui/card';
import { Input } from '../../components/ui/input';
import { Modal } from '../../components/ui/modal';
import { Select } from '../../components/ui/select';
import { useToast } from '../../components/ui/toast';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../../components/ui/table';
import { ApiError } from '../../lib/api-client';
import {
createUser,
@@ -401,64 +404,50 @@ export function UsersPage(): ReactNode {
<Button onClick={() => setCreateOpen(true)}>+ Benutzer anlegen</Button>
</div>
<div className="overflow-x-auto rounded-xl border border-slate-200 bg-white shadow-sm">
<table className="w-full min-w-[720px] text-sm">
<thead>
<tr className="border-b border-slate-200 bg-slate-50 text-left text-xs uppercase tracking-wide text-slate-500">
<th className="px-4 py-3 font-semibold">Benutzer</th>
<th className="px-4 py-3 font-semibold">Rolle</th>
<th className="px-4 py-3 font-semibold">Status</th>
<th className="px-4 py-3 font-semibold">Letzter Login</th>
<th className="px-4 py-3 font-semibold">Aktionen</th>
</tr>
</thead>
<tbody>
<Card className="overflow-x-auto rounded-xl">
<Table className="w-full min-w-[720px] text-sm">
<TableHeader>
<TableRow className="border-b border-slate-200 bg-slate-50 text-left text-xs uppercase tracking-wide text-slate-500">
<TableHead className="px-4 py-3 font-semibold">Benutzer</TableHead>
<TableHead className="px-4 py-3 font-semibold">Rolle</TableHead>
<TableHead className="px-4 py-3 font-semibold">Status</TableHead>
<TableHead className="px-4 py-3 font-semibold">Letzter Login</TableHead>
<TableHead className="px-4 py-3 font-semibold">Aktionen</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{usersQuery.isLoading && (
<tr>
<td colSpan={5} className="px-4 py-8 text-center text-slate-500">
<TableRow>
<TableCell colSpan={5} className="px-4 py-8 text-center text-slate-500">
Benutzer werden geladen…
</td>
</tr>
</TableCell>
</TableRow>
)}
{usersQuery.isError && (
<tr>
<td colSpan={5} className="px-4 py-8 text-center text-red-600">
<TableRow>
<TableCell colSpan={5} className="px-4 py-8 text-center text-red-600">
Benutzer konnten nicht geladen werden.
</td>
</tr>
</TableCell>
</TableRow>
)}
{usersQuery.data?.map((user) => (
<tr key={user.id} className="border-b border-slate-100 last:border-0">
<td className="px-4 py-3">
<TableRow key={user.id} className="border-b border-slate-100 last:border-0">
<TableCell className="px-4 py-3">
<div className="font-medium text-slate-900">{user.displayName}</div>
<div className="text-xs text-slate-500">@{user.username}</div>
</td>
<td className="px-4 py-3">
<span
className={`inline-flex rounded-full px-2.5 py-0.5 text-xs font-medium ring-1 ring-inset
${
user.role === 'ADMIN'
? 'bg-brand-50 text-brand-700 ring-brand-600/20'
: 'bg-slate-100 text-slate-600 ring-slate-500/20'
}`}
>
</TableCell>
<TableCell className="px-4 py-3">
<Badge variant={user.role === 'ADMIN' ? 'info' : 'neutral'}>
{user.role === 'ADMIN' ? 'Admin' : 'Benutzer'}
</span>
</td>
<td className="px-4 py-3">
<span
className={`inline-flex rounded-full px-2.5 py-0.5 text-xs font-medium ring-1 ring-inset
${
user.isActive
? 'bg-emerald-50 text-emerald-700 ring-emerald-600/20'
: 'bg-red-50 text-red-700 ring-red-600/20'
}`}
>
</Badge>
</TableCell>
<TableCell className="px-4 py-3">
<Badge variant={user.isActive ? 'success' : 'danger'}>
{user.isActive ? 'Aktiv' : 'Deaktiviert'}
</span>
</td>
<td className="px-4 py-3 text-slate-500">{formatDate(user.lastLoginAt)}</td>
<td className="px-4 py-3">
</Badge>
</TableCell>
<TableCell className="px-4 py-3 text-slate-500">{formatDate(user.lastLoginAt)}</TableCell>
<TableCell className="px-4 py-3">
<div className="flex flex-wrap gap-1">
<Button size="sm" variant="ghost" onClick={() => setEditUser(user)}>
Bearbeiten
@@ -488,17 +477,17 @@ export function UsersPage(): ReactNode {
</>
)}
</div>
</td>
</tr>
</TableCell>
</TableRow>
))}
</tbody>
</table>
</TableBody>
</Table>
{usersQuery.data?.length === 0 && (
<p className="px-4 py-8 text-center text-slate-500">
Noch keine Benutzer vorhanden.
</p>
)}
</div>
</Card>
{createOpen && (
<CreateUserModal

View File

@@ -2,6 +2,7 @@ import { type FormEvent, type ReactNode, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { useAuth } from './auth-context';
import { Button } from '../../components/ui/button';
import { Card } from '../../components/ui/card';
import { Input } from '../../components/ui/input';
import { ApiError } from '../../lib/api-client';
import { loginSchema } from '../../lib/schemas';
@@ -64,9 +65,10 @@ export function LoginPage(): ReactNode {
</p>
</div>
<Card asChild className="rounded-xl p-6">
<form
onSubmit={(event) => void handleSubmit(event)}
className="rounded-xl border border-slate-200 bg-white p-6 shadow-sm"
className=""
noValidate
>
<div className="space-y-4">
@@ -98,7 +100,8 @@ export function LoginPage(): ReactNode {
Anmelden
</Button>
</form>
</Card>
</div>
</div>
);
}
}

View File

@@ -4,7 +4,7 @@ import { useAuth } from '../auth/auth-context';
import { apiRequest } from '../../lib/api-client';
import { fetchAccessibleModules } from '../../lib/modules-api';
import { healthSchema, type Health } from '../../lib/schemas';
import { Card, CardBody, CardHeader } from '../../components/ui/card';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../../components/ui/card';
import { Badge } from '../../components/ui/badge';
import { EmptyState, ErrorState, Spinner } from '../../components/ui/states';
import { Icon } from '../../components/ui/icon';
@@ -41,11 +41,10 @@ export function DashboardPage(): ReactNode {
{/* Meine Anwendungen: Kacheln ausschließlich nach tatsächlichen Berechtigungen */}
<Card>
<CardHeader
title="Meine Anwendungen"
description="Freigegebene Module der Plattform"
/>
<CardBody>
<CardHeader>
<div><CardTitle>Meine Anwendungen</CardTitle><CardDescription>Freigegebene Module der Plattform</CardDescription></div>
</CardHeader>
<CardContent>
{modulesQuery.isLoading && <Spinner label="Anwendungen werden geladen…" />}
{modulesQuery.isError && (
<ErrorState
@@ -66,6 +65,8 @@ export function DashboardPage(): ReactNode {
<a
key={module.id}
href={`/${module.slug}`}
target="_blank"
rel="noopener noreferrer"
className="mpm-module-tile group rounded-xl border border-slate-200 p-5 transition-all duration-150 hover:-translate-y-0.5 hover:border-slate-400 hover:bg-slate-50 hover:shadow-md"
>
<div className="flex items-start justify-between">
@@ -88,17 +89,16 @@ export function DashboardPage(): ReactNode {
))}
</div>
)}
</CardBody>
</CardContent>
</Card>
{/* Systemstatus (nur für Admins) */}
{isAdmin && (
<Card>
<CardHeader
title="Systemstatus"
description="Live-Status der Plattform-Komponenten"
/>
<CardBody>
<CardHeader>
<div><CardTitle>Systemstatus</CardTitle><CardDescription>Live-Status der Plattform-Komponenten</CardDescription></div>
</CardHeader>
<CardContent>
{healthQuery.isLoading && <Spinner label="Status wird geladen…" />}
{healthQuery.isError && (
<ErrorState
@@ -128,7 +128,7 @@ export function DashboardPage(): ReactNode {
/>
</div>
)}
</CardBody>
</CardContent>
</Card>
)}
</div>

View File

@@ -1,7 +1,7 @@
import { type FormEvent, type ReactNode, useState } from 'react';
import { useMutation, useQuery } from '@tanstack/react-query';
import { Button } from '../../components/ui/button';
import { Card, CardBody, CardHeader } from '../../components/ui/card';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../../components/ui/card';
import { Input } from '../../components/ui/input';
import { Modal } from '../../components/ui/modal';
import { useToast } from '../../components/ui/toast';
@@ -77,8 +77,8 @@ export function ProfilePage({ onClose }: { onClose: () => void }): ReactNode {
>
<div className="space-y-5">
<Card>
<CardHeader title="Persönliche Daten" />
<CardBody>
<CardHeader><CardTitle>Persönliche Daten</CardTitle></CardHeader>
<CardContent>
{profileQuery.isLoading && <p className="text-sm text-slate-500">Wird geladen…</p>}
{profileQuery.isError && <p className="text-sm text-red-600">Profil konnte nicht geladen werden.</p>}
{profile && (
@@ -91,12 +91,12 @@ export function ProfilePage({ onClose }: { onClose: () => void }): ReactNode {
<ProfileField label="Mitglied seit" value={formatDate(profile.createdAt)} />
</dl>
)}
</CardBody>
</CardContent>
</Card>
<Card>
<CardHeader title="Passwort ändern" description="Andere aktive Sitzungen werden danach abgemeldet." />
<CardBody>
<CardHeader><div><CardTitle>Passwort ändern</CardTitle><CardDescription>Andere aktive Sitzungen werden danach abgemeldet.</CardDescription></div></CardHeader>
<CardContent>
<form onSubmit={handleSubmit} className="space-y-4" noValidate>
<Input label="Aktuelles Passwort" name="currentPassword" type="password" autoComplete="current-password" error={fieldErrors.currentPassword} />
<Input label="Neues Passwort" name="newPassword" type="password" autoComplete="new-password" hint="Mindestens 10 Zeichen" error={fieldErrors.newPassword} />
@@ -106,7 +106,7 @@ export function ProfilePage({ onClose }: { onClose: () => void }): ReactNode {
<Button type="submit" loading={changePasswordMutation.isPending}>Passwort ändern</Button>
</div>
</form>
</CardBody>
</CardContent>
</Card>
</div>
</Modal>

View File

@@ -0,0 +1,19 @@
import * as React from "react"
const MOBILE_BREAKPOINT = 768
export function useIsMobile() {
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
React.useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
const onChange = () => {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
}
mql.addEventListener("change", onChange)
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
return () => mql.removeEventListener("change", onChange)
}, [])
return !!isMobile
}

View File

@@ -1,4 +1,16 @@
@import "tailwindcss";
@import "tw-animate-css";
@keyframes mpm-progress-sweep {
from { transform: translateX(-110%); }
to { transform: translateX(260%); }
}
.mpm-indeterminate-progress {
animation: mpm-progress-sweep 1.4s ease-in-out infinite;
}
@custom-variant dark (&:where(html[data-theme='dark'], html[data-theme='dark'] *));
/* =============================================================
MPM Design-System – zentrale Design-Tokens (Tailwind v4)
@@ -19,6 +31,72 @@
--color-brand-950: oklch(0.24 0.08 265);
}
/* shadcn/ui semantic palette; legacy MPM utilities keep their existing colors. */
:root {
--background: #ffffff;
--foreground: #0f172a;
--card: #ffffff;
--card-foreground: #0f172a;
--popover: #ffffff;
--popover-foreground: #0f172a;
--primary: var(--color-brand-600);
--primary-foreground: #ffffff;
--secondary: #f1f5f9;
--secondary-foreground: #334155;
--muted: #f1f5f9;
--muted-foreground: #64748b;
--accent: #f1f5f9;
--accent-foreground: #0f172a;
--destructive: #dc2626;
--destructive-foreground: #ffffff;
--border: #e2e8f0;
--input: #cbd5e1;
--ring: var(--color-brand-500);
--radius: 0.5rem;
--sidebar: #ffffff;
--sidebar-foreground: #475569;
--sidebar-primary: var(--color-brand-600);
--sidebar-primary-foreground: #ffffff;
--sidebar-accent: #f1f5f9;
--sidebar-accent-foreground: #0f172a;
--sidebar-border: #e2e8f0;
--sidebar-ring: var(--color-brand-500);
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-destructive-foreground: var(--destructive-foreground);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
}
/* Fokus-Stil für Tastaturnavigation (Barrierefreiheit) */
@layer base {
:focus-visible {
@@ -31,6 +109,33 @@
Markenakzente werden neutral statt blau. */
html[data-theme='dark'] {
color-scheme: dark;
--sidebar: #303337;
--sidebar-foreground: #c2c6cb;
--sidebar-primary: #565b61;
--sidebar-primary-foreground: #f3f4f6;
--sidebar-accent: #3c4044;
--sidebar-accent-foreground: #e5e7eb;
--sidebar-border: #474b50;
--sidebar-ring: #92979d;
--background: #272a2d;
--foreground: #e5e7eb;
--card: #303337;
--card-foreground: #e5e7eb;
--popover: #303337;
--popover-foreground: #e5e7eb;
--primary: #565b61;
--primary-foreground: #f3f4f6;
--secondary: #3c4044;
--secondary-foreground: #e5e7eb;
--muted: #3c4044;
--muted-foreground: #aeb3b9;
--accent: #3c4044;
--accent-foreground: #e5e7eb;
--destructive: #dc2626;
--destructive-foreground: #ffffff;
--border: #474b50;
--input: #565b61;
--ring: #92979d;
--color-slate-50: #272a2d;
--color-slate-100: #3c4044;
--color-slate-200: #474b50;

View File

@@ -11,6 +11,8 @@ export class ApiError extends Error {
public readonly status: number,
message: string,
public readonly details?: Record<string, string | string[]>,
public readonly code?: string,
public readonly diagnostic?: string,
) {
super(message);
this.name = 'ApiError';
@@ -78,10 +80,14 @@ export async function apiRequest<TResponse>(
if (!response.ok) {
let message = 'Ein unerwarteter Fehler ist aufgetreten.';
let details: Record<string, string[]> | undefined;
let code: string | undefined;
let diagnostic: string | undefined;
try {
const errorBody = (await response.json()) as {
message?: string | string[];
details?: Record<string, string[]>;
code?: string;
diagnostic?: string;
};
if (typeof errorBody.message === 'string') {
message = errorBody.message;
@@ -89,10 +95,12 @@ export async function apiRequest<TResponse>(
message = errorBody.message.join(', ');
}
details = errorBody.details;
code = errorBody.code;
diagnostic = errorBody.diagnostic;
} catch {
// Antwort enthält kein JSON – Standardmeldung verwenden.
}
throw new ApiError(response.status, message, details);
throw new ApiError(response.status, message, details, code, diagnostic);
}
return (await response.json()) as TResponse;

View File

@@ -3,9 +3,11 @@ import {
accessibleModuleSchema,
modulePermissionSchema,
moduleSchema,
moduleConfigurationSchema,
type AccessibleModule,
type Module,
type ModulePermission,
type ModuleConfiguration,
} from './schemas';
/** Typsichere API-Funktionen für die Modul-Verwaltung. */
@@ -35,10 +37,14 @@ export async function installModule(file: File): Promise<Module> {
if (!response.ok) {
let message = 'Installation fehlgeschlagen';
let details: Record<string, string | string[]> | undefined;
let code: string | undefined;
let diagnostic: string | undefined;
try {
const errorBody = (await response.json()) as {
message?: string | string[];
details?: Record<string, string | string[]>;
code?: string;
diagnostic?: string;
};
if (typeof errorBody.message === 'string') {
message = errorBody.message;
@@ -46,10 +52,12 @@ export async function installModule(file: File): Promise<Module> {
message = errorBody.message.join(', ');
}
details = errorBody.details;
code = errorBody.code;
diagnostic = errorBody.diagnostic;
} catch {
// Kein JSON in der Antwort – Standardmeldung verwenden.
}
throw new ApiError(response.status, message, details);
throw new ApiError(response.status, message, details, code, diagnostic);
}
const response_ = (await response.json()) as { module: unknown };
@@ -85,8 +93,21 @@ export async function setModuleEnabled(id: string, enabled: boolean): Promise<Mo
return moduleSchema.parse(response.module);
}
export async function removeModule(id: string): Promise<void> {
await apiRequest(`/api/v1/modules/${id}`, { method: 'DELETE' });
export async function removeModule(id: string): Promise<{ cleanupWarning?: string }> {
return apiRequest<{ cleanupWarning?: string }>(`/api/v1/modules/${id}`, { method: 'DELETE' });
}
export async function fetchModuleConfiguration(id: string): Promise<ModuleConfiguration> {
return moduleConfigurationSchema.parse(await apiRequest(`/api/v1/modules/${id}/configuration`));
}
export async function saveModuleConfiguration(
id: string,
input: { values: Record<string, string>; clearKeys: string[] },
): Promise<ModuleConfiguration> {
return moduleConfigurationSchema.parse(await apiRequest(`/api/v1/modules/${id}/configuration`, {
method: 'PATCH', body: input,
}));
}
export async function checkModuleHealth(
@@ -166,6 +187,24 @@ export async function installMarketplaceRepository(
return moduleSchema.parse(response.module);
}
export interface MarketplaceUpdateState {
installedBranch: string;
installedCommit: string | null;
branches: Array<{ name: string; commit: string }>;
}
export async function fetchMarketplaceUpdates(moduleId: string): Promise<MarketplaceUpdateState> {
return apiRequest<MarketplaceUpdateState>(`/api/v1/marketplace/modules/${encodeURIComponent(moduleId)}/updates`);
}
export async function updateMarketplaceModule(moduleId: string, branch: string): Promise<Module> {
const response = await apiRequest<{ module: unknown }>(
`/api/v1/marketplace/modules/${encodeURIComponent(moduleId)}/update`,
{ method: 'POST', body: { branch } },
);
return moduleSchema.parse(response.module);
}
export async function fetchMarketplaceProviders(): Promise<MarketplaceProvider[]> {
return apiRequest<MarketplaceProvider[]>('/api/v1/marketplace/providers');
}

View File

@@ -134,9 +134,25 @@ export const moduleSchema = z.object({
healthcheckUrl: z.string(),
enabled: z.boolean(),
createdAt: z.string(),
configuration: z.array(z.object({
key: z.string(), label: z.string(), description: z.string(),
type: z.enum(['text', 'url', 'boolean']), secret: z.boolean(), required: z.boolean(),
defaultValue: z.string().optional(), services: z.array(z.string()),
})),
configurationReady: z.boolean(),
});
export type Module = z.infer<typeof moduleSchema>;
export const moduleConfigurationSchema = z.object({
ready: z.boolean(),
fields: z.array(z.object({
key: z.string(), label: z.string(), description: z.string(),
type: z.enum(['text', 'url', 'boolean']), secret: z.boolean(), required: z.boolean(),
services: z.array(z.string()), isSet: z.boolean(), value: z.string().optional(),
})),
});
export type ModuleConfiguration = z.infer<typeof moduleConfigurationSchema>;
/** Modul-Kachel für das Dashboard (/api/v1/profile/modules). */
export const accessibleModuleSchema = z.object({
id: z.string(),
@@ -155,4 +171,4 @@ export const modulePermissionSchema = z.object({
moduleName: z.string(),
permission: z.enum(['GRANTED', 'DENIED']),
});
export type ModulePermission = z.infer<typeof modulePermissionSchema>;
export type ModulePermission = z.infer<typeof modulePermissionSchema>;

View File

@@ -0,0 +1,6 @@
import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]): string {
return twMerge(clsx(inputs));
}