Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 | 5x 174x 190x 4x 4x 3x 64x 3x 64x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 42x 42x 42x 42x 40x 40x 42x 16x 15x 15x 15x 15x 15x 3x 3x 1x 174x 4x 2x 174x 64x 58x 56x 58x 4x 4x 4x 2x 2x 2x 2x 2x 1x 58x 58x 58x 58x 58x 58x 58x 58x 58x 174x 64x 60x 2x 1x 60x 25x 25x 60x 60x 60x 60x 60x 174x 64x 60x 9x 9x 60x 60x 60x 60x 60x 60x 60x 174x 64x 60x 13x 13x 13x 13x 13x 6x 6x 60x 60x 174x 64x 60x 1x 1x 1x 60x 60x 174x 64x 64x 174x | import { useCallback, useEffect, useRef, useState } from "react";
import { enqueueSnackbar } from "notistack";
import { StudentAssignmentAPI } from "@/api/student/StudentAssignmentAPI.js";
const SNACKBAR_THROTTLE_MS = 4000;
function isFullscreenSupported() {
return Boolean(
document.fullscreenEnabled ||
document.webkitFullscreenEnabled ||
document.mozFullScreenEnabled ||
document.msFullscreenEnabled
);
}
function getFullscreenElement() {
return (
document.fullscreenElement ||
document.webkitFullscreenElement ||
document.mozFullScreenElement ||
document.msFullscreenElement ||
null
);
}
function requestFullscreenOn(element) {
const request =
element.requestFullscreen ||
element.webkitRequestFullscreen ||
element.mozRequestFullScreen ||
element.msRequestFullscreen;
if (!request) return Promise.reject(new Error("Fullscreen API not supported"));
return request.call(element);
}
function exitFullscreenIfActive() {
if (!getFullscreenElement()) return;
const exit =
document.exitFullscreen ||
document.webkitExitFullscreen ||
document.mozCancelFullScreen ||
document.msExitFullscreen;
if (exit) exit.call(document).catch(() => {});
}
/**
* Client-side "soft lockdown" deterrents for a quiz/assessment-taking page:
* fullscreen enforcement, tab-switch/window-blur detection, copy/paste/
* dev-tools-shortcut blocking, and a beforeunload warning. Right-click is
* intentionally left alone — see the copy/cut/paste effect below.
*
* This is NOT true lockdown (see docs/implementation/browser-lockdown.md) — everything here
* is bypassable by a student with dev tools open. It deters casual cheating.
*
* When `assignmentId` is given, every recorded violation is also reported to the
* backend (see docs/implementation/browser_lockdown_violation_tracking.md), which is the
* source of truth for the running count (and its per-type breakdown, exposed as
* `violationBreakdown`) across refreshes/reconnects. Once the backend reports the
* 3-violation threshold exceeded, `onThresholdExceeded` fires exactly once so the
* caller can auto-submit the assignment — the hook itself does not know how to
* build/submit an answers payload, that's page-specific.
*
* Omitting `assignmentId` (e.g. the teacher's "View As Student" preview, which has no
* real attempt behind it) skips all backend reporting and auto-submit — violations are
* still recorded and toasted locally, same as before.
*
* @param {boolean} [enabled=true]
* @param {string} [assignmentId] - enables backend violation reporting + auto-submit
* @param {(payload: {violationCount: number, maxViolations: number}) => void} [onThresholdExceeded]
*/
export function useAssessmentLockdown({ enabled = true, assignmentId = null, onThresholdExceeded } = {}) {
const [isFullscreen, setIsFullscreen] = useState(() => Boolean(getFullscreenElement()));
const [needsFullscreenPrompt, setNeedsFullscreenPrompt] = useState(false);
const [violations, setViolations] = useState([]);
const [thresholdExceeded, setThresholdExceeded] = useState(false);
/** Backend-reported per-type counts for this attempt, e.g. {tab_hidden: 3}. Only
* meaningful when `assignmentId` was given — see the return value below. */
const [violationBreakdown, setViolationBreakdown] = useState({});
const lastWarnedRef = useRef({});
const hasEnteredFullscreenOnceRef = useRef(false);
const fullscreenSupportedRef = useRef(isFullscreenSupported());
/** Guards against calling onThresholdExceeded (and thus auto-submitting) more than once. */
const hasNotifiedThresholdRef = useRef(false);
const onThresholdExceededRef = useRef(onThresholdExceeded);
onThresholdExceededRef.current = onThresholdExceeded;
const recordViolation = useCallback(
(type, message) => {
setViolations((prev) => [...prev, { type, message, timestamp: Date.now() }]);
const now = Date.now();
const last = lastWarnedRef.current[type] || 0;
if (now - last > SNACKBAR_THROTTLE_MS) {
lastWarnedRef.current[type] = now;
enqueueSnackbar(message, { variant: "warning" });
}
// No real attempt to report against (preview mode), or already told the
// caller once — further violations still happen locally but stop hitting
// the network, since the assignment is either not real or already over.
if (!assignmentId || hasNotifiedThresholdRef.current) return;
StudentAssignmentAPI.prototype
.reportViolation(assignmentId, type)
.then((response) => {
const data = response?.data;
Iif (!data) return;
if (data.violation_breakdown) setViolationBreakdown(data.violation_breakdown);
if (data.threshold_exceeded) setThresholdExceeded(true);
if (data.threshold_exceeded && data.auto_submit && !hasNotifiedThresholdRef.current) {
hasNotifiedThresholdRef.current = true;
onThresholdExceededRef.current?.({
violationCount: data.violation_count,
maxViolations: data.max_violations,
});
}
})
.catch((error) => {
// Soft-fail: a dropped violation report must not interrupt the
// assessment. The backend remains the source of truth and will
// catch up on the next reported violation.
console.warn("Failed to report lockdown violation:", error);
});
},
[assignmentId]
);
const requestFullscreen = useCallback(() => {
return requestFullscreenOn(document.documentElement).catch(() => {
// Denied, or unsupported (e.g. iOS Safari) — don't block the
// assessment on a permission a student may not be able to grant.
setNeedsFullscreenPrompt(false);
});
}, []);
// Fullscreen entry prompt + exit detection.
useEffect(() => {
if (!enabled || !fullscreenSupportedRef.current) return undefined;
if (!getFullscreenElement()) {
setNeedsFullscreenPrompt(true);
}
const handleChange = () => {
const active = Boolean(getFullscreenElement());
setIsFullscreen(active);
if (active) {
hasEnteredFullscreenOnceRef.current = true;
setNeedsFullscreenPrompt(false);
return;
}
setNeedsFullscreenPrompt(true);
if (hasEnteredFullscreenOnceRef.current) {
recordViolation("fullscreen_exit", "You exited fullscreen. Please return to fullscreen to continue.");
}
};
document.addEventListener("fullscreenchange", handleChange);
document.addEventListener("webkitfullscreenchange", handleChange);
document.addEventListener("mozfullscreenchange", handleChange);
document.addEventListener("MSFullscreenChange", handleChange);
return () => {
document.removeEventListener("fullscreenchange", handleChange);
document.removeEventListener("webkitfullscreenchange", handleChange);
document.removeEventListener("mozfullscreenchange", handleChange);
document.removeEventListener("MSFullscreenChange", handleChange);
};
}, [enabled, recordViolation]);
// Tab-switch / window-focus loss.
useEffect(() => {
if (!enabled) return undefined;
const handleVisibility = () => {
if (document.hidden) {
recordViolation("tab_hidden", "Tab/window switch detected. This has been noted.");
}
};
const handleBlur = () => {
// Focus moving into an in-page iframe (e.g. the free-response answer's
// editable TinyMCE field) fires this exact same window "blur" event as
// genuinely switching to another window/app — the browser can't tell
// the difference at the event level. When focus lands on an iframe,
// though, the parent document's activeElement becomes that <iframe>
// element itself, which true window-switching never does (activeElement
// stays whatever it already was). That's the only reliable way to tell
// "student clicked into the answer editor" apart from "student left the
// assessment window" — without it, typing a free-response answer
// falsely recorded a violation on every click into the editor.
Iif (document.activeElement?.tagName === "IFRAME") return;
recordViolation("window_blur", "You navigated away from the assessment window. This has been noted.");
};
document.addEventListener("visibilitychange", handleVisibility);
window.addEventListener("blur", handleBlur);
return () => {
document.removeEventListener("visibilitychange", handleVisibility);
window.removeEventListener("blur", handleBlur);
};
}, [enabled, recordViolation]);
// Copy / cut / paste. Right-click is deliberately NOT blocked — it's a normal
// browser affordance students use for things unrelated to cheating (e.g. text
// selection tools, accessibility features), and blocking it produced more
// friction than deterrent value.
useEffect(() => {
if (!enabled) return undefined;
const blockClipboardEvent = (event) => {
event.preventDefault();
recordViolation("clipboard_blocked", "Copy/paste is disabled during this assessment.");
};
document.addEventListener("copy", blockClipboardEvent);
document.addEventListener("cut", blockClipboardEvent);
document.addEventListener("paste", blockClipboardEvent);
return () => {
document.removeEventListener("copy", blockClipboardEvent);
document.removeEventListener("cut", blockClipboardEvent);
document.removeEventListener("paste", blockClipboardEvent);
};
}, [enabled, recordViolation]);
// Print / view-source / dev-tools shortcuts. Ctrl/Cmd+C/V/X are handled by
// the copy/cut/paste listeners above, not here, to avoid double-logging
// the same keystroke as two different violation types.
useEffect(() => {
if (!enabled) return undefined;
const handleKeyDown = (event) => {
const key = event.key?.toLowerCase();
const ctrlOrCmd = event.ctrlKey || event.metaKey;
const isDevToolsKey = key === "f12" || (ctrlOrCmd && event.shiftKey && ["i", "j", "c"].includes(key));
const isBlockedShortcut = ctrlOrCmd && ["p", "u"].includes(key);
if (isDevToolsKey || isBlockedShortcut) {
event.preventDefault();
recordViolation("blocked_shortcut", "That keyboard shortcut is disabled during this assessment.");
}
};
window.addEventListener("keydown", handleKeyDown, true);
return () => window.removeEventListener("keydown", handleKeyDown, true);
}, [enabled, recordViolation]);
// Warn on refresh / tab-close / address-bar navigation.
useEffect(() => {
if (!enabled) return undefined;
const handleBeforeUnload = (event) => {
event.preventDefault();
event.returnValue = "";
return "";
};
window.addEventListener("beforeunload", handleBeforeUnload);
return () => window.removeEventListener("beforeunload", handleBeforeUnload);
}, [enabled]);
// Leave fullscreen behind when the guarded page unmounts (back button,
// auto-submit on timeout, etc.) so the browser isn't left locked.
useEffect(() => {
return () => {
exitFullscreenIfActive();
};
}, []);
return {
isFullscreen,
needsFullscreenPrompt: enabled && fullscreenSupportedRef.current && needsFullscreenPrompt,
fullscreenSupported: fullscreenSupportedRef.current,
requestFullscreen,
violations,
violationCount: violations.length,
// Backend-reported state — only meaningful when `assignmentId` was given.
thresholdExceeded,
violationBreakdown,
};
}
export default useAssessmentLockdown;
|