Files
meditation-admin/app/dashboard/breathing/page.tsx
T
2026-06-17 19:33:19 +03:30

386 lines
12 KiB
TypeScript

"use client";
import { useState } from "react";
import { apiFetch, ApiError, toFormData } from "@/lib/api";
import { useList } from "@/lib/useResource";
import { useToast } from "@/components/toast";
import { DataTable, type Column } from "@/components/DataTable";
import {
Button,
ConfirmDialog,
Field,
Input,
Textarea,
Modal,
PageHeader,
} from "@/components/ui";
import { EditIcon, PlusIcon, TrashIcon } from "@/components/icons";
import { toFa, formatDuration } from "@/lib/utils";
interface BreathingTemplate {
id: number;
name?: string;
inhale?: number;
exhale?: number;
breath_hold?: number;
duration?: number;
description?: string;
image_id?: number;
breathing_color_id?: number | null;
breathing_color?: BreathingColor | null;
}
interface BreathingColor {
id: number;
name?: string | null;
colors: string[];
}
// "#AARRGGBB" (ARGB) or "#RRGGBB" → a CSS color string.
function cssColor(c?: string): string {
if (!c) return "transparent";
const hex = c.replace("#", "");
if (hex.length === 8) return `#${hex.slice(2)}${hex.slice(0, 2)}`; // ARGB→RGB(drop alpha)
return `#${hex}`;
}
// Linear gradient (or solid) preview for a list of colors.
function gradientStyle(colors: string[]): React.CSSProperties {
const cs = (colors.length ? colors : ["#00000000"]).map(cssColor);
if (cs.length === 1) return { background: cs[0] };
return { background: `linear-gradient(135deg, ${cs.join(", ")})` };
}
interface BreathingForm {
name: string;
inhale: string;
exhale: string;
breath_hold: string;
duration: string;
description: string;
image_id: string;
}
const emptyForm: BreathingForm = {
name: "",
inhale: "",
exhale: "",
breath_hold: "",
duration: "",
description: "",
image_id: "",
};
function numOrUndefined(v: string): number | undefined {
if (v === "") return undefined;
const n = Number(v);
return Number.isNaN(n) ? undefined : n;
}
export default function BreathingPage() {
const { data, loading, error, reload } =
useList<BreathingTemplate>("/breathing-templates");
const { data: palette } = useList<BreathingColor>("/breathing-colors");
const toast = useToast();
const [editing, setEditing] = useState<BreathingTemplate | null>(null);
const [open, setOpen] = useState(false);
const [form, setForm] = useState<BreathingForm>(emptyForm);
const [breathingColorId, setBreathingColorId] = useState<number | null>(null);
const [saving, setSaving] = useState(false);
const [deleting, setDeleting] = useState<BreathingTemplate | null>(null);
const [removing, setRemoving] = useState(false);
function set<K extends keyof BreathingForm>(key: K, value: string) {
setForm((f) => ({ ...f, [key]: value }));
}
function openCreate() {
setEditing(null);
setForm(emptyForm);
setBreathingColorId(null);
setOpen(true);
}
function openEdit(row: BreathingTemplate) {
setEditing(row);
setForm({
name: row.name ?? "",
inhale: row.inhale != null ? String(row.inhale) : "",
exhale: row.exhale != null ? String(row.exhale) : "",
breath_hold: row.breath_hold != null ? String(row.breath_hold) : "",
duration: row.duration != null ? String(row.duration) : "",
description: row.description ?? "",
image_id: row.image_id != null ? String(row.image_id) : "",
});
setBreathingColorId(row.breathing_color_id ?? null);
setOpen(true);
}
async function save(e: React.FormEvent) {
e.preventDefault();
setSaving(true);
try {
const payload = {
name: form.name,
inhale: numOrUndefined(form.inhale),
exhale: numOrUndefined(form.exhale),
breath_hold: numOrUndefined(form.breath_hold),
duration: numOrUndefined(form.duration),
description: form.description,
image_id: numOrUndefined(form.image_id),
// Send null (not undefined) so choosing "بدون رنگ" actually clears it.
breathing_color_id: breathingColorId,
};
if (editing) {
// Update is JSON on /breathing-templates/:id
await apiFetch(`/breathing-templates/${editing.id}`, {
method: "PUT",
body: payload,
});
toast.success("قالب تنفس ویرایش شد.");
} else {
// Create is multipart on /breathing-templates
await apiFetch("/breathing-templates", {
method: "POST",
body: toFormData(payload),
});
toast.success("قالب تنفس افزوده شد.");
}
setOpen(false);
reload();
} catch (err) {
toast.error(err instanceof ApiError ? err.message : "خطا در ذخیره‌سازی");
} finally {
setSaving(false);
}
}
async function confirmDelete() {
if (!deleting) return;
setRemoving(true);
try {
await apiFetch(`/breathing-templates/${deleting.id}`, {
method: "DELETE",
});
toast.success("قالب تنفس حذف شد.");
setDeleting(null);
reload();
} catch (err) {
toast.error(err instanceof ApiError ? err.message : "خطا در حذف");
} finally {
setRemoving(false);
}
}
const columns: Column<BreathingTemplate>[] = [
{ key: "id", header: "شناسه", render: (r) => toFa(r.id), className: "w-20" },
{ key: "name", header: "نام", render: (r) => r.name ?? "—" },
{
key: "inhale",
header: "دم",
render: (r) => (r.inhale != null ? toFa(r.inhale) : "—"),
},
{
key: "exhale",
header: "بازدم",
render: (r) => (r.exhale != null ? toFa(r.exhale) : "—"),
},
{
key: "breath_hold",
header: "حبس نفس",
render: (r) => (r.breath_hold != null ? toFa(r.breath_hold) : "—"),
},
{
key: "duration",
header: "مدت زمان",
render: (r) => (r.duration != null ? formatDuration(r.duration) : "—"),
},
{
key: "color",
header: "رنگ",
className: "w-20",
render: (r) =>
r.breathing_color?.colors?.length ? (
<span
className="inline-block h-6 w-10 rounded-md border border-border"
style={gradientStyle(r.breathing_color.colors)}
title={r.breathing_color.name ?? ""}
/>
) : (
"—"
),
},
];
return (
<div>
<PageHeader
title="قالب‌های تنفس"
subtitle="مدیریت الگوهای تمرین تنفس"
action={
<Button icon={<PlusIcon className="h-4 w-4" />} onClick={openCreate}>
قالب جدید
</Button>
}
/>
<DataTable
columns={columns}
rows={data}
loading={loading}
error={error}
onRetry={reload}
emptyMessage="هنوز قالب تنفسی ثبت نشده است."
emptyAction={
<Button icon={<PlusIcon className="h-4 w-4" />} onClick={openCreate}>
قالب جدید
</Button>
}
actions={(row) => (
<>
<Button variant="ghost" onClick={() => openEdit(row)} aria-label="ویرایش">
<EditIcon className="h-4 w-4" />
</Button>
<Button
variant="ghost"
onClick={() => setDeleting(row)}
aria-label="حذف"
className="text-danger"
>
<TrashIcon className="h-4 w-4" />
</Button>
</>
)}
/>
<Modal
open={open}
onClose={() => setOpen(false)}
title={editing ? "ویرایش قالب تنفس" : "قالب تنفس جدید"}
footer={
<>
<Button variant="secondary" onClick={() => setOpen(false)}>
انصراف
</Button>
<Button form="breathing-form" type="submit" loading={saving}>
ذخیره
</Button>
</>
}
>
<form
id="breathing-form"
onSubmit={save}
className="flex flex-col gap-4"
>
<Field label="نام" required>
<Input
value={form.name}
onChange={(e) => set("name", e.target.value)}
placeholder="مثلاً تنفس آرام‌بخش"
required
autoFocus
/>
</Field>
<div className="grid grid-cols-2 gap-4">
<Field label="دم (ثانیه)">
<Input
type="number"
value={form.inhale}
onChange={(e) => set("inhale", e.target.value)}
dir="ltr"
/>
</Field>
<Field label="بازدم (ثانیه)">
<Input
type="number"
value={form.exhale}
onChange={(e) => set("exhale", e.target.value)}
dir="ltr"
/>
</Field>
<Field label="حبس نفس (ثانیه)">
<Input
type="number"
value={form.breath_hold}
onChange={(e) => set("breath_hold", e.target.value)}
dir="ltr"
/>
</Field>
<Field label="مدت زمان (ثانیه)">
<Input
type="number"
value={form.duration}
onChange={(e) => set("duration", e.target.value)}
dir="ltr"
/>
</Field>
</div>
<Field label="شناسه تصویر">
<Input
type="number"
value={form.image_id}
onChange={(e) => set("image_id", e.target.value)}
dir="ltr"
/>
</Field>
<Field label="توضیحات">
<Textarea
value={form.description}
onChange={(e) => set("description", e.target.value)}
placeholder="توضیح کوتاه درباره قالب"
/>
</Field>
<Field
label="رنگ تمرین"
hint={
palette.length
? "یک رنگ از پالت انتخاب کنید (در «رنگ‌های تنفس» مدیریت می‌شود)."
: "هنوز رنگی در «رنگ‌های تنفس» تعریف نشده است."
}
>
<div className="flex flex-wrap items-center gap-2">
{/* "no color" option */}
<button
type="button"
title="بدون رنگ"
onClick={() => setBreathingColorId(null)}
className={`flex h-9 w-9 items-center justify-center rounded-full border-2 text-muted ${
breathingColorId === null ? "border-primary ring-2 ring-primary/40" : "border-border"
}`}
>
</button>
{palette.map((p) => {
const selected = breathingColorId === p.id;
return (
<button
key={p.id}
type="button"
title={p.name ?? ""}
onClick={() => setBreathingColorId(p.id)}
style={gradientStyle(p.colors)}
className={`h-9 w-9 rounded-full border-2 transition ${
selected ? "border-primary ring-2 ring-primary/40" : "border-border"
}`}
/>
);
})}
</div>
</Field>
</form>
</Modal>
<ConfirmDialog
open={!!deleting}
message={`آیا از حذف «${deleting?.name ?? deleting?.id}» مطمئن هستید؟`}
loading={removing}
onConfirm={confirmDelete}
onClose={() => setDeleting(null)}
/>
</div>
);
}