Refactor admin area and remove legacy root paths
CI / quality (push) Waiting to run

This commit is contained in:
MOH
2026-03-13 16:14:04 +01:00
parent e32ac4cacb
commit db897e22bf
65 changed files with 216 additions and 140 deletions
+165
View File
@@ -0,0 +1,165 @@
import type { ReactNode } from "react";
import {
FolderKanban,
Globe2,
ImageIcon,
LayoutDashboard,
LogOut,
PlusSquare,
ShieldAlert,
SwatchBook,
Tags,
Type,
} from "lucide-react";
import Link from "next/link";
import { DashboardLayout } from "@/components/dashboard/dashboard-layout";
import { MotionFade } from "@/components/motion-fade";
import { SidebarMaintenanceControl } from "@/components/admin/sidebar-maintenance-control";
import { SoundToggle } from "@/components/sound-toggle";
import { ThemeToggle } from "@/components/theme-toggle";
import { Button } from "@/components/ui/button";
import { buildSiteUrl } from "@/lib/admin-routing";
import { getMaintenanceMode, getSiteSettingsMediaBindings } from "@/lib/app-config";
import { getAdminNavigation } from "@/lib/admin-navigation";
import { updateMaintenanceModeAction } from "@/app/_admin/maintenance/actions";
type AdminDashboardCopy = {
title: string;
subtitle: string;
overview: string;
maintenance: string;
uiKit: string;
portfolio: string;
media: string;
siteSettings: string;
marquee?: string;
smtp?: string;
contactProtection?: string;
logout: string;
backToSite: string;
};
type AdminDashboardShellProps = {
copy: AdminDashboardCopy;
active: "overview" | "maintenance" | "ui-kit" | "portfolio" | "media" | "site-settings" | "smtp" | "marquee";
smtpChild?: "settings" | "contact-protection";
portfolioChild?: "overview" | "projects" | "new-project" | "categories";
logoutAction: () => Promise<void>;
headerTitle: string;
headerDescription: string;
headerActions?: ReactNode;
sidebarTopContent?: ReactNode;
toolbar?: ReactNode;
children: ReactNode;
};
export async function AdminDashboardShell({
copy,
active,
smtpChild,
portfolioChild,
logoutAction,
headerTitle,
headerDescription,
headerActions,
sidebarTopContent,
toolbar,
children,
}: AdminDashboardShellProps) {
const [mediaBindings, maintenanceEnabled] = await Promise.all([
getSiteSettingsMediaBindings(),
getMaintenanceMode(),
]);
const sidebarItems = getAdminNavigation(copy, active, smtpChild, portfolioChild);
const normalizedSidebarItems = sidebarItems.filter(
(item) =>
item.href !== "/maintenance" &&
item.href !== "/ui-kit" &&
item.href !== "/smtp" &&
item.href !== "/marquee",
);
const footerSidebarItems = ["/marquee", "/smtp"]
.map((href) => sidebarItems.find((item) => item.href === href))
.filter((item): item is NonNullable<typeof item> => Boolean(item));
const headerIcon =
active === "overview"
? LayoutDashboard
: active === "maintenance"
? ShieldAlert
: active === "ui-kit"
? SwatchBook
: active === "site-settings"
? Globe2
: active === "marquee"
? Type
: active === "smtp"
? ShieldAlert
: active === "media"
? ImageIcon
: portfolioChild === "categories"
? Tags
: portfolioChild === "new-project"
? PlusSquare
: FolderKanban;
return (
<DashboardLayout
title={headerTitle}
description={headerDescription}
icon={headerIcon}
items={normalizedSidebarItems}
sidebarIconSrc={mediaBindings.favicon?.url}
sidebarBrandHref={buildSiteUrl()}
sidebarBrandHoverLabel={copy.backToSite}
sidebarTop={sidebarTopContent}
sidebarFooterItems={footerSidebarItems}
sidebarFooter={
<>
<SidebarMaintenanceControl
action={updateMaintenanceModeAction}
initialEnabled={maintenanceEnabled}
label="Mohs Status"
/>
<Button
asChild
variant={active === "ui-kit" ? "default" : "outline"}
className="w-full justify-between"
>
<Link href="/ui-kit">
{copy.uiKit}
<SwatchBook className="h-4 w-4" />
</Link>
</Button>
<form action={logoutAction}>
<Button type="submit" variant="ghost" className="w-full justify-between text-destructive hover:bg-destructive/10 hover:text-destructive">
{copy.logout}
<LogOut className="h-4 w-4" />
</Button>
</form>
</>
}
headerActions={
<div className="flex flex-wrap items-center justify-end gap-2">
{headerActions}
<SoundToggle
ariaLabel="Mute sounds"
mutedAriaLabel="Unmute sounds"
mutedToastLabel="Sound muted"
unmutedToastLabel="Sound enabled"
/>
<ThemeToggle
ariaLabel="Theme wechseln"
lightToastLabel="Light mode enabled"
darkToastLabel="Dark mode enabled"
/>
</div>
}
>
<div className="space-y-6">
{toolbar ? <MotionFade delay={0.05}>{toolbar}</MotionFade> : null}
{children}
</div>
</DashboardLayout>
);
}
@@ -0,0 +1,137 @@
"use client";
import { useState } from "react";
import { AppCard } from "@/components/ui/app-card";
import { Button } from "@/components/ui/button";
import { CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import type { ContactProtectionFormValues } from "@/lib/contact-protection";
type ContactProtectionFormProps = {
action: (formData: FormData) => Promise<void>;
initialSettings: ContactProtectionFormValues;
};
export function ContactProtectionForm({
action,
initialSettings,
}: ContactProtectionFormProps) {
const [turnstileEnabled, setTurnstileEnabled] = useState(initialSettings.turnstile.enabled);
const [rateLimitEnabled, setRateLimitEnabled] = useState(initialSettings.rateLimit.enabled);
return (
<form id="contact-protection-form" action={action} className="grid gap-6 xl:grid-cols-2">
<AppCard>
<CardHeader>
<CardTitle>Turnstile</CardTitle>
<CardDescription>Cloudflare Schutz fuer das Kontaktformular.</CardDescription>
</CardHeader>
<CardContent className="grid gap-5 p-4 md:grid-cols-2">
<div className="space-y-4 md:col-span-2">
<label
htmlFor="turnstileEnabled"
className="flex cursor-pointer items-start gap-3 rounded-nested border border-input bg-card px-4 py-4 transition-colors hover:bg-accent/20"
>
<Checkbox
id="turnstileEnabled"
name="turnstileEnabled"
checked={turnstileEnabled}
onCheckedChange={(checked) => setTurnstileEnabled(checked === true)}
className="mt-0.5"
/>
<span className="space-y-1">
<span className="block text-sm font-medium text-foreground">Enable Turnstile</span>
<span className="block text-xs text-muted-foreground">
{turnstileEnabled
? "ON: Besucher muessen die Pruefung bestehen."
: "OFF: Kein Turnstile Schutz im Formular."}
</span>
</span>
</label>
</div>
<div className="space-y-2">
<Label htmlFor="turnstileSiteKey">Turnstile Site Key</Label>
<Input
id="turnstileSiteKey"
name="turnstileSiteKey"
defaultValue={initialSettings.turnstile.siteKey}
autoComplete="off"
/>
</div>
<div className="space-y-2">
<Label htmlFor="turnstileSecretKey">Turnstile Secret Key</Label>
<Input
id="turnstileSecretKey"
name="turnstileSecretKey"
type="password"
defaultValue={initialSettings.turnstile.secretKey}
placeholder={initialSettings.turnstile.hasSecretKey ? "Saved secret key will be kept" : "Secret key"}
autoComplete="new-password"
/>
</div>
</CardContent>
</AppCard>
<AppCard>
<CardHeader>
<CardTitle>Rate Limiting</CardTitle>
<CardDescription>Begrenzung wiederholter Kontaktanfragen.</CardDescription>
</CardHeader>
<CardContent className="grid gap-5 p-4 md:grid-cols-2">
<div className="space-y-4 md:col-span-2">
<label
htmlFor="contactRateLimitEnabled"
className="flex cursor-pointer items-start gap-3 rounded-nested border border-input bg-card px-4 py-4 transition-colors hover:bg-accent/20"
>
<Checkbox
id="contactRateLimitEnabled"
name="contactRateLimitEnabled"
checked={rateLimitEnabled}
onCheckedChange={(checked) => setRateLimitEnabled(checked === true)}
className="mt-0.5"
/>
<span className="space-y-1">
<span className="block text-sm font-medium text-foreground">Enable rate limiting</span>
<span className="block text-xs text-muted-foreground">
{rateLimitEnabled
? "ON: Das Formular blockiert zu viele Anfragen pro Zeitfenster."
: "OFF: Keine serverseitige Begrenzung aktiv."}
</span>
</span>
</label>
</div>
<div className="space-y-2">
<Label htmlFor="contactRateLimitMaxRequests">Max Requests</Label>
<Input
id="contactRateLimitMaxRequests"
name="contactRateLimitMaxRequests"
type="number"
min="1"
defaultValue={initialSettings.rateLimit.maxRequests}
/>
</div>
<div className="space-y-2">
<Label htmlFor="contactRateLimitWindowMinutes">Window Minutes</Label>
<Input
id="contactRateLimitWindowMinutes"
name="contactRateLimitWindowMinutes"
type="number"
min="1"
defaultValue={initialSettings.rateLimit.windowMinutes}
/>
</div>
</CardContent>
</AppCard>
<div className="xl:col-span-2 flex justify-end">
<Button type="submit">Save Protection</Button>
</div>
</form>
);
}
@@ -0,0 +1,48 @@
import { AppCard } from "@/components/ui/app-card";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import type { MarqueeSettings } from "@/lib/marquee-settings";
type MarqueeSettingsFormProps = {
action: (formData: FormData) => Promise<void>;
initialSettings: MarqueeSettings;
};
const rowMeta = [
{ key: "row1", label: "Row 1" },
{ key: "row2", label: "Row 2" },
{ key: "row3", label: "Row 3" },
{ key: "row4", label: "Row 4" },
] as const;
export function MarqueeSettingsForm({
action,
initialSettings,
}: MarqueeSettingsFormProps) {
return (
<form id="marquee-settings-form" action={action} className="space-y-5">
<div className="space-y-2">
<h2 className="text-lg font-semibold text-foreground">Marquee Rows</h2>
<p className="text-sm text-muted-foreground">Nur Deutsch bearbeiten. Die Werte werden fuer alle Sprachen uebernommen.</p>
</div>
<div className="grid gap-4 xl:grid-cols-4">
{rowMeta.map((row) => (
<AppCard key={`de-${row.key}`} level={2} padding="sm" className="space-y-2">
<Label htmlFor={`${row.key}-de`} className="text-sm font-semibold text-foreground">{row.label}</Label>
<Textarea
id={`${row.key}-de`}
name={`${row.key}-de`}
defaultValue={initialSettings.locales.de[row.key]}
className="min-h-[220px] resize-y"
/>
</AppCard>
))}
</div>
<div className="flex justify-end">
<Button type="submit">Save Marquee</Button>
</div>
</form>
);
}
+220
View File
@@ -0,0 +1,220 @@
"use client";
/* eslint-disable @next/next/no-img-element */
import type { MediaKind } from "@prisma/client";
import { Check, ImageIcon, Search, Trash2 } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import { AppCard } from "@/components/ui/app-card";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import type { MediaOption } from "@/lib/media";
import { cn } from "@/lib/utils";
export type MediaFieldState = {
mode: "upload" | "external" | "library";
assetId: string;
url: string;
label: string;
kind: MediaKind;
isCleared?: boolean;
};
type MediaFieldPickerProps = {
title: string;
value: MediaFieldState;
onChange: (nextValue: MediaFieldState) => void;
options: MediaOption[];
hasInitialValue?: boolean;
inputName: string;
fileFieldName: string;
allowClear?: boolean;
clearLabel?: string;
emptyValue?: Partial<MediaFieldState>;
};
export function MediaFieldPicker({
title,
value,
onChange,
options,
hasInitialValue = false,
inputName,
allowClear = false,
clearLabel = "Remove",
emptyValue,
}: MediaFieldPickerProps) {
const hiddenInputRef = useRef<HTMLInputElement | null>(null);
const [open, setOpen] = useState(false);
const [query, setQuery] = useState("");
const filteredOptions = options.filter((option) => option.kind === value.kind);
const selectedOption = filteredOptions.find((option) => option.id === value.assetId) ?? null;
const visibleOptions = useMemo(() => {
const normalizedQuery = query.trim().toLowerCase();
if (!normalizedQuery) {
return filteredOptions;
}
return filteredOptions.filter((option) => option.label.toLowerCase().includes(normalizedQuery));
}, [filteredOptions, query]);
const serializedValue = JSON.stringify({
mode: value.mode,
assetId: value.assetId,
url: value.url,
label: value.label,
kind: value.kind,
});
const canClear = allowClear && (Boolean(value.assetId) || (hasInitialValue && !value.isCleared));
useEffect(() => {
const hiddenInput = hiddenInputRef.current;
if (!hiddenInput) {
return;
}
hiddenInput.dispatchEvent(new Event("input", { bubbles: true }));
hiddenInput.dispatchEvent(new Event("change", { bubbles: true }));
}, [serializedValue]);
return (
<AppCard level={2} padding="sm" className="space-y-4">
<input ref={hiddenInputRef} type="hidden" name={inputName} value={serializedValue} />
<div className="flex items-start justify-between gap-4">
<div className="space-y-1">
<Label className="text-sm font-semibold text-foreground">{title}</Label>
<p className="text-sm text-muted-foreground">
Media must be selected from the
{" "}
Media Library
.
</p>
</div>
<div className="flex gap-2">
<Button type="button" variant="outline" onClick={() => setOpen(true)}>
<ImageIcon className="h-4 w-4" />
Select from Media
</Button>
{canClear ? (
<Button
type="button"
variant="ghost"
className="text-destructive hover:text-destructive"
onClick={() =>
onChange({
...value,
mode: emptyValue?.mode ?? "upload",
assetId: emptyValue?.assetId ?? "",
url: emptyValue?.url ?? "",
label: emptyValue?.label ?? "",
isCleared: true,
})
}
>
<Trash2 className="h-4 w-4" />
{clearLabel}
</Button>
) : null}
</div>
</div>
<AppCard padding="sm" className="rounded-nested border-border/70">
{selectedOption ? (
<div className="flex items-center gap-4">
<img
src={selectedOption.url}
alt={selectedOption.label}
className="h-16 w-16 rounded-nested object-cover"
/>
<div className="min-w-0">
<p className="truncate text-sm font-medium text-foreground">{selectedOption.label}</p>
<p className="truncate text-xs text-muted-foreground">{selectedOption.source}</p>
</div>
</div>
) : (
<div className="rounded-nested border border-dashed border-border/70 px-4 py-6 text-sm text-muted-foreground">
No media selected.
</div>
)}
</AppCard>
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent className="max-w-4xl">
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
<DialogDescription>Select an existing item from the media library.</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div className="relative">
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
value={query}
onChange={(event) => setQuery(event.target.value)}
placeholder="Search media"
className="pl-9"
/>
</div>
<div className="grid max-h-[55vh] gap-3 overflow-y-auto md:grid-cols-2 xl:grid-cols-3">
{visibleOptions.map((option) => {
const isActive = option.id === value.assetId;
return (
<button
key={option.id}
type="button"
onClick={() => {
onChange({
...value,
mode: "library",
assetId: option.id,
url: option.url,
label: option.label,
isCleared: false,
});
setOpen(false);
}}
className={cn(
"overflow-hidden rounded-surface border text-left transition-colors",
isActive
? "border-input bg-accent/20"
: "border-border/70 bg-card hover:border-input hover:bg-accent/10",
)}
>
<img src={option.url} alt={option.label} className="h-40 w-full object-cover" />
<div className="flex items-center justify-between gap-3 p-4">
<div className="min-w-0">
<p className="truncate text-sm font-medium text-foreground">{option.label}</p>
<p className="truncate text-xs text-muted-foreground">{option.source}</p>
</div>
{isActive ? <Check className="h-4 w-4 text-brand-primary" /> : null}
</div>
</button>
);
})}
</div>
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={() => setOpen(false)}>
Close
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</AppCard>
);
}
+508
View File
@@ -0,0 +1,508 @@
"use client";
/* eslint-disable @next/next/no-img-element */
import type { MediaKind } from "@prisma/client";
import { FileType2, Grid2x2, ImageIcon, LayoutList, LoaderCircle, Trash2, Upload } from "lucide-react";
import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import { useFormStatus } from "react-dom";
import { useSearchParams } from "next/navigation";
import type { MediaAssetView } from "@/lib/media";
import { MotionFade } from "@/components/motion-fade";
import { AppCard } from "@/components/ui/app-card";
import { Button } from "@/components/ui/button";
import { CardContent } from "@/components/ui/card";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Table, TableBody, TableCell, TableRow } from "@/components/ui/table";
import { cn } from "@/lib/utils";
import { createMediaAssetAction, deleteMediaAssetAction } from "@/app/_admin/media/actions";
const copy = {
addMedia: "Upload Media File",
addMediaDescription: "Datei hochladen und direkt in die Media Library uebernehmen.",
addMediaHint: "PNG, JPG, GIF oder PDF bis 5 MB",
label: "Bezeichnung",
kind: "Typ",
image: "Image",
document: "Document",
upload: "Upload",
uploading: "Uploading...",
selectFile: "Datei auswaehlen",
empty: "Noch keine Bilder vorhanden.",
grid: "Grid",
list: "List",
detailsButton: "Details",
open: "Open",
delete: "Delete",
deleteConfirm: "Delete this media file?",
usages: "Verwendungen",
source: "Quelle",
fileName: "Dateiname",
url: "URL",
mimeType: "MIME Type",
size: "Dateigroesse",
createdAt: "Erstellt",
close: "Close",
details: "Bilddetails",
detailsDescription: "Metadaten und Verwendungen der ausgewaehlten Datei.",
};
function formatFileSize(size: number | null) {
if (!size) {
return "—";
}
if (size < 1024) {
return `${size} B`;
}
if (size < 1024 * 1024) {
return `${(size / 1024).toFixed(1)} KB`;
}
return `${(size / (1024 * 1024)).toFixed(1)} MB`;
}
function formatCreatedAt(value: string | Date) {
const date = value instanceof Date ? value : new Date(value);
return new Intl.DateTimeFormat("de-DE", {
dateStyle: "medium",
timeStyle: "short",
}).format(date);
}
function getAbsoluteUrl(path: string) {
if (/^https?:\/\//.test(path)) {
return path;
}
if (typeof window === "undefined") {
return path;
}
return new URL(path, window.location.origin).toString();
}
function UploadSubmitButton() {
const { pending } = useFormStatus();
return (
<Button type="submit" disabled={pending} className="w-full sm:w-auto">
{pending ? <LoaderCircle className="h-4 w-4 animate-spin" /> : <Upload className="h-4 w-4" />}
{pending ? copy.uploading : copy.upload}
</Button>
);
}
function MediaUploadDialog({
open,
onOpenChange,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
}) {
const [kind, setKind] = useState<MediaKind>("IMAGE");
const [label, setLabel] = useState("");
const [isLabelDirty, setIsLabelDirty] = useState(false);
useEffect(() => {
if (!open) {
setKind("IMAGE");
setLabel("");
setIsLabelDirty(false);
}
}, [open]);
function handleFileChange(event: React.ChangeEvent<HTMLInputElement>) {
const file = event.target.files?.[0];
if (!file || isLabelDirty) {
return;
}
setLabel(file.name.replace(/\.[^.]+$/, ""));
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogTrigger asChild>
<button
type="button"
className="group block w-full rounded-surface border-2 border-dashed border-border/80 bg-surface-2 p-3 text-left transition-colors hover:border-primary/50 hover:bg-accent/30"
>
<div className="flex min-h-[240px] flex-col items-center justify-center rounded-nested border border-border/60 bg-background px-6 py-10 text-center">
<div className="flex h-16 w-16 items-center justify-center rounded-nested bg-muted text-muted-foreground">
<ImageIcon className="h-8 w-8" />
</div>
<p className="mt-6 text-2xl font-semibold text-foreground">{copy.addMedia}</p>
<p className="mt-2 text-sm text-muted-foreground">{copy.addMediaHint}</p>
<span className="mt-6 inline-flex h-11 items-center justify-center rounded-nested bg-primary px-5 text-sm font-medium text-primary-foreground shadow-sm transition-colors group-hover:bg-primary/92">
{copy.addMedia}
</span>
</div>
</button>
</DialogTrigger>
<DialogContent className="max-h-[calc(100vh-1.5rem)] w-[calc(100vw-1rem)] max-w-2xl overflow-y-auto">
<DialogHeader>
<DialogTitle>{copy.addMedia}</DialogTitle>
<DialogDescription>{copy.addMediaDescription}</DialogDescription>
</DialogHeader>
<form action={createMediaAssetAction} className="space-y-6">
<div className="space-y-2">
<Label htmlFor="media-label">{copy.label}</Label>
<Input
id="media-label"
name="label"
value={label}
onChange={(event) => {
setLabel(event.target.value);
setIsLabelDirty(true);
}}
placeholder={copy.label}
/>
</div>
<div className="space-y-3">
<Label>{copy.kind}</Label>
<div className="flex flex-wrap gap-2">
{[
{ value: "IMAGE" as const, label: copy.image, icon: ImageIcon },
{ value: "DOCUMENT" as const, label: copy.document, icon: FileType2 },
].map((option) => {
const Icon = option.icon;
const isActive = kind === option.value;
return (
<button
key={option.value}
type="button"
onClick={() => setKind(option.value)}
className={cn(
"inline-flex items-center gap-2 rounded-nested border px-4 py-2 text-sm transition-colors",
isActive
? "border-input bg-primary text-primary-foreground"
: "border-input bg-background text-foreground/75 hover:bg-accent hover:text-accent-foreground",
)}
>
<Icon className="h-4 w-4" />
{option.label}
</button>
);
})}
</div>
<input type="hidden" name="kind" value={kind} />
</div>
<div className="space-y-2">
<Label htmlFor="media-file">{copy.selectFile}</Label>
<Input
id="media-file"
name="file"
type="file"
required
accept={kind === "IMAGE" ? "image/png,image/jpeg,image/gif,image/webp,image/svg+xml" : "application/pdf"}
className="file:mr-3"
onChange={handleFileChange}
/>
<p className="text-xs text-muted-foreground">{copy.addMediaHint}</p>
</div>
<DialogFooter className="sm:justify-start">
<UploadSubmitButton />
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
}
function MediaDetailsDialog({
asset,
open,
onOpenChange,
}: {
asset: MediaAssetView | null;
open: boolean;
onOpenChange: (open: boolean) => void;
}) {
if (!asset) {
return null;
}
const absoluteUrl = getAbsoluteUrl(asset.url);
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-h-[calc(100vh-1.5rem)] w-[calc(100vw-1rem)] max-w-5xl overflow-y-auto p-0">
<div className="grid gap-0 md:grid-cols-[minmax(0,1.3fr)_minmax(320px,0.9fr)]">
<div className="border-b border-border/70 bg-muted/30 md:border-b-0 md:border-r">
<div className="flex h-full items-center justify-center p-4 sm:p-6">
<Link href={asset.url} target="_blank" rel="noreferrer" className="block w-full">
<img
src={asset.url}
alt={asset.label}
className="max-h-[55vh] w-full rounded-nested object-contain transition-transform duration-300 hover:scale-[1.02] md:max-h-[75vh]"
/>
</Link>
</div>
</div>
<div className="space-y-6 p-4 sm:p-6">
<DialogHeader className="space-y-2 text-left">
<DialogTitle className="pr-8">{asset.label}</DialogTitle>
<DialogDescription>{copy.detailsDescription}</DialogDescription>
</DialogHeader>
<div className="rounded-nested border">
<Table>
<TableBody>
<TableRow>
<TableCell className="w-36 font-medium text-muted-foreground">{copy.kind}</TableCell>
<TableCell>{asset.kind}</TableCell>
</TableRow>
<TableRow>
<TableCell className="w-36 font-medium text-muted-foreground">{copy.source}</TableCell>
<TableCell>{asset.source}</TableCell>
</TableRow>
<TableRow>
<TableCell className="w-36 font-medium text-muted-foreground">{copy.fileName}</TableCell>
<TableCell className="break-all">{asset.fileName || "—"}</TableCell>
</TableRow>
<TableRow>
<TableCell className="w-36 font-medium text-muted-foreground">{copy.mimeType}</TableCell>
<TableCell className="break-all">{asset.mimeType || "—"}</TableCell>
</TableRow>
<TableRow>
<TableCell className="w-36 font-medium text-muted-foreground">{copy.size}</TableCell>
<TableCell>{formatFileSize(asset.size)}</TableCell>
</TableRow>
<TableRow>
<TableCell className="w-36 font-medium text-muted-foreground">{copy.createdAt}</TableCell>
<TableCell>{formatCreatedAt(asset.createdAt)}</TableCell>
</TableRow>
</TableBody>
</Table>
</div>
{asset.usages.length > 0 ? (
<div className="space-y-2 rounded-nested border bg-muted/40 p-4 text-xs text-muted-foreground">
<p className="font-medium text-foreground">
{asset.usages.length} {copy.usages}
</p>
{asset.usages.map((usage) => (
<p key={usage.id}>
{usage.usageType} / {usage.entityType} / {usage.fieldKey}
</p>
))}
</div>
) : null}
<div className="space-y-2 rounded-nested border bg-muted/20 p-4 text-sm">
<p className="font-medium text-foreground">{copy.url}</p>
<p className="break-all text-muted-foreground">{absoluteUrl}</p>
</div>
<DialogFooter className="items-stretch sm:items-center sm:justify-between">
<Button asChild variant="outline" className="w-full sm:w-auto">
<Link href={asset.url} target="_blank" rel="noreferrer">
{copy.open}
</Link>
</Button>
<form action={deleteMediaAssetAction} className="w-full sm:w-auto">
<input type="hidden" name="assetId" value={asset.id} />
<Button
type="submit"
variant="destructive"
disabled={asset.usages.length > 0}
className="w-full sm:w-auto"
onClick={(event) => {
if (!window.confirm(copy.deleteConfirm)) {
event.preventDefault();
}
}}
>
<Trash2 className="h-4 w-4" />
{copy.delete}
</Button>
</form>
</DialogFooter>
</div>
</div>
</DialogContent>
</Dialog>
);
}
export function MediaLibraryManager({
mediaAssets,
}: {
mediaAssets: MediaAssetView[];
}) {
const searchParams = useSearchParams();
const [isUploadDialogOpen, setIsUploadDialogOpen] = useState(false);
const [selectedAssetId, setSelectedAssetId] = useState<string | null>(null);
const [viewMode, setViewMode] = useState<"grid" | "list">("grid");
const imageAssets = useMemo(
() => mediaAssets.filter((asset) => asset.kind === "IMAGE"),
[mediaAssets],
);
const selectedAsset = imageAssets.find((asset) => asset.id === selectedAssetId) ?? null;
useEffect(() => {
if (searchParams.has("success")) {
setIsUploadDialogOpen(false);
setSelectedAssetId(null);
}
}, [searchParams]);
return (
<div className="space-y-6">
<MotionFade delay={0.15}>
<MediaUploadDialog open={isUploadDialogOpen} onOpenChange={setIsUploadDialogOpen} />
</MotionFade>
{imageAssets.length > 0 ? (
<div className="flex justify-end">
<div className="inline-flex rounded-nested border border-input bg-background p-1">
<button
type="button"
onClick={() => setViewMode("grid")}
className={cn(
"inline-flex items-center gap-2 rounded-nested px-3 py-2 text-sm transition-colors",
viewMode === "grid"
? "bg-primary text-primary-foreground"
: "text-foreground/75 hover:bg-accent hover:text-accent-foreground",
)}
>
<Grid2x2 className="h-4 w-4" />
{copy.grid}
</button>
<button
type="button"
onClick={() => setViewMode("list")}
className={cn(
"inline-flex items-center gap-2 rounded-nested px-3 py-2 text-sm transition-colors",
viewMode === "list"
? "bg-primary text-primary-foreground"
: "text-foreground/75 hover:bg-accent hover:text-accent-foreground",
)}
>
<LayoutList className="h-4 w-4" />
{copy.list}
</button>
</div>
</div>
) : null}
{imageAssets.length > 0 ? (
viewMode === "grid" ? (
<div className="grid grid-cols-[repeat(auto-fill,minmax(160px,1fr))] gap-4 sm:grid-cols-[repeat(auto-fill,minmax(180px,1fr))] xl:grid-cols-[repeat(auto-fill,minmax(210px,1fr))]">
{imageAssets.map((asset, index) => (
<MotionFade key={asset.id} delay={0.18 + index * 0.02}>
<button
type="button"
onClick={() => setSelectedAssetId(asset.id)}
className="group text-left"
>
<AppCard
layer="single"
padding="none"
interactive
className="overflow-hidden"
>
<div className="aspect-square overflow-hidden bg-muted/30">
<img
src={asset.url}
alt={asset.label}
className="h-full w-full object-cover transition-transform duration-300 group-hover:scale-110"
/>
</div>
</AppCard>
</button>
</MotionFade>
))}
</div>
) : (
<div className="space-y-3">
{imageAssets.map((asset, index) => (
<MotionFade key={asset.id} delay={0.18 + index * 0.02}>
<AppCard layer="single" padding="none" className="overflow-hidden">
<div className="flex flex-col gap-4 p-4 sm:flex-row sm:items-center">
<button
type="button"
onClick={() => setSelectedAssetId(asset.id)}
className="group h-24 w-full overflow-hidden rounded-nested border bg-muted/30 sm:w-24"
>
<img
src={asset.url}
alt={asset.label}
className="h-full w-full object-cover transition-transform duration-300 group-hover:scale-110"
/>
</button>
<div className="min-w-0 flex-1 space-y-1">
<p className="truncate font-medium text-foreground">{asset.label}</p>
<p className="text-sm text-muted-foreground">{formatFileSize(asset.size)}</p>
<p className="truncate text-sm text-muted-foreground">{formatCreatedAt(asset.createdAt)}</p>
</div>
<div className="flex w-full flex-col gap-2 sm:w-auto sm:flex-row">
<Button
type="button"
variant="outline"
className="w-full sm:w-auto"
onClick={() => setSelectedAssetId(asset.id)}
>
{copy.detailsButton}
</Button>
<Button asChild variant="outline" className="w-full sm:w-auto">
<Link href={asset.url} target="_blank" rel="noreferrer">
{copy.open}
</Link>
</Button>
</div>
</div>
</AppCard>
</MotionFade>
))}
</div>
)
) : (
<MotionFade delay={0.18}>
<AppCard>
<CardContent className="p-6 text-sm text-muted-foreground">
{copy.empty}
</CardContent>
</AppCard>
</MotionFade>
)}
<MediaDetailsDialog
asset={selectedAsset}
open={Boolean(selectedAsset)}
onOpenChange={(open) => {
if (!open) {
setSelectedAssetId(null);
}
}}
/>
</div>
);
}
@@ -0,0 +1,449 @@
"use client";
import { useEffect, useState } from "react";
import { useSearchParams } from "next/navigation";
import {
FileText,
FolderPlus,
Hash,
Layers3,
Pencil,
Sparkles,
Text,
Trash2,
} from "lucide-react";
import type { deleteCategoryAction, upsertCategoryAction } from "@/app/_admin/portfolio/actions";
import { StatsCard } from "@/components/dashboard/stats-card";
import { AppCard } from "@/components/ui/app-card";
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@/components/ui/accordion";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { CardContent } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
import { Textarea } from "@/components/ui/textarea";
import type { PortfolioCategoryView } from "@/lib/portfolio";
const locales = [
{ key: "Ar", label: "Arabic" },
{ key: "En", label: "English" },
{ key: "De", label: "German" },
] as const;
const copy = {
addCategory: "Add Category",
saveCategory: "Save Category",
save: "Save",
delete: "Delete",
active: "Active",
sortOrder: "Sort Order",
projects: "Projects",
description: "Description",
currentCategories: "Current Categories",
modalDescription: "Create a new category with a faster flow for basics, localization, and status.",
editDescription: "Update category content, change status, or remove the category if it has no assigned projects.",
empty: "No categories yet.",
deleteBlocked: "Delete becomes available only when no projects are assigned.",
editCategory: "Edit Category",
};
type CategoryAction = typeof upsertCategoryAction;
type CategoryDeleteAction = typeof deleteCategoryAction;
type CategoryFormValues = {
slug?: string;
sortOrder?: number;
isActive?: boolean;
nameAr?: string;
nameEn?: string;
nameDe?: string;
descriptionAr?: string;
descriptionEn?: string;
descriptionDe?: string;
};
type PortfolioCategoriesManagerProps = {
categories: Array<PortfolioCategoryView & { projectCount: number }>;
activeCount: number;
assignedProjects: number;
saveCategoryAction: CategoryAction;
removeCategoryAction: CategoryDeleteAction;
};
function CategoryLocaleFields({
idPrefix,
values,
}: {
idPrefix: string;
values?: CategoryFormValues;
}) {
return (
<div className="space-y-4">
<div className="space-y-1">
<p className="text-sm font-semibold text-foreground">Localized Content</p>
<p className="text-sm text-muted-foreground">
Keep names and descriptions ready in all supported locales.
</p>
</div>
<div className="grid gap-4 xl:grid-cols-3">
{locales.map((locale) => {
const nameKey = `name${locale.key}` as const;
const descriptionKey = `description${locale.key}` as const;
return (
<AppCard key={`${idPrefix}-${locale.key}`} level={2} padding="sm" className="space-y-4 rounded-nested">
<p className="text-sm font-medium text-foreground">{locale.label}</p>
<div className="space-y-2">
<Label htmlFor={`${idPrefix}-${nameKey}`}>Name</Label>
<div className="relative">
<Text className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
id={`${idPrefix}-${nameKey}`}
name={nameKey}
defaultValue={values?.[nameKey] ?? ""}
required
placeholder={`Name ${locale.label}`}
className="pl-9"
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor={`${idPrefix}-${descriptionKey}`}>{copy.description}</Label>
<div className="relative">
<FileText className="pointer-events-none absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
<Textarea
id={`${idPrefix}-${descriptionKey}`}
name={descriptionKey}
rows={5}
defaultValue={values?.[descriptionKey] ?? ""}
required
placeholder={`${copy.description} ${locale.label}`}
className="pl-9"
/>
</div>
</div>
</AppCard>
);
})}
</div>
</div>
);
}
function CategoryForm({
formId,
action,
values,
categoryId,
}: {
formId: string;
action: CategoryAction;
values?: CategoryFormValues;
categoryId?: string;
}) {
return (
<form id={formId} action={action} className="space-y-6">
{categoryId ? <input type="hidden" name="id" value={categoryId} /> : null}
<input type="hidden" name="redirectPath" value="/portfolio/categories" />
<div className="space-y-4">
<div className="space-y-1">
<p className="text-sm font-semibold text-foreground">Basics</p>
<p className="text-sm text-muted-foreground">
Set the stable identifier and display order first.
</p>
</div>
<div className="grid gap-4 lg:grid-cols-3">
<div className="space-y-2">
<Label htmlFor={`${formId}-slug`}>Slug</Label>
<div className="relative">
<Text className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
id={`${formId}-slug`}
name="slug"
defaultValue={values?.slug ?? ""}
required
placeholder="Slug"
className="pl-9"
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor={`${formId}-sortOrder`}>{copy.sortOrder}</Label>
<div className="relative">
<Hash className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
id={`${formId}-sortOrder`}
name="sortOrder"
type="number"
min="0"
defaultValue={values?.sortOrder ?? 0}
required
className="pl-9"
/>
</div>
</div>
<label className="flex items-center gap-3 rounded-nested border border-input bg-card px-4 py-3 text-sm">
<Checkbox name="isActive" defaultChecked={values?.isActive ?? true} />
{copy.active}
</label>
</div>
</div>
<Separator />
<CategoryLocaleFields idPrefix={formId} values={values} />
</form>
);
}
function EditCategoryDialog({
category,
open,
onOpenChange,
saveCategoryAction,
removeCategoryAction,
}: {
category: PortfolioCategoriesManagerProps["categories"][number];
open: boolean;
onOpenChange: (open: boolean) => void;
saveCategoryAction: CategoryAction;
removeCategoryAction: CategoryDeleteAction;
}) {
const formId = `portfolio-category-form-${category.id}`;
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>{copy.editCategory}</DialogTitle>
<DialogDescription>{copy.editDescription}</DialogDescription>
</DialogHeader>
<div className="grid gap-3 sm:grid-cols-3">
<AppCard level={2} padding="sm" className="rounded-nested">
<p className="text-xs uppercase tracking-[0.18em] text-muted-foreground">Projects</p>
<p className="mt-2 text-lg font-semibold text-foreground">{category.projectCount}</p>
</AppCard>
<AppCard level={2} padding="sm" className="rounded-nested">
<p className="text-xs uppercase tracking-[0.18em] text-muted-foreground">Status</p>
<div className="mt-2">
<Badge variant={category.isActive ? "success" : "warning"}>
{category.isActive ? "Active" : "Inactive"}
</Badge>
</div>
</AppCard>
<AppCard level={2} padding="sm" className="rounded-nested">
<p className="text-xs uppercase tracking-[0.18em] text-muted-foreground">Order</p>
<p className="mt-2 text-lg font-semibold text-foreground">{category.sortOrder}</p>
</AppCard>
</div>
<CategoryForm
formId={formId}
action={saveCategoryAction}
categoryId={category.id}
values={{
slug: category.slug,
sortOrder: category.sortOrder,
isActive: category.isActive,
nameAr: category.name.ar,
nameEn: category.name.en,
nameDe: category.name.de,
descriptionAr: category.description.ar,
descriptionEn: category.description.en,
descriptionDe: category.description.de,
}}
/>
<DialogFooter className="items-center justify-between sm:flex-row">
<p className="text-sm text-muted-foreground">
{category.projectCount > 0 ? copy.deleteBlocked : "Category can be deleted."}
</p>
<div className="flex w-full flex-col-reverse gap-2 sm:w-auto sm:flex-row">
<form action={removeCategoryAction}>
<input type="hidden" name="id" value={category.id} />
<input type="hidden" name="redirectPath" value="/portfolio/categories" />
<Button type="submit" variant="destructive" disabled={category.projectCount > 0}>
<Trash2 className="h-4 w-4" />
{copy.delete}
</Button>
</form>
<Button type="submit" form={formId}>
{copy.save}
</Button>
</div>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
export function PortfolioCategoriesManager({
categories,
activeCount,
assignedProjects,
saveCategoryAction,
removeCategoryAction,
}: PortfolioCategoriesManagerProps) {
const searchParams = useSearchParams();
const [createOpen, setCreateOpen] = useState(false);
const [editingCategoryId, setEditingCategoryId] = useState<string | null>(null);
useEffect(() => {
if (searchParams.has("success")) {
setCreateOpen(false);
setEditingCategoryId(null);
}
}, [searchParams]);
return (
<div className="space-y-6">
<AppCard level={3}>
<CardContent className="flex flex-col gap-6 p-6 lg:flex-row lg:items-end lg:justify-between lg:p-8">
<div className="grid gap-4 sm:grid-cols-3">
<StatsCard title="Total" value={String(categories.length)} />
<StatsCard title="Active" value={String(activeCount)} />
<StatsCard title="Assigned" value={String(assignedProjects)} />
</div>
<Dialog open={createOpen} onOpenChange={setCreateOpen}>
<DialogTrigger asChild>
<Button>
<FolderPlus className="h-4 w-4" />
{copy.addCategory}
</Button>
</DialogTrigger>
<DialogContent className="max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>{copy.addCategory}</DialogTitle>
<DialogDescription>{copy.modalDescription}</DialogDescription>
</DialogHeader>
<div className="grid gap-3 sm:grid-cols-3">
<AppCard level={2} padding="sm" className="rounded-nested">
<Sparkles className="h-4 w-4 text-brand-primary" />
<p className="mt-3 text-sm font-medium text-foreground">Start with basics</p>
<p className="mt-1 text-sm text-muted-foreground">Slug and sort order first.</p>
</AppCard>
<AppCard level={2} padding="sm" className="rounded-nested">
<Layers3 className="h-4 w-4 text-brand-primary" />
<p className="mt-3 text-sm font-medium text-foreground">Fill all locales</p>
<p className="mt-1 text-sm text-muted-foreground">Keep names and descriptions complete.</p>
</AppCard>
<AppCard level={2} padding="sm" className="rounded-nested">
<Pencil className="h-4 w-4 text-brand-primary" />
<p className="mt-3 text-sm font-medium text-foreground">Publish when ready</p>
<p className="mt-1 text-sm text-muted-foreground">Categories stay manageable from day one.</p>
</AppCard>
</div>
<CategoryForm
formId="portfolio-category-create-form"
action={saveCategoryAction}
/>
<DialogFooter>
<Button type="submit" form="portfolio-category-create-form">
{copy.saveCategory}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</CardContent>
</AppCard>
<AppCard level={3}>
<CardContent className="space-y-4 p-6">
<div className="flex items-center gap-3">
<Layers3 className="h-5 w-5 text-brand-primary" />
<h2 className="text-lg font-semibold text-foreground">{copy.currentCategories}</h2>
</div>
{categories.length === 0 ? (
<p className="text-sm text-muted-foreground">{copy.empty}</p>
) : (
<Accordion type="single" collapsible className="space-y-3">
{categories.map((category) => (
<AccordionItem key={category.id} value={category.id}>
<AccordionTrigger className="bg-surface-2 hover:no-underline">
<div className="flex min-w-0 flex-1 flex-col gap-3 text-left lg:flex-row lg:items-center lg:justify-between">
<div className="space-y-1">
<div className="flex flex-wrap items-center gap-2">
<span className="text-base font-semibold text-foreground">
{category.name.de || category.name.en || category.name.ar}
</span>
<Badge variant={category.isActive ? "success" : "warning"}>
{category.isActive ? "Active" : "Inactive"}
</Badge>
</div>
<div className="flex flex-wrap gap-2 text-xs text-muted-foreground">
<span>{category.slug}</span>
<span>{copy.projects}: {category.projectCount}</span>
<span>{copy.sortOrder}: {category.sortOrder}</span>
</div>
</div>
<Button
type="button"
variant="outline"
onClick={(event) => {
event.preventDefault();
setEditingCategoryId(category.id);
}}
>
<Pencil className="h-4 w-4" />
Edit
</Button>
</div>
</AccordionTrigger>
<AccordionContent className="space-y-4">
<div className="grid gap-4 xl:grid-cols-3">
{locales.map((locale) => (
<AppCard key={`${category.id}-${locale.key}`} level={2} padding="sm" className="space-y-3 rounded-nested">
<p className="text-sm font-medium text-foreground">{locale.label}</p>
<p className="text-sm font-semibold text-foreground">
{category.name[locale.key.toLowerCase() as "ar" | "en" | "de"]}
</p>
<p className="text-sm leading-6 text-muted-foreground">
{category.description[locale.key.toLowerCase() as "ar" | "en" | "de"]}
</p>
</AppCard>
))}
</div>
<EditCategoryDialog
category={category}
open={editingCategoryId === category.id}
onOpenChange={(open) => setEditingCategoryId(open ? category.id : null)}
saveCategoryAction={saveCategoryAction}
removeCategoryAction={removeCategoryAction}
/>
</AccordionContent>
</AccordionItem>
))}
</Accordion>
)}
</CardContent>
</AppCard>
</div>
);
}
@@ -0,0 +1,80 @@
"use client";
import { FolderKanban, MoreVertical, Trash2 } from "lucide-react";
import Link from "next/link";
import { useState } from "react";
import { deleteProjectAction } from "@/app/_admin/portfolio/actions";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
const copy = {
editProject: "Bearbeiten",
deleteProject: "Loeschen",
};
export function PortfolioProjectActions({ projectId }: { projectId: string }) {
const [confirmOpen, setConfirmOpen] = useState(false);
return (
<Dialog open={confirmOpen} onOpenChange={setConfirmOpen}>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button type="button" variant="outline" size="icon">
<MoreVertical className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem asChild>
<Link href={`/portfolio/projects/${projectId}`}>
<FolderKanban className="mr-2 h-4 w-4" />
{copy.editProject}
</Link>
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
className="text-destructive focus:text-destructive"
onSelect={(event) => {
event.preventDefault();
setConfirmOpen(true);
}}
>
<Trash2 className="mr-2 h-4 w-4" />
{copy.deleteProject}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<DialogContent>
<DialogHeader>
<DialogTitle>{copy.deleteProject}</DialogTitle>
<DialogDescription>
This action permanently removes the project from the portfolio.
</DialogDescription>
</DialogHeader>
<DialogFooter>
<form action={deleteProjectAction}>
<input type="hidden" name="id" value={projectId} />
<Button type="submit" variant="destructive">
Confirm Delete
</Button>
</form>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
+670
View File
@@ -0,0 +1,670 @@
"use client";
import type { PortfolioProjectViewMode, PortfolioSectionType } from "@prisma/client";
import {
ArrowDown,
ArrowUp,
CalendarDays,
FolderTree,
Layers3,
Link2,
Plus,
Text,
Trash2,
UserRound,
} from "lucide-react";
import { type ReactNode, useEffect, useRef, useState } from "react";
import { MediaFieldPicker, type MediaFieldState } from "@/components/admin/media-field-picker";
import { AppCard } from "@/components/ui/app-card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { moveArrayItem } from "@/lib/array";
import type { MediaOption } from "@/lib/media";
import type { PortfolioCategoryView, PortfolioProjectView } from "@/lib/portfolio";
import { cn } from "@/lib/utils";
type SectionFormValue = {
id?: string;
type: PortfolioSectionType;
titleAr: string;
titleEn: string;
titleDe: string;
bodyAr: string;
bodyEn: string;
bodyDe: string;
imagePath: string;
media: MediaFieldState;
linkUrl: string;
sortOrder: number;
};
type AssetFormValue = {
id?: string;
kind: "IMAGE";
filePath: string;
fileFieldName: string;
media: MediaFieldState;
altAr: string;
altEn: string;
altDe: string;
sortOrder: number;
};
type ProjectFormState = {
categoryId: string;
slug: string;
clientName: string;
projectYear: string;
previewUrl: string;
sortOrder: string;
viewMode: PortfolioProjectViewMode;
isFeatured: boolean;
isPublished: boolean;
titleAr: string;
titleEn: string;
titleDe: string;
serviceLabelAr: string;
serviceLabelEn: string;
serviceLabelDe: string;
summaryAr: string;
summaryEn: string;
summaryDe: string;
};
type PortfolioProjectFormProps = {
action: (formData: FormData) => void | Promise<void>;
categories: PortfolioCategoryView[];
mediaOptions: MediaOption[];
project?: PortfolioProjectView | null;
formId: string;
redirectPath: string;
};
const locales = [
{ suffix: "Ar" as const, label: "Arabic" },
{ suffix: "En" as const, label: "English" },
{ suffix: "De" as const, label: "German" },
] as const;
const sectionTypeOptions: PortfolioSectionType[] = [
"RICH_TEXT",
"GALLERY",
"STATS",
"DELIVERABLES",
"LINK",
];
const viewModeOptions: Array<{
value: PortfolioProjectViewMode;
label: string;
description: string;
}> = [
{ value: "GRID", label: "Grid", description: "Balanced modular layout." },
{ value: "STORY", label: "Story", description: "Narrative section flow." },
{ value: "CASE_STUDY", label: "Case Study", description: "Structured challenge and result view." },
];
function createMediaFieldState(params: {
kind: "IMAGE";
assetId?: string | null;
url?: string | null;
label?: string | null;
}): MediaFieldState {
return {
mode: params.assetId ? "library" : "upload",
assetId: params.assetId ?? "",
url: params.url ?? "",
label: params.label ?? "",
kind: params.kind,
};
}
function createInitialState(
project: PortfolioProjectView | null | undefined,
categories: PortfolioCategoryView[],
): ProjectFormState {
return {
categoryId: project?.category.id ?? categories[0]?.id ?? "",
slug: project?.slug ?? "",
clientName: project?.clientName ?? "",
projectYear: String(project?.projectYear ?? new Date().getFullYear()),
previewUrl: project?.previewUrl ?? "",
sortOrder: String(project?.sortOrder ?? 0),
viewMode: project?.viewMode ?? "GRID",
isFeatured: project?.isFeatured ?? false,
isPublished: project?.isPublished ?? false,
titleAr: project?.title.ar ?? "",
titleEn: project?.title.en ?? "",
titleDe: project?.title.de ?? "",
serviceLabelAr: project?.serviceLabel.ar ?? "",
serviceLabelEn: project?.serviceLabel.en ?? "",
serviceLabelDe: project?.serviceLabel.de ?? "",
summaryAr: project?.summary.ar ?? "",
summaryEn: project?.summary.en ?? "",
summaryDe: project?.summary.de ?? "",
};
}
function createEmptySection(index: number): SectionFormValue {
return {
type: "RICH_TEXT",
titleAr: "",
titleEn: "",
titleDe: "",
bodyAr: "",
bodyEn: "",
bodyDe: "",
imagePath: "",
media: createMediaFieldState({ kind: "IMAGE" }),
linkUrl: "",
sortOrder: index,
};
}
function createEmptyAsset(index: number): AssetFormValue {
return {
kind: "IMAGE",
filePath: "",
fileFieldName: `asset-upload-${index}`,
media: createMediaFieldState({ kind: "IMAGE" }),
altAr: "",
altEn: "",
altDe: "",
sortOrder: index,
};
}
function hasText(value: string) {
return value.trim().length > 0;
}
function sectionReady(section: SectionFormValue) {
if (!hasText(section.titleAr) || !hasText(section.titleEn) || !hasText(section.titleDe)) {
return false;
}
if (section.type === "GALLERY") {
return hasText(section.media.assetId);
}
if (section.type === "LINK") {
return hasText(section.linkUrl);
}
return hasText(section.bodyAr) && hasText(section.bodyEn) && hasText(section.bodyDe);
}
function assetReady(asset: AssetFormValue) {
return hasText(asset.media.assetId) && hasText(asset.altAr) && hasText(asset.altEn) && hasText(asset.altDe);
}
function LocaleInputs({
title,
namePrefix,
values,
onChange,
multiline = false,
}: {
title: string;
namePrefix?: string;
values: { Ar: string; En: string; De: string };
onChange: (key: "Ar" | "En" | "De", value: string) => void;
multiline?: boolean;
}) {
return (
<div className="space-y-3">
<p className="text-sm font-medium text-foreground">{title}</p>
<div className="grid gap-3 xl:grid-cols-3">
{locales.map((locale) => (
<AppCard key={`${title}-${locale.suffix}`} level={2} padding="sm" className="space-y-2 rounded-nested">
<p className="text-xs uppercase tracking-[0.18em] text-muted-foreground">{locale.label}</p>
{multiline ? (
<Textarea
name={namePrefix ? `${namePrefix}${locale.suffix}` : undefined}
rows={5}
value={values[locale.suffix]}
onChange={(event) => onChange(locale.suffix, event.target.value)}
/>
) : (
<Input
name={namePrefix ? `${namePrefix}${locale.suffix}` : undefined}
value={values[locale.suffix]}
onChange={(event) => onChange(locale.suffix, event.target.value)}
/>
)}
</AppCard>
))}
</div>
</div>
);
}
function SectionHeader({
title,
description,
action,
}: {
title: string;
description: string;
action?: ReactNode;
}) {
return (
<div className="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
<div className="space-y-1">
<h3 className="text-lg font-semibold text-foreground">{title}</h3>
<p className="text-sm text-muted-foreground">{description}</p>
</div>
{action}
</div>
);
}
export function PortfolioProjectForm({
action,
categories,
mediaOptions,
project,
formId,
redirectPath,
}: PortfolioProjectFormProps) {
const [projectState, setProjectState] = useState<ProjectFormState>(createInitialState(project, categories));
const [coverMedia, setCoverMedia] = useState<MediaFieldState>(
createMediaFieldState({
kind: "IMAGE",
assetId: project?.coverMediaAssetId,
url: project?.coverImagePath,
label: project?.title.de ?? project?.title.en ?? project?.title.ar ?? "",
}),
);
const [sections, setSections] = useState<SectionFormValue[]>(
project?.sections.length
? project.sections.map((section, index) => ({
id: section.id,
type: section.type,
titleAr: section.title.ar,
titleEn: section.title.en,
titleDe: section.title.de,
bodyAr: section.body.ar,
bodyEn: section.body.en,
bodyDe: section.body.de,
imagePath: section.imagePath ?? "",
media: createMediaFieldState({
kind: "IMAGE",
assetId: section.mediaAssetId,
url: section.imagePath,
label: section.title.de || section.title.en || section.title.ar,
}),
linkUrl: section.linkUrl ?? "",
sortOrder: index,
}))
: [createEmptySection(0)],
);
const [assets, setAssets] = useState<AssetFormValue[]>(
project?.assets.length
? project.assets.map((asset, index) => ({
id: asset.id,
kind: "IMAGE",
filePath: asset.filePath,
fileFieldName: `asset-upload-${index}`,
media: createMediaFieldState({
kind: "IMAGE",
assetId: asset.mediaAssetId,
url: asset.filePath,
label: asset.alt.de || asset.alt.en || asset.alt.ar,
}),
altAr: asset.alt.ar,
altEn: asset.alt.en,
altDe: asset.alt.de,
sortOrder: index,
}))
: [createEmptyAsset(0)],
);
const sectionsInputRef = useRef<HTMLInputElement | null>(null);
const assetsInputRef = useRef<HTMLInputElement | null>(null);
const sectionsPayload = JSON.stringify(sections.map((section, index) => ({ ...section, sortOrder: index })));
const assetsPayload = JSON.stringify(assets.map((asset, index) => ({ ...asset, sortOrder: index })));
useEffect(() => {
sectionsInputRef.current?.dispatchEvent(new Event("input", { bubbles: true }));
sectionsInputRef.current?.dispatchEvent(new Event("change", { bubbles: true }));
}, [sectionsPayload]);
useEffect(() => {
assetsInputRef.current?.dispatchEvent(new Event("input", { bubbles: true }));
assetsInputRef.current?.dispatchEvent(new Event("change", { bubbles: true }));
}, [assetsPayload]);
return (
<form id={formId} action={action} className="space-y-10">
<input type="hidden" name="id" value={project?.id ?? ""} />
<input type="hidden" name="redirectPath" value={redirectPath} />
<input type="hidden" name="currentCoverImagePath" value={project?.coverImagePath ?? ""} />
<input type="hidden" name="viewMode" value={projectState.viewMode} />
<input ref={sectionsInputRef} type="hidden" name="sections" value={sectionsPayload} />
<input ref={assetsInputRef} type="hidden" name="assets" value={assetsPayload} />
<section className="space-y-5">
<SectionHeader
title="Basic Information"
description="Core data, visibility, and chosen project view."
/>
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
<div className="space-y-2">
<Label htmlFor="categoryId">Category</Label>
<div className="relative">
<FolderTree className="pointer-events-none absolute left-3 top-1/2 z-10 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Select
name="categoryId"
value={projectState.categoryId}
onValueChange={(value) => setProjectState((current) => ({ ...current, categoryId: value }))}
>
<SelectTrigger id="categoryId" className="pl-9">
<SelectValue placeholder="Category" />
</SelectTrigger>
<SelectContent>
{categories.map((category) => (
<SelectItem key={category.id} value={category.id}>
{category.name.de} / {category.name.en}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="slug">Slug</Label>
<div className="relative">
<Text className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input id="slug" name="slug" value={projectState.slug} onChange={(event) => setProjectState((current) => ({ ...current, slug: event.target.value }))} className="pl-9" />
</div>
</div>
<div className="space-y-2">
<Label htmlFor="clientName">Client</Label>
<div className="relative">
<UserRound className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input id="clientName" name="clientName" value={projectState.clientName} onChange={(event) => setProjectState((current) => ({ ...current, clientName: event.target.value }))} className="pl-9" />
</div>
</div>
<div className="space-y-2">
<Label htmlFor="projectYear">Year</Label>
<div className="relative">
<CalendarDays className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input id="projectYear" name="projectYear" type="number" min="2000" max="2100" value={projectState.projectYear} onChange={(event) => setProjectState((current) => ({ ...current, projectYear: event.target.value }))} className="pl-9" />
</div>
</div>
<div className="space-y-2">
<Label htmlFor="previewUrl">Preview URL</Label>
<div className="relative">
<Link2 className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input id="previewUrl" name="previewUrl" value={projectState.previewUrl} onChange={(event) => setProjectState((current) => ({ ...current, previewUrl: event.target.value }))} className="pl-9" />
</div>
</div>
<div className="space-y-2">
<Label htmlFor="sortOrder">Sort Order</Label>
<div className="relative">
<Layers3 className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input id="sortOrder" name="sortOrder" type="number" min="0" value={projectState.sortOrder} onChange={(event) => setProjectState((current) => ({ ...current, sortOrder: event.target.value }))} className="pl-9" />
</div>
</div>
</div>
<div className="grid gap-3 xl:grid-cols-3">
{viewModeOptions.map((option) => (
<button
key={option.value}
type="button"
onClick={() => setProjectState((current) => ({ ...current, viewMode: option.value }))}
className={cn(
"rounded-surface border px-4 py-4 text-left transition-colors",
projectState.viewMode === option.value
? "border-input bg-accent/20"
: "border-border/70 bg-background hover:border-input hover:bg-accent/10",
)}
>
<p className="text-sm font-semibold text-foreground">{option.label}</p>
<p className="mt-1 text-sm text-muted-foreground">{option.description}</p>
</button>
))}
</div>
<div className="grid gap-3 md:grid-cols-2">
<label className="flex items-center justify-between rounded-nested border border-input bg-card px-4 py-3">
<div>
<p className="text-sm font-medium text-foreground">Featured</p>
</div>
<input type="checkbox" name="isFeatured" checked={projectState.isFeatured} onChange={(event) => setProjectState((current) => ({ ...current, isFeatured: event.target.checked }))} />
</label>
<label className="flex items-center justify-between rounded-nested border border-input bg-card px-4 py-3">
<div>
<p className="text-sm font-medium text-foreground">Published</p>
</div>
<input type="checkbox" name="isPublished" checked={projectState.isPublished} onChange={(event) => setProjectState((current) => ({ ...current, isPublished: event.target.checked }))} />
</label>
</div>
</section>
<section className="space-y-5">
<SectionHeader
title="Localized Content"
description="Project title, service label, and summary in all locales."
/>
<LocaleInputs
title="Project Title"
namePrefix="title"
values={{ Ar: projectState.titleAr, En: projectState.titleEn, De: projectState.titleDe }}
onChange={(key, value) => setProjectState((current) => ({ ...current, [`title${key}`]: value }))}
/>
<LocaleInputs
title="Service Label"
namePrefix="serviceLabel"
values={{ Ar: projectState.serviceLabelAr, En: projectState.serviceLabelEn, De: projectState.serviceLabelDe }}
onChange={(key, value) => setProjectState((current) => ({ ...current, [`serviceLabel${key}`]: value }))}
/>
<LocaleInputs
title="Summary"
namePrefix="summary"
values={{ Ar: projectState.summaryAr, En: projectState.summaryEn, De: projectState.summaryDe }}
onChange={(key, value) => setProjectState((current) => ({ ...current, [`summary${key}`]: value }))}
multiline
/>
</section>
<section className="space-y-5">
<SectionHeader
title="Cover Media"
description="Select the cover only from media library."
/>
<MediaFieldPicker
title="Cover"
value={coverMedia}
onChange={setCoverMedia}
options={mediaOptions}
hasInitialValue={Boolean(project?.coverImagePath || project?.coverMediaAssetId)}
inputName="coverMedia"
fileFieldName="coverFile"
allowClear
clearLabel="Remove Cover"
emptyValue={{ mode: "upload", assetId: "", url: "", label: "" }}
/>
</section>
<section className="space-y-5">
<SectionHeader
title="Sections"
description="Every section stays inline and simple."
action={(
<Button type="button" variant="outline" onClick={() => setSections((current) => [...current, createEmptySection(current.length)])}>
<Plus className="h-4 w-4" />
Add Section
</Button>
)}
/>
<div className="space-y-4">
{sections.map((section, index) => (
<div key={section.id ?? `section-${index}`} className="space-y-4 rounded-surface border border-border/70 bg-background p-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex items-center gap-3">
<Badge variant={sectionReady(section) ? "success" : "outline"}>
{sectionReady(section) ? "Ready" : "Open"}
</Badge>
<p className="text-sm font-medium text-foreground">{`Section ${index + 1}`}</p>
</div>
<div className="flex gap-2">
<Button type="button" variant="outline" onClick={() => setSections((current) => moveArrayItem(current, index, index - 1))} disabled={index === 0}>
<ArrowUp className="h-4 w-4" />
</Button>
<Button type="button" variant="outline" onClick={() => setSections((current) => moveArrayItem(current, index, index + 1))} disabled={index === sections.length - 1}>
<ArrowDown className="h-4 w-4" />
</Button>
<Button type="button" variant="ghost" className="text-destructive" onClick={() => sections.length > 1 && setSections((current) => current.filter((_, currentIndex) => currentIndex !== index))} disabled={sections.length === 1}>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
<div className="grid gap-4 md:grid-cols-2">
<div className="space-y-2">
<Label>Type</Label>
<Select value={section.type} onValueChange={(value) => setSections((current) => current.map((item, currentIndex) => currentIndex === index ? { ...item, type: value as PortfolioSectionType } : item))}>
<SelectTrigger>
<SelectValue placeholder="Type" />
</SelectTrigger>
<SelectContent>
{sectionTypeOptions.map((type) => (
<SelectItem key={type} value={type}>{type}</SelectItem>
))}
</SelectContent>
</Select>
</div>
{section.type === "LINK" ? (
<div className="space-y-2">
<Label>Link URL</Label>
<Input value={section.linkUrl} onChange={(event) => setSections((current) => current.map((item, currentIndex) => currentIndex === index ? { ...item, linkUrl: event.target.value } : item))} />
</div>
) : null}
</div>
{section.type === "GALLERY" ? (
<MediaFieldPicker
title="Section Image"
value={section.media}
onChange={(media) => setSections((current) => current.map((item, currentIndex) => currentIndex === index ? { ...item, media, imagePath: media.url } : item))}
options={mediaOptions}
hasInitialValue={Boolean(section.media.assetId || section.imagePath)}
inputName={`section-media-${index}`}
fileFieldName={`section-image-upload-${index}`}
allowClear
clearLabel="Remove Image"
emptyValue={{ mode: "upload", assetId: "", url: "", label: "" }}
/>
) : null}
<LocaleInputs
title="Section Title"
values={{ Ar: section.titleAr, En: section.titleEn, De: section.titleDe }}
onChange={(key, value) => setSections((current) => current.map((item, currentIndex) => currentIndex === index ? { ...item, [`title${key}`]: value } : item))}
/>
{section.type !== "GALLERY" && section.type !== "LINK" ? (
<LocaleInputs
title="Section Body"
values={{ Ar: section.bodyAr, En: section.bodyEn, De: section.bodyDe }}
onChange={(key, value) => setSections((current) => current.map((item, currentIndex) => currentIndex === index ? { ...item, [`body${key}`]: value } : item))}
multiline
/>
) : null}
</div>
))}
</div>
</section>
<section className="space-y-5">
<SectionHeader
title="Assets"
description="Images from media library only."
action={(
<Button type="button" variant="outline" onClick={() => setAssets((current) => [...current, createEmptyAsset(current.length)])}>
<Plus className="h-4 w-4" />
Add Asset
</Button>
)}
/>
<div className="space-y-4">
{assets.map((asset, index) => (
<div key={asset.id ?? `asset-${index}`} className="space-y-4 rounded-surface border border-border/70 bg-background p-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex items-center gap-3">
<Badge variant={assetReady(asset) ? "success" : "outline"}>
{assetReady(asset) ? "Ready" : "Open"}
</Badge>
<p className="text-sm font-medium text-foreground">{`Asset ${index + 1}`}</p>
</div>
<div className="flex gap-2">
<Button type="button" variant="outline" onClick={() => setAssets((current) => moveArrayItem(current, index, index - 1))} disabled={index === 0}>
<ArrowUp className="h-4 w-4" />
</Button>
<Button type="button" variant="outline" onClick={() => setAssets((current) => moveArrayItem(current, index, index + 1))} disabled={index === assets.length - 1}>
<ArrowDown className="h-4 w-4" />
</Button>
<Button type="button" variant="ghost" className="text-destructive" onClick={() => assets.length > 1 && setAssets((current) => current.filter((_, currentIndex) => currentIndex !== index))} disabled={assets.length === 1}>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
<MediaFieldPicker
title="Asset Image"
value={asset.media}
onChange={(media) => setAssets((current) => current.map((item, currentIndex) => currentIndex === index ? { ...item, media, filePath: media.url } : item))}
options={mediaOptions}
hasInitialValue={Boolean(asset.media.assetId || asset.filePath)}
inputName={`asset-media-${index}`}
fileFieldName={asset.fileFieldName}
allowClear
clearLabel="Remove Asset"
emptyValue={{ mode: "upload", assetId: "", url: "", label: "" }}
/>
<LocaleInputs
title="Alt Text"
values={{ Ar: asset.altAr, En: asset.altEn, De: asset.altDe }}
onChange={(key, value) => setAssets((current) => current.map((item, currentIndex) => currentIndex === index ? { ...item, [`alt${key}`]: value } : item))}
/>
</div>
))}
</div>
</section>
<div className="flex justify-end">
<Button type="submit">
Save Project
</Button>
</div>
</form>
);
}
@@ -0,0 +1,129 @@
import { ExternalLink, Plus, Tags } from "lucide-react";
import Link from "next/link";
import { StatsCard } from "@/components/dashboard/stats-card";
import { MotionFade } from "@/components/motion-fade";
import { PortfolioProjectActions } from "@/components/admin/portfolio-project-actions";
import { AppCard } from "@/components/ui/app-card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { CardContent } from "@/components/ui/card";
import { getLocalizedPath } from "@/lib/locale";
import { getLocalizedValue, type PortfolioCategoryView, type PortfolioProjectView } from "@/lib/portfolio";
type PortfolioProjectsOverviewProps = {
categories: PortfolioCategoryView[];
projects: PortfolioProjectView[];
selectedCategory: string;
selectedStatus: "all" | "draft" | "published";
};
const copy = {
all: "Alle",
newProject: "Neues Projekt",
newCategory: "Neues Kategorie",
openProject: "Ansehen",
untitled: "Unbenanntes Projekt",
empty: "Noch keine Projekte vorhanden.",
};
export function PortfolioProjectsOverview({
categories,
projects,
selectedCategory,
}: PortfolioProjectsOverviewProps) {
return (
<div className="space-y-6">
<div className="flex flex-col gap-4 xl:flex-row xl:items-end xl:justify-between">
<div className="grid gap-4 md:grid-cols-3 xl:min-w-[520px]">
<StatsCard title="Projects" value={String(projects.length)} />
<StatsCard title="Categories" value={String(categories.length)} />
<StatsCard
title="Published"
value={String(projects.filter((project) => project.isPublished).length)}
/>
</div>
<div className="flex flex-wrap gap-2">
<Button asChild>
<Link href="/portfolio/projects/new">
<Plus className="h-4 w-4" />
{copy.newProject}
</Link>
</Button>
<Button asChild variant="outline">
<Link href="/portfolio/categories">
<Tags className="h-4 w-4" />
{copy.newCategory}
</Link>
</Button>
</div>
</div>
<div className="flex flex-wrap gap-2">
<Button asChild variant={selectedCategory === "" ? "default" : "outline"}>
<Link href="/portfolio">{copy.all}</Link>
</Button>
{categories.map((category) => (
<Button
key={category.id}
asChild
variant={selectedCategory === category.id ? "default" : "outline"}
>
<Link href={`/portfolio?category=${category.id}`}>
{category.name.de || category.name.en || category.name.ar}
</Link>
</Button>
))}
</div>
<div className="grid gap-4">
{projects.map((project, index) => (
<MotionFade key={project.id} delay={0.06 + index * 0.03}>
<AppCard interactive>
<CardContent className="flex flex-col gap-4 p-5 lg:flex-row lg:items-center lg:justify-between">
<div className="space-y-2">
<div className="flex flex-wrap items-center gap-2">
<p className="text-xl font-semibold text-foreground">
{getLocalizedValue(project.title, "de") || copy.untitled}
</p>
<Badge variant={project.isPublished ? "success" : "warning"}>
{project.isPublished ? "Published" : "Draft"}
</Badge>
<Badge variant="outline">{project.viewMode}</Badge>
</div>
<div className="flex flex-wrap gap-2 text-sm text-muted-foreground">
<span>{project.category.name.de || project.category.name.en || project.category.name.ar}</span>
<span>{project.projectYear}</span>
</div>
</div>
<div className="flex flex-wrap gap-3">
<Button asChild variant="outline">
<Link
href={getLocalizedPath("de", `/portfolio/${project.slug}`)}
target="_blank"
rel="noreferrer"
>
<ExternalLink className="h-4 w-4" />
{copy.openProject}
</Link>
</Button>
<PortfolioProjectActions projectId={project.id} />
</div>
</CardContent>
</AppCard>
</MotionFade>
))}
{projects.length === 0 ? (
<AppCard>
<CardContent className="p-6 text-sm text-muted-foreground">
{copy.empty}
</CardContent>
</AppCard>
) : null}
</div>
</div>
);
}
+45
View File
@@ -0,0 +1,45 @@
import Link from "next/link";
import { AppCard } from "@/components/ui/app-card";
import { CardContent } from "@/components/ui/card";
import { cn } from "@/lib/utils";
type PortfolioSubnavProps = {
active: "projects" | "categories";
};
const items = [
{
key: "projects",
label: "Projekte",
href: "/portfolio",
},
{
key: "categories",
label: "Kategorien",
href: "/portfolio/categories",
},
] as const;
export function PortfolioSubnav({ active }: PortfolioSubnavProps) {
return (
<AppCard level={2}>
<CardContent className="flex flex-wrap gap-2 p-4">
{items.map((item) => (
<Link
key={item.key}
href={item.href}
className={cn(
"rounded-nested border px-4 py-2 text-sm transition-colors",
active === item.key
? "border-input bg-primary text-primary-foreground"
: "border-input bg-background text-foreground/75 hover:bg-accent hover:text-accent-foreground",
)}
>
{item.label}
</Link>
))}
</CardContent>
</AppCard>
);
}
+86
View File
@@ -0,0 +1,86 @@
"use client";
import { useEffect, useRef } from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { toast } from "@/lib/toast";
const TOAST_PARAM_NAMES = ["success", "error"] as const;
const PENDING_TOAST_STORAGE_KEY = "mohfarawati-pending-toast";
export function QueryToastBridge() {
const pathname = usePathname();
const router = useRouter();
const searchParams = useSearchParams();
const handledKeyRef = useRef<string | null>(null);
useEffect(() => {
const rawToast = window.sessionStorage.getItem(PENDING_TOAST_STORAGE_KEY);
if (!rawToast) {
return;
}
try {
const pendingToast = JSON.parse(rawToast) as {
message?: string;
type?: "success" | "error";
};
const localizedMessage = pendingToast.message;
if (!localizedMessage) {
return;
}
if (pendingToast.type === "error") {
toast.error(localizedMessage);
} else if (pendingToast.type === "success") {
toast.success(localizedMessage);
} else {
toast(localizedMessage);
}
} finally {
window.sessionStorage.removeItem(PENDING_TOAST_STORAGE_KEY);
}
}, [pathname]);
useEffect(() => {
const successMessage = searchParams.get("success");
const errorMessage = searchParams.get("error");
if (!successMessage && !errorMessage) {
handledKeyRef.current = null;
return;
}
const handledKey = `${pathname}:${successMessage ?? ""}:${errorMessage ?? ""}`;
if (handledKeyRef.current === handledKey) {
return;
}
handledKeyRef.current = handledKey;
if (successMessage) {
toast.success(successMessage);
}
if (errorMessage) {
toast.error(errorMessage);
}
const nextParams = new URLSearchParams(searchParams.toString());
for (const name of TOAST_PARAM_NAMES) {
nextParams.delete(name);
}
const nextQuery = nextParams.toString();
router.replace(nextQuery ? `${pathname}?${nextQuery}` : pathname, {
scroll: false,
});
}, [pathname, router, searchParams]);
return null;
}
@@ -0,0 +1,116 @@
"use client";
import { ShieldAlert } from "lucide-react";
import { usePathname } from "next/navigation";
import { useRef, useState } from "react";
import { useFormStatus } from "react-dom";
import { Badge } from "@/components/ui/badge";
import { Checkbox } from "@/components/ui/checkbox";
import { cn } from "@/lib/utils";
type SidebarMaintenanceControlProps = {
action: (formData: FormData) => Promise<void>;
initialEnabled: boolean;
label: string;
};
type SidebarMaintenanceFieldProps = Omit<
SidebarMaintenanceControlProps,
"action" | "initialEnabled"
> & {
enabled: boolean;
onToggle: (checked: boolean) => void;
};
function SidebarMaintenanceField({
enabled,
label,
onToggle,
}: SidebarMaintenanceFieldProps) {
const { pending } = useFormStatus();
return (
<>
<label
htmlFor="sidebar-maintenance-enabled"
aria-disabled={pending}
className={cn(
"flex items-center justify-between gap-3 rounded-nested border px-3 py-2 transition-colors",
pending && "cursor-wait opacity-70",
!pending && "cursor-pointer",
enabled
? "border-status-warning/40 bg-status-warning-soft/80"
: "border-status-success/30 bg-status-success-soft/80 hover:bg-status-success-soft",
)}
>
<span className="flex min-w-0 items-center gap-3">
<span
className={cn(
"flex h-9 w-9 items-center justify-center rounded-pill border",
enabled
? "border-status-warning/40 bg-status-warning-soft text-status-warning"
: "border-status-success/30 bg-status-success-soft text-status-success",
)}
>
<ShieldAlert className="h-4 w-4" />
</span>
<span className="min-w-0 text-sm font-medium text-foreground">{label}</span>
</span>
<Badge variant={enabled ? "warning" : "success"}>
{enabled ? "OFFLINE" : "LIVE"}
</Badge>
</label>
<Checkbox
id="sidebar-maintenance-enabled"
checked={enabled}
checkedValue="true"
uncheckedValue="false"
disabled={pending}
onCheckedChange={(checked) => onToggle(checked === true)}
className="sr-only"
/>
</>
);
}
export function SidebarMaintenanceControl({
action,
initialEnabled,
label,
}: SidebarMaintenanceControlProps) {
const formRef = useRef<HTMLFormElement>(null);
const enabledInputRef = useRef<HTMLInputElement>(null);
const pathname = usePathname();
const [enabled, setEnabled] = useState(initialEnabled);
return (
<form
id="sidebar-maintenance-form"
ref={formRef}
action={action}
className="space-y-2"
>
<input type="hidden" name="redirectPath" value={pathname} />
<input
ref={enabledInputRef}
type="hidden"
name="enabled"
value={enabled ? "true" : "false"}
/>
<SidebarMaintenanceField
enabled={enabled}
label={label}
onToggle={(checked) => {
setEnabled(checked);
if (enabledInputRef.current) {
enabledInputRef.current.value = checked ? "true" : "false";
}
formRef.current?.requestSubmit();
}}
/>
</form>
);
}
+736
View File
@@ -0,0 +1,736 @@
"use client";
/* eslint-disable @next/next/no-img-element */
import { MediaKind } from "@prisma/client";
import { Check, FileText, ImageIcon, Search, Type, Upload } from "lucide-react";
import { useEffect, useId, useMemo, useRef, useState } from "react";
import { AppCard } from "@/components/ui/app-card";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Table, TableBody, TableCell, TableRow } from "@/components/ui/table";
import type { AppLocale } from "@/lib/locale";
import type { MediaOption } from "@/lib/media";
import { cn } from "@/lib/utils";
import {
PAGE_TITLE_TOKEN,
SITE_NAME_TOKEN,
type SiteSettings,
type SiteSettingsMediaBindings,
} from "@/lib/site-settings";
type SiteSettingsFormProps = {
action: (formData: FormData) => Promise<void>;
initialSettings: SiteSettings;
initialBindings: SiteSettingsMediaBindings;
mediaOptions: MediaOption[];
};
type MediaFieldState = {
mode: "upload" | "library";
assetId: string;
url: string;
label: string;
kind: MediaKind;
};
const localeFields: Array<{
key: AppLocale;
label: string;
suffix: "Ar" | "En" | "De";
sampleTitle: string;
}> = [
{
key: "ar",
label: "Arabic",
suffix: "Ar",
sampleTitle: "Home",
},
{
key: "en",
label: "English",
suffix: "En",
sampleTitle: "About",
},
{
key: "de",
label: "Deutsch",
suffix: "De",
sampleTitle: "Portfolio",
},
];
function createImageFieldState(
assetId: string | null | undefined,
url: string | null | undefined,
label: string,
): MediaFieldState {
if (assetId) {
return {
mode: "library",
assetId,
url: "",
label,
kind: MediaKind.IMAGE,
};
}
return {
mode: "upload",
assetId: "",
url: url ?? "",
label,
kind: MediaKind.IMAGE,
};
}
function getMediaPreviewUrl(
value: MediaFieldState,
options: MediaOption[],
fallbackUrl: string | null | undefined,
) {
if (value.mode === "library") {
return options.find((option) => option.id === value.assetId)?.url ?? fallbackUrl ?? "";
}
return fallbackUrl ?? "";
}
function buildPreviewTitle(
titleTemplate: string,
sampleTitle: string,
siteName: string,
) {
return titleTemplate.includes(PAGE_TITLE_TOKEN)
? titleTemplate
.replace(PAGE_TITLE_TOKEN, sampleTitle)
.replaceAll(SITE_NAME_TOKEN, siteName)
: `${sampleTitle} | ${siteName}`;
}
function MediaLibraryModal({
open,
onOpenChange,
options,
selectedAssetId,
onSelect,
title,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
options: MediaOption[];
selectedAssetId: string;
onSelect: (option: MediaOption) => void;
title: string;
}) {
const searchId = useId();
const [query, setQuery] = useState("");
const visibleOptions = useMemo(() => {
const normalizedQuery = query.trim().toLowerCase();
if (!normalizedQuery) {
return options;
}
return options.filter((option) => option.label.toLowerCase().includes(normalizedQuery));
}, [options, query]);
useEffect(() => {
if (!open) {
setQuery("");
}
}, [open]);
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-h-[calc(100vh-1.5rem)] w-[calc(100vw-1rem)] max-w-4xl overflow-y-auto">
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
<DialogDescription>Bild aus der Media Library auswaehlen.</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div className="relative">
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
id={searchId}
value={query}
onChange={(event) => setQuery(event.target.value)}
className="pl-9"
placeholder="Search media"
/>
</div>
<div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
{visibleOptions.length > 0 ? (
visibleOptions.map((option) => {
const isActive = option.id === selectedAssetId;
return (
<button
key={option.id}
type="button"
onClick={() => {
onSelect(option);
onOpenChange(false);
}}
className={cn(
"overflow-hidden rounded-nested border text-left transition-colors",
isActive
? "border-input bg-accent/30"
: "border-border/70 bg-background hover:bg-accent/10",
)}
>
<div className="aspect-[4/3] bg-muted/30">
{option.url ? (
<img src={option.url} alt={option.label} className="h-full w-full object-cover" />
) : null}
</div>
<div className="flex items-center gap-3 p-3">
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium text-foreground">{option.label}</p>
<p className="truncate text-xs text-muted-foreground">{option.source}</p>
</div>
{isActive ? <Check className="h-4 w-4 text-brand-primary" /> : null}
</div>
</button>
);
})
) : (
<div className="col-span-full rounded-nested border border-dashed border-input px-4 py-8 text-sm text-muted-foreground">
No media found.
</div>
)}
</div>
</div>
</DialogContent>
</Dialog>
);
}
function SiteSettingsMediaRow({
title,
value,
onChange,
options,
inputName,
fileFieldName,
accept,
clearLabel,
fallbackUrl,
}: {
title: string;
value: MediaFieldState;
onChange: (nextValue: MediaFieldState) => void;
options: MediaOption[];
inputName: string;
fileFieldName: string;
accept: string;
clearLabel: string;
fallbackUrl?: string | null;
}) {
const [isLibraryOpen, setIsLibraryOpen] = useState(false);
const hiddenInputRef = useRef<HTMLInputElement | null>(null);
const fileInputId = useId();
const previewUrl = getMediaPreviewUrl(value, options, fallbackUrl);
const serializedValue = JSON.stringify({
mode: value.mode,
assetId: value.assetId,
url: value.url,
label: value.label,
kind: value.kind,
});
useEffect(() => {
const hiddenInput = hiddenInputRef.current;
if (!hiddenInput) {
return;
}
hiddenInput.dispatchEvent(new Event("input", { bubbles: true }));
hiddenInput.dispatchEvent(new Event("change", { bubbles: true }));
}, [serializedValue]);
return (
<>
<AppCard level={2} padding="sm">
<div className="grid gap-4 lg:grid-cols-[180px_minmax(0,1fr)]">
<div className="space-y-2">
<p className="text-sm font-semibold text-foreground">{title}</p>
<div className="flex h-20 w-full items-center justify-center overflow-hidden rounded-nested border border-border/70 bg-muted/30">
{previewUrl ? (
<img src={previewUrl} alt={title} className="h-full w-full object-contain p-2" />
) : (
<ImageIcon className="h-5 w-5 text-muted-foreground" />
)}
</div>
</div>
<div className="space-y-3">
<input ref={hiddenInputRef} type="hidden" name={inputName} value={serializedValue} />
<div className="grid gap-3 md:grid-cols-[minmax(0,1fr)_auto_auto]">
<div className="relative">
<Type className="pointer-events-none absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
<Input
value={value.label}
onChange={(event) => onChange({ ...value, label: event.target.value })}
placeholder="Label"
className="pl-8"
/>
</div>
<label
htmlFor={fileInputId}
className="inline-flex h-10 cursor-pointer items-center justify-center gap-2 rounded-nested border border-input bg-background px-4 text-sm transition-colors hover:bg-accent hover:text-accent-foreground"
>
<Upload className="h-4 w-4" />
Upload
</label>
<Button type="button" variant="outline" onClick={() => setIsLibraryOpen(true)}>
<ImageIcon className="h-4 w-4" />
Library
</Button>
</div>
<input
id={fileInputId}
name={fileFieldName}
type="file"
accept={accept}
className="hidden"
onChange={(event) => {
const nextLabel = event.target.files?.[0]?.name.replace(/\.[^.]+$/, "") ?? value.label;
onChange({
...value,
mode: "upload",
assetId: "",
label: value.label.trim() ? value.label : nextLabel,
});
}}
/>
<div className="flex flex-wrap items-center gap-2">
<BadgeLike>{value.mode === "library" && value.assetId ? "Library selected" : "Upload mode"}</BadgeLike>
{value.assetId ? (
<Button
type="button"
variant="ghost"
size="sm"
className="h-8 px-2 text-destructive hover:bg-destructive/5 hover:text-destructive"
onClick={() =>
onChange({
...value,
mode: "upload",
assetId: "",
url: "",
})
}
>
{clearLabel}
</Button>
) : null}
</div>
</div>
</div>
</AppCard>
<MediaLibraryModal
open={isLibraryOpen}
onOpenChange={setIsLibraryOpen}
options={options.filter((option) => option.kind === MediaKind.IMAGE)}
selectedAssetId={value.assetId}
title={title}
onSelect={(option) =>
onChange({
...value,
mode: "library",
assetId: option.id,
url: "",
label: option.label,
})
}
/>
</>
);
}
function BadgeLike({ children }: { children: string }) {
return (
<span className="inline-flex items-center rounded-full border border-border/70 bg-muted/30 px-2.5 py-1 text-xs text-muted-foreground">
{children}
</span>
);
}
export function SiteSettingsForm({
action,
initialSettings,
initialBindings,
mediaOptions,
}: SiteSettingsFormProps) {
const [settings, setSettings] = useState(initialSettings);
const [siteLogoLight, setSiteLogoLight] = useState<MediaFieldState>(
createImageFieldState(
initialBindings.siteLogoLight?.assetId,
initialBindings.siteLogoLight?.url,
"Site Logo Light",
),
);
const [siteLogoDark, setSiteLogoDark] = useState<MediaFieldState>(
createImageFieldState(
initialBindings.siteLogoDark?.assetId,
initialBindings.siteLogoDark?.url,
"Site Logo Dark",
),
);
const [favicon, setFavicon] = useState<MediaFieldState>(
createImageFieldState(
initialBindings.favicon?.assetId,
initialBindings.favicon?.url,
"Favicon",
),
);
const [defaultOgImage, setDefaultOgImage] = useState<MediaFieldState>(
createImageFieldState(
initialBindings.defaultOgImage?.assetId,
initialBindings.defaultOgImage?.url,
"Default OG Image",
),
);
const siteLogoLightPreviewUrl = getMediaPreviewUrl(
siteLogoLight,
mediaOptions,
initialBindings.siteLogoLight?.url,
);
const siteLogoDarkPreviewUrl = getMediaPreviewUrl(
siteLogoDark,
mediaOptions,
initialBindings.siteLogoDark?.url,
);
const faviconPreviewUrl = getMediaPreviewUrl(favicon, mediaOptions, initialBindings.favicon?.url);
const defaultOgImagePreviewUrl = getMediaPreviewUrl(
defaultOgImage,
mediaOptions,
initialBindings.defaultOgImage?.url,
);
return (
<form id="site-settings-form" action={action} className="space-y-6">
<div className="grid gap-6 xl:grid-cols-[minmax(0,3fr)_minmax(300px,1fr)]">
<div className="space-y-6">
<section className="space-y-5">
<div className="space-y-2">
<h2 className="text-lg font-semibold text-foreground">Localized Titles And Copy</h2>
<p className="text-sm text-muted-foreground">
Nutze
{" "}
<code>{PAGE_TITLE_TOKEN}</code>
{" "}
und
{" "}
<code>{SITE_NAME_TOKEN}</code>
{" "}
fuer die globalen Titelvorlagen pro Sprache.
</p>
</div>
<div className="grid gap-5 lg:grid-cols-3">
{localeFields.map((locale) => (
<AppCard key={locale.key} level={2} padding="sm" className="space-y-4">
<p className="text-sm font-semibold text-foreground">{locale.label}</p>
<div className="space-y-2">
<Label htmlFor={`siteName${locale.suffix}`} className="sr-only">Site Name</Label>
<div className="relative">
<Type className="pointer-events-none absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
<Input
id={`siteName${locale.suffix}`}
name={`siteName${locale.suffix}`}
value={settings.locales[locale.key].siteName}
onChange={(event) =>
setSettings((current) => ({
...current,
locales: {
...current.locales,
[locale.key]: {
...current.locales[locale.key],
siteName: event.target.value,
},
},
}))
}
placeholder="Site Name"
className="pl-8"
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor={`titleTemplate${locale.suffix}`} className="sr-only">Title Template</Label>
<div className="relative">
<Search className="pointer-events-none absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
<Input
id={`titleTemplate${locale.suffix}`}
name={`titleTemplate${locale.suffix}`}
value={settings.locales[locale.key].titleTemplate}
onChange={(event) =>
setSettings((current) => ({
...current,
locales: {
...current.locales,
[locale.key]: {
...current.locales[locale.key],
titleTemplate: event.target.value,
},
},
}))
}
placeholder="Title Template"
className="pl-8"
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor={`siteDescription${locale.suffix}`} className="sr-only">Site Description</Label>
<div className="relative">
<FileText className="pointer-events-none absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
<Input
id={`siteDescription${locale.suffix}`}
name={`siteDescription${locale.suffix}`}
value={settings.locales[locale.key].siteDescription}
onChange={(event) =>
setSettings((current) => ({
...current,
locales: {
...current.locales,
[locale.key]: {
...current.locales[locale.key],
siteDescription: event.target.value,
},
},
}))
}
placeholder="Site Description"
className="pl-8"
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor={`subhead${locale.suffix}`} className="sr-only">Subhead</Label>
<div className="relative">
<Type className="pointer-events-none absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
<Input
id={`subhead${locale.suffix}`}
name={`subhead${locale.suffix}`}
value={settings.locales[locale.key].subhead}
onChange={(event) =>
setSettings((current) => ({
...current,
locales: {
...current.locales,
[locale.key]: {
...current.locales[locale.key],
subhead: event.target.value,
},
},
}))
}
placeholder="Subhead"
className="pl-8"
/>
</div>
</div>
</AppCard>
))}
</div>
</section>
<section className="space-y-4">
<h2 className="text-lg font-semibold text-foreground">Brand And Preview Images</h2>
<SiteSettingsMediaRow
title="Site Logo Light"
value={siteLogoLight}
onChange={setSiteLogoLight}
options={mediaOptions}
inputName="siteLogoLightMedia"
fileFieldName="siteLogoLightFile"
accept="image/*,.svg"
clearLabel="Remove"
fallbackUrl={initialBindings.siteLogoLight?.url}
/>
<SiteSettingsMediaRow
title="Site Logo Dark"
value={siteLogoDark}
onChange={setSiteLogoDark}
options={mediaOptions}
inputName="siteLogoDarkMedia"
fileFieldName="siteLogoDarkFile"
accept="image/*,.svg"
clearLabel="Remove"
fallbackUrl={initialBindings.siteLogoDark?.url}
/>
<SiteSettingsMediaRow
title="Favicon"
value={favicon}
onChange={setFavicon}
options={mediaOptions}
inputName="faviconMedia"
fileFieldName="faviconFile"
accept=".png,.svg,.ico,image/png,image/svg+xml,image/x-icon,image/vnd.microsoft.icon"
clearLabel="Remove"
fallbackUrl={initialBindings.favicon?.url}
/>
<SiteSettingsMediaRow
title="Default OG Image"
value={defaultOgImage}
onChange={setDefaultOgImage}
options={mediaOptions}
inputName="defaultOgImageMedia"
fileFieldName="defaultOgImageFile"
accept="image/*,.svg"
clearLabel="Remove"
fallbackUrl={initialBindings.defaultOgImage?.url}
/>
</section>
</div>
<div className="xl:sticky xl:top-6 xl:self-start">
<section className="space-y-4">
<h2 className="text-lg font-semibold text-foreground">Preview</h2>
<AppCard level={2} padding="sm" className="space-y-2">
<p className="text-sm font-semibold text-foreground">Search Result</p>
<div className="rounded-nested border border-border/70 bg-background p-3">
<div className="flex items-center gap-3">
{faviconPreviewUrl ? (
<img src={faviconPreviewUrl} alt="Favicon" className="h-4 w-4 rounded-sm object-cover" />
) : (
<div className="flex h-4 w-4 items-center justify-center rounded-sm border border-border/70 bg-muted/40">
<Type className="h-3 w-3 text-muted-foreground" />
</div>
)}
<p className="text-sm font-medium text-brand-primary">
{buildPreviewTitle(
settings.locales.de.titleTemplate,
"About",
settings.locales.de.siteName,
)}
</p>
</div>
<p className="mt-2 text-xs text-muted-foreground">
{settings.locales.de.siteDescription || "No description"}
</p>
</div>
</AppCard>
<AppCard level={2} padding="sm" className="space-y-2">
<p className="text-sm font-semibold text-foreground">Brand Assets</p>
<div className="grid gap-3 sm:grid-cols-2">
<AppCard level={1} padding="sm">
<p className="mb-2 text-xs font-medium uppercase tracking-[0.12em] text-muted-foreground">Light</p>
{siteLogoLightPreviewUrl ? (
<img
src={siteLogoLightPreviewUrl}
alt="Site Logo Light"
className="h-10 w-full object-contain"
/>
) : (
<div className="flex h-10 items-center text-sm text-muted-foreground">No logo selected</div>
)}
</AppCard>
<div className="rounded-nested border border-border/70 bg-slate-950 p-3">
<p className="mb-2 text-xs font-medium uppercase tracking-[0.12em] text-white/55">Dark</p>
{siteLogoDarkPreviewUrl ? (
<img
src={siteLogoDarkPreviewUrl}
alt="Site Logo Dark"
className="h-10 w-full object-contain"
/>
) : (
<div className="flex h-10 items-center text-sm text-white/60">No logo selected</div>
)}
</div>
</div>
</AppCard>
<AppCard level={2} padding="sm" className="space-y-2">
<p className="text-sm font-semibold text-foreground">Social Preview</p>
<div className="overflow-hidden rounded-nested border border-border/70 bg-background">
{defaultOgImagePreviewUrl ? (
<img src={defaultOgImagePreviewUrl} alt="Default OG" className="h-24 w-full object-cover" />
) : (
<div className="flex h-24 items-center justify-center bg-muted/30 text-sm text-muted-foreground">
No OG image selected
</div>
)}
<div className="space-y-1.5 p-3">
<p className="text-sm font-medium text-foreground">
{buildPreviewTitle(
settings.locales.en.titleTemplate,
"Portfolio",
settings.locales.en.siteName,
)}
</p>
<p className="text-xs text-muted-foreground">
{settings.locales.en.siteDescription || "No description"}
</p>
</div>
</div>
</AppCard>
<AppCard level={2} padding="sm" className="space-y-2">
<p className="text-sm font-semibold text-foreground">Locale Summary</p>
<div className="rounded-nested border border-border/70 bg-background">
<Table>
<TableBody>
{localeFields.map((locale) => (
<TableRow key={locale.key}>
<TableCell className="w-24 font-medium">{locale.label}</TableCell>
<TableCell>
<p className="text-sm font-medium text-foreground">
{buildPreviewTitle(
settings.locales[locale.key].titleTemplate,
locale.sampleTitle,
settings.locales[locale.key].siteName,
)}
</p>
<p className="mt-1 text-xs text-muted-foreground">
{settings.locales[locale.key].subhead || "No subhead"}
</p>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
</AppCard>
</section>
</div>
</div>
<div className="flex justify-end">
<Button type="submit">Save Settings</Button>
</div>
</form>
);
}
+180
View File
@@ -0,0 +1,180 @@
"use client";
import { KeyRound, Mail, Send, Server } from "lucide-react";
import { useState } from "react";
import { AppCard } from "@/components/ui/app-card";
import { Button } from "@/components/ui/button";
import { CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import type { MailSettingsFormValues } from "@/lib/mail-settings";
type SMTPSettingsFormProps = {
action: (formData: FormData) => Promise<void>;
initialSettings: MailSettingsFormValues;
};
export function SMTPSettingsForm({
action,
initialSettings,
}: SMTPSettingsFormProps) {
const [smtpSecure, setSmtpSecure] = useState(initialSettings.smtp.secure);
return (
<form id="smtp-settings-form" action={action} className="space-y-6">
<div className="grid gap-6 xl:grid-cols-2">
<AppCard>
<CardHeader>
<CardTitle>SMTP Connection</CardTitle>
<CardDescription>Server und Login.</CardDescription>
</CardHeader>
<CardContent className="grid gap-5 p-4 md:grid-cols-2">
<div className="space-y-2 md:col-span-2">
<Label htmlFor="smtpHost">SMTP Host</Label>
<div className="relative">
<Server className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
id="smtpHost"
name="smtpHost"
defaultValue={initialSettings.smtp.host}
autoComplete="off"
className="pl-9"
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="smtpPort">SMTP Port</Label>
<Input
id="smtpPort"
name="smtpPort"
type="number"
min="1"
defaultValue={initialSettings.smtp.port}
/>
</div>
<div className="space-y-2">
<Label htmlFor="smtpUsername">SMTP Username</Label>
<div className="relative">
<Mail className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
id="smtpUsername"
name="smtpUsername"
defaultValue={initialSettings.smtp.username}
autoComplete="off"
className="pl-9"
/>
</div>
</div>
<div className="space-y-2 md:col-span-2">
<Label htmlFor="smtpPassword">SMTP Password</Label>
<div className="relative">
<KeyRound className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
id="smtpPassword"
name="smtpPassword"
type="password"
defaultValue={initialSettings.smtp.password}
placeholder={initialSettings.smtp.hasPassword ? "Saved password will be kept" : "SMTP password"}
autoComplete="new-password"
className="pl-9"
/>
</div>
</div>
<div className="md:col-span-2">
<label
htmlFor="smtpSecure"
className="flex cursor-pointer items-start gap-3 rounded-nested border border-input bg-card px-4 py-4 transition-colors hover:bg-accent/20"
>
<Checkbox
id="smtpSecure"
name="smtpSecure"
checked={smtpSecure}
onCheckedChange={(checked) => setSmtpSecure(checked === true)}
className="mt-0.5"
/>
<span className="space-y-1">
<span className="block text-sm font-medium text-foreground">Use secure SMTP</span>
<span className="block text-xs text-muted-foreground">
{smtpSecure ? "ON: meist Port 465." : "OFF: meist Port 587."}
</span>
</span>
</label>
</div>
</CardContent>
</AppCard>
<AppCard>
<CardHeader>
<CardTitle>Sender And Recipients</CardTitle>
<CardDescription>Absender und Ziele.</CardDescription>
</CardHeader>
<CardContent className="grid gap-5 p-4 md:grid-cols-2">
<div className="space-y-2 md:col-span-2">
<Label htmlFor="mailFromEmail">From Email</Label>
<div className="relative">
<Mail className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
id="mailFromEmail"
name="mailFromEmail"
type="email"
defaultValue={initialSettings.sender.email}
autoComplete="off"
className="pl-9"
/>
</div>
</div>
<div className="space-y-2 md:col-span-2">
<Label htmlFor="mailFromName">From Name</Label>
<Input
id="mailFromName"
name="mailFromName"
defaultValue={initialSettings.sender.name}
autoComplete="off"
/>
</div>
<div className="space-y-2">
<Label htmlFor="mailContactRecipient">Contact Recipient Email</Label>
<div className="relative">
<Send className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
id="mailContactRecipient"
name="mailContactRecipient"
type="email"
defaultValue={initialSettings.recipients.contact}
autoComplete="off"
className="pl-9"
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="mailTestRecipient">Test Recipient Email</Label>
<div className="relative">
<Send className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
id="mailTestRecipient"
name="mailTestRecipient"
type="email"
defaultValue={initialSettings.recipients.test}
autoComplete="off"
className="pl-9"
/>
</div>
</div>
</CardContent>
</AppCard>
</div>
<div className="flex justify-end">
<Button type="submit">Save SMTP</Button>
</div>
</form>
);
}
+123
View File
@@ -0,0 +1,123 @@
import type { ReactNode } from "react";
import { AppCard } from "@/components/ui/app-card";
import { Badge } from "@/components/ui/badge";
import { CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { cn } from "@/lib/utils";
export function WorkspaceHero({
eyebrow,
title,
description,
aside,
}: {
eyebrow: string;
title: string;
description: string;
aside?: ReactNode;
}) {
return (
<AppCard level={3}>
<CardContent className="flex flex-col gap-4 p-6 lg:flex-row lg:items-end lg:justify-between lg:p-8">
<div className="space-y-2">
<p className="text-xs font-semibold uppercase tracking-[0.14em] text-muted-foreground">
{eyebrow}
</p>
<h2 className="text-2xl font-semibold text-foreground">{title}</h2>
<p className="max-w-3xl text-sm text-muted-foreground">{description}</p>
</div>
{aside ? <div className="flex flex-wrap gap-2">{aside}</div> : null}
</CardContent>
</AppCard>
);
}
export function WorkspaceSidebarPanel({
title,
children,
}: {
title: string;
children: ReactNode;
}) {
return (
<AppCard level={2}>
<CardHeader className="pb-4">
<CardTitle className="text-base">{title}</CardTitle>
</CardHeader>
<CardContent className="space-y-4">{children}</CardContent>
</AppCard>
);
}
export function WorkspaceStepButton({
active,
completed,
index,
label,
eyebrow,
onClick,
completeIcon,
}: {
active: boolean;
completed: boolean;
index: number;
label: string;
eyebrow: string;
onClick: () => void;
completeIcon?: ReactNode;
}) {
return (
<button
type="button"
onClick={onClick}
className={cn(
"flex w-full items-start gap-3 rounded-surface border px-4 py-3 text-left transition-colors",
active
? "border-input bg-accent/40"
: "border-input bg-background hover:bg-accent/20",
)}
>
<div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-pill border border-input bg-background text-sm font-semibold text-foreground">
{completed ? completeIcon ?? "OK" : index + 1}
</div>
<div className="min-w-0">
<p className="text-xs font-semibold uppercase tracking-[0.12em] text-muted-foreground">
{eyebrow}
</p>
<p className="mt-1 text-sm font-medium text-foreground">{label}</p>
</div>
</button>
);
}
export function WorkspaceLocaleCard({
title,
hint,
children,
}: {
title: string;
hint: string;
children: ReactNode;
}) {
return (
<AppCard level={2}>
<CardHeader className="pb-4">
<CardTitle className="text-lg">{title}</CardTitle>
<CardDescription>{hint}</CardDescription>
</CardHeader>
<CardContent className="space-y-4">{children}</CardContent>
</AppCard>
);
}
export function WorkspaceStatusBadge({
done,
doneLabel = "Ready",
openLabel = "Open",
}: {
done: boolean;
doneLabel?: string;
openLabel?: string;
}) {
return <Badge variant={done ? "success" : "warning"}>{done ? doneLabel : openLabel}</Badge>;
}