@pie-qti/assessment-player 0.1.28 → 1.0.0-beta.0

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.
Files changed (34) hide show
  1. package/README.md +13 -0
  2. package/dist/core/AssessmentPlayer.d.ts +54 -14
  3. package/dist/core/AssessmentPlayer.js +204 -166
  4. package/dist/core/AssessmentPlayer.js.map +1 -1
  5. package/dist/core/AssessmentSessionCoordinator.d.ts +10 -2
  6. package/dist/core/AssessmentSessionCoordinator.js +24 -3
  7. package/dist/core/AssessmentSessionCoordinator.js.map +1 -1
  8. package/dist/core/ItemSessionController.d.ts +14 -3
  9. package/dist/core/ItemSessionController.js +31 -12
  10. package/dist/core/ItemSessionController.js.map +1 -1
  11. package/dist/core/TimeManager.d.ts +20 -7
  12. package/dist/core/TimeManager.js +20 -18
  13. package/dist/core/TimeManager.js.map +1 -1
  14. package/dist/core/testStructure.d.ts +65 -0
  15. package/dist/core/testStructure.js +336 -0
  16. package/dist/core/testStructure.js.map +1 -0
  17. package/dist/index.d.ts +2 -1
  18. package/dist/index.js +2 -0
  19. package/dist/index.js.map +1 -1
  20. package/dist/integration/ReferenceBackendAdapter.d.ts +53 -5
  21. package/dist/integration/ReferenceBackendAdapter.js +317 -230
  22. package/dist/integration/ReferenceBackendAdapter.js.map +1 -1
  23. package/dist/integration/api-contract.d.ts +92 -49
  24. package/dist/integration/api-contract.js.map +1 -1
  25. package/dist/integration/assessment-item-scorer.d.ts +11 -1
  26. package/dist/integration/assessment-item-scorer.js +102 -12
  27. package/dist/integration/assessment-item-scorer.js.map +1 -1
  28. package/dist/integration/index.d.ts +1 -1
  29. package/dist/integration/index.js.map +1 -1
  30. package/dist/integration/toSectionComposition.js +1 -0
  31. package/dist/integration/toSectionComposition.js.map +1 -1
  32. package/dist/types/index.d.ts +10 -0
  33. package/dist/types/index.js.map +1 -1
  34. package/package.json +10 -10
@@ -8,9 +8,11 @@
8
8
  * - Apply backend navigation decisions + session state
9
9
  */
10
10
  import { createAssessmentItemDefinition, } from '@pie-qti/item-player';
11
+ import { isShownByIdentifier } from '@pie-qti/qti-common';
11
12
  import { AssessmentSessionCoordinator } from './AssessmentSessionCoordinator.js';
12
13
  import { NavigationManager } from './NavigationManager.js';
13
- import { TimeManager } from './TimeManager.js';
14
+ import { deliveredItems, evaluateTestExpression, isAdaptiveItemXml, plainQtiValue, resolveItemSessionControl, sectionComponents, testOutcomeDeclarations, } from './testStructure.js';
15
+ import { extendTimeLimit, TimeManager } from './TimeManager.js';
14
16
  export class AssessmentPlayer {
15
17
  static async create(config) {
16
18
  const init = await config.backend.initSession(config.initSession);
@@ -24,22 +26,28 @@ export class AssessmentPlayer {
24
26
  this.itemDefinitions = new Map();
25
27
  this.currentItemSession = null;
26
28
  this.currentItemSessionUnsubscribe = null;
27
- this.visibleFeedback = [];
29
+ /** Test-level outcomes from the last outcome processing; null until it first runs. */
30
+ this.testOutcomes = null;
31
+ this.finalized = false;
32
+ /** Scopes whose time limit expired without late submission, keyed `scope:identifier`. */
33
+ this.lockedScopes = new Set();
28
34
  // Event listeners
29
35
  this.itemChangeListeners = new Set();
30
36
  this.sectionChangeListeners = new Set();
31
37
  this.responseChangeListeners = new Set();
32
38
  this.completeListeners = new Set();
39
+ this.testFeedbackChangeListeners = new Set();
33
40
  this.timeWarningListeners = new Set();
34
41
  this.timeExpiredListeners = new Set();
35
42
  this.timeTickListeners = new Set();
36
43
  this.backend = config.backend;
37
44
  this.sessionId = init.sessionId;
38
45
  this.assessment = init.assessment;
46
+ this.testOutcomes = init.outcomes ? cloneData(init.outcomes) : null;
39
47
  this.i18nProvider = config.i18nProvider ?? this.createDefaultI18nProvider();
40
48
  const initialState = init.restoredState ??
41
49
  {
42
- currentItemIdentifier: '',
50
+ currentItemIdentifier: init.currentItemIdentifier ?? '',
43
51
  visitedItems: [],
44
52
  itemResponses: {},
45
53
  itemScores: {},
@@ -50,19 +58,19 @@ export class AssessmentPlayer {
50
58
  const navigationMode = this.assessment.navigationMode || 'nonlinear';
51
59
  this.navigationManager = new NavigationManager(navigationMode, this.items.length);
52
60
  // Item session control is a UI hint; backend remains authoritative.
53
- // Start with testPart-level defaults; section-level overrides are applied per item in navigateTo().
54
- const itemSessionControl = this.assessment.testParts?.[0]?.itemSessionControl;
55
61
  this.sessionCoordinator = new AssessmentSessionCoordinator({
56
62
  state: initialState,
57
63
  itemIdentifiers: this.items.map((q) => q.identifier),
58
- itemSessionControl,
64
+ itemSessionControlByItem: Object.fromEntries(this.items.map((q) => [q.identifier, resolveItemSessionControl(q.testPart, q.sections, q.item)])),
59
65
  });
60
66
  this.timeManager = new TimeManager({
61
67
  assessmentTimeLimits: this.assessment.timeLimits,
62
68
  warningThreshold: config.timeWarningThreshold || 60,
69
+ now: config.now,
63
70
  extendedTime: config.pnp?.content?.extendedTime,
64
71
  onWarning: (remainingSeconds) => this.notifyTimeWarning(remainingSeconds),
65
72
  onExpired: () => this.notifyTimeExpired(),
73
+ onScopeExpired: (scope, identifier) => this.handleScopeExpired(scope, identifier),
66
74
  onTick: (remainingSeconds, elapsedSeconds) => this.notifyTimeTick(remainingSeconds, elapsedSeconds),
67
75
  });
68
76
  if (init.restoredState?.timing) {
@@ -84,28 +92,6 @@ export class AssessmentPlayer {
84
92
  set state(state) {
85
93
  this.sessionCoordinator.restoreState(state);
86
94
  }
87
- /**
88
- * Compute effective itemSessionControl for a given item using three-level fallback:
89
- * section-level (highest priority) → testPart-level → defaults.
90
- * Section-level values override testPart-level when present.
91
- */
92
- getEffectiveItemSessionControl(flat) {
93
- const testPartControl = flat.testPart.itemSessionControl;
94
- const sectionControl = flat.section.itemSessionControl;
95
- if (!sectionControl)
96
- return testPartControl;
97
- if (!testPartControl)
98
- return sectionControl;
99
- return {
100
- maxAttempts: sectionControl.maxAttempts ?? testPartControl.maxAttempts,
101
- showFeedback: sectionControl.showFeedback ?? testPartControl.showFeedback,
102
- allowReview: sectionControl.allowReview ?? testPartControl.allowReview,
103
- showSolution: sectionControl.showSolution ?? testPartControl.showSolution,
104
- allowComment: sectionControl.allowComment ?? testPartControl.allowComment,
105
- allowSkipping: sectionControl.allowSkipping ?? testPartControl.allowSkipping,
106
- validateResponses: sectionControl.validateResponses ?? testPartControl.validateResponses,
107
- };
108
- }
109
95
  getEffectiveItemTimeLimits(flat) {
110
96
  const scopes = [
111
97
  { source: 'assessment', limits: this.assessment.timeLimits },
@@ -124,12 +110,7 @@ export class AssessmentPlayer {
124
110
  minTime = minTime === undefined ? scope.limits.minTime : Math.max(minTime, scope.limits.minTime);
125
111
  }
126
112
  if (scope.limits.maxTime !== undefined) {
127
- const extended = this.config.pnp?.content?.extendedTime;
128
- const scopedMaxTime = extended?.active
129
- ? extended.multiplier === Infinity
130
- ? undefined
131
- : scope.limits.maxTime * extended.multiplier
132
- : scope.limits.maxTime;
113
+ const scopedMaxTime = extendTimeLimit(scope.limits.maxTime, this.config.pnp?.content?.extendedTime);
133
114
  if (scopedMaxTime !== undefined && (maxTime === undefined || scopedMaxTime < maxTime)) {
134
115
  maxTime = scopedMaxTime;
135
116
  source = scope.source;
@@ -199,80 +180,42 @@ export class AssessmentPlayer {
199
180
  if (current === target)
200
181
  return;
201
182
  this.assertMinimumTime('item', current);
202
- if (current.section !== target.section)
183
+ if (current.section.identifier !== target.section.identifier)
203
184
  this.assertMinimumTime('section', current);
204
185
  if (current.testPart !== target.testPart)
205
186
  this.assertMinimumTime('testPart', current);
206
187
  }
207
188
  flattenItems(assessment) {
208
- const out = [];
209
- const testParts = assessment.testParts || [];
210
- let idx = 0;
211
- let secIdx = 0;
212
- const rng = this.config.rng ?? Math.random;
213
- const visitSection = (section, tp) => {
214
- const currentSectionIndex = secIdx++;
215
- let components = section.children
216
- ? [...section.children]
217
- : [
218
- ...(section.assessmentItemRefs ?? []).map((item) => ({ type: 'item', item })),
219
- ...(section.sections ?? []).map((child) => ({ type: 'section', section: child })),
220
- ];
221
- // Selection is applied to direct children only. Required children are always
222
- // included, and selection preserves source order; ordering is a later step.
223
- if (section.selection) {
224
- const count = Math.max(0, section.selection.select);
225
- const indexed = components.map((component, sourceIndex) => ({ component, sourceIndex }));
226
- const required = indexed.filter(({ component }) => isRequiredSectionComponent(component));
227
- if (count < required.length) {
228
- throw new Error(`Section "${section.identifier}" selects ${count} components but contains ${required.length} required components.`);
229
- }
230
- if (count > indexed.length) {
231
- const replacement = section.selection.withReplacement === true;
232
- throw new Error(replacement
233
- ? `Section "${section.identifier}" requires cloned item instances for withReplacement selection; the backend must materialize those instances before delivery.`
234
- : `Section "${section.identifier}" selects ${count} components without replacement but only contains ${indexed.length}.`);
235
- }
236
- const optional = shuffleArray(indexed.filter(({ component }) => !isRequiredSectionComponent(component)), rng);
237
- components = [...required, ...optional.slice(0, count - required.length)]
238
- .sort((a, b) => a.sourceIndex - b.sourceIndex)
239
- .map(({ component }) => component);
240
- }
241
- if (section.ordering?.shuffle) {
242
- components = shuffleSectionComponents(components, rng);
243
- }
244
- for (const component of components) {
245
- if (component.type === 'section') {
246
- visitSection(component.section, tp);
247
- continue;
248
- }
249
- const item = component.item;
250
- out.push({
251
- identifier: item.identifier,
252
- item,
253
- section,
254
- testPart: tp,
255
- index: idx++,
256
- sectionIndex: currentSectionIndex,
257
- });
258
- }
259
- };
260
- for (const tp of testParts) {
261
- for (const section of tp.sections || [])
262
- visitSection(section, tp);
263
- }
264
- return out;
189
+ const sectionIndexes = new Map(this.getAllSections().map((section) => [section.id, section.index]));
190
+ return deliveredItems(assessment).map(({ item, testPart, sections }, index) => {
191
+ const section = sections[sections.length - 1];
192
+ return {
193
+ identifier: item.identifier,
194
+ item,
195
+ section,
196
+ sections,
197
+ testPart,
198
+ index,
199
+ sectionIndex: sectionIndexes.get(section.identifier) ?? 0,
200
+ };
201
+ });
265
202
  }
266
203
  // ---------------------------------------------------------------------------
267
204
  // Public API used by components
268
205
  // ---------------------------------------------------------------------------
269
206
  getAllSections() {
270
207
  const out = [];
271
- let idx = 0;
208
+ const seen = new Set();
272
209
  const visit = (section) => {
273
- out.push({ id: section.identifier, title: section.title, visible: section.visible, index: idx++ });
274
- for (const child of section.sections ?? [])
275
- visit(child);
210
+ // A keepTogether="false" section mixed into its parent's shuffle appears as several fragments.
211
+ if (!seen.has(section.identifier)) {
212
+ seen.add(section.identifier);
213
+ out.push({ id: section.identifier, title: section.title, visible: section.visible, index: out.length });
214
+ }
215
+ for (const component of sectionComponents(section)) {
216
+ if (component.type === 'section')
217
+ visit(component.section);
218
+ }
276
219
  };
277
220
  for (const tp of this.assessment.testParts || []) {
278
221
  for (const section of tp.sections || [])
@@ -325,7 +268,7 @@ export class AssessmentPlayer {
325
268
  if (!current)
326
269
  return [];
327
270
  return this.items
328
- .filter((item) => item.section === current.section)
271
+ .filter((item) => item.section.identifier === current.section.identifier)
329
272
  .map((item) => {
330
273
  const itemRef = item.item;
331
274
  return {
@@ -355,8 +298,55 @@ export class AssessmentPlayer {
355
298
  return [];
356
299
  return q.section.rubricBlocks || q.testPart.rubricBlocks || [];
357
300
  }
301
+ /**
302
+ * Test feedback shown now, test-level first, then each test part's. Nothing shows before outcome
303
+ * processing first runs. `during` feedback then shows by its outcome, test-part `during`
304
+ * feedback while its part is current; `atEnd` feedback shows once the test, or its test part,
305
+ * has ended.
306
+ */
358
307
  getVisibleFeedback() {
359
- return this.visibleFeedback.map((item) => ({ ...item }));
308
+ const outcomes = this.testOutcomes;
309
+ const parts = this.assessment.testParts ?? [];
310
+ const hasStructured = (this.assessment.testFeedback?.length ?? 0) > 0 || parts.some((part) => (part.testFeedback?.length ?? 0) > 0);
311
+ if (!hasStructured) {
312
+ return this.finalized && this.legacyFeedback
313
+ ? [{ key: 'testFeedback', identifier: 'testFeedback', content: this.legacyFeedback, access: 'atEnd' }]
314
+ : [];
315
+ }
316
+ if (!outcomes)
317
+ return [];
318
+ const shown = [];
319
+ const add = (items, ended, current, part) => {
320
+ items?.forEach((fb, index) => {
321
+ if (fb.access === 'atEnd' ? !ended : !current)
322
+ return;
323
+ if (!isShownByIdentifier(outcomes[fb.outcomeIdentifier] ?? null, fb.identifier, fb.showHide))
324
+ return;
325
+ shown.push({
326
+ key: part ? `part:${part.identifier}:${index}` : `test:${index}`,
327
+ identifier: fb.identifier,
328
+ content: fb.content,
329
+ access: fb.access,
330
+ ...(part ? { testPartIdentifier: part.identifier } : {}),
331
+ });
332
+ });
333
+ };
334
+ add(this.assessment.testFeedback, this.finalized, true);
335
+ const currentPart = this.currentTestPartIndex();
336
+ parts.forEach((part, index) => {
337
+ add(part.testFeedback, this.finalized || currentPart > index, currentPart === index, part);
338
+ });
339
+ return shown;
340
+ }
341
+ currentTestPartIndex() {
342
+ const part = this.items[this.currentItemIndex]?.testPart;
343
+ return part ? (this.assessment.testParts ?? []).findIndex((p) => p.identifier === part.identifier) : -1;
344
+ }
345
+ setTestOutcomes(outcomes) {
346
+ if (!outcomes)
347
+ return;
348
+ this.testOutcomes = cloneData(outcomes);
349
+ this.notifyTestFeedbackChange();
360
350
  }
361
351
  updateResponse(responseId, value) {
362
352
  const active = this.items[this.currentItemIndex];
@@ -425,12 +415,19 @@ export class AssessmentPlayer {
425
415
  return itemSession;
426
416
  }
427
417
  endItemSessionForSubmit(q, responses, itemSession) {
418
+ const validateResponses = this.sessionCoordinator.mustValidateResponses(q.identifier);
419
+ const endAttempt = (session) => {
420
+ const result = session.dispatch({ action: 'endAttempt', validateResponses }).result;
421
+ if (result?.validation && !result.validation.valid) {
422
+ throw new Error(result.validation.issues[0]?.message || `Submit failed: invalid response for item ${q.identifier}`);
423
+ }
424
+ return result?.sessionState ?? session.serialize();
425
+ };
428
426
  const active = this.items[this.currentItemIndex];
429
427
  if (active === q &&
430
428
  this.currentItemSession &&
431
429
  this.currentItemSession.state().lifecycleStatus !== 'suspended') {
432
- const transition = this.currentItemSession.dispatch({ action: 'endAttempt' });
433
- return transition.result?.sessionState ?? this.currentItemSession.serialize();
430
+ return endAttempt(this.currentItemSession);
434
431
  }
435
432
  const session = this.getItemDefinition(q).openSession({
436
433
  restore: itemSession,
@@ -438,8 +435,7 @@ export class AssessmentPlayer {
438
435
  activate: true,
439
436
  });
440
437
  try {
441
- const transition = session.dispatch({ action: 'endAttempt' });
442
- return transition.result?.sessionState ?? session.serialize();
438
+ return endAttempt(session);
443
439
  }
444
440
  finally {
445
441
  session.dispose();
@@ -559,12 +555,15 @@ export class AssessmentPlayer {
559
555
  // Enforce navigation rules (UI hints, still backend-authoritative for real deployments).
560
556
  if (!options.restoring && this.currentItemIndex >= 0 && !this.canNavigateByTestPart(index, this.currentItemIndex)) {
561
557
  const currentMode = this.items[this.currentItemIndex]?.testPart.navigationMode ?? this.assessment.navigationMode;
562
- if (currentMode === 'linear' && index > this.currentItemIndex + 1) {
558
+ if (currentMode === 'linear' && index > this.nextUnlockedIndex(this.currentItemIndex)) {
563
559
  throw new Error('In linear navigation mode, you can only move to the next question.');
564
560
  }
565
561
  throw new Error('Navigation is not allowed.');
566
562
  }
567
563
  const target = this.items[index];
564
+ if (!options.restoring && target && this.isItemLocked(target)) {
565
+ throw new Error('The time limit for this question has expired.');
566
+ }
568
567
  if (!options.restoring && target && !this.sessionCoordinator.canReview(target.identifier)) {
569
568
  throw new Error('You cannot go back to previous questions in this assessment.');
570
569
  }
@@ -602,24 +601,28 @@ export class AssessmentPlayer {
602
601
  section: { identifier: q.section.identifier, timeLimits: q.section.timeLimits },
603
602
  item: { identifier: q.identifier, timeLimits: q.item.timeLimits },
604
603
  });
605
- // Apply three-level itemSessionControl fallback for this item's section (S1).
606
- const effectiveControl = this.getEffectiveItemSessionControl(q);
607
- if (effectiveControl) {
608
- this.sessionCoordinator.updateItemSessionControl(effectiveControl);
609
- }
610
604
  // Restore responses into one live session owned by the assessment. The section
611
605
  // composition and item renderer receive this exact object.
612
606
  const responses = this.sessionCoordinator.activateItem(q.identifier);
613
607
  const restoredItemSession = this.state.itemSessions?.[q.identifier];
608
+ const control = this.sessionCoordinator.getItemSettings(q.identifier);
614
609
  this.releaseCurrentItemSession();
615
610
  const session = this.getItemDefinition(q).openSession({
616
611
  restore: restoredItemSession,
617
612
  responses: restoredItemSession ? undefined : responses,
618
613
  activate: true,
614
+ templateDefaults: restoredItemSession ? undefined : this.evaluateTemplateDefaults(q),
615
+ presentation: {
616
+ // Feedback during an adaptive item's attempts is part of the item, whatever showFeedback says.
617
+ showFeedback: control.showFeedback === true || isAdaptiveItemXml(q.item.itemXml),
618
+ showSolution: control.showSolution === true,
619
+ },
619
620
  });
620
621
  this.attachCurrentItemSession(q, session);
621
622
  this.notifyItemChange();
622
623
  this.notifySectionChange();
624
+ if (currentItem?.testPart.identifier !== q.testPart.identifier)
625
+ this.notifyTestFeedbackChange();
623
626
  }
624
627
  async navigateToSection(sectionId) {
625
628
  const idx = this.items.findIndex((q) => q.section.identifier === sectionId);
@@ -638,8 +641,12 @@ export class AssessmentPlayer {
638
641
  if (!navAway.allowed) {
639
642
  throw new Error(navAway.reason || 'You must answer this question before continuing.');
640
643
  }
641
- // In individual submission mode, submit current item before moving forward.
642
- if ((q.testPart.submissionMode ?? this.assessment.submissionMode) === 'individual') {
644
+ // In individual submission mode, submit the current item before moving forward
645
+ // unless its attempts are used up or it is already closed.
646
+ const lifecycle = this.currentItemSession?.state().lifecycleStatus;
647
+ if ((q.testPart.submissionMode ?? this.assessment.submissionMode) === 'individual' &&
648
+ this.sessionCoordinator.canSubmit(q.identifier) &&
649
+ lifecycle !== 'closed') {
643
650
  const before = this.currentItemIndex;
644
651
  await this.submitCurrentItem();
645
652
  // submitCurrentItem may branch/navigate; if it did, we're done.
@@ -647,7 +654,10 @@ export class AssessmentPlayer {
647
654
  return;
648
655
  }
649
656
  }
650
- await this.navigateTo(this.currentItemIndex + 1);
657
+ const nextIndex = this.nextUnlockedIndex(this.currentItemIndex);
658
+ if (nextIndex < 0)
659
+ return;
660
+ await this.navigateTo(nextIndex);
651
661
  }
652
662
  async previous() {
653
663
  const state = this.getNavigationState();
@@ -673,7 +683,7 @@ export class AssessmentPlayer {
673
683
  if (submittedSession) {
674
684
  const transition = submittedSession.dispatch({
675
685
  action: 'endAttempt',
676
- validateResponses: this.sessionCoordinator.mustValidateResponses(),
686
+ validateResponses: this.sessionCoordinator.mustValidateResponses(q.identifier),
677
687
  });
678
688
  const attempt = transition.result;
679
689
  if (!attempt)
@@ -691,6 +701,7 @@ export class AssessmentPlayer {
691
701
  timeSpent: itemSession?.duration,
692
702
  timing: this.getSubmitTimingEvidence(q, itemSession?.duration ?? 0),
693
703
  itemSession: this.config.sendItemSessionToBackend ? itemSession : undefined,
704
+ comment: this.sessionCoordinator.getItemComment(q.identifier),
694
705
  });
695
706
  if (!res.success || !res.result) {
696
707
  throw new Error(res.error || 'Submit failed');
@@ -728,6 +739,7 @@ export class AssessmentPlayer {
728
739
  this.sessionCoordinator.setItemSession(q.identifier, itemSession);
729
740
  }
730
741
  }
742
+ this.setTestOutcomes(res.outcomes);
731
743
  const itemResult = {
732
744
  itemIdentifier: q.identifier,
733
745
  score: res.result.score,
@@ -785,7 +797,7 @@ export class AssessmentPlayer {
785
797
  if (this.currentItemIndex <= 0)
786
798
  return false;
787
799
  const prev = this.items[this.currentItemIndex - 1];
788
- if (!prev)
800
+ if (!prev || this.isItemLocked(prev))
789
801
  return false;
790
802
  if (!this.canNavigateByTestPart(this.currentItemIndex - 1, this.currentItemIndex))
791
803
  return false;
@@ -794,8 +806,8 @@ export class AssessmentPlayer {
794
806
  canNext() {
795
807
  if (this.currentItemIndex < 0)
796
808
  return false;
797
- const nextIdx = this.currentItemIndex + 1;
798
- if (nextIdx >= this.items.length)
809
+ const nextIdx = this.nextUnlockedIndex(this.currentItemIndex);
810
+ if (nextIdx < 0)
799
811
  return false;
800
812
  if (!this.canNavigateByTestPart(nextIdx, this.currentItemIndex))
801
813
  return false;
@@ -809,13 +821,15 @@ export class AssessmentPlayer {
809
821
  const target = this.items[targetIndex];
810
822
  if (!current || !target)
811
823
  return false;
824
+ // Items locked by an expired time limit are passed over.
825
+ const nextIndex = this.nextUnlockedIndex(currentIndex);
812
826
  if (current.testPart !== target.testPart) {
813
827
  // QTI testParts are delivered in sequence. A candidate may enter the next
814
828
  // part, but cannot jump across parts or return to a completed part.
815
- return targetIndex === currentIndex + 1;
829
+ return targetIndex === nextIndex;
816
830
  }
817
831
  const mode = current.testPart.navigationMode ?? this.assessment.navigationMode ?? 'nonlinear';
818
- return mode === 'nonlinear' || targetIndex === currentIndex || targetIndex === currentIndex + 1;
832
+ return mode === 'nonlinear' || targetIndex === currentIndex || targetIndex === nextIndex;
819
833
  }
820
834
  async submitSimultaneousItems(items) {
821
835
  if (items.every((q) => this.sessionCoordinator.hasItemResult(q.identifier)))
@@ -851,6 +865,7 @@ export class AssessmentPlayer {
851
865
  timeSpent: itemSession.duration,
852
866
  timing: this.getSubmitTimingEvidence(q, itemSession.duration),
853
867
  itemSession: this.config.sendItemSessionToBackend ? itemSession : undefined,
868
+ comment: this.sessionCoordinator.getItemComment(q.identifier),
854
869
  });
855
870
  if (!res.success || !res.result) {
856
871
  throw new Error(res.error || `Submit failed for item ${q.identifier}`);
@@ -872,6 +887,7 @@ export class AssessmentPlayer {
872
887
  maxScore: res.result.maxScore,
873
888
  responses: this.state.itemResponses[q.identifier] || {},
874
889
  });
890
+ this.setTestOutcomes(res.outcomes);
875
891
  }
876
892
  // The attached item must represent the same accepted lifecycle as persistence.
877
893
  // Replace the provisional suspended object with one restored from the accepted
@@ -937,27 +953,12 @@ export class AssessmentPlayer {
937
953
  maxScore: r.maxScore,
938
954
  responses: this.state.itemResponses[r.itemIdentifier] || {},
939
955
  }));
940
- // Evaluate testFeedback visibility using QTI string equality:
941
- // show when outcomeIdentifier's value equals feedback.identifier (for showHide='show'),
942
- // or does NOT equal it (for showHide='hide').
943
- const structuredFeedback = this.assessment.testFeedback ?? [];
944
- const outcomes = finalized.outcomes ?? {};
945
- if (structuredFeedback.length > 0) {
946
- this.visibleFeedback = structuredFeedback
947
- .filter((fb) => fb.access === 'atEnd')
948
- .filter((fb) => {
949
- const outcomeValue = String(outcomes[fb.outcomeIdentifier] ?? '');
950
- const matches = outcomeValue === fb.identifier;
951
- return fb.showHide === 'show' ? matches : !matches;
952
- })
953
- .map((fb) => ({ identifier: fb.identifier, content: fb.content, access: fb.access }));
954
- }
955
- else {
956
- // Legacy: backend returns a plain feedback string
957
- this.visibleFeedback = finalized.feedback
958
- ? [{ identifier: 'testFeedback', content: finalized.feedback, access: 'atEnd' }]
959
- : [];
960
- }
956
+ // Outcome processing has run by the end of the test, so a backend returning no outcomes
957
+ // leaves them all NULL.
958
+ this.finalized = true;
959
+ this.legacyFeedback = finalized.feedback;
960
+ this.testOutcomes = cloneData(finalized.outcomes ?? this.testOutcomes ?? {});
961
+ this.notifyTestFeedbackChange();
961
962
  this.notifyComplete();
962
963
  if (this.config.onComplete)
963
964
  this.config.onComplete();
@@ -978,6 +979,20 @@ export class AssessmentPlayer {
978
979
  const id = q.identifier;
979
980
  return this.sessionCoordinator.getItemSessionInfo(id);
980
981
  }
982
+ /**
983
+ * Records the candidate's comment on an item (QTI `allowComment`), sent with its next submission.
984
+ * Defaults to the current item; throws when the item does not allow comments.
985
+ */
986
+ setItemComment(comment, itemIdentifier) {
987
+ const id = itemIdentifier ?? this.items[this.currentItemIndex]?.identifier;
988
+ if (!id)
989
+ throw new Error('No current item');
990
+ this.sessionCoordinator.setItemComment(id, comment);
991
+ }
992
+ getItemComment(itemIdentifier) {
993
+ const id = itemIdentifier ?? this.items[this.currentItemIndex]?.identifier;
994
+ return id ? this.sessionCoordinator.getItemComment(id) : undefined;
995
+ }
981
996
  getRemainingTime() {
982
997
  // TimeManager exposes seconds getters.
983
998
  return this.timeManager?.getRemainingSeconds() ?? 0;
@@ -1007,6 +1022,11 @@ export class AssessmentPlayer {
1007
1022
  this.completeListeners.add(listener);
1008
1023
  return () => this.completeListeners.delete(listener);
1009
1024
  }
1025
+ /** Called when `getVisibleFeedback()` may have changed: new outcomes, a new test part, or the end. */
1026
+ onTestFeedbackChange(listener) {
1027
+ this.testFeedbackChangeListeners.add(listener);
1028
+ return () => this.testFeedbackChangeListeners.delete(listener);
1029
+ }
1010
1030
  onTimeWarning(listener) {
1011
1031
  this.timeWarningListeners.add(listener);
1012
1032
  return () => this.timeWarningListeners.delete(listener);
@@ -1027,6 +1047,7 @@ export class AssessmentPlayer {
1027
1047
  this.sectionChangeListeners.clear();
1028
1048
  this.responseChangeListeners.clear();
1029
1049
  this.completeListeners.clear();
1050
+ this.testFeedbackChangeListeners.clear();
1030
1051
  this.timeWarningListeners.clear();
1031
1052
  this.timeExpiredListeners.clear();
1032
1053
  this.timeTickListeners.clear();
@@ -1057,10 +1078,55 @@ export class AssessmentPlayer {
1057
1078
  for (const l of this.completeListeners)
1058
1079
  l();
1059
1080
  }
1081
+ notifyTestFeedbackChange() {
1082
+ for (const l of this.testFeedbackChangeListeners)
1083
+ l();
1084
+ }
1060
1085
  notifyTimeWarning(remainingSeconds) {
1061
1086
  for (const l of this.timeWarningListeners)
1062
1087
  l(remainingSeconds);
1063
1088
  }
1089
+ evaluateTemplateDefaults(q) {
1090
+ const defaults = q.item.templateDefaults;
1091
+ if (!defaults?.length)
1092
+ return undefined;
1093
+ const declarations = testOutcomeDeclarations(this.assessment, this.testOutcomes ?? undefined);
1094
+ const out = {};
1095
+ for (const { templateIdentifier, expressionXml } of defaults) {
1096
+ out[templateIdentifier] = plainQtiValue(evaluateTestExpression(expressionXml, declarations, Math.random));
1097
+ }
1098
+ return out;
1099
+ }
1100
+ isItemLocked(q) {
1101
+ return (this.lockedScopes.has(`item:${q.identifier}`) ||
1102
+ this.lockedScopes.has(`testPart:${q.testPart.identifier}`) ||
1103
+ q.sections.some((section) => this.lockedScopes.has(`section:${section.identifier}`)));
1104
+ }
1105
+ nextUnlockedIndex(fromIndex) {
1106
+ for (let i = fromIndex + 1; i < this.items.length; i++) {
1107
+ if (!this.isItemLocked(this.items[i]))
1108
+ return i;
1109
+ }
1110
+ return -1;
1111
+ }
1112
+ /**
1113
+ * A test part, section or item without late submission ran out of time: its items close for the
1114
+ * candidate, and delivery moves to the next item outside it.
1115
+ */
1116
+ handleScopeExpired(scope, identifier) {
1117
+ this.lockedScopes.add(`${scope}:${identifier}`);
1118
+ const current = this.items[this.currentItemIndex];
1119
+ if (!current || !this.isItemLocked(current))
1120
+ return;
1121
+ this.saveCurrentItemSession();
1122
+ this.notifyItemChange();
1123
+ const nextIndex = this.nextUnlockedIndex(this.currentItemIndex);
1124
+ if (nextIndex < 0) {
1125
+ this.notifyTimeExpired();
1126
+ return;
1127
+ }
1128
+ this.navigateTo(nextIndex, { restoring: true }).catch(() => { });
1129
+ }
1064
1130
  notifyTimeExpired() {
1065
1131
  for (const l of this.timeExpiredListeners)
1066
1132
  l();
@@ -1090,34 +1156,6 @@ export class AssessmentPlayer {
1090
1156
  };
1091
1157
  }
1092
1158
  }
1093
- /** Fisher-Yates shuffle using a provided RNG (returns a new array). */
1094
- function shuffleArray(arr, rng) {
1095
- const out = [...arr];
1096
- for (let i = out.length - 1; i > 0; i--) {
1097
- const j = Math.floor(rng() * (i + 1));
1098
- [out[i], out[j]] = [out[j], out[i]];
1099
- }
1100
- return out;
1101
- }
1102
- function isRequiredSectionComponent(component) {
1103
- return component.type === 'item' ? component.item.required === true : component.section.required === true;
1104
- }
1105
- function isFixedSectionComponent(component) {
1106
- return component.type === 'item' ? component.item.fixed === true : component.section.fixed === true;
1107
- }
1108
- /** Shuffle non-fixed children while retaining fixed children at their post-selection positions. */
1109
- function shuffleSectionComponents(components, rng) {
1110
- const result = [...components];
1111
- const movableIndexes = components
1112
- .map((component, index) => ({ component, index }))
1113
- .filter(({ component }) => !isFixedSectionComponent(component))
1114
- .map(({ index }) => index);
1115
- const shuffled = shuffleArray(movableIndexes.map((index) => components[index]), rng);
1116
- for (let index = 0; index < movableIndexes.length; index++) {
1117
- result[movableIndexes[index]] = shuffled[index];
1118
- }
1119
- return result;
1120
- }
1121
1159
  function cloneData(value) {
1122
1160
  return value === undefined ? undefined : structuredClone(value);
1123
1161
  }