Add the admin panel for managing site content

Server-rendered CMS at /admin, reachable only with an authenticated admin.
There was no way to change anything on the site without a database session,
while every mutating endpoint used to be anonymous, so the site was either
unmanageable or, before the API lock-down, wide open.

Everything runs through Server Actions, so the httpOnly
parsaaghayi_admin_session cookie set by the backend is read server-side and
forwarded as a bearer token. No token ever reaches client JavaScript and the
browser never talks to the backend cross-origin, so CORS and CSRF do not
apply. Unauthenticated visits to any panel route redirect to /admin/login.

Resources are declared once in a registry (src/app/lib/admin/resources.ts)
and the list, create and edit screens are generated from it, so adding a
content type is a data change rather than three new pages. Covered: posts,
categories, tags, projects, about-me.

Records are read from GET /api/admin/resources/{resource}, which returns
stored rows including every locale; the public endpoints only expose
translated display payloads and cannot populate an editing form.

Verified: tsc --noEmit clean, eslint clean, next build compiles and registers
all five admin routes as dynamic, and /admin, /admin/posts redirect 307 to
/admin/login while /admin/login renders.

Post bodies are rendered as text nodes, never as HTML.
This commit is contained in:
root committed 2026-10-01 16:01:40 -04:00
1 parent 76cf4da118
commit 2b7eda656a
16 files changed
+1242

No files matched your search

+121
View File
@@ -0,0 +1,121 @@
'use server';
import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
import { AdminApiError, adminFetch, currentAdmin, loginAdmin, logoutAdmin } from './api';
import { RESOURCE_BY_SLUG, type ResourceDef } from './resources';
import type { FormState } from './format';
function message(error: unknown): string {
if (error instanceof AdminApiError) return error.message;
return 'خطای پیش‌بینی‌نشده رخ داد.';
}
function require(slug: string): ResourceDef {
const resource = RESOURCE_BY_SLUG[slug];
if (!resource) throw new AdminApiError('منبع نامعتبر است.', 404);
return resource;
}
/** Fields the API requires that the form should not make the author supply. */
function implicitFields(resource: ResourceDef, adminId: number): Record<string, unknown> {
if (resource.slug === 'posts') return { author_id: adminId };
return {};
}
function collect(formData: FormData, resource: ResourceDef, adminId: number): Record<string, unknown> {
const payload: Record<string, unknown> = implicitFields(resource, adminId);
for (const field of resource.fields) {
if (field.kind === 'multiselect') {
const values = formData.getAll(field.name).map(Number).filter((id) => Number.isFinite(id));
if (values.length > 0) payload[field.name] = values;
continue;
}
const raw = formData.get(field.name);
if (raw === null || raw === '') continue;
const value = typeof raw === 'string' ? raw.trim() : raw;
if (field.kind === 'number') {
payload[field.name] = Number(value);
continue;
}
if (field.kind === 'datetime') {
payload[field.name] = new Date(String(value)).toISOString();
continue;
}
payload[field.name] = value;
}
return payload;
}
export async function loginAction(_previous: FormState, formData: FormData): Promise<FormState> {
const email = String(formData.get('email') ?? '').trim();
const password = String(formData.get('password') ?? '');
const remember = formData.get('remember') === 'on';
if (!email || !password) return { error: 'ایمیل و گذرواژه الزامی است.' };
try {
await loginAdmin(email, password, remember);
} catch (error) {
return { error: message(error) };
}
redirect('/admin');
}
export async function logoutAction(): Promise<void> {
await logoutAdmin();
redirect('/admin/login');
}
export async function saveResourceAction(
_previous: FormState,
formData: FormData,
): Promise<FormState> {
const resource = require(String(formData.get('__resource') ?? ''));
const recordId = String(formData.get('__id') ?? '');
const admin = await currentAdmin();
if (!admin) return { error: 'نشست مدیریتی برقرار نیست.' };
const payload = collect(formData, resource, admin.id);
const isUpdate = recordId !== '';
try {
await adminFetch(isUpdate ? `${resource.basePath}/${recordId}` : resource.basePath, {
method: isUpdate ? 'PUT' : 'POST',
body: payload,
});
} catch (error) {
return { error: message(error) };
}
revalidatePath('/admin', 'layout');
redirect(`/admin/${resource.slug}`);
}
export async function deleteResourceAction(formData: FormData): Promise<void> {
const resource = require(String(formData.get('__resource') ?? ''));
const recordId = String(formData.get('__id') ?? '');
if (!recordId || !resource.supportsDelete) return;
await adminFetch(`${resource.basePath}/${recordId}`, { method: 'DELETE' });
revalidatePath('/admin', 'layout');
redirect(`/admin/${resource.slug}`);
}
+179
View File
@@ -0,0 +1,179 @@
import { cookies } from 'next/headers';
export const ADMIN_COOKIE = 'parsaaghayi_admin_session';
const BACKEND = process.env.NEXT_PUBLIC_BACK_URL || 'https://backend.parsaaghayi.ir';
export type AdminUser = {
id: number;
name: string;
email: string;
is_admin: boolean;
created_at: string;
updated_at: string;
};
export class AdminApiError extends Error {
status: number;
constructor(message: string, status: number) {
super(message);
this.name = 'AdminApiError';
this.status = status;
}
}
export function cookieDomain(): string | undefined {
const host = (() => {
try {
return new URL(process.env.NEXT_PUBLIC_FRONT_URL || 'https://parsaaghayi.ir').hostname;
} catch {
return '';
}
})();
if (!host || host === 'localhost' || host === '127.0.0.1') return undefined;
return host.startsWith('www.') ? `.${host.slice(4)}` : `.${host}`;
}
export async function adminToken(): Promise<string | null> {
const jar = await cookies();
return jar.get(ADMIN_COOKIE)?.value ?? null;
}
function readSetCookie(response: Response, name: string): string | null {
const lines =
typeof response.headers.getSetCookie === 'function' ? response.headers.getSetCookie() : [];
const line = lines.find((entry) => entry.startsWith(`${name}=`));
if (!line) return null;
return decodeURIComponent(line.slice(name.length + 1).split(';')[0] ?? '');
}
function messageFrom(payload: unknown, fallback: string): string {
if (payload && typeof payload === 'object') {
const errors = (payload as { errors?: Record<string, string[]> }).errors;
const first = errors ? Object.values(errors)[0]?.[0] : undefined;
if (first) return first;
const message = (payload as { message?: string }).message;
if (message) return message;
}
return fallback;
}
type AdminFetchOptions = {
method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
body?: unknown;
};
export async function adminFetch<T>(path: string, options: AdminFetchOptions = {}): Promise<T> {
const { method = 'GET', body } = options;
const token = await adminToken();
if (!token) throw new AdminApiError('نشست مدیریتی برقرار نیست.', 401);
const headers: Record<string, string> = {
Accept: 'application/json',
Authorization: `Bearer ${token}`,
};
if (body !== undefined) headers['Content-Type'] = 'application/json';
const response = await fetch(`${BACKEND}/api${path}`, {
method,
headers,
body: body === undefined ? undefined : JSON.stringify(body),
cache: 'no-store',
});
const text = await response.text();
const payload: unknown = text ? safeJson(text) : null;
if (!response.ok) {
throw new AdminApiError(messageFrom(payload, `درخواست با خطا مواجه شد (${response.status}).`), response.status);
}
return payload as T;
}
function safeJson(text: string): unknown {
try {
return JSON.parse(text);
} catch {
return null;
}
}
export async function listRows<T>(path: string): Promise<T[]> {
const payload = await adminFetch<{ data?: T[] } | T[]>(path);
return Array.isArray(payload) ? payload : (payload?.data ?? []);
}
export async function loginAdmin(email: string, password: string, remember: boolean): Promise<AdminUser> {
const response = await fetch(`${BACKEND}/api/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify({ email, password, remember }),
cache: 'no-store',
});
const text = await response.text();
const payload: unknown = text ? safeJson(text) : null;
if (!response.ok) {
throw new AdminApiError(
messageFrom(payload, 'ورود ناموفق بود. ایمیل یا گذرواژه نادرست است.'),
response.status,
);
}
const token = readSetCookie(response, ADMIN_COOKIE);
if (!token) throw new AdminApiError('توکن نشست از سمت سرور دریافت نشد.', 500);
const jar = await cookies();
jar.set(ADMIN_COOKIE, token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
path: '/',
domain: cookieDomain(),
maxAge: remember ? 60 * 60 * 24 * 14 : undefined,
});
return (payload as { user: AdminUser }).user;
}
export async function logoutAdmin(): Promise<void> {
try {
await adminFetch('/auth/logout', { method: 'POST' });
} finally {
const jar = await cookies();
jar.delete(ADMIN_COOKIE);
}
}
export async function currentAdmin(): Promise<AdminUser | null> {
const token = await adminToken();
if (!token) return null;
try {
const response = await fetch(`${BACKEND}/api/auth/me`, {
headers: { Accept: 'application/json', Authorization: `Bearer ${token}` },
cache: 'no-store',
});
if (!response.ok) return null;
const payload = (await response.json()) as { user: AdminUser };
return payload.user ?? null;
} catch {
return null;
}
}
+36
View File
@@ -0,0 +1,36 @@
export type FormState = { error: string | null };
export const EMPTY_STATE: FormState = { error: null };
export function toDateTimeInput(value: unknown): string {
if (typeof value !== 'string' || value === '') return '';
const parsed = new Date(value);
if (Number.isNaN(parsed.getTime())) return '';
const pad = (input: number) => String(input).padStart(2, '0');
return `${parsed.getFullYear()}-${pad(parsed.getMonth() + 1)}-${pad(parsed.getDate())}T${pad(
parsed.getHours(),
)}:${pad(parsed.getMinutes())}`;
}
export function formatDate(value: unknown): string {
if (typeof value !== 'string' || value === '') return '—';
const parsed = new Date(value);
if (Number.isNaN(parsed.getTime())) return String(value);
return new Intl.DateTimeFormat('fa-IR', { dateStyle: 'medium' }).format(parsed);
}
export function textValue(value: unknown): string {
if (value === null || value === undefined) return '';
if (Array.isArray(value)) return value.join('، ');
if (typeof value === 'object') return JSON.stringify(value);
return String(value);
}
+38
View File
@@ -0,0 +1,38 @@
import { listRows } from './api';
import {
RESOURCE_BY_SLUG,
optionLabel,
type AdminRow,
type OptionRow,
type ResourceDef,
} from './resources';
export async function loadRows(slug: string): Promise<AdminRow[]> {
return listRows<AdminRow>(`/admin/resources/${slug}`);
}
export function optionSources(resource: ResourceDef): string[] {
const sources = resource.fields
.map((field) => field.optionsFrom)
.filter((source): source is NonNullable<typeof source> => Boolean(source));
return Array.from(new Set(sources));
}
export async function loadOptions(sources: string[]): Promise<Record<string, OptionRow[]>> {
const entries = await Promise.all(
sources.map(async (source) => {
const rows = await loadRows(source);
const definition = RESOURCE_BY_SLUG[source];
const options = rows.map((row) => ({
id: row.id,
label: definition ? optionLabel(row, definition) : String(row.id),
}));
return [source, options] as const;
}),
);
return Object.fromEntries(entries);
}
+49
View File
@@ -0,0 +1,49 @@
'use client';
import { useActionState } from 'react';
import { loginAction } from './actions';
import { EMPTY_STATE } from './format';
import { Alert, Button, Field, inputClass } from './ui';
export default function LoginForm() {
const [state, formAction, isPending] = useActionState(loginAction, EMPTY_STATE);
return (
<form action={formAction} className="flex flex-col gap-5">
{state.error ? <Alert tone="error">{state.error}</Alert> : null}
<Field label="ایمیل" htmlFor="email" required>
<input
id="email"
name="email"
type="email"
autoComplete="username"
required
dir="ltr"
className={inputClass}
/>
</Field>
<Field label="گذرواژه" htmlFor="password" required>
<input
id="password"
name="password"
type="password"
autoComplete="current-password"
required
dir="ltr"
className={inputClass}
/>
</Field>
<label className="flex items-center gap-2 text-sm text-muted-foreground">
<input type="checkbox" name="remember" className="h-4 w-4 accent-primary" />
مرا به خاطر بسپار
</label>
<Button type="submit" disabled={isPending} className="w-full">
{isPending ? 'در حال ورود…' : 'ورود'}
</Button>
</form>
);
}
+168
View File
@@ -0,0 +1,168 @@
'use client';
import { useActionState } from 'react';
import { EMPTY_STATE, toDateTimeInput } from './format';
import { saveResourceAction } from './actions';
import type { AdminRow, FieldDef, OptionRow, ResourceDef } from './resources';
import { Alert, Button, Field, inputClass } from './ui';
const LOCALE_TITLES: Record<string, string> = {
fa: 'نسخه فارسی',
en: 'English version',
};
function initialValue(row: AdminRow | null, field: FieldDef): string | string[] {
if (!row) return field.kind === 'multiselect' ? [] : '';
if (field.kind === 'multiselect') {
const selected = row[field.name];
if (Array.isArray(selected)) {
return selected.map((entry) =>
String(typeof entry === 'object' && entry !== null ? (entry as { id: number }).id : entry),
);
}
return [];
}
if (field.localeGroup) {
const translations = (row.translations ?? {}) as Record<string, Record<string, string> | undefined>;
const key = field.name.replace(/_(fa|en)$/, '');
return String(translations[key]?.[field.localeGroup] ?? '');
}
const value = row[field.name];
if (field.kind === 'datetime') return toDateTimeInput(value);
if (value === null || value === undefined) return '';
if (Array.isArray(value)) return value.join('، ');
if (typeof value === 'object') return JSON.stringify(value);
return String(value);
}
export default function ResourceForm({
resource,
row,
options,
}: {
resource: ResourceDef;
row: AdminRow | null;
options: Record<string, OptionRow[]>;
}) {
const [state, formAction, isPending] = useActionState(saveResourceAction, EMPTY_STATE);
const ungrouped = resource.fields.filter((field) => !field.localeGroup);
const locales = Array.from(
new Set(resource.fields.map((field) => field.localeGroup).filter(Boolean)),
) as string[];
const renderField = (field: FieldDef) => {
const id = `field-${field.name}`;
const value = initialValue(row, field);
if (field.kind === 'select') {
return (
<Field key={field.name} label={field.label} htmlFor={id} help={field.help} required={field.required}>
<select id={id} name={field.name} defaultValue={value} className={inputClass} required={field.required}>
<option value="">انتخاب کنید…</option>
{(options[field.optionsFrom ?? ''] ?? []).map((option) => (
<option key={option.id} value={option.id}>
{option.label}
</option>
))}
</select>
</Field>
);
}
if (field.kind === 'multiselect') {
return (
<Field key={field.name} label={field.label} htmlFor={id} help={field.help}>
<select
id={id}
name={field.name}
multiple
defaultValue={value as string[]}
size={Math.min(8, Math.max(3, (options[field.optionsFrom ?? ''] ?? []).length))}
className={inputClass}
>
{(options[field.optionsFrom ?? ''] ?? []).map((option) => (
<option key={option.id} value={option.id}>
{option.label}
</option>
))}
</select>
</Field>
);
}
if (field.kind === 'textarea') {
return (
<Field key={field.name} label={field.label} htmlFor={id} help={field.help} required={field.required}>
<textarea
id={id}
name={field.name}
rows={field.rows ?? 4}
defaultValue={value as string}
placeholder={field.placeholder}
required={field.required}
className={`${inputClass} font-mono text-[13px] leading-7`}
/>
</Field>
);
}
return (
<Field key={field.name} label={field.label} htmlFor={id} help={field.help} required={field.required}>
<input
id={id}
name={field.name}
type={field.kind === 'number' ? 'number' : field.kind === 'datetime' ? 'datetime-local' : 'text'}
defaultValue={value as string}
placeholder={field.placeholder}
required={field.required}
dir={field.localeGroup === 'en' ? 'ltr' : undefined}
className={inputClass}
/>
</Field>
);
};
return (
<form action={formAction} className="flex flex-col gap-6">
<input type="hidden" name="__resource" value={resource.slug} />
<input type="hidden" name="__id" value={row ? String(row.id) : ''} />
{state.error ? <Alert tone="error">{state.error}</Alert> : null}
<div className="flex flex-col gap-6">
{ungrouped.map(renderField)}
{locales.map((locale) => (
<section key={locale} className="flex flex-col gap-5 rounded-2xl border border-border p-5">
<h2 className="text-sm font-semibold text-foreground">{LOCALE_TITLES[locale] ?? locale}</h2>
{resource.fields.filter((field) => field.localeGroup === locale).map(renderField)}
</section>
))}
</div>
<div className="flex items-center gap-3">
<Button type="submit" disabled={isPending}>
{isPending ? 'در حال ذخیره…' : row ? 'ذخیره تغییرات' : 'ایجاد'}
</Button>
<a
href={`/admin/${resource.slug}`}
className="text-sm text-muted-foreground underline-offset-4 hover:underline"
>
انصراف
</a>
</div>
</form>
);
}
+224
View File
@@ -0,0 +1,224 @@
export type FieldKind =
| 'text'
| 'textarea'
| 'number'
| 'url'
| 'datetime'
| 'select'
| 'multiselect';
export type FieldDef = {
name: string;
label: string;
kind: FieldKind;
required?: boolean;
help?: string;
rows?: number;
placeholder?: string;
/** Resource whose rows populate a select or multiselect. */
optionsFrom?: 'categories' | 'tags' | 'project-categories';
/** Half of the site is Persian and half is English; these fields repeat per locale. */
localeGroup?: string;
};
export type ResourceDef = {
slug: string;
title: string;
singular: string;
/** Base path of the write API, e.g. /blog/posts */
basePath: string;
fields: FieldDef[];
listColumns: { key: string; label: string }[];
labelField: string;
supportsCreate?: boolean;
supportsDelete?: boolean;
/** Show a create form and an "add" button. */
hint?: string;
};
export const RESOURCES: ResourceDef[] = [
{
slug: 'posts',
title: 'نوشته‌ها',
singular: 'نوشته',
basePath: '/blog/posts',
labelField: 'title',
supportsCreate: true,
supportsDelete: true,
hint: 'متن کامل نوشته در فیلد «متن نوشته» قرار می‌گیرد و در صفحه عمومی نمایش داده می‌شود.',
listColumns: [
{ key: 'title', label: 'عنوان' },
{ key: 'slug', label: 'نشانی' },
{ key: 'category_id', label: 'دسته' },
{ key: 'published_at', label: 'انتشار' },
],
fields: [
{ name: 'title', label: 'عنوان', kind: 'text', required: true },
{ name: 'slug', label: 'نشانی (slug)', kind: 'text', required: true, help: 'فقط حروف کوچک لاتین، عدد و خط تیره.' },
{
name: 'category_id',
label: 'دسته‌بندی',
kind: 'select',
required: true,
optionsFrom: 'categories',
},
{ name: 'tags', label: 'برچسب‌ها', kind: 'multiselect', optionsFrom: 'tags' },
{ name: 'excerpt', label: 'خلاصه', kind: 'textarea', rows: 3, help: 'حداکثر ۵۰۰ کاراکتر. در فهرست نوشته‌ها نمایش داده می‌شود.' },
{ name: 'body', label: 'متن نوشته', kind: 'textarea', rows: 18, required: true },
{ name: 'featured_image', label: 'تصویر شاخص', kind: 'url', placeholder: 'https://example.com/image.jpg' },
{ name: 'published_at', label: 'زمان انتشار', kind: 'datetime', help: 'خالی بگذارید تا پیش‌نویس بماند.' },
{ name: 'views', label: 'بازدید', kind: 'number' },
{ name: 'likes', label: 'پسند', kind: 'number' },
],
},
{
slug: 'categories',
title: 'دسته‌بندی‌ها',
singular: 'دسته‌بندی',
basePath: '/blog/categories',
labelField: 'name',
supportsCreate: true,
supportsDelete: true,
listColumns: [
{ key: 'name', label: 'نام' },
{ key: 'slug', label: 'نشانی' },
{ key: 'short_description', label: 'توضیح کوتاه' },
],
fields: [
{ name: 'name', label: 'نام', kind: 'text', required: true },
{ name: 'slug', label: 'نشانی (slug)', kind: 'text', required: true },
{ name: 'short_description', label: 'توضیح کوتاه', kind: 'textarea', rows: 3 },
{ name: 'description', label: 'توضیح کامل', kind: 'textarea', rows: 8, required: true },
{ name: 'image', label: 'تصویر', kind: 'url', placeholder: 'https://example.com/image.jpg' },
],
},
{
slug: 'tags',
title: 'برچسب‌ها',
singular: 'برچسب',
basePath: '/blog/tags',
labelField: 'name',
supportsCreate: true,
supportsDelete: true,
listColumns: [
{ key: 'name', label: 'نام' },
{ key: 'slug', label: 'نشانی' },
],
fields: [
{ name: 'name', label: 'نام', kind: 'text', required: true },
{ name: 'slug', label: 'نشانی (slug)', kind: 'text', required: true },
],
},
{
slug: 'projects',
title: 'پروژه‌ها',
singular: 'پروژه',
basePath: '/website/projects',
labelField: 'title_fa',
supportsCreate: true,
supportsDelete: true,
hint: 'عنوان و توضیح هر پروژه برای هر زبان جداگانه ذخیره می‌شود.',
listColumns: [
{ key: 'title_fa', label: 'عنوان (فارسی)' },
{ key: 'title_en', label: 'عنوان (انگلیسی)' },
{ key: 'category_id', label: 'دسته' },
],
fields: [
{
name: 'category_id',
label: 'دسته‌بندی',
kind: 'select',
required: true,
optionsFrom: 'project-categories',
},
{ name: 'title_fa', label: 'عنوان فارسی', kind: 'text', required: true, localeGroup: 'fa' },
{ name: 'description_fa', label: 'توضیح فارسی', kind: 'textarea', rows: 6, required: true, localeGroup: 'fa' },
{ name: 'title_en', label: 'عنوان انگلیسی', kind: 'text', required: true, localeGroup: 'en' },
{ name: 'description_en', label: 'توضیح انگلیسی', kind: 'textarea', rows: 6, required: true, localeGroup: 'en' },
{ name: 'image1', label: 'تصویر اول', kind: 'text', required: true, placeholder: '/images/projects/one.jpg' },
{ name: 'image2', label: 'تصویر دوم', kind: 'text', required: true, placeholder: '/images/projects/two.jpg' },
],
},
{
slug: 'about-me',
title: 'درباره من',
singular: 'درباره من',
basePath: '/website/about-me',
labelField: 'title_fa',
supportsCreate: false,
supportsDelete: false,
hint: 'عنوان و معرفی هر زبان جداگانه ذخیره می‌شود. این متن در صفحه اصلی نمایش داده می‌شود.',
listColumns: [
{ key: 'title_fa', label: 'عنوان (فارسی)' },
{ key: 'image', label: 'تصویر' },
],
fields: [
{ name: 'title_fa', label: 'عنوان فارسی', kind: 'text', localeGroup: 'fa' },
{ name: 'description_fa', label: 'معرفی فارسی', kind: 'textarea', rows: 10, localeGroup: 'fa' },
{ name: 'title_en', label: 'عنوان انگلیسی', kind: 'text', localeGroup: 'en' },
{ name: 'description_en', label: 'معرفی انگلیسی', kind: 'textarea', rows: 10, localeGroup: 'en' },
{ name: 'image', label: 'تصویر پروفایل', kind: 'text', required: true, placeholder: '/images/profile.png' },
],
},
];
export const RESOURCE_BY_SLUG: Record<string, ResourceDef> = Object.fromEntries(
RESOURCES.map((resource) => [resource.slug, resource]),
);
export type AdminRow = Record<string, unknown> & { id: number };
export type OptionRow = { id: number; label: string };
type Translations = Record<string, Record<string, string> | undefined>;
function translationsOf(row: AdminRow): Translations {
return (row.translations ?? {}) as Translations;
}
function pickLocale(translations: Translations, base: string): string {
const value = translations[base];
if (!value) return '';
return String(value.fa ?? value.en ?? '');
}
/** Values for locale-suffixed fields such as title_fa / description_en. */
export function cellValue(row: AdminRow, key: string): string {
if (/_(fa|en)$/.test(key)) {
const base = key.replace(/_(fa|en)$/, '');
const locale = key.slice(-2);
const translations = translationsOf(row);
return String(translations[base]?.[locale] ?? '');
}
const value = row[key];
if (value === null || value === undefined) return '';
if (Array.isArray(value)) return value.map((entry) => optionId(entry)).join('، ');
if (typeof value === 'object') return JSON.stringify(value);
return String(value);
}
function optionId(entry: unknown): string {
if (entry && typeof entry === 'object' && 'id' in entry) {
return String((entry as { id: unknown }).id);
}
return String(entry);
}
export function optionLabel(row: AdminRow, resource: ResourceDef): string {
if (resource.slug === 'categories' || resource.slug === 'tags') {
return String(row.name ?? row.slug ?? row.id);
}
const translated = pickLocale(translationsOf(row), 'title');
if (translated) return translated;
return String((row.slug as string | undefined) ?? row.id);
}
+112
View File
@@ -0,0 +1,112 @@
import type { ReactNode } from 'react';
export function PageHeader({
title,
description,
action,
}: {
title: string;
description?: string;
action?: ReactNode;
}) {
return (
<header className="mb-8 flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
<div>
<h1 className="text-2xl font-bold text-foreground">{title}</h1>
{description ? (
<p className="mt-2 max-w-2xl text-sm text-muted-foreground">{description}</p>
) : null}
</div>
{action}
</header>
);
}
export function Card({ children, className = '' }: { children: ReactNode; className?: string }) {
return (
<div
className={`rounded-2xl border border-border bg-card p-5 text-card-foreground shadow-sm ${className}`}
>
{children}
</div>
);
}
export function Alert({ tone, children }: { tone: 'error' | 'info'; children: ReactNode }) {
const styles =
tone === 'error'
? 'border-destructive/40 bg-destructive/10 text-destructive'
: 'border-primary/30 bg-primary/10 text-foreground';
return (
<div role="alert" className={`mb-6 rounded-xl border px-4 py-3 text-sm ${styles}`}>
{children}
</div>
);
}
export function Button({
children,
variant = 'primary',
type = 'button',
disabled = false,
className = '',
}: {
children: ReactNode;
variant?: 'primary' | 'ghost' | 'danger';
type?: 'button' | 'submit';
disabled?: boolean;
className?: string;
}) {
const variants: Record<string, string> = {
primary: 'bg-primary text-primary-foreground hover:opacity-90',
ghost: 'border border-border bg-transparent text-foreground hover:bg-accent',
danger: 'bg-destructive text-destructive-foreground hover:opacity-90',
};
return (
<button
type={type}
disabled={disabled}
className={`inline-flex items-center justify-center rounded-lg px-4 py-2 text-sm font-medium transition disabled:cursor-not-allowed disabled:opacity-60 ${variants[variant]} ${className}`}
>
{children}
</button>
);
}
export function Field({
label,
htmlFor,
help,
required,
children,
}: {
label: string;
htmlFor: string;
help?: string;
required?: boolean;
children: ReactNode;
}) {
return (
<div className="flex flex-col gap-2">
<label htmlFor={htmlFor} className="text-sm font-medium text-foreground">
{label}
{required ? <span className="text-destructive"> *</span> : null}
</label>
{children}
{help ? <p className="text-xs text-muted-foreground">{help}</p> : null}
</div>
);
}
export const inputClass =
'w-full rounded-lg border border-input bg-background px-3 py-2 text-sm text-foreground outline-none transition focus:border-primary focus:ring-2 focus:ring-primary/30';
export function EmptyState({ message }: { message: string }) {
return (
<p className="rounded-xl border border-dashed border-border px-4 py-8 text-center text-sm text-muted-foreground">
{message}
</p>
);
}