chore: merge web repo history into monorepo at web/
git-subtree-dir: web git-subtree-mainline:75a0ba593dgit-subtree-split:8f624e7416
This commit is contained in:
@@ -0,0 +1,84 @@
|
||||
"use client";
|
||||
|
||||
import { ReactNode } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { ChevronRight } from "lucide-react";
|
||||
import { ONBOARDING_STEPS } from "@/lib/onboarding-steps";
|
||||
|
||||
interface OnboardingScreenProps {
|
||||
order: number;
|
||||
title: string;
|
||||
emoji: string;
|
||||
description?: string;
|
||||
children: ReactNode;
|
||||
onBack?: () => void;
|
||||
// وقتی پروفایل قبلاً کامل شده (در انتظار بررسی یا ردشده)، کاربر میتونه
|
||||
// مستقیم روی هر بخش از نوار پیشرفت بزنه و بین مراحل جابهجا بشه
|
||||
onJumpToStep?: (slug: string) => void;
|
||||
}
|
||||
|
||||
export function OnboardingScreen({
|
||||
order,
|
||||
title,
|
||||
emoji,
|
||||
description,
|
||||
children,
|
||||
onBack,
|
||||
onJumpToStep,
|
||||
}: OnboardingScreenProps) {
|
||||
const router = useRouter();
|
||||
const total = ONBOARDING_STEPS.length;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-dvh">
|
||||
<div className="shrink-0 flex items-center gap-3 px-5 pt-[calc(env(safe-area-inset-top)+16px)] pb-2">
|
||||
<button
|
||||
onClick={onBack ?? (() => router.back())}
|
||||
className="w-9 h-9 rounded-full flex items-center justify-center hover:bg-(--color-bg-secondary) shrink-0"
|
||||
aria-label="بازگشت"
|
||||
>
|
||||
<ChevronRight size={20} className="text-(--color-content-secondary)" />
|
||||
</button>
|
||||
<div className="flex-1 flex gap-1.5">
|
||||
{ONBOARDING_STEPS.map((s) =>
|
||||
onJumpToStep ? (
|
||||
<button
|
||||
key={s.key}
|
||||
onClick={() => onJumpToStep(s.slug)}
|
||||
aria-label={s.title}
|
||||
className={`h-1.5 flex-1 rounded-(--radius-full) transition-colors duration-300 cursor-pointer ${
|
||||
s.order <= order ? "bg-(--color-brand-500)" : "bg-(--color-bg-tertiary)"
|
||||
}`}
|
||||
/>
|
||||
) : (
|
||||
<div
|
||||
key={s.key}
|
||||
className={`h-1.5 flex-1 rounded-(--radius-full) transition-colors duration-300 ${
|
||||
s.order <= order ? "bg-(--color-brand-500)" : "bg-(--color-bg-tertiary)"
|
||||
}`}
|
||||
/>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
<span className="text-[11px] font-bold text-(--color-content-tertiary) shrink-0">
|
||||
{order}/{total}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="shrink-0 flex flex-col gap-2 px-6 pt-6 pb-2">
|
||||
<h1 className="font-[var(--font-display)] font-extrabold text-[24px] text-(--color-content-primary) leading-snug">
|
||||
{title} <span>{emoji}</span>
|
||||
</h1>
|
||||
{description && (
|
||||
<p className="text-[14px] text-(--color-content-secondary) leading-6">
|
||||
{description}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 px-6 py-4 overflow-y-auto pb-[calc(env(safe-area-inset-bottom)+24px)]">
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
"use client";
|
||||
|
||||
import { ButtonHTMLAttributes } from "react";
|
||||
import { Button } from "@/components/ui/Button";
|
||||
|
||||
interface StepFooterButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
|
||||
isLoading?: boolean;
|
||||
}
|
||||
|
||||
// دکمهی اصلی هر مرحلهی onboarding؛ چون داخل ناحیهی overflow-y-auto صفحه است،
|
||||
// sticky bottom-0 نسبت به همون ناحیه چسبیده میمونه، نه اینکه ته لیست اسکرول بشه.
|
||||
export function StepFooterButton({
|
||||
children,
|
||||
isLoading,
|
||||
disabled,
|
||||
...props
|
||||
}: StepFooterButtonProps) {
|
||||
return (
|
||||
<div className="sticky bottom-0 -mx-6 px-6 pt-4 pb-[calc(env(safe-area-inset-bottom)+16px)] bg-(--color-bg-primary) border-t border-(--color-border-subtle)">
|
||||
<Button size="lg" isBlock isLoading={isLoading} disabled={disabled} {...props}>
|
||||
{children}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { StepFooterButton } from "@/components/onboarding/StepFooterButton";
|
||||
import { TextField } from "@/components/ui/TextField";
|
||||
import { ErrorBanner } from "@/components/ui/ErrorBanner";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { submitBasicInfo, FullProfile } from "@/lib/api";
|
||||
import { formatApiError } from "@/lib/hooks";
|
||||
|
||||
export function BasicInfoStep({
|
||||
initialProfile,
|
||||
onNext,
|
||||
}: {
|
||||
initialProfile: FullProfile | null;
|
||||
onNext: () => void;
|
||||
}) {
|
||||
const [gender, setGender] = useState<"male" | "female" | null>(
|
||||
initialProfile?.user.gender ?? null
|
||||
);
|
||||
const [firstName, setFirstName] = useState(initialProfile?.user.first_name ?? "");
|
||||
const [birthDate, setBirthDate] = useState(initialProfile?.user.birth_date ?? "");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const isValid = gender && firstName.trim().length >= 2 && birthDate;
|
||||
|
||||
async function handleSubmit() {
|
||||
if (!isValid || !gender) return;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
await submitBasicInfo({ gender, first_name: firstName.trim(), birth_date: birthDate });
|
||||
onNext();
|
||||
} catch (err) {
|
||||
setError(formatApiError(err));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div className="flex flex-col gap-2">
|
||||
<label className="text-[13px] font-semibold text-(--color-content-secondary) px-1">
|
||||
جنسیت
|
||||
</label>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
{(["female", "male"] as const).map((g) => (
|
||||
<button
|
||||
key={g}
|
||||
onClick={() => setGender(g)}
|
||||
className={cn(
|
||||
"h-14 rounded-(--radius-md) border-2 font-bold text-[15px] transition-all",
|
||||
gender === g
|
||||
? "bg-(--color-brand-500) border-(--color-brand-500) text-white shadow-(--shadow-cute-sm)"
|
||||
: "bg-(--color-surface-default) border-(--color-border-default) text-(--color-content-secondary)"
|
||||
)}
|
||||
>
|
||||
{g === "female" ? "زن 👩" : "مرد 👨"}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<TextField
|
||||
label="اسم کوچیکت چیه؟"
|
||||
placeholder="مثلاً سارا"
|
||||
value={firstName}
|
||||
onChange={(e) => setFirstName(e.target.value)}
|
||||
/>
|
||||
|
||||
<TextField
|
||||
label="تاریخ تولد"
|
||||
type="date"
|
||||
value={birthDate}
|
||||
onChange={(e) => setBirthDate(e.target.value)}
|
||||
/>
|
||||
|
||||
<ErrorBanner message={error} />
|
||||
|
||||
<StepFooterButton disabled={!isValid} isLoading={loading} onClick={handleSubmit}>
|
||||
بریم مرحله بعد
|
||||
</StepFooterButton>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { StepFooterButton } from "@/components/onboarding/StepFooterButton";
|
||||
import { TextField } from "@/components/ui/TextField";
|
||||
import { ErrorBanner } from "@/components/ui/ErrorBanner";
|
||||
import { submitBodyInfo, FullProfile } from "@/lib/api";
|
||||
import { formatApiError } from "@/lib/hooks";
|
||||
|
||||
export function BodyInfoStep({
|
||||
initialProfile,
|
||||
onNext,
|
||||
}: {
|
||||
initialProfile: FullProfile | null;
|
||||
onNext: () => void;
|
||||
}) {
|
||||
const [height, setHeight] = useState(
|
||||
initialProfile?.user.height_cm?.toString() ?? ""
|
||||
);
|
||||
const [weight, setWeight] = useState(
|
||||
initialProfile?.user.weight_kg?.toString() ?? ""
|
||||
);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const h = parseInt(height, 10);
|
||||
const w = parseInt(weight, 10);
|
||||
const isValid = h >= 100 && h <= 250 && w >= 30 && w <= 250;
|
||||
|
||||
async function handleSubmit() {
|
||||
if (!isValid) return;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
await submitBodyInfo({ height_cm: h, weight_kg: w });
|
||||
onNext();
|
||||
} catch (err) {
|
||||
setError(formatApiError(err));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<TextField
|
||||
label="قد (سانتیمتر)"
|
||||
type="number"
|
||||
placeholder="مثلاً 172"
|
||||
value={height}
|
||||
onChange={(e) => setHeight(e.target.value)}
|
||||
/>
|
||||
<TextField
|
||||
label="وزن (کیلوگرم)"
|
||||
type="number"
|
||||
placeholder="مثلاً 65"
|
||||
value={weight}
|
||||
onChange={(e) => setWeight(e.target.value)}
|
||||
/>
|
||||
<ErrorBanner message={error} />
|
||||
<StepFooterButton disabled={!isValid} isLoading={loading} onClick={handleSubmit}>
|
||||
بریم مرحله بعد
|
||||
</StepFooterButton>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { StepFooterButton } from "@/components/onboarding/StepFooterButton";
|
||||
import { ErrorBanner } from "@/components/ui/ErrorBanner";
|
||||
import { FullScreenLoader } from "@/components/ui/FullScreenLoader";
|
||||
import { OptionPicker } from "@/components/ui/OptionPicker";
|
||||
import { getOptions, submitEducation, Option, FullProfile } from "@/lib/api";
|
||||
import { formatApiError } from "@/lib/hooks";
|
||||
|
||||
function findSelection(profile: FullProfile | null, key: string): number[] {
|
||||
return profile?.selections.find((s) => s.category_key === key)?.option_ids ?? [];
|
||||
}
|
||||
|
||||
export function EducationStep({
|
||||
initialProfile,
|
||||
onNext,
|
||||
}: {
|
||||
initialProfile: FullProfile | null;
|
||||
onNext: () => void;
|
||||
}) {
|
||||
const [levelOptions, setLevelOptions] = useState<Option[] | null>(null);
|
||||
const [fieldOptions, setFieldOptions] = useState<Option[] | null>(null);
|
||||
const [levelId, setLevelId] = useState<number[]>(
|
||||
findSelection(initialProfile, "education_level")
|
||||
);
|
||||
const [fieldId, setFieldId] = useState<number[]>(
|
||||
findSelection(initialProfile, "field_of_study")
|
||||
);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
Promise.all([getOptions("education_level"), getOptions("field_of_study")])
|
||||
.then(([lvl, field]) => {
|
||||
setLevelOptions(lvl);
|
||||
setFieldOptions(field);
|
||||
})
|
||||
.catch((err) => setError(formatApiError(err)));
|
||||
}, []);
|
||||
|
||||
const isValid = levelId.length === 1 && fieldId.length === 1;
|
||||
|
||||
async function handleSubmit() {
|
||||
if (!isValid) return;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
await submitEducation({
|
||||
education_level_option_id: levelId[0],
|
||||
field_of_study_option_id: fieldId[0],
|
||||
});
|
||||
onNext();
|
||||
} catch (err) {
|
||||
setError(formatApiError(err));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (!levelOptions || !fieldOptions) return <FullScreenLoader label="گزینهها رو میاریم..." />;
|
||||
|
||||
if (levelOptions.length === 0 || fieldOptions.length === 0) {
|
||||
return (
|
||||
<ErrorBanner message="هنوز گزینهای برای تحصیلات توی پنل ادمین ثبت نشده. اول باید ادمین اینها رو اضافه کنه." />
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-7">
|
||||
<div className="flex flex-col gap-3">
|
||||
<label className="text-[13px] font-semibold text-(--color-content-secondary) px-1">
|
||||
سطح تحصیلات
|
||||
</label>
|
||||
<OptionPicker options={levelOptions} selectedIds={levelId} onChange={setLevelId} mode="single" />
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-3">
|
||||
<label className="text-[13px] font-semibold text-(--color-content-secondary) px-1">
|
||||
رشته تحصیلی
|
||||
</label>
|
||||
<OptionPicker options={fieldOptions} selectedIds={fieldId} onChange={setFieldId} mode="single" />
|
||||
</div>
|
||||
|
||||
<ErrorBanner message={error} />
|
||||
|
||||
<StepFooterButton disabled={!isValid} isLoading={loading} onClick={handleSubmit}>
|
||||
بریم مرحله بعد
|
||||
</StepFooterButton>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { StepFooterButton } from "@/components/onboarding/StepFooterButton";
|
||||
import { ErrorBanner } from "@/components/ui/ErrorBanner";
|
||||
import { FullScreenLoader } from "@/components/ui/FullScreenLoader";
|
||||
import { OptionPicker } from "@/components/ui/OptionPicker";
|
||||
import { getOptions, CategoryKey, FullProfile } from "@/lib/api";
|
||||
import { formatApiError } from "@/lib/hooks";
|
||||
|
||||
interface GenericOptionStepProps {
|
||||
initialProfile: FullProfile | null;
|
||||
onNext: () => void;
|
||||
category: CategoryKey;
|
||||
mode: "single" | "multi";
|
||||
min: number;
|
||||
max?: number;
|
||||
submitFn: (ids: number[]) => Promise<unknown>;
|
||||
helperText?: string;
|
||||
emptyMessage: string;
|
||||
}
|
||||
|
||||
export function GenericOptionStep({
|
||||
initialProfile,
|
||||
onNext,
|
||||
category,
|
||||
mode,
|
||||
min,
|
||||
max,
|
||||
submitFn,
|
||||
helperText,
|
||||
emptyMessage,
|
||||
}: GenericOptionStepProps) {
|
||||
const [options, setOptions] = useState<
|
||||
Awaited<ReturnType<typeof getOptions>> | null
|
||||
>(null);
|
||||
const [selectedIds, setSelectedIds] = useState<number[]>(
|
||||
initialProfile?.selections.find((s) => s.category_key === category)?.option_ids ?? []
|
||||
);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
getOptions(category)
|
||||
.then(setOptions)
|
||||
.catch((err) => setError(formatApiError(err)));
|
||||
}, [category]);
|
||||
|
||||
const isValid = selectedIds.length >= min && (max ? selectedIds.length <= max : true);
|
||||
|
||||
async function handleSubmit() {
|
||||
if (!isValid) return;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
await submitFn(selectedIds);
|
||||
onNext();
|
||||
} catch (err) {
|
||||
setError(formatApiError(err));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (!options) return <FullScreenLoader label="گزینهها رو میاریم..." />;
|
||||
|
||||
if (options.length === 0) {
|
||||
return <ErrorBanner message={emptyMessage} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
{helperText && (
|
||||
<p className="text-[13px] font-semibold text-(--color-content-secondary)">
|
||||
{helperText} {max ? `(${selectedIds.length}/${max})` : ""}
|
||||
</p>
|
||||
)}
|
||||
<OptionPicker
|
||||
options={options}
|
||||
selectedIds={selectedIds}
|
||||
onChange={setSelectedIds}
|
||||
mode={mode}
|
||||
max={max}
|
||||
/>
|
||||
<ErrorBanner message={error} />
|
||||
<StepFooterButton disabled={!isValid} isLoading={loading} onClick={handleSubmit}>
|
||||
بریم مرحله بعد
|
||||
</StepFooterButton>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
"use client";
|
||||
|
||||
import { useRef, useState } from "react";
|
||||
import { Plus, X } from "lucide-react";
|
||||
import { StepFooterButton } from "@/components/onboarding/StepFooterButton";
|
||||
import { ErrorBanner } from "@/components/ui/ErrorBanner";
|
||||
import { confirmPhotosStep, uploadPhoto, deletePhoto, photoUrl, FullProfile, Photo } from "@/lib/api";
|
||||
import { formatApiError } from "@/lib/hooks";
|
||||
import { validatePhotoSize } from "@/lib/utils";
|
||||
|
||||
const MAX_PHOTOS = 6;
|
||||
|
||||
export function PhotosStep({
|
||||
initialProfile,
|
||||
onNext,
|
||||
}: {
|
||||
initialProfile: FullProfile | null;
|
||||
onNext: () => void;
|
||||
}) {
|
||||
const [photos, setPhotos] = useState<Photo[]>(initialProfile?.photos ?? []);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
async function handleFile(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const file = e.target.files?.[0];
|
||||
e.target.value = "";
|
||||
if (!file) return;
|
||||
const sizeError = validatePhotoSize(file);
|
||||
if (sizeError) {
|
||||
setError(sizeError);
|
||||
return;
|
||||
}
|
||||
setUploading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const photo = await uploadPhoto(file);
|
||||
setPhotos((prev) => [...prev, photo]);
|
||||
} catch (err) {
|
||||
setError(formatApiError(err));
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDelete(id: number) {
|
||||
setError(null);
|
||||
try {
|
||||
await deletePhoto(id);
|
||||
setPhotos((prev) => prev.filter((p) => p.id !== id));
|
||||
} catch (err) {
|
||||
setError(formatApiError(err));
|
||||
}
|
||||
}
|
||||
|
||||
async function handleNext() {
|
||||
if (photos.length === 0) return;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
await confirmPhotosStep();
|
||||
onNext();
|
||||
} catch (err) {
|
||||
setError(formatApiError(err));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<p className="text-[13px] font-semibold text-(--color-content-secondary)">
|
||||
حداقل ۱ عکس لازمه؛ هرچی بیشتر بذاری، شانس دیده شدنت بیشتره ({photos.length}/{MAX_PHOTOS})
|
||||
</p>
|
||||
|
||||
<div className="grid grid-cols-3 gap-2.5">
|
||||
{photos.map((p) => (
|
||||
<div key={p.id} className="relative aspect-square rounded-(--radius-md) overflow-hidden">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src={photoUrl(p.url)} alt="" className="w-full h-full object-cover" />
|
||||
<button
|
||||
onClick={() => handleDelete(p.id)}
|
||||
className="absolute top-1 left-1 w-6 h-6 rounded-full bg-black/50 flex items-center justify-center text-white"
|
||||
aria-label="حذف عکس"
|
||||
>
|
||||
<X size={13} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
{photos.length < MAX_PHOTOS && (
|
||||
<button
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
disabled={uploading}
|
||||
className="aspect-square rounded-(--radius-md) border-2 border-dashed border-(--color-border-default) flex items-center justify-center text-(--color-content-tertiary) disabled:opacity-50"
|
||||
>
|
||||
<Plus size={22} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/webp"
|
||||
className="hidden"
|
||||
onChange={handleFile}
|
||||
/>
|
||||
|
||||
<ErrorBanner message={error} />
|
||||
|
||||
<StepFooterButton disabled={photos.length === 0} isLoading={loading} onClick={handleNext}>
|
||||
بریم مرحله بعد
|
||||
</StepFooterButton>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { StepFooterButton } from "@/components/onboarding/StepFooterButton";
|
||||
import { ErrorBanner } from "@/components/ui/ErrorBanner";
|
||||
import { FullScreenLoader } from "@/components/ui/FullScreenLoader";
|
||||
import { cn } from "@/lib/utils";
|
||||
import {
|
||||
getAvailableQuestions,
|
||||
submitProfileQuestions,
|
||||
ProfileQuestion,
|
||||
FullProfile,
|
||||
} from "@/lib/api";
|
||||
import { formatApiError } from "@/lib/hooks";
|
||||
import { ChevronRight, Pencil } from "lucide-react";
|
||||
|
||||
const REQUIRED = 3;
|
||||
|
||||
interface SlotAnswer {
|
||||
questionId: number;
|
||||
answer: string;
|
||||
}
|
||||
|
||||
// این مرحله بهجای اینکه یهو ۳ تا سوال رو با هم جلوی کاربر بذاره (که خستهکننده
|
||||
// و شلوغه)، یکییکی جلو میبره: اول انتخاب سوال، بعد جواب همون سوال، بعد سوال
|
||||
// بعدی — دقیقاً مثل یه مصاحبهی کوتاه، نه یه فرم بلند.
|
||||
export function ProfileQuestionsStep({
|
||||
initialProfile,
|
||||
onNext,
|
||||
}: {
|
||||
initialProfile: FullProfile | null;
|
||||
onNext: () => void;
|
||||
}) {
|
||||
const [questions, setQuestions] = useState<ProfileQuestion[] | null>(null);
|
||||
const [slots, setSlots] = useState<(SlotAnswer | null)[]>(() => {
|
||||
const initial = initialProfile?.profile_answers.slice(0, REQUIRED) ?? [];
|
||||
const arr: (SlotAnswer | null)[] = initial.map((a) => ({
|
||||
questionId: a.question_id,
|
||||
answer: a.answer,
|
||||
}));
|
||||
while (arr.length < REQUIRED) arr.push(null);
|
||||
return arr;
|
||||
});
|
||||
const [activeSlot, setActiveSlot] = useState(() => {
|
||||
const firstEmpty = slots.findIndex((s) => s === null);
|
||||
return firstEmpty === -1 ? REQUIRED - 1 : firstEmpty;
|
||||
});
|
||||
const [draftAnswer, setDraftAnswer] = useState(slots[activeSlot]?.answer ?? "");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
getAvailableQuestions()
|
||||
.then(setQuestions)
|
||||
.catch((err) => setError(formatApiError(err)));
|
||||
}, []);
|
||||
|
||||
if (!questions) return <FullScreenLoader label="سوالات رو میاریم..." />;
|
||||
|
||||
const usedQuestionIds = slots
|
||||
.filter((s, i) => s && i !== activeSlot)
|
||||
.map((s) => s!.questionId);
|
||||
const currentQuestion = questions.find((q) => q.id === slots[activeSlot]?.questionId) ?? null;
|
||||
const availableForSlot = questions.filter((q) => !usedQuestionIds.includes(q.id));
|
||||
|
||||
function saveDraftInto(list: (SlotAnswer | null)[]) {
|
||||
const next = [...list];
|
||||
if (next[activeSlot]) {
|
||||
next[activeSlot] = { ...next[activeSlot]!, answer: draftAnswer.trim() };
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
function pickQuestion(id: number) {
|
||||
setSlots((prev) => {
|
||||
const next = [...prev];
|
||||
next[activeSlot] = { questionId: id, answer: "" };
|
||||
return next;
|
||||
});
|
||||
setDraftAnswer("");
|
||||
}
|
||||
|
||||
function clearCurrentQuestion() {
|
||||
setSlots((prev) => {
|
||||
const next = [...prev];
|
||||
next[activeSlot] = null;
|
||||
return next;
|
||||
});
|
||||
setDraftAnswer("");
|
||||
}
|
||||
|
||||
function goToSlot(index: number) {
|
||||
setSlots((prev) => saveDraftInto(prev));
|
||||
setActiveSlot(index);
|
||||
setDraftAnswer(slots[index]?.answer ?? "");
|
||||
}
|
||||
|
||||
function goNext() {
|
||||
setSlots((prev) => saveDraftInto(prev));
|
||||
goToSlot(activeSlot + 1);
|
||||
}
|
||||
|
||||
const isLastSlot = activeSlot === REQUIRED - 1;
|
||||
const canAdvance = currentQuestion !== null && draftAnswer.trim().length > 0;
|
||||
|
||||
async function handleSubmit() {
|
||||
const finalSlots = saveDraftInto(slots);
|
||||
if (finalSlots.some((s) => !s || !s.answer)) return;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
await submitProfileQuestions(
|
||||
finalSlots.map((s) => ({ question_id: s!.questionId, answer: s!.answer }))
|
||||
);
|
||||
onNext();
|
||||
} catch (err) {
|
||||
setError(formatApiError(err));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
{Array.from({ length: REQUIRED }).map((_, i) => (
|
||||
<button
|
||||
key={i}
|
||||
onClick={() => (slots[i] || i < activeSlot) && goToSlot(i)}
|
||||
className={cn(
|
||||
"h-1.5 rounded-(--radius-full) transition-all",
|
||||
i === activeSlot
|
||||
? "w-8 bg-(--color-brand-500)"
|
||||
: slots[i]
|
||||
? "w-4 bg-(--color-brand-200)"
|
||||
: "w-4 bg-(--color-bg-tertiary)"
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<p className="text-[13px] font-semibold text-(--color-content-secondary) text-center">
|
||||
سوال {activeSlot + 1} از {REQUIRED}
|
||||
</p>
|
||||
|
||||
{activeSlot > 0 && (
|
||||
<button
|
||||
onClick={() => goToSlot(activeSlot - 1)}
|
||||
className="flex items-center gap-1 text-[13px] text-(--color-content-tertiary) w-fit"
|
||||
>
|
||||
<ChevronRight size={14} />
|
||||
سوال قبلی
|
||||
</button>
|
||||
)}
|
||||
|
||||
{!currentQuestion ? (
|
||||
<div className="flex flex-col gap-2">
|
||||
<p className="text-[13px] text-(--color-content-tertiary) px-1">
|
||||
یکی از این سوالها رو انتخاب کن:
|
||||
</p>
|
||||
{availableForSlot.map((q) => (
|
||||
<button
|
||||
key={q.id}
|
||||
onClick={() => pickQuestion(q.id)}
|
||||
className="text-right rounded-(--radius-md) border-2 border-(--color-border-default) bg-(--color-surface-default) px-4 py-3.5 text-[14px] text-(--color-content-primary) hover:border-(--color-brand-300) transition-colors"
|
||||
>
|
||||
{q.text}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex items-center justify-between gap-2 px-1">
|
||||
<label className="text-[14px] font-bold text-(--color-content-primary)">
|
||||
{currentQuestion.text}
|
||||
</label>
|
||||
<button
|
||||
onClick={clearCurrentQuestion}
|
||||
className="flex items-center gap-1 text-[12px] font-semibold text-(--color-brand-600) shrink-0"
|
||||
>
|
||||
<Pencil size={12} />
|
||||
عوض کردن سوال
|
||||
</button>
|
||||
</div>
|
||||
<textarea
|
||||
key={currentQuestion.id}
|
||||
value={draftAnswer}
|
||||
onChange={(e) => setDraftAnswer(e.target.value)}
|
||||
rows={5}
|
||||
autoFocus
|
||||
placeholder="جواب بده..."
|
||||
className="rounded-(--radius-sm) border-2 border-(--color-border-default) bg-(--color-surface-default) px-4 py-3 text-[14px] focus:outline-none focus:border-(--color-border-interactive) focus:ring-4 focus:ring-(--color-brand-100) resize-none"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ErrorBanner message={error} />
|
||||
|
||||
<StepFooterButton
|
||||
disabled={!canAdvance}
|
||||
isLoading={loading}
|
||||
onClick={isLastSlot ? handleSubmit : goNext}
|
||||
>
|
||||
{isLastSlot ? "ثبت و ادامه" : "سوال بعدی"}
|
||||
</StepFooterButton>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user