import { useEffect, useRef, useState } from 'react'; import { ACTIVITY_LIMIT, SIGNAL_LIMIT, activitySummary } from '../../shared/examActivity.js'; import { isOwnEdit } from './editProvenance.js'; import { examFetch } from './examTransport.js'; export function useExamActivity(auth, active) { const tracker = useRef(null), current = useRef({ auth, active }), rescan = useRef(null); current.current = { auth, active }; const [tick, setTick] = useState(0), [syncError, setSyncError] = useState(false); const snapshot = () => tracker.current ? structuredClone(tracker.current.log) : null; async function sync() { const item = tracker.current; if (!item) return; const data = snapshot(); try { const reply = await examFetch('activity', { activity: data }, current.current.auth.token, { timeout: 10000, keepalive: true }); if (!reply.ok) throw Error(); if (tracker.current === item) setSyncError(false); } catch { if (tracker.current === item) setSyncError(true); } } function record(state) { const item = tracker.current; if (!item || item.finished || item.log.events.at(-1)?.state === state) return; item.log.events.push({ at: Math.max(Date.now(), item.log.events.at(-1)?.at || 0), state }); item.log.revision++; if (item.log.events.length > ACTIVITY_LIMIT) { item.log.events.shift(); item.log.dropped++; } try { localStorage.setItem(item.key, JSON.stringify(item.log)); } catch { setSyncError(true); } setTick(value => value + 1); void sync(); } // Clues of outside help, only while the assessment is open. Returns false // when nothing was recorded so the caller can retry later. function signal(kind, detail) { const item = tracker.current; if (!item || item.finished || !current.current.active) return false; item.log.signals.push({ at: Math.max(Date.now(), item.log.signals.at(-1)?.at || 0), kind, detail: String(detail).slice(0, 120) }); item.log.revision++; if (item.log.signals.length > SIGNAL_LIMIT) { item.log.signals.shift(); item.log.signalsDropped++; } try { localStorage.setItem(item.key, JSON.stringify(item.log)); } catch { setSyncError(true); } setTick(value => value + 1); void sync(); return true; } const state = () => !current.current.active ? 'outside' : document.hidden ? 'hidden' : !document.hasFocus() ? 'unfocused' : 'active'; useEffect(() => { if (!auth) { tracker.current = null; return; } let tab; try { tab = sessionStorage.getItem('exam-activity-tab'); } catch { /* optional storage */ } if (!tab) { tab = crypto.randomUUID(); try { sessionStorage.setItem('exam-activity-tab', tab); } catch { /* optional storage */ } } const key = `exam-activity:${auth.exam.id}:${auth.studentKey}:${tab}`; let log; try { log = JSON.parse(localStorage.getItem(key)); } catch { /* start a fresh journal */ } if (!log || !Array.isArray(log.events)) log = { id: crypto.randomUUID(), revision: 0, dropped: 0, events: [] }; if (!Array.isArray(log.signals)) { log.signals = []; log.signalsDropped = 0; } tracker.current = { key, log, finished: log.events.at(-1)?.state === 'finished' }; record(state()); const change = () => record(state()); const blur = () => record(!current.current.active ? 'outside' : document.hidden ? 'hidden' : 'unfocused'); const hide = () => record('closed'); document.addEventListener('visibilitychange', change); window.addEventListener('focus', change); window.addEventListener('blur', blur); window.addEventListener('pagehide', hide); window.addEventListener('pageshow', change); window.addEventListener('online', sync); const chars = count => `${count} caractère${count > 1 ? 's' : ''}`; const paste = event => signal('paste', chars(event.clipboardData?.getData('text').length || 0)); const drop = event => { const text = event.dataTransfer?.getData('text') || ''; if (text) signal('drop', chars(text.length)); }; const copy = event => { const field = event.target; const count = typeof field?.selectionStart === 'number' ? field.selectionEnd - field.selectionStart : String(getSelection()).length; if (count) signal('copy', `${chars(count)}${event.type === 'cut' ? ' (couper)' : ''}`); }; // Typing inserts a character or a short composed word; a whole block in // one event comes from a writing assistant or an autocompletion tool. const beforeInput = event => { if (!event.isTrusted || isOwnEdit() || /^insertFrom(Paste|Drop)/.test(event.inputType)) return; const count = event.data?.length || 0; if (event.inputType === 'insertReplacementText' || count >= 25) signal('insertion', `${event.inputType} · ${chars(count)}`); }; const input = event => { if (!event.isTrusted && !isOwnEdit()) signal('synthetic', event.inputType || event.type); }; // A docked side panel (Copilot, Gemini, an extension, DevTools) narrows // the page while the window keeps its size and zoom. let view = { inner: innerWidth, outer: outerWidth, ratio: devicePixelRatio }, resizeTimer; const resize = () => { clearTimeout(resizeTimer); resizeTimer = setTimeout(() => { if (outerWidth !== view.outer || devicePixelRatio !== view.ratio) view = { inner: innerWidth, outer: outerWidth, ratio: devicePixelRatio }; else if (Math.abs(innerWidth - view.inner) >= 120 && signal('panel', `zone de la page : ${view.inner} → ${innerWidth} px`)) view.inner = innerWidth; }, 800); }; // Extensions mount their UI as custom elements or iframes and mark the // page with attributes; the app itself uses neither. const seen = new Set(); const report = (name, when) => { if (!seen.has(name) && signal('extension', `${when}${name}`)) seen.add(name); }; const inspect = (node, when = '') => { if (node.nodeType !== 1) return; const tag = node.tagName.toLowerCase(); if (tag.includes('-') || tag === 'iframe') report(`<${tag}${node.id ? `#${node.id}` : ''}>`, when); }; const attribute = (element, name, when = '') => { if (!['class', 'style', 'lang', 'dir'].includes(name)) report(`${element.tagName.toLowerCase()}[${name}]`, when); }; const scan = () => { for (const element of [document.documentElement, document.body]) { for (const name of element.getAttributeNames()) attribute(element, name, 'présent à l’ouverture : '); for (const node of element.querySelectorAll('*')) inspect(node, 'présent à l’ouverture : '); } }; // Two observers: observing twice would replace the first options. const nodes = new MutationObserver(records => { for (const item of records) for (const node of item.addedNodes) inspect(node); }); const marks = new MutationObserver(records => { for (const item of records) attribute(item.target, item.attributeName); }); nodes.observe(document.documentElement, { childList: true, subtree: true }); for (const element of [document.documentElement, document.body]) marks.observe(element, { attributes: true }); scan(); rescan.current = scan; document.addEventListener('paste', paste, true); document.addEventListener('drop', drop, true); document.addEventListener('copy', copy, true); document.addEventListener('cut', copy, true); document.addEventListener('beforeinput', beforeInput, true); document.addEventListener('input', input, true); window.addEventListener('resize', resize); const timer = setInterval(() => { void sync(); }, 30000); const displayTimer = setInterval(() => setTick(value => value + 1), 1000); return () => { record('outside'); document.removeEventListener('visibilitychange', change); window.removeEventListener('focus', change); window.removeEventListener('blur', blur); window.removeEventListener('pagehide', hide); window.removeEventListener('pageshow', change); window.removeEventListener('online', sync); clearInterval(timer); clearInterval(displayTimer); document.removeEventListener('paste', paste, true); document.removeEventListener('drop', drop, true); document.removeEventListener('copy', copy, true); document.removeEventListener('cut', copy, true); document.removeEventListener('beforeinput', beforeInput, true); document.removeEventListener('input', input, true); window.removeEventListener('resize', resize); clearTimeout(resizeTimer); nodes.disconnect(); marks.disconnect(); rescan.current = null; }; }, [auth?.studentKey, auth?.exam.id]); useEffect(() => { record(state()); }, [active]); // Extensions already in the page are reported each time the assessment opens. useEffect(() => { if (active) rescan.current?.(); }, [active]); function finish() { record('finished'); if (tracker.current) tracker.current.finished = true; } function resume() { if (!tracker.current?.finished) return; tracker.current.finished = false; record(state()); } return { snapshot, finish, resume, syncError, summary: activitySummary(tracker.current?.log), signals: (tracker.current?.log.signals.length || 0) + (tracker.current?.log.signalsDropped || 0), tick }; }