rebuild the app on a typed, modular structure wired to the real API

The whole app lived in one 3,071-line App.tsx on a Figma scaffold (60 unused
packages, 45 unused UI components, no type-check). The live site could not
reach the backend, Persian-keyboard digits were erased from the phone field,
guests were signed out after an hour, "mark read" hit a method the server
does not accept (405), and iOS Safari blocked the payment window.

What changed:
- src/ split into api/ (one typed client: timeouts, GET retry, single-flight
  refresh, SSE), screens/ (one file each), components/, state/, nav/, lib/.
- The API address is configuration only: public/config.js at runtime, then
  VITE_API_BASE_URL at build time, then same-origin /api. No domain in code.
- Responsive shell instead of a fixed 390x844 phone frame; self-hosted
  Vazirmatn instead of Google Fonts; strict TypeScript, `npm run build`
  type-checks first.
- Everything on the handoff list: tutor answers keep their line breaks, have
  thumbs up/down, follow-ups, "from the book" badge, retry, history that
  survives tab switches and reloads, "why was I wrong" from a wrong answer
  with questionId; question reports; hearts with maxHearts/unlimited and a
  no-hearts screen with the refill time; result screen and a visible error
  when lesson completion fails; subscription status, badge, discount code
  before the gateway and the payment-return message; guest refresh token;
  6-digit OTP with resend timer; age saved as a Jalali birthYear; PATCH
  read-all; leaderboard refetched on open with "you" highlighted; selected
  companion shown across the app; logout that revokes the refresh token.
- New screens for endpoints that had none: profile, streak calendar,
  support tickets and bug reports, parents, invite-a-friend (with ?ref=
  tracking), guest-to-phone upgrade.
- Browser/phone back button walks the screen stack.

Checked with a headless-Chrome walkthrough against a local backend at
390x844 and 360x740 (fresh guest: onboarding, setup, a full lesson, map,
island sheet, every tab and sub-screen, one real tutor question, reload,
logout): no console errors, no failed API calls. Real SMS login and a real
Zarinpal payment were not exercised.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-09-26 23:35:48 +03:30
parent b411b636f4
commit 348bfecea6
120 changed files with 5840 additions and 12783 deletions

111
src/state/AppData.tsx Normal file
View File

@@ -0,0 +1,111 @@
import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from 'react';
import { api, type Character, type Grade, type HomeResponse, type UserProfile, type UserSummary } from '@/api';
import { seyarFromSlug, type SeyarChar } from '@/mascots/seyar';
/**
* داده‌هایی که چند صفحه با هم لازم دارند: پروفایل، آمار، نقشه، همراهِ انتخابی
* و تعدادِ اعلانِ نخوانده. هر صفحه بعد از کاری که این‌ها را عوض می‌کند
* (پایانِ درس، عوض کردنِ پایه، …) refresh را صدا می‌زند.
*/
interface AppData {
profile: UserProfile;
grades: Grade[];
gradeTitle: string;
summary: UserSummary | null;
home: HomeResponse | null;
homeError: unknown;
/** همراهی که کاربر در صفحه‌ی کاراکترها انتخاب کرده؛ پیش‌فرض سیگما. */
companion: SeyarChar;
unreadCount: number;
refreshHome: () => Promise<void>;
refreshSummary: () => Promise<void>;
refreshUnread: () => Promise<void>;
setProfile: (profile: UserProfile) => void;
setCompanion: (character: Character) => void;
setUnreadCount: (count: number) => void;
}
const AppDataContext = createContext<AppData | null>(null);
export function AppDataProvider({
initialProfile,
grades,
children,
}: {
initialProfile: UserProfile;
grades: Grade[];
children: ReactNode;
}) {
const [profile, setProfile] = useState(initialProfile);
const [summary, setSummary] = useState<UserSummary | null>(null);
const [home, setHome] = useState<HomeResponse | null>(null);
const [homeError, setHomeError] = useState<unknown>(null);
const [companion, setCompanionChar] = useState<SeyarChar>('sigma');
const [unreadCount, setUnreadCount] = useState(0);
const refreshHome = useCallback(async () => {
try {
setHome(await api.home());
setHomeError(null);
} catch (err) {
setHomeError(err);
}
}, []);
const refreshSummary = useCallback(async () => {
try {
setSummary(await api.summary());
} catch {
/* آمار تزئینی است؛ نبودنش صفحه را خراب نمی‌کند */
}
}, []);
const refreshUnread = useCallback(async () => {
try {
setUnreadCount((await api.notifications.list()).unreadCount);
} catch {
/* نشانِ اعلان اختیاری است */
}
}, []);
useEffect(() => {
void refreshHome();
void refreshSummary();
void refreshUnread();
api.characters
.list()
.then((list) => {
const selected = seyarFromSlug(list.find((c) => c.selected)?.slug);
if (selected) setCompanionChar(selected);
})
.catch(() => {});
}, [refreshHome, refreshSummary, refreshUnread]);
const value = useMemo<AppData>(
() => ({
profile,
grades,
gradeTitle: grades.find((g) => g.id === profile.gradeId)?.title ?? '',
summary,
home,
homeError,
companion,
unreadCount,
refreshHome,
refreshSummary,
refreshUnread,
setProfile,
setCompanion: (character) => setCompanionChar(seyarFromSlug(character.slug) ?? 'sigma'),
setUnreadCount,
}),
[profile, grades, summary, home, homeError, companion, unreadCount, refreshHome, refreshSummary, refreshUnread],
);
return <AppDataContext.Provider value={value}>{children}</AppDataContext.Provider>;
}
export function useAppData(): AppData {
const data = useContext(AppDataContext);
if (!data) throw new Error('useAppData بیرون از AppDataProvider صدا زده شد');
return data;
}

86
src/state/askStore.ts Normal file
View File

@@ -0,0 +1,86 @@
import { useSyncExternalStore } from 'react';
import type { UsedChunk } from '@/api';
import { KEYS, store } from '@/lib/storage';
/**
* گفتگوی دستیار، بیرون از کامپوننت تا با عوض کردنِ تب پاک نشود.
* شناسه‌ی گفتگو در localStorage می‌ماند و بعد از بستنِ اپ تاریخچه از سرور برمی‌گردد.
*/
export interface ChatMessage {
localId: number;
role: 'user' | 'assistant';
text: string;
messageId?: string;
usedChunks?: UsedChunk[];
followUps?: string[];
feedback?: 'up' | 'down';
/** پیامِ خطا به‌جای پاسخ؛ با «دوباره» همان سوال دوباره فرستاده می‌شود. */
failedQuestion?: string;
}
interface AskState {
messages: ChatMessage[];
conversationId: string | null;
/** درسی که گفتگو درباره‌ی آن است؛ عوض شدنش یعنی گفتگوی تازه. */
lessonId: number | null;
historyLoaded: boolean;
}
let state: AskState = {
messages: [],
conversationId: store.get(KEYS.conversationId),
lessonId: null,
historyLoaded: false,
};
let nextLocalId = 1;
const listeners = new Set<() => void>();
function emit(next: Partial<AskState>) {
state = { ...state, ...next };
if ('conversationId' in next) {
if (state.conversationId) store.set(KEYS.conversationId, state.conversationId);
else store.remove(KEYS.conversationId);
}
listeners.forEach((l) => l());
}
export const askStore = {
get: () => state,
subscribe(listener: () => void) {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
},
add(message: Omit<ChatMessage, 'localId'>): number {
const localId = nextLocalId++;
emit({ messages: [...state.messages, { ...message, localId }] });
return localId;
},
update(localId: number, patch: Partial<ChatMessage>) {
emit({ messages: state.messages.map((m) => (m.localId === localId ? { ...m, ...patch } : m)) });
},
remove(localId: number) {
emit({ messages: state.messages.filter((m) => m.localId !== localId) });
},
setConversation(conversationId: string | null, lessonId: number | null = state.lessonId) {
emit({ conversationId, lessonId });
},
setHistory(messages: Omit<ChatMessage, 'localId'>[]) {
emit({ messages: messages.map((m) => ({ ...m, localId: nextLocalId++ })), historyLoaded: true });
},
markHistoryLoaded() {
emit({ historyLoaded: true });
},
reset(lessonId: number | null = null) {
emit({ messages: [], conversationId: null, lessonId, historyLoaded: true });
},
/** بعد از خروج از حساب، گفتگوی کاربرِ قبلی نباید بماند. */
clear() {
emit({ messages: [], conversationId: null, lessonId: null, historyLoaded: false });
},
};
export function useAskState(): AskState {
return useSyncExternalStore(askStore.subscribe, askStore.get);
}

57
src/state/curriculum.ts Normal file
View File

@@ -0,0 +1,57 @@
import type { HomeNode, HomeResponse, HomeUnit, NodeStatus } from '@/api';
/** رنگِ فصل‌ها؛ سرور برای فصل رنگ نمی‌دهد، پس چرخشی انتخاب می‌شود. */
const UNIT_PALETTE = ['#ED6956', '#91ADC6', '#97C0C0', '#9B7BFF', '#FF7A3D', '#F3A9B0', '#4C5FD5', '#5FBF8F', '#E06BAE'];
export const unitColor = (index: number) => UNIT_PALETTE[((index % UNIT_PALETTE.length) + UNIT_PALETTE.length) % UNIT_PALETTE.length];
export function unitProgress(unit: HomeUnit) {
const total = unit.nodes.length;
const done = unit.nodes.filter((n) => n.status === 'completed').length;
return { done, total, percent: total ? Math.round((done / total) * 100) : 0 };
}
export const isPlayable = (status: NodeStatus) => status !== 'locked';
export interface NodeRef {
unit: HomeUnit;
unitIndex: number;
node: HomeNode;
}
/** اولین جزیره‌ی بازِ ناتمام در کلِ نقشه؛ برای «ادامه بده». */
export function findContinue(home: HomeResponse | null): NodeRef | null {
if (!home) return null;
for (let i = 0; i < home.units.length; i++) {
const node = home.units[i].nodes.find((n) => n.status !== 'completed' && n.status !== 'locked');
if (node) return { unit: home.units[i], unitIndex: i, node };
}
return null;
}
export function findNode(home: HomeResponse | null, nodeId: string | undefined): NodeRef | null {
if (!home || !nodeId) return null;
for (let i = 0; i < home.units.length; i++) {
const node = home.units[i].nodes.find((n) => n.id === nodeId);
if (node) return { unit: home.units[i], unitIndex: i, node };
}
return null;
}
export function findUnit(home: HomeResponse | null, unitId: string) {
const index = home?.units.findIndex((u) => u.id === unitId) ?? -1;
return index >= 0 ? { unit: home!.units[index], unitIndex: index } : null;
}
/** جزیره‌ای که این درس در آن است. */
export function findNodeOfLesson(home: HomeResponse | null, lessonId: number): NodeRef | null {
if (!home) return null;
for (let i = 0; i < home.units.length; i++) {
const node = home.units[i].nodes.find((n) => n.lessonIds.includes(lessonId));
if (node) return { unit: home.units[i], unitIndex: i, node };
}
return null;
}
/** درسی که با زدنِ جزیره باز می‌شود. */
export const nextLessonOf = (node: HomeNode): number | null => node.nextLessonId ?? node.lessonIds[0] ?? null;