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

@@ -0,0 +1,33 @@
import { notFound } from 'next/navigation';
import { loadOptions, loadRows, optionSources } from '@/app/lib/admin/load';
import { RESOURCE_BY_SLUG, type AdminRow } from '@/app/lib/admin/resources';
import ResourceForm from '@/app/lib/admin/resource-form';
import { PageHeader } from '@/app/lib/admin/ui';
export const dynamic = 'force-dynamic';
export default async function EditResourcePage({
params,
}: {
params: Promise<{ resource: string; id: string }>;
}) {
const { resource: slug, id } = await params;
const resource = RESOURCE_BY_SLUG[slug];
if (!resource) notFound();
const rows = await loadRows(resource.slug);
const row: AdminRow | undefined = rows.find((entry) => String(entry.id) === id);
if (!row) notFound();
const options = await loadOptions(optionSources(resource));
return (
<>
<PageHeader title={`ویرایش ${resource.singular}`} description={resource.hint} />
<ResourceForm resource={resource} row={row} options={options} />
</>
);
}
@@ -0,0 +1,32 @@
import { notFound } from 'next/navigation';
import { loadOptions, optionSources } from '@/app/lib/admin/load';
import { RESOURCE_BY_SLUG } from '@/app/lib/admin/resources';
import ResourceForm from '@/app/lib/admin/resource-form';
import { Alert, PageHeader } from '@/app/lib/admin/ui';
export const dynamic = 'force-dynamic';
export default async function NewResourcePage({
params,
}: {
params: Promise<{ resource: string }>;
}) {
const { resource: slug } = await params;
const resource = RESOURCE_BY_SLUG[slug];
if (!resource || !resource.supportsCreate) notFound();
const options = await loadOptions(optionSources(resource));
return (
<>
<PageHeader title={`${resource.singular} جدید`} description={resource.hint} />
{Object.keys(options).length === 0 ? (
<Alert tone="info">هیچ گزینه‌ای برای انتخاب وجود ندارد.</Alert>
) : null}
<ResourceForm resource={resource} row={null} options={options} />
</>
);
}
@@ -0,0 +1,87 @@
import Link from 'next/link';
import { notFound } from 'next/navigation';
import { deleteResourceAction } from '@/app/lib/admin/actions';
import { cellValue, RESOURCE_BY_SLUG, type AdminRow } from '@/app/lib/admin/resources';
import { loadRows } from '@/app/lib/admin/load';
import { Card, EmptyState, PageHeader } from '@/app/lib/admin/ui';
export const dynamic = 'force-dynamic';
export default async function ResourceListPage({
params,
}: {
params: Promise<{ resource: string }>;
}) {
const { resource: slug } = await params;
const resource = RESOURCE_BY_SLUG[slug];
if (!resource) notFound();
let rows: AdminRow[] = [];
try {
rows = await loadRows(resource.slug);
} catch {
rows = [];
}
return (
<>
<PageHeader
title={resource.title}
description={resource.hint}
action={
resource.supportsCreate ? (
<Link
href={`/admin/${resource.slug}/new`}
className="inline-flex items-center justify-center rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition hover:opacity-90"
>
افزودن {resource.singular}
</Link>
) : undefined
}
/>
{rows.length === 0 ? (
<EmptyState message={`هنوز ${resource.singular} ثبت نشده است.`} />
) : (
<div className="flex flex-col gap-3">
{rows.map((row) => (
<Card key={row.id} className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div className="min-w-0">
{resource.listColumns.map((column) => (
<p key={column.key} className="truncate text-sm text-foreground">
<span className="text-muted-foreground">{column.label}: </span>
{cellValue(row, column.key) || '—'}
</p>
))}
</div>
<div className="flex shrink-0 items-center gap-4 text-sm">
<Link
href={`/admin/${resource.slug}/${row.id}`}
className="text-primary underline-offset-4 hover:underline"
>
ویرایش
</Link>
{resource.supportsDelete ? (
<form action={deleteResourceAction}>
<input type="hidden" name="__resource" value={resource.slug} />
<input type="hidden" name="__id" value={row.id} />
<button
type="submit"
className="text-destructive underline-offset-4 hover:underline"
>
حذف
</button>
</form>
) : null}
</div>
</Card>
))}
</div>
)}
</>
);
}
+18
View File
@@ -0,0 +1,18 @@
import { redirect } from 'next/navigation';
import { currentAdmin } from '@/app/lib/admin/api';
import AdminNav from './nav';
export const dynamic = 'force-dynamic';
export default async function PanelLayout({ children }: { children: React.ReactNode }) {
const admin = await currentAdmin();
if (!admin) redirect('/admin/login');
return (
<div className="mx-auto flex w-full max-w-[1200px] flex-col gap-8 px-5 py-10 lg:flex-row">
<AdminNav email={admin.email} />
<div className="min-w-0 flex-1">{children}</div>
</div>
);
}
+53
View File
@@ -0,0 +1,53 @@
import Link from 'next/link';
import { logoutAction } from '@/app/lib/admin/actions';
import { RESOURCES } from '@/app/lib/admin/resources';
export default function AdminNav({ email }: { email: string }) {
return (
<aside className="flex w-full shrink-0 flex-col gap-6 lg:sticky lg:top-10 lg:w-60">
<div>
<p className="text-sm font-bold text-foreground">پنل مدیریت</p>
<p className="mt-1 truncate text-xs text-muted-foreground" dir="ltr">
{email}
</p>
</div>
<nav className="flex flex-row flex-wrap gap-1 lg:flex-col">
<Link
href="/admin"
className="rounded-lg px-3 py-2 text-sm text-muted-foreground transition hover:bg-accent hover:text-foreground"
>
پیشخوان
</Link>
{RESOURCES.map((resource) => (
<Link
key={resource.slug}
href={`/admin/${resource.slug}`}
className="rounded-lg px-3 py-2 text-sm text-muted-foreground transition hover:bg-accent hover:text-foreground"
>
{resource.title}
</Link>
))}
</nav>
<div className="mt-auto flex flex-col gap-2">
<Link
href="/"
className="rounded-lg border border-border px-3 py-2 text-center text-sm text-foreground transition hover:bg-accent"
>
مشاهده سایت
</Link>
<form action={logoutAction}>
<button
type="submit"
className="w-full rounded-lg border border-border px-3 py-2 text-sm text-destructive transition hover:bg-destructive/10"
>
خروج
</button>
</form>
</div>
</aside>
);
}
+54
View File
@@ -0,0 +1,54 @@
import Link from 'next/link';
import { loadRows } from '@/app/lib/admin/load';
import { RESOURCES } from '@/app/lib/admin/resources';
import { Card, PageHeader } from '@/app/lib/admin/ui';
export const dynamic = 'force-dynamic';
export default async function AdminDashboardPage() {
const counts = await Promise.all(
RESOURCES.map(async (resource) => {
try {
const rows = await loadRows(resource.slug);
return { resource, total: rows.length };
} catch {
return { resource, total: -1 };
}
}),
);
const draftPosts = await (async () => {
try {
const rows = await loadRows('posts');
return rows.filter((row) => !row.published_at).length;
} catch {
return -1;
}
})();
return (
<>
<PageHeader title="پیشخوان" description="وضعیت محتوای سایت." />
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
{counts.map(({ resource, total }) => (
<Link key={resource.slug} href={`/admin/${resource.slug}`}>
<Card className="h-full transition hover:border-primary">
<p className="text-sm text-muted-foreground">{resource.title}</p>
<p className="mt-2 text-3xl font-bold text-foreground">
{total === -1 ? '—' : total.toLocaleString('fa-IR')}
</p>
</Card>
</Link>
))}
</div>
<Card className="mt-6">
<p className="text-sm text-muted-foreground">نوشته‌های پیش‌نویس</p>
<p className="mt-2 text-2xl font-bold text-foreground">
{draftPosts === -1 ? '—' : draftPosts.toLocaleString('fa-IR')}
</p>
</Card>
</>
);
}
+13
View File
@@ -0,0 +1,13 @@
import type { Metadata } from 'next';
import type { ReactNode } from 'react';
export const metadata: Metadata = {
title: 'پنل مدیریت',
robots: { index: false, follow: false, nocache: true },
};
export default function AdminLayout({ children }: { children: ReactNode }) {
return (
<div className="min-h-screen w-full bg-background text-foreground">{children}</div>
);
}
+25
View File
@@ -0,0 +1,25 @@
import { redirect } from 'next/navigation';
import { currentAdmin } from '@/app/lib/admin/api';
import LoginForm from '@/app/lib/admin/login-form';
import { Card } from '@/app/lib/admin/ui';
export const dynamic = 'force-dynamic';
export default async function AdminLoginPage() {
if (await currentAdmin()) redirect('/admin');
return (
<div className="flex min-h-screen items-center justify-center px-4 py-16">
<Card className="w-full max-w-sm">
<div className="mb-6">
<h1 className="text-xl font-bold text-foreground">پنل مدیریت</h1>
<p className="mt-2 text-sm text-muted-foreground">
برای مدیریت محتوای سایت وارد شوید.
</p>
</div>
<LoginForm />
</Card>
</div>
);
}
+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>
);
}