RustyCMS: File-based headless CMS with REST API, admin UI, multilingual support

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Peter Meier
2026-02-16 09:30:30 +01:00
commit aad93d145f
224 changed files with 19225 additions and 0 deletions

View 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>
);
}

View 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"
>
&lt;/&gt;
</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>
);
}

View 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>
);
}

View 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>
);
}