@pie-qti/assessment-player 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +1 -0
- package/BACKEND-INTEGRATION.md +620 -0
- package/CHANGELOG.md +11 -0
- package/EXTENSIBILITY.md +551 -0
- package/README.md +1137 -0
- package/dist/core/AssessmentPlayer.d.ts +151 -0
- package/dist/core/AssessmentPlayer.d.ts.map +1 -0
- package/dist/core/AssessmentPlayer.js +595 -0
- package/dist/core/ItemSessionController.d.ts +119 -0
- package/dist/core/ItemSessionController.d.ts.map +1 -0
- package/dist/core/ItemSessionController.js +227 -0
- package/dist/core/NavigationManager.d.ts +59 -0
- package/dist/core/NavigationManager.d.ts.map +1 -0
- package/dist/core/NavigationManager.js +104 -0
- package/dist/core/StatePersistenceManager.d.ts +126 -0
- package/dist/core/StatePersistenceManager.d.ts.map +1 -0
- package/dist/core/StatePersistenceManager.js +267 -0
- package/dist/core/TimeManager.d.ts +123 -0
- package/dist/core/TimeManager.d.ts.map +1 -0
- package/dist/core/TimeManager.js +217 -0
- package/dist/core/index.d.ts +10 -0
- package/dist/core/index.d.ts.map +1 -0
- package/dist/core/index.js +5 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +7 -0
- package/dist/integration/ReferenceBackendAdapter.d.ts +128 -0
- package/dist/integration/ReferenceBackendAdapter.d.ts.map +1 -0
- package/dist/integration/ReferenceBackendAdapter.js +735 -0
- package/dist/integration/api-contract.d.ts +319 -0
- package/dist/integration/api-contract.d.ts.map +1 -0
- package/dist/integration/api-contract.js +19 -0
- package/dist/integration/index.d.ts +47 -0
- package/dist/integration/index.d.ts.map +1 -0
- package/dist/integration/index.js +46 -0
- package/dist/types/index.d.ts +51 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/index.js +7 -0
- package/dist/utils/PerformanceMonitor.d.ts +115 -0
- package/dist/utils/PerformanceMonitor.d.ts.map +1 -0
- package/dist/utils/PerformanceMonitor.js +171 -0
- package/package.json +82 -0
- package/src/ambient.d.ts +55 -0
- package/src/components/AccessibilityAnnouncer.svelte +102 -0
- package/src/components/AssessmentHeader.svelte +76 -0
- package/src/components/AssessmentShell.svelte +485 -0
- package/src/components/AssessmentTimer.svelte +228 -0
- package/src/components/ItemRenderer.svelte +147 -0
- package/src/components/ItemSessionInfo.svelte +241 -0
- package/src/components/NavigationBar.svelte +142 -0
- package/src/components/RubricDisplay.svelte +185 -0
- package/src/components/SectionMenu.svelte +206 -0
- package/src/components/SplitPaneResizer.svelte +288 -0
- package/src/components/TestFeedback.svelte +147 -0
- package/src/components/index.ts +19 -0
- package/src/core/AssessmentPlayer.ts +720 -0
- package/src/core/ItemSessionController.ts +287 -0
- package/src/core/NavigationManager.ts +126 -0
- package/src/core/StatePersistenceManager.ts +344 -0
- package/src/core/TimeManager.ts +289 -0
- package/src/core/index.ts +15 -0
- package/src/index.ts +13 -0
- package/src/integration/ReferenceBackendAdapter.ts +861 -0
- package/src/integration/api-contract.ts +377 -0
- package/src/integration/index.ts +70 -0
- package/src/svelte-shims.d.ts +7 -0
- package/src/types/index.ts +56 -0
- package/src/utils/PerformanceMonitor.ts +222 -0
- package/svelte.config.js +8 -0
- package/tests/ReferenceBackendAdapter.spec.ts +309 -0
- package/tests/setup.ts +103 -0
- package/tests/smoke.test.ts +7 -0
- package/tsconfig.json +20 -0
- package/tsconfig.svelte.json +10 -0
|
@@ -0,0 +1,720 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AssessmentPlayer (backend-authoritative)
|
|
3
|
+
*
|
|
4
|
+
* Client responsibilities:
|
|
5
|
+
* - Render items using @pie-qti/item-player
|
|
6
|
+
* - Collect candidate responses
|
|
7
|
+
* - Submit responses to BackendAdapter
|
|
8
|
+
* - Apply backend navigation decisions + session state
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { QTIRole } from '@pie-qti/item-player';
|
|
12
|
+
import { Player } from '@pie-qti/item-player';
|
|
13
|
+
import type {
|
|
14
|
+
BackendAdapter,
|
|
15
|
+
FinalizeAssessmentResponse,
|
|
16
|
+
InitSessionRequest,
|
|
17
|
+
InitSessionResponse,
|
|
18
|
+
ScoringResult,
|
|
19
|
+
SecureAssessment,
|
|
20
|
+
SecureItemRef,
|
|
21
|
+
SecureSection,
|
|
22
|
+
SecureTestPart,
|
|
23
|
+
SessionId,
|
|
24
|
+
SessionState,
|
|
25
|
+
} from '../integration/api-contract.js';
|
|
26
|
+
import type {
|
|
27
|
+
AssessmentResults,
|
|
28
|
+
ItemResult,
|
|
29
|
+
NavigationState,
|
|
30
|
+
} from '../types/index.js';
|
|
31
|
+
import { ItemSessionController } from './ItemSessionController.js';
|
|
32
|
+
import { NavigationManager } from './NavigationManager.js';
|
|
33
|
+
import { TimeManager } from './TimeManager.js';
|
|
34
|
+
|
|
35
|
+
export interface BackendAssessmentPlayerConfig {
|
|
36
|
+
backend: BackendAdapter;
|
|
37
|
+
initSession: InitSessionRequest;
|
|
38
|
+
role?: QTIRole;
|
|
39
|
+
/**
|
|
40
|
+
* Optional hint for item renderers that support multiple extended text editors.
|
|
41
|
+
* (Plumbed through the shell; the item player remains authoritative for behavior.)
|
|
42
|
+
*/
|
|
43
|
+
extendedTextEditor?: string;
|
|
44
|
+
/**
|
|
45
|
+
* Optional i18n provider for internationalization.
|
|
46
|
+
* If provided, this will be shared across all item players in the assessment.
|
|
47
|
+
*/
|
|
48
|
+
i18nProvider?: any; // Will be I18nProvider from @pie-qti/i18n
|
|
49
|
+
/**
|
|
50
|
+
* Security configuration for URL policy and content restrictions.
|
|
51
|
+
* If provided, this will be passed to all item players in the assessment.
|
|
52
|
+
*/
|
|
53
|
+
security?: any; // Will be PlayerSecurityConfig from @pie-qti/item-player
|
|
54
|
+
// UI options
|
|
55
|
+
showSections?: boolean;
|
|
56
|
+
allowSectionNavigation?: boolean;
|
|
57
|
+
showProgress?: boolean;
|
|
58
|
+
// Time management
|
|
59
|
+
timeWarningThreshold?: number;
|
|
60
|
+
// Callbacks
|
|
61
|
+
onItemChange?: (itemIndex: number, totalItems: number) => void;
|
|
62
|
+
onSectionChange?: (sectionIndex: number, totalSections: number) => void;
|
|
63
|
+
onResponseChange?: (responses: Record<string, unknown>) => void;
|
|
64
|
+
onComplete?: () => void;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
type FlatQuestion = {
|
|
68
|
+
identifier: string;
|
|
69
|
+
item: SecureItemRef;
|
|
70
|
+
section: SecureSection;
|
|
71
|
+
testPart: SecureTestPart;
|
|
72
|
+
index: number;
|
|
73
|
+
sectionIndex: number;
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
export class AssessmentPlayer {
|
|
77
|
+
public static async create(config: BackendAssessmentPlayerConfig): Promise<AssessmentPlayer> {
|
|
78
|
+
const init = await config.backend.initSession(config.initSession);
|
|
79
|
+
return new AssessmentPlayer(config, init);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
private backend: BackendAdapter;
|
|
83
|
+
private sessionId: SessionId;
|
|
84
|
+
private assessment: SecureAssessment;
|
|
85
|
+
private state: SessionState;
|
|
86
|
+
private i18nProvider: any; // I18nProvider from @pie-qti/i18n
|
|
87
|
+
|
|
88
|
+
private navigationManager: NavigationManager;
|
|
89
|
+
private sessionController: ItemSessionController;
|
|
90
|
+
private timeManager: TimeManager | null = null;
|
|
91
|
+
|
|
92
|
+
private questions: FlatQuestion[] = [];
|
|
93
|
+
private currentItemIndex = -1;
|
|
94
|
+
private currentItemPlayer: Player | null = null;
|
|
95
|
+
private responses: Record<string, unknown> = {};
|
|
96
|
+
private itemResults: Map<string, ItemResult> = new Map();
|
|
97
|
+
private visibleFeedback: Array<{ identifier: string; content: string; access: string }> = [];
|
|
98
|
+
|
|
99
|
+
// Event listeners
|
|
100
|
+
private itemChangeListeners = new Set<(index: number, total: number) => void>();
|
|
101
|
+
private sectionChangeListeners = new Set<(index: number, total: number) => void>();
|
|
102
|
+
private responseChangeListeners = new Set<(responses: Record<string, unknown>) => void>();
|
|
103
|
+
private completeListeners = new Set<() => void>();
|
|
104
|
+
private timeWarningListeners = new Set<(remainingSeconds: number) => void>();
|
|
105
|
+
private timeExpiredListeners = new Set<() => void>();
|
|
106
|
+
private timeTickListeners = new Set<(remainingSeconds: number, elapsedSeconds: number) => void>();
|
|
107
|
+
|
|
108
|
+
private constructor(private config: BackendAssessmentPlayerConfig, init: InitSessionResponse) {
|
|
109
|
+
this.backend = config.backend;
|
|
110
|
+
this.sessionId = init.sessionId;
|
|
111
|
+
this.assessment = init.assessment;
|
|
112
|
+
this.i18nProvider = config.i18nProvider ?? this.createDefaultI18nProvider();
|
|
113
|
+
this.state =
|
|
114
|
+
init.restoredState ??
|
|
115
|
+
({
|
|
116
|
+
currentItemIdentifier: '',
|
|
117
|
+
visitedItems: [],
|
|
118
|
+
itemResponses: {},
|
|
119
|
+
itemScores: {},
|
|
120
|
+
timing: { startedAt: Date.now(), itemTimes: {}, totalTime: 0 },
|
|
121
|
+
} as SessionState);
|
|
122
|
+
|
|
123
|
+
this.questions = this.flattenQuestions(this.assessment);
|
|
124
|
+
|
|
125
|
+
const navigationMode = this.assessment.navigationMode || 'nonlinear';
|
|
126
|
+
this.navigationManager = new NavigationManager(navigationMode, this.questions.length);
|
|
127
|
+
|
|
128
|
+
// Item session control is a UI hint; backend remains authoritative.
|
|
129
|
+
const itemSessionControl = this.assessment.testParts?.[0]?.itemSessionControl;
|
|
130
|
+
this.sessionController = new ItemSessionController(itemSessionControl);
|
|
131
|
+
|
|
132
|
+
// Initialize per-item session state so itemSessionControl checks work immediately.
|
|
133
|
+
for (const q of this.questions) {
|
|
134
|
+
this.sessionController.initializeItem(q.identifier);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// Initialize time manager if time limits exist
|
|
138
|
+
if (this.assessment.timeLimits?.maxTime) {
|
|
139
|
+
this.timeManager = new TimeManager({
|
|
140
|
+
assessmentTimeLimits: this.assessment.timeLimits,
|
|
141
|
+
warningThreshold: config.timeWarningThreshold || 60,
|
|
142
|
+
onWarning: (remainingSeconds) => this.notifyTimeWarning(remainingSeconds),
|
|
143
|
+
onExpired: () => this.notifyTimeExpired(),
|
|
144
|
+
onTick: (remainingSeconds, elapsedSeconds) => this.notifyTimeTick(remainingSeconds, elapsedSeconds),
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// Restore to backend-provided current item if present
|
|
149
|
+
const startId = this.state.currentItemIdentifier;
|
|
150
|
+
const idx = startId ? this.questions.findIndex((q) => q.identifier === startId) : -1;
|
|
151
|
+
if (idx >= 0) {
|
|
152
|
+
this.navigateTo(idx).catch(() => {});
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
private hasAnyResponse(responses: Record<string, unknown>): boolean {
|
|
157
|
+
for (const v of Object.values(responses)) {
|
|
158
|
+
if (v == null) continue;
|
|
159
|
+
if (Array.isArray(v)) {
|
|
160
|
+
if (v.length > 0) return true;
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
if (typeof v === 'string') {
|
|
164
|
+
if (v.trim().length > 0) return true;
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
// object / number / boolean etc.
|
|
168
|
+
return true;
|
|
169
|
+
}
|
|
170
|
+
return false;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
private flattenQuestions(assessment: SecureAssessment): FlatQuestion[] {
|
|
174
|
+
const out: FlatQuestion[] = [];
|
|
175
|
+
const testParts = assessment.testParts || [];
|
|
176
|
+
let idx = 0;
|
|
177
|
+
let secIdx = 0;
|
|
178
|
+
|
|
179
|
+
for (const tp of testParts) {
|
|
180
|
+
for (const section of tp.sections || []) {
|
|
181
|
+
for (const item of section.items || []) {
|
|
182
|
+
out.push({
|
|
183
|
+
identifier: item.identifier,
|
|
184
|
+
item,
|
|
185
|
+
section,
|
|
186
|
+
testPart: tp,
|
|
187
|
+
index: idx++,
|
|
188
|
+
sectionIndex: secIdx,
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
secIdx++;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
return out;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// ---------------------------------------------------------------------------
|
|
198
|
+
// Public API used by components
|
|
199
|
+
// ---------------------------------------------------------------------------
|
|
200
|
+
|
|
201
|
+
public getAllSections(): Array<{ id: string; title?: string; visible: boolean; index: number }> {
|
|
202
|
+
const out: Array<{ id: string; title?: string; visible: boolean; index: number }> = [];
|
|
203
|
+
let idx = 0;
|
|
204
|
+
for (const tp of this.assessment.testParts || []) {
|
|
205
|
+
for (const s of tp.sections || []) {
|
|
206
|
+
out.push({ id: s.identifier, title: s.title, visible: s.visible, index: idx++ });
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
return out;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
public getNavigationState(): NavigationState {
|
|
213
|
+
const total = this.questions.length;
|
|
214
|
+
const canPrevious = this.canPrevious();
|
|
215
|
+
const canNext = this.canNext();
|
|
216
|
+
const q = this.questions[this.currentItemIndex];
|
|
217
|
+
const totalSections = this.getAllSections().length;
|
|
218
|
+
return {
|
|
219
|
+
currentIndex: this.currentItemIndex,
|
|
220
|
+
totalItems: total,
|
|
221
|
+
canNext,
|
|
222
|
+
canPrevious,
|
|
223
|
+
isLoading: false,
|
|
224
|
+
currentSection: q
|
|
225
|
+
? { id: q.section.identifier, title: q.section.title, index: q.sectionIndex }
|
|
226
|
+
: undefined,
|
|
227
|
+
totalSections,
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
public getCurrentQuestion(): any | null {
|
|
232
|
+
const q = this.questions[this.currentItemIndex];
|
|
233
|
+
if (!q) return null;
|
|
234
|
+
// Keep the legacy QuestionRef-ish shape expected by ItemRenderer.svelte
|
|
235
|
+
return {
|
|
236
|
+
identifier: q.item.identifier,
|
|
237
|
+
title: q.section.title,
|
|
238
|
+
required: q.item.required,
|
|
239
|
+
itemXml: q.item.itemXml,
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
public getCurrentRubricBlocks(): any[] {
|
|
244
|
+
const q = this.questions[this.currentItemIndex];
|
|
245
|
+
if (!q) return [];
|
|
246
|
+
return q.section.rubrics || q.testPart.rubrics || [];
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
public getVisibleFeedback(): Array<{ identifier: string; content: string; access: string }> {
|
|
250
|
+
return this.visibleFeedback;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
public updateResponse(responseId: string, value: unknown): void {
|
|
254
|
+
this.responses = { ...this.responses, [responseId]: value };
|
|
255
|
+
const q = this.questions[this.currentItemIndex];
|
|
256
|
+
if (q) {
|
|
257
|
+
this.state.itemResponses[q.identifier] = this.responses as any;
|
|
258
|
+
this.sessionController.markAnswered(q.identifier, this.hasAnyResponse(this.responses));
|
|
259
|
+
}
|
|
260
|
+
this.notifyResponseChange();
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Update a response for a specific item.
|
|
265
|
+
* Useful when response events are observed outside the current-item renderer and we
|
|
266
|
+
* want to be explicit about which item receives the response (some assessments reuse
|
|
267
|
+
* the same responseIdentifier like "RESPONSE" across items).
|
|
268
|
+
*/
|
|
269
|
+
public updateResponseForItem(itemIdentifier: string, responseId: string, value: unknown): void {
|
|
270
|
+
const prev = (this.state.itemResponses?.[itemIdentifier] || {}) as Record<string, unknown>;
|
|
271
|
+
const next = { ...prev, [responseId]: value };
|
|
272
|
+
this.state.itemResponses[itemIdentifier] = next as any;
|
|
273
|
+
|
|
274
|
+
// If this is the active item, keep the live response state + UI hints in sync.
|
|
275
|
+
const active = this.questions[this.currentItemIndex];
|
|
276
|
+
if (active?.identifier === itemIdentifier) {
|
|
277
|
+
this.responses = next;
|
|
278
|
+
this.sessionController.markAnswered(itemIdentifier, this.hasAnyResponse(this.responses));
|
|
279
|
+
this.currentItemPlayer?.setResponses(this.responses as any);
|
|
280
|
+
this.notifyResponseChange();
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* Get current unsaved responses for the active item.
|
|
286
|
+
* (Useful for host integrations / web components.)
|
|
287
|
+
*/
|
|
288
|
+
public getResponses(): Record<string, unknown> {
|
|
289
|
+
return { ...this.responses };
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Get the current session state snapshot (client-side view).
|
|
294
|
+
* Note: backend remains authoritative; this is intended for simple save/resume.
|
|
295
|
+
*/
|
|
296
|
+
public getState(): SessionState {
|
|
297
|
+
// Shallow clone to avoid accidental external mutation.
|
|
298
|
+
return {
|
|
299
|
+
...this.state,
|
|
300
|
+
visitedItems: [...this.state.visitedItems],
|
|
301
|
+
itemResponses: { ...this.state.itemResponses },
|
|
302
|
+
itemScores: this.state.itemScores ? { ...this.state.itemScores } : undefined,
|
|
303
|
+
timing: {
|
|
304
|
+
...this.state.timing,
|
|
305
|
+
itemTimes: { ...this.state.timing.itemTimes },
|
|
306
|
+
},
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Restore a previously saved session state.
|
|
312
|
+
*/
|
|
313
|
+
public async restoreState(state: SessionState): Promise<void> {
|
|
314
|
+
this.state = state;
|
|
315
|
+
|
|
316
|
+
// Restore visited state for UI navigation hints.
|
|
317
|
+
const visitedIdx = (state.visitedItems || [])
|
|
318
|
+
.map((id) => this.questions.findIndex((q) => q.identifier === id))
|
|
319
|
+
.filter((i) => i >= 0);
|
|
320
|
+
this.navigationManager.restoreState(visitedIdx);
|
|
321
|
+
|
|
322
|
+
// Rehydrate itemResults from scores if present, so submit() can behave sensibly.
|
|
323
|
+
this.itemResults.clear();
|
|
324
|
+
if (state.itemScores) {
|
|
325
|
+
for (const [itemIdentifier, scoring] of Object.entries(state.itemScores)) {
|
|
326
|
+
this.itemResults.set(itemIdentifier, {
|
|
327
|
+
itemIdentifier,
|
|
328
|
+
score: scoring.score,
|
|
329
|
+
maxScore: scoring.maxScore,
|
|
330
|
+
responses: state.itemResponses?.[itemIdentifier] || {},
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
const currentId = state.currentItemIdentifier;
|
|
336
|
+
const idx = currentId ? this.questions.findIndex((q) => q.identifier === currentId) : -1;
|
|
337
|
+
if (idx >= 0) {
|
|
338
|
+
await this.navigateTo(idx);
|
|
339
|
+
} else if (this.questions.length > 0) {
|
|
340
|
+
await this.navigateTo(0);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
public async navigateTo(index: number): Promise<void> {
|
|
345
|
+
if (index < 0 || index >= this.questions.length) throw new Error(`Invalid item index: ${index}`);
|
|
346
|
+
|
|
347
|
+
// Enforce navigation rules (UI hints, still backend-authoritative for real deployments).
|
|
348
|
+
if (this.currentItemIndex >= 0 && !this.navigationManager.canNavigateTo(index, this.currentItemIndex)) {
|
|
349
|
+
if (this.navigationManager.getMode() === 'linear' && index > this.currentItemIndex + 1) {
|
|
350
|
+
throw new Error('In linear navigation mode, you can only move to the next question.');
|
|
351
|
+
}
|
|
352
|
+
throw new Error('Navigation is not allowed.');
|
|
353
|
+
}
|
|
354
|
+
const target = this.questions[index];
|
|
355
|
+
if (target && !this.sessionController.canReview(target.identifier)) {
|
|
356
|
+
throw new Error('You cannot go back to previous questions in this assessment.');
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
this.currentItemIndex = index;
|
|
360
|
+
const q = this.questions[index]!;
|
|
361
|
+
this.state.currentItemIdentifier = q.identifier;
|
|
362
|
+
|
|
363
|
+
// Restore responses
|
|
364
|
+
this.responses = { ...(this.state.itemResponses[q.identifier] || {}) };
|
|
365
|
+
|
|
366
|
+
// Create item player
|
|
367
|
+
this.currentItemPlayer = new Player({
|
|
368
|
+
itemXml: q.item.itemXml,
|
|
369
|
+
role: q.item.role,
|
|
370
|
+
i18nProvider: this.i18nProvider,
|
|
371
|
+
});
|
|
372
|
+
this.currentItemPlayer.setResponses(this.responses as any);
|
|
373
|
+
|
|
374
|
+
this.notifyItemChange();
|
|
375
|
+
this.notifySectionChange();
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
public async navigateToSection(sectionId: string): Promise<void> {
|
|
379
|
+
const idx = this.questions.findIndex((q) => q.section.identifier === sectionId);
|
|
380
|
+
if (idx >= 0) await this.navigateTo(idx);
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
public async next(): Promise<void> {
|
|
384
|
+
const state = this.getNavigationState();
|
|
385
|
+
if (!state.canNext) return;
|
|
386
|
+
|
|
387
|
+
const q = this.questions[this.currentItemIndex];
|
|
388
|
+
if (q) {
|
|
389
|
+
const hasResponses = this.hasAnyResponse(this.responses);
|
|
390
|
+
this.sessionController.markAnswered(q.identifier, hasResponses);
|
|
391
|
+
|
|
392
|
+
const navAway = this.sessionController.canNavigateAway(q.identifier, hasResponses);
|
|
393
|
+
if (!navAway.allowed) {
|
|
394
|
+
throw new Error(navAway.reason || 'You must answer this question before continuing.');
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
// In individual submission mode, submit current item before moving forward.
|
|
398
|
+
if (this.assessment.submissionMode === 'individual') {
|
|
399
|
+
const before = this.currentItemIndex;
|
|
400
|
+
await this.submitCurrentItem();
|
|
401
|
+
// submitCurrentItem may branch/navigate; if it did, we're done.
|
|
402
|
+
if (this.currentItemIndex !== before) return;
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
await this.navigateTo(this.currentItemIndex + 1);
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
public async previous(): Promise<void> {
|
|
410
|
+
const state = this.getNavigationState();
|
|
411
|
+
if (!state.canPrevious) return;
|
|
412
|
+
await this.navigateTo(this.currentItemIndex - 1);
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/** Submit current item (server-side scoring) */
|
|
416
|
+
public async submitCurrentItem(): Promise<ItemResult> {
|
|
417
|
+
const q = this.questions[this.currentItemIndex];
|
|
418
|
+
if (!q) throw new Error('No current item');
|
|
419
|
+
|
|
420
|
+
const submittedAt = Date.now();
|
|
421
|
+
const res = await this.backend.submitResponses({
|
|
422
|
+
sessionId: this.sessionId,
|
|
423
|
+
itemIdentifier: q.identifier,
|
|
424
|
+
responses: this.responses as any,
|
|
425
|
+
submittedAt,
|
|
426
|
+
});
|
|
427
|
+
|
|
428
|
+
if (!res.success || !res.result) {
|
|
429
|
+
throw new Error(res.error || 'Submit failed');
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
if (res.updatedState) {
|
|
433
|
+
this.state = res.updatedState;
|
|
434
|
+
} else {
|
|
435
|
+
// Minimal state update when backend doesn't return full state.
|
|
436
|
+
this.state.itemScores = this.state.itemScores || {};
|
|
437
|
+
this.state.itemScores[q.identifier] = res.result;
|
|
438
|
+
if (!this.state.visitedItems.includes(q.identifier)) this.state.visitedItems.push(q.identifier);
|
|
439
|
+
this.state.itemResponses[q.identifier] = this.responses as any;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
const itemResult: ItemResult = {
|
|
443
|
+
itemIdentifier: q.identifier,
|
|
444
|
+
score: res.result.score,
|
|
445
|
+
maxScore: res.result.maxScore,
|
|
446
|
+
responses: { ...this.responses },
|
|
447
|
+
};
|
|
448
|
+
this.itemResults.set(q.identifier, itemResult);
|
|
449
|
+
|
|
450
|
+
// Track item session rules (review/attempts) and visited items for navigation hints.
|
|
451
|
+
try {
|
|
452
|
+
this.sessionController.recordAttempt(q.identifier);
|
|
453
|
+
} catch {
|
|
454
|
+
// ignore
|
|
455
|
+
}
|
|
456
|
+
this.sessionController.markAnswered(q.identifier, this.hasAnyResponse(this.responses));
|
|
457
|
+
this.navigationManager.markVisited(this.currentItemIndex);
|
|
458
|
+
|
|
459
|
+
// Apply backend branching decision if provided
|
|
460
|
+
if (res.nextItemIdentifier) {
|
|
461
|
+
const nextIdx = this.questions.findIndex((x) => x.identifier === res.nextItemIdentifier);
|
|
462
|
+
if (nextIdx >= 0) {
|
|
463
|
+
await this.navigateTo(nextIdx);
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
return itemResult;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
private canPrevious(): boolean {
|
|
471
|
+
if (this.currentItemIndex <= 0) return false;
|
|
472
|
+
const prev = this.questions[this.currentItemIndex - 1];
|
|
473
|
+
if (!prev) return false;
|
|
474
|
+
if (!this.navigationManager.canNavigateTo(this.currentItemIndex - 1, this.currentItemIndex)) return false;
|
|
475
|
+
return this.sessionController.canReview(prev.identifier);
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
private canNext(): boolean {
|
|
479
|
+
if (this.currentItemIndex < 0) return false;
|
|
480
|
+
const nextIdx = this.currentItemIndex + 1;
|
|
481
|
+
if (nextIdx >= this.questions.length) return false;
|
|
482
|
+
if (!this.navigationManager.canNavigateTo(nextIdx, this.currentItemIndex)) return false;
|
|
483
|
+
// Note: itemSessionControl constraints on leaving current item are enforced in next().
|
|
484
|
+
return true;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/** Submit entire assessment (finalize on backend) */
|
|
488
|
+
public async submit(): Promise<AssessmentResults> {
|
|
489
|
+
// For simultaneous submission, ensure all items are submitted before finalize so
|
|
490
|
+
// the backend can compute a complete test score.
|
|
491
|
+
if (this.assessment.submissionMode === 'simultaneous') {
|
|
492
|
+
// Preserve client-collected responses across backend state updates.
|
|
493
|
+
// Some backend adapters return an updatedState snapshot that may only include
|
|
494
|
+
// responses for items that have been submitted so far, which would otherwise
|
|
495
|
+
// wipe out responses for later items during this loop.
|
|
496
|
+
const allItemResponses = { ...(this.state.itemResponses || {}) } as any;
|
|
497
|
+
|
|
498
|
+
for (const q of this.questions) {
|
|
499
|
+
if (this.itemResults.has(q.identifier)) continue;
|
|
500
|
+
const submittedAt = Date.now();
|
|
501
|
+
const responsesForItem = (allItemResponses?.[q.identifier] || {}) as any;
|
|
502
|
+
const res = await this.backend.submitResponses({
|
|
503
|
+
sessionId: this.sessionId,
|
|
504
|
+
itemIdentifier: q.identifier,
|
|
505
|
+
responses: responsesForItem,
|
|
506
|
+
submittedAt,
|
|
507
|
+
});
|
|
508
|
+
if (!res.success || !res.result) {
|
|
509
|
+
throw new Error(res.error || `Submit failed for item ${q.identifier}`);
|
|
510
|
+
}
|
|
511
|
+
if (res.updatedState) {
|
|
512
|
+
this.state = res.updatedState;
|
|
513
|
+
// Restore full response map captured on the client.
|
|
514
|
+
this.state.itemResponses = allItemResponses;
|
|
515
|
+
} else {
|
|
516
|
+
this.state.itemScores = this.state.itemScores || {};
|
|
517
|
+
this.state.itemScores[q.identifier] = res.result;
|
|
518
|
+
if (!this.state.visitedItems.includes(q.identifier)) this.state.visitedItems.push(q.identifier);
|
|
519
|
+
this.state.itemResponses[q.identifier] = responsesForItem;
|
|
520
|
+
}
|
|
521
|
+
this.itemResults.set(q.identifier, {
|
|
522
|
+
itemIdentifier: q.identifier,
|
|
523
|
+
score: res.result.score,
|
|
524
|
+
maxScore: res.result.maxScore,
|
|
525
|
+
responses: this.state.itemResponses[q.identifier] || {},
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
} else {
|
|
529
|
+
// Ensure current item is submitted (individual submission mode)
|
|
530
|
+
const q = this.questions[this.currentItemIndex];
|
|
531
|
+
if (q && !this.itemResults.has(q.identifier)) {
|
|
532
|
+
await this.submitCurrentItem();
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
const finalized: FinalizeAssessmentResponse = await this.backend.finalizeAssessment({
|
|
537
|
+
sessionId: this.sessionId,
|
|
538
|
+
});
|
|
539
|
+
if (!finalized.success) throw new Error('Finalize failed');
|
|
540
|
+
|
|
541
|
+
// Map backend itemScores to ItemResult[]
|
|
542
|
+
const itemScores = finalized.itemScores || {};
|
|
543
|
+
const itemResults: ItemResult[] = Object.values(itemScores).map((r: ScoringResult) => ({
|
|
544
|
+
itemIdentifier: r.itemIdentifier,
|
|
545
|
+
score: r.score,
|
|
546
|
+
maxScore: r.maxScore,
|
|
547
|
+
responses: this.state.itemResponses[r.itemIdentifier] || {},
|
|
548
|
+
}));
|
|
549
|
+
|
|
550
|
+
this.visibleFeedback = finalized.feedback
|
|
551
|
+
? [{ identifier: 'testFeedback', content: finalized.feedback, access: 'atEnd' }]
|
|
552
|
+
: [];
|
|
553
|
+
|
|
554
|
+
this.notifyComplete();
|
|
555
|
+
if (this.config.onComplete) this.config.onComplete();
|
|
556
|
+
|
|
557
|
+
return {
|
|
558
|
+
totalScore: finalized.totalScore,
|
|
559
|
+
maxScore: finalized.maxScore,
|
|
560
|
+
itemResults,
|
|
561
|
+
completedAt: new Date(finalized.finalizedAt),
|
|
562
|
+
};
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
// ---------------------------------------------------------------------------
|
|
566
|
+
// Session info + time helpers
|
|
567
|
+
// ---------------------------------------------------------------------------
|
|
568
|
+
|
|
569
|
+
public getItemSessionInfo(_itemIdentifier?: string): {
|
|
570
|
+
canSubmit: boolean;
|
|
571
|
+
remainingAttempts: number | null;
|
|
572
|
+
attemptCount: number;
|
|
573
|
+
showFeedback: boolean;
|
|
574
|
+
showSolution: boolean;
|
|
575
|
+
canReview: boolean;
|
|
576
|
+
canSkip: boolean;
|
|
577
|
+
} | null {
|
|
578
|
+
const q = this.questions[this.currentItemIndex];
|
|
579
|
+
if (!q) return null;
|
|
580
|
+
const id = q.identifier;
|
|
581
|
+
|
|
582
|
+
const state = this.sessionController.getItemState(id);
|
|
583
|
+
if (!state) {
|
|
584
|
+
this.sessionController.initializeItem(id);
|
|
585
|
+
}
|
|
586
|
+
const st = this.sessionController.getItemState(id);
|
|
587
|
+
return {
|
|
588
|
+
canSubmit: this.sessionController.canSubmit(id),
|
|
589
|
+
remainingAttempts: this.sessionController.getRemainingAttempts(id),
|
|
590
|
+
attemptCount: st?.attemptCount ?? 0,
|
|
591
|
+
showFeedback: this.sessionController.shouldShowFeedback(id),
|
|
592
|
+
showSolution: this.sessionController.shouldShowSolution(id),
|
|
593
|
+
canReview: this.sessionController.canReview(id),
|
|
594
|
+
canSkip: this.sessionController.canSkip(id),
|
|
595
|
+
};
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
public getRemainingTime(): number {
|
|
599
|
+
// TimeManager exposes seconds getters.
|
|
600
|
+
return this.timeManager?.getRemainingSeconds() ?? 0;
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
public getElapsedTime(): number {
|
|
604
|
+
return this.timeManager?.getElapsedSeconds() ?? 0;
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
public isTimeExpired(): boolean {
|
|
608
|
+
return this.timeManager?.isExpired() ?? false;
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
// ---------------------------------------------------------------------------
|
|
612
|
+
// Event subscriptions
|
|
613
|
+
// ---------------------------------------------------------------------------
|
|
614
|
+
|
|
615
|
+
public onItemChange(listener: (index: number, total: number) => void): () => void {
|
|
616
|
+
this.itemChangeListeners.add(listener);
|
|
617
|
+
return () => this.itemChangeListeners.delete(listener);
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
public onSectionChange(listener: (index: number, total: number) => void): () => void {
|
|
621
|
+
this.sectionChangeListeners.add(listener);
|
|
622
|
+
return () => this.sectionChangeListeners.delete(listener);
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
public onResponseChange(listener: (responses: Record<string, unknown>) => void): () => void {
|
|
626
|
+
this.responseChangeListeners.add(listener);
|
|
627
|
+
return () => this.responseChangeListeners.delete(listener);
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
public onComplete(listener: () => void): () => void {
|
|
631
|
+
this.completeListeners.add(listener);
|
|
632
|
+
return () => this.completeListeners.delete(listener);
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
public onTimeWarning(listener: (remainingSeconds: number) => void): () => void {
|
|
636
|
+
this.timeWarningListeners.add(listener);
|
|
637
|
+
return () => this.timeWarningListeners.delete(listener);
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
public onTimeExpired(listener: () => void): () => void {
|
|
641
|
+
this.timeExpiredListeners.add(listener);
|
|
642
|
+
return () => this.timeExpiredListeners.delete(listener);
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
public onTimeTick(listener: (remainingSeconds: number, elapsedSeconds: number) => void): () => void {
|
|
646
|
+
this.timeTickListeners.add(listener);
|
|
647
|
+
return () => this.timeTickListeners.delete(listener);
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
public destroy(): void {
|
|
651
|
+
this.itemChangeListeners.clear();
|
|
652
|
+
this.sectionChangeListeners.clear();
|
|
653
|
+
this.responseChangeListeners.clear();
|
|
654
|
+
this.completeListeners.clear();
|
|
655
|
+
this.timeWarningListeners.clear();
|
|
656
|
+
this.timeExpiredListeners.clear();
|
|
657
|
+
this.timeTickListeners.clear();
|
|
658
|
+
this.currentItemPlayer = null;
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
// ---------------------------------------------------------------------------
|
|
662
|
+
// Internal notify helpers
|
|
663
|
+
// ---------------------------------------------------------------------------
|
|
664
|
+
|
|
665
|
+
private notifyItemChange(): void {
|
|
666
|
+
for (const l of this.itemChangeListeners) l(this.currentItemIndex, this.questions.length);
|
|
667
|
+
this.config.onItemChange?.(this.currentItemIndex, this.questions.length);
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
private notifySectionChange(): void {
|
|
671
|
+
const q = this.questions[this.currentItemIndex];
|
|
672
|
+
const sectionIndex = q?.sectionIndex ?? 0;
|
|
673
|
+
const totalSections = this.getAllSections().length;
|
|
674
|
+
for (const l of this.sectionChangeListeners) l(sectionIndex, totalSections);
|
|
675
|
+
this.config.onSectionChange?.(sectionIndex, totalSections);
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
private notifyResponseChange(): void {
|
|
679
|
+
for (const l of this.responseChangeListeners) l(this.responses);
|
|
680
|
+
this.config.onResponseChange?.(this.responses);
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
private notifyComplete(): void {
|
|
684
|
+
for (const l of this.completeListeners) l();
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
private notifyTimeWarning(remainingSeconds: number): void {
|
|
688
|
+
for (const l of this.timeWarningListeners) l(remainingSeconds);
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
private notifyTimeExpired(): void {
|
|
692
|
+
for (const l of this.timeExpiredListeners) l();
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
private notifyTimeTick(remainingSeconds: number, elapsedSeconds: number): void {
|
|
696
|
+
for (const l of this.timeTickListeners) l(remainingSeconds, elapsedSeconds);
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
/**
|
|
700
|
+
* Get the i18n provider instance
|
|
701
|
+
* @returns I18nProvider instance
|
|
702
|
+
*/
|
|
703
|
+
public getI18nProvider(): any {
|
|
704
|
+
return this.i18nProvider;
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
/**
|
|
708
|
+
* Create a simple fallback i18n provider when none is provided
|
|
709
|
+
*/
|
|
710
|
+
private createDefaultI18nProvider(): any {
|
|
711
|
+
return {
|
|
712
|
+
getLocale: () => 'en-US',
|
|
713
|
+
setLocale: () => {},
|
|
714
|
+
t: (key: string) => key, // Fallback to key
|
|
715
|
+
plural: (key: string) => key,
|
|
716
|
+
formatNumber: (value: number) => value.toString(),
|
|
717
|
+
formatDate: (date: Date) => date.toISOString(),
|
|
718
|
+
};
|
|
719
|
+
}
|
|
720
|
+
}
|