RustyCMS: file-based headless CMS — API, Admin UI (content, types, assets), Docker/Caddy, image transform; only demo type and demo content in version control

Made-with: Cursor
This commit is contained in:
Peter Meier
2026-03-12 14:21:49 +01:00
parent aad93d145f
commit 7795a238e1
278 changed files with 15551 additions and 4072 deletions

5
admin-ui/.dockerignore Normal file
View File

@@ -0,0 +1,5 @@
node_modules/
.next/
.git/
.env*
*.md

28
admin-ui/Dockerfile Normal file
View File

@@ -0,0 +1,28 @@
# Stage 1: Build
FROM node:22-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
ENV NEXT_TELEMETRY_DISABLED=1
# API URL is baked in at build time (NEXT_PUBLIC_ vars are static)
ARG NEXT_PUBLIC_RUSTYCMS_API_URL
ARG NEXT_PUBLIC_RUSTYCMS_API_KEY
ENV NEXT_PUBLIC_RUSTYCMS_API_URL=$NEXT_PUBLIC_RUSTYCMS_API_URL
ENV NEXT_PUBLIC_RUSTYCMS_API_KEY=$NEXT_PUBLIC_RUSTYCMS_API_KEY
RUN npm run build
# Stage 2: Minimal runtime image
FROM node:22-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
RUN addgroup --system --gid 1001 nodejs && adduser --system --uid 1001 nextjs
COPY --from=builder /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
USER nextjs
EXPOSE 3001
ENV PORT=3001
ENV HOSTNAME="0.0.0.0"
CMD ["node", "server.js"]

1
admin-ui/components.json Normal file
View File

@@ -0,0 +1 @@
{"style":"new-york","rsc":true,"tsx":true,"tailwind":{"config":"","css":"src/app/globals.css","baseColor":"neutral","cssVariables":true},"aliases":{"components":"@/components","utils":"@/lib/utils","ui":"@/components/ui","lib":"@/lib","hooks":"@/hooks"}}

11
admin-ui/i18n/request.ts Normal file
View File

@@ -0,0 +1,11 @@
import { getRequestConfig } from 'next-intl/server';
import { cookies } from 'next/headers';
export default getRequestConfig(async () => {
const store = await cookies();
const locale = store.get('locale')?.value ?? 'en';
return {
locale,
messages: (await import(`../messages/${locale}.json`)).default,
};
});

263
admin-ui/messages/de.json Normal file
View File

@@ -0,0 +1,263 @@
{
"Sidebar": {
"dashboard": "Dashboard",
"types": "Typen",
"assets": "Assets",
"searchPlaceholder": "Sammlungen suchen…",
"searchAriaLabel": "Sammlungen suchen",
"closeMenu": "Menü schließen",
"loading": "Laden…",
"errorLoading": "Fehler beim Laden der Sammlungen",
"noResults": "Keine Ergebnisse für \"{query}\""
},
"ContentForm": {
"slugRequired": "Slug ist erforderlich.",
"slugInUse": "Slug bereits vergeben.",
"slugMustStartWith": "Der Slug muss mit \"{prefix}\" beginnen.",
"slugPrefix": "Präfix",
"slugSuffixPlaceholder": "z. B. meine-kampagne",
"slugSuffixAriaLabel": "Slug-Suffix (Präfix ist fest)",
"slugPlaceholder": "z. B. mein-beitrag",
"slugHint": "Kleinbuchstaben (a-z), Ziffern (0-9), Bindestriche. Leerzeichen werden zu Bindestrichen.",
"savedSuccessfully": "Erfolgreich gespeichert.",
"errorSaving": "Fehler beim Speichern",
"saving": "Speichern…",
"save": "Speichern",
"backToList": "Zurück zur Liste",
"pleaseSelect": "— Bitte auswählen —",
"removeEntry": "Entfernen",
"addEntry": "+ Eintrag hinzufügen",
"keyPlaceholder": "Schlüssel",
"valuePlaceholder": "Wert"
},
"SearchableSelect": {
"placeholder": "\u2014 Bitte ausw\u00e4hlen \u2014",
"clearLabel": "\u2014 Auswahl aufheben \u2014",
"filterPlaceholder": "Filtern\u2026",
"emptyLabel": "Keine Treffer"
},
"ReferenceField": {
"typeLabel": "Typ: {collection}",
"typesLabel": "Typen: {collections}",
"selectType": "\u2014 Typ w\u00e4hlen \u2014",
"newEntry": "Neuer Eintrag",
"noCollection": "Keine Referenz-Collection im Schema. Setze {collectionCode} oder {collectionsCode} im Typ, oder starte die API und lade die Seite neu."
},
"ReferenceArrayField": {
"typeLabel": "Typ: {collection}",
"typesLabel": "Typen: {collections}",
"componentType": "Komponententyp",
"selectType": "\u2014 Typ w\u00e4hlen \u2014",
"selectFromExisting": "\u2014 Aus vorhandenen w\u00e4hlen \u2014",
"filterPlaceholder": "Filtern\u2026",
"emptyLabel": "Keine Treffer",
"selectExistingAriaLabel": "Vorhandenen Eintrag zum Hinzuf\u00fcgen ausw\u00e4hlen",
"moveUp": "Nach oben",
"moveDown": "Nach unten",
"remove": "Entfernen",
"newComponent": "+ Neue {collection}-Komponente",
"createNewComponent": "+ Neue Komponente erstellen\u2026",
"openInNewTab": "In neuem Tab \u00f6ffnen; dann Seite neu laden.",
"noCollection": "Keine Referenz-Collection im Schema. Setze {collectionCode} oder {collectionsCode} im Typ, oder starte die API und lade die Seite neu."
},
"MarkdownEditor": {
"bold": "Fett",
"italic": "Kursiv",
"code": "Code",
"link": "Link",
"bulletList": "Aufz\u00e4hlungsliste",
"bulletListButton": "\u2022 Liste",
"placeholder": "Markdown eingeben\u2026 **fett**, *kursiv*, [Link](url), - Liste",
"preview": "Vorschau",
"emptyPreview": "Leer \u2014 Vorschau erscheint beim Tippen."
},
"PaginationLinks": {
"back": "Zur\u00fcck",
"next": "Weiter",
"pageInfo": "Seite {page} von {totalPages} ({total} Eintr\u00e4ge)"
},
"DataPreviewPanel": {
"hide": "Daten-Vorschau ausblenden",
"show": "Daten-Vorschau",
"loading": "Laden\u2026",
"errorLoading": "Fehler beim Laden"
},
"SchemaPanel": {
"hide": "Schema ausblenden",
"show": "Schema anzeigen"
},
"SchemaAndEditBar": {
"editSchema": "Schema bearbeiten"
},
"SchemaAndPreviewBar": {
"hideSchema": "Schema ausblenden",
"showSchema": "Schema anzeigen",
"editSchema": "Schema bearbeiten",
"hidePreview": "Daten-Vorschau ausblenden",
"showPreview": "Daten-Vorschau",
"loading": "Laden\u2026",
"errorLoading": "Fehler beim Laden"
},
"ReferenceOrInlineField": {
"reference": "Referenz",
"inline": "Eingebettet",
"inlineObject": "Eingebettetes Objekt (keine Referenz)",
"noInlineSchema": "Kein Inline-Schema. Seite neu laden oder API pr\u00fcfen (useFields / collection)."
},
"LocaleSwitcher": {
"label": "Sprache"
},
"ContentLocaleSwitcher": {
"label": "Inhaltssprache"
},
"Dashboard": {
"title": "Dashboard",
"subtitle": "W\u00e4hle eine Sammlung zur Inhaltsverwaltung.",
"noCollections": "Keine Sammlungen geladen. Pr\u00fcfe ob die RustyCMS-API unter {url} erreichbar ist."
},
"TypesPage": {
"title": "Typen",
"newType": "Neuer Typ",
"description": "Inhaltstypen (Sammlungen). Schema bearbeiten oder Typ l\u00f6schen. Beim L\u00f6schen wird nur die Typdefinitionsdatei entfernt; vorhandene Inhaltseintr\u00e4ge bleiben erhalten.",
"loading": "Laden\u2026",
"errorLoading": "Fehler beim Laden der Typen: {error}",
"noTypes": "Noch keine Typen vorhanden. Erstelle einen mit \"Neuer Typ\".",
"colName": "Name",
"colDescription": "Beschreibung",
"colCategory": "Kategorie",
"colActions": "Aktionen",
"confirmDelete": "\"{name}\" l\u00f6schen?",
"confirmDeleteFinal": "\"{name}\" wirklich l\u00f6schen? Dies kann nicht r\u00fcckg\u00e4ngig gemacht werden.",
"delete": "L\u00f6schen",
"yesDelete": "Ja, l\u00f6schen",
"deleting": "\u2026",
"cancel": "Abbrechen",
"edit": "Bearbeiten"
},
"NewTypePage": {
"title": "Neuen Typ anlegen",
"description": "Erstellt einen neuen Inhaltstyp (Sammlung). Die Schemadatei wird auf dem Server unter {path} gespeichert und per Hot-Reload geladen.",
"nameRequired": "Name ist erforderlich.",
"nameInvalid": "Name: nur Kleinbuchstaben, Ziffern und Unterstriche.",
"fieldRequired": "Mindestens ein Feld erforderlich.",
"fieldNamesUnique": "Feldnamen m\u00fcssen eindeutig sein.",
"errorCreating": "Fehler beim Erstellen des Typs.",
"nameLabel": "Name",
"namePlaceholder": "z.\u00a0B. produkt, blogbeitrag",
"nameHint": "Nur Kleinbuchstaben, Ziffern und Unterstriche.",
"descriptionLabel": "Beschreibung",
"categoryLabel": "Kategorie",
"categoryPlaceholder": "z.\u00a0B. inhalt",
"tagsLabel": "Tags (kommagetrennt)",
"tagsPlaceholder": "z.\u00a0B. inhalt, blog",
"strictLabel": "Strikt (unbekannte Felder ablehnen)",
"fieldsLabel": "Felder",
"addField": "Feld hinzuf\u00fcgen",
"fieldNamePlaceholder": "Feldname",
"required": "Pflichtfeld",
"removeField": "Feld entfernen",
"collectionPlaceholder": "Sammlung (z.\u00a0B. seite)",
"fieldDescriptionPlaceholder": "Feldbeschreibung (optional)",
"creating": "Erstellen\u2026",
"createType": "Typ erstellen",
"cancel": "Abbrechen"
},
"EditTypePage": {
"fieldRequired": "Mindestens ein Feld erforderlich.",
"fieldNamesUnique": "Feldnamen m\u00fcssen eindeutig sein.",
"errorSaving": "Fehler beim Speichern des Typs.",
"missingName": "Typname fehlt.",
"backToTypes": "Zur\u00fcck zu Typen",
"loading": "Laden\u2026",
"errorLoading": "Fehler beim Laden des Typs: {error}",
"title": "Typ bearbeiten: {name}",
"description": "Beschreibung, Kategorie, Tags und Felder \u00e4ndern. Die Schemadatei wird auf dem Server aktualisiert.",
"nameLabel": "Name",
"descriptionLabel": "Beschreibung",
"categoryLabel": "Kategorie",
"categoryPlaceholder": "z.\u00a0B. inhalt",
"tagsLabel": "Tags (kommagetrennt)",
"tagsPlaceholder": "z.\u00a0B. inhalt, blog",
"strictLabel": "Strikt (unbekannte Felder ablehnen)",
"fieldsLabel": "Felder",
"addField": "Feld hinzuf\u00fcgen",
"fieldNamePlaceholder": "Feldname",
"required": "Pflichtfeld",
"removeField": "Feld entfernen",
"collectionPlaceholder": "Sammlung (z.\u00a0B. seite)",
"fieldDescriptionPlaceholder": "Feldbeschreibung (optional)",
"saving": "Speichern\u2026",
"save": "Speichern",
"cancel": "Abbrechen"
},
"ErrorBoundary": {
"title": "Etwas ist schiefgelaufen",
"reload": "Seite neu laden"
},
"Breadcrumbs": {
"ariaLabel": "Breadcrumb",
"content": "Inhalte"
},
"ContentListPage": {
"title": "Einträge",
"newEntry": "Neuer Eintrag",
"colActions": "Aktionen",
"noEntries": "Keine Einträge.",
"noEntriesCreate": "Noch keine Einträge. Erstellen Sie den ersten.",
"edit": "Bearbeiten",
"searchPlaceholder": "Suchen…",
"loading": "Laden…",
"sortBy": "Sortieren nach {field}",
"sortAsc": "Aufsteigend",
"sortDesc": "Absteigend"
},
"ContentNewPage": {
"breadcrumbNew": "Neu",
"title": "Neuen Eintrag anlegen"
},
"ContentEditPage": {
"title": "Eintrag bearbeiten",
"apiLink": "API-Link (Daten-Vorschau):"
},
"AssetsPage": {
"titleAll": "Alle Assets",
"titleRoot": "Root",
"assetCount": "{count} Bild(er)",
"upload": "Hochladen",
"uploading": "Wird hochgeladen…",
"uploadedCount": "{count} Datei(en) hochgeladen.",
"dropZoneHintRoot": "Klicken oder hierher ziehen (Root)",
"dropZoneHintFolder": "Klicken oder hierher ziehen → \"{folder}\"",
"loading": "Laden…",
"errorLoading": "Fehler beim Laden der Assets",
"noAssets": "Noch keine Assets hier.",
"urlCopied": "URL kopiert.",
"copyUrl": "URL kopieren",
"confirmDelete": "\"{filename}\" löschen?",
"confirmDeleteDesc": "Dies kann nicht rückgängig gemacht werden.",
"yesDelete": "Ja, löschen",
"deleting": "…",
"cancel": "Abbrechen",
"deleted": "\"{filename}\" gelöscht.",
"folders": "Ordner",
"all": "Alle",
"root": "Root",
"newFolder": "Neuer Ordner",
"folderNamePlaceholder": "z. B. blog",
"folderCreated": "Ordner \"{name}\" erstellt.",
"folderDeleted": "Ordner \"{name}\" gelöscht.",
"confirmDeleteFolder": "Ordner \"{name}\" löschen?",
"confirmDeleteFolderDesc": "Nur leere Ordner können gelöscht werden.",
"renameTitle": "Bild umbenennen",
"renameFilenameLabel": "Dateiname",
"rename": "Umbenennen",
"renaming": "Wird umbenannt…",
"renamed": "\"{filename}\" umbenannt.",
"copyWithTransformTitle": "Kopie mit Transformation",
"copyWithTransformDesc": "Neues Asset aus diesem Bild mit Größe/Beschnitt/Format. Gleicher Ordner.",
"copyWithTransformNewName": "Neuer Dateiname",
"copyWithTransformCreate": "Kopie erstellen",
"copyWithTransformDone": "Transformierte Kopie erstellt.",
"creating": "Wird erstellt…"
}
}

263
admin-ui/messages/en.json Normal file
View File

@@ -0,0 +1,263 @@
{
"Sidebar": {
"dashboard": "Dashboard",
"types": "Types",
"assets": "Assets",
"searchPlaceholder": "Search collections…",
"searchAriaLabel": "Search collections",
"closeMenu": "Close menu",
"loading": "Loading…",
"errorLoading": "Error loading collections",
"noResults": "No results for \"{query}\""
},
"ContentForm": {
"slugRequired": "Slug is required.",
"slugInUse": "Slug already in use.",
"slugMustStartWith": "Slug must start with \"{prefix}\".",
"slugPrefix": "prefix",
"slugSuffixPlaceholder": "e.g. my-campaign",
"slugSuffixAriaLabel": "Slug suffix (prefix is fixed)",
"slugPlaceholder": "e.g. my-post",
"slugHint": "Lowercase letters (a-z), digits (0-9), hyphens. Spaces become hyphens.",
"savedSuccessfully": "Saved successfully.",
"errorSaving": "Error saving",
"saving": "Saving…",
"save": "Save",
"backToList": "Back to list",
"pleaseSelect": "— Please select —",
"removeEntry": "Remove",
"addEntry": "+ Add entry",
"keyPlaceholder": "Key",
"valuePlaceholder": "Value"
},
"SearchableSelect": {
"placeholder": "— Please select —",
"clearLabel": "— Clear selection —",
"filterPlaceholder": "Filter…",
"emptyLabel": "No matches"
},
"ReferenceField": {
"typeLabel": "Type: {collection}",
"typesLabel": "Types: {collections}",
"selectType": "— Select type —",
"newEntry": "New entry",
"noCollection": "No reference collection in schema. Set {collectionCode} or {collectionsCode} in the type, or start the API and reload the page."
},
"ReferenceArrayField": {
"typeLabel": "Type: {collection}",
"typesLabel": "Types: {collections}",
"componentType": "Component type",
"selectType": "— Select type —",
"selectFromExisting": "— Select from existing —",
"filterPlaceholder": "Filter…",
"emptyLabel": "No matches",
"selectExistingAriaLabel": "Select existing entry to add",
"moveUp": "Move up",
"moveDown": "Move down",
"remove": "Remove",
"newComponent": "+ New {collection} component",
"createNewComponent": "+ Create new component…",
"openInNewTab": "Open in new tab; then reload this page.",
"noCollection": "No reference collection in schema. Set {collectionCode} or {collectionsCode} in the type, or start the API and reload the page."
},
"MarkdownEditor": {
"bold": "Bold",
"italic": "Italic",
"code": "Code",
"link": "Link",
"bulletList": "Bullet list",
"bulletListButton": "• List",
"placeholder": "Enter markdown… **bold**, *italic*, [link](url), - list",
"preview": "Preview",
"emptyPreview": "Empty — preview appears as you type."
},
"PaginationLinks": {
"back": "Back",
"next": "Next",
"pageInfo": "Page {page} of {totalPages} ({total} entries)"
},
"DataPreviewPanel": {
"hide": "Hide data preview",
"show": "Data preview",
"loading": "Loading…",
"errorLoading": "Error loading"
},
"SchemaPanel": {
"hide": "Hide schema",
"show": "Show schema"
},
"SchemaAndEditBar": {
"editSchema": "Edit schema"
},
"SchemaAndPreviewBar": {
"hideSchema": "Hide schema",
"showSchema": "Show schema",
"editSchema": "Edit schema",
"hidePreview": "Hide data preview",
"showPreview": "Data preview",
"loading": "Loading…",
"errorLoading": "Error loading"
},
"ReferenceOrInlineField": {
"reference": "Reference",
"inline": "Inline",
"inlineObject": "Inline object (no reference)",
"noInlineSchema": "No inline schema. Reload or check API (useFields / collection)."
},
"LocaleSwitcher": {
"label": "Language"
},
"ContentLocaleSwitcher": {
"label": "Content language"
},
"Dashboard": {
"title": "Dashboard",
"subtitle": "Choose a collection to manage content.",
"noCollections": "No collections loaded. Check that the RustyCMS API is running at {url}."
},
"TypesPage": {
"title": "Types",
"newType": "New type",
"description": "Content types (collections). Edit the schema or delete a type. Deleting removes the type definition file; existing content entries are not removed.",
"loading": "Loading…",
"errorLoading": "Error loading types: {error}",
"noTypes": "No types yet. Create one with \"New type\".",
"colName": "Name",
"colDescription": "Description",
"colCategory": "Category",
"colActions": "Actions",
"confirmDelete": "Delete \"{name}\"?",
"confirmDeleteFinal": "Really delete \"{name}\"? This cannot be undone.",
"delete": "Delete",
"yesDelete": "Yes, delete",
"deleting": "…",
"cancel": "Cancel",
"edit": "Edit"
},
"NewTypePage": {
"title": "Add new type",
"description": "Creates a new content type (collection). The schema file is saved on the server at {path} and loaded via hot-reload.",
"nameRequired": "Name is required.",
"nameInvalid": "Name: only lowercase letters, digits and underscores.",
"fieldRequired": "At least one field required.",
"fieldNamesUnique": "Field names must be unique.",
"errorCreating": "Error creating type.",
"nameLabel": "Name",
"namePlaceholder": "e.g. product, blog_post",
"nameHint": "Lowercase letters, digits and underscores only.",
"descriptionLabel": "Description",
"categoryLabel": "Category",
"categoryPlaceholder": "e.g. content",
"tagsLabel": "Tags (comma-separated)",
"tagsPlaceholder": "e.g. content, blog",
"strictLabel": "Strict (reject unknown fields)",
"fieldsLabel": "Fields",
"addField": "Add field",
"fieldNamePlaceholder": "Field name",
"required": "Required",
"removeField": "Remove field",
"collectionPlaceholder": "Collection (e.g. page)",
"fieldDescriptionPlaceholder": "Field description (optional)",
"creating": "Creating…",
"createType": "Create type",
"cancel": "Cancel"
},
"EditTypePage": {
"fieldRequired": "At least one field required.",
"fieldNamesUnique": "Field names must be unique.",
"errorSaving": "Error saving type.",
"missingName": "Missing type name.",
"backToTypes": "Back to Types",
"loading": "Loading…",
"errorLoading": "Error loading type: {error}",
"title": "Edit type: {name}",
"description": "Change description, category, tags, and fields. The schema file is updated on the server.",
"nameLabel": "Name",
"descriptionLabel": "Description",
"categoryLabel": "Category",
"categoryPlaceholder": "e.g. content",
"tagsLabel": "Tags (comma-separated)",
"tagsPlaceholder": "e.g. content, blog",
"strictLabel": "Strict (reject unknown fields)",
"fieldsLabel": "Fields",
"addField": "Add field",
"fieldNamePlaceholder": "Field name",
"required": "Required",
"removeField": "Remove field",
"collectionPlaceholder": "Collection (e.g. page)",
"fieldDescriptionPlaceholder": "Field description (optional)",
"saving": "Saving…",
"save": "Save",
"cancel": "Cancel"
},
"ErrorBoundary": {
"title": "Something went wrong",
"reload": "Reload page"
},
"Breadcrumbs": {
"ariaLabel": "Breadcrumb",
"content": "Content"
},
"ContentListPage": {
"title": "Entries",
"newEntry": "New entry",
"colActions": "Actions",
"noEntries": "No entries.",
"noEntriesCreate": "No entries yet. Create the first one.",
"edit": "Edit",
"searchPlaceholder": "Search…",
"loading": "Loading…",
"sortBy": "Sort by {field}",
"sortAsc": "Ascending",
"sortDesc": "Descending"
},
"ContentNewPage": {
"breadcrumbNew": "New",
"title": "Create new entry"
},
"ContentEditPage": {
"title": "Edit entry",
"apiLink": "API link (data preview):"
},
"AssetsPage": {
"titleAll": "All assets",
"titleRoot": "Root",
"assetCount": "{count} image(s)",
"upload": "Upload",
"uploading": "Uploading…",
"uploadedCount": "Uploaded {count} file(s).",
"dropZoneHintRoot": "Click or drag & drop to upload to root",
"dropZoneHintFolder": "Click or drag & drop to upload to \"{folder}\"",
"loading": "Loading…",
"errorLoading": "Error loading assets",
"noAssets": "No assets here yet.",
"urlCopied": "URL copied.",
"copyUrl": "Copy URL",
"confirmDelete": "Delete \"{filename}\"?",
"confirmDeleteDesc": "This cannot be undone.",
"yesDelete": "Yes, delete",
"deleting": "…",
"cancel": "Cancel",
"deleted": "\"{filename}\" deleted.",
"folders": "Folders",
"all": "All",
"root": "Root",
"newFolder": "New folder",
"folderNamePlaceholder": "e.g. blog",
"folderCreated": "Folder \"{name}\" created.",
"folderDeleted": "Folder \"{name}\" deleted.",
"confirmDeleteFolder": "Delete folder \"{name}\"?",
"confirmDeleteFolderDesc": "Only empty folders can be deleted.",
"renameTitle": "Rename image",
"renameFilenameLabel": "Filename",
"rename": "Rename",
"renaming": "Renaming…",
"renamed": "\"{filename}\" renamed.",
"copyWithTransformTitle": "Copy with transformation",
"copyWithTransformDesc": "Create a new asset from this image with resize/crop/format. Same folder.",
"copyWithTransformNewName": "New filename",
"copyWithTransformCreate": "Create copy",
"copyWithTransformDone": "Transformed copy created.",
"creating": "Creating…"
}
}

View File

@@ -1,7 +1,7 @@
import type { NextConfig } from "next";
import createNextIntlPlugin from 'next-intl/plugin';
const nextConfig: NextConfig = {
/* config options here */
};
const withNextIntl = createNextIntlPlugin('./i18n/request.ts');
export default nextConfig;
export default withNextIntl({
output: 'standalone',
});

File diff suppressed because it is too large Load Diff

View File

@@ -9,12 +9,23 @@
"lint": "eslint"
},
"dependencies": {
"@fontsource-variable/space-grotesk": "^5.2.10",
"@iconify/react": "^6.0.2",
"@tanstack/react-query": "^5.90.21",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"lucide-react": "^0.577.0",
"next": "16.1.6",
"next-intl": "^4.8.3",
"radix-ui": "^1.4.3",
"react": "19.2.3",
"react-dom": "19.2.3",
"react-hook-form": "^7.71.1",
"react-markdown": "^10.1.0"
"react-markdown": "^10.1.0",
"sonner": "^2.0.7",
"tailwind-merge": "^3.5.0",
"tailwindcss-animate": "^1.0.7"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",

View File

@@ -3,21 +3,25 @@
import { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Icon } from "@iconify/react";
import { useQueryClient } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { createSchema, type SchemaDefinition, type FieldDefinition } from "@/lib/api";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
const FIELD_TYPES = [
"string",
"number",
"integer",
"boolean",
"datetime",
"richtext",
"html",
"markdown",
"reference",
"array",
"object",
"string", "number", "integer", "boolean", "datetime",
"richtext", "html", "markdown", "reference", "array", "object",
] as const;
type FieldRow = {
@@ -34,6 +38,7 @@ function nextId() {
}
export default function NewTypePage() {
const t = useTranslations("NewTypePage");
const router = useRouter();
const queryClient = useQueryClient();
const [name, setName] = useState("");
@@ -59,45 +64,29 @@ export default function NewTypePage() {
};
const updateField = (id: string, patch: Partial<FieldRow>) => {
setFields((prev) =>
prev.map((f) => (f.id === id ? { ...f, ...patch } : f))
);
setFields((prev) => prev.map((f) => (f.id === id ? { ...f, ...patch } : f)));
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
const nameTrim = name.trim().toLowerCase().replace(/\s+/g, "_");
if (!nameTrim) {
setError("Name is required.");
return;
}
if (!/^[a-z0-9_]+$/.test(nameTrim)) {
setError("Name: only lowercase letters, digits and underscores.");
return;
}
if (!nameTrim) { setError(t("nameRequired")); return; }
if (!/^[a-z0-9_]+$/.test(nameTrim)) { setError(t("nameInvalid")); return; }
const fieldNames = fields.map((f) => f.name.trim()).filter(Boolean);
if (fieldNames.length === 0) {
setError("At least one field required.");
return;
}
const unique = new Set(fieldNames);
if (unique.size !== fieldNames.length) {
setError("Field names must be unique.");
return;
}
if (fieldNames.length === 0) { setError(t("fieldRequired")); return; }
if (new Set(fieldNames).size !== fieldNames.length) { setError(t("fieldNamesUnique")); return; }
const fieldsObj: Record<string, FieldDefinition> = {};
for (const row of fields) {
const fn = row.name.trim();
if (!fn) continue;
const def: FieldDefinition = {
fieldsObj[fn] = {
type: row.type,
required: row.required,
description: row.description.trim() || undefined,
collection: row.type === "reference" && row.collection.trim() ? row.collection.trim() : undefined,
};
fieldsObj[fn] = def;
}
const schema: SchemaDefinition = {
@@ -117,17 +106,16 @@ export default function NewTypePage() {
router.push(`/content/${nameTrim}`);
router.refresh();
} catch (err) {
setError(err instanceof Error ? err.message : "Error creating type.");
setError(err instanceof Error ? err.message : t("errorCreating"));
setSubmitting(false);
}
};
return (
<div className="max-w-2xl">
<h1 className="mb-6 text-2xl font-semibold text-gray-900">Add new type</h1>
<h1 className="mb-6 text-2xl font-semibold text-gray-900">{t("title")}</h1>
<p className="mb-6 text-sm text-gray-600">
Creates a new content type (collection). The schema file is saved on the server at{" "}
<code className="rounded bg-gray-100 px-1">types/&lt;name&gt;.json</code> and loaded via hot-reload.
{t("description", { path: "types/<name>.json" })}
</p>
<form onSubmit={handleSubmit} className="space-y-6">
@@ -136,78 +124,67 @@ export default function NewTypePage() {
)}
<div>
<label className="mb-1 block text-sm font-medium text-gray-700">
Name <span className="text-red-500">*</span>
</label>
<input
<Label className="mb-1 block">
{t("nameLabel")} <span className="text-red-500">*</span>
</Label>
<Input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="e.g. product, blog_post"
className="block w-full rounded border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900"
placeholder={t("namePlaceholder")}
required
/>
<p className="mt-0.5 text-xs text-gray-500">
Lowercase letters, digits and underscores only.
</p>
<p className="mt-0.5 text-xs text-gray-500">{t("nameHint")}</p>
</div>
<div>
<label className="mb-1 block text-sm font-medium text-gray-700">Description</label>
<input
<Label className="mb-1 block">{t("descriptionLabel")}</Label>
<Input
type="text"
value={description}
onChange={(e) => setDescription(e.target.value)}
className="block w-full rounded border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900"
/>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div>
<label className="mb-1 block text-sm font-medium text-gray-700">Category</label>
<input
<Label className="mb-1 block">{t("categoryLabel")}</Label>
<Input
type="text"
value={category}
onChange={(e) => setCategory(e.target.value)}
placeholder="e.g. content"
className="block w-full rounded border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900"
placeholder={t("categoryPlaceholder")}
/>
</div>
<div>
<label className="mb-1 block text-sm font-medium text-gray-700">Tags (comma-separated)</label>
<input
<Label className="mb-1 block">{t("tagsLabel")}</Label>
<Input
type="text"
value={tagsStr}
onChange={(e) => setTagsStr(e.target.value)}
placeholder="e.g. content, blog"
className="block w-full rounded border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900"
placeholder={t("tagsPlaceholder")}
/>
</div>
</div>
<div className="flex items-center gap-2">
<input
type="checkbox"
<Checkbox
id="strict"
checked={strict}
onChange={(e) => setStrict(e.target.checked)}
className="h-4 w-4 rounded border-gray-300"
onCheckedChange={(checked) => setStrict(!!checked)}
/>
<label htmlFor="strict" className="text-sm text-gray-700">
Strict (reject unknown fields)
{t("strictLabel")}
</label>
</div>
<div>
<div className="mb-2 flex items-center justify-between">
<label className="text-sm font-medium text-gray-700">Fields</label>
<button
type="button"
onClick={addField}
className="rounded border border-gray-300 bg-white px-2 py-1 text-sm text-gray-700 hover:bg-gray-50"
>
+ Add field
</button>
<Label>{t("fieldsLabel")}</Label>
<Button type="button" variant="outline" size="sm" onClick={addField}>
<Icon icon="mdi:plus" className="size-4" aria-hidden />
{t("addField")}
</Button>
</div>
<div className="space-y-3 rounded-lg border border-gray-200 bg-gray-50/50 p-4">
{fields.map((f) => (
@@ -215,56 +192,57 @@ export default function NewTypePage() {
key={f.id}
className="grid gap-2 rounded border border-gray-200 bg-white p-3 sm:grid-cols-[1fr_1fr_auto_auto]"
>
<input
<Input
type="text"
value={f.name}
onChange={(e) => updateField(f.id, { name: e.target.value })}
placeholder="Field name"
className="rounded border border-gray-300 px-2 py-1.5 text-sm"
placeholder={t("fieldNamePlaceholder")}
className="h-8 text-sm"
/>
<select
<Select
value={f.type}
onChange={(e) => updateField(f.id, { type: e.target.value })}
className="rounded border border-gray-300 px-2 py-1.5 text-sm"
onValueChange={(v) => updateField(f.id, { type: v })}
>
{FIELD_TYPES.map((t) => (
<option key={t} value={t}>
{t}
</option>
))}
</select>
<label className="flex items-center gap-1 text-sm">
<input
type="checkbox"
<SelectTrigger className="h-8 text-sm">
<SelectValue />
</SelectTrigger>
<SelectContent>
{FIELD_TYPES.map((type) => (
<SelectItem key={type} value={type}>{type}</SelectItem>
))}
</SelectContent>
</Select>
<label className="flex items-center gap-1 text-sm text-foreground">
<Checkbox
checked={f.required}
onChange={(e) => updateField(f.id, { required: e.target.checked })}
className="h-4 w-4 rounded border-gray-300"
onCheckedChange={(checked) => updateField(f.id, { required: !!checked })}
/>
Required
{t("required")}
</label>
<button
type="button"
onClick={() => removeField(f.id)}
className="rounded px-2 py-1 text-sm text-red-600 hover:bg-red-50"
title="Remove field"
title={t("removeField")}
aria-label={t("removeField")}
className="rounded p-1.5 text-red-600 hover:bg-red-50"
>
Entfernen
<Icon icon="mdi:delete-outline" className="size-5" aria-hidden />
</button>
{f.type === "reference" && (
<input
<Input
type="text"
value={f.collection}
onChange={(e) => updateField(f.id, { collection: e.target.value })}
placeholder="Collection (e.g. page)"
className="sm:col-span-2 rounded border border-gray-300 px-2 py-1.5 text-sm"
placeholder={t("collectionPlaceholder")}
className="h-8 text-sm sm:col-span-2"
/>
)}
<input
<Input
type="text"
value={f.description}
onChange={(e) => updateField(f.id, { description: e.target.value })}
placeholder="Field description (optional)"
className="sm:col-span-2 rounded border border-gray-300 px-2 py-1.5 text-sm"
placeholder={t("fieldDescriptionPlaceholder")}
className="h-8 text-sm sm:col-span-2"
/>
</div>
))}
@@ -272,19 +250,12 @@ export default function NewTypePage() {
</div>
<div className="flex gap-3">
<button
type="submit"
disabled={submitting}
className="rounded-lg bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:bg-gray-800 disabled:opacity-50"
>
{submitting ? "Creating…" : "Create type"}
</button>
<Link
href="/"
className="rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50"
>
Cancel
</Link>
<Button type="submit" disabled={submitting}>
{submitting ? t("creating") : t("createType")}
</Button>
<Button variant="outline" asChild>
<Link href="/">{t("cancel")}</Link>
</Button>
</div>
</form>
</div>

View File

@@ -0,0 +1,303 @@
"use client";
import { useState, useEffect } from "react";
import { useRouter, useParams } from "next/navigation";
import Link from "next/link";
import { Icon } from "@iconify/react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { fetchSchema, updateSchema, type SchemaDefinition, type FieldDefinition } from "@/lib/api";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
const FIELD_TYPES = [
"string", "number", "integer", "boolean", "datetime",
"richtext", "html", "markdown", "reference", "array", "object",
"textOrRef", "referenceOrInline",
] as const;
type FieldRow = {
id: string;
name: string;
type: string;
required: boolean;
description: string;
collection: string;
original?: FieldDefinition;
};
function nextId() {
return Math.random().toString(36).slice(2, 9);
}
function schemaToFieldRows(schema: SchemaDefinition): FieldRow[] {
const fields = schema.fields ?? {};
return Object.entries(fields).map(([name, def]) => ({
id: nextId(),
name,
type: def.type ?? "string",
required: !!def.required,
description: (def.description as string) ?? "",
collection: (def.collection as string) ?? "",
original: def,
}));
}
export default function EditTypePage() {
const t = useTranslations("EditTypePage");
const router = useRouter();
const params = useParams();
const name = typeof params.name === "string" ? params.name : "";
const queryClient = useQueryClient();
const { data: schema, isLoading, error: fetchError } = useQuery({
queryKey: ["schema", name],
queryFn: () => fetchSchema(name),
enabled: !!name,
});
const [description, setDescription] = useState("");
const [category, setCategory] = useState("");
const [tagsStr, setTagsStr] = useState("");
const [strict, setStrict] = useState(false);
const [fields, setFields] = useState<FieldRow[]>([]);
const [error, setError] = useState<string | null>(null);
const [submitting, setSubmitting] = useState(false);
useEffect(() => {
if (schema) {
setDescription(schema.description ?? "");
setCategory(schema.category ?? "");
setTagsStr(schema.tags?.length ? schema.tags.join(", ") : "");
setStrict(!!schema.strict);
setFields(schemaToFieldRows(schema));
}
}, [schema]);
const addField = () => {
setFields((prev) => [
...prev,
{ id: nextId(), name: "", type: "string", required: false, description: "", collection: "" },
]);
};
const removeField = (id: string) => {
setFields((prev) => (prev.length <= 1 ? prev : prev.filter((f) => f.id !== id)));
};
const updateField = (id: string, patch: Partial<FieldRow>) => {
setFields((prev) => prev.map((f) => (f.id === id ? { ...f, ...patch } : f)));
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
const fieldNames = fields.map((f) => f.name.trim()).filter(Boolean);
if (fieldNames.length === 0) { setError(t("fieldRequired")); return; }
if (new Set(fieldNames).size !== fieldNames.length) { setError(t("fieldNamesUnique")); return; }
const fieldsObj: Record<string, FieldDefinition> = {};
for (const row of fields) {
const fn = row.name.trim();
if (!fn) continue;
const base = row.original ?? {};
fieldsObj[fn] = {
...base,
type: row.type,
required: row.required,
description: row.description.trim() || undefined,
collection: row.type === "reference" && row.collection.trim() ? row.collection.trim() : undefined,
};
}
const payload: SchemaDefinition = {
...schema!,
name,
description: description.trim() || undefined,
category: category.trim() || undefined,
tags: tagsStr.trim() ? tagsStr.split(",").map((t) => t.trim()).filter(Boolean) : undefined,
strict,
fields: fieldsObj,
};
setSubmitting(true);
try {
await updateSchema(name, payload);
await queryClient.invalidateQueries({ queryKey: ["collections"] });
await queryClient.invalidateQueries({ queryKey: ["schema", name] });
router.push("/admin/types");
router.refresh();
} catch (err) {
setError(err instanceof Error ? err.message : t("errorSaving"));
setSubmitting(false);
}
};
if (!name) {
return (
<div>
<p className="text-gray-500">{t("missingName")}</p>
<Link href="/admin/types" className="link-accent mt-2 inline-block">{t("backToTypes")}</Link>
</div>
);
}
if (isLoading || !schema) {
return <p className="text-gray-500">{t("loading")}</p>;
}
if (fetchError) {
return (
<div>
<p className="text-red-600">{t("errorLoading", { error: String(fetchError) })}</p>
<Link href="/admin/types" className="link-accent mt-2 inline-block">{t("backToTypes")}</Link>
</div>
);
}
return (
<div className="max-w-2xl">
<h1 className="mb-6 text-2xl font-semibold text-gray-900">{t("title", { name })}</h1>
<p className="mb-6 text-sm text-gray-600">{t("description")}</p>
<form onSubmit={handleSubmit} className="space-y-6">
{error && (
<div className="rounded-lg bg-red-50 p-3 text-sm text-red-700">{error}</div>
)}
<div>
<Label className="mb-1 block">{t("nameLabel")}</Label>
<Input type="text" value={name} readOnly className="bg-gray-100 text-gray-600" />
</div>
<div>
<Label className="mb-1 block">{t("descriptionLabel")}</Label>
<Input
type="text"
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div>
<Label className="mb-1 block">{t("categoryLabel")}</Label>
<Input
type="text"
value={category}
onChange={(e) => setCategory(e.target.value)}
placeholder={t("categoryPlaceholder")}
/>
</div>
<div>
<Label className="mb-1 block">{t("tagsLabel")}</Label>
<Input
type="text"
value={tagsStr}
onChange={(e) => setTagsStr(e.target.value)}
placeholder={t("tagsPlaceholder")}
/>
</div>
</div>
<div className="flex items-center gap-2">
<Checkbox
id="strict"
checked={strict}
onCheckedChange={(checked) => setStrict(!!checked)}
/>
<label htmlFor="strict" className="text-sm text-gray-700">{t("strictLabel")}</label>
</div>
<div>
<div className="mb-2 flex items-center justify-between">
<Label>{t("fieldsLabel")}</Label>
<Button type="button" variant="outline" size="sm" onClick={addField}>
<Icon icon="mdi:plus" className="size-4" aria-hidden />
{t("addField")}
</Button>
</div>
<div className="space-y-3 rounded-lg border border-gray-200 bg-gray-50/50 p-4">
{fields.map((f) => (
<div
key={f.id}
className="grid gap-2 rounded border border-gray-200 bg-white p-3 sm:grid-cols-[1fr_1fr_auto_auto]"
>
<Input
type="text"
value={f.name}
onChange={(e) => updateField(f.id, { name: e.target.value })}
placeholder={t("fieldNamePlaceholder")}
className="h-8 text-sm"
/>
<Select
value={f.type}
onValueChange={(v) => updateField(f.id, { type: v })}
>
<SelectTrigger className="h-8 text-sm">
<SelectValue />
</SelectTrigger>
<SelectContent>
{FIELD_TYPES.map((type) => (
<SelectItem key={type} value={type}>{type}</SelectItem>
))}
</SelectContent>
</Select>
<label className="flex items-center gap-1 text-sm text-foreground">
<Checkbox
checked={f.required}
onCheckedChange={(checked) => updateField(f.id, { required: !!checked })}
/>
{t("required")}
</label>
<button
type="button"
onClick={() => removeField(f.id)}
title={t("removeField")}
aria-label={t("removeField")}
className="rounded p-1.5 text-red-600 hover:bg-red-50"
>
<Icon icon="mdi:delete-outline" className="size-5" aria-hidden />
</button>
{f.type === "reference" && (
<Input
type="text"
value={f.collection}
onChange={(e) => updateField(f.id, { collection: e.target.value })}
placeholder={t("collectionPlaceholder")}
className="h-8 text-sm sm:col-span-2"
/>
)}
<Input
type="text"
value={f.description}
onChange={(e) => updateField(f.id, { description: e.target.value })}
placeholder={t("fieldDescriptionPlaceholder")}
className="h-8 text-sm sm:col-span-2"
/>
</div>
))}
</div>
</div>
<div className="flex gap-3">
<Button type="submit" disabled={submitting}>
{submitting ? t("saving") : t("save")}
</Button>
<Button variant="outline" asChild>
<Link href="/admin/types">{t("cancel")}</Link>
</Button>
</div>
</form>
</div>
);
}

View File

@@ -0,0 +1,149 @@
"use client";
import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Icon } from "@iconify/react";
import { useTranslations } from "next-intl";
import { toast } from "sonner";
import { fetchCollections, deleteSchema } from "@/lib/api";
import type { CollectionMeta } from "@/lib/api";
import { Button } from "@/components/ui/button";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
export default function TypesPage() {
const t = useTranslations("TypesPage");
const router = useRouter();
const queryClient = useQueryClient();
const [pendingDelete, setPendingDelete] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false);
const { data, isLoading, error: fetchError } = useQuery({
queryKey: ["collections"],
queryFn: fetchCollections,
});
const types = data?.collections ?? [];
const handleDoDelete = async () => {
if (!pendingDelete) return;
setDeleting(true);
try {
await deleteSchema(pendingDelete);
await queryClient.invalidateQueries({ queryKey: ["collections"] });
setPendingDelete(null);
router.refresh();
} catch (e) {
toast.error(e instanceof Error ? e.message : "Delete failed.");
} finally {
setDeleting(false);
}
};
return (
<div>
<div className="mb-6 flex items-center justify-between">
<h1 className="text-2xl font-semibold text-gray-900">{t("title")}</h1>
<Button asChild>
<Link href="/admin/new-type">
<Icon icon="mdi:plus" className="size-5" aria-hidden />
{t("newType")}
</Link>
</Button>
</div>
<p className="mb-6 text-sm text-gray-600">{t("description")}</p>
{isLoading && <p className="text-gray-500">{t("loading")}</p>}
{fetchError && (
<p className="text-red-600">{t("errorLoading", { error: String(fetchError) })}</p>
)}
{!isLoading && !fetchError && types.length === 0 && (
<p className="text-gray-500">{t("noTypes")}</p>
)}
{!isLoading && !fetchError && types.length > 0 && (
<div className="overflow-x-auto -mx-4 px-4 sm:mx-0 sm:px-0 rounded-lg border border-gray-200">
<Table className="min-w-[400px]">
<TableHeader>
<TableRow>
<TableHead>{t("colName")}</TableHead>
<TableHead>{t("colDescription")}</TableHead>
<TableHead>{t("colCategory")}</TableHead>
<TableHead className="text-right">{t("colActions")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{types.map((c: CollectionMeta) => (
<TableRow key={c.name}>
<TableCell className="font-medium">{c.name}</TableCell>
<TableCell className="max-w-xs truncate text-gray-600" title={c.description}>
{c.description ?? "—"}
</TableCell>
<TableCell className="text-gray-600">{c.category ?? "—"}</TableCell>
<TableCell className="text-right">
<div className="flex items-center justify-end gap-2">
<Button variant="outline" size="sm" asChild>
<Link href={`/admin/types/${encodeURIComponent(c.name)}/edit`}>
<Icon icon="mdi:pencil-outline" className="size-4" aria-hidden />
{t("edit")}
</Link>
</Button>
<Button
variant="outline"
size="sm"
onClick={() => setPendingDelete(c.name)}
className="border-red-200 text-red-700 hover:bg-red-50 hover:text-red-800"
>
<Icon icon="mdi:delete-outline" className="size-4" aria-hidden />
{t("delete")}
</Button>
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
)}
<AlertDialog open={!!pendingDelete} onOpenChange={(o) => !o && setPendingDelete(null)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t("confirmDelete", { name: pendingDelete ?? "" })}</AlertDialogTitle>
<AlertDialogDescription>
{t("confirmDeleteFinal", { name: pendingDelete ?? "" })}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={deleting}>{t("cancel")}</AlertDialogCancel>
<AlertDialogAction
onClick={handleDoDelete}
disabled={deleting}
className="bg-destructive text-white hover:bg-destructive/90"
>
{deleting ? t("deleting") : t("yesDelete")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}

View File

@@ -0,0 +1,838 @@
"use client";
import { useRef, useState } from "react";
import Image from "next/image";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Icon } from "@iconify/react";
import { useTranslations } from "next-intl";
import { toast } from "sonner";
import {
fetchAssets,
fetchFolders,
uploadAsset,
deleteAsset,
renameAsset as apiRenameAsset,
copyAssetWithTransformation,
getTransformedFilename,
createFolder,
deleteFolder,
} from "@/lib/api";
import type { Asset, AssetFolder, TransformParams } from "@/lib/api";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
const API_BASE = process.env.NEXT_PUBLIC_RUSTYCMS_API_URL ?? "http://127.0.0.1:3000";
const ALL = "__all__";
const ROOT = "";
function formatBytes(n: number) {
if (n < 1024) return `${n} B`;
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
return `${(n / 1024 / 1024).toFixed(1)} MB`;
}
function assetPath(asset: Asset) {
return asset.folder ? `${asset.folder}/${asset.filename}` : asset.filename;
}
export default function AssetsPage() {
const t = useTranslations("AssetsPage");
const qc = useQueryClient();
const fileInputRef = useRef<HTMLInputElement>(null);
// Folder navigation: ALL | ROOT ("") | folder name
const [selected, setSelected] = useState<string>(ALL);
// Upload
const [uploading, setUploading] = useState(false);
const [dragOver, setDragOver] = useState(false);
// Delete asset
const [pendingDeleteAsset, setPendingDeleteAsset] = useState<Asset | null>(null);
const [deletingAsset, setDeletingAsset] = useState(false);
// Preview
const [previewAsset, setPreviewAsset] = useState<Asset | null>(null);
// Delete folder
const [pendingDeleteFolder, setPendingDeleteFolder] = useState<AssetFolder | null>(null);
const [deletingFolder, setDeletingFolder] = useState(false);
// New folder
const [newFolderOpen, setNewFolderOpen] = useState(false);
const [newFolderName, setNewFolderName] = useState("");
const [creatingFolder, setCreatingFolder] = useState(false);
// Rename
const [renameTarget, setRenameTarget] = useState<Asset | null>(null);
const [renameFilename, setRenameFilename] = useState("");
const [renaming, setRenaming] = useState(false);
// Copy with transformation
const [copyTransformTarget, setCopyTransformTarget] = useState<Asset | null>(null);
const [copyTransformParams, setCopyTransformParams] = useState<TransformParams>({ format: "webp" });
const [copyTransformLoading, setCopyTransformLoading] = useState(false);
// Assets query: undefined = all, "" = root, "name" = folder
const assetsFolder = selected === ALL ? undefined : selected;
const { data: assetsData, isLoading: assetsLoading, error: assetsError } = useQuery({
queryKey: ["assets", assetsFolder],
queryFn: () => fetchAssets(assetsFolder),
});
const { data: foldersData, isLoading: foldersLoading } = useQuery({
queryKey: ["folders"],
queryFn: fetchFolders,
});
const assets = assetsData?.assets ?? [];
const folders = foldersData?.folders ?? [];
// ── Upload ──────────────────────────────────────────────────────────────
async function handleFiles(files: FileList | null) {
if (!files || files.length === 0) return;
setUploading(true);
const targetFolder = selected === ALL || selected === ROOT ? undefined : selected;
let ok = 0;
for (const file of Array.from(files)) {
try {
await uploadAsset(file, targetFolder);
ok++;
} catch (e) {
toast.error(`${file.name}: ${e instanceof Error ? e.message : "Upload failed"}`);
}
}
if (ok > 0) {
toast.success(t("uploadedCount", { count: ok }));
await qc.invalidateQueries({ queryKey: ["assets"] });
await qc.invalidateQueries({ queryKey: ["folders"] });
}
setUploading(false);
if (fileInputRef.current) fileInputRef.current.value = "";
}
// ── Delete asset ─────────────────────────────────────────────────────────
async function handleDeleteAsset() {
if (!pendingDeleteAsset) return;
setDeletingAsset(true);
try {
await deleteAsset(assetPath(pendingDeleteAsset));
toast.success(t("deleted", { filename: pendingDeleteAsset.filename }));
await qc.invalidateQueries({ queryKey: ["assets"] });
await qc.invalidateQueries({ queryKey: ["folders"] });
setPendingDeleteAsset(null);
} catch (e) {
toast.error(e instanceof Error ? e.message : "Delete failed");
} finally {
setDeletingAsset(false);
}
}
// ── Delete folder ────────────────────────────────────────────────────────
async function handleDeleteFolder() {
if (!pendingDeleteFolder) return;
setDeletingFolder(true);
try {
await deleteFolder(pendingDeleteFolder.name);
toast.success(t("folderDeleted", { name: pendingDeleteFolder.name }));
await qc.invalidateQueries({ queryKey: ["folders"] });
await qc.invalidateQueries({ queryKey: ["assets"] });
if (selected === pendingDeleteFolder.name) setSelected(ALL);
setPendingDeleteFolder(null);
} catch (e) {
toast.error(e instanceof Error ? e.message : "Delete folder failed");
} finally {
setDeletingFolder(false);
}
}
// ── Create folder ────────────────────────────────────────────────────────
async function handleCreateFolder(e: React.FormEvent) {
e.preventDefault();
if (!newFolderName.trim()) return;
setCreatingFolder(true);
try {
await createFolder(newFolderName.trim());
toast.success(t("folderCreated", { name: newFolderName.trim() }));
await qc.invalidateQueries({ queryKey: ["folders"] });
setSelected(newFolderName.trim().toLowerCase());
setNewFolderName("");
setNewFolderOpen(false);
} catch (e) {
toast.error(e instanceof Error ? e.message : "Create folder failed");
} finally {
setCreatingFolder(false);
}
}
// ── Copy URL ──────────────────────────────────────────────────────────────
function copyUrl(asset: Asset) {
navigator.clipboard.writeText(`${API_BASE}${asset.url}`);
toast.success(t("urlCopied"));
}
// ── Rename ───────────────────────────────────────────────────────────────
async function handleRename(e: React.FormEvent) {
e.preventDefault();
if (!renameTarget || !renameFilename.trim()) return;
setRenaming(true);
try {
const path = assetPath(renameTarget);
await apiRenameAsset(path, renameFilename.trim());
toast.success(t("renamed", { filename: renameFilename.trim() }));
await qc.invalidateQueries({ queryKey: ["assets"] });
await qc.invalidateQueries({ queryKey: ["folders"] });
setRenameTarget(null);
setRenameFilename("");
} catch (err) {
toast.error(err instanceof Error ? err.message : "Rename failed");
} finally {
setRenaming(false);
}
}
// ── Copy with transformation ──────────────────────────────────────────────
async function handleCopyWithTransform(e: React.FormEvent) {
e.preventDefault();
if (!copyTransformTarget) return;
setCopyTransformLoading(true);
try {
const folder = copyTransformTarget.folder ?? undefined;
await copyAssetWithTransformation(copyTransformTarget, copyTransformParams, folder);
toast.success(t("copyWithTransformDone"));
await qc.invalidateQueries({ queryKey: ["assets"] });
await qc.invalidateQueries({ queryKey: ["folders"] });
setCopyTransformTarget(null);
} catch (err) {
toast.error(err instanceof Error ? err.message : "Copy failed");
} finally {
setCopyTransformLoading(false);
}
}
// ── Upload hint ───────────────────────────────────────────────────────────
const uploadHint =
selected === ALL || selected === ROOT
? t("dropZoneHintRoot")
: t("dropZoneHintFolder", { folder: selected });
// ── Render ────────────────────────────────────────────────────────────────
const folderOptions = [
{ value: ALL, label: t("all") },
{ value: ROOT, label: t("root") },
...folders.map((f) => ({ value: f.name, label: f.name })),
];
return (
<div className="-m-4 flex h-full min-h-0 flex-col md:-m-6 md:flex-row">
{/* ── Folder sidebar (desktop) ── */}
<aside className="hidden w-52 shrink-0 flex-col border-r border-border bg-accent-50/40 md:flex">
<div className="flex items-center justify-between px-4 py-3">
<span className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
{t("folders")}
</span>
</div>
<nav className="flex-1 overflow-y-auto px-2 pb-2">
<FolderItem
label={t("all")}
icon="mdi:layers-outline"
active={selected === ALL}
onClick={() => setSelected(ALL)}
/>
<FolderItem
label={t("root")}
icon="mdi:folder-home-outline"
active={selected === ROOT}
onClick={() => setSelected(ROOT)}
/>
{foldersLoading && (
<p className="px-2 py-1 text-xs text-muted-foreground">{t("loading")}</p>
)}
{folders.length > 0 && <div className="my-1 border-t border-border/50" />}
{folders.map((f) => (
<FolderItem
key={f.name}
label={f.name}
count={f.count}
icon="mdi:folder-outline"
active={selected === f.name}
onClick={() => setSelected(f.name)}
onDelete={() => setPendingDeleteFolder(f)}
/>
))}
</nav>
<div className="border-t border-border px-2 py-2">
{newFolderOpen ? (
<form onSubmit={handleCreateFolder} className="flex gap-1">
<Input
value={newFolderName}
onChange={(e) => setNewFolderName(e.target.value)}
placeholder={t("folderNamePlaceholder")}
className="h-7 text-xs"
autoFocus
disabled={creatingFolder}
/>
<Button type="submit" size="sm" className="h-7 px-2" disabled={creatingFolder || !newFolderName.trim()}>
<Icon icon="mdi:check" className="size-3.5" />
</Button>
<Button
type="button"
size="sm"
variant="ghost"
className="h-7 px-2"
onClick={() => { setNewFolderOpen(false); setNewFolderName(""); }}
>
<Icon icon="mdi:close" className="size-3.5" />
</Button>
</form>
) : (
<button
type="button"
onClick={() => setNewFolderOpen(true)}
className="flex w-full items-center gap-1.5 rounded px-2 py-1.5 text-xs text-muted-foreground hover:bg-accent-100 hover:text-foreground"
>
<Icon icon="mdi:folder-plus-outline" className="size-4 shrink-0" aria-hidden />
{t("newFolder")}
</button>
)}
</div>
</aside>
{/* ── Mobile folder selector ── */}
<div className="shrink-0 border-b border-border bg-accent-50/40 px-4 py-3 md:hidden">
<div className="flex flex-wrap items-center gap-2">
<span className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
{t("folders")}:
</span>
<select
value={selected}
onChange={(e) => setSelected(e.target.value)}
className="min-h-[44px] flex-1 rounded-md border border-input bg-background px-3 py-2 text-sm font-medium touch-manipulation min-w-[120px]"
aria-label={t("folders")}
>
{folderOptions.map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</select>
{!newFolderOpen ? (
<Button
type="button"
variant="outline"
size="sm"
className="min-h-[44px] shrink-0"
onClick={() => setNewFolderOpen(true)}
>
<Icon icon="mdi:folder-plus-outline" className="size-4" aria-hidden />
{t("newFolder")}
</Button>
) : null}
</div>
{newFolderOpen && (
<form onSubmit={handleCreateFolder} className="mt-3 flex gap-2">
<Input
value={newFolderName}
onChange={(e) => setNewFolderName(e.target.value)}
placeholder={t("folderNamePlaceholder")}
className="min-h-[44px] flex-1 text-sm"
autoFocus
disabled={creatingFolder}
/>
<Button type="submit" size="sm" className="min-h-[44px] shrink-0" disabled={creatingFolder || !newFolderName.trim()}>
<Icon icon="mdi:check" className="size-4" aria-hidden />
</Button>
<Button
type="button"
size="sm"
variant="ghost"
className="min-h-[44px] shrink-0"
onClick={() => { setNewFolderOpen(false); setNewFolderName(""); }}
>
<Icon icon="mdi:close" className="size-4" aria-hidden />
</Button>
</form>
)}
</div>
{/* ── Main content ── */}
<div className="flex min-w-0 flex-1 flex-col overflow-hidden">
{/* Header */}
<div className="flex flex-col gap-3 border-b border-border px-4 py-3 sm:flex-row sm:items-center sm:justify-between md:px-6">
<div className="min-w-0">
<h1 className="truncate text-base font-semibold text-foreground sm:text-lg">
{selected === ALL ? t("titleAll") : selected === ROOT ? t("titleRoot") : selected}
</h1>
<p className="text-xs text-muted-foreground">
{t("assetCount", { count: assetsData?.total ?? 0 })}
</p>
</div>
<Button
onClick={() => fileInputRef.current?.click()}
disabled={uploading}
size="sm"
className="min-h-[44px] w-full shrink-0 sm:w-auto"
>
<Icon icon="mdi:upload" className="size-4" aria-hidden />
{uploading ? t("uploading") : t("upload")}
</Button>
</div>
{/* Hidden file input */}
<input
ref={fileInputRef}
type="file"
accept="image/jpeg,image/png,image/webp,image/avif,image/gif,image/svg+xml"
multiple
className="hidden"
onChange={(e) => handleFiles(e.target.files)}
/>
{/* Scrollable grid area */}
<div className="flex-1 overflow-y-auto p-4 md:p-6">
{/* Drop zone */}
<div
onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
onDragLeave={() => setDragOver(false)}
onDrop={(e) => { e.preventDefault(); setDragOver(false); handleFiles(e.dataTransfer.files); }}
onClick={() => fileInputRef.current?.click()}
className={`mb-4 flex min-h-[56px] cursor-pointer items-center justify-center rounded-lg border-2 border-dashed px-4 py-4 transition-colors md:mb-6 md:py-5 md:px-6 touch-manipulation ${
dragOver
? "border-primary bg-primary/5"
: "border-accent-200 hover:border-accent-300 hover:bg-accent-50"
}`}
>
<div className="flex items-center gap-3 text-center text-sm text-muted-foreground sm:text-left">
<Icon icon="mdi:image-plus" className="size-5 shrink-0 text-accent-400" aria-hidden />
<span>{uploadHint}</span>
</div>
</div>
{/* Loading / error */}
{assetsLoading && <p className="text-sm text-muted-foreground">{t("loading")}</p>}
{assetsError && <p className="text-sm text-destructive">{t("errorLoading")}</p>}
{/* Empty */}
{!assetsLoading && !assetsError && assets.length === 0 && (
<p className="text-sm text-muted-foreground">{t("noAssets")}</p>
)}
{/* Grid */}
{assets.length > 0 && (
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 sm:gap-4 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
{assets.map((asset) => (
<AssetCard
key={assetPath(asset)}
asset={asset}
showFolder={selected === ALL}
onPreview={() => setPreviewAsset(asset)}
onCopy={() => copyUrl(asset)}
onRename={() => { setRenameTarget(asset); setRenameFilename(asset.filename); }}
onCopyTransform={() => { setCopyTransformTarget(asset); setCopyTransformParams({ format: "webp" }); }}
onDelete={() => setPendingDeleteAsset(asset)}
/>
))}
</div>
)}
</div>
</div>
{/* ── Rename dialog ── */}
<Dialog open={!!renameTarget} onOpenChange={(o) => { if (!o) { setRenameTarget(null); setRenameFilename(""); } }}>
<DialogContent className="sm:max-w-md" showCloseButton>
<DialogHeader>
<DialogTitle>{t("renameTitle")}</DialogTitle>
</DialogHeader>
<form onSubmit={handleRename} className="flex flex-col gap-4">
<div>
<label htmlFor="rename-filename" className="mb-1 block text-sm font-medium text-foreground">
{t("renameFilenameLabel")}
</label>
<Input
id="rename-filename"
value={renameFilename}
onChange={(e) => setRenameFilename(e.target.value)}
placeholder="image.jpg"
disabled={renaming}
/>
</div>
<div className="flex justify-end gap-2">
<Button type="button" variant="outline" onClick={() => { setRenameTarget(null); setRenameFilename(""); }}>
{t("cancel")}
</Button>
<Button type="submit" disabled={renaming || !renameFilename.trim()}>
{renaming ? t("renaming") : t("rename")}
</Button>
</div>
</form>
</DialogContent>
</Dialog>
{/* ── Copy with transformation dialog ── */}
<Dialog open={!!copyTransformTarget} onOpenChange={(o) => { if (!o) setCopyTransformTarget(null); }}>
<DialogContent className="sm:max-w-md" showCloseButton>
<DialogHeader>
<DialogTitle>{t("copyWithTransformTitle")}</DialogTitle>
</DialogHeader>
<form onSubmit={handleCopyWithTransform} className="flex flex-col gap-4">
<p className="text-sm text-muted-foreground">{t("copyWithTransformDesc")}</p>
<div className="grid grid-cols-2 gap-3">
<div>
<label htmlFor="tw" className="mb-1 block text-xs font-medium text-foreground">Width</label>
<Input
id="tw"
type="number"
min={1}
placeholder="—"
value={copyTransformParams.w ?? ""}
onChange={(e) => setCopyTransformParams((p) => ({ ...p, w: e.target.value ? Number(e.target.value) : undefined }))}
className="h-8 text-sm"
/>
</div>
<div>
<label htmlFor="th" className="mb-1 block text-xs font-medium text-foreground">Height</label>
<Input
id="th"
type="number"
min={1}
placeholder="—"
value={copyTransformParams.h ?? ""}
onChange={(e) => setCopyTransformParams((p) => ({ ...p, h: e.target.value ? Number(e.target.value) : undefined }))}
className="h-8 text-sm"
/>
</div>
<div>
<label htmlFor="tar" className="mb-1 block text-xs font-medium text-foreground">Aspect (e.g. 1:1)</label>
<Input
id="tar"
placeholder="—"
value={copyTransformParams.ar ?? ""}
onChange={(e) => setCopyTransformParams((p) => ({ ...p, ar: e.target.value || undefined }))}
className="h-8 text-sm"
/>
</div>
<div>
<label htmlFor="tfit" className="mb-1 block text-xs font-medium text-foreground">Fit</label>
<select
id="tfit"
value={copyTransformParams.fit ?? "contain"}
onChange={(e) => setCopyTransformParams((p) => ({ ...p, fit: e.target.value as TransformParams["fit"] }))}
className="h-8 w-full rounded-md border border-input bg-background px-3 py-1 text-sm"
>
<option value="contain">contain</option>
<option value="cover">cover</option>
<option value="fill">fill</option>
</select>
</div>
<div className="col-span-2">
<label htmlFor="tformat" className="mb-1 block text-xs font-medium text-foreground">Format</label>
<select
id="tformat"
value={copyTransformParams.format ?? "webp"}
onChange={(e) => setCopyTransformParams((p) => ({ ...p, format: e.target.value as TransformParams["format"] }))}
className="h-8 w-full rounded-md border border-input bg-background px-3 py-1 text-sm"
>
<option value="jpeg">JPEG</option>
<option value="png">PNG</option>
<option value="webp">WebP</option>
<option value="avif">AVIF</option>
</select>
</div>
</div>
{copyTransformTarget && (
<p className="text-xs text-muted-foreground">
{t("copyWithTransformNewName")}: <span className="font-mono">{getTransformedFilename(copyTransformTarget.filename, copyTransformParams)}</span>
</p>
)}
<div className="flex justify-end gap-2">
<Button type="button" variant="outline" onClick={() => setCopyTransformTarget(null)}>
{t("cancel")}
</Button>
<Button type="submit" disabled={copyTransformLoading}>
{copyTransformLoading ? t("creating") : t("copyWithTransformCreate")}
</Button>
</div>
</form>
</DialogContent>
</Dialog>
{/* ── Preview dialog ── */}
<Dialog open={!!previewAsset} onOpenChange={(o) => { if (!o) setPreviewAsset(null); }}>
<DialogContent className="flex max-h-[90vh] max-w-4xl flex-col overflow-hidden" showCloseButton>
{previewAsset && (
<>
<DialogHeader className="shrink-0">
<DialogTitle className="truncate pr-8" title={previewAsset.filename}>
{previewAsset.filename}
</DialogTitle>
</DialogHeader>
<div className="flex min-h-0 flex-1 flex-col gap-4 overflow-hidden">
<div className="flex min-h-0 flex-1 justify-center overflow-hidden rounded-md bg-accent-50 p-4">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={`${API_BASE}${previewAsset.url}`}
alt={previewAsset.filename}
className="max-h-[60vh] max-w-full object-contain"
/>
</div>
<p className="text-xs text-muted-foreground">
{formatBytes(previewAsset.size)}
{previewAsset.folder && (
<span className="ml-2 rounded bg-accent-100 px-1.5 py-0.5 text-accent-700">
{previewAsset.folder}
</span>
)}
</p>
<Button
variant="outline"
size="sm"
onClick={() => previewAsset && copyUrl(previewAsset)}
>
<Icon icon="mdi:content-copy" className="size-4" aria-hidden />
{t("copyUrl")}
</Button>
</div>
</>
)}
</DialogContent>
</Dialog>
{/* ── Delete asset dialog ── */}
<AlertDialog
open={!!pendingDeleteAsset}
onOpenChange={(o) => { if (!o) setPendingDeleteAsset(null); }}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t("confirmDelete", { filename: pendingDeleteAsset?.filename ?? "" })}</AlertDialogTitle>
<AlertDialogDescription>{t("confirmDeleteDesc")}</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={deletingAsset}>{t("cancel")}</AlertDialogCancel>
<AlertDialogAction
onClick={handleDeleteAsset}
disabled={deletingAsset}
className="bg-destructive text-white hover:bg-destructive/90"
>
{deletingAsset ? t("deleting") : t("yesDelete")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{/* ── Delete folder dialog ── */}
<AlertDialog
open={!!pendingDeleteFolder}
onOpenChange={(o) => { if (!o) setPendingDeleteFolder(null); }}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t("confirmDeleteFolder", { name: pendingDeleteFolder?.name ?? "" })}</AlertDialogTitle>
<AlertDialogDescription>{t("confirmDeleteFolderDesc")}</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={deletingFolder}>{t("cancel")}</AlertDialogCancel>
<AlertDialogAction
onClick={handleDeleteFolder}
disabled={deletingFolder}
className="bg-destructive text-white hover:bg-destructive/90"
>
{deletingFolder ? t("deleting") : t("yesDelete")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}
// ── Sub-components ──────────────────────────────────────────────────────────
function FolderItem({
label,
icon,
count,
active,
onClick,
onDelete,
}: {
label: string;
icon: string;
count?: number;
active: boolean;
onClick: () => void;
onDelete?: () => void;
}) {
return (
<div
className={`group flex items-center justify-between rounded px-2 py-1.5 text-sm cursor-pointer ${
active
? "bg-accent-200/70 font-medium text-gray-900"
: "text-gray-700 hover:bg-accent-100/80 hover:text-gray-900"
}`}
onClick={onClick}
>
<span className="flex min-w-0 items-center gap-2">
<Icon icon={icon} className="size-4 shrink-0" aria-hidden />
<span className="truncate">{label}</span>
</span>
<span className="flex shrink-0 items-center gap-1">
{count !== undefined && (
<span className="text-xs text-muted-foreground tabular-nums">{count}</span>
)}
{onDelete && (
<button
type="button"
onClick={(e) => { e.stopPropagation(); onDelete(); }}
className="rounded p-0.5 opacity-0 hover:bg-destructive/10 hover:text-destructive group-hover:opacity-100"
title="Delete folder"
>
<Icon icon="mdi:trash-can-outline" className="size-3.5" aria-hidden />
</button>
)}
</span>
</div>
);
}
function AssetCard({
asset,
showFolder,
onPreview,
onCopy,
onRename,
onCopyTransform,
onDelete,
}: {
asset: Asset;
showFolder: boolean;
onPreview: () => void;
onCopy: () => void;
onRename: () => void;
onCopyTransform: () => void;
onDelete: () => void;
}) {
return (
<div className="group relative overflow-hidden rounded-lg border border-border bg-white shadow-xs">
{/* Thumbnail (click to preview) */}
<button
type="button"
onClick={onPreview}
className="relative aspect-square w-full cursor-pointer bg-accent-50 focus:outline-none focus:ring-2 focus:ring-primary focus:ring-inset touch-manipulation"
>
{asset.mime_type === "image/svg+xml" ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={`${API_BASE}${asset.url}`}
alt={asset.filename}
className="h-full w-full object-contain p-2"
/>
) : (
<Image
src={`${API_BASE}${asset.url}`}
alt={asset.filename}
fill
className="object-cover"
sizes="(max-width: 640px) 50vw, 200px"
unoptimized
/>
)}
</button>
{/* Info */}
<div className="px-2 py-1.5">
<p className="truncate text-xs font-medium text-foreground" title={asset.filename}>
{asset.filename}
</p>
<p className="text-xs text-muted-foreground">
{showFolder && asset.folder && (
<span className="mr-1 rounded bg-accent-100 px-1 text-accent-700">{asset.folder}</span>
)}
{formatBytes(asset.size)}
</p>
</div>
{/* Mobile: always-visible action row (touch-friendly) */}
<div className="flex items-center justify-end gap-1 border-t border-border/50 px-2 py-1.5 md:hidden">
<button type="button" onClick={(e) => { e.stopPropagation(); onCopy(); }} className="inline-flex size-9 shrink-0 items-center justify-center rounded-md border border-border bg-white text-gray-700 hover:bg-accent-50 touch-manipulation" title="Copy URL" aria-label="Copy URL">
<Icon icon="mdi:content-copy" className="size-4" aria-hidden />
</button>
<button type="button" onClick={(e) => { e.stopPropagation(); onRename(); }} className="inline-flex size-9 shrink-0 items-center justify-center rounded-md border border-border bg-white text-gray-700 hover:bg-accent-50 touch-manipulation" title="Rename" aria-label="Rename">
<Icon icon="mdi:pencil" className="size-4" aria-hidden />
</button>
<button type="button" onClick={(e) => { e.stopPropagation(); onCopyTransform(); }} className="inline-flex size-9 shrink-0 items-center justify-center rounded-md border border-border bg-white text-gray-700 hover:bg-accent-50 touch-manipulation" title="Copy with transformation" aria-label="Copy with transformation">
<Icon icon="mdi:image-multiple-outline" className="size-4" aria-hidden />
</button>
<button type="button" onClick={(e) => { e.stopPropagation(); onDelete(); }} className="inline-flex size-9 shrink-0 items-center justify-center rounded-md border border-border bg-white text-gray-700 hover:bg-destructive hover:text-white touch-manipulation" title="Delete" aria-label="Delete">
<Icon icon="mdi:trash-can-outline" className="size-4" aria-hidden />
</button>
</div>
{/* Hover actions stopPropagation so click doesnt trigger thumbnail preview */}
<div className="absolute inset-x-0 top-0 hidden flex-wrap justify-end gap-0.5 p-1 opacity-0 transition-opacity group-hover:opacity-100 md:flex">
<button
type="button"
onClick={(e) => { e.stopPropagation(); onCopy(); }}
title="Copy URL"
className="rounded bg-white/90 p-1 shadow-sm hover:bg-white"
>
<Icon icon="mdi:content-copy" className="size-4 text-gray-700" aria-hidden />
</button>
<button
type="button"
onClick={(e) => { e.stopPropagation(); onRename(); }}
title="Rename"
className="rounded bg-white/90 p-1 shadow-sm hover:bg-white"
>
<Icon icon="mdi:pencil" className="size-4 text-gray-700" aria-hidden />
</button>
<button
type="button"
onClick={(e) => { e.stopPropagation(); onCopyTransform(); }}
title="Copy with transformation"
className="rounded bg-white/90 p-1 shadow-sm hover:bg-white"
>
<Icon icon="mdi:image-multiple-outline" className="size-4 text-gray-700" aria-hidden />
</button>
<button
type="button"
onClick={(e) => { e.stopPropagation(); onDelete(); }}
title="Delete"
className="rounded bg-white/90 p-1 shadow-sm hover:bg-destructive hover:text-white"
>
<Icon icon="mdi:trash-can-outline" className="size-4" aria-hidden />
</button>
</div>
</div>
);
}

View File

@@ -0,0 +1,148 @@
"use client";
import { useEffect } from "react";
import Link from "next/link";
import { useParams, useSearchParams } from "next/navigation";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Icon } from "@iconify/react";
import { useTranslations } from "next-intl";
import { fetchSchema, fetchEntry, fetchLocales } from "@/lib/api";
import { ContentForm } from "@/components/ContentForm";
import { SchemaAndPreviewBar } from "@/components/SchemaAndPreviewBar";
import { ContentLocaleSwitcher } from "@/components/ContentLocaleSwitcher";
import { Breadcrumbs } from "@/components/Breadcrumbs";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
export default function ContentEditPage() {
const t = useTranslations("ContentEditPage");
const tList = useTranslations("ContentForm");
const params = useParams();
const searchParams = useSearchParams();
const queryClient = useQueryClient();
const collection = typeof params.collection === "string" ? params.collection : "";
const slug = typeof params.slug === "string" ? params.slug : "";
const locale = searchParams.get("_locale") ?? undefined;
const { data: schema, isLoading: schemaLoading, error: schemaError } = useQuery({
queryKey: ["schema", collection],
queryFn: () => fetchSchema(collection),
enabled: !!collection,
});
const {
data: entry,
isLoading: entryLoading,
error: entryError,
} = useQuery({
queryKey: ["entry", collection, slug, locale ?? ""],
queryFn: () =>
fetchEntry(collection, slug, {
...(locale ? { _locale: locale } : {}),
}),
enabled: !!collection && !!slug,
});
const { data: localesData } = useQuery({
queryKey: ["locales"],
queryFn: fetchLocales,
});
const locales = localesData?.locales ?? [];
const defaultLocale = localesData?.default ?? null;
const onSuccess = () => {
void queryClient.invalidateQueries({ queryKey: ["entry", collection, slug] });
void queryClient.invalidateQueries({ queryKey: ["content", collection] });
};
if (!collection || !slug) {
return (
<div className="rounded bg-amber-50 p-4 text-amber-800">
Missing collection or slug.
</div>
);
}
const localeQ = locale ? `?_locale=${locale}` : "";
const listHref = `/content/${collection}${localeQ}`;
const isLoading = schemaLoading || entryLoading;
const error = schemaError ?? entryError;
const tBread = useTranslations("Breadcrumbs");
useEffect(() => {
document.title = schema && entry
? `${slug}${collection} — RustyCMS Admin`
: "RustyCMS Admin";
return () => {
document.title = "RustyCMS Admin";
};
}, [collection, slug, schema, entry]);
return (
<div>
<Breadcrumbs
items={[
{ label: tBread("content"), href: "/" },
{ label: collection, href: listHref },
{ label: slug },
]}
/>
<div className="mb-4 flex flex-wrap items-center justify-between gap-3">
<div className="flex flex-wrap items-center gap-3">
<Button variant="outline" size="sm" asChild>
<Link href={listHref}>
<Icon icon="mdi:arrow-left" className="size-4" aria-hidden />
{tList("backToList")}
</Link>
</Button>
<ContentLocaleSwitcher
locales={locales}
defaultLocale={defaultLocale}
currentLocale={locale}
/>
</div>
<SchemaAndPreviewBar
schema={schema ?? null}
collection={collection}
slug={slug}
locale={locale}
/>
</div>
<h1 className="mb-6 text-2xl font-semibold text-gray-900">
{t("title")} {slug}
</h1>
{isLoading && (
<div className="max-w-2xl space-y-8">
<Skeleton className="h-10 w-full" />
<Skeleton className="h-24 w-full" />
<Skeleton className="h-24 w-full" />
<Skeleton className="h-32 w-full" />
</div>
)}
{error && (
<p className="text-red-600" role="alert">
{error instanceof Error ? error.message : String(error)}
</p>
)}
{!isLoading && !error && schema && entry && (
<ContentForm
collection={collection}
schema={schema}
initialValues={entry as Record<string, unknown>}
slug={slug}
locale={locale}
onSuccess={onSuccess}
/>
)}
{!isLoading && !error && schema && !entry && (
<p className="text-amber-700">
Entry not found. It may have been deleted or the slug is wrong.
</p>
)}
</div>
);
}

View File

@@ -0,0 +1,102 @@
"use client";
import { useEffect } from "react";
import Link from "next/link";
import { useParams, useSearchParams } from "next/navigation";
import { useQuery } from "@tanstack/react-query";
import { Icon } from "@iconify/react";
import { useTranslations } from "next-intl";
import { fetchSchema, fetchLocales } from "@/lib/api";
import { ContentForm } from "@/components/ContentForm";
import { SchemaAndEditBar } from "@/components/SchemaAndEditBar";
import { ContentLocaleSwitcher } from "@/components/ContentLocaleSwitcher";
import { Breadcrumbs } from "@/components/Breadcrumbs";
import { Button } from "@/components/ui/button";
export default function ContentNewPage() {
const t = useTranslations("ContentNewPage");
const tList = useTranslations("ContentForm");
const params = useParams();
const searchParams = useSearchParams();
const collection = typeof params.collection === "string" ? params.collection : "";
const locale = searchParams.get("_locale") ?? undefined;
const { data: schema, isLoading: schemaLoading, error: schemaError } = useQuery({
queryKey: ["schema", collection],
queryFn: () => fetchSchema(collection),
enabled: !!collection,
});
const { data: localesData } = useQuery({
queryKey: ["locales"],
queryFn: fetchLocales,
});
const locales = localesData?.locales ?? [];
const defaultLocale = localesData?.default ?? null;
if (!collection) {
return (
<div className="rounded bg-amber-50 p-4 text-amber-800">
Missing collection name.
</div>
);
}
const localeQ = locale ? `?_locale=${locale}` : "";
const listHref = `/content/${collection}${localeQ}`;
const tBread = useTranslations("Breadcrumbs");
const tNew = useTranslations("ContentNewPage");
useEffect(() => {
document.title = collection ? `New — ${collection} — RustyCMS Admin` : "RustyCMS Admin";
return () => {
document.title = "RustyCMS Admin";
};
}, [collection]);
return (
<div>
<Breadcrumbs
items={[
{ label: tBread("content"), href: "/" },
{ label: collection, href: listHref },
{ label: tNew("breadcrumbNew") },
]}
/>
<div className="mb-4 flex flex-wrap items-center justify-between gap-3">
<div className="flex flex-wrap items-center gap-3">
<Button variant="outline" size="sm" asChild>
<Link href={listHref}>
<Icon icon="mdi:arrow-left" className="size-4" aria-hidden />
{tList("backToList")}
</Link>
</Button>
<ContentLocaleSwitcher
locales={locales}
defaultLocale={defaultLocale}
currentLocale={locale}
/>
</div>
<SchemaAndEditBar schema={schema ?? null} collection={collection} />
</div>
<h1 className="mb-6 text-2xl font-semibold text-gray-900">
{t("title")} {collection}
</h1>
{schemaLoading && <p className="text-gray-500">Loading</p>}
{schemaError && (
<p className="text-red-600" role="alert">
{schemaError instanceof Error ? schemaError.message : String(schemaError)}
</p>
)}
{!schemaLoading && !schemaError && schema && (
<ContentForm
collection={collection}
schema={schema}
locale={locale}
/>
)}
</div>
);
}

View File

@@ -0,0 +1,233 @@
"use client";
import { useEffect } from "react";
import Link from "next/link";
import { useParams, useSearchParams } from "next/navigation";
import { useQuery } from "@tanstack/react-query";
import { Icon } from "@iconify/react";
import { useTranslations } from "next-intl";
import { fetchContentList, fetchLocales } from "@/lib/api";
import { Button } from "@/components/ui/button";
import { SearchBar } from "@/components/SearchBar";
import { PaginationLinks } from "@/components/PaginationLinks";
import { ContentLocaleSwitcher } from "@/components/ContentLocaleSwitcher";
import { Breadcrumbs } from "@/components/Breadcrumbs";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { Skeleton } from "@/components/ui/skeleton";
const PER_PAGE = 20;
export default function ContentListPage() {
const t = useTranslations("ContentListPage");
const params = useParams();
const searchParams = useSearchParams();
const collection = typeof params.collection === "string" ? params.collection : "";
const page = Math.max(1, parseInt(searchParams.get("_page") ?? "1", 10) || 1);
const sort = searchParams.get("_sort") ?? undefined;
const order = (searchParams.get("_order") ?? "asc") as "asc" | "desc";
const q = searchParams.get("_q") ?? undefined;
const locale = searchParams.get("_locale") ?? undefined;
const { data: localesData } = useQuery({
queryKey: ["locales"],
queryFn: fetchLocales,
});
const locales = localesData?.locales ?? [];
const defaultLocale = localesData?.default ?? null;
const listParams = {
_page: page,
_per_page: PER_PAGE,
...(sort ? { _sort: sort, _order: order } : {}),
...(q?.trim() ? { _q: q.trim() } : {}),
...(locale ? { _locale: locale } : {}),
};
const { data, isLoading, error } = useQuery({
queryKey: ["content", collection, listParams],
queryFn: () => fetchContentList(collection, listParams),
enabled: !!collection,
});
if (!collection) {
return (
<div className="rounded bg-amber-50 p-4 text-amber-800">
Missing collection name.
</div>
);
}
const items = data?.items ?? [];
const total = data?.total ?? 0;
const totalPages = data?.total_pages ?? 1;
const localeQ = locale ? `_locale=${locale}` : "";
const baseQuery = new URLSearchParams();
if (locale) baseQuery.set("_locale", locale);
if (q?.trim()) baseQuery.set("_q", q.trim());
const sortQuery = (field: string, order: "asc" | "desc") => {
const p = new URLSearchParams(baseQuery);
p.set("_sort", field);
p.set("_order", order);
return p.toString();
};
const isSortSlug = sort === "_slug" || !sort;
const nextSlugOrder = isSortSlug && order === "asc" ? "desc" : "asc";
const tBread = useTranslations("Breadcrumbs");
useEffect(() => {
document.title = collection ? `${collection} — RustyCMS Admin` : "RustyCMS Admin";
return () => {
document.title = "RustyCMS Admin";
};
}, [collection]);
return (
<div>
<Breadcrumbs
items={[
{ label: tBread("content"), href: "/" },
{ label: collection },
]}
/>
<div className="mb-6 flex flex-col gap-4 sm:flex-row sm:flex-wrap sm:items-center sm:justify-between">
<h1 className="text-xl font-semibold text-gray-900 sm:text-2xl truncate">
{collection}
</h1>
<div className="flex flex-wrap items-center gap-3">
<ContentLocaleSwitcher
locales={locales}
defaultLocale={defaultLocale}
currentLocale={locale}
/>
<SearchBar
placeholder={t("searchPlaceholder")}
paramName="_q"
/>
<Button asChild className="min-h-[44px] sm:min-h-0">
<Link href={`/content/${collection}/new${localeQ ? `?${localeQ}` : ""}`}>
<Icon icon="mdi:plus" className="size-5" aria-hidden />
{t("newEntry")}
</Link>
</Button>
</div>
</div>
{isLoading && (
<div className="space-y-3">
<Skeleton className="h-10 w-full max-w-md" />
<div className="rounded-lg border border-gray-200">
<Table>
<TableHeader>
<TableRow>
<TableHead>_slug</TableHead>
<TableHead className="w-24 text-right">{t("colActions")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{[1, 2, 3, 4, 5].map((i) => (
<TableRow key={i}>
<TableCell><Skeleton className="h-5 w-48" /></TableCell>
<TableCell className="text-right"><Skeleton className="ml-auto h-8 w-16" /></TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
</div>
)}
{error && (
<p className="text-red-600" role="alert">
{error instanceof Error ? error.message : String(error)}
</p>
)}
{!isLoading && !error && items.length === 0 && (
<div
className="mx-auto max-w-md rounded-xl border border-gray-200 bg-gray-50/80 px-8 text-center shadow-sm"
style={{ marginTop: "1.25rem", marginBottom: "1.25rem", paddingTop: "2rem", paddingBottom: "2.5rem" }}
>
<p className="text-base text-gray-600" style={{ marginBottom: "1.5rem" }}>
{t("noEntriesCreate")}
</p>
<div className="flex justify-center" style={{ marginBottom: "1rem" }}>
<Button asChild className="min-h-[44px] sm:min-h-0">
<Link href={`/content/${collection}/new${localeQ ? `?${localeQ}` : ""}`}>
<Icon icon="mdi:plus" className="size-5" aria-hidden />
{t("newEntry")}
</Link>
</Button>
</div>
</div>
)}
{!isLoading && !error && items.length > 0 && (
<>
<div className="overflow-x-auto -mx-4 px-4 sm:mx-0 sm:px-0 rounded-lg border border-gray-200">
<Table className="min-w-[280px]">
<TableHeader>
<TableRow>
<TableHead>
<Link
href={`/content/${collection}?${sortQuery("_slug", nextSlugOrder)}`}
className="inline-flex items-center gap-1 font-medium hover:underline"
title={t("sortBy", { field: "_slug" })}
>
_slug
{isSortSlug && (
<Icon
icon={order === "asc" ? "mdi:chevron-up" : "mdi:chevron-down"}
className="size-4"
aria-label={order === "asc" ? t("sortAsc") : t("sortDesc")}
/>
)}
</Link>
</TableHead>
<TableHead className="w-24 text-right">{t("colActions")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{items.map((entry: Record<string, unknown>) => {
const slug = entry._slug as string | undefined;
if (slug == null) return null;
const editHref = `/content/${collection}/${encodeURIComponent(slug)}${localeQ ? `?${localeQ}` : ""}`;
return (
<TableRow key={slug}>
<TableCell className="font-mono text-sm">{slug}</TableCell>
<TableCell className="text-right">
<Button variant="outline" size="sm" asChild className="min-h-[44px] sm:min-h-0">
<Link href={editHref}>
<Icon icon="mdi:pencil-outline" className="size-4" aria-hidden />
{t("edit")}
</Link>
</Button>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</div>
<PaginationLinks
collection={collection}
page={page}
totalPages={totalPages}
total={total}
locale={locale ?? undefined}
sort={sort}
order={order}
q={q ?? undefined}
/>
</>
)}
</div>
);
}

View File

@@ -1,34 +1,125 @@
@import "tailwindcss";
@plugin "tailwindcss-animate";
@import "@fontsource-variable/space-grotesk";
:root {
--background: #ffffff;
--foreground: #171717;
--font-sans: "Space Grotesk Variable", ui-sans-serif, system-ui, sans-serif;
/* Rose/Rost Accent-Skala (bleibt erhalten für bestehende Tailwind-Utilities) */
--accent-50: #fff1f2;
--accent-100: #ffe4e6;
--accent-200: #fecdd3;
--accent-300: #fda4af;
--accent-400: #fb7185;
--accent-500: #f43f5e;
--accent-600: #e11d48;
--accent-700: #be123c;
--accent-800: #9f1239;
--accent-900: #881337;
/* shadcn semantische Variablen — primary = rose */
--primary: #e11d48;
--primary-foreground: #ffffff;
--secondary: #fff1f2;
--secondary-foreground: #9f1239;
--muted: #f9fafb;
--muted-foreground: #6b7280;
--card: #ffffff;
--card-foreground: #171717;
--popover: #ffffff;
--popover-foreground: #171717;
--border: #d1d5db;
--input: #d1d5db;
--ring: #fda4af;
--destructive: #dc2626;
--destructive-foreground: #ffffff;
--radius: 0.5rem;
/* shadcn accent = subtiler Hover-Hintergrund (z.B. SelectItem, CommandItem) */
--shadcn-accent: #fff1f2;
--shadcn-accent-foreground: #881337;
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-sans);
/* Accent-Skala für bestehende Utilities */
--color-accent-50: var(--accent-50);
--color-accent-100: var(--accent-100);
--color-accent-200: var(--accent-200);
--color-accent-300: var(--accent-300);
--color-accent-400: var(--accent-400);
--color-accent-500: var(--accent-500);
--color-accent-600: var(--accent-600);
--color-accent-700: var(--accent-700);
--color-accent-800: var(--accent-800);
--color-accent-900: var(--accent-900);
/* shadcn semantische Tokens */
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
--color-destructive: var(--destructive);
--color-destructive-foreground: var(--destructive-foreground);
/* shadcn accent Utility-Klassen (bg-accent, text-accent-foreground) */
--color-accent: var(--shadcn-accent);
--color-accent-foreground: var(--shadcn-accent-foreground);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
html, body {
height: 100%;
overflow: hidden;
}
/* Safe area for notched devices (e.g. iPhone) */
@supports (padding: env(safe-area-inset-top)) {
body {
padding-left: env(safe-area-inset-left);
padding-right: env(safe-area-inset-right);
}
}
body {
background: var(--background);
color: var(--foreground);
font-family: Arial, Helvetica, sans-serif;
font-family: var(--font-sans);
}
/* Lesbare Eingabefelder: dunkler Text, heller Hintergrund */
input:not([type="checkbox"]):not([type="radio"]),
textarea,
select {
color: #111827; /* gray-900 */
background-color: #ffffff;
/* Links: exclude elements used as buttons (Slot.Root forwards data-slot) */
a:not([data-slot="button"]) {
color: var(--accent-700);
text-decoration: underline;
text-underline-offset: 2px;
}
a:not([data-slot="button"]):hover {
color: var(--accent-800);
}
/* Text-Links (Rostrot) */
.link-accent {
color: var(--accent-700);
text-decoration: underline;
text-underline-offset: 2px;
}
.link-accent:hover {
color: var(--accent-800);
}

View File

@@ -0,0 +1,110 @@
@import "tailwindcss";
@import "@fontsource-variable/space-grotesk";
/* Accent (Rost/Rose) zentral für Buttons, Links, Hover; hier anpassen für neues Look */
:root {
--background: #ffffff;
--foreground: #171717;
--font-sans: "Space Grotesk Variable", ui-sans-serif, system-ui, sans-serif;
--accent-50: #fff1f2;
--accent-100: #ffe4e6;
--accent-200: #fecdd3;
--accent-300: #fda4af;
--accent-400: #fb7185;
--accent-500: #f43f5e;
--accent-600: #e11d48;
--accent-700: #be123c;
--accent-800: #9f1239;
--accent-900: #881337;
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-sans);
--font-mono: var(--font-geist-mono);
--color-accent-50: var(--accent-50);
--color-accent-100: var(--accent-100);
--color-accent-200: var(--accent-200);
--color-accent-300: var(--accent-300);
--color-accent-400: var(--accent-400);
--color-accent-500: var(--accent-500);
--color-accent-600: var(--accent-600);
--color-accent-700: var(--accent-700);
--color-accent-800: var(--accent-800);
--color-accent-900: var(--accent-900);
}
/* Primär-Button (z.B. „Speichern“, „New entry“) */
.btn-primary {
@apply shrink-0 whitespace-nowrap rounded-lg px-4 py-2 text-sm font-medium text-white transition-colors;
background-color: var(--accent-600);
}
.btn-primary:hover:not(:disabled) {
background-color: var(--accent-700);
}
.btn-primary:disabled {
@apply opacity-50;
}
/* Sekundär-Button / Outline (z.B. „Abbrechen“, „Back“) */
.btn-secondary {
@apply rounded-lg border px-4 py-2 text-sm font-medium transition-colors;
border-color: var(--accent-200);
color: var(--accent-800);
background-color: #fff;
}
.btn-secondary:hover {
background-color: var(--accent-50);
}
/* Kleine Outline-Buttons / Links (z.B. Schema bearbeiten, Pagination) */
.btn-outline {
@apply inline-flex items-center gap-2 rounded border px-3 py-1.5 text-sm font-medium transition-colors;
border-color: var(--accent-200);
color: var(--accent-800);
background-color: #fff;
}
.btn-outline:hover {
background-color: var(--accent-50);
}
/* Text-Links (Rostrot, zentral steuerbar) Klasse für Inline-Links */
.link-accent {
color: var(--accent-700);
text-decoration: underline;
text-underline-offset: 2px;
}
.link-accent:hover {
color: var(--accent-800);
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}
body {
background: var(--background);
color: var(--foreground);
font-family: var(--font-sans);
}
a {
color: var(--accent-700);
text-decoration: underline;
text-underline-offset: 2px;
}
a:hover {
color: var(--accent-800);
}
/* Lesbare Eingabefelder: dunkler Text, heller Hintergrund */
input:not([type="checkbox"]):not([type="radio"]),
textarea,
select {
color: #111827; /* gray-900 */
background-color: #ffffff;
}

View File

@@ -1,14 +1,12 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import type { Metadata, Viewport } from "next";
import { Geist_Mono } from "next/font/google";
import { NextIntlClientProvider } from "next-intl";
import { getLocale, getMessages } from "next-intl/server";
import { Providers } from "./providers";
import { Sidebar } from "@/components/Sidebar";
import { AppShell } from "@/components/AppShell";
import { Toaster } from "sonner";
import "./globals.css";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
@@ -19,22 +17,29 @@ export const metadata: Metadata = {
description: "RustyCMS admin interface",
};
export default function RootLayout({
export const viewport: Viewport = {
width: "device-width",
initialScale: 1,
viewportFit: "cover",
};
export default async function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
const locale = await getLocale();
const messages = await getMessages();
return (
<html lang="en">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
<Providers>
<div className="flex h-screen overflow-hidden bg-white">
<Sidebar />
<main className="min-h-0 flex-1 overflow-auto p-6">{children}</main>
</div>
</Providers>
<html lang={locale}>
<body className={`${geistMono.variable} font-sans antialiased`}>
<NextIntlClientProvider messages={messages}>
<Providers>
<AppShell locale={locale}>{children}</AppShell>
<Toaster richColors position="top-right" />
</Providers>
</NextIntlClientProvider>
</body>
</html>
);

View File

@@ -1,7 +1,9 @@
import Link from "next/link";
import { getTranslations } from "next-intl/server";
import { fetchCollections } from "@/lib/api";
export default async function DashboardPage() {
const t = await getTranslations("Dashboard");
let collections: { name: string }[] = [];
try {
const res = await fetchCollections();
@@ -12,16 +14,16 @@ export default async function DashboardPage() {
return (
<div>
<h1 className="mb-6 text-2xl font-semibold text-gray-900">Dashboard</h1>
<h1 className="mb-6 text-2xl font-semibold text-gray-900">{t("title")}</h1>
<p className="mb-6 text-gray-600">
Choose a collection to manage content.
{t("subtitle")}
</p>
<ul className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{collections.map((c) => (
<li key={c.name}>
<Link
href={`/content/${c.name}`}
className="block rounded-lg border border-gray-200 bg-gray-50 px-4 py-3 font-medium text-gray-900 hover:border-gray-300 hover:bg-gray-100"
className="block min-h-[48px] rounded-lg border border-accent-200 bg-accent-50/50 px-4 py-3 font-medium text-gray-900 hover:border-accent-300 hover:bg-accent-100/80 active:bg-accent-200/60 [touch-action:manipulation]"
>
{c.name}
</Link>
@@ -30,12 +32,9 @@ export default async function DashboardPage() {
</ul>
{collections.length === 0 && (
<p className="text-gray-500">
No collections loaded. Check that the RustyCMS API is running at{" "}
<code className="rounded bg-gray-100 px-1">
{process.env.NEXT_PUBLIC_RUSTYCMS_API_URL ??
"http://127.0.0.1:3000"}
</code>
.
{t("noCollections", {
url: process.env.NEXT_PUBLIC_RUSTYCMS_API_URL ?? "http://127.0.0.1:3000",
})}
</p>
)}
</div>

View File

@@ -0,0 +1,52 @@
"use client";
import { useState } from "react";
import { Sidebar } from "@/components/Sidebar";
import { ErrorBoundary } from "@/components/ErrorBoundary";
type AppShellProps = {
locale: string;
children: React.ReactNode;
};
export function AppShell({ locale, children }: AppShellProps) {
const [sidebarOpen, setSidebarOpen] = useState(false);
return (
<div className="flex h-screen overflow-hidden bg-white">
{/* Mobile backdrop */}
{sidebarOpen && (
<button
type="button"
onClick={() => setSidebarOpen(false)}
className="fixed inset-0 z-30 bg-black/50 md:hidden"
aria-label="Close menu"
/>
)}
<Sidebar
locale={locale}
mobileOpen={sidebarOpen}
onClose={() => setSidebarOpen(false)}
/>
<div className="flex min-w-0 flex-1 flex-col">
{/* Mobile menu button */}
<header className="flex shrink-0 items-center gap-3 border-b border-gray-200 bg-white px-4 py-3 md:hidden">
<button
type="button"
onClick={() => setSidebarOpen(true)}
className="inline-flex size-11 items-center justify-center rounded-lg border border-gray-200 bg-gray-50 text-gray-700 hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-accent-300"
aria-label="Open menu"
>
<svg className="size-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden>
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
</svg>
</button>
<span className="text-sm font-semibold text-gray-900 truncate">RustyCMS Admin</span>
</header>
<main className="min-h-0 flex-1 overflow-auto p-4 sm:p-5 md:p-6">
<ErrorBoundary>{children}</ErrorBoundary>
</main>
</div>
</div>
);
}

View File

@@ -0,0 +1,18 @@
"use client";
import { useRouter } from "next/navigation";
import { Icon } from "@iconify/react";
export function BackButton({ label = "Back" }: { label?: string }) {
const router = useRouter();
return (
<button
type="button"
onClick={() => router.back()}
className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"
>
<Icon icon="mdi:arrow-left" className="size-4" aria-hidden />
{label}
</button>
);
}

View File

@@ -0,0 +1,44 @@
"use client";
import Link from "next/link";
import { useTranslations } from "next-intl";
export type BreadcrumbItem = { label: string; href?: string };
type Props = { items: BreadcrumbItem[] };
export function Breadcrumbs({ items }: Props) {
if (items.length === 0) return null;
const t = useTranslations("Breadcrumbs");
return (
<nav aria-label={t("ariaLabel")} className="mb-4 text-sm text-gray-600">
<ol className="flex flex-wrap items-center gap-1">
{items.map((item, i) => {
const isLast = i === items.length - 1;
return (
<li key={i} className="flex items-center gap-1">
{i > 0 && (
<span className="text-gray-400" aria-hidden>
/
</span>
)}
{item.href != null && !isLast ? (
<Link
href={item.href}
className="text-gray-600 underline decoration-gray-300 underline-offset-2 hover:text-gray-900 hover:decoration-gray-500"
>
{item.label}
</Link>
) : (
<span className={isLast ? "font-medium text-gray-900" : undefined}>
{item.label}
</span>
)}
</li>
);
})}
</ol>
</nav>
);
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,61 @@
"use client";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useTranslations } from "next-intl";
import { useCallback } from "react";
type Props = {
locales: string[];
defaultLocale: string | null;
currentLocale: string | undefined;
};
export function ContentLocaleSwitcher({ locales, defaultLocale, currentLocale }: Props) {
const t = useTranslations("ContentLocaleSwitcher");
const pathname = usePathname();
const searchParams = useSearchParams();
const router = useRouter();
const switchLocale = useCallback(
(locale: string) => {
const params = new URLSearchParams(searchParams.toString());
// Remove pagination on locale switch
params.delete("_page");
if (locale === defaultLocale) {
params.delete("_locale");
} else {
params.set("_locale", locale);
}
const qs = params.toString();
router.push(`${pathname}${qs ? `?${qs}` : ""}`);
},
[pathname, searchParams, router, defaultLocale]
);
if (locales.length <= 1) return null;
const active = currentLocale ?? defaultLocale ?? locales[0];
return (
<div className="flex items-center gap-2">
<span className="text-xs font-medium text-gray-500 uppercase tracking-wide">
{t("label")}:
</span>
<div className="flex gap-1">
{locales.map((locale) => (
<button
key={locale}
onClick={() => switchLocale(locale)}
className={`rounded px-2 py-0.5 text-xs font-semibold uppercase transition-colors ${
locale === active
? "bg-accent-700 text-white hover:bg-accent-800"
: "bg-gray-100 text-gray-600 hover:bg-gray-200"
}`}
>
{locale}
</button>
))}
</div>
</div>
);
}

View File

@@ -0,0 +1,69 @@
"use client";
import { useState } from "react";
import { Icon } from "@iconify/react";
import { useQuery } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { fetchEntry } from "@/lib/api";
import { Button } from "@/components/ui/button";
type Props = {
collection: string;
slug: string;
locale?: string;
className?: string;
};
export function DataPreviewPanel({
collection,
slug,
locale,
className = "",
}: Props) {
const t = useTranslations("DataPreviewPanel");
const [open, setOpen] = useState(false);
const { data, isLoading, error, isFetching } = useQuery({
queryKey: ["entry-preview", collection, slug, locale ?? ""],
queryFn: () =>
fetchEntry(collection, slug, {
_resolve: "all",
...(locale ? { _locale: locale } : {}),
}),
enabled: open,
});
const json = data != null ? JSON.stringify(data, null, 2) : "";
return (
<div className={className}>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => setOpen((v) => !v)}
aria-expanded={open}
>
<Icon icon="mdi:code-json" className="size-4 text-gray-500" aria-hidden />
{open ? t("hide") : t("show")}
</Button>
{open && (
<div className="mt-3 overflow-hidden rounded-lg border border-gray-200 bg-gray-50">
<div className="max-h-[60vh] overflow-auto p-4">
{isLoading || isFetching ? (
<p className="text-sm text-gray-500">{t("loading")}</p>
) : error ? (
<p className="text-sm text-red-600">
{error instanceof Error ? error.message : t("errorLoading")}
</p>
) : (
<pre className="whitespace-pre-wrap break-words font-mono text-xs text-gray-800">
{json}
</pre>
)}
</div>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,52 @@
"use client";
import { Component, type ReactNode } from "react";
import { Icon } from "@iconify/react";
import { useTranslations } from "next-intl";
type Props = { children: ReactNode };
type State = { hasError: boolean; error: Error | null };
export class ErrorBoundary extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error: Error): State {
return { hasError: true, error };
}
render() {
if (this.state.hasError && this.state.error) {
return <ErrorFallback error={this.state.error} />;
}
return this.props.children;
}
}
function ErrorFallback({ error }: { error: Error }) {
const t = useTranslations("ErrorBoundary");
return (
<div className="rounded-lg border border-red-200 bg-red-50 p-6" role="alert">
<div className="flex items-start gap-3">
<span className="flex size-10 shrink-0 items-center justify-center rounded-full bg-red-200 text-red-700">
<Icon icon="mdi:alert-circle" className="size-6" aria-hidden />
</span>
<div className="min-w-0 flex-1">
<h2 className="font-semibold text-red-900">{t("title")}</h2>
<p className="mt-1 text-sm text-red-800">{error.message}</p>
<button
type="button"
onClick={() => window.location.reload()}
className="mt-4 rounded-md bg-red-700 px-3 py-1.5 text-sm font-medium text-white hover:bg-red-800 focus:outline-none focus:ring-2 focus:ring-red-500"
>
{t("reload")}
</button>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,38 @@
"use client";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
export function LocaleSwitcher({ locale }: { locale: string }) {
const router = useRouter();
const t = useTranslations("LocaleSwitcher");
const set = (l: string) => {
// eslint-disable-next-line react-hooks/immutability
document.cookie = `locale=${l}; path=/; max-age=31536000`;
router.refresh();
};
return (
<div className="mt-auto shrink-0 border-t border-accent-200/50 px-4 py-3">
<p className="mb-1.5 text-xs font-medium text-gray-500">{t("label")}</p>
<div className="flex gap-1">
{(["en", "de"] as const).map((l) => (
<button
key={l}
type="button"
onClick={() => set(l)}
className={`rounded px-2.5 py-1 text-xs font-medium transition-colors ${
locale === l
? "bg-accent-200/70 text-gray-900"
: "text-gray-600 hover:bg-accent-100/80 hover:text-gray-900"
}`}
aria-pressed={locale === l}
>
{l.toUpperCase()}
</button>
))}
</div>
</div>
);
}

View File

@@ -2,6 +2,7 @@
import { useId, useRef } from "react";
import ReactMarkdown from "react-markdown";
import { useTranslations } from "next-intl";
type Props = {
value: string;
@@ -52,6 +53,7 @@ export function MarkdownEditor({
readOnly,
rows = 12,
}: Props) {
const t = useTranslations("MarkdownEditor");
const id = useId();
const previewId = `${id}-preview`;
const textareaRef = useRef<HTMLTextAreaElement>(null);
@@ -96,7 +98,7 @@ export function MarkdownEditor({
type="button"
onClick={() => handleToolbar("**", "**", "bold")}
className="rounded px-2 py-1 text-sm font-bold text-gray-700 hover:bg-gray-200"
title="Bold"
title={t("bold")}
>
B
</button>
@@ -104,7 +106,7 @@ export function MarkdownEditor({
type="button"
onClick={() => handleToolbar("*", "*", "italic")}
className="rounded px-2 py-1 text-sm italic text-gray-700 hover:bg-gray-200"
title="Italic"
title={t("italic")}
>
I
</button>
@@ -112,7 +114,7 @@ export function MarkdownEditor({
type="button"
onClick={() => handleToolbar("`", "`", "code")}
className="rounded px-2 py-1 font-mono text-sm text-gray-700 hover:bg-gray-200"
title="Code"
title={t("code")}
>
&lt;/&gt;
</button>
@@ -120,17 +122,17 @@ export function MarkdownEditor({
type="button"
onClick={() => handleInsert("[Link-Text](url)", 10)}
className="rounded px-2 py-1 text-sm text-gray-700 hover:bg-gray-200"
title="Link"
title={t("link")}
>
Link
{t("link")}
</button>
<button
type="button"
onClick={() => handleInsert("\n- ", 3)}
className="rounded px-2 py-1 text-sm text-gray-700 hover:bg-gray-200"
title="Bullet list"
title={t("bulletList")}
>
List
{t("bulletListButton")}
</button>
</div>
)}
@@ -143,7 +145,7 @@ export function MarkdownEditor({
readOnly={readOnly}
required={required}
aria-describedby={previewId}
placeholder="Enter markdown… **bold**, *italic*, [link](url), - list"
placeholder={t("placeholder")}
className="block w-full rounded border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 font-mono focus:border-gray-400 focus:outline-none focus:ring-1 focus:ring-gray-400"
/>
{error ? (
@@ -153,16 +155,16 @@ export function MarkdownEditor({
) : null}
<div className="mt-3">
<span className="mb-1 block text-xs font-medium text-gray-500">
Preview
{t("preview")}
</span>
<div
id={previewId}
className="min-h-[120px] rounded border border-gray-200 bg-gray-50 px-3 py-2 text-sm text-gray-800 [&_ul]:list-inside [&_ul]:list-disc [&_ol]:list-inside [&_ol]:list-decimal [&_pre]:overflow-x-auto [&_pre]:rounded [&_pre]:bg-gray-200 [&_pre]:p-2 [&_code]:rounded [&_code]:bg-gray-200 [&_code]:px-1 [&_pre_code]:bg-transparent [&_pre_code]:p-0 [&_h1]:text-lg [&_h1]:font-bold [&_h2]:text-base [&_h2]:font-bold [&_h3]:text-sm [&_h3]:font-bold [&_a]:text-blue-600 [&_a]:underline"
className="min-h-[120px] rounded border border-gray-200 bg-gray-50 px-3 py-2 text-sm text-gray-800 [&_ul]:list-inside [&_ul]:list-disc [&_ol]:list-inside [&_ol]:list-decimal [&_pre]:overflow-x-auto [&_pre]:rounded [&_pre]:bg-gray-200 [&_pre]:p-2 [&_code]:rounded [&_code]:bg-gray-200 [&_code]:px-1 [&_pre_code]:bg-transparent [&_pre_code]:p-0 [&_h1]:text-lg [&_h1]:font-bold [&_h2]:text-base [&_h2]:font-bold [&_h3]:text-sm [&_h3]:font-bold [&_a]:text-accent-700 [&_a]:underline [&_a:hover]:text-accent-800"
>
{(value ?? "").trim() ? (
<ReactMarkdown>{value}</ReactMarkdown>
) : (
<span className="text-gray-400">Empty preview appears as you type.</span>
<span className="text-gray-400">{t("emptyPreview")}</span>
)}
</div>
</div>

View File

@@ -0,0 +1,68 @@
"use client";
import Link from "next/link";
import { Icon } from "@iconify/react";
import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
type Props = {
collection: string;
page: number;
totalPages: number;
total: number;
locale?: string;
sort?: string;
order?: string;
q?: string;
};
export function PaginationLinks({
collection,
page,
totalPages,
total,
locale,
sort,
order,
q,
}: Props) {
const t = useTranslations("PaginationLinks");
const base = `/content/${collection}`;
const localeQ = locale ? `&_locale=${locale}` : "";
const sortQ = sort ? `&_sort=${sort}&_order=${order ?? "asc"}` : "";
const searchQ = q ? `&_q=${encodeURIComponent(q)}` : "";
return (
<div className="mt-6 flex flex-wrap items-center gap-3 sm:gap-4">
{page > 1 ? (
<Button variant="outline" asChild className="min-h-[44px] sm:min-h-0">
<Link href={`${base}?_page=${page - 1}${localeQ}${sortQ}${searchQ}`}>
<Icon icon="mdi:chevron-left" className="size-5" aria-hidden />
{t("back")}
</Link>
</Button>
) : (
<Button variant="outline" disabled className="min-h-[44px] sm:min-h-0">
<Icon icon="mdi:chevron-left" className="size-5" aria-hidden />
{t("back")}
</Button>
)}
<span className="text-sm text-gray-600 shrink-0">
{t("pageInfo", { page, totalPages, total })}
</span>
{page < totalPages ? (
<Button variant="outline" asChild className="min-h-[44px] sm:min-h-0">
<Link href={`${base}?_page=${page + 1}${localeQ}${sortQ}${searchQ}`}>
{t("next")}
<Icon icon="mdi:chevron-right" className="size-5" aria-hidden />
</Link>
</Button>
) : (
<Button variant="outline" disabled className="min-h-[44px] sm:min-h-0">
{t("next")}
<Icon icon="mdi:chevron-right" className="size-5" aria-hidden />
</Button>
)}
</div>
);
}

View File

@@ -3,8 +3,22 @@
import { useState } from "react";
import Link from "next/link";
import { useQuery } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { fetchContentList, fetchCollections } from "@/lib/api";
import type { FieldDefinition } from "@/lib/api";
import { getOptionLabel } from "@/lib/referenceOptionLabel";
import {
SearchableSelect,
type SearchableSelectOption,
} from "./SearchableSelect";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Button } from "@/components/ui/button";
type Props = {
name: string;
@@ -37,19 +51,35 @@ export function ReferenceArrayField({
locale,
label,
}: Props) {
const t = useTranslations("ReferenceArrayField");
const schemaCollections = getCollections(def);
const singleCollection =
schemaCollections.length === 1 ? schemaCollections[0] : null;
const multipleCollections =
schemaCollections.length > 1 ? schemaCollections : [];
const valueList: string[] = Array.isArray(value)
? value
: typeof value === "string"
? value
.split(/[\n,]+/)
.map((s) => s.trim())
.filter(Boolean)
: [];
/** Normalise to string[]: API may return resolved refs as objects with _slug. */
function toSlugList(raw: unknown): string[] {
if (Array.isArray(raw)) {
return raw
.map((v) =>
typeof v === "object" && v !== null && "_slug" in v
? String((v as { _slug?: string })._slug ?? "")
: typeof v === "string"
? v.trim()
: "",
)
.filter(Boolean);
}
if (typeof raw === "string") {
return raw
.split(/[\n,]+/)
.map((s) => s.trim())
.filter(Boolean);
}
return [];
}
const valueList: string[] = toSlugList(value);
const [pickedCollection, setPickedCollection] = useState<string>(
singleCollection ?? multipleCollections[0] ?? "",
@@ -130,6 +160,24 @@ export function ReferenceArrayField({
add(slug);
};
/** Options for the "add existing" SearchableSelect: full label, exclude already selected. */
const addSelectOptions: SearchableSelectOption[] =
multipleCollections.length > 1 && multiQueries.data
? multiQueries.data.flatMap(({ collection: coll, items: list }) =>
(list as Record<string, unknown>[])
.filter((i) => !valueList.includes(String(i._slug ?? "")))
.map((i) => ({
value: `${coll}:${i._slug ?? ""}`,
label: getOptionLabel(i),
}))
)
: ((singleQuery.data?.items ?? []) as Record<string, unknown>[])
.filter((i) => !valueList.includes(String(i._slug ?? "")))
.map((i) => ({
value: String(i._slug ?? ""),
label: getOptionLabel(i),
}));
const remove = (index: number) => {
onChange(valueList.filter((_, i) => i !== index));
};
@@ -153,33 +201,47 @@ export function ReferenceArrayField({
return (
<div>
<div className="mb-1 flex items-center justify-between">
<span className="text-sm font-medium text-gray-700">{label}</span>
<div className="mb-1">
{label}
{schemaCollections.length > 0 ? (
<span className="text-xs text-gray-500">
<p className="mt-0.5 text-xs text-gray-500">
{schemaCollections.length === 1
? `Typ: ${schemaCollections[0]}`
: `Typen: ${schemaCollections.join(", ")}`}
</span>
? t("typeLabel", { collection: schemaCollections[0] })
: t("typesLabel", { collections: schemaCollections.join(", ") })}
</p>
) : null}
</div>
{/* Selected entries */}
<ul className="mb-2 space-y-1.5">
{valueList.map((slug, index) => (
{valueList.map((slug, index) => {
const collForSlug =
options.find((o) => o.slug === slug)?.collection ??
effectiveCollection ??
null;
return (
<li
key={`${slug}-${index}`}
className="flex items-center gap-2 rounded border border-gray-200 bg-gray-50 px-3 py-2 text-sm"
>
<span className="flex-1 font-mono text-gray-900">{slug}</span>
<div className="flex items-center gap-1">
{collForSlug && (
<Link
href={`/content/${collForSlug}/${encodeURIComponent(slug)}${locale ? `?_locale=${locale}` : ""}`}
className="rounded p-1 text-accent-700 hover:bg-accent-50 hover:text-accent-900"
title="Open entry"
>
</Link>
)}
<button
type="button"
onClick={() => move(index, -1)}
disabled={index === 0}
className="rounded p-1 text-gray-500 hover:bg-gray-200 hover:text-gray-700 disabled:opacity-40"
title="Move up"
aria-label="Move up"
title={t("moveUp")}
aria-label={t("moveUp")}
>
<svg
className="h-4 w-4"
@@ -200,8 +262,8 @@ export function ReferenceArrayField({
onClick={() => move(index, 1)}
disabled={index === valueList.length - 1}
className="rounded p-1 text-gray-500 hover:bg-gray-200 hover:text-gray-700 disabled:opacity-40"
title="Move down"
aria-label="Move down"
title={t("moveDown")}
aria-label={t("moveDown")}
>
<svg
className="h-4 w-4"
@@ -221,8 +283,8 @@ export function ReferenceArrayField({
type="button"
onClick={() => remove(index)}
className="rounded p-1 text-red-600 hover:bg-red-50 hover:text-red-700"
title="Remove"
aria-label="Remove"
title={t("remove")}
aria-label={t("remove")}
>
<svg
className="h-4 w-4"
@@ -240,7 +302,8 @@ export function ReferenceArrayField({
</button>
</div>
</li>
))}
);
})}
</ul>
{/* Without schema collection: choose component type first */}
@@ -249,93 +312,75 @@ export function ReferenceArrayField({
availableCollections.length > 0 ? (
<div className="mb-2">
<label className="mb-1 block text-xs font-medium text-gray-500">
Component type
{t("componentType")}
</label>
<select
value={pickedCollection}
onChange={(e) => setPickedCollection(e.target.value)}
className="block w-full rounded border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900"
>
<option value=""> Select type </option>
{availableCollections.map((c) => (
<option key={c} value={c}>
{c}
</option>
))}
</select>
<Select value={pickedCollection} onValueChange={setPickedCollection}>
<SelectTrigger className="w-full">
<SelectValue placeholder={t("selectType")} />
</SelectTrigger>
<SelectContent>
{availableCollections.map((c) => (
<SelectItem key={c} value={c}>{c}</SelectItem>
))}
</SelectContent>
</Select>
</div>
) : null}
{/* Add: select from existing + create new component */}
{effectiveCollection || multipleCollections.length > 1 ? (
<div className="flex flex-col gap-2 sm:flex-row sm:items-start">
<select
value=""
onChange={(e) => {
const v = e.target.value;
if (v) addFromOption(v);
e.target.value = "";
}}
className="block flex-1 rounded border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900"
disabled={isLoading}
>
<option value=""> Select from existing </option>
{options.map((item) => {
const key =
multipleCollections.length > 1
? `${item.collection}:${item.slug}`
: item.slug;
const alreadySelected = valueList.includes(item.slug);
const label =
multipleCollections.length > 1
? `${item.slug} (${item.collection})`
: item.slug;
return (
<option key={key} value={key} disabled={alreadySelected}>
{alreadySelected ? `${label} (already selected)` : label}
</option>
);
})}
</select>
<div className="min-w-0 flex-1">
<SearchableSelect
value=""
onChange={(v) => v && addFromOption(v)}
options={addSelectOptions}
placeholder={t("selectFromExisting")}
clearable={false}
filterPlaceholder={t("filterPlaceholder")}
emptyLabel={t("emptyLabel")}
disabled={isLoading}
ariaLabel={t("selectExistingAriaLabel")}
/>
</div>
{collectionsForNew.length > 0 ? (
<span className="flex shrink-0 flex-col gap-0.5">
{collectionsForNew.length === 1 ? (
<Link
href={
collectionsForNew[0]
? `/content/${collectionsForNew[0]}/new${locale ? `?_locale=${locale}` : ""}`
: "#"
}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center justify-center gap-1 rounded border border-gray-300 bg-white px-3 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50"
>
<span aria-hidden>+</span> New {collectionsForNew[0]} component
</Link>
<Button variant="outline" size="sm" asChild>
<Link
href={
collectionsForNew[0]
? `/content/${collectionsForNew[0]}/new${locale ? `?_locale=${locale}` : ""}`
: "#"
}
target="_blank"
rel="noopener noreferrer"
>
{t("newComponent", { collection: collectionsForNew[0] })}
</Link>
</Button>
) : (
<select
className="rounded border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900"
<Select
value=""
onChange={(e) => {
const c = e.target.value;
if (c)
window.open(
`/content/${c}/new${locale ? `?_locale=${locale}` : ""}`,
"_blank",
);
e.target.value = "";
onValueChange={(c) => {
if (c) window.open(
`/content/${c}/new${locale ? `?_locale=${locale}` : ""}`,
"_blank",
);
}}
>
<option value="">+ Create new component</option>
{collectionsForNew.map((c) => (
<option key={c} value={c}>
{c}
</option>
))}
</select>
<SelectTrigger className="w-full">
<SelectValue placeholder={t("createNewComponent")} />
</SelectTrigger>
<SelectContent>
{collectionsForNew.map((c) => (
<SelectItem key={c} value={c}>{c}</SelectItem>
))}
</SelectContent>
</Select>
)}
<span className="text-xs text-gray-500">
Open in new tab; then reload this page.
{t("openInNewTab")}
</span>
</span>
) : null}
@@ -344,10 +389,10 @@ export function ReferenceArrayField({
{schemaCollections.length === 0 && availableCollections.length === 0 ? (
<p className="text-xs text-amber-600">
No reference collection in schema. Set{" "}
<code className="rounded bg-gray-100 px-1">items.collection</code> or{" "}
<code className="rounded bg-gray-100 px-1">items.collections</code>{" "}
in the type, or start the API and reload the page.
{t("noCollection", {
collectionCode: "items.collection",
collectionsCode: "items.collections",
})}
</p>
) : null}

View File

@@ -0,0 +1,240 @@
"use client";
import { useState } from "react";
import Link from "next/link";
import { useQuery } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { fetchContentList, fetchCollections } from "@/lib/api";
import type { FieldDefinition } from "@/lib/api";
import { getOptionLabel } from "@/lib/referenceOptionLabel";
import { SearchableSelect } from "./SearchableSelect";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Button } from "@/components/ui/button";
type Props = {
name: string;
def: FieldDefinition;
value: string;
onChange: (value: string) => void;
required?: boolean;
error?: unknown;
locale?: string;
label: React.ReactNode;
readOnly?: boolean;
};
/** Target collection(s) from schema: single collection or list for polymorphic. */
function getCollections(def: FieldDefinition): string[] {
if (def.collection) return [def.collection];
if (Array.isArray(def.collections) && def.collections.length > 0)
return def.collections;
return [];
}
export function ReferenceField({
name,
def,
value,
onChange,
required,
error,
locale,
label,
readOnly = false,
}: Props) {
const t = useTranslations("ReferenceField");
const schemaCollections = getCollections(def);
const singleCollection =
schemaCollections.length === 1 ? schemaCollections[0] : null;
const multipleCollections =
schemaCollections.length > 1 ? schemaCollections : [];
const [pickedCollection, setPickedCollection] = useState<string>(
singleCollection ?? multipleCollections[0] ?? "",
);
const { data: collectionsData } = useQuery({
queryKey: ["collections"],
queryFn: fetchCollections,
enabled: schemaCollections.length === 0,
});
const availableCollections =
schemaCollections.length > 0
? schemaCollections
: (collectionsData?.collections ?? [])
.map((c) => c.name)
.filter(
(n) =>
n !== "content_layout" && n !== "component_layout" && n !== "seo",
);
const effectiveCollection = singleCollection ?? pickedCollection;
const listParams = { _per_page: 200, ...(locale ? { _locale: locale } : {}) };
const singleQuery = useQuery({
queryKey: ["content", effectiveCollection, listParams],
queryFn: () => fetchContentList(effectiveCollection!, listParams),
enabled: !!effectiveCollection && schemaCollections.length <= 1,
});
const multiQueries = useQuery({
queryKey: ["content-multi", multipleCollections, listParams],
queryFn: async () => {
const results = await Promise.all(
multipleCollections.map((coll) => fetchContentList(coll, listParams)),
);
return multipleCollections.map((coll, i) => ({
collection: coll,
items: results[i]?.items ?? [],
}));
},
enabled: multipleCollections.length > 1,
});
type OptionItem = { slug: string; collection: string; label: string };
const options: OptionItem[] =
multipleCollections.length > 1 && multiQueries.data
? multiQueries.data.flatMap(({ collection: coll, items }) =>
(items as Record<string, unknown>[])
.map((o) => ({
slug: String(o._slug ?? ""),
collection: coll,
label:
multipleCollections.length > 1
? `${o._slug} (${coll})`
: getOptionLabel(o),
}))
.filter((o) => o.slug),
)
: ((singleQuery.data?.items ?? []) as Record<string, unknown>[])
.map((o) => ({
slug: String(o._slug ?? ""),
collection: effectiveCollection ?? "",
label: getOptionLabel(o),
}))
.filter((o) => o.slug);
const isLoading =
schemaCollections.length <= 1
? singleQuery.isLoading
: multiQueries.isLoading;
/** Stored value: for single collection only slug, for multi "collection:slug". */
const currentValue = typeof value === "string" ? value.trim() : "";
const selectOptions = options.map((o) => ({
value:
multipleCollections.length > 1
? `${o.collection}:${o.slug}`
: o.slug,
label: o.label,
}));
if (readOnly) {
return (
<div>
{label}
<div className="block w-full rounded border border-gray-200 bg-gray-50 px-3 py-2 text-sm font-mono text-gray-700">
{currentValue || "—"}
</div>
{error ? (
<p className="mt-1 text-sm text-red-600">
{String((error as { message?: string })?.message ?? error)}
</p>
) : null}
</div>
);
}
return (
<div>
<div className="mb-1 flex items-center justify-between">
<span className="text-sm font-medium text-gray-700">{label}</span>
{schemaCollections.length > 0 ? (
<span className="text-xs text-gray-500">
{schemaCollections.length === 1
? t("typeLabel", { collection: schemaCollections[0] })
: t("typesLabel", { collections: schemaCollections.join(", ") })}
</span>
) : null}
</div>
{/* Without schema collection: choose type first */}
{!singleCollection &&
schemaCollections.length === 0 &&
availableCollections.length > 0 ? (
<div className="mb-2">
<Select value={pickedCollection} onValueChange={setPickedCollection}>
<SelectTrigger className="w-full">
<SelectValue placeholder={t("selectType")} />
</SelectTrigger>
<SelectContent>
{availableCollections.map((c) => (
<SelectItem key={c} value={c}>{c}</SelectItem>
))}
</SelectContent>
</Select>
</div>
) : null}
<div className="flex flex-col gap-2 sm:flex-row sm:items-start">
<div className="min-w-0 flex-1">
<SearchableSelect
name={name}
value={currentValue}
onChange={onChange}
options={selectOptions}
clearable
disabled={isLoading}
ariaLabel={typeof label === "string" ? label : t("newEntry")}
/>
</div>
<div className="flex shrink-0 gap-1">
{currentValue && effectiveCollection && (
<Button variant="outline" size="sm" asChild>
<Link
href={`/content/${effectiveCollection}/${encodeURIComponent(currentValue.includes(":") ? currentValue.split(":")[1] : currentValue)}${locale ? `?_locale=${locale}` : ""}`}
>
<span aria-hidden></span>
</Link>
</Button>
)}
{effectiveCollection ? (
<Button variant="outline" size="sm" asChild className="shrink-0">
<Link
href={`/content/${effectiveCollection}/new${locale ? `?_locale=${locale}` : ""}`}
target="_blank"
rel="noopener noreferrer"
>
<span aria-hidden>+</span> {t("newEntry")}
</Link>
</Button>
) : null}
</div>
</div>
{schemaCollections.length === 0 && availableCollections.length === 0 ? (
<p className="mt-1 text-xs text-amber-600">
{t("noCollection", {
collectionCode: "collection",
collectionsCode: "collections",
})}
</p>
) : null}
{error ? (
<p className="mt-1 text-sm text-red-600">
{String((error as { message?: string })?.message ?? error)}
</p>
) : null}
</div>
);
}

View File

@@ -0,0 +1,171 @@
"use client";
import { useMemo } from "react";
import { useTranslations } from "next-intl";
import type { FieldDefinition } from "@/lib/api";
import { ReferenceField } from "./ReferenceField";
type Props = {
name: string;
def: FieldDefinition;
value: string | Record<string, unknown>;
onChange: (value: string | Record<string, unknown>) => void;
required?: boolean;
error?: unknown;
locale?: string;
label: React.ReactNode;
readOnly?: boolean;
};
/** Synthetic def for reference-only mode (ReferenceField expects type "reference"). */
function refDef(def: FieldDefinition): FieldDefinition {
return {
...def,
type: "reference",
};
}
/**
* ReferenceOrInline: either a reference (slug) to an entry in def.collection,
* or an inline object matching the schema from def.fields (resolved by API).
*/
export function ReferenceOrInlineField({
name,
def,
value,
onChange,
required,
error,
locale,
label,
readOnly = false,
}: Props) {
const t = useTranslations("ReferenceOrInlineField");
// API may return a resolved reference as {_slug, _type, ...} — treat as reference.
const normalizedValue = useMemo<string | Record<string, unknown>>(() => {
if (
value != null &&
typeof value === "object" &&
!Array.isArray(value) &&
"_slug" in (value as Record<string, unknown>)
) {
return String((value as Record<string, unknown>)._slug ?? "");
}
return value as string | Record<string, unknown>;
}, [value]);
const isReference = typeof normalizedValue === "string";
const inlineFields = (def.fields as Record<string, FieldDefinition> | undefined) ?? {};
const inlineValue = useMemo(
() =>
normalizedValue != null && typeof normalizedValue === "object" && !Array.isArray(normalizedValue)
? (normalizedValue as Record<string, unknown>)
: {},
[normalizedValue],
);
if (readOnly) {
return (
<div>
{label}
<div className="block w-full rounded border border-gray-200 bg-gray-50 px-3 py-2 text-sm font-mono text-gray-700">
{isReference ? normalizedValue || "—" : "(inline object)"}
</div>
{error ? (
<p className="mt-1 text-sm text-red-600">
{String((error as { message?: string })?.message ?? error)}
</p>
) : null}
</div>
);
}
return (
<div className="space-y-3">
<div className="mb-1 flex items-center justify-between">
<span className="text-sm font-medium text-gray-700">{label}</span>
</div>
{/* Mode switch: Reference | Inline */}
<div className="flex gap-4 border-b border-gray-200 pb-2">
<label className="flex cursor-pointer items-center gap-2">
<input
type="radio"
name={`${name}-mode`}
checked={isReference}
onChange={() => onChange("")}
className="h-4 w-4 border-gray-300 text-accent-600 focus:ring-accent-500"
/>
<span className="text-sm text-gray-700">{t("reference")}</span>
</label>
<label className="flex cursor-pointer items-center gap-2">
<input
type="radio"
name={`${name}-mode`}
checked={!isReference}
onChange={() => onChange({})}
className="h-4 w-4 border-gray-300 text-accent-600 focus:ring-accent-500"
/>
<span className="text-sm text-gray-700">{t("inline")}</span>
</label>
</div>
{isReference ? (
<ReferenceField
name={name}
def={refDef(def)}
value={normalizedValue as string}
onChange={(v) => onChange(v)}
required={required}
error={error}
locale={locale}
label={null}
/>
) : (
<div className="rounded border border-gray-200 bg-gray-50/50 p-4">
<p className="mb-3 text-xs text-gray-500">{t("inlineObject")}</p>
<div className="space-y-3">
{Object.entries(inlineFields).map(([subName, subDef]) => {
const sub = subDef as FieldDefinition;
const subValue = inlineValue[subName];
const val = subValue != null ? String(subValue) : "";
const isReq = !!sub.required;
return (
<div key={subName}>
<label className="mb-1 block text-xs font-medium text-gray-700">
{subName}
{isReq && <span className="text-red-500"> *</span>}
</label>
<input
type="text"
value={val}
onChange={(e) =>
onChange({
...inlineValue,
[subName]: e.target.value,
})
}
className="block w-full rounded border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900"
placeholder={sub.description ?? subName}
/>
</div>
);
})}
{Object.keys(inlineFields).length === 0 ? (
<p className="text-xs text-amber-600">
{t("noInlineSchema")}
</p>
) : null}
</div>
</div>
)}
{error ? (
<p className="mt-1 text-sm text-red-600">
{String((error as { message?: string })?.message ?? error)}
</p>
) : null}
</div>
);
}

View File

@@ -0,0 +1,31 @@
"use client";
import Link from "next/link";
import { Icon } from "@iconify/react";
import { useTranslations } from "next-intl";
import { SchemaPanel } from "@/components/SchemaPanel";
import type { SchemaDefinition } from "@/lib/api";
import { Button } from "@/components/ui/button";
type Props = {
schema: SchemaDefinition | null;
collection: string;
className?: string;
};
export function SchemaAndEditBar({ schema, collection, className = "" }: Props) {
const t = useTranslations("SchemaAndEditBar");
return (
<div className={`flex flex-wrap items-center gap-2 ${className}`}>
<SchemaPanel schema={schema} />
{schema && (
<Button variant="outline" size="sm" asChild>
<Link href={`/admin/types/${encodeURIComponent(collection)}/edit`}>
<Icon icon="mdi:pencil-outline" className="size-4 text-gray-500" aria-hidden />
{t("editSchema")}
</Link>
</Button>
)}
</div>
);
}

View File

@@ -0,0 +1,115 @@
"use client";
import { useState } from "react";
import Link from "next/link";
import { Icon } from "@iconify/react";
import { useQuery } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { fetchEntry } from "@/lib/api";
import type { SchemaDefinition } from "@/lib/api";
import { Button } from "@/components/ui/button";
type Props = {
schema: SchemaDefinition | null;
collection: string;
slug: string;
locale?: string;
className?: string;
};
const boxClass = "overflow-hidden rounded-lg border border-gray-200 bg-gray-50";
const innerClass = "max-h-[60vh] overflow-auto p-4";
const preClass = "whitespace-pre-wrap break-words font-mono text-xs text-gray-800";
export function SchemaAndPreviewBar({
schema,
collection,
slug,
locale,
className = "",
}: Props) {
const t = useTranslations("SchemaAndPreviewBar");
const [schemaOpen, setSchemaOpen] = useState(false);
const [previewOpen, setPreviewOpen] = useState(false);
const { data: previewData, isLoading, error, isFetching } = useQuery({
queryKey: ["entry-preview", collection, slug, locale ?? ""],
queryFn: () =>
fetchEntry(collection, slug, {
_resolve: "all",
...(locale ? { _locale: locale } : {}),
}),
enabled: previewOpen,
});
const schemaJson = schema ? JSON.stringify(schema, null, 2) : "";
const previewJson = previewData != null ? JSON.stringify(previewData, null, 2) : "";
return (
<div className={className}>
<div className="flex flex-wrap items-center gap-2">
{schema && (
<>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => setSchemaOpen((v) => !v)}
aria-expanded={schemaOpen}
>
<Icon
icon={schemaOpen ? "mdi:eye-off-outline" : "mdi:eye-outline"}
className="size-4 text-gray-500"
aria-hidden
/>
{schemaOpen ? t("hideSchema") : t("showSchema")}
</Button>
<Button variant="outline" size="sm" asChild>
<Link href={`/admin/types/${encodeURIComponent(collection)}/edit`}>
<Icon icon="mdi:pencil-outline" className="size-4 text-gray-500" aria-hidden />
{t("editSchema")}
</Link>
</Button>
</>
)}
<Button
type="button"
variant="outline"
size="sm"
onClick={() => setPreviewOpen((v) => !v)}
aria-expanded={previewOpen}
>
<Icon icon="mdi:code-json" className="size-4 text-gray-500" aria-hidden />
{previewOpen ? t("hidePreview") : t("showPreview")}
</Button>
</div>
{(schemaOpen || previewOpen) && (
<div className="mt-3 flex flex-col gap-3">
{schemaOpen && (
<div className={boxClass}>
<div className={innerClass}>
<pre className={preClass}>{schemaJson}</pre>
</div>
</div>
)}
{previewOpen && (
<div className={boxClass}>
<div className={innerClass}>
{isLoading || isFetching ? (
<p className="text-sm text-gray-500">{t("loading")}</p>
) : error ? (
<p className="text-sm text-red-600">
{error instanceof Error ? error.message : t("errorLoading")}
</p>
) : (
<pre className={preClass}>{previewJson}</pre>
)}
</div>
</div>
)}
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,49 @@
"use client";
import { useState } from "react";
import { Icon } from "@iconify/react";
import { useTranslations } from "next-intl";
import type { SchemaDefinition } from "@/lib/api";
import { Button } from "@/components/ui/button";
type Props = {
schema: SchemaDefinition | null;
className?: string;
};
export function SchemaPanel({ schema, className = "" }: Props) {
const t = useTranslations("SchemaPanel");
const [open, setOpen] = useState(false);
if (!schema) return null;
const json = JSON.stringify(schema, null, 2);
return (
<div className={className}>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => setOpen((v) => !v)}
aria-expanded={open}
>
<Icon
icon={open ? "mdi:eye-off-outline" : "mdi:eye-outline"}
className="size-4 text-gray-500"
aria-hidden
/>
{open ? t("hide") : t("show")}
</Button>
{open && (
<div className="mt-3 overflow-hidden rounded-lg border border-gray-200 bg-gray-50">
<div className="max-h-[60vh] overflow-auto p-4">
<pre className="whitespace-pre-wrap break-words font-mono text-xs text-gray-800">
{json}
</pre>
</div>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,63 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { useRouter, useSearchParams, usePathname } from "next/navigation";
import { Icon } from "@iconify/react";
export function SearchBar({
placeholder = "Search…",
paramName = "_q",
}: {
placeholder?: string;
paramName?: string;
}) {
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
const [value, setValue] = useState(searchParams.get(paramName) ?? "");
// Sync when URL changes externally
useEffect(() => {
setValue(searchParams.get(paramName) ?? "");
}, [searchParams, paramName]);
const push = useCallback(
(q: string) => {
const sp = new URLSearchParams(searchParams.toString());
if (q.trim()) {
sp.set(paramName, q.trim());
} else {
sp.delete(paramName);
}
sp.set("_page", "1");
router.push(`${pathname}?${sp.toString()}`);
},
[router, pathname, searchParams, paramName]
);
// Debounce: push URL 300ms after typing stops
useEffect(() => {
const timer = setTimeout(() => {
const current = searchParams.get(paramName) ?? "";
if (value.trim() !== current) push(value);
}, 300);
return () => clearTimeout(timer);
}, [value]); // eslint-disable-line react-hooks/exhaustive-deps
return (
<div className="relative w-full min-w-0 sm:w-56">
<Icon
icon="mdi:magnify"
className="pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"
aria-hidden
/>
<input
type="search"
value={value}
onChange={(e) => setValue(e.target.value)}
placeholder={placeholder}
className="h-10 w-full min-w-0 rounded-md border border-input bg-background pl-8 pr-3 text-base text-foreground placeholder:text-muted-foreground focus:border-ring focus:outline-none focus:ring-[3px] focus:ring-ring/50 sm:h-9 sm:text-sm [touch-action:manipulation]"
/>
</div>
);
}

View File

@@ -0,0 +1,124 @@
"use client";
import * as React from "react";
import { Check, ChevronsUpDown } from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from "@/components/ui/command";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
export type SearchableSelectOption = {
value: string;
label: string;
};
type Props = {
name?: string;
value: string;
onChange: (value: string) => void;
options: SearchableSelectOption[];
placeholder?: string;
clearLabel?: string;
filterPlaceholder?: string;
emptyLabel?: string;
clearable?: boolean;
disabled?: boolean;
ariaLabel?: string;
listMaxHeight?: string;
className?: string;
};
export function SearchableSelect({
name,
value,
onChange,
options,
placeholder = "— Please select —",
clearLabel = "— Clear selection —",
filterPlaceholder = "Filter…",
emptyLabel = "No matches",
clearable = true,
disabled = false,
ariaLabel,
className = "",
}: Props) {
const [open, setOpen] = React.useState(false);
const selectedOption = options.find((o) => o.value === value);
return (
<div className={cn("relative min-w-0", className)}>
{name && <input type="hidden" name={name} value={value ?? ""} />}
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={open}
aria-label={ariaLabel}
disabled={disabled}
className="w-full justify-between font-normal"
>
<span className="truncate">
{selectedOption ? selectedOption.label : placeholder}
</span>
<ChevronsUpDown className="ml-2 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent
className="w-[var(--radix-popover-trigger-width)] p-0"
align="start"
>
<Command>
<CommandInput placeholder={filterPlaceholder} />
<CommandList>
<CommandEmpty>{emptyLabel}</CommandEmpty>
<CommandGroup>
{clearable && (
<CommandItem
value={clearLabel}
onSelect={() => {
onChange("");
setOpen(false);
}}
className="italic text-muted-foreground"
>
{clearLabel}
</CommandItem>
)}
{options.map((option) => (
<CommandItem
key={option.value}
value={option.label}
onSelect={() => {
onChange(option.value);
setOpen(false);
}}
>
<Check
className={cn(
"mr-2",
value === option.value ? "opacity-100" : "opacity-0"
)}
/>
{option.label}
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
</div>
);
}

View File

@@ -3,10 +3,22 @@
import { useState, useMemo } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { Icon } from "@iconify/react";
import { useQueries, useQuery } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { fetchCollections, fetchContentList } from "@/lib/api";
import { LocaleSwitcher } from "./LocaleSwitcher";
export function Sidebar() {
const navLinkClass = "inline-flex items-center gap-2 rounded-lg px-3 py-2.5 text-sm font-medium min-h-[44px] md:min-h-0 md:py-2";
type SidebarProps = {
locale: string;
mobileOpen?: boolean;
onClose?: () => void;
};
export function Sidebar({ locale, mobileOpen = false, onClose }: SidebarProps) {
const t = useTranslations("Sidebar");
const pathname = usePathname();
const [search, setSearch] = useState("");
const { data, isLoading, error } = useQuery({
@@ -38,88 +50,138 @@ export function Sidebar() {
const formatCount = (n: number) => (n >= 100 ? "99+" : String(n));
const tSidebar = useTranslations("Sidebar");
const isDrawer = typeof onClose === "function";
const asideClass =
"flex h-screen flex-col overflow-hidden border-r border-accent-200/50 bg-gradient-to-b from-violet-50/95 via-accent-50/90 to-amber-50/85 shadow-[2px_0_16px_-2px_rgba(225,29,72,0.06)] " +
(isDrawer
? "fixed left-0 top-0 z-40 w-72 max-w-[85vw] transition-transform duration-200 ease-out md:relative md:z-auto md:w-56 md:shrink-0 md:translate-x-0 " +
(mobileOpen ? "translate-x-0" : "-translate-x-full md:translate-x-0")
: "w-56 shrink-0");
return (
<aside className="flex h-full w-56 shrink-0 flex-col overflow-y-auto border-r border-gray-200 bg-gray-50 p-4">
<nav className="flex flex-col gap-1">
<Link
href="/"
className={`rounded px-3 py-2 text-sm font-bold ${pathname === "/" ? "bg-gray-200 text-gray-900" : "text-gray-600 hover:bg-gray-100 hover:text-gray-900"}`}
>
Dashboard
</Link>
<hr />
<div className="px-1 py-2">
<aside className={asideClass}>
<nav className="flex flex-1 min-h-0 flex-col p-4">
{/* Brand / logo row */}
<div className="flex shrink-0 items-center gap-2 pb-3">
<Link
href="/"
onClick={onClose}
className="flex min-w-0 flex-1 items-center gap-2 rounded-lg py-2 pr-1 text-gray-900 no-underline outline-none focus-visible:ring-2 focus-visible:ring-accent-300"
>
<span className="flex size-9 shrink-0 items-center justify-center rounded-md bg-accent-200/80 text-accent-800">
<Icon icon="mdi:cog-outline" className="size-5" aria-hidden />
</span>
<span className="truncate text-lg font-bold tracking-tight">RustyCMS</span>
</Link>
{isDrawer && (
<button
type="button"
onClick={onClose}
className="inline-flex size-10 shrink-0 items-center justify-center rounded-lg text-gray-600 hover:bg-accent-100/80 hover:text-gray-900 md:hidden"
aria-label={tSidebar("closeMenu")}
>
<Icon icon="mdi:close" className="size-6" aria-hidden />
</button>
)}
</div>
<div className="flex shrink-0 flex-col gap-1">
<Link
href="/"
onClick={onClose}
className={`${navLinkClass} font-bold ${pathname === "/" ? "bg-accent-200/70 text-gray-900" : "text-gray-700 hover:bg-accent-100/80 hover:text-gray-900"}`}
>
<Icon icon="mdi:view-dashboard-outline" className="size-5 shrink-0" aria-hidden />
{t("dashboard")}
</Link>
<Link
href="/admin/types"
onClick={onClose}
className={`${navLinkClass} ${pathname?.startsWith("/admin/types") ? "bg-accent-200/70 text-gray-900" : "text-gray-700 hover:bg-accent-100/80 hover:text-gray-900"}`}
>
<Icon icon="mdi:shape-outline" className="size-5 shrink-0" aria-hidden />
{t("types")}
</Link>
<Link
href="/assets"
onClick={onClose}
className={`${navLinkClass} ${pathname?.startsWith("/assets") ? "bg-accent-200/70 text-gray-900" : "text-gray-700 hover:bg-accent-100/80 hover:text-gray-900"}`}
>
<Icon icon="mdi:image-multiple-outline" className="size-5 shrink-0" aria-hidden />
{t("assets")}
</Link>
</div>
<hr className="my-3 shrink-0 border-accent-200/50" />
<div className="shrink-0 px-1 pb-2">
<input
type="search"
placeholder="Search collections…"
placeholder={t("searchPlaceholder")}
value={search}
onChange={(e) => setSearch(e.target.value)}
className="w-full rounded border border-gray-200 bg-white px-2 py-1.5 text-sm text-gray-900 placeholder:text-gray-400 focus:border-gray-300 focus:outline-none focus:ring-1 focus:ring-gray-300"
aria-label="Search collections"
className="w-full rounded border border-accent-200/60 bg-white/90 px-2 py-1.5 text-sm text-gray-900 placeholder:text-gray-500 focus:border-accent-300 focus:outline-none focus:ring-1 focus:ring-accent-200/80"
aria-label={t("searchAriaLabel")}
/>
</div>
{isLoading && (
<div className="px-3 py-2 text-sm text-gray-400">Loading</div>
)}
{error && (
<div className="px-3 py-2 text-sm text-red-600">
Error loading collections
</div>
)}
{!isLoading && !error && search.trim() && filteredCollections.length === 0 && (
<div className="px-3 py-2 text-sm text-gray-500">
No results for "{search.trim()}"
</div>
)}
{filteredCollections.map((c, i) => {
const href = `/content/${c.name}`;
const active = pathname === href || pathname.startsWith(href + "/");
const hasMeta =
c.description || (c.tags?.length ?? 0) > 0 || c.category;
const countResult = countQueries[i];
const count =
countResult?.data !== undefined ? countResult.data : null;
return (
<Link
key={c.name}
href={href}
title={c.description ?? undefined}
className={`rounded px-3 py-2 text-sm font-medium ${active ? "bg-gray-200 text-gray-900" : "text-gray-600 hover:bg-gray-100 hover:text-gray-900"}`}
>
<span className="flex items-center justify-between gap-2">
<span className="min-w-0 truncate">{c.name}</span>
{count !== null && (
<span className="shrink-0 text-xs font-normal text-gray-500 tabular-nums">
{formatCount(count)}
</span>
)}
</span>
{hasMeta && (
<span className="mt-0.5 block text-xs font-normal text-gray-500">
<div className="min-h-0 flex-1 overflow-y-auto overscroll-contain">
{isLoading && (
<div className="px-3 py-2 text-sm text-gray-400">{t("loading")}</div>
)}
{error && (
<div className="px-3 py-2 text-sm text-red-600">
{t("errorLoading")}
</div>
)}
{!isLoading && !error && search.trim() && filteredCollections.length === 0 && (
<div className="px-3 py-2 text-sm text-gray-500">
{t("noResults", { query: search.trim() })}
</div>
)}
{filteredCollections.map((c, i) => {
const href = `/content/${c.name}`;
const active = pathname === href || pathname.startsWith(href + "/");
const hasMeta =
c.description || (c.tags?.length ?? 0) > 0 || c.category;
const countResult = countQueries[i];
const count =
countResult?.data !== undefined ? countResult.data : null;
return (
<Link
key={c.name}
href={href}
onClick={onClose}
title={c.description ?? undefined}
className={`flex flex-col justify-center rounded-lg px-3 py-2.5 text-sm font-medium min-h-[44px] md:min-h-0 md:py-2 ${active ? "bg-accent-200/70 text-gray-900" : "text-gray-700 hover:bg-accent-100/80 hover:text-gray-900"}`}
>
<span className="flex items-center justify-between gap-2">
<span className="min-w-0 truncate">{c.name}</span>
{count !== null && (
<span className="shrink-0 text-xs font-normal text-gray-500 tabular-nums">
{formatCount(count)}
</span>
)}
</span>
{hasMeta && (
<span className="mt-0.5 block text-xs font-normal text-gray-500">
{c.category && (
<span className="rounded bg-gray-200 px-1">
<span className="rounded bg-accent-200/50 px-1">
{c.category}
</span>
)}
{c.tags?.length ? (
<span className="ml-1">
{c.tags.slice(0, 2).join(", ")}
{c.tags.length > 2 ? " …" : ""}
</span>
) : null}
</span>
)}
</Link>
);
})}
<hr className="my-2" />
<Link
href="/admin/new-type"
className="rounded px-3 py-2 text-sm font-medium text-gray-600 hover:bg-gray-100 hover:text-gray-900"
>
+ Add new type
</Link>
{c.tags?.length ? (
<span className="ml-1">
{c.tags.slice(0, 2).join(", ")}
{c.tags.length > 2 ? " …" : ""}
</span>
) : null}
</span>
)}
</Link>
);
})}
</div>
</nav>
<LocaleSwitcher locale={locale} />
</aside>
);
}

View File

@@ -0,0 +1,196 @@
"use client"
import * as React from "react"
import { AlertDialog as AlertDialogPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
function AlertDialog({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />
}
function AlertDialogTrigger({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
return (
<AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
)
}
function AlertDialogPortal({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
return (
<AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
)
}
function AlertDialogOverlay({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
return (
<AlertDialogPrimitive.Overlay
data-slot="alert-dialog-overlay"
className={cn(
"fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",
className
)}
{...props}
/>
)
}
function AlertDialogContent({
className,
size = "default",
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Content> & {
size?: "default" | "sm"
}) {
return (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
data-slot="alert-dialog-content"
data-size={size}
className={cn(
"group/alert-dialog-content fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 data-[size=sm]:max-w-xs data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 data-[size=default]:sm:max-w-lg",
className
)}
{...props}
/>
</AlertDialogPortal>
)
}
function AlertDialogHeader({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-header"
className={cn(
"grid grid-rows-[auto_1fr] place-items-center gap-1.5 text-center has-data-[slot=alert-dialog-media]:grid-rows-[auto_auto_1fr] has-data-[slot=alert-dialog-media]:gap-x-6 sm:group-data-[size=default]/alert-dialog-content:place-items-start sm:group-data-[size=default]/alert-dialog-content:text-left sm:group-data-[size=default]/alert-dialog-content:has-data-[slot=alert-dialog-media]:grid-rows-[auto_1fr]",
className
)}
{...props}
/>
)
}
function AlertDialogFooter({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 group-data-[size=sm]/alert-dialog-content:grid group-data-[size=sm]/alert-dialog-content:grid-cols-2 sm:flex-row sm:justify-end",
className
)}
{...props}
/>
)
}
function AlertDialogTitle({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
return (
<AlertDialogPrimitive.Title
data-slot="alert-dialog-title"
className={cn(
"text-lg font-semibold sm:group-data-[size=default]/alert-dialog-content:group-has-data-[slot=alert-dialog-media]/alert-dialog-content:col-start-2",
className
)}
{...props}
/>
)
}
function AlertDialogDescription({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
return (
<AlertDialogPrimitive.Description
data-slot="alert-dialog-description"
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
)
}
function AlertDialogMedia({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-media"
className={cn(
"mb-2 inline-flex size-16 items-center justify-center rounded-md bg-muted sm:group-data-[size=default]/alert-dialog-content:row-span-2 *:[svg:not([class*='size-'])]:size-8",
className
)}
{...props}
/>
)
}
function AlertDialogAction({
className,
variant = "default",
size = "default",
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Action> &
Pick<React.ComponentProps<typeof Button>, "variant" | "size">) {
return (
<Button variant={variant} size={size} asChild>
<AlertDialogPrimitive.Action
data-slot="alert-dialog-action"
className={cn(className)}
{...props}
/>
</Button>
)
}
function AlertDialogCancel({
className,
variant = "outline",
size = "default",
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel> &
Pick<React.ComponentProps<typeof Button>, "variant" | "size">) {
return (
<Button variant={variant} size={size} asChild>
<AlertDialogPrimitive.Cancel
data-slot="alert-dialog-cancel"
className={cn(className)}
{...props}
/>
</Button>
)
}
export {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogMedia,
AlertDialogOverlay,
AlertDialogPortal,
AlertDialogTitle,
AlertDialogTrigger,
}

View File

@@ -0,0 +1,48 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { Slot } from "radix-ui"
import { cn } from "@/lib/utils"
const badgeVariants = cva(
"inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-full border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
secondary:
"bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
destructive:
"bg-destructive text-white focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40 [a&]:hover:bg-destructive/90",
outline:
"border-border text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
ghost: "[a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
link: "text-primary underline-offset-4 [a&]:hover:underline",
},
},
defaultVariants: {
variant: "default",
},
}
)
function Badge({
className,
variant = "default",
asChild = false,
...props
}: React.ComponentProps<"span"> &
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
const Comp = asChild ? Slot.Root : "span"
return (
<Comp
data-slot="badge"
data-variant={variant}
className={cn(badgeVariants({ variant }), className)}
{...props}
/>
)
}
export { Badge, badgeVariants }

View File

@@ -0,0 +1,65 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { Slot } from "radix-ui"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 no-underline",
{
variants: {
variant: {
default:
"bg-accent-700 text-white hover:bg-accent-800 focus-visible:ring-accent-500/40",
destructive:
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40",
outline:
"border border-accent-200 bg-background text-accent-800 shadow-xs hover:bg-accent-50 dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
secondary:
"bg-accent-100 text-accent-800 border border-accent-200/80 hover:bg-accent-200/80 hover:border-accent-300",
ghost:
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
link: "text-accent-700 underline-offset-4 hover:text-accent-800 hover:underline",
},
size: {
default: "h-9 px-4 py-2 has-[>svg]:px-3",
xs: "h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",
sm: "h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
icon: "size-9",
"icon-xs": "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3",
"icon-sm": "size-8",
"icon-lg": "size-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function Button({
className,
variant = "default",
size = "default",
asChild = false,
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot.Root : "button"
return (
<Comp
data-slot="button"
data-variant={variant}
data-size={size}
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
)
}
export { Button, buttonVariants }

View File

@@ -0,0 +1,32 @@
"use client"
import * as React from "react"
import { CheckIcon } from "lucide-react"
import { Checkbox as CheckboxPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function Checkbox({
className,
...props
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
return (
<CheckboxPrimitive.Root
data-slot="checkbox"
className={cn(
"peer size-4 shrink-0 rounded-[4px] border border-input bg-background shadow-xs transition-shadow outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[state=checked]:border-primary data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:aria-invalid:ring-destructive/40",
className
)}
{...props}
>
<CheckboxPrimitive.Indicator
data-slot="checkbox-indicator"
className="grid place-content-center text-current transition-none"
>
<CheckIcon className="size-3.5" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
)
}
export { Checkbox }

View File

@@ -0,0 +1,42 @@
"use client";
import { Collapsible as CollapsiblePrimitive } from "radix-ui";
import { Icon } from "@iconify/react";
import { cn } from "@/lib/utils";
const Collapsible = CollapsiblePrimitive.Root;
const CollapsibleTrigger = CollapsiblePrimitive.Trigger;
const CollapsibleContent = CollapsiblePrimitive.Content;
/** Section with collapsible content and a clickable header (label + chevron). */
function CollapsibleSection({
title,
children,
defaultOpen = true,
className,
contentClassName,
}: {
title: React.ReactNode;
children: React.ReactNode;
defaultOpen?: boolean;
className?: string;
contentClassName?: string;
}) {
return (
<Collapsible defaultOpen={defaultOpen} className={cn("group rounded border border-gray-200 bg-gray-50/50", className)}>
<CollapsibleTrigger className="flex w-full items-center justify-between gap-2 px-4 py-3 text-left text-sm font-medium text-gray-700 hover:bg-gray-100/80 focus:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 rounded-t-[inherit] data-[state=open]:rounded-b-none">
{title}
<Icon
icon="mdi:chevron-down"
className="size-5 shrink-0 text-gray-500 transition-transform group-data-[state=open]:rotate-180"
aria-hidden
/>
</CollapsibleTrigger>
<CollapsibleContent>
<div className={cn("border-t border-gray-200 px-4 py-4", contentClassName)}>{children}</div>
</CollapsibleContent>
</Collapsible>
);
}
export { Collapsible, CollapsibleTrigger, CollapsibleContent, CollapsibleSection };

View File

@@ -0,0 +1,184 @@
"use client"
import * as React from "react"
import { Command as CommandPrimitive } from "cmdk"
import { SearchIcon } from "lucide-react"
import { cn } from "@/lib/utils"
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
function Command({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive>) {
return (
<CommandPrimitive
data-slot="command"
className={cn(
"flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",
className
)}
{...props}
/>
)
}
function CommandDialog({
title = "Command Palette",
description = "Search for a command to run...",
children,
className,
showCloseButton = true,
...props
}: React.ComponentProps<typeof Dialog> & {
title?: string
description?: string
className?: string
showCloseButton?: boolean
}) {
return (
<Dialog {...props}>
<DialogHeader className="sr-only">
<DialogTitle>{title}</DialogTitle>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<DialogContent
className={cn("overflow-hidden p-0", className)}
showCloseButton={showCloseButton}
>
<Command className="**:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
{children}
</Command>
</DialogContent>
</Dialog>
)
}
function CommandInput({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Input>) {
return (
<div
data-slot="command-input-wrapper"
className="flex h-9 items-center gap-2 border-b px-3"
>
<SearchIcon className="size-4 shrink-0 opacity-50" />
<CommandPrimitive.Input
data-slot="command-input"
className={cn(
"flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
/>
</div>
)
}
function CommandList({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.List>) {
return (
<CommandPrimitive.List
data-slot="command-list"
className={cn(
"max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",
className
)}
{...props}
/>
)
}
function CommandEmpty({
...props
}: React.ComponentProps<typeof CommandPrimitive.Empty>) {
return (
<CommandPrimitive.Empty
data-slot="command-empty"
className="py-6 text-center text-sm"
{...props}
/>
)
}
function CommandGroup({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Group>) {
return (
<CommandPrimitive.Group
data-slot="command-group"
className={cn(
"overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",
className
)}
{...props}
/>
)
}
function CommandSeparator({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Separator>) {
return (
<CommandPrimitive.Separator
data-slot="command-separator"
className={cn("-mx-1 h-px bg-border", className)}
{...props}
/>
)
}
function CommandItem({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Item>) {
return (
<CommandPrimitive.Item
data-slot="command-item"
className={cn(
"relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",
className
)}
{...props}
/>
)
}
function CommandShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="command-shortcut"
className={cn(
"ml-auto text-xs tracking-widest text-muted-foreground",
className
)}
{...props}
/>
)
}
export {
Command,
CommandDialog,
CommandInput,
CommandList,
CommandEmpty,
CommandGroup,
CommandItem,
CommandShortcut,
CommandSeparator,
}

View File

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

View File

@@ -0,0 +1,21 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
<input
type={type}
data-slot="input"
className={cn(
"h-9 w-full min-w-0 rounded-md border border-input bg-background text-foreground px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
"focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",
"aria-invalid:border-destructive aria-invalid:ring-destructive/20",
className
)}
{...props}
/>
)
}
export { Input }

View File

@@ -0,0 +1,24 @@
"use client"
import * as React from "react"
import { Label as LabelPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function Label({
className,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
return (
<LabelPrimitive.Root
data-slot="label"
className={cn(
"flex items-center gap-2 text-sm leading-none font-medium text-foreground select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
className
)}
{...props}
/>
)
}
export { Label }

View File

@@ -0,0 +1,89 @@
"use client"
import * as React from "react"
import { Popover as PopoverPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function Popover({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
return <PopoverPrimitive.Root data-slot="popover" {...props} />
}
function PopoverTrigger({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
}
function PopoverContent({
className,
align = "center",
sideOffset = 4,
...props
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
return (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
data-slot="popover-content"
align={align}
sideOffset={sideOffset}
className={cn(
"z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-hidden data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
className
)}
{...props}
/>
</PopoverPrimitive.Portal>
)
}
function PopoverAnchor({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
}
function PopoverHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="popover-header"
className={cn("flex flex-col gap-1 text-sm", className)}
{...props}
/>
)
}
function PopoverTitle({ className, ...props }: React.ComponentProps<"h2">) {
return (
<div
data-slot="popover-title"
className={cn("font-medium", className)}
{...props}
/>
)
}
function PopoverDescription({
className,
...props
}: React.ComponentProps<"p">) {
return (
<p
data-slot="popover-description"
className={cn("text-muted-foreground", className)}
{...props}
/>
)
}
export {
Popover,
PopoverTrigger,
PopoverContent,
PopoverAnchor,
PopoverHeader,
PopoverTitle,
PopoverDescription,
}

View File

@@ -0,0 +1,190 @@
"use client"
import * as React from "react"
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"
import { Select as SelectPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function Select({
...props
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
return <SelectPrimitive.Root data-slot="select" {...props} />
}
function SelectGroup({
...props
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
return <SelectPrimitive.Group data-slot="select-group" {...props} />
}
function SelectValue({
...props
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
return <SelectPrimitive.Value data-slot="select-value" {...props} />
}
function SelectTrigger({
className,
size = "default",
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
size?: "sm" | "default"
}) {
return (
<SelectPrimitive.Trigger
data-slot="select-trigger"
data-size={size}
className={cn(
"flex w-fit items-center justify-between gap-2 rounded-md border border-input bg-background text-foreground px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[placeholder]:text-muted-foreground data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDownIcon className="size-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
)
}
function SelectContent({
className,
children,
position = "item-aligned",
align = "center",
...props
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
return (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
data-slot="select-content"
className={cn(
"relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className
)}
position={position}
align={align}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
"p-1",
position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
)
}
function SelectLabel({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
return (
<SelectPrimitive.Label
data-slot="select-label"
className={cn("px-2 py-1.5 text-xs text-muted-foreground", className)}
{...props}
/>
)
}
function SelectItem({
className,
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
return (
<SelectPrimitive.Item
data-slot="select-item"
className={cn(
"relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
className
)}
{...props}
>
<span
data-slot="select-item-indicator"
className="absolute right-2 flex size-3.5 items-center justify-center"
>
<SelectPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
)
}
function SelectSeparator({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
return (
<SelectPrimitive.Separator
data-slot="select-separator"
className={cn("pointer-events-none -mx-1 my-1 h-px bg-border", className)}
{...props}
/>
)
}
function SelectScrollUpButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
return (
<SelectPrimitive.ScrollUpButton
data-slot="select-scroll-up-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronUpIcon className="size-4" />
</SelectPrimitive.ScrollUpButton>
)
}
function SelectScrollDownButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
return (
<SelectPrimitive.ScrollDownButton
data-slot="select-scroll-down-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronDownIcon className="size-4" />
</SelectPrimitive.ScrollDownButton>
)
}
export {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectScrollDownButton,
SelectScrollUpButton,
SelectSeparator,
SelectTrigger,
SelectValue,
}

View File

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

View File

@@ -0,0 +1,116 @@
"use client"
import * as React from "react"
import { cn } from "@/lib/utils"
function Table({ className, ...props }: React.ComponentProps<"table">) {
return (
<div
data-slot="table-container"
className="relative w-full overflow-x-auto"
>
<table
data-slot="table"
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
)
}
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
return (
<thead
data-slot="table-header"
className={cn("[&_tr]:border-b [&_tr]:border-gray-200/80", className)}
{...props}
/>
)
}
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
return (
<tbody
data-slot="table-body"
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
)
}
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
return (
<tfoot
data-slot="table-footer"
className={cn(
"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
className
)}
{...props}
/>
)
}
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
return (
<tr
data-slot="table-row"
className={cn(
"border-b border-gray-200/60 transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",
className
)}
{...props}
/>
)
}
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
return (
<th
data-slot="table-head"
className={cn(
"h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
)}
{...props}
/>
)
}
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
return (
<td
data-slot="table-cell"
className={cn(
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
)}
{...props}
/>
)
}
function TableCaption({
className,
...props
}: React.ComponentProps<"caption">) {
return (
<caption
data-slot="table-caption"
className={cn("mt-4 text-sm text-muted-foreground", className)}
{...props}
/>
)
}
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
}

View File

@@ -0,0 +1,18 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
return (
<textarea
data-slot="textarea"
className={cn(
"flex field-sizing-content min-h-16 w-full rounded-md border border-input bg-background text-foreground px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 md:text-sm",
className
)}
{...props}
/>
)
}
export { Textarea }

View File

@@ -42,6 +42,8 @@ export type FieldDefinition = {
enum?: unknown[];
default?: unknown;
items?: FieldDefinition;
/** Optional section key for grouping fields in the admin UI (collapsible blocks). */
section?: string;
[key: string]: unknown;
};
@@ -99,6 +101,34 @@ export async function createSchema(
return res.json();
}
export async function updateSchema(
name: string,
schema: SchemaDefinition
): Promise<SchemaDefinition> {
const res = await fetch(`${getBaseUrl()}/api/schemas/${encodeURIComponent(name)}`, {
method: "PUT",
headers: getHeaders(),
body: JSON.stringify(schema),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
const msg = (err as { error?: string }).error ?? (err as { errors?: string[] })?.errors?.join(", ") ?? `Update schema: ${res.status}`;
throw new Error(msg);
}
return res.json();
}
export async function deleteSchema(name: string): Promise<void> {
const res = await fetch(`${getBaseUrl()}/api/schemas/${encodeURIComponent(name)}`, {
method: "DELETE",
headers: getHeaders(),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error((err as { error?: string }).error ?? `Delete schema: ${res.status}`);
}
}
export type SlugCheckResponse = {
valid: boolean;
normalized: string;
@@ -177,8 +207,11 @@ export async function createEntry(
body: JSON.stringify(data),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error((err as { message?: string }).message || `Create: ${res.status}`);
const err = await res.json().catch(() => ({})) as { error?: string; errors?: string[] };
const msg = err.errors?.length ? err.errors.join("\n") : err.error ?? `Create: ${res.status}`;
const e = new Error(msg) as Error & { apiErrors?: string[] };
e.apiErrors = err.errors;
throw e;
}
return res.json();
}
@@ -199,12 +232,199 @@ export async function updateEntry(
body: JSON.stringify(data),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error((err as { message?: string }).message || `Update: ${res.status}`);
const err = await res.json().catch(() => ({})) as { error?: string; errors?: string[] };
const msg = err.errors?.length ? err.errors.join("\n") : err.error ?? `Update: ${res.status}`;
const e = new Error(msg) as Error & { apiErrors?: string[] };
e.apiErrors = err.errors;
throw e;
}
return res.json();
}
export type Asset = {
filename: string;
folder: string | null;
url: string;
mime_type: string;
size: number;
};
export type AssetsResponse = {
assets: Asset[];
total: number;
};
export type AssetFolder = {
name: string;
count: number;
};
export type FoldersResponse = {
folders: AssetFolder[];
};
/** folder=undefined → all; folder="" → root only; folder="name" → specific folder */
export async function fetchAssets(folder?: string): Promise<AssetsResponse> {
const url = new URL(`${getBaseUrl()}/api/assets`);
if (folder !== undefined) url.searchParams.set("folder", folder);
const res = await fetch(url.toString(), { headers: getHeaders() });
if (!res.ok) throw new Error(`Assets: ${res.status}`);
return res.json();
}
export async function fetchFolders(): Promise<FoldersResponse> {
const res = await fetch(`${getBaseUrl()}/api/assets/folders`, { headers: getHeaders() });
if (!res.ok) throw new Error(`Folders: ${res.status}`);
return res.json();
}
export async function createFolder(name: string): Promise<void> {
const res = await fetch(`${getBaseUrl()}/api/assets/folders`, {
method: "POST",
headers: getHeaders(),
body: JSON.stringify({ name }),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error((err as { error?: string }).error ?? `Create folder: ${res.status}`);
}
}
export async function deleteFolder(name: string): Promise<void> {
const res = await fetch(`${getBaseUrl()}/api/assets/folders/${encodeURIComponent(name)}`, {
method: "DELETE",
headers: getHeaders(),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error((err as { error?: string }).error ?? `Delete folder: ${res.status}`);
}
}
const getUploadHeaders = (): HeadersInit => {
const key =
typeof window !== "undefined"
? process.env.NEXT_PUBLIC_RUSTYCMS_API_KEY ?? null
: process.env.RUSTYCMS_API_KEY ?? process.env.NEXT_PUBLIC_RUSTYCMS_API_KEY ?? null;
const headers: HeadersInit = {};
if (key) headers["X-API-Key"] = key;
return headers;
};
export async function uploadAsset(file: File, folder?: string): Promise<Asset> {
const url = new URL(`${getBaseUrl()}/api/assets`);
if (folder) url.searchParams.set("folder", folder);
const body = new FormData();
body.append("file", file);
const res = await fetch(url.toString(), { method: "POST", headers: getUploadHeaders(), body });
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error((err as { error?: string }).error ?? `Upload: ${res.status}`);
}
return res.json();
}
/** path = "hero.jpg" or "blog/hero.jpg" */
export async function deleteAsset(path: string): Promise<void> {
const res = await fetch(`${getBaseUrl()}/api/assets/${path}`, {
method: "DELETE",
headers: getHeaders(),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error((err as { error?: string }).error ?? `Delete asset: ${res.status}`);
}
}
/** Rename asset; path = "hero.jpg" or "blog/hero.jpg", newFilename = "newname.jpg" */
export async function renameAsset(path: string, newFilename: string): Promise<Asset> {
const res = await fetch(`${getBaseUrl()}/api/assets/${path}`, {
method: "PATCH",
headers: getHeaders(),
body: JSON.stringify({ filename: newFilename }),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error((err as { error?: string }).error ?? `Rename: ${res.status}`);
}
return res.json();
}
/** Query params for GET /api/transform (w, h, ar, fit, format). */
export type TransformParams = {
w?: number;
h?: number;
ar?: string;
fit?: "fill" | "contain" | "cover";
format?: "jpeg" | "png" | "webp" | "avif";
quality?: number;
};
/** Build URL for transformed image (same origin or full URL). */
export function getTransformUrl(imageUrl: string, params: TransformParams): string {
const base = getBaseUrl();
const fullUrl = imageUrl.startsWith("http") ? imageUrl : `${base}${imageUrl.startsWith("/") ? "" : "/"}${imageUrl}`;
const u = new URL(`${base}/api/transform`);
u.searchParams.set("url", fullUrl);
if (params.w != null) u.searchParams.set("w", String(params.w));
if (params.h != null) u.searchParams.set("h", String(params.h));
if (params.ar != null) u.searchParams.set("ar", params.ar);
if (params.fit != null) u.searchParams.set("fit", params.fit);
if (params.format != null) u.searchParams.set("format", params.format);
if (params.quality != null) u.searchParams.set("quality", String(params.quality));
return u.toString();
}
/** Build a filename for a transformed copy: base-w800-h600.webp */
export function getTransformedFilename(originalFilename: string, params: TransformParams): string {
const lastDot = originalFilename.lastIndexOf(".");
const base = lastDot >= 0 ? originalFilename.slice(0, lastDot) : originalFilename;
const ext = (params.format ?? "jpeg") === "jpeg" ? "jpg" : (params.format ?? "jpeg");
const parts: string[] = [];
if (params.w != null) parts.push(`w${params.w}`);
if (params.h != null) parts.push(`h${params.h}`);
if (params.ar != null) parts.push(`ar${params.ar.replace(":", "x")}`);
if (params.fit != null) parts.push(params.fit);
const suffix = parts.length ? `-${parts.join("-")}` : "";
return `${base}${suffix}.${ext}`;
}
/** Fetch transformed image and upload as new asset. Returns the new asset. */
export async function copyAssetWithTransformation(
asset: Asset,
params: TransformParams,
folder?: string
): Promise<Asset> {
const imageUrl = `${getBaseUrl()}${asset.url}`;
const transformUrl = getTransformUrl(asset.url, params);
const res = await fetch(transformUrl);
if (!res.ok) throw new Error(`Transform failed: ${res.status}`);
const blob = await res.blob();
const contentType = res.headers.get("Content-Type") ?? "image/jpeg";
const ext = (params.format ?? "jpeg") === "jpeg" ? "jpg" : (params.format ?? "jpeg");
const suggestedName = getTransformedFilename(asset.filename, params);
const file = new File([blob], suggestedName, { type: contentType });
return uploadAsset(file, folder);
}
export type LocalesResponse = {
locales: string[];
default: string | null;
};
export async function fetchLocales(): Promise<LocalesResponse> {
try {
const res = await fetch(`${getBaseUrl()}/api/locales`, {
headers: getHeaders(),
next: { revalidate: 300 },
});
if (res.ok) return res.json();
} catch { /* API not reachable */ }
const envLocales = (process.env.NEXT_PUBLIC_RUSTYCMS_LOCALES ?? "")
.split(",").map((s) => s.trim()).filter(Boolean);
return { locales: envLocales, default: envLocales[0] ?? null };
}
export async function deleteEntry(
collection: string,
slug: string,

View File

@@ -0,0 +1,12 @@
/**
* Build a display label for a reference option (entry from any collection).
* Used by ReferenceField and ReferenceArrayField for consistent option labels.
*/
export function getOptionLabel(item: Record<string, unknown>): string {
const slug = String(item._slug ?? "");
const name = item.name != null ? String(item.name) : "";
const headline = item.headline != null ? String(item.headline) : "";
const linkName = item.linkName != null ? String(item.linkName) : "";
const full = name || headline || linkName || slug;
return full !== slug ? `${slug}${full}` : slug;
}

View File

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