Compare commits
2 Commits
main
...
feat/devic
| Author | SHA1 | Date | |
|---|---|---|---|
| 2f42f08368 | |||
| 28a1ad5228 |
|
|
@ -2,7 +2,7 @@
|
|||
// https://api.rezina.yaltopia.com (2026-11-02): GET /catalog/courses and GET /catalog/courses/12.
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { absolute, ids, mapIssue, mapNotification, mapOutline, mapStudent, slugify, type RawOutline } from './api.ts';
|
||||
import { absolute, ApiDataSource, DeviceLimitError, ids, mapIssue, mapNotification, mapOutline, mapStudent, slugify, type RawOutline } from './api.ts';
|
||||
|
||||
const BASE = 'https://api.rezina.yaltopia.com';
|
||||
const fixture = (f: string) => JSON.parse(readFileSync(new URL(f, import.meta.url), 'utf8')).data;
|
||||
|
|
@ -70,4 +70,193 @@ assert.equal(s.progress.l39?.positionSec, 40, 'this session’s resume point sur
|
|||
assert.equal(s.issues['1']?.type, 'PAYMENT');
|
||||
assert.equal(mapStudent({ id: 1, preferred_language: 'fr' }, null, [], {}, now).locale, 'en', 'unknown language falls back to English');
|
||||
|
||||
// sign-out revocation (mocked transport only: these checks never contact the production API)
|
||||
const TOKEN_KEY = 'lms.api.tokens';
|
||||
const storage = new Map<string, string>();
|
||||
Object.defineProperty(globalThis, 'localStorage', { configurable: true, value: {
|
||||
getItem: (key: string) => storage.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => storage.set(key, value),
|
||||
removeItem: (key: string) => storage.delete(key),
|
||||
} });
|
||||
const oldTokens = { access: 'access-old', refresh: 'refresh-old', userId: 9 };
|
||||
const seedTokens = () => storage.set(TOKEN_KEY, JSON.stringify(oldTokens));
|
||||
const mockBase = 'https://mock.invalid';
|
||||
const response = (body: unknown, status = 200) => new Response(body == null ? null : JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
|
||||
|
||||
// normal logout carries both credentials, then removes the local session
|
||||
seedTokens();
|
||||
let calls: { url: string; init?: RequestInit }[] = [];
|
||||
globalThis.fetch = async (input, init) => { calls.push({ url: String(input), init }); return response(null, 204); };
|
||||
await new ApiDataSource(mockBase).auth.signOut();
|
||||
assert.equal(calls.length, 1);
|
||||
assert.equal(calls[0].url, `${mockBase}/api/v1/auth/logout`);
|
||||
assert.equal(new Headers(calls[0].init?.headers).get('authorization'), 'Bearer access-old');
|
||||
assert.deepEqual(JSON.parse(String(calls[0].init?.body)), { refresh_token: 'refresh-old' });
|
||||
assert.equal(storage.get(TOKEN_KEY), undefined);
|
||||
|
||||
// an expired access token refreshes once, then revokes with the rotated pair
|
||||
seedTokens(); calls = [];
|
||||
globalThis.fetch = async (input, init) => {
|
||||
const url = String(input); calls.push({ url, init });
|
||||
if (url.endsWith('/auth/logout') && calls.filter((x) => x.url.endsWith('/auth/logout')).length === 1) return response({ message: 'expired' }, 401);
|
||||
if (url.endsWith('/auth/refresh')) return response({ data: { access_token: 'access-new', refresh_token: 'refresh-new', user_id: 9 } });
|
||||
return response(null, 204);
|
||||
};
|
||||
await new ApiDataSource(mockBase).auth.signOut();
|
||||
assert.deepEqual(calls.map((x) => x.url.slice(mockBase.length)), ['/api/v1/auth/logout', '/api/v1/auth/refresh', '/api/v1/auth/logout']);
|
||||
assert.equal(new Headers(calls[2].init?.headers).get('authorization'), 'Bearer access-new');
|
||||
assert.deepEqual(JSON.parse(String(calls[2].init?.body)), { refresh_token: 'refresh-new' });
|
||||
assert.equal(storage.get(TOKEN_KEY), undefined);
|
||||
|
||||
// network failure never prevents local sign-out
|
||||
seedTokens();
|
||||
globalThis.fetch = async () => { throw new Error('offline'); };
|
||||
await new ApiDataSource(mockBase).auth.signOut();
|
||||
assert.equal(storage.get(TOKEN_KEY), undefined);
|
||||
|
||||
// a refresh that started before sign-out cannot restore its result afterward
|
||||
seedTokens();
|
||||
let releaseRefresh!: (value: Response) => void;
|
||||
let refreshStarted!: () => void;
|
||||
const started = new Promise<void>((resolve) => { refreshStarted = resolve; });
|
||||
globalThis.fetch = async (input) => {
|
||||
const url = String(input);
|
||||
if (url.endsWith('/user/user-profile')) return response({ message: 'expired' }, 401);
|
||||
if (url.endsWith('/auth/refresh')) { refreshStarted(); return new Promise<Response>((resolve) => { releaseRefresh = resolve; }); }
|
||||
if (url.endsWith('/auth/logout')) return response(null, 204);
|
||||
throw new Error(`unexpected mocked request: ${url}`);
|
||||
};
|
||||
const racing = new ApiDataSource(mockBase);
|
||||
const viewing = racing.viewer();
|
||||
await started;
|
||||
const signingOut = racing.auth.signOut();
|
||||
releaseRefresh(response({ data: { access_token: 'late-access', refresh_token: 'late-refresh', user_id: 9 } }));
|
||||
await Promise.all([viewing, signingOut]);
|
||||
assert.equal(storage.get(TOKEN_KEY), undefined, 'late refresh must not recreate the signed-out session');
|
||||
|
||||
// device sessions and cross-tab tokens (mocked transport only)
|
||||
const newTokens = { access: 'access-new', refresh: 'refresh-new', userId: 9 };
|
||||
const stored = () => JSON.parse(storage.get(TOKEN_KEY) ?? 'null');
|
||||
const profile = { id: 9, first_name: 'Test', status: 'ACTIVE' };
|
||||
const bearer = (init?: RequestInit) => new Headers(init?.headers).get('authorization');
|
||||
|
||||
// two tabs: one refresh, and the second adopts the rotated pair
|
||||
seedTokens();
|
||||
let refreshes = 0;
|
||||
globalThis.fetch = async (input, init) => {
|
||||
const url = String(input);
|
||||
if (url.endsWith('/auth/refresh')) { refreshes++; return response({ data: { access_token: 'access-new', refresh_token: 'refresh-new', user_id: 9 } }); }
|
||||
return bearer(init) === 'Bearer access-new' ? response({ data: profile }) : response({ message: 'expired' }, 401);
|
||||
};
|
||||
const [tabA, tabB] = [new ApiDataSource(mockBase), new ApiDataSource(mockBase)];
|
||||
const viewers = await Promise.all([tabA.viewer(), tabB.viewer()]);
|
||||
assert.deepEqual(viewers.map((v) => v.id), ['9', '9']);
|
||||
assert.equal(refreshes, 1, 'a rotated token is never submitted twice');
|
||||
assert.deepEqual(stored(), newTokens);
|
||||
|
||||
// without Web Locks, a stale 401 adopts the newer stored pair and never erases it
|
||||
seedTokens();
|
||||
Object.defineProperty(navigator, 'locks', { configurable: true, value: undefined });
|
||||
globalThis.fetch = async (input, init) => {
|
||||
const url = String(input);
|
||||
if (url.endsWith('/auth/refresh')) { storage.set(TOKEN_KEY, JSON.stringify(newTokens)); return response({ message: 'not found' }, 401); }
|
||||
return bearer(init) === 'Bearer access-new' ? response({ data: profile }) : response({ message: 'expired' }, 401);
|
||||
};
|
||||
assert.equal((await new ApiDataSource(mockBase).viewer()).id, '9');
|
||||
assert.deepEqual(stored(), newTokens, 'a stale refresh failure must not erase a newer session');
|
||||
delete (navigator as unknown as Record<string, unknown>).locks;
|
||||
|
||||
// server and network failures during refresh keep the session
|
||||
for (const fail of [async () => response({ message: 'down' }, 503), async () => { throw new Error('offline'); }]) {
|
||||
seedTokens();
|
||||
globalThis.fetch = async (input) => (String(input).endsWith('/auth/refresh') ? fail() : response({ message: 'expired' }, 401));
|
||||
await new ApiDataSource(mockBase).viewer();
|
||||
assert.deepEqual(stored(), oldTokens, 'only a 401 from refresh ends the session');
|
||||
}
|
||||
|
||||
// a stable device id goes out on login, OTP and refresh
|
||||
storage.delete(TOKEN_KEY);
|
||||
const deviceIds = new Map<string, string | null>();
|
||||
globalThis.fetch = async (input, init) => {
|
||||
const path = String(input).slice(`${mockBase}/api/v1`.length);
|
||||
deviceIds.set(path, new Headers(init?.headers).get('x-device-id'));
|
||||
assert.equal(new Headers(init?.headers).has('x-device-platform'), false);
|
||||
if (path === '/user/checkPhoneEmailExist') return response({ data: { email_exist: true, phone_number_exist: false } });
|
||||
if (path === '/auth/customer-login' || path === '/user/verify-otp' || path === '/auth/refresh') return response({ data: { access_token: 'a2', refresh_token: 'r2', user_id: 9 } });
|
||||
return path === '/user/user-profile' && deviceIds.has('/auth/refresh') ? response({ data: profile }) : response({ message: 'expired' }, 401);
|
||||
};
|
||||
const deviceSource = new ApiDataSource(mockBase);
|
||||
await deviceSource.auth.start({ email: 'learner@example.test', password: 'password1' });
|
||||
await deviceSource.auth.verify({ phone: '+251900000000' }, '123456');
|
||||
storage.set(TOKEN_KEY, JSON.stringify(oldTokens));
|
||||
await new ApiDataSource(mockBase).viewer();
|
||||
const sentIds = ['/auth/customer-login', '/user/verify-otp', '/auth/refresh'].map((p) => deviceIds.get(p));
|
||||
assert.ok(sentIds[0]); assert.equal(new Set(sentIds).size, 1, 'the same device id on every call');
|
||||
assert.equal(storage.get('lms.deviceId'), sentIds[0]);
|
||||
|
||||
// a device-limit answer is typed and stores nothing
|
||||
storage.delete(TOKEN_KEY);
|
||||
const limit = { challenge_token: 'challenge', expires_at: '2026-11-23T12:05:00Z', devices: [{ id: 's1', label: 'Chrome on Android', platform: 'android', last_seen_at: now }] };
|
||||
globalThis.fetch = async (input) => (String(input).endsWith('/user/checkPhoneEmailExist')
|
||||
? response({ data: { email_exist: true, phone_number_exist: false } })
|
||||
: response({ message: 'Device limit reached', code: 'DEVICE_LIMIT_REACHED', data: limit }, 409));
|
||||
const limited = new ApiDataSource(mockBase);
|
||||
await assert.rejects(limited.auth.start({ email: 'learner@example.test', password: 'password1' }), (e: unknown) => e instanceof DeviceLimitError && e.challengeToken === 'challenge' && e.devices.length === 1);
|
||||
assert.equal(storage.get(TOKEN_KEY), undefined);
|
||||
|
||||
// replacing a device sends no bearer and stores the new session
|
||||
calls = [];
|
||||
globalThis.fetch = async (input, init) => { calls.push({ url: String(input), init }); return response({ data: { access_token: 'access-new', refresh_token: 'refresh-new', user_id: 9 } }); };
|
||||
await limited.auth.replaceDevice('challenge', 's1');
|
||||
assert.equal(calls[0].url, `${mockBase}/api/v1/auth/sessions/replace`);
|
||||
assert.equal(bearer(calls[0].init), null);
|
||||
assert.deepEqual(JSON.parse(String(calls[0].init?.body)), { challenge_token: 'challenge', session_id: 's1' });
|
||||
assert.deepEqual(stored(), newTokens);
|
||||
|
||||
// replacement failures stay distinguishable, so a dropped connection can retry
|
||||
storage.delete(TOKEN_KEY);
|
||||
globalThis.fetch = async () => { throw new Error('offline'); };
|
||||
await assert.rejects(limited.auth.replaceDevice('challenge', 's1'), (e: { status?: number }) => e.status === 0);
|
||||
globalThis.fetch = async () => response({ message: 'Invalid session replacement' }, 401);
|
||||
await assert.rejects(limited.auth.replaceDevice('challenge', 's1'), (e: { status?: number }) => e.status === 401);
|
||||
|
||||
// a revoked session skips refresh and notifies once across parallel calls
|
||||
seedTokens();
|
||||
refreshes = 0;
|
||||
globalThis.fetch = async (input) => {
|
||||
if (String(input).endsWith('/auth/refresh')) refreshes++;
|
||||
return response({ message: 'Session revoked', code: 'SESSION_REVOKED' }, 401);
|
||||
};
|
||||
const revoked = new ApiDataSource(mockBase);
|
||||
let revokedCount = 0;
|
||||
revoked.auth.onSessionRevoked(() => { revokedCount++; });
|
||||
await Promise.all([revoked.viewer(), revoked.viewer(), revoked.viewer()]);
|
||||
assert.equal(refreshes, 0); assert.equal(revokedCount, 1); assert.equal(storage.get(TOKEN_KEY), undefined);
|
||||
|
||||
// an expired token on a removed device learns about it from refresh
|
||||
seedTokens();
|
||||
globalThis.fetch = async (input) => (String(input).endsWith('/auth/refresh')
|
||||
? response({ message: 'Session revoked', code: 'SESSION_REVOKED' }, 401)
|
||||
: response({ message: 'Access token expired' }, 401));
|
||||
const expiredRevoked = new ApiDataSource(mockBase);
|
||||
let expiredCount = 0;
|
||||
expiredRevoked.auth.onSessionRevoked(() => { expiredCount++; });
|
||||
await expiredRevoked.viewer();
|
||||
assert.equal(expiredCount, 1); assert.equal(storage.get(TOKEN_KEY), undefined);
|
||||
|
||||
// another tab: a rotation is adopted silently, a sign-out clears this tab
|
||||
seedTokens();
|
||||
let tabCalls = 0;
|
||||
globalThis.fetch = async (input) => { tabCalls++; return response({ data: String(input).includes('/catalog/courses') ? { courses: [], total_count: 0 } : profile }); };
|
||||
const listening = new ApiDataSource(mockBase) as unknown as { onStorage(e: { key: string | null; newValue: string | null }): void; auth: { signedIn(): boolean }; tokens: unknown };
|
||||
const courseWatch = (listening as unknown as ApiDataSource).watchCourses(() => {});
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
tabCalls = 0;
|
||||
listening.onStorage({ key: TOKEN_KEY, newValue: JSON.stringify(newTokens) });
|
||||
assert.deepEqual(listening.tokens, newTokens);
|
||||
assert.equal(tabCalls, 0, 'a routine rotation must not refetch the catalog');
|
||||
listening.onStorage({ key: TOKEN_KEY, newValue: null });
|
||||
assert.equal(listening.auth.signedIn(), false);
|
||||
courseWatch();
|
||||
|
||||
console.log('api checks: all passed');
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@
|
|||
// Screens never see the API's shapes: everything is mapped onto the domain types in ./index.
|
||||
import type {
|
||||
Campaign, Category, Course, DataSource, InboxItem, Issue, IssueStatus, IssueType, LessonProgress, Locale, Settings,
|
||||
Student, Unsub, UserStatus, Viewer, AuditEntry,
|
||||
Student, Unsub, UserStatus, Viewer, AuditEntry, DeviceSession, DeviceSummary,
|
||||
} from './index';
|
||||
|
||||
// ---------------------------------------------------------------- API shapes (the subset we read)
|
||||
|
|
@ -115,15 +115,26 @@ export function mapStudent(p: RawProfile, summary: RawSummary | null, issues: Ra
|
|||
|
||||
export class ApiError extends Error {
|
||||
readonly status: number; readonly code: string;
|
||||
constructor(status: number, message: string) {
|
||||
constructor(status: number, message: string, serverCode?: string) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
this.code = status === 0 ? 'network' : status === 401 ? 'unauthenticated' : status === 403 ? 'not_granted' : 'api_error';
|
||||
this.code = serverCode || (status === 0 ? 'network' : status === 401 ? 'unauthenticated' : status === 403 ? 'not_granted' : 'api_error');
|
||||
}
|
||||
}
|
||||
export class DeviceLimitError extends ApiError {
|
||||
readonly challengeToken: string; readonly expiresAt: string; readonly devices: DeviceSummary[];
|
||||
constructor(message: string, data: { challenge_token: string; expires_at: string; devices: DeviceSummary[] }) {
|
||||
super(409, message, 'DEVICE_LIMIT_REACHED');
|
||||
this.challengeToken = data.challenge_token;
|
||||
this.expiresAt = data.expires_at;
|
||||
this.devices = data.devices;
|
||||
}
|
||||
}
|
||||
const notConnected = (what: string) => Object.assign(new Error(`${what} isn't connected to the API yet.`), { code: 'not_granted' });
|
||||
|
||||
const TOKENS_KEY = 'lms.api.tokens';
|
||||
const DEVICE_KEY = 'lms.deviceId';
|
||||
const REFRESH_LOCK = 'lms.api.refresh';
|
||||
const REQUEST_TIMEOUT_MS = 12000;
|
||||
const REQUEST_RETRIES = 2;
|
||||
const PARALLEL = 3; // the catalog fans out one call per course/chapter; a smaller burst is gentler on the server
|
||||
|
|
@ -136,8 +147,30 @@ async function mapLimit<T, R>(items: T[], limit: number, fn: (x: T) => Promise<R
|
|||
}));
|
||||
return out;
|
||||
}
|
||||
const readTokens = (): Tokens | null => { try { return JSON.parse(localStorage.getItem(TOKENS_KEY) ?? 'null'); } catch { return null; } };
|
||||
const validTokens = (x: unknown): x is Tokens => !!x && typeof x === 'object'
|
||||
&& typeof (x as Tokens).access === 'string' && !!(x as Tokens).access
|
||||
&& typeof (x as Tokens).refresh === 'string' && !!(x as Tokens).refresh
|
||||
&& Number.isFinite((x as Tokens).userId);
|
||||
const parseTokens = (raw: string | null): Tokens | null => { try { const x = JSON.parse(raw ?? 'null'); return validTokens(x) ? x : null; } catch { return null; } };
|
||||
const readTokens = (): Tokens | null => { try { return parseTokens(localStorage.getItem(TOKENS_KEY)); } catch { return null; } };
|
||||
const writeTokens = (t: Tokens | null) => { try { t ? localStorage.setItem(TOKENS_KEY, JSON.stringify(t)) : localStorage.removeItem(TOKENS_KEY); } catch { /* storage blocked: session-only */ } };
|
||||
let memoryDeviceId: string | null = null;
|
||||
const randomDeviceId = () => {
|
||||
const c = globalThis.crypto;
|
||||
if (c?.randomUUID) return c.randomUUID();
|
||||
const bytes = new Uint8Array(16); c?.getRandomValues?.(bytes);
|
||||
bytes[6] = (bytes[6] & 0x0f) | 0x40; bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
||||
return [...bytes].map((b, i) => `${i === 4 || i === 6 || i === 8 || i === 10 ? '-' : ''}${b.toString(16).padStart(2, '0')}`).join('');
|
||||
};
|
||||
const deviceId = () => {
|
||||
if (memoryDeviceId) return memoryDeviceId;
|
||||
try {
|
||||
const saved = localStorage.getItem(DEVICE_KEY);
|
||||
if (saved) return (memoryDeviceId = saved);
|
||||
memoryDeviceId = randomDeviceId(); localStorage.setItem(DEVICE_KEY, memoryDeviceId); return memoryDeviceId;
|
||||
} catch { return (memoryDeviceId ??= randomDeviceId()); }
|
||||
};
|
||||
const samePair = (a: Tokens | null, b: Tokens | null) => !!a && !!b && a.access === b.access && a.refresh === b.refresh && a.userId === b.userId;
|
||||
|
||||
// ---------------------------------------------------------------- data source
|
||||
|
||||
|
|
@ -146,7 +179,10 @@ type Contact = { phone?: string; email?: string; password?: string };
|
|||
export class ApiDataSource implements DataSource {
|
||||
readonly kind = 'api' as const;
|
||||
private tokens: Tokens | null = readTokens();
|
||||
private refreshing: Promise<boolean> | null = null;
|
||||
private tokenVersion = 0;
|
||||
private refreshing: { version: number; promise: Promise<boolean> } | null = null;
|
||||
private revokedCbs = new Set<() => void>();
|
||||
private revokedNotified = false;
|
||||
private courseCbs = new Set<(c: Course[]) => void>();
|
||||
private studentCbs = new Map<(s: Student | null) => void, string>();
|
||||
private inboxCbs = new Set<(i: InboxItem[]) => void>();
|
||||
|
|
@ -154,7 +190,21 @@ export class ApiDataSource implements DataSource {
|
|||
private localProgress: Record<string, LessonProgress> = {};
|
||||
|
||||
readonly base: string;
|
||||
constructor(base: string) { this.base = base; }
|
||||
constructor(base: string) {
|
||||
this.base = base;
|
||||
if (typeof addEventListener === 'function') addEventListener('storage', this.onStorage);
|
||||
}
|
||||
|
||||
private onStorage = (event: StorageEvent) => {
|
||||
if (event.key !== TOKENS_KEY && event.key !== null) return; // null: storage was cleared
|
||||
const next = event.key === null ? null : parseTokens(event.newValue);
|
||||
if (samePair(next, this.tokens) || (!next && !this.tokens)) return;
|
||||
const sameUser = !!next && next.userId === this.tokens?.userId;
|
||||
this.setTokens(next, false);
|
||||
if (sameUser) return; // a routine rotation in another tab: nothing on screen changed
|
||||
this.localProgress = {};
|
||||
this.refreshAll();
|
||||
};
|
||||
|
||||
// ---- transport
|
||||
|
||||
|
|
@ -165,11 +215,19 @@ export class ApiDataSource implements DataSource {
|
|||
* so a learner can't get two texts or burn a code.
|
||||
*/
|
||||
private async request<T>(method: string, path: string, body?: unknown, auth = true, retry = method === 'GET'): Promise<T> {
|
||||
const attempt = () => fetch(`${this.base.replace(/\/+$/, '')}/api/v1${path}`, {
|
||||
method, headers: { 'content-type': 'application/json', ...(auth && this.tokens ? { authorization: `Bearer ${this.tokens.access}` } : {}) },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
});
|
||||
let sent: Tokens | null = null;
|
||||
const attempt = () => {
|
||||
sent = this.tokens;
|
||||
return fetch(`${this.base.replace(/\/+$/, '')}/api/v1${path}`, {
|
||||
method, headers: {
|
||||
'content-type': 'application/json',
|
||||
...(auth && sent ? { authorization: `Bearer ${sent.access}` } : {}),
|
||||
...(path === '/auth/customer-login' || path === '/user/verify-otp' ? { 'X-Device-Id': deviceId() } : {}),
|
||||
},
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
});
|
||||
};
|
||||
const send = async () => {
|
||||
for (let i = 0; ; i++) {
|
||||
try { return await attempt(); }
|
||||
|
|
@ -177,29 +235,115 @@ export class ApiDataSource implements DataSource {
|
|||
}
|
||||
};
|
||||
let res = await send();
|
||||
if (res.status === 401 && auth && this.tokens && (await this.refresh())) res = await send();
|
||||
const json = await res.json().catch(() => null);
|
||||
let json = await res.json().catch(() => null);
|
||||
if (res.status === 401 && auth && sent) {
|
||||
if (json?.code === 'SESSION_REVOKED') {
|
||||
if (this.adoptNewer(sent)) { res = await send(); json = await res.json().catch(() => null); }
|
||||
else this.endRevokedSession(sent);
|
||||
} else if (await this.refresh(sent)) {
|
||||
res = await send(); json = await res.json().catch(() => null);
|
||||
}
|
||||
}
|
||||
// Some endpoints answer `success: false` on a 200, so the HTTP status is what counts.
|
||||
if (!res.ok) throw new ApiError(res.status, json?.message || json?.error || res.statusText);
|
||||
if (!res.ok) {
|
||||
if (res.status === 409 && json?.code === 'DEVICE_LIMIT_REACHED' && json?.data?.challenge_token) {
|
||||
throw new DeviceLimitError(json.message || 'Device limit reached', json.data);
|
||||
}
|
||||
throw new ApiError(res.status, json?.message || json?.error || res.statusText, json?.code);
|
||||
}
|
||||
return (json && 'data' in json ? json.data : json) as T;
|
||||
}
|
||||
|
||||
private refresh(): Promise<boolean> {
|
||||
if (!this.tokens) return Promise.resolve(false);
|
||||
this.refreshing ??= fetch(`${this.base.replace(/\/+$/, '')}/api/v1/auth/refresh`, {
|
||||
method: 'POST', headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ access_token: this.tokens.access, refresh_token: this.tokens.refresh }),
|
||||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
}).then(async (r) => {
|
||||
const j = await r.json().catch(() => null);
|
||||
if (!r.ok || !j?.data?.access_token) { this.setTokens(null); return false; }
|
||||
this.setTokens({ access: j.data.access_token, refresh: j.data.refresh_token, userId: j.data.user_id });
|
||||
return true;
|
||||
}, () => false).finally(() => { this.refreshing = null; });
|
||||
return this.refreshing;
|
||||
private refresh(tokens: Tokens): Promise<boolean> {
|
||||
if (!samePair(this.tokens, tokens)) return Promise.resolve(this.adoptNewer(tokens));
|
||||
const version = this.tokenVersion;
|
||||
if (this.refreshing?.version === version) return this.refreshing.promise;
|
||||
const run = async () => {
|
||||
const locks = typeof navigator !== 'undefined' ? navigator.locks : undefined;
|
||||
if (locks?.request) return locks.request(REFRESH_LOCK, async () => {
|
||||
// Signed out or replaced while queued: never spend the old token.
|
||||
if (version !== this.tokenVersion) return this.adoptNewer(tokens);
|
||||
return this.adoptNewer(tokens) || this.performRefresh(tokens, version);
|
||||
});
|
||||
return this.performRefresh(tokens, version);
|
||||
};
|
||||
const promise = run().finally(() => { if (this.refreshing?.promise === promise) this.refreshing = null; });
|
||||
this.refreshing = { version, promise };
|
||||
return promise;
|
||||
}
|
||||
|
||||
private setTokens(t: Tokens | null) { this.tokens = t; writeTokens(t); }
|
||||
private async performRefresh(tokens: Tokens, version: number): Promise<boolean> {
|
||||
let r: Response;
|
||||
try {
|
||||
r = await fetch(`${this.base.replace(/\/+$/, '')}/api/v1/auth/refresh`, {
|
||||
method: 'POST', headers: { 'content-type': 'application/json', 'X-Device-Id': deviceId() },
|
||||
body: JSON.stringify({ access_token: tokens.access, refresh_token: tokens.refresh }),
|
||||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
});
|
||||
} catch { throw new ApiError(0, "Couldn't reach the server."); }
|
||||
const j = await r.json().catch(() => null);
|
||||
if (version !== this.tokenVersion || !samePair(this.tokens, tokens)) return this.adoptNewer(tokens);
|
||||
if (r.status === 401) {
|
||||
if (this.adoptNewer(tokens)) return true;
|
||||
if (j?.code === 'SESSION_REVOKED') this.endRevokedSession(tokens); else this.clearFailedTokens(tokens);
|
||||
return false;
|
||||
}
|
||||
if (!r.ok) throw new ApiError(r.status, j?.message || j?.error || r.statusText, j?.code);
|
||||
if (!j?.data?.access_token || !j.data.refresh_token) throw new ApiError(r.status, 'The server returned an invalid session.');
|
||||
this.setTokens({ access: j.data.access_token, refresh: j.data.refresh_token, userId: j.data.user_id ?? tokens.userId });
|
||||
return true;
|
||||
}
|
||||
|
||||
private adoptNewer(failed: Tokens): boolean {
|
||||
if (this.tokens && this.tokens.userId === failed.userId && !samePair(this.tokens, failed)) return true;
|
||||
const stored = readTokens();
|
||||
if (stored?.userId !== failed.userId || samePair(stored, failed)) return false;
|
||||
this.setTokens(stored, false);
|
||||
return true;
|
||||
}
|
||||
|
||||
private clearFailedTokens(failed: Tokens) {
|
||||
const stored = readTokens();
|
||||
if (samePair(stored, failed)) writeTokens(null);
|
||||
this.setTokens(null, false);
|
||||
}
|
||||
|
||||
private endRevokedSession(failed: Tokens) {
|
||||
if (this.revokedNotified && !this.tokens) return; // parallel calls failing together end the session once
|
||||
this.clearFailedTokens(failed);
|
||||
this.localProgress = {};
|
||||
this.refreshAll();
|
||||
if (!this.revokedNotified) { this.revokedNotified = true; this.revokedCbs.forEach((cb) => cb()); }
|
||||
}
|
||||
|
||||
private setTokens(t: Tokens | null, persist = true) {
|
||||
this.tokenVersion++; this.tokens = t;
|
||||
if (t) this.revokedNotified = false;
|
||||
if (persist) writeTokens(t);
|
||||
}
|
||||
|
||||
private logoutRequest(t: Tokens) {
|
||||
return fetch(`${this.base.replace(/\/+$/, '')}/api/v1/auth/logout`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json', authorization: `Bearer ${t.access}` },
|
||||
body: JSON.stringify({ refresh_token: t.refresh }),
|
||||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
});
|
||||
}
|
||||
|
||||
/** Refresh only for a final revoke attempt. These tokens are never installed into the signed-out client. */
|
||||
private async refreshForLogout(t: Tokens): Promise<Tokens | null> {
|
||||
try {
|
||||
const r = await fetch(`${this.base.replace(/\/+$/, '')}/api/v1/auth/refresh`, {
|
||||
method: 'POST', headers: { 'content-type': 'application/json', 'X-Device-Id': deviceId() },
|
||||
body: JSON.stringify({ access_token: t.access, refresh_token: t.refresh }),
|
||||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
});
|
||||
const j = await r.json().catch(() => null);
|
||||
if (!r.ok || !j?.data?.access_token || !j.data.refresh_token) return null;
|
||||
return { access: j.data.access_token, refresh: j.data.refresh_token, userId: j.data.user_id ?? t.userId };
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
// ---- auth (the screens reach this through `ds.auth` when it exists; the demo has none)
|
||||
|
||||
|
|
@ -229,12 +373,45 @@ export class ApiDataSource implements DataSource {
|
|||
this.setTokens({ access: t.access_token, refresh: t.refresh_token, userId: t.user_id });
|
||||
this.refreshAll();
|
||||
},
|
||||
replaceDevice: async (challengeToken: string, sessionId: string): Promise<void> => {
|
||||
let r: Response;
|
||||
try {
|
||||
r = await fetch(`${this.base.replace(/\/+$/, '')}/api/v1/auth/sessions/replace`, {
|
||||
method: 'POST', headers: { 'content-type': 'application/json', 'X-Device-Id': deviceId() },
|
||||
body: JSON.stringify({ challenge_token: challengeToken, session_id: sessionId }),
|
||||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
});
|
||||
} catch { throw new ApiError(0, "Couldn't reach the server."); } // the picker stays open so the learner can retry
|
||||
const j = await r.json().catch(() => null);
|
||||
if (!r.ok) throw new ApiError(r.status, j?.message || r.statusText, j?.code);
|
||||
if (!j?.data?.access_token || !j.data.refresh_token) throw new ApiError(502, 'The server returned an invalid session.');
|
||||
this.setTokens({ access: j.data.access_token, refresh: j.data.refresh_token, userId: j.data.user_id });
|
||||
this.refreshAll();
|
||||
},
|
||||
listDevices: async (): Promise<DeviceSession[]> => {
|
||||
const r = await this.request<DeviceSession[] | { sessions: DeviceSession[] }>('GET', '/user/me/sessions');
|
||||
return Array.isArray(r) ? r : r.sessions ?? [];
|
||||
},
|
||||
removeDevice: async (id: string): Promise<void> => {
|
||||
await this.request('DELETE', `/user/me/sessions/${encodeURIComponent(id)}`, undefined, true, false);
|
||||
},
|
||||
onSessionRevoked: (cb: () => void): Unsub => { this.revokedCbs.add(cb); return () => this.revokedCbs.delete(cb); },
|
||||
signOut: async () => {
|
||||
const t = this.tokens;
|
||||
// Invalidate every refresh already in flight before doing any network work.
|
||||
this.setTokens(null);
|
||||
if (t) await this.request('POST', '/auth/logout', { refresh_token: t.refresh }, false).catch(() => { /* already gone server-side */ });
|
||||
this.localProgress = {};
|
||||
this.refreshAll();
|
||||
try {
|
||||
if (t) {
|
||||
const first = await this.logoutRequest(t);
|
||||
if (first.status === 401) {
|
||||
const fresh = await this.refreshForLogout(t);
|
||||
if (fresh) await this.logoutRequest(fresh);
|
||||
}
|
||||
}
|
||||
} catch { /* local sign-out still wins on timeout, network failure, or API failure */ }
|
||||
// Tokens were cleared above; clearing again here would erase a sign-in made while logout was pending.
|
||||
finally { this.refreshAll(); }
|
||||
},
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -107,6 +107,14 @@ export interface AuditEntry { id: string; adminId: string; action: string; entit
|
|||
|
||||
export interface Viewer { id: string | null; name: string; avatarUrl: string; isOwner: boolean; canEdit: boolean }
|
||||
|
||||
export interface DeviceSummary {
|
||||
id: string; label: string; platform: string; last_seen_at: string;
|
||||
}
|
||||
|
||||
export interface DeviceSession extends DeviceSummary {
|
||||
created_at: string; expires_at: string; is_current: boolean;
|
||||
}
|
||||
|
||||
export type Unsub = () => void;
|
||||
|
||||
/** Real sign-in, present only on data sources backed by an account system (the API); the demo simulates it. */
|
||||
|
|
@ -115,6 +123,10 @@ export interface AuthApi {
|
|||
/** Starts sign-in or sign-up for a phone, or an email with password: 'code' means a one-time code was sent. */
|
||||
start(c: { phone?: string; email?: string; password?: string }): Promise<'code' | 'done'>;
|
||||
verify(c: { phone?: string; email?: string; password?: string }, code: string): Promise<void>;
|
||||
replaceDevice(challengeToken: string, sessionId: string): Promise<void>;
|
||||
listDevices(): Promise<DeviceSession[]>;
|
||||
removeDevice(id: string): Promise<void>;
|
||||
onSessionRevoked(cb: () => void): Unsub;
|
||||
signOut(): Promise<void>;
|
||||
}
|
||||
|
||||
|
|
@ -238,4 +250,4 @@ export class ClaudeDbDataSource implements DataSource {
|
|||
|
||||
export const newId = (prefix = '') => prefix + Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
|
||||
|
||||
export { ApiDataSource, ApiError } from './api';
|
||||
export { ApiDataSource, ApiError, DeviceLimitError } from './api';
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import type { Course, Student } from '@lms/data';
|
||||
import { applyHeartbeat, DomainError, gradeAssessment, applyPaymentEvent, createOrder, dashboardMetrics, effectiveStatus, isStudentVisible, lessonAccess, publishProblems, validateLocation, validPassword } from './domain.ts';
|
||||
import { decodeLearnerCode, encodeLearnerCode } from './learnerCode.ts';
|
||||
|
||||
const lesson = (id: string, extra = {}) => ({ id, sortOrder: Number(id.slice(-1)), isPreview: false, isPublished: true, durationSec: 100, videoStatus: 'READY' as const, translations: { en: { title: id } }, ...extra });
|
||||
const course = (id: string, extra: Partial<Course> = {}): Course => ({
|
||||
|
|
@ -88,4 +89,13 @@ assert.deepEqual([g2.score, g2.bestPct, g2.passed, g2.attempts], [1, 100, true,
|
|||
assert.equal(gradeAssessment(A, quiz, [1, 1, 1], undefined, now).passed, false);
|
||||
assert.throws(() => gradeAssessment(A, quiz, [0, 1], undefined, now), DomainError);
|
||||
|
||||
// Traceable player watermark: numeric learner ids round-trip without ambiguous characters.
|
||||
for (const id of [0, 1, 31, 32, 9_847_231, Number.MAX_SAFE_INTEGER]) {
|
||||
const code = encodeLearnerCode(id);
|
||||
assert.match(code, /^RZ-[2-9A-HJ-NP-Z]+$/);
|
||||
assert.equal(decodeLearnerCode(code), id);
|
||||
}
|
||||
assert.equal(decodeLearnerCode('RZ-O01I'), null);
|
||||
assert.throws(() => encodeLearnerCode(-1), RangeError);
|
||||
|
||||
console.log('domain checks: all passed');
|
||||
|
|
|
|||
29
packages/features/src/learnerCode.ts
Normal file
29
packages/features/src/learnerCode.ts
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
// A compact support identifier, not a secret. The alphabet omits 0/O and 1/I.
|
||||
const ALPHABET = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
|
||||
const PREFIX = 'RZ-';
|
||||
|
||||
export function encodeLearnerCode(id: number): string {
|
||||
if (!Number.isSafeInteger(id) || id < 0) throw new RangeError('Learner id must be a non-negative safe integer');
|
||||
let n = id;
|
||||
let body = '';
|
||||
do {
|
||||
body = ALPHABET[n % ALPHABET.length] + body;
|
||||
n = Math.floor(n / ALPHABET.length);
|
||||
} while (n > 0);
|
||||
return PREFIX + body.padStart(4, ALPHABET[0]);
|
||||
}
|
||||
|
||||
export function decodeLearnerCode(code: string): number | null {
|
||||
const value = code.trim().toUpperCase();
|
||||
if (!value.startsWith(PREFIX)) return null;
|
||||
const body = value.slice(PREFIX.length);
|
||||
if (!body) return null;
|
||||
let id = 0;
|
||||
for (const char of body) {
|
||||
const digit = ALPHABET.indexOf(char);
|
||||
if (digit < 0) return null;
|
||||
id = id * ALPHABET.length + digit;
|
||||
if (!Number.isSafeInteger(id)) return null;
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
|
@ -112,6 +112,27 @@ export function AppProvider({ ds, children }: { ds: DataSource; children: ReactN
|
|||
toastTimer.current = setTimeout(() => setToastMsg(null), 3200);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!ds.auth) return;
|
||||
return ds.auth.onSessionRevoked(() => {
|
||||
store.set('signedOut', '1');
|
||||
setSignedOut(true);
|
||||
setViewer({ id: null, name: '', avatarUrl: '', isOwner: false, canEdit: false });
|
||||
toast(lookup(locale, 'auth.sessionRevoked'));
|
||||
});
|
||||
}, [ds, locale, toast]);
|
||||
|
||||
// Signing in or out in another tab updates this one too.
|
||||
useEffect(() => {
|
||||
const sync = (e: StorageEvent) => {
|
||||
if (e.key !== 'lms.signedOut') return;
|
||||
setSignedOut(e.newValue === '1');
|
||||
ds.viewer().then(setViewer, () => {});
|
||||
};
|
||||
addEventListener('storage', sync);
|
||||
return () => removeEventListener('storage', sync);
|
||||
}, [ds]);
|
||||
|
||||
const msg = useCallback((loc: Locale, key: string, vars?: Record<string, string | number>) => lookup(loc, key, vars), []);
|
||||
|
||||
const write = useCallback((fn: () => Promise<void>, okMsg?: string) => {
|
||||
|
|
|
|||
|
|
@ -1,16 +1,17 @@
|
|||
'use client';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import type { Assessment, AssessmentResult, Course, Issue, IssueType, Lesson, Locale, Order, Student } from '@lms/data';
|
||||
import { LOCALES, newId } from '@lms/data';
|
||||
import type { Assessment, AssessmentResult, Course, DeviceSession, DeviceSummary, Issue, IssueType, Lesson, Locale, Order, Student } from '@lms/data';
|
||||
import { DeviceLimitError, LOCALES, newId } from '@lms/data';
|
||||
import { LOCALE_NAMES, DRAFT_LOCALES } from '@lms/i18n';
|
||||
import { lookup, useApp } from './store';
|
||||
import {
|
||||
applyHeartbeat, applyPaymentEvent, clock, COUNTRIES, courseDuration, courseProgress, createOrder, DomainError, effectiveStatus,
|
||||
ET_CITIES, formatDuration, formatMoney, gradeAssessment, isCompleted, isStudentVisible, lessonAccess, owns, publishedLessons, resumePoint, tr, validateLocation, validPassword,
|
||||
} from './domain';
|
||||
import { CAT_PHOTOS, CopyText, Cover, coursePhoto, Empty, FeedbackButton, fmtDate, Icon, KitIcon, Logo, Modal, VIMEO_ORIGIN, VIMEO_PLACEHOLDER, Ring, Skeleton, StatusPill } from './ui';
|
||||
import { CAT_PHOTOS, CopyText, Cover, coursePhoto, Empty, FeedbackButton, fmtDate, fmtDateTime, Icon, KitIcon, Logo, Modal, VIMEO_ORIGIN, VIMEO_PLACEHOLDER, Ring, Skeleton, StatusPill } from './ui';
|
||||
import { PAY_LOGOS } from './payLogos';
|
||||
import { encodeLearnerCode } from './learnerCode';
|
||||
|
||||
const ISSUE_TYPES: IssueType[] = ['BUG', 'PAYMENT', 'VIDEO', 'ACCOUNT', 'CONTENT', 'OTHER'];
|
||||
// Demo checkout lists every method we plan to accept; all of them run through the same simulated ETB order.
|
||||
|
|
@ -955,7 +956,7 @@ export function vimeoPlayerUrl(url: string): string | null {
|
|||
|
||||
function VideoPanel({ c, lesson, next, head }: { c: Course; lesson: Lesson; next?: Lesson; head?: ReactNode }) {
|
||||
const t = useTranslations();
|
||||
const { me, locale, nav, ds, write, signedIn, viewer } = useApp();
|
||||
const { me, locale, nav, ds, write, signedIn } = useApp();
|
||||
// A Vimeo link (what the API's lessons carry) plays in Vimeo's player; no video yet plays the sample clip.
|
||||
const placeholder = !lesson.videoAssetId;
|
||||
const vimeoSrc = placeholder ? VIMEO_PLACEHOLDER : vimeoPlayerUrl(lesson.videoAssetId!);
|
||||
|
|
@ -963,7 +964,9 @@ function VideoPanel({ c, lesson, next, head }: { c: Course; lesson: Lesson; next
|
|||
const [vdur, setVdur] = useState(0);
|
||||
const dur = (vimeo && vdur) || lesson.durationSec || 1;
|
||||
const saved = me?.progress?.[lesson.id];
|
||||
const [pos, setPos] = useState(() => (saved && !saved.completedAt ? Math.min(saved.positionSec, dur - 5) : 0));
|
||||
const [pos, setPos] = useState(() => (saved && !saved.completedAt
|
||||
? Math.max(0, lesson.durationSec ? Math.min(saved.positionSec, lesson.durationSec - 5) : saved.positionSec)
|
||||
: 0));
|
||||
const [playing, setPlaying] = useState(false);
|
||||
const [rate, setRate] = useState(1);
|
||||
const conn = typeof navigator !== 'undefined' ? (navigator as any).connection : undefined;
|
||||
|
|
@ -973,6 +976,8 @@ function VideoPanel({ c, lesson, next, head }: { c: Course; lesson: Lesson; next
|
|||
// L4: when a lesson ends, "up next" appears over the video and plays it after a short count the student can cancel
|
||||
const [ended, setEnded] = useState(false);
|
||||
const [auto, setAuto] = useState<number | null>(null);
|
||||
const [fillViewport, setFillViewport] = useState(false);
|
||||
const [nativeFullscreen, setNativeFullscreen] = useState(false);
|
||||
const videoRef = useRef<HTMLVideoElement>(null);
|
||||
const frameRef = useRef<HTMLIFrameElement>(null);
|
||||
const screenRef = useRef<HTMLDivElement>(null);
|
||||
|
|
@ -1023,6 +1028,26 @@ function VideoPanel({ c, lesson, next, head }: { c: Course; lesson: Lesson; next
|
|||
}, [heartbeat]);
|
||||
useEffect(() => { const v = videoRef.current; if (v) v.playbackRate = rate; }, [rate]);
|
||||
useEffect(() => { if (vimeo && rate !== 1) vcall('setPlaybackRate', rate); }, [rate]);
|
||||
useEffect(() => {
|
||||
const changed = () => setNativeFullscreen(document.fullscreenElement === screenRef.current);
|
||||
document.addEventListener('fullscreenchange', changed);
|
||||
return () => document.removeEventListener('fullscreenchange', changed);
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
if (!fillViewport) return;
|
||||
const root = document.documentElement;
|
||||
const body = document.body;
|
||||
const scrollY = window.scrollY;
|
||||
const before = { rootOverflow: root.style.overflow, bodyOverflow: body.style.overflow, position: body.style.position, top: body.style.top, width: body.style.width };
|
||||
root.style.overflow = 'hidden'; body.style.overflow = 'hidden'; body.style.position = 'fixed'; body.style.top = `-${scrollY}px`; body.style.width = '100%';
|
||||
const escape = (e: KeyboardEvent) => { if (e.key === 'Escape') setFillViewport(false); };
|
||||
addEventListener('keydown', escape, true);
|
||||
return () => {
|
||||
removeEventListener('keydown', escape, true);
|
||||
root.style.overflow = before.rootOverflow; body.style.overflow = before.bodyOverflow; body.style.position = before.position; body.style.top = before.top; body.style.width = before.width;
|
||||
window.scrollTo(0, scrollY);
|
||||
};
|
||||
}, [fillViewport]);
|
||||
const goNext = () => { if (next) nav(`/${locale}/learn/${c.slug}/${next.id}`); };
|
||||
useEffect(() => { if (ended && next) setAuto(AUTO_NEXT_SEC); }, [ended, next]);
|
||||
useEffect(() => {
|
||||
|
|
@ -1038,26 +1063,39 @@ function VideoPanel({ c, lesson, next, head }: { c: Course; lesson: Lesson; next
|
|||
vcall(playing ? 'pause' : 'play');
|
||||
};
|
||||
const seek = (to: number) => { const n = Math.max(0, Math.min(dur, to)); setPos(n); if (videoRef.current) videoRef.current.currentTime = n; else vcall('setCurrentTime', n); };
|
||||
const full = () => { screenRef.current?.requestFullscreen?.().catch(() => { /* not allowed in this frame */ }); };
|
||||
const onKey = (e: React.KeyboardEvent) => {
|
||||
if ((e.target as HTMLElement).tagName === 'SELECT' || (e.target as HTMLElement).tagName === 'INPUT') return;
|
||||
if (e.key === 'Escape' && auto != null) { setAuto(null); return; }
|
||||
if (e.key === ' ') { e.preventDefault(); toggle(); } else if (e.key === 'ArrowLeft') seek(pos - 10); else if (e.key === 'ArrowRight') seek(pos + 10); else if (e.key === 'f') full(); else if (e.key === 'm' && videoRef.current) videoRef.current.muted = !videoRef.current.muted;
|
||||
const full = () => {
|
||||
const screen = screenRef.current;
|
||||
if (!screen) return;
|
||||
if (fillViewport) { setFillViewport(false); return; }
|
||||
if (document.fullscreenElement === screen) { document.exitFullscreen().catch(() => {}); return; }
|
||||
if (!screen.requestFullscreen) { setFillViewport(true); return; }
|
||||
screen.requestFullscreen().catch(() => setFillViewport(true));
|
||||
};
|
||||
const mark = (me?.phone || me?.email || viewer?.name || 'student').replace(/^(.{3}).*(.{2})$/, '$1•••$2');
|
||||
const onKey = (e: React.KeyboardEvent) => {
|
||||
const el = e.target as HTMLElement;
|
||||
if (el.tagName === 'SELECT' || el.tagName === 'INPUT' || (el.tagName === 'BUTTON' && (e.key === ' ' || e.key === 'Enter'))) return;
|
||||
if (e.key === 'Escape' && auto != null) { setAuto(null); return; }
|
||||
if (e.key === ' ') { e.preventDefault(); toggle(); } else if (e.key === 'ArrowLeft') seek(pos - 10); else if (e.key === 'ArrowRight') seek(pos + 10); else if (e.key.toLowerCase() === 'f') full(); else if (e.key.toLowerCase() === 'm' && videoRef.current) videoRef.current.muted = !videoRef.current.muted;
|
||||
};
|
||||
const numericLearnerId = me && /^(0|[1-9]\d*)$/.test(me.id) ? Number(me.id) : NaN;
|
||||
const mark = signedIn && Number.isSafeInteger(numericLearnerId) ? encodeLearnerCode(numericLearnerId) : null;
|
||||
const isFullscreen = fillViewport || nativeFullscreen;
|
||||
const done = isCompleted(me, lesson.id) || justDone;
|
||||
const pct = courseProgress(c, me).pct;
|
||||
return (
|
||||
<div className="stack">
|
||||
<div className="screen" ref={screenRef} tabIndex={0} onKeyDown={onKey} aria-label={lessonTitle(lesson, locale)}>
|
||||
{lesson.videoAssetId ? (
|
||||
<video ref={videoRef} src={ds.assetUrl(lesson.videoAssetId)} playsInline preload="metadata"
|
||||
<div className={`screen${fillViewport ? ' is-fill-viewport' : ''}`} ref={screenRef} tabIndex={0} onKeyDown={onKey} aria-label={lessonTitle(lesson, locale)}>
|
||||
{vimeoSrc ? (
|
||||
<iframe ref={frameRef} src={vimeoSrc} onLoad={vlisten} title={lessonTitle(lesson, locale)} allow="autoplay; picture-in-picture" />
|
||||
) : (
|
||||
<video ref={videoRef} src={ds.assetUrl(lesson.videoAssetId!)} playsInline preload="metadata"
|
||||
onLoadedMetadata={(e) => { if (pos) e.currentTarget.currentTime = pos; }}
|
||||
onTimeUpdate={(e) => setPos(e.currentTarget.currentTime)} onPlay={() => { setPlaying(true); setEnded(false); setAuto(null); }} onPause={() => setPlaying(false)} onEnded={() => { setPlaying(false); setEnded(true); }} />
|
||||
) : (
|
||||
<iframe ref={frameRef} src={vimeoSrc!} onLoad={vlisten} title={lessonTitle(lesson, locale)} allow="autoplay; fullscreen; picture-in-picture" allowFullScreen />
|
||||
)}
|
||||
{canSave && <span className="wm" aria-hidden>{mark}</span>}
|
||||
{mark && <span className="wm" aria-hidden>{mark}</span>}
|
||||
<button className="p-full" onClick={full} aria-label={t(isFullscreen ? 'player.exitFullscreen' : 'player.fullscreen')}>
|
||||
<Icon name={isFullscreen ? 'x' : 'expand'} size={20} />
|
||||
</button>
|
||||
{auto != null && next && <div className="p-upnext" role="status">
|
||||
<span className="p-upnext-k">{t('player.upNext')}</span>
|
||||
<strong>{lessonNumber(c, next.id)}. {lessonTitle(next, locale)}</strong>
|
||||
|
|
@ -1082,7 +1120,6 @@ function VideoPanel({ c, lesson, next, head }: { c: Course; lesson: Lesson; next
|
|||
<option value="auto">Auto{saver ? ' (≤360p)' : ''}</option>{['240p', '360p', '480p', '720p'].map((q) => <option key={q} value={q} disabled={saver && (q === '480p' || q === '720p')}>{q}</option>)}
|
||||
</select>
|
||||
<button aria-pressed={saver} onClick={() => { setSaver((s) => !s); if (!saver && (quality === '480p' || quality === '720p')) setQuality('360p'); }}>{t('player.dataSaver')}: {saver ? 'on' : 'off'}</button>
|
||||
<button onClick={full} aria-label={t('player.fullscreen')}><Icon name="expand" size={16} /></button>
|
||||
</div>
|
||||
</div>}
|
||||
</div>
|
||||
|
|
@ -1398,13 +1435,18 @@ function SignIn() {
|
|||
const [dial, setDial] = useState(() => { const r = (typeof navigator !== 'undefined' ? navigator.language : '').split('-')[1]?.toUpperCase(); return r && DIALS[r] ? r : 'ET'; });
|
||||
const [email, setEmail] = useState('');
|
||||
const [pw, setPw] = useState('');
|
||||
const [step, setStep] = useState<'start' | 'code' | 'setup'>('start');
|
||||
const [step, setStep] = useState<'start' | 'code' | 'devices' | 'setup'>('start');
|
||||
const [code, setCode] = useState('');
|
||||
const [entered, setEntered] = useState('');
|
||||
const [tries, setTries] = useState(5);
|
||||
const [wait, setWait] = useState(0);
|
||||
const [err, setErr] = useState('');
|
||||
const [challenge, setChallenge] = useState<{ token: string; devices: DeviceSummary[] } | null>(null);
|
||||
const [removeId, setRemoveId] = useState('');
|
||||
const stepHeading = useRef<HTMLHeadingElement>(null);
|
||||
useEffect(() => { if (wait <= 0) return; const id = setTimeout(() => setWait((w) => w - 1), 1000); return () => clearTimeout(id); }, [wait]);
|
||||
const firstStep = useRef(true);
|
||||
useEffect(() => { if (firstStep.current) { firstStep.current = false; return; } stepHeading.current?.focus(); }, [step]);
|
||||
if (!ready) return <Skeleton h={200} />;
|
||||
const local = phone.replace(/\D/g, '').replace(/^0/, '');
|
||||
const e164 = `+${DIALS[dial]}${local}`;
|
||||
|
|
@ -1420,6 +1462,12 @@ function SignIn() {
|
|||
const contact = () => (mode === 'phone' ? { phone: e164 } : { email, password: pw });
|
||||
// The server's own message when it gave one; a plain "couldn't reach the server" when it never answered.
|
||||
const apiErr = (e: unknown) => ((e as { code?: string })?.code === 'network' ? t('auth.networkError') : (e as Error)?.message || t('auth.networkError'));
|
||||
const deviceLimit = (e: unknown) => {
|
||||
if (!(e instanceof DeviceLimitError)) return false;
|
||||
setChallenge({ token: e.challengeToken, devices: e.devices });
|
||||
setRemoveId(''); setErr(''); setStep('devices');
|
||||
return true;
|
||||
};
|
||||
// After a real sign-in: a learner without a name yet goes to profile setup, everyone else home.
|
||||
const finish = async () => {
|
||||
await reloadViewer(); signIn();
|
||||
|
|
@ -1431,7 +1479,7 @@ function SignIn() {
|
|||
try {
|
||||
const next = await auth!.start(contact());
|
||||
if (next === 'done') await finish(); else { setEntered(''); setWait(60); setStep('code'); }
|
||||
} catch (e) { setErr(apiErr(e)); }
|
||||
} catch (e) { if (!deviceLimit(e)) setErr(apiErr(e)); }
|
||||
setBusy(false);
|
||||
};
|
||||
const verify = async (e: React.FormEvent) => {
|
||||
|
|
@ -1439,7 +1487,7 @@ function SignIn() {
|
|||
if (auth) {
|
||||
setBusy(true);
|
||||
try { await auth.verify(contact(), entered); await finish(); }
|
||||
catch (x) { setErr(apiErr(x)); }
|
||||
catch (x) { if (!deviceLimit(x)) setErr(apiErr(x)); }
|
||||
setBusy(false);
|
||||
return;
|
||||
}
|
||||
|
|
@ -1447,6 +1495,19 @@ function SignIn() {
|
|||
if (entered !== code) { const left = tries - 1; setTries(left); setErr(left ? t('auth.wrongCode', { n: left }) : t('auth.locked')); return; }
|
||||
if (me && !me.deletedAt) { signIn(); nav(`/${locale}`); } else setStep('setup');
|
||||
};
|
||||
const replaceDevice = async (e: React.FormEvent) => {
|
||||
e.preventDefault(); setErr('');
|
||||
if (!removeId) { setErr(t('auth.chooseDevice')); return; }
|
||||
if (!challenge || busy) return;
|
||||
setBusy(true);
|
||||
try { await auth!.replaceDevice(challenge.token, removeId); setChallenge(null); await finish(); }
|
||||
catch (x) {
|
||||
if ((x as { status?: number })?.status === 401) {
|
||||
setChallenge(null); setRemoveId(''); setStep('start'); setErr(t('auth.replaceExpired'));
|
||||
} else setErr(apiErr(x));
|
||||
}
|
||||
setBusy(false);
|
||||
};
|
||||
if (step === 'setup') return <ProfileSetup phone={mode === 'phone' ? e164 : undefined} email={mode === 'email' ? email : undefined} />;
|
||||
return (
|
||||
<section className="auth">
|
||||
|
|
@ -1459,7 +1520,7 @@ function SignIn() {
|
|||
</div>
|
||||
<div className="auth-main">
|
||||
{!auth && !viewer?.id ? <Empty>{t('auth.noIdentity')}</Empty> : step === 'start' ? <form className="stack" onSubmit={(e) => { e.preventDefault(); send(); }}>
|
||||
<div className="stack-sm"><h1>{t('auth.welcome')}</h1><p className="muted">{t('auth.welcomeLead')}</p></div>
|
||||
<div className="stack-sm"><h1 ref={stepHeading} tabIndex={-1}>{t('auth.welcome')}</h1><p className="muted">{t('auth.welcomeLead')}</p></div>
|
||||
{me && !me.deletedAt && <button type="button" className="btn btn-accent btn-block btn-lg" onClick={() => { signIn(); nav(`/${locale}`); }}>{t('auth.continueAs', { name: me.name.split(' ')[0] })}</button>}
|
||||
{/* Google / Apple need the providers' own sign-in SDKs before they can run against the API */}
|
||||
{!auth && <><SocialLogins onPick={() => { if (me && !me.deletedAt) { signIn(); nav(`/${locale}`); } else setStep('setup'); }} />
|
||||
|
|
@ -1476,8 +1537,8 @@ function SignIn() {
|
|||
{err && <p className="err" role="alert">{err}</p>}
|
||||
<button className="btn btn-block" disabled={busy}>{t('auth.sendCode')}</button>
|
||||
<button type="button" className="link" onClick={() => { setMode(mode === 'phone' ? 'email' : 'phone'); setErr(''); }}>{mode === 'phone' ? t('auth.useEmail') : t('auth.usePhone')}</button>
|
||||
</form> : <form className="stack" onSubmit={verify}>
|
||||
<h1>{t('auth.codeTitle')}</h1>
|
||||
</form> : step === 'code' ? <form className="stack" onSubmit={verify}>
|
||||
<h1 ref={stepHeading} tabIndex={-1}>{t('auth.codeTitle')}</h1>
|
||||
<p>{t('auth.codeSent', { target })}</p>
|
||||
{!auth && <p className="banner"><strong>{t('auth.demoCode', { code })}</strong></p>}
|
||||
<label className="field"><span className="sr-only">{t('auth.codeTitle')}</span><input id="otp" className="input otp" inputMode="numeric" autoComplete="one-time-code" maxLength={6} value={entered} onChange={(e) => setEntered(e.target.value.replace(/\D/g, ''))} /></label>
|
||||
|
|
@ -1485,6 +1546,21 @@ function SignIn() {
|
|||
<button className="btn btn-accent btn-block" disabled={busy || entered.length < 4 || (!auth && (entered.length !== 6 || tries <= 0))}>{t('auth.verify')}</button>
|
||||
<button type="button" className="btn btn-ghost btn-block" disabled={wait > 0} onClick={send}>{wait > 0 ? t('auth.resendIn', { s: wait }) : t('auth.resend')}</button>
|
||||
<button type="button" className="link" onClick={() => setStep('start')}>{t('common.back')}</button>
|
||||
</form> : <form className="stack device-picker" onSubmit={replaceDevice}>
|
||||
<div className="stack-sm">
|
||||
<h1 ref={stepHeading} tabIndex={-1}>{t('auth.deviceLimitTitle', { n: challenge?.devices.length ?? 0 })}</h1>
|
||||
<p className="muted">{t('auth.deviceLimitLead')}</p>
|
||||
</div>
|
||||
<fieldset className="device-options">
|
||||
<legend className="sr-only">{t('auth.deviceLegend')}</legend>
|
||||
{challenge?.devices.map((device) => <label className="device-option" key={device.id}>
|
||||
<input type="radio" name="remove-device" value={device.id} checked={removeId === device.id} onChange={() => { setRemoveId(device.id); setErr(''); }} />
|
||||
<span className="device-copy"><strong>{device.label}</strong><span>{t('auth.lastActive', { date: fmtDateTime(device.last_seen_at) })}</span></span>
|
||||
</label>)}
|
||||
</fieldset>
|
||||
{err && <p className="err" role="alert">{err}</p>}
|
||||
<button className="btn btn-accent btn-block" disabled={busy}>{t('auth.removeContinue')}</button>
|
||||
<button type="button" className="btn btn-ghost btn-block" disabled={busy} onClick={() => { setChallenge(null); setRemoveId(''); setErr(''); setStep('start'); }}>{t('common.cancel')}</button>
|
||||
</form>}
|
||||
</div>
|
||||
</section>
|
||||
|
|
@ -1562,6 +1638,64 @@ function ProfileSetup({ phone, email }: { phone?: string; email?: string }) {
|
|||
|
||||
const NOTIF_TYPES = ['PAYMENT', 'NEW_LESSON', 'ISSUE', 'ANNOUNCEMENT'] as const;
|
||||
|
||||
function ProfileDevices() {
|
||||
const t = useTranslations();
|
||||
const { ds, signOut, nav, locale, toast, settings } = useApp();
|
||||
const auth = ds.auth!;
|
||||
const [devices, setDevices] = useState<DeviceSession[] | null>(null);
|
||||
const [failed, setFailed] = useState(false);
|
||||
const [confirming, setConfirming] = useState<DeviceSession | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [err, setErr] = useState('');
|
||||
const load = useCallback(async () => {
|
||||
setFailed(false);
|
||||
try { setDevices(await auth.listDevices()); } catch { setFailed(true); }
|
||||
}, [auth]);
|
||||
useEffect(() => { load(); }, [load]);
|
||||
const close = useCallback(() => { if (!busy) { setConfirming(null); setErr(''); } }, [busy]);
|
||||
const remove = async () => {
|
||||
if (!confirming || busy) return;
|
||||
const target = confirming;
|
||||
setBusy(true); setErr('');
|
||||
try { await auth.removeDevice(target.id); }
|
||||
catch (e) {
|
||||
// Already gone (removed elsewhere or expired) is the outcome the learner wanted.
|
||||
if ((e as { status?: number })?.status !== 404) { setErr(t('profile.deviceRemoveFailed')); setBusy(false); return; }
|
||||
}
|
||||
setDevices((list) => list?.filter((d) => d.id !== target.id) ?? null);
|
||||
setConfirming(null); setBusy(false);
|
||||
toast(t('profile.deviceRemoved'));
|
||||
load();
|
||||
};
|
||||
if (!devices) return failed
|
||||
? <div className="stack-sm"><p className="err" role="alert">{t('profile.devicesFailed')}</p><button className="btn btn-ghost btn-sm" onClick={load}>{t('profile.devicesRetry')}</button></div>
|
||||
: <Skeleton h={56} />;
|
||||
const ordered = [...devices].sort((a, b) => Number(b.is_current) - Number(a.is_current));
|
||||
return <>
|
||||
<p className="small muted">{t('profile.deviceLimit', { n: settings.sessionLimit })}</p>
|
||||
<ul className="device-list">{ordered.map((d) => <li className="device-row" key={d.id}>
|
||||
<span className="device-copy">
|
||||
<strong>{d.label}</strong>
|
||||
<span>{d.is_current ? `${t('profile.currentDevice')} · ` : ''}{t('auth.lastActive', { date: fmtDateTime(d.last_seen_at) })}</span>
|
||||
</span>
|
||||
{d.is_current
|
||||
? <button className="btn btn-ghost btn-sm" onClick={() => { signOut(); nav(`/${locale}`); }}>{t('profile.signOutSession')}</button>
|
||||
: <button className="btn btn-ghost btn-sm" aria-label={`${t('profile.deviceRemove')}: ${d.label}`} onClick={() => { setErr(''); setConfirming(d); }}>{t('profile.deviceRemove')}</button>}
|
||||
</li>)}</ul>
|
||||
{failed && <p className="err" role="alert">{t('profile.devicesFailed')}</p>}
|
||||
{confirming && <Modal title={t('profile.deviceRemoveTitle')} onClose={close}>
|
||||
<div className="stack">
|
||||
<p>{t('profile.deviceRemoveBody', { device: confirming.label })}</p>
|
||||
{err && <p className="err" role="alert">{err}</p>}
|
||||
<div className="device-actions">
|
||||
<button className="btn btn-ghost" disabled={busy} onClick={close}>{t('common.cancel')}</button>
|
||||
<button className="btn btn-accent" disabled={busy} onClick={remove}>{t('profile.deviceRemove')}</button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>}
|
||||
</>;
|
||||
}
|
||||
|
||||
function Profile() {
|
||||
const t = useTranslations();
|
||||
const { me, ds, write, courses, categories, locale, setLocale, signOut, nav } = useApp();
|
||||
|
|
@ -1651,7 +1785,7 @@ function Profile() {
|
|||
</div>
|
||||
<div className="card stack-sm">
|
||||
<h2 style={{ fontSize: 'var(--fs-lg)' }}>{t('profile.sessions')}</h2>
|
||||
<div className="row-between"><span><Icon name="shield" size={16} /> {t('profile.thisDevice')}</span><button className="btn btn-ghost btn-sm" onClick={() => { signOut(); nav(`/${locale}`); }}>{t('profile.signOutSession')}</button></div>
|
||||
{ds.auth ? <ProfileDevices /> : <div className="row-between"><span><Icon name="shield" size={16} /> {t('profile.thisDevice')}</span><button className="btn btn-ghost btn-sm" onClick={() => { signOut(); nav(`/${locale}`); }}>{t('profile.signOutSession')}</button></div>}
|
||||
</div>
|
||||
<div className="card stack-sm">
|
||||
<h2 style={{ fontSize: 'var(--fs-lg)' }}>{t('profile.purchases')}</h2>
|
||||
|
|
|
|||
|
|
@ -237,12 +237,21 @@ textarea.input { min-height: 110px; resize: vertical; }
|
|||
@media (min-width: 1024px) { .l-bar { display: none; } }
|
||||
@media (min-width: 1024px) { .p-wrap { grid-template-columns: 340px 1fr; align-items: start; } .p-side { position: sticky; top: 80px; max-height: calc(100vh - 100px); overflow: auto; } .p-side-order { order: -1; } }
|
||||
.screen { position: relative; background: #111; color: #fff; border-radius: var(--r-lg); overflow: hidden; aspect-ratio: 16 / 9; max-width: 100%; }
|
||||
.screen:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
|
||||
.screen video { width: 100%; height: 100%; object-fit: contain; background: #000; }
|
||||
.screen .sim { position: absolute; inset: 0; display: flex; flex-direction: column; justify-content: center; align-items: center; gap: 10px; padding: 24px; text-align: center; background: radial-gradient(circle at 30% 20%, #3A3A3A, #111 70%); }
|
||||
.screen .sim h2 { font-family: var(--f-serif); font-size: clamp(22px, 4vw, 36px); color: #fff; }
|
||||
.screen .sim .muted { color: #C8C8C8; }
|
||||
.wm { position: absolute; font-size: 12px; color: rgba(255, 255, 255, .28); pointer-events: none; user-select: none; animation: wm 40s linear infinite alternate; font-variant-numeric: tabular-nums; }
|
||||
.wm { position: absolute; z-index: 1; left: 6%; top: 10%; padding: 2px 5px; border-radius: 4px; background: rgba(0, 0, 0, .16); color: rgba(255, 255, 255, .56); text-shadow: 0 1px 2px rgba(0, 0, 0, .9); font-size: 12px; font-weight: 700; letter-spacing: .08em; pointer-events: none; user-select: none; animation: wm 40s linear infinite alternate; font-variant-numeric: tabular-nums; }
|
||||
@keyframes wm { 0% { left: 6%; top: 10%; } 33% { left: 60%; top: 30%; } 66% { left: 20%; top: 70%; } 100% { left: 70%; top: 80%; } }
|
||||
.p-full { position: absolute; z-index: 4; inset-block-start: calc(8px + env(safe-area-inset-top, 0px)); inset-inline-end: calc(8px + env(safe-area-inset-right, 0px)); width: 44px; height: 44px; display: grid; place-items: center; padding: 0; border: 1px solid rgba(255, 255, 255, .22); border-radius: var(--r-pill); background: rgba(10, 10, 10, .72); color: #fff; box-shadow: 0 2px 10px rgba(0, 0, 0, .28); cursor: pointer; }
|
||||
.p-full:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
|
||||
@media (hover: hover) and (pointer: fine) { .p-full:hover { background: rgba(10, 10, 10, .9); } }
|
||||
.screen:fullscreen, .screen.is-fill-viewport { width: 100vw; height: 100vh; height: 100dvh; max-width: none; aspect-ratio: auto; border-radius: 0; }
|
||||
.screen.is-fill-viewport { position: fixed; inset: 0; z-index: 100; margin: 0 !important; }
|
||||
.screen.is-fill-viewport iframe { inset: env(safe-area-inset-top, 0px) env(safe-area-inset-right, 0px) env(safe-area-inset-bottom, 0px) env(safe-area-inset-left, 0px); width: auto; height: auto; }
|
||||
.screen.is-fill-viewport video { box-sizing: border-box; padding: env(safe-area-inset-top, 0px) env(safe-area-inset-right, 0px) env(safe-area-inset-bottom, 0px) env(safe-area-inset-left, 0px); }
|
||||
.screen.is-fill-viewport .controls { padding-bottom: calc(10px + env(safe-area-inset-bottom, 0px)); padding-inline: calc(12px + env(safe-area-inset-left, 0px)) calc(12px + env(safe-area-inset-right, 0px)); }
|
||||
.controls { position: absolute; left: 0; right: 0; bottom: 0; padding: 10px 12px; display: flex; flex-direction: column; gap: 8px; background: linear-gradient(transparent, rgba(0, 0, 0, .75)); }
|
||||
.controls .row { gap: 6px; }
|
||||
.controls button, .controls select { background: rgba(255, 255, 255, .12); color: #fff; border: 0; border-radius: var(--r-sm); min-height: 36px; min-width: 36px; padding: 0 10px; cursor: pointer; font-size: var(--fs-sm); font-weight: 700; }
|
||||
|
|
@ -1251,3 +1260,19 @@ fieldset[disabled] .quiz-opt { cursor: default; }
|
|||
.lsheet-grip { width: 40px; height: 5px; border-radius: 3px; background: var(--line); }
|
||||
.lsheet-top .icon-btn { position: absolute; inset-inline-end: 0; }
|
||||
@media (min-width: 640px) { .lsheet { max-width: 560px; margin-inline: auto; } }
|
||||
|
||||
/* Device picker and profile devices */
|
||||
.auth-main h1:focus { outline: none; }
|
||||
.device-options { display: grid; gap: 8px; min-width: 0; margin: 0; padding: 0; border: 0; }
|
||||
.device-option { display: flex; align-items: center; gap: 12px; min-height: 56px; padding: 10px 14px; border: 1px solid var(--line); border-radius: var(--r-md); cursor: pointer; }
|
||||
.device-option:has(input:checked) { border-color: var(--accent); box-shadow: inset 0 0 0 1px var(--accent); background: var(--mist); }
|
||||
.device-option:has(input:focus-visible) { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
.device-option input { flex: none; width: 20px; height: 20px; margin: 0; accent-color: var(--accent); }
|
||||
.device-copy { display: flex; flex-direction: column; gap: 2px; flex: 1; min-width: 0; overflow-wrap: anywhere; }
|
||||
.device-copy > span { font-size: var(--fs-sm); color: var(--ink-3); font-variant-numeric: tabular-nums; }
|
||||
.device-list { display: grid; list-style: none; margin: 0; padding: 0; }
|
||||
.device-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 10px 0; border-top: 1px solid var(--line); }
|
||||
.device-row:first-child { border-top: 0; }
|
||||
.device-row .btn { flex: none; min-height: 44px; }
|
||||
.device-actions { display: flex; justify-content: flex-end; flex-wrap: wrap; gap: 8px; }
|
||||
.device-actions .btn { min-height: 44px; }
|
||||
|
|
|
|||
|
|
@ -65,6 +65,14 @@
|
|||
"waitPill": "በቅርቡ ይከፈታል · የተጠባባቂ ዝርዝሩን ይቀላቀሉ"
|
||||
},
|
||||
"auth": {
|
||||
"deviceLimitTitle": "በ{n} መሣሪያዎች ገብተዋል",
|
||||
"deviceLimitLead": "እዚህ ለመቀጠል አንዱን ያስወግዱ። ወዲያውኑ ይወጣል።",
|
||||
"deviceLegend": "የሚያስወግዱትን መሣሪያ ይምረጡ",
|
||||
"lastActive": "መጨረሻ የታየው {date}",
|
||||
"chooseDevice": "የሚያስወግዱትን መሣሪያ ይምረጡ።",
|
||||
"removeContinue": "አስወግድና ቀጥል",
|
||||
"replaceExpired": "ይህ ጥያቄ ጊዜው አልፏል። እባክዎ እንደገና ይግቡ።",
|
||||
"sessionRevoked": "ይህ መሣሪያ ከመለያዎ ተወግዷል።",
|
||||
"socialLabel": "በሌላ መለያ ይግቡ",
|
||||
"continueWith": "በ{name} ይቀጥሉ",
|
||||
"phoneTitle": "በስልክዎ ይግቡ",
|
||||
|
|
@ -220,6 +228,7 @@
|
|||
"back10": "10 ሰከንድ ወደ ኋላ",
|
||||
"fwd10": "10 ሰከንድ ወደ ፊት",
|
||||
"fullscreen": "ሙሉ ማያ",
|
||||
"exitFullscreen": "ከሙሉ ማያ ውጣ",
|
||||
"contents": "ይዘት",
|
||||
"progress": "ከ{total} ትምህርቶች {done} ተጠናቀዋል",
|
||||
"nowPlaying": "አሁን እየታየ",
|
||||
|
|
@ -276,6 +285,15 @@
|
|||
"required": "ርዕሱንና የተፈጠረውን ይሙሉ።"
|
||||
},
|
||||
"profile": {
|
||||
"currentDevice": "ይህ መሣሪያ",
|
||||
"deviceLimit": "እስከ {n} መሣሪያዎች መጠቀም ይችላሉ።",
|
||||
"devicesFailed": "መሣሪያዎችዎን መጫን አልተቻለም።",
|
||||
"devicesRetry": "እንደገና ሞክር",
|
||||
"deviceRemove": "አስወግድ",
|
||||
"deviceRemoveTitle": "ይህ መሣሪያ ይወገድ?",
|
||||
"deviceRemoveBody": "{device} ይወገድ? ወዲያውኑ ይወጣል።",
|
||||
"deviceRemoveFailed": "መሣሪያውን ማስወገድ አልተቻለም። እንደገና ይሞክሩ።",
|
||||
"deviceRemoved": "መሣሪያው ተወግዷል።",
|
||||
"lessonsList": "ትምህርቶችና ፈተናዎች",
|
||||
"account": "የመለያ ቅንብሮች",
|
||||
"statTime": "የታየ ጊዜ",
|
||||
|
|
|
|||
|
|
@ -65,6 +65,14 @@
|
|||
"waitPill": "Opening soon · Join the waitlist"
|
||||
},
|
||||
"auth": {
|
||||
"deviceLimitTitle": "You're signed in on {n} devices",
|
||||
"deviceLimitLead": "Remove one to continue here. It will be signed out right away.",
|
||||
"deviceLegend": "Choose a device to remove",
|
||||
"lastActive": "Last active {date}",
|
||||
"chooseDevice": "Choose a device to remove.",
|
||||
"removeContinue": "Remove and continue",
|
||||
"replaceExpired": "This request expired. Please sign in again.",
|
||||
"sessionRevoked": "This device was removed from your account.",
|
||||
"socialLabel": "Sign in with another account",
|
||||
"continueWith": "Continue with {name}",
|
||||
"phoneTitle": "Sign in with your phone",
|
||||
|
|
@ -220,6 +228,7 @@
|
|||
"back10": "Back 10 seconds",
|
||||
"fwd10": "Forward 10 seconds",
|
||||
"fullscreen": "Full screen",
|
||||
"exitFullscreen": "Exit full screen",
|
||||
"contents": "Contents",
|
||||
"progress": "{done} of {total} lessons completed",
|
||||
"nowPlaying": "Now playing",
|
||||
|
|
@ -276,6 +285,15 @@
|
|||
"required": "Fill in the subject and what happened."
|
||||
},
|
||||
"profile": {
|
||||
"currentDevice": "This device",
|
||||
"deviceLimit": "You can use up to {n} devices.",
|
||||
"devicesFailed": "We couldn't load your devices.",
|
||||
"devicesRetry": "Try again",
|
||||
"deviceRemove": "Remove",
|
||||
"deviceRemoveTitle": "Remove this device?",
|
||||
"deviceRemoveBody": "Remove {device}? It will be signed out right away.",
|
||||
"deviceRemoveFailed": "We couldn't remove this device. Try again.",
|
||||
"deviceRemoved": "Device removed.",
|
||||
"lessonsList": "Lessons and quizzes",
|
||||
"account": "Account settings",
|
||||
"statTime": "Watch time",
|
||||
|
|
|
|||
|
|
@ -65,6 +65,14 @@
|
|||
"waitPill": "Dhiyootti banama · Tarree eegdotaatti makami"
|
||||
},
|
||||
"auth": {
|
||||
"deviceLimitTitle": "Meeshaalee {n} irratti seentaniirtu",
|
||||
"deviceLimitLead": "Asitti itti fufuuf tokko balleessaa. Battalumatti ni bahama.",
|
||||
"deviceLegend": "Meeshaa balleessitan filadhaa",
|
||||
"lastActive": "Yeroo dhumaa kan hojjete {date}",
|
||||
"chooseDevice": "Meeshaa balleessitan filadhaa.",
|
||||
"removeContinue": "Balleessii itti fufi",
|
||||
"replaceExpired": "Gaaffiin kun yeroon isaa darbeera. Maaloo irra deebi'aa seenaa.",
|
||||
"sessionRevoked": "Meeshaan kun herrega keessan irraa balleeffameera.",
|
||||
"socialLabel": "Herrega biraatiin seeni",
|
||||
"continueWith": "{name}n itti fufi",
|
||||
"phoneTitle": "Bilbila keetiin seeni",
|
||||
|
|
@ -220,6 +228,7 @@
|
|||
"back10": "Sekondii 10 duubatti",
|
||||
"fwd10": "Sekondii 10 fuulduratti",
|
||||
"fullscreen": "Guutuu iskiriinii",
|
||||
"exitFullscreen": "Iskiriinii guutuu keessaa ba'i",
|
||||
"contents": "Qabiyyee",
|
||||
"progress": "Barnoota {total} keessaa {done} xumurameera",
|
||||
"nowPlaying": "Amma taphachaa jira",
|
||||
|
|
@ -276,6 +285,15 @@
|
|||
"required": "Mata-duree fi waan uumame guuti."
|
||||
},
|
||||
"profile": {
|
||||
"currentDevice": "Meeshaa kana",
|
||||
"deviceLimit": "Hanga meeshaalee {n} fayyadamuu dandeessu.",
|
||||
"devicesFailed": "Meeshaalee keessan fe'uun hin danda'amne.",
|
||||
"devicesRetry": "Irra deebi'ii yaali",
|
||||
"deviceRemove": "Balleessi",
|
||||
"deviceRemoveTitle": "Meeshaan kun haa balleeffamu?",
|
||||
"deviceRemoveBody": "{device} haa balleeffamu? Battalumatti ni baha.",
|
||||
"deviceRemoveFailed": "Meeshaa kana balleessuun hin danda'amne. Irra deebi'aa yaalaa.",
|
||||
"deviceRemoved": "Meeshaan balleeffameera.",
|
||||
"lessonsList": "Barnootaa fi qormaata",
|
||||
"account": "Qindaa'ina herregaa",
|
||||
"statTime": "Yeroo ilaalame",
|
||||
|
|
|
|||
|
|
@ -65,6 +65,14 @@
|
|||
"waitPill": "ቀልጢፉ ይኽፈት · ናብ ዝርዝር ተጸበይቲ ተጸንበር"
|
||||
},
|
||||
"auth": {
|
||||
"deviceLimitTitle": "ኣብ {n} መሳርሒታት ኣቲኹም ኣለኹም",
|
||||
"deviceLimitLead": "ኣብዚ ንምቕጻል ሓደ ኣልግሱ። ብቕጽበት ክወጽእ እዩ።",
|
||||
"deviceLegend": "እትኣልግሱዎ መሳርሒ ምረጹ",
|
||||
"lastActive": "ናይ መወዳእታ ንጥፈት {date}",
|
||||
"chooseDevice": "እትኣልግሱዎ መሳርሒ ምረጹ።",
|
||||
"removeContinue": "ኣልግስን ቀጽልን",
|
||||
"replaceExpired": "እዚ ሕቶ ግዜኡ ሓሊፉ። በጃኹም ደጊምኩም እተዉ።",
|
||||
"sessionRevoked": "እዚ መሳርሒ ካብ ሕሳብኩም ተኣልዩ።",
|
||||
"socialLabel": "ብካልእ ሕሳብ እቶ",
|
||||
"continueWith": "ብ{name} ቀጽል",
|
||||
"phoneTitle": "ብተሌፎንካ እቶ",
|
||||
|
|
@ -220,6 +228,7 @@
|
|||
"back10": "10 ካልኢት ንድሕሪት",
|
||||
"fwd10": "10 ካልኢት ንቕድሚት",
|
||||
"fullscreen": "ምሉእ ስክሪን",
|
||||
"exitFullscreen": "ካብ ምሉእ ስክሪን ውጻእ",
|
||||
"contents": "ትሕዝቶ",
|
||||
"progress": "ካብ {total} ትምህርትታት {done} ተወዲኦም",
|
||||
"nowPlaying": "ሕጂ ይርአ ኣሎ",
|
||||
|
|
@ -276,6 +285,15 @@
|
|||
"required": "ኣርእስትን ዘጋጠመን ምላእ።"
|
||||
},
|
||||
"profile": {
|
||||
"currentDevice": "እዚ መሳርሒ",
|
||||
"deviceLimit": "ክሳብ {n} መሳርሒታት ክትጥቀሙ ትኽእሉ።",
|
||||
"devicesFailed": "መሳርሒታትኩም ክጽዓኑ ኣይከኣሉን።",
|
||||
"devicesRetry": "ደጊምካ ፈትን",
|
||||
"deviceRemove": "ኣልግስ",
|
||||
"deviceRemoveTitle": "እዚ መሳርሒ ይለገስ?",
|
||||
"deviceRemoveBody": "{device} ይለገስ? ብቕጽበት ክወጽእ እዩ።",
|
||||
"deviceRemoveFailed": "ነዚ መሳርሒ ምእላይ ኣይተኻእለን። ደጊምኩም ፈትኑ።",
|
||||
"deviceRemoved": "መሳርሒ ተኣልዩ።",
|
||||
"lessonsList": "ትምህርትታትን ፈተናታትን",
|
||||
"account": "ምድላው ሕሳብ",
|
||||
"statTime": "ዝተራእየ ግዜ",
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user