lighter first load, math reads left-to-right in quizzes, tickets from the server, readable separators

- Every screen but home is its own chunk and preloads when the browser is
  idle; React and motion get their own long-cached chunks. The app entry
  goes from 505 kB (160 kB gzip) to 85 kB (27 kB gzip).
- Quiz prompts, options and lesson examples go through MathText, so
  '10 + 3 - 7 - 2' reads from the left; an unpaired bracket at the edge of
  a math run stays with the Persian sentence.
- Support lists tickets from GET /support/tickets instead of this
  browser's localStorage; a ticket's messages load when it is opened.
- '·' next to a Persian zero read as another digit ('فصلِ ۱ · ۰' looked
  like ۱۰۰); a thin bar separates them now. Notification bodies show
  Persian digits.
- A root or vertex the model already marked with coordinates is no longer
  labelled a second time on top of it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-09-29 21:18:49 +03:30
parent 63f4ea8da0
commit 0957ef476b
15 changed files with 146 additions and 70 deletions

View File

@@ -172,6 +172,8 @@ export const api = {
support: { support: {
createTicket: (subject: string, category: string) => createTicket: (subject: string, category: string) =>
http.create<{ ticketId: string; status: string }>('/support/tickets', { subject, category }), http.create<{ ticketId: string; status: string }>('/support/tickets', { subject, category }),
/** تیکت‌های همین کاربر، تازه‌ترین اول (۲۰ تای آخر). */
tickets: () => http.get<{ tickets: T.TicketSummary[] }>('/support/tickets').then((r) => r.tickets),
ticket: (ticketId: string) => http.get<T.Ticket>(`/support/tickets/${ticketId}`), ticket: (ticketId: string) => http.get<T.Ticket>(`/support/tickets/${ticketId}`),
reply: (ticketId: string, text: string) => reply: (ticketId: string, text: string) =>
http.create<{ messageId: string; success: boolean }>(`/support/tickets/${ticketId}/messages`, { text }), http.create<{ messageId: string; success: boolean }>(`/support/tickets/${ticketId}/messages`, { text }),

View File

@@ -271,6 +271,16 @@ export interface OrderStatus {
amount: number; amount: number;
} }
/** یک ردیف از فهرستِ تیکت‌های کاربر (GET /support/tickets). */
export interface TicketSummary {
ticketId: string;
subject: string;
category: string;
status: string;
createdAt: string;
supportReplies: number;
}
export interface Ticket { export interface Ticket {
ticketId: string; ticketId: string;
subject: string; subject: string;

View File

@@ -1,4 +1,4 @@
import { useEffect, useState } from 'react'; import { lazy, Suspense, useEffect, useState, type ComponentType } from 'react';
import { AnimatePresence, motion } from 'motion/react'; import { AnimatePresence, motion } from 'motion/react';
import { CheckCircle2, XCircle } from 'lucide-react'; import { CheckCircle2, XCircle } from 'lucide-react';
import { api, type Grade, type UserProfile } from '@/api'; import { api, type Grade, type UserProfile } from '@/api';
@@ -8,25 +8,46 @@ import { isTab, type Route } from '@/nav/routes';
import { BottomNav } from '@/components/BottomNav'; import { BottomNav } from '@/components/BottomNav';
import { Sheet } from '@/components/Sheet'; import { Sheet } from '@/components/Sheet';
import { useToast } from '@/components/Toast'; import { useToast } from '@/components/Toast';
import { PrimaryButton } from '@/components/ui'; import { LoadingState, PrimaryButton } from '@/components/ui';
import { AskScreen } from '@/screens/AskScreen';
import { CharactersScreen } from '@/screens/CharactersScreen';
import { FamilyScreen } from '@/screens/FamilyScreen';
import { HomeScreen } from '@/screens/HomeScreen'; import { HomeScreen } from '@/screens/HomeScreen';
import { InviteScreen } from '@/screens/InviteScreen';
import { LeaderboardScreen } from '@/screens/LeaderboardScreen';
import { LessonScreen } from '@/screens/LessonScreen';
import { LoginScreen } from '@/screens/LoginScreen'; import { LoginScreen } from '@/screens/LoginScreen';
import { MapScreen } from '@/screens/MapScreen';
import { NotificationsScreen } from '@/screens/NotificationsScreen';
import { ProfileScreen } from '@/screens/ProfileScreen';
import { QuizScreen } from '@/screens/QuizScreen';
import { StreakScreen } from '@/screens/StreakScreen';
import { SubscriptionScreen } from '@/screens/SubscriptionScreen';
import { SupportScreen } from '@/screens/SupportScreen';
import { UnitScreen } from '@/screens/UnitScreen';
import type { PaymentReturn } from './launchParams'; import type { PaymentReturn } from './launchParams';
/**
* خانه همراهِ خودِ اپ بار می‌شود؛ بقیه‌ی صفحه‌ها هر کدام فایلِ جدا دارند تا بارِ اول
* سبک باشد (قبلاً کلِ اپ یک فایلِ ۵۰۵ کیلوبایتی بود، و دستیار با ماژولِ شکل‌ها
* بزرگ‌ترین تکه‌اش). بعد از بالا آمدنِ خانه همه در پس‌زمینه گرفته می‌شوند
* (preloadScreens)، پس رفتن به صفحه‌ی بعدی منتظرِ شبکه نمی‌ماند.
*/
const loaders: (() => Promise<unknown>)[] = [];
function screen<M extends Record<K, ComponentType<any>>, K extends keyof M>(load: () => Promise<M>, name: K) {
loaders.push(load);
return lazy(async () => ({ default: (await load())[name] }));
}
const AskScreen = screen(() => import('@/screens/AskScreen'), 'AskScreen');
const CharactersScreen = screen(() => import('@/screens/CharactersScreen'), 'CharactersScreen');
const FamilyScreen = screen(() => import('@/screens/FamilyScreen'), 'FamilyScreen');
const InviteScreen = screen(() => import('@/screens/InviteScreen'), 'InviteScreen');
const LeaderboardScreen = screen(() => import('@/screens/LeaderboardScreen'), 'LeaderboardScreen');
const LessonScreen = screen(() => import('@/screens/LessonScreen'), 'LessonScreen');
const MapScreen = screen(() => import('@/screens/MapScreen'), 'MapScreen');
const NotificationsScreen = screen(() => import('@/screens/NotificationsScreen'), 'NotificationsScreen');
const ProfileScreen = screen(() => import('@/screens/ProfileScreen'), 'ProfileScreen');
const QuizScreen = screen(() => import('@/screens/QuizScreen'), 'QuizScreen');
const StreakScreen = screen(() => import('@/screens/StreakScreen'), 'StreakScreen');
const SubscriptionScreen = screen(() => import('@/screens/SubscriptionScreen'), 'SubscriptionScreen');
const SupportScreen = screen(() => import('@/screens/SupportScreen'), 'SupportScreen');
const UnitScreen = screen(() => import('@/screens/UnitScreen'), 'UnitScreen');
let preloaded = false;
function preloadScreens() {
if (preloaded) return;
preloaded = true;
const run = () => loaders.forEach((load) => void load().catch(() => {}));
if ('requestIdleCallback' in window) window.requestIdleCallback(run, { timeout: 2500 });
else setTimeout(run, 1200);
}
interface Props { interface Props {
profile: UserProfile; profile: UserProfile;
grades: Grade[]; grades: Grade[];
@@ -39,6 +60,7 @@ interface Props {
/** اپِ اصلی بعد از ورود: تب‌ها، صفحه‌ها و داده‌ی مشترک. */ /** اپِ اصلی بعد از ورود: تب‌ها، صفحه‌ها و داده‌ی مشترک. */
export function MainApp({ profile, grades, payment, start, onSignedOut, onRegistered }: Props) { export function MainApp({ profile, grades, payment, start, onSignedOut, onRegistered }: Props) {
useEffect(preloadScreens, []);
return ( return (
<AppDataProvider initialProfile={profile} grades={grades}> <AppDataProvider initialProfile={profile} grades={grades}>
<NavigatorProvider initial={start ?? { name: payment ? 'subscription' : 'home' }}> <NavigatorProvider initial={start ?? { name: payment ? 'subscription' : 'home' }}>
@@ -66,7 +88,9 @@ function Screens({ onSignedOut, onRegistered }: Pick<Props, 'onSignedOut' | 'onR
exit={{ opacity: 0, x: 18 }} exit={{ opacity: 0, x: 18 }}
transition={{ duration: 0.18 }} transition={{ duration: 0.18 }}
> >
<RouteView route={route} onSignedOut={onSignedOut} onRegistered={onRegistered} /> <Suspense fallback={<LoadingState />}>
<RouteView route={route} onSignedOut={onSignedOut} onRegistered={onRegistered} />
</Suspense>
</motion.div> </motion.div>
</AnimatePresence> </AnimatePresence>
</div> </div>

View File

@@ -154,6 +154,14 @@ export function EmptyState({ text, char = 'pi' as SeyarChar }: { text: string; c
return <StateBox char={char} mood="idle" text={text} />; return <StateBox char={char} mood="idle" text={text} />;
} }
/**
* جداکننده‌ی میانِ دو تکه‌ی متن. «·» کنارِ صفرِ فارسی (که خودش یک نقطه است)
* خوانده نمی‌شد: «فصلِ ۱ · ۰ از ۴» شبیهِ «۱۰۰» دیده می‌شد.
*/
export function Sep() {
return <span aria-hidden className="mx-1.5 inline-block h-2.5 w-px bg-current align-middle opacity-40" />;
}
export function InlineError({ children }: { children: ReactNode }) { export function InlineError({ children }: { children: ReactNode }) {
return ( return (
<div role="alert" className="rounded-xl border border-red-200 bg-red-50 px-3 py-2.5 text-xs leading-6 text-red-600"> <div role="alert" className="rounded-xl border border-red-200 bg-red-50 px-3 py-2.5 text-xs leading-6 text-red-600">

View File

@@ -637,8 +637,12 @@ export function Plane({ spec: raw }: { spec: PlaneSpec }) {
// بیش از چهار نقطه از یک نوع (ریشه‌های سینوس) فقط نقطه می‌گیرند، نه برچسب؛ وگرنه روی هم می‌افتند. // بیش از چهار نقطه از یک نوع (ریشه‌های سینوس) فقط نقطه می‌گیرند، نه برچسب؛ وگرنه روی هم می‌افتند.
const kindCount = new Map<string, number>(); const kindCount = new Map<string, number>();
markPts.forEach((m) => kindCount.set(m.kind === 'max' || m.kind === 'min' ? 'ext' : m.kind, (kindCount.get(m.kind === 'max' || m.kind === 'min' ? 'ext' : m.kind) ?? 0) + 1)); markPts.forEach((m) => kindCount.set(m.kind === 'max' || m.kind === 'min' ? 'ext' : m.kind, (kindCount.get(m.kind === 'max' || m.kind === 'min' ? 'ext' : m.kind) ?? 0) + 1));
// اگر مدل خودش روی همان ریشه یا رأس نقطه‌ی نام‌دار گذاشته، برچسبِ ما تکرار نشود // اگر مدل خودش روی همان ریشه یا رأس نقطه گذاشته (نام‌دار یا با مختصات)، برچسبِ ما
const namedXY = [...named.values()]; // تکرار نشود؛ وگرنه «(۳، ۰)» دو بار و روی هم نوشته می‌شد.
const namedXY = [
...named.values(),
...spec.items.flatMap((it) => (it.type === 'point' && typeof it.point !== 'string' ? [it.point as XY] : [])),
];
for (const m of markPts) { for (const m of markPts) {
if (namedXY.some((q) => Math.abs(q[0] - m.xy[0]) < 1e-3 && Math.abs(q[1] - m.xy[1]) < 1e-3)) continue; if (namedXY.some((q) => Math.abs(q[0] - m.xy[0]) < 1e-3 && Math.abs(q[1] - m.xy[1]) < 1e-3)) continue;
const [px, py] = P(m.xy); const [px, py] = P(m.xy);

View File

@@ -32,12 +32,36 @@ export function MathText({ text }: { text: string }) {
run = run.slice(lead.length); run = run.slice(lead.length);
const tail = EDGE_END.exec(run)?.[0] ?? ''; const tail = EDGE_END.exec(run)?.[0] ?? '';
run = run.slice(0, run.length - tail.length); run = run.slice(0, run.length - tail.length);
// «(۱، −۴)» باید کامل قفل شود، ولی پرانتزِ بازِ بی‌جفت در سرِ تکه مالِ جمله است. // «(۱، −۴)» باید کامل قفل شود، ولی پرانتزِ بی‌جفت در لبه‌ی تکه مالِ جمله است:
// در «۱۰ − ۲ (با محاسبه…)» پرانتزِ باز جزوِ جمله‌ی فارسیِ بعدی است و اگر قفل شود
// به سمتِ غلط می‌رود.
const edge = trimUnpaired(run);
const head = lead + edge.head;
run = edge.run;
if (!run || !/[0-9۰-۹]/.test(run)) continue; if (!run || !/[0-9۰-۹]/.test(run)) continue;
out.push(text.slice(last, start + lead.length)); out.push(text.slice(last, start + head.length));
out.push(<span key={i++} style={LTR}>{run}</span>); out.push(<span key={i++} style={LTR}>{run}</span>);
last = start + lead.length + run.length; last = start + head.length + run.length;
} }
out.push(text.slice(last)); out.push(text.slice(last));
return <>{out.map((n, j) => (typeof n === 'string' ? <Fragment key={`t${j}`}>{n}</Fragment> : n))}</>; return <>{out.map((n, j) => (typeof n === 'string' ? <Fragment key={`t${j}`}>{n}</Fragment> : n))}</>;
} }
const count = (s: string, ch: string) => s.split(ch).length - 1;
/**
* پرانتزِ بازِ بی‌جفت در تهِ تکه و بسته‌ی بی‌جفت در سرش را (با فاصله‌ی کنارش) کنار
* می‌گذارد؛ `head` یعنی چه مقدار از سرِ تکه به جمله‌ی فارسی برگشت.
*/
function trimUnpaired(run: string): { head: string; run: string } {
let head = '';
while (/[(\[]\s*$/.test(run) && count(run, '(') + count(run, '[') > count(run, ')') + count(run, ']')) {
run = run.slice(0, run.length - /\s*[(\[]\s*$/.exec(run)![0].length);
}
while (/^\s*[)\]]/.test(run) && count(run, ')') + count(run, ']') > count(run, '(') + count(run, '[')) {
const m = /^\s*[)\]]\s*/.exec(run)![0];
head += m;
run = run.slice(m.length);
}
return { head, run };
}

View File

@@ -27,7 +27,6 @@ export const KEYS = {
deviceId: 'deviceId', deviceId: 'deviceId',
onboarded: 'tadrisino.onboarded', onboarded: 'tadrisino.onboarded',
conversationId: 'tadrisino.conversationId', conversationId: 'tadrisino.conversationId',
ticketIds: 'tadrisino.ticketIds',
sound: 'tadrisino.sound', sound: 'tadrisino.sound',
referralCode: 'tadrisino.referralCode', referralCode: 'tadrisino.referralCode',
} as const; } as const;

View File

@@ -6,7 +6,7 @@ import { useAsync } from '@/lib/useAsync';
import { SeyarMascot } from '@/mascots/SeyarMascot'; import { SeyarMascot } from '@/mascots/SeyarMascot';
import { SEYAR_INFO, seyarFromSlug } from '@/mascots/seyar'; import { SEYAR_INFO, seyarFromSlug } from '@/mascots/seyar';
import { useToast } from '@/components/Toast'; import { useToast } from '@/components/Toast';
import { EmptyState, ErrorState, LoadingState, Screen, ScreenHeader } from '@/components/ui'; import { EmptyState, ErrorState, LoadingState, Screen, ScreenHeader, Sep } from '@/components/ui';
import { friendlyError } from '@/lib/errors'; import { friendlyError } from '@/lib/errors';
import { toFa } from '@/lib/format'; import { toFa } from '@/lib/format';
@@ -39,7 +39,7 @@ export function CharactersScreen() {
<Screen> <Screen>
<ScreenHeader <ScreenHeader
title="همراهت رو انتخاب کن" title="همراهت رو انتخاب کن"
subtitle={`امتیازِ تو: ${toFa(summary?.xp ?? 0)} · با امتیازِ بیشتر همراه‌های بیشتری باز می‌شن`} subtitle={<>امتیازِ تو: {toFa(summary?.xp ?? 0)}<Sep />با امتیازِ بیشتر همراه‌های بیشتری باز می‌شن</>}
color="#9B7BFF" color="#9B7BFF"
back back
/> />

View File

@@ -7,7 +7,7 @@ import { useNav } from '@/nav/Navigator';
import { SeyarMascot } from '@/mascots/SeyarMascot'; import { SeyarMascot } from '@/mascots/SeyarMascot';
import { IslandPath } from '@/components/IslandPath'; import { IslandPath } from '@/components/IslandPath';
import { IslandSheet } from '@/components/IslandSheet'; import { IslandSheet } from '@/components/IslandSheet';
import { EmptyState, ErrorState, LoadingState, Screen } from '@/components/ui'; import { EmptyState, ErrorState, LoadingState, Screen, Sep } from '@/components/ui';
import { shade } from '@/lib/color'; import { shade } from '@/lib/color';
import { toFa } from '@/lib/format'; import { toFa } from '@/lib/format';
@@ -109,7 +109,7 @@ export function HomeScreen() {
> >
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<div className="text-[11px] font-bold text-white/80"> <div className="text-[11px] font-bold text-white/80">
فصلِ {toFa(i + 1)} · {toFa(p.done)} از {toFa(p.total)} جزیره فصلِ {toFa(i + 1)}<Sep />{toFa(p.done)} از {toFa(p.total)} جزیره
{isCurrentUnit && <span className="mr-1.5 rounded-full bg-white/25 px-2 py-0.5">الان اینجایی</span>} {isCurrentUnit && <span className="mr-1.5 rounded-full bg-white/25 px-2 py-0.5">الان اینجایی</span>}
</div> </div>
<div className="mt-0.5 truncate text-[15px] font-black">{unit.title.replace(/^فصل\s*\S+\s*[::]\s*/, '')}</div> <div className="mt-0.5 truncate text-[15px] font-black">{unit.title.replace(/^فصل\s*\S+\s*[::]\s*/, '')}</div>

View File

@@ -6,8 +6,9 @@ import { useNav } from '@/nav/Navigator';
import { useAsync } from '@/lib/useAsync'; import { useAsync } from '@/lib/useAsync';
import { SeyarMascot } from '@/mascots/SeyarMascot'; import { SeyarMascot } from '@/mascots/SeyarMascot';
import { moodFromServer } from '@/mascots/seyar'; import { moodFromServer } from '@/mascots/seyar';
import { ErrorState, LoadingState, PrimaryButton, Screen, ScreenBody, ScreenHeader } from '@/components/ui'; import { ErrorState, LoadingState, PrimaryButton, Screen, ScreenBody, ScreenHeader, Sep } from '@/components/ui';
import { toFa } from '@/lib/format'; import { toFa } from '@/lib/format';
import { MathText } from '@/lib/MathText';
/** معرفیِ درس، پیش از تمرین. */ /** معرفیِ درس، پیش از تمرین. */
export function LessonScreen({ lessonId, nodeId }: { lessonId: number; nodeId?: string }) { export function LessonScreen({ lessonId, nodeId }: { lessonId: number; nodeId?: string }) {
@@ -29,7 +30,7 @@ export function LessonScreen({ lessonId, nodeId }: { lessonId: number; nodeId?:
ref && ( ref && (
<span className="inline-flex items-center gap-1.5 rounded-full bg-white/15 px-3 py-1"> <span className="inline-flex items-center gap-1.5 rounded-full bg-white/15 px-3 py-1">
{/* ترتیبِ lessonIds «درسِ بعدی اول» است، نه ترتیبِ کتاب؛ پس شماره‌ی درس از آن درنمی‌آید. */} {/* ترتیبِ lessonIds «درسِ بعدی اول» است، نه ترتیبِ کتاب؛ پس شماره‌ی درس از آن درنمی‌آید. */}
<Zap size={11} fill="white" /> {ref.node.title} · {toFa(ref.node.lessonIds.length)} درس <Zap size={11} fill="white" /> {ref.node.title}<Sep />{toFa(ref.node.lessonIds.length)} درس
</span> </span>
) )
} }
@@ -56,7 +57,7 @@ export function LessonScreen({ lessonId, nodeId }: { lessonId: number; nodeId?:
{data.example && ( {data.example && (
<section className="rounded-3xl border border-line bg-white p-4"> <section className="rounded-3xl border border-line bg-white p-4">
<h2 className="mb-2 text-xs font-black text-muted">مثال</h2> <h2 className="mb-2 text-xs font-black text-muted">مثال</h2>
<p className="whitespace-pre-line text-sm leading-[1.95] text-ink">{data.example}</p> <p className="whitespace-pre-line text-sm leading-[1.95] text-ink"><MathText text={data.example} /></p>
</section> </section>
)} )}
@@ -69,7 +70,7 @@ export function LessonScreen({ lessonId, nodeId }: { lessonId: number; nodeId?:
<span className="flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-full text-xs font-black text-white" style={{ backgroundColor: color }}> <span className="flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-full text-xs font-black text-white" style={{ backgroundColor: color }}>
{toFa(i + 1)} {toFa(i + 1)}
</span> </span>
<span className="flex-1 whitespace-pre-line">{step}</span> <span className="flex-1 whitespace-pre-line"><MathText text={step} /></span>
</li> </li>
))} ))}
</ol> </ol>

View File

@@ -4,7 +4,7 @@ import { useAppData } from '@/state/AppData';
import { unitColor, unitProgress } from '@/state/curriculum'; import { unitColor, unitProgress } from '@/state/curriculum';
import { useNav } from '@/nav/Navigator'; import { useNav } from '@/nav/Navigator';
import { SeyarMascot } from '@/mascots/SeyarMascot'; import { SeyarMascot } from '@/mascots/SeyarMascot';
import { EmptyState, ErrorState, LoadingState, ProgressBar, Screen, ScreenHeader } from '@/components/ui'; import { EmptyState, ErrorState, LoadingState, ProgressBar, Screen, ScreenHeader, Sep } from '@/components/ui';
import { ZigzagPath, zigzagPositions } from '@/components/ZigzagPath'; import { ZigzagPath, zigzagPositions } from '@/components/ZigzagPath';
import { iconFor } from '@/components/NodeIcon'; import { iconFor } from '@/components/NodeIcon';
import { toFa } from '@/lib/format'; import { toFa } from '@/lib/format';
@@ -22,7 +22,7 @@ export function MapScreen() {
<Screen className="bg-[#f7f8ff]"> <Screen className="bg-[#f7f8ff]">
<ScreenHeader <ScreenHeader
title="نقشه‌ی فصل‌ها" title="نقشه‌ی فصل‌ها"
subtitle={`${gradeTitle ? `${gradeTitle} · ` : ''}${toFa(overall)}٪ از کلِ مسیر`} subtitle={<>{gradeTitle && <>{gradeTitle}<Sep /></>}{toFa(overall)}٪ از کلِ مسیر</>}
color="#91ADC6" color="#91ADC6"
mascot={{ char: 'sigma', mood: overall > 0 ? 'happy' : 'idle' }} mascot={{ char: 'sigma', mood: overall > 0 ? 'happy' : 'idle' }}
> >

View File

@@ -4,7 +4,7 @@ import { useAppData } from '@/state/AppData';
import { useAsync } from '@/lib/useAsync'; import { useAsync } from '@/lib/useAsync';
import { useToast } from '@/components/Toast'; import { useToast } from '@/components/Toast';
import { EmptyState, ErrorState, LoadingState, Screen, ScreenHeader } from '@/components/ui'; import { EmptyState, ErrorState, LoadingState, Screen, ScreenHeader } from '@/components/ui';
import { relativeTime } from '@/lib/format'; import { relativeTime, toFa } from '@/lib/format';
const STYLE: Record<string, { icon: LucideIcon; color: string; bg: string }> = { const STYLE: Record<string, { icon: LucideIcon; color: string; bg: string }> = {
xp_earned: { icon: Star, color: '#E8A400', bg: '#FFF8E1' }, xp_earned: { icon: Star, color: '#E8A400', bg: '#FFF8E1' },
@@ -83,7 +83,7 @@ export function NotificationsScreen() {
</span> </span>
<span className="min-w-0 flex-1"> <span className="min-w-0 flex-1">
<span className={`block text-sm ${n.isRead ? 'text-muted' : 'font-bold text-ink'}`}>{n.title}</span> <span className={`block text-sm ${n.isRead ? 'text-muted' : 'font-bold text-ink'}`}>{n.title}</span>
{n.body && <span className="mt-0.5 block whitespace-pre-line text-xs leading-6 text-body">{n.body}</span>} {n.body && <span className="mt-0.5 block whitespace-pre-line text-xs leading-6 text-body">{toFa(n.body)}</span>}
<span className="mt-1 block text-[10px] text-faint">{relativeTime(n.createdAt)}</span> <span className="mt-1 block text-[10px] text-faint">{relativeTime(n.createdAt)}</span>
</span> </span>
{!n.isRead && <span className="mt-1.5 h-2 w-2 flex-shrink-0 rounded-full bg-coral" />} {!n.isRead && <span className="mt-1.5 h-2 w-2 flex-shrink-0 rounded-full bg-coral" />}

View File

@@ -14,6 +14,7 @@ import { useToast } from '@/components/Toast';
import { ErrorState, InlineError, LoadingState, PrimaryButton, SecondaryButton, Screen } from '@/components/ui'; import { ErrorState, InlineError, LoadingState, PrimaryButton, SecondaryButton, Screen } from '@/components/ui';
import { friendlyError } from '@/lib/errors'; import { friendlyError } from '@/lib/errors';
import { timeUntil, toFa } from '@/lib/format'; import { timeUntil, toFa } from '@/lib/format';
import { MathText } from '@/lib/MathText';
import { sounds } from '@/lib/sound'; import { sounds } from '@/lib/sound';
type Phase = type Phase =
@@ -272,7 +273,7 @@ export function QuizScreen({ lessonId, nodeId }: { lessonId?: number; nodeId?: s
<Flag size={12} /> گزارشِ ایراد <Flag size={12} /> گزارشِ ایراد
</button> </button>
</div> </div>
<h2 className="whitespace-pre-line text-base font-bold leading-8 text-ink">{question.prompt}</h2> <h2 className="whitespace-pre-line text-base font-bold leading-8 text-ink"><MathText text={question.prompt} /></h2>
</div> </div>
<div className={shortOptions ? 'grid grid-cols-2 gap-2.5' : 'flex flex-col gap-2.5'}> <div className={shortOptions ? 'grid grid-cols-2 gap-2.5' : 'flex flex-col gap-2.5'}>
@@ -285,7 +286,7 @@ export function QuizScreen({ lessonId, nodeId }: { lessonId?: number; nodeId?: s
whileTap={{ scale: selected === null ? 0.95 : 1 }} whileTap={{ scale: selected === null ? 0.95 : 1 }}
className={`flex min-h-14 items-center justify-center gap-1.5 rounded-2xl border-2 border-b-4 px-3 py-3 font-black transition-colors ${shortOptions ? 'text-xl' : 'text-base'} ${optionClass(option.id)}`} className={`flex min-h-14 items-center justify-center gap-1.5 rounded-2xl border-2 border-b-4 px-3 py-3 font-black transition-colors ${shortOptions ? 'text-xl' : 'text-base'} ${optionClass(option.id)}`}
> >
<span dir="auto">{option.value}</span> <span><MathText text={option.value} /></span>
{answer && option.id === answer.correctOptionId && <Check size={16} className="text-green-500" strokeWidth={3} />} {answer && option.id === answer.correctOptionId && <Check size={16} className="text-green-500" strokeWidth={3} />}
{answer && option.id === selected && !answer.correct && <X size={16} className="text-red-400" strokeWidth={3} />} {answer && option.id === selected && !answer.correct && <X size={16} className="text-red-400" strokeWidth={3} />}
</motion.button> </motion.button>

View File

@@ -1,10 +1,9 @@
import { useState } from 'react'; import { useState } from 'react';
import { Bug, MessageCircle, Send } from 'lucide-react'; import { Bug, MessageCircle, Send } from 'lucide-react';
import { api, type Ticket } from '@/api'; import { api, type TicketSummary } from '@/api';
import { useAsync } from '@/lib/useAsync'; import { useAsync } from '@/lib/useAsync';
import { KEYS, store } from '@/lib/storage';
import { useToast } from '@/components/Toast'; import { useToast } from '@/components/Toast';
import { InlineError, PrimaryButton, Screen, ScreenBody, ScreenHeader } from '@/components/ui'; import { InlineError, PrimaryButton, Screen, ScreenBody, ScreenHeader, Sep } from '@/components/ui';
import { friendlyError } from '@/lib/errors'; import { friendlyError } from '@/lib/errors';
import { toFa } from '@/lib/format'; import { toFa } from '@/lib/format';
@@ -22,15 +21,6 @@ const STATUS_LABEL: Record<string, string> = {
closed: 'بسته', closed: 'بسته',
}; };
/** سرور فهرستِ تیکت‌ها را نمی‌دهد؛ شناسه‌ها را همین‌جا نگه می‌داریم. */
function savedTicketIds(): string[] {
try {
return JSON.parse(store.get(KEYS.ticketIds) ?? '[]') as string[];
} catch {
return [];
}
}
export function SupportScreen() { export function SupportScreen() {
const toast = useToast(); const toast = useToast();
const [mode, setMode] = useState<'ticket' | 'bug'>('ticket'); const [mode, setMode] = useState<'ticket' | 'bug'>('ticket');
@@ -39,7 +29,8 @@ export function SupportScreen() {
const [text, setText] = useState(''); const [text, setText] = useState('');
const [sending, setSending] = useState(false); const [sending, setSending] = useState(false);
const [error, setError] = useState(''); const [error, setError] = useState('');
const [ticketIds, setTicketIds] = useState(savedTicketIds); // فهرست از سرور می‌آید، پس تیکت و پاسخش با عوض شدنِ گوشی هم دیده می‌شود.
const tickets = useAsync(() => api.support.tickets(), []);
async function submit() { async function submit() {
if (!subject.trim() || !text.trim()) return; if (!subject.trim() || !text.trim()) return;
@@ -52,9 +43,7 @@ export function SupportScreen() {
} else { } else {
const t = await api.support.createTicket(subject.trim(), category); const t = await api.support.createTicket(subject.trim(), category);
await api.support.reply(t.ticketId, text.trim()); await api.support.reply(t.ticketId, text.trim());
const ids = [t.ticketId, ...ticketIds].slice(0, 20); tickets.reload();
store.set(KEYS.ticketIds, JSON.stringify(ids));
setTicketIds(ids);
toast('پیامت رسید؛ جواب همین‌جا و در اعلان‌ها میاد.', 'success'); toast('پیامت رسید؛ جواب همین‌جا و در اعلان‌ها میاد.', 'success');
} }
setSubject(''); setSubject('');
@@ -116,11 +105,11 @@ export function SupportScreen() {
<Send size={16} className="-scale-x-100" /> ارسال <Send size={16} className="-scale-x-100" /> ارسال
</PrimaryButton> </PrimaryButton>
{ticketIds.length > 0 && ( {!!tickets.data?.length && (
<section> <section>
<h2 className="mb-2 mt-2 text-sm font-black text-ink">پیام‌های قبلیِ تو</h2> <h2 className="mb-2 mt-2 text-sm font-black text-ink">پیام‌های قبلیِ تو</h2>
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
{ticketIds.map((id) => <TicketCard key={id} ticketId={id} />)} {tickets.data.map((t) => <TicketCard key={t.ticketId} summary={t} />)}
</div> </div>
</section> </section>
)} )}
@@ -129,26 +118,24 @@ export function SupportScreen() {
); );
} }
function TicketCard({ ticketId }: { ticketId: string }) { function TicketCard({ summary }: { summary: TicketSummary }) {
const toast = useToast(); const toast = useToast();
const ticket = useAsync(() => api.support.ticket(ticketId), [ticketId]);
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
// پیام‌ها فقط وقتی کارت باز شود گرفته می‌شوند؛ فهرست خودش خلاصه را دارد.
const detail = useAsync(() => (open ? api.support.ticket(summary.ticketId) : Promise.resolve(null)), [open, summary.ticketId]);
const [reply, setReply] = useState(''); const [reply, setReply] = useState('');
const [sending, setSending] = useState(false); const [sending, setSending] = useState(false);
const t = detail.data;
if (ticket.error || !ticket.data) { const status = t?.status ?? summary.status;
return ticket.loading ? <div className="h-14 animate-pulse rounded-2xl bg-soft" /> : null; const staffReplies = t ? t.messages.filter((m) => m.sender !== 'user').length : summary.supportReplies;
}
const t: Ticket = ticket.data;
const staffReplies = t.messages.filter((m) => m.sender !== 'user').length;
async function send() { async function send() {
if (!reply.trim()) return; if (!reply.trim()) return;
setSending(true); setSending(true);
try { try {
await api.support.reply(ticketId, reply.trim()); await api.support.reply(summary.ticketId, reply.trim());
setReply(''); setReply('');
ticket.reload(); detail.reload();
} catch (err) { } catch (err) {
toast(friendlyError(err), 'error'); toast(friendlyError(err), 'error');
} finally { } finally {
@@ -160,16 +147,20 @@ function TicketCard({ ticketId }: { ticketId: string }) {
<div className="rounded-2xl border border-line bg-white"> <div className="rounded-2xl border border-line bg-white">
<button type="button" onClick={() => setOpen((o) => !o)} className="flex w-full items-center gap-3 p-3.5 text-right"> <button type="button" onClick={() => setOpen((o) => !o)} className="flex w-full items-center gap-3 p-3.5 text-right">
<span className="min-w-0 flex-1"> <span className="min-w-0 flex-1">
<span className="block truncate text-sm font-bold text-ink">{t.subject}</span> <span className="block truncate text-sm font-bold text-ink">{summary.subject}</span>
<span className="text-[11px] text-muted"> <span className="text-[11px] text-muted">
{STATUS_LABEL[t.status] ?? t.status} {STATUS_LABEL[status] ?? status}
{staffReplies > 0 && ` · ${toFa(staffReplies)} پاسخ`} {staffReplies > 0 && <><Sep />{toFa(staffReplies)} پاسخ</>}
</span> </span>
</span> </span>
{staffReplies > 0 && !open && <span className="h-2 w-2 flex-shrink-0 rounded-full bg-indigo" aria-hidden />}
</button> </button>
{open && ( {open && (
<div className="flex flex-col gap-2 border-t border-line p-3.5"> <div className="flex flex-col gap-2 border-t border-line p-3.5">
{t.messages.map((m) => ( {!t && (detail.error
? <InlineError>{friendlyError(detail.error)}</InlineError>
: <div className="h-10 animate-pulse rounded-2xl bg-soft" />)}
{t?.messages.map((m) => (
<div <div
key={m.id} key={m.id}
className={`whitespace-pre-line rounded-2xl px-3.5 py-2.5 text-xs leading-6 ${m.sender === 'user' ? 'mr-8 bg-soft text-body' : 'ml-8 bg-[#EEF1FF] text-ink'}`} className={`whitespace-pre-line rounded-2xl px-3.5 py-2.5 text-xs leading-6 ${m.sender === 'user' ? 'mr-8 bg-soft text-body' : 'ml-8 bg-[#EEF1FF] text-ink'}`}
@@ -177,7 +168,7 @@ function TicketCard({ ticketId }: { ticketId: string }) {
{m.text} {m.text}
</div> </div>
))} ))}
{t.status !== 'closed' && ( {t && status !== 'closed' && (
<div className="mt-1 flex gap-2"> <div className="mt-1 flex gap-2">
<input <input
value={reply} value={reply}

View File

@@ -12,6 +12,18 @@ export default defineConfig(({ mode }) => {
resolve: { resolve: {
alias: { '@': path.resolve(__dirname, './src') }, alias: { '@': path.resolve(__dirname, './src') },
}, },
build: {
rollupOptions: {
output: {
// کتابخانه‌ها با هر انتشار عوض نمی‌شوند؛ فایلِ جدا یعنی بعد از هر دیپلوی
// از کشِ مرورگر می‌آیند و فقط کدِ خودِ اپ دوباره دانلود می‌شود.
manualChunks: {
react: ['react', 'react-dom'],
motion: ['motion/react'],
},
},
},
},
server: { server: {
// در توسعه /api هم‌دامنه است و به بک‌اند پاس داده می‌شود؛ CORS لازم نیست. // در توسعه /api هم‌دامنه است و به بک‌اند پاس داده می‌شود؛ CORS لازم نیست.
proxy: { proxy: {