Repository Public
1/**2 * Anonymous local learning state: schema and pure transitions. The state lives only in the visitor’s3 * browser (localStorage). Nothing here talks to a server; export/import is a file the visitor handles.4 */5import { z } from "zod";67// This schema runs in the browser, under a CSP without 'unsafe-eval'. zod otherwise probes `Function("")`8// to decide whether it may compile validators, which the CSP blocks and reports. Validate without it.9z.config({ jitless: true });1011export const STORAGE_KEY = "atlas.v1";12export const COMPLETION_THRESHOLD = 0.9;1314const Iso = z.string().max(40);15const CapsuleProgress = z.object({16 position: z.number().nonnegative(),17 duration: z.number().nonnegative(),18 /** Furthest fraction reached (0–1). */19 watched: z.number().min(0).max(1),20 completed: z.boolean(),21 updatedAt: Iso,22});23const Bookmark = z.object({ id: z.string().max(40), t: z.number().nonnegative(), label: z.string().max(200), createdAt: Iso });24const Attempt = z.object({ at: Iso, score: z.number().nonnegative(), total: z.number().int().nonnegative(), correct: z.number().int().nonnegative(), answers: z.record(z.string(), z.unknown()) });2526export const LocalState = z.object({27 v: z.literal(1),28 updatedAt: Iso,29 prefs: z.object({30 theme: z.enum(["system", "light", "dark"]).optional(),31 speed: z.number().min(0.25).max(4).optional(),32 volume: z.number().min(0).max(1).optional(),33 muted: z.boolean().optional(),34 captions: z.string().max(12).nullable().optional(),35 theater: z.boolean().optional(),36 }),37 /** Keyed by "S01/capsule-id". */38 capsules: z.record(z.string().max(120), CapsuleProgress),39 bookmarks: z.record(z.string().max(120), z.array(Bookmark).max(500)),40 /** Keyed by session id. */41 notes: z.record(z.string().max(20), z.object({ text: z.string().max(200_000), updatedAt: Iso })),42 /** Keyed by quiz id. */43 quizzes: z.record(z.string().max(60), z.object({ attempts: z.array(Attempt).max(200) })),44 /** Sessions the learner marked as done by hand. */45 done: z.record(z.string().max(20), Iso),46 /** Last slide viewed in each session's deck, keyed by session id. Absent in states saved before the slide viewer existed. */47 slides: z.record(z.string().max(20), z.object({ n: z.number().int().positive().max(1000), updatedAt: Iso })).default({}),48 /**49 * Interactive lessons, keyed by session id: the sections the learner marked as read and the last result of50 * each check question. Absent in states saved before the lessons existed.51 */52 lessons: z.record(z.string().max(20), z.object({53 sections: z.record(z.string().max(120), Iso),54 checks: z.record(z.string().max(60), z.object({ correct: z.boolean(), at: Iso })),55 updatedAt: Iso,56 })).default({}),57});58export type LocalState = z.infer<typeof LocalState>;59export type CapsuleProgress = z.infer<typeof CapsuleProgress>;60export type Bookmark = z.infer<typeof Bookmark>;61export type Attempt = z.infer<typeof Attempt>;6263export const emptyState = (now = new Date()): LocalState => ({ v: 1, updatedAt: now.toISOString(), prefs: {}, capsules: {}, bookmarks: {}, notes: {}, quizzes: {}, done: {}, slides: {}, lessons: {} });6465export const capsuleKey = (sessionId: string, capsuleId: string) => `${sessionId}/${capsuleId}`;6667const touch = (s: LocalState, now: Date): LocalState => ({ ...s, updatedAt: now.toISOString() });6869export function setPrefs(s: LocalState, prefs: Partial<LocalState["prefs"]>, now = new Date()): LocalState {70 return touch({ ...s, prefs: { ...s.prefs, ...prefs } }, now);71}7273/** Records the playhead. Completion is sticky: rewinding never un-completes a capsule. */74export function setPosition(s: LocalState, key: string, position: number, duration: number, now = new Date()): LocalState {75 const prev = s.capsules[key];76 const d = Number.isFinite(duration) && duration > 0 ? duration : prev?.duration ?? 0;77 const p = Math.max(0, d > 0 ? Math.min(position, d) : position);78 const watched = Math.min(1, Math.max(prev?.watched ?? 0, d > 0 ? p / d : 0));79 const completed = (prev?.completed ?? false) || watched >= COMPLETION_THRESHOLD;80 return touch({ ...s, capsules: { ...s.capsules, [key]: { position: p, duration: d, watched, completed, updatedAt: now.toISOString() } } }, now);81}8283/** Where to resume: nowhere near the very start or the very end. */84export function resumePosition(p: CapsuleProgress | undefined): number {85 if (!p || p.position < 5) return 0;86 if (p.duration > 0 && p.position > p.duration - 5) return 0;87 return p.position;88}8990export function addBookmark(s: LocalState, key: string, t: number, label: string, now = new Date()): LocalState {91 const list = s.bookmarks[key] ?? [];92 const mark: Bookmark = { id: `${now.getTime().toString(36)}${Math.floor(t)}`, t: Math.max(0, t), label: label.trim().slice(0, 200), createdAt: now.toISOString() };93 return touch({ ...s, bookmarks: { ...s.bookmarks, [key]: [...list, mark].sort((a, b) => a.t - b.t) } }, now);94}9596export function removeBookmark(s: LocalState, key: string, id: string, now = new Date()): LocalState {97 const list = (s.bookmarks[key] ?? []).filter((b) => b.id !== id);98 const bookmarks = { ...s.bookmarks };99 if (list.length) bookmarks[key] = list; else delete bookmarks[key];100 return touch({ ...s, bookmarks }, now);101}102103export function setNote(s: LocalState, sessionId: string, text: string, now = new Date()): LocalState {104 const notes = { ...s.notes };105 if (text.trim() === "") delete notes[sessionId]; else notes[sessionId] = { text, updatedAt: now.toISOString() };106 return touch({ ...s, notes }, now);107}108109export function recordAttempt(s: LocalState, quizId: string, attempt: Omit<Attempt, "at">, now = new Date()): LocalState {110 const prev = s.quizzes[quizId]?.attempts ?? [];111 return touch({ ...s, quizzes: { ...s.quizzes, [quizId]: { attempts: [...prev, { ...attempt, at: now.toISOString() }].slice(-200) } } }, now);112}113114/** Remembers the slide being viewed, to resume there on the next visit. */115export function setSlide(s: LocalState, sessionId: string, n: number, now = new Date()): LocalState {116 if (s.slides?.[sessionId]?.n === n) return s;117 return touch({ ...s, slides: { ...s.slides, [sessionId]: { n, updatedAt: now.toISOString() } } }, now);118}119120const lessonOf = (s: LocalState, sessionId: string) => s.lessons?.[sessionId] ?? { sections: {}, checks: {}, updatedAt: "" };121122/** Marks a section of a session's interactive lesson as read (or not). The first date a section was read is kept. */123export function setSectionRead(s: LocalState, sessionId: string, sectionId: string, read: boolean, now = new Date()): LocalState {124 const cur = lessonOf(s, sessionId);125 if (Boolean(cur.sections[sectionId]) === read) return s;126 const sections = { ...cur.sections };127 if (read) sections[sectionId] = now.toISOString(); else delete sections[sectionId];128 return touch({ ...s, lessons: { ...s.lessons, [sessionId]: { ...cur, sections, updatedAt: now.toISOString() } } }, now);129}130131/** Records the result of a check question answered inside a lesson (the last result replaces the previous one). */132export function recordCheck(s: LocalState, sessionId: string, questionId: string, correct: boolean, now = new Date()): LocalState {133 const cur = lessonOf(s, sessionId);134 return touch({ ...s, lessons: { ...s.lessons, [sessionId]: { ...cur, checks: { ...cur.checks, [questionId]: { correct, at: now.toISOString() } }, updatedAt: now.toISOString() } } }, now);135}136137export function setDone(s: LocalState, sessionId: string, done: boolean, now = new Date()): LocalState {138 const next = { ...s.done };139 if (done) next[sessionId] = now.toISOString(); else delete next[sessionId];140 return touch({ ...s, done: next }, now);141}142143/* ---- Export / import ---- */144145export interface ExportFile { app: "atlas-ia"; kind: "etat-local"; exportedAt: string; state: LocalState }146147export function exportState(s: LocalState, now = new Date()): string {148 const file: ExportFile = { app: "atlas-ia", kind: "etat-local", exportedAt: now.toISOString(), state: s };149 return JSON.stringify(file, null, 2);150}151152export type ImportResult = { ok: true; state: LocalState } | { ok: false; error: string };153154const MAX_IMPORT_BYTES = 5_000_000;155156/** Parses and validates a file produced by `exportState`. Rejects anything else; never evaluates content. */157export function parseImport(json: string): ImportResult {158 if (json.length > MAX_IMPORT_BYTES) return { ok: false, error: "Le fichier est trop volumineux pour être un export ATLAS IA." };159 let raw: unknown;160 try { raw = JSON.parse(json); } catch { return { ok: false, error: "Ce fichier n’est pas un fichier JSON valide." }; }161 if (typeof raw !== "object" || raw === null || (raw as { app?: unknown }).app !== "atlas-ia") return { ok: false, error: "Ce fichier ne provient pas d’un export ATLAS IA." };162 const parsed = LocalState.safeParse((raw as { state?: unknown }).state);163 if (!parsed.success) return { ok: false, error: "Le contenu du fichier ne correspond pas au format attendu (version 1)." };164 return { ok: true, state: parsed.data };165}166167/** Merge policy: for each item the most recently updated side wins; bookmarks and attempts are united. */168export function mergeStates(current: LocalState, incoming: LocalState, now = new Date()): LocalState {169 const newest = <T extends { updatedAt: string }>(a: Record<string, T>, b: Record<string, T>) => {170 const out: Record<string, T> = { ...a };171 for (const [k, v] of Object.entries(b)) if (!out[k] || out[k]!.updatedAt < v.updatedAt) out[k] = v;172 return out;173 };174 const capsules = newest(current.capsules, incoming.capsules);175 for (const k of Object.keys(capsules)) {176 const a = current.capsules[k], b = incoming.capsules[k];177 if (a && b) capsules[k] = { ...capsules[k]!, watched: Math.max(a.watched, b.watched), completed: a.completed || b.completed };178 }179 const bookmarks: LocalState["bookmarks"] = { ...current.bookmarks };180 for (const [k, list] of Object.entries(incoming.bookmarks)) {181 const seen = new Set((bookmarks[k] ?? []).map((b) => `${Math.floor(b.t)}|${b.label}`));182 bookmarks[k] = [...(bookmarks[k] ?? []), ...list.filter((b) => !seen.has(`${Math.floor(b.t)}|${b.label}`))].sort((a, b) => a.t - b.t).slice(0, 500);183 }184 const quizzes: LocalState["quizzes"] = { ...current.quizzes };185 for (const [k, q] of Object.entries(incoming.quizzes)) {186 const seen = new Set((quizzes[k]?.attempts ?? []).map((a) => a.at));187 quizzes[k] = { attempts: [...(quizzes[k]?.attempts ?? []), ...q.attempts.filter((a) => !seen.has(a.at))].sort((a, b) => a.at.localeCompare(b.at)).slice(-200) };188 }189 const done = { ...incoming.done, ...current.done };190 // Lessons: sections read on either side stay read (earliest date); for each check question the latest result wins.191 const lessons: LocalState["lessons"] = { ...(current.lessons ?? {}) };192 for (const [id, inc] of Object.entries(incoming.lessons ?? {})) {193 const cur = lessons[id];194 if (!cur) { lessons[id] = inc; continue; }195 const sections = { ...inc.sections };196 for (const [k, at] of Object.entries(cur.sections)) sections[k] = sections[k] && sections[k]! < at ? sections[k]! : at;197 const checks = { ...inc.checks };198 for (const [k, c] of Object.entries(cur.checks)) if (!checks[k] || checks[k]!.at <= c.at) checks[k] = c;199 lessons[id] = { sections, checks, updatedAt: cur.updatedAt > inc.updatedAt ? cur.updatedAt : inc.updatedAt };200 }201 return { v: 1, updatedAt: now.toISOString(), prefs: { ...incoming.prefs, ...current.prefs }, capsules, bookmarks, notes: newest(current.notes, incoming.notes), quizzes, done, slides: newest(current.slides ?? {}, incoming.slides ?? {}), lessons };202}203204/* ---- Derived progress ---- */205206export interface SessionShape { id: string; capsules: { id: string; optional: boolean }[]; quizId: string | null; /** Sections of the interactive lesson, when the session has one. */ lessonSections?: string[] }207export interface SessionProgress {208 /** Steps required by the completion rule, and how many are met. */209 required: number;210 met: number;211 fraction: number;212 done: boolean;213 /** Done because the learner said so, not because the rule is met. */214 manual: boolean;215 started: boolean;216}217218/**219 * Completion rule, stated in the interface as well: a session is complete when every section of its220 * interactive lesson has been marked as read, every mandatory capsule has been watched to 90 % and, if the221 * session has a quiz, at least one attempt exists — or when the learner marks it as done by hand.222 */223export function sessionProgress(session: SessionShape, s: LocalState): SessionProgress {224 const mandatory = session.capsules.filter((c) => !c.optional);225 const capsuleMet = mandatory.filter((c) => s.capsules[capsuleKey(session.id, c.id)]?.completed).length;226 const quizMet = session.quizId && (s.quizzes[session.quizId]?.attempts.length ?? 0) > 0 ? 1 : 0;227 const lessonSections = session.lessonSections ?? [], read = s.lessons?.[session.id]?.sections ?? {};228 const lessonMet = lessonSections.filter((id) => read[id]).length;229 const required = lessonSections.length + mandatory.length + (session.quizId ? 1 : 0), met = lessonMet + capsuleMet + quizMet;230 const manual = Boolean(s.done[session.id]);231 const ruleDone = required > 0 && met === required;232 const started = met > 0 || Object.keys(s.lessons?.[session.id]?.checks ?? {}).length > 0 || session.capsules.some((c) => (s.capsules[capsuleKey(session.id, c.id)]?.position ?? 0) > 0) || Boolean(s.notes[session.id]);233 return { required, met, fraction: manual ? 1 : required ? met / required : 0, done: manual || ruleDone, manual: manual && !ruleDone, started: started || manual };234}235236/** Notes of every session as one Markdown document. */237export function notesToMarkdown(s: LocalState, titles: Record<string, string>): string {238 const ids = Object.keys(s.notes).sort();239 const lines = ["# Mes notes — ATLAS IA", ""];240 for (const id of ids) lines.push(`## ${id} — ${titles[id] ?? id}`, "", s.notes[id]!.text.trim(), "");241 return lines.join("\n");242}243244/** Reads notes back from a document produced by `notesToMarkdown`. Unknown headings are ignored. */245export function notesFromMarkdown(md: string): Record<string, string> {246 const out: Record<string, string> = {};247 let current: string | null = null, buf: string[] = [];248 const flush = () => { if (current) { const t = buf.join("\n").trim(); if (t) out[current] = t; } buf = []; };249 for (const line of md.split(/\r?\n/)) {250 const m = /^## (S\d{2,3}) — /.exec(line);251 if (m) { flush(); current = m[1]!; continue; }252 if (current) buf.push(line);253 }254 flush();255 return out;256}257