RezinaLMS-CustomerEnd/packages/features/src/store.tsx
kirukib 81e27661e1 feat: Sirkul brand, landing refresh, new footer, international waitlist phone
- Sirkul logo everywhere (header wordmark, phone monogram, favicon, footer); brand name "Sirkul Makeup"
- One font (Plus Jakarta Sans) across app and waitlist; cursive serif removed
- Habesha model photos from Wikimedia Commons (CC BY-SA, credited in footer and waitlist)
- Landing: light/dark theme toggle, live waitlist pill, photo category cards,
  how-it-works + grouped payment panel, photo CTA; less emphasis on languages
- Footer: framed card with starter-kit list (IconPark icons), student-work photo reel, credits
- Waitlist: international country-code picker, live "people waiting" pill fed by a
  doGet signup count in the Apps Script (count only, no personal data)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 11:22:28 +03:00

154 lines
7.3 KiB
TypeScript

'use client';
import { createContext, useCallback, useContext, useEffect, useRef, useState, type ReactNode } from 'react';
import type { Category, Course, DataSource, InboxItem, Locale, Settings, Student, Viewer } from '@lms/data';
import { LOCALES, newId } from '@lms/data';
import { messages } from '@lms/i18n';
export const DEFAULT_SETTINGS: Settings = { brandName: 'Sirkul Makeup', supportPhone: '+251 911 000 000', telegramLink: 'https://t.me/', supportEmail: 'support@example.com', sessionLimit: 2, maintenanceBanner: '' };
const store = {
get(k: string) { try { return localStorage.getItem('lms.' + k); } catch { return null; } },
set(k: string, v: string | null) { try { v == null ? localStorage.removeItem('lms.' + k) : localStorage.setItem('lms.' + k, v); } catch { /* per-viewer convenience only */ } },
};
// ---------------------------------------------------------------- hash router
export function parseRoute(hash: string): string[] {
return hash.replace(/^#\/?/, '').split('/').filter(Boolean).map(decodeURIComponent);
}
interface Ctx {
ds: DataSource;
viewer: Viewer | null;
ready: boolean;
categories: Category[]; courses: Course[]; settings: Settings; catalogLoaded: boolean;
/** The signed-in student; null when signed out, so no screen shows a signed-out visitor's courses. */
me: Student | null; meLoaded: boolean; signedIn: boolean;
/** The stored student record even when signed out (sign-in uses it for "Continue as"). */
account: Student | null;
inbox: InboxItem[];
locale: Locale; setLocale(l: Locale): void;
route: string[]; nav(path: string): void;
toast(msg: string): void;
/** Serialized writes: the db wants one write at a time per document. */
write(fn: () => Promise<void>, okMsg?: string): Promise<boolean>;
signIn(): void; signOut(): void;
notify(studentId: string, item: Omit<InboxItem, 'id' | 'createdAt'>): Promise<void>;
msg(loc: Locale, key: string, vars?: Record<string, string | number>): string;
}
const AppCtx = createContext<Ctx | null>(null);
export const useApp = () => { const c = useContext(AppCtx); if (!c) throw new Error('AppProvider missing'); return c; };
/** Message lookup outside React components (system notifications are written in the student's language). */
export function lookup(loc: Locale, key: string, vars: Record<string, string | number> = {}): string {
const get = (l: Locale) => key.split('.').reduce<any>((o, k) => o?.[k], messages[l]);
const raw: string = get(loc) ?? get('en') ?? key;
return raw.replace(/\{(\w+)(?:, plural,[^{}]*(?:\{[^{}]*\}[^{}]*)*)?\}/g, (_m, k) => String(vars[k] ?? ''));
}
export function AppProvider({ ds, children }: { ds: DataSource; children: ReactNode }) {
const [viewer, setViewer] = useState<Viewer | null>(null);
const [ready, setReady] = useState(false);
const [categories, setCategories] = useState<Category[]>([]);
const [courses, setCourses] = useState<Course[]>([]);
const [settings, setSettings] = useState<Settings | null>(null);
const [catalogLoaded, setCatalogLoaded] = useState(false);
const [me, setMe] = useState<Student | null>(null);
const [meLoaded, setMeLoaded] = useState(false);
const [inbox, setInbox] = useState<InboxItem[]>([]);
const [route, setRoute] = useState<string[]>([]);
const [locale, setLocaleState] = useState<Locale>('en');
const [toastMsg, setToastMsg] = useState<string | null>(null);
const [signedOut, setSignedOut] = useState(false);
const chain = useRef<Promise<unknown>>(Promise.resolve());
const toastTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
// initial route + locale (client only)
useEffect(() => {
const r = parseRoute(location.hash);
const saved = store.get('locale') as Locale | null;
const loc = (LOCALES as string[]).includes(r[0]) ? (r[0] as Locale) : saved && LOCALES.includes(saved) ? saved : 'en';
setLocaleState(loc);
setRoute(r.length ? r : [loc]);
setSignedOut(store.get('signedOut') === '1');
const onHash = () => setRoute(parseRoute(location.hash));
addEventListener('hashchange', onHash); addEventListener('popstate', onHash);
return () => { removeEventListener('hashchange', onHash); removeEventListener('popstate', onHash); };
}, []);
useEffect(() => {
let alive = true;
ds.viewer().then((v) => { if (alive) { setViewer(v); setReady(true); } });
let gotCourses = false, gotCats = false;
const done = () => { if (gotCourses && gotCats) setCatalogLoaded(true); };
const u1 = ds.watchCourses((c) => { setCourses(c); gotCourses = true; done(); });
const u2 = ds.watchCategories((c) => { setCategories([...c].sort((a, b) => a.sortOrder - b.sortOrder)); gotCats = true; done(); });
const u3 = ds.watchSettings(setSettings);
return () => { alive = false; u1(); u2(); u3(); };
}, [ds]);
const uid = viewer?.id ?? null;
useEffect(() => {
if (!ready) return;
if (!uid) { setMeLoaded(true); return; }
const u1 = ds.watchStudent(uid, (s) => { setMe(s); setMeLoaded(true); });
const u2 = ds.watchInbox(uid, setInbox);
return () => { u1(); u2(); };
}, [ds, uid, ready]);
const nav = useCallback((path: string) => {
const r = parseRoute(path);
setRoute(r);
try { if (location.hash !== '#' + path) history.pushState(null, '', '#' + path); } catch { /* sandboxed history: state already updated */ }
try { scrollTo({ top: 0 }); } catch { /* jsdom */ }
}, []);
const toast = useCallback((m: string) => {
setToastMsg(m);
if (toastTimer.current) clearTimeout(toastTimer.current);
toastTimer.current = setTimeout(() => setToastMsg(null), 3200);
}, []);
const msg = useCallback((loc: Locale, key: string, vars?: Record<string, string | number>) => lookup(loc, key, vars), []);
const write = useCallback((fn: () => Promise<void>, okMsg?: string) => {
const p = chain.current.then(fn).then(() => { if (okMsg) toast(okMsg); return true; }, (e) => {
console.warn(e); toast(e?.code === 'not_granted' || e?.code === 'invalid_argument' ? lookup(locale, 'common.readOnly') : lookup(locale, 'common.saveFailed'));
return false;
});
chain.current = p;
return p;
}, [toast, locale]);
const setLocale = useCallback((l: Locale) => {
setLocaleState(l); store.set('locale', l);
setRoute((r) => {
const next = (LOCALES as string[]).includes(r[0]) ? [l, ...r.slice(1)] : r;
try { history.replaceState(null, '', '#/' + next.join('/')); } catch { /* ignore */ }
return next;
});
if (me && me.locale !== l && !me.deletedAt) write(() => ds.patchStudent(me.id, { locale: l }));
}, [me, ds, write]);
const notify = useCallback(async (studentId: string, item: Omit<InboxItem, 'id' | 'createdAt'>) => {
await ds.addInbox(studentId, { ...item, id: newId('n_'), createdAt: new Date().toISOString(), readAt: null });
}, [ds]);
const value: Ctx = {
ds, viewer, ready, categories, courses, settings: settings ?? DEFAULT_SETTINGS, catalogLoaded,
me: me && !me.deletedAt && !signedOut ? me : null, account: me, meLoaded, signedIn: !!me && !me.deletedAt && !signedOut, inbox,
locale, setLocale, route, nav, toast, write,
signIn: () => { store.set('signedOut', null); setSignedOut(false); },
signOut: () => { store.set('signedOut', '1'); setSignedOut(true); },
notify, msg,
};
return (
<AppCtx.Provider value={value}>
{children}
{toastMsg && <div className="toast" role="status">{toastMsg}</div>}
</AppCtx.Provider>
);
}