File size: 9,182 Bytes
b09157d db2d194 b968036 b09157d db2d194 b09157d b968036 b09157d db2d194 b09157d db2d194 b09157d db2d194 b09157d db2d194 b09157d db2d194 b09157d db2d194 b09157d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 | 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 <html> 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 };
}
|