Compare commits
10
Commits
V1.0.26
...
e248943f4c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e248943f4c | ||
|
|
fdbf02bc07 | ||
|
|
1898dbb322 | ||
|
|
fee184c0e6 | ||
|
|
faf95327f1 | ||
|
|
b4d8e32fdd | ||
|
|
96c74601c8 | ||
|
|
5c4af242fc | ||
|
|
aba556618b | ||
|
|
ec79ea2771 |
@@ -14,8 +14,9 @@ import {
|
||||
Textarea,
|
||||
Modal,
|
||||
PageHeader,
|
||||
Switch,
|
||||
} from "@/components/ui";
|
||||
import { EditIcon, PlusIcon, TrashIcon } from "@/components/icons";
|
||||
import { EditIcon, EyeIcon, PlusIcon, TrashIcon } from "@/components/icons";
|
||||
import { MediaPreview } from "@/components/MediaPreview";
|
||||
import { pickUrl } from "@/lib/media";
|
||||
import { toFa } from "@/lib/utils";
|
||||
@@ -29,6 +30,8 @@ interface Category {
|
||||
order?: number;
|
||||
description?: string | null;
|
||||
icon?: string | null;
|
||||
is_deeplink_only?: boolean;
|
||||
deep_link?: string | null;
|
||||
subcategories_count?: number;
|
||||
}
|
||||
|
||||
@@ -48,9 +51,16 @@ const ICON_KEYS = ["icon", "icon_url"];
|
||||
|
||||
export default function CategoriesPage() {
|
||||
const [typeFilter, setTypeFilter] = useState<CategoryType>("media");
|
||||
const { data, loading, error, reload } = useList<Category>("/categories", {
|
||||
type: typeFilter,
|
||||
});
|
||||
// Deep-link-only categories are hidden from the normal listing, so they need
|
||||
// their own view here — otherwise a category sent to deep links disappears
|
||||
// from this page and can only be brought back from the deep-links screen.
|
||||
const [showDeepLinks, setShowDeepLinks] = useState(false);
|
||||
const { data, loading, error, reload } = useList<Category>(
|
||||
"/categories",
|
||||
// `deeplink_only` returns every hidden category regardless of type, so the
|
||||
// type filter is not sent alongside it.
|
||||
showDeepLinks ? { deeplink_only: 1 } : { type: typeFilter },
|
||||
);
|
||||
const toast = useToast();
|
||||
|
||||
const [editing, setEditing] = useState<Category | null>(null);
|
||||
@@ -128,6 +138,25 @@ export default function CategoriesPage() {
|
||||
}
|
||||
}
|
||||
|
||||
// Move a category into or out of deep-link-only mode, both directions.
|
||||
// Playlist categories live in music_categories, which has no such column.
|
||||
async function toggleDeepLink(row: Category) {
|
||||
try {
|
||||
await apiFetch(`/categories/${row.id}`, {
|
||||
method: "POST",
|
||||
body: toFormData({ is_deeplink_only: row.is_deeplink_only ? 0 : 1 }),
|
||||
});
|
||||
toast.success(
|
||||
row.is_deeplink_only
|
||||
? "به فهرست عادی بازگشت."
|
||||
: "به لینک مستقیم تبدیل شد.",
|
||||
);
|
||||
reload();
|
||||
} catch (err) {
|
||||
toast.error(err instanceof ApiError ? err.message : "خطا در ذخیرهسازی");
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmDelete() {
|
||||
if (!deleting) return;
|
||||
setRemoving(true);
|
||||
@@ -174,6 +203,25 @@ export default function CategoriesPage() {
|
||||
header: "توضیحات",
|
||||
render: (r) => r.description || "—",
|
||||
},
|
||||
{
|
||||
key: "deep_link",
|
||||
header: "لینک مستقیم",
|
||||
className: "w-56",
|
||||
render: (r) =>
|
||||
r.is_deeplink_only ? (
|
||||
<a
|
||||
href={r.deep_link ?? undefined}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
dir="ltr"
|
||||
className="inline-block max-w-[200px] truncate text-xs text-primary underline"
|
||||
>
|
||||
{r.deep_link ?? "—"}
|
||||
</a>
|
||||
) : (
|
||||
<span className="text-xs text-muted">—</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "subcategories_count",
|
||||
header: "زیردستهها",
|
||||
@@ -189,11 +237,17 @@ export default function CategoriesPage() {
|
||||
subtitle="مدیریت دستهبندیهای عمومی رسانه، پلیلیست و قالب تنفس"
|
||||
action={
|
||||
<div className="flex items-center gap-3">
|
||||
<Switch
|
||||
checked={showDeepLinks}
|
||||
onChange={setShowDeepLinks}
|
||||
label="فقط لینکهای مستقیم"
|
||||
/>
|
||||
<Select
|
||||
value={typeFilter}
|
||||
onChange={(e) => setTypeFilter(e.target.value as CategoryType)}
|
||||
aria-label="نوع دستهبندی"
|
||||
className="w-40"
|
||||
disabled={showDeepLinks}
|
||||
>
|
||||
{TYPE_OPTIONS.map((o) => (
|
||||
<option key={o.value} value={o.value}>
|
||||
@@ -214,7 +268,11 @@ export default function CategoriesPage() {
|
||||
loading={loading}
|
||||
error={error}
|
||||
onRetry={reload}
|
||||
emptyMessage="هنوز دستهبندیای ثبت نشده است. اولین دستهبندی را بسازید."
|
||||
emptyMessage={
|
||||
showDeepLinks
|
||||
? "هیچ دستهبندی لینک مستقیمی وجود ندارد."
|
||||
: "هنوز دستهبندیای ثبت نشده است. اولین دستهبندی را بسازید."
|
||||
}
|
||||
emptyAction={
|
||||
<Button icon={<PlusIcon className="h-4 w-4" />} onClick={openCreate}>
|
||||
دستهبندی جدید
|
||||
@@ -225,6 +283,25 @@ export default function CategoriesPage() {
|
||||
<Button variant="ghost" onClick={() => openEdit(row)} aria-label="ویرایش">
|
||||
<EditIcon className="h-4 w-4" />
|
||||
</Button>
|
||||
{row.type !== "playlist" && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => toggleDeepLink(row)}
|
||||
aria-label={
|
||||
row.is_deeplink_only
|
||||
? "بازگرداندن به فهرست"
|
||||
: "تبدیل به لینک مستقیم"
|
||||
}
|
||||
title={
|
||||
row.is_deeplink_only
|
||||
? "بازگرداندن به فهرست"
|
||||
: "تبدیل به لینک مستقیم"
|
||||
}
|
||||
className={row.is_deeplink_only ? "text-primary" : undefined}
|
||||
>
|
||||
<EyeIcon className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => setDeleting(row)}
|
||||
|
||||
@@ -0,0 +1,413 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, 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,
|
||||
Modal,
|
||||
PageHeader,
|
||||
Select,
|
||||
Textarea,
|
||||
} from "@/components/ui";
|
||||
import { EditIcon, EyeIcon, PlusIcon, TrashIcon } from "@/components/icons";
|
||||
import { MediaPreview } from "@/components/MediaPreview";
|
||||
import { pickUrl } from "@/lib/media";
|
||||
import { toFa } from "@/lib/utils";
|
||||
|
||||
interface Category {
|
||||
id: number;
|
||||
name: string;
|
||||
type: string;
|
||||
order?: number;
|
||||
description?: string | null;
|
||||
icon?: string | null;
|
||||
icon_url?: string | null;
|
||||
deep_link?: string | null;
|
||||
is_deeplink_only?: boolean;
|
||||
subcategories_count?: number;
|
||||
}
|
||||
|
||||
const ICON_KEYS = ["icon", "icon_url"];
|
||||
|
||||
export default function CategoryDeepLinksPage() {
|
||||
const { data, loading, error, reload: reloadHidden } = useList<Category>(
|
||||
"/categories",
|
||||
{ deeplink_only: 1 },
|
||||
);
|
||||
// The "use an existing category" picker. /categories only lists visible ones,
|
||||
// so it must be refetched on every toggle — otherwise a just-unhidden
|
||||
// category is missing from the picker until a full page reload.
|
||||
const {
|
||||
data: allSelectable,
|
||||
loading: allLoading,
|
||||
reload: reloadAll,
|
||||
} = useList<Category>("/categories");
|
||||
const toast = useToast();
|
||||
|
||||
// Only rows from the `categories` table can be toggled — /categories with no
|
||||
// type also folds in music (playlist) categories, whose IDs belong to another
|
||||
// table and which have no deep-link column.
|
||||
const allCategories = allSelectable.filter((c) => c.type !== "playlist");
|
||||
|
||||
// Both lists change together on every toggle.
|
||||
const reload = useCallback(() => {
|
||||
reloadHidden();
|
||||
reloadAll();
|
||||
}, [reloadHidden, reloadAll]);
|
||||
|
||||
// Non-null while the modal edits an existing row (null = create).
|
||||
const [editing, setEditing] = useState<Category | null>(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
// Source: 'existing' (pick an existing category to hide — the common case,
|
||||
// and it avoids the "name already taken" error you get from re-creating one)
|
||||
// or 'new' (create a fresh hidden category).
|
||||
const [source, setSource] = useState<"new" | "existing">("existing");
|
||||
const [existingId, setExistingId] = useState<string>("");
|
||||
|
||||
// Fields for creating a new hidden category.
|
||||
const [name, setName] = useState("");
|
||||
const [type, setType] = useState("media");
|
||||
const [order, setOrder] = useState("0");
|
||||
const [description, setDescription] = useState("");
|
||||
const [icon, setIcon] = useState<File | null>(null);
|
||||
|
||||
const [deleting, setDeleting] = useState<Category | null>(null);
|
||||
const [removing, setRemoving] = useState(false);
|
||||
|
||||
function resetForm() {
|
||||
setSource("existing");
|
||||
setExistingId("");
|
||||
setName("");
|
||||
setType("media");
|
||||
setOrder("0");
|
||||
setDescription("");
|
||||
setIcon(null);
|
||||
}
|
||||
|
||||
function openCreate() {
|
||||
setEditing(null);
|
||||
resetForm();
|
||||
setOpen(true);
|
||||
}
|
||||
|
||||
function openEdit(row: Category) {
|
||||
setEditing(row);
|
||||
setSource("new"); // the edit form always shows the category fields
|
||||
setExistingId("");
|
||||
setName(row.name ?? "");
|
||||
setType(row.type ?? "media");
|
||||
setOrder(row.order != null ? String(row.order) : "0");
|
||||
setDescription(row.description ?? "");
|
||||
setIcon(null);
|
||||
setOpen(true);
|
||||
}
|
||||
|
||||
// Take a category back out of deep-link-only mode (it returns to the lists).
|
||||
async function unhide(row: Category) {
|
||||
try {
|
||||
await apiFetch(`/categories/${row.id}`, {
|
||||
method: "POST",
|
||||
body: toFormData({ is_deeplink_only: 0 }),
|
||||
});
|
||||
toast.success("از لینک مستقیم خارج شد.");
|
||||
reload();
|
||||
} catch (err) {
|
||||
toast.error(err instanceof ApiError ? err.message : "خطا در ذخیرهسازی");
|
||||
}
|
||||
}
|
||||
|
||||
async function save(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setSaving(true);
|
||||
try {
|
||||
if (editing) {
|
||||
// Edit an existing deep-link category. It stays deeplink-only.
|
||||
await apiFetch(`/categories/${editing.id}`, {
|
||||
method: "POST",
|
||||
body: toFormData({ name, type, order, description, icon }),
|
||||
});
|
||||
toast.success("لینک مستقیم بهروزرسانی شد.");
|
||||
} else if (source === "existing") {
|
||||
if (!existingId) {
|
||||
toast.error("دستهبندی را انتخاب کنید.");
|
||||
return;
|
||||
}
|
||||
await apiFetch(`/categories/${existingId}`, {
|
||||
method: "POST",
|
||||
body: toFormData({ is_deeplink_only: 1 }),
|
||||
});
|
||||
toast.success("دستهبندی به لینک مستقیم تبدیل شد.");
|
||||
} else {
|
||||
const body = toFormData({
|
||||
name,
|
||||
type,
|
||||
order,
|
||||
description,
|
||||
icon,
|
||||
is_deeplink_only: true,
|
||||
});
|
||||
await apiFetch("/categories", { method: "POST", body });
|
||||
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(`/categories/${deleting.id}`, { method: "DELETE" });
|
||||
toast.success("دستهبندی حذف شد.");
|
||||
setDeleting(null);
|
||||
reload();
|
||||
} catch (err) {
|
||||
toast.error(err instanceof ApiError ? err.message : "خطا در حذف");
|
||||
} finally {
|
||||
setRemoving(false);
|
||||
}
|
||||
}
|
||||
|
||||
const columns: Column<Category>[] = [
|
||||
{
|
||||
key: "icon",
|
||||
header: "آیکن",
|
||||
className: "w-20",
|
||||
render: (r) => (
|
||||
<MediaPreview kind="image" src={pickUrl(r, ICON_KEYS)} label={r.name} />
|
||||
),
|
||||
},
|
||||
{ key: "name", header: "نام دستهبندی" },
|
||||
{
|
||||
key: "type",
|
||||
header: "نوع",
|
||||
render: (r) =>
|
||||
r.type === "media"
|
||||
? "رسانه"
|
||||
: r.type === "playlist"
|
||||
? "پلیلیست"
|
||||
: r.type === "breathing_template"
|
||||
? "قالب تنفس"
|
||||
: r.type,
|
||||
className: "w-28",
|
||||
},
|
||||
{
|
||||
key: "deep_link",
|
||||
header: "لینک مستقیم",
|
||||
render: (r) =>
|
||||
r.deep_link ? (
|
||||
<a
|
||||
href={r.deep_link}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
dir="ltr"
|
||||
className="inline-block max-w-[220px] truncate text-xs text-primary underline"
|
||||
>
|
||||
{r.deep_link}
|
||||
</a>
|
||||
) : (
|
||||
<span className="text-xs text-muted">—</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "subcategories_count",
|
||||
header: "زیردستهها",
|
||||
render: (r) => toFa(r.subcategories_count ?? 0),
|
||||
className: "w-28",
|
||||
},
|
||||
];
|
||||
|
||||
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={() => unhide(row)}
|
||||
aria-label="نمایش در فهرست"
|
||||
title="نمایش در فهرست"
|
||||
>
|
||||
<EyeIcon 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="cat-deeplink-form" type="submit" loading={saving}>
|
||||
ذخیره
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<form
|
||||
id="cat-deeplink-form"
|
||||
onSubmit={save}
|
||||
className="flex flex-col gap-4"
|
||||
>
|
||||
{!editing && (
|
||||
<Field label="منبع دستهبندی" required>
|
||||
<Select
|
||||
value={source}
|
||||
onChange={(e) => setSource(e.target.value as "new" | "existing")}
|
||||
>
|
||||
<option value="new">ساخت دستهبندی جدید</option>
|
||||
<option value="existing">استفاده از دستهبندی موجود</option>
|
||||
</Select>
|
||||
</Field>
|
||||
)}
|
||||
|
||||
{source === "existing" ? (
|
||||
<Field label="انتخاب دستهبندی" required>
|
||||
{allCategories.length ? (
|
||||
<Select
|
||||
value={existingId}
|
||||
onChange={(e) => setExistingId(e.target.value)}
|
||||
>
|
||||
<option value="">انتخاب کنید...</option>
|
||||
{allCategories.map((c) => (
|
||||
<option key={c.id} value={String(c.id)}>
|
||||
{c.name} ({c.type})
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
) : (
|
||||
<p className="text-xs text-muted">
|
||||
{allLoading ? "در حال بارگذاری..." : "دستهبندیای موجود نیست."}
|
||||
</p>
|
||||
)}
|
||||
</Field>
|
||||
) : (
|
||||
<>
|
||||
<Field label="نام دستهبندی" required>
|
||||
<Input
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="مثلاً مدیتیشن شبانه"
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
</Field>
|
||||
|
||||
{/* No playlist option: playlist categories live in the
|
||||
music_categories table, which has no deep-link column. */}
|
||||
<Field label="نوع">
|
||||
<Select
|
||||
value={type}
|
||||
onChange={(e) => setType(e.target.value)}
|
||||
>
|
||||
<option value="media">رسانه</option>
|
||||
<option value="breathing_template">قالب تنفس</option>
|
||||
</Select>
|
||||
</Field>
|
||||
|
||||
<Field label="ترتیب">
|
||||
<Input
|
||||
type="number"
|
||||
dir="ltr"
|
||||
value={order}
|
||||
onChange={(e) => setOrder(e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<Field label="توضیحات">
|
||||
<Textarea
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
placeholder="توضیح کوتاه"
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<Field label={editing ? "آیکن (در صورت تغییر)" : "آیکن"}>
|
||||
<Input
|
||||
type="file"
|
||||
accept="image/*"
|
||||
onChange={(e) => setIcon(e.target.files?.[0] ?? null)}
|
||||
/>
|
||||
</Field>
|
||||
</>
|
||||
)}
|
||||
|
||||
<p className="rounded-xl border border-border bg-surface-muted p-3 text-xs text-muted">
|
||||
{editing ? (
|
||||
<>
|
||||
این دستهبندی در فهرست نمایش داده نمیشود و فقط با لینک مستقیم قابل
|
||||
دسترسی است. برای بازگرداندن آن به فهرست، از دکمه «نمایش در فهرست»
|
||||
استفاده کنید.
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
پس از ذخیره، این دستهبندی در فهرست نمایش داده نمیشود و فقط با لینک
|
||||
مستقیم قابل دسترسی است.
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
</form>
|
||||
</Modal>
|
||||
|
||||
<ConfirmDialog
|
||||
open={!!deleting}
|
||||
message={`آیا از حذف «${deleting?.name ?? ""}» مطمئن هستید؟`}
|
||||
loading={removing}
|
||||
onConfirm={confirmDelete}
|
||||
onClose={() => setDeleting(null)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,460 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, 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,
|
||||
Modal,
|
||||
PageHeader,
|
||||
Select,
|
||||
Textarea,
|
||||
} from "@/components/ui";
|
||||
import { EditIcon, EyeIcon, PlusIcon, TrashIcon } from "@/components/icons";
|
||||
import { MediaPreview } from "@/components/MediaPreview";
|
||||
import { ImagePicker } from "@/components/ImagePicker";
|
||||
import { pickUrl, SOUND_KEYS, VIDEO_KEYS, IMAGE_KEYS } from "@/lib/media";
|
||||
import { formatMinutes, fileNameToTitle } from "@/lib/utils";
|
||||
|
||||
interface Cat {
|
||||
id: number;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
interface Media {
|
||||
id: number;
|
||||
title?: string;
|
||||
caption?: string;
|
||||
type?: string;
|
||||
duration?: number;
|
||||
visibility?: string;
|
||||
is_deeplink_only?: boolean;
|
||||
is_premium?: boolean;
|
||||
external_url?: string | null;
|
||||
deep_link?: string | null;
|
||||
image_id?: number | null;
|
||||
image?: unknown;
|
||||
detail_image_id?: number | null;
|
||||
detail_image?: unknown;
|
||||
categories?: Cat[];
|
||||
sub_categories?: Cat[];
|
||||
subcategories?: Cat[];
|
||||
subCategories?: Cat[];
|
||||
}
|
||||
|
||||
function DeepLink({ deep_link }: { deep_link?: string | null }) {
|
||||
return (
|
||||
<div>
|
||||
{deep_link ? (
|
||||
<a
|
||||
href={deep_link}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
dir="ltr"
|
||||
className="inline-block max-w-[220px] truncate text-xs text-primary underline"
|
||||
>
|
||||
{deep_link}
|
||||
</a>
|
||||
) : (
|
||||
<span className="text-xs text-muted">—</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function MediaDeepLinksPage() {
|
||||
const { data, loading, error, reload: reloadHidden } = useList<Media>(
|
||||
"/media",
|
||||
{ deeplink_only: 1 },
|
||||
);
|
||||
// The "use an existing media" picker. /media only lists visible media, so it
|
||||
// must be refetched whenever a media moves in or out of deep-link mode —
|
||||
// otherwise a just-unhidden media is missing from the picker until a reload.
|
||||
const {
|
||||
data: allMedia,
|
||||
loading: allLoading,
|
||||
reload: reloadAll,
|
||||
} = useList<Media>("/media", { count: 500 });
|
||||
const toast = useToast();
|
||||
|
||||
// Both lists change together on every toggle.
|
||||
const reload = useCallback(() => {
|
||||
reloadHidden();
|
||||
reloadAll();
|
||||
}, [reloadHidden, reloadAll]);
|
||||
|
||||
// Non-null while the modal edits an existing row (null = create).
|
||||
const [editing, setEditing] = useState<Media | null>(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
// Source: 'new' (upload / external url) or 'existing' (pick a media record).
|
||||
const [source, setSource] = useState<"new" | "existing">("new");
|
||||
const [existingId, setExistingId] = useState<string>("");
|
||||
|
||||
// Fields for creating a new hidden media.
|
||||
const [title, setTitle] = useState("");
|
||||
const [caption, setCaption] = useState("");
|
||||
const [type, setType] = useState("audio");
|
||||
const [duration, setDuration] = useState("");
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [externalUrl, setExternalUrl] = useState("");
|
||||
const [imageId, setImageId] = useState<number | null>(null);
|
||||
const [imageFile, setImageFile] = useState<File | null>(null);
|
||||
|
||||
const [deleting, setDeleting] = useState<Media | null>(null);
|
||||
const [removing, setRemoving] = useState(false);
|
||||
|
||||
function resetForm() {
|
||||
setSource("new");
|
||||
setExistingId("");
|
||||
setTitle("");
|
||||
setCaption("");
|
||||
setType("audio");
|
||||
setDuration("");
|
||||
setFile(null);
|
||||
setExternalUrl("");
|
||||
setImageId(null);
|
||||
setImageFile(null);
|
||||
}
|
||||
|
||||
function openCreate() {
|
||||
setEditing(null);
|
||||
resetForm();
|
||||
setOpen(true);
|
||||
}
|
||||
|
||||
function openEdit(row: Media) {
|
||||
setEditing(row);
|
||||
setSource("new"); // the edit form always shows the media fields
|
||||
setExistingId("");
|
||||
setTitle(row.title ?? "");
|
||||
setCaption(row.caption ?? "");
|
||||
setType(row.type ?? "audio");
|
||||
setDuration(row.duration != null ? String(row.duration) : "");
|
||||
setFile(null);
|
||||
setExternalUrl(row.external_url ?? "");
|
||||
setImageId(row.image_id ?? null);
|
||||
setImageFile(null);
|
||||
setOpen(true);
|
||||
}
|
||||
|
||||
// Take a media back out of deep-link-only mode (it returns to the lists).
|
||||
async function unhide(row: Media) {
|
||||
try {
|
||||
await apiFetch(`/media/${row.id}`, {
|
||||
method: "POST",
|
||||
body: toFormData({ is_deeplink_only: 0 }),
|
||||
});
|
||||
toast.success("از لینک مستقیم خارج شد.");
|
||||
reload();
|
||||
} catch (err) {
|
||||
toast.error(err instanceof ApiError ? err.message : "خطا در ذخیرهسازی");
|
||||
}
|
||||
}
|
||||
|
||||
async function save(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setSaving(true);
|
||||
try {
|
||||
if (editing) {
|
||||
// Edit an existing deep-link media. It stays deeplink-only.
|
||||
const body = toFormData({
|
||||
title,
|
||||
caption,
|
||||
type,
|
||||
duration,
|
||||
file,
|
||||
external_url: externalUrl,
|
||||
image_id: imageId,
|
||||
image: imageFile,
|
||||
});
|
||||
await apiFetch(`/media/${editing.id}`, { method: "POST", body });
|
||||
toast.success("لینک مستقیم بهروزرسانی شد.");
|
||||
} else if (source === "existing") {
|
||||
// Toggle the chosen existing media to deeplink-only.
|
||||
if (!existingId) {
|
||||
toast.error("رسانهای را انتخاب کنید.");
|
||||
return;
|
||||
}
|
||||
await apiFetch(`/media/${existingId}`, {
|
||||
method: "POST",
|
||||
body: toFormData({ is_deeplink_only: 1 }),
|
||||
});
|
||||
toast.success("رسانه به لینک مستقیم تبدیل شد.");
|
||||
} else {
|
||||
// Create a brand new hidden media (upload / external url).
|
||||
const body = toFormData({
|
||||
title,
|
||||
caption,
|
||||
type,
|
||||
duration,
|
||||
file,
|
||||
external_url: externalUrl,
|
||||
image_id: imageId,
|
||||
image: imageFile,
|
||||
is_deeplink_only: true,
|
||||
});
|
||||
await apiFetch("/media", { method: "POST", body });
|
||||
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(`/media/${deleting.id}`, { method: "DELETE" });
|
||||
toast.success("رسانه حذف شد.");
|
||||
setDeleting(null);
|
||||
reload();
|
||||
} catch (err) {
|
||||
toast.error(err instanceof ApiError ? err.message : "خطا در حذف");
|
||||
} finally {
|
||||
setRemoving(false);
|
||||
}
|
||||
}
|
||||
|
||||
const columns: Column<Media>[] = [
|
||||
{
|
||||
key: "play",
|
||||
header: "پخش",
|
||||
className: "w-20",
|
||||
render: (r) =>
|
||||
r.type === "video" ? (
|
||||
<MediaPreview kind="video" src={pickUrl(r, VIDEO_KEYS)} label={r.title} />
|
||||
) : (
|
||||
<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: "عنوان", render: (r) => r.title ?? "—" },
|
||||
{
|
||||
key: "deep_link",
|
||||
header: "لینک مستقیم",
|
||||
render: (r) => <DeepLink deep_link={r.deep_link} />,
|
||||
},
|
||||
{
|
||||
key: "duration",
|
||||
header: "مدت",
|
||||
render: (r) => formatMinutes(r.duration),
|
||||
},
|
||||
];
|
||||
|
||||
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={() => unhide(row)}
|
||||
aria-label="نمایش در فهرست"
|
||||
title="نمایش در فهرست"
|
||||
>
|
||||
<EyeIcon 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="deeplink-form" type="submit" loading={saving}>
|
||||
ذخیره
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<form
|
||||
id="deeplink-form"
|
||||
onSubmit={save}
|
||||
className="flex flex-col gap-4"
|
||||
>
|
||||
{!editing && (
|
||||
<Field label="منبع رسانه" required>
|
||||
<Select
|
||||
value={source}
|
||||
onChange={(e) => setSource(e.target.value as "new" | "existing")}
|
||||
>
|
||||
<option value="new">بارگذاری رسانه جدید</option>
|
||||
<option value="existing">استفاده از رسانه موجود</option>
|
||||
</Select>
|
||||
</Field>
|
||||
)}
|
||||
|
||||
{source === "existing" ? (
|
||||
<Field label="انتخاب رسانه" required>
|
||||
{allMedia.length ? (
|
||||
<Select value={existingId} onChange={(e) => setExistingId(e.target.value)}>
|
||||
<option value="">انتخاب کنید...</option>
|
||||
{allMedia.map((m) => (
|
||||
<option key={m.id} value={String(m.id)}>
|
||||
{m.title ?? `#${m.id}`}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
) : (
|
||||
<p className="text-xs text-muted">
|
||||
{allLoading ? "در حال بارگذاری..." : "رسانهای موجود نیست."}
|
||||
</p>
|
||||
)}
|
||||
</Field>
|
||||
) : (
|
||||
<>
|
||||
<Field label="عنوان" required>
|
||||
<Input
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
placeholder="مثلاً مدیتیشن شبانه"
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<Field label="توضیحات">
|
||||
<Textarea
|
||||
value={caption}
|
||||
onChange={(e) => setCaption(e.target.value)}
|
||||
placeholder="توضیح کوتاه"
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<Field label="تصویر">
|
||||
<ImagePicker
|
||||
imageId={imageId}
|
||||
onPickId={setImageId}
|
||||
file={imageFile}
|
||||
onPickFile={setImageFile}
|
||||
existingUrl={editing ? pickUrl(editing, IMAGE_KEYS) : null}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<Field label="نوع" required>
|
||||
<Select value={type} onChange={(e) => setType(e.target.value)} required>
|
||||
<option value="audio">صوت</option>
|
||||
<option value="video">ویدیو</option>
|
||||
</Select>
|
||||
</Field>
|
||||
|
||||
<Field
|
||||
label={editing ? "فایل (در صورت تغییر)" : "فایل"}
|
||||
hint="بارگذاری فایل یا وارد کردن لینک خارجی"
|
||||
>
|
||||
<Input
|
||||
type="file"
|
||||
accept="audio/*,video/*"
|
||||
onChange={(e) => {
|
||||
const f = e.target.files?.[0] ?? null;
|
||||
setFile(f);
|
||||
if (f && !title.trim()) setTitle(fileNameToTitle(f.name));
|
||||
}}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<Field label="لینک خارجی" hint="اگر فایل آپلود نمیکنید، آدرس مستقیم فایل.">
|
||||
<Input
|
||||
dir="ltr"
|
||||
value={externalUrl}
|
||||
onChange={(e) => setExternalUrl(e.target.value)}
|
||||
placeholder="https://..."
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<Field label="مدت (دقیقه)">
|
||||
<Input
|
||||
type="number"
|
||||
dir="ltr"
|
||||
value={duration}
|
||||
onChange={(e) => setDuration(e.target.value)}
|
||||
placeholder="مثلاً ۱۰"
|
||||
/>
|
||||
</Field>
|
||||
</>
|
||||
)}
|
||||
|
||||
<p className="rounded-xl border border-border bg-surface-muted p-3 text-xs text-muted">
|
||||
{editing ? (
|
||||
<>
|
||||
این رسانه در فهرست «رسانهها» نمایش داده نمیشود و فقط با لینک مستقیم
|
||||
قابل دسترسی است. برای بازگرداندن آن به فهرست، از دکمه «نمایش در فهرست»
|
||||
استفاده کنید.
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
پس از ذخیره، این رسانه در فهرست «رسانهها» نمایش داده نمیشود و فقط با
|
||||
لینک مستقیم قابل دسترسی است.
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
</form>
|
||||
</Modal>
|
||||
|
||||
<ConfirmDialog
|
||||
open={!!deleting}
|
||||
message={`آیا از حذف «${deleting?.title ?? ""}» مطمئن هستید؟`}
|
||||
loading={removing}
|
||||
onConfirm={confirmDelete}
|
||||
onClose={() => setDeleting(null)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
PageHeader,
|
||||
Badge,
|
||||
} from "@/components/ui";
|
||||
import { EditIcon, PlusIcon, TrashIcon } from "@/components/icons";
|
||||
import { EditIcon, EyeIcon, PlusIcon, TrashIcon } from "@/components/icons";
|
||||
import { formatMinutes, fileNameToTitle } from "@/lib/utils";
|
||||
import { MediaPreview } from "@/components/MediaPreview";
|
||||
import { ImagePicker } from "@/components/ImagePicker";
|
||||
@@ -42,6 +42,8 @@ interface Media {
|
||||
duration?: number;
|
||||
visibility?: string;
|
||||
is_premium?: boolean;
|
||||
is_deeplink_only?: boolean;
|
||||
deep_link?: string | null;
|
||||
external_url?: string | null;
|
||||
image_id?: number | null;
|
||||
image?: unknown;
|
||||
@@ -86,7 +88,13 @@ function ChipMultiSelect({
|
||||
|
||||
export default function MediaPage() {
|
||||
const [search, setSearch] = useState("");
|
||||
const { data, loading, error, reload } = useList<Media>("/media", { search });
|
||||
// Deep-link-only media is hidden from the normal listing, so it needs its own
|
||||
// view here — otherwise media sent to deep links disappears from this page.
|
||||
const [showDeepLinks, setShowDeepLinks] = useState(false);
|
||||
const { data, loading, error, reload } = useList<Media>(
|
||||
"/media",
|
||||
showDeepLinks ? { deeplink_only: 1 } : { search },
|
||||
);
|
||||
const { data: categories } = useList<Category>("/categories", {
|
||||
type: "media",
|
||||
});
|
||||
@@ -203,6 +211,24 @@ export default function MediaPage() {
|
||||
}
|
||||
}
|
||||
|
||||
// Move a media into or out of deep-link-only mode, both directions.
|
||||
async function toggleDeepLink(row: Media) {
|
||||
try {
|
||||
await apiFetch(`/media/${row.id}`, {
|
||||
method: "POST",
|
||||
body: toFormData({ is_deeplink_only: row.is_deeplink_only ? 0 : 1 }),
|
||||
});
|
||||
toast.success(
|
||||
row.is_deeplink_only
|
||||
? "به فهرست عادی بازگشت."
|
||||
: "به لینک مستقیم تبدیل شد.",
|
||||
);
|
||||
reload();
|
||||
} catch (err) {
|
||||
toast.error(err instanceof ApiError ? err.message : "خطا در ذخیرهسازی");
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmDelete() {
|
||||
if (!deleting) return;
|
||||
setRemoving(true);
|
||||
@@ -258,6 +284,25 @@ export default function MediaPage() {
|
||||
header: "مدت",
|
||||
render: (r) => formatMinutes(r.duration),
|
||||
},
|
||||
{
|
||||
key: "deep_link",
|
||||
header: "لینک مستقیم",
|
||||
className: "w-56",
|
||||
render: (r) =>
|
||||
r.is_deeplink_only ? (
|
||||
<a
|
||||
href={r.deep_link ?? undefined}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
dir="ltr"
|
||||
className="inline-block max-w-[200px] truncate text-xs text-primary underline"
|
||||
>
|
||||
{r.deep_link ?? "—"}
|
||||
</a>
|
||||
) : (
|
||||
<span className="text-xs text-muted">—</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "is_premium",
|
||||
header: "ویژه",
|
||||
@@ -282,11 +327,19 @@ export default function MediaPage() {
|
||||
}
|
||||
/>
|
||||
|
||||
<div className="mb-4 max-w-sm">
|
||||
<Input
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder="جستجو در رسانهها..."
|
||||
<div className="mb-4 flex items-center gap-4">
|
||||
<div className="max-w-sm flex-1">
|
||||
<Input
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder="جستجو در رسانهها..."
|
||||
disabled={showDeepLinks}
|
||||
/>
|
||||
</div>
|
||||
<Switch
|
||||
checked={showDeepLinks}
|
||||
onChange={setShowDeepLinks}
|
||||
label="فقط لینکهای مستقیم"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -296,7 +349,11 @@ export default function MediaPage() {
|
||||
loading={loading}
|
||||
error={error}
|
||||
onRetry={reload}
|
||||
emptyMessage="هنوز رسانهای اضافه نکردهاید. اولین رسانه را بارگذاری کنید."
|
||||
emptyMessage={
|
||||
showDeepLinks
|
||||
? "هیچ رسانه لینک مستقیمی وجود ندارد."
|
||||
: "هنوز رسانهای اضافه نکردهاید. اولین رسانه را بارگذاری کنید."
|
||||
}
|
||||
emptyAction={
|
||||
<Button icon={<PlusIcon className="h-4 w-4" />} onClick={openCreate}>
|
||||
رسانه جدید
|
||||
@@ -307,6 +364,23 @@ export default function MediaPage() {
|
||||
<Button variant="ghost" onClick={() => openEdit(row)} aria-label="ویرایش">
|
||||
<EditIcon className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => toggleDeepLink(row)}
|
||||
aria-label={
|
||||
row.is_deeplink_only
|
||||
? "بازگرداندن به فهرست"
|
||||
: "تبدیل به لینک مستقیم"
|
||||
}
|
||||
title={
|
||||
row.is_deeplink_only
|
||||
? "بازگرداندن به فهرست"
|
||||
: "تبدیل به لینک مستقیم"
|
||||
}
|
||||
className={row.is_deeplink_only ? "text-primary" : undefined}
|
||||
>
|
||||
<EyeIcon className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => setDeleting(row)}
|
||||
|
||||
@@ -6,6 +6,7 @@ import { useList } from "@/lib/useResource";
|
||||
import { useToast } from "@/components/toast";
|
||||
import { DataTable, type Column } from "@/components/DataTable";
|
||||
import {
|
||||
Badge,
|
||||
Button,
|
||||
ConfirmDialog,
|
||||
Field,
|
||||
@@ -13,6 +14,7 @@ import {
|
||||
Textarea,
|
||||
Modal,
|
||||
PageHeader,
|
||||
Switch,
|
||||
} from "@/components/ui";
|
||||
import { EditIcon, PlusIcon, TrashIcon } from "@/components/icons";
|
||||
import { ImagePicker } from "@/components/ImagePicker";
|
||||
@@ -28,6 +30,9 @@ interface Playlist {
|
||||
image?: unknown;
|
||||
detail_image_id?: number | null;
|
||||
detail_image?: unknown;
|
||||
is_premium?: boolean;
|
||||
categories?: { id: number; name?: string }[];
|
||||
subcategories?: { id: number; name?: string }[];
|
||||
}
|
||||
|
||||
interface MusicCategory {
|
||||
@@ -53,6 +58,7 @@ export default function MusicPlaylistsPage() {
|
||||
const [imageFile, setImageFile] = useState<File | null>(null);
|
||||
const [detailImageId, setDetailImageId] = useState<number | null>(null);
|
||||
const [detailImageFile, setDetailImageFile] = useState<File | null>(null);
|
||||
const [isPremium, setIsPremium] = useState(false);
|
||||
|
||||
const [deleting, setDeleting] = useState<Playlist | null>(null);
|
||||
const [removing, setRemoving] = useState(false);
|
||||
@@ -71,6 +77,7 @@ export default function MusicPlaylistsPage() {
|
||||
setImageFile(null);
|
||||
setDetailImageId(null);
|
||||
setDetailImageFile(null);
|
||||
setIsPremium(false);
|
||||
setOpen(true);
|
||||
}
|
||||
function openEdit(row: Playlist) {
|
||||
@@ -83,6 +90,7 @@ export default function MusicPlaylistsPage() {
|
||||
setImageFile(null);
|
||||
setDetailImageId(row.detail_image_id ?? null);
|
||||
setDetailImageFile(null);
|
||||
setIsPremium(row.is_premium ?? false);
|
||||
setOpen(true);
|
||||
}
|
||||
|
||||
@@ -101,6 +109,7 @@ export default function MusicPlaylistsPage() {
|
||||
image: imageFile,
|
||||
detail_image_id: detailImageId,
|
||||
detail_image: detailImageFile,
|
||||
is_premium: isPremium,
|
||||
}),
|
||||
});
|
||||
toast.success("پلیلیست ویرایش شد.");
|
||||
@@ -117,6 +126,7 @@ export default function MusicPlaylistsPage() {
|
||||
image: imageFile,
|
||||
detail_image_id: detailImageId,
|
||||
detail_image: detailImageFile,
|
||||
is_premium: isPremium,
|
||||
}),
|
||||
});
|
||||
toast.success("پلیلیست افزوده شد.");
|
||||
@@ -156,11 +166,30 @@ export default function MusicPlaylistsPage() {
|
||||
),
|
||||
},
|
||||
{ key: "name", header: "نام" },
|
||||
{
|
||||
key: "subcategories",
|
||||
header: "زیردسته",
|
||||
render: (r) =>
|
||||
r.subcategories?.length
|
||||
? r.subcategories.map((s) => s.name).filter(Boolean).join("، ")
|
||||
: "—",
|
||||
},
|
||||
{
|
||||
key: "description",
|
||||
header: "توضیحات",
|
||||
render: (r) => r.description ?? "—",
|
||||
},
|
||||
{
|
||||
key: "is_premium",
|
||||
header: "ویژه",
|
||||
className: "w-20",
|
||||
render: (r) =>
|
||||
r.is_premium ? (
|
||||
<Badge tone="primary">ویژه</Badge>
|
||||
) : (
|
||||
<Badge tone="neutral">رایگان</Badge>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
@@ -257,6 +286,8 @@ export default function MusicPlaylistsPage() {
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<Switch checked={isPremium} onChange={setIsPremium} label="ویژه (پرمیوم)" />
|
||||
|
||||
{!editing && (
|
||||
<>
|
||||
<Field label="دستهبندیها">
|
||||
|
||||
@@ -0,0 +1,562 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { apiFetch, getApproToken } from "@/lib/api";
|
||||
import { APPRO_BASE_URL, MEDITATION_BASE_URL } from "@/lib/config";
|
||||
import { usePaginated } from "@/lib/useResource";
|
||||
import { DataTable, type Column } from "@/components/DataTable";
|
||||
import {
|
||||
Badge,
|
||||
Button,
|
||||
Card,
|
||||
Modal,
|
||||
PageHeader,
|
||||
Field,
|
||||
Input,
|
||||
Pagination,
|
||||
Select,
|
||||
Spinner,
|
||||
} from "@/components/ui";
|
||||
import { DownloadIcon, EyeIcon } from "@/components/icons";
|
||||
import { useToast } from "@/components/toast";
|
||||
import { exportToExcel, mapWithConcurrency } from "@/lib/excel";
|
||||
import { toFa } from "@/lib/utils";
|
||||
|
||||
interface MeditationUser {
|
||||
id: number;
|
||||
full_name?: string;
|
||||
first_name?: string;
|
||||
last_name?: string;
|
||||
age?: number | null;
|
||||
gender?: number | null;
|
||||
email?: string | null;
|
||||
mobile?: string | null;
|
||||
identifier?: string | null;
|
||||
created_at?: string;
|
||||
answers_count?: number;
|
||||
questions_answered?: number;
|
||||
}
|
||||
|
||||
interface ApproUser {
|
||||
id: number;
|
||||
uuid?: string;
|
||||
first_name?: string;
|
||||
last_name?: string;
|
||||
full_name?: string;
|
||||
age?: number | null;
|
||||
gender?: number | null;
|
||||
email?: string | null;
|
||||
mobile?: string | null;
|
||||
birthday?: string | null;
|
||||
created_at?: string;
|
||||
}
|
||||
|
||||
interface SurveyAnswerItem {
|
||||
question_id: number;
|
||||
question?: string;
|
||||
type?: string;
|
||||
answers: { option_id: number; label: string }[];
|
||||
}
|
||||
|
||||
interface DetailData {
|
||||
appro: ApproUser | null;
|
||||
survey_answers: SurveyAnswerItem[];
|
||||
answers_count?: number;
|
||||
questions_answered?: number;
|
||||
}
|
||||
|
||||
// Confirmation password for the full export. This is a guard against an
|
||||
// accidental click, not a security boundary — it ships in the client bundle, so
|
||||
// anyone with the page can read it. Real protection belongs on the API side.
|
||||
const EXPORT_PASSWORD = "amnk1380";
|
||||
|
||||
const GENDER_LABELS: Record<number, string> = {
|
||||
1: "مرد",
|
||||
2: "زن",
|
||||
};
|
||||
|
||||
function faDate(value?: string): string {
|
||||
if (!value) return "—";
|
||||
try {
|
||||
return toFa(new Date(value).toLocaleDateString("fa-IR"));
|
||||
} catch {
|
||||
return "—";
|
||||
}
|
||||
}
|
||||
|
||||
export default function UsersPage() {
|
||||
const [answered, setAnswered] = useState<string>("");
|
||||
const { data, meta, page, setPage, loading, error, reload } =
|
||||
usePaginated<MeditationUser>("/admin/survey-users", {
|
||||
perPage: 20,
|
||||
query: answered ? { answered } : undefined,
|
||||
});
|
||||
|
||||
const toast = useToast();
|
||||
const [exporting, setExporting] = useState(false);
|
||||
const [exportProgress, setExportProgress] = useState(0);
|
||||
|
||||
// The full export hammers the API with one request per user, so it sits
|
||||
// behind a confirmation password instead of being one stray click away.
|
||||
const [gateOpen, setGateOpen] = useState(false);
|
||||
const [gatePassword, setGatePassword] = useState("");
|
||||
const [gateError, setGateError] = useState<string | null>(null);
|
||||
|
||||
const [detailUser, setDetailUser] = useState<MeditationUser | null>(null);
|
||||
const [detailData, setDetailData] = useState<DetailData | null>(null);
|
||||
const [detailOpen, setDetailOpen] = useState(false);
|
||||
const [detailLoading, setDetailLoading] = useState(false);
|
||||
|
||||
async function openDetail(user: MeditationUser) {
|
||||
setDetailOpen(true);
|
||||
setDetailLoading(true);
|
||||
setDetailUser(user);
|
||||
setDetailData(null);
|
||||
|
||||
const [appro, survey] = await Promise.all([
|
||||
user.mobile
|
||||
? apiFetch<{ data: ApproUser[] }>("/admin/users", {
|
||||
query: { mobile: user.mobile, per_page: 1 },
|
||||
baseUrl: APPRO_BASE_URL,
|
||||
headers: { Authorization: `Bearer ${getApproToken()}` },
|
||||
}).then((r) => r.data?.[0] ?? null)
|
||||
: Promise.resolve(null),
|
||||
apiFetch<{ survey_answers: SurveyAnswerItem[]; answers_count?: number; questions_answered?: number }>(
|
||||
`/admin/survey-users/${user.identifier || user.id}`,
|
||||
{ baseUrl: MEDITATION_BASE_URL },
|
||||
).catch(() => ({ survey_answers: [], answers_count: undefined, questions_answered: undefined })),
|
||||
]);
|
||||
|
||||
// Sync approagency data back to meditation DB if user has null fields
|
||||
if (appro && user.mobile && (!user.first_name || user.age == null || user.gender == null)) {
|
||||
apiFetch(`/admin/survey-users/${user.identifier || user.id}`, {
|
||||
method: "PATCH",
|
||||
baseUrl: MEDITATION_BASE_URL,
|
||||
body: {
|
||||
first_name: appro.first_name,
|
||||
last_name: appro.last_name,
|
||||
age: appro.age,
|
||||
gender: appro.gender,
|
||||
birthday: appro.birthday,
|
||||
identifier: appro.uuid,
|
||||
email: appro.email,
|
||||
},
|
||||
}).catch(() => {}); // fire-and-forget
|
||||
}
|
||||
|
||||
setDetailData({
|
||||
appro,
|
||||
survey_answers: survey.survey_answers ?? [],
|
||||
answers_count: survey.answers_count,
|
||||
questions_answered: survey.questions_answered,
|
||||
});
|
||||
setDetailLoading(false);
|
||||
}
|
||||
|
||||
function genderLabel(value?: number | null) {
|
||||
return value != null ? GENDER_LABELS[value] ?? "—" : "—";
|
||||
}
|
||||
|
||||
function openGate() {
|
||||
if (exporting) return;
|
||||
setGatePassword("");
|
||||
setGateError(null);
|
||||
setGateOpen(true);
|
||||
}
|
||||
|
||||
function submitGate() {
|
||||
if (gatePassword !== EXPORT_PASSWORD) {
|
||||
setGateError("رمز عبور نادرست است.");
|
||||
return;
|
||||
}
|
||||
setGateOpen(false);
|
||||
setGatePassword("");
|
||||
setGateError(null);
|
||||
void exportAll();
|
||||
}
|
||||
|
||||
// Full export: walks every page of the current filter, then pulls each user's
|
||||
// survey answers so the sheet gets one column per question.
|
||||
async function exportAll() {
|
||||
if (exporting) return;
|
||||
setExporting(true);
|
||||
setExportProgress(0);
|
||||
|
||||
try {
|
||||
const users: MeditationUser[] = [];
|
||||
let currentPage = 1;
|
||||
let lastPage = 1;
|
||||
|
||||
do {
|
||||
const res = await apiFetch<{
|
||||
data: MeditationUser[];
|
||||
last_page?: number;
|
||||
meta?: { last_page?: number };
|
||||
}>("/admin/survey-users", {
|
||||
baseUrl: MEDITATION_BASE_URL,
|
||||
query: {
|
||||
page: currentPage,
|
||||
per_page: 100,
|
||||
...(answered ? { answered } : {}),
|
||||
},
|
||||
});
|
||||
users.push(...(res.data ?? []));
|
||||
lastPage = Number(res.last_page ?? res.meta?.last_page ?? 1);
|
||||
currentPage++;
|
||||
} while (currentPage <= lastPage);
|
||||
|
||||
if (users.length === 0) {
|
||||
toast.error("کاربری برای خروجی گرفتن وجود ندارد.");
|
||||
return;
|
||||
}
|
||||
|
||||
const details = await mapWithConcurrency(
|
||||
users,
|
||||
6,
|
||||
(user) =>
|
||||
apiFetch<{ survey_answers?: SurveyAnswerItem[] }>(
|
||||
`/admin/survey-users/${user.identifier || user.id}`,
|
||||
{ baseUrl: MEDITATION_BASE_URL },
|
||||
)
|
||||
.then((r) => r.survey_answers ?? [])
|
||||
.catch(() => [] as SurveyAnswerItem[]),
|
||||
(done, total) => setExportProgress(Math.round((done / total) * 100)),
|
||||
);
|
||||
|
||||
// Union of questions, in first-seen order, so every row lines up.
|
||||
const questionOrder: number[] = [];
|
||||
const questionTitles = new Map<number, string>();
|
||||
for (const answers of details) {
|
||||
for (const item of answers) {
|
||||
if (!questionTitles.has(item.question_id)) {
|
||||
questionTitles.set(item.question_id, item.question || `سوال ${item.question_id}`);
|
||||
questionOrder.push(item.question_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const headers = [
|
||||
"شناسه",
|
||||
"نام",
|
||||
"سن",
|
||||
"جنسیت",
|
||||
"ایمیل",
|
||||
"موبایل",
|
||||
"تاریخ ثبتنام",
|
||||
"تعداد پاسخها",
|
||||
"سوالات پاسخ داده شده",
|
||||
...questionOrder.map((id) => questionTitles.get(id)!),
|
||||
];
|
||||
|
||||
const rows = users.map((user, i) => {
|
||||
const byQuestion = new Map(
|
||||
details[i].map((item) => [
|
||||
item.question_id,
|
||||
item.answers.map((a) => a.label).join("، "),
|
||||
]),
|
||||
);
|
||||
return [
|
||||
user.id,
|
||||
user.full_name || [user.first_name, user.last_name].filter(Boolean).join(" ") || "—",
|
||||
user.age ?? "—",
|
||||
genderLabel(user.gender),
|
||||
user.email || "—",
|
||||
user.mobile || "—",
|
||||
faDate(user.created_at),
|
||||
user.answers_count ?? "—",
|
||||
user.questions_answered ?? "—",
|
||||
...questionOrder.map((id) => byQuestion.get(id) || ""),
|
||||
];
|
||||
});
|
||||
|
||||
const suffix = answered === "1" ? "-answered" : answered === "0" ? "-unanswered" : "";
|
||||
exportToExcel(`survey-users${suffix}`, headers, rows, "کاربران");
|
||||
toast.success(`خروجی اکسل ${toFa(users.length)} کاربر آماده شد.`);
|
||||
} catch {
|
||||
toast.error("خطا در تهیه خروجی اکسل.");
|
||||
} finally {
|
||||
setExporting(false);
|
||||
setExportProgress(0);
|
||||
}
|
||||
}
|
||||
|
||||
// Single-user export: profile fields plus that user's survey answers, taken
|
||||
// straight from what the open modal already loaded.
|
||||
function exportDetail() {
|
||||
if (!detailUser || !detailData) return;
|
||||
const appro = detailData.appro;
|
||||
|
||||
const headers = ["عنوان", "مقدار"];
|
||||
const rows: (string | number)[][] = [
|
||||
["شناسه", detailUser.id],
|
||||
["نام", userName || "—"],
|
||||
["سن", (appro?.age ?? detailUser.age) ?? "—"],
|
||||
["جنسیت", genderLabel(appro?.gender ?? detailUser.gender)],
|
||||
["تاریخ تولد", appro?.birthday ? faDate(appro.birthday) : "—"],
|
||||
["ایمیل", (appro?.email ?? detailUser.email) || "—"],
|
||||
["موبایل", detailUser.mobile || "—"],
|
||||
["تاریخ ثبتنام", faDate(detailUser.created_at)],
|
||||
["تعداد پاسخها", detailData.answers_count ?? "—"],
|
||||
["سوالات پاسخ داده شده", detailData.questions_answered ?? "—"],
|
||||
["", ""],
|
||||
["سوال", "پاسخ"],
|
||||
...detailData.survey_answers.map((item) => [
|
||||
item.question || `سوال ${item.question_id}`,
|
||||
item.answers.map((a) => a.label).join("، ") || "بدون پاسخ",
|
||||
]),
|
||||
];
|
||||
|
||||
exportToExcel(`survey-user-${detailUser.id}`, headers, rows, "جزئیات کاربر");
|
||||
}
|
||||
|
||||
const columns: Column<MeditationUser>[] = [
|
||||
{ key: "id", header: "شناسه", render: (r) => toFa(r.id), className: "w-20" },
|
||||
{
|
||||
key: "full_name",
|
||||
header: "نام",
|
||||
render: (r) => r.full_name || [r.first_name, r.last_name].filter(Boolean).join(" ") || "—",
|
||||
},
|
||||
{
|
||||
key: "questions_answered",
|
||||
header: "پاسخ به سوالات",
|
||||
className: "w-32",
|
||||
render: (r) =>
|
||||
r.questions_answered != null ? toFa(r.questions_answered) : "—",
|
||||
},
|
||||
{
|
||||
key: "created_at",
|
||||
header: "تاریخ ثبتنام",
|
||||
className: "w-32",
|
||||
render: (r) => faDate(r.created_at),
|
||||
},
|
||||
];
|
||||
|
||||
const a = detailData?.appro;
|
||||
const s = detailData;
|
||||
const userName = a
|
||||
? a.full_name || [a.first_name, a.last_name].filter(Boolean).join(" ") || ""
|
||||
: detailUser
|
||||
? detailUser.full_name || [detailUser.first_name, detailUser.last_name].filter(Boolean).join(" ") || ""
|
||||
: "";
|
||||
|
||||
return (
|
||||
<div>
|
||||
<PageHeader
|
||||
title="کاربران نظرسنجی"
|
||||
subtitle="فهرست کاربران و پاسخهای نظرسنجی آنها"
|
||||
action={
|
||||
<Button onClick={openGate} disabled={exporting}>
|
||||
{exporting ? (
|
||||
<>
|
||||
<Spinner className="h-4 w-4" />
|
||||
<span>در حال آمادهسازی… {toFa(exportProgress)}٪</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<DownloadIcon className="h-4 w-4" />
|
||||
<span>خروجی اکسل</span>
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
|
||||
<div className="mb-4 flex items-center gap-3">
|
||||
<label className="text-sm text-muted">فیلتر:</label>
|
||||
<Select value={answered} onChange={(e) => { setAnswered(e.target.value); setPage(1); }}>
|
||||
<option value="">همه کاربران</option>
|
||||
<option value="1">پاسخ دادهاند</option>
|
||||
<option value="0">پاسخ ندادهاند</option>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
rows={data}
|
||||
loading={loading}
|
||||
error={error}
|
||||
onRetry={reload}
|
||||
emptyTitle="کاربری یافت نشد"
|
||||
emptyMessage="هنوز کاربری در نظرسنجی شرکت نکرده است."
|
||||
actions={(row) => (
|
||||
<Button variant="ghost" onClick={() => openDetail(row)} aria-label="جزئیات">
|
||||
<EyeIcon className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
/>
|
||||
|
||||
{meta && (
|
||||
<Pagination
|
||||
page={page}
|
||||
lastPage={meta.last_page}
|
||||
total={meta.total}
|
||||
onChange={setPage}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Modal
|
||||
open={gateOpen}
|
||||
onClose={() => setGateOpen(false)}
|
||||
title="تایید خروجی اکسل"
|
||||
footer={
|
||||
<>
|
||||
<Button onClick={submitGate} disabled={!gatePassword}>
|
||||
تایید و شروع خروجی
|
||||
</Button>
|
||||
<Button variant="secondary" onClick={() => setGateOpen(false)}>
|
||||
انصراف
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
submitGate();
|
||||
}}
|
||||
className="flex flex-col gap-3"
|
||||
>
|
||||
<p className="text-sm text-muted">
|
||||
این عملیات اطلاعات همه کاربران و پاسخهای نظرسنجی را از سرور
|
||||
میخواند و ممکن است بار زیادی روی سرور بگذارد. برای ادامه رمز عبور
|
||||
را وارد کنید.
|
||||
</p>
|
||||
<Field label="رمز عبور" required>
|
||||
<Input
|
||||
type="password"
|
||||
autoFocus
|
||||
value={gatePassword}
|
||||
onChange={(e) => {
|
||||
setGatePassword(e.target.value);
|
||||
setGateError(null);
|
||||
}}
|
||||
placeholder="رمز عبور خروجی"
|
||||
dir="ltr"
|
||||
/>
|
||||
</Field>
|
||||
{gateError && <p className="text-sm text-danger">{gateError}</p>}
|
||||
{/* Lets Enter submit the form even though the button lives in the footer. */}
|
||||
<button type="submit" className="hidden" aria-hidden />
|
||||
</form>
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
open={detailOpen}
|
||||
onClose={() => setDetailOpen(false)}
|
||||
title={userName ? `جزئیات کاربر — ${userName}` : "جزئیات کاربر"}
|
||||
footer={
|
||||
<>
|
||||
<Button
|
||||
onClick={exportDetail}
|
||||
disabled={detailLoading || !detailData}
|
||||
>
|
||||
<DownloadIcon className="h-4 w-4" />
|
||||
<span>خروجی اکسل</span>
|
||||
</Button>
|
||||
<Button variant="secondary" onClick={() => setDetailOpen(false)}>
|
||||
بستن
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{detailLoading && (
|
||||
<div className="flex justify-center py-8">
|
||||
<Spinner className="h-6 w-6" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{s && !detailLoading && (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<Card>
|
||||
<p className="text-sm text-muted">نام</p>
|
||||
<p className="mt-1 font-bold text-foreground">{userName || "—"}</p>
|
||||
</Card>
|
||||
<Card>
|
||||
<p className="text-sm text-muted">سن</p>
|
||||
<p className="mt-1 font-bold text-foreground">
|
||||
{(a?.age ?? detailUser?.age) != null ? toFa(a?.age ?? detailUser!.age!) : "—"}
|
||||
</p>
|
||||
</Card>
|
||||
<Card>
|
||||
<p className="text-sm text-muted">جنسیت</p>
|
||||
<p className="mt-1 font-bold text-foreground">
|
||||
{(a?.gender ?? detailUser?.gender) != null
|
||||
? GENDER_LABELS[a?.gender ?? detailUser!.gender!] ?? "—"
|
||||
: "—"}
|
||||
</p>
|
||||
</Card>
|
||||
<Card>
|
||||
<p className="text-sm text-muted">تاریخ تولد</p>
|
||||
<p className="mt-1 font-bold text-foreground">
|
||||
{a?.birthday ? faDate(a.birthday) : "—"}
|
||||
</p>
|
||||
</Card>
|
||||
<Card>
|
||||
<p className="text-sm text-muted">ایمیل</p>
|
||||
<p className="mt-1 font-bold text-foreground" dir="ltr">
|
||||
{(a?.email ?? detailUser?.email) || "—"}
|
||||
</p>
|
||||
</Card>
|
||||
<Card>
|
||||
<p className="text-sm text-muted">موبایل</p>
|
||||
<p className="mt-1 font-bold text-foreground" dir="ltr">
|
||||
{detailUser?.mobile || "—"}
|
||||
</p>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<Card>
|
||||
<p className="text-sm text-muted">تعداد پاسخها</p>
|
||||
<p className="mt-1 font-bold text-foreground">
|
||||
{s.answers_count != null ? toFa(s.answers_count) : "—"}
|
||||
</p>
|
||||
</Card>
|
||||
<Card>
|
||||
<p className="text-sm text-muted">سوالات پاسخ داده شده</p>
|
||||
<p className="mt-1 font-bold text-foreground">
|
||||
{s.questions_answered != null ? toFa(s.questions_answered) : "—"}
|
||||
</p>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{s.survey_answers.length > 0 ? (
|
||||
<div>
|
||||
<h3 className="mb-3 text-sm font-bold text-foreground">
|
||||
پاسخهای نظرسنجی
|
||||
</h3>
|
||||
<div className="flex flex-col gap-2">
|
||||
{s.survey_answers.map((item) => (
|
||||
<div
|
||||
key={item.question_id}
|
||||
className="rounded-xl border border-border p-3"
|
||||
>
|
||||
<p className="text-sm font-medium text-foreground">
|
||||
{item.question}
|
||||
</p>
|
||||
<div className="mt-1 flex flex-wrap gap-1">
|
||||
{item.answers.map((a) => (
|
||||
<Badge key={a.option_id} tone="primary">
|
||||
{a.label}
|
||||
</Badge>
|
||||
))}
|
||||
{item.answers.length === 0 && (
|
||||
<span className="text-xs text-muted">بدون پاسخ</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-center text-sm text-muted">
|
||||
این کاربر هنوز به هیچ سوالی پاسخ نداده است.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+1
-1
@@ -16,7 +16,7 @@ export const metadata: Metadata = {
|
||||
|
||||
// Runs before paint to set the `.dark` class from saved preference / system,
|
||||
// avoiding a light flash on load. Kept inline + minimal on purpose.
|
||||
const noFlashTheme = `(function(){try{var t=localStorage.getItem('aram_theme');if(!t){t=window.matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light';}if(t==='dark'){document.documentElement.classList.add('dark');}}catch(e){}})();`;
|
||||
const noFlashTheme = `(function(){try{var t=localStorage.getItem('aram_theme');if(t==='dark'||(t!=='light'&&(t='system',window.matchMedia('(prefers-color-scheme: dark)').matches))){document.documentElement.classList.add('dark');}}catch(e){}})();`;
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
|
||||
@@ -1,21 +1,33 @@
|
||||
"use client";
|
||||
|
||||
import { useTheme } from "@/lib/theme";
|
||||
import { SunIcon, MoonIcon } from "./icons";
|
||||
import { SunIcon, MoonIcon, MonitorIcon } from "./icons";
|
||||
|
||||
const LABELS = {
|
||||
light: "حالت روشن",
|
||||
dark: "حالت تاریک",
|
||||
system: "حالت سیستم",
|
||||
};
|
||||
|
||||
const ICONS = {
|
||||
light: SunIcon,
|
||||
dark: MoonIcon,
|
||||
system: MonitorIcon,
|
||||
};
|
||||
|
||||
export function ThemeToggle({ className }: { className?: string }) {
|
||||
const { theme, toggle } = useTheme();
|
||||
const dark = theme === "dark";
|
||||
const Icon = ICONS[theme];
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggle}
|
||||
aria-label={dark ? "حالت روشن" : "حالت تاریک"}
|
||||
title={dark ? "حالت روشن" : "حالت تاریک"}
|
||||
aria-label={LABELS[theme]}
|
||||
title={LABELS[theme]}
|
||||
className={`rounded-lg p-2 text-muted transition hover:bg-surface-muted hover:text-foreground ${className ?? ""}`}
|
||||
>
|
||||
{dark ? <SunIcon className="h-5 w-5" /> : <MoonIcon className="h-5 w-5" />}
|
||||
<Icon className="h-5 w-5" />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -24,6 +24,14 @@ export const PlusIcon = (p: IconProps) => (
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const DownloadIcon = (p: IconProps) => (
|
||||
<svg {...base(p)}>
|
||||
<path d="M12 3v12" />
|
||||
<path d="m7 10 5 5 5-5" />
|
||||
<path d="M5 21h14" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const EditIcon = (p: IconProps) => (
|
||||
<svg {...base(p)}>
|
||||
<path d="M12 20h9" />
|
||||
@@ -196,3 +204,17 @@ export const TagIcon = (p: IconProps) => (
|
||||
<circle cx="7.5" cy="7.5" r="1.2" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const UserIcon = (p: IconProps) => (
|
||||
<svg {...base(p)}>
|
||||
<circle cx="12" cy="8" r="4" />
|
||||
<path d="M6 21v-2a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v2" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const MonitorIcon = (p: IconProps) => (
|
||||
<svg {...base(p)}>
|
||||
<rect x="2" y="3" width="20" height="14" rx="2" />
|
||||
<path d="M8 21h8M12 17v4" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
+27
-2
@@ -1,7 +1,11 @@
|
||||
// Thin fetch wrapper for the meditation API. The app is a static SPA, so every
|
||||
// call runs in the browser and carries the bearer token from localStorage.
|
||||
|
||||
import { MEDITATION_BASE_URL, TOKEN_STORAGE_KEY } from "./config";
|
||||
import {
|
||||
APPRO_TOKEN_STORAGE_KEY,
|
||||
MEDITATION_BASE_URL,
|
||||
TOKEN_STORAGE_KEY,
|
||||
} from "./config";
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
@@ -29,6 +33,21 @@ export function clearToken() {
|
||||
window.localStorage.removeItem(TOKEN_STORAGE_KEY);
|
||||
}
|
||||
|
||||
export function getApproToken(): string | null {
|
||||
if (typeof window === "undefined") return null;
|
||||
return window.localStorage.getItem(APPRO_TOKEN_STORAGE_KEY);
|
||||
}
|
||||
|
||||
export function setApproToken(token: string) {
|
||||
if (typeof window === "undefined") return;
|
||||
window.localStorage.setItem(APPRO_TOKEN_STORAGE_KEY, token);
|
||||
}
|
||||
|
||||
export function clearApproToken() {
|
||||
if (typeof window === "undefined") return;
|
||||
window.localStorage.removeItem(APPRO_TOKEN_STORAGE_KEY);
|
||||
}
|
||||
|
||||
type Query = Record<string, string | number | boolean | undefined | null>;
|
||||
|
||||
interface RequestOptions {
|
||||
@@ -40,6 +59,8 @@ interface RequestOptions {
|
||||
baseUrl?: string;
|
||||
// Skip attaching the bearer token (used by the login calls).
|
||||
auth?: boolean;
|
||||
// Extra headers to merge into the request.
|
||||
headers?: Record<string, string>;
|
||||
}
|
||||
|
||||
function buildUrl(path: string, query?: Query, baseUrl = MEDITATION_BASE_URL) {
|
||||
@@ -60,7 +81,7 @@ export async function apiFetch<T = unknown>(
|
||||
path: string,
|
||||
options: RequestOptions = {},
|
||||
): Promise<T> {
|
||||
const { method = "GET", body, query, baseUrl, auth = true } = options;
|
||||
const { method = "GET", body, query, baseUrl, auth = true, headers: extraHeaders } = options;
|
||||
|
||||
const headers: Record<string, string> = { Accept: "application/json" };
|
||||
|
||||
@@ -69,6 +90,10 @@ export async function apiFetch<T = unknown>(
|
||||
if (token) headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
if (extraHeaders) {
|
||||
Object.assign(headers, extraHeaders);
|
||||
}
|
||||
|
||||
let payload: BodyInit | undefined;
|
||||
if (body instanceof FormData) {
|
||||
payload = body; // browser sets multipart Content-Type + boundary
|
||||
|
||||
+6
-8
@@ -13,7 +13,6 @@ import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useState,
|
||||
} from "react";
|
||||
import { APPRO_BASE_URL, MEDITATION_BASE_URL, PACKAGE_NAME } from "./config";
|
||||
@@ -21,8 +20,10 @@ import {
|
||||
ApiError,
|
||||
apiFetch,
|
||||
clearToken,
|
||||
clearApproToken,
|
||||
getToken,
|
||||
setToken,
|
||||
setApproToken,
|
||||
toFormData,
|
||||
} from "./api";
|
||||
|
||||
@@ -73,16 +74,12 @@ async function meditationLogin(approoToken: string): Promise<string> {
|
||||
}
|
||||
|
||||
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
const [token, setTokenState] = useState<string | null>(null);
|
||||
const [ready, setReady] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setTokenState(getToken());
|
||||
setReady(true);
|
||||
}, []);
|
||||
const [token, setTokenState] = useState<string | null>(() => getToken());
|
||||
const [ready] = useState(true);
|
||||
|
||||
const login = useCallback(async (identifier: string, password: string) => {
|
||||
const approoToken = await approAgencyLogin(identifier, password);
|
||||
setApproToken(approoToken);
|
||||
const medToken = await meditationLogin(approoToken);
|
||||
setToken(medToken);
|
||||
setTokenState(medToken);
|
||||
@@ -90,6 +87,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
|
||||
const logout = useCallback(() => {
|
||||
clearToken();
|
||||
clearApproToken();
|
||||
setTokenState(null);
|
||||
}, []);
|
||||
|
||||
|
||||
+2
-1
@@ -19,5 +19,6 @@ export const ASSET_BASE_URL =
|
||||
process.env.NEXT_PUBLIC_ASSET_BASE_URL ??
|
||||
MEDITATION_BASE_URL.replace(/\/api\/?$/, "");
|
||||
|
||||
// localStorage key for the meditation bearer token.
|
||||
// localStorage keys for the meditation bearer token and approagency token.
|
||||
export const TOKEN_STORAGE_KEY = "meditation_admin_token";
|
||||
export const APPRO_TOKEN_STORAGE_KEY = "approagency_admin_token";
|
||||
|
||||
+304
@@ -0,0 +1,304 @@
|
||||
// Dependency-free .xlsx writer. An .xlsx is just a ZIP of XML parts, so we
|
||||
// build the parts by hand and pack them with STORE (no compression) — that
|
||||
// keeps us from needing a deflate implementation while still producing a file
|
||||
// Excel opens natively, with no "format and extension don't match" warning.
|
||||
|
||||
type Cell = string | number | null | undefined;
|
||||
|
||||
/* --------------------------------- ZIP ---------------------------------- */
|
||||
|
||||
const CRC_TABLE = (() => {
|
||||
const table = new Uint32Array(256);
|
||||
for (let i = 0; i < 256; i++) {
|
||||
let c = i;
|
||||
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
||||
table[i] = c >>> 0;
|
||||
}
|
||||
return table;
|
||||
})();
|
||||
|
||||
function crc32(bytes: Uint8Array): number {
|
||||
let c = 0xffffffff;
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
c = CRC_TABLE[(c ^ bytes[i]) & 0xff] ^ (c >>> 8);
|
||||
}
|
||||
return (c ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
|
||||
interface ZipEntry {
|
||||
name: string;
|
||||
data: Uint8Array;
|
||||
crc: number;
|
||||
offset: number;
|
||||
}
|
||||
|
||||
// Builds a ZIP archive with stored (uncompressed) entries. Fixed DOS timestamp
|
||||
// so repeated exports of the same data are byte-identical.
|
||||
function zip(files: { name: string; content: string }[]): Blob {
|
||||
const encoder = new TextEncoder();
|
||||
const chunks: Uint8Array[] = [];
|
||||
const entries: ZipEntry[] = [];
|
||||
let offset = 0;
|
||||
|
||||
const DOS_TIME = 0; // 00:00:00
|
||||
const DOS_DATE = (2020 - 1980) << 9 | (1 << 5) | 1; // 2020-01-01
|
||||
|
||||
function push(bytes: Uint8Array) {
|
||||
chunks.push(bytes);
|
||||
offset += bytes.length;
|
||||
}
|
||||
|
||||
function header(size: number) {
|
||||
const buf = new ArrayBuffer(size);
|
||||
return { view: new DataView(buf), bytes: new Uint8Array(buf) };
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
const nameBytes = encoder.encode(file.name);
|
||||
const data = encoder.encode(file.content);
|
||||
const crc = crc32(data);
|
||||
const local = header(30 + nameBytes.length);
|
||||
|
||||
local.view.setUint32(0, 0x04034b50, true); // local file header signature
|
||||
local.view.setUint16(4, 20, true); // version needed
|
||||
local.view.setUint16(6, 0x0800, true); // flags: UTF-8 names
|
||||
local.view.setUint16(8, 0, true); // method: stored
|
||||
local.view.setUint16(10, DOS_TIME, true);
|
||||
local.view.setUint16(12, DOS_DATE, true);
|
||||
local.view.setUint32(14, crc, true);
|
||||
local.view.setUint32(18, data.length, true); // compressed size
|
||||
local.view.setUint32(22, data.length, true); // uncompressed size
|
||||
local.view.setUint16(26, nameBytes.length, true);
|
||||
local.view.setUint16(28, 0, true); // extra field length
|
||||
local.bytes.set(nameBytes, 30);
|
||||
|
||||
entries.push({ name: file.name, data, crc, offset });
|
||||
push(local.bytes);
|
||||
push(data);
|
||||
}
|
||||
|
||||
const centralStart = offset;
|
||||
for (const entry of entries) {
|
||||
const nameBytes = encoder.encode(entry.name);
|
||||
const central = header(46 + nameBytes.length);
|
||||
|
||||
central.view.setUint32(0, 0x02014b50, true); // central directory signature
|
||||
central.view.setUint16(4, 20, true); // version made by
|
||||
central.view.setUint16(6, 20, true); // version needed
|
||||
central.view.setUint16(8, 0x0800, true); // flags: UTF-8 names
|
||||
central.view.setUint16(10, 0, true); // method: stored
|
||||
central.view.setUint16(12, DOS_TIME, true);
|
||||
central.view.setUint16(14, DOS_DATE, true);
|
||||
central.view.setUint32(16, entry.crc, true);
|
||||
central.view.setUint32(20, entry.data.length, true);
|
||||
central.view.setUint32(24, entry.data.length, true);
|
||||
central.view.setUint16(28, nameBytes.length, true);
|
||||
central.view.setUint16(30, 0, true); // extra
|
||||
central.view.setUint16(32, 0, true); // comment
|
||||
central.view.setUint16(34, 0, true); // disk number
|
||||
central.view.setUint16(36, 0, true); // internal attrs
|
||||
central.view.setUint32(38, 0, true); // external attrs
|
||||
central.view.setUint32(42, entry.offset, true);
|
||||
central.bytes.set(nameBytes, 46);
|
||||
|
||||
push(central.bytes);
|
||||
}
|
||||
|
||||
const end = header(22);
|
||||
end.view.setUint32(0, 0x06054b50, true); // end of central directory
|
||||
end.view.setUint16(8, entries.length, true);
|
||||
end.view.setUint16(10, entries.length, true);
|
||||
end.view.setUint32(12, offset - centralStart, true);
|
||||
end.view.setUint32(16, centralStart, true);
|
||||
push(end.bytes);
|
||||
|
||||
return new Blob(chunks as BlobPart[], {
|
||||
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
});
|
||||
}
|
||||
|
||||
/* --------------------------------- XML ---------------------------------- */
|
||||
|
||||
// Built via RegExp so the source file stays free of literal control bytes.
|
||||
const CONTROL_CHARS = new RegExp(
|
||||
"[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F]",
|
||||
"g",
|
||||
);
|
||||
|
||||
function escapeXml(value: string): string {
|
||||
return value
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """)
|
||||
// Control characters are illegal in XML 1.0 and make Excel reject the file.
|
||||
.replace(CONTROL_CHARS, "");
|
||||
}
|
||||
|
||||
// 0 -> A, 25 -> Z, 26 -> AA ...
|
||||
function columnName(index: number): string {
|
||||
let name = "";
|
||||
let n = index;
|
||||
while (n >= 0) {
|
||||
name = String.fromCharCode(65 + (n % 26)) + name;
|
||||
n = Math.floor(n / 26) - 1;
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
function cellXml(ref: string, value: Cell, style: number): string {
|
||||
if (value === null || value === undefined || value === "") {
|
||||
return `<c r="${ref}" s="${style}"/>`;
|
||||
}
|
||||
if (typeof value === "number" && Number.isFinite(value)) {
|
||||
return `<c r="${ref}" s="${style}"><v>${value}</v></c>`;
|
||||
}
|
||||
// Inline strings keep us from having to build a sharedStrings part.
|
||||
return `<c r="${ref}" s="${style}" t="inlineStr"><is><t xml:space="preserve">${escapeXml(
|
||||
String(value),
|
||||
)}</t></is></c>`;
|
||||
}
|
||||
|
||||
function sheetXml(headers: string[], rows: Cell[][]): string {
|
||||
const width = Math.max(headers.length, ...rows.map((r) => r.length), 1);
|
||||
const cols =
|
||||
`<cols>` +
|
||||
Array.from(
|
||||
{ length: width },
|
||||
(_, i) => `<col min="${i + 1}" max="${i + 1}" width="22" customWidth="1"/>`,
|
||||
).join("") +
|
||||
`</cols>`;
|
||||
|
||||
const lines: string[] = [];
|
||||
lines.push(
|
||||
`<row r="1">${headers
|
||||
.map((h, i) => cellXml(`${columnName(i)}1`, h, 1))
|
||||
.join("")}</row>`,
|
||||
);
|
||||
rows.forEach((row, r) => {
|
||||
const n = r + 2;
|
||||
lines.push(
|
||||
`<row r="${n}">${row
|
||||
.map((cell, i) => cellXml(`${columnName(i)}${n}`, cell, 0))
|
||||
.join("")}</row>`,
|
||||
);
|
||||
});
|
||||
|
||||
return (
|
||||
`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` +
|
||||
`<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">` +
|
||||
// rightToLeft so the sheet opens in RTL orientation, and a frozen header row.
|
||||
`<sheetViews><sheetView rightToLeft="1" workbookViewId="0" tabSelected="1">` +
|
||||
`<pane ySplit="1" topLeftCell="A2" activePane="bottomLeft" state="frozen"/>` +
|
||||
`</sheetView></sheetViews>` +
|
||||
cols +
|
||||
`<sheetData>${lines.join("")}</sheetData>` +
|
||||
`<autoFilter ref="A1:${columnName(width - 1)}${rows.length + 1}"/>` +
|
||||
`</worksheet>`
|
||||
);
|
||||
}
|
||||
|
||||
// Two cell formats: 0 = body, 1 = bold header on a grey fill.
|
||||
const STYLES_XML =
|
||||
`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` +
|
||||
`<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">` +
|
||||
`<fonts count="2"><font><sz val="11"/><name val="Calibri"/></font>` +
|
||||
`<font><b/><sz val="11"/><name val="Calibri"/></font></fonts>` +
|
||||
`<fills count="3"><fill><patternFill patternType="none"/></fill>` +
|
||||
`<fill><patternFill patternType="gray125"/></fill>` +
|
||||
`<fill><patternFill patternType="solid"><fgColor rgb="FFEEEEEE"/><bgColor indexed="64"/></patternFill></fill></fills>` +
|
||||
`<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>` +
|
||||
`<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>` +
|
||||
`<cellXfs count="2">` +
|
||||
`<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment vertical="center" wrapText="1"/></xf>` +
|
||||
`<xf numFmtId="0" fontId="1" fillId="2" borderId="0" xfId="0" applyFont="1" applyFill="1" applyAlignment="1"><alignment horizontal="center" vertical="center"/></xf>` +
|
||||
`</cellXfs><cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles></styleSheet>`;
|
||||
|
||||
/* -------------------------------- Public -------------------------------- */
|
||||
|
||||
export function exportToExcel(
|
||||
filename: string,
|
||||
headers: string[],
|
||||
rows: Cell[][],
|
||||
sheetName = "Sheet1",
|
||||
) {
|
||||
const safeSheet = escapeXml(sheetName.replace(/[[\]:*?/\\]/g, "").slice(0, 31)) || "Sheet1";
|
||||
|
||||
const blob = zip([
|
||||
{
|
||||
name: "[Content_Types].xml",
|
||||
content:
|
||||
`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` +
|
||||
`<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">` +
|
||||
`<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>` +
|
||||
`<Default Extension="xml" ContentType="application/xml"/>` +
|
||||
`<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>` +
|
||||
`<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>` +
|
||||
`<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>` +
|
||||
`</Types>`,
|
||||
},
|
||||
{
|
||||
name: "_rels/.rels",
|
||||
content:
|
||||
`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` +
|
||||
`<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
|
||||
`<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>` +
|
||||
`</Relationships>`,
|
||||
},
|
||||
{
|
||||
name: "xl/workbook.xml",
|
||||
content:
|
||||
`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` +
|
||||
`<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" ` +
|
||||
`xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">` +
|
||||
`<sheets><sheet name="${safeSheet}" sheetId="1" r:id="rId1"/></sheets></workbook>`,
|
||||
},
|
||||
{
|
||||
name: "xl/_rels/workbook.xml.rels",
|
||||
content:
|
||||
`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` +
|
||||
`<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
|
||||
`<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>` +
|
||||
`<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>` +
|
||||
`</Relationships>`,
|
||||
},
|
||||
{ name: "xl/styles.xml", content: STYLES_XML },
|
||||
{ name: "xl/worksheets/sheet1.xml", content: sheetXml(headers, rows) },
|
||||
]);
|
||||
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = filename.endsWith(".xlsx") ? filename : `${filename}.xlsx`;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
// Runs `worker` over `items` with a bounded number of in-flight promises so a
|
||||
// few thousand rows don't open a few thousand sockets at once.
|
||||
export async function mapWithConcurrency<T, R>(
|
||||
items: T[],
|
||||
limit: number,
|
||||
worker: (item: T, index: number) => Promise<R>,
|
||||
onProgress?: (done: number, total: number) => void,
|
||||
): Promise<R[]> {
|
||||
const results = new Array<R>(items.length);
|
||||
let cursor = 0;
|
||||
let done = 0;
|
||||
|
||||
async function run() {
|
||||
while (cursor < items.length) {
|
||||
const index = cursor++;
|
||||
results[index] = await worker(items[index], index);
|
||||
done++;
|
||||
onProgress?.(done, items.length);
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.all(
|
||||
Array.from({ length: Math.min(limit, items.length) }, run),
|
||||
);
|
||||
return results;
|
||||
}
|
||||
+15
@@ -2,6 +2,7 @@ import type { ComponentType, SVGProps } from "react";
|
||||
import {
|
||||
BreathIcon,
|
||||
ChatIcon,
|
||||
EyeIcon,
|
||||
HomeIcon,
|
||||
ImageIcon,
|
||||
MediaIcon,
|
||||
@@ -14,6 +15,7 @@ import {
|
||||
TagIcon,
|
||||
TimerIcon,
|
||||
TrophyIcon,
|
||||
UserIcon,
|
||||
WorryIcon,
|
||||
} from "@/components/icons";
|
||||
|
||||
@@ -80,6 +82,14 @@ export const NAV: NavSection[] = [
|
||||
icon: SliderIcon,
|
||||
items: [{ href: "/dashboard/sliders", label: "اسلایدرها" }],
|
||||
},
|
||||
{
|
||||
label: "لینکهای مستقیم",
|
||||
icon: EyeIcon,
|
||||
items: [
|
||||
{ href: "/dashboard/deep-links/media", label: "رسانهها" },
|
||||
{ href: "/dashboard/deep-links/categories", label: "دستهبندیها" },
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "اعلانها",
|
||||
icon: SliderIcon,
|
||||
@@ -113,6 +123,11 @@ export const NAV: NavSection[] = [
|
||||
icon: SurveyIcon,
|
||||
items: [{ href: "/dashboard/surveys", label: "پرسشهای نظرسنجی" }],
|
||||
},
|
||||
{
|
||||
label: "کاربران",
|
||||
icon: UserIcon,
|
||||
items: [{ href: "/dashboard/users", label: "کاربران نظرسنجی" }],
|
||||
},
|
||||
{
|
||||
label: "گفتگو با مشاور",
|
||||
icon: ChatIcon,
|
||||
|
||||
+69
-25
@@ -1,59 +1,103 @@
|
||||
"use client";
|
||||
|
||||
// Light/dark theme state. The actual `.dark` class is set on <html> by an inline
|
||||
// script in the root layout (before paint, to avoid a flash) and kept in sync
|
||||
// here. Preference persists in localStorage.
|
||||
// Light / dark / system theme state. The actual `.dark` class is set on <html>
|
||||
// by an inline script in the root layout (before paint) and kept in sync here.
|
||||
// Preference persists in localStorage.
|
||||
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
|
||||
export const THEME_STORAGE_KEY = "aram_theme";
|
||||
type Theme = "light" | "dark";
|
||||
export type Theme = "light" | "dark" | "system";
|
||||
|
||||
interface ThemeApi {
|
||||
theme: Theme;
|
||||
resolved: "light" | "dark";
|
||||
toggle: () => void;
|
||||
setTheme: (t: Theme) => void;
|
||||
}
|
||||
|
||||
const ThemeContext = createContext<ThemeApi | null>(null);
|
||||
|
||||
function applyClass(theme: Theme) {
|
||||
document.documentElement.classList.toggle("dark", theme === "dark");
|
||||
function isSystemDark(): boolean {
|
||||
if (typeof window === "undefined") return false;
|
||||
return window.matchMedia("(prefers-color-scheme: dark)").matches;
|
||||
}
|
||||
|
||||
function applyClass(resolved: "light" | "dark") {
|
||||
document.documentElement.classList.toggle("dark", resolved === "dark");
|
||||
}
|
||||
|
||||
function readStorage(): Theme {
|
||||
if (typeof window === "undefined") return "system";
|
||||
try {
|
||||
const t = localStorage.getItem(THEME_STORAGE_KEY);
|
||||
if (t === "light" || t === "dark" || t === "system") return t;
|
||||
} catch { /* private mode */ }
|
||||
return "system";
|
||||
}
|
||||
|
||||
function resolve(theme: Theme): "light" | "dark" {
|
||||
return theme === "system" ? (isSystemDark() ? "dark" : "light") : theme;
|
||||
}
|
||||
|
||||
export function ThemeProvider({ children }: { children: React.ReactNode }) {
|
||||
const [theme, setThemeState] = useState<Theme>("light");
|
||||
const [theme, setThemeState] = useState<Theme>("system");
|
||||
const [resolved, setResolved] = useState<"light" | "dark">("light");
|
||||
const mqRef = useRef<MediaQueryList | null>(null);
|
||||
|
||||
// Read whatever the no-flash script already decided.
|
||||
// Apply theme to <html> and update resolved state.
|
||||
const apply = useCallback((t: Theme) => {
|
||||
const r = resolve(t);
|
||||
applyClass(r);
|
||||
setResolved(r);
|
||||
}, []);
|
||||
|
||||
// On mount: read preference, apply, listen to system changes.
|
||||
useEffect(() => {
|
||||
const isDark = document.documentElement.classList.contains("dark");
|
||||
setThemeState(isDark ? "dark" : "light");
|
||||
}, []);
|
||||
|
||||
const setTheme = useCallback((t: Theme) => {
|
||||
const t = readStorage();
|
||||
setThemeState(t);
|
||||
applyClass(t);
|
||||
try {
|
||||
window.localStorage.setItem(THEME_STORAGE_KEY, t);
|
||||
} catch {
|
||||
/* ignore (private mode) */
|
||||
}
|
||||
}, []);
|
||||
apply(t);
|
||||
|
||||
const mq = window.matchMedia("(prefers-color-scheme: dark)");
|
||||
mqRef.current = mq;
|
||||
|
||||
const handler = () => {
|
||||
// Re-read theme from state (via ref won't work for closures, so re-read localStorage).
|
||||
const current = readStorage();
|
||||
if (current === "system") {
|
||||
apply("system");
|
||||
}
|
||||
};
|
||||
mq.addEventListener("change", handler);
|
||||
return () => mq.removeEventListener("change", handler);
|
||||
}, [apply]);
|
||||
|
||||
const setTheme = useCallback(
|
||||
(t: Theme) => {
|
||||
setThemeState(t);
|
||||
apply(t);
|
||||
try {
|
||||
localStorage.setItem(THEME_STORAGE_KEY, t);
|
||||
} catch { /* private mode */ }
|
||||
},
|
||||
[apply],
|
||||
);
|
||||
|
||||
const toggle = useCallback(() => {
|
||||
setTheme(
|
||||
document.documentElement.classList.contains("dark") ? "light" : "dark",
|
||||
);
|
||||
}, [setTheme]);
|
||||
const order: Theme[] = ["light", "dark", "system"];
|
||||
const next = order[(order.indexOf(theme) + 1) % order.length];
|
||||
setTheme(next);
|
||||
}, [theme, setTheme]);
|
||||
|
||||
return (
|
||||
<ThemeContext.Provider value={{ theme, toggle, setTheme }}>
|
||||
<ThemeContext.Provider value={{ theme, resolved, toggle, setTheme }}>
|
||||
{children}
|
||||
</ThemeContext.Provider>
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user