Files
2026-06-12 15:34:19 +03:30

376 lines
11 KiB
TypeScript

"use client";
import { useState } from "react";
import { apiFetch, ApiError, toFormData } from "@/lib/api";
import { useList, usePaginated } from "@/lib/useResource";
import { useToast } from "@/components/toast";
import { DataTable, type Column } from "@/components/DataTable";
import {
Button,
ConfirmDialog,
Field,
Input,
Select,
Modal,
PageHeader,
Pagination,
} from "@/components/ui";
import { EditIcon, PlusIcon, TrashIcon } from "@/components/icons";
import { formatMinutes, fileNameToTitle } from "@/lib/utils";
import { MediaPreview } from "@/components/MediaPreview";
import { ImagePicker } from "@/components/ImagePicker";
import { pickUrl, SOUND_KEYS, IMAGE_KEYS } from "@/lib/media";
interface Playlist {
id: number;
name?: string;
// Some endpoints nest the playlist's sub-categories; key casing varies.
subcategories?: Playlist[];
subCategories?: Playlist[];
}
interface Track {
id: number;
title?: string;
artist?: string;
duration?: number | null;
type?: string;
playlist_id?: number;
image_id?: number | null;
// A track belongs to many playlists; the /music row embeds them as an array.
playlists?: Playlist[];
// Sub-categories may also be embedded directly on the track (key casing varies).
subcategories?: Playlist[];
subCategories?: Playlist[];
sub_categories?: Playlist[];
}
export default function MusicTracksPage() {
const { data, meta, page, setPage, loading, error, reload } =
usePaginated<Track>("/music", { perPage: 20 });
const { data: playlists } = useList<Playlist>("/music-playlists");
const toast = useToast();
const [editing, setEditing] = useState<Track | null>(null);
const [open, setOpen] = useState(false);
const [saving, setSaving] = useState(false);
const [title, setTitle] = useState("");
const [artist, setArtist] = useState("");
const [type, setType] = useState("public");
const [duration, setDuration] = useState("");
const [playlistId, setPlaylistId] = useState("");
const [imageId, setImageId] = useState<number | null>(null);
const [imageFile, setImageFile] = useState<File | null>(null);
const [file, setFile] = useState<File | null>(null);
const [deleting, setDeleting] = useState<Track | null>(null);
const [removing, setRemoving] = useState(false);
// A track belongs to many playlists — list their names.
function playlistName(r: Track): string {
const names = (r.playlists ?? []).map((p) => p.name).filter(Boolean);
return names.length ? (names as string[]).join("، ") : "—";
}
// Sub-categories may sit on the track directly or come through its playlists;
// key casing varies between endpoints, so gather from every shape.
function subCategoryNames(r: Track): string {
const subs: Playlist[] = [
...(r.subcategories ?? r.subCategories ?? r.sub_categories ?? []),
...(r.playlists ?? []).flatMap(
(p) => p.subcategories ?? p.subCategories ?? [],
),
];
const names = subs.map((s) => s.name).filter(Boolean) as string[];
const unique = Array.from(new Set(names));
return unique.length ? unique.join("، ") : "—";
}
function resetForm() {
setTitle("");
setArtist("");
setType("public");
setDuration("");
setPlaylistId("");
setImageId(null);
setImageFile(null);
setFile(null);
}
function openCreate() {
setEditing(null);
resetForm();
setOpen(true);
}
function openEdit(row: Track) {
setEditing(row);
setTitle(row.title ?? "");
setArtist(row.artist ?? "");
setType(row.type ?? "public");
setDuration(row.duration != null ? String(row.duration) : "");
setPlaylistId(row.playlist_id != null ? String(row.playlist_id) : "");
setImageId(row.image_id ?? null);
setImageFile(null);
setFile(null);
setOpen(true);
}
async function save(e: React.FormEvent) {
e.preventDefault();
setSaving(true);
try {
if (editing) {
// The PUT /music/:id route can carry files, so we POST multipart with
// Laravel method spoofing (_method=PUT).
const body = toFormData({
_method: "PUT",
title,
artist,
type,
duration,
image_id: imageId,
image: imageFile,
file,
});
await apiFetch(`/music/${editing.id}`, { method: "POST", body });
toast.success("آهنگ ویرایش شد.");
} else {
await apiFetch("/music", {
method: "POST",
body: toFormData({
title,
artist,
type,
duration,
playlist_id: playlistId,
image_id: imageId,
image: imageFile,
file,
}),
});
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(`/music/${deleting.id}`, { method: "DELETE" });
toast.success("آهنگ حذف شد.");
setDeleting(null);
reload();
} catch (err) {
toast.error(err instanceof ApiError ? err.message : "خطا در حذف");
} finally {
setRemoving(false);
}
}
const columns: Column<Track>[] = [
{
key: "play",
header: "پخش",
className: "w-20",
render: (r) => (
<MediaPreview kind="audio" src={pickUrl(r, SOUND_KEYS)} label={r.title} />
),
},
{
key: "thumbnail",
header: "تصویر",
className: "w-20",
render: (r) => (
<MediaPreview kind="image" src={pickUrl(r, IMAGE_KEYS)} label={r.title} />
),
},
{ key: "title", header: "عنوان" },
{ key: "artist", header: "هنرمند", render: (r) => r.artist ?? "—" },
{
key: "playlist",
header: "پلی‌لیست",
render: (r) => playlistName(r),
},
{
key: "subcategory",
header: "زیر‌دسته",
render: (r) => subCategoryNames(r),
},
{
key: "duration",
header: "مدت زمان",
render: (r) => formatMinutes(r.duration),
},
{
key: "type",
header: "نوع",
render: (r) =>
r.type === "private" ? "خصوصی" : r.type === "public" ? "عمومی" : (r.type ?? "—"),
},
];
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>
</>
)}
/>
{meta && (
<Pagination
page={page}
lastPage={meta.last_page}
total={meta.total}
onChange={setPage}
/>
)}
<Modal
open={open}
onClose={() => setOpen(false)}
title={editing ? "ویرایش آهنگ" : "آهنگ جدید"}
footer={
<>
<Button variant="secondary" onClick={() => setOpen(false)}>
انصراف
</Button>
<Button form="track-form" type="submit" loading={saving}>
ذخیره
</Button>
</>
}
>
<form id="track-form" onSubmit={save} className="flex flex-col gap-4">
<Field label="عنوان" required>
<Input
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="مثلاً آرامش شبانه"
required
autoFocus
/>
</Field>
<Field label="هنرمند">
<Input
value={artist}
onChange={(e) => setArtist(e.target.value)}
placeholder="نام هنرمند"
/>
</Field>
<Field label="تصویر جلد" hint="انتخاب از کتابخانه یا بارگذاری تصویر جدید">
<ImagePicker
imageId={imageId}
onPickId={setImageId}
file={imageFile}
onPickFile={setImageFile}
existingUrl={editing ? pickUrl(editing, IMAGE_KEYS) : null}
/>
</Field>
<Field label="نوع">
<Select value={type} onChange={(e) => setType(e.target.value)}>
<option value="public">عمومی</option>
<option value="private">خصوصی</option>
</Select>
</Field>
<Field label="مدت زمان (دقیقه)">
<Input
type="number"
value={duration}
onChange={(e) => setDuration(e.target.value)}
dir="ltr"
/>
</Field>
{!editing && (
<Field label="پلی‌لیست">
<Select
value={playlistId}
onChange={(e) => setPlaylistId(e.target.value)}
>
<option value="">انتخاب کنید…</option>
{playlists.map((p) => (
<option key={p.id} value={p.id}>
{p.name ?? `#${p.id}`}
</option>
))}
</Select>
</Field>
)}
<Field
label={editing ? "فایل صوتی (در صورت تغییر)" : "فایل صوتی"}
hint={editing ? "در صورت خالی بودن، فایل قبلی حفظ می‌شود." : undefined}
required={!editing}
>
<Input
type="file"
accept="audio/*"
onChange={(e) => {
const f = e.target.files?.[0] ?? null;
setFile(f);
// Fill the title from the file name if still empty.
if (f && !title.trim()) setTitle(fileNameToTitle(f.name));
}}
required={!editing}
/>
</Field>
</form>
</Modal>
<ConfirmDialog
open={!!deleting}
message={`آیا از حذف «${deleting?.title ?? ""}» مطمئن هستید؟`}
loading={removing}
onConfirm={confirmDelete}
onClose={() => setDeleting(null)}
/>
</div>
);
}