RustyCMS: File-based headless CMS with REST API, admin UI, multilingual support
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
41
admin-ui/.gitignore
vendored
Normal file
41
admin-ui/.gitignore
vendored
Normal file
@@ -0,0 +1,41 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.*
|
||||
.yarn/*
|
||||
!.yarn/patches
|
||||
!.yarn/plugins
|
||||
!.yarn/releases
|
||||
!.yarn/versions
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# next.js
|
||||
/.next/
|
||||
/out/
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
*.pem
|
||||
|
||||
# debug
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
# env files (can opt-in for committing if needed)
|
||||
.env*
|
||||
|
||||
# vercel
|
||||
.vercel
|
||||
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
36
admin-ui/README.md
Normal file
36
admin-ui/README.md
Normal file
@@ -0,0 +1,36 @@
|
||||
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
|
||||
|
||||
## Getting Started
|
||||
|
||||
First, run the development server:
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
# or
|
||||
yarn dev
|
||||
# or
|
||||
pnpm dev
|
||||
# or
|
||||
bun dev
|
||||
```
|
||||
|
||||
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
|
||||
|
||||
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
|
||||
|
||||
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
|
||||
|
||||
## Learn More
|
||||
|
||||
To learn more about Next.js, take a look at the following resources:
|
||||
|
||||
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
|
||||
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
|
||||
|
||||
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
|
||||
|
||||
## Deploy on Vercel
|
||||
|
||||
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
|
||||
|
||||
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
|
||||
18
admin-ui/eslint.config.mjs
Normal file
18
admin-ui/eslint.config.mjs
Normal file
@@ -0,0 +1,18 @@
|
||||
import { defineConfig, globalIgnores } from "eslint/config";
|
||||
import nextVitals from "eslint-config-next/core-web-vitals";
|
||||
import nextTs from "eslint-config-next/typescript";
|
||||
|
||||
const eslintConfig = defineConfig([
|
||||
...nextVitals,
|
||||
...nextTs,
|
||||
// Override default ignores of eslint-config-next.
|
||||
globalIgnores([
|
||||
// Default ignores of eslint-config-next:
|
||||
".next/**",
|
||||
"out/**",
|
||||
"build/**",
|
||||
"next-env.d.ts",
|
||||
]),
|
||||
]);
|
||||
|
||||
export default eslintConfig;
|
||||
7
admin-ui/next.config.ts
Normal file
7
admin-ui/next.config.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
/* config options here */
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
7752
admin-ui/package-lock.json
generated
Normal file
7752
admin-ui/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
29
admin-ui/package.json
Normal file
29
admin-ui/package.json
Normal file
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "admin-ui",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev -p 2001",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "eslint"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tanstack/react-query": "^5.90.21",
|
||||
"next": "16.1.6",
|
||||
"react": "19.2.3",
|
||||
"react-dom": "19.2.3",
|
||||
"react-hook-form": "^7.71.1",
|
||||
"react-markdown": "^10.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4",
|
||||
"@types/node": "^20",
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19",
|
||||
"eslint": "^9",
|
||||
"eslint-config-next": "16.1.6",
|
||||
"tailwindcss": "^4",
|
||||
"typescript": "^5"
|
||||
}
|
||||
}
|
||||
7
admin-ui/postcss.config.mjs
Normal file
7
admin-ui/postcss.config.mjs
Normal file
@@ -0,0 +1,7 @@
|
||||
const config = {
|
||||
plugins: {
|
||||
"@tailwindcss/postcss": {},
|
||||
},
|
||||
};
|
||||
|
||||
export default config;
|
||||
1
admin-ui/public/file.svg
Normal file
1
admin-ui/public/file.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>
|
||||
|
After Width: | Height: | Size: 391 B |
1
admin-ui/public/globe.svg
Normal file
1
admin-ui/public/globe.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>
|
||||
|
After Width: | Height: | Size: 1.0 KiB |
1
admin-ui/public/next.svg
Normal file
1
admin-ui/public/next.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
1
admin-ui/public/vercel.svg
Normal file
1
admin-ui/public/vercel.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>
|
||||
|
After Width: | Height: | Size: 128 B |
1
admin-ui/public/window.svg
Normal file
1
admin-ui/public/window.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>
|
||||
|
After Width: | Height: | Size: 385 B |
292
admin-ui/src/app/admin/new-type/page.tsx
Normal file
292
admin-ui/src/app/admin/new-type/page.tsx
Normal file
@@ -0,0 +1,292 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { createSchema, type SchemaDefinition, type FieldDefinition } from "@/lib/api";
|
||||
|
||||
const FIELD_TYPES = [
|
||||
"string",
|
||||
"number",
|
||||
"integer",
|
||||
"boolean",
|
||||
"datetime",
|
||||
"richtext",
|
||||
"html",
|
||||
"markdown",
|
||||
"reference",
|
||||
"array",
|
||||
"object",
|
||||
] as const;
|
||||
|
||||
type FieldRow = {
|
||||
id: string;
|
||||
name: string;
|
||||
type: string;
|
||||
required: boolean;
|
||||
description: string;
|
||||
collection: string;
|
||||
};
|
||||
|
||||
function nextId() {
|
||||
return Math.random().toString(36).slice(2, 9);
|
||||
}
|
||||
|
||||
export default function NewTypePage() {
|
||||
const router = useRouter();
|
||||
const queryClient = useQueryClient();
|
||||
const [name, setName] = useState("");
|
||||
const [description, setDescription] = useState("");
|
||||
const [category, setCategory] = useState("");
|
||||
const [tagsStr, setTagsStr] = useState("");
|
||||
const [strict, setStrict] = useState(false);
|
||||
const [fields, setFields] = useState<FieldRow[]>([
|
||||
{ id: nextId(), name: "title", type: "string", required: true, description: "", collection: "" },
|
||||
]);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
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 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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
const fieldsObj: Record<string, FieldDefinition> = {};
|
||||
for (const row of fields) {
|
||||
const fn = row.name.trim();
|
||||
if (!fn) continue;
|
||||
const def: FieldDefinition = {
|
||||
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 = {
|
||||
name: nameTrim,
|
||||
description: description.trim() || undefined,
|
||||
category: category.trim() || undefined,
|
||||
tags: tagsStr.trim() ? tagsStr.split(",").map((t) => t.trim()).filter(Boolean) : undefined,
|
||||
strict,
|
||||
reusable: false,
|
||||
fields: fieldsObj,
|
||||
};
|
||||
|
||||
setSubmitting(true);
|
||||
try {
|
||||
await createSchema(schema);
|
||||
await queryClient.invalidateQueries({ queryKey: ["collections"] });
|
||||
router.push(`/content/${nameTrim}`);
|
||||
router.refresh();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Error creating type.");
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="max-w-2xl">
|
||||
<h1 className="mb-6 text-2xl font-semibold text-gray-900">Add new type</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/<name>.json</code> and loaded via hot-reload.
|
||||
</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 text-sm font-medium text-gray-700">
|
||||
Name <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"
|
||||
required
|
||||
/>
|
||||
<p className="mt-0.5 text-xs text-gray-500">
|
||||
Lowercase letters, digits and underscores only.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="mb-1 block text-sm font-medium text-gray-700">Description</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
|
||||
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"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-1 block text-sm font-medium text-gray-700">Tags (comma-separated)</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"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="strict"
|
||||
checked={strict}
|
||||
onChange={(e) => setStrict(e.target.checked)}
|
||||
className="h-4 w-4 rounded border-gray-300"
|
||||
/>
|
||||
<label htmlFor="strict" className="text-sm text-gray-700">
|
||||
Strict (reject unknown fields)
|
||||
</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>
|
||||
</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="Field name"
|
||||
className="rounded border border-gray-300 px-2 py-1.5 text-sm"
|
||||
/>
|
||||
<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"
|
||||
>
|
||||
{FIELD_TYPES.map((t) => (
|
||||
<option key={t} value={t}>
|
||||
{t}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<label className="flex items-center gap-1 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={f.required}
|
||||
onChange={(e) => updateField(f.id, { required: e.target.checked })}
|
||||
className="h-4 w-4 rounded border-gray-300"
|
||||
/>
|
||||
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"
|
||||
>
|
||||
Entfernen
|
||||
</button>
|
||||
{f.type === "reference" && (
|
||||
<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"
|
||||
/>
|
||||
)}
|
||||
<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"
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</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>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
BIN
admin-ui/src/app/favicon.ico
Normal file
BIN
admin-ui/src/app/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
34
admin-ui/src/app/globals.css
Normal file
34
admin-ui/src/app/globals.css
Normal file
@@ -0,0 +1,34 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
:root {
|
||||
--background: #ffffff;
|
||||
--foreground: #171717;
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--font-sans: var(--font-geist-sans);
|
||||
--font-mono: var(--font-geist-mono);
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--background: #0a0a0a;
|
||||
--foreground: #ededed;
|
||||
}
|
||||
}
|
||||
|
||||
body {
|
||||
background: var(--background);
|
||||
color: var(--foreground);
|
||||
font-family: Arial, Helvetica, sans-serif;
|
||||
}
|
||||
|
||||
/* Lesbare Eingabefelder: dunkler Text, heller Hintergrund */
|
||||
input:not([type="checkbox"]):not([type="radio"]),
|
||||
textarea,
|
||||
select {
|
||||
color: #111827; /* gray-900 */
|
||||
background-color: #ffffff;
|
||||
}
|
||||
41
admin-ui/src/app/layout.tsx
Normal file
41
admin-ui/src/app/layout.tsx
Normal file
@@ -0,0 +1,41 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Geist, Geist_Mono } from "next/font/google";
|
||||
import { Providers } from "./providers";
|
||||
import { Sidebar } from "@/components/Sidebar";
|
||||
import "./globals.css";
|
||||
|
||||
const geistSans = Geist({
|
||||
variable: "--font-geist-sans",
|
||||
subsets: ["latin"],
|
||||
});
|
||||
|
||||
const geistMono = Geist_Mono({
|
||||
variable: "--font-geist-mono",
|
||||
subsets: ["latin"],
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "RustyCMS Admin",
|
||||
description: "RustyCMS admin interface",
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
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>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
43
admin-ui/src/app/page.tsx
Normal file
43
admin-ui/src/app/page.tsx
Normal file
@@ -0,0 +1,43 @@
|
||||
import Link from "next/link";
|
||||
import { fetchCollections } from "@/lib/api";
|
||||
|
||||
export default async function DashboardPage() {
|
||||
let collections: { name: string }[] = [];
|
||||
try {
|
||||
const res = await fetchCollections();
|
||||
collections = res.collections ?? [];
|
||||
} catch {
|
||||
// API unreachable etc.
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1 className="mb-6 text-2xl font-semibold text-gray-900">Dashboard</h1>
|
||||
<p className="mb-6 text-gray-600">
|
||||
Choose a collection to manage content.
|
||||
</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"
|
||||
>
|
||||
{c.name}
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</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>
|
||||
.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
18
admin-ui/src/app/providers.tsx
Normal file
18
admin-ui/src/app/providers.tsx
Normal file
@@ -0,0 +1,18 @@
|
||||
"use client";
|
||||
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { useState } from "react";
|
||||
|
||||
export function Providers({ children }: { children: React.ReactNode }) {
|
||||
const [client] = useState(
|
||||
() =>
|
||||
new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { staleTime: 60 * 1000 },
|
||||
},
|
||||
})
|
||||
);
|
||||
return (
|
||||
<QueryClientProvider client={client}>{children}</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
632
admin-ui/src/components/ContentForm.tsx
Normal file
632
admin-ui/src/components/ContentForm.tsx
Normal file
@@ -0,0 +1,632 @@
|
||||
"use client";
|
||||
|
||||
import { useId } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useForm, Controller } from "react-hook-form";
|
||||
import type { SchemaDefinition, FieldDefinition } from "@/lib/api";
|
||||
import { checkSlug } from "@/lib/api";
|
||||
import { ReferenceArrayField } from "./ReferenceArrayField";
|
||||
import { MarkdownEditor } from "./MarkdownEditor";
|
||||
|
||||
type Props = {
|
||||
collection: string;
|
||||
schema: SchemaDefinition;
|
||||
initialValues?: Record<string, unknown>;
|
||||
slug?: string;
|
||||
locale?: string;
|
||||
onSuccess?: () => void;
|
||||
};
|
||||
|
||||
/** _slug field with format and duplicate check via API. */
|
||||
function SlugField({
|
||||
collection,
|
||||
currentSlug,
|
||||
locale,
|
||||
register,
|
||||
setError,
|
||||
clearErrors,
|
||||
error,
|
||||
}: {
|
||||
collection: string;
|
||||
currentSlug?: string;
|
||||
locale?: string;
|
||||
register: ReturnType<typeof useForm>["register"];
|
||||
setError: ReturnType<typeof useForm>["setError"];
|
||||
clearErrors: ReturnType<typeof useForm>["clearErrors"];
|
||||
error: ReturnType<typeof useForm>["formState"]["errors"]["_slug"];
|
||||
}) {
|
||||
const { ref, onChange, onBlur, name } = register("_slug", {
|
||||
required: "Slug is required.",
|
||||
});
|
||||
|
||||
const handleBlur = async (e: React.FocusEvent<HTMLInputElement>) => {
|
||||
onBlur(e);
|
||||
const value = e.target.value?.trim();
|
||||
if (!value) return;
|
||||
try {
|
||||
const res = await checkSlug(collection, value, {
|
||||
exclude: currentSlug ?? undefined,
|
||||
_locale: locale,
|
||||
});
|
||||
if (!res.valid && res.error) {
|
||||
setError("_slug", { type: "server", message: res.error });
|
||||
return;
|
||||
}
|
||||
if (!res.available) {
|
||||
setError("_slug", {
|
||||
type: "server",
|
||||
message: "Slug already in use.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
clearErrors("_slug");
|
||||
} catch {
|
||||
// Network error etc. – no setError, user will see it on submit
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<label className="mb-1 block text-sm font-medium text-gray-700">
|
||||
_slug <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
ref={ref}
|
||||
name={name}
|
||||
onChange={onChange}
|
||||
onBlur={handleBlur}
|
||||
placeholder="e.g. my-post"
|
||||
className="block w-full rounded border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 font-mono"
|
||||
autoComplete="off"
|
||||
/>
|
||||
<p className="mt-1 text-xs text-gray-500">
|
||||
Lowercase letters (a-z), digits (0-9), hyphens. Spaces become hyphens.
|
||||
</p>
|
||||
{error ? (
|
||||
<p className="mt-1 text-sm text-red-600">{String(error.message)}</p>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Builds form initial values from API response: references → slug strings, objects recursively. */
|
||||
function buildDefaultValues(
|
||||
schema: SchemaDefinition,
|
||||
initialValues?: Record<string, unknown>,
|
||||
): Record<string, unknown> {
|
||||
const out: Record<string, unknown> = {};
|
||||
const fields = schema.fields ?? {};
|
||||
if (initialValues) {
|
||||
for (const [key, value] of Object.entries(initialValues)) {
|
||||
const def = fields[key] as FieldDefinition | undefined;
|
||||
if (value == null) {
|
||||
out[key] = value;
|
||||
continue;
|
||||
}
|
||||
if (def?.type === "reference") {
|
||||
out[key] =
|
||||
typeof value === "object" && value !== null && "_slug" in value
|
||||
? String((value as { _slug?: string })._slug ?? "")
|
||||
: typeof value === "string"
|
||||
? value
|
||||
: "";
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
def?.type === "array" &&
|
||||
def.items?.type === "reference" &&
|
||||
Array.isArray(value)
|
||||
) {
|
||||
out[key] = value.map((v) =>
|
||||
typeof v === "object" && v !== null && "_slug" in v
|
||||
? (v as { _slug: string })._slug
|
||||
: String(v),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
def?.type === "object" &&
|
||||
def.fields &&
|
||||
typeof value === "object" &&
|
||||
value !== null &&
|
||||
!Array.isArray(value)
|
||||
) {
|
||||
out[key] = buildDefaultValues(
|
||||
{ name: key, fields: def.fields as Record<string, FieldDefinition> },
|
||||
value as Record<string, unknown>,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
out[key] = value;
|
||||
}
|
||||
}
|
||||
for (const key of Object.keys(fields)) {
|
||||
if (!(key in out)) {
|
||||
const def = fields[key] as FieldDefinition | undefined;
|
||||
if (def?.default !== undefined && def.default !== null) {
|
||||
if (
|
||||
def?.type === "object" &&
|
||||
def.fields &&
|
||||
typeof def.default === "object" &&
|
||||
def.default !== null &&
|
||||
!Array.isArray(def.default)
|
||||
) {
|
||||
out[key] = buildDefaultValues(
|
||||
{
|
||||
name: key,
|
||||
fields: def.fields as Record<string, FieldDefinition>,
|
||||
},
|
||||
def.default as Record<string, unknown>,
|
||||
);
|
||||
} else {
|
||||
out[key] = def.default;
|
||||
}
|
||||
} else if (def?.type === "boolean") out[key] = false;
|
||||
else if (def?.type === "array")
|
||||
out[key] =
|
||||
(def as FieldDefinition).items?.type === "reference" ? [] : "";
|
||||
else if (def?.type === "object" && def.fields)
|
||||
out[key] = buildDefaultValues(
|
||||
{ name: key, fields: def.fields as Record<string, FieldDefinition> },
|
||||
{},
|
||||
);
|
||||
else out[key] = "";
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function ContentForm({
|
||||
collection,
|
||||
schema,
|
||||
initialValues,
|
||||
slug,
|
||||
locale,
|
||||
onSuccess,
|
||||
}: Props) {
|
||||
const router = useRouter();
|
||||
const isEdit = !!slug;
|
||||
const defaultValues = buildDefaultValues(schema, initialValues);
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
setError,
|
||||
clearErrors,
|
||||
control,
|
||||
formState: { errors, isSubmitting },
|
||||
} = useForm({
|
||||
defaultValues,
|
||||
});
|
||||
|
||||
const onSubmit = async (data: Record<string, unknown>) => {
|
||||
const payload: Record<string, unknown> = {};
|
||||
for (const [key, value] of Object.entries(data)) {
|
||||
const def = schema.fields?.[key];
|
||||
if (def?.type === "array" && def.items?.type === "reference") {
|
||||
payload[key] = Array.isArray(value)
|
||||
? value
|
||||
: typeof value === "string"
|
||||
? value
|
||||
.split(/[\n,]+/)
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean)
|
||||
: [];
|
||||
} else {
|
||||
payload[key] = value;
|
||||
}
|
||||
}
|
||||
if (isEdit) {
|
||||
delete payload._slug;
|
||||
}
|
||||
try {
|
||||
const params = locale ? { _locale: locale } : {};
|
||||
if (isEdit) {
|
||||
const { updateEntry } = await import("@/lib/api");
|
||||
await updateEntry(collection, slug!, payload, params);
|
||||
onSuccess?.();
|
||||
} else {
|
||||
const { createEntry } = await import("@/lib/api");
|
||||
await createEntry(collection, payload, params);
|
||||
onSuccess?.();
|
||||
const newSlug = payload._slug as string | undefined;
|
||||
const q = locale ? `?_locale=${locale}` : "";
|
||||
if (newSlug) {
|
||||
router.push(
|
||||
`/content/${collection}/${encodeURIComponent(newSlug)}${q}`,
|
||||
);
|
||||
} else {
|
||||
router.push(`/content/${collection}${q}`);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
setError("root", {
|
||||
message: err instanceof Error ? err.message : "Error saving",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const fields = schema.fields ?? {};
|
||||
const slugParam = locale ? `?_locale=${locale}` : "";
|
||||
const showSlugField = !isEdit && !(fields._slug != null);
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="max-w-2xl space-y-4">
|
||||
{errors.root && (
|
||||
<div className="rounded bg-red-50 p-3 text-sm text-red-700">
|
||||
{errors.root.message}
|
||||
</div>
|
||||
)}
|
||||
{showSlugField && (
|
||||
<SlugField
|
||||
collection={collection}
|
||||
currentSlug={slug}
|
||||
locale={locale}
|
||||
register={register}
|
||||
setError={setError}
|
||||
clearErrors={clearErrors}
|
||||
error={errors._slug}
|
||||
/>
|
||||
)}
|
||||
{Object.entries(fields).map(([name, def]) =>
|
||||
(def as FieldDefinition).type === "object" &&
|
||||
(def as FieldDefinition).fields ? (
|
||||
<ObjectFieldSet
|
||||
key={name}
|
||||
name={name}
|
||||
def={def as FieldDefinition}
|
||||
register={register}
|
||||
control={control}
|
||||
errors={errors}
|
||||
isEdit={isEdit}
|
||||
locale={locale}
|
||||
/>
|
||||
) : (
|
||||
<Field
|
||||
key={name}
|
||||
name={name}
|
||||
def={def as FieldDefinition}
|
||||
register={register}
|
||||
control={control}
|
||||
errors={errors}
|
||||
isEdit={isEdit}
|
||||
locale={locale}
|
||||
/>
|
||||
),
|
||||
)}
|
||||
<div className="flex gap-3 pt-4">
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isSubmitting}
|
||||
className="rounded-lg bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:bg-gray-800 disabled:opacity-50"
|
||||
>
|
||||
{isSubmitting ? "Saving…" : "Save"}
|
||||
</button>
|
||||
{isEdit && (
|
||||
<a
|
||||
href={`/content/${collection}${slugParam}`}
|
||||
className="rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50"
|
||||
>
|
||||
Back to list
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
/** Get error for path "layout.mobile" from errors.layout.mobile */
|
||||
function getFieldError(errors: Record<string, unknown>, name: string): unknown {
|
||||
const parts = name.split(".");
|
||||
let current: unknown = errors;
|
||||
for (const p of parts) {
|
||||
current =
|
||||
current != null && typeof current === "object" && p in current
|
||||
? (current as Record<string, unknown>)[p]
|
||||
: undefined;
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
function ObjectFieldSet({
|
||||
name,
|
||||
def,
|
||||
register,
|
||||
control,
|
||||
errors,
|
||||
isEdit,
|
||||
locale,
|
||||
}: {
|
||||
name: string;
|
||||
def: FieldDefinition;
|
||||
register: ReturnType<typeof useForm>["register"];
|
||||
control: ReturnType<typeof useForm>["control"];
|
||||
errors: ReturnType<typeof useForm>["formState"]["errors"];
|
||||
isEdit: boolean;
|
||||
locale?: string;
|
||||
}) {
|
||||
const nestedFields = def.fields ?? {};
|
||||
const displayName = name.split(".").pop() ?? name;
|
||||
return (
|
||||
<fieldset className="rounded border border-gray-200 bg-gray-50/50 p-4">
|
||||
<legend className="mb-3 text-sm font-medium text-gray-700">
|
||||
{displayName}
|
||||
</legend>
|
||||
<div className="space-y-4">
|
||||
{Object.entries(nestedFields).map(([subName, subDef]) => (
|
||||
<Field
|
||||
key={subName}
|
||||
name={`${name}.${subName}`}
|
||||
def={subDef as FieldDefinition}
|
||||
register={register}
|
||||
control={control}
|
||||
errors={errors}
|
||||
isEdit={isEdit}
|
||||
locale={locale}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</fieldset>
|
||||
);
|
||||
}
|
||||
|
||||
function Field({
|
||||
name,
|
||||
def,
|
||||
register,
|
||||
control,
|
||||
errors,
|
||||
isEdit,
|
||||
locale,
|
||||
}: {
|
||||
name: string;
|
||||
def: FieldDefinition;
|
||||
register: ReturnType<typeof useForm>["register"];
|
||||
control: ReturnType<typeof useForm>["control"];
|
||||
errors: ReturnType<typeof useForm>["formState"]["errors"];
|
||||
isEdit: boolean;
|
||||
locale?: string;
|
||||
}) {
|
||||
const type = (def.type ?? "string") as string;
|
||||
const required = !!def.required;
|
||||
const isSlug = name === "_slug";
|
||||
const readonly = isEdit && isSlug;
|
||||
const fieldError = getFieldError(errors as Record<string, unknown>, name);
|
||||
const fieldId = useId();
|
||||
|
||||
const fieldDescription = def.description ? (
|
||||
<p className="mt-0.5 text-xs text-gray-500">{def.description}</p>
|
||||
) : null;
|
||||
|
||||
const label = (
|
||||
<>
|
||||
<label className="mb-1 block text-sm font-bold text-gray-700">
|
||||
{name.split(".").pop()}
|
||||
{required && <span className="text-red-500"> *</span>}
|
||||
</label>
|
||||
{fieldDescription}
|
||||
</>
|
||||
);
|
||||
|
||||
if (type === "boolean") {
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-start gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
id={fieldId}
|
||||
{...register(name)}
|
||||
className="mt-0.5 h-5 w-5 rounded border-gray-300 focus:ring-gray-400"
|
||||
/>
|
||||
<label
|
||||
htmlFor={fieldId}
|
||||
className="cursor-pointer text-sm font-medium text-gray-700"
|
||||
>
|
||||
{name.split(".").pop()}
|
||||
{required && <span className="text-red-500"> *</span>}
|
||||
</label>
|
||||
</div>
|
||||
{fieldDescription}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (type === "number") {
|
||||
return (
|
||||
<div>
|
||||
{label}
|
||||
<input
|
||||
type="number"
|
||||
step="any"
|
||||
{...register(name, { valueAsNumber: true, required })}
|
||||
className="block w-full rounded border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900"
|
||||
/>
|
||||
{fieldError ? (
|
||||
<p className="mt-1 text-sm text-red-600">
|
||||
{String((fieldError as { message?: string })?.message)}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (type === "integer") {
|
||||
return (
|
||||
<div>
|
||||
{label}
|
||||
<input
|
||||
type="number"
|
||||
step={1}
|
||||
{...register(name, { valueAsNumber: true, required })}
|
||||
className="block w-full rounded border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900"
|
||||
/>
|
||||
{fieldError ? (
|
||||
<p className="mt-1 text-sm text-red-600">
|
||||
{String((fieldError as { message?: string })?.message)}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* Markdown: editor with live preview */
|
||||
if (type === "markdown") {
|
||||
return (
|
||||
<Controller
|
||||
name={name}
|
||||
control={control!}
|
||||
rules={{ required }}
|
||||
render={({ field }) => (
|
||||
<MarkdownEditor
|
||||
value={typeof field.value === "string" ? field.value : ""}
|
||||
onChange={field.onChange}
|
||||
label={label}
|
||||
error={fieldError}
|
||||
required={required}
|
||||
readOnly={readonly}
|
||||
rows={12}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/* Lange Texte: richtext, html → Textarea */
|
||||
if (type === "richtext" || type === "html") {
|
||||
return (
|
||||
<div>
|
||||
{label}
|
||||
<textarea
|
||||
{...register(name, { required })}
|
||||
rows={10}
|
||||
readOnly={readonly}
|
||||
className="block w-full rounded border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 font-mono"
|
||||
/>
|
||||
{fieldError ? (
|
||||
<p className="mt-1 text-sm text-red-600">
|
||||
{String((fieldError as { message?: string })?.message)}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (type === "datetime") {
|
||||
return (
|
||||
<div>
|
||||
{label}
|
||||
<input
|
||||
type="datetime-local"
|
||||
{...register(name, { required })}
|
||||
readOnly={readonly}
|
||||
className="block w-full rounded border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900"
|
||||
/>
|
||||
{fieldError ? (
|
||||
<p className="mt-1 text-sm text-red-600">
|
||||
{String((fieldError as { message?: string })?.message)}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (type === "array" && def.items?.type === "reference") {
|
||||
return (
|
||||
<Controller
|
||||
name={name}
|
||||
control={control!}
|
||||
rules={{ required }}
|
||||
render={({ field }) => (
|
||||
<ReferenceArrayField
|
||||
name={name}
|
||||
def={def}
|
||||
value={Array.isArray(field.value) ? field.value : []}
|
||||
onChange={field.onChange}
|
||||
required={required}
|
||||
error={fieldError}
|
||||
locale={locale}
|
||||
label={label}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (type === "reference") {
|
||||
return (
|
||||
<div>
|
||||
{label}
|
||||
<input
|
||||
type="text"
|
||||
{...register(name, { required })}
|
||||
placeholder="Slug of referenced entry"
|
||||
readOnly={readonly}
|
||||
className="block w-full rounded border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 font-mono"
|
||||
/>
|
||||
{fieldError ? (
|
||||
<p className="mt-1 text-sm text-red-600">
|
||||
{String((fieldError as { message?: string })?.message)}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* Nested objects (e.g. file.details, file.details.image) recursively as fieldset */
|
||||
if (type === "object" && def.fields) {
|
||||
return (
|
||||
<ObjectFieldSet
|
||||
name={name}
|
||||
def={def}
|
||||
register={register}
|
||||
control={control}
|
||||
errors={errors}
|
||||
isEdit={isEdit}
|
||||
locale={locale}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// string, default
|
||||
const enumValues = def.enum as string[] | undefined;
|
||||
if (Array.isArray(enumValues) && enumValues.length > 0) {
|
||||
return (
|
||||
<div>
|
||||
{label}
|
||||
<select
|
||||
{...register(name, { required })}
|
||||
className="block w-full rounded border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900"
|
||||
>
|
||||
<option value="">— Please select —</option>
|
||||
{enumValues.map((v) => (
|
||||
<option key={String(v)} value={String(v)}>
|
||||
{String(v)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{fieldError ? (
|
||||
<p className="mt-1 text-sm text-red-600">
|
||||
{String((fieldError as { message?: string })?.message)}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
{label}
|
||||
<input
|
||||
type="text"
|
||||
{...register(name, { required })}
|
||||
readOnly={readonly}
|
||||
className="block w-full rounded border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900"
|
||||
/>
|
||||
{fieldError ? (
|
||||
<p className="mt-1 text-sm text-red-600">
|
||||
{String((fieldError as { message?: string })?.message)}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
171
admin-ui/src/components/MarkdownEditor.tsx
Normal file
171
admin-ui/src/components/MarkdownEditor.tsx
Normal file
@@ -0,0 +1,171 @@
|
||||
"use client";
|
||||
|
||||
import { useId, useRef } from "react";
|
||||
import ReactMarkdown from "react-markdown";
|
||||
|
||||
type Props = {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
label: React.ReactNode;
|
||||
error?: unknown;
|
||||
required?: boolean;
|
||||
readOnly?: boolean;
|
||||
rows?: number;
|
||||
};
|
||||
|
||||
function wrapSelection(
|
||||
text: string,
|
||||
start: number,
|
||||
end: number,
|
||||
before: string,
|
||||
after: string
|
||||
): { newText: string; newStart: number; newEnd: number } {
|
||||
const sel = text.slice(start, end);
|
||||
const newText = text.slice(0, start) + before + sel + after + text.slice(end);
|
||||
return {
|
||||
newText,
|
||||
newStart: start + before.length,
|
||||
newEnd: end + before.length,
|
||||
};
|
||||
}
|
||||
|
||||
function insertAtCursor(
|
||||
text: string,
|
||||
start: number,
|
||||
end: number,
|
||||
placeholder: string,
|
||||
cursorAfter: number
|
||||
): { newText: string; newStart: number; newEnd: number } {
|
||||
const insert = start === end ? placeholder : text.slice(start, end);
|
||||
const newText = text.slice(0, start) + insert + text.slice(end);
|
||||
const newStart = start + (start === end ? cursorAfter : 0);
|
||||
const newEnd = start === end ? newStart : newStart + insert.length;
|
||||
return { newText, newStart, newEnd };
|
||||
}
|
||||
|
||||
export function MarkdownEditor({
|
||||
value,
|
||||
onChange,
|
||||
label,
|
||||
error,
|
||||
required,
|
||||
readOnly,
|
||||
rows = 12,
|
||||
}: Props) {
|
||||
const id = useId();
|
||||
const previewId = `${id}-preview`;
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
|
||||
const apply = (result: { newText: string; newStart: number; newEnd: number }) => {
|
||||
onChange(result.newText);
|
||||
requestAnimationFrame(() => {
|
||||
const el = textareaRef.current;
|
||||
if (el) {
|
||||
el.focus();
|
||||
el.setSelectionRange(result.newStart, result.newEnd);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const handleToolbar = (before: string, after: string, placeholder = "Text") => {
|
||||
const el = textareaRef.current;
|
||||
if (!el || readOnly) return;
|
||||
const start = el.selectionStart;
|
||||
const end = el.selectionEnd;
|
||||
const result = wrapSelection(el.value, start, end, before, after);
|
||||
if (start === end) {
|
||||
result.newEnd = result.newStart + placeholder.length;
|
||||
}
|
||||
apply(result);
|
||||
};
|
||||
|
||||
const handleInsert = (placeholder: string, cursorOffset: number) => {
|
||||
const el = textareaRef.current;
|
||||
if (!el || readOnly) return;
|
||||
const start = el.selectionStart;
|
||||
const end = el.selectionEnd;
|
||||
apply(insertAtCursor(el.value, start, end, placeholder, cursorOffset));
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
{label}
|
||||
{!readOnly && (
|
||||
<div className="mb-1 flex flex-wrap items-center gap-1 rounded border border-gray-200 bg-gray-100 px-2 py-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleToolbar("**", "**", "bold")}
|
||||
className="rounded px-2 py-1 text-sm font-bold text-gray-700 hover:bg-gray-200"
|
||||
title="Bold"
|
||||
>
|
||||
B
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleToolbar("*", "*", "italic")}
|
||||
className="rounded px-2 py-1 text-sm italic text-gray-700 hover:bg-gray-200"
|
||||
title="Italic"
|
||||
>
|
||||
I
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleToolbar("`", "`", "code")}
|
||||
className="rounded px-2 py-1 font-mono text-sm text-gray-700 hover:bg-gray-200"
|
||||
title="Code"
|
||||
>
|
||||
</>
|
||||
</button>
|
||||
<button
|
||||
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"
|
||||
>
|
||||
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"
|
||||
>
|
||||
• List
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
id={id}
|
||||
value={value ?? ""}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
rows={rows}
|
||||
readOnly={readOnly}
|
||||
required={required}
|
||||
aria-describedby={previewId}
|
||||
placeholder="Enter markdown… **bold**, *italic*, [link](url), - list"
|
||||
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 ? (
|
||||
<p className="mt-1 text-sm text-red-600">
|
||||
{String((error as { message?: string })?.message)}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="mt-3">
|
||||
<span className="mb-1 block text-xs font-medium text-gray-500">
|
||||
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"
|
||||
>
|
||||
{(value ?? "").trim() ? (
|
||||
<ReactMarkdown>{value}</ReactMarkdown>
|
||||
) : (
|
||||
<span className="text-gray-400">Empty — preview appears as you type.</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
361
admin-ui/src/components/ReferenceArrayField.tsx
Normal file
361
admin-ui/src/components/ReferenceArrayField.tsx
Normal file
@@ -0,0 +1,361 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { fetchContentList, fetchCollections } from "@/lib/api";
|
||||
import type { FieldDefinition } from "@/lib/api";
|
||||
|
||||
type Props = {
|
||||
name: string;
|
||||
def: FieldDefinition;
|
||||
value: string[] | string;
|
||||
onChange: (value: string[]) => void;
|
||||
required?: boolean;
|
||||
error?: unknown;
|
||||
locale?: string;
|
||||
label: React.ReactNode;
|
||||
};
|
||||
|
||||
/** Referenced collection(s) from schema: single collection or list for polymorphic. */
|
||||
function getCollections(def: FieldDefinition): string[] {
|
||||
const items = def.items as FieldDefinition | undefined;
|
||||
if (!items) return [];
|
||||
if (items.collection) return [items.collection];
|
||||
if (Array.isArray(items.collections) && items.collections.length > 0)
|
||||
return items.collections;
|
||||
return [];
|
||||
}
|
||||
|
||||
export function ReferenceArrayField({
|
||||
name,
|
||||
def,
|
||||
value,
|
||||
onChange,
|
||||
required,
|
||||
error,
|
||||
locale,
|
||||
label,
|
||||
}: Props) {
|
||||
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)
|
||||
: [];
|
||||
|
||||
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 };
|
||||
const options: OptionItem[] =
|
||||
multipleCollections.length > 1 && multiQueries.data
|
||||
? multiQueries.data.flatMap(({ collection: coll, items }) =>
|
||||
(items as { _slug?: string }[])
|
||||
.map((o) => ({
|
||||
slug: String(o._slug ?? ""),
|
||||
collection: coll,
|
||||
}))
|
||||
.filter((o) => o.slug),
|
||||
)
|
||||
: ((singleQuery.data?.items ?? []) as { _slug?: string }[])
|
||||
.map((o) => ({
|
||||
slug: String(o._slug ?? ""),
|
||||
collection: effectiveCollection ?? "",
|
||||
}))
|
||||
.filter((o) => o.slug);
|
||||
|
||||
const isLoading =
|
||||
schemaCollections.length <= 1
|
||||
? singleQuery.isLoading
|
||||
: multiQueries.isLoading;
|
||||
|
||||
const add = (slug: string) => {
|
||||
if (!slug || valueList.includes(slug)) return;
|
||||
onChange([...valueList, slug]);
|
||||
};
|
||||
|
||||
const addFromOption = (optionValue: string) => {
|
||||
const slug = optionValue.includes(":")
|
||||
? optionValue.split(":")[1]!
|
||||
: optionValue;
|
||||
add(slug);
|
||||
};
|
||||
|
||||
const remove = (index: number) => {
|
||||
onChange(valueList.filter((_, i) => i !== index));
|
||||
};
|
||||
|
||||
const move = (index: number, dir: number) => {
|
||||
const next = index + dir;
|
||||
if (next < 0 || next >= valueList.length) return;
|
||||
const copy = [...valueList];
|
||||
const tmp = copy[index];
|
||||
copy[index] = copy[next];
|
||||
copy[next] = tmp;
|
||||
onChange(copy);
|
||||
};
|
||||
|
||||
const collectionsForNew =
|
||||
multipleCollections.length > 1
|
||||
? multipleCollections
|
||||
: effectiveCollection
|
||||
? [effectiveCollection]
|
||||
: [];
|
||||
|
||||
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
|
||||
? `Typ: ${schemaCollections[0]}`
|
||||
: `Typen: ${schemaCollections.join(", ")}`}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{/* Selected entries */}
|
||||
<ul className="mb-2 space-y-1.5">
|
||||
{valueList.map((slug, index) => (
|
||||
<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">
|
||||
<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"
|
||||
>
|
||||
<svg
|
||||
className="h-4 w-4"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M5 15l7-7 7 7"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
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"
|
||||
>
|
||||
<svg
|
||||
className="h-4 w-4"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M19 9l-7 7-7-7"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
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"
|
||||
>
|
||||
<svg
|
||||
className="h-4 w-4"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M6 18L18 6M6 6l12 12"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
{/* Without schema collection: choose component type first */}
|
||||
{!singleCollection &&
|
||||
schemaCollections.length === 0 &&
|
||||
availableCollections.length > 0 ? (
|
||||
<div className="mb-2">
|
||||
<label className="mb-1 block text-xs font-medium text-gray-500">
|
||||
Component type
|
||||
</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>
|
||||
</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>
|
||||
{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>
|
||||
) : (
|
||||
<select
|
||||
className="rounded border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900"
|
||||
value=""
|
||||
onChange={(e) => {
|
||||
const c = e.target.value;
|
||||
if (c)
|
||||
window.open(
|
||||
`/content/${c}/new${locale ? `?_locale=${locale}` : ""}`,
|
||||
"_blank",
|
||||
);
|
||||
e.target.value = "";
|
||||
}}
|
||||
>
|
||||
<option value="">+ Create new component…</option>
|
||||
{collectionsForNew.map((c) => (
|
||||
<option key={c} value={c}>
|
||||
{c}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
<span className="text-xs text-gray-500">
|
||||
Open in new tab; then reload this page.
|
||||
</span>
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{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.
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{error ? (
|
||||
<p className="mt-1 text-sm text-red-600">
|
||||
{String((error as { message?: string })?.message ?? error)}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
125
admin-ui/src/components/Sidebar.tsx
Normal file
125
admin-ui/src/components/Sidebar.tsx
Normal file
@@ -0,0 +1,125 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useMemo } from "react";
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useQueries, useQuery } from "@tanstack/react-query";
|
||||
import { fetchCollections, fetchContentList } from "@/lib/api";
|
||||
|
||||
export function Sidebar() {
|
||||
const pathname = usePathname();
|
||||
const [search, setSearch] = useState("");
|
||||
const { data, isLoading, error } = useQuery({
|
||||
queryKey: ["collections"],
|
||||
queryFn: fetchCollections,
|
||||
});
|
||||
|
||||
const filteredCollections = useMemo(() => {
|
||||
const list = data?.collections ?? [];
|
||||
if (!search.trim()) return list;
|
||||
const q = search.trim().toLowerCase();
|
||||
return list.filter(
|
||||
(c) =>
|
||||
c.name.toLowerCase().includes(q) ||
|
||||
(c.category?.toLowerCase().includes(q) ?? false) ||
|
||||
(c.tags?.some((t) => t.toLowerCase().includes(q)) ?? false) ||
|
||||
(c.description?.toLowerCase().includes(q) ?? false)
|
||||
);
|
||||
}, [data?.collections, search]);
|
||||
|
||||
const countQueries = useQueries({
|
||||
queries: filteredCollections.map((c) => ({
|
||||
queryKey: ["contentCount", c.name],
|
||||
queryFn: () =>
|
||||
fetchContentList(c.name, { _per_page: 1 }).then((r) => r.total),
|
||||
staleTime: 60_000,
|
||||
})),
|
||||
});
|
||||
|
||||
const formatCount = (n: number) => (n >= 100 ? "99+" : String(n));
|
||||
|
||||
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">
|
||||
<input
|
||||
type="search"
|
||||
placeholder="Search collections…"
|
||||
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"
|
||||
/>
|
||||
</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">
|
||||
{c.category && (
|
||||
<span className="rounded bg-gray-200 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>
|
||||
</nav>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
222
admin-ui/src/lib/api.ts
Normal file
222
admin-ui/src/lib/api.ts
Normal file
@@ -0,0 +1,222 @@
|
||||
/**
|
||||
* RustyCMS API client. Base URL from NEXT_PUBLIC_RUSTYCMS_API_URL.
|
||||
* Optional RUSTYCMS_API_KEY for write operations (sent as X-API-Key).
|
||||
*/
|
||||
|
||||
const getBaseUrl = () =>
|
||||
process.env.NEXT_PUBLIC_RUSTYCMS_API_URL || "http://127.0.0.1:3000";
|
||||
|
||||
const getHeaders = (): HeadersInit => {
|
||||
const headers: HeadersInit = {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
};
|
||||
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;
|
||||
if (key) headers["X-API-Key"] = key;
|
||||
return headers;
|
||||
};
|
||||
|
||||
export type CollectionMeta = {
|
||||
name: string;
|
||||
description?: string;
|
||||
tags?: string[];
|
||||
category?: string;
|
||||
field_count?: number;
|
||||
extends?: string | string[];
|
||||
strict?: boolean;
|
||||
};
|
||||
|
||||
export type CollectionsResponse = {
|
||||
collections: CollectionMeta[];
|
||||
};
|
||||
|
||||
export type FieldDefinition = {
|
||||
type: string;
|
||||
required?: boolean;
|
||||
description?: string;
|
||||
collection?: string;
|
||||
collections?: string[];
|
||||
enum?: unknown[];
|
||||
default?: unknown;
|
||||
items?: FieldDefinition;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
|
||||
export type SchemaDefinition = {
|
||||
name: string;
|
||||
description?: string;
|
||||
tags?: string[];
|
||||
category?: string;
|
||||
fields: Record<string, FieldDefinition>;
|
||||
extends?: string | string[];
|
||||
reusable?: boolean;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
|
||||
export type ListResponse<T = Record<string, unknown>> = {
|
||||
items: T[];
|
||||
total: number;
|
||||
page: number;
|
||||
per_page: number;
|
||||
total_pages: number;
|
||||
};
|
||||
|
||||
export async function fetchCollections(): Promise<CollectionsResponse> {
|
||||
const res = await fetch(`${getBaseUrl()}/api/collections`, {
|
||||
headers: getHeaders(),
|
||||
});
|
||||
if (!res.ok) throw new Error(`Collections: ${res.status}`);
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export async function fetchSchema(
|
||||
collection: string
|
||||
): Promise<SchemaDefinition> {
|
||||
const res = await fetch(
|
||||
`${getBaseUrl()}/api/collections/${encodeURIComponent(collection)}`,
|
||||
{ headers: getHeaders() }
|
||||
);
|
||||
if (!res.ok) throw new Error(`Schema ${collection}: ${res.status}`);
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export async function createSchema(
|
||||
schema: SchemaDefinition
|
||||
): Promise<SchemaDefinition> {
|
||||
const res = await fetch(`${getBaseUrl()}/api/schemas`, {
|
||||
method: "POST",
|
||||
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(", ") ?? `Schema: ${res.status}`;
|
||||
throw new Error(msg);
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export type SlugCheckResponse = {
|
||||
valid: boolean;
|
||||
normalized: string;
|
||||
available: boolean;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
export async function checkSlug(
|
||||
collection: string,
|
||||
slug: string,
|
||||
params: { exclude?: string; _locale?: string } = {}
|
||||
): Promise<SlugCheckResponse> {
|
||||
const sp = new URLSearchParams({ slug: slug.trim() });
|
||||
if (params.exclude) sp.set("exclude", params.exclude);
|
||||
if (params._locale) sp.set("_locale", params._locale);
|
||||
const res = await fetch(
|
||||
`${getBaseUrl()}/api/collections/${encodeURIComponent(collection)}/slug-check?${sp}`,
|
||||
{ headers: getHeaders() }
|
||||
);
|
||||
if (!res.ok) throw new Error(`Slug-Check: ${res.status}`);
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export type ContentListParams = {
|
||||
_page?: number;
|
||||
_per_page?: number;
|
||||
_sort?: string;
|
||||
_order?: "asc" | "desc";
|
||||
_resolve?: string;
|
||||
_locale?: string;
|
||||
[key: string]: string | number | undefined;
|
||||
};
|
||||
|
||||
export async function fetchContentList<T = Record<string, unknown>>(
|
||||
collection: string,
|
||||
params: ContentListParams = {}
|
||||
): Promise<ListResponse<T>> {
|
||||
const sp = new URLSearchParams();
|
||||
Object.entries(params).forEach(([k, v]) => {
|
||||
if (v !== undefined && v !== "") sp.set(k, String(v));
|
||||
});
|
||||
const qs = sp.toString();
|
||||
const url = `${getBaseUrl()}/api/content/${encodeURIComponent(collection)}${qs ? `?${qs}` : ""}`;
|
||||
const res = await fetch(url, { headers: getHeaders() });
|
||||
if (!res.ok) throw new Error(`List ${collection}: ${res.status}`);
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export async function fetchEntry<T = Record<string, unknown>>(
|
||||
collection: string,
|
||||
slug: string,
|
||||
params: { _resolve?: string; _locale?: string } = {}
|
||||
): Promise<T> {
|
||||
const sp = new URLSearchParams();
|
||||
if (params._resolve) sp.set("_resolve", params._resolve);
|
||||
if (params._locale) sp.set("_locale", params._locale);
|
||||
const qs = sp.toString();
|
||||
const url = `${getBaseUrl()}/api/content/${encodeURIComponent(collection)}/${encodeURIComponent(slug)}${qs ? `?${qs}` : ""}`;
|
||||
const res = await fetch(url, { headers: getHeaders() });
|
||||
if (!res.ok) throw new Error(`Entry ${collection}/${slug}: ${res.status}`);
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export async function createEntry(
|
||||
collection: string,
|
||||
data: Record<string, unknown>,
|
||||
params: { _locale?: string } = {}
|
||||
): Promise<Record<string, unknown>> {
|
||||
const sp = new URLSearchParams();
|
||||
if (params._locale) sp.set("_locale", params._locale);
|
||||
const qs = sp.toString();
|
||||
const url = `${getBaseUrl()}/api/content/${encodeURIComponent(collection)}${qs ? `?${qs}` : ""}`;
|
||||
const res = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: getHeaders(),
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error((err as { message?: string }).message || `Create: ${res.status}`);
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export async function updateEntry(
|
||||
collection: string,
|
||||
slug: string,
|
||||
data: Record<string, unknown>,
|
||||
params: { _locale?: string } = {}
|
||||
): Promise<Record<string, unknown>> {
|
||||
const sp = new URLSearchParams();
|
||||
if (params._locale) sp.set("_locale", params._locale);
|
||||
const qs = sp.toString();
|
||||
const url = `${getBaseUrl()}/api/content/${encodeURIComponent(collection)}/${encodeURIComponent(slug)}${qs ? `?${qs}` : ""}`;
|
||||
const res = await fetch(url, {
|
||||
method: "PUT",
|
||||
headers: getHeaders(),
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error((err as { message?: string }).message || `Update: ${res.status}`);
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export async function deleteEntry(
|
||||
collection: string,
|
||||
slug: string,
|
||||
params: { _locale?: string } = {}
|
||||
): Promise<void> {
|
||||
const sp = new URLSearchParams();
|
||||
if (params._locale) sp.set("_locale", params._locale);
|
||||
const qs = sp.toString();
|
||||
const url = `${getBaseUrl()}/api/content/${encodeURIComponent(collection)}/${encodeURIComponent(slug)}${qs ? `?${qs}` : ""}`;
|
||||
const res = await fetch(url, {
|
||||
method: "DELETE",
|
||||
headers: getHeaders(),
|
||||
});
|
||||
if (!res.ok) throw new Error(`Delete: ${res.status}`);
|
||||
}
|
||||
34
admin-ui/tsconfig.json
Normal file
34
admin-ui/tsconfig.json
Normal file
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2017",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "react-jsx",
|
||||
"incremental": true,
|
||||
"plugins": [
|
||||
{
|
||||
"name": "next"
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
},
|
||||
"include": [
|
||||
"next-env.d.ts",
|
||||
"**/*.ts",
|
||||
"**/*.tsx",
|
||||
".next/types/**/*.ts",
|
||||
".next/dev/types/**/*.ts",
|
||||
"**/*.mts"
|
||||
],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
Reference in New Issue
Block a user