feat(assessment): keep real attempts in fullscreen and protect the task text

This commit is contained in:
shira committed 2026-10-11 03:03:55 +03:00
1 parent 56dcf32f8c
commit efa41d5967
46 files changed
+1940 -72

No files matched your search

@@ -0,0 +1,69 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import type { AssessmentItem } from "../../../shared/api/schemas";
import { AnswerForm } from "./answer-form";
const item = {
id: "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d02",
sequence: 1,
prompt: "Выберите вариант",
content: {
format: "choice",
multiple: false,
options: [
{ id: "a", text: "Первый вариант" },
{ id: "b", text: "Второй вариант" },
],
},
} satisfies AssessmentItem;
const numberItem = {
id: "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d03",
sequence: 2,
prompt: "Сколько",
content: { format: "number", unit: null },
} satisfies AssessmentItem;
const practiceItem = {
id: "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d04",
sequence: 3,
prompt: "Решите",
content: {
format: "practice",
languages: ["python"],
public_examples: [],
max_source_length: 4096,
},
} satisfies AssessmentItem;
function render(concealed: boolean, answered: AssessmentItem = item): string {
return renderToStaticMarkup(
<AnswerForm
attemptId="attempt"
item={answered}
isSaving={false}
retryable={false}
errorMessage={null}
concealed={concealed}
onSubmit={() => undefined}
onRetry={() => undefined}
/>,
);
}
describe("answer form", () => {
it("shows the options and the submit button", () => {
const markup = render(false);
expect(markup).toContain("Первый вариант");
expect(markup).toContain("Отправить ответ");
});
it("renders nothing while concealed, so no option text stays in the page", () => {
expect(render(true)).toBe("");
});
it("marks only the code editor as a field where pasting is allowed", () => {
expect(render(false, practiceItem)).toContain('data-paste="allowed"');
expect(render(false, numberItem)).not.toContain("data-paste");
});
});
@@ -11,6 +11,11 @@ type AnswerFormProps = {
isSaving: boolean;
retryable: boolean;
errorMessage: string | null;
/**
* Renders nothing while the task is hidden. The form stays mounted, so the
* draft in its state survives and the task content is not in the page.
*/
concealed?: boolean;
onSubmit: (draft: AnswerDraft) => void;
onRetry: () => void;
};
@@ -21,6 +26,7 @@ export function AnswerForm({
isSaving,
retryable,
errorMessage,
concealed = false,
onSubmit,
onRetry,
}: AnswerFormProps) {
@@ -67,6 +73,8 @@ export function AnswerForm({
option.click();
}
if (concealed) return null;
return (
<form className={styles.form} onSubmit={submit} onKeyDown={handleKeyDown}>
<fieldset
@@ -313,6 +321,8 @@ function AnswerFields({ item, draft, setDraft }: AnswerFieldsProps) {
autoComplete="off"
maxLength={content.max_source_length}
name="practice-answer"
// A code editor: pasting is allowed, and the page records its size as a signal.
data-paste="allowed"
rows={16}
spellCheck={false}
value={draft.format === "practice" ? draft.sourceCode : ""}
@@ -0,0 +1,4 @@
export { useAttemptLockdown } from "./model/use-attempt-lockdown";
export type { AttemptLockdown } from "./model/use-attempt-lockdown";
export { FullscreenFallbackNotice } from "./ui/fullscreen-fallback-notice";
export { ProtectedRegion } from "./ui/protected-region";
@@ -0,0 +1,67 @@
import { describe, expect, it } from "vitest";
import { coverReason, lockdownMode, type PageState } from "./cover";
const inside: PageState = { visible: true, focused: true, fullscreen: true };
describe("cover reason", () => {
it("shows the task while the candidate is in fullscreen, visible and focused", () => {
expect(coverReason({ page: inside, mode: "fullscreen", fullscreenPending: false })).toBeNull();
});
it("covers when fullscreen is left", () => {
expect(
coverReason({
page: { ...inside, fullscreen: false },
mode: "fullscreen",
fullscreenPending: false,
}),
).toBe("fullscreen");
});
it("covers when the tab is hidden or the window loses focus", () => {
for (const page of [
{ ...inside, visible: false },
{ ...inside, focused: false },
]) {
expect(coverReason({ page, mode: "fullscreen", fullscreenPending: false })).toBe("away");
}
});
it("keeps the fullscreen cover when both are lost, because it has the way back", () => {
expect(
coverReason({
page: { visible: false, focused: false, fullscreen: false },
mode: "fullscreen",
fullscreenPending: false,
}),
).toBe("fullscreen");
});
it("does not treat a pending fullscreen request as an exit", () => {
expect(
coverReason({
page: { ...inside, fullscreen: false },
mode: "fullscreen",
fullscreenPending: true,
}),
).toBeNull();
});
it("without fullscreen the task is covered only while the tab or window is left", () => {
const outside: PageState = { visible: true, focused: true, fullscreen: false };
expect(coverReason({ page: outside, mode: "overlay", fullscreenPending: false })).toBeNull();
expect(
coverReason({
page: { ...outside, visible: false },
mode: "overlay",
fullscreenPending: false,
}),
).toBe("away");
});
it("requires fullscreen unless a fallback applies", () => {
expect(lockdownMode(null)).toBe("fullscreen");
expect(lockdownMode("unsupported")).toBe("overlay");
expect(lockdownMode("denied")).toBe("overlay");
});
});
@@ -0,0 +1,41 @@
/** How the attempt is protected: fullscreen is required, or only the tab is watched. */
export type LockdownMode = "fullscreen" | "overlay";
/** Why fullscreen is not required for this attempt, or null when it is required. */
export type FullscreenFallback = "unsupported" | "denied" | null;
/** What the browser reports about the page right now. */
export type PageState = {
/** The tab is visible (document.visibilityState). */
visible: boolean;
/** The window has the keyboard focus (document.hasFocus()). */
focused: boolean;
/** The page is in fullscreen. */
fullscreen: boolean;
};
export type CoverReason = "away" | "fullscreen";
export type CoverInputs = {
page: PageState;
mode: LockdownMode;
/** A fullscreen request is in flight, so the missing fullscreen is not yet an exit. */
fullscreenPending: boolean;
};
/**
* Decides whether the task is covered and why.
*
* Leaving the tab or the window always covers. In fullscreen mode, being out of
* fullscreen covers as well, and it wins over "away" because only the
* fullscreen cover has a way back (a click that is a user gesture).
*/
export function coverReason({ page, mode, fullscreenPending }: CoverInputs): CoverReason | null {
if (mode === "fullscreen" && !page.fullscreen && !fullscreenPending) return "fullscreen";
if (!page.visible || !page.focused) return "away";
return null;
}
export function lockdownMode(fallback: FullscreenFallback): LockdownMode {
return fallback === null ? "fullscreen" : "overlay";
}
@@ -0,0 +1,81 @@
import { describe, expect, it, vi } from "vitest";
import {
isFullscreenSupported,
leaveFullscreen,
requestFullscreen,
type FullscreenDocument,
} from "./fullscreen";
function fakeDocument(overrides: Partial<FullscreenDocument> = {}): FullscreenDocument {
return {
fullscreenEnabled: true,
fullscreenElement: null,
documentElement: { requestFullscreen: () => Promise.resolve() },
exitFullscreen: () => Promise.resolve(),
...overrides,
};
}
describe("fullscreen support", () => {
it("is supported only when the browser enables it and the element can request it", () => {
expect(isFullscreenSupported(fakeDocument())).toBe(true);
expect(isFullscreenSupported(fakeDocument({ fullscreenEnabled: false }))).toBe(false);
// iPhone Safari: no fullscreenEnabled and no element request.
expect(isFullscreenSupported(fakeDocument({ documentElement: {} }))).toBe(false);
const withoutEnabled = fakeDocument();
delete (withoutEnabled as { fullscreenEnabled?: boolean }).fullscreenEnabled;
expect(isFullscreenSupported(withoutEnabled)).toBe(false);
});
});
describe("requesting fullscreen", () => {
it("issues the request synchronously and hides the browser navigation", async () => {
const request = vi.fn(() => Promise.resolve());
const doc = fakeDocument({ documentElement: { requestFullscreen: request } });
const pending = requestFullscreen(doc);
// The request is already made before the promise settles: it stays in the gesture.
expect(request).toHaveBeenCalledWith({ navigationUI: "hide" });
await expect(pending).resolves.toBe("entered");
});
it("reports a refusal instead of throwing", async () => {
const doc = fakeDocument({
documentElement: { requestFullscreen: () => Promise.reject(new TypeError("denied")) },
});
await expect(requestFullscreen(doc)).resolves.toBe("failed");
});
it("does not ask again when the page is already fullscreen", async () => {
const request = vi.fn(() => Promise.resolve());
const doc = fakeDocument({
fullscreenElement: {},
documentElement: { requestFullscreen: request },
});
await expect(requestFullscreen(doc)).resolves.toBe("already");
expect(request).not.toHaveBeenCalled();
});
it("fails without an element request", async () => {
await expect(requestFullscreen(fakeDocument({ documentElement: {} }))).resolves.toBe("failed");
});
});
describe("leaving fullscreen", () => {
it("exits only from fullscreen and ignores a refusal", async () => {
const exit = vi.fn(() => Promise.resolve());
await leaveFullscreen(fakeDocument({ exitFullscreen: exit }));
expect(exit).not.toHaveBeenCalled();
await leaveFullscreen(fakeDocument({ fullscreenElement: {}, exitFullscreen: exit }));
expect(exit).toHaveBeenCalledTimes(1);
await expect(
leaveFullscreen(
fakeDocument({
fullscreenElement: {},
exitFullscreen: () => Promise.reject(new Error("x")),
}),
),
).resolves.toBeUndefined();
});
});
@@ -0,0 +1,55 @@
/** The part of an element the lockdown asks to go fullscreen. */
export type FullscreenTarget = {
requestFullscreen?: (options?: { navigationUI?: "hide" | "show" | "auto" }) => Promise<void>;
};
/** The part of `document` the lockdown reads and drives; tests pass small fakes. */
export type FullscreenDocument = {
readonly fullscreenEnabled?: boolean;
readonly fullscreenElement: unknown;
readonly documentElement: FullscreenTarget;
exitFullscreen?: () => Promise<void>;
};
/**
* True when the browser can put the page into fullscreen. iPhone Safari has no
* element fullscreen, so both checks guard against a half-present API.
*/
export function isFullscreenSupported(doc: FullscreenDocument): boolean {
return (
doc.fullscreenEnabled === true && typeof doc.documentElement.requestFullscreen === "function"
);
}
export function isFullscreenActive(doc: FullscreenDocument): boolean {
return doc.fullscreenElement != null;
}
export type FullscreenRequestResult = "entered" | "already" | "failed";
/**
* Asks the browser for fullscreen. The request is issued synchronously, so the
* caller must run it inside a click or key handler: browsers refuse the request
* without a user gesture. A refusal is reported as "failed", never thrown.
*/
export async function requestFullscreen(doc: FullscreenDocument): Promise<FullscreenRequestResult> {
if (isFullscreenActive(doc)) return "already";
const request = doc.documentElement.requestFullscreen;
if (typeof request !== "function") return "failed";
try {
await request.call(doc.documentElement, { navigationUI: "hide" });
return "entered";
} catch {
return "failed";
}
}
/** Leaves fullscreen when the page is in it; a refusal is ignored. */
export async function leaveFullscreen(doc: FullscreenDocument): Promise<void> {
if (!isFullscreenActive(doc) || typeof doc.exitFullscreen !== "function") return;
try {
await doc.exitFullscreen();
} catch {
// The browser may already have left fullscreen.
}
}
@@ -0,0 +1,175 @@
import { describe, expect, it, vi } from "vitest";
import {
createTaskGuard,
describeField,
inputIsBlocked,
type ElementLike,
type GuardEvent,
type SelectionLike,
} from "./task-guard";
// A tiny element: `matches` lists the selectors that find it from itself, and
// `parent` is the element a text node or a child belongs to.
function element(
tagName: string,
options: { type?: string; paste?: boolean; parent?: ElementLike } = {},
): ElementLike {
const self: ElementLike = {
tagName: tagName.toUpperCase(),
...(options.type !== undefined ? { type: options.type } : {}),
closest(selector: string) {
if (selector === "input, textarea" && (tagName === "input" || tagName === "textarea")) {
return self;
}
if (selector === '[data-paste="allowed"]' && options.paste) return self;
return options.parent?.closest(selector) ?? null;
},
};
return self;
}
const taskText = element("p");
const numberField = element("input", { type: "text" });
const configField = element("textarea");
const editor = element("textarea", { paste: true });
const checkbox = element("input", { type: "checkbox" });
const textNodeOfTask = { parentElement: taskText };
describe("describeField", () => {
it("tells text fields from task content and finds the paste exception", () => {
expect(describeField(numberField)).toEqual({ textField: true, pasteAllowed: false });
expect(describeField(configField)).toEqual({ textField: true, pasteAllowed: false });
expect(describeField(editor)).toEqual({ textField: true, pasteAllowed: true });
expect(describeField(taskText)).toEqual({ textField: false, pasteAllowed: false });
expect(describeField(textNodeOfTask)).toEqual({ textField: false, pasteAllowed: false });
// An option is task content: it holds no text of the candidate.
expect(describeField(checkbox)).toEqual({ textField: false, pasteAllowed: false });
expect(describeField(null)).toEqual({ textField: false, pasteAllowed: false });
});
});
function guardWith(options: { selection?: SelectionLike | null; insideRegion?: unknown[] } = {}) {
const pasteBlocked = vi.fn();
const inside = new Set<unknown>(options.insideRegion ?? [taskText, numberField, editor]);
const guard = createTaskGuard({
region: { contains: (node) => inside.has(node) },
selection: () => options.selection ?? null,
onPasteBlocked: pasteBlocked,
});
return { guard, pasteBlocked };
}
function event(target: unknown, extra: Partial<GuardEvent> = {}) {
const preventDefault = vi.fn();
const setData = vi.fn();
const value = {
target,
preventDefault,
clipboardData: { setData },
...extra,
} satisfies GuardEvent;
return { event: value, preventDefault, setData };
}
describe("task guard", () => {
it("blocks selection, the context menu, and drag on the task text only", () => {
const { guard } = guardWith();
for (const handler of [guard.onSelectStart, guard.onContextMenu, guard.onDragStart]) {
const onTask = event(taskText);
handler(onTask.event);
expect(onTask.preventDefault).toHaveBeenCalledTimes(1);
const onField = event(numberField);
handler(onField.event);
expect(onField.preventDefault).not.toHaveBeenCalled();
}
});
it("never lets a drop fill an answer field", () => {
const { guard } = guardWith();
const dropped = event(editor);
guard.onDrop(dropped.event);
expect(dropped.preventDefault).toHaveBeenCalledTimes(1);
});
it("refuses paste in answer fields, says so, and allows it in the code editor", () => {
const { guard, pasteBlocked } = guardWith();
const intoNumber = event(numberField);
guard.onPaste(intoNumber.event);
expect(intoNumber.preventDefault).toHaveBeenCalledTimes(1);
expect(pasteBlocked).toHaveBeenCalledTimes(1);
const intoEditor = event(editor);
guard.onPaste(intoEditor.event);
expect(intoEditor.preventDefault).not.toHaveBeenCalled();
expect(pasteBlocked).toHaveBeenCalledTimes(1);
});
it("closes the beforeinput routes that bypass the paste event", () => {
const numberInfo = describeField(numberField);
const editorInfo = describeField(editor);
expect(inputIsBlocked(numberInfo, "insertFromPaste")).toBe(true);
expect(inputIsBlocked(numberInfo, "insertFromDrop")).toBe(true);
expect(inputIsBlocked(editorInfo, "insertFromPaste")).toBe(false);
expect(inputIsBlocked(editorInfo, "insertFromDrop")).toBe(true);
// Typing, deleting, and composing are never touched.
for (const inputType of ["insertText", "deleteContentBackward", "insertCompositionText"]) {
expect(inputIsBlocked(numberInfo, inputType)).toBe(false);
}
const { guard, pasteBlocked } = guardWith();
const typing = event(numberField, { inputType: "insertText" });
guard.onBeforeInput(typing.event);
expect(typing.preventDefault).not.toHaveBeenCalled();
const pasted = event(numberField, { inputType: "insertFromPaste" });
guard.onBeforeInput(pasted.event);
expect(pasted.preventDefault).toHaveBeenCalledTimes(1);
expect(pasteBlocked).toHaveBeenCalledTimes(1);
});
it("copies nothing from the task text and leaves an empty clipboard text", () => {
const { guard } = guardWith();
const copy = event(taskText);
guard.onClipboardRead(copy.event);
expect(copy.preventDefault).toHaveBeenCalledTimes(1);
expect(copy.setData).toHaveBeenCalledWith("text/plain", "");
});
it("lets a field copy and cut its own text", () => {
const { guard } = guardWith();
for (const field of [numberField, editor]) {
const copy = event(field);
guard.onClipboardRead(copy.event);
expect(copy.preventDefault).not.toHaveBeenCalled();
expect(copy.setData).not.toHaveBeenCalled();
}
});
it("blocks a select-all copy that starts outside the region but reaches into it", () => {
const body = element("body");
const selection: SelectionLike = {
rangeCount: 1,
anchorNode: body,
focusNode: body,
containsNode: (node, partial) => node !== null && partial === true,
};
const { guard } = guardWith({ selection });
const copy = event(body);
guard.onClipboardRead(copy.event);
expect(copy.preventDefault).toHaveBeenCalledTimes(1);
});
it("leaves a copy alone when neither the target nor the selection touches the region", () => {
const header = element("h1");
const selection: SelectionLike = {
rangeCount: 1,
anchorNode: header,
focusNode: header,
containsNode: () => false,
};
const { guard } = guardWith({ selection });
const copy = event(header);
guard.onClipboardRead(copy.event);
expect(copy.preventDefault).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,180 @@
/**
* Rules that keep the task text from being copied out of an attempt and keep
* foreign text out of the answer fields.
*
* Nothing here touches keyboard input or assistive technology: the text stays
* in the page for screen readers, typing is never intercepted, and a field's own
* text can still be selected, copied, and cut. The decisions are plain
* functions of small structural types so they run without a DOM in tests.
*/
/** The part of an element the rules read. */
export type ElementLike = {
closest(selector: string): ElementLike | null;
readonly tagName?: string;
readonly type?: string;
};
/** What a target is for the rules: a text field (and whether paste may go in) or anything else. */
export type FieldInfo = { textField: boolean; pasteAllowed: boolean };
const textInputTypes = new Set(["", "text", "search", "number", "email", "url", "tel", "password"]);
function isElementLike(value: unknown): value is ElementLike {
return (
typeof value === "object" &&
value !== null &&
typeof (value as { closest?: unknown }).closest === "function"
);
}
/** The element of an event target; a text node stands for its parent element. */
export function targetElement(target: unknown): ElementLike | null {
if (isElementLike(target)) return target;
const parent = (target as { parentElement?: unknown } | null)?.parentElement;
return isElementLike(parent) ? parent : null;
}
/**
* Classifies a target. A text field is a textarea or a text-like input: checkboxes
* and radio buttons hold no text of the candidate, so they count as task content.
* Paste is allowed in a field that sits in an element marked `data-paste="allowed"`
* (the practice code editor).
*/
export function describeField(target: unknown): FieldInfo {
const element = targetElement(target);
const field = element?.closest("input, textarea") ?? null;
const tag = field?.tagName?.toLowerCase();
const textField =
tag === "textarea" ||
(tag === "input" && textInputTypes.has((field?.type ?? "").toLowerCase()));
const pasteAllowed = textField && field?.closest('[data-paste="allowed"]') != null;
return { textField, pasteAllowed };
}
/** The task text is not selectable; the candidate's own text is. */
export function selectionStartIsBlocked(info: FieldInfo): boolean {
return !info.textField;
}
/** The context menu offers copy and "search for selection" on the task text; fields keep theirs. */
export function contextMenuIsBlocked(info: FieldInfo): boolean {
return !info.textField;
}
/** Task text cannot be dragged out; a selection inside a field can still be moved. */
export function dragStartIsBlocked(info: FieldInfo): boolean {
return !info.textField;
}
/** Foreign text is refused by every answer field except the code editor. */
export function pasteIsBlocked(info: FieldInfo): boolean {
return info.textField && !info.pasteAllowed;
}
/**
* Copy and cut are refused when they would read the task: the target is not a
* field and it, or the selection, reaches into the protected region.
*/
export function clipboardReadIsBlocked(
info: FieldInfo,
reach: { targetInRegion: boolean; selectionInRegion: boolean },
): boolean {
return !info.textField && (reach.targetInRegion || reach.selectionInRegion);
}
const pasteInputTypes = new Set(["insertFromPaste", "insertFromPasteAsQuotation"]);
const dropInputTypes = new Set(["insertFromDrop"]);
/** What a `beforeinput` event does to a field, judged by its input type. */
export function inputIsBlocked(info: FieldInfo, inputType: string): boolean {
if (!info.textField) return false;
if (dropInputTypes.has(inputType)) return true;
return pasteInputTypes.has(inputType) && !info.pasteAllowed;
}
// DOM glue: the handlers below turn events into the decisions above.
/** The part of an event the handlers read and change. */
export type GuardEvent = {
readonly target: unknown;
readonly inputType?: string;
readonly clipboardData?: { setData(format: string, data: string): void } | null;
preventDefault(): void;
};
/** The part of `Selection` the copy rule reads. */
export type SelectionLike = {
readonly rangeCount: number;
readonly anchorNode: unknown;
readonly focusNode: unknown;
containsNode(node: unknown, allowPartialContainment?: boolean): boolean;
};
export type TaskGuardOptions = {
region: { contains(node: unknown): boolean };
selection: () => SelectionLike | null;
/** Called when a paste into an answer field was refused, so the screen can say so. */
onPasteBlocked?: () => void;
};
export type TaskGuard = {
onSelectStart(event: GuardEvent): void;
onContextMenu(event: GuardEvent): void;
onDragStart(event: GuardEvent): void;
onDrop(event: GuardEvent): void;
onPaste(event: GuardEvent): void;
onBeforeInput(event: GuardEvent): void;
onClipboardRead(event: GuardEvent): void;
};
export function createTaskGuard(options: TaskGuardOptions): TaskGuard {
function selectionInRegion(): boolean {
const selection = options.selection();
if (!selection || selection.rangeCount === 0) return false;
return (
options.region.contains(selection.anchorNode) ||
options.region.contains(selection.focusNode) ||
selection.containsNode(options.region, true)
);
}
return {
onSelectStart(event) {
if (selectionStartIsBlocked(describeField(event.target))) event.preventDefault();
},
onContextMenu(event) {
if (contextMenuIsBlocked(describeField(event.target))) event.preventDefault();
},
onDragStart(event) {
if (dragStartIsBlocked(describeField(event.target))) event.preventDefault();
},
onDrop(event) {
// Dropped text is foreign text too, and the drop is never recorded as a paste.
event.preventDefault();
},
onPaste(event) {
if (!pasteIsBlocked(describeField(event.target))) return;
event.preventDefault();
options.onPasteBlocked?.();
},
onBeforeInput(event) {
const info = describeField(event.target);
if (!inputIsBlocked(info, event.inputType ?? "")) return;
event.preventDefault();
if (pasteInputTypes.has(event.inputType ?? "")) options.onPasteBlocked?.();
},
onClipboardRead(event) {
const info = describeField(event.target);
const targetInRegion = options.region.contains(event.target);
if (
!clipboardReadIsBlocked(info, { targetInRegion, selectionInRegion: selectionInRegion() })
) {
return;
}
event.preventDefault();
// An empty text overwrites nothing useful and leaves no task text in the clipboard.
event.clipboardData?.setData("text/plain", "");
},
};
}
@@ -0,0 +1,126 @@
import { useCallback, useEffect, useState, useSyncExternalStore } from "react";
import {
coverReason,
lockdownMode,
type CoverReason,
type FullscreenFallback,
type LockdownMode,
type PageState,
} from "./cover";
import {
isFullscreenActive,
isFullscreenSupported,
leaveFullscreen,
requestFullscreen,
} from "./fullscreen";
export type AttemptLockdown = {
/** Fullscreen is required, or only leaving the tab covers the task. */
mode: LockdownMode;
/** Why fullscreen is not required, or null when it is. */
fallback: FullscreenFallback;
/** The task is hidden right now. */
covered: boolean;
reason: CoverReason | null;
/**
* Asks for fullscreen. Call it from the click that starts or resumes the work:
* the browser accepts the request only inside a user gesture.
*/
enter: () => Promise<void>;
/** Leaves fullscreen, for example when the candidate declines to start. */
leave: () => void;
};
type Options = {
/** A real attempt that is not finished: fullscreen and the cover apply. */
applies: boolean;
/** The candidate started or resumed the work, so a task is on the screen. */
running: boolean;
};
// The page state is packed in one number so that the store snapshot is a
// primitive and React compares it without extra bookkeeping.
const visibleBit = 1;
const focusedBit = 2;
const fullscreenBit = 4;
function readPage(): number {
return (
(document.visibilityState === "visible" ? visibleBit : 0) |
(document.hasFocus() ? focusedBit : 0) |
(isFullscreenActive(document) ? fullscreenBit : 0)
);
}
// Rendered without a browser (server markup in tests), nothing is left, so nothing is covered.
function readServerPage(): number {
return visibleBit | focusedBit | fullscreenBit;
}
function subscribePage(onChange: () => void): () => void {
document.addEventListener("visibilitychange", onChange);
document.addEventListener("fullscreenchange", onChange);
window.addEventListener("focus", onChange);
window.addEventListener("blur", onChange);
return () => {
document.removeEventListener("visibilitychange", onChange);
document.removeEventListener("fullscreenchange", onChange);
window.removeEventListener("focus", onChange);
window.removeEventListener("blur", onChange);
};
}
function pageFromBits(bits: number): PageState {
return {
visible: (bits & visibleBit) !== 0,
focused: (bits & focusedBit) !== 0,
fullscreen: (bits & fullscreenBit) !== 0,
};
}
/**
* Keeps a real attempt in fullscreen and hides the task whenever the candidate
* leaves the tab, the window, or fullscreen. It only decides what is shown: the
* attempt timer and the answer state stay on the server and in the form, and
* the passive signal collector records the same exits on its own.
*
* A browser without element fullscreen (iPhone Safari) or one that refuses the
* request keeps the candidate in the test with the tab watch alone; `fallback`
* says which case it is so the screen can explain it.
*/
export function useAttemptLockdown({ applies, running }: Options): AttemptLockdown {
const supported = useState(
() => typeof document !== "undefined" && isFullscreenSupported(document),
)[0];
const [denied, setDenied] = useState(false);
const [pending, setPending] = useState(false);
const page = pageFromBits(useSyncExternalStore(subscribePage, readPage, readServerPage));
const fallback: FullscreenFallback = !supported ? "unsupported" : denied ? "denied" : null;
const mode = lockdownMode(fallback);
const reason =
applies && running ? coverReason({ page, mode, fullscreenPending: pending }) : null;
const enter = useCallback(async () => {
if (!applies || fallback !== null) return;
setPending(true);
// The request is issued synchronously inside this call, still within the gesture.
const result = await requestFullscreen(document);
setPending(false);
if (result === "failed") setDenied(true);
}, [applies, fallback]);
const leave = useCallback(() => {
void leaveFullscreen(document);
}, []);
useEffect(() => {
if (!applies) return undefined;
// A finished attempt, or a page that is left, must not stay fullscreen.
return () => {
void leaveFullscreen(document);
};
}, [applies]);
return { mode, fallback, covered: reason !== null, reason, enter, leave };
}
@@ -0,0 +1,51 @@
import { useEffect, type RefObject } from "react";
import { createTaskGuard, type GuardEvent, type TaskGuard } from "./task-guard";
/**
* Registers the guard on a region and on its document. Copy and cut are heard
* on the document because a select-all copy starts outside the region. Nothing
* stops propagation, so the passive signal collector still sees every paste,
* copy, and cut, including the ones refused here.
*/
export function attachTaskGuard(region: HTMLElement, guard: TaskGuard): () => void {
const doc = region.ownerDocument;
const registered: Array<[EventTarget, string, EventListener]> = [];
function listen(target: EventTarget, type: string, handler: (event: GuardEvent) => void): void {
const listener: EventListener = (event) => handler(event as unknown as GuardEvent);
target.addEventListener(type, listener);
registered.push([target, type, listener]);
}
listen(region, "selectstart", guard.onSelectStart);
listen(region, "contextmenu", guard.onContextMenu);
listen(region, "dragstart", guard.onDragStart);
listen(region, "drop", guard.onDrop);
listen(region, "paste", guard.onPaste);
listen(region, "beforeinput", guard.onBeforeInput);
listen(doc, "copy", guard.onClipboardRead);
listen(doc, "cut", guard.onClipboardRead);
return () => {
for (const [target, type, listener] of registered) target.removeEventListener(type, listener);
registered.length = 0;
};
}
/** Applies the task guard to the region while `enabled`. */
export function useTaskGuard(
regionRef: RefObject<HTMLElement | null>,
enabled: boolean,
onPasteBlocked: () => void,
): void {
useEffect(() => {
const region = regionRef.current;
if (!enabled || !region) return undefined;
const guard = createTaskGuard({
region,
selection: () => region.ownerDocument.getSelection(),
onPasteBlocked,
});
return attachTaskGuard(region, guard);
}, [regionRef, enabled, onPasteBlocked]);
}
@@ -0,0 +1,31 @@
.cover {
display: grid;
gap: var(--space-3);
min-width: 0;
}
.cover:focus {
outline: none;
}
.cover:focus-visible {
outline: var(--focus-ring-width) solid var(--color-focus-ring);
outline-offset: var(--focus-ring-offset);
}
.title {
margin: 0;
color: var(--color-text-strong);
font-size: var(--font-size-l);
}
.text {
margin: 0;
color: var(--color-text-secondary);
}
.actions {
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
}
@@ -0,0 +1,39 @@
import { forwardRef } from "react";
import { Button } from "../../../shared/ui";
import type { CoverReason } from "../model/cover";
import styles from "./attempt-cover.module.css";
type AttemptCoverProps = {
reason: CoverReason;
headingId: string;
onContinue: () => void;
};
const bodies: Readonly<Record<CoverReason, string>> = {
fullscreen: "Тест идет в полноэкранном режиме. Вернитесь в него, чтобы продолжить.",
away: "Вы вышли из вкладки или окна. Вернитесь, чтобы продолжить.",
};
/**
* Stands in for the task while the candidate is away. The task is not rendered
* under it: it is replaced, so nothing of the task stays in the page, in a
* screenshot, or for a reader that ignores styles.
*/
export const AttemptCover = forwardRef<HTMLDivElement, AttemptCoverProps>(function AttemptCover(
{ reason, headingId, onContinue },
ref,
) {
return (
<div ref={ref} className={styles.cover} tabIndex={-1} role="status">
<h3 id={headingId} className={styles.title}>
Задание скрыто
</h3>
<p className={styles.text}>{bodies[reason]} Введенный ответ сохранен.</p>
{reason === "fullscreen" ? (
<div className={styles.actions}>
<Button onClick={onContinue}>Продолжить в полном экране</Button>
</div>
) : null}
</div>
);
});
@@ -0,0 +1,21 @@
import { Notice } from "../../../shared/ui";
import type { FullscreenFallback } from "../model/cover";
const messages: Readonly<Record<NonNullable<FullscreenFallback>, string>> = {
unsupported:
"Этот браузер не поддерживает полноэкранный режим. Тест можно пройти и без него: при выходе из вкладки или окна задание скрывается.",
denied:
"Браузер не включил полноэкранный режим. Тест продолжается без него: при выходе из вкладки или окна задание скрывается.",
};
/** Explains why fullscreen is not asked for. It is information, not an error. */
export function FullscreenFallbackNotice({ fallback }: { fallback: FullscreenFallback }) {
if (fallback === null) return null;
return (
<div role="status">
<Notice tone="info">
<p>{messages[fallback]}</p>
</Notice>
</div>
);
}
@@ -0,0 +1,32 @@
/* The task text cannot be selected or dragged out. Fields keep their own
* selection, and the text stays in the page for screen readers.
* Safari still needs the -webkit- forms of user-select (the lint exception is
* for those lines only); without the explicit rule on fields, Safari refuses
* to edit them inside a non-selectable region. */
.region {
/* stylelint-disable-next-line property-no-vendor-prefix */
-webkit-user-select: none;
user-select: none;
-webkit-touch-callout: none;
}
.region :is(input:not([type="checkbox"], [type="radio"]), textarea) {
/* stylelint-disable-next-line property-no-vendor-prefix */
-webkit-user-select: text;
user-select: text;
}
.refused {
margin: 0;
color: var(--color-text-secondary);
font-size: var(--font-size-s);
}
/* Printing leaves the task, its options, and the answer fields out. The
* element selector keeps this rule above the page's own display rule for the
* panel, whichever stylesheet loads last. */
@media print {
article.region {
display: none;
}
}
@@ -0,0 +1,93 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import type { AttemptLockdown } from "../model/use-attempt-lockdown";
import { FullscreenFallbackNotice } from "./fullscreen-fallback-notice";
import { ProtectedRegion } from "./protected-region";
const prompt = "SECRET-PROMPT-TEXT";
function lockdown(overrides: Partial<AttemptLockdown>): AttemptLockdown {
return {
mode: "fullscreen",
fallback: null,
covered: false,
reason: null,
enter: () => Promise.resolve(),
leave: () => undefined,
...overrides,
};
}
// Stands in for the answer form, which hides its own options while concealed.
function AnswerStub({ concealed }: { concealed: boolean }) {
return concealed ? null : <form>SECRET-OPTION-ONE</form>;
}
function render(state: AttemptLockdown | null): string {
return renderToStaticMarkup(
<ProtectedRegion
lockdown={state}
headingId="item-title"
task={
<>
<h3 id="item-title">Задание 1</h3>
<p>{prompt}</p>
</>
}
>
<AnswerStub concealed={state?.covered ?? false} />
</ProtectedRegion>,
);
}
describe("protected region", () => {
it("shows the task and the answer form while the candidate is in fullscreen", () => {
const markup = render(lockdown({}));
expect(markup).toContain("SECRET-PROMPT-TEXT");
expect(markup).toContain("SECRET-OPTION-ONE");
expect(markup).not.toContain("Задание скрыто");
});
it("replaces the task and the options with the cover, leaving none of their text in the page", () => {
const markup = render(lockdown({ covered: true, reason: "fullscreen" }));
expect(markup).toContain("Задание скрыто");
expect(markup).toContain("Продолжить в полном экране");
expect(markup).not.toContain("SECRET-PROMPT-TEXT");
expect(markup).not.toContain("SECRET-OPTION");
});
it("covers a left tab without a fullscreen button", () => {
const markup = render(lockdown({ covered: true, reason: "away" }));
expect(markup).toContain("Вы вышли из вкладки или окна");
expect(markup).not.toContain("Продолжить в полном экране");
expect(markup).not.toContain("SECRET-PROMPT-TEXT");
});
it("marks a protected region for the selection and print rules, and no other", () => {
expect(render(lockdown({}))).toContain("region");
expect(render(null)).not.toContain("region");
// The paste notice appears only after a paste was refused.
expect(render(lockdown({}))).not.toContain("Вставка в поля ответа отключена");
});
it("leaves an unprotected attempt as it is", () => {
const markup = render(null);
expect(markup).toContain("SECRET-PROMPT-TEXT");
expect(markup).not.toContain("Задание скрыто");
});
});
describe("fullscreen fallback notice", () => {
it("explains an unsupported browser and a refused request, and stays silent otherwise", () => {
expect(renderToStaticMarkup(<FullscreenFallbackNotice fallback="unsupported" />)).toContain(
"не поддерживает полноэкранный режим",
);
expect(renderToStaticMarkup(<FullscreenFallbackNotice fallback="unsupported" />)).toContain(
"Тест можно пройти и без него",
);
expect(renderToStaticMarkup(<FullscreenFallbackNotice fallback="denied" />)).toContain(
"не включил полноэкранный режим",
);
expect(renderToStaticMarkup(<FullscreenFallbackNotice fallback={null} />)).toBe("");
});
});
@@ -0,0 +1,77 @@
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
import type { AttemptLockdown } from "../model/use-attempt-lockdown";
import { useTaskGuard } from "../model/use-task-guard";
import { AttemptCover } from "./attempt-cover";
import styles from "./protected-region.module.css";
type ProtectedRegionProps = {
/** The lockdown of a real attempt, or null for an attempt that is not protected. */
lockdown: AttemptLockdown | null;
className?: string | undefined;
headingId: string;
/** The task text. It is replaced by the cover while the candidate is away. */
task: ReactNode;
/** The answer controls. They hide their own task content while `lockdown.covered`. */
children: ReactNode;
};
/**
* The panel of the current item. It shows the task, or the cover in its place,
* and puts the keyboard focus where the candidate can continue: on the cover
* while the task is hidden, on the panel when the task comes back.
*/
export function ProtectedRegion({
lockdown,
className,
headingId,
task,
children,
}: ProtectedRegionProps) {
const regionRef = useRef<HTMLElement>(null);
const coverRef = useRef<HTMLDivElement>(null);
const wasCovered = useRef(false);
const covered = lockdown?.covered ?? false;
const protectedText = lockdown !== null;
const [pasteRefused, setPasteRefused] = useState(false);
const refusePaste = useCallback(() => setPasteRefused(true), []);
useTaskGuard(regionRef, protectedText, refusePaste);
useEffect(() => {
if (covered) {
wasCovered.current = true;
const action = coverRef.current?.querySelector<HTMLElement>("button");
(action ?? coverRef.current)?.focus();
} else if (wasCovered.current) {
wasCovered.current = false;
regionRef.current?.focus();
}
}, [covered]);
return (
<article
ref={regionRef}
className={protectedText ? `${styles.region} ${className ?? ""}`.trim() : className}
aria-labelledby={headingId}
tabIndex={-1}
// Typing in a field means the candidate went on, so the refusal notice goes.
onInput={() => setPasteRefused(false)}
>
{lockdown && lockdown.reason ? (
<AttemptCover
ref={coverRef}
reason={lockdown.reason}
headingId={headingId}
onContinue={() => void lockdown.enter()}
/>
) : (
task
)}
{children}
{pasteRefused && !covered ? (
<p className={styles.refused} role="status">
Вставка в поля ответа отключена. Введите ответ вручную.
</p>
) : null}
</article>
);
}
@@ -3,7 +3,7 @@
* candidate acknowledged; change this number together with the text and with
* the version the server requires, so that everyone acknowledges the new text.
*/
export const knownSignalNoticeVersion = 1;
export const knownSignalNoticeVersion = 2;
export type DisclosedSignal = { code: string; title: string; detail: string };
@@ -22,7 +22,42 @@ export const browserSignals: readonly DisclosedSignal[] = [
{
code: "fullscreen",
title: "Выход из полноэкранного режима",
detail: "Только факт выхода. Полноэкранный режим включать не нужно.",
detail: "Только факт выхода.",
},
];
/**
* What the page does itself during a real attempt. These measures record
* nothing on their own: the browser signals above are the only record.
*/
export const attemptMeasures: readonly DisclosedSignal[] = [
{
code: "fullscreen",
title: "Полноэкранный режим",
detail:
"Попытка идет на весь экран. Если браузер его не поддерживает, тест идет без него, и вы увидите это на экране.",
},
{
code: "cover",
title: "Скрытие задания",
detail:
"При выходе из полноэкранного режима, вкладки или окна задание скрывается, пока вы не вернетесь. Введенный ответ сохраняется.",
},
{
code: "task_text",
title: "Защита текста задания",
detail:
"Копирование, вырезание, выделение, контекстное меню, перетаскивание и печать текста задания отключены.",
},
{
code: "paste",
title: "Вставка в поля ответа",
detail: "Отключена. В редакторе кода вставка разрешена, фиксируется только ее размер.",
},
{
code: "watermark",
title: "Водяной знак на странице задания",
detail: "Планируется. Пока не используется.",
},
];
@@ -13,9 +13,11 @@ export type SignalNoticeGate = {
/**
* Runs the action at once when the notice is acknowledged on the server.
* Otherwise the notice dialog opens, and the action runs only after the
* candidate confirms and the server stores the confirmation.
* candidate confirms and the server stores the confirmation. `onDeclined`
* runs when the action will not run: the notice state could not be read or
* is outdated, or the candidate closed the notice without confirming.
*/
guard: (action: () => void) => Promise<void>;
guard: (action: () => void, onDeclined?: () => void) => Promise<void>;
/** A message when the notice state could not be read or is outdated. */
checkError: string | null;
dialog: {
@@ -40,13 +42,15 @@ export function useSignalNoticeGate({ actor, queryClient, enabled }: Options): S
const [dialog, dispatch] = useReducer(noticeDialogReducer, closedNoticeDialog);
const [checkError, setCheckError] = useState<string | null>(null);
const pendingAction = useRef<(() => void) | null>(null);
const pendingDeclined = useRef<(() => void) | null>(null);
async function guard(action: () => void): Promise<void> {
async function guard(action: () => void, onDeclined?: () => void): Promise<void> {
setCheckError(null);
const current = notice.data ?? (await notice.refetch()).data;
const decision = decideNotice(current);
if (decision.kind === "unavailable" || decision.kind === "outdated") {
setCheckError(decision.message);
onDeclined?.();
return;
}
if (decision.kind === "proceed") {
@@ -54,6 +58,7 @@ export function useSignalNoticeGate({ actor, queryClient, enabled }: Options): S
return;
}
pendingAction.current = action;
pendingDeclined.current = onDeclined ?? null;
dispatch({ type: "open" });
}
@@ -70,13 +75,17 @@ export function useSignalNoticeGate({ actor, queryClient, enabled }: Options): S
dispatch({ type: "confirmed" });
const action = pendingAction.current;
pendingAction.current = null;
pendingDeclined.current = null;
action?.();
}
function close(): void {
if (dialog.busy) return;
pendingAction.current = null;
const declined = pendingDeclined.current;
pendingDeclined.current = null;
dispatch({ type: "close" });
declined?.();
}
return {
@@ -1,8 +1,32 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import { knownSignalNoticeVersion } from "../model/notice-content";
import { SignalNoticeContent, SignalNoticeDialog, SignalNoticeSummary } from "./signal-notice";
describe("signal notice", () => {
it("is version 2, the text that added the attempt measures", () => {
expect(knownSignalNoticeVersion).toBe(2);
});
it("lists every measure the page applies during a real attempt", () => {
const markup = renderToStaticMarkup(<SignalNoticeContent headingLevel="h3" />);
expect(markup).toContain("Что ограничено во время теста");
expect(markup).toContain("Полноэкранный режим");
expect(markup).toContain("Скрытие задания");
expect(markup).toContain("Защита текста задания");
expect(markup).toContain("Копирование, вырезание, выделение, контекстное меню");
expect(markup).toContain("печать текста задания отключены");
expect(markup).toContain("Вставка в поля ответа");
expect(markup).toContain("В редакторе кода вставка разрешена");
expect(markup).toContain("Водяной знак на странице задания");
expect(markup).toContain("Планируется");
});
it("says that keyboard input and screen readers keep working", () => {
const markup = renderToStaticMarkup(<SignalNoticeContent headingLevel="h3" />);
expect(markup).toContain("Ввод с клавиатуры, чтение с экрана");
});
it("lists the browser signals and the server signals", () => {
const markup = renderToStaticMarkup(<SignalNoticeContent headingLevel="h3" />);
expect(markup).toContain("Смена вкладки или окна");
@@ -1,6 +1,7 @@
import { useEffect, useRef } from "react";
import { Button } from "../../../shared/ui";
import {
attemptMeasures,
browserSignals,
notCollected,
serverSignals,
@@ -37,6 +38,8 @@ export function SignalNoticeContent({ headingLevel }: ContentProps) {
<Heading>Что фиксирует браузер</Heading>
<p>События сохраняются, только пока действует согласие C3.</p>
<SignalList signals={browserSignals} />
<Heading>Что ограничено во время теста</Heading>
<SignalList signals={attemptMeasures} />
<Heading>Что измеряет сервер</Heading>
<SignalList signals={serverSignals} />
<Heading>Что не собирается</Heading>
@@ -46,11 +49,11 @@ export function SignalNoticeContent({ headingLevel }: ContentProps) {
))}
</ul>
<p>
Адреса и токены сессий не хранятся: для них есть только односторонние отпечатки. Во время
теста сбор ничего не показывает и не блокирует: ввод, вставка и отправка ответов работают
как обычно. Браузерные сигналы легко исказить, а ложные срабатывания возможны, например при
случайном переключении окна, поэтому это только подсказка. Экспресс-тест сигналы не
собирает.
Адреса и токены сессий не хранятся: для них есть только односторонние отпечатки. Сбор
сигналов ничего не показывает. Ввод с клавиатуры, чтение с экрана и отправка ответов
работают как обычно. Браузерные сигналы легко исказить, а ложные срабатывания возможны,
например при случайном переключении окна, поэтому это только подсказка. Экспресс-тест
сигналы не собирает и не ограничивает.
</p>
<p>
Подтверждение хранится на сервере. Оно не заменяет согласие C3, которое управляется отдельно
@@ -126,7 +129,7 @@ export function SignalNoticeDialog({
{open ? (
<>
<h2 id="signal-notice-title" tabIndex={-1} className={styles.title}>
Перед началом: какие сигналы собираются
Перед началом: какие сигналы собираются и что ограничено
</h2>
<SignalNoticeContent headingLevel="h3" />
{errorMessage ? (
@@ -199,6 +199,15 @@
background: var(--color-surface);
}
.item:focus {
outline: none;
}
.item:focus-visible {
outline: var(--focus-ring-width) solid var(--color-focus-ring);
outline-offset: var(--focus-ring-offset);
}
.item-heading {
display: flex;
flex-wrap: wrap;
@@ -53,6 +53,11 @@ import {
submitPendingAnswerCommand,
} from "../../../features/answer-assessment";
import type { AnswerDraft, PendingAnswerCommand } from "../../../features/answer-assessment";
import {
FullscreenFallbackNotice,
ProtectedRegion,
useAttemptLockdown,
} from "../../../features/assessment-lockdown";
import {
SignalNoticeDialog,
shouldCollectSignals,
@@ -153,6 +158,12 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
}),
),
});
// A real attempt runs in fullscreen and hides the task when the candidate
// leaves the tab, the window, or fullscreen. The express run is not protected.
const lockdown = useAttemptLockdown({
applies: Boolean(attempt && collectsSignals && !isTerminal(attempt)),
running: workReady,
});
const [resumeBusy, setResumeBusy] = useState(false);
const [pendingResume, setPendingResume] = useState<{ key: string; version: number } | null>(null);
const [pendingAnswer, setPendingAnswer] = useState<PendingAnswerCommand | null>(null);
@@ -598,6 +609,10 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
/>
) : null}
{collectsSignals && !terminal ? (
<FullscreenFallbackNotice fallback={lockdown.fallback} />
) : null}
{resumedExpress && attempt.kind === "demo_express" && !terminal ? (
<Notice tone="info" title="Незавершенный экспресс-тест продолжен">
<p>
@@ -630,11 +645,16 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
<div className={attemptStyles.actions}>
<Button
isBusy={resumeBusy}
onClick={() =>
void (collectsSignals
? signalNotice.guard(() => void resumeWork())
: resumeWork())
}
onClick={() => {
if (!collectsSignals) {
void resumeWork();
return;
}
// Fullscreen is requested here, inside the click: the notice check below
// is asynchronous and the browser would no longer see a user gesture.
void lockdown.enter();
void signalNotice.guard(() => void resumeWork(), lockdown.leave);
}}
>
{resumeBusy
? "Проверяем попытку..."
@@ -667,19 +687,27 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
currentItem &&
!terminal &&
(!pendingAnswer || pendingAnswer.itemId === currentItem.id) ? (
<article className={attemptStyles.item} aria-labelledby="assessment-item-title">
<div className={attemptStyles["item-heading"]}>
<h3 id="assessment-item-title">Задание {currentItem.sequence}</h3>
<span className={attemptStyles["item-counter"]} aria-hidden="true">
<Mono strong>{String(currentItem.sequence).padStart(2, "0")}</Mono>
<span>/</span>
<Mono>{String(attempt.progress.max_items).padStart(2, "0")}</Mono>
</span>
<VisuallyHidden>
{`${currentItem.sequence} из ${attempt.progress.max_items}`}
</VisuallyHidden>
</div>
<p className={attemptStyles.prompt}>{currentItem.prompt}</p>
<ProtectedRegion
lockdown={collectsSignals ? lockdown : null}
className={attemptStyles.item}
headingId="assessment-item-title"
task={
<>
<div className={attemptStyles["item-heading"]}>
<h3 id="assessment-item-title">Задание {currentItem.sequence}</h3>
<span className={attemptStyles["item-counter"]} aria-hidden="true">
<Mono strong>{String(currentItem.sequence).padStart(2, "0")}</Mono>
<span>/</span>
<Mono>{String(attempt.progress.max_items).padStart(2, "0")}</Mono>
</span>
<VisuallyHidden>
{`${currentItem.sequence} из ${attempt.progress.max_items}`}
</VisuallyHidden>
</div>
<p className={attemptStyles.prompt}>{currentItem.prompt}</p>
</>
}
>
<AnswerForm
key={currentItem.id}
attemptId={attempt.id}
@@ -687,15 +715,16 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
isSaving={answerBusy}
retryable={Boolean(pendingAnswer && pendingAnswer.itemId === currentItem.id)}
errorMessage={answerError}
concealed={collectsSignals && lockdown.covered}
onSubmit={(draft) => void sendAnswer(draft)}
onRetry={() => void retryAnswer()}
/>
{answerNeedsReview ? (
{answerNeedsReview && !(collectsSignals && lockdown.covered) ? (
<p className={attemptStyles.info} role="status">
Черновик остался в форме. Проверьте его и отправьте для актуальной версии попытки.
</p>
) : null}
</article>
</ProtectedRegion>
) : null}
{workReady && practicePending && !currentItem && !pendingAnswerNeedsReplay ? (
@@ -293,9 +293,9 @@ export const getGetMyAssessmentSignalNoticeUrl = () => {
}
/**
* Requires the session cookie of a candidate account with a confirmed email; the candidate comes from the session. Returns the notice version that the server requires now and whether this candidate acknowledged it. The notice lists the signals that are collected during a real assessment attempt and states that images, sound, and clipboard contents are not collected. Client signals are the time away from the tab or window, copy, paste and cut with a size only, and exits from fullscreen mode. Server signals are the response time of each item measured by the server, a change of network address during the attempt, parallel sessions, and the comparison of answers to variants of the same task by candidates. The server stores for these only one-way keyed digests: it stores no network address, no session token, and no answer text. Client signals are stored only while the C3 consent is current. The client shows it before a real attempt starts and does not start the attempt until the notice is acknowledged.
* Requires the session cookie of a candidate account with a confirmed email; the candidate comes from the session. Returns the notice version that the server requires now and whether this candidate acknowledged it. The notice lists the signals that are collected during a real assessment attempt and states that images, sound, and clipboard contents are not collected. Client signals are the time away from the tab or window, copy, paste and cut with a size only, and exits from fullscreen mode. Server signals are the response time of each item measured by the server, a change of network address during the attempt, parallel sessions, and the comparison of answers to variants of the same task by candidates. The server stores for these only one-way keyed digests: it stores no network address, no session token, and no answer text. Client signals are stored only while the C3 consent is current. The notice also lists the measures that the page applies during a real attempt: fullscreen mode, hiding the task when the candidate leaves fullscreen, the tab, or the window, blocking copy, selection, the context menu, drag, and printing of the task text, and blocking paste into answer fields (paste into the practice code editor is allowed and recorded as a signal with a size only). A watermark on the task page is announced as planned. These measures are applied by the client and never change a score, a category, or a quota. The client shows the notice before a real attempt starts and does not start the attempt until the notice is acknowledged.
*
* The acknowledgement is stored on the server per account and notice version, so it survives a reload and a new browser. It is not a consent and never changes C3: the signal operation still requires a current C3 consent, and an unacknowledged notice does not make that operation fail. The demo_express training mode collects no signals and needs no acknowledgement.
* The acknowledgement is stored on the server per account and notice version, so it survives a reload and a new browser. An acknowledgement of an earlier version never counts for the current one: when the text gains a version, every candidate acknowledges it again. It is not a consent and never changes C3: the signal operation still requires a current C3 consent, and an unacknowledged notice does not make that operation fail. The demo_express training mode collects no signals and needs no acknowledgement.
*
* A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account or an unconfirmed email answers 403 forbidden.
* @summary Read whether the current candidate acknowledged the signal notice.